Skip to content

Add API keys and a daily new-scan allowance to core - #63

Merged
maaland merged 1 commit into
mainfrom
feat/access-core-36
Oct 12, 2026
Merged

maaland merged 1 commit into
mainfrom
feat/access-core-36

Conversation

@maaland

@maaland maaland commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Refs #36

The first of two PRs for #36: the keys and the allowance, in core and Postgres. The next PR adds POST /api/keys and DELETE /api/keys/current and closes #36. #41 (website gating) and #37 (HTTP scan API) spend the allowance.

What changes

packages/core/src/access.ts (no Vercel, no Node-only APIs: Web Crypto only):

  • Subjects: key:<id> for API keys and visitor:<hmac of IP> for anonymous website visitors. The IP is hashed with a secret (an env var, wired in Website gating: anonymous allowance and bot check #41), never stored.
  • createApiKey(ipHash): a key is sp_ plus 32 random bytes in base64url. Stored only as a SHA-256, with its first 10 characters kept to tell keys apart. At most 3 new keys a day per IP, otherwise a LimitError with resetAt. Each new key also drops usage older than 30 days.
  • findApiKey(key): returns the live key, or null if it's unknown, malformed or revoked.
  • allowance / assertAllowance(subject, limit): new scans used today, with the day resetting at UTC midnight. Throws LimitError: "Daily limit of N new scans reached. Recent scans are still free to read. Resets at …".
  • Constants: KEY_SCANS_PER_DAY = 10, VISITOR_SCANS_PER_DAY = 3, KEYS_PER_IP_PER_DAY = 3, USAGE_KEPT_DAYS = 30.
  • AccessStore interface and MemoryAccessStore, with a shared contract suite in core/test/access-contract.ts.

packages/store-postgres:

  • Migration 0003_access.sql: api_keys (hash unique, prefix, ip_hash, limits, created/revoked) and usage (subject, endpoint, new_scan, at), indexed for the counts. Row level security is on with no policies, like the existing tables.
  • PostgresAccessStore passes the same contract suite on PGlite. connectPostgres() now also returns access.

SQLite isn't touched: it only backs the local CLI and MCP, which are never gated.

Checked

  • Contract suite on memory and Postgres. Unit tests cover key format and hashing, revocation, 3 keys per IP with the UTC reset, the 30-day prune, allowance counting (reused scans free, reset at midnight) and visitor hashing (stable, secret-dependent, never the IP).
  • The migration tests list the new tables, with row level security on.
  • pnpm lint, pnpm typecheck, pnpm test (369 passing).

After merge

Run pnpm db:migrate against Supabase to apply 0003.

🤖 Generated with Claude Code

One allowance for every caller: a subject is an API key or an anonymous
visitor (a keyed hash of their IP, never the IP). New scans count
against a daily limit that resets at UTC midnight; reused scans and
reads don't. Keys are sp_ plus 32 random bytes, stored only as a
SHA-256 with their first characters kept to tell them apart, at most 3
new keys a day per IP. Usage older than 30 days is dropped when keys
are made.

AccessStore sits beside Store: in memory for tests, Postgres in
store-postgres with migration 0003 (row level security on, no
policies). The web endpoints come next.

Refs #36

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@drippa-ai

drippa-ai Bot commented Oct 12, 2026

Copy link
Copy Markdown

Drippa Sign-Off: Add API keys and a shared daily new-scan allowance to core and Postgres

⚠️ Partly delivers ticket #36 — 3 of 5 outcomes

Open in Drippa

What was promised

  • ✅ Self-serve API keys #36 A new key is created on the spot with a 10-scans-a-day limit and is kept only in hashed form, with a short prefix to tell keys apart.
  • ⚠️ Self-serve API keys #36 One address can create at most 3 keys a day, and the 4th attempt is refused with the time the limit resets.
  • ✅ Self-serve API keys #36 Each key or anonymous visitor gets a daily new-scan allowance that resets at UTC midnight, reused recent scans cost nothing, and going over gives a clear…
  • ⚠️ Self-serve API keys #36 A key can be revoked and stops working afterwards.
  • ✅ Self-serve API keys #36 Storage for keys and usage exists with row level security on, visitor IPs are kept only as keyed hashes, and usage older than 30 days is deleted.

Not in this change: The public addresses for creating and revoking a key, which return the "too many requests" error, plus actually logging each keyed request; the description says these come next.

Proof
Not tested in the browser: nothing to test by hand.

Details

This adds the core logic for self-serve API keys. Keys are generated, stored only as a hash with a short prefix kept, capped at 3 new keys per IP per day, and can be revoked. It also adds one daily new-scan allowance for both API keys and anonymous visitors, which resets at UTC midnight and does not charge for reused scans, plus the two database tables with row level security on. The public addresses for creating and revoking keys come in a later pull request, and the scan API and website gating will be the first to use the allowance.

Test coverage: ✅ Well covered — Tests cover key format and hashing, revocation, the 3-keys-per-IP cap and its reset, the 30-day cleanup, allowance counting and visitor hashing, on both in-memory and database storage.

🔍 Checked: 3 tickets (1 delivered in part, 2 cited only), 8 changed files, 5 diffs read


Updated by Drippa • 2026-10-12 18:25 UTC

Comment @drippa-ai review for a fresh review.

@drippa-ai drippa-ai Bot mentioned this pull request Oct 12, 2026
@maaland
maaland merged commit 12b4a79 into main Oct 12, 2026
5 checks passed
@maaland
maaland deleted the feat/access-core-36 branch October 12, 2026 19:04
@vercel

vercel Bot commented Oct 12, 2026

Copy link
Copy Markdown

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

Project Deployment Actions Updated
stackprobe Ready Ready Preview Oct 12, 2026 7:06pm UTC

Request Review

maaland added a commit that referenced this pull request Oct 12, 2026
Closes #36

Stacked on #63 (keys and allowance in core and Postgres); merge that
first and this retargets to `main`.

Covers #36's "Done when":
- Creating, revoking and the key-creation limit are tested at the
endpoint, and using and exceeding the daily scan allowance at the
allowance level (#63). The first endpoint that spends it is #37.
- Keys never appear in logs or responses after creation.
- Migration with row level security is in #63.

## What changes
- **`POST /api/keys`** → `201 { key, prefix, limits: { scansPerDay: 10
}, note }`. The note says to store the key now, send it as
`Authorization: Bearer <key>`, and revoke it with `DELETE
/api/keys/current`. A fourth key from one IP in a UTC day → `429 {
error: "rate_limited", message, resetAt }` with `Retry-After`.
- **`DELETE /api/keys/current`** with the key → `200 { revoked:
"<prefix>" }`. Missing, malformed, unknown or revoked → `401 { error:
"invalid_key", message }` with `WWW-Authenticate: Bearer`.
- **Usage:** every request made with a key is logged against `key:<id>`,
never with the key.
- **Headers:** responses are `Cache-Control: no-store` and
`Access-Control-Allow-Origin: *`.
- **Caller IP:** the first `x-forwarded-for` entry (Vercel sets it),
then `x-real-ip`. It's hashed with **`STACKPROBE_IP_HASH_SECRET`** and
never stored as is. Production refuses to run without the secret;
development uses a fixed stand-in. Added to `.env.example`.
- `services.ts` shares one Postgres connection between the scan store
and the new `getAccess()`.

## Checked
- Unit tests for create, the 3-a-day limit with `Retry-After`, revoke,
then the revoked key failing, bad `Authorization` headers, usage logged
without the key, and `clientIp`.
- Production build against a throwaway database with the 0003 migration:
three `POST /api/keys` → 201, the fourth → 429 with reset at the next
UTC midnight; `DELETE` → 200, again → 401. No key appears in the server
log.
- `pnpm lint`, `pnpm typecheck`, `pnpm test` pass.

## Before deploying
- Set `STACKPROBE_IP_HASH_SECRET` on Vercel (production and preview):
`openssl rand -base64 32`.
- Run `pnpm db:migrate` against Supabase (migration 0003 from #63).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

This branch was successfully deployed

1 active deployment
Preview — 8135d25b Deployed Oct 12, 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.

Self-serve API keys

1 participant