@zjazj/server 0.0.7 → 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,8 +1,9 @@
1
- import { Hono, Context, 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';
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';
3
+ import { Context, Hono, ErrorHandler, NotFoundHandler, MiddlewareHandler } from 'hono';
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
+ import { StandardSchemaWithJSON } from '@modelcontextprotocol/server';
6
7
  import 'jose';
7
8
  import 'drizzle-orm';
8
9
  import 'drizzle-orm/pg-core';
@@ -24,7 +25,86 @@ interface PermissionDefinition {
24
25
  /** Declare the app's permission catalog. Codes must be unique and use `app:resource:action`. */
25
26
  declare function definePermissions<const T extends readonly PermissionDefinition[]>(definitions: T): T;
26
27
 
27
- type Env$2 = Record<string, string | undefined>;
28
+ /** What a tool name may be: lower case, digits and underscores, at most 41 characters. */
29
+ declare const TOOL_NAME_PATTERN: RegExp;
30
+ /**
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).
36
+ */
37
+ type ToolAnnotations = {
38
+ readOnlyHint: true;
39
+ idempotentHint?: boolean;
40
+ /** True when the tool calls a system outside the platform, such as an outside API. */
41
+ openWorldHint: boolean;
42
+ } | {
43
+ readOnlyHint: false;
44
+ /** True when the tool can delete or overwrite data, false when it only adds. */
45
+ destructiveHint: boolean;
46
+ /** True when calling it twice with the same input does no more than once. */
47
+ idempotentHint?: boolean;
48
+ /** True when the tool calls a system outside the platform, such as an outside API. */
49
+ openWorldHint: boolean;
50
+ };
51
+ /**
52
+ * A schema for a tool's input or output: a Standard Schema that also gives its JSON Schema,
53
+ * such as a zod 4 object.
54
+ */
55
+ type ToolSchema = StandardSchemaWithJSON;
56
+ /** The value a schema produces from valid input. */
57
+ type ToolInput<S extends ToolSchema> = StandardSchemaWithJSON.InferOutput<S>;
58
+ interface ToolDefinition<S extends ToolSchema = ToolSchema> {
59
+ /** Unique in the app. The gateway shows it as `<app>_<name>`. */
60
+ name: string;
61
+ /** A name for people. */
62
+ title?: string;
63
+ /** What the tool does and when to use it, for the model. */
64
+ description: string;
65
+ /** The input, as an object schema. */
66
+ input: S;
67
+ /** The shape of what the handler returns, when it is an object. Optional. */
68
+ output?: ToolSchema;
69
+ /** The permission the caller needs. It must be in the app's permission catalog. */
70
+ permission: string;
71
+ annotations: ToolAnnotations;
72
+ /**
73
+ * Does the work, with the request's context: `getUser(c)` and `db(c)` work as in a route.
74
+ * Return a string, an object, an array, or nothing. Throw an `AppError` to refuse: its
75
+ * message reaches the caller. Any other error is reported as an internal error, and the
76
+ * request's database work is undone either way.
77
+ */
78
+ handler: (c: Context, input: ToolInput<S>) => unknown;
79
+ }
80
+ declare const TOOL_SET: unique symbol;
81
+ /** The tools of an app, as `defineTools` returns them. */
82
+ type ToolSet = readonly ToolDefinition[] & {
83
+ readonly [TOOL_SET]: true;
84
+ };
85
+ /** One tool as the manifest lists it, for `platform check` and the control plane's screens. */
86
+ interface ToolManifestEntry {
87
+ name: string;
88
+ title: string | null;
89
+ description: string;
90
+ permission: string;
91
+ annotations: ToolAnnotations;
92
+ }
93
+ /** True for what `defineTools` returned. */
94
+ declare function isToolSet(value: unknown): value is ToolSet;
95
+ /** The problems of a list of tools, one sentence each. Empty when there are none. */
96
+ declare function toolProblems(tools: readonly ToolDefinition[]): string[];
97
+ /**
98
+ * Declare an app's tools. Throws, with every problem found, when a name, a description, a
99
+ * permission or the annotations are not as the platform requires.
100
+ */
101
+ declare function defineTools<const S extends readonly ToolSchema[]>(tools: {
102
+ [K in keyof S]: ToolDefinition<S[K]>;
103
+ }): ToolSet;
104
+ /** The manifest's list of tools. */
105
+ declare function toolManifest(tools: readonly ToolDefinition[]): ToolManifestEntry[];
106
+
107
+ type Env$3 = Record<string, string | undefined>;
28
108
  /** The parts of the app's package.json the runtime uses. */
29
109
  interface AppManifest {
30
110
  /** URL segment and app code. */
@@ -56,14 +136,28 @@ interface PlatformManifest {
56
136
  title: string;
57
137
  description: string | null;
58
138
  }[];
139
+ /**
140
+ * The app's tools for agents, served at `<base>/mcp`: for `platform check` and the control
141
+ * plane's screens. The gateway reads the tools from the endpoint, not from here.
142
+ */
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[];
59
150
  release_version: string | null;
60
151
  source_commit: string | null;
61
152
  }
62
153
  interface PlatformManifestOptions {
63
154
  manifest: AppManifest;
64
155
  permissions?: readonly PermissionDefinition[];
156
+ tools?: readonly ToolDefinition[];
157
+ /** The routes that accept API keys. `PlatformApp.platformManifest()` fills it in. */
158
+ apiKeyRoutes?: readonly ApiKeyRoute[];
65
159
  /** Read for `GIT_SHA`. Defaults to `process.env`. */
66
- env?: Env$2;
160
+ env?: Env$3;
67
161
  }
68
162
  /**
69
163
  * The app's manifest for the control plane. Every app answers it at
@@ -72,7 +166,7 @@ interface PlatformManifestOptions {
72
166
  */
73
167
  declare function platformManifest(options: PlatformManifestOptions): PlatformManifest;
74
168
 
75
- type Env$1 = Record<string, string | undefined>;
169
+ type Env$2 = Record<string, string | undefined>;
76
170
  interface CreateAppOptions {
77
171
  /** The app's package.json. `name` and `id` are required. */
78
172
  manifest: AppManifest;
@@ -87,9 +181,20 @@ interface CreateAppOptions {
87
181
  };
88
182
  /** Folder of the built frontend. Defaults to `dist/client` under the working directory. */
89
183
  staticDir?: string;
184
+ /**
185
+ * The app's tools for agents, from `defineTools`. They are served over MCP at
186
+ * `<basePath>/mcp` with the same checks as `api`, and listed in the manifest. Each tool's
187
+ * permission must be in `permissions`.
188
+ */
189
+ tools?: readonly ToolDefinition[];
90
190
  /** Token verifier. Defaults to one built from `LOGTO_*`. */
91
191
  verifier?: Verifier;
92
- env?: Env$1;
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;
197
+ env?: Env$2;
93
198
  /** What the built-in routes call the control plane with. Defaults to `fetch`. For tests. */
94
199
  fetch?: typeof fetch;
95
200
  }
@@ -118,6 +223,11 @@ interface PlatformApp {
118
223
  fetch: (request: Request, ...rest: unknown[]) => Response | Promise<Response>;
119
224
  /** The app's database. Opens it and runs migrations on first use. */
120
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;
121
231
  /** Migrate and listen. Call it from the production entry. */
122
232
  start(): Promise<RunningApp>;
123
233
  }
@@ -171,6 +281,102 @@ declare function toErrorResponse(error: unknown): {
171
281
  declare function errorHandler(onUnexpected?: (error: unknown, c: Context) => void): ErrorHandler;
172
282
  declare function notFoundHandler(): NotFoundHandler;
173
283
 
284
+ /** An authorization server's metadata (RFC 8414 or OpenID Connect Discovery), as served. */
285
+ interface OAuthServerMetadata {
286
+ issuer: string;
287
+ authorization_endpoint?: string;
288
+ token_endpoint?: string;
289
+ scopes_supported?: string[];
290
+ code_challenge_methods_supported?: string[];
291
+ token_endpoint_auth_methods_supported?: string[];
292
+ [key: string]: unknown;
293
+ }
294
+ /** What `discoverOAuth` found. Store it with the service. */
295
+ interface OAuthDiscovery {
296
+ /**
297
+ * The resource indicator to ask tokens for (RFC 8707), from the service's protected
298
+ * resource metadata (RFC 9728). Null when the service publishes none.
299
+ */
300
+ resource: string | null;
301
+ /** The authorization server's issuer. */
302
+ issuer: string;
303
+ /** The scopes the service says it supports, or the server's when it says none. */
304
+ scopes: string[];
305
+ server: OAuthServerMetadata;
306
+ }
307
+ /** Tokens as an app stores them, encrypted. */
308
+ interface OAuthTokens {
309
+ accessToken: string;
310
+ tokenType: string;
311
+ /** The refresh token to keep: a new one when the server rotated it. Null when none. */
312
+ refreshToken: string | null;
313
+ /** When the access token expires, in seconds since 1970. Null when the server says not. */
314
+ expiresAt: number | null;
315
+ scope: string | null;
316
+ }
317
+ /** Where to send the user, and what to keep until the user comes back. */
318
+ interface OAuthAuthorization {
319
+ url: string;
320
+ /** Keep with the attempt and compare in `exchangeCode`. */
321
+ state: string;
322
+ /** Keep secret, server side, until `exchangeCode`. */
323
+ codeVerifier: string;
324
+ }
325
+ interface OAuthRequestOptions {
326
+ /** What the requests are made with. Defaults to `fetch`. Pass a guarded fetch for an address a user typed. */
327
+ fetch?: typeof fetch;
328
+ /** Accept `http:` addresses. For a server on the developer machine only. */
329
+ allowHttp?: boolean;
330
+ }
331
+ interface OAuthClientOptions extends OAuthRequestOptions {
332
+ server: OAuthServerMetadata;
333
+ /** A client id typed in, or the address of a client metadata document. */
334
+ clientId: string;
335
+ /** Omit for a public client, which proves itself with PKCE alone. */
336
+ clientSecret?: string;
337
+ }
338
+ interface OAuthClient {
339
+ /** The address of the authorization request, with PKCE (S256) and a new state. */
340
+ authorize(input: {
341
+ redirectUri: string;
342
+ scope?: string;
343
+ resource?: string | null;
344
+ }): Promise<OAuthAuthorization>;
345
+ /**
346
+ * Exchange what the server sent to the redirect address: the whole address it called, or
347
+ * its query parameters (`code`, `state`, and `iss` when the server sends one).
348
+ */
349
+ exchangeCode(input: {
350
+ callback: string | Record<string, string>;
351
+ redirectUri: string;
352
+ state: string;
353
+ codeVerifier: string;
354
+ resource?: string | null;
355
+ }): Promise<OAuthTokens>;
356
+ /** Renew the tokens. `invalid_grant` means the user has to authorize again. */
357
+ refresh(refreshToken: string, input?: {
358
+ scope?: string;
359
+ resource?: string | null;
360
+ }): Promise<OAuthTokens>;
361
+ }
362
+ /** A refusal of the authorization server, or a server that could not be used. */
363
+ declare class OAuthError extends AppError {
364
+ /** The OAuth error code, such as `invalid_grant`, or `server_error` when there is none. */
365
+ readonly oauthError: string;
366
+ /** True when the grant is gone and only a new authorization helps. */
367
+ readonly needsAuthorization: boolean;
368
+ constructor(message: string, oauthError: string, cause?: unknown);
369
+ }
370
+ /**
371
+ * Find the authorization server of a service, such as an MCP server's address. Reads the
372
+ * service's protected resource metadata (RFC 9728) for the server, or takes the service's
373
+ * origin when it has none, then the server's metadata, as RFC 8414 and then as OpenID
374
+ * Connect Discovery.
375
+ */
376
+ declare function discoverOAuth(serviceUrl: string, options?: OAuthRequestOptions): Promise<OAuthDiscovery>;
377
+ /** A client of one authorization server, from the metadata `discoverOAuth` found. */
378
+ declare function createOAuthClient(options: OAuthClientOptions): OAuthClient;
379
+
174
380
  declare const DEFAULT_PAGE_SIZE = 20;
175
381
  declare const MAX_PAGE_SIZE = 100;
176
382
  interface PageParams {
@@ -193,7 +399,7 @@ interface Page<T> {
193
399
  declare function parsePage(source: Context | Record<string, string | undefined>): PageParams;
194
400
  declare function pageOf<T>(items: T[], total: number, params: PageParams): Page<T>;
195
401
 
196
- type Env = Record<string, string | undefined>;
402
+ type Env$1 = Record<string, string | undefined>;
197
403
  interface PlatformCall {
198
404
  /** Defaults to GET. */
199
405
  method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
@@ -203,7 +409,7 @@ interface PlatformCall {
203
409
  query?: Record<string, string | number | boolean | undefined>;
204
410
  }
205
411
  interface PlatformCallOptions {
206
- env?: Env;
412
+ env?: Env$1;
207
413
  fetch?: typeof fetch;
208
414
  /** Milliseconds to wait for the answer. Defaults to 10 seconds. */
209
415
  timeout?: number;
@@ -245,6 +451,39 @@ declare module 'hono' {
245
451
  }
246
452
  }
247
453
 
454
+ type Env = Record<string, string | undefined>;
455
+ /** A key shorter than this is refused. */
456
+ declare const MIN_SECRET_KEY_LENGTH = 32;
457
+ interface SecretBoxOptions {
458
+ /** The variable that holds the key, such as `ADMIN_SECRET_KEY`. Named in errors. */
459
+ keyVariable: string;
460
+ /**
461
+ * What the key is for, as the HKDF info, such as `admin/mcp-credentials/v1`. Two boxes
462
+ * with different purposes cannot read each other's values, also with one key.
463
+ */
464
+ purpose: string;
465
+ /** Read at every call. Defaults to `process.env`. */
466
+ env?: Env;
467
+ }
468
+ interface SecretBox {
469
+ /**
470
+ * Encrypt `plain`. `context` names what the value belongs to, such as `credential:<id>`.
471
+ * A value copied to another row no longer decrypts.
472
+ */
473
+ encrypt(plain: string, context: string): string;
474
+ /**
475
+ * Decrypt what `encrypt` returned for the same `context`. Throws 409
476
+ * `credential_unreadable` when the key changed or the value was damaged or moved.
477
+ */
478
+ decrypt(stored: string, context: string): string;
479
+ }
480
+ /**
481
+ * Encryption for the secrets an app stores. Without a key of at least 32 characters every
482
+ * call throws 503 `secret_key_missing`, except with the dev identity, which has a key of its
483
+ * own that protects nothing.
484
+ */
485
+ declare function createSecretBox(options: SecretBoxOptions): SecretBox;
486
+
248
487
  /** Thrown when a URL points somewhere the server must not call. */
249
488
  declare class UnsafeUrlError extends AppError {
250
489
  constructor(message: string);
@@ -266,4 +505,4 @@ interface UrlGuardOptions {
266
505
  */
267
506
  declare function assertPublicUrl(input: string | URL, options?: UrlGuardOptions): Promise<URL>;
268
507
 
269
- export { AppError, type AppErrorOptions, type AppManifest, AuthUser, ConflictError, type CreateAppOptions, DEFAULT_PAGE_SIZE, type ErrorBody, ForbiddenError, MAX_PAGE_SIZE, NotFoundError, type Page, type PageParams, type PermissionDefinition, type PlatformApp, type PlatformCall, type PlatformCallOptions, type PlatformManifest, type PlatformManifestOptions, REQUEST_ID_HEADER, type RequestContext, type RunningApp, UnauthorizedError, UnsafeUrlError, type UrlGuardOptions, ValidationError, Verifier, assertPublicUrl, callPlatform, coerceRequestId, createApp, definePermissions, errorHandler, getRequestContext, getRequestId, hasPermissions, isReservedAddress, notFoundHandler, pageOf, parsePage, permissionMatches, platformManifest, requestContext, toErrorResponse };
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 };