Skip to content

refactor(syntropy): bounded TTL cache + config DI follow-ups from PR #9 review - #12

Merged
supmo668 merged 1 commit into
mainfrom
fix/syntropy-followups-cache-config-di
May 12, 2026
Merged

supmo668 merged 1 commit into
mainfrom
fix/syntropy-followups-cache-config-di

Conversation

@supmo668

Copy link
Copy Markdown

Summary

Addresses items 2 + 3 from the PR #9 code review follow-up list. Item 1 (token storage hardening) is intentionally NOT in this PR — see below for the Unkey alignment finding.

Changes

Item 2 — bounded TTL cache (replaces unbounded `Map`)

`extensions/syntropy/src/cache.ts` — `TtlCache<K,V>` with:

  • TTL per entry (10 min for the user-cache use case)
  • Size-bounded with oldest-inserted eviction on overflow (10 000 entries)
  • Lazy expiry on `get` (no background timers; zero-async)
  • 11 unit tests covering set/get/expiry/eviction/bounded/error paths

`extensions/syntropy/src/index.ts` — `resolvedUsers` switched from `new Map<string, ResolvedUser>()` to a `TtlCache` instance. Long-running gateways no longer accumulate stale entries indefinitely; stale tokens drop out after a server-side rotation rather than persisting until process restart.

Item 3 — config DI with validation (replaces silent localhost fallback)

`extensions/syntropy/src/config.ts` — `parseSyntropyConfig(raw, env)`:

`extensions/syntropy/src/index.ts` — `register()` now parses config at plugin registration time; on failure logs the structured error and returns early ("plugin disabled") rather than running with bogus defaults.

Item 1 — Unkey for token storage (intentionally NOT in this PR)

Unkey is the documented system-of-record for SJ-side API token issuance + verification (see `apps/Syntropy-Journals/.claude/PRPs/prds/unkey-migration.prd.md`).

Alignment finding: openclaw is a downstream consumer of already-issued `sj_*` tokens — it stores them as Bearer credentials for subsequent MCP calls. Unkey's API doesn't include a "vault arbitrary secret" primitive; storing tokens in `key.meta` would be an abuse pattern, not the design intent.

Verdict: Unkey is the right answer for SJ; wrong tool for openclaw's storage layer. Recommend pgcrypto column-level encryption on `syntropy_tokens.auth_token` with the encryption key sourced from Infisical (matches the project's existing secrets discipline).

Tracked as a separate follow-up — security-sensitive enough to merit its own review cycle, and orthogonal to the cache/config work here.

Verification

```
pnpm oxlint --type-aware extensions/syntropy/src/
→ 0 warnings, 0 errors

pnpm tsc --noEmit -p tsconfig.json
→ 0 errors in extensions/syntropy/ (pre-existing bluebubbles error unrelated)

pnpm vitest run extensions/syntropy --config vitest.extensions.config.ts
→ 22/22 tests passing (11 cache + 11 config)
```

Test plan

… review

Addresses items 2 + 3 from the PR #9 code review follow-up list. Item 1
(token storage hardening via Unkey) is intentionally NOT in this PR —
see commit body for the alignment finding.

## Changes

### Item 2 — bounded TTL cache (replaces unbounded Map)

`extensions/syntropy/src/cache.ts` — `TtlCache<K,V>` with:
- TTL per entry (10 min for the user cache use case)
- Size-bounded with oldest-inserted eviction on overflow
- Lazy expiry on `get` (no background timers; zero-async)
- 11 tests covering set/get/expiry/eviction/bound/error paths

`extensions/syntropy/src/index.ts` — `resolvedUsers` switched from
`new Map<string, ResolvedUser>()` to a `TtlCache` instance with
`ttlMs: 10*60_000, maxSize: 10_000`. Long-running gateways no longer
accumulate stale entries indefinitely; stale tokens drop out after a
server-side rotation rather than persisting until process restart.

### Item 3 — config DI with validation (replaces silent localhost fallback)

`extensions/syntropy/src/config.ts` — `parseSyntropyConfig(raw, env)`:
- TypeBox-validated schema for `{ syntropyBaseUrl, databaseUrl }`
- `syntropyBaseUrl` is REQUIRED in production (NODE_ENV=production).
  Missing field throws a structured error rather than silently routing
  to `http://localhost:3000`.
- `databaseUrl` accepts explicit `pluginConfig.databaseUrl` first, then
  `env.DATABASE_URL`, then throws.
- Dev fallback to localhost retained for local-dev ergonomics.
- Unknown fields stripped (no silent leak into plugin closure).
- 11 tests covering valid input, production failure modes, dev fallback,
  layered DB URL precedence, URL parseability, and error message ops-debug
  context.

`extensions/syntropy/src/index.ts` — `register()` now parses config at
plugin registration; on failure logs the structured error and returns
early ("plugin disabled") rather than running with bogus defaults.

## Item 1 (Unkey for token storage) — not in this PR

Unkey is the documented choice for SJ-side API token *issuance +
verification* (per `apps/Syntropy-Journals/.claude/PRPs/prds/unkey-migration.prd.md`).
Openclaw stores already-issued `sj_*` tokens as Bearer credentials for
downstream MCP calls — a different use case. Unkey's API doesn't include
a "vault arbitrary secret" primitive; storing tokens in `key.meta` would
be an abuse pattern.

Recommended next step is pgcrypto column-level encryption on
`syntropy_tokens.auth_token` with the encryption key sourced from
Infisical. Tracked as a separate follow-up — security-sensitive enough
to merit its own review cycle, and orthogonal to the cache/config work
here.

## Verification

```
pnpm oxlint --type-aware extensions/syntropy/src/
  → 0 warnings, 0 errors
pnpm tsc --noEmit -p tsconfig.json
  → 0 errors in extensions/syntropy/ (pre-existing bluebubbles error unrelated)
pnpm vitest run extensions/syntropy --config vitest.extensions.config.ts
  → 22/22 tests passing
```
@supmo668
supmo668 merged commit 1132d48 into main May 12, 2026
6 of 10 checks passed
@supmo668
supmo668 deleted the fix/syntropy-followups-cache-config-di branch May 12, 2026 19:27
@github-actions

Copy link
Copy Markdown

⚠️ Formal models conformance drift detected

The formal models extracted constants (generated/*) do not match this openclaw PR.

This check is informational (not blocking merges yet).
See the formal-models-conformance-drift artifact for the diff.

If this change is intentional, follow up by updating the formal models repo or regenerating the extracted artifacts there.

supmo668 added a commit that referenced this pull request May 12, 2026
…up, Item 1) (#13)

Closes the plaintext-token finding from the PR #9 review (Item 1) by
leaning on Supabase Vault rather than building column-level encryption
in Fly.io Postgres.

## Architecture

Tokens are stored in the existing **mobile Supabase project** at
`mmxvpogrdnblzgdeuhne.supabase.co`, accessed via three SECURITY DEFINER
RPCs that scope service_role access to the `syntropy_user_*` namespace:

  - app_syntropy_token_set(p_name, p_plaintext)
  - app_syntropy_token_get(p_name)            -- returns text|null
  - app_syntropy_token_delete(p_name)

SQL migration at `extensions/syntropy/supabase-migrations/0001_syntropy_vault_rpcs.sql`
must be applied to the mobile Supabase project before openclaw deploys
with Vault enabled in production.

The Fly.io `syntropy_tokens` table now stores only `vault_secret_name`
(the lookup key); the actual plaintext never reaches openclaw's DB.

## Files

NEW:
- `src/vault.ts` — `SyntropyVault` wrapper + `createSupabaseVault` factory
  with injectable RPC client (testable without a live Supabase project)
- `src/vault.test.ts` — 14 unit tests (set/get/delete + validation)
- `supabase-migrations/0001_syntropy_vault_rpcs.sql` — SECURITY DEFINER
  RPCs + grants. Scopes service_role access to `syntropy_user_*` names only.

MODIFIED:
- `src/config.ts` — added `supabaseUrl` + `supabaseServiceRoleKey` fields.
  Both required in production; both optional in dev for legacy plaintext
  fallback during local development.
- `src/config.test.ts` — 6 new tests (now 17 total) covering Supabase
  field validation + env-var fallback chain.
- `src/db.ts` — schema migration adds `vault_secret_name TEXT` column,
  makes `auth_token` nullable. Dual-write path: when vault available,
  writes to vault + writes secret name to Postgres with auth_token=NULL.
  Falls back to plaintext column when vault not configured (dev only).
- `src/index.ts` — `resolveUser` reads from vault when `vault_secret_name`
  is present, falls back to legacy `auth_token` for pre-migration rows.
  Logs which path was used so ops can monitor backfill progress.

ADDED DEPENDENCY:
- `@supabase/supabase-js@^2.105.4` in `extensions/syntropy/package.json`

## Config — Infisical key paths (need provisioning)

- `SUPABASE_URL` — already exists for mobile; mirror to openclaw scope
- `SUPABASE_SERVICE_ROLE_KEY` — NEW; service-role JWT from the mobile
  Supabase project. Required to be granted only to openclaw.

## Failure semantics

| Scenario                          | Behaviour                                         |
|-----------------------------------|---------------------------------------------------|
| Vault reachable, secret present   | Decrypt + return; populate TtlCache (10 min)      |
| Vault reachable, secret missing   | Return null → SYNTROPY_GATE fires                 |
| Vault unreachable in production   | Throws from resolveUser → SYNTROPY_GATE fires     |
| Vault not configured in dev       | Falls back to legacy `auth_token` column          |

Better to deny than fall back to plaintext in production.

## Migration plan

This PR does NOT backfill existing plaintext rows. A separate follow-up
PR will:
1. Walk all `syntropy_tokens` rows with `auth_token IS NOT NULL`
2. For each: call `vault.set('syntropy_user_<userId>', auth_token)` then
   `UPDATE syntropy_tokens SET vault_secret_name = ..., auth_token = NULL`
3. Verify no plaintext remains: `SELECT count(*) FROM syntropy_tokens WHERE auth_token IS NOT NULL`
4. `ALTER TABLE syntropy_tokens DROP COLUMN auth_token`

Until that PR lands, reads transparently use whichever column is populated.

## Verification

  pnpm vitest run extensions/syntropy --config vitest.extensions.config.ts
    → 42/42 tests passing (11 cache + 17 config + 14 vault)

  pnpm tsc --noEmit -p tsconfig.json
    → 0 errors in extensions/syntropy/

  pnpm oxlint --type-aware extensions/syntropy/src/
    → 0 warnings, 0 errors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant