@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
|
@@ -0,0 +1,615 @@
|
|
|
1
|
+
import { sql } from "drizzle-orm";
|
|
2
|
+
import { toJsonObject } from "../audit/json.js";
|
|
3
|
+
import { ipInBlocks } from "../internal/cidr.js";
|
|
4
|
+
import { deriveSubkey, timingSafeEqual } from "../internal/crypto.js";
|
|
5
|
+
import { rowsOf, toNumber } from "../internal/db.js";
|
|
6
|
+
import { isDuration, parseDuration } from "../internal/duration.js";
|
|
7
|
+
import { GroundworkError } from "../internal/errors.js";
|
|
8
|
+
import { consoleLogger, createOnceLogger } from "../internal/logger.js";
|
|
9
|
+
import { assertTableColumns } from "../internal/table.js";
|
|
10
|
+
import { API_KEY_COLUMNS } from "../schema/api-keys.js";
|
|
11
|
+
import { displayPrefix, generateKey, hashKey, parseKey, redactKeys, validateNamespace, } from "./format.js";
|
|
12
|
+
import { createIpCache, extractKey, normalizeOrigin, validateIps, validateOrigins, } from "./policy.js";
|
|
13
|
+
import { failureHeaders, failureResponse, MESSAGES, STATUS } from "./responses.js";
|
|
14
|
+
import { createScopeRules } from "./scopes.js";
|
|
15
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
16
|
+
const TOUCH_EVERY_MS = 60_000;
|
|
17
|
+
const MAX_LIST = 1_000;
|
|
18
|
+
const SYSTEM = { type: "system" };
|
|
19
|
+
const noRedaction = () => false;
|
|
20
|
+
const ms = (column) => `(extract(epoch from ${column}) * 1000)::float8`;
|
|
21
|
+
// The whole record as one JSON object: one parser for every query, the same on every driver.
|
|
22
|
+
const RECORD = sql.raw(`jsonb_build_object(
|
|
23
|
+
'id', k.id::text, 'name', k.name, 'description', k.description, 'prefix', k.prefix,
|
|
24
|
+
'scopes', to_jsonb(k.scopes), 'owner_id', k.owner_id,
|
|
25
|
+
'rate_limit', k.rate_limit, 'rate_limit_window', k.rate_limit_window, 'daily_quota', k.daily_quota,
|
|
26
|
+
'allowed_ips', to_jsonb(k.allowed_ips), 'allowed_origins', to_jsonb(k.allowed_origins),
|
|
27
|
+
'metadata', k.metadata,
|
|
28
|
+
'expires_at', ${ms("k.expires_at")}, 'revoked_at', ${ms("k.revoked_at")}, 'revoked_reason', k.revoked_reason,
|
|
29
|
+
'suspended_until', ${ms("k.suspended_until")}, 'suspended_reason', k.suspended_reason,
|
|
30
|
+
'rotated_at', ${ms("k.rotated_at")}, 'previous_key_expires_at', ${ms("k.previous_key_expires_at")},
|
|
31
|
+
'last_used_at', ${ms("k.last_used_at")}, 'last_used_ip', k.last_used_ip, 'created_by', k.created_by,
|
|
32
|
+
'created_at', ${ms("k.created_at")}, 'updated_at', ${ms("k.updated_at")}
|
|
33
|
+
)::text`);
|
|
34
|
+
const toDate = (value) => (value === null ? null : new Date(value));
|
|
35
|
+
function statusAt(row, now) {
|
|
36
|
+
if (row.revoked_at !== null)
|
|
37
|
+
return "revoked";
|
|
38
|
+
if (row.expires_at !== null && row.expires_at <= now)
|
|
39
|
+
return "expired";
|
|
40
|
+
if (row.suspended_until !== null && row.suspended_until > now)
|
|
41
|
+
return "suspended";
|
|
42
|
+
return "active";
|
|
43
|
+
}
|
|
44
|
+
/** Postgres's error code, whether the driver or Drizzle wrapped it. */
|
|
45
|
+
function pgCode(error) {
|
|
46
|
+
const own = error?.code;
|
|
47
|
+
if (typeof own === "string")
|
|
48
|
+
return own;
|
|
49
|
+
const cause = error?.cause?.code;
|
|
50
|
+
return typeof cause === "string" ? cause : undefined;
|
|
51
|
+
}
|
|
52
|
+
/** A text[] parameter. Drizzle expands JS arrays into lists, so they travel as JSON instead. */
|
|
53
|
+
const textArray = (values) => sql `array(select value from jsonb_array_elements_text(${JSON.stringify(values)}::jsonb) with ordinality as t(value, position) order by position)::text[]`;
|
|
54
|
+
function actorName(actor) {
|
|
55
|
+
if (actor.id !== undefined && actor.id !== null)
|
|
56
|
+
return String(actor.id);
|
|
57
|
+
return actor.label ?? null;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Creates scoped API keys stored in your Postgres.
|
|
61
|
+
*
|
|
62
|
+
* ```ts
|
|
63
|
+
* const apiKeys = createApiKeys({ db, table, secret, namespace: "vnt", scopes: { "posts:read": "Read posts" }, rateLimiter });
|
|
64
|
+
* const { key } = await apiKeys.create({ name: "CI", scopes: ["posts:read"] });
|
|
65
|
+
* const auth = await apiKeys.verify(request, { scopes: ["posts:read"] });
|
|
66
|
+
* if (!auth.ok) return auth.response;
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
export function createApiKeys(options) {
|
|
70
|
+
if (typeof options !== "object" || options === null) {
|
|
71
|
+
throw new GroundworkError("invalid_config", "createApiKeys needs an options object.");
|
|
72
|
+
}
|
|
73
|
+
const { db, table, clock, rateLimiter, legacyHash, onEvent } = options;
|
|
74
|
+
if (!db || typeof db.execute !== "function") {
|
|
75
|
+
throw new GroundworkError("invalid_config", "db must be a Drizzle Postgres database.");
|
|
76
|
+
}
|
|
77
|
+
assertTableColumns(table, API_KEY_COLUMNS, "apiKeys table from groundworkTables()");
|
|
78
|
+
const namespace = validateNamespace(options.namespace);
|
|
79
|
+
const scopeRules = createScopeRules(options.scopes);
|
|
80
|
+
const checksum = options.checksum ?? true;
|
|
81
|
+
const subkey = deriveSubkey(options.secret, "api-keys");
|
|
82
|
+
const logger = createOnceLogger(options.logger ?? consoleLogger);
|
|
83
|
+
const waitUntil = options.waitUntil ??
|
|
84
|
+
((promise) => {
|
|
85
|
+
void promise;
|
|
86
|
+
});
|
|
87
|
+
if (legacyHash !== undefined && typeof legacyHash !== "function") {
|
|
88
|
+
throw new GroundworkError("invalid_config", "legacyHash must be a function.");
|
|
89
|
+
}
|
|
90
|
+
function validateRateLimit(value, label, code) {
|
|
91
|
+
if (value === null)
|
|
92
|
+
return null;
|
|
93
|
+
const limit = value?.limit;
|
|
94
|
+
const window = value?.window;
|
|
95
|
+
if (typeof value !== "object" ||
|
|
96
|
+
!Number.isSafeInteger(limit) ||
|
|
97
|
+
limit < 1 ||
|
|
98
|
+
!isDuration(window)) {
|
|
99
|
+
throw new GroundworkError(code, `${label} must be { limit: a positive integer, window: a duration such as "1m" }, or null.`);
|
|
100
|
+
}
|
|
101
|
+
parseDuration(window, { label: `${label}.window`, minMs: 1 });
|
|
102
|
+
return { limit: limit, window };
|
|
103
|
+
}
|
|
104
|
+
const defaultRateLimit = options.defaultRateLimit === undefined
|
|
105
|
+
? { limit: 60, window: "1m" }
|
|
106
|
+
: validateRateLimit(options.defaultRateLimit, "defaultRateLimit", "invalid_config");
|
|
107
|
+
if (defaultRateLimit !== null && rateLimiter === undefined) {
|
|
108
|
+
throw new GroundworkError("invalid_config", "API keys get a 60-per-minute limit by default, which needs a rateLimiter. Pass one, or set defaultRateLimit: null.");
|
|
109
|
+
}
|
|
110
|
+
const now = () => (clock ? sql `${clock.now().toISOString()}::timestamptz` : sql `now()`);
|
|
111
|
+
const ipBlocks = createIpCache();
|
|
112
|
+
const recentTouches = new Map();
|
|
113
|
+
const rules = new Map();
|
|
114
|
+
function toRecord(row, at) {
|
|
115
|
+
return {
|
|
116
|
+
id: row.id,
|
|
117
|
+
name: row.name,
|
|
118
|
+
description: row.description,
|
|
119
|
+
prefix: displayPrefix(namespace, row.prefix),
|
|
120
|
+
scopes: row.scopes,
|
|
121
|
+
ownerId: row.owner_id,
|
|
122
|
+
rateLimit: row.rate_limit === null || row.rate_limit_window === null
|
|
123
|
+
? null
|
|
124
|
+
: { limit: row.rate_limit, window: row.rate_limit_window },
|
|
125
|
+
dailyQuota: row.daily_quota,
|
|
126
|
+
allowedIps: row.allowed_ips,
|
|
127
|
+
allowedOrigins: row.allowed_origins,
|
|
128
|
+
metadata: row.metadata,
|
|
129
|
+
status: statusAt(row, at),
|
|
130
|
+
expiresAt: toDate(row.expires_at),
|
|
131
|
+
revokedAt: toDate(row.revoked_at),
|
|
132
|
+
revokedReason: row.revoked_reason,
|
|
133
|
+
suspendedUntil: toDate(row.suspended_until),
|
|
134
|
+
suspendedReason: row.suspended_reason,
|
|
135
|
+
rotatedAt: toDate(row.rotated_at),
|
|
136
|
+
previousKeyExpiresAt: toDate(row.previous_key_expires_at),
|
|
137
|
+
lastUsedAt: toDate(row.last_used_at),
|
|
138
|
+
lastUsedIp: row.last_used_ip,
|
|
139
|
+
createdBy: row.created_by,
|
|
140
|
+
createdAt: new Date(row.created_at),
|
|
141
|
+
updatedAt: new Date(row.updated_at),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
/** Runs a statement that returns `record` (and optionally `before`) plus `now`. */
|
|
145
|
+
async function run(target, query) {
|
|
146
|
+
const rows = rowsOf(await target.execute(query));
|
|
147
|
+
return rows.map((row) => {
|
|
148
|
+
const at = toNumber(row.now);
|
|
149
|
+
return {
|
|
150
|
+
record: toRecord(JSON.parse(row.record), at),
|
|
151
|
+
before: row.before === undefined
|
|
152
|
+
? undefined
|
|
153
|
+
: toRecord(JSON.parse(row.before), at),
|
|
154
|
+
raw: JSON.parse(row.record),
|
|
155
|
+
at,
|
|
156
|
+
};
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
/** `with input as (now) <body> select <body result>.record, now`: every mutation's shape. */
|
|
160
|
+
const mutation = (body, select = sql `changed.record`) => sql `with input as materialized (select ${now()} as now), ${body} select ${select}, ${sql.raw(ms("input.now"))} as now from changed, input`;
|
|
161
|
+
async function emit(event) {
|
|
162
|
+
if (onEvent)
|
|
163
|
+
await onEvent(event);
|
|
164
|
+
}
|
|
165
|
+
function policyValues(input, partial) {
|
|
166
|
+
const out = {};
|
|
167
|
+
if (!partial || input.name !== undefined) {
|
|
168
|
+
if (typeof input.name !== "string" || input.name.trim() === "" || input.name.length > 200) {
|
|
169
|
+
throw new GroundworkError("invalid_argument", "name must be a non-empty string of at most 200 characters.");
|
|
170
|
+
}
|
|
171
|
+
out.name = sql `${input.name.trim()}::text`;
|
|
172
|
+
}
|
|
173
|
+
if (input.description !== undefined) {
|
|
174
|
+
if (input.description !== null &&
|
|
175
|
+
(typeof input.description !== "string" || input.description.length > 2_000)) {
|
|
176
|
+
throw new GroundworkError("invalid_argument", "description must be a string of at most 2,000 characters.");
|
|
177
|
+
}
|
|
178
|
+
out.description = sql `${input.description}::text`;
|
|
179
|
+
}
|
|
180
|
+
if (!partial || input.scopes !== undefined) {
|
|
181
|
+
out.scopes = textArray(scopeRules.grantable(input.scopes, "scopes"));
|
|
182
|
+
}
|
|
183
|
+
if (input.ownerId !== undefined) {
|
|
184
|
+
if (input.ownerId !== null &&
|
|
185
|
+
typeof input.ownerId !== "string" &&
|
|
186
|
+
typeof input.ownerId !== "number") {
|
|
187
|
+
throw new GroundworkError("invalid_argument", "ownerId must be a string or a number.");
|
|
188
|
+
}
|
|
189
|
+
out.owner_id = sql `${input.ownerId === null ? null : String(input.ownerId)}::text`;
|
|
190
|
+
}
|
|
191
|
+
if (input.rateLimit !== undefined || !partial) {
|
|
192
|
+
const rateLimit = input.rateLimit === undefined
|
|
193
|
+
? defaultRateLimit
|
|
194
|
+
: validateRateLimit(input.rateLimit, "rateLimit", "invalid_argument");
|
|
195
|
+
if (rateLimit !== null && rateLimiter === undefined) {
|
|
196
|
+
throw new GroundworkError("invalid_argument", "A per-key rateLimit needs the module's rateLimiter.");
|
|
197
|
+
}
|
|
198
|
+
out.rate_limit = sql `${rateLimit?.limit ?? null}::int`;
|
|
199
|
+
out.rate_limit_window = sql `${rateLimit?.window ?? null}::text`;
|
|
200
|
+
}
|
|
201
|
+
if (input.dailyQuota !== undefined) {
|
|
202
|
+
if (input.dailyQuota !== null) {
|
|
203
|
+
if (!Number.isSafeInteger(input.dailyQuota) ||
|
|
204
|
+
input.dailyQuota < 1 ||
|
|
205
|
+
input.dailyQuota > 2_147_483_647) {
|
|
206
|
+
throw new GroundworkError("invalid_argument", "dailyQuota must be a positive integer, or null.");
|
|
207
|
+
}
|
|
208
|
+
if (rateLimiter === undefined) {
|
|
209
|
+
throw new GroundworkError("invalid_argument", "A dailyQuota needs the module's rateLimiter.");
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
out.daily_quota = sql `${input.dailyQuota}::int`;
|
|
213
|
+
}
|
|
214
|
+
if (input.allowedIps !== undefined)
|
|
215
|
+
out.allowed_ips = textArray(validateIps(input.allowedIps, "allowedIps"));
|
|
216
|
+
if (input.allowedOrigins !== undefined) {
|
|
217
|
+
out.allowed_origins = textArray(validateOrigins(input.allowedOrigins, "allowedOrigins"));
|
|
218
|
+
}
|
|
219
|
+
if (input.metadata !== undefined) {
|
|
220
|
+
const metadata = toJsonObject(input.metadata, noRedaction, "metadata");
|
|
221
|
+
out.metadata = sql `${metadata === null ? null : JSON.stringify(metadata)}::jsonb`;
|
|
222
|
+
}
|
|
223
|
+
if (input.expiresAt !== undefined) {
|
|
224
|
+
if (input.expiresAt !== null) {
|
|
225
|
+
if (!(input.expiresAt instanceof Date) || Number.isNaN(input.expiresAt.getTime())) {
|
|
226
|
+
throw new GroundworkError("invalid_argument", "expiresAt must be a valid Date, or null.");
|
|
227
|
+
}
|
|
228
|
+
if (input.expiresAt.getTime() <= (clock?.now() ?? new Date()).getTime()) {
|
|
229
|
+
throw new GroundworkError("invalid_argument", "expiresAt must be in the future.");
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
out.expires_at = sql `${input.expiresAt === null ? null : input.expiresAt.toISOString()}::timestamptz`;
|
|
233
|
+
}
|
|
234
|
+
return out;
|
|
235
|
+
}
|
|
236
|
+
const validId = (id) => typeof id === "string" && UUID.test(id);
|
|
237
|
+
function ruleFor(kind, limit, window) {
|
|
238
|
+
const id = `${kind}/${limit}/${window}`;
|
|
239
|
+
let rule = rules.get(id);
|
|
240
|
+
if (!rule) {
|
|
241
|
+
if (!rateLimiter) {
|
|
242
|
+
throw new GroundworkError("invalid_config", "This key has a rate limit or quota, but the API-key module has no rateLimiter.");
|
|
243
|
+
}
|
|
244
|
+
// One name per kind: changing a key's limit keeps its counter.
|
|
245
|
+
rule = rateLimiter.rule({
|
|
246
|
+
name: kind === "rate" ? `${namespace}:key` : `${namespace}:key.daily`,
|
|
247
|
+
limit,
|
|
248
|
+
window,
|
|
249
|
+
});
|
|
250
|
+
if (rules.size >= 1_000)
|
|
251
|
+
rules.clear();
|
|
252
|
+
rules.set(id, rule);
|
|
253
|
+
}
|
|
254
|
+
return rule;
|
|
255
|
+
}
|
|
256
|
+
function fail(reason, key = null, extra = {}) {
|
|
257
|
+
const missingScopes = extra.missingScopes ?? [];
|
|
258
|
+
const headers = failureHeaders(reason, missingScopes, extra.limit?.headers ?? {});
|
|
259
|
+
return {
|
|
260
|
+
ok: false,
|
|
261
|
+
reason,
|
|
262
|
+
status: STATUS[reason],
|
|
263
|
+
message: MESSAGES[reason],
|
|
264
|
+
key,
|
|
265
|
+
prefix: extra.prefix ?? null,
|
|
266
|
+
...(missingScopes.length > 0 ? { missingScopes } : {}),
|
|
267
|
+
headers,
|
|
268
|
+
response: failureResponse(reason, headers, missingScopes),
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
/** Records lastUsedAt / lastUsedIp at most once a minute per key, off the request's path. */
|
|
272
|
+
function touch(row, at, ip, legacy) {
|
|
273
|
+
const recent = recentTouches.get(row.id);
|
|
274
|
+
const stale = (row.last_used_at === null || at - row.last_used_at >= TOUCH_EVERY_MS) &&
|
|
275
|
+
(recent === undefined || at - recent >= TOUCH_EVERY_MS);
|
|
276
|
+
if (!stale && !legacy)
|
|
277
|
+
return;
|
|
278
|
+
if (stale) {
|
|
279
|
+
if (recentTouches.size >= 10_000)
|
|
280
|
+
recentTouches.clear();
|
|
281
|
+
recentTouches.set(row.id, at);
|
|
282
|
+
}
|
|
283
|
+
const work = (async () => {
|
|
284
|
+
if (legacy) {
|
|
285
|
+
// Move a legacy key to groundwork's hash, once.
|
|
286
|
+
await db.execute(sql `update ${table} as k set key_hash = ${legacy.to}::text where k.id = ${row.id}::uuid and k.key_hash = ${legacy.from}::text`);
|
|
287
|
+
}
|
|
288
|
+
if (stale) {
|
|
289
|
+
await db.execute(sql `
|
|
290
|
+
update ${table} as k set last_used_at = ${now()}, last_used_ip = ${ip}::text
|
|
291
|
+
where k.id = ${row.id}::uuid
|
|
292
|
+
and (k.last_used_at is null or k.last_used_at <= ${now()} - interval '1 minute')`);
|
|
293
|
+
}
|
|
294
|
+
})().catch((error) => {
|
|
295
|
+
logger.once("warn", "touch", "Could not record an API key's last use; it will be retried on later requests.", {
|
|
296
|
+
error: error instanceof Error ? { name: error.name, message: error.message } : String(error),
|
|
297
|
+
});
|
|
298
|
+
});
|
|
299
|
+
waitUntil(work);
|
|
300
|
+
}
|
|
301
|
+
const apiKeys = {
|
|
302
|
+
namespace,
|
|
303
|
+
scopes: Object.freeze({ ...options.scopes }),
|
|
304
|
+
async create(input, mutationOptions) {
|
|
305
|
+
if (typeof input !== "object" || input === null) {
|
|
306
|
+
throw new GroundworkError("invalid_argument", "create needs { name, scopes }.");
|
|
307
|
+
}
|
|
308
|
+
const actor = mutationOptions?.actor ?? SYSTEM;
|
|
309
|
+
const values = policyValues(input, false);
|
|
310
|
+
let expires = sql `null::timestamptz`;
|
|
311
|
+
if (input.expiresIn !== undefined &&
|
|
312
|
+
input.expiresAt !== undefined &&
|
|
313
|
+
input.expiresAt !== null) {
|
|
314
|
+
throw new GroundworkError("invalid_argument", "Pass expiresIn or expiresAt, not both.");
|
|
315
|
+
}
|
|
316
|
+
if (input.expiresIn !== undefined) {
|
|
317
|
+
const inMs = parseDuration(input.expiresIn, { label: "expiresIn", minMs: 1 });
|
|
318
|
+
expires = sql `input.now + ${inMs}::float8 * interval '1 millisecond'`;
|
|
319
|
+
}
|
|
320
|
+
else if (values.expires_at) {
|
|
321
|
+
expires = values.expires_at;
|
|
322
|
+
}
|
|
323
|
+
const target = mutationOptions?.tx ?? db;
|
|
324
|
+
// A 48-bit prefix can collide; the unique index catches it, and we draw a new key.
|
|
325
|
+
for (let attempt = 0;; attempt++) {
|
|
326
|
+
const generated = generateKey(namespace, checksum);
|
|
327
|
+
try {
|
|
328
|
+
const [result] = await run(target, mutation(sql `changed as (
|
|
329
|
+
insert into ${table} as k (name, description, prefix, key_hash, scopes, owner_id, rate_limit, rate_limit_window, daily_quota, allowed_ips, allowed_origins, metadata, expires_at, created_by, created_at, updated_at)
|
|
330
|
+
select ${values.name}, ${values.description ?? sql `null::text`}, ${generated.prefix}::text, ${hashKey(subkey, generated.body)}::text,
|
|
331
|
+
${values.scopes}, ${values.owner_id ?? sql `null::text`}, ${values.rate_limit}, ${values.rate_limit_window},
|
|
332
|
+
${values.daily_quota ?? sql `null::int`}, ${values.allowed_ips ?? sql `'{}'::text[]`}, ${values.allowed_origins ?? sql `'{}'::text[]`},
|
|
333
|
+
${values.metadata ?? sql `null::jsonb`}, ${expires}, ${actorName(actor)}::text, input.now, input.now
|
|
334
|
+
from input
|
|
335
|
+
returning ${RECORD} as record
|
|
336
|
+
)`));
|
|
337
|
+
if (!result)
|
|
338
|
+
throw new Error("API key insert returned no row");
|
|
339
|
+
await emit({ type: "create", key: result.record, actor, tx: mutationOptions?.tx });
|
|
340
|
+
return { key: generated.key, record: result.record };
|
|
341
|
+
}
|
|
342
|
+
catch (error) {
|
|
343
|
+
if (pgCode(error) === "23505" && attempt < 3)
|
|
344
|
+
continue;
|
|
345
|
+
throw error;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
},
|
|
349
|
+
async get(id) {
|
|
350
|
+
if (!validId(id))
|
|
351
|
+
return null;
|
|
352
|
+
const [result] = await run(db, sql `with input as materialized (select ${now()} as now)
|
|
353
|
+
select ${RECORD} as record, ${sql.raw(ms("input.now"))} as now from ${table} as k, input where k.id = ${id}::uuid`);
|
|
354
|
+
return result?.record ?? null;
|
|
355
|
+
},
|
|
356
|
+
async list(filter = {}) {
|
|
357
|
+
const limit = filter.limit ?? MAX_LIST;
|
|
358
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_LIST) {
|
|
359
|
+
throw new GroundworkError("invalid_argument", `limit must be an integer from 1 to ${MAX_LIST}.`);
|
|
360
|
+
}
|
|
361
|
+
const conditions = [];
|
|
362
|
+
if (filter.ownerId !== undefined)
|
|
363
|
+
conditions.push(sql `k.owner_id = ${String(filter.ownerId)}::text`);
|
|
364
|
+
if (filter.status !== undefined) {
|
|
365
|
+
const statuses = (Array.isArray(filter.status) ? filter.status : [filter.status]);
|
|
366
|
+
const byStatus = {
|
|
367
|
+
revoked: sql `k.revoked_at is not null`,
|
|
368
|
+
expired: sql `(k.revoked_at is null and k.expires_at <= input.now)`,
|
|
369
|
+
suspended: sql `(k.revoked_at is null and (k.expires_at is null or k.expires_at > input.now) and k.suspended_until > input.now)`,
|
|
370
|
+
active: sql `(k.revoked_at is null and (k.expires_at is null or k.expires_at > input.now) and (k.suspended_until is null or k.suspended_until <= input.now))`,
|
|
371
|
+
};
|
|
372
|
+
for (const status of statuses) {
|
|
373
|
+
if (!(status in byStatus)) {
|
|
374
|
+
throw new GroundworkError("invalid_argument", `Unknown status ${JSON.stringify(status)}.`);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
conditions.push(statuses.length === 0
|
|
378
|
+
? sql `false`
|
|
379
|
+
: sql `(${sql.join(statuses.map((s) => byStatus[s]), sql ` or `)})`);
|
|
380
|
+
}
|
|
381
|
+
const where = conditions.length === 0 ? sql `` : sql `where ${sql.join(conditions, sql ` and `)}`;
|
|
382
|
+
const results = await run(db, sql `with input as materialized (select ${now()} as now)
|
|
383
|
+
select ${RECORD} as record, ${sql.raw(ms("input.now"))} as now from ${table} as k, input ${where}
|
|
384
|
+
order by k.created_at desc, k.id desc limit ${limit}`);
|
|
385
|
+
return results.map((result) => result.record);
|
|
386
|
+
},
|
|
387
|
+
async update(id, patch, mutationOptions) {
|
|
388
|
+
if (typeof patch !== "object" || patch === null) {
|
|
389
|
+
throw new GroundworkError("invalid_argument", "update needs an object of fields to change.");
|
|
390
|
+
}
|
|
391
|
+
const values = policyValues(patch, true);
|
|
392
|
+
if (!validId(id))
|
|
393
|
+
return null;
|
|
394
|
+
const assignments = Object.entries(values).map(([column, value]) => sql `${sql.raw(column)} = ${value}`);
|
|
395
|
+
const [result] = await run(mutationOptions?.tx ?? db, mutation(sql `before as (select ${RECORD} as record, k.id from ${table} as k where k.id = ${id}::uuid for update),
|
|
396
|
+
changed as (
|
|
397
|
+
update ${table} as k set ${sql.join([...assignments, sql `updated_at = input.now`], sql `, `)}
|
|
398
|
+
from input, before where k.id = before.id
|
|
399
|
+
returning ${RECORD} as record
|
|
400
|
+
)`, sql `changed.record, (select record from before) as before`));
|
|
401
|
+
if (!result)
|
|
402
|
+
return null;
|
|
403
|
+
await emit({
|
|
404
|
+
type: "update",
|
|
405
|
+
key: result.record,
|
|
406
|
+
before: result.before,
|
|
407
|
+
actor: mutationOptions?.actor ?? SYSTEM,
|
|
408
|
+
tx: mutationOptions?.tx,
|
|
409
|
+
});
|
|
410
|
+
return result.record;
|
|
411
|
+
},
|
|
412
|
+
async rotate(id, rotateOptions = {}) {
|
|
413
|
+
const grace = rotateOptions.grace ?? "24h";
|
|
414
|
+
const graceMs = parseDuration(grace, { label: "grace" });
|
|
415
|
+
if (!validId(id))
|
|
416
|
+
return null;
|
|
417
|
+
const generated = generateKey(namespace, checksum);
|
|
418
|
+
const [result] = await run(rotateOptions.tx ?? db, mutation(sql `changed as (
|
|
419
|
+
update ${table} as k set
|
|
420
|
+
key_hash = ${hashKey(subkey, generated.body)}::text,
|
|
421
|
+
prefix = ${generated.prefix}::text,
|
|
422
|
+
previous_key_hash = case when ${graceMs}::float8 > 0 then k.key_hash else null end,
|
|
423
|
+
previous_key_expires_at = case when ${graceMs}::float8 > 0 then input.now + ${graceMs}::float8 * interval '1 millisecond' else null end,
|
|
424
|
+
rotated_at = input.now,
|
|
425
|
+
updated_at = input.now
|
|
426
|
+
from input where k.id = ${id}::uuid and k.revoked_at is null
|
|
427
|
+
returning ${RECORD} as record
|
|
428
|
+
)`));
|
|
429
|
+
if (!result)
|
|
430
|
+
return null;
|
|
431
|
+
await emit({
|
|
432
|
+
type: "rotate",
|
|
433
|
+
key: result.record,
|
|
434
|
+
actor: rotateOptions.actor ?? SYSTEM,
|
|
435
|
+
tx: rotateOptions.tx,
|
|
436
|
+
grace,
|
|
437
|
+
});
|
|
438
|
+
return { key: generated.key, record: result.record };
|
|
439
|
+
},
|
|
440
|
+
async revoke(id, revokeOptions = {}) {
|
|
441
|
+
const reason = revokeOptions.reason ?? null;
|
|
442
|
+
if (reason !== null && typeof reason !== "string") {
|
|
443
|
+
throw new GroundworkError("invalid_argument", "reason must be a string.");
|
|
444
|
+
}
|
|
445
|
+
if (!validId(id))
|
|
446
|
+
return null;
|
|
447
|
+
const [result] = await run(revokeOptions.tx ?? db, mutation(sql `changed as (
|
|
448
|
+
update ${table} as k set revoked_at = input.now, revoked_reason = ${reason}::text,
|
|
449
|
+
previous_key_hash = null, previous_key_expires_at = null, updated_at = input.now
|
|
450
|
+
from input where k.id = ${id}::uuid and k.revoked_at is null
|
|
451
|
+
returning ${RECORD} as record
|
|
452
|
+
)`));
|
|
453
|
+
if (!result)
|
|
454
|
+
return null;
|
|
455
|
+
await emit({
|
|
456
|
+
type: "revoke",
|
|
457
|
+
key: result.record,
|
|
458
|
+
actor: revokeOptions.actor ?? SYSTEM,
|
|
459
|
+
tx: revokeOptions.tx,
|
|
460
|
+
reason,
|
|
461
|
+
});
|
|
462
|
+
return result.record;
|
|
463
|
+
},
|
|
464
|
+
async suspend(id, suspendOptions) {
|
|
465
|
+
if (typeof suspendOptions !== "object" || suspendOptions === null) {
|
|
466
|
+
throw new GroundworkError("invalid_argument", 'suspend needs { for: "1h" }.');
|
|
467
|
+
}
|
|
468
|
+
const forMs = parseDuration(suspendOptions.for, { label: "for", minMs: 1 });
|
|
469
|
+
const reason = suspendOptions.reason ?? null;
|
|
470
|
+
if (reason !== null && typeof reason !== "string") {
|
|
471
|
+
throw new GroundworkError("invalid_argument", "reason must be a string.");
|
|
472
|
+
}
|
|
473
|
+
if (!validId(id))
|
|
474
|
+
return null;
|
|
475
|
+
const [result] = await run(suspendOptions.tx ?? db, mutation(sql `changed as (
|
|
476
|
+
update ${table} as k set suspended_until = input.now + ${forMs}::float8 * interval '1 millisecond',
|
|
477
|
+
suspended_reason = ${reason}::text, updated_at = input.now
|
|
478
|
+
from input where k.id = ${id}::uuid and k.revoked_at is null
|
|
479
|
+
returning ${RECORD} as record
|
|
480
|
+
)`));
|
|
481
|
+
if (!result)
|
|
482
|
+
return null;
|
|
483
|
+
await emit({
|
|
484
|
+
type: "suspend",
|
|
485
|
+
key: result.record,
|
|
486
|
+
actor: suspendOptions.actor ?? SYSTEM,
|
|
487
|
+
tx: suspendOptions.tx,
|
|
488
|
+
reason,
|
|
489
|
+
});
|
|
490
|
+
return result.record;
|
|
491
|
+
},
|
|
492
|
+
async reinstate(id, mutationOptions = {}) {
|
|
493
|
+
if (!validId(id))
|
|
494
|
+
return null;
|
|
495
|
+
const [result] = await run(mutationOptions.tx ?? db, mutation(sql `changed as (
|
|
496
|
+
update ${table} as k set suspended_until = null, suspended_reason = null, updated_at = input.now
|
|
497
|
+
from input where k.id = ${id}::uuid and k.revoked_at is null
|
|
498
|
+
returning ${RECORD} as record
|
|
499
|
+
)`));
|
|
500
|
+
if (!result)
|
|
501
|
+
return null;
|
|
502
|
+
await emit({
|
|
503
|
+
type: "reinstate",
|
|
504
|
+
key: result.record,
|
|
505
|
+
actor: mutationOptions.actor ?? SYSTEM,
|
|
506
|
+
tx: mutationOptions.tx,
|
|
507
|
+
});
|
|
508
|
+
return result.record;
|
|
509
|
+
},
|
|
510
|
+
async delete(id, mutationOptions = {}) {
|
|
511
|
+
if (!validId(id))
|
|
512
|
+
return false;
|
|
513
|
+
const [result] = await run(mutationOptions.tx ?? db, mutation(sql `changed as (
|
|
514
|
+
delete from ${table} as k where k.id = ${id}::uuid and k.revoked_at is not null
|
|
515
|
+
returning ${RECORD} as record
|
|
516
|
+
)`));
|
|
517
|
+
if (!result)
|
|
518
|
+
return false;
|
|
519
|
+
await emit({
|
|
520
|
+
type: "delete",
|
|
521
|
+
key: result.record,
|
|
522
|
+
actor: mutationOptions.actor ?? SYSTEM,
|
|
523
|
+
tx: mutationOptions.tx,
|
|
524
|
+
});
|
|
525
|
+
return true;
|
|
526
|
+
},
|
|
527
|
+
async verify(input, verifyOptions = {}) {
|
|
528
|
+
const raw = extractKey(input);
|
|
529
|
+
if (raw === null)
|
|
530
|
+
return fail("missing");
|
|
531
|
+
// Malformed keys, including typos caught by the checksum, never reach the database.
|
|
532
|
+
const parsed = parseKey(raw, namespace);
|
|
533
|
+
if (parsed === null)
|
|
534
|
+
return fail("malformed");
|
|
535
|
+
// From here on, failures carry the presented key's prefix (never the key) for logging.
|
|
536
|
+
const presented = displayPrefix(namespace, parsed.prefix);
|
|
537
|
+
const denied = (reason, key = null, extra = {}) => fail(reason, key, { ...extra, prefix: presented });
|
|
538
|
+
const hash = hashKey(subkey, parsed.body);
|
|
539
|
+
const legacy = legacyHash ? legacyHash(parsed.body) : null;
|
|
540
|
+
if (legacy !== null && typeof legacy !== "string") {
|
|
541
|
+
throw new GroundworkError("invalid_config", "legacyHash must return a string.");
|
|
542
|
+
}
|
|
543
|
+
// One round trip: the current key, or the previous one within its grace period.
|
|
544
|
+
const rows = rowsOf(await db.execute(sql `
|
|
545
|
+
with input as materialized (select ${now()} as now)
|
|
546
|
+
select ${RECORD} as record, k.key_hash, k.previous_key_hash, ${sql.raw(ms("input.now"))} as now
|
|
547
|
+
from ${table} as k, input
|
|
548
|
+
where k.key_hash in (${hash}::text, ${legacy}::text)
|
|
549
|
+
or (k.previous_key_hash in (${hash}::text, ${legacy}::text) and k.previous_key_expires_at > input.now)
|
|
550
|
+
limit 1`));
|
|
551
|
+
const row = rows[0];
|
|
552
|
+
if (!row)
|
|
553
|
+
return denied("invalid");
|
|
554
|
+
const at = toNumber(row.now);
|
|
555
|
+
const stored = JSON.parse(row.record);
|
|
556
|
+
const matches = (candidate) => candidate !== null &&
|
|
557
|
+
(timingSafeEqual(candidate, hash) ||
|
|
558
|
+
(legacy !== null && timingSafeEqual(candidate, legacy)));
|
|
559
|
+
const current = matches(row.key_hash);
|
|
560
|
+
const previous = !current &&
|
|
561
|
+
matches(row.previous_key_hash) &&
|
|
562
|
+
stored.previous_key_expires_at !== null &&
|
|
563
|
+
stored.previous_key_expires_at > at;
|
|
564
|
+
if (!current && !previous)
|
|
565
|
+
return denied("invalid");
|
|
566
|
+
const key = toRecord(stored, at);
|
|
567
|
+
if (key.status === "revoked")
|
|
568
|
+
return denied("revoked", key);
|
|
569
|
+
if (key.status === "expired")
|
|
570
|
+
return denied("expired", key);
|
|
571
|
+
if (key.status === "suspended")
|
|
572
|
+
return denied("suspended", key);
|
|
573
|
+
const request = input === null || input === undefined || typeof input === "string"
|
|
574
|
+
? null
|
|
575
|
+
: input instanceof Headers
|
|
576
|
+
? input
|
|
577
|
+
: input.headers;
|
|
578
|
+
const ip = verifyOptions.ip ?? null;
|
|
579
|
+
if (key.allowedIps.length > 0 && (ip === null || !ipInBlocks(ip, ipBlocks(key.allowedIps)))) {
|
|
580
|
+
return denied("ip_denied", key);
|
|
581
|
+
}
|
|
582
|
+
const origin = verifyOptions.origin !== undefined
|
|
583
|
+
? verifyOptions.origin
|
|
584
|
+
: (request?.get("origin") ?? null);
|
|
585
|
+
// Only browsers send Origin; a request without one isn't held to the list.
|
|
586
|
+
if (key.allowedOrigins.length > 0 && origin !== null) {
|
|
587
|
+
const normalized = normalizeOrigin(origin);
|
|
588
|
+
if (normalized === null || !key.allowedOrigins.includes(normalized))
|
|
589
|
+
return denied("origin_denied", key);
|
|
590
|
+
}
|
|
591
|
+
const required = verifyOptions.scopes ?? [];
|
|
592
|
+
const missingScopes = scopeRules.missing(key.scopes, required);
|
|
593
|
+
if (missingScopes.length > 0)
|
|
594
|
+
return denied("forbidden_scope", key, { missingScopes });
|
|
595
|
+
let headers = {};
|
|
596
|
+
if (key.rateLimit) {
|
|
597
|
+
const limit = await ruleFor("rate", key.rateLimit.limit, key.rateLimit.window).check(key.id);
|
|
598
|
+
if (!limit.allowed)
|
|
599
|
+
return denied("rate_limited", key, { limit });
|
|
600
|
+
headers = limit.headers;
|
|
601
|
+
}
|
|
602
|
+
if (key.dailyQuota !== null) {
|
|
603
|
+
const quota = await ruleFor("quota", key.dailyQuota, "1d").check(key.id);
|
|
604
|
+
if (!quota.allowed)
|
|
605
|
+
return denied("quota_exceeded", key, { limit: quota });
|
|
606
|
+
}
|
|
607
|
+
const legacyMatch = current && legacy !== null && timingSafeEqual(row.key_hash, legacy);
|
|
608
|
+
touch(stored, at, ip, legacyMatch ? { from: legacy, to: hash } : null);
|
|
609
|
+
return { ok: true, key, headers };
|
|
610
|
+
},
|
|
611
|
+
redactKeys: (text) => redactKeys(text, namespace),
|
|
612
|
+
};
|
|
613
|
+
return apiKeys;
|
|
614
|
+
}
|
|
615
|
+
//# sourceMappingURL=api-keys.js.map
|