@zjazj/server 0.0.4 → 0.0.6

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
@@ -37,4 +37,12 @@ Routes go on one of four routers:
37
37
 
38
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
39
 
40
+ Every app also answers `<base>/api/_platform/tenants` and `<base>/api/_platform/support`, which the frame of `@zjazj/web` calls when a platform operator enters a tenant as platform support. They pass the request on to the control plane. An app adds nothing under that prefix.
41
+
42
+ The control plane reads what an app is from `/internal/_platform/manifest` when it publishes the app: name, title, icon, version, commit and permission catalog. `platformManifest()` returns the same object. An app does not register itself when it starts, and adds nothing under `/internal/_platform`.
43
+
44
+ Everything under `/internal` answers only to a caller that reaches the app directly. A request that a proxy passed on, which the headers the proxy adds give away, gets a 404.
45
+
46
+ `tenantTable` and `globalTable` take the table's further indexes and constraints as a fourth argument, written as for Drizzle's `pgTable`. `drizzle-orm` and `postgres` are optional: an app without a database does not install them.
47
+
40
48
  Part of [platform-cli](https://github.com/zjazj/platform-cli). All `@zjazj/*` packages share one version. Install them at the same version.
@@ -13,9 +13,25 @@ interface AuthUser {
13
13
  permissions: string[];
14
14
  /** IANA time zone of the tenant, when the token carries one. */
15
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;
16
21
  /** True only for the local dev identity. */
17
22
  isDev?: boolean;
18
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;
19
35
  /** Organization tokens carry this audience prefix followed by the organization id. */
20
36
  declare const ORGANIZATION_AUDIENCE_PREFIX = "urn:logto:organization:";
21
37
  type VerifyKey = Parameters<typeof jwtVerify>[1];
@@ -62,4 +78,4 @@ declare module 'hono' {
62
78
  }
63
79
  }
64
80
 
65
- export { type AuthUser as A, ORGANIZATION_AUDIENCE_PREFIX as O, 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, userFromClaims as u, verifierFromEnv as v };
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 };
@@ -42,6 +42,12 @@ function definePermissions(definitions) {
42
42
 
43
43
  // src/auth.ts
44
44
  import { createRemoteJWKSet, errors as joseErrors, jwtVerify } from "jose";
45
+ function supportFromClaims(claims) {
46
+ const { support_until: until, support_mode: mode } = claims;
47
+ if (typeof until !== "number" || !Number.isFinite(until)) return void 0;
48
+ if (typeof mode !== "string" || mode === "") return void 0;
49
+ return { until, mode };
50
+ }
45
51
  var ORGANIZATION_AUDIENCE_PREFIX = "urn:logto:organization:";
46
52
  var DEFAULT_ALGORITHMS = ["ES384", "ES256", "RS256"];
47
53
  function strings(value) {
@@ -59,6 +65,7 @@ function userFromClaims(claims) {
59
65
  throw new UnauthorizedError("token has no tenant");
60
66
  }
61
67
  const roles = strings(claims.organization_roles);
68
+ const support = supportFromClaims(claims);
62
69
  return {
63
70
  id: claims.sub,
64
71
  tenantId: tenantId.toLowerCase(),
@@ -66,7 +73,8 @@ function userFromClaims(claims) {
66
73
  username: firstString(claims.username, claims.name, claims.email) ?? claims.sub,
67
74
  roles: roles.length > 0 ? roles : strings(claims.roles),
68
75
  permissions: strings(claims.permissions),
69
- timeZone: firstString(claims.tenant_time_zone)
76
+ timeZone: firstString(claims.tenant_time_zone),
77
+ ...support ? { support } : {}
70
78
  };
71
79
  }
72
80
  function hasOrganizationAudience(audience) {
@@ -169,6 +177,7 @@ export {
169
177
  permissionMatches,
170
178
  hasPermissions,
171
179
  definePermissions,
180
+ supportFromClaims,
172
181
  ORGANIZATION_AUDIENCE_PREFIX,
173
182
  userFromClaims,
174
183
  createVerifier,
@@ -1,7 +1,7 @@
1
1
  import * as drizzle_orm from 'drizzle-orm';
2
- import { BuildColumns } from 'drizzle-orm';
2
+ import { BuildColumns, BuildExtraConfigColumns } from 'drizzle-orm';
3
3
  import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
4
- import { PgDatabase, PgColumnBuilderBase, PgTableWithColumns, PgSchema } from 'drizzle-orm/pg-core';
4
+ import { PgDatabase, PgColumnBuilderBase, PgTableWithColumns, PgTableExtraConfigValue, PgSchema } from 'drizzle-orm/pg-core';
5
5
  import { Context, MiddlewareHandler } from 'hono';
6
6
 
7
7
  /** `name` in package.json: the URL segment and the app code in the registry. */
@@ -111,9 +111,20 @@ declare function tenantColumns(): {
111
111
  /**
112
112
  * Define a table whose rows belong to a tenant. It gets `id`, `tenant_id`, `created_at`
113
113
  * and `updated_at`, an index on `tenant_id`, and row-level security once migrated.
114
+ *
115
+ * `extras` declares further indexes and constraints, as the third argument of Drizzle's
116
+ * `pgTable` does. It gets the tenant columns too, so a value that must be unique inside a
117
+ * tenant is `uniqueIndex('items_tenant_code_key').on(table.tenantId, table.code)`. A unique
118
+ * index without `tenantId` is unique across all tenants, and tells one tenant what another
119
+ * one has.
114
120
  */
115
- declare function tenantTable<TName extends string, TColumns extends Record<string, PgColumnBuilderBase>>(schema: PgSchema<string>, name: TName, columns: TColumns): TenantTable<TName, TColumns>;
121
+ declare function tenantTable<TName extends string, TColumns extends Record<string, PgColumnBuilderBase>>(schema: PgSchema<string>, name: TName, columns: TColumns, extras?: TableExtras<TName, TenantColumnBuilders & TColumns>): TenantTable<TName, TColumns>;
116
122
  type TenantColumnBuilders = ReturnType<typeof tenantColumns>;
123
+ /**
124
+ * Further indexes and constraints of a table: a function that gets the table's columns and
125
+ * returns a list, as in Drizzle's `pgTable`.
126
+ */
127
+ type TableExtras<TName extends string, TColumns extends Record<string, PgColumnBuilderBase>> = (table: BuildExtraConfigColumns<TName, TColumns, 'pg'>) => PgTableExtraConfigValue[];
117
128
  /** A table created by `tenantTable`: the given columns plus the tenant columns. */
118
129
  type TenantTable<TName extends string, TColumns extends Record<string, PgColumnBuilderBase>> = PgTableWithColumns<{
119
130
  name: TName;
@@ -131,7 +142,8 @@ type GlobalTable<TName extends string, TColumns extends Record<string, PgColumnB
131
142
  /**
132
143
  * Define a table shared by all tenants, such as a lookup list. It has no `tenant_id` and
133
144
  * no row-level security. Using this helper states that the table is global on purpose.
145
+ * `extras` declares indexes and constraints, as for `tenantTable`.
134
146
  */
135
- declare function globalTable<TName extends string, TColumns extends Record<string, PgColumnBuilderBase>>(schema: PgSchema<string>, name: TName, columns: TColumns): GlobalTable<TName, TColumns>;
147
+ declare function globalTable<TName extends string, TColumns extends Record<string, PgColumnBuilderBase>>(schema: PgSchema<string>, name: TName, columns: TColumns, extras?: TableExtras<TName, TColumns>): GlobalTable<TName, TColumns>;
136
148
 
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 };
149
+ export { APP_ID_PATTERN as A, type CreateDatabaseOptions as C, type Database as D, type GlobalTable as G, type MigrateOptions as M, type TableExtras as T, APP_NAME_PATTERN as a, appBasePath as b, isValidAppId as c, isValidAppName as d, type Db as e, type TenantTable as f, generateAppId as g, appSchema as h, isUuid as i, applyTenantPolicies as j, createDatabase as k, db as l, globalTable as m, migrate as n, tenantDatabase as o, tenantTable as p, withTenant as q, 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, 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';
4
+ export { C as CreateDatabaseOptions, D as Database, e as Db, G as GlobalTable, M as MigrateOptions, T as TableExtras, f as TenantTable, h as appSchema, j as applyTenantPolicies, k as createDatabase, l as db, m as globalTable, n as migrate, t as tenantColumns, o as tenantDatabase, p as tenantTable, u as uuidv7, w as withAllTenants, q as withTenant } from './db-Dp7BB3Kc.js';
package/dist/db.js CHANGED
@@ -250,14 +250,15 @@ function tenantColumns() {
250
250
  updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow().$onUpdate(() => /* @__PURE__ */ new Date())
251
251
  };
252
252
  }
253
- function tenantTable(schema, name, columns) {
253
+ function tenantTable(schema, name, columns, extras) {
254
254
  return schema.table(name, { ...tenantColumns(), ...columns }, (table) => [
255
255
  // biome-ignore lint/suspicious/noExplicitAny: the generic spread hides the column type
256
- index(`${name}_tenant_id_idx`).on(table.tenantId)
256
+ index(`${name}_tenant_id_idx`).on(table.tenantId),
257
+ ...extras?.(table) ?? []
257
258
  ]);
258
259
  }
259
- function globalTable(schema, name, columns) {
260
- return schema.table(name, columns);
260
+ function globalTable(schema, name, columns, extras) {
261
+ return schema.table(name, columns, extras);
261
262
  }
262
263
  export {
263
264
  appSchema,
package/dist/dev.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as AuthUser } from './auth-DqrXYPCf.js';
1
+ import { A as AuthUser } from './auth-Ckmm4C6y.js';
2
2
  import 'hono';
3
3
  import 'jose';
4
4
 
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { Hono, Context, ErrorHandler, NotFoundHandler, MiddlewareHandler } from 'hono';
2
- import { V as Verifier, A as AuthUser } from './auth-DqrXYPCf.js';
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-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';
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';
6
6
  import 'jose';
7
7
  import 'drizzle-orm';
8
8
  import 'drizzle-orm/pg-core';
@@ -15,7 +15,7 @@ import 'drizzle-orm/pg-core';
15
15
  declare function permissionMatches(granted: ReadonlySet<string>, code: string): boolean;
16
16
  /** True when every required code is covered. An empty requirement is always satisfied. */
17
17
  declare function hasPermissions(granted: Iterable<string>, required: readonly string[]): boolean;
18
- /** One entry of an app's permission catalog, reported to the platform at registration. */
18
+ /** One entry of an app's permission catalog. The control plane reads it from the manifest. */
19
19
  interface PermissionDefinition {
20
20
  code: string;
21
21
  title: string;
@@ -38,34 +38,45 @@ interface AppManifest {
38
38
  icon?: string;
39
39
  };
40
40
  }
41
- interface RegistrationOptions {
41
+ /**
42
+ * What the control plane reads from an app when it publishes it, at
43
+ * `/internal/_platform/manifest`. The field names are those of the `/services/register`
44
+ * body this replaces. The address, port and path are not in it: the control plane decides
45
+ * them itself.
46
+ */
47
+ interface PlatformManifest {
48
+ app_code: string;
49
+ app_id: string;
50
+ name: string;
51
+ description: string | null;
52
+ portal_nav_title: string;
53
+ portal_nav_icon: string | null;
54
+ permission_manifest: {
55
+ code: string;
56
+ title: string;
57
+ description: string | null;
58
+ }[];
59
+ release_version: string | null;
60
+ source_commit: string | null;
61
+ }
62
+ interface PlatformManifestOptions {
42
63
  manifest: AppManifest;
43
64
  permissions?: readonly PermissionDefinition[];
44
- port: number;
45
- basePath: string;
65
+ /** Read for `GIT_SHA`. Defaults to `process.env`. */
46
66
  env?: Env$2;
47
- fetch?: typeof fetch;
48
- /** Attempts before giving up. Registration never blocks startup. */
49
- attempts?: number;
50
- onResult?: (result: {
51
- ok: boolean;
52
- attempt: number;
53
- detail: string;
54
- }) => void;
55
67
  }
56
- /** The payload sent to the platform's `/services/register` endpoint. */
57
- declare function registrationPayload(options: RegistrationOptions): Record<string, unknown>;
58
68
  /**
59
- * Announce the app to the platform. Skipped when `PLATFORM_URL` is not set, which is the
60
- * case in local development. Failures are reported through `onResult` and never thrown.
69
+ * The app's manifest for the control plane. Every app answers it at
70
+ * `/internal/_platform/manifest`. The control plane itself calls it to record its own
71
+ * catalog without calling itself.
61
72
  */
62
- declare function registerApp(options: RegistrationOptions): Promise<boolean>;
73
+ declare function platformManifest(options: PlatformManifestOptions): PlatformManifest;
63
74
 
64
75
  type Env$1 = Record<string, string | undefined>;
65
76
  interface CreateAppOptions {
66
77
  /** The app's package.json. `name` and `id` are required. */
67
78
  manifest: AppManifest;
68
- /** The permission catalog, reported to the platform at registration. */
79
+ /** The permission catalog. The control plane reads it from the app's manifest. */
69
80
  permissions?: readonly PermissionDefinition[];
70
81
  /**
71
82
  * Turn on the tenant database. Each authenticated request then gets a transaction bound
@@ -79,6 +90,8 @@ interface CreateAppOptions {
79
90
  /** Token verifier. Defaults to one built from `LOGTO_*`. */
80
91
  verifier?: Verifier;
81
92
  env?: Env$1;
93
+ /** What the built-in routes call the control plane with. Defaults to `fetch`. For tests. */
94
+ fetch?: typeof fetch;
82
95
  }
83
96
  interface RunningApp {
84
97
  port: number;
@@ -105,7 +118,7 @@ interface PlatformApp {
105
118
  fetch: (request: Request, ...rest: unknown[]) => Response | Promise<Response>;
106
119
  /** The app's database. Opens it and runs migrations on first use. */
107
120
  database(): Promise<Database>;
108
- /** Migrate, listen, and register with the platform. Call it from the production entry. */
121
+ /** Migrate and listen. Call it from the production entry. */
109
122
  start(): Promise<RunningApp>;
110
123
  }
111
124
  /**
@@ -253,4 +266,4 @@ interface UrlGuardOptions {
253
266
  */
254
267
  declare function assertPublicUrl(input: string | URL, options?: UrlGuardOptions): Promise<URL>;
255
268
 
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 };
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 };
package/dist/index.js CHANGED
@@ -14,9 +14,10 @@ import {
14
14
  permissionMatches,
15
15
  requirePermission,
16
16
  requireRole,
17
+ supportFromClaims,
17
18
  userFromClaims,
18
19
  verifierFromEnv
19
- } from "./chunk-PIZAN32W.js";
20
+ } from "./chunk-YSHW7Q4H.js";
20
21
  import {
21
22
  APP_ID_PATTERN,
22
23
  APP_NAME_PATTERN,
@@ -55,22 +56,17 @@ import { serve } from "@hono/node-server";
55
56
  import { serveStatic } from "@hono/node-server/serve-static";
56
57
  import { Hono } from "hono";
57
58
 
58
- // src/registry.ts
59
- import { hostname } from "os";
60
- function registrationPayload(options) {
59
+ // src/manifest.ts
60
+ function platformManifest(options) {
61
61
  const env = options.env ?? process.env;
62
62
  const { manifest } = options;
63
+ const title = manifest.platform?.title ?? manifest.name;
63
64
  return {
64
65
  app_code: manifest.name,
65
66
  app_id: manifest.id,
66
- name: manifest.platform?.title ?? manifest.name,
67
+ name: title,
67
68
  description: manifest.description ?? null,
68
- service_endpoint: env.ADVERTISED_ENDPOINT || `http://${hostname()}:${options.port}`,
69
- container_port: options.port,
70
- health_path: "/healthz",
71
- surface_type: "standalone",
72
- route_base: options.basePath || "/",
73
- portal_nav_title: manifest.platform?.title ?? manifest.name,
69
+ portal_nav_title: title,
74
70
  portal_nav_icon: manifest.platform?.icon ?? null,
75
71
  permission_manifest: (options.permissions ?? []).map((permission) => ({
76
72
  code: permission.code,
@@ -81,40 +77,80 @@ function registrationPayload(options) {
81
77
  source_commit: env.GIT_SHA || null
82
78
  };
83
79
  }
84
- var delay = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
85
- async function registerApp(options) {
80
+
81
+ // src/platform.ts
82
+ function parseJson(text) {
83
+ if (text === "") return null;
84
+ try {
85
+ return JSON.parse(text);
86
+ } catch {
87
+ return void 0;
88
+ }
89
+ }
90
+ function errorBody(value) {
91
+ if (!value || typeof value !== "object") return void 0;
92
+ const { code, message, field } = value;
93
+ if (typeof code !== "string" || typeof message !== "string") return void 0;
94
+ return { code, message, field: typeof field === "string" ? field : void 0 };
95
+ }
96
+ async function callPlatform(c, path2, call = {}, options = {}) {
86
97
  const env = options.env ?? process.env;
87
- const platformUrl = env.PLATFORM_URL?.replace(/\/+$/, "");
88
- if (!platformUrl) return false;
89
- const request = options.fetch ?? fetch;
90
- const attempts = options.attempts ?? 5;
91
- const body = JSON.stringify(registrationPayload(options));
92
- for (let attempt = 1; attempt <= attempts; attempt += 1) {
93
- try {
94
- const response = await request(`${platformUrl}/api/v1/services/register`, {
95
- method: "POST",
96
- headers: {
97
- "Content-Type": "application/json",
98
- ...env.SERVICE_REGISTRATION_TOKEN ? { Authorization: `Bearer ${env.SERVICE_REGISTRATION_TOKEN}` } : {}
99
- },
100
- body
101
- });
102
- if (response.ok) {
103
- options.onResult?.({ ok: true, attempt, detail: `registered (${response.status})` });
104
- return true;
105
- }
106
- options.onResult?.({ ok: false, attempt, detail: `platform answered ${response.status}` });
107
- if (response.status >= 400 && response.status < 500) return false;
108
- } catch (error) {
109
- options.onResult?.({
110
- ok: false,
111
- attempt,
112
- detail: error instanceof Error ? error.message : String(error)
98
+ const base = env.PLATFORM_URL?.replace(/\/+$/, "");
99
+ if (!base) {
100
+ throw new AppError("The control plane is not configured: set PLATFORM_URL", {
101
+ code: "platform_not_configured",
102
+ status: 503
103
+ });
104
+ }
105
+ if (!path2.startsWith("/") || path2.startsWith("//") || path2.split("/").includes("..")) {
106
+ throw new Error(`callPlatform: the path must start with one "/" and name no "..": ${path2}`);
107
+ }
108
+ const url = new URL(`${base}/delegated${path2}`);
109
+ for (const [name, value] of Object.entries(call.query ?? {})) {
110
+ if (value !== void 0) url.searchParams.set(name, String(value));
111
+ }
112
+ const headers = { Accept: "application/json" };
113
+ const authorization = c.req.header("Authorization");
114
+ if (authorization) headers.Authorization = authorization;
115
+ const requestId = getRequestId();
116
+ if (requestId) headers[REQUEST_ID_HEADER] = requestId;
117
+ const hasBody = call.body !== void 0;
118
+ if (hasBody) headers["Content-Type"] = "application/json";
119
+ let status;
120
+ let answer;
121
+ try {
122
+ const response = await (options.fetch ?? fetch)(url, {
123
+ method: call.method ?? "GET",
124
+ headers,
125
+ body: hasBody ? JSON.stringify(call.body) : void 0,
126
+ signal: AbortSignal.timeout(options.timeout ?? 1e4)
127
+ });
128
+ status = response.status;
129
+ answer = parseJson(await response.text());
130
+ } catch (error) {
131
+ throw new AppError("The control plane cannot be reached", {
132
+ code: "platform_unavailable",
133
+ status: 503,
134
+ cause: error
135
+ });
136
+ }
137
+ if (status >= 200 && status < 300) {
138
+ if (answer === void 0) {
139
+ throw new AppError("The control plane answered with something that is not JSON", {
140
+ code: "platform_error",
141
+ status: 502
113
142
  });
114
143
  }
115
- if (attempt < attempts) await delay(Math.min(1e3 * 2 ** (attempt - 1), 15e3));
144
+ return answer;
145
+ }
146
+ const refused = status < 500 ? errorBody(answer) : void 0;
147
+ if (refused) {
148
+ throw new AppError(refused.message, { code: refused.code, status, field: refused.field });
116
149
  }
117
- return false;
150
+ throw new AppError(
151
+ status < 500 ? "The control plane refused the request" : "The control plane failed",
152
+ { code: "platform_error", status: status < 500 ? status : 502 }
153
+ );
118
154
  }
119
155
 
120
156
  // src/app.ts
@@ -124,6 +160,24 @@ function databaseCache() {
124
160
  holder[DATABASES] ??= /* @__PURE__ */ new Map();
125
161
  return holder[DATABASES];
126
162
  }
163
+ var PROXY_HEADERS = [
164
+ "forwarded",
165
+ "via",
166
+ "x-forwarded-for",
167
+ "x-forwarded-host",
168
+ "x-forwarded-port",
169
+ "x-forwarded-proto",
170
+ "x-forwarded-server",
171
+ "x-real-ip"
172
+ ];
173
+ var internalCallersOnly = async (c, next) => {
174
+ const header = PROXY_HEADERS.find((name) => c.req.header(name) !== void 0);
175
+ if (header) {
176
+ log.warn("Refused an internal route to a request that came through a proxy", { header });
177
+ return c.notFound();
178
+ }
179
+ await next();
180
+ };
127
181
  function normalizeBasePath(value) {
128
182
  const trimmed = (value ?? "/").trim().replace(/\/+$/, "");
129
183
  if (trimmed === "") return "";
@@ -179,6 +233,33 @@ function createApp(options) {
179
233
  const delegated = forUsers();
180
234
  const publicApi = new Hono();
181
235
  const internal = new Hono();
236
+ const platformRoutes = new Hono();
237
+ platformRoutes.use("*", authenticate({ verifier: options.verifier, env }));
238
+ const toPlatform = { env, fetch: options.fetch };
239
+ platformRoutes.get("/tenants", async (c) => {
240
+ const { q, page, page_size: pageSize } = c.req.query();
241
+ const query = { q, page, page_size: pageSize };
242
+ return c.json(await callPlatform(c, "/support/tenants", { query }, toPlatform));
243
+ });
244
+ platformRoutes.get(
245
+ "/support",
246
+ async (c) => c.json(await callPlatform(c, "/support/sessions/current", {}, toPlatform))
247
+ );
248
+ platformRoutes.post("/support", async (c) => {
249
+ const body = await c.req.json().catch(() => ({ tenant_id: void 0 }));
250
+ if (!isUuid(body.tenant_id)) throw new ValidationError("tenant_id must be a UUID", "tenant_id");
251
+ const session = await callPlatform(
252
+ c,
253
+ "/support/sessions",
254
+ { method: "POST", body: { tenant_id: body.tenant_id } },
255
+ toPlatform
256
+ );
257
+ return c.json(session, 201);
258
+ });
259
+ platformRoutes.delete("/support", async (c) => {
260
+ await callPlatform(c, "/support/sessions/current", { method: "DELETE" }, toPlatform);
261
+ return c.body(null, 204);
262
+ });
182
263
  let built;
183
264
  const build = () => {
184
265
  const root = new Hono();
@@ -187,6 +268,12 @@ function createApp(options) {
187
268
  root.onError(errorHandler((error) => log.error("Unhandled error", { err: error })));
188
269
  root.notFound(notFoundHandler());
189
270
  root.get("/healthz", (c) => c.json({ status: "ok", app: manifest.name }));
271
+ root.use("/internal/*", internalCallersOnly);
272
+ root.get(
273
+ "/internal/_platform/manifest",
274
+ (c) => c.json(platformManifest({ manifest, permissions: options.permissions, env }))
275
+ );
276
+ root.all("/internal/_platform/*", (c) => c.notFound());
190
277
  root.route("/internal/delegated", delegated);
191
278
  root.all("/internal/delegated/*", (c) => c.notFound());
192
279
  root.route("/internal", internal);
@@ -202,6 +289,7 @@ function createApp(options) {
202
289
  })
203
290
  );
204
291
  scoped.route("/api/public", publicApi);
292
+ scoped.route("/api/_platform", platformRoutes);
205
293
  scoped.route("/api", api);
206
294
  scoped.all("/api/*", (c) => c.notFound());
207
295
  const staticDir = path.resolve(options.staticDir ?? "dist/client");
@@ -247,19 +335,6 @@ function createApp(options) {
247
335
  if (isDevIdentityEnabled(env)) {
248
336
  log.warn("ENV=dev: no token is verified and every request is the dev identity");
249
337
  }
250
- if (!isDevIdentityEnabled(env)) {
251
- void registerApp({
252
- manifest,
253
- permissions: options.permissions,
254
- port,
255
- basePath,
256
- env,
257
- onResult: (result) => {
258
- if (result.ok) log.info("Registered with the platform", result);
259
- else log.warn("Registration with the platform failed", result);
260
- }
261
- });
262
- }
263
338
  const close = async () => {
264
339
  await new Promise((resolve2) => server.close(() => resolve2()));
265
340
  if (databaseOptions) {
@@ -303,81 +378,6 @@ function pageOf(items, total, params) {
303
378
  return { items, page: params.page, page_size: params.pageSize, total };
304
379
  }
305
380
 
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
-
381
381
  // src/url-guard.ts
382
382
  import { lookup as dnsLookup } from "dns/promises";
383
383
  import { BlockList, isIP } from "net";
@@ -430,8 +430,8 @@ function isReservedAddress(address) {
430
430
  function envAllowList() {
431
431
  return (process.env.URL_GUARD_ALLOW_HOSTS ?? "").split(",").map((host) => host.trim().toLowerCase()).filter(Boolean);
432
432
  }
433
- async function resolve(hostname2) {
434
- const records = await dnsLookup(hostname2, { all: true });
433
+ async function resolve(hostname) {
434
+ const records = await dnsLookup(hostname, { all: true });
435
435
  return records.map((record) => record.address);
436
436
  }
437
437
  async function assertPublicUrl(input, options = {}) {
@@ -444,19 +444,19 @@ async function assertPublicUrl(input, options = {}) {
444
444
  if (url.protocol !== "http:" && url.protocol !== "https:") {
445
445
  throw new UnsafeUrlError("URL must use http or https");
446
446
  }
447
- const hostname2 = url.hostname.replace(/^\[|\]$/g, "").toLowerCase();
448
- if (!hostname2) throw new UnsafeUrlError("URL has no host");
447
+ const hostname = url.hostname.replace(/^\[|\]$/g, "").toLowerCase();
448
+ if (!hostname) throw new UnsafeUrlError("URL has no host");
449
449
  const allowed = [
450
450
  ...(options.allowHosts ?? []).map((host) => host.toLowerCase()),
451
451
  ...envAllowList()
452
452
  ];
453
- if (allowed.includes(hostname2)) return url;
453
+ if (allowed.includes(hostname)) return url;
454
454
  let addresses;
455
- if (isIP(hostname2)) {
456
- addresses = [hostname2];
455
+ if (isIP(hostname)) {
456
+ addresses = [hostname];
457
457
  } else {
458
458
  try {
459
- addresses = await (options.lookup ?? resolve)(hostname2);
459
+ addresses = await (options.lookup ?? resolve)(hostname);
460
460
  } catch {
461
461
  throw new UnsafeUrlError("URL host cannot be resolved");
462
462
  }
@@ -503,11 +503,11 @@ export {
503
503
  pageOf,
504
504
  parsePage,
505
505
  permissionMatches,
506
- registerApp,
507
- registrationPayload,
506
+ platformManifest,
508
507
  requestContext,
509
508
  requirePermission,
510
509
  requireRole,
510
+ supportFromClaims,
511
511
  toErrorResponse,
512
512
  userFromClaims,
513
513
  uuidv7,
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { V as Verifier } from './auth-DqrXYPCf.js';
1
+ import { V as Verifier } from './auth-Ckmm4C6y.js';
2
2
  import 'hono';
3
3
  import 'jose';
4
4
 
package/dist/testing.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createVerifier
3
- } from "./chunk-PIZAN32W.js";
3
+ } from "./chunk-YSHW7Q4H.js";
4
4
  import "./chunk-UWDDQH25.js";
5
5
  import "./chunk-NMKEVYGN.js";
6
6
  import "./chunk-ERGI2X5S.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zjazj/server",
3
- "version": "0.0.4",
3
+ "version": "0.0.6",
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",