@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.
package/dist/dev.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as AuthUser } from './auth-Ckmm4C6y.js';
1
+ import { A as AuthUser, a as ApiKeyKind } from './api-keys-R2145cd9.js';
2
2
  import 'hono';
3
3
  import 'jose';
4
4
 
@@ -7,6 +7,8 @@ type Env = Record<string, string | undefined>;
7
7
  declare const DEFAULT_DEV_TENANT_ID = "0190a000-0000-7000-8000-000000000001";
8
8
  /** Dev tokens are not signed. They are accepted only while the dev identity is enabled. */
9
9
  declare const DEV_TOKEN_PREFIX = "dev.";
10
+ /** An API key of the dev identity. Like a dev token, it is read only in development. */
11
+ declare const DEV_API_KEY_PREFIX = "pk_dev.";
10
12
  /**
11
13
  * The dev identity is on only when `ENV` is exactly `dev` and the process is not running in
12
14
  * production. The comparison is case sensitive on purpose, so a typo in a deployment can
@@ -27,5 +29,19 @@ declare function decodeDevToken(token: string | undefined): DevTokenPayload | un
27
29
  * lets the browser switch tenant or permissions without restarting the server.
28
30
  */
29
31
  declare function resolveDevUser(token: string | undefined, env?: Env): AuthUser;
32
+ type DevApiKeyPayload = DevTokenPayload & {
33
+ kind?: ApiKeyKind;
34
+ };
35
+ /**
36
+ * An API key for tests and local development. It is read like a dev token, but the request
37
+ * is made with a key: only a route that accepts keys takes it. `kind` defaults to `user`.
38
+ */
39
+ declare function encodeDevApiKey(user?: DevApiKeyPayload): string;
40
+ /**
41
+ * The dev user for a request made with an API key. A dev key may replace parts of the
42
+ * identity as a dev token does. Any other key is the dev identity as it is. No key is
43
+ * checked: in development nothing asks the control plane.
44
+ */
45
+ declare function resolveDevKeyUser(key: string, env?: Env): AuthUser;
30
46
 
31
- export { DEFAULT_DEV_TENANT_ID, DEV_TOKEN_PREFIX, decodeDevToken, devIdentity, encodeDevToken, isDevIdentityEnabled, resolveDevUser };
47
+ export { DEFAULT_DEV_TENANT_ID, DEV_API_KEY_PREFIX, DEV_TOKEN_PREFIX, decodeDevToken, devIdentity, encodeDevApiKey, encodeDevToken, isDevIdentityEnabled, resolveDevKeyUser, resolveDevUser };
package/dist/dev.js CHANGED
@@ -1,18 +1,24 @@
1
1
  import {
2
2
  DEFAULT_DEV_TENANT_ID,
3
+ DEV_API_KEY_PREFIX,
3
4
  DEV_TOKEN_PREFIX,
4
5
  decodeDevToken,
5
6
  devIdentity,
7
+ encodeDevApiKey,
6
8
  encodeDevToken,
7
9
  isDevIdentityEnabled,
10
+ resolveDevKeyUser,
8
11
  resolveDevUser
9
- } from "./chunk-NMKEVYGN.js";
12
+ } from "./chunk-SLNRMJDM.js";
10
13
  export {
11
14
  DEFAULT_DEV_TENANT_ID,
15
+ DEV_API_KEY_PREFIX,
12
16
  DEV_TOKEN_PREFIX,
13
17
  decodeDevToken,
14
18
  devIdentity,
19
+ encodeDevApiKey,
15
20
  encodeDevToken,
16
21
  isDevIdentityEnabled,
22
+ resolveDevKeyUser,
17
23
  resolveDevUser
18
24
  };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
+ import { b as ApiKeyRoute, V as Verifier, K as KeyVerifier, A as AuthUser } from './api-keys-R2145cd9.js';
2
+ export { c as API_KEY_PREFIX, d as API_KEY_REFUSAL_SECONDS, e as ApiKeyInfo, a as ApiKeyKind, f as ApiKeyVerification, g as AuthenticateOptions, h as KeyVerifierOptions, M as MAX_API_KEY_CACHE_SECONDS, O as ORGANIZATION_AUDIENCE_PREFIX, S as SupportSession, i as VerifierOptions, j as acceptApiKey, k as apiKeyRoutes, l as assertApiKeyAccepted, m as authenticate, n as bearerToken, o as createKeyVerifier, p as createVerifier, q as getUser, r as isApiKey, s as requirePermission, t as requireRole, u as supportFromClaims, v as userFromClaims, w as userFromKeyVerification, x as verifierFromEnv } from './api-keys-R2145cd9.js';
1
3
  import { Context, Hono, ErrorHandler, NotFoundHandler, MiddlewareHandler } from 'hono';
2
- import { V as Verifier, A as AuthUser } from './auth-Ckmm4C6y.js';
3
- export { a as AuthenticateOptions, O as ORGANIZATION_AUDIENCE_PREFIX, S as SupportSession, b as VerifierOptions, c as authenticate, d as bearerToken, e as createVerifier, g as getUser, r as requirePermission, f as requireRole, s as supportFromClaims, u as userFromClaims, v as verifierFromEnv } from './auth-Ckmm4C6y.js';
4
4
  import { D as Database } from './db-Dp7BB3Kc.js';
5
5
  export { A as APP_ID_PATTERN, a as APP_NAME_PATTERN, b as appBasePath, g as generateAppId, i as isUuid, c as isValidAppId, d as isValidAppName, u as uuidv7 } from './db-Dp7BB3Kc.js';
6
6
  import { StandardSchemaWithJSON } from '@modelcontextprotocol/server';
@@ -28,22 +28,25 @@ declare function definePermissions<const T extends readonly PermissionDefinition
28
28
  /** What a tool name may be: lower case, digits and underscores, at most 41 characters. */
29
29
  declare const TOOL_NAME_PATTERN: RegExp;
30
30
  /**
31
- * What a tool does to data, for the people who choose whether an agent may call it on its
32
- * own. A tool that only reads says so. Any other tool says whether it can destroy data.
31
+ * What a tool does, for the people who choose whether an agent may call it on its own. A
32
+ * tool that only reads says so. Any other tool says whether it can destroy data. Every tool
33
+ * says whether it reaches outside the platform: MCP takes a tool that does not say as one
34
+ * that does, and there is no default here, as a tool that reaches outside and forgets to
35
+ * say so would be the dangerous mistake (`docs/mcp-plan.md`, section 7).
33
36
  */
34
37
  type ToolAnnotations = {
35
38
  readOnlyHint: true;
36
39
  idempotentHint?: boolean;
37
- /** True when the tool reaches a system outside the platform. */
38
- openWorldHint?: boolean;
40
+ /** True when the tool calls a system outside the platform, such as an outside API. */
41
+ openWorldHint: boolean;
39
42
  } | {
40
43
  readOnlyHint: false;
41
44
  /** True when the tool can delete or overwrite data, false when it only adds. */
42
45
  destructiveHint: boolean;
43
46
  /** True when calling it twice with the same input does no more than once. */
44
47
  idempotentHint?: boolean;
45
- /** True when the tool reaches a system outside the platform. */
46
- openWorldHint?: boolean;
48
+ /** True when the tool calls a system outside the platform, such as an outside API. */
49
+ openWorldHint: boolean;
47
50
  };
48
51
  /**
49
52
  * A schema for a tool's input or output: a Standard Schema that also gives its JSON Schema,
@@ -138,6 +141,12 @@ interface PlatformManifest {
138
141
  * plane's screens. The gateway reads the tools from the endpoint, not from here.
139
142
  */
140
143
  tools: ToolManifestEntry[];
144
+ /**
145
+ * The routes that accept an API key as well as a token, for screens and documentation.
146
+ * Paths are under the app's base, except those under `/internal`. The MCP endpoint is
147
+ * one when the app has tools.
148
+ */
149
+ api_key_routes: ApiKeyRoute[];
141
150
  release_version: string | null;
142
151
  source_commit: string | null;
143
152
  }
@@ -145,6 +154,8 @@ interface PlatformManifestOptions {
145
154
  manifest: AppManifest;
146
155
  permissions?: readonly PermissionDefinition[];
147
156
  tools?: readonly ToolDefinition[];
157
+ /** The routes that accept API keys. `PlatformApp.platformManifest()` fills it in. */
158
+ apiKeyRoutes?: readonly ApiKeyRoute[];
148
159
  /** Read for `GIT_SHA`. Defaults to `process.env`. */
149
160
  env?: Env$3;
150
161
  }
@@ -178,6 +189,11 @@ interface CreateAppOptions {
178
189
  tools?: readonly ToolDefinition[];
179
190
  /** Token verifier. Defaults to one built from `LOGTO_*`. */
180
191
  verifier?: Verifier;
192
+ /**
193
+ * API key verifier. Defaults to one that asks the control plane at `PLATFORM_URL`. The
194
+ * control plane passes `createKeyVerifier({ check })` to check keys itself.
195
+ */
196
+ keyVerifier?: KeyVerifier;
181
197
  env?: Env$2;
182
198
  /** What the built-in routes call the control plane with. Defaults to `fetch`. For tests. */
183
199
  fetch?: typeof fetch;
@@ -207,6 +223,11 @@ interface PlatformApp {
207
223
  fetch: (request: Request, ...rest: unknown[]) => Response | Promise<Response>;
208
224
  /** The app's database. Opens it and runs migrations on first use. */
209
225
  database(): Promise<Database>;
226
+ /**
227
+ * What `/internal/_platform/manifest` answers, with the routes that accept API keys as
228
+ * they are now. The control plane records its own catalog with it.
229
+ */
230
+ platformManifest(): PlatformManifest;
210
231
  /** Migrate and listen. Call it from the production entry. */
211
232
  start(): Promise<RunningApp>;
212
233
  }
@@ -484,4 +505,4 @@ interface UrlGuardOptions {
484
505
  */
485
506
  declare function assertPublicUrl(input: string | URL, options?: UrlGuardOptions): Promise<URL>;
486
507
 
487
- export { AppError, type AppErrorOptions, type AppManifest, AuthUser, ConflictError, type CreateAppOptions, DEFAULT_PAGE_SIZE, type ErrorBody, ForbiddenError, MAX_PAGE_SIZE, MIN_SECRET_KEY_LENGTH, NotFoundError, type OAuthAuthorization, type OAuthClient, type OAuthClientOptions, type OAuthDiscovery, OAuthError, type OAuthRequestOptions, type OAuthServerMetadata, type OAuthTokens, type Page, type PageParams, type PermissionDefinition, type PlatformApp, type PlatformCall, type PlatformCallOptions, type PlatformManifest, type PlatformManifestOptions, REQUEST_ID_HEADER, type RequestContext, type RunningApp, type SecretBox, type SecretBoxOptions, TOOL_NAME_PATTERN, type ToolAnnotations, type ToolDefinition, type ToolInput, type ToolManifestEntry, type ToolSchema, type ToolSet, UnauthorizedError, UnsafeUrlError, type UrlGuardOptions, ValidationError, Verifier, assertPublicUrl, callPlatform, coerceRequestId, createApp, createOAuthClient, createSecretBox, definePermissions, defineTools, discoverOAuth, errorHandler, getRequestContext, getRequestId, hasPermissions, isReservedAddress, isToolSet, notFoundHandler, pageOf, parsePage, permissionMatches, platformManifest, requestContext, toErrorResponse, toolManifest, toolProblems };
508
+ export { ApiKeyRoute, AppError, type AppErrorOptions, type AppManifest, AuthUser, ConflictError, type CreateAppOptions, DEFAULT_PAGE_SIZE, type ErrorBody, ForbiddenError, KeyVerifier, MAX_PAGE_SIZE, MIN_SECRET_KEY_LENGTH, NotFoundError, type OAuthAuthorization, type OAuthClient, type OAuthClientOptions, type OAuthDiscovery, OAuthError, type OAuthRequestOptions, type OAuthServerMetadata, type OAuthTokens, type Page, type PageParams, type PermissionDefinition, type PlatformApp, type PlatformCall, type PlatformCallOptions, type PlatformManifest, type PlatformManifestOptions, REQUEST_ID_HEADER, type RequestContext, type RunningApp, type SecretBox, type SecretBoxOptions, TOOL_NAME_PATTERN, type ToolAnnotations, type ToolDefinition, type ToolInput, type ToolManifestEntry, type ToolSchema, type ToolSet, UnauthorizedError, UnsafeUrlError, type UrlGuardOptions, ValidationError, Verifier, assertPublicUrl, callPlatform, coerceRequestId, createApp, createOAuthClient, createSecretBox, definePermissions, defineTools, discoverOAuth, errorHandler, getRequestContext, getRequestId, hasPermissions, isReservedAddress, isToolSet, notFoundHandler, pageOf, parsePage, permissionMatches, platformManifest, requestContext, toErrorResponse, toolManifest, toolProblems };
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  configureLog,
3
3
  log,
4
4
  requestLogger
5
- } from "./chunk-26AAYRI3.js";
5
+ } from "./chunk-VJRJ53T2.js";
6
6
  import {
7
7
  ORGANIZATION_AUDIENCE_PREFIX,
8
8
  authenticate,
@@ -17,30 +17,39 @@ import {
17
17
  supportFromClaims,
18
18
  userFromClaims,
19
19
  verifierFromEnv
20
- } from "./chunk-EIZ24ILA.js";
20
+ } from "./chunk-44UTXMKV.js";
21
21
  import {
22
+ API_KEY_PREFIX,
23
+ API_KEY_REFUSAL_SECONDS,
22
24
  APP_ID_PATTERN,
23
25
  APP_NAME_PATTERN,
24
26
  AppError,
25
27
  ConflictError,
26
28
  ForbiddenError,
29
+ MAX_API_KEY_CACHE_SECONDS,
27
30
  NotFoundError,
28
31
  UnauthorizedError,
29
32
  ValidationError,
33
+ acceptApiKey,
34
+ apiKeyRoutes,
30
35
  appBasePath,
36
+ assertApiKeyAccepted,
31
37
  assertValidAppId,
38
+ createKeyVerifier,
32
39
  errorHandler,
33
40
  generateAppId,
41
+ isApiKey,
34
42
  isUuid,
35
43
  isValidAppId,
36
44
  isValidAppName,
37
45
  notFoundHandler,
38
46
  toErrorResponse,
47
+ userFromKeyVerification,
39
48
  uuidv7
40
- } from "./chunk-UWDDQH25.js";
49
+ } from "./chunk-UWTSXBJL.js";
41
50
  import {
42
51
  isDevIdentityEnabled
43
- } from "./chunk-NMKEVYGN.js";
52
+ } from "./chunk-SLNRMJDM.js";
44
53
  import {
45
54
  REQUEST_ID_HEADER,
46
55
  coerceRequestId,
@@ -93,6 +102,11 @@ function toolProblems(tools) {
93
102
  `${label}: a tool that changes data must say destructiveHint, true when it can delete or overwrite data.`
94
103
  );
95
104
  }
105
+ if (annotations && typeof annotations.openWorldHint !== "boolean") {
106
+ problems.push(
107
+ `${label}: the annotations must say openWorldHint, true when the tool calls a system outside the platform and false otherwise.`
108
+ );
109
+ }
96
110
  const input = tool?.input;
97
111
  if (!input || typeof input !== "object" || !("~standard" in input)) {
98
112
  problems.push(`${label}: the input must be a schema, such as z.object({ ... }).`);
@@ -139,6 +153,7 @@ function platformManifest(options) {
139
153
  description: permission.description ?? null
140
154
  })),
141
155
  tools: toolManifest(options.tools ?? []),
156
+ api_key_routes: (options.apiKeyRoutes ?? []).map((route) => ({ ...route })),
142
157
  release_version: manifest.version ?? null,
143
158
  source_commit: env.GIT_SHA || null
144
159
  };
@@ -160,6 +175,7 @@ function errorBody(value) {
160
175
  return { code, message, field: typeof field === "string" ? field : void 0 };
161
176
  }
162
177
  async function callPlatform(c, path2, call = {}, options = {}) {
178
+ assertApiKeyAccepted(c);
163
179
  const env = options.env ?? process.env;
164
180
  const base = env.PLATFORM_URL?.replace(/\/+$/, "");
165
181
  if (!base) {
@@ -294,9 +310,11 @@ function createApp(options) {
294
310
  }
295
311
  return pending;
296
312
  };
313
+ const keyVerifier = options.keyVerifier ?? createKeyVerifier({ env, fetch: options.fetch });
314
+ const credentials = { verifier: options.verifier, keyVerifier, env };
297
315
  const forUsers = () => {
298
316
  const router = new Hono();
299
- router.use("*", authenticate({ verifier: options.verifier, env }));
317
+ router.use("*", authenticate(credentials));
300
318
  if (databaseOptions) {
301
319
  router.use("*", async (c, next) => {
302
320
  const { tenantDatabase } = await import("./db.js");
@@ -310,7 +328,7 @@ function createApp(options) {
310
328
  const publicApi = new Hono();
311
329
  const internal = new Hono();
312
330
  const platformRoutes = new Hono();
313
- platformRoutes.use("*", authenticate({ verifier: options.verifier, env }));
331
+ platformRoutes.use("*", authenticate(credentials));
314
332
  const toPlatform = { env, fetch: options.fetch };
315
333
  platformRoutes.get("/tenants", async (c) => {
316
334
  const { q, page, page_size: pageSize } = c.req.query();
@@ -345,10 +363,7 @@ function createApp(options) {
345
363
  root.notFound(notFoundHandler());
346
364
  root.get("/healthz", (c) => c.json({ status: "ok", app: manifest.name }));
347
365
  root.use("/internal/*", internalCallersOnly);
348
- root.get(
349
- "/internal/_platform/manifest",
350
- (c) => c.json(platformManifest({ manifest, permissions: options.permissions, tools, env }))
351
- );
366
+ root.get("/internal/_platform/manifest", (c) => c.json(manifestNow()));
352
367
  root.all("/internal/_platform/*", (c) => c.notFound());
353
368
  root.route("/internal/delegated", delegated);
354
369
  root.all("/internal/delegated/*", (c) => c.notFound());
@@ -370,11 +385,11 @@ function createApp(options) {
370
385
  scoped.all("/api/*", (c) => c.notFound());
371
386
  if (tools.length > 0) {
372
387
  const mcp = new Hono();
373
- mcp.use("*", authenticate({ verifier: options.verifier, env }));
388
+ mcp.use("*", authenticate({ ...credentials, acceptApiKeys: true }));
374
389
  let route;
375
390
  mcp.all("/", async (c) => {
376
391
  if (!route) {
377
- const { createMcpRoute } = await import("./mcp-UM4G354G.js");
392
+ const { createMcpRoute } = await import("./mcp-4RD7G65J.js");
378
393
  route ??= createMcpRoute({
379
394
  manifest,
380
395
  tools,
@@ -406,6 +421,17 @@ function createApp(options) {
406
421
  root.route(basePath || "/", scoped);
407
422
  return root;
408
423
  };
424
+ const manifestNow = () => platformManifest({
425
+ manifest,
426
+ permissions: options.permissions,
427
+ tools,
428
+ apiKeyRoutes: [
429
+ ...tools.length > 0 ? [{ method: "POST", path: "/mcp" }] : [],
430
+ ...apiKeyRoutes(api, "/api"),
431
+ ...apiKeyRoutes(delegated, "/internal/delegated")
432
+ ],
433
+ env
434
+ });
409
435
  const fetchHandler = (request, ...rest) => {
410
436
  built ??= build();
411
437
  return built.fetch(request, ...rest);
@@ -419,6 +445,7 @@ function createApp(options) {
419
445
  delegated,
420
446
  fetch: fetchHandler,
421
447
  database: getDatabase,
448
+ platformManifest: manifestNow,
422
449
  async start() {
423
450
  const port = Number(env.PORT ?? 8080);
424
451
  if (!Number.isInteger(port) || port <= 0) throw new Error(`Invalid PORT: ${env.PORT}`);
@@ -808,12 +835,15 @@ async function assertPublicUrl(input, options = {}) {
808
835
  return url;
809
836
  }
810
837
  export {
838
+ API_KEY_PREFIX,
839
+ API_KEY_REFUSAL_SECONDS,
811
840
  APP_ID_PATTERN,
812
841
  APP_NAME_PATTERN,
813
842
  AppError,
814
843
  ConflictError,
815
844
  DEFAULT_PAGE_SIZE,
816
845
  ForbiddenError,
846
+ MAX_API_KEY_CACHE_SECONDS,
817
847
  MAX_PAGE_SIZE,
818
848
  MIN_SECRET_KEY_LENGTH,
819
849
  NotFoundError,
@@ -824,13 +854,17 @@ export {
824
854
  UnauthorizedError,
825
855
  UnsafeUrlError,
826
856
  ValidationError,
857
+ acceptApiKey,
858
+ apiKeyRoutes,
827
859
  appBasePath,
860
+ assertApiKeyAccepted,
828
861
  assertPublicUrl,
829
862
  authenticate,
830
863
  bearerToken,
831
864
  callPlatform,
832
865
  coerceRequestId,
833
866
  createApp,
867
+ createKeyVerifier,
834
868
  createOAuthClient,
835
869
  createSecretBox,
836
870
  createVerifier,
@@ -843,6 +877,7 @@ export {
843
877
  getRequestId,
844
878
  getUser,
845
879
  hasPermissions,
880
+ isApiKey,
846
881
  isReservedAddress,
847
882
  isToolSet,
848
883
  isUuid,
@@ -861,6 +896,7 @@ export {
861
896
  toolManifest,
862
897
  toolProblems,
863
898
  userFromClaims,
899
+ userFromKeyVerification,
864
900
  uuidv7,
865
901
  verifierFromEnv
866
902
  };
package/dist/log.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  configureLog,
4
4
  log,
5
5
  requestLogger
6
- } from "./chunk-26AAYRI3.js";
6
+ } from "./chunk-VJRJ53T2.js";
7
7
  import "./chunk-ERGI2X5S.js";
8
8
  export {
9
9
  audit,
@@ -1,15 +1,15 @@
1
1
  import {
2
2
  log
3
- } from "./chunk-26AAYRI3.js";
3
+ } from "./chunk-VJRJ53T2.js";
4
4
  import {
5
5
  bearerToken,
6
6
  getUser,
7
7
  hasPermissions
8
- } from "./chunk-EIZ24ILA.js";
8
+ } from "./chunk-44UTXMKV.js";
9
9
  import {
10
10
  AppError
11
- } from "./chunk-UWDDQH25.js";
12
- import "./chunk-NMKEVYGN.js";
11
+ } from "./chunk-UWTSXBJL.js";
12
+ import "./chunk-SLNRMJDM.js";
13
13
  import {
14
14
  getRequestId
15
15
  } from "./chunk-ERGI2X5S.js";
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { V as Verifier } from './auth-Ckmm4C6y.js';
1
+ import { V as Verifier, f as ApiKeyVerification, K as KeyVerifier } from './api-keys-R2145cd9.js';
2
2
  import 'hono';
3
3
  import 'jose';
4
4
 
@@ -22,16 +22,32 @@ declare const TEST_TENANT_ID = "0190a000-0000-7000-8000-0000000000a1";
22
22
  * network call.
23
23
  */
24
24
  declare function createTestIssuer(issuer?: string): Promise<TestIssuer>;
25
+ /**
26
+ * A key verifier that knows only the keys given, for tests that run without the dev
27
+ * identity: pass it to `createApp({ keyVerifier })` and call with `Bearer <key>`. Each key
28
+ * starts with `pk_` and maps to the parts of the control plane's answer that differ from
29
+ * a user key of `TEST_TENANT_ID` with no roles and no permissions. Any other key is
30
+ * refused with 401 `invalid_key`. Nothing is kept, so each request asks again.
31
+ *
32
+ * ```ts
33
+ * const keyVerifier = createTestKeyVerifier({
34
+ * pk_test_reader: { permissions: ['stock:item:read'] },
35
+ * pk_test_tenant: { kind: 'tenant', roles: ['sync'], permissions: ['stock:item:write'] },
36
+ * })
37
+ * ```
38
+ */
39
+ declare function createTestKeyVerifier(keys: Record<string, Partial<ApiKeyVerification>>): KeyVerifier;
25
40
  /** The MCP revision `mcpRequest` speaks. */
26
41
  declare const MCP_PROTOCOL_VERSION = "2026-07-28";
27
42
  /**
28
43
  * One request to an app's MCP endpoint, as a client of MCP 2026-07-28 sends it: the
29
44
  * method and its name in headers, the revision and the client's capabilities in `_meta`.
30
- * Pass the token in `headers`. Read the answer with `await response.json()`: `result` or
31
- * `error`.
45
+ * `token` is sent as `Authorization: Bearer`: a token, a dev token or an API key, as an
46
+ * agent sends its key. Read the answer with `await response.json()`: `result` or `error`.
32
47
  */
33
48
  declare function mcpRequest(url: string, method: string, params?: Record<string, unknown>, init?: {
49
+ token?: string;
34
50
  headers?: Record<string, string>;
35
51
  }): Request;
36
52
 
37
- export { MCP_PROTOCOL_VERSION, type SignOptions, TEST_TENANT_ID, type TestIssuer, createTestIssuer, mcpRequest };
53
+ export { MCP_PROTOCOL_VERSION, type SignOptions, TEST_TENANT_ID, type TestIssuer, createTestIssuer, createTestKeyVerifier, mcpRequest };
package/dist/testing.js CHANGED
@@ -1,8 +1,11 @@
1
1
  import {
2
2
  createVerifier
3
- } from "./chunk-EIZ24ILA.js";
4
- import "./chunk-UWDDQH25.js";
5
- import "./chunk-NMKEVYGN.js";
3
+ } from "./chunk-44UTXMKV.js";
4
+ import {
5
+ createKeyVerifier,
6
+ isApiKey
7
+ } from "./chunk-UWTSXBJL.js";
8
+ import "./chunk-SLNRMJDM.js";
6
9
  import "./chunk-ERGI2X5S.js";
7
10
 
8
11
  // src/testing.ts
@@ -35,6 +38,31 @@ async function createTestIssuer(issuer = "https://auth.test/oidc") {
35
38
  }
36
39
  };
37
40
  }
41
+ function createTestKeyVerifier(keys) {
42
+ for (const key of Object.keys(keys)) {
43
+ if (!isApiKey(key)) throw new Error(`createTestKeyVerifier: ${key} does not start with pk_`);
44
+ }
45
+ return createKeyVerifier({
46
+ async check(key) {
47
+ const given = Object.hasOwn(keys, key) ? keys[key] : void 0;
48
+ if (!given) return void 0;
49
+ const kind = given.kind ?? "user";
50
+ const keyId = given.key_id ?? `key-${key.slice(3)}`;
51
+ return {
52
+ subject: kind === "tenant" ? `key:${keyId}` : "user-test",
53
+ key_id: keyId,
54
+ tenant_id: TEST_TENANT_ID,
55
+ tenant_slug: "org-test",
56
+ username: kind === "tenant" ? keyId : "user-test",
57
+ roles: [],
58
+ permissions: [],
59
+ ...given,
60
+ kind,
61
+ cache_seconds: 0
62
+ };
63
+ }
64
+ });
65
+ }
38
66
  var MCP_PROTOCOL_VERSION = "2026-07-28";
39
67
  function mcpRequest(url, method, params = {}, init = {}) {
40
68
  const named = params.name ?? params.uri;
@@ -46,6 +74,7 @@ function mcpRequest(url, method, params = {}, init = {}) {
46
74
  "MCP-Protocol-Version": MCP_PROTOCOL_VERSION,
47
75
  "Mcp-Method": method,
48
76
  ...typeof named === "string" ? { "Mcp-Name": named } : {},
77
+ ...init.token ? { Authorization: `Bearer ${init.token}` } : {},
49
78
  ...init.headers
50
79
  },
51
80
  body: JSON.stringify({
@@ -67,5 +96,6 @@ export {
67
96
  MCP_PROTOCOL_VERSION,
68
97
  TEST_TENANT_ID,
69
98
  createTestIssuer,
99
+ createTestKeyVerifier,
70
100
  mcpRequest
71
101
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zjazj/server",
3
- "version": "0.0.8",
3
+ "version": "0.0.9",
4
4
  "description": "Backend runtime for platform apps: auth, logging, tenant-safe database access and app assembly on Hono.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -1,81 +0,0 @@
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
- /** True only for the local dev identity. */
22
- isDev?: boolean;
23
- }
24
- /** A platform operator's time in a customer's tenant, as the token states it. */
25
- interface SupportSession {
26
- until: number;
27
- /** `support` today. */
28
- mode: string;
29
- }
30
- /**
31
- * The support session a token states, from `support_until` and `support_mode`. Both or
32
- * nothing: half of it is not a session. Mirrored in `@zjazj/web`.
33
- */
34
- declare function supportFromClaims(claims: Record<string, unknown>): SupportSession | undefined;
35
- /** Organization tokens carry this audience prefix followed by the organization id. */
36
- declare const ORGANIZATION_AUDIENCE_PREFIX = "urn:logto:organization:";
37
- type VerifyKey = Parameters<typeof jwtVerify>[1];
38
- interface VerifierOptions {
39
- /** The token issuer, for example `https://auth.example.com/oidc`. */
40
- issuer: string;
41
- /** A fixed audience. Leave unset to accept organization tokens. */
42
- audience?: string;
43
- /** Defaults to `<issuer>/jwks`. */
44
- jwksUri?: string;
45
- /** A key or key resolver, used instead of fetching the JWKS. Meant for tests. */
46
- key?: VerifyKey;
47
- algorithms?: string[];
48
- }
49
- interface Verifier {
50
- verify(token: string): Promise<AuthUser>;
51
- }
52
- /** Project verified token claims into an `AuthUser`. */
53
- declare function userFromClaims(claims: JWTPayload): AuthUser;
54
- /** Build a verifier for tokens issued by the platform's identity provider. */
55
- declare function createVerifier(options: VerifierOptions): Verifier;
56
- type Env = Record<string, string | undefined>;
57
- /** Build the verifier from `LOGTO_ISSUER`, `LOGTO_AUDIENCE` and `LOGTO_JWKS_URI`. */
58
- declare function verifierFromEnv(env?: Env): Verifier | undefined;
59
- declare function bearerToken(header: string | undefined): string | undefined;
60
- interface AuthenticateOptions {
61
- verifier?: Verifier;
62
- env?: Env;
63
- }
64
- /**
65
- * Require an authenticated caller. On success the user is available through `getUser(c)`.
66
- * With the dev identity enabled no token is verified and every request is the dev user.
67
- */
68
- declare function authenticate(options?: AuthenticateOptions): MiddlewareHandler;
69
- /** The authenticated user of this request. Throws 401 when the route is not authenticated. */
70
- declare function getUser(c: Context): AuthUser;
71
- /** Require every listed permission. Wildcards in the granted set count. */
72
- declare function requirePermission(...codes: string[]): MiddlewareHandler;
73
- /** Require at least one of the listed roles. */
74
- declare function requireRole(...roles: string[]): MiddlewareHandler;
75
- declare module 'hono' {
76
- interface ContextVariableMap {
77
- user: AuthUser;
78
- }
79
- }
80
-
81
- export { type AuthUser as A, ORGANIZATION_AUDIENCE_PREFIX as O, type SupportSession as S, type Verifier as V, type AuthenticateOptions as a, type VerifierOptions as b, authenticate as c, bearerToken as d, createVerifier as e, requireRole as f, getUser as g, requirePermission as r, supportFromClaims as s, userFromClaims as u, verifierFromEnv as v };