@blindsight/security
v1.1.0
Published
Official TypeScript/JavaScript SDK for Blindsight Runtime Security: scan prompts, responses, files and tool-calls, or route your LLM traffic through the guardrail reverse proxy.
Maintainers
Readme
Blindsight Runtime Security: TypeScript SDK
The official TypeScript/JavaScript client for Blindsight Runtime Security. Inspect prompts, responses, files, and agent tool-calls for prompt injection and sensitive data, or route your existing LLM client through the guardrail proxy.
Requirements
- Node.js 18+ (or any runtime with a global
fetch) - Zero runtime dependencies
Installation
npm install @blindsight/securityQuick start
Scan the prompt before it reaches the model, and the response before it reaches the user:
import OpenAI from "openai";
import { RuntimeSecurity } from "@blindsight/security";
const rs = new RuntimeSecurity({
baseUrl: "https://platform.blindsight.io",
apiKey: "ak_…",
appId: "<App id>", // optional
});
const openai = new OpenAI();
const verdict = await rs.scanInput(userText, { provider: "openai", model: "gpt-4o" });
if (verdict.blocked) throw new Error(verdict.blockedReason ?? "blocked");
const safePrompt = verdict.safeText; // redacted when the prompt carries PII
const completion = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: safePrompt }],
});
const answer = completion.choices[0].message.content ?? "";
const result = await rs.scanOutput(answer, { prompt: safePrompt });
const final = result.safeText; // empty when blockedScanning
Content the user did not write
If the prompt is assembled from more than the user's own words, say so. Pass the retrieved documents, tool results, fetched pages or email bodies as untrusted spans and the firewall judges them as data: inside a declared span an instruction aimed at the assistant is a finding however ordinary it sounds, because the user never asked for it.
const verdict = await rs.scanInput(prompt, {
untrusted: [
{ content: chunk, source: "retrieval", label: "kb-8842" },
{ content: toolOutput, source: "tool_result", label: "calendar" },
],
});
for (const i of verdict.untrusted?.flaggedSpans ?? []) {
console.warn(`span ${i} was steering the model; dropping it`);
}Why it matters: the hardest indirect injections are not menacing. "Summarize the main findings of the 2020 climate report" is the most ordinary request there is from a user, and an attack from inside a retrieved document. Nothing in the text separates the two, only where it came from.
tool_result and web are strict by default, because a tool returning prose
that tells the assistant what to do next is compromised or misdesigned. The
others are balanced, because retrieved prose legitimately contains imperatives
and questions. Override per span with strictness. A bare string is accepted
and defaults to retrieval. At most 32 spans, and only scanInput takes them.
Findings come back per span on verdict.untrusted, so an offending document can
be dropped or re-fetched without failing the whole request. It is undefined
when no spans were declared, which is not the same as declared and clean.
Conversations
An App can act on one kind of personal data only when another has been part of
the same conversation, for example mask a person's name only once a national
ID or an account number has appeared, in an earlier turn or a later one. Name
the conversation with sessionId and, optionally, number the turns:
const result = await rs.scanInput(prompt, { sessionId: conversationId, turn: 3 });
// undefined when the App has no conversation conditions
for (const item of result.conversation?.exposedEarlier ?? []) {
// An earlier turn sent a value out before this turn's trigger arrived.
purgeTurn(item.turn);
}result.conversation.state is new, continued, unknown (a later turn of a
conversation the platform no longer remembers), saturated or unavailable.
In the last three the App's setting decides: by default every target is masked
as if its trigger had been seen. A retried call with the same turn is not
counted twice. The platform remembers keyed hashes and data-type labels, never
the values or the conversation id.
Pseudonymize and restore
On an App set to pseudonymize, personal data comes back replaced, with a
mapping to the real values in result.pseudonyms. Personal names, email
addresses and phone numbers can be replaced by realistic stand-ins (a name that
looks like a name, an address at a reserved example domain); every other type is replaced by a
numbered token such as <IBAN_1>, and one text can hold both.
result.pseudonymFormat says which you got: "stand_in" when the mapping holds
at least one stand-in, "token" otherwise. Send the replaced text to your model
and put the values back in its reply with the SDK's restore, not by parsing the
text yourself:
import { restoreReply } from "@blindsight/security";
const inp = await rs.scanInput(userText, { sessionId: conversationId });
const reply = await callYourModel(inp.safeText); // the model sees the replaced text only
const out = await rs.scanOutput(reply, { prompt: inp.safeText, sessionId: conversationId });
if (out.blocked) return "Sorry, I can't help with that.";
const res = restoreReply(out.safeText, inp, out); // one restore for the whole turn
if (res.unrestored.length) return "Sorry, I can't answer that right now."; // or ask the model again; never show res.text
const final = res.text; // the user's own values are back inrestoreReply joins the mappings of the input and output scans and restores once.
Personal data the model wrote on its own, which the output scan hid, stays hidden
([hidden]); a stand-in the output scan masked a second time is put back, or listed
in unrestored. result.restore(text) of version 1.0 uses one result's mapping only;
it keeps working but logs a warning (console.warn) when it leaves a stand-in.
restore works for both formats in one pass, longest replacement first, and
never expands a restored value again. Only the keys of the mapping are
restored. A stand-in name matches on word boundaries in the case it was issued
(and in ALL CAPS when it has four letters or more), so an ordinary word is never
touched; an English possessive or a German genitive s right after it is
tolerated. A first name or surname the mapping holds beside the full name is
restored too ("Hi Elif", "Dear Ms. Hargreaves", "Hargreaves, Elif"), unless it
stands next to another capitalised name word. Emails and phone numbers match
exactly. A stand-in inside anything that can be a link or a resource is left as
it is. unrestored lists the stand-ins it could not restore (found in a link, in
another case, spelled another way, or next to an initial), once per full name,
email or phone: look at it before you show the text. An empty list is not a
promise that nothing fake is left.
The output scan takes known_stand_ins (the keys of the stand-ins already issued, never the originals): on an output scan the server leaves the whole issued name, email or phone in place for the restore, and new stand-ins avoid these keys, so two people never share a part across turns when there is no session. The SDK sends it for you from the stand-ins it saw for the session id; without a session id pass the knownStandIns option.
For a caller that uses stand-ins, a reply that addresses the person in a greeting (a common greeting in English, German, French, Italian, Spanish or Portuguese, optionally a title, then the first name or the surname, followed by a comma, an exclamation mark, a colon or a line break) keeps that name for the restore. The output scan result lists the stand-ins it masked a second time in reMaskedStandIns; restoreReply uses it.
restoreReply never restores a key that two of its results map to different values (for example <IBAN_1> in two turns scanned without a session id): it leaves the key in the text and lists it in unrestored. Pass a session id, or restore each turn with its own results. Entries of an output scan that the server does not list as masked again stay hidden, and a token it lists in standInVariants (a variant of an issued stand-in) stays hidden with the issued name it resembles listed in unrestored.
If your reply uses only part of a name somewhere else ("Hi Elif,") and you scan it with the
output scan before restoring, the output scan masks that part again; after
restore it comes back as the stand-in part and the full name is listed in
unrestored: reported, never silent, and a real third person is never renamed.
Restoring without an output scan in between restores the part. Pass true as the second argument of restore or restoreDetailed to never restore parts and only report them. To see the list, use restoreDetailed:
const res = restoreReply(out.safeText, inp, out);
if (res.unrestored.length) console.warn("not restored:", res.unrestored); // e.g. ["Keller"]
const final = res.text;A stand-in is only sent to a caller that can restore it: this SDK says so with
every request (X-Blindsight-SDK), so on SDK 1.1 or later you get stand-ins
without doing anything. Pass { pseudonymFormat: "token" } to scanInput,
scanOutput, scanBatch or scanDocument to get numbered tokens only. A
caller that sends plain HTTP asks for stand-ins with
"pseudonym_format": "stand_in" in the request and restores through
/scan/restore; a caller that asks for nothing gets numbered tokens. SDK 1.0
only understands numbered tokens, so upgrade to 1.1 before you rely on stand-ins.
1.1 sends X-Blindsight-SDK: @blindsight/security/1.1.0 with every request, and
the mapping stays in your hands: Blindsight does not keep it.
Send the same sessionId for a whole conversation and the text the model saw
as prompt. Hiding the output's own placeholders before restoring means a
value the model wrote itself is never replaced by one of your user's values.
Each call numbers its tokens from 1, so <PERSON_1> in two calls can be
two people (and a stand-in is only fixed for a call or a sessionId): if your model is given the earlier turns too, renumber each turn
into one numbering for the conversation before you send it, and restore with
that conversation's mapping. A placeholder is <KIND_n>, sometimes with a
short tag before the number (<PERSON_T3_1>); restore handles both. The
mapping is in the response only. Keep it server-side and never log it.
Files
import { readFile, writeFile } from "node:fs/promises";
const bytes = await readFile("resume.pdf");
const result = await rs.scanFile(bytes, { filename: "resume.pdf", mediaType: "application/pdf" });
if (result.wasRedacted) await writeFile("resume.clean.pdf", result.fileBytes);Agent tool-calls
import { assertNotBlocked } from "@blindsight/security";
const gate = await rs.scanToolCall("delete_file", { path: requestedPath });
assertNotBlocked(gate); // throws ContentBlockedError on a block verdict
await deleteFile(gate.safeArguments);Batch
Up to 32 texts in a single round-trip:
const results = await rs.scanBatch([
{ text: docA, direction: "input" },
{ text: docB, direction: "input" },
]);Long documents (Unreleased)
scanDocument splits a text of any length at paragraph, sentence and
whitespace boundaries (never inside a word), scans the pieces in order and
gives you one result. A name that appears in piece 1 and piece 5 gets one
token, and restore works on the whole document.
const doc = await rs.scanDocument(longText, 16000);
const safe = doc.redactedText; // the pieces joined
const res = restoreReply(await llm(safe), doc); // originals back; check res.unrestored before you show res.text
const answer = res.text;
console.log(doc.billableRequests); // the Billable-Requests headers, summedOn a 413 it splits again once at the size the API recommends. Chunking can add
at most one request per piece compared with one large call. New error classes:
BlindsightTextTooLongError (both text_too_long and PAYLOAD_TOO_LARGE),
BlindsightPlanRequiredError, and BlindsightScanIncompleteError (sent again after its
Retry-After).
Result fields
Every result exposes uuid, verdict, injection, pii, redactedText,
blockedReason, latencyMs, and textLength, along with the boolean flags
allowed / flagged / redacted / blocked, plus safeText,
injectionScore, piiCategories, and raw (the full JSON response). Use
assertNotBlocked(result) to throw on a block verdict.
Reverse proxy
Route an existing vendor client through the guardrail without writing explicit scan calls:
import OpenAI from "openai";
const openai = new OpenAI({ apiKey: OPENAI_KEY, ...rs.proxy.openai() });
import Anthropic from "@anthropic-ai/sdk";
const anthropic = new Anthropic({ apiKey: ANTHROPIC_KEY, ...rs.proxy.anthropic() });Additional providers are available via rs.proxy.gemini(), rs.proxy.vertex(),
rs.proxy.bedrock(), and rs.proxy.openaiCompatible({ provider: "groq" }). Each
returns { baseURL, defaultHeaders }, ready to spread into the vendor client
options.
Error handling
All exceptions derive from BlindsightError:
BlindsightApiError: a non-2xx answer, with.statusCode,.code(for exampleAPP_NOT_ALLOWED) and.retryAfterwhen the answer gave oneBlindsightAuthError(401 / 403): a wrong, revoked or expired key, or a key not allowed for this AppBlindsightQuotaError(402 / 429). A 429 with codeDAILY_ALLOWANCE_SOFT_LIMITis temporary: requests are paced, so wait.retryAfterseconds and send the same call again
BlindsightConnectionError: no answer (network failure or timeout)ContentBlockedError: thrown byassertNotBlocked()on a block verdict
Error messages never contain your key or the text you sent.
When Blindsight cannot answer
The client never answers for you. Every failure is thrown, so nothing reaches your model unscanned unless your own code decides to send it. Choose what your application does in that case: refusing to answer is the safe default; answering without protection sends personal data to your model.
timeoutMs(default 10000) bounds each request.maxRetries(default 2) retries a 429 or a 503, and a connection that never reached the server, with a growing pause andRetry-Afterhonoured. A timeout is never retried, because the scan may already have run.maxRetryWaitMs(default 30000) caps the time all retries of one call may wait. A longerRetry-Afteris not waited for: the error is thrown at once, with.retryAfterset.
const rs = new RuntimeSecurity({ baseUrl, apiKey, timeoutMs: 5000, maxRetries: 2, maxRetryWaitMs: 10000 });
try {
const verdict = await rs.scanInput(userText);
} catch (err) {
if (err instanceof BlindsightConnectionError) return "The assistant is unavailable for a moment."; // fail closed
throw err;
}Development
npm install
npm run build # tsc, writes dist/
npm test # builds, then runs node --testLicense
Apache-2.0, Copyright 2026 Blindsight Technologies AG: see LICENSE and
NOTICE. The license covers this client library; the Blindsight service it connects to stays under Blindsight's own
terms of service.
