@zjazj/server 0.0.8 → 0.0.9

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.
@@ -0,0 +1,208 @@
1
+ import { MiddlewareHandler, Context } from 'hono';
2
+ import { jwtVerify, JWTPayload } from 'jose';
3
+
4
+ /** The authenticated caller. */
5
+ interface AuthUser {
6
+ /** The identity provider's user id. An opaque string. */
7
+ id: string;
8
+ /** The tenant the token was issued for. A UUID. */
9
+ tenantId: string;
10
+ tenantSlug: string;
11
+ username: string;
12
+ roles: string[];
13
+ permissions: string[];
14
+ /** IANA time zone of the tenant, when the token carries one. */
15
+ timeZone?: string;
16
+ /**
17
+ * Set when a platform operator works in this tenant as platform support. `until` is when
18
+ * the session ends, in seconds since 1970. The subject is the operator.
19
+ */
20
+ support?: SupportSession;
21
+ /**
22
+ * Set when the request was made with an API key rather than a person's token. A user key
23
+ * acts as its user, a tenant key as the tenant, with the roles it was given.
24
+ */
25
+ apiKey?: ApiKeyInfo;
26
+ /** True only for the local dev identity. */
27
+ isDev?: boolean;
28
+ }
29
+ /** A platform operator's time in a customer's tenant, as the token states it. */
30
+ interface SupportSession {
31
+ until: number;
32
+ /** `support` today. */
33
+ mode: string;
34
+ }
35
+ /**
36
+ * The support session a token states, from `support_until` and `support_mode`. Both or
37
+ * nothing: half of it is not a session. Mirrored in `@zjazj/web`.
38
+ */
39
+ declare function supportFromClaims(claims: Record<string, unknown>): SupportSession | undefined;
40
+ /** Organization tokens carry this audience prefix followed by the organization id. */
41
+ declare const ORGANIZATION_AUDIENCE_PREFIX = "urn:logto:organization:";
42
+ type VerifyKey = Parameters<typeof jwtVerify>[1];
43
+ interface VerifierOptions {
44
+ /** The token issuer, for example `https://auth.example.com/oidc`. */
45
+ issuer: string;
46
+ /** A fixed audience. Leave unset to accept organization tokens. */
47
+ audience?: string;
48
+ /** Defaults to `<issuer>/jwks`. */
49
+ jwksUri?: string;
50
+ /** A key or key resolver, used instead of fetching the JWKS. Meant for tests. */
51
+ key?: VerifyKey;
52
+ algorithms?: string[];
53
+ }
54
+ interface Verifier {
55
+ verify(token: string): Promise<AuthUser>;
56
+ }
57
+ /** Project verified token claims into an `AuthUser`. */
58
+ declare function userFromClaims(claims: JWTPayload): AuthUser;
59
+ /** Build a verifier for tokens issued by the platform's identity provider. */
60
+ declare function createVerifier(options: VerifierOptions): Verifier;
61
+ type Env$1 = Record<string, string | undefined>;
62
+ /** Build the verifier from `LOGTO_ISSUER`, `LOGTO_AUDIENCE` and `LOGTO_JWKS_URI`. */
63
+ declare function verifierFromEnv(env?: Env$1): Verifier | undefined;
64
+ declare function bearerToken(header: string | undefined): string | undefined;
65
+ interface AuthenticateOptions {
66
+ verifier?: Verifier;
67
+ /** Checks API keys. Defaults to asking the control plane at `PLATFORM_URL`. */
68
+ keyVerifier?: KeyVerifier;
69
+ /**
70
+ * Every route behind this middleware accepts an API key, as the MCP endpoint does.
71
+ * Otherwise only a route with `acceptApiKey()` does.
72
+ */
73
+ acceptApiKeys?: boolean;
74
+ env?: Env$1;
75
+ }
76
+ /**
77
+ * Require an authenticated caller. On success the user is available through `getUser(c)`.
78
+ * With the dev identity enabled no token is verified and every request is the dev user.
79
+ *
80
+ * A bearer value that starts with `pk_` is an API key. It is taken only on a route that
81
+ * accepts keys (`acceptApiKey()`), and checked by the key verifier; the caller then has
82
+ * the shape of a signed-in user, with `apiKey` set. In development a key is the dev
83
+ * identity, and a dev key (`encodeDevApiKey`) changes it as a dev token does.
84
+ */
85
+ declare function authenticate(options?: AuthenticateOptions): MiddlewareHandler;
86
+ /** The authenticated user of this request. Throws 401 when the route is not authenticated. */
87
+ declare function getUser(c: Context): AuthUser;
88
+ /** Require every listed permission. Wildcards in the granted set count. */
89
+ declare function requirePermission(...codes: string[]): MiddlewareHandler;
90
+ /** Require at least one of the listed roles. */
91
+ declare function requireRole(...roles: string[]): MiddlewareHandler;
92
+ declare module 'hono' {
93
+ interface ContextVariableMap {
94
+ user: AuthUser;
95
+ }
96
+ }
97
+
98
+ type Env = Record<string, string | undefined>;
99
+ /** Every API key starts with this. A bearer value without it is a token. */
100
+ declare const API_KEY_PREFIX = "pk_";
101
+ /** A user key acts as its user in one tenant. A tenant key acts as the tenant. */
102
+ type ApiKeyKind = 'user' | 'tenant';
103
+ /** The key a request was made with, on `AuthUser.apiKey`. */
104
+ interface ApiKeyInfo {
105
+ id: string;
106
+ kind: ApiKeyKind;
107
+ }
108
+ /**
109
+ * The answer of `POST /internal/api-keys/verify` on the control plane for a key it
110
+ * accepts (`docs/mcp-plan.md`, section 6).
111
+ */
112
+ interface ApiKeyVerification {
113
+ /** The user's id, or `key:<key id>` for a tenant key. */
114
+ subject: string;
115
+ kind: ApiKeyKind;
116
+ key_id: string;
117
+ tenant_id: string;
118
+ tenant_slug?: string;
119
+ tenant_time_zone?: string | null;
120
+ username?: string;
121
+ roles?: string[];
122
+ permissions?: string[];
123
+ /** How long the answer may be kept. Capped at `MAX_API_KEY_CACHE_SECONDS`. */
124
+ cache_seconds?: number;
125
+ }
126
+ /** Checks an API key and returns the caller it acts as. */
127
+ interface KeyVerifier {
128
+ verify(key: string): Promise<AuthUser>;
129
+ }
130
+ interface KeyVerifierOptions {
131
+ /**
132
+ * Checks a key here instead of asking the control plane: for the control plane itself,
133
+ * which holds the keys. Returns what `POST /internal/api-keys/verify` would answer, or
134
+ * undefined for a key it refuses. Its answers are kept like the control plane's.
135
+ */
136
+ check?: (key: string) => Promise<ApiKeyVerification | undefined>;
137
+ /** Read for `PLATFORM_URL`. Defaults to `process.env`. */
138
+ env?: Env;
139
+ fetch?: typeof fetch;
140
+ /** Milliseconds to wait for the control plane. Defaults to 5 seconds. */
141
+ timeout?: number;
142
+ }
143
+ /** The longest an answer is kept. Revoking a key takes effect within this time. */
144
+ declare const MAX_API_KEY_CACHE_SECONDS = 60;
145
+ /** How long a refused key is refused without asking again. */
146
+ declare const API_KEY_REFUSAL_SECONDS = 5;
147
+ /** True when the bearer value is an API key rather than a token. */
148
+ declare function isApiKey(value: string | undefined): value is string;
149
+ /**
150
+ * The caller an answer of the control plane describes, in the shape a signed-in user has,
151
+ * so that a route checks a key the way it checks a person. Throws 502 for an answer that
152
+ * does not have the fields a caller needs.
153
+ */
154
+ declare function userFromKeyVerification(answer: unknown): AuthUser;
155
+ /**
156
+ * Checks API keys against the control plane, `POST <PLATFORM_URL>/api-keys/verify`, or
157
+ * with `check` in its place. An answer is kept for its `cache_seconds`, at most a minute,
158
+ * under the key's sha256; a refusal for 5 seconds. Calls for the same key at the same time
159
+ * share one check. A control plane that cannot be reached or fails is a 503 or 502, never
160
+ * a refusal, and nothing is kept.
161
+ */
162
+ declare function createKeyVerifier(options?: KeyVerifierOptions): KeyVerifier;
163
+ /**
164
+ * Lets a route accept an API key as well as a signed-in user's token. Put it in the
165
+ * route's own handlers, where the route is defined:
166
+ *
167
+ * ```ts
168
+ * app.api.get('/reports', acceptApiKey(), requirePermission('bi:report:read'), handler)
169
+ * ```
170
+ *
171
+ * A route without it refuses a key with 401 `api_key_not_accepted`. The MCP endpoint
172
+ * accepts keys without it. The routes that have it are listed in the app's manifest.
173
+ */
174
+ declare function acceptApiKey(): MiddlewareHandler;
175
+ /**
176
+ * Refuses a request made with an API key whose route did not accept it. `authenticate`
177
+ * refuses such a request before any handler runs. This covers what it cannot see: two
178
+ * routes that match one path, where the one that answers has no `acceptApiKey()`.
179
+ * `getUser`, `db` and `callPlatform` call it, so that route can reach neither the caller
180
+ * nor the tenant's data.
181
+ */
182
+ declare function assertApiKeyAccepted(c: Context): void;
183
+ /** A route that accepts API keys, as the manifest lists it. */
184
+ interface ApiKeyRoute {
185
+ /** `GET`, `POST` and so on, or `ALL` for every method. */
186
+ method: string;
187
+ /** The path as it is served: under the app's base, or under `/internal` for another app. */
188
+ path: string;
189
+ }
190
+ /**
191
+ * The routes of a router that have `acceptApiKey()`, with `prefix` put before their
192
+ * paths: `apiKeyRoutes(app.api, '/api')`.
193
+ */
194
+ declare function apiKeyRoutes(router: {
195
+ routes: readonly {
196
+ method: string;
197
+ path: string;
198
+ handler: unknown;
199
+ }[];
200
+ }, prefix: string): ApiKeyRoute[];
201
+ declare module 'hono' {
202
+ interface ContextVariableMap {
203
+ /** Set by `acceptApiKey()`, and by `authenticate` where every route takes a key. */
204
+ apiKeyAccepted: boolean;
205
+ }
206
+ }
207
+
208
+ export { type AuthUser as A, type KeyVerifier as K, MAX_API_KEY_CACHE_SECONDS as M, ORGANIZATION_AUDIENCE_PREFIX as O, type SupportSession as S, type Verifier as V, type ApiKeyKind as a, type ApiKeyRoute as b, API_KEY_PREFIX as c, API_KEY_REFUSAL_SECONDS as d, type ApiKeyInfo as e, type ApiKeyVerification as f, type AuthenticateOptions as g, type KeyVerifierOptions as h, type VerifierOptions as i, acceptApiKey as j, apiKeyRoutes as k, assertApiKeyAccepted as l, authenticate as m, bearerToken as n, createKeyVerifier as o, createVerifier as p, getUser as q, isApiKey as r, requirePermission as s, requireRole as t, supportFromClaims as u, userFromClaims as v, userFromKeyVerification as w, verifierFromEnv as x };
@@ -2,12 +2,17 @@ import {
2
2
  AppError,
3
3
  ForbiddenError,
4
4
  UUID_PATTERN,
5
- UnauthorizedError
6
- } from "./chunk-UWDDQH25.js";
5
+ UnauthorizedError,
6
+ assertApiKeyAccepted,
7
+ createKeyVerifier,
8
+ isApiKey,
9
+ refuseApiKeyUnlessAccepted
10
+ } from "./chunk-UWTSXBJL.js";
7
11
  import {
8
12
  isDevIdentityEnabled,
13
+ resolveDevKeyUser,
9
14
  resolveDevUser
10
- } from "./chunk-NMKEVYGN.js";
15
+ } from "./chunk-SLNRMJDM.js";
11
16
  import {
12
17
  getRequestContext
13
18
  } from "./chunk-ERGI2X5S.js";
@@ -131,10 +136,20 @@ function authenticate(options = {}) {
131
136
  const env = options.env ?? process.env;
132
137
  const dev = isDevIdentityEnabled(env);
133
138
  let verifier = options.verifier;
139
+ let keyVerifier = options.keyVerifier;
134
140
  return async (c, next) => {
135
141
  const token = bearerToken(c.req.header("Authorization"));
136
142
  let user;
137
- if (dev) {
143
+ if (isApiKey(token)) {
144
+ if (options.acceptApiKeys) c.set("apiKeyAccepted", true);
145
+ else refuseApiKeyUnlessAccepted(c);
146
+ if (dev) {
147
+ user = resolveDevKeyUser(token, env);
148
+ } else {
149
+ keyVerifier ??= createKeyVerifier({ env });
150
+ user = await keyVerifier.verify(token);
151
+ }
152
+ } else if (dev) {
138
153
  user = resolveDevUser(token, env);
139
154
  } else {
140
155
  if (!token) throw new UnauthorizedError("missing bearer token");
@@ -156,6 +171,7 @@ function authenticate(options = {}) {
156
171
  function getUser(c) {
157
172
  const user = c.get("user");
158
173
  if (!user) throw new UnauthorizedError();
174
+ assertApiKeyAccepted(c);
159
175
  return user;
160
176
  }
161
177
  function requirePermission(...codes) {
@@ -1,6 +1,7 @@
1
1
  // src/dev.ts
2
2
  var DEFAULT_DEV_TENANT_ID = "0190a000-0000-7000-8000-000000000001";
3
3
  var DEV_TOKEN_PREFIX = "dev.";
4
+ var DEV_API_KEY_PREFIX = "pk_dev.";
4
5
  function isDevIdentityEnabled(env = process.env) {
5
6
  return env.ENV === "dev" && env.NODE_ENV !== "production";
6
7
  }
@@ -49,13 +50,31 @@ function resolveDevUser(token, env = process.env) {
49
50
  ...typeof override.timeZone === "string" ? { timeZone: override.timeZone } : {}
50
51
  };
51
52
  }
53
+ function encodeDevApiKey(user = {}) {
54
+ return DEV_API_KEY_PREFIX + Buffer.from(JSON.stringify(user), "utf8").toString("base64url");
55
+ }
56
+ function resolveDevKeyUser(key, env = process.env) {
57
+ const payload = key.startsWith(DEV_API_KEY_PREFIX) ? `${DEV_TOKEN_PREFIX}${key.slice(DEV_API_KEY_PREFIX.length)}` : void 0;
58
+ const override = decodeDevToken(payload);
59
+ const kind = override?.kind === "tenant" ? "tenant" : "user";
60
+ const user = resolveDevUser(payload, env);
61
+ return {
62
+ ...user,
63
+ // A tenant key acts as the tenant: its subject is the key, as the control plane says.
64
+ ...kind === "tenant" && typeof override?.id !== "string" ? { id: "key:dev" } : {},
65
+ apiKey: { id: "dev", kind }
66
+ };
67
+ }
52
68
 
53
69
  export {
54
70
  DEFAULT_DEV_TENANT_ID,
55
71
  DEV_TOKEN_PREFIX,
72
+ DEV_API_KEY_PREFIX,
56
73
  isDevIdentityEnabled,
57
74
  devIdentity,
58
75
  encodeDevToken,
59
76
  decodeDevToken,
60
- resolveDevUser
77
+ resolveDevUser,
78
+ encodeDevApiKey,
79
+ resolveDevKeyUser
61
80
  };
@@ -0,0 +1,345 @@
1
+ import {
2
+ REQUEST_ID_HEADER,
3
+ getRequestId
4
+ } from "./chunk-ERGI2X5S.js";
5
+
6
+ // src/errors.ts
7
+ import { HTTPException } from "hono/http-exception";
8
+ var AppError = class extends Error {
9
+ code;
10
+ status;
11
+ field;
12
+ constructor(message, options = {}) {
13
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
14
+ this.name = new.target.name;
15
+ this.code = options.code ?? "app_error";
16
+ this.status = options.status ?? 400;
17
+ this.field = options.field;
18
+ }
19
+ };
20
+ var UnauthorizedError = class extends AppError {
21
+ constructor(message = "Authentication required", options = {}) {
22
+ super(message, { code: "unauthorized", status: 401, ...options });
23
+ }
24
+ };
25
+ var ForbiddenError = class extends AppError {
26
+ constructor(message = "Forbidden", options = {}) {
27
+ super(message, { code: "forbidden", status: 403, ...options });
28
+ }
29
+ };
30
+ var NotFoundError = class extends AppError {
31
+ constructor(message = "Not found", options = {}) {
32
+ super(message, { code: "not_found", status: 404, ...options });
33
+ }
34
+ };
35
+ var ConflictError = class extends AppError {
36
+ constructor(message = "Conflict", options = {}) {
37
+ super(message, { code: "conflict", status: 409, ...options });
38
+ }
39
+ };
40
+ var ValidationError = class extends AppError {
41
+ constructor(message, field, options = {}) {
42
+ super(message, { code: "validation_error", status: 422, field, ...options });
43
+ }
44
+ };
45
+ function withTrace(body) {
46
+ const traceId = getRequestId();
47
+ return traceId ? { ...body, trace_id: traceId } : body;
48
+ }
49
+ function toErrorResponse(error) {
50
+ if (error instanceof AppError) {
51
+ const body = { code: error.code, message: error.message };
52
+ if (error.field) body.field = error.field;
53
+ return { status: error.status, body: withTrace(body) };
54
+ }
55
+ if (error instanceof HTTPException) {
56
+ const code = error.status === 404 ? "not_found" : error.status >= 500 ? "internal_error" : "http_error";
57
+ return {
58
+ status: error.status,
59
+ body: withTrace({ code, message: error.message || "Request failed" })
60
+ };
61
+ }
62
+ return {
63
+ status: 500,
64
+ body: withTrace({ code: "internal_error", message: "Internal server error" })
65
+ };
66
+ }
67
+ function respond(c, status, body) {
68
+ if (status === 401) c.header("WWW-Authenticate", "Bearer");
69
+ return c.json(body, status);
70
+ }
71
+ function errorHandler(onUnexpected) {
72
+ return (error, c) => {
73
+ const { status, body } = toErrorResponse(error);
74
+ if (status >= 500) onUnexpected?.(error, c);
75
+ return respond(c, status, body);
76
+ };
77
+ }
78
+ function notFoundHandler() {
79
+ return (c) => respond(c, 404, withTrace({ code: "not_found", message: "Not found" }));
80
+ }
81
+
82
+ // src/ids.ts
83
+ import { randomBytes, randomInt } from "crypto";
84
+ var APP_NAME_PATTERN = /^[a-z][a-z0-9-]{1,30}$/;
85
+ var APP_ID_PATTERN = /^app[a-z0-9]{6}$/;
86
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
87
+ var ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
88
+ function isUuid(value) {
89
+ return typeof value === "string" && UUID_PATTERN.test(value);
90
+ }
91
+ function isValidAppName(value) {
92
+ return typeof value === "string" && APP_NAME_PATTERN.test(value);
93
+ }
94
+ function isValidAppId(value) {
95
+ return typeof value === "string" && APP_ID_PATTERN.test(value);
96
+ }
97
+ function appBasePath(name) {
98
+ return `/apps/${name}/`;
99
+ }
100
+ function assertValidAppId(value) {
101
+ if (!isValidAppId(value)) {
102
+ throw new Error(
103
+ `Invalid app id ${JSON.stringify(value)}. Expected "app" followed by six characters from [a-z0-9].`
104
+ );
105
+ }
106
+ }
107
+ function generateAppId() {
108
+ let id = "app";
109
+ for (let i = 0; i < 6; i += 1) id += ID_ALPHABET[randomInt(ID_ALPHABET.length)];
110
+ return id;
111
+ }
112
+ function uuidv7(now = Date.now()) {
113
+ const bytes = randomBytes(16);
114
+ const time = BigInt(now);
115
+ bytes[0] = Number(time >> 40n & 0xffn);
116
+ bytes[1] = Number(time >> 32n & 0xffn);
117
+ bytes[2] = Number(time >> 24n & 0xffn);
118
+ bytes[3] = Number(time >> 16n & 0xffn);
119
+ bytes[4] = Number(time >> 8n & 0xffn);
120
+ bytes[5] = Number(time & 0xffn);
121
+ bytes[6] = (bytes[6] ?? 0) & 15 | 112;
122
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
123
+ const hex = bytes.toString("hex");
124
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
125
+ }
126
+
127
+ // src/api-keys.ts
128
+ import { createHash } from "crypto";
129
+ import { matchedRoutes } from "hono/route";
130
+ var API_KEY_PREFIX = "pk_";
131
+ var MAX_API_KEY_CACHE_SECONDS = 60;
132
+ var API_KEY_REFUSAL_SECONDS = 5;
133
+ var MAX_CACHED_KEYS = 1e4;
134
+ function isApiKey(value) {
135
+ return typeof value === "string" && value.startsWith(API_KEY_PREFIX);
136
+ }
137
+ function strings(value) {
138
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
139
+ }
140
+ function text(value) {
141
+ return typeof value === "string" && value !== "" ? value : void 0;
142
+ }
143
+ function userFromKeyVerification(answer) {
144
+ const fields = answer && typeof answer === "object" ? answer : {};
145
+ const subject = text(fields.subject);
146
+ const keyId = text(fields.key_id);
147
+ const tenantId = text(fields.tenant_id);
148
+ const kind = fields.kind;
149
+ if (!subject || !keyId || !tenantId || !UUID_PATTERN.test(tenantId) || kind !== "user" && kind !== "tenant") {
150
+ throw new AppError("The control plane answered a key check without a caller", {
151
+ code: "platform_error",
152
+ status: 502
153
+ });
154
+ }
155
+ return {
156
+ id: subject,
157
+ tenantId: tenantId.toLowerCase(),
158
+ tenantSlug: text(fields.tenant_slug) ?? "",
159
+ username: text(fields.username) ?? subject,
160
+ roles: strings(fields.roles),
161
+ permissions: strings(fields.permissions),
162
+ timeZone: text(fields.tenant_time_zone),
163
+ apiKey: { id: keyId, kind }
164
+ };
165
+ }
166
+ function copyUser(user) {
167
+ return {
168
+ ...user,
169
+ roles: [...user.roles],
170
+ permissions: [...user.permissions],
171
+ ...user.apiKey ? { apiKey: { ...user.apiKey } } : {}
172
+ };
173
+ }
174
+ function invalidKey() {
175
+ return new UnauthorizedError("invalid API key", { code: "invalid_key" });
176
+ }
177
+ function cacheSeconds(value) {
178
+ if (typeof value !== "number" || !Number.isFinite(value)) return MAX_API_KEY_CACHE_SECONDS;
179
+ return Math.min(Math.max(value, 0), MAX_API_KEY_CACHE_SECONDS);
180
+ }
181
+ async function askControlPlane(key, options) {
182
+ const env = options.env ?? process.env;
183
+ const base = env.PLATFORM_URL?.replace(/\/+$/, "");
184
+ if (!base) {
185
+ throw new AppError("API keys cannot be checked: set PLATFORM_URL", {
186
+ code: "platform_not_configured",
187
+ status: 503
188
+ });
189
+ }
190
+ const headers = {
191
+ Accept: "application/json",
192
+ "Content-Type": "application/json"
193
+ };
194
+ const requestId = getRequestId();
195
+ if (requestId) headers[REQUEST_ID_HEADER] = requestId;
196
+ let status;
197
+ let answer;
198
+ try {
199
+ const response = await (options.fetch ?? fetch)(`${base}/api-keys/verify`, {
200
+ method: "POST",
201
+ headers,
202
+ body: JSON.stringify({ key }),
203
+ signal: AbortSignal.timeout(options.timeout ?? 5e3)
204
+ });
205
+ status = response.status;
206
+ answer = await response.json().catch(() => void 0);
207
+ } catch (error) {
208
+ throw new AppError("The control plane cannot be reached to check the API key", {
209
+ code: "platform_unavailable",
210
+ status: 503,
211
+ cause: error
212
+ });
213
+ }
214
+ if (status === 401) return void 0;
215
+ if (status < 200 || status >= 300) {
216
+ throw new AppError("The control plane failed to check the API key", {
217
+ code: "platform_error",
218
+ status: 502
219
+ });
220
+ }
221
+ const seconds = cacheSeconds(answer?.cache_seconds);
222
+ return { user: userFromKeyVerification(answer), seconds };
223
+ }
224
+ function createKeyVerifier(options = {}) {
225
+ const kept = /* @__PURE__ */ new Map();
226
+ const pending = /* @__PURE__ */ new Map();
227
+ const keep = (hash, entry) => {
228
+ kept.delete(hash);
229
+ if (kept.size >= MAX_CACHED_KEYS) {
230
+ const now = Date.now();
231
+ for (const [name, value] of kept) if (value.until <= now) kept.delete(name);
232
+ while (kept.size >= MAX_CACHED_KEYS) {
233
+ const oldest = kept.keys().next().value;
234
+ if (oldest === void 0) break;
235
+ kept.delete(oldest);
236
+ }
237
+ }
238
+ if (entry.until > Date.now()) kept.set(hash, entry);
239
+ };
240
+ const check = async (key, hash) => {
241
+ let entry;
242
+ if (options.check) {
243
+ const answer = await options.check(key);
244
+ entry = answer ? {
245
+ user: userFromKeyVerification(answer),
246
+ until: Date.now() + cacheSeconds(answer.cache_seconds) * 1e3
247
+ } : { until: Date.now() + API_KEY_REFUSAL_SECONDS * 1e3 };
248
+ } else {
249
+ const answer = await askControlPlane(key, options);
250
+ entry = answer ? { user: answer.user, until: Date.now() + answer.seconds * 1e3 } : { until: Date.now() + API_KEY_REFUSAL_SECONDS * 1e3 };
251
+ }
252
+ keep(hash, entry);
253
+ return entry;
254
+ };
255
+ return {
256
+ async verify(key) {
257
+ if (!isApiKey(key)) throw invalidKey();
258
+ const hash = createHash("sha256").update(key).digest("base64url");
259
+ let entry = kept.get(hash);
260
+ if (!entry || entry.until <= Date.now()) {
261
+ let running = pending.get(hash);
262
+ if (!running) {
263
+ running = check(key, hash).finally(() => pending.delete(hash));
264
+ pending.set(hash, running);
265
+ }
266
+ entry = await running;
267
+ }
268
+ if (!entry.user) throw invalidKey();
269
+ return copyUser(entry.user);
270
+ }
271
+ };
272
+ }
273
+ var ACCEPTS_API_KEY = /* @__PURE__ */ Symbol.for("zjazj.platform.acceptsApiKey");
274
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
275
+ function isApiKeyMarker(handler) {
276
+ let current = handler;
277
+ for (let depth = 0; typeof current === "function" && depth < 10; depth += 1) {
278
+ if (current[ACCEPTS_API_KEY] === true) return true;
279
+ current = current[COMPOSED_HANDLER];
280
+ }
281
+ return false;
282
+ }
283
+ function acceptApiKey() {
284
+ const handler = async (c, next) => {
285
+ c.set("apiKeyAccepted", true);
286
+ await next();
287
+ };
288
+ Object.defineProperty(handler, ACCEPTS_API_KEY, { value: true });
289
+ return handler;
290
+ }
291
+ function routeAcceptsApiKey(c) {
292
+ return matchedRoutes(c).some((route) => isApiKeyMarker(route.handler));
293
+ }
294
+ function notAccepted() {
295
+ return new UnauthorizedError("this route does not accept an API key", {
296
+ code: "api_key_not_accepted"
297
+ });
298
+ }
299
+ function assertApiKeyAccepted(c) {
300
+ if (c.get("user")?.apiKey && !c.get("apiKeyAccepted")) throw notAccepted();
301
+ }
302
+ function refuseApiKeyUnlessAccepted(c) {
303
+ if (!routeAcceptsApiKey(c)) throw notAccepted();
304
+ }
305
+ function apiKeyRoutes(router, prefix) {
306
+ const found = /* @__PURE__ */ new Map();
307
+ for (const route of router.routes) {
308
+ if (!isApiKeyMarker(route.handler)) continue;
309
+ const path = `${prefix.replace(/\/+$/, "")}${route.path === "/" ? "" : route.path}` || "/";
310
+ found.set(`${route.method} ${path}`, { method: route.method, path });
311
+ }
312
+ return [...found.values()];
313
+ }
314
+
315
+ export {
316
+ AppError,
317
+ UnauthorizedError,
318
+ ForbiddenError,
319
+ NotFoundError,
320
+ ConflictError,
321
+ ValidationError,
322
+ toErrorResponse,
323
+ errorHandler,
324
+ notFoundHandler,
325
+ APP_NAME_PATTERN,
326
+ APP_ID_PATTERN,
327
+ UUID_PATTERN,
328
+ isUuid,
329
+ isValidAppName,
330
+ isValidAppId,
331
+ appBasePath,
332
+ assertValidAppId,
333
+ generateAppId,
334
+ uuidv7,
335
+ API_KEY_PREFIX,
336
+ MAX_API_KEY_CACHE_SECONDS,
337
+ API_KEY_REFUSAL_SECONDS,
338
+ isApiKey,
339
+ userFromKeyVerification,
340
+ createKeyVerifier,
341
+ acceptApiKey,
342
+ assertApiKeyAccepted,
343
+ refuseApiKeyUnlessAccepted,
344
+ apiKeyRoutes
345
+ };
@@ -24,6 +24,7 @@ function build() {
24
24
  if (context.user) {
25
25
  fields.tenant_id = context.user.tenantId;
26
26
  fields.user_id = context.user.id;
27
+ if (context.user.apiKey) fields.api_key_id = context.user.apiKey.id;
27
28
  }
28
29
  return fields;
29
30
  },
package/dist/db.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import {
2
2
  AppError,
3
3
  UUID_PATTERN,
4
+ assertApiKeyAccepted,
4
5
  assertValidAppId,
5
6
  uuidv7
6
- } from "./chunk-UWDDQH25.js";
7
+ } from "./chunk-UWTSXBJL.js";
7
8
  import "./chunk-ERGI2X5S.js";
8
9
 
9
10
  // src/db.ts
@@ -229,6 +230,7 @@ function tenantDatabase(getDatabase) {
229
230
  };
230
231
  }
231
232
  function db(c) {
233
+ assertApiKeyAccepted(c);
232
234
  const handle = c.get("db");
233
235
  if (!handle) {
234
236
  throw new AppError(