@zjazj/server 0.0.9 → 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/dev.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  isDevIdentityEnabled,
10
10
  resolveDevKeyUser,
11
11
  resolveDevUser
12
- } from "./chunk-SLNRMJDM.js";
12
+ } from "./chunk-3X4RSAM6.js";
13
13
  export {
14
14
  DEFAULT_DEV_TENANT_ID,
15
15
  DEV_API_KEY_PREFIX,
package/dist/index.d.ts CHANGED
@@ -1,13 +1,81 @@
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
- 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;
@@ -104,7 +181,7 @@ declare function defineTools<const S extends readonly ToolSchema[]>(tools: {
104
181
  /** The manifest's list of tools. */
105
182
  declare function toolManifest(tools: readonly ToolDefinition[]): ToolManifestEntry[];
106
183
 
107
- type Env$3 = Record<string, string | undefined>;
184
+ type Env$4 = Record<string, string | undefined>;
108
185
  /** The parts of the app's package.json the runtime uses. */
109
186
  interface AppManifest {
110
187
  /** URL segment and app code. */
@@ -131,10 +208,15 @@ interface PlatformManifest {
131
208
  description: string | null;
132
209
  portal_nav_title: string;
133
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
+ */
134
215
  permission_manifest: {
135
216
  code: string;
136
217
  title: string;
137
218
  description: string | null;
219
+ scope: PermissionScope;
138
220
  }[];
139
221
  /**
140
222
  * The app's tools for agents, served at `<base>/mcp`: for `platform check` and the control
@@ -147,6 +229,11 @@ interface PlatformManifest {
147
229
  * one when the app has tools.
148
230
  */
149
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[];
150
237
  release_version: string | null;
151
238
  source_commit: string | null;
152
239
  }
@@ -156,8 +243,10 @@ interface PlatformManifestOptions {
156
243
  tools?: readonly ToolDefinition[];
157
244
  /** The routes that accept API keys. `PlatformApp.platformManifest()` fills it in. */
158
245
  apiKeyRoutes?: readonly ApiKeyRoute[];
246
+ /** The jobs of `app.jobs`. `PlatformApp.platformManifest()` fills it in. */
247
+ jobs?: readonly JobManifestEntry[];
159
248
  /** Read for `GIT_SHA`. Defaults to `process.env`. */
160
- env?: Env$3;
249
+ env?: Env$4;
161
250
  }
162
251
  /**
163
252
  * The app's manifest for the control plane. Every app answers it at
@@ -166,7 +255,7 @@ interface PlatformManifestOptions {
166
255
  */
167
256
  declare function platformManifest(options: PlatformManifestOptions): PlatformManifest;
168
257
 
169
- type Env$2 = Record<string, string | undefined>;
258
+ type Env$3 = Record<string, string | undefined>;
170
259
  interface CreateAppOptions {
171
260
  /** The app's package.json. `name` and `id` are required. */
172
261
  manifest: AppManifest;
@@ -187,6 +276,13 @@ interface CreateAppOptions {
187
276
  * permission must be in `permissions`.
188
277
  */
189
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;
190
286
  /** Token verifier. Defaults to one built from `LOGTO_*`. */
191
287
  verifier?: Verifier;
192
288
  /**
@@ -194,7 +290,7 @@ interface CreateAppOptions {
194
290
  * control plane passes `createKeyVerifier({ check })` to check keys itself.
195
291
  */
196
292
  keyVerifier?: KeyVerifier;
197
- env?: Env$2;
293
+ env?: Env$3;
198
294
  /** What the built-in routes call the control plane with. Defaults to `fetch`. For tests. */
199
295
  fetch?: typeof fetch;
200
296
  }
@@ -219,6 +315,14 @@ interface PlatformApp {
219
315
  * database work the same. The gateway never routes them.
220
316
  */
221
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;
222
326
  /** The request handler. Lets the app be the default export for the Vite dev server. */
223
327
  fetch: (request: Request, ...rest: unknown[]) => Response | Promise<Response>;
224
328
  /** The app's database. Opens it and runs migrations on first use. */
@@ -281,6 +385,110 @@ declare function toErrorResponse(error: unknown): {
281
385
  declare function errorHandler(onUnexpected?: (error: unknown, c: Context) => void): ErrorHandler;
282
386
  declare function notFoundHandler(): NotFoundHandler;
283
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
+
284
492
  /** An authorization server's metadata (RFC 8414 or OpenID Connect Discovery), as served. */
285
493
  interface OAuthServerMetadata {
286
494
  issuer: string;
@@ -484,25 +692,4 @@ interface SecretBox {
484
692
  */
485
693
  declare function createSecretBox(options: SecretBoxOptions): SecretBox;
486
694
 
487
- /** Thrown when a URL points somewhere the server must not call. */
488
- declare class UnsafeUrlError extends AppError {
489
- constructor(message: string);
490
- }
491
- /** True when the address is private, loopback, link-local or otherwise reserved. */
492
- declare function isReservedAddress(address: string): boolean;
493
- interface UrlGuardOptions {
494
- /** Hosts that are allowed even when they resolve to a reserved address. */
495
- allowHosts?: string[];
496
- /** Replace the DNS lookup. Meant for tests. */
497
- lookup?: (hostname: string) => Promise<string[]>;
498
- }
499
- /**
500
- * Check a URL before the server calls it on behalf of a user. Rejects anything that is not
501
- * http or https and any host that resolves to a private or reserved address.
502
- *
503
- * The check and the later request resolve the name separately. Do not use this as the only
504
- * defence where an attacker controls DNS.
505
- */
506
- declare function assertPublicUrl(input: string | URL, options?: UrlGuardOptions): Promise<URL>;
507
-
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 };
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 };