@zjazj/server 0.0.0-stage → 0.0.1

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.
@@ -0,0 +1,130 @@
1
+ import * as drizzle_orm from 'drizzle-orm';
2
+ import { BuildColumns } from 'drizzle-orm';
3
+ import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
4
+ import { PgDatabase, PgColumnBuilderBase, PgTableWithColumns, PgSchema } from 'drizzle-orm/pg-core';
5
+ import { Context, MiddlewareHandler } from 'hono';
6
+
7
+ /** `name` in package.json: the URL segment and the app code in the registry. */
8
+ declare const APP_NAME_PATTERN: RegExp;
9
+ /** `id` in package.json: `app` plus six characters. It is the PostgreSQL schema name. */
10
+ declare const APP_ID_PATTERN: RegExp;
11
+ /** True for a well-formed UUID. Check a path parameter with it before using it in a query. */
12
+ declare function isUuid(value: unknown): value is string;
13
+ declare function isValidAppName(value: unknown): value is string;
14
+ declare function isValidAppId(value: unknown): value is string;
15
+ /** Generate a new app id. Called once, by `platform create`. */
16
+ declare function generateAppId(): string;
17
+ /** A time-ordered UUID (version 7). Use it for primary keys. */
18
+ declare function uuidv7(now?: number): string;
19
+
20
+ type Db = PgDatabase<any, any, any>;
21
+ type Env = Record<string, string | undefined>;
22
+ interface Database {
23
+ /** The app id. Every table of the app lives in the schema with this name. */
24
+ schema: string;
25
+ driver: 'postgres' | 'pglite';
26
+ /**
27
+ * A handle that is NOT bound to a tenant. Row-level security hides every tenant row from
28
+ * it. Use `withTenant` or `withAllTenants` to read or write tenant data.
29
+ */
30
+ drizzle: Db;
31
+ /** Set when the connection role would bypass row-level security. See `enterScope`. */
32
+ runtimeRole?: string;
33
+ close(): Promise<void>;
34
+ }
35
+ interface CreateDatabaseOptions {
36
+ /** The app id from package.json. */
37
+ schema: string;
38
+ /** PostgreSQL connection string. Defaults to `DATABASE_URL`. */
39
+ url?: string;
40
+ /**
41
+ * Folder of the embedded development database. `memory://` keeps it in memory.
42
+ * Defaults to `PGLITE_DATA_DIR`, then `.data/pg`.
43
+ */
44
+ dataDir?: string;
45
+ env?: Env;
46
+ }
47
+ /**
48
+ * Open the app's database.
49
+ *
50
+ * With a connection string it connects to PostgreSQL. Without one, outside production, it
51
+ * starts an embedded PostgreSQL in `.data/pg` so local development needs no database
52
+ * server. Production always requires `DATABASE_URL`.
53
+ */
54
+ declare function createDatabase(options: CreateDatabaseOptions): Promise<Database>;
55
+ /**
56
+ * Turn on row-level security for every table of the schema that has a `tenant_id` column.
57
+ * Safe to run repeatedly. `migrate` calls it after applying migrations.
58
+ */
59
+ declare function applyTenantPolicies(database: Database): Promise<string[]>;
60
+ interface MigrateOptions {
61
+ /** Folder written by `drizzle-kit generate`. Defaults to `./drizzle`. */
62
+ migrationsFolder?: string;
63
+ /** Stored as the schema comment, so the schema can be told apart from others. */
64
+ appName?: string;
65
+ }
66
+ /**
67
+ * Apply pending migrations, then enforce tenant isolation on every tenant table. On
68
+ * PostgreSQL the run holds an advisory lock, so two instances starting together do not
69
+ * migrate at the same time.
70
+ */
71
+ declare function migrate(database: Database, options?: MigrateOptions): Promise<void>;
72
+ /**
73
+ * Run `fn` in a transaction that can only see and write rows of one tenant. Use it for
74
+ * work outside a request, such as a scheduled endpoint that loops over tenants.
75
+ */
76
+ declare function withTenant<T>(database: Database, tenantId: string, fn: (tx: Db) => Promise<T>): Promise<T>;
77
+ /**
78
+ * Run `fn` in a transaction that sees every tenant. This is the one way around tenant
79
+ * isolation. Use it only for platform-level work such as reports across tenants, and say
80
+ * why in a comment at the call site.
81
+ */
82
+ declare function withAllTenants<T>(database: Database, fn: (tx: Db) => Promise<T>): Promise<T>;
83
+ /**
84
+ * Give each authenticated request one transaction bound to the caller's tenant. It commits
85
+ * when the handler returns and rolls back when the handler throws. Read it with `db(c)`.
86
+ */
87
+ declare function tenantDatabase(getDatabase: () => Promise<Database>): MiddlewareHandler;
88
+ /** The request's tenant-bound database. Every query through it is limited to the tenant. */
89
+ declare function db(c: Context): Db;
90
+ declare module 'hono' {
91
+ interface ContextVariableMap {
92
+ db: Db;
93
+ }
94
+ }
95
+ /** The app's schema. Pass the `id` from package.json. */
96
+ declare function appSchema(id: string): PgSchema<string>;
97
+ /** Columns every tenant-owned table has. `tenant_id` fills itself from the transaction. */
98
+ declare function tenantColumns(): {
99
+ id: drizzle_orm.HasRuntimeDefault<drizzle_orm.HasDefault<drizzle_orm.IsPrimaryKey<drizzle_orm.NotNull<drizzle_orm_pg_core.PgUUIDBuilderInitial<"id">>>>>;
100
+ tenantId: drizzle_orm.HasDefault<drizzle_orm.NotNull<drizzle_orm_pg_core.PgUUIDBuilderInitial<"tenant_id">>>;
101
+ createdAt: drizzle_orm.HasDefault<drizzle_orm.NotNull<drizzle_orm_pg_core.PgTimestampBuilderInitial<"created_at">>>;
102
+ updatedAt: drizzle_orm.HasDefault<drizzle_orm.HasDefault<drizzle_orm.NotNull<drizzle_orm_pg_core.PgTimestampBuilderInitial<"updated_at">>>>;
103
+ };
104
+ /**
105
+ * Define a table whose rows belong to a tenant. It gets `id`, `tenant_id`, `created_at`
106
+ * and `updated_at`, an index on `tenant_id`, and row-level security once migrated.
107
+ */
108
+ declare function tenantTable<TName extends string, TColumns extends Record<string, PgColumnBuilderBase>>(schema: PgSchema<string>, name: TName, columns: TColumns): TenantTable<TName, TColumns>;
109
+ type TenantColumnBuilders = ReturnType<typeof tenantColumns>;
110
+ /** A table created by `tenantTable`: the given columns plus the tenant columns. */
111
+ type TenantTable<TName extends string, TColumns extends Record<string, PgColumnBuilderBase>> = PgTableWithColumns<{
112
+ name: TName;
113
+ schema: string;
114
+ columns: BuildColumns<TName, TenantColumnBuilders & TColumns, 'pg'>;
115
+ dialect: 'pg';
116
+ }>;
117
+ /** A table created by `globalTable`. */
118
+ type GlobalTable<TName extends string, TColumns extends Record<string, PgColumnBuilderBase>> = PgTableWithColumns<{
119
+ name: TName;
120
+ schema: string;
121
+ columns: BuildColumns<TName, TColumns, 'pg'>;
122
+ dialect: 'pg';
123
+ }>;
124
+ /**
125
+ * Define a table shared by all tenants, such as a lookup list. It has no `tenant_id` and
126
+ * no row-level security. Using this helper states that the table is global on purpose.
127
+ */
128
+ declare function globalTable<TName extends string, TColumns extends Record<string, PgColumnBuilderBase>>(schema: PgSchema<string>, name: TName, columns: TColumns): GlobalTable<TName, TColumns>;
129
+
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 };
package/dist/db.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import 'drizzle-orm';
2
+ import 'drizzle-orm/pg-core';
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';
package/dist/db.js ADDED
@@ -0,0 +1,275 @@
1
+ import {
2
+ AppError,
3
+ UUID_PATTERN,
4
+ assertValidAppId,
5
+ uuidv7
6
+ } from "./chunk-6IYKARAJ.js";
7
+ import "./chunk-ERGI2X5S.js";
8
+
9
+ // src/db.ts
10
+ import { existsSync, mkdirSync } from "fs";
11
+ import path from "path";
12
+ import { sql } from "drizzle-orm";
13
+ import { readMigrationFiles } from "drizzle-orm/migrator";
14
+ import {
15
+ index,
16
+ pgSchema,
17
+ timestamp,
18
+ uuid
19
+ } from "drizzle-orm/pg-core";
20
+ var RUNTIME_ROLE = "platform_app_runtime";
21
+ var MIGRATIONS_TABLE = "__migrations";
22
+ var IDENTIFIER = /^[a-z_][a-z0-9_]*$/;
23
+ function ident(name) {
24
+ if (!IDENTIFIER.test(name)) throw new Error(`Unsafe SQL identifier: ${JSON.stringify(name)}`);
25
+ return `"${name}"`;
26
+ }
27
+ function rowsOf(result) {
28
+ if (Array.isArray(result)) return result;
29
+ const rows = result?.rows;
30
+ return Array.isArray(rows) ? rows : [];
31
+ }
32
+ async function executeEach(handle, statements) {
33
+ for (const statement of statements) await handle.execute(sql.raw(statement));
34
+ }
35
+ async function schemaExists(database) {
36
+ const [row] = rowsOf(
37
+ await database.drizzle.execute(
38
+ sql`select 1 from information_schema.schemata where schema_name = ${database.schema}`
39
+ )
40
+ );
41
+ return row !== void 0;
42
+ }
43
+ var clients = /* @__PURE__ */ new WeakMap();
44
+ async function createDatabase(options) {
45
+ assertValidAppId(options.schema);
46
+ const env = options.env ?? process.env;
47
+ const url = options.url ?? env.DATABASE_URL;
48
+ let database;
49
+ if (url) {
50
+ const { default: postgres } = await import("postgres");
51
+ const { drizzle } = await import("drizzle-orm/postgres-js");
52
+ const client = postgres(url, { max: Number(env.DB_POOL_MAX ?? 10), onnotice: () => {
53
+ } });
54
+ database = {
55
+ schema: options.schema,
56
+ driver: "postgres",
57
+ drizzle: drizzle(client),
58
+ close: () => client.end({ timeout: 5 })
59
+ };
60
+ clients.set(database, client);
61
+ } else {
62
+ if (env.NODE_ENV === "production") {
63
+ throw new Error("DATABASE_URL is required in production");
64
+ }
65
+ const { PGlite } = await import("@electric-sql/pglite");
66
+ const { drizzle } = await import("drizzle-orm/pglite");
67
+ const dataDir = options.dataDir ?? env.PGLITE_DATA_DIR ?? path.resolve(".data/pg");
68
+ if (!dataDir.includes("://")) {
69
+ mkdirSync(path.dirname(path.resolve(dataDir)), { recursive: true });
70
+ }
71
+ const client = new PGlite(dataDir);
72
+ await client.waitReady;
73
+ database = {
74
+ schema: options.schema,
75
+ driver: "pglite",
76
+ drizzle: drizzle(client),
77
+ close: () => client.close()
78
+ };
79
+ clients.set(database, client);
80
+ }
81
+ const [role] = rowsOf(
82
+ await database.drizzle.execute(
83
+ sql`select (rolsuper or rolbypassrls) as bypass from pg_roles where rolname = current_user`
84
+ )
85
+ );
86
+ if (role?.bypass) {
87
+ await database.drizzle.execute(
88
+ sql.raw(
89
+ `do $$ begin
90
+ if not exists (select from pg_roles where rolname = '${RUNTIME_ROLE}') then
91
+ create role ${RUNTIME_ROLE} nologin;
92
+ end if;
93
+ end $$`
94
+ )
95
+ );
96
+ database.runtimeRole = RUNTIME_ROLE;
97
+ }
98
+ return database;
99
+ }
100
+ var POLICY = `current_setting('app.tenant_scope', true) = 'all'
101
+ or tenant_id = nullif(current_setting('app.tenant_id', true), '')::uuid`;
102
+ async function applyTenantPolicies(database) {
103
+ const schema = ident(database.schema);
104
+ const tables = rowsOf(
105
+ await database.drizzle.execute(
106
+ sql`select c.table_name
107
+ from information_schema.columns c
108
+ join information_schema.tables t
109
+ on t.table_schema = c.table_schema and t.table_name = c.table_name
110
+ where c.table_schema = ${database.schema}
111
+ and c.column_name = 'tenant_id'
112
+ and t.table_type = 'BASE TABLE'
113
+ order by c.table_name`
114
+ )
115
+ ).map((row) => row.table_name);
116
+ for (const name of tables) {
117
+ const table = `${schema}.${ident(name)}`;
118
+ await executeEach(database.drizzle, [
119
+ `alter table ${table} enable row level security`,
120
+ `alter table ${table} force row level security`,
121
+ `drop policy if exists tenant_isolation on ${table}`,
122
+ `create policy tenant_isolation on ${table} using (${POLICY}) with check (${POLICY})`
123
+ ]);
124
+ }
125
+ if (database.runtimeRole && await schemaExists(database)) {
126
+ await executeEach(database.drizzle, [
127
+ `grant usage on schema ${schema} to ${RUNTIME_ROLE}`,
128
+ `grant select, insert, update, delete on all tables in schema ${schema} to ${RUNTIME_ROLE}`
129
+ ]);
130
+ }
131
+ return tables;
132
+ }
133
+ async function applyMigrations(database, folder) {
134
+ const schema = ident(database.schema);
135
+ const table = `${schema}.${ident(MIGRATIONS_TABLE)}`;
136
+ const migrations = readMigrationFiles({ migrationsFolder: folder });
137
+ const createsOwnSchema = new RegExp(
138
+ String.raw`^\s*create\s+schema\s+(if\s+not\s+exists\s+)?"?` + database.schema + String.raw`"?\s*;?\s*$`,
139
+ "i"
140
+ );
141
+ await executeEach(database.drizzle, [
142
+ `create schema if not exists ${schema}`,
143
+ `create table if not exists ${table} (id serial primary key, hash text not null, created_at bigint)`
144
+ ]);
145
+ const [last] = rowsOf(
146
+ await database.drizzle.execute(
147
+ sql.raw(`select created_at from ${table} order by created_at desc limit 1`)
148
+ )
149
+ );
150
+ const appliedUntil = last ? Number(last.created_at) : -1;
151
+ for (const migration of migrations) {
152
+ if (migration.folderMillis <= appliedUntil) continue;
153
+ await database.drizzle.transaction(async (tx) => {
154
+ for (const statement of migration.sql) {
155
+ if (!statement.trim() || createsOwnSchema.test(statement)) continue;
156
+ await tx.execute(sql.raw(statement));
157
+ }
158
+ await tx.execute(
159
+ sql`insert into ${sql.raw(table)} (hash, created_at) values (${migration.hash}, ${migration.folderMillis})`
160
+ );
161
+ });
162
+ }
163
+ }
164
+ async function migrate(database, options = {}) {
165
+ const folder = options.migrationsFolder ?? path.resolve("drizzle");
166
+ const hasMigrations = existsSync(path.join(folder, "meta", "_journal.json"));
167
+ const run = async () => {
168
+ if (hasMigrations) await applyMigrations(database, folder);
169
+ await applyTenantPolicies(database);
170
+ if (options.appName && await schemaExists(database)) {
171
+ const comment = `app: ${options.appName}`.replaceAll("'", "''");
172
+ await database.drizzle.execute(
173
+ sql.raw(`comment on schema ${ident(database.schema)} is '${comment}'`)
174
+ );
175
+ }
176
+ };
177
+ if (database.driver !== "postgres") return run();
178
+ const client = clients.get(database);
179
+ const reserved = await client.reserve();
180
+ try {
181
+ await reserved`select pg_advisory_lock(hashtext(${database.schema}))`;
182
+ await run();
183
+ } finally {
184
+ await reserved`select pg_advisory_unlock(hashtext(${database.schema}))`.catch(() => {
185
+ });
186
+ reserved.release();
187
+ }
188
+ }
189
+ async function enterScope(tx, database, scope) {
190
+ if (database.runtimeRole) {
191
+ await tx.execute(sql`select set_config('role', ${database.runtimeRole}, true)`);
192
+ }
193
+ if (scope === "all") {
194
+ await tx.execute(sql`select set_config('app.tenant_scope', 'all', true)`);
195
+ } else {
196
+ await tx.execute(sql`select set_config('app.tenant_id', ${scope.tenantId}, true)`);
197
+ }
198
+ }
199
+ function withTenant(database, tenantId, fn) {
200
+ if (!UUID_PATTERN.test(tenantId)) {
201
+ throw new AppError("Tenant id is not a UUID", { code: "invalid_tenant", status: 500 });
202
+ }
203
+ return database.drizzle.transaction(async (tx) => {
204
+ await enterScope(tx, database, { tenantId });
205
+ return fn(tx);
206
+ });
207
+ }
208
+ function withAllTenants(database, fn) {
209
+ return database.drizzle.transaction(async (tx) => {
210
+ await enterScope(tx, database, "all");
211
+ return fn(tx);
212
+ });
213
+ }
214
+ var ROLLBACK = /* @__PURE__ */ Symbol("rollback");
215
+ function tenantDatabase(getDatabase) {
216
+ return async (c, next) => {
217
+ const user = c.get("user");
218
+ if (!user) return next();
219
+ const database = await getDatabase();
220
+ try {
221
+ await withTenant(database, user.tenantId, async (tx) => {
222
+ c.set("db", tx);
223
+ await next();
224
+ if (c.error) throw ROLLBACK;
225
+ });
226
+ } catch (error) {
227
+ if (error !== ROLLBACK) throw error;
228
+ }
229
+ };
230
+ }
231
+ function db(c) {
232
+ const handle = c.get("db");
233
+ if (!handle) {
234
+ throw new AppError(
235
+ "No tenant database on this request. Enable `database` in createApp and use an authenticated route.",
236
+ { code: "database_unavailable", status: 500 }
237
+ );
238
+ }
239
+ return handle;
240
+ }
241
+ function appSchema(id) {
242
+ assertValidAppId(id);
243
+ return pgSchema(id);
244
+ }
245
+ function tenantColumns() {
246
+ return {
247
+ id: uuid("id").primaryKey().$defaultFn(() => uuidv7()),
248
+ tenantId: uuid("tenant_id").notNull().default(sql`nullif(current_setting('app.tenant_id', true), '')::uuid`),
249
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
250
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow().$onUpdate(() => /* @__PURE__ */ new Date())
251
+ };
252
+ }
253
+ function tenantTable(schema, name, columns) {
254
+ return schema.table(name, { ...tenantColumns(), ...columns }, (table) => [
255
+ // biome-ignore lint/suspicious/noExplicitAny: the generic spread hides the column type
256
+ index(`${name}_tenant_id_idx`).on(table.tenantId)
257
+ ]);
258
+ }
259
+ function globalTable(schema, name, columns) {
260
+ return schema.table(name, columns);
261
+ }
262
+ export {
263
+ appSchema,
264
+ applyTenantPolicies,
265
+ createDatabase,
266
+ db,
267
+ globalTable,
268
+ migrate,
269
+ tenantColumns,
270
+ tenantDatabase,
271
+ tenantTable,
272
+ uuidv7,
273
+ withAllTenants,
274
+ withTenant
275
+ };
package/dist/dev.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ import { A as AuthUser } from './auth-DqrXYPCf.js';
2
+ import 'hono';
3
+ import 'jose';
4
+
5
+ type Env = Record<string, string | undefined>;
6
+ /** Tenant used by the dev identity unless `DEV_TENANT_ID` overrides it. */
7
+ declare const DEFAULT_DEV_TENANT_ID = "0190a000-0000-7000-8000-000000000001";
8
+ /** Dev tokens are not signed. They are accepted only while the dev identity is enabled. */
9
+ declare const DEV_TOKEN_PREFIX = "dev.";
10
+ /**
11
+ * The dev identity is on only when `ENV` is exactly `dev` and the process is not running in
12
+ * production. The comparison is case sensitive on purpose, so a typo in a deployment can
13
+ * never switch verification off.
14
+ */
15
+ declare function isDevIdentityEnabled(env?: Env): boolean;
16
+ /**
17
+ * The identity every request gets in local development. Override parts of it in
18
+ * `.env.local` to exercise tenant isolation and permission checks:
19
+ * `DEV_TENANT_ID`, `DEV_ROLES`, `DEV_PERMISSIONS`, `DEV_USER_ID`, `DEV_USERNAME`.
20
+ */
21
+ declare function devIdentity(env?: Env): AuthUser;
22
+ type DevTokenPayload = Partial<Omit<AuthUser, 'isDev'>>;
23
+ declare function encodeDevToken(user: DevTokenPayload): string;
24
+ declare function decodeDevToken(token: string | undefined): DevTokenPayload | undefined;
25
+ /**
26
+ * Resolve the dev user for a request. A dev token may replace parts of the identity, which
27
+ * lets the browser switch tenant or permissions without restarting the server.
28
+ */
29
+ declare function resolveDevUser(token: string | undefined, env?: Env): AuthUser;
30
+
31
+ export { DEFAULT_DEV_TENANT_ID, DEV_TOKEN_PREFIX, decodeDevToken, devIdentity, encodeDevToken, isDevIdentityEnabled, resolveDevUser };
package/dist/dev.js ADDED
@@ -0,0 +1,18 @@
1
+ import {
2
+ DEFAULT_DEV_TENANT_ID,
3
+ DEV_TOKEN_PREFIX,
4
+ decodeDevToken,
5
+ devIdentity,
6
+ encodeDevToken,
7
+ isDevIdentityEnabled,
8
+ resolveDevUser
9
+ } from "./chunk-NMKEVYGN.js";
10
+ export {
11
+ DEFAULT_DEV_TENANT_ID,
12
+ DEV_TOKEN_PREFIX,
13
+ decodeDevToken,
14
+ devIdentity,
15
+ encodeDevToken,
16
+ isDevIdentityEnabled,
17
+ resolveDevUser
18
+ };
@@ -0,0 +1,220 @@
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-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';
6
+ import 'jose';
7
+ import 'drizzle-orm';
8
+ import 'drizzle-orm/pg-core';
9
+
10
+ /**
11
+ * True when `code` is covered by the granted set: an exact match, a bare `*`, or a granted
12
+ * code whose trailing segments are wildcards, for example `inventory:item:*` or
13
+ * `inventory:*:*` for `inventory:item:read`.
14
+ */
15
+ declare function permissionMatches(granted: ReadonlySet<string>, code: string): boolean;
16
+ /** True when every required code is covered. An empty requirement is always satisfied. */
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. */
19
+ interface PermissionDefinition {
20
+ code: string;
21
+ title: string;
22
+ description?: string;
23
+ }
24
+ /** Declare the app's permission catalog. Codes must be unique and use `app:resource:action`. */
25
+ declare function definePermissions<const T extends readonly PermissionDefinition[]>(definitions: T): T;
26
+
27
+ type Env$1 = Record<string, string | undefined>;
28
+ /** The parts of the app's package.json the runtime uses. */
29
+ interface AppManifest {
30
+ /** URL segment and app code. */
31
+ name: string;
32
+ /** Immutable id. Also the PostgreSQL schema name. */
33
+ id: string;
34
+ version?: string;
35
+ description?: string;
36
+ platform?: {
37
+ title?: string;
38
+ icon?: string;
39
+ };
40
+ }
41
+ interface RegistrationOptions {
42
+ manifest: AppManifest;
43
+ permissions?: readonly PermissionDefinition[];
44
+ port: number;
45
+ basePath: string;
46
+ env?: Env$1;
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
+ }
56
+ /** The payload sent to the platform's `/services/register` endpoint. */
57
+ declare function registrationPayload(options: RegistrationOptions): Record<string, unknown>;
58
+ /**
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.
61
+ */
62
+ declare function registerApp(options: RegistrationOptions): Promise<boolean>;
63
+
64
+ type Env = Record<string, string | undefined>;
65
+ interface CreateAppOptions {
66
+ /** The app's package.json. `name` and `id` are required. */
67
+ manifest: AppManifest;
68
+ /** The permission catalog, reported to the platform at registration. */
69
+ permissions?: readonly PermissionDefinition[];
70
+ /**
71
+ * Turn on the tenant database. Each authenticated request then gets a transaction bound
72
+ * to the caller's tenant, read with `db(c)` from `@zjazj/server/db`.
73
+ */
74
+ database?: boolean | {
75
+ migrationsFolder?: string;
76
+ };
77
+ /** Folder of the built frontend. Defaults to `dist/client` under the working directory. */
78
+ staticDir?: string;
79
+ /** Token verifier. Defaults to one built from `LOGTO_*`. */
80
+ verifier?: Verifier;
81
+ env?: Env;
82
+ }
83
+ interface RunningApp {
84
+ port: number;
85
+ close(): Promise<void>;
86
+ }
87
+ interface PlatformApp {
88
+ manifest: AppManifest;
89
+ /** Mount prefix without a trailing slash. Empty in local development. */
90
+ basePath: string;
91
+ /** Authenticated routes, served under `<basePath>/api`. Export its type for the client. */
92
+ api: Hono;
93
+ /** Routes without authentication, served under `<basePath>/api/public`. */
94
+ publicApi: Hono;
95
+ /** Routes for other apps, served under `/internal`. The gateway never routes them. */
96
+ internal: Hono;
97
+ /** The request handler. Lets the app be the default export for the Vite dev server. */
98
+ fetch: (request: Request, ...rest: unknown[]) => Response | Promise<Response>;
99
+ /** The app's database. Opens it and runs migrations on first use. */
100
+ database(): Promise<Database>;
101
+ /** Migrate, listen, and register with the platform. Call it from the production entry. */
102
+ start(): Promise<RunningApp>;
103
+ }
104
+ /**
105
+ * Assemble a platform app. Add routes to `app.api`, then either export the app as the
106
+ * default export (development) or call `app.start()` (production).
107
+ */
108
+ declare function createApp(options: CreateAppOptions): PlatformApp;
109
+
110
+ /** The body of every error response. */
111
+ interface ErrorBody {
112
+ code: string;
113
+ message: string;
114
+ trace_id?: string;
115
+ field?: string;
116
+ }
117
+ interface AppErrorOptions {
118
+ code?: string;
119
+ status?: number;
120
+ field?: string;
121
+ cause?: unknown;
122
+ }
123
+ /** An error that is safe to show to the caller. Throw it from a route or a service. */
124
+ declare class AppError extends Error {
125
+ readonly code: string;
126
+ readonly status: number;
127
+ readonly field?: string;
128
+ constructor(message: string, options?: AppErrorOptions);
129
+ }
130
+ declare class UnauthorizedError extends AppError {
131
+ constructor(message?: string, options?: AppErrorOptions);
132
+ }
133
+ declare class ForbiddenError extends AppError {
134
+ constructor(message?: string, options?: AppErrorOptions);
135
+ }
136
+ declare class NotFoundError extends AppError {
137
+ constructor(message?: string, options?: AppErrorOptions);
138
+ }
139
+ declare class ConflictError extends AppError {
140
+ constructor(message?: string, options?: AppErrorOptions);
141
+ }
142
+ declare class ValidationError extends AppError {
143
+ constructor(message: string, field?: string, options?: AppErrorOptions);
144
+ }
145
+ /** Convert anything thrown into a status and a body. Unknown errors never leak details. */
146
+ declare function toErrorResponse(error: unknown): {
147
+ status: number;
148
+ body: ErrorBody;
149
+ };
150
+ /** Hono error handler. `onUnexpected` receives errors that were not thrown as `AppError`. */
151
+ declare function errorHandler(onUnexpected?: (error: unknown, c: Context) => void): ErrorHandler;
152
+ declare function notFoundHandler(): NotFoundHandler;
153
+
154
+ declare const DEFAULT_PAGE_SIZE = 20;
155
+ declare const MAX_PAGE_SIZE = 100;
156
+ interface PageParams {
157
+ page: number;
158
+ pageSize: number;
159
+ keyword?: string;
160
+ /** Rows to skip. Pass to `.offset()`. */
161
+ offset: number;
162
+ /** Rows to take. Pass to `.limit()`. */
163
+ limit: number;
164
+ }
165
+ /** The body of every list response. */
166
+ interface Page<T> {
167
+ items: T[];
168
+ page: number;
169
+ page_size: number;
170
+ total: number;
171
+ }
172
+ /** Read `page`, `page_size` and `keyword` from the query string. */
173
+ declare function parsePage(source: Context | Record<string, string | undefined>): PageParams;
174
+ declare function pageOf<T>(items: T[], total: number, params: PageParams): Page<T>;
175
+
176
+ /** Header that carries the request id in and out. */
177
+ declare const REQUEST_ID_HEADER = "X-Request-Id";
178
+ interface RequestContext {
179
+ requestId: string;
180
+ user?: AuthUser;
181
+ }
182
+ /** Keep an inbound request id only when it is well formed. */
183
+ declare function coerceRequestId(value: string | null | undefined): string | undefined;
184
+ /** The context of the request being handled, or undefined outside a request. */
185
+ declare function getRequestContext(): RequestContext | undefined;
186
+ declare function getRequestId(): string | undefined;
187
+ /**
188
+ * Give every request an id: the inbound `X-Request-Id` when valid, otherwise a new one.
189
+ * The id is available through `getRequestId()` anywhere below this middleware and is
190
+ * returned on the response.
191
+ */
192
+ declare function requestContext(): MiddlewareHandler;
193
+ declare module 'hono' {
194
+ interface ContextVariableMap {
195
+ requestId: string;
196
+ }
197
+ }
198
+
199
+ /** Thrown when a URL points somewhere the server must not call. */
200
+ declare class UnsafeUrlError extends AppError {
201
+ constructor(message: string);
202
+ }
203
+ /** True when the address is private, loopback, link-local or otherwise reserved. */
204
+ declare function isReservedAddress(address: string): boolean;
205
+ interface UrlGuardOptions {
206
+ /** Hosts that are allowed even when they resolve to a reserved address. */
207
+ allowHosts?: string[];
208
+ /** Replace the DNS lookup. Meant for tests. */
209
+ lookup?: (hostname: string) => Promise<string[]>;
210
+ }
211
+ /**
212
+ * Check a URL before the server calls it on behalf of a user. Rejects anything that is not
213
+ * http or https and any host that resolves to a private or reserved address.
214
+ *
215
+ * The check and the later request resolve the name separately. Do not use this as the only
216
+ * defence where an attacker controls DNS.
217
+ */
218
+ declare function assertPublicUrl(input: string | URL, options?: UrlGuardOptions): Promise<URL>;
219
+
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 };