@zjazj/server 0.0.8 → 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.
- package/dist/api-keys-BY7RCE9v.d.ts +215 -0
- package/dist/{chunk-NMKEVYGN.js → chunk-3X4RSAM6.js} +20 -1
- package/dist/{chunk-EIZ24ILA.js → chunk-7FPH47F6.js} +25 -4
- package/dist/chunk-OBKMOVBA.js +345 -0
- package/dist/{chunk-26AAYRI3.js → chunk-VJRJ53T2.js} +1 -0
- package/dist/chunk-XWJAL6GX.js +291 -0
- package/dist/{db-Dp7BB3Kc.d.ts → db-NCwvoAnt.d.ts} +9 -2
- package/dist/db.d.ts +1 -1
- package/dist/db.js +14 -259
- package/dist/dev.d.ts +20 -2
- package/dist/dev.js +7 -1
- package/dist/index.d.ts +245 -37
- package/dist/index.js +687 -110
- package/dist/log.js +1 -1
- package/dist/{mcp-UM4G354G.js → mcp-6W7AB46O.js} +14 -8
- package/dist/objects.d.ts +225 -0
- package/dist/objects.js +371 -0
- package/dist/testing.d.ts +20 -4
- package/dist/testing.js +33 -3
- package/package.json +5 -1
- package/dist/auth-Ckmm4C6y.d.ts +0 -81
- package/dist/chunk-UWDDQH25.js +0 -146
|
@@ -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
|
|
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
|
|
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,
|
|
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,265 +1,20 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
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 {
|
|
5
15
|
uuidv7
|
|
6
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-OBKMOVBA.js";
|
|
7
17
|
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, extras) {
|
|
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
|
-
...extras?.(table) ?? []
|
|
258
|
-
]);
|
|
259
|
-
}
|
|
260
|
-
function globalTable(schema, name, columns, extras) {
|
|
261
|
-
return schema.table(name, columns, extras);
|
|
262
|
-
}
|
|
263
18
|
export {
|
|
264
19
|
appSchema,
|
|
265
20
|
applyTenantPolicies,
|
package/dist/dev.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as AuthUser } from './
|
|
1
|
+
import { A as AuthUser, a as ApiKeyKind } from './api-keys-BY7RCE9v.js';
|
|
2
2
|
import 'hono';
|
|
3
3
|
import 'jose';
|
|
4
4
|
|
|
@@ -7,6 +7,8 @@ type Env = Record<string, string | undefined>;
|
|
|
7
7
|
declare const DEFAULT_DEV_TENANT_ID = "0190a000-0000-7000-8000-000000000001";
|
|
8
8
|
/** Dev tokens are not signed. They are accepted only while the dev identity is enabled. */
|
|
9
9
|
declare const DEV_TOKEN_PREFIX = "dev.";
|
|
10
|
+
/** An API key of the dev identity. Like a dev token, it is read only in development. */
|
|
11
|
+
declare const DEV_API_KEY_PREFIX = "pk_dev.";
|
|
10
12
|
/**
|
|
11
13
|
* The dev identity is on only when `ENV` is exactly `dev` and the process is not running in
|
|
12
14
|
* production. The comparison is case sensitive on purpose, so a typo in a deployment can
|
|
@@ -27,5 +29,21 @@ declare function decodeDevToken(token: string | undefined): DevTokenPayload | un
|
|
|
27
29
|
* lets the browser switch tenant or permissions without restarting the server.
|
|
28
30
|
*/
|
|
29
31
|
declare function resolveDevUser(token: string | undefined, env?: Env): AuthUser;
|
|
32
|
+
type DevApiKeyPayload = DevTokenPayload & {
|
|
33
|
+
kind?: ApiKeyKind;
|
|
34
|
+
platform?: boolean;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* An API key for tests and local development. It is read like a dev token, but the request
|
|
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.
|
|
40
|
+
*/
|
|
41
|
+
declare function encodeDevApiKey(user?: DevApiKeyPayload): string;
|
|
42
|
+
/**
|
|
43
|
+
* The dev user for a request made with an API key. A dev key may replace parts of the
|
|
44
|
+
* identity as a dev token does. Any other key is the dev identity as it is. No key is
|
|
45
|
+
* checked: in development nothing asks the control plane.
|
|
46
|
+
*/
|
|
47
|
+
declare function resolveDevKeyUser(key: string, env?: Env): AuthUser;
|
|
30
48
|
|
|
31
|
-
export { DEFAULT_DEV_TENANT_ID, DEV_TOKEN_PREFIX, decodeDevToken, devIdentity, encodeDevToken, isDevIdentityEnabled, resolveDevUser };
|
|
49
|
+
export { DEFAULT_DEV_TENANT_ID, DEV_API_KEY_PREFIX, DEV_TOKEN_PREFIX, decodeDevToken, devIdentity, encodeDevApiKey, encodeDevToken, isDevIdentityEnabled, resolveDevKeyUser, resolveDevUser };
|
package/dist/dev.js
CHANGED
|
@@ -1,18 +1,24 @@
|
|
|
1
1
|
import {
|
|
2
2
|
DEFAULT_DEV_TENANT_ID,
|
|
3
|
+
DEV_API_KEY_PREFIX,
|
|
3
4
|
DEV_TOKEN_PREFIX,
|
|
4
5
|
decodeDevToken,
|
|
5
6
|
devIdentity,
|
|
7
|
+
encodeDevApiKey,
|
|
6
8
|
encodeDevToken,
|
|
7
9
|
isDevIdentityEnabled,
|
|
10
|
+
resolveDevKeyUser,
|
|
8
11
|
resolveDevUser
|
|
9
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-3X4RSAM6.js";
|
|
10
13
|
export {
|
|
11
14
|
DEFAULT_DEV_TENANT_ID,
|
|
15
|
+
DEV_API_KEY_PREFIX,
|
|
12
16
|
DEV_TOKEN_PREFIX,
|
|
13
17
|
decodeDevToken,
|
|
14
18
|
devIdentity,
|
|
19
|
+
encodeDevApiKey,
|
|
15
20
|
encodeDevToken,
|
|
16
21
|
isDevIdentityEnabled,
|
|
22
|
+
resolveDevKeyUser,
|
|
17
23
|
resolveDevUser
|
|
18
24
|
};
|