@zjazj/server 0.0.8 → 0.0.10

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/index.d.ts CHANGED
@@ -1,13 +1,81 @@
1
- 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
- import { D as Database } from './db-Dp7BB3Kc.js';
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';
1
+ import { K as KeyVerifier, b as ApiKeyRoute, V as Verifier, A as AuthUser } from './api-keys-BY7RCE9v.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-BY7RCE9v.js';
3
+ import { MiddlewareHandler, Context, Hono, ErrorHandler, NotFoundHandler } from 'hono';
4
+ import { D as Database } from './db-NCwvoAnt.js';
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-NCwvoAnt.js';
6
6
  import { StandardSchemaWithJSON } from '@modelcontextprotocol/server';
7
+ import { ObjectKinds } from './objects.js';
7
8
  import 'jose';
8
9
  import 'drizzle-orm';
9
10
  import 'drizzle-orm/pg-core';
10
11
 
12
+ type Env$5 = Record<string, string | undefined>;
13
+ /**
14
+ * Where a job works. A `tenant` job works in the tenant of the key it is called with. A
15
+ * `platform` job works across tenants and is called only with a key of the platform's own
16
+ * tenant.
17
+ */
18
+ type JobScope = 'tenant' | 'platform';
19
+ /** What `job()` says about a route of `app.jobs`. */
20
+ interface JobOptions {
21
+ scope: JobScope;
22
+ /**
23
+ * The code a user needs to schedule a tenant job, such as `connect:api:manage`. It must
24
+ * be in the app's catalog. Leave it out for a platform job, which an operator schedules,
25
+ * and for a tenant job that no user may schedule.
26
+ */
27
+ schedulableWith?: string;
28
+ /** A short name for the scheduler's screens. */
29
+ title?: string;
30
+ }
31
+ /** A job as the manifest lists it. The scheduler calls `POST <path>`. */
32
+ interface JobManifestEntry {
33
+ name: string;
34
+ path: string;
35
+ title: string | null;
36
+ scope: JobScope;
37
+ schedulable_with: string | null;
38
+ }
39
+ /**
40
+ * A job's name, which is its path under `/internal/jobs`: at most 63 characters, as the
41
+ * control plane records it.
42
+ */
43
+ declare const JOB_NAME_PATTERN: RegExp;
44
+ /** The code a key needs to call the jobs of an app. The SDK declares it by itself. */
45
+ declare function jobCode(appName: string): string;
46
+ /**
47
+ * Declares a route of `app.jobs` as a job. Put it first in the route's handlers:
48
+ *
49
+ * ```ts
50
+ * app.jobs.post('/sync-api', job({ scope: 'tenant', schedulableWith: 'connect:api:manage' }), handler)
51
+ * ```
52
+ *
53
+ * The route is then listed in the app's manifest, and only a tenant API key that holds
54
+ * `<app>:job:run` can call it. A route of `app.jobs` without it is never reached.
55
+ */
56
+ declare function job(options: JobOptions): MiddlewareHandler;
57
+ interface AuthenticateJobOptions {
58
+ /** The app's name: its job code is `<name>:job:run`. */
59
+ appName: string;
60
+ keyVerifier: KeyVerifier;
61
+ env?: Env$5;
62
+ }
63
+ /**
64
+ * Lets a job run only for the scheduler's call: a tenant API key that holds the app's job
65
+ * code, and for a platform job a key of the platform's own tenant. The caller is then
66
+ * `getUser(c)`, and `c.get('job')` says which job it is.
67
+ */
68
+ declare function authenticateJob(options: AuthenticateJobOptions): MiddlewareHandler;
69
+ declare module 'hono' {
70
+ interface ContextVariableMap {
71
+ /** Set on a request of `app.jobs`: the job, and whether it works in one tenant. */
72
+ job: {
73
+ name: string;
74
+ scope: JobScope;
75
+ };
76
+ }
77
+ }
78
+
11
79
  /**
12
80
  * True when `code` is covered by the granted set: an exact match, a bare `*`, or a granted
13
81
  * code whose trailing segments are wildcards, for example `inventory:item:*` or
@@ -16,11 +84,20 @@ import 'drizzle-orm/pg-core';
16
84
  declare function permissionMatches(granted: ReadonlySet<string>, code: string): boolean;
17
85
  /** True when every required code is covered. An empty requirement is always satisfied. */
18
86
  declare function hasPermissions(granted: Iterable<string>, required: readonly string[]): boolean;
87
+ /**
88
+ * Who may hold a code. A `tenant` code is given to roles of every tenant. A `platform`
89
+ * code is given only in the platform's own tenant, to its operators, and only for an app
90
+ * the control plane records as part of the platform: it refuses the publish of any other
91
+ * app that declares one.
92
+ */
93
+ type PermissionScope = 'tenant' | 'platform';
19
94
  /** One entry of an app's permission catalog. The control plane reads it from the manifest. */
20
95
  interface PermissionDefinition {
21
96
  code: string;
22
97
  title: string;
23
98
  description?: string;
99
+ /** Defaults to `tenant`. */
100
+ scope?: PermissionScope;
24
101
  }
25
102
  /** Declare the app's permission catalog. Codes must be unique and use `app:resource:action`. */
26
103
  declare function definePermissions<const T extends readonly PermissionDefinition[]>(definitions: T): T;
@@ -28,22 +105,25 @@ declare function definePermissions<const T extends readonly PermissionDefinition
28
105
  /** What a tool name may be: lower case, digits and underscores, at most 41 characters. */
29
106
  declare const TOOL_NAME_PATTERN: RegExp;
30
107
  /**
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.
108
+ * What a tool does, for the people who choose whether an agent may call it on its own. A
109
+ * tool that only reads says so. Any other tool says whether it can destroy data. Every tool
110
+ * says whether it reaches outside the platform: MCP takes a tool that does not say as one
111
+ * that does, and there is no default here, as a tool that reaches outside and forgets to
112
+ * say so would be the dangerous mistake (`docs/mcp-plan.md`, section 7).
33
113
  */
34
114
  type ToolAnnotations = {
35
115
  readOnlyHint: true;
36
116
  idempotentHint?: boolean;
37
- /** True when the tool reaches a system outside the platform. */
38
- openWorldHint?: boolean;
117
+ /** True when the tool calls a system outside the platform, such as an outside API. */
118
+ openWorldHint: boolean;
39
119
  } | {
40
120
  readOnlyHint: false;
41
121
  /** True when the tool can delete or overwrite data, false when it only adds. */
42
122
  destructiveHint: boolean;
43
123
  /** True when calling it twice with the same input does no more than once. */
44
124
  idempotentHint?: boolean;
45
- /** True when the tool reaches a system outside the platform. */
46
- openWorldHint?: boolean;
125
+ /** True when the tool calls a system outside the platform, such as an outside API. */
126
+ openWorldHint: boolean;
47
127
  };
48
128
  /**
49
129
  * A schema for a tool's input or output: a Standard Schema that also gives its JSON Schema,
@@ -101,7 +181,7 @@ declare function defineTools<const S extends readonly ToolSchema[]>(tools: {
101
181
  /** The manifest's list of tools. */
102
182
  declare function toolManifest(tools: readonly ToolDefinition[]): ToolManifestEntry[];
103
183
 
104
- type Env$3 = Record<string, string | undefined>;
184
+ type Env$4 = Record<string, string | undefined>;
105
185
  /** The parts of the app's package.json the runtime uses. */
106
186
  interface AppManifest {
107
187
  /** URL segment and app code. */
@@ -128,16 +208,32 @@ interface PlatformManifest {
128
208
  description: string | null;
129
209
  portal_nav_title: string;
130
210
  portal_nav_icon: string | null;
211
+ /**
212
+ * The permission catalog. The control plane records a `platform` code as such only for
213
+ * a project it marks as part of the platform, and refuses the publish of any other.
214
+ */
131
215
  permission_manifest: {
132
216
  code: string;
133
217
  title: string;
134
218
  description: string | null;
219
+ scope: PermissionScope;
135
220
  }[];
136
221
  /**
137
222
  * The app's tools for agents, served at `<base>/mcp`: for `platform check` and the control
138
223
  * plane's screens. The gateway reads the tools from the endpoint, not from here.
139
224
  */
140
225
  tools: ToolManifestEntry[];
226
+ /**
227
+ * The routes that accept an API key as well as a token, for screens and documentation.
228
+ * Paths are under the app's base, except those under `/internal`. The MCP endpoint is
229
+ * one when the app has tools.
230
+ */
231
+ api_key_routes: ApiKeyRoute[];
232
+ /**
233
+ * The jobs the scheduler may call, at `POST <path>` with the API key of a tenant. The
234
+ * key must hold `<app_code>:job:run`, which is in the catalog when there are jobs.
235
+ */
236
+ jobs: JobManifestEntry[];
141
237
  release_version: string | null;
142
238
  source_commit: string | null;
143
239
  }
@@ -145,8 +241,12 @@ interface PlatformManifestOptions {
145
241
  manifest: AppManifest;
146
242
  permissions?: readonly PermissionDefinition[];
147
243
  tools?: readonly ToolDefinition[];
244
+ /** The routes that accept API keys. `PlatformApp.platformManifest()` fills it in. */
245
+ apiKeyRoutes?: readonly ApiKeyRoute[];
246
+ /** The jobs of `app.jobs`. `PlatformApp.platformManifest()` fills it in. */
247
+ jobs?: readonly JobManifestEntry[];
148
248
  /** Read for `GIT_SHA`. Defaults to `process.env`. */
149
- env?: Env$3;
249
+ env?: Env$4;
150
250
  }
151
251
  /**
152
252
  * The app's manifest for the control plane. Every app answers it at
@@ -155,7 +255,7 @@ interface PlatformManifestOptions {
155
255
  */
156
256
  declare function platformManifest(options: PlatformManifestOptions): PlatformManifest;
157
257
 
158
- type Env$2 = Record<string, string | undefined>;
258
+ type Env$3 = Record<string, string | undefined>;
159
259
  interface CreateAppOptions {
160
260
  /** The app's package.json. `name` and `id` are required. */
161
261
  manifest: AppManifest;
@@ -176,9 +276,21 @@ interface CreateAppOptions {
176
276
  * permission must be in `permissions`.
177
277
  */
178
278
  tools?: readonly ToolDefinition[];
279
+ /**
280
+ * The app's object kinds, from `defineObjects` in `@zjazj/server/objects`. Each object
281
+ * then has an owner, a visibility and grants, checked with `assertCan` and `visibleTo`,
282
+ * and the Share dialog of `@zjazj/web` works for it. The app's override code
283
+ * `<app>:object:admin` is added to the catalog.
284
+ */
285
+ objects?: ObjectKinds;
179
286
  /** Token verifier. Defaults to one built from `LOGTO_*`. */
180
287
  verifier?: Verifier;
181
- env?: Env$2;
288
+ /**
289
+ * API key verifier. Defaults to one that asks the control plane at `PLATFORM_URL`. The
290
+ * control plane passes `createKeyVerifier({ check })` to check keys itself.
291
+ */
292
+ keyVerifier?: KeyVerifier;
293
+ env?: Env$3;
182
294
  /** What the built-in routes call the control plane with. Defaults to `fetch`. For tests. */
183
295
  fetch?: typeof fetch;
184
296
  }
@@ -203,10 +315,23 @@ interface PlatformApp {
203
315
  * database work the same. The gateway never routes them.
204
316
  */
205
317
  delegated: Hono;
318
+ /**
319
+ * The app's jobs, served under `/internal/jobs` and called by the platform's scheduler.
320
+ * Each route starts with `job({ scope, schedulableWith })` and is `POST /<name>`. It is
321
+ * called only with the API key of a tenant that holds `<app>:job:run`, which is added to
322
+ * the catalog, and a tenant job's `db(c)` is bound to the key's tenant. The gateway never
323
+ * routes them.
324
+ */
325
+ jobs: Hono;
206
326
  /** The request handler. Lets the app be the default export for the Vite dev server. */
207
327
  fetch: (request: Request, ...rest: unknown[]) => Response | Promise<Response>;
208
328
  /** The app's database. Opens it and runs migrations on first use. */
209
329
  database(): Promise<Database>;
330
+ /**
331
+ * What `/internal/_platform/manifest` answers, with the routes that accept API keys as
332
+ * they are now. The control plane records its own catalog with it.
333
+ */
334
+ platformManifest(): PlatformManifest;
210
335
  /** Migrate and listen. Call it from the production entry. */
211
336
  start(): Promise<RunningApp>;
212
337
  }
@@ -260,6 +385,110 @@ declare function toErrorResponse(error: unknown): {
260
385
  declare function errorHandler(onUnexpected?: (error: unknown, c: Context) => void): ErrorHandler;
261
386
  declare function notFoundHandler(): NotFoundHandler;
262
387
 
388
+ type Env$2 = Record<string, string | undefined>;
389
+ /** Thrown when a URL points somewhere the server must not call. */
390
+ declare class UnsafeUrlError extends AppError {
391
+ constructor(message: string);
392
+ }
393
+ /**
394
+ * True when the address is not public: private, loopback, link-local, shared (CGNAT),
395
+ * multicast, unspecified, documentation, an IPv6 unique local address, an IPv4-mapped form
396
+ * of any of these, and every IPv6 address outside global unicast. Also true for a string
397
+ * that is no IP address.
398
+ */
399
+ declare function isReservedAddress(address: string): boolean;
400
+ interface UrlGuardOptions {
401
+ /** Hosts that are allowed even when they resolve to a reserved address. */
402
+ allowHosts?: string[];
403
+ /** Replace the DNS lookup. Meant for tests. */
404
+ lookup?: (hostname: string) => Promise<string[]>;
405
+ /**
406
+ * Read for the development allowances, `URL_GUARD_ALLOW_HOSTS` and `DEV_PUBLIC_NETWORKS`,
407
+ * which count only while the dev identity is on (`ENV=dev`). Defaults to `process.env`.
408
+ */
409
+ env?: Env$2;
410
+ }
411
+ /** A URL that passed the check, and the addresses its host was found at. */
412
+ interface CheckedUrl {
413
+ url: URL;
414
+ /**
415
+ * Every address the host resolved to, each one checked. Empty for a host that is an IP
416
+ * address, and for one that a development allowance names: those are not looked up.
417
+ */
418
+ addresses: string[];
419
+ }
420
+ /**
421
+ * Checks a URL and returns the addresses it checked, so that a request can go to exactly
422
+ * those. `fetchPublic` does that; `assertPublicUrl` returns the URL alone.
423
+ */
424
+ declare function checkPublicUrl(input: string | URL, options?: UrlGuardOptions): Promise<CheckedUrl>;
425
+ /**
426
+ * Check a URL given by a user: http or https, and a host whose every address is public.
427
+ *
428
+ * Use it to refuse an address when a form is saved. To call the address, use
429
+ * `fetchPublic`: a request with `fetch` looks the name up again, and the name may point
430
+ * somewhere private by then.
431
+ */
432
+ declare function assertPublicUrl(input: string | URL, options?: UrlGuardOptions): Promise<URL>;
433
+
434
+ /** Why a request of `fetchPublic` got no usable answer. */
435
+ type FetchPublicFailure = 'redirect' | 'timeout' | 'unreachable' | 'too_large';
436
+ /**
437
+ * The address was public, but no answer came that can be used. `reason` says why. The
438
+ * caller of the app's route gets a 502 or a 504 with the code, never the address's answer.
439
+ */
440
+ declare class FetchPublicError extends AppError {
441
+ readonly reason: FetchPublicFailure;
442
+ /** The status of a redirect the address answered with. */
443
+ readonly upstreamStatus?: number;
444
+ constructor(reason: FetchPublicFailure, message: string, options?: {
445
+ upstreamStatus?: number;
446
+ cause?: unknown;
447
+ });
448
+ }
449
+ interface FetchPublicInit extends UrlGuardOptions {
450
+ /** Defaults to GET. */
451
+ method?: string;
452
+ headers?: ConstructorParameters<typeof Headers>[0];
453
+ body?: string | Uint8Array | null;
454
+ /** Milliseconds for the whole exchange, from the lookup to the end of the answer. Defaults to 10 seconds. */
455
+ timeout?: number;
456
+ /** The most bytes of the answer's body that are read. Defaults to 5 MiB. */
457
+ maxBytes?: number;
458
+ signal?: AbortSignal;
459
+ }
460
+ /** 10 seconds. */
461
+ declare const FETCH_PUBLIC_TIMEOUT = 10000;
462
+ /** 5 MiB. */
463
+ declare const FETCH_PUBLIC_MAX_BYTES: number;
464
+ /**
465
+ * Call an address that a user gave, such as a webhook, an outside API or a feed.
466
+ *
467
+ * The app runs inside the platform's network, where the control plane, the database and
468
+ * every app's `/internal` routes answer without asking who calls. An address from a user
469
+ * must never lead there, so this:
470
+ *
471
+ * - takes http and https only;
472
+ * - looks the name up once and refuses it unless every address it has is public
473
+ * (`isReservedAddress`);
474
+ * - connects to exactly those addresses, so a name that points elsewhere a moment later
475
+ * changes nothing. `Host` and, for https, the name the certificate must be for stay the
476
+ * URL's;
477
+ * - takes a redirect as a failure and does not follow it: it leads to an address nobody
478
+ * checked. To go on, check the new address with another call;
479
+ * - gives up after `timeout` and refuses a body longer than `maxBytes`.
480
+ *
481
+ * It answers with a `Response` whose body has been read, so `ok`, `status`, `headers`,
482
+ * `json()` and `text()` work as after `fetch`. The body is asked for without compression.
483
+ * A refused address is a 400 `unsafe_url` (`UnsafeUrlError`); an answer that cannot be
484
+ * used is a `FetchPublicError` (502 or 504). A status of 4xx or 5xx is an answer, returned
485
+ * as it is.
486
+ *
487
+ * With `ENV=dev`, `DEV_PUBLIC_NETWORKS` and `URL_GUARD_ALLOW_HOSTS` let a developer machine
488
+ * through (see `assertPublicUrl`). Nothing else does.
489
+ */
490
+ declare function fetchPublic(input: string | URL, init?: FetchPublicInit): Promise<Response>;
491
+
263
492
  /** An authorization server's metadata (RFC 8414 or OpenID Connect Discovery), as served. */
264
493
  interface OAuthServerMetadata {
265
494
  issuer: string;
@@ -463,25 +692,4 @@ interface SecretBox {
463
692
  */
464
693
  declare function createSecretBox(options: SecretBoxOptions): SecretBox;
465
694
 
466
- /** Thrown when a URL points somewhere the server must not call. */
467
- declare class UnsafeUrlError extends AppError {
468
- constructor(message: string);
469
- }
470
- /** True when the address is private, loopback, link-local or otherwise reserved. */
471
- declare function isReservedAddress(address: string): boolean;
472
- interface UrlGuardOptions {
473
- /** Hosts that are allowed even when they resolve to a reserved address. */
474
- allowHosts?: string[];
475
- /** Replace the DNS lookup. Meant for tests. */
476
- lookup?: (hostname: string) => Promise<string[]>;
477
- }
478
- /**
479
- * Check a URL before the server calls it on behalf of a user. Rejects anything that is not
480
- * http or https and any host that resolves to a private or reserved address.
481
- *
482
- * The check and the later request resolve the name separately. Do not use this as the only
483
- * defence where an attacker controls DNS.
484
- */
485
- declare function assertPublicUrl(input: string | URL, options?: UrlGuardOptions): Promise<URL>;
486
-
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 };
695
+ export { ApiKeyRoute, AppError, type AppErrorOptions, type AppManifest, AuthUser, type AuthenticateJobOptions, type CheckedUrl, ConflictError, type CreateAppOptions, DEFAULT_PAGE_SIZE, type ErrorBody, FETCH_PUBLIC_MAX_BYTES, FETCH_PUBLIC_TIMEOUT, FetchPublicError, type FetchPublicFailure, type FetchPublicInit, ForbiddenError, JOB_NAME_PATTERN, type JobManifestEntry, type JobOptions, type JobScope, 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 PermissionScope, 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, authenticateJob, callPlatform, checkPublicUrl, coerceRequestId, createApp, createOAuthClient, createSecretBox, definePermissions, defineTools, discoverOAuth, errorHandler, fetchPublic, getRequestContext, getRequestId, hasPermissions, isReservedAddress, isToolSet, job, jobCode, notFoundHandler, pageOf, parsePage, permissionMatches, platformManifest, requestContext, toErrorResponse, toolManifest, toolProblems };