3 Commits
Author SHA1 Message Date
CatoandClaude Fable 5.1 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>
2026-09-15 13:53:38 -07:00
CatoandClaude Fable 5.1 d96db4830a refactor(companions): AI assistants become Companions in every label and path (#1039)
A companion is a being with its own soul and a memory of the person it
talks to, created privately, published by choice, clonable without its
memories. The entity type, tables and API path keep their names (the
group entity set the precedent); only what a person reads moves:

- registry name, plural, description, action label
- /ai-assistants -> /companions, /dashboard/ai-assistants -> /dashboard/companions
  (directories moved; old paths 301 via next.config)
- page titles, dashboard copy, profile tab id, CLI view paths

Phase one of Companions; memory, privacy and the room follow in their own PRs.


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

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 22:40:05 -07:00
Your Name 1b2a2371e9 refactor: Complete codebase improvements per engineering principles
- Fix currency defaults (SATS → CHF) across forms, configs, and API routes
- Remove @ts-nocheck from socialService.ts and improve type safety
- Replace console.log statements with proper logger utility in production code
- Additional type safety improvements and code quality enhancements
- Documentation updates for improved maintainability

All changes follow DRY, SSOT, and separation of concerns principles.
2026-01-04 12:25:26 +01:00