@zjazj/server 0.0.9 → 0.0.10

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.
@@ -104,6 +104,11 @@ type ApiKeyKind = 'user' | 'tenant';
104
104
  interface ApiKeyInfo {
105
105
  id: string;
106
106
  kind: ApiKeyKind;
107
+ /**
108
+ * True for a key of the platform's own tenant. Only such a key calls a platform job,
109
+ * which works across tenants.
110
+ */
111
+ platform: boolean;
107
112
  }
108
113
  /**
109
114
  * The answer of `POST /internal/api-keys/verify` on the control plane for a key it
@@ -120,6 +125,8 @@ interface ApiKeyVerification {
120
125
  username?: string;
121
126
  roles?: string[];
122
127
  permissions?: string[];
128
+ /** True when the key's tenant is the platform's own. Anything else counts as false. */
129
+ platform?: boolean;
123
130
  /** How long the answer may be kept. Capped at `MAX_API_KEY_CACHE_SECONDS`. */
124
131
  cache_seconds?: number;
125
132
  }
@@ -62,7 +62,7 @@ function resolveDevKeyUser(key, env = process.env) {
62
62
  ...user,
63
63
  // A tenant key acts as the tenant: its subject is the key, as the control plane says.
64
64
  ...kind === "tenant" && typeof override?.id !== "string" ? { id: "key:dev" } : {},
65
- apiKey: { id: "dev", kind }
65
+ apiKey: { id: "dev", kind, platform: override?.platform === true }
66
66
  };
67
67
  }
68
68
 
@@ -7,12 +7,12 @@ import {
7
7
  createKeyVerifier,
8
8
  isApiKey,
9
9
  refuseApiKeyUnlessAccepted
10
- } from "./chunk-UWTSXBJL.js";
10
+ } from "./chunk-OBKMOVBA.js";
11
11
  import {
12
12
  isDevIdentityEnabled,
13
13
  resolveDevKeyUser,
14
14
  resolveDevUser
15
- } from "./chunk-SLNRMJDM.js";
15
+ } from "./chunk-3X4RSAM6.js";
16
16
  import {
17
17
  getRequestContext
18
18
  } from "./chunk-ERGI2X5S.js";
@@ -40,6 +40,11 @@ function definePermissions(definitions) {
40
40
  if (seen.has(definition.code)) {
41
41
  throw new Error(`Duplicate permission code: ${definition.code}`);
42
42
  }
43
+ if (definition.scope !== void 0 && !["tenant", "platform"].includes(definition.scope)) {
44
+ throw new Error(
45
+ `Invalid scope of ${definition.code}: ${JSON.stringify(definition.scope)}. Use 'tenant' or 'platform'.`
46
+ );
47
+ }
43
48
  seen.add(definition.code);
44
49
  }
45
50
  return definitions;
@@ -160,7 +160,7 @@ function userFromKeyVerification(answer) {
160
160
  roles: strings(fields.roles),
161
161
  permissions: strings(fields.permissions),
162
162
  timeZone: text(fields.tenant_time_zone),
163
- apiKey: { id: keyId, kind }
163
+ apiKey: { id: keyId, kind, platform: fields.platform === true }
164
164
  };
165
165
  }
166
166
  function copyUser(user) {
@@ -0,0 +1,291 @@
1
+ import {
2
+ AppError,
3
+ UUID_PATTERN,
4
+ assertApiKeyAccepted,
5
+ assertValidAppId,
6
+ uuidv7
7
+ } from "./chunk-OBKMOVBA.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
+ await tx.execute(sql`select set_config('app.tenant_scope', 'all', true)`);
155
+ for (const statement of migration.sql) {
156
+ if (!statement.trim() || createsOwnSchema.test(statement)) continue;
157
+ await tx.execute(sql.raw(statement));
158
+ }
159
+ await tx.execute(
160
+ sql`insert into ${sql.raw(table)} (hash, created_at) values (${migration.hash}, ${migration.folderMillis})`
161
+ );
162
+ });
163
+ }
164
+ }
165
+ async function migrate(database, options = {}) {
166
+ const folder = options.migrationsFolder ?? path.resolve("drizzle");
167
+ const hasMigrations = existsSync(path.join(folder, "meta", "_journal.json"));
168
+ const run = async () => {
169
+ if (hasMigrations) await applyMigrations(database, folder);
170
+ await applyTenantPolicies(database);
171
+ if (options.appName && await schemaExists(database)) {
172
+ const comment = `app: ${options.appName}`.replaceAll("'", "''");
173
+ await database.drizzle.execute(
174
+ sql.raw(`comment on schema ${ident(database.schema)} is '${comment}'`)
175
+ );
176
+ }
177
+ };
178
+ if (database.driver !== "postgres") return run();
179
+ const client = clients.get(database);
180
+ const reserved = await client.reserve();
181
+ try {
182
+ await reserved`select pg_advisory_lock(hashtext(${database.schema}))`;
183
+ await run();
184
+ } finally {
185
+ await reserved`select pg_advisory_unlock(hashtext(${database.schema}))`.catch(() => {
186
+ });
187
+ reserved.release();
188
+ }
189
+ }
190
+ async function enterScope(tx, database, scope) {
191
+ if (database.runtimeRole) {
192
+ await tx.execute(sql`select set_config('role', ${database.runtimeRole}, true)`);
193
+ }
194
+ if (scope === "all") {
195
+ await tx.execute(sql`select set_config('app.tenant_scope', 'all', true)`);
196
+ } else {
197
+ await tx.execute(
198
+ sql`select set_config('app.tenant_id', ${scope.tenantId}, true), set_config('app.user_id', ${scope.userId ?? ""}, true)`
199
+ );
200
+ }
201
+ }
202
+ function withTenant(database, tenantId, fn, options = {}) {
203
+ if (!UUID_PATTERN.test(tenantId)) {
204
+ throw new AppError("Tenant id is not a UUID", { code: "invalid_tenant", status: 500 });
205
+ }
206
+ return database.drizzle.transaction(async (tx) => {
207
+ await enterScope(tx, database, { tenantId, userId: options.userId });
208
+ return fn(tx);
209
+ });
210
+ }
211
+ function withAllTenants(database, fn) {
212
+ return database.drizzle.transaction(async (tx) => {
213
+ await enterScope(tx, database, "all");
214
+ return fn(tx);
215
+ });
216
+ }
217
+ var ROLLBACK = /* @__PURE__ */ Symbol("rollback");
218
+ function tenantDatabase(getDatabase) {
219
+ return async (c, next) => {
220
+ const user = c.get("user");
221
+ if (!user) return next();
222
+ const database = await getDatabase();
223
+ try {
224
+ await withTenant(
225
+ database,
226
+ user.tenantId,
227
+ async (tx) => {
228
+ c.set("db", tx);
229
+ await next();
230
+ if (c.error) throw ROLLBACK;
231
+ },
232
+ { userId: user.id }
233
+ );
234
+ } catch (error) {
235
+ if (error !== ROLLBACK) throw error;
236
+ }
237
+ };
238
+ }
239
+ function db(c) {
240
+ assertApiKeyAccepted(c);
241
+ const handle = c.get("db");
242
+ if (!handle && c.get("job")?.scope === "platform") {
243
+ throw new AppError(
244
+ "A platform job works across tenants and has no tenant database: use withAllTenants(await app.database(), ...), or withTenant for each tenant.",
245
+ { code: "database_unavailable", status: 500 }
246
+ );
247
+ }
248
+ if (!handle) {
249
+ throw new AppError(
250
+ "No tenant database on this request. Enable `database` in createApp and use an authenticated route.",
251
+ { code: "database_unavailable", status: 500 }
252
+ );
253
+ }
254
+ return handle;
255
+ }
256
+ function appSchema(id) {
257
+ assertValidAppId(id);
258
+ return pgSchema(id);
259
+ }
260
+ function tenantColumns() {
261
+ return {
262
+ id: uuid("id").primaryKey().$defaultFn(() => uuidv7()),
263
+ tenantId: uuid("tenant_id").notNull().default(sql`nullif(current_setting('app.tenant_id', true), '')::uuid`),
264
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
265
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow().$onUpdate(() => /* @__PURE__ */ new Date())
266
+ };
267
+ }
268
+ function tenantTable(schema, name, columns, extras) {
269
+ return schema.table(name, { ...tenantColumns(), ...columns }, (table) => [
270
+ // biome-ignore lint/suspicious/noExplicitAny: the generic spread hides the column type
271
+ index(`${name}_tenant_id_idx`).on(table.tenantId),
272
+ ...extras?.(table) ?? []
273
+ ]);
274
+ }
275
+ function globalTable(schema, name, columns, extras) {
276
+ return schema.table(name, columns, extras);
277
+ }
278
+
279
+ export {
280
+ createDatabase,
281
+ applyTenantPolicies,
282
+ migrate,
283
+ withTenant,
284
+ withAllTenants,
285
+ tenantDatabase,
286
+ db,
287
+ appSchema,
288
+ tenantColumns,
289
+ tenantTable,
290
+ globalTable
291
+ };
@@ -76,11 +76,18 @@ interface MigrateOptions {
76
76
  * migrate at the same time.
77
77
  */
78
78
  declare function migrate(database: Database, options?: MigrateOptions): Promise<void>;
79
+ interface WithTenantOptions {
80
+ /**
81
+ * Who the work is done for. A row of an object kind (`objectColumns`) made in the
82
+ * transaction gets this owner. A request's transaction has the caller.
83
+ */
84
+ userId?: string;
85
+ }
79
86
  /**
80
87
  * Run `fn` in a transaction that can only see and write rows of one tenant. Use it for
81
88
  * work outside a request, such as a scheduled endpoint that loops over tenants.
82
89
  */
83
- declare function withTenant<T>(database: Database, tenantId: string, fn: (tx: Db) => Promise<T>): Promise<T>;
90
+ declare function withTenant<T>(database: Database, tenantId: string, fn: (tx: Db) => Promise<T>, options?: WithTenantOptions): Promise<T>;
84
91
  /**
85
92
  * Run `fn` in a transaction that sees every tenant. This is the one way around tenant
86
93
  * isolation. Use it only for platform-level work such as reports across tenants, and say
@@ -146,4 +153,4 @@ type GlobalTable<TName extends string, TColumns extends Record<string, PgColumnB
146
153
  */
147
154
  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>;
148
155
 
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 };
156
+ 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, type WithTenantOptions as W, APP_NAME_PATTERN as a, appBasePath as b, isValidAppId as c, isValidAppName as d, type Db as e, type TableExtras 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 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';
4
+ export { C as CreateDatabaseOptions, D as Database, e as Db, G as GlobalTable, M as MigrateOptions, f as TableExtras, T as TenantTable, W as WithTenantOptions, 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-NCwvoAnt.js';
package/dist/db.js CHANGED
@@ -1,267 +1,20 @@
1
1
  import {
2
- AppError,
3
- UUID_PATTERN,
4
- assertApiKeyAccepted,
5
- assertValidAppId,
2
+ appSchema,
3
+ applyTenantPolicies,
4
+ createDatabase,
5
+ db,
6
+ globalTable,
7
+ migrate,
8
+ tenantColumns,
9
+ tenantDatabase,
10
+ tenantTable,
11
+ withAllTenants,
12
+ withTenant
13
+ } from "./chunk-XWJAL6GX.js";
14
+ import {
6
15
  uuidv7
7
- } from "./chunk-UWTSXBJL.js";
16
+ } from "./chunk-OBKMOVBA.js";
8
17
  import "./chunk-ERGI2X5S.js";
9
-
10
- // src/db.ts
11
- import { existsSync, mkdirSync } from "fs";
12
- import path from "path";
13
- import { sql } from "drizzle-orm";
14
- import { readMigrationFiles } from "drizzle-orm/migrator";
15
- import {
16
- index,
17
- pgSchema,
18
- timestamp,
19
- uuid
20
- } from "drizzle-orm/pg-core";
21
- var RUNTIME_ROLE = "platform_app_runtime";
22
- var MIGRATIONS_TABLE = "__migrations";
23
- var IDENTIFIER = /^[a-z_][a-z0-9_]*$/;
24
- function ident(name) {
25
- if (!IDENTIFIER.test(name)) throw new Error(`Unsafe SQL identifier: ${JSON.stringify(name)}`);
26
- return `"${name}"`;
27
- }
28
- function rowsOf(result) {
29
- if (Array.isArray(result)) return result;
30
- const rows = result?.rows;
31
- return Array.isArray(rows) ? rows : [];
32
- }
33
- async function executeEach(handle, statements) {
34
- for (const statement of statements) await handle.execute(sql.raw(statement));
35
- }
36
- async function schemaExists(database) {
37
- const [row] = rowsOf(
38
- await database.drizzle.execute(
39
- sql`select 1 from information_schema.schemata where schema_name = ${database.schema}`
40
- )
41
- );
42
- return row !== void 0;
43
- }
44
- var clients = /* @__PURE__ */ new WeakMap();
45
- async function createDatabase(options) {
46
- assertValidAppId(options.schema);
47
- const env = options.env ?? process.env;
48
- const url = options.url ?? env.DATABASE_URL;
49
- let database;
50
- if (url) {
51
- const { default: postgres } = await import("postgres");
52
- const { drizzle } = await import("drizzle-orm/postgres-js");
53
- const client = postgres(url, { max: Number(env.DB_POOL_MAX ?? 10), onnotice: () => {
54
- } });
55
- database = {
56
- schema: options.schema,
57
- driver: "postgres",
58
- drizzle: drizzle(client),
59
- close: () => client.end({ timeout: 5 })
60
- };
61
- clients.set(database, client);
62
- } else {
63
- if (env.NODE_ENV === "production") {
64
- throw new Error("DATABASE_URL is required in production");
65
- }
66
- const { PGlite } = await import("@electric-sql/pglite");
67
- const { drizzle } = await import("drizzle-orm/pglite");
68
- const dataDir = options.dataDir ?? env.PGLITE_DATA_DIR ?? path.resolve(".data/pg");
69
- if (!dataDir.includes("://")) {
70
- mkdirSync(path.dirname(path.resolve(dataDir)), { recursive: true });
71
- }
72
- const client = new PGlite(dataDir);
73
- await client.waitReady;
74
- database = {
75
- schema: options.schema,
76
- driver: "pglite",
77
- drizzle: drizzle(client),
78
- close: () => client.close()
79
- };
80
- clients.set(database, client);
81
- }
82
- const [role] = rowsOf(
83
- await database.drizzle.execute(
84
- sql`select (rolsuper or rolbypassrls) as bypass from pg_roles where rolname = current_user`
85
- )
86
- );
87
- if (role?.bypass) {
88
- await database.drizzle.execute(
89
- sql.raw(
90
- `do $$ begin
91
- if not exists (select from pg_roles where rolname = '${RUNTIME_ROLE}') then
92
- create role ${RUNTIME_ROLE} nologin;
93
- end if;
94
- end $$`
95
- )
96
- );
97
- database.runtimeRole = RUNTIME_ROLE;
98
- }
99
- return database;
100
- }
101
- var POLICY = `current_setting('app.tenant_scope', true) = 'all'
102
- or tenant_id = nullif(current_setting('app.tenant_id', true), '')::uuid`;
103
- async function applyTenantPolicies(database) {
104
- const schema = ident(database.schema);
105
- const tables = rowsOf(
106
- await database.drizzle.execute(
107
- sql`select c.table_name
108
- from information_schema.columns c
109
- join information_schema.tables t
110
- on t.table_schema = c.table_schema and t.table_name = c.table_name
111
- where c.table_schema = ${database.schema}
112
- and c.column_name = 'tenant_id'
113
- and t.table_type = 'BASE TABLE'
114
- order by c.table_name`
115
- )
116
- ).map((row) => row.table_name);
117
- for (const name of tables) {
118
- const table = `${schema}.${ident(name)}`;
119
- await executeEach(database.drizzle, [
120
- `alter table ${table} enable row level security`,
121
- `alter table ${table} force row level security`,
122
- `drop policy if exists tenant_isolation on ${table}`,
123
- `create policy tenant_isolation on ${table} using (${POLICY}) with check (${POLICY})`
124
- ]);
125
- }
126
- if (database.runtimeRole && await schemaExists(database)) {
127
- await executeEach(database.drizzle, [
128
- `grant usage on schema ${schema} to ${RUNTIME_ROLE}`,
129
- `grant select, insert, update, delete on all tables in schema ${schema} to ${RUNTIME_ROLE}`
130
- ]);
131
- }
132
- return tables;
133
- }
134
- async function applyMigrations(database, folder) {
135
- const schema = ident(database.schema);
136
- const table = `${schema}.${ident(MIGRATIONS_TABLE)}`;
137
- const migrations = readMigrationFiles({ migrationsFolder: folder });
138
- const createsOwnSchema = new RegExp(
139
- String.raw`^\s*create\s+schema\s+(if\s+not\s+exists\s+)?"?` + database.schema + String.raw`"?\s*;?\s*$`,
140
- "i"
141
- );
142
- await executeEach(database.drizzle, [
143
- `create schema if not exists ${schema}`,
144
- `create table if not exists ${table} (id serial primary key, hash text not null, created_at bigint)`
145
- ]);
146
- const [last] = rowsOf(
147
- await database.drizzle.execute(
148
- sql.raw(`select created_at from ${table} order by created_at desc limit 1`)
149
- )
150
- );
151
- const appliedUntil = last ? Number(last.created_at) : -1;
152
- for (const migration of migrations) {
153
- if (migration.folderMillis <= appliedUntil) continue;
154
- await database.drizzle.transaction(async (tx) => {
155
- for (const statement of migration.sql) {
156
- if (!statement.trim() || createsOwnSchema.test(statement)) continue;
157
- await tx.execute(sql.raw(statement));
158
- }
159
- await tx.execute(
160
- sql`insert into ${sql.raw(table)} (hash, created_at) values (${migration.hash}, ${migration.folderMillis})`
161
- );
162
- });
163
- }
164
- }
165
- async function migrate(database, options = {}) {
166
- const folder = options.migrationsFolder ?? path.resolve("drizzle");
167
- const hasMigrations = existsSync(path.join(folder, "meta", "_journal.json"));
168
- const run = async () => {
169
- if (hasMigrations) await applyMigrations(database, folder);
170
- await applyTenantPolicies(database);
171
- if (options.appName && await schemaExists(database)) {
172
- const comment = `app: ${options.appName}`.replaceAll("'", "''");
173
- await database.drizzle.execute(
174
- sql.raw(`comment on schema ${ident(database.schema)} is '${comment}'`)
175
- );
176
- }
177
- };
178
- if (database.driver !== "postgres") return run();
179
- const client = clients.get(database);
180
- const reserved = await client.reserve();
181
- try {
182
- await reserved`select pg_advisory_lock(hashtext(${database.schema}))`;
183
- await run();
184
- } finally {
185
- await reserved`select pg_advisory_unlock(hashtext(${database.schema}))`.catch(() => {
186
- });
187
- reserved.release();
188
- }
189
- }
190
- async function enterScope(tx, database, scope) {
191
- if (database.runtimeRole) {
192
- await tx.execute(sql`select set_config('role', ${database.runtimeRole}, true)`);
193
- }
194
- if (scope === "all") {
195
- await tx.execute(sql`select set_config('app.tenant_scope', 'all', true)`);
196
- } else {
197
- await tx.execute(sql`select set_config('app.tenant_id', ${scope.tenantId}, true)`);
198
- }
199
- }
200
- function withTenant(database, tenantId, fn) {
201
- if (!UUID_PATTERN.test(tenantId)) {
202
- throw new AppError("Tenant id is not a UUID", { code: "invalid_tenant", status: 500 });
203
- }
204
- return database.drizzle.transaction(async (tx) => {
205
- await enterScope(tx, database, { tenantId });
206
- return fn(tx);
207
- });
208
- }
209
- function withAllTenants(database, fn) {
210
- return database.drizzle.transaction(async (tx) => {
211
- await enterScope(tx, database, "all");
212
- return fn(tx);
213
- });
214
- }
215
- var ROLLBACK = /* @__PURE__ */ Symbol("rollback");
216
- function tenantDatabase(getDatabase) {
217
- return async (c, next) => {
218
- const user = c.get("user");
219
- if (!user) return next();
220
- const database = await getDatabase();
221
- try {
222
- await withTenant(database, user.tenantId, async (tx) => {
223
- c.set("db", tx);
224
- await next();
225
- if (c.error) throw ROLLBACK;
226
- });
227
- } catch (error) {
228
- if (error !== ROLLBACK) throw error;
229
- }
230
- };
231
- }
232
- function db(c) {
233
- assertApiKeyAccepted(c);
234
- const handle = c.get("db");
235
- if (!handle) {
236
- throw new AppError(
237
- "No tenant database on this request. Enable `database` in createApp and use an authenticated route.",
238
- { code: "database_unavailable", status: 500 }
239
- );
240
- }
241
- return handle;
242
- }
243
- function appSchema(id) {
244
- assertValidAppId(id);
245
- return pgSchema(id);
246
- }
247
- function tenantColumns() {
248
- return {
249
- id: uuid("id").primaryKey().$defaultFn(() => uuidv7()),
250
- tenantId: uuid("tenant_id").notNull().default(sql`nullif(current_setting('app.tenant_id', true), '')::uuid`),
251
- createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
252
- updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow().$onUpdate(() => /* @__PURE__ */ new Date())
253
- };
254
- }
255
- function tenantTable(schema, name, columns, extras) {
256
- return schema.table(name, { ...tenantColumns(), ...columns }, (table) => [
257
- // biome-ignore lint/suspicious/noExplicitAny: the generic spread hides the column type
258
- index(`${name}_tenant_id_idx`).on(table.tenantId),
259
- ...extras?.(table) ?? []
260
- ]);
261
- }
262
- function globalTable(schema, name, columns, extras) {
263
- return schema.table(name, columns, extras);
264
- }
265
18
  export {
266
19
  appSchema,
267
20
  applyTenantPolicies,
package/dist/dev.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as AuthUser, a as ApiKeyKind } from './api-keys-R2145cd9.js';
1
+ import { A as AuthUser, a as ApiKeyKind } from './api-keys-BY7RCE9v.js';
2
2
  import 'hono';
3
3
  import 'jose';
4
4
 
@@ -31,10 +31,12 @@ declare function decodeDevToken(token: string | undefined): DevTokenPayload | un
31
31
  declare function resolveDevUser(token: string | undefined, env?: Env): AuthUser;
32
32
  type DevApiKeyPayload = DevTokenPayload & {
33
33
  kind?: ApiKeyKind;
34
+ platform?: boolean;
34
35
  };
35
36
  /**
36
37
  * An API key for tests and local development. It is read like a dev token, but the request
37
38
  * is made with a key: only a route that accepts keys takes it. `kind` defaults to `user`.
39
+ * `platform: true` makes it a key of the platform's own tenant, which a platform job takes.
38
40
  */
39
41
  declare function encodeDevApiKey(user?: DevApiKeyPayload): string;
40
42
  /**