@zjazj/server 0.0.2 → 0.0.4

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/README.md CHANGED
@@ -26,4 +26,15 @@ export default app
26
26
 
27
27
  `db(c)` can only see rows of the caller's tenant. The database enforces it with row-level security.
28
28
 
29
+ Routes go on one of four routers:
30
+
31
+ | Router | Served at | Caller |
32
+ | --- | --- | --- |
33
+ | `app.api` | `<base>/api` | The app's own frontend, with the user's token |
34
+ | `app.publicApi` | `<base>/api/public` | Anyone |
35
+ | `app.internal` | `/internal` | Other services inside the platform's network, with a credential the route checks |
36
+ | `app.delegated` | `/internal/delegated` | Another app's backend acting for its signed-in user, with that user's token |
37
+
38
+ `callPlatform(c, path)` is the calling side of `app.delegated`: it asks the control plane with the token of the request's user and returns the answer.
39
+
29
40
  Part of [platform-cli](https://github.com/zjazj/platform-cli). All `@zjazj/*` packages share one version. Install them at the same version.
@@ -3,7 +3,7 @@ import {
3
3
  ForbiddenError,
4
4
  UUID_PATTERN,
5
5
  UnauthorizedError
6
- } from "./chunk-6IYKARAJ.js";
6
+ } from "./chunk-UWDDQH25.js";
7
7
  import {
8
8
  isDevIdentityEnabled,
9
9
  resolveDevUser
@@ -93,6 +93,9 @@ function isValidAppName(value) {
93
93
  function isValidAppId(value) {
94
94
  return typeof value === "string" && APP_ID_PATTERN.test(value);
95
95
  }
96
+ function appBasePath(name) {
97
+ return `/apps/${name}/`;
98
+ }
96
99
  function assertValidAppId(value) {
97
100
  if (!isValidAppId(value)) {
98
101
  throw new Error(
@@ -136,6 +139,7 @@ export {
136
139
  isUuid,
137
140
  isValidAppName,
138
141
  isValidAppId,
142
+ appBasePath,
139
143
  assertValidAppId,
140
144
  generateAppId,
141
145
  uuidv7
@@ -12,6 +12,13 @@ declare const APP_ID_PATTERN: RegExp;
12
12
  declare function isUuid(value: unknown): value is string;
13
13
  declare function isValidAppName(value: unknown): value is string;
14
14
  declare function isValidAppId(value: unknown): value is string;
15
+ /**
16
+ * Where the app of this name is served on the platform's address, with a trailing slash:
17
+ * `/apps/<name>/`. A deployed app uses it unless `BASE_URL` says otherwise. The control
18
+ * plane uses it to route an app and to tell the build which path to build for. An app
19
+ * itself never needs it: links and API calls already carry the base path.
20
+ */
21
+ declare function appBasePath(name: string): string;
15
22
  /** Generate a new app id. Called once, by `platform create`. */
16
23
  declare function generateAppId(): string;
17
24
  /** A time-ordered UUID (version 7). Use it for primary keys. */
@@ -127,4 +134,4 @@ type GlobalTable<TName extends string, TColumns extends Record<string, PgColumnB
127
134
  */
128
135
  declare function globalTable<TName extends string, TColumns extends Record<string, PgColumnBuilderBase>>(schema: PgSchema<string>, name: TName, columns: TColumns): GlobalTable<TName, TColumns>;
129
136
 
130
- export { APP_ID_PATTERN as A, type CreateDatabaseOptions as C, type Database as D, type GlobalTable as G, type MigrateOptions as M, type TenantTable as T, APP_NAME_PATTERN as a, isValidAppId as b, isValidAppName as c, type Db as d, appSchema as e, applyTenantPolicies as f, generateAppId as g, createDatabase as h, isUuid as i, db as j, globalTable as k, tenantDatabase as l, migrate as m, tenantTable as n, withTenant as o, tenantColumns as t, uuidv7 as u, withAllTenants as w };
137
+ export { APP_ID_PATTERN as A, type CreateDatabaseOptions as C, type Database as D, type GlobalTable as G, type MigrateOptions as M, type TenantTable as T, APP_NAME_PATTERN as a, appBasePath as b, isValidAppId as c, isValidAppName as d, type Db as e, appSchema as f, generateAppId as g, applyTenantPolicies as h, isUuid as i, createDatabase as j, db as k, globalTable as l, migrate as m, tenantDatabase as n, tenantTable as o, withTenant as p, tenantColumns as t, uuidv7 as u, withAllTenants as w };
package/dist/db.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import 'drizzle-orm';
2
2
  import 'drizzle-orm/pg-core';
3
3
  import 'hono';
4
- export { C as CreateDatabaseOptions, D as Database, d as Db, G as GlobalTable, M as MigrateOptions, T as TenantTable, e as appSchema, f as applyTenantPolicies, h as createDatabase, j as db, k as globalTable, m as migrate, t as tenantColumns, l as tenantDatabase, n as tenantTable, u as uuidv7, w as withAllTenants, o as withTenant } from './db-CWKXPFWA.js';
4
+ export { C as CreateDatabaseOptions, D as Database, e as Db, G as GlobalTable, M as MigrateOptions, T as TenantTable, f as appSchema, h as applyTenantPolicies, j as createDatabase, k as db, l as globalTable, m as migrate, t as tenantColumns, n as tenantDatabase, o as tenantTable, u as uuidv7, w as withAllTenants, p as withTenant } from './db-BmTPWKyI.js';
package/dist/db.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  UUID_PATTERN,
4
4
  assertValidAppId,
5
5
  uuidv7
6
- } from "./chunk-6IYKARAJ.js";
6
+ } from "./chunk-UWDDQH25.js";
7
7
  import "./chunk-ERGI2X5S.js";
8
8
 
9
9
  // src/db.ts
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { Hono, Context, ErrorHandler, NotFoundHandler, MiddlewareHandler } from 'hono';
2
2
  import { V as Verifier, A as AuthUser } from './auth-DqrXYPCf.js';
3
3
  export { a as AuthenticateOptions, O as ORGANIZATION_AUDIENCE_PREFIX, b as VerifierOptions, c as authenticate, d as bearerToken, e as createVerifier, g as getUser, r as requirePermission, f as requireRole, u as userFromClaims, v as verifierFromEnv } from './auth-DqrXYPCf.js';
4
- import { D as Database } from './db-CWKXPFWA.js';
5
- export { A as APP_ID_PATTERN, a as APP_NAME_PATTERN, g as generateAppId, i as isUuid, b as isValidAppId, c as isValidAppName, u as uuidv7 } from './db-CWKXPFWA.js';
4
+ import { D as Database } from './db-BmTPWKyI.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-BmTPWKyI.js';
6
6
  import 'jose';
7
7
  import 'drizzle-orm';
8
8
  import 'drizzle-orm/pg-core';
@@ -24,7 +24,7 @@ interface PermissionDefinition {
24
24
  /** Declare the app's permission catalog. Codes must be unique and use `app:resource:action`. */
25
25
  declare function definePermissions<const T extends readonly PermissionDefinition[]>(definitions: T): T;
26
26
 
27
- type Env$1 = Record<string, string | undefined>;
27
+ type Env$2 = Record<string, string | undefined>;
28
28
  /** The parts of the app's package.json the runtime uses. */
29
29
  interface AppManifest {
30
30
  /** URL segment and app code. */
@@ -43,7 +43,7 @@ interface RegistrationOptions {
43
43
  permissions?: readonly PermissionDefinition[];
44
44
  port: number;
45
45
  basePath: string;
46
- env?: Env$1;
46
+ env?: Env$2;
47
47
  fetch?: typeof fetch;
48
48
  /** Attempts before giving up. Registration never blocks startup. */
49
49
  attempts?: number;
@@ -61,7 +61,7 @@ declare function registrationPayload(options: RegistrationOptions): Record<strin
61
61
  */
62
62
  declare function registerApp(options: RegistrationOptions): Promise<boolean>;
63
63
 
64
- type Env = Record<string, string | undefined>;
64
+ type Env$1 = Record<string, string | undefined>;
65
65
  interface CreateAppOptions {
66
66
  /** The app's package.json. `name` and `id` are required. */
67
67
  manifest: AppManifest;
@@ -78,7 +78,7 @@ interface CreateAppOptions {
78
78
  staticDir?: string;
79
79
  /** Token verifier. Defaults to one built from `LOGTO_*`. */
80
80
  verifier?: Verifier;
81
- env?: Env;
81
+ env?: Env$1;
82
82
  }
83
83
  interface RunningApp {
84
84
  port: number;
@@ -94,6 +94,13 @@ interface PlatformApp {
94
94
  publicApi: Hono;
95
95
  /** Routes for other apps, served under `/internal`. The gateway never routes them. */
96
96
  internal: Hono;
97
+ /**
98
+ * Routes that another app calls for its signed-in user, served under
99
+ * `/internal/delegated`. The caller passes the user's token on (`callPlatform`). It is
100
+ * verified here exactly as on `api`, so `getUser`, `requirePermission` and the tenant
101
+ * database work the same. The gateway never routes them.
102
+ */
103
+ delegated: Hono;
97
104
  /** The request handler. Lets the app be the default export for the Vite dev server. */
98
105
  fetch: (request: Request, ...rest: unknown[]) => Response | Promise<Response>;
99
106
  /** The app's database. Opens it and runs migrations on first use. */
@@ -173,6 +180,35 @@ interface Page<T> {
173
180
  declare function parsePage(source: Context | Record<string, string | undefined>): PageParams;
174
181
  declare function pageOf<T>(items: T[], total: number, params: PageParams): Page<T>;
175
182
 
183
+ type Env = Record<string, string | undefined>;
184
+ interface PlatformCall {
185
+ /** Defaults to GET. */
186
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
187
+ /** Sent as the JSON body. */
188
+ body?: unknown;
189
+ /** Added to the address. An entry that is undefined is left out. */
190
+ query?: Record<string, string | number | boolean | undefined>;
191
+ }
192
+ interface PlatformCallOptions {
193
+ env?: Env;
194
+ fetch?: typeof fetch;
195
+ /** Milliseconds to wait for the answer. Defaults to 10 seconds. */
196
+ timeout?: number;
197
+ }
198
+ /**
199
+ * Call the control plane for the user of this request.
200
+ *
201
+ * The request goes to `<PLATFORM_URL>/delegated<path>`, inside the platform's network, with
202
+ * the user's own `Authorization` header. The control plane verifies that token and checks
203
+ * the permission and the tenant itself. This app adds no credential, so the call can do
204
+ * nothing the user may not do.
205
+ *
206
+ * Returns the parsed JSON answer, or null for an empty one. Check its shape before use:
207
+ * the other app is released separately. An error answer is thrown again with the same
208
+ * status, code and message, so the browser sees what the control plane said.
209
+ */
210
+ declare function callPlatform(c: Context, path: string, call?: PlatformCall, options?: PlatformCallOptions): Promise<unknown>;
211
+
176
212
  /** Header that carries the request id in and out. */
177
213
  declare const REQUEST_ID_HEADER = "X-Request-Id";
178
214
  interface RequestContext {
@@ -217,4 +253,4 @@ interface UrlGuardOptions {
217
253
  */
218
254
  declare function assertPublicUrl(input: string | URL, options?: UrlGuardOptions): Promise<URL>;
219
255
 
220
- 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, REQUEST_ID_HEADER, type RegistrationOptions, type RequestContext, type RunningApp, UnauthorizedError, UnsafeUrlError, type UrlGuardOptions, ValidationError, Verifier, assertPublicUrl, coerceRequestId, createApp, definePermissions, errorHandler, getRequestContext, getRequestId, hasPermissions, isReservedAddress, notFoundHandler, pageOf, parsePage, permissionMatches, registerApp, registrationPayload, requestContext, toErrorResponse };
256
+ 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, REQUEST_ID_HEADER, type RegistrationOptions, type RequestContext, type RunningApp, UnauthorizedError, UnsafeUrlError, type UrlGuardOptions, ValidationError, Verifier, assertPublicUrl, callPlatform, coerceRequestId, createApp, definePermissions, errorHandler, getRequestContext, getRequestId, hasPermissions, isReservedAddress, notFoundHandler, pageOf, parsePage, permissionMatches, registerApp, registrationPayload, requestContext, toErrorResponse };
package/dist/index.js CHANGED
@@ -16,7 +16,7 @@ import {
16
16
  requireRole,
17
17
  userFromClaims,
18
18
  verifierFromEnv
19
- } from "./chunk-SVZCJQNB.js";
19
+ } from "./chunk-PIZAN32W.js";
20
20
  import {
21
21
  APP_ID_PATTERN,
22
22
  APP_NAME_PATTERN,
@@ -26,6 +26,7 @@ import {
26
26
  NotFoundError,
27
27
  UnauthorizedError,
28
28
  ValidationError,
29
+ appBasePath,
29
30
  assertValidAppId,
30
31
  errorHandler,
31
32
  generateAppId,
@@ -35,7 +36,7 @@ import {
35
36
  notFoundHandler,
36
37
  toErrorResponse,
37
38
  uuidv7
38
- } from "./chunk-6IYKARAJ.js";
39
+ } from "./chunk-UWDDQH25.js";
39
40
  import {
40
41
  isDevIdentityEnabled
41
42
  } from "./chunk-NMKEVYGN.js";
@@ -136,7 +137,7 @@ function createApp(options) {
136
137
  }
137
138
  assertValidAppId(manifest.id);
138
139
  const basePath = normalizeBasePath(
139
- env.BASE_URL || (env.NODE_ENV === "production" ? `/apps/${manifest.name}/` : "/")
140
+ env.BASE_URL || (env.NODE_ENV === "production" ? appBasePath(manifest.name) : "/")
140
141
  );
141
142
  configureLog({ app: manifest.name, env: env.ENV || env.NODE_ENV || "development" });
142
143
  const databaseOptions = typeof options.database === "object" ? options.database : options.database ? {} : void 0;
@@ -163,14 +164,19 @@ function createApp(options) {
163
164
  }
164
165
  return pending;
165
166
  };
166
- const api = new Hono();
167
- api.use("*", authenticate({ verifier: options.verifier, env }));
168
- if (databaseOptions) {
169
- api.use("*", async (c, next) => {
170
- const { tenantDatabase } = await import("./db.js");
171
- return tenantDatabase(getDatabase)(c, next);
172
- });
173
- }
167
+ const forUsers = () => {
168
+ const router = new Hono();
169
+ router.use("*", authenticate({ verifier: options.verifier, env }));
170
+ if (databaseOptions) {
171
+ router.use("*", async (c, next) => {
172
+ const { tenantDatabase } = await import("./db.js");
173
+ return tenantDatabase(getDatabase)(c, next);
174
+ });
175
+ }
176
+ return router;
177
+ };
178
+ const api = forUsers();
179
+ const delegated = forUsers();
174
180
  const publicApi = new Hono();
175
181
  const internal = new Hono();
176
182
  let built;
@@ -181,6 +187,8 @@ function createApp(options) {
181
187
  root.onError(errorHandler((error) => log.error("Unhandled error", { err: error })));
182
188
  root.notFound(notFoundHandler());
183
189
  root.get("/healthz", (c) => c.json({ status: "ok", app: manifest.name }));
190
+ root.route("/internal/delegated", delegated);
191
+ root.all("/internal/delegated/*", (c) => c.notFound());
184
192
  root.route("/internal", internal);
185
193
  const scoped = new Hono();
186
194
  scoped.get(
@@ -227,6 +235,7 @@ function createApp(options) {
227
235
  api,
228
236
  publicApi,
229
237
  internal,
238
+ delegated,
230
239
  fetch: fetchHandler,
231
240
  database: getDatabase,
232
241
  async start() {
@@ -294,6 +303,81 @@ function pageOf(items, total, params) {
294
303
  return { items, page: params.page, page_size: params.pageSize, total };
295
304
  }
296
305
 
306
+ // src/platform.ts
307
+ function parseJson(text) {
308
+ if (text === "") return null;
309
+ try {
310
+ return JSON.parse(text);
311
+ } catch {
312
+ return void 0;
313
+ }
314
+ }
315
+ function errorBody(value) {
316
+ if (!value || typeof value !== "object") return void 0;
317
+ const { code, message, field } = value;
318
+ if (typeof code !== "string" || typeof message !== "string") return void 0;
319
+ return { code, message, field: typeof field === "string" ? field : void 0 };
320
+ }
321
+ async function callPlatform(c, path2, call = {}, options = {}) {
322
+ const env = options.env ?? process.env;
323
+ const base = env.PLATFORM_URL?.replace(/\/+$/, "");
324
+ if (!base) {
325
+ throw new AppError("The control plane is not configured: set PLATFORM_URL", {
326
+ code: "platform_not_configured",
327
+ status: 503
328
+ });
329
+ }
330
+ if (!path2.startsWith("/") || path2.startsWith("//") || path2.split("/").includes("..")) {
331
+ throw new Error(`callPlatform: the path must start with one "/" and name no "..": ${path2}`);
332
+ }
333
+ const url = new URL(`${base}/delegated${path2}`);
334
+ for (const [name, value] of Object.entries(call.query ?? {})) {
335
+ if (value !== void 0) url.searchParams.set(name, String(value));
336
+ }
337
+ const headers = { Accept: "application/json" };
338
+ const authorization = c.req.header("Authorization");
339
+ if (authorization) headers.Authorization = authorization;
340
+ const requestId = getRequestId();
341
+ if (requestId) headers[REQUEST_ID_HEADER] = requestId;
342
+ const hasBody = call.body !== void 0;
343
+ if (hasBody) headers["Content-Type"] = "application/json";
344
+ let status;
345
+ let answer;
346
+ try {
347
+ const response = await (options.fetch ?? fetch)(url, {
348
+ method: call.method ?? "GET",
349
+ headers,
350
+ body: hasBody ? JSON.stringify(call.body) : void 0,
351
+ signal: AbortSignal.timeout(options.timeout ?? 1e4)
352
+ });
353
+ status = response.status;
354
+ answer = parseJson(await response.text());
355
+ } catch (error) {
356
+ throw new AppError("The control plane cannot be reached", {
357
+ code: "platform_unavailable",
358
+ status: 503,
359
+ cause: error
360
+ });
361
+ }
362
+ if (status >= 200 && status < 300) {
363
+ if (answer === void 0) {
364
+ throw new AppError("The control plane answered with something that is not JSON", {
365
+ code: "platform_error",
366
+ status: 502
367
+ });
368
+ }
369
+ return answer;
370
+ }
371
+ const refused = status < 500 ? errorBody(answer) : void 0;
372
+ if (refused) {
373
+ throw new AppError(refused.message, { code: refused.code, status, field: refused.field });
374
+ }
375
+ throw new AppError(
376
+ status < 500 ? "The control plane refused the request" : "The control plane failed",
377
+ { code: "platform_error", status: status < 500 ? status : 502 }
378
+ );
379
+ }
380
+
297
381
  // src/url-guard.ts
298
382
  import { lookup as dnsLookup } from "dns/promises";
299
383
  import { BlockList, isIP } from "net";
@@ -396,9 +480,11 @@ export {
396
480
  UnauthorizedError,
397
481
  UnsafeUrlError,
398
482
  ValidationError,
483
+ appBasePath,
399
484
  assertPublicUrl,
400
485
  authenticate,
401
486
  bearerToken,
487
+ callPlatform,
402
488
  coerceRequestId,
403
489
  createApp,
404
490
  createVerifier,
package/dist/testing.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createVerifier
3
- } from "./chunk-SVZCJQNB.js";
4
- import "./chunk-6IYKARAJ.js";
3
+ } from "./chunk-PIZAN32W.js";
4
+ import "./chunk-UWDDQH25.js";
5
5
  import "./chunk-NMKEVYGN.js";
6
6
  import "./chunk-ERGI2X5S.js";
7
7
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zjazj/server",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
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",