An API key that never reaches the browser
Your API key or each customer's own key, used from your server without ever reaching a browser
For when the answer to “It calls an AI or a paid API with a secret key” is yes.
In SaaS, BYOK or "bring your own key" means each CUSTOMER supplies a provider key and your app holds it in custody.
Skip the rebuild
You do not write this one. It arrives in your project as ordinary source you can read, change and keep, with its audit record and its caveats beside it.
- Download the Playground. It is free and runs on your own machine.
- Start a new app and tick “It calls an AI or a paid API with a secret key”.
- This block is written in, along with anything else you ticked.
The mistake it removes
Two failures, both quiet until they are expensive. A key that reaches the client is public the moment the bundle ships and can only be rotated, never hidden, and it is not just a bundle: a config endpoint, a source map, or an error body echoed from the provider will all do it. And an unbounded call loop against a metered API is a bill with no ceiling, which arrives overnight and is nobody's fault by morning.
What is already handled
Every item here is checked by running the block’s own tests every time its checks run. Tested means the block’s own test suite runs that code. It does not mean a live run against an outside service such as a payment provider.
- Unit-tested in this repository's suite: the redactor, the ceiling's refusal boundary (the eleventh $1 hold against a $10 ceiling), the refusal on an unpriced response, and the untrusted-content wrapper. Tested
- Executed, not asserted: a mistyped or negative ceiling throws instead of returning unbounded; ten concurrent $1 holds against a $10 ceiling take the whole ceiling as PENDING with $0 yet spent, and the eleventh is refused before any money is spent (the refusal carries statusCode 402); an unpriceable response costs ONE upstream call rather than three and banks the estimate rather than $0. The permitted direction is tested too: a correct ceiling still allows an ordinary call, and every call below the configured rate limit still passes. Tested
- Executed, not asserted: the real vault is handed to gradeVault(), the executable form of rubric 21(b), and passes every clause; a record copied from one tenant's slot into another's is refused; a stopped rotation writes nothing; rotation leaves the key's own ciphertext untouched and re-wraps only the data key; callApi sends each tenant's own key and never the owner's; and a provider error echoing a key the pattern redactor cannot recognize reaches the caller without it. No real provider is called (test/vault.test.mjs). Tested
- Executed, not asserted: the month's spend survives a restart once a durable ledger is passed to useLedger(). The suite writes $9 through to a stand-in table, re-imports the module as a fresh process, reopens the ledger and finds $9 still there, and a $2 hold against the $10 ceiling is then refused with 402 while a $1 hold is allowed. The same run shows the default in-memory ledger starting a restarted process at $0, and assertConfigValid() printing that note once at boot. Tested
- Executed, not asserted, on a faked clock: a call is banked in the month its hold was checked against. An $8 hold taken at 23:59:59 on 31 January and settled after a $5 February call leaves January at $8 and February at $5, where it used to put February at $13 against a $10 ceiling. The hold is released from January while February's own hold stays counted, an unpriced settle banks its estimate in January too, a call held and settled inside one month is unchanged, and with a stand-in table ledger the straddling cost is written to January's row, so a process restarted in February still reads $5. Tested
- Executed, not asserted, on a faked clock: a price above its estimate is recorded in full and stops the month. A $2 hold settled at $50 against a $10 ceiling banks $50, marks the month $40 over, prints a warning naming it, and the next hold is refused with 402, still refused after the ceiling is raised to $100 and allowed again in April. A January hold settling for $100 in June marks January $90 over and leaves June untouched. With a $2 and an $8 hold in flight, a $5 price on the first leaves the month $3 over, exactly the underestimate. Settles at or below their estimates warn, mark and block nothing. Tested
- Executed, not asserted (test/tenant-ceiling.test.mjs): the spend ceiling is PER TENANT. With a $10 tenant ceiling, tenant-a's eleventh $1 hold is refused with 402 and tenant-b, with tenant-a full, still takes its own ten; neither lands in the owner's bucket. Tenant-a at its cap refuses no other tenant and not the owner's key, and the owner at its cap refuses no tenant. Tenant-b settling a $2 hold at $50 marks tenant-b over and nobody else. An abandoned hold goes back to the tenant that took it, a settle and an unpriced settle bank in that tenant only, a January hold settled in February lands in that tenant's January, and each tenant's total is written to its own ledger row and read back after a restart. Through callApi with a vault, a tenant at its $1 ceiling is refused before any request goes out while another tenant's call goes through, and ten concurrent calls at $0.25 against $1 let exactly four out. Tested
- Executed, not asserted, with a stubbed KMS client and no AWS call (test/kms.test.mjs): a vault whose master is an AWS KMS key passes every clause of the vault bar. The bar also catches the KMS-specific defect it was pointed at: an adapter whose Decrypt leaves out the key id fails at-rest-needs-master and the rotation clause, because KMS then opens a record with the key it was made under. Every Encrypt and Decrypt names the configured key and carries the tenant in the encryption context, so a record copied into another tenant's slot is refused by KMS. A KMS outage or an IAM refusal is a 503 that names the AWS error and carries none of its text, stores nothing and leaves a rotation unwritten. Rotation to another KMS key re-wraps only the data key, after which the old key id opens nothing; records move from the built-in master into KMS and back out with rotateMaster(). With BYOK_KMS_KEY_ID unset the built-in vault is used and the AWS SDK is never imported. Tested
What the audit found
Named rather than summarized. The reasoning behind each one ships inside the block, so it travels with the code instead of living on a page you have to trust. A finding marked fixed was fixed after the audit ran; the verdict above is still the one the audit gave.
- The monthly spend ceiling lives only in process memory and resets to $0 on every restart; the block does not say so major · 12 API cost & abuse safety / 25(d0) reported-but-unenforced control Fixed after the audit in
d40ad746c - redact() strips hostnames and ordinary identifiers, so the error a caller receives loses what it needs to diagnose minor · 7 Error handling & resilience (redaction over-eats diagnostic context) Fixed after the audit in
afdb3538d - dd.json says the vault is 'awaiting an independent verifier' while block.json and the archive say it was confirmed minor · 25 Claims match behavior (d: a doc describing a state that has since changed) Fixed after the audit in
3ec1497eb - Two functions over 100 lines; no circular imports; floor otherwise clear minor · 9 Code quality (mechanical floor, counted not judged) Fixed after the audit in
df83161ef
What you still have to do
A copied file cannot own your secrets, your host or your legal obligations. This is the part the block deliberately does not claim.
- Your own authenticated caller id, passed to the rate limiter. This block has no user model, and BYOK_RATE_PER_MIN keyed on anything a caller can write (a header, a query param) is not a limit at all.
- A shared-store (Redis/Upstash) rate limiter once you run more than one instance, plus a spend cap set in the provider's own dashboard. The ceiling and the per-minute limit here are per-process: two instances behind a load balancer each enforce their own, so the effective cap is the cap times the instance count.
- API_KEY must live in your host's environment or secret manager and never in a bundled config file, a source map, or a checked-in .env. The redactor covers what leaves this process; it cannot un-ship a key your build already put in the browser bundle.
- Your own review of anything the model's output is allowed to trigger: an allowlist of tool calls, a human step before an irreversible action. wrapUntrusted() marks content as data the model must not obey, which reduces prompt injection; no delimiter scheme eliminates it.
- The vault encrypts, isolates, rotates and deletes, but three things around it are yours. The master: keep it in a secret manager or a KMS, apart from the store, and rotate it with rotateMaster(). The store: a table only the server can read, with backups treated as holding ciphertext under a master you may later retire. The tenant id: take it from your authenticated session and never from a request, or one customer can spend another's key. Blast radius if the store AND the master leak together: every stored customer key, which means those customers' own provider accounts.
- BYOK, SAID PLAINLY: per-customer key custody is built (node/vault.js), passes this repository's vault bar, and was confirmed by an independent verifier, so a search for "BYOK" or "bring your own key" returns this block. The master can be a hex key you supply or a key in AWS KMS (node/kms.js, chosen by setting BYOK_KMS_KEY_ID); the built-in master stays the default when it is unset. Each customer has a spend ceiling of its own: a call made on a customer's stored key is held against that customer's monthly ceiling, never against a pool shared with other customers or with your own key, so one customer at its cap refuses only that customer. What the vault does NOT do: give you a database table (you pass the store), or create, rotate or retire the KMS key itself (that is done in AWS).
- The master is the one secret that opens every record. Keep it out of the store's database, out of the repository and out of any backup of the store. Rotating it re-wraps every record; if any record cannot be opened, rotation writes nothing and names the tenant.
- The spend ceiling counts what THIS app spends. If the same key is used elsewhere the ceiling cannot see it, so it is an upper bound on this app's share, not on the bill.
- WHERE THE SPEND TOTAL LIVES: by default the month's spend is kept in this process's memory, so a restart, a redeploy or a crash returns the month to $0 spent and the ceiling counts from nothing again. assertConfigValid() prints a note at boot while that default is in use. To keep the total across restarts, pass a ledger backed by a database table to useLedger() at startup; it is read once per month and every recorded cost is written through to it.
- Instances that share one useLedger() store overwrite each other's total: each process writes the month's figure as IT counts it, so the last writer wins and the other instance's spend drops out of the table. A shared useTenantLedger() store does the same when it has set() only. Give it an atomic add(tenantId, month, deltaUsd) as well and each banked cost is written as that call's delta instead, so instances sharing a tenant's row sum and nothing is overwritten (test/tenant-ceiling.test.mjs, section 6b). Either way each process checks the ceiling against its OWN count, read from the row when the month loads, so each instance can spend up to the ceiling before it sees what the others spent. Like the rate limit, the ceiling is per process: give each instance its own row, or put one shared ceiling in front of them, before relying on one cap across instances.
- callApi() needs `estimateUsd`, a positive upper guess at the call's cost, whenever a ceiling is set. It is held against the ceiling for the duration of the call and replaced by the real price afterwards. Without a reservation the ceiling is a tripwire rather than a cap: every call in flight reads a total none of the others has written to yet.
- THE EXACT GUARANTEE. If every estimateUsd is a true upper bound for its call (for a model: the input price plus max_tokens times the output price), a month never goes over BYOK_MONTHLY_USD. If a real price comes in above its estimate, the real price is still recorded, because the call was made and billed and a clamped ledger would lie. The month can then go over, but only by what that call and any others already in flight beat their estimates by. The settle that takes it over marks the month (overCeilingMonths()) and prints a warning naming the overshoot, and every later call that month is refused with 402 until the calendar month changes, even if the ceiling is raised in the same process. Every settle above its estimate is listed by underestimatedCalls(). The mark lives in this process; after a restart on a durable ledger, the banked total above the ceiling keeps refusing on its own.
- If a response cannot be priced, the call still happened and was still billed, so the ESTIMATE is recorded and the error is not retried. That is an approximation of the true cost, and it is deliberate: the alternative is recording a paid call as $0.
- The rate-limit map is keyed on a caller id you supply, so its size is your cardinality, not ours. Stale entries are swept once a minute and a window containing more than 10,000 distinct callers is refused rather than forgotten.
What lands in your project
node
- node/byok.js
- node/vault.js
- node/kms.js
callApi(): the key read server-side only, a hard timeout, a bounded retry, per-caller rate limiting, a spend ceiling that RESERVES before the call and settles after it (kept in memory unless you pass a durable ledger to useLedger()), a separate monthly ceiling per customer when a customer's stored key is spent (useTenantLedger() keeps those totals), a startup refusal on any unusable setting, and redact() over every log and error. Pass { vault, tenantId } to spend that customer's stored key instead of API_KEY. createKeyVault({ store, master }) in vault.js: put, use, revoke, rotateMaster, list. Pass { store, kms } instead to keep the master in AWS KMS: createAwsKmsKek(), kmsFromEnv() and vaultFromEnv() in kms.js. Only kms.js needs @aws-sdk/client-kms, and only when BYOK_KMS_KEY_ID is set; it is imported on demand, so the block loads without it. Plus wrapUntrusted() for the model case.
Needs @aws-sdk/client-kms ^3 from npm.
What you supply
- API_KEY: server-side environment variable. Never import this into anything the bundler can see.
- BYOK_MONTHLY_USD: the spend ceiling in dollars, and it is REQUIRED. Unset, mistyped or negative REFUSES TO START: a ceiling that falls back to unbounded on a typo is worse than none, because the healthy state is silent too. Set a number, or set it to the word `unbounded` to say out loud that you accept a bill with no ceiling.
- BYOK_RATE_PER_MIN: per-caller request cap, keyed on your authenticated user id, never on a header a caller controls. Unset defaults to 20/min, which is still a bound; a value that is not a whole number above zero REFUSES TO START.
- BYOK_TENANT_MONTHLY_USD: OPTIONAL. The monthly ceiling EACH customer gets for calls made on its own stored key, in dollars, or the word `unbounded`. Every tenant gets the whole figure for itself; it is not a pool. Unset, each tenant gets the BYOK_MONTHLY_USD figure for itself. Set and unreadable REFUSES TO START. setTenantCeilings(tenantId => dollars) overrides it per tenant (a plan, a contract), and a resolver that throws or returns something unreadable refuses the call.
- BYOK_MASTER_KEY: the vault's built-in master key, 64 hex characters from `openssl rand -hex 32`, read with masterFromEnv(). Used when BYOK_KMS_KEY_ID is unset. Unset or malformed REFUSES TO START. Keep it in your secret manager, never beside the store: whoever holds both holds every customer's key.
- BYOK_KMS_KEY_ID: OPTIONAL. The AWS KMS key (id, ARN or alias) that wraps every customer's data key instead of BYOK_MASTER_KEY, read by kmsFromEnv()/vaultFromEnv(). Needs `npm i @aws-sdk/client-kms`, a region, and an IAM role allowed kms:Encrypt and kms:Decrypt on that key; credentials come from the AWS SDK's default chain. Setting both this and BYOK_MASTER_KEY REFUSES TO START: move existing records with rotateMaster(await kmsFromEnv()), then unset BYOK_MASTER_KEY.
- BYOK_KMS_REGION: OPTIONAL. The region the KMS key lives in; AWS_REGION or AWS_DEFAULT_REGION is used when it is unset. With BYOK_KMS_KEY_ID set and no region at all, the vault REFUSES TO START.
Licensed MIT. It is a starting point, not a finished product.
Get it
Download the Playground See the other blocks
Nothing here is locked. The files are yours, in your folder, under a permissive license.
Questions
- Is An API key that never reaches the browser audited?
- It was audited on 2026-09-29, and the verdict was not a clean pass. 4 findings have been fixed since then, and the verdict stands until the block is audited again.
- What do I still have to do myself?
- Your own authenticated caller id, passed to the rate limiter. This block has no user model, and BYOK_RATE_PER_MIN keyed on anything a caller can write (a header, a query param) is not a limit at all.
- How do I get this code?
- Download the Playground, start a new app, and tick “It calls an AI or a paid API with a secret key”. The block is written into your project as ordinary source you can read and edit.
All pre-built code blocks · Learn to build from zero · The coding guide