@zjazj/server 0.0.5 → 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 +4 -0
- package/dist/{auth-DqrXYPCf.d.ts → auth-Ckmm4C6y.d.ts} +17 -1
- package/dist/{chunk-PIZAN32W.js → chunk-YSHW7Q4H.js} +10 -1
- package/dist/dev.d.ts +1 -1
- package/dist/index.d.ts +35 -22
- package/dist/index.js +120 -139
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -37,6 +37,10 @@ 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
|
+
|
|
40
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.
|
|
41
45
|
|
|
42
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.
|
|
@@ -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,
|
package/dist/dev.d.ts
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Hono, Context, ErrorHandler, NotFoundHandler, MiddlewareHandler } from 'hono';
|
|
2
|
-
import { V as Verifier, A as AuthUser } from './auth-
|
|
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-
|
|
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
4
|
import { D as Database } from './db-Dp7BB3Kc.js';
|
|
5
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';
|
|
@@ -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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
60
|
-
*
|
|
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
|
|
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
|
|
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
|
|
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,
|
|
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-
|
|
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/
|
|
59
|
-
|
|
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:
|
|
67
|
+
name: title,
|
|
67
68
|
description: manifest.description ?? null,
|
|
68
|
-
|
|
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
|
-
|
|
85
|
-
|
|
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
|
|
88
|
-
if (!
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
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
|
-
|
|
144
|
+
return answer;
|
|
116
145
|
}
|
|
117
|
-
|
|
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 });
|
|
149
|
+
}
|
|
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
|
|
@@ -197,6 +233,33 @@ function createApp(options) {
|
|
|
197
233
|
const delegated = forUsers();
|
|
198
234
|
const publicApi = new Hono();
|
|
199
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
|
+
});
|
|
200
263
|
let built;
|
|
201
264
|
const build = () => {
|
|
202
265
|
const root = new Hono();
|
|
@@ -206,6 +269,11 @@ function createApp(options) {
|
|
|
206
269
|
root.notFound(notFoundHandler());
|
|
207
270
|
root.get("/healthz", (c) => c.json({ status: "ok", app: manifest.name }));
|
|
208
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());
|
|
209
277
|
root.route("/internal/delegated", delegated);
|
|
210
278
|
root.all("/internal/delegated/*", (c) => c.notFound());
|
|
211
279
|
root.route("/internal", internal);
|
|
@@ -221,6 +289,7 @@ function createApp(options) {
|
|
|
221
289
|
})
|
|
222
290
|
);
|
|
223
291
|
scoped.route("/api/public", publicApi);
|
|
292
|
+
scoped.route("/api/_platform", platformRoutes);
|
|
224
293
|
scoped.route("/api", api);
|
|
225
294
|
scoped.all("/api/*", (c) => c.notFound());
|
|
226
295
|
const staticDir = path.resolve(options.staticDir ?? "dist/client");
|
|
@@ -266,19 +335,6 @@ function createApp(options) {
|
|
|
266
335
|
if (isDevIdentityEnabled(env)) {
|
|
267
336
|
log.warn("ENV=dev: no token is verified and every request is the dev identity");
|
|
268
337
|
}
|
|
269
|
-
if (!isDevIdentityEnabled(env)) {
|
|
270
|
-
void registerApp({
|
|
271
|
-
manifest,
|
|
272
|
-
permissions: options.permissions,
|
|
273
|
-
port,
|
|
274
|
-
basePath,
|
|
275
|
-
env,
|
|
276
|
-
onResult: (result) => {
|
|
277
|
-
if (result.ok) log.info("Registered with the platform", result);
|
|
278
|
-
else log.warn("Registration with the platform failed", result);
|
|
279
|
-
}
|
|
280
|
-
});
|
|
281
|
-
}
|
|
282
338
|
const close = async () => {
|
|
283
339
|
await new Promise((resolve2) => server.close(() => resolve2()));
|
|
284
340
|
if (databaseOptions) {
|
|
@@ -322,81 +378,6 @@ function pageOf(items, total, params) {
|
|
|
322
378
|
return { items, page: params.page, page_size: params.pageSize, total };
|
|
323
379
|
}
|
|
324
380
|
|
|
325
|
-
// src/platform.ts
|
|
326
|
-
function parseJson(text) {
|
|
327
|
-
if (text === "") return null;
|
|
328
|
-
try {
|
|
329
|
-
return JSON.parse(text);
|
|
330
|
-
} catch {
|
|
331
|
-
return void 0;
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
function errorBody(value) {
|
|
335
|
-
if (!value || typeof value !== "object") return void 0;
|
|
336
|
-
const { code, message, field } = value;
|
|
337
|
-
if (typeof code !== "string" || typeof message !== "string") return void 0;
|
|
338
|
-
return { code, message, field: typeof field === "string" ? field : void 0 };
|
|
339
|
-
}
|
|
340
|
-
async function callPlatform(c, path2, call = {}, options = {}) {
|
|
341
|
-
const env = options.env ?? process.env;
|
|
342
|
-
const base = env.PLATFORM_URL?.replace(/\/+$/, "");
|
|
343
|
-
if (!base) {
|
|
344
|
-
throw new AppError("The control plane is not configured: set PLATFORM_URL", {
|
|
345
|
-
code: "platform_not_configured",
|
|
346
|
-
status: 503
|
|
347
|
-
});
|
|
348
|
-
}
|
|
349
|
-
if (!path2.startsWith("/") || path2.startsWith("//") || path2.split("/").includes("..")) {
|
|
350
|
-
throw new Error(`callPlatform: the path must start with one "/" and name no "..": ${path2}`);
|
|
351
|
-
}
|
|
352
|
-
const url = new URL(`${base}/delegated${path2}`);
|
|
353
|
-
for (const [name, value] of Object.entries(call.query ?? {})) {
|
|
354
|
-
if (value !== void 0) url.searchParams.set(name, String(value));
|
|
355
|
-
}
|
|
356
|
-
const headers = { Accept: "application/json" };
|
|
357
|
-
const authorization = c.req.header("Authorization");
|
|
358
|
-
if (authorization) headers.Authorization = authorization;
|
|
359
|
-
const requestId = getRequestId();
|
|
360
|
-
if (requestId) headers[REQUEST_ID_HEADER] = requestId;
|
|
361
|
-
const hasBody = call.body !== void 0;
|
|
362
|
-
if (hasBody) headers["Content-Type"] = "application/json";
|
|
363
|
-
let status;
|
|
364
|
-
let answer;
|
|
365
|
-
try {
|
|
366
|
-
const response = await (options.fetch ?? fetch)(url, {
|
|
367
|
-
method: call.method ?? "GET",
|
|
368
|
-
headers,
|
|
369
|
-
body: hasBody ? JSON.stringify(call.body) : void 0,
|
|
370
|
-
signal: AbortSignal.timeout(options.timeout ?? 1e4)
|
|
371
|
-
});
|
|
372
|
-
status = response.status;
|
|
373
|
-
answer = parseJson(await response.text());
|
|
374
|
-
} catch (error) {
|
|
375
|
-
throw new AppError("The control plane cannot be reached", {
|
|
376
|
-
code: "platform_unavailable",
|
|
377
|
-
status: 503,
|
|
378
|
-
cause: error
|
|
379
|
-
});
|
|
380
|
-
}
|
|
381
|
-
if (status >= 200 && status < 300) {
|
|
382
|
-
if (answer === void 0) {
|
|
383
|
-
throw new AppError("The control plane answered with something that is not JSON", {
|
|
384
|
-
code: "platform_error",
|
|
385
|
-
status: 502
|
|
386
|
-
});
|
|
387
|
-
}
|
|
388
|
-
return answer;
|
|
389
|
-
}
|
|
390
|
-
const refused = status < 500 ? errorBody(answer) : void 0;
|
|
391
|
-
if (refused) {
|
|
392
|
-
throw new AppError(refused.message, { code: refused.code, status, field: refused.field });
|
|
393
|
-
}
|
|
394
|
-
throw new AppError(
|
|
395
|
-
status < 500 ? "The control plane refused the request" : "The control plane failed",
|
|
396
|
-
{ code: "platform_error", status: status < 500 ? status : 502 }
|
|
397
|
-
);
|
|
398
|
-
}
|
|
399
|
-
|
|
400
381
|
// src/url-guard.ts
|
|
401
382
|
import { lookup as dnsLookup } from "dns/promises";
|
|
402
383
|
import { BlockList, isIP } from "net";
|
|
@@ -449,8 +430,8 @@ function isReservedAddress(address) {
|
|
|
449
430
|
function envAllowList() {
|
|
450
431
|
return (process.env.URL_GUARD_ALLOW_HOSTS ?? "").split(",").map((host) => host.trim().toLowerCase()).filter(Boolean);
|
|
451
432
|
}
|
|
452
|
-
async function resolve(
|
|
453
|
-
const records = await dnsLookup(
|
|
433
|
+
async function resolve(hostname) {
|
|
434
|
+
const records = await dnsLookup(hostname, { all: true });
|
|
454
435
|
return records.map((record) => record.address);
|
|
455
436
|
}
|
|
456
437
|
async function assertPublicUrl(input, options = {}) {
|
|
@@ -463,19 +444,19 @@ async function assertPublicUrl(input, options = {}) {
|
|
|
463
444
|
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
464
445
|
throw new UnsafeUrlError("URL must use http or https");
|
|
465
446
|
}
|
|
466
|
-
const
|
|
467
|
-
if (!
|
|
447
|
+
const hostname = url.hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
|
448
|
+
if (!hostname) throw new UnsafeUrlError("URL has no host");
|
|
468
449
|
const allowed = [
|
|
469
450
|
...(options.allowHosts ?? []).map((host) => host.toLowerCase()),
|
|
470
451
|
...envAllowList()
|
|
471
452
|
];
|
|
472
|
-
if (allowed.includes(
|
|
453
|
+
if (allowed.includes(hostname)) return url;
|
|
473
454
|
let addresses;
|
|
474
|
-
if (isIP(
|
|
475
|
-
addresses = [
|
|
455
|
+
if (isIP(hostname)) {
|
|
456
|
+
addresses = [hostname];
|
|
476
457
|
} else {
|
|
477
458
|
try {
|
|
478
|
-
addresses = await (options.lookup ?? resolve)(
|
|
459
|
+
addresses = await (options.lookup ?? resolve)(hostname);
|
|
479
460
|
} catch {
|
|
480
461
|
throw new UnsafeUrlError("URL host cannot be resolved");
|
|
481
462
|
}
|
|
@@ -522,11 +503,11 @@ export {
|
|
|
522
503
|
pageOf,
|
|
523
504
|
parsePage,
|
|
524
505
|
permissionMatches,
|
|
525
|
-
|
|
526
|
-
registrationPayload,
|
|
506
|
+
platformManifest,
|
|
527
507
|
requestContext,
|
|
528
508
|
requirePermission,
|
|
529
509
|
requireRole,
|
|
510
|
+
supportFromClaims,
|
|
530
511
|
toErrorResponse,
|
|
531
512
|
userFromClaims,
|
|
532
513
|
uuidv7,
|
package/dist/testing.d.ts
CHANGED
package/dist/testing.js
CHANGED
package/package.json
CHANGED