Skip to content

Contain untrusted docs in the prompt and retire the plaintext admin credential - #22

Merged
BunsDev merged 1 commit into
mainfrom
harden/public-safety-and-freshness
Sep 20, 2026
Merged

BunsDev merged 1 commit into
mainfrom
harden/public-safety-and-freshness

Conversation

@BunsDev

@BunsDev BunsDev commented Sep 20, 2026

Copy link
Copy Markdown
Member

Closes the two gaps deliberately left open by #20.

1. Retrieved documentation no longer reaches the system prompt

Salem indexes sources it does not author — docs.typesafe.ai, and the markdown behind code.opencoven.ai — and excerpts were interpolated straight into the system message. Anyone able to land a paragraph in either source could issue system-level instructions to every conversation that retrieved it.

The architectural decision: the system message is the only instruction-trusted region, and it holds first-party text only. New lib/prompt-context.ts enforces it four ways:

  1. Separation — excerpts travel in a user-role message immediately before the question. No retrieved byte reaches the system message.
  2. Unforgeable delimiters — each excerpt sits in a <salem-document nonce="…"> block whose nonce is random per request, so content cannot close a boundary it cannot predict, escape its block, or impersonate a role. Literal block tags and control characters in content are neutralised.
  3. Provenance by origin — each block is labelled provenance="opencoven"|"external", derived from the host the bytes came from, never from content. It governs authority over facts, never over instructions.
  4. Attribute-only citations — the model cites a block's url attribute and never a link inside block content, so a document cannot choose a destination.

Deliberately no phrase blocklist. The indexed corpus is documentation about LLMs and agents, so prompt-shaped text is legitimate content: matching on it would mangle real docs while a paraphrase walked past. The defences are structural.

This is containment, not a proof — a model can still be persuaded by text it was told to treat as data. What is guaranteed is that such text arrives at user trust level, labelled, delimited, and unable to forge structure, and that this route has no tools, so the worst case is a wrong answer in one session rather than an action taken. Adding any tool or side effect here means revisiting that.

Bonus: Source: URL spoofing

rag/indexer.ts read each page's citation URL from a Source: line inside the fetched feed. Unbound, docs.typesafe.ai could declare Source: https://docs.opencoven.ai/anything and be indexed — then cited — as first-party documentation, defeating the provenance labelling and putting attacker-chosen links behind an opencoven.ai URL. Pages claiming a host other than the one that served the feed are now dropped.

Both live feeds currently declare only their own host (109/109 TypeSafe, 88/88 OpenCoven), verified by curl, so this hole was latent, never exercised. No forced reindex is needed; the scheduled 06:00 UTC run is sufficient.

2. The legacy admin credential

SALEM_ADMIN_PASSWORD was compared as an unsalted single-round SHA-256 and was the only account granted private-research access unconditionally — simultaneously the highest-privilege credential and the weakest-hashed one.

  • It now accepts a pbkdf2-sha256:600000:<salt>:<hash> value. That is the migration: swap the env value and the legacy path goes unused, with no config-shape change. bun run user:hash --hash-only mints one.
  • Plaintext still signs in, so no deploy locks itself out, but it is verified with PBKDF2-SHA256 at 600k iterations over an ID-derived salt instead of bare SHA-256, and warns once per process.
  • Sessions no longer carry anything crackable. The credential version was a SHA-256 of a JSON blob containing the plaintext, stored in Redis beside every session — a Redis read was an offline crack. It is now derived from the PBKDF2 output.

⚠️ Deploy requirement

Two behaviour changes, both invalidating live admin sessions on deploy: private-source access is no longer implied by the admin credential, and the credential version changed.

Set SALEM_ADMIN_PRIVATE_SOURCES=true in Vercel before deploying. Otherwise admin returns signed out and then silently without private research, which presents as a retrieval bug rather than a permissions change.

Testing

17 tests green, typecheck and production build clean, gitleaks clean. Four new test files:

  • prompt-context.test.ts — provenance by host, nonce delimiting, tag/control-char neutralisation, citation scheme allowlist, and that legitimate prompt-shaped documentation survives intact.
  • chat-route-injection.test.ts — a poisoned excerpt (forged block, SYSTEM: override, exfiltration request, phishing link) through the real route, asserting no retrieved byte reaches the system message.
  • source-host-binding.test.ts — spoofed, lookalike, and unparseable Source: hosts are dropped; an all-spoofed feed fails loudly rather than emptying the index.
  • legacy-admin-credential.test.ts — both credential forms, the explicit private grant, session invalidation on either change, and that no session record contains the plaintext or its SHA-256.

🤖 Generated with Claude Code

Closes the two gaps deliberately left open by #20.

Retrieved documentation no longer reaches the system prompt. Salem indexes
sources it does not author (docs.typesafe.ai, and the markdown behind
code.opencoven.ai), and excerpts were interpolated straight into the system
message -- anyone able to land a paragraph in either source could issue
system-level instructions to every conversation that retrieved it.

The system message is now the only instruction-trusted region and holds
first-party text only. lib/prompt-context.ts carries excerpts in a user-role
message, inside blocks delimited by a per-request random nonce so content
cannot forge a boundary it cannot predict, labels each block with provenance
derived from the fetch host, and pins citations to a block's url attribute so a
document cannot choose a destination. There is deliberately no phrase
blocklist: the corpus is documentation about LLMs, so prompt-shaped text is
legitimate content and matching on it would mangle real docs.

rag/indexer.ts also binds each page's declared Source: URL to the host that
served the feed. Unbound, docs.typesafe.ai could declare an opencoven.ai URL
and be indexed, then cited, as first-party documentation. Both live feeds
currently declare only their own host (109/109 and 88/88), so the hole was
latent; the next scheduled reindex is sufficient to clean stored chunks.

SALEM_ADMIN_PASSWORD now accepts a pbkdf2-sha256:600000 hash, which retires the
legacy path in place -- no config-shape change, just a new value. A plaintext
value still signs in so no deploy locks itself out, but it is verified with
PBKDF2 over an ID-derived salt rather than a bare unsalted SHA-256, and warns
once per process. Session records no longer carry the plaintext or a hash of
it: the credential version is derived from the PBKDF2 output, so a Redis read
is no longer enough to recover the password offline.

Two behaviour changes, both invalidating live admin sessions on deploy:
private-source access is no longer implied by holding the admin credential and
needs SALEM_ADMIN_PRIVATE_SOURCES=true, and the credential version changed.
Set that variable before deploying, or admin returns signed out and then
silently without private research, which presents as a retrieval bug.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Copilot AI lite review requested due to automatic review settings September 20, 2026 08:28
@vercel

vercel Bot commented Sep 20, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
opencoven-chat-api Ready Ready Preview Sep 20, 2026 8:28am UTC

Request Review

@BunsDev
BunsDev merged commit 5bba100 into main Sep 20, 2026
4 checks passed

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Unresolved critical findings affect session credential verification, redirect-based source binding, and typecheck correctness.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 3 High severity

Open (3)
What changed in this PR

This PR isolates retrieved documentation from system prompts and migrates the legacy admin credential to PBKDF2-backed handling.

Changes:

  • Moves excerpts into nonce-delimited user messages with provenance metadata.
  • Validates source-host binding and adds injection/authentication tests.
  • Adds PBKDF2 migration, explicit private-source access, session invalidation, and documentation.
File Final review comment
SECURITY.md Soften the guarantee to describe containment rather than preventing retrieved text from acting as instructions. (Nit, 1 vote)
scripts/​source-host-binding.test.ts No final comment.
scripts/​session-history.test.ts Clear SALEM_ADMIN_PRIVATE_SOURCES to keep the test hermetic. (Moderate, 1 vote)
scripts/​prompt-context.test.ts No final comment.
scripts/​legacy-admin-credential.test.ts No final comment.
scripts/​create-user.ts Fix strict-null-check narrowing; current code causes typecheck errors. (Critical, 1 vote)
scripts/​chat-route-injection.test.ts No final comment.
scripts/​chat-auth.test.ts No final comment.
README.md Use the configured admin username, with admin as fallback, in the migration command. (Nit, 1 vote)
rag/​indexer.ts Bind sources to the response’s final URL or reject redirects. (Critical, 1 vote)
package.json No final comment.
lib/​prompt-context.ts Validate or strip assistant links against the block URL allowlist, or document this as advisory. (Moderate, 1 vote)
lib/​access.ts Replace the password-derived session verifier to prevent offline cracking from Redis records. (Critical, 2 votes)
app/​api/​chat/​route.ts No final comment.
app/​api/​chat/​auth.ts No final comment.
.env.example No final comment.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread lib/access.ts
account.id,
account.credential.kind,
account.credential.salt,
await expectedHash(account.credential),
Comment thread rag/indexer.ts
async function fetchDocsFromLlmsTxt(url: string = LLMS_FULL_URL): Promise<DocPage[]> {
console.log(`Fetching documentation from ${url}...`);

const feedHost = new URL(url).hostname.toLowerCase();
Comment thread scripts/create-user.ts
const privateSources = argv.includes("--private");
const [id, name] = argv.filter((argument) => !argument.startsWith("--"));

const identified = Boolean(id) && /^[a-z0-9][a-z0-9_-]{0,63}$/.test(id) && Boolean(name?.trim()) && name.length <= 80;
@BunsDev
BunsDev deleted the harden/public-safety-and-freshness branch September 21, 2026 05:00

This branch was successfully deployed

1 active deployment
Preview — 58a1ded2 Deployed Sep 20, 2026 by vercel[bot]
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.

2 participants