@vantedev/groundwork 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +77 -0
- package/LICENSE +21 -0
- package/README.md +350 -2
- package/dist/api-keys/api-keys.d.ts +53 -0
- package/dist/api-keys/api-keys.d.ts.map +1 -0
- package/dist/api-keys/api-keys.js +615 -0
- package/dist/api-keys/api-keys.js.map +1 -0
- package/dist/api-keys/audit.d.ts +17 -0
- package/dist/api-keys/audit.d.ts.map +1 -0
- package/dist/api-keys/audit.js +76 -0
- package/dist/api-keys/audit.js.map +1 -0
- package/dist/api-keys/format.d.ts +32 -0
- package/dist/api-keys/format.d.ts.map +1 -0
- package/dist/api-keys/format.js +92 -0
- package/dist/api-keys/format.js.map +1 -0
- package/dist/api-keys/index.d.ts +25 -0
- package/dist/api-keys/index.d.ts.map +1 -0
- package/dist/api-keys/index.js +23 -0
- package/dist/api-keys/index.js.map +1 -0
- package/dist/api-keys/policy.d.ts +16 -0
- package/dist/api-keys/policy.d.ts.map +1 -0
- package/dist/api-keys/policy.js +95 -0
- package/dist/api-keys/policy.js.map +1 -0
- package/dist/api-keys/responses.d.ts +6 -0
- package/dist/api-keys/responses.d.ts.map +1 -0
- package/dist/api-keys/responses.js +54 -0
- package/dist/api-keys/responses.js.map +1 -0
- package/dist/api-keys/scopes.d.ts +13 -0
- package/dist/api-keys/scopes.d.ts.map +1 -0
- package/dist/api-keys/scopes.js +49 -0
- package/dist/api-keys/scopes.js.map +1 -0
- package/dist/api-keys/types.d.ts +164 -0
- package/dist/api-keys/types.d.ts.map +1 -0
- package/dist/api-keys/types.js +2 -0
- package/dist/api-keys/types.js.map +1 -0
- package/dist/audit/audit-log.d.ts +35 -0
- package/dist/audit/audit-log.d.ts.map +1 -0
- package/dist/audit/audit-log.js +269 -0
- package/dist/audit/audit-log.js.map +1 -0
- package/dist/audit/cursor.d.ts +13 -0
- package/dist/audit/cursor.d.ts.map +1 -0
- package/dist/audit/cursor.js +26 -0
- package/dist/audit/cursor.js.map +1 -0
- package/dist/audit/diff.d.ts +19 -0
- package/dist/audit/diff.d.ts.map +1 -0
- package/dist/audit/diff.js +59 -0
- package/dist/audit/diff.js.map +1 -0
- package/dist/audit/index.d.ts +25 -0
- package/dist/audit/index.d.ts.map +1 -0
- package/dist/audit/index.js +24 -0
- package/dist/audit/index.js.map +1 -0
- package/dist/audit/json.d.ts +23 -0
- package/dist/audit/json.d.ts.map +1 -0
- package/dist/audit/json.js +120 -0
- package/dist/audit/json.js.map +1 -0
- package/dist/audit/types.d.ts +112 -0
- package/dist/audit/types.d.ts.map +1 -0
- package/dist/audit/types.js +2 -0
- package/dist/audit/types.js.map +1 -0
- package/dist/idempotency/http.d.ts +27 -0
- package/dist/idempotency/http.d.ts.map +1 -0
- package/dist/idempotency/http.js +130 -0
- package/dist/idempotency/http.js.map +1 -0
- package/dist/idempotency/idempotency.d.ts +42 -0
- package/dist/idempotency/idempotency.d.ts.map +1 -0
- package/dist/idempotency/idempotency.js +302 -0
- package/dist/idempotency/idempotency.js.map +1 -0
- package/dist/idempotency/index.d.ts +25 -0
- package/dist/idempotency/index.d.ts.map +1 -0
- package/dist/idempotency/index.js +24 -0
- package/dist/idempotency/index.js.map +1 -0
- package/dist/idempotency/keys.d.ts +12 -0
- package/dist/idempotency/keys.d.ts.map +1 -0
- package/dist/idempotency/keys.js +8 -0
- package/dist/idempotency/keys.js.map +1 -0
- package/dist/idempotency/types.d.ts +92 -0
- package/dist/idempotency/types.d.ts.map +1 -0
- package/dist/idempotency/types.js +2 -0
- package/dist/idempotency/types.js.map +1 -0
- package/dist/index.d.ts +115 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +200 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/cidr.d.ts +21 -0
- package/dist/internal/cidr.d.ts.map +1 -0
- package/dist/internal/cidr.js +159 -0
- package/dist/internal/cidr.js.map +1 -0
- package/dist/internal/clock.d.ts +6 -0
- package/dist/internal/clock.d.ts.map +1 -0
- package/dist/internal/clock.js +4 -0
- package/dist/internal/clock.js.map +1 -0
- package/dist/internal/crypto.d.ts +31 -0
- package/dist/internal/crypto.d.ts.map +1 -0
- package/dist/internal/crypto.js +77 -0
- package/dist/internal/crypto.js.map +1 -0
- package/dist/internal/db.d.ts +14 -0
- package/dist/internal/db.d.ts.map +1 -0
- package/dist/internal/db.js +20 -0
- package/dist/internal/db.js.map +1 -0
- package/dist/internal/duration.d.ts +25 -0
- package/dist/internal/duration.d.ts.map +1 -0
- package/dist/internal/duration.js +39 -0
- package/dist/internal/duration.js.map +1 -0
- package/dist/internal/errors.d.ts +33 -0
- package/dist/internal/errors.d.ts.map +1 -0
- package/dist/internal/errors.js +29 -0
- package/dist/internal/errors.js.map +1 -0
- package/dist/internal/logger.d.ts +27 -0
- package/dist/internal/logger.d.ts.map +1 -0
- package/dist/internal/logger.js +38 -0
- package/dist/internal/logger.js.map +1 -0
- package/dist/internal/standard-schema.d.ts +49 -0
- package/dist/internal/standard-schema.d.ts.map +1 -0
- package/dist/internal/standard-schema.js +16 -0
- package/dist/internal/standard-schema.js.map +1 -0
- package/dist/internal/table.d.ts +7 -0
- package/dist/internal/table.d.ts.map +1 -0
- package/dist/internal/table.js +20 -0
- package/dist/internal/table.js.map +1 -0
- package/dist/jobs/backoff.d.ts +7 -0
- package/dist/jobs/backoff.d.ts.map +1 -0
- package/dist/jobs/backoff.js +10 -0
- package/dist/jobs/backoff.js.map +1 -0
- package/dist/jobs/index.d.ts +31 -0
- package/dist/jobs/index.d.ts.map +1 -0
- package/dist/jobs/index.js +29 -0
- package/dist/jobs/index.js.map +1 -0
- package/dist/jobs/jobs.d.ts +42 -0
- package/dist/jobs/jobs.d.ts.map +1 -0
- package/dist/jobs/jobs.js +736 -0
- package/dist/jobs/jobs.js.map +1 -0
- package/dist/jobs/types.d.ts +195 -0
- package/dist/jobs/types.d.ts.map +1 -0
- package/dist/jobs/types.js +2 -0
- package/dist/jobs/types.js.map +1 -0
- package/dist/next/client-ip.d.ts +42 -0
- package/dist/next/client-ip.d.ts.map +1 -0
- package/dist/next/client-ip.js +59 -0
- package/dist/next/client-ip.js.map +1 -0
- package/dist/next/index.d.ts +29 -0
- package/dist/next/index.d.ts.map +1 -0
- package/dist/next/index.js +29 -0
- package/dist/next/index.js.map +1 -0
- package/dist/next/jobs-route.d.ts +31 -0
- package/dist/next/jobs-route.d.ts.map +1 -0
- package/dist/next/jobs-route.js +53 -0
- package/dist/next/jobs-route.js.map +1 -0
- package/dist/next/response.d.ts +6 -0
- package/dist/next/response.d.ts.map +1 -0
- package/dist/next/response.js +25 -0
- package/dist/next/response.js.map +1 -0
- package/dist/next/route-helpers.d.ts +67 -0
- package/dist/next/route-helpers.d.ts.map +1 -0
- package/dist/next/route-helpers.js +93 -0
- package/dist/next/route-helpers.js.map +1 -0
- package/dist/rate-limit/index.d.ts +19 -0
- package/dist/rate-limit/index.d.ts.map +1 -0
- package/dist/rate-limit/index.js +18 -0
- package/dist/rate-limit/index.js.map +1 -0
- package/dist/rate-limit/limiter.d.ts +57 -0
- package/dist/rate-limit/limiter.d.ts.map +1 -0
- package/dist/rate-limit/limiter.js +147 -0
- package/dist/rate-limit/limiter.js.map +1 -0
- package/dist/rate-limit/memory-store.d.ts +23 -0
- package/dist/rate-limit/memory-store.d.ts.map +1 -0
- package/dist/rate-limit/memory-store.js +77 -0
- package/dist/rate-limit/memory-store.js.map +1 -0
- package/dist/rate-limit/policy.d.ts +31 -0
- package/dist/rate-limit/policy.d.ts.map +1 -0
- package/dist/rate-limit/policy.js +174 -0
- package/dist/rate-limit/policy.js.map +1 -0
- package/dist/rate-limit/postgres-store.d.ts +13 -0
- package/dist/rate-limit/postgres-store.d.ts.map +1 -0
- package/dist/rate-limit/postgres-store.js +129 -0
- package/dist/rate-limit/postgres-store.js.map +1 -0
- package/dist/rate-limit/redis-store.d.ts +24 -0
- package/dist/rate-limit/redis-store.d.ts.map +1 -0
- package/dist/rate-limit/redis-store.js +97 -0
- package/dist/rate-limit/redis-store.js.map +1 -0
- package/dist/rate-limit/types.d.ts +137 -0
- package/dist/rate-limit/types.d.ts.map +1 -0
- package/dist/rate-limit/types.js +2 -0
- package/dist/rate-limit/types.js.map +1 -0
- package/dist/schema/api-keys.d.ts +545 -0
- package/dist/schema/api-keys.d.ts.map +1 -0
- package/dist/schema/api-keys.js +83 -0
- package/dist/schema/api-keys.js.map +1 -0
- package/dist/schema/audit-log.d.ts +248 -0
- package/dist/schema/audit-log.d.ts.map +1 -0
- package/dist/schema/audit-log.js +56 -0
- package/dist/schema/audit-log.js.map +1 -0
- package/dist/schema/factory.d.ts +19 -0
- package/dist/schema/factory.d.ts.map +1 -0
- package/dist/schema/factory.js +39 -0
- package/dist/schema/factory.js.map +1 -0
- package/dist/schema/idempotency-keys.d.ts +178 -0
- package/dist/schema/idempotency-keys.d.ts.map +1 -0
- package/dist/schema/idempotency-keys.js +41 -0
- package/dist/schema/idempotency-keys.js.map +1 -0
- package/dist/schema/index.d.ts +61 -0
- package/dist/schema/index.d.ts.map +1 -0
- package/dist/schema/index.js +28 -0
- package/dist/schema/index.js.map +1 -0
- package/dist/schema/jobs.d.ts +487 -0
- package/dist/schema/jobs.d.ts.map +1 -0
- package/dist/schema/jobs.js +103 -0
- package/dist/schema/jobs.js.map +1 -0
- package/dist/schema/rate-limits.d.ts +108 -0
- package/dist/schema/rate-limits.d.ts.map +1 -0
- package/dist/schema/rate-limits.js +27 -0
- package/dist/schema/rate-limits.js.map +1 -0
- package/dist/testing/index.d.ts +25 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +37 -0
- package/dist/testing/index.js.map +1 -0
- package/package.json +117 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# @vantedev/groundwork
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- d6c1960: Package skeleton: ESM-only subpath exports (`@vantedev/groundwork`, `/schema`, `/rate-limit`, `/audit`, `/api-keys`, `/jobs`, `/idempotency`, `/next`, `/testing`), with `drizzle-orm` as the only peer dependency. The root entry exports `GroundworkError`, `isGroundworkError` and the shared `Duration`, `Logger`, `Clock` and `Secret` types.
|
|
8
|
+
- ab377d2: Rate limiting, and the table factories it stores its counters in.
|
|
9
|
+
|
|
10
|
+
- `@vantedev/groundwork/schema`: `groundworkTables({ prefix, schema })` returns Drizzle tables for your schema. The default prefix is `gw_`. When `schema` is set, the returned schema object must be exported too, so drizzle-kit generates `CREATE SCHEMA`.
|
|
11
|
+
- `@vantedev/groundwork/rate-limit`: `createRateLimiter()` with fixed-window and token-bucket rules.
|
|
12
|
+
- Each check is one SQL statement, correct under concurrency across app instances. Time comes from the database unless a `clock` is injected.
|
|
13
|
+
- A request whose `cost` doesn't fit is denied and uses nothing.
|
|
14
|
+
- Results include `RateLimit-Policy`, `RateLimit` (draft-ietf-httpapi-ratelimit-headers-11) and `Retry-After` headers.
|
|
15
|
+
- If the store fails or times out (default `"1s"`), rules fall back to `onError: "memory" | "allow" | "deny"`. A circuit breaker stops retrying for 5 seconds, and the outage is logged once.
|
|
16
|
+
- `reset()` can join a transaction. `cleanup()` deletes in batches.
|
|
17
|
+
- `memoryStore()` and an optional `redisStore()`, which takes any client with `eval` and adds no dependency.
|
|
18
|
+
- `createGroundwork({ db, tables, secret })` exposes the limiter as `gw.rateLimit`.
|
|
19
|
+
- `@vantedev/groundwork/testing`: `createTestClock()`.
|
|
20
|
+
- 8a132d1: Audit log.
|
|
21
|
+
|
|
22
|
+
- `groundworkTables()` now also returns `auditLog` (`gw_audit_log`). It is append-only: identity ids, `occurred_at` defaults to the transaction's `now()`, and every filter column is indexed together with `(occurred_at, id)`.
|
|
23
|
+
- `@vantedev/groundwork/audit`: `createAuditLog({ db, table, actions, entityTypes?, redact?, redactDefaults? })`.
|
|
24
|
+
- Actions and entity types are inferred from the config.
|
|
25
|
+
- `record(event, { tx })` writes inside your transaction; `recordMany` writes up to 1,000 entries in one statement, all or none.
|
|
26
|
+
- Events are validated before anything is sent, and recording throws rather than swallowing errors.
|
|
27
|
+
- `changes` and `metadata` are redacted at any depth, using `DEFAULT_REDACT` plus your rules, and normalised to JSON.
|
|
28
|
+
- `query()` uses keyset pagination on `(occurred_at, id)` and filters by action, actor, entity, request id, time range, literal text search, or any Drizzle `where`. It reads newest first, or oldest first with `order: "asc"`.
|
|
29
|
+
- `count()` takes the same filters; `prune({ olderThan })` deletes in batches.
|
|
30
|
+
- `diff(before, after, { ignore })` returns only the changed fields, as `[before, after]`.
|
|
31
|
+
- `createGroundwork({ audit: { actions } })` exposes the log as `gw.audit`.
|
|
32
|
+
- e7b1e91: Scoped API keys.
|
|
33
|
+
|
|
34
|
+
- `groundworkTables()` now also returns `apiKeys` (`gw_api_keys`). Only an HMAC of each key is stored, under a unique index. The table also keeps a partial index on the previous hash, used during rotation grace periods.
|
|
35
|
+
- `@vantedev/groundwork/api-keys`: `createApiKeys({ db, table, secret, namespace, scopes, rateLimiter })`, or `gw.apiKeys` from `createGroundwork({ apiKeys })`.
|
|
36
|
+
- Keys look like `<namespace>_<12 hex>_<43 base64url>` with a CRC32 checksum suffix. Typos and foreign keys are rejected without a database lookup, and keys without a checksum still verify.
|
|
37
|
+
- Scopes are typed from the config and can be granted as `resource:*` wildcards.
|
|
38
|
+
- `verify(request | headers | key, { scopes, ip, origin })` finds the key, current or within its rotation grace period, in one query.
|
|
39
|
+
- It returns `{ ok: true, key, headers }`, or `{ ok: false, reason, status, response }`. Reasons: `missing`, `malformed`, `invalid`, `revoked`, `expired`, `suspended`, `ip_denied`, `origin_denied`, `forbidden_scope`, `rate_limited`, `quota_exceeded`.
|
|
40
|
+
- The JSON response carries RFC 6750 `WWW-Authenticate` headers.
|
|
41
|
+
- IPv4 and IPv6 CIDR allowlists, which also match IPv4-mapped addresses, and origin allowlists.
|
|
42
|
+
- Per-key rate limit (default 60/min) and daily quota through the rate limiter.
|
|
43
|
+
- Lifecycle: `create`, `update`, `rotate({ grace })`, `suspend({ for })`, `reinstate`, `revoke`, `delete`, `get`, `list`. Every method takes `{ actor, tx }`.
|
|
44
|
+
- `lastUsedAt` and `lastUsedIp` are written at most once a minute, in the background (`waitUntil` hook).
|
|
45
|
+
- `legacyHash` keeps keys from an older system working, and upgrades each one on first use.
|
|
46
|
+
- `redactKeys(text)`.
|
|
47
|
+
- With the audit log wired, every key change is recorded as `api_key.*`, which `gw.audit` accepts automatically. `apiKeyAuditEvent()` maps events for standalone use.
|
|
48
|
+
- 1761981: Background jobs and schedules.
|
|
49
|
+
|
|
50
|
+
- `groundworkTables()` now also returns `jobs` (`gw_jobs`) and `jobSchedules` (`gw_job_schedules`).
|
|
51
|
+
- Status is checked text, not an enum, so nothing extra has to be exported.
|
|
52
|
+
- A partial claim index on `(priority desc, run_at, id)`, so a claim reads only the next few rows.
|
|
53
|
+
- A partial unique index on `(type, dedupe_key)` while a job is pending or running.
|
|
54
|
+
- `@vantedev/groundwork/jobs`: `createJobs({ db, table, schedulesTable, lease })`, or `gw.jobs` from `createGroundwork`.
|
|
55
|
+
- `define(type, { schema, run, maxAttempts, backoff, timeout, priority, onExhausted })` returns a typed handle. Payloads are typed from a Standard Schema (zod, valibot, arktype…), which also validates them, or from `run`'s parameter.
|
|
56
|
+
- `enqueue(payload, { tx, runAt, delay, priority, dedupeKey, maxAttempts })` returns `{ id, created }`.
|
|
57
|
+
- Workers claim batches with `FOR UPDATE SKIP LOCKED` in one statement. Each job is leased, and the lease is renewed while the handler runs; a dead worker's jobs come back when its lease ends. The attempt number fences out late results from a worker that lost its lease.
|
|
58
|
+
- Retries use capped exponential backoff with full jitter. Timeouts abort `context.signal`.
|
|
59
|
+
- `work({ concurrency, pollInterval, signal })` finishes running jobs on abort. `runOnce({ budgetMs, concurrency })` is for cron and HTTP triggers.
|
|
60
|
+
- `schedule(name, { every }, fn)`: each tick runs exactly once across instances, as a job, so it gets retries, history and health. Overlapping ticks are skipped. `trigger(name)` runs a schedule now.
|
|
61
|
+
- `get`, `list`, `retry`, `cancel`, `prune`, and `health()`, which reports per-type queue stats and per-schedule last success, failure and health.
|
|
62
|
+
- `createGroundwork` schedules `gw.rateLimit.cleanup()` hourly when rate limiting is set up.
|
|
63
|
+
- 5de6fdf: Idempotency keys and Next.js route helpers.
|
|
64
|
+
|
|
65
|
+
- `groundworkTables()` now also returns `idempotencyKeys` (`gw_idempotency_keys`). Keys and request fingerprints are stored as HMACs; responses are stored as JSON text.
|
|
66
|
+
- `@vantedev/groundwork/idempotency`: `createIdempotency({ db, table, secret, ttl, lease })`, or `gw.idempotency` from `createGroundwork`.
|
|
67
|
+
- `handle(request, { scope, required, ttl, fingerprint }, handler)` follows draft-ietf-httpapi-idempotency-key-header-08. A completed 2xx or 3xx response is replayed with `Idempotent-Replayed: true`; reuse with a different body, path or method is a 422; a duplicate while the first request runs is a 409; a missing (when `required`) or malformed key is a 400. Errors aren't stored, so clients can retry.
|
|
68
|
+
- Concurrent duplicates run the handler once. A running request holds its key with a lease that is renewed while it runs, so a crashed request frees its key within `lease` (default `"30s"`).
|
|
69
|
+
- `Set-Cookie` and per-request headers are never stored.
|
|
70
|
+
- `run({ scope, key, fingerprint }, fn)` does the same for anything that isn't an HTTP handler, and returns the stored JSON value, typed with `Jsonify<T>`.
|
|
71
|
+
- `cleanup()` deletes expired keys. `createGroundwork` schedules it hourly once you use `gw.jobs` (`jobs: { idempotencyCleanup: false }` turns it off).
|
|
72
|
+
- `@vantedev/groundwork/next`, with no dependency on `next`:
|
|
73
|
+
- `createRouteHelpers(gw, { trustProxy })` returns `withApiKey(scopes, handler)`, `withRateLimit(rule, key, handler)`, `withIdempotency(options, handler)` and `clientIp(request)`. Wrappers nest, and what an outer one adds (`context.apiKey`) is typed in the ones inside.
|
|
74
|
+
- `jobsRoute(gw, { secret, budgetMs, concurrency })`: a bearer-protected HTTP trigger for `gw.jobs.runOnce()`, for Vercel Cron and other schedulers. `?schedule=<name>` runs a schedule now.
|
|
75
|
+
- `getClientIp(request, { trustProxy })` reads only the header you trust: `"vercel"`, `"cloudflare"`, or `{ header, hops }` for `X-Forwarded-For` behind your own proxies. The default, `"none"`, reads nothing.
|
|
76
|
+
- `examples/next-app` uses every module in a Next.js 16 app.
|
|
77
|
+
- First public release, as `@vantedev/groundwork` (the unscoped name `groundwork` belongs to another package on npm). Import from `@vantedev/groundwork`, `@vantedev/groundwork/schema`, `@vantedev/groundwork/next` and the other subpaths. New guides cover testing your app and migrating from hand-rolled tables.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vante
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,351 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<picture>
|
|
4
|
+
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/banner-dark.svg">
|
|
5
|
+
<img alt="groundwork: the plumbing every Postgres app rebuilds, in your own Drizzle schema" src="docs/assets/banner-light.svg" width="100%">
|
|
6
|
+
</picture>
|
|
7
|
+
|
|
8
|
+
<br>
|
|
9
|
+
|
|
10
|
+
**Rate limiting, audit logs, scoped API keys, background jobs and idempotency keys for TypeScript apps on Postgres. The tables live in your Drizzle schema, every write joins your transaction, and you don't need Redis.**
|
|
11
|
+
|
|
12
|
+
<br>
|
|
13
|
+
|
|
14
|
+
[](https://github.com/kaanxsrd/groundwork/actions/workflows/ci.yml)
|
|
15
|
+
[](https://www.npmjs.com/package/@vantedev/groundwork)
|
|
16
|
+
[](https://www.typescriptlang.org)
|
|
17
|
+
[](https://www.postgresql.org)
|
|
18
|
+
[](https://orm.drizzle.team)
|
|
19
|
+
[](docs/next.md)
|
|
20
|
+
[](https://nodejs.org/api/esm.html)
|
|
21
|
+
[](https://biomejs.dev)
|
|
22
|
+
[](LICENSE)
|
|
23
|
+
|
|
24
|
+
**[Quickstart](#quickstart)** ·
|
|
25
|
+
**[Docs](docs/README.md)** ·
|
|
26
|
+
**[Example app](examples/next-app)** ·
|
|
27
|
+
**[Changelog](CHANGELOG.md)** ·
|
|
28
|
+
**[Contributing](CONTRIBUTING.md)** ·
|
|
29
|
+
**[Security](SECURITY.md)**
|
|
30
|
+
|
|
31
|
+
</div>
|
|
32
|
+
|
|
33
|
+
<br>
|
|
34
|
+
|
|
35
|
+
> [!NOTE]
|
|
36
|
+
> **0.x:** the API can still change before 1.0. Each change is in the [changelog](CHANGELOG.md), with what to update.
|
|
37
|
+
|
|
38
|
+
## Why
|
|
39
|
+
|
|
40
|
+
Self-hosted Next.js + Drizzle + Postgres apps keep hand-writing the same five pieces. Libraries exist for each of them, but most bring their own schema, their own migrations, a Redis server or a hosted service. groundwork works differently:
|
|
41
|
+
|
|
42
|
+
- **Your schema.** The tables are factories you export from your own Drizzle schema, and your drizzle-kit migrates them. groundwork never runs DDL.
|
|
43
|
+
- **Your transaction.** Pass `{ tx }`, and an audit entry or an enqueued job commits or rolls back with the change that caused it.
|
|
44
|
+
- **Your names, typed.** Scopes, audit actions and job payloads are declared once, and TypeScript checks every place they're used.
|
|
45
|
+
- **Only Postgres.** A rate-limit check is one round trip. Redis is an option for rate limits, never a requirement.
|
|
46
|
+
- **Secure by default.** API keys, rate-limit subjects and idempotency keys are stored as HMACs, comparisons are timing-safe, configured audit fields are redacted, and secrets never reach a log.
|
|
47
|
+
|
|
48
|
+
## What's inside
|
|
49
|
+
|
|
50
|
+
<table>
|
|
51
|
+
<tr>
|
|
52
|
+
<td width="50%" valign="top">
|
|
53
|
+
|
|
54
|
+
**[Rate limiting](docs/rate-limiting.md)**<br>
|
|
55
|
+
Fixed windows and token buckets in one atomic statement, with the standard `RateLimit` headers. If the database is down it falls back to memory, or fails open or closed, as you choose.
|
|
56
|
+
|
|
57
|
+
</td>
|
|
58
|
+
<td width="50%" valign="top">
|
|
59
|
+
|
|
60
|
+
**[Audit log](docs/audit.md)**<br>
|
|
61
|
+
Typed actions recorded in your transaction, field-level diffs, redaction of secrets before they're stored, and keyset pagination that never skips a row.
|
|
62
|
+
|
|
63
|
+
</td>
|
|
64
|
+
</tr>
|
|
65
|
+
<tr>
|
|
66
|
+
<td width="50%" valign="top">
|
|
67
|
+
|
|
68
|
+
**[Scoped API keys](docs/api-keys.md)**<br>
|
|
69
|
+
Keys that secret scanners recognise, stored as HMACs. Rotation with a grace period, suspension, IP and origin allowlists, and per-key rate limits and daily quotas.
|
|
70
|
+
|
|
71
|
+
</td>
|
|
72
|
+
<td width="50%" valign="top">
|
|
73
|
+
|
|
74
|
+
**[Background jobs](docs/jobs.md)**<br>
|
|
75
|
+
Typed jobs enqueued in your transaction and claimed in batches. Leases bring back a crashed worker's jobs, retries back off with jitter, and schedules run each tick exactly once.
|
|
76
|
+
|
|
77
|
+
</td>
|
|
78
|
+
</tr>
|
|
79
|
+
<tr>
|
|
80
|
+
<td width="50%" valign="top">
|
|
81
|
+
|
|
82
|
+
**[Idempotency keys](docs/idempotency.md)**<br>
|
|
83
|
+
Safe retries per the IETF draft. A repeated request gets the stored response; a duplicate that arrives while the first is still running gets a 409 and doesn't run twice.
|
|
84
|
+
|
|
85
|
+
</td>
|
|
86
|
+
<td width="50%" valign="top">
|
|
87
|
+
|
|
88
|
+
**[Next.js helpers](docs/next.md)**<br>
|
|
89
|
+
`withApiKey`, `withRateLimit` and `withIdempotency` route wrappers that nest with full typing, a cron route for jobs, and client IPs read only from the proxy you trust.
|
|
90
|
+
|
|
91
|
+
</td>
|
|
92
|
+
</tr>
|
|
93
|
+
</table>
|
|
94
|
+
|
|
95
|
+
## Quickstart
|
|
96
|
+
|
|
97
|
+
In a Next.js app (`npx create-next-app@latest`) with a Postgres database:
|
|
98
|
+
|
|
99
|
+
```sh
|
|
100
|
+
npm install @vantedev/groundwork drizzle-orm postgres
|
|
101
|
+
npm install -D drizzle-kit
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
**1. Add groundwork's tables to your Drizzle schema**, and let drizzle-kit create them. Put `DATABASE_URL` in `.env.local`, plus `GROUNDWORK_SECRET` and `CRON_SECRET`, each from `openssl rand -base64 32`.
|
|
105
|
+
|
|
106
|
+
```ts filename="db/schema.ts"
|
|
107
|
+
import { groundworkTables } from "@vantedev/groundwork/schema";
|
|
108
|
+
|
|
109
|
+
export const { rateLimits, auditLog, apiKeys, jobs, jobSchedules, idempotencyKeys } =
|
|
110
|
+
groundworkTables();
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
```ts filename="drizzle.config.ts"
|
|
114
|
+
import { defineConfig } from "drizzle-kit";
|
|
115
|
+
|
|
116
|
+
process.loadEnvFile(".env.local");
|
|
117
|
+
|
|
118
|
+
export default defineConfig({
|
|
119
|
+
dialect: "postgresql",
|
|
120
|
+
schema: "./db/schema.ts",
|
|
121
|
+
out: "./drizzle",
|
|
122
|
+
dbCredentials: { url: process.env.DATABASE_URL ?? "" },
|
|
123
|
+
});
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
```sh
|
|
127
|
+
npx drizzle-kit generate
|
|
128
|
+
npx drizzle-kit migrate
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
**2. Create one instance** with your own names. Audit actions, API-key scopes and job payloads are typed from here on.
|
|
132
|
+
|
|
133
|
+
```ts filename="lib/groundwork.ts"
|
|
134
|
+
import { drizzle } from "drizzle-orm/postgres-js";
|
|
135
|
+
import { createGroundwork } from "@vantedev/groundwork";
|
|
136
|
+
import { createRouteHelpers } from "@vantedev/groundwork/next";
|
|
137
|
+
import postgres from "postgres";
|
|
138
|
+
import * as tables from "@/db/schema";
|
|
139
|
+
|
|
140
|
+
export const db = drizzle(postgres(process.env.DATABASE_URL ?? ""));
|
|
141
|
+
|
|
142
|
+
export const gw = createGroundwork({
|
|
143
|
+
db,
|
|
144
|
+
tables,
|
|
145
|
+
secret: process.env.GROUNDWORK_SECRET ?? "",
|
|
146
|
+
audit: { actions: ["note.create"] },
|
|
147
|
+
apiKeys: { namespace: "demo", scopes: { "notes:write": "Create notes" } },
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
export const { withApiKey, withIdempotency } = createRouteHelpers(gw);
|
|
151
|
+
|
|
152
|
+
export const noteCreated = gw.jobs.define("note.created", {
|
|
153
|
+
async run(note: { id: string }) {
|
|
154
|
+
console.log(`Note ${note.id} was created.`);
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
**3. Protect a route** with a scoped API key and make it safe to retry. The audit entry and the job commit together with your write, or not at all:
|
|
160
|
+
|
|
161
|
+
```ts filename="app/api/notes/route.ts"
|
|
162
|
+
import { db, gw, noteCreated, withApiKey, withIdempotency } from "@/lib/groundwork";
|
|
163
|
+
|
|
164
|
+
export const POST = withApiKey(
|
|
165
|
+
["notes:write"],
|
|
166
|
+
withIdempotency(
|
|
167
|
+
{ scope: (_request, { apiKey }) => `apikey:${apiKey.id}` },
|
|
168
|
+
async (request, { apiKey }) => {
|
|
169
|
+
const { text } = await request.json();
|
|
170
|
+
const id = crypto.randomUUID();
|
|
171
|
+
await db.transaction(async (tx) => {
|
|
172
|
+
await gw.audit.record(
|
|
173
|
+
{ actor: { type: "api_key", id: apiKey.id }, action: "note.create", metadata: { id, text } },
|
|
174
|
+
{ tx },
|
|
175
|
+
);
|
|
176
|
+
await noteCreated.enqueue({ id }, { tx });
|
|
177
|
+
});
|
|
178
|
+
return Response.json({ id }, { status: 201 });
|
|
179
|
+
},
|
|
180
|
+
),
|
|
181
|
+
);
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
**4. Run jobs** from a cron route (Vercel Cron sends `CRON_SECRET` for you), or with `gw.jobs.work()` in a long-running process:
|
|
185
|
+
|
|
186
|
+
```ts filename="app/api/jobs/route.ts"
|
|
187
|
+
import { jobsRoute } from "@vantedev/groundwork/next";
|
|
188
|
+
import { gw } from "@/lib/groundwork";
|
|
189
|
+
|
|
190
|
+
export const GET = jobsRoute(gw, { secret: process.env.CRON_SECRET ?? "" });
|
|
191
|
+
export const POST = GET;
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
**5. Create a key** once, from a script or your admin UI, and call the route. A retry with the same `Idempotency-Key` gets the first response back:
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
const { key } = await gw.apiKeys.create({ name: "My CLI", scopes: ["notes:write"] });
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
```sh
|
|
201
|
+
curl -X POST http://localhost:3000/api/notes -H "Authorization: Bearer $KEY" -H "Idempotency-Key: $(uuidgen)" -d '{"text":"Hello"}'
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
[`examples/next-app`](examples/next-app) uses every module, with rate limits, a schedule and an audit-log endpoint. CI builds both it and this quickstart in a fresh `create-next-app` project, then runs requests against them.
|
|
205
|
+
|
|
206
|
+
## The modules
|
|
207
|
+
|
|
208
|
+
Each one also works on its own, without `createGroundwork`: `createRateLimiter({ db, table, secret })`, and so on.
|
|
209
|
+
|
|
210
|
+
### Rate limiting
|
|
211
|
+
|
|
212
|
+
```ts
|
|
213
|
+
const login = gw.rateLimit.rule({ name: "login:ip", limit: 5, window: "15m" });
|
|
214
|
+
const api = gw.rateLimit.rule({ name: "api", algorithm: "token-bucket", rate: 10, per: "1s", burst: 120 });
|
|
215
|
+
|
|
216
|
+
const result = await login.check(ip);
|
|
217
|
+
if (!result.allowed) return new Response("Too many attempts", { status: 429, headers: result.headers });
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
Subjects are stored as HMACs, never as raw IPs or user ids. A batch that doesn't fit is rejected without using anything. [Docs](docs/rate-limiting.md)
|
|
221
|
+
|
|
222
|
+
### Audit log
|
|
223
|
+
|
|
224
|
+
```ts
|
|
225
|
+
await db.transaction(async (tx) => {
|
|
226
|
+
const [before] = await tx.select().from(posts).where(eq(posts.id, id));
|
|
227
|
+
const [after] = await tx.update(posts).set(input).where(eq(posts.id, id)).returning();
|
|
228
|
+
await gw.audit.record(
|
|
229
|
+
{ actor: { type: "user", id: user.id }, action: "post.update", entity: { type: "post", id }, changes: diff(before, after) },
|
|
230
|
+
{ tx },
|
|
231
|
+
);
|
|
232
|
+
});
|
|
233
|
+
const { entries, nextCursor } = await gw.audit.query({ entity: { type: "post", id } });
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
`record()` only accepts the actions you declared. [Docs](docs/audit.md)
|
|
237
|
+
|
|
238
|
+
### API keys
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
const { key } = await gw.apiKeys.create({ name: "CI deploy", scopes: ["posts:write"], expiresIn: "90d" });
|
|
242
|
+
|
|
243
|
+
const auth = await gw.apiKeys.verify(request, { scopes: ["posts:write"] });
|
|
244
|
+
if (!auth.ok) return auth.response; // a JSON 401, 403 or 429 with the right headers
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
The key is shown once; only its hash is stored. `rotate()` keeps the old key working for a grace period. [Docs](docs/api-keys.md)
|
|
248
|
+
|
|
249
|
+
### Background jobs
|
|
250
|
+
|
|
251
|
+
```ts
|
|
252
|
+
export const sendReceipt = gw.jobs.define("email.receipt", {
|
|
253
|
+
schema: z.object({ orderId: z.string() }), // or any Standard Schema
|
|
254
|
+
async run({ orderId }, { signal }) {
|
|
255
|
+
await mailer.sendReceipt(orderId, { signal });
|
|
256
|
+
},
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
await sendReceipt.enqueue({ orderId }, { tx, dedupeKey: `receipt:${orderId}` });
|
|
260
|
+
gw.jobs.schedule("reports.nightly", { every: "1d" }, () => buildReports());
|
|
261
|
+
await gw.jobs.work({ concurrency: 4, signal }); // or runOnce() from a cron route
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
[Docs](docs/jobs.md)
|
|
265
|
+
|
|
266
|
+
### Idempotency keys
|
|
267
|
+
|
|
268
|
+
```ts
|
|
269
|
+
return gw.idempotency.handle(request, { scope: `user:${user.id}` }, async () => {
|
|
270
|
+
const order = await createOrder(await request.json());
|
|
271
|
+
return Response.json(order, { status: 201 });
|
|
272
|
+
});
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
`run()` does the same for webhooks and anything else that isn't an HTTP handler. [Docs](docs/idempotency.md)
|
|
276
|
+
|
|
277
|
+
### Next.js
|
|
278
|
+
|
|
279
|
+
```ts
|
|
280
|
+
export const POST = withApiKey(
|
|
281
|
+
["posts:write"],
|
|
282
|
+
withRateLimit(
|
|
283
|
+
postWrites,
|
|
284
|
+
(_request, { apiKey }) => apiKey.id,
|
|
285
|
+
withIdempotency({ scope: (_request, { apiKey }) => `apikey:${apiKey.id}` }, createPost),
|
|
286
|
+
),
|
|
287
|
+
);
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
[Docs](docs/next.md)
|
|
291
|
+
|
|
292
|
+
## Compared with
|
|
293
|
+
|
|
294
|
+
There are good libraries for each of these pieces. groundwork's angle is having all five in your own schema and transactions. Here's when another tool fits better:
|
|
295
|
+
|
|
296
|
+
| You need | groundwork gives you | Consider instead |
|
|
297
|
+
| --- | --- | --- |
|
|
298
|
+
| Rate limiting | Fixed window and token bucket in your Postgres, hashed subjects, a memory fallback, optional Redis | [@upstash/ratelimit](https://github.com/upstash/ratelimit-js) on edge runtimes or without Postgres. [rate-limiter-flexible](https://github.com/animir/node-rate-limiter-flexible) for many more backends; its `RateLimiterDrizzle` also keeps its table in your schema (fixed window, no `tx`). |
|
|
299
|
+
| An audit log | Explicit, typed `record()` calls in your transaction, with diffs and redaction | [drizzle-audit](https://www.npmjs.com/package/drizzle-audit) to capture every ORM write automatically. Database triggers to also catch writes from outside your app. |
|
|
300
|
+
| API keys | Hashed, scoped keys in your database, with rotation grace, IP and origin allowlists and per-key limits | [Unkey](https://www.unkey.com), a hosted service with usage analytics. better-auth's [api-key plugin](https://www.npmjs.com/package/@better-auth/api-key) when keys belong to better-auth users and you need no more than it offers. |
|
|
301
|
+
| Background jobs | Typed jobs in your schema, enqueued in your transaction, leases, and a cron-friendly `runOnce()` | [pg-boss](https://github.com/timgit/pg-boss) or [graphile-worker](https://worker.graphile.org) for high volume, cron expressions, or job dependencies and workflows. Both bring their own schema and migrations. |
|
|
302
|
+
| Idempotency keys | The IETF draft's behaviour, with stored responses and crash recovery | Few libraries do this. If a payment provider is the only side effect, its own idempotency keys may be enough. |
|
|
303
|
+
|
|
304
|
+
groundwork isn't for edge runtimes, databases other than Postgres, or stacks that already run everything through Redis.
|
|
305
|
+
|
|
306
|
+
## Requirements
|
|
307
|
+
|
|
308
|
+
- PostgreSQL 16 or newer.
|
|
309
|
+
- `drizzle-orm` 0.45 with any Postgres driver (`postgres`, `pg`, Neon's websocket driver…). groundwork's own statements are all single statements; passing `{ tx }` needs a driver that supports transactions. CI tests `postgres` and `pg`.
|
|
310
|
+
- Node.js 22+ or Bun 1.4+. ESM only.
|
|
311
|
+
- TypeScript 5.9+ if you use the types (CI checks 5.9, 6.0 and 7.0).
|
|
312
|
+
- For `@vantedev/groundwork/next`: nothing extra. It never imports `next`; CI tests it with Next.js 16.
|
|
313
|
+
- Optional: Redis, only for the Redis rate-limit store (tested with Redis 8, ioredis 6 and node-redis 6).
|
|
314
|
+
|
|
315
|
+
## Documentation
|
|
316
|
+
|
|
317
|
+
| Guide | What's inside |
|
|
318
|
+
| --- | --- |
|
|
319
|
+
| [Core concepts](docs/core-concepts.md) | Durations, the app secret, errors, logging and clocks |
|
|
320
|
+
| [Table factories](docs/schema.md) | Putting groundwork's tables in your schema, column by column |
|
|
321
|
+
| [Rate limiting](docs/rate-limiting.md) | Algorithms, headers, failure modes, Redis |
|
|
322
|
+
| [Audit log](docs/audit.md) | Recording in transactions, diffs, redaction, querying, retention |
|
|
323
|
+
| [API keys](docs/api-keys.md) | Key format, scopes, verification, rotation, allowlists, per-key limits |
|
|
324
|
+
| [Background jobs](docs/jobs.md) | Workers, leases, retries, schedules, health |
|
|
325
|
+
| [Idempotency keys](docs/idempotency.md) | What's stored, status codes, crashes, `run()` |
|
|
326
|
+
| [Next.js helpers](docs/next.md) | Route wrappers, the jobs cron route, client IPs |
|
|
327
|
+
| [Testing your app](docs/testing.md) | Real Postgres, the test clock, calling routes directly |
|
|
328
|
+
| [Migrating](docs/migrating.md) | Moving off hand-rolled tables, module by module |
|
|
329
|
+
| [Example app](examples/next-app) | Every module in one Next.js 16 app |
|
|
330
|
+
| [Releasing](docs/releasing.md) | For maintainers: versions, provenance, trusted publishing |
|
|
331
|
+
|
|
332
|
+
## Develop
|
|
333
|
+
|
|
334
|
+
```sh
|
|
335
|
+
bun install
|
|
336
|
+
bun run db:up # Postgres (127.0.0.1:54330) and Redis (:63790) in Docker
|
|
337
|
+
bun run check # Biome, TypeScript and unit tests
|
|
338
|
+
bun run test # everything, including the integration tests
|
|
339
|
+
bun run example # the example app and this README's quickstart, built and run
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
[CONTRIBUTING.md](CONTRIBUTING.md) explains the test harness, the migration workflow and the conventions. [PLAN.md](PLAN.md) has the roadmap and every design decision.
|
|
343
|
+
|
|
344
|
+
## License
|
|
345
|
+
|
|
346
|
+
[MIT](LICENSE) © Vante
|
|
347
|
+
|
|
348
|
+
<div align="center">
|
|
349
|
+
<br>
|
|
350
|
+
<sub>Built to be the last time you write a rate limiter.</sub>
|
|
351
|
+
</div>
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { Clock } from "../internal/clock.ts";
|
|
2
|
+
import { type Secret } from "../internal/crypto.ts";
|
|
3
|
+
import { type GroundworkDatabase } from "../internal/db.ts";
|
|
4
|
+
import { type Logger } from "../internal/logger.ts";
|
|
5
|
+
import type { RateLimiter } from "../rate-limit/types.ts";
|
|
6
|
+
import { type ApiKeysTable } from "../schema/api-keys.ts";
|
|
7
|
+
import type { ApiKeyEvent, ApiKeyRateLimit, ApiKeys } from "./types.ts";
|
|
8
|
+
export interface ApiKeysOptions<TScopes extends Record<string, string>> {
|
|
9
|
+
readonly db: GroundworkDatabase;
|
|
10
|
+
/** The `apiKeys` table from `groundworkTables()`. */
|
|
11
|
+
readonly table: ApiKeysTable;
|
|
12
|
+
/** The app secret. Keys are stored as HMACs under a subkey derived from it. */
|
|
13
|
+
readonly secret: Secret;
|
|
14
|
+
/** The start of every key, such as `"vnt"` for `vnt_…`. Pick something unique to your app. */
|
|
15
|
+
readonly namespace: string;
|
|
16
|
+
/** Every scope your API knows, with a description: `{ "posts:read": "Read posts" }`. */
|
|
17
|
+
readonly scopes: TScopes;
|
|
18
|
+
/** Append a CRC32 checksum to new keys (`true`, the default). Keys without one still verify. */
|
|
19
|
+
readonly checksum?: boolean | undefined;
|
|
20
|
+
/** Enforces per-key rate limits and daily quotas. Required unless `defaultRateLimit` is `null`. */
|
|
21
|
+
readonly rateLimiter?: RateLimiter | undefined;
|
|
22
|
+
/** The limit new keys get when `create()` doesn't set one. Defaults to 60 per minute. */
|
|
23
|
+
readonly defaultRateLimit?: ApiKeyRateLimit | null | undefined;
|
|
24
|
+
/**
|
|
25
|
+
* For keys created by a previous system: the hash it stored for a key, such as
|
|
26
|
+
* `(key) => createHmac("sha256", oldPepper).update(key).digest("hex")`. Such keys verify, and
|
|
27
|
+
* are moved to groundwork's hash the first time they're used.
|
|
28
|
+
*/
|
|
29
|
+
readonly legacyHash?: ((key: string) => string) | undefined;
|
|
30
|
+
/** Called after every change to a key, in its transaction. `createGroundwork` uses it for the audit log. */
|
|
31
|
+
readonly onEvent?: ((event: ApiKeyEvent<keyof TScopes & string>) => void | Promise<void>) | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* Receives background writes (`lastUsedAt`) so a serverless platform can wait for them:
|
|
34
|
+
* Next.js `after`, or `ctx.waitUntil`. Defaults to letting them run on their own.
|
|
35
|
+
*/
|
|
36
|
+
readonly waitUntil?: ((promise: Promise<unknown>) => void) | undefined;
|
|
37
|
+
/** Defaults to Postgres's time. Inject one in tests. */
|
|
38
|
+
readonly clock?: Clock | undefined;
|
|
39
|
+
/** Defaults to `console` (warnings and errors only). */
|
|
40
|
+
readonly logger?: Logger | undefined;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Creates scoped API keys stored in your Postgres.
|
|
44
|
+
*
|
|
45
|
+
* ```ts
|
|
46
|
+
* const apiKeys = createApiKeys({ db, table, secret, namespace: "vnt", scopes: { "posts:read": "Read posts" }, rateLimiter });
|
|
47
|
+
* const { key } = await apiKeys.create({ name: "CI", scopes: ["posts:read"] });
|
|
48
|
+
* const auth = await apiKeys.verify(request, { scopes: ["posts:read"] });
|
|
49
|
+
* if (!auth.ok) return auth.response;
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
export declare function createApiKeys<const TScopes extends Record<string, string>>(options: ApiKeysOptions<TScopes>): ApiKeys<keyof TScopes & string>;
|
|
53
|
+
//# sourceMappingURL=api-keys.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api-keys.d.ts","sourceRoot":"","sources":["../../src/api-keys/api-keys.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAgB,KAAK,MAAM,EAAmB,MAAM,uBAAuB,CAAC;AACnF,OAAO,EAAE,KAAK,kBAAkB,EAAoB,MAAM,mBAAmB,CAAC;AAG9E,OAAO,EAAmC,KAAK,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAErF,OAAO,KAAK,EAAE,WAAW,EAAkC,MAAM,wBAAwB,CAAC;AAC1F,OAAO,EAAmB,KAAK,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAkB3E,OAAO,KAAK,EACV,WAAW,EAEX,eAAe,EAGf,OAAO,EAOR,MAAM,YAAY,CAAC;AAEpB,MAAM,WAAW,cAAc,CAAC,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IACpE,QAAQ,CAAC,EAAE,EAAE,kBAAkB,CAAC;IAChC,qDAAqD;IACrD,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC;IAC7B,+EAA+E;IAC/E,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,8FAA8F;IAC9F,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,wFAAwF;IACxF,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,gGAAgG;IAChG,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IACxC,mGAAmG;IACnG,QAAQ,CAAC,WAAW,CAAC,EAAE,WAAW,GAAG,SAAS,CAAC;IAC/C,yFAAyF;IACzF,QAAQ,CAAC,gBAAgB,CAAC,EAAE,eAAe,GAAG,IAAI,GAAG,SAAS,CAAC;IAC/D;;;;OAIG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,MAAM,KAAK,MAAM,CAAC,GAAG,SAAS,CAAC;IAC5D,4GAA4G;IAC5G,QAAQ,CAAC,OAAO,CAAC,EACb,CAAC,CAAC,KAAK,EAAE,WAAW,CAAC,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,GACtE,SAAS,CAAC;IACd;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IACvE,wDAAwD;IACxD,QAAQ,CAAC,KAAK,CAAC,EAAE,KAAK,GAAG,SAAS,CAAC;IACnC,wDAAwD;IACxD,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACtC;AA6ED;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,KAAK,CAAC,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EACxE,OAAO,EAAE,cAAc,CAAC,OAAO,CAAC,GAC/B,OAAO,CAAC,MAAM,OAAO,GAAG,MAAM,CAAC,CAkqBjC"}
|