Commit Graph
12 Commits
Author SHA1 Message Date
CatoandClaude Fable 5.1 dbe9caaa49 feat(cat): temporary chat — never listed, never remembered, gone when you leave (#1374)
* feat(cat): temporary chat — never listed, never remembered, gone when you leave

"Temporary chat" in the conversations rail: the row the first send creates
is `ephemeral` (cat_conversations.ephemeral, migration 20261021120000). It is
never in the list, the Cat learns no memories from it, and it is deleted the
moment the person leaves it — a new chat, another thread, a closed tab (the
delete goes with keepalive). The daily cleanup cron sweeps any left behind
by a dead phone. The toolbar says "Temporary chat" while one is open or
armed. src/lib/chat/temporary-chat.ts holds the leave rule, pure and tested.

The cleanup cron's tasks moved to services/maintenance/cleanup-tasks.ts to
keep the route under its size limit.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018WZnBnaLP6RhwFkLxRTKgE

* test(cron): the cleanup test knows the temporary-chat sweep; unique migration timestamp

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018WZnBnaLP6RhwFkLxRTKgE

* fix(cat): the answer row sits under the answer, not inside the provenance line

It was inserted inside the provider · model span (#1373); CodeQL flagged
the guard that misplacement made always-true. Now it follows the
provenance block, on every assistant answer with content.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018WZnBnaLP6RhwFkLxRTKgE

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-21 07:23:34 +02:00
CatoandClaude Fable 5.1 b5ea104f6e feat(oauth): sweep self-registered clients nobody consented to (#1189)
* feat(oauth,mcp): connect AI apps to OrangeCat and Loki with one OrangeCat sign-in

OrangeCat becomes a full MCP-grade authorization server, and gets its own
MCP server.

Authorization server
- RFC 8707 resource indicators: OAUTH_RESOURCES (config.ts) names OrangeCat's
  MCP server (${OAUTH_ISSUER}/api/mcp) and Loki's (LOKI_MCP_RESOURCE, default
  https://loki.orangecat.ch/api/mcp), each with the scopes it honours.
  /oauth/authorize takes `resource` (unknown -> invalid_target), binds it to
  the code and refresh token, and the access token's aud becomes it. No scope
  + a resource defaults to that resource's scopes; always intersected with the
  client's ceiling. /oauth/token accepts a repeated `resource` and answers
  invalid_target on mismatch before a code is burned or a refresh token
  revoked. Access tokens now carry a client_id claim.
- New scopes loki.chat and loki.act (minted here, honoured by Loki).
- RFC 7591 Dynamic Client Registration at POST /oauth/register: public
  clients only, PKCE, https or loopback redirects, <= 5, no fragments or
  userinfo, cleaned name <= 80 chars, dcr_ client ids, never trusted, rate
  limited 10/hour per IP. The consent screen says a self-registered app is
  unverified and names the host it returns to.
- RFC 8414 /.well-known/oauth-authorization-server serves the same document
  as the OIDC discovery route (one builder), now with registration_endpoint.
- RFC 9728 protected-resource metadata at /.well-known/oauth-protected-resource
  (and the /api/mcp path-suffixed form).
- /api/v1 now refuses OrangeCat tokens whose aud is Loki's resource, so a token
  handed to Loki cannot be replayed here. Other tokens are unaffected.
- Migration: resource on oauth_auth_codes and oauth_refresh_tokens,
  registered_via (admin | dcr) on oauth_clients.

MCP server (POST /api/mcp, stateless Streamable HTTP, JSON responses)
- Accepts an OrangeCat token whose aud is this server (audience checked) or
  an ock_ integration key; otherwise 401 with WWW-Authenticate
  resource_metadata=... (plus error="invalid_token" for a refused token).
- Tools: orangecat_whoami, orangecat_search, orangecat_my_entities,
  orangecat_create_project, orangecat_post_update. Writes run the /api/v1
  handlers in-process with the caller's own bearer, so scope, rate limit,
  validation, idempotency, audit and webhooks are the same code. A missing
  scope is a tool error naming the scope. Per-person limit of 120 req/min.
- CORS on the MCP, metadata, register and token endpoints.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018tsc8Yu7TQR9a6Y5xNYkeD

* fix(oauth): say on the consent screen that approving through Loki runs the action

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018tsc8Yu7TQR9a6Y5xNYkeD

* feat(oauth): sweep self-registered clients nobody consented to

Anyone can register a client at /oauth/register, so rows accumulated from
probes and from connector sign-ins that were started and never finished,
and nothing removed them. The daily cleanup cron now deletes self-registered
clients older than a day that hold no grant and no live refresh token. A
client in use is kept at any age; an operator-registered client is never
touched — the DELETE itself is fenced to registered_via = 'dcr'.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018tsc8Yu7TQR9a6Y5xNYkeD

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-29 08:32:06 -07:00
CatoandClaude Fable 5.1 9a352d3646 refactor: rename FleetCrown to Loki across the integration (#1016)
The sibling product was renamed on 2026-09-14. Every reference follows:
service and route paths (src/services/loki, /api/integrations/loki),
env keys (LOKI_*), the build-intent audience and timeline source ('loki'),
ecosystem config, docs, tests, and 13 file names.

Tool labels keep "Loki" capitalised: the old name had an internal capital
and passed the "looks like a name" shape test for free; a one-word name
needs listing, so softLower now carries a small PROPER_NOUNS set.

Box and data were moved ahead of this: LOKI_* keys sit beside the old ones
in the app env, the OAuth client is `loki` with the new callback host, and
timeline/metadata rows carrying the old name were rewritten.


Claude-Session: https://claude.ai/code/session_016YJVAanfj8keVSXyZnTemh

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 16:40:27 -07:00
bae4be1aa3 refactor(test): migrate the unit suite from Jest 30 to Vitest 4 (#859)
Full parity: 282 test files / 2645 tests green before and after.

- vitest.config.ts mirrors the old moduleNameMapper as ordered resolve.alias
  entries; jsdom env, globals, 30s timeout, v8 coverage with the same ratchet.
- vitest.setup.ts ports jest.setup.ts; lucide-react is now a vi.mock Proxy
  (any icon resolves — the old CJS-alias Proxy surfaced no named exports and
  every unlisted icon crashed renders as "Element type is invalid").
- Codemod jest.* -> vi.* across tests; @jest-environment -> @vitest-environment.
- Constructor mocks use function expressions (vitest news the implementation;
  arrows are not constructable).
- Factories returning a bare component now return { default: ... };
  one TDZ factory moved under vi.hoisted; one require() -> await import().
- jest.isolateModulesAsync dropped in the auth smoke test (resetModules +
  doMock per test covers it).
- Scripts ported (positional path filters replace --testPathPatterns);
  verify's --watchAll flag removed; ci.yml comment updated.
- Deleted jest.config.js, jest.setup.ts, __mocks__/vitest.js,
  tsconfig.test.json, tests/jest-dom.d.ts, and the unimported jest-era
  tests/utils.ts; uninstalled jest, ts-jest, jest-environment-jsdom,
  @types/jest; dropped the dead mcp:jest script.
- Snapshot file rewritten in Vitest format (content byte-identical).


Claude-Session: https://claude.ai/code/session_01WqKqMnHQHSmkGFfc5t7Rxn

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-31 16:14:36 +00:00
abf03b811f fix(api): rate-limit + validate unguarded mutating routes, add route-walker gate (#559)
Audit slice 2 (docs/AUDIT_REPORT.md, 2026-08-02):
- per-IP limits on unauthenticated auth endpoints (verify-captcha, sync,
  callback) — they trigger external calls / session mutation
- per-user write limits: cat/offers-from-text (LLM per request), all six
  loan writes via one loanWriteRateLimit helper, stakeholders,
  webhook-endpoints incl. delivery replay (outbound HTTP),
  integration-keys incl. rotate; integration-key limits on
  v1/stakeholders + v1/timeline/publish
- zod at the boundary for the raw-body mutators (projects status,
  notification preferences, follow/unfollow, wallets POST); dead _body
  parse removed
- api-route-guards.test.ts walks every route.ts and pins two invariants:
  every mutating route authenticates, every mutating route rate-limits —
  allowlists are explicit and reasoned

Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-02 17:15:30 +02:00
Georgy ButaevandClaude Opus 4.8 a52836c793 chore: remove all Vercel — everything runs on Hetzner
Production is fully self-hosted on the Hetzner box (bitbaum, behind Caddy)
with self-hosted Supabase. This scrubs the remaining Vercel footprint:

Code (src/ now has zero Vercel references):
- security page: "Hosted on Vercel" → self-hosted infrastructure
- FleetCrown URL fleetcrown.vercel.app → fleetcrown.orangecat.ch (entity
  registry + external-publish allowlist; the dead vercel.app subdomain was
  also a re-registration risk in an allowlist)
- webhook-secret error + cron/env comments point at the box, not Vercel
- corrected stale "Vercel kills the function on response" comments (false
  on a persistent server) to accurate await-before-respond reasoning

Security/config:
- supabase/config.toml: dropped dead *.vercel.app auth redirect URLs
- @vercel/mcp-adapter dependency removed (unused)

Artifacts removed:
- scripts/auth/vercel-login.js, scripts/preview-url.sh,
  scripts/dev/merge-env.js, scripts/monitoring/deployment-monitor.js,
  scripts/db/setup-env.js, mcp-servers/vercel-openapi.json, .vercel/
- setup_vercel_secrets MCP tool in mcp-servers/github-server.js
- .gitignore Vercel section; env scripts stripped of vercel-login/token

Docs + .claude rules/commands rewritten to the self-host deploy flow
(scripts/deploy-selfhost.sh / .github/workflows/cd.yml; env at
/opt/orangecat/app/.env). Historical/archive records left intact.

Verified: tsc 0 errors, SELF_HOST=1 build green, cron unit tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 08:50:43 +02:00
Georgy ButaevandClaude Opus 4.7 5f051a83a6 test(api): lock GET /api/cron/webhook-worker branches
The most state-touching route on the platform. Vercel cron runs this
every minute; silent regressions in processDelivery silently drop
customer deliveries — they see "0 deliveries" with no signal until
they complain. Last remaining untested platform route.

12 tests across 5 sections:

Auth (2):
  - 401 no header (pickDueDeliveries verified NOT called)
  - 401 wrong secret (same assertion)

Empty batch (1):
  - processed:0 returned; fetch + claim verified NOT called

processDelivery branches (7) — each delivery row exercises one branch:
  - skipped: claimDelivery returns false → no further work, summary
    has only skipped++, getEndpointSigningContext + fetch + mark*
    verified NOT called
  - delivered (revoked): signing-context null → markDelivered called
    with (id, 0, '[endpoint revoked]'); fetch + touchEndpoint NOT called
  - delivered (2xx): POST with all 4 X-OrangeCat-* headers asserted
    (Signature from signWebhookPayload, Event-Id, Event-Type,
    Content-Type); markDelivered called with response body; touchEndpoint
    called with endpoint_id; markFailedOrRetry NOT called
  - retry (non-2xx under MAX): markFailedOrRetry called with
    claimedDelivery (attempt_count=3 after bump), response status,
    body; markDelivered NOT called; summary.retry++
  - failed (non-2xx after MAX): attempt_count=6 input bumps to 7
    (>MAX_ATTEMPTS) → summary.failed++ instead of retry; verifies
    the matching boundary fix from eb5fc998
  - retry (network error): markFailedOrRetry with (null,
    '[network] ECONNRESET'); summary.retry++
  - retry (non-Error network rejection): String() coerced to '[network] unknown'

Top-level error (1):
  - 500 INTERNAL_ERROR when pickDueDeliveries throws

Batch summary (1):
  - 3 deliveries, mixed outcomes (delivered + skipped + retry):
    summary aggregates correctly, processed:3; apiSuccess called
    with full summary shape

Mock pattern: all four services + signing + global fetch + logger
mocked at module-import level; CRON_SECRET set per-test in beforeEach,
deleted in afterAll; per-delivery defaults in beforeEach so tests
opt into delivery rows via pickDueDeliveries override.

Suite: 54 suites · 701 tests · 0 failures. tsc + eslint clean.
All untested platform routes now covered.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-04 03:03:20 +02:00
Georgy ButaevandClaude Opus 4.7 8f9f184158 fix(webhooks): reject unknown event_types at mint instead of silently never firing
Pre-2026-06-04 the POST /api/webhook-endpoints schema accepted any
string in event_types (max length only). A curl-mint with
`event_types: ['totally.fake']` passed validation, persisted, and
then never fired anything — enqueueWebhookEvent's exact-match filter
`ep.event_types.includes(params.eventType)` excludes unknown tokens.
The user saw "0 deliveries" with no signal why.

The mint UI sourced its grid from PUBLIC_API_WEBHOOK_EVENTS so this
only hit curl callers, but curl + the SDK are first-class clients of
the public API.

Fix: validate the array against the SSOT allowlist via z.enum, same
shape as the existing publicized contract. Invalid event types now
get a 400 with the standard validation_error envelope at mint time —
fail fast, clear signal.

Test:
  - 16th branch in route.test.ts: event_types=['totally.fake']
    returns 400, apiValidationError called, createWebhookEndpoint
    verified NOT called

Suite: 53 suites · 689 tests · 0 failures. tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-04 02:56:43 +02:00
Georgy ButaevandClaude Opus 4.7 c6c0a173b8 test(api): lock /api/webhook-endpoints CRUD branches (GET/POST/DELETE)
Customer-facing mint flow. Silent regressions here mean FleetCrown +
future customers can't subscribe to events. 211188a3 shipped all three
handlers without tests; this commit locks 15 branches.

GET (3):
  - 401 when no session user (service not called)
  - happy path returns endpoints scoped to session user id
  - 500 fall-through via handleApiError on service throw

POST (8):
  - 400 (validation_error) when Zod rejects the body — empty name +
    non-URL — and createWebhookEndpoint verified NOT called
  - 401 when no session user
  - 403 in production when URL is http:// (NODE_ENV swap inside the
    test; canonical message asserted; service not called)
  - http:// localhost ALLOWED in dev (jest NODE_ENV='test' takes the
    same path), 201 success returned
  - 403 on ActorNotPermittedError with canonical message; handleApiError
    verified NOT called (branch routing)
  - 500 fall-through on unknown service exception
  - 201 happy path returns endpoint + secret via apiSuccess({status:201});
    service called with (userId, actorId, name, url, eventTypes:null)
  - event_types threaded through to the service when present in body

DELETE (4):
  - 401 when no session user (service not called)
  - 404 (Webhook endpoint) when revokeWebhookEndpoint returns false —
    same envelope so probers can't distinguish missing-endpoint from
    wrong-owner
  - 200 happy path with revoked:true; service called with (id, userId)
  - 500 fall-through via handleApiError on service throw

Mock pattern: ActorNotPermittedError inlined as a class in the
webhookEndpointsService mock so `instanceof` checks work; standardResponse
returns shaped objects; minimal request shim with `.json()` for the
compose+withZodBody POST and `.headers.get()` for withRequestId.

Suite: 53 suites · 688 tests · 0 failures. tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-04 02:50:32 +02:00
Georgy ButaevandClaude Opus 4.7 6c8cb6a09a test(api): lock GET /api/cron/cleanup branches
Vercel cron runs this daily at 02:00 UTC. Silent failures mean
idempotency_results + webhook_deliveries (delivered rows) grow
unbounded — invisible until the deliveries drawer takes ages to
render or pg_stat_activity flags table bloat. 3d9e9acb + 2d17a05f
shipped the route without handler tests; this commit locks the 9
branches.

Tests:
  Auth (3):
    - 401 when no authorization header
    - 401 when Bearer secret doesn't match CRON_SECRET
    - 401 when token is well-formed but missing the Bearer prefix
    pruneDeliveredWebhookDeliveries verified NOT called on each 401

  Happy path (3):
    - Both tasks succeed → per-task deleted counts in summary
    - Zero pruning → 0 in both fields (not omitted)
    - Idempotency null count → 0 (the ?? 0 coalesce)

  Partial failure — contract: 200 with per-task error string,
  the OTHER task still runs and reports its count (3):
    - idempotency error → 'error: connection_reset' + webhook count kept
    - webhook error → 'error: table_lock' + idempotency count kept
    - non-Error rejection from webhook task → String(error) coerced
      ('error: weird')

Mock pattern: module-scope mutable adminDeleteResult lets each test
control the inline idempotency prune outcome; pruneDeliveredWebhook-
Deliveries mocked at the service-import level; standardResponse
mocks return shaped objects; minimal { headers.get } request shim
avoids jsdom's missing global Request constructor (same shim as
38d8282d).

Suite: 52 suites · 673 tests · 0 failures. tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-04 02:44:13 +02:00
Georgy ButaevandClaude Opus 4.7 38d8282d00 test(api): lock POST /api/integration-keys/[id]/rotate branches
Rotation is the leak-response path: when a user thinks they've burnt
a key they MUST actually have burnt it. Silent regressions here would
either falsely-fail rotation (user keeps shipping a leaked key) or
misroute exceptions (a generic 500 instead of the 403 / 404 envelopes
the UI is built against).

7ddc1311 shipped the route without tests. This commit locks the 5
branches following the bdef16f4 pattern.

Tests:
  - 401 when no session user (service never called)
  - 403 on ActorNotPermittedError (user lost the right to act as the
    key's actor since mint); apiForbidden called with the canonical
    string; generic 500 + 404 paths verified NOT taken
  - 404 on "Key not found" sentinel error; apiNotFound('Integration key');
    other branches verified NOT taken — operators rely on this 404
    not being a 409 so probers can't distinguish missing-key from
    wrong-owner
  - 500 fall-through to handleApiError for unknown exceptions
    (e.g. connection_reset); branch routing assertions confirm
    apiForbidden + apiNotFound were skipped
  - 201 happy path returns key + plaintext via apiSuccess with the
    correct status; rotateIntegrationKey called with (id, userId)

Mock pattern mirrors the existing deliveries route tests (bdef16f4):
explicit standardResponse mocks return shaped objects, ActorNotPermittedError
inlined as a class in the integrationKeys mock so `instanceof` checks
work inside the handler.

Suite: 51 suites · 664 tests · 0 failures. tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-04 02:37:59 +02:00
Georgy ButaevandClaude Opus 4.7 bdef16f4ff test(api): lock the two webhook-deliveries operator routes
GET /api/webhook-endpoints/[id]/deliveries (246216a4 — powers the
drawer) and POST .../[deliveryId]/replay (bfd39b6d — the manual
retry button) both shipped to operators without handler-level tests.
Following the eb5fc998 pattern: writing the coverage proves the
contracts hold AND surfaces any silent bugs in the auth + ownership
chain before customers hit them.

11 tests across both routes:

GET (6 tests):
  - 401 when no session user
  - 404 (Webhook endpoint) when userOwnsEndpoint returns false
    (service not called)
  - happy path returns deliveries + default limit 50
  - ?limit=25 routed verbatim
  - ?limit=999 capped at MAX (100)
  - ?limit=abc / ?limit=0 fall back to DEFAULT (50)

POST replay (5 tests):
  - 401 when no session user (no service calls)
  - 404 (Webhook endpoint) when userOwnsEndpoint false; chain stops
  - 404 (Webhook delivery) when deliveryBelongsToEndpoint false;
    same envelope as endpoint-mismatch (probers can't distinguish)
  - 500 when enqueueDeliveryReplay returns false
  - happy path returns replayed:true with enqueue called with
    correct deliveryId

Mock pattern mirrors the existing services-api.test.ts shape:
explicit standardResponse mocks return shaped objects so handler-level
assertions are clean. A minimal `{ url }` shim avoids jsdom's missing
global Request constructor.

Suite: 50 suites · 659 tests · 0 failures. tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-04 02:25:12 +02:00