@zjazj/server 0.0.2 → 0.0.3

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.
package/dist/index.d.ts CHANGED
@@ -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
@@ -163,14 +163,19 @@ function createApp(options) {
163
163
  }
164
164
  return pending;
165
165
  };
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
- }
166
+ const forUsers = () => {
167
+ const router = new Hono();
168
+ router.use("*", authenticate({ verifier: options.verifier, env }));
169
+ if (databaseOptions) {
170
+ router.use("*", async (c, next) => {
171
+ const { tenantDatabase } = await import("./db.js");
172
+ return tenantDatabase(getDatabase)(c, next);
173
+ });
174
+ }
175
+ return router;
176
+ };
177
+ const api = forUsers();
178
+ const delegated = forUsers();
174
179
  const publicApi = new Hono();
175
180
  const internal = new Hono();
176
181
  let built;
@@ -181,6 +186,8 @@ function createApp(options) {
181
186
  root.onError(errorHandler((error) => log.error("Unhandled error", { err: error })));
182
187
  root.notFound(notFoundHandler());
183
188
  root.get("/healthz", (c) => c.json({ status: "ok", app: manifest.name }));
189
+ root.route("/internal/delegated", delegated);
190
+ root.all("/internal/delegated/*", (c) => c.notFound());
184
191
  root.route("/internal", internal);
185
192
  const scoped = new Hono();
186
193
  scoped.get(
@@ -227,6 +234,7 @@ function createApp(options) {
227
234
  api,
228
235
  publicApi,
229
236
  internal,
237
+ delegated,
230
238
  fetch: fetchHandler,
231
239
  database: getDatabase,
232
240
  async start() {
@@ -294,6 +302,81 @@ function pageOf(items, total, params) {
294
302
  return { items, page: params.page, page_size: params.pageSize, total };
295
303
  }
296
304
 
305
+ // src/platform.ts
306
+ function parseJson(text) {
307
+ if (text === "") return null;
308
+ try {
309
+ return JSON.parse(text);
310
+ } catch {
311
+ return void 0;
312
+ }
313
+ }
314
+ function errorBody(value) {
315
+ if (!value || typeof value !== "object") return void 0;
316
+ const { code, message, field } = value;
317
+ if (typeof code !== "string" || typeof message !== "string") return void 0;
318
+ return { code, message, field: typeof field === "string" ? field : void 0 };
319
+ }
320
+ async function callPlatform(c, path2, call = {}, options = {}) {
321
+ const env = options.env ?? process.env;
322
+ const base = env.PLATFORM_URL?.replace(/\/+$/, "");
323
+ if (!base) {
324
+ throw new AppError("The control plane is not configured: set PLATFORM_URL", {
325
+ code: "platform_not_configured",
326
+ status: 503
327
+ });
328
+ }
329
+ if (!path2.startsWith("/") || path2.startsWith("//") || path2.split("/").includes("..")) {
330
+ throw new Error(`callPlatform: the path must start with one "/" and name no "..": ${path2}`);
331
+ }
332
+ const url = new URL(`${base}/delegated${path2}`);
333
+ for (const [name, value] of Object.entries(call.query ?? {})) {
334
+ if (value !== void 0) url.searchParams.set(name, String(value));
335
+ }
336
+ const headers = { Accept: "application/json" };
337
+ const authorization = c.req.header("Authorization");
338
+ if (authorization) headers.Authorization = authorization;
339
+ const requestId = getRequestId();
340
+ if (requestId) headers[REQUEST_ID_HEADER] = requestId;
341
+ const hasBody = call.body !== void 0;
342
+ if (hasBody) headers["Content-Type"] = "application/json";
343
+ let status;
344
+ let answer;
345
+ try {
346
+ const response = await (options.fetch ?? fetch)(url, {
347
+ method: call.method ?? "GET",
348
+ headers,
349
+ body: hasBody ? JSON.stringify(call.body) : void 0,
350
+ signal: AbortSignal.timeout(options.timeout ?? 1e4)
351
+ });
352
+ status = response.status;
353
+ answer = parseJson(await response.text());
354
+ } catch (error) {
355
+ throw new AppError("The control plane cannot be reached", {
356
+ code: "platform_unavailable",
357
+ status: 503,
358
+ cause: error
359
+ });
360
+ }
361
+ if (status >= 200 && status < 300) {
362
+ if (answer === void 0) {
363
+ throw new AppError("The control plane answered with something that is not JSON", {
364
+ code: "platform_error",
365
+ status: 502
366
+ });
367
+ }
368
+ return answer;
369
+ }
370
+ const refused = status < 500 ? errorBody(answer) : void 0;
371
+ if (refused) {
372
+ throw new AppError(refused.message, { code: refused.code, status, field: refused.field });
373
+ }
374
+ throw new AppError(
375
+ status < 500 ? "The control plane refused the request" : "The control plane failed",
376
+ { code: "platform_error", status: status < 500 ? status : 502 }
377
+ );
378
+ }
379
+
297
380
  // src/url-guard.ts
298
381
  import { lookup as dnsLookup } from "dns/promises";
299
382
  import { BlockList, isIP } from "net";
@@ -399,6 +482,7 @@ export {
399
482
  assertPublicUrl,
400
483
  authenticate,
401
484
  bearerToken,
485
+ callPlatform,
402
486
  coerceRequestId,
403
487
  createApp,
404
488
  createVerifier,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zjazj/server",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
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",