@kaloma-ai/framework-api 0.0.0-stage → 0.6.0

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,3486 @@
1
+ import {
2
+ apikey,
3
+ invitation,
4
+ member,
5
+ organization,
6
+ schema_exports,
7
+ user
8
+ } from "./chunk-R6W6GTUR.js";
9
+
10
+ // src/config.ts
11
+ import { z } from "zod";
12
+ var schema = z.object({
13
+ NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
14
+ PORT: z.coerce.number().int().positive().default(3e3),
15
+ DATABASE_URL: z.string().min(1, "DATABASE_URL is required"),
16
+ APP_NAME: z.string().default("appai"),
17
+ /** Public address of the app, used in emails and as the auth base URL. */
18
+ PUBLIC_URL: z.string().url().default("http://localhost:8080"),
19
+ /** Secret used to sign sessions and tokens. At least 32 characters. */
20
+ AUTH_SECRET: z.string().min(32, "AUTH_SECRET must be at least 32 characters"),
21
+ /**
22
+ * Key that encrypts the credentials stored on the Connections page (API keys, tokens). At least 32 characters.
23
+ * Without it a key is derived from AUTH_SECRET; changing either one means entering the credentials again.
24
+ */
25
+ SECRETS_KEY: z.preprocess((v) => v === "" ? void 0 : v, z.string().min(32, "SECRETS_KEY must be at least 32 characters").optional()),
26
+ /** The only email allowed to sign up while the app has no users; becomes the first admin. */
27
+ INITIAL_ADMIN_EMAIL: z.string().email().optional(),
28
+ /** Days an external user keeps access after accepting an invitation (renewable by an Admin). */
29
+ EXTERNAL_ACCESS_DAYS: z.coerce.number().int().positive().default(90),
30
+ /** Folder with brand.json and the logo/font files (see docs/theming.md). Missing means the built-in look. */
31
+ BRAND_DIR: z.string().default("brand"),
32
+ /** Daily backups of the database (and FILES_DIR) into BACKUP_DIR. */
33
+ BACKUP_ENABLED: z.enum(["true", "false"]).default("true").transform((v) => v === "true"),
34
+ BACKUP_DIR: z.string().default("backups"),
35
+ /** Time of the daily backup, HH:MM in UTC. */
36
+ BACKUP_TIME: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, "use HH:MM, e.g. 02:00").default("02:00"),
37
+ /** How many backups to keep. */
38
+ BACKUP_KEEP: z.coerce.number().int().min(1).default(14),
39
+ /** Folder with files uploaded by the app; included in every backup when it exists. */
40
+ FILES_DIR: z.string().default("files"),
41
+ /** Comma-separated addresses that receive alerts (failed backup, database down, disk full). */
42
+ ALERT_EMAILS: z.string().default("").transform((v) => v.split(",").map((a) => a.trim()).filter(Boolean)).pipe(z.array(z.email())),
43
+ /** Alert when less than this share of the disk is free. */
44
+ DISK_MIN_FREE_PERCENT: z.coerce.number().min(1).max(90).default(10),
45
+ /** How often the health checks run. */
46
+ HEALTH_CHECK_SECONDS: z.coerce.number().int().min(5).default(60),
47
+ EMAIL_TRANSPORT: z.enum(["console", "smtp"]).default("console"),
48
+ EMAIL_FROM: z.string().default("appai <no-reply@localhost>"),
49
+ EMAIL_REPLY_TO: z.string().optional(),
50
+ SMTP_HOST: z.string().optional(),
51
+ SMTP_PORT: z.coerce.number().int().positive().default(587),
52
+ SMTP_USER: z.string().optional(),
53
+ SMTP_PASSWORD: z.string().optional()
54
+ });
55
+ function loadConfig(env = process.env) {
56
+ const parsed = schema.safeParse(env);
57
+ if (!parsed.success) {
58
+ const problems = parsed.error.issues.map((i) => ` - ${i.path.join(".")}: ${i.message}`);
59
+ throw new Error(`Invalid configuration:
60
+ ${problems.join("\n")}`);
61
+ }
62
+ const config = parsed.data;
63
+ if (config.EMAIL_TRANSPORT === "smtp" && !config.SMTP_HOST) {
64
+ throw new Error("Invalid configuration:\n - SMTP_HOST: required when EMAIL_TRANSPORT=smtp");
65
+ }
66
+ return config;
67
+ }
68
+
69
+ // src/db.ts
70
+ import { drizzle } from "drizzle-orm/postgres-js";
71
+ import postgres from "postgres";
72
+ function createDb(databaseUrl) {
73
+ const client = postgres(databaseUrl, { max: 10 });
74
+ const db = drizzle(client);
75
+ return { db, client, close: () => client.end() };
76
+ }
77
+
78
+ // src/migrate.ts
79
+ import { readFileSync } from "fs";
80
+ import { join } from "path";
81
+ import { fileURLToPath } from "url";
82
+ import { sql } from "drizzle-orm";
83
+ import { migrate } from "drizzle-orm/postgres-js/migrator";
84
+ import { readMigrationFiles } from "drizzle-orm/migrator";
85
+ function frameworkMigrationsDir() {
86
+ return fileURLToPath(new URL("../drizzle", import.meta.url));
87
+ }
88
+ var DEFAULT_TABLE = "__drizzle_migrations";
89
+ var SCHEMA = "drizzle";
90
+ async function runMigrations(db, migrationsFolder, table = DEFAULT_TABLE) {
91
+ await migrate(db, { migrationsFolder, migrationsTable: table });
92
+ await assertAllApplied(db, migrationsFolder, table);
93
+ }
94
+ async function assertAllApplied(db, migrationsFolder, table) {
95
+ const applied = new Set(
96
+ (await db.execute(sql`select hash from ${sql.identifier(SCHEMA)}.${sql.identifier(table)}`)).map((row) => String(row.hash))
97
+ );
98
+ const skipped = readMigrationFiles({ migrationsFolder }).filter((m) => !applied.has(m.hash));
99
+ if (skipped.length === 0) return;
100
+ const journal = JSON.parse(readFileSync(join(migrationsFolder, "meta/_journal.json"), "utf8"));
101
+ const names = skipped.map((m) => journal.entries.find((e) => e.when === m.folderMillis)?.tag ?? String(m.folderMillis));
102
+ throw new Error(
103
+ `Migration(s) not applied from ${migrationsFolder}: ${names.join(", ")}. Each is older than a migration the database has already applied (${SCHEMA}.${table}), so it was skipped. Regenerate it so that it is newer (delete it and run db:generate again), or apply it by hand and record it in that table.`
104
+ );
105
+ }
106
+
107
+ // src/storage/index.ts
108
+ import { createReadStream, createWriteStream } from "fs";
109
+ import { mkdir, readdir, readFile, rm, stat, writeFile } from "fs/promises";
110
+ import { dirname, join as join2, resolve, sep } from "path";
111
+ import { pipeline } from "stream/promises";
112
+ var NAME = "[\\w-]+(?:\\.[\\w-]+)*";
113
+ var KEY = new RegExp(`^${NAME}(?:/${NAME})*$`);
114
+ function assertValidKey(key) {
115
+ if (!KEY.test(key)) throw new Error(`Invalid file key "${key}"`);
116
+ }
117
+ function createLocalFileStorage(dir) {
118
+ const root = resolve(dir);
119
+ const path = (key) => {
120
+ assertValidKey(key);
121
+ const full = resolve(join2(root, key));
122
+ if (!full.startsWith(root + sep)) throw new Error(`Invalid file key "${key}"`);
123
+ return full;
124
+ };
125
+ async function walk(folder, prefix) {
126
+ const entries = await readdir(folder, { withFileTypes: true }).catch((e) => {
127
+ if (e.code === "ENOENT" || e.code === "ENOTDIR") return [];
128
+ throw e;
129
+ });
130
+ const files = [];
131
+ for (const entry of entries) {
132
+ const key = prefix ? `${prefix}/${entry.name}` : entry.name;
133
+ if (entry.isDirectory()) files.push(...await walk(join2(folder, entry.name), key));
134
+ else if (entry.isFile()) files.push({ key, size: (await stat(join2(folder, entry.name))).size });
135
+ }
136
+ return files;
137
+ }
138
+ return {
139
+ async put(key, data) {
140
+ const file = path(key);
141
+ await mkdir(dirname(file), { recursive: true });
142
+ await writeFile(file, data);
143
+ },
144
+ async putStream(key, data) {
145
+ const file = path(key);
146
+ await mkdir(dirname(file), { recursive: true });
147
+ await pipeline(data, createWriteStream(file));
148
+ },
149
+ async get(key) {
150
+ return readFile(path(key)).catch((e) => {
151
+ if (e.code === "ENOENT") return null;
152
+ throw e;
153
+ });
154
+ },
155
+ async delete(key) {
156
+ await rm(path(key), { force: true });
157
+ },
158
+ async list(prefix) {
159
+ return walk(prefix ? path(prefix) : root, prefix);
160
+ },
161
+ async deleteTree(prefix) {
162
+ await rm(path(prefix), { recursive: true, force: true });
163
+ }
164
+ };
165
+ }
166
+ var BACKUP_STORAGE_PREFIX = "backups";
167
+
168
+ // src/authz/service.ts
169
+ import { randomUUID } from "crypto";
170
+ import { and, count, desc as desc2, eq, gt, sql as sql2 } from "drizzle-orm";
171
+
172
+ // src/authz/audit.ts
173
+ import { desc, lt } from "drizzle-orm";
174
+
175
+ // src/authz/schema.ts
176
+ import { jsonb, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
177
+ var customRole = pgTable("custom_role", {
178
+ key: text("key").primaryKey(),
179
+ label: text("label").notNull(),
180
+ permissions: text("permissions").array().notNull(),
181
+ createdAt: timestamp("created_at").defaultNow().notNull(),
182
+ updatedAt: timestamp("updated_at").defaultNow().notNull()
183
+ });
184
+ var userAccess = pgTable("user_access", {
185
+ userId: text("user_id").primaryKey().references(() => user.id, { onDelete: "cascade" }),
186
+ expiresAt: timestamp("expires_at"),
187
+ deactivatedAt: timestamp("deactivated_at")
188
+ });
189
+ var auditLog = pgTable("audit_log", {
190
+ id: uuid("id").primaryKey().defaultRandom(),
191
+ at: timestamp("at").defaultNow().notNull(),
192
+ actorUserId: text("actor_user_id"),
193
+ /** Email of the actor at the time, so the log stays readable if the user is renamed. */
194
+ actorEmail: text("actor_email"),
195
+ /** Set when the action was done with an API key ("user X via key Y"). */
196
+ viaKeyId: text("via_key_id"),
197
+ action: text("action").notNull(),
198
+ target: text("target"),
199
+ details: jsonb("details").$type()
200
+ });
201
+
202
+ // src/authz/audit.ts
203
+ function createAudit(db) {
204
+ return {
205
+ async record(actor, action, target, details) {
206
+ await db.insert(auditLog).values({
207
+ actorUserId: actor.userId,
208
+ actorEmail: actor.email,
209
+ viaKeyId: actor.viaKeyId ?? null,
210
+ action,
211
+ target: target ?? null,
212
+ details: details ?? null
213
+ });
214
+ },
215
+ async list(limit = 100, before) {
216
+ return db.select().from(auditLog).where(before ? lt(auditLog.at, before) : void 0).orderBy(desc(auditLog.at)).limit(Math.min(limit, 500));
217
+ }
218
+ };
219
+ }
220
+
221
+ // src/authz/service.ts
222
+ var AuthzError = class extends Error {
223
+ constructor(message, status = 400) {
224
+ super(message);
225
+ this.status = status;
226
+ }
227
+ status;
228
+ };
229
+ var DAY = 24 * 60 * 60 * 1e3;
230
+ function createAuthz({ db, catalog, externalAccessDays }) {
231
+ const audit = createAudit(db);
232
+ async function custom() {
233
+ const rows = await db.select().from(customRole).orderBy(customRole.label);
234
+ return rows.map((r) => ({ key: r.key, label: r.label, permissions: r.permissions, builtIn: false }));
235
+ }
236
+ async function listRoles() {
237
+ const builtIn = [...catalog.roles.values()].map((r) => ({ ...r, builtIn: true }));
238
+ return [...builtIn, ...await custom()];
239
+ }
240
+ async function roleKeysOf(userId) {
241
+ const [row] = await db.select({ role: member.role }).from(member).where(eq(member.userId, userId)).limit(1);
242
+ return row ? row.role.split(",").map((r) => r.trim()).filter(Boolean) : [];
243
+ }
244
+ async function permissionsOf(userId) {
245
+ const keys = await roleKeysOf(userId);
246
+ const byKey = new Map((await listRoles()).map((r) => [r.key, r]));
247
+ const granted = /* @__PURE__ */ new Set();
248
+ for (const key of keys) for (const p of byKey.get(key)?.permissions ?? []) granted.add(p);
249
+ return granted;
250
+ }
251
+ async function accessOf(userId) {
252
+ const [row] = await db.select().from(userAccess).where(eq(userAccess.userId, userId)).limit(1);
253
+ if (row?.deactivatedAt) return { active: false, reason: "deactivated" };
254
+ if (row?.expiresAt && row.expiresAt.getTime() <= Date.now()) return { active: false, reason: "expired" };
255
+ return { active: true, expiresAt: row?.expiresAt ?? null };
256
+ }
257
+ function assertKnownRoles(keys, known) {
258
+ const names = new Set(known.map((r) => r.key));
259
+ const unknown = keys.filter((k) => !names.has(k));
260
+ if (unknown.length > 0) throw new AuthzError(`Unknown role: ${unknown.join(", ")}`);
261
+ }
262
+ async function normaliseRoles(keys) {
263
+ const unique = [...new Set(keys.map((k) => k.trim()).filter(Boolean))];
264
+ if (unique.length === 0) unique.push("member");
265
+ assertKnownRoles(unique, await listRoles());
266
+ return unique;
267
+ }
268
+ function hasExternalRole(keys) {
269
+ return keys.some((k) => catalog.roles.get(k)?.external);
270
+ }
271
+ async function setExpiry(userId, expiresAt) {
272
+ await db.insert(userAccess).values({ userId, expiresAt }).onConflictDoUpdate({ target: userAccess.userId, set: { expiresAt } });
273
+ }
274
+ async function onJoined(userId, roles) {
275
+ if (hasExternalRole(roles.split(","))) await setExpiry(userId, new Date(Date.now() + externalAccessDays * DAY));
276
+ }
277
+ const joining = /* @__PURE__ */ new Map();
278
+ function joinPendingInvitation(userId) {
279
+ const running = joining.get(userId);
280
+ if (running) return running;
281
+ const task = (async () => {
282
+ const [u] = await db.select({ email: user.email, verified: user.emailVerified }).from(user).where(eq(user.id, userId)).limit(1);
283
+ if (!u?.verified || (await roleKeysOf(userId)).length > 0) return null;
284
+ const [invite] = await db.select().from(invitation).where(
285
+ and(
286
+ sql2`lower(${invitation.email}) = ${u.email.toLowerCase()}`,
287
+ eq(invitation.status, "pending"),
288
+ gt(invitation.expiresAt, /* @__PURE__ */ new Date())
289
+ )
290
+ ).orderBy(desc2(invitation.createdAt)).limit(1);
291
+ if (!invite) return null;
292
+ const role = invite.role ?? "member";
293
+ await db.insert(member).values({ id: randomUUID(), organizationId: invite.organizationId, userId, role, createdAt: /* @__PURE__ */ new Date() });
294
+ await db.update(invitation).set({ status: "accepted" }).where(eq(invitation.id, invite.id));
295
+ await onJoined(userId, role);
296
+ await audit.record({ userId, email: u.email }, "user.joined", userId, { roles: role });
297
+ return role.split(",");
298
+ })().finally(() => joining.delete(userId));
299
+ joining.set(userId, task);
300
+ return task;
301
+ }
302
+ async function ownerCount() {
303
+ const [row] = await db.select({ n: count() }).from(member).where(sql2`',' || ${member.role} || ',' like '%,owner,%'`);
304
+ return row?.n ?? 0;
305
+ }
306
+ async function setUserRoles(actorId, userId, keys) {
307
+ const roles = await normaliseRoles(keys);
308
+ const before = await roleKeysOf(userId);
309
+ if (before.length === 0) throw new AuthzError("User not found", 404);
310
+ const ownerChange = before.includes("owner") !== roles.includes("owner");
311
+ if (ownerChange && !(await roleKeysOf(actorId)).includes("owner")) {
312
+ throw new AuthzError("Only an Admin can grant or remove the Admin role", 403);
313
+ }
314
+ if (before.includes("owner") && !roles.includes("owner") && await ownerCount() <= 1) {
315
+ throw new AuthzError("There must be at least one Admin", 409);
316
+ }
317
+ await db.update(member).set({ role: roles.join(",") }).where(eq(member.userId, userId));
318
+ if (hasExternalRole(roles) && !hasExternalRole(before)) {
319
+ await setExpiry(userId, new Date(Date.now() + externalAccessDays * DAY));
320
+ } else if (!hasExternalRole(roles) && hasExternalRole(before)) {
321
+ await setExpiry(userId, null);
322
+ }
323
+ return roles;
324
+ }
325
+ async function setDeactivated(userId, deactivated) {
326
+ const deactivatedAt = deactivated ? /* @__PURE__ */ new Date() : null;
327
+ await db.insert(userAccess).values({ userId, deactivatedAt }).onConflictDoUpdate({ target: userAccess.userId, set: { deactivatedAt } });
328
+ }
329
+ async function renewAccess(userId, days) {
330
+ await setExpiry(userId, days === null ? null : new Date(Date.now() + days * DAY));
331
+ }
332
+ function validatePermissions(names) {
333
+ const unique = [...new Set(names)];
334
+ const unknown = unique.filter((p) => !catalog.permissions.has(p));
335
+ if (unknown.length > 0) throw new AuthzError(`Unknown permission: ${unknown.join(", ")}`);
336
+ return unique;
337
+ }
338
+ const slug = (label) => label.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
339
+ async function createRole(label, permissions) {
340
+ const key = slug(label);
341
+ if (!key) throw new AuthzError("Role name is required");
342
+ if (catalog.roles.has(key) || (await db.select().from(customRole).where(eq(customRole.key, key))).length > 0) {
343
+ throw new AuthzError("A role with this name already exists", 409);
344
+ }
345
+ const perms = validatePermissions(permissions);
346
+ await db.insert(customRole).values({ key, label: label.trim(), permissions: perms });
347
+ return { key, label: label.trim(), permissions: perms, builtIn: false };
348
+ }
349
+ async function updateRole(key, label, permissions) {
350
+ if (catalog.roles.has(key)) throw new AuthzError("Built-in roles cannot be edited", 403);
351
+ const perms = validatePermissions(permissions);
352
+ const updated = await db.update(customRole).set({ label: label.trim(), permissions: perms, updatedAt: /* @__PURE__ */ new Date() }).where(eq(customRole.key, key)).returning({ key: customRole.key });
353
+ if (updated.length === 0) throw new AuthzError("Role not found", 404);
354
+ return { key, label: label.trim(), permissions: perms, builtIn: false };
355
+ }
356
+ async function deleteRole(key) {
357
+ if (catalog.roles.has(key)) throw new AuthzError("Built-in roles cannot be deleted", 403);
358
+ const [inUse] = await db.select({ n: count() }).from(member).where(sql2`',' || ${member.role} || ',' like ${`%,${key},%`}`);
359
+ if ((inUse?.n ?? 0) > 0) throw new AuthzError("This role is still assigned to users", 409);
360
+ const deleted = await db.delete(customRole).where(eq(customRole.key, key)).returning({ key: customRole.key });
361
+ if (deleted.length === 0) throw new AuthzError("Role not found", 404);
362
+ }
363
+ return {
364
+ db,
365
+ catalog,
366
+ audit,
367
+ listRoles,
368
+ roleKeysOf,
369
+ permissionsOf,
370
+ accessOf,
371
+ normaliseRoles,
372
+ onJoined,
373
+ joinPendingInvitation,
374
+ setUserRoles,
375
+ setDeactivated,
376
+ renewAccess,
377
+ createRole,
378
+ updateRole,
379
+ deleteRole
380
+ };
381
+ }
382
+
383
+ // src/email/index.ts
384
+ import nodemailer from "nodemailer";
385
+ function consoleEmailSender() {
386
+ return {
387
+ async send({ to, subject, text: text6 }) {
388
+ console.log(`
389
+ --- EMAIL to ${to} ---
390
+ Subject: ${subject}
391
+
392
+ ${text6}
393
+ --- END EMAIL ---
394
+ `);
395
+ }
396
+ };
397
+ }
398
+ function smtpSender({ host, port, user: user2, password, from, replyTo }) {
399
+ const transport = nodemailer.createTransport({
400
+ host,
401
+ port,
402
+ secure: port === 465,
403
+ auth: user2 ? { user: user2, pass: password } : void 0
404
+ });
405
+ return {
406
+ async send({ to, subject, text: text6 }) {
407
+ await transport.sendMail({ from, replyTo: replyTo || void 0, to, subject, text: text6 });
408
+ }
409
+ };
410
+ }
411
+ function smtpEmailSender(config) {
412
+ return smtpSender({
413
+ host: config.SMTP_HOST,
414
+ port: config.SMTP_PORT,
415
+ user: config.SMTP_USER,
416
+ password: config.SMTP_PASSWORD,
417
+ from: config.EMAIL_FROM,
418
+ replyTo: config.EMAIL_REPLY_TO
419
+ });
420
+ }
421
+ function createEmailSender(config, connections) {
422
+ const fromEnvironment = config.EMAIL_TRANSPORT === "smtp" ? smtpEmailSender(config) : consoleEmailSender();
423
+ return connections ? connections.emailSender(fromEnvironment) : fromEnvironment;
424
+ }
425
+
426
+ // src/connections/types.ts
427
+ var CONNECTION_KINDS = ["llm", "storage", "email"];
428
+ var CONNECTION_ID = /^[a-z][a-z0-9-]{0,39}$/;
429
+ var BACKUP_STORAGE = "appai-backup";
430
+ var EMAIL_CONNECTION = "appai-email";
431
+ var DEFAULT_STORAGE = "default";
432
+ var ConnectionError = class extends AuthzError {
433
+ constructor(message) {
434
+ super(message, 409);
435
+ }
436
+ };
437
+
438
+ // src/connections/service.ts
439
+ import { randomBytes as randomBytes2 } from "crypto";
440
+ import { and as and2, desc as desc3, eq as eq2, gte, sql as sql3 } from "drizzle-orm";
441
+ import { generateText, streamText, Output } from "ai";
442
+
443
+ // src/connections/providers.ts
444
+ import { createAnthropic } from "@ai-sdk/anthropic";
445
+ import { createAzure } from "@ai-sdk/azure";
446
+ import { createGoogle } from "@ai-sdk/google";
447
+ import { createMistral } from "@ai-sdk/mistral";
448
+ import { createOpenAI } from "@ai-sdk/openai";
449
+ import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
450
+ import { isAbsolute, resolve as resolve2, sep as sep2 } from "path";
451
+
452
+ // src/connections/oauth.ts
453
+ async function postForm(fetchFn, url, form) {
454
+ const res = await fetchFn(url, {
455
+ method: "POST",
456
+ headers: { "content-type": "application/x-www-form-urlencoded" },
457
+ body: new URLSearchParams(form)
458
+ });
459
+ const body = await res.json().catch(() => ({}));
460
+ if (!res.ok) {
461
+ const reason = String(body.error_description ?? body.error ?? res.statusText);
462
+ throw new Error(`Sign-in with the provider failed: ${reason}`);
463
+ }
464
+ return body;
465
+ }
466
+ function createTokenSource({ tokenUrl, clientId, clientSecret, refreshToken, fetch: fetchFn, now = Date.now }) {
467
+ let cached = null;
468
+ const token = async () => {
469
+ if (cached && cached.expiresAt - 6e4 > now()) return cached.token;
470
+ const body = await postForm(fetchFn, tokenUrl, {
471
+ grant_type: "refresh_token",
472
+ refresh_token: refreshToken,
473
+ client_id: clientId,
474
+ client_secret: clientSecret
475
+ });
476
+ const access = String(body.access_token ?? "");
477
+ if (!access) throw new Error("The provider did not return an access token");
478
+ cached = { token: access, expiresAt: now() + Number(body.expires_in ?? 3600) * 1e3 };
479
+ return access;
480
+ };
481
+ return Object.assign(token, { forget: () => void (cached = null) });
482
+ }
483
+ function authorizedFetch(fetchFn, token) {
484
+ return async (input, init) => {
485
+ for (let attempt = 0; ; attempt++) {
486
+ const headers = new Headers(init?.headers);
487
+ headers.set("authorization", `Bearer ${await token()}`);
488
+ const res = await fetchFn(input, { ...init, headers });
489
+ if (res.status !== 401 || attempt > 0) return res;
490
+ token.forget();
491
+ }
492
+ };
493
+ }
494
+
495
+ // src/storage/chunks.ts
496
+ async function* chunksOf(stream, size) {
497
+ let pending = [];
498
+ let held = 0;
499
+ for await (const part of stream) {
500
+ const buffer = Buffer.isBuffer(part) ? part : Buffer.from(part);
501
+ pending.push(buffer);
502
+ held += buffer.length;
503
+ while (held >= size) {
504
+ const all = Buffer.concat(pending);
505
+ yield all.subarray(0, size);
506
+ const rest = all.subarray(size);
507
+ pending = rest.length > 0 ? [rest] : [];
508
+ held = rest.length;
509
+ }
510
+ }
511
+ if (held > 0) yield Buffer.concat(pending);
512
+ }
513
+ var asBody = (buffer) => buffer;
514
+
515
+ // src/storage/dropbox.ts
516
+ var CHUNK = 32 * 1024 * 1024;
517
+ function createDropboxStorage({ clientId, clientSecret, refreshToken, fetch: base = fetch }) {
518
+ const token = createTokenSource({ tokenUrl: "https://api.dropboxapi.com/oauth2/token", clientId, clientSecret, refreshToken, fetch: base });
519
+ const call = authorizedFetch(base, token);
520
+ const fail = async (what, res) => {
521
+ const text6 = await res.text().catch(() => "");
522
+ throw new Error(`Dropbox ${what} failed (${res.status}): ${text6.slice(0, 300)}`);
523
+ };
524
+ const isMissing = async (res) => res.status === 409 && /not_found/.test(await res.clone().text().catch(() => ""));
525
+ const rpc = (endpoint, body) => call(`https://api.dropboxapi.com/2/${endpoint}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
526
+ const content = (endpoint, arg, body) => call(`https://content.dropboxapi.com/2/${endpoint}`, {
527
+ method: "POST",
528
+ headers: { "dropbox-api-arg": JSON.stringify(arg), "content-type": "application/octet-stream" },
529
+ body: body && asBody(body)
530
+ });
531
+ const path = (key) => {
532
+ assertValidKey(key);
533
+ return `/${key}`;
534
+ };
535
+ async function upload(key, data) {
536
+ const res = await content("files/upload", { path: path(key), mode: "overwrite", mute: true }, data);
537
+ if (!res.ok) await fail("upload", res);
538
+ }
539
+ async function uploadInChunks(key, data) {
540
+ let sessionId = null;
541
+ let offset = 0;
542
+ let held = null;
543
+ const send = async (chunk) => {
544
+ if (!sessionId) {
545
+ const res2 = await content("files/upload_session/start", { close: false }, chunk);
546
+ if (!res2.ok) await fail("upload", res2);
547
+ sessionId = (await res2.json()).session_id;
548
+ } else {
549
+ const res2 = await content("files/upload_session/append_v2", { cursor: { session_id: sessionId, offset }, close: false }, chunk);
550
+ if (!res2.ok) await fail("upload", res2);
551
+ }
552
+ offset += chunk.length;
553
+ };
554
+ for await (const chunk of chunksOf(data, CHUNK)) {
555
+ if (held) await send(held);
556
+ held = chunk;
557
+ }
558
+ if (!sessionId) return upload(key, held ?? Buffer.alloc(0));
559
+ const res = await content(
560
+ "files/upload_session/finish",
561
+ { cursor: { session_id: sessionId, offset }, commit: { path: path(key), mode: "overwrite", mute: true } },
562
+ held
563
+ );
564
+ if (!res.ok) await fail("upload", res);
565
+ }
566
+ async function list(prefix) {
567
+ const files = [];
568
+ let res = await rpc("files/list_folder", { path: prefix ? path(prefix) : "", recursive: true, limit: 1e3 });
569
+ for (; ; ) {
570
+ if (await isMissing(res)) return [];
571
+ if (!res.ok) await fail("listing", res);
572
+ const page = await res.json();
573
+ for (const e of page.entries) if (e[".tag"] === "file") files.push({ key: e.path_display.replace(/^\//, ""), size: e.size ?? 0 });
574
+ if (!page.has_more) return files;
575
+ res = await rpc("files/list_folder/continue", { cursor: page.cursor });
576
+ }
577
+ }
578
+ async function remove(target) {
579
+ const res = await rpc("files/delete_v2", { path: target });
580
+ if (!res.ok && !await isMissing(res)) await fail("delete", res);
581
+ }
582
+ return {
583
+ put: (key, data) => upload(key, Buffer.from(data)),
584
+ putStream: (key, data) => uploadInChunks(key, data),
585
+ async get(key) {
586
+ const res = await content("files/download", { path: path(key) });
587
+ if (await isMissing(res)) return null;
588
+ if (!res.ok) await fail("download", res);
589
+ return Buffer.from(await res.arrayBuffer());
590
+ },
591
+ delete: (key) => remove(path(key)),
592
+ list,
593
+ deleteTree: (prefix) => remove(path(prefix))
594
+ };
595
+ }
596
+
597
+ // src/storage/googledrive.ts
598
+ import { Readable } from "stream";
599
+ var FOLDER = "application/vnd.google-apps.folder";
600
+ var API = "https://www.googleapis.com/drive/v3";
601
+ var UPLOAD = "https://www.googleapis.com/upload/drive/v3";
602
+ var CHUNK2 = 8 * 1024 * 1024;
603
+ var quote = (s) => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
604
+ function createGoogleDriveStorage(o) {
605
+ const base = o.fetch ?? fetch;
606
+ const token = createTokenSource({ tokenUrl: "https://oauth2.googleapis.com/token", clientId: o.clientId, clientSecret: o.clientSecret, refreshToken: o.refreshToken, fetch: base });
607
+ const call = authorizedFetch(base, token);
608
+ const known = /* @__PURE__ */ new Map();
609
+ let root = o.folderId;
610
+ const fail = async (what, res) => {
611
+ const text6 = await res.text().catch(() => "");
612
+ throw new Error(`Google Drive ${what} failed (${res.status}): ${text6.slice(0, 300)}`);
613
+ };
614
+ const json = async (what, res) => {
615
+ if (!res.ok) await fail(what, res);
616
+ return await res.json();
617
+ };
618
+ const sendJson = (url, method, body) => call(url, { method, headers: { "content-type": "application/json; charset=UTF-8" }, body: JSON.stringify(body) });
619
+ async function children(parent, extra = "") {
620
+ const items = [];
621
+ let pageToken = "";
622
+ do {
623
+ const params = new URLSearchParams({
624
+ q: `${quote(parent)} in parents and trashed = false${extra}`,
625
+ fields: "nextPageToken,files(id,name,mimeType,size)",
626
+ pageSize: "1000",
627
+ spaces: "drive",
628
+ ...pageToken ? { pageToken } : {}
629
+ });
630
+ const page = await json("listing", await call(`${API}/files?${params}`));
631
+ items.push(...page.files);
632
+ pageToken = page.nextPageToken ?? "";
633
+ } while (pageToken);
634
+ return items;
635
+ }
636
+ async function createFolder(name2, parent) {
637
+ const made = await json("folder creation", await sendJson(`${API}/files`, "POST", { name: name2, mimeType: FOLDER, parents: [parent] }));
638
+ return made.id;
639
+ }
640
+ async function rootId() {
641
+ if (root) return root;
642
+ const existing = (await children("root", ` and mimeType = '${FOLDER}' and name = ${quote(o.folderName)}`))[0];
643
+ root = existing?.id ?? await createFolder(o.folderName, "root");
644
+ await o.saveFolderId(root);
645
+ return root;
646
+ }
647
+ async function folder(segments, create) {
648
+ let parent = await rootId();
649
+ for (let i = 0; i < segments.length; i++) {
650
+ const path = segments.slice(0, i + 1).join("/");
651
+ let id = known.get(path);
652
+ if (!id) {
653
+ const found = (await children(parent, ` and mimeType = '${FOLDER}' and name = ${quote(segments[i])}`))[0];
654
+ id = found?.id ?? (create ? await createFolder(segments[i], parent) : void 0);
655
+ if (!id) return null;
656
+ known.set(path, id);
657
+ }
658
+ parent = id;
659
+ }
660
+ return parent;
661
+ }
662
+ const split = (key) => {
663
+ assertValidKey(key);
664
+ const parts = key.split("/");
665
+ return { dirs: parts.slice(0, -1), name: parts[parts.length - 1] };
666
+ };
667
+ async function fileId(key) {
668
+ const { dirs, name: name2 } = split(key);
669
+ const parent = await folder(dirs, false);
670
+ if (!parent) return null;
671
+ return (await children(parent, ` and name = ${quote(name2)} and mimeType != '${FOLDER}'`))[0]?.id ?? null;
672
+ }
673
+ async function putStream(key, data, size) {
674
+ const { dirs, name: name2 } = split(key);
675
+ const parent = await folder(dirs, true);
676
+ const existing = (await children(parent, ` and name = ${quote(name2)} and mimeType != '${FOLDER}'`))[0];
677
+ if (size === 0) {
678
+ if (existing) return;
679
+ await json("upload", await sendJson(`${API}/files`, "POST", { name: name2, parents: [parent] }));
680
+ return;
681
+ }
682
+ const start = await call(
683
+ existing ? `${UPLOAD}/files/${existing.id}?uploadType=resumable` : `${UPLOAD}/files?uploadType=resumable`,
684
+ {
685
+ method: existing ? "PATCH" : "POST",
686
+ headers: { "content-type": "application/json; charset=UTF-8", "x-upload-content-length": String(size) },
687
+ body: JSON.stringify(existing ? {} : { name: name2, parents: [parent] })
688
+ }
689
+ );
690
+ if (!start.ok) await fail("upload", start);
691
+ const session = start.headers.get("location");
692
+ if (!session) throw new Error("Google Drive did not start an upload session");
693
+ let offset = 0;
694
+ for await (const chunk of chunksOf(data, CHUNK2)) {
695
+ const res = await call(session, {
696
+ method: "PUT",
697
+ headers: { "content-range": `bytes ${offset}-${offset + chunk.length - 1}/${size}` },
698
+ body: asBody(chunk),
699
+ redirect: "manual"
700
+ });
701
+ offset += chunk.length;
702
+ if (res.status !== 308 && res.status !== 200 && res.status !== 201) await fail("upload", res);
703
+ }
704
+ if (offset !== size) throw new Error(`Google Drive upload: expected ${size} bytes but sent ${offset}`);
705
+ }
706
+ async function walk(parent, prefix) {
707
+ const files = [];
708
+ for (const item of await children(parent)) {
709
+ const key = prefix ? `${prefix}/${item.name}` : item.name;
710
+ if (item.mimeType === FOLDER) files.push(...await walk(item.id, key));
711
+ else files.push({ key, size: Number(item.size ?? 0) });
712
+ }
713
+ return files;
714
+ }
715
+ return {
716
+ put: (key, data) => putStream(key, Readable.from(Buffer.from(data)), data.length),
717
+ putStream,
718
+ async get(key) {
719
+ const id = await fileId(key);
720
+ if (!id) return null;
721
+ const res = await call(`${API}/files/${id}?alt=media`);
722
+ if (res.status === 404) return null;
723
+ if (!res.ok) await fail("download", res);
724
+ return Buffer.from(await res.arrayBuffer());
725
+ },
726
+ async delete(key) {
727
+ const id = await fileId(key);
728
+ if (!id) return;
729
+ const res = await call(`${API}/files/${id}`, { method: "DELETE" });
730
+ if (!res.ok && res.status !== 404) await fail("delete", res);
731
+ },
732
+ async list(prefix) {
733
+ const start = await folder(prefix ? prefix.split("/") : [], false);
734
+ return start ? walk(start, prefix) : [];
735
+ },
736
+ async deleteTree(prefix) {
737
+ if (!prefix) throw new Error("Refusing to delete the whole storage");
738
+ assertValidKey(prefix);
739
+ const id = await folder(prefix.split("/"), false);
740
+ if (!id) return;
741
+ const res = await call(`${API}/files/${id}`, { method: "DELETE" });
742
+ if (!res.ok && res.status !== 404) await fail("delete", res);
743
+ for (const path of known.keys()) if (path === prefix || path.startsWith(`${prefix}/`)) known.delete(path);
744
+ }
745
+ };
746
+ }
747
+
748
+ // src/storage/s3.ts
749
+ import { DeleteObjectCommand, DeleteObjectsCommand, GetObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
750
+ import { Upload } from "@aws-sdk/lib-storage";
751
+ function createS3Storage(o) {
752
+ const client = o.client ?? new S3Client({
753
+ region: o.region,
754
+ endpoint: o.endpoint || void 0,
755
+ forcePathStyle: o.forcePathStyle,
756
+ credentials: { accessKeyId: o.accessKeyId, secretAccessKey: o.secretAccessKey },
757
+ // Not every S3-compatible service accepts the checksums that newer AWS SDKs add by default.
758
+ requestChecksumCalculation: "WHEN_REQUIRED",
759
+ responseChecksumValidation: "WHEN_REQUIRED"
760
+ });
761
+ const folder = (o.prefix ?? "").replace(/^\/+|\/+$/g, "");
762
+ const full = (key2) => folder ? `${folder}/${key2}` : key2;
763
+ const key = (k) => {
764
+ assertValidKey(k);
765
+ return full(k);
766
+ };
767
+ async function list(prefix) {
768
+ const files = [];
769
+ const strip = folder ? folder.length + 1 : 0;
770
+ let token;
771
+ const start = prefix ? `${key(prefix)}/` : folder ? `${folder}/` : "";
772
+ do {
773
+ const page = await client.send(new ListObjectsV2Command({ Bucket: o.bucket, Prefix: start, ContinuationToken: token }));
774
+ for (const item of page.Contents ?? []) if (item.Key && !item.Key.endsWith("/")) files.push({ key: item.Key.slice(strip), size: item.Size ?? 0 });
775
+ token = page.IsTruncated ? page.NextContinuationToken : void 0;
776
+ } while (token);
777
+ return files;
778
+ }
779
+ return {
780
+ async put(k, data) {
781
+ await client.send(new PutObjectCommand({ Bucket: o.bucket, Key: key(k), Body: data }));
782
+ },
783
+ async putStream(k, data) {
784
+ await new Upload({ client, params: { Bucket: o.bucket, Key: key(k), Body: data } }).done();
785
+ },
786
+ async get(k) {
787
+ try {
788
+ const res = await client.send(new GetObjectCommand({ Bucket: o.bucket, Key: key(k) }));
789
+ return Buffer.from(await res.Body.transformToByteArray());
790
+ } catch (e) {
791
+ if (e.name === "NoSuchKey") return null;
792
+ throw e;
793
+ }
794
+ },
795
+ async delete(k) {
796
+ await client.send(new DeleteObjectCommand({ Bucket: o.bucket, Key: key(k) }));
797
+ },
798
+ list,
799
+ async deleteTree(prefix) {
800
+ if (!prefix) throw new Error("Refusing to delete the whole storage");
801
+ const keys = (await list(prefix)).map((f) => full(f.key));
802
+ for (let i = 0; i < keys.length; i += 1e3) {
803
+ await client.send(new DeleteObjectsCommand({ Bucket: o.bucket, Delete: { Objects: keys.slice(i, i + 1e3).map((Key) => ({ Key })), Quiet: true } }));
804
+ }
805
+ }
806
+ };
807
+ }
808
+
809
+ // src/connections/providers.ts
810
+ var str = (v) => typeof v === "string" ? v : "";
811
+ var local = {
812
+ kind: "storage",
813
+ key: "local",
814
+ label: "Folder on this server",
815
+ description: "A folder on the server or on a drive mounted into it, for example a NAS or a USB disk.",
816
+ fields: [{ key: "directory", label: "Folder", type: "text", required: true, placeholder: "/mnt/backup", help: "Absolute path inside the app's container. Mount the drive in compose.override.yaml first." }],
817
+ check: (config) => isAbsolute(str(config.directory)) ? null : "The folder must be an absolute path such as /mnt/backup",
818
+ inBackup: ({ config }, filesDir) => {
819
+ const dir = resolve2(str(config.directory));
820
+ const files = resolve2(filesDir);
821
+ return dir === files || dir.startsWith(files + sep2);
822
+ },
823
+ create: ({ config }) => createLocalFileStorage(str(config.directory))
824
+ };
825
+ var s3 = {
826
+ kind: "storage",
827
+ key: "s3",
828
+ label: "S3-compatible bucket",
829
+ description: "Amazon S3, Hetzner, Scaleway, OVH, Backblaze B2, Cloudflare R2, Wasabi, MinIO and others.",
830
+ fields: [
831
+ { key: "endpoint", label: "Endpoint address", type: "text", placeholder: "https://fsn1.your-objectstorage.com", help: "Leave empty for Amazon S3." },
832
+ { key: "region", label: "Region", type: "text", required: true, default: "eu-central-1", help: 'Use "auto" for Cloudflare R2.' },
833
+ { key: "bucket", label: "Bucket", type: "text", required: true },
834
+ { key: "prefix", label: "Folder in the bucket", type: "text", help: "Optional. Everything is stored below this folder." },
835
+ { key: "accessKeyId", label: "Access key ID", type: "text", required: true },
836
+ { key: "secretAccessKey", label: "Secret access key", type: "secret", required: true },
837
+ { key: "forcePathStyle", label: "Use path-style addresses", type: "boolean", help: "Needed for MinIO and some other providers." }
838
+ ],
839
+ create: ({ config, secrets }) => createS3Storage({
840
+ bucket: str(config.bucket),
841
+ prefix: str(config.prefix),
842
+ region: str(config.region) || "us-east-1",
843
+ endpoint: str(config.endpoint),
844
+ forcePathStyle: config.forcePathStyle === true,
845
+ accessKeyId: str(config.accessKeyId),
846
+ secretAccessKey: secrets.secretAccessKey ?? ""
847
+ })
848
+ };
849
+ var redirectHelp = "Add this redirect address in the provider's console exactly as shown.";
850
+ var oauthFields = [
851
+ { key: "clientId", label: "Client ID", type: "text", required: true },
852
+ { key: "clientSecret", label: "Client secret", type: "secret", required: true, help: redirectHelp }
853
+ ];
854
+ var dropbox = {
855
+ kind: "storage",
856
+ key: "dropbox",
857
+ label: "Dropbox",
858
+ description: `Files go into the app's own folder in Dropbox (Apps > your app). Create a Dropbox app with "App folder" access and the permissions files.content.write, files.content.read and files.metadata.read.`,
859
+ fields: [{ key: "clientId", label: "App key", type: "text", required: true }, { key: "clientSecret", label: "App secret", type: "secret", required: true, help: redirectHelp }],
860
+ oauth: {
861
+ authorizeUrl: (ctx, state) => `https://www.dropbox.com/oauth2/authorize?${new URLSearchParams({ client_id: str(ctx.config.clientId), response_type: "code", token_access_type: "offline", redirect_uri: ctx.redirectUri, state })}`,
862
+ async exchange(ctx, code) {
863
+ const body = await postForm(ctx.fetch, "https://api.dropboxapi.com/oauth2/token", {
864
+ grant_type: "authorization_code",
865
+ code,
866
+ redirect_uri: ctx.redirectUri,
867
+ client_id: str(ctx.config.clientId),
868
+ client_secret: ctx.secrets.clientSecret ?? ""
869
+ });
870
+ if (!body.refresh_token) throw new Error("Dropbox did not return a refresh token. Check that the app allows offline access.");
871
+ return { refreshToken: String(body.refresh_token) };
872
+ }
873
+ },
874
+ inBackup: () => false,
875
+ create: ({ config, secrets, fetch: fetch2 }) => createDropboxStorage({ clientId: str(config.clientId), clientSecret: secrets.clientSecret ?? "", refreshToken: secrets.refreshToken ?? "", fetch: fetch2 })
876
+ };
877
+ var googleDrive = {
878
+ kind: "storage",
879
+ key: "googledrive",
880
+ label: "Google Drive",
881
+ description: "Files go into one folder of the signed-in Google account. Create an OAuth client (type: web application) in Google Cloud and allow the scope .../auth/drive.file; the app then sees only the files it created.",
882
+ fields: [
883
+ ...oauthFields,
884
+ { key: "folderName", label: "Folder in My Drive", type: "text", default: "appai", help: "Created when you connect. Everything is stored inside it." }
885
+ ],
886
+ oauth: {
887
+ authorizeUrl: (ctx, state) => `https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({
888
+ client_id: str(ctx.config.clientId),
889
+ redirect_uri: ctx.redirectUri,
890
+ response_type: "code",
891
+ scope: "https://www.googleapis.com/auth/drive.file",
892
+ access_type: "offline",
893
+ prompt: "consent",
894
+ state
895
+ })}`,
896
+ async exchange(ctx, code) {
897
+ const body = await postForm(ctx.fetch, "https://oauth2.googleapis.com/token", {
898
+ grant_type: "authorization_code",
899
+ code,
900
+ redirect_uri: ctx.redirectUri,
901
+ client_id: str(ctx.config.clientId),
902
+ client_secret: ctx.secrets.clientSecret ?? ""
903
+ });
904
+ if (!body.refresh_token) throw new Error("Google did not return a refresh token. Remove the app's access in your Google account and connect again.");
905
+ return { refreshToken: String(body.refresh_token) };
906
+ }
907
+ },
908
+ inBackup: () => false,
909
+ create: ({ config, secrets, fetch: fetch2, saveConfig }) => createGoogleDriveStorage({
910
+ clientId: str(config.clientId),
911
+ clientSecret: secrets.clientSecret ?? "",
912
+ refreshToken: secrets.refreshToken ?? "",
913
+ folderName: str(config.folderName) || "appai",
914
+ folderId: str(config.folderId) || void 0,
915
+ saveFolderId: (folderId) => saveConfig({ folderId }),
916
+ fetch: fetch2
917
+ })
918
+ };
919
+ var storageProviders = [googleDrive, dropbox, s3, local];
920
+ var llmFields = (extra, key) => [
921
+ ...extra,
922
+ ...key ? [key] : [],
923
+ { key: "model", label: "Model", type: "text", required: true, placeholder: "model name" },
924
+ { key: "maxOutputTokens", label: "Longest answer (tokens)", type: "number", min: 1, max: 2e5, help: "Optional upper limit for one answer." },
925
+ { key: "temperature", label: "Temperature", type: "number", min: 0, max: 2, help: "Optional. Lower is more predictable." },
926
+ { key: "timeoutSeconds", label: "Give up after (seconds)", type: "number", min: 5, max: 900, default: 120 },
927
+ { key: "local", label: "Runs on our own server or network", type: "boolean", help: "Nothing leaves your premises." },
928
+ { key: "personalDataApproved", label: "Approved for personal data", type: "boolean", help: "Only connections you tick here are used by features that send personal data." }
929
+ ];
930
+ var apiKey = (required) => ({ key: "apiKey", label: "API key", type: "secret", required });
931
+ var llm = (key, label, description2, extra, keyRequired, create) => ({
932
+ kind: "llm",
933
+ key,
934
+ label,
935
+ description: description2,
936
+ fields: llmFields(extra, apiKey(keyRequired)),
937
+ create: (ctx) => create(ctx, str(ctx.config.model))
938
+ });
939
+ var llmProviders = [
940
+ llm(
941
+ "anthropic",
942
+ "Anthropic (Claude)",
943
+ "Claude models through the Anthropic API.",
944
+ [],
945
+ true,
946
+ (ctx, model) => createAnthropic({ apiKey: ctx.secrets.apiKey, fetch: ctx.fetch })(model)
947
+ ),
948
+ llm("openai", "OpenAI", "GPT models through the OpenAI API.", [], true, (ctx, model) => createOpenAI({ apiKey: ctx.secrets.apiKey, fetch: ctx.fetch })(model)),
949
+ llm("google", "Google (Gemini)", "Gemini models through the Google AI API.", [], true, (ctx, model) => createGoogle({ apiKey: ctx.secrets.apiKey, fetch: ctx.fetch })(model)),
950
+ llm("mistral", "Mistral", "Mistral models (hosted in the EU).", [], true, (ctx, model) => createMistral({ apiKey: ctx.secrets.apiKey, fetch: ctx.fetch })(model)),
951
+ llm(
952
+ "azure",
953
+ "Azure OpenAI",
954
+ "Models you deployed in your own Azure OpenAI resource. Use the deployment name as the model.",
955
+ [{ key: "resourceName", label: "Azure resource name", type: "text", required: true }],
956
+ true,
957
+ (ctx, model) => createAzure({ resourceName: str(ctx.config.resourceName), apiKey: ctx.secrets.apiKey, fetch: ctx.fetch })(model)
958
+ ),
959
+ llm(
960
+ "openai-compatible",
961
+ "OpenAI-compatible server",
962
+ "Ollama, LM Studio, vLLM, llama.cpp, a LiteLLM gateway or any server that speaks the OpenAI API.",
963
+ [{ key: "baseURL", label: "Server address", type: "text", required: true, placeholder: "http://host.docker.internal:11434/v1" }],
964
+ false,
965
+ (ctx, model) => createOpenAICompatible({ name: "openai-compatible", baseURL: str(ctx.config.baseURL), apiKey: ctx.secrets.apiKey, fetch: ctx.fetch }).chatModel(model)
966
+ )
967
+ ];
968
+ var looksLikeAddress = (text6) => /^[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+$/.test(text6.replace(/^.*<(.*)>\s*$/, "$1").trim());
969
+ var smtp = {
970
+ kind: "email",
971
+ key: "smtp",
972
+ label: "SMTP server",
973
+ description: "Any mailbox or mail service that offers SMTP: Google Workspace (smtp.gmail.com with an app password), Microsoft 365, the customer's own mail server or a transactional provider.",
974
+ fields: [
975
+ { key: "host", label: "Server", type: "text", required: true, placeholder: "smtp.gmail.com" },
976
+ { key: "port", label: "Port", type: "number", required: true, default: 587, min: 1, max: 65535, help: "587 (STARTTLS) for most servers; 465 for a server that uses TLS from the start." },
977
+ { key: "user", label: "User name", type: "text", help: "Usually the full address of the sending mailbox. Leave empty for a server that needs no sign-in." },
978
+ { key: "password", label: "Password", type: "secret", help: "For Google Workspace use an app password, not the mailbox password." },
979
+ { key: "from", label: "Sender", type: "text", required: true, placeholder: "Customer Name <no-reply@customer.eu>", help: "Shown as the sender of every email. The mail server usually requires an address it hosts or has approved." },
980
+ { key: "replyTo", label: "Reply-to address", type: "text", placeholder: "privacy@customer.eu", help: "Optional. Replies go here instead of to the sender." }
981
+ ],
982
+ check: (config) => {
983
+ if (!looksLikeAddress(str(config.from))) return "The sender must contain an email address, for example Customer Name <no-reply@customer.eu>";
984
+ if (str(config.replyTo) && !looksLikeAddress(str(config.replyTo))) return "The reply-to address is not a valid email address";
985
+ return null;
986
+ },
987
+ create: ({ config, secrets }) => smtpSender({
988
+ host: str(config.host),
989
+ port: typeof config.port === "number" ? config.port : 587,
990
+ user: str(config.user) || void 0,
991
+ password: secrets.password,
992
+ from: str(config.from),
993
+ replyTo: str(config.replyTo) || void 0
994
+ })
995
+ };
996
+ var emailProviders = [smtp];
997
+ var frameworkProviders = [...storageProviders, ...llmProviders, ...emailProviders];
998
+
999
+ // src/connections/schema.ts
1000
+ import { boolean, index, integer, jsonb as jsonb2, pgTable as pgTable2, primaryKey, text as text2, timestamp as timestamp2, uuid as uuid2 } from "drizzle-orm/pg-core";
1001
+ var connection = pgTable2(
1002
+ "connection",
1003
+ {
1004
+ /** llm | storage */
1005
+ kind: text2("kind").notNull(),
1006
+ id: text2("id").notNull(),
1007
+ label: text2("label").notNull(),
1008
+ provider: text2("provider").notNull(),
1009
+ config: jsonb2("config").$type().notNull().default({}),
1010
+ /** Encrypted JSON object, see secrets.ts. */
1011
+ secrets: text2("secrets"),
1012
+ enabled: boolean("enabled").notNull().default(true),
1013
+ lastTestAt: timestamp2("last_test_at"),
1014
+ lastTestOk: boolean("last_test_ok"),
1015
+ lastTestMessage: text2("last_test_message"),
1016
+ createdAt: timestamp2("created_at").defaultNow().notNull(),
1017
+ updatedAt: timestamp2("updated_at").defaultNow().notNull(),
1018
+ updatedBy: text2("updated_by")
1019
+ },
1020
+ (t) => [primaryKey({ columns: [t.kind, t.id] })]
1021
+ );
1022
+ var llmCall = pgTable2(
1023
+ "llm_call",
1024
+ {
1025
+ id: uuid2("id").primaryKey().defaultRandom(),
1026
+ at: timestamp2("at").defaultNow().notNull(),
1027
+ connectionId: text2("connection_id").notNull(),
1028
+ model: text2("model").notNull(),
1029
+ inputTokens: integer("input_tokens"),
1030
+ outputTokens: integer("output_tokens"),
1031
+ durationMs: integer("duration_ms").notNull(),
1032
+ /** ok | error */
1033
+ status: text2("status").notNull(),
1034
+ error: text2("error"),
1035
+ userId: text2("user_id"),
1036
+ /** What the app used it for, e.g. "policy-summary". */
1037
+ feature: text2("feature")
1038
+ },
1039
+ (t) => [index("llm_call_at_idx").on(t.at)]
1040
+ );
1041
+
1042
+ // src/connections/secrets.ts
1043
+ import { createCipheriv, createDecipheriv, createHmac, hkdfSync, randomBytes, timingSafeEqual } from "crypto";
1044
+ var VERSION = "v1";
1045
+ function createSecretBox(secret) {
1046
+ const derive2 = (info) => Buffer.from(hkdfSync("sha256", secret, "appai-secrets-v1", info, 32));
1047
+ const key = derive2("connection-secrets");
1048
+ const signingKey = derive2("signed-values");
1049
+ return {
1050
+ encrypt(values) {
1051
+ const iv = randomBytes(12);
1052
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
1053
+ const data = Buffer.concat([cipher.update(JSON.stringify(values), "utf8"), cipher.final()]);
1054
+ return `${VERSION}.${Buffer.concat([iv, cipher.getAuthTag(), data]).toString("base64url")}`;
1055
+ },
1056
+ /** Throws when the text was changed or was encrypted with another key. */
1057
+ decrypt(text6) {
1058
+ const [version, body] = text6.split(".");
1059
+ if (version !== VERSION || !body) throw new Error("Unknown format of stored credentials");
1060
+ const raw = Buffer.from(body, "base64url");
1061
+ const decipher = createDecipheriv("aes-256-gcm", key, raw.subarray(0, 12));
1062
+ decipher.setAuthTag(raw.subarray(12, 28));
1063
+ try {
1064
+ return JSON.parse(Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString("utf8"));
1065
+ } catch (e) {
1066
+ throw new Error("Stored credentials cannot be read (was SECRETS_KEY or AUTH_SECRET changed?). Enter them again.", { cause: e });
1067
+ }
1068
+ },
1069
+ /** `payload.signature`, readable by anyone but not forgeable. */
1070
+ sign(payload) {
1071
+ const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
1072
+ return `${body}.${createHmac("sha256", signingKey).update(body).digest("base64url")}`;
1073
+ },
1074
+ verify(signed) {
1075
+ const [body, signature] = signed.split(".");
1076
+ if (!body || !signature) return null;
1077
+ const expected = createHmac("sha256", signingKey).update(body).digest();
1078
+ const given = Buffer.from(signature, "base64url");
1079
+ if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null;
1080
+ try {
1081
+ return JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
1082
+ } catch {
1083
+ return null;
1084
+ }
1085
+ }
1086
+ };
1087
+ }
1088
+
1089
+ // src/connections/service.ts
1090
+ var KIND_LABEL = { llm: "AI model", storage: "Storage", email: "Email" };
1091
+ var OAUTH_MINUTES = 10;
1092
+ var frameworkSlots = [
1093
+ {
1094
+ kind: "storage",
1095
+ id: BACKUP_STORAGE,
1096
+ purpose: "Where backups are copied to (Status page). Backups are copied to this storage and to no other.",
1097
+ extraFields: [
1098
+ {
1099
+ key: "encryptionPassphrase",
1100
+ label: "Backup passphrase",
1101
+ type: "secret",
1102
+ help: "Optional. When set, backups are encrypted before they are copied. Keep the passphrase outside this server: without it the copies cannot be opened."
1103
+ }
1104
+ ]
1105
+ },
1106
+ {
1107
+ kind: "email",
1108
+ id: EMAIL_CONNECTION,
1109
+ purpose: "How the app sends invitations, password resets, reminders and alerts. Without it the server's EMAIL_* settings are used."
1110
+ }
1111
+ ];
1112
+ function redact(text6, secrets) {
1113
+ let out = text6;
1114
+ for (const value of Object.values(secrets)) if (value.length >= 6) out = out.split(value).join("***");
1115
+ return out.slice(0, 400);
1116
+ }
1117
+ function createConnections({ db, config, slots = [], providers = [], fetch: fetchFn = fetch }) {
1118
+ const box = createSecretBox(config.SECRETS_KEY ?? config.AUTH_SECRET);
1119
+ const publicUrl = config.PUBLIC_URL.replace(/\/+$/, "");
1120
+ const allProviders = /* @__PURE__ */ new Map();
1121
+ for (const p of [...frameworkProviders, ...providers]) allProviders.set(`${p.kind}:${p.key}`, p);
1122
+ const allSlots = [...frameworkSlots];
1123
+ for (const slot of slots) {
1124
+ if (!CONNECTION_ID.test(slot.id)) throw new Error(`Invalid connection id "${slot.id}" (use lowercase letters, digits and dashes)`);
1125
+ if (slot.id === DEFAULT_STORAGE && slot.kind === "storage") throw new Error(`The storage "${DEFAULT_STORAGE}" is built in`);
1126
+ if (allSlots.some((s) => s.kind === slot.kind && s.id === slot.id)) throw new Error(`Connection ${slot.kind} "${slot.id}" is declared twice`);
1127
+ allSlots.push(slot);
1128
+ }
1129
+ const rows = /* @__PURE__ */ new Map();
1130
+ let loaded = null;
1131
+ const keyOf = (kind, id) => `${kind}:${id}`;
1132
+ const ready = () => loaded ??= db.select().from(connection).then((all) => {
1133
+ rows.clear();
1134
+ for (const row of all) rows.set(keyOf(row.kind, row.id), row);
1135
+ });
1136
+ const slotOf = (kind, id) => allSlots.find((s) => s.kind === kind && s.id === id);
1137
+ const providerOf = (kind, key) => allProviders.get(`${kind}:${key}`);
1138
+ const fieldsOf = (provider, slot) => [...provider.fields, ...slot?.extraFields ?? []];
1139
+ const redirectUri = (kind) => `${publicUrl}/api/connections/${kind}/oauth/callback`;
1140
+ const defaultStorage = createLocalFileStorage(config.FILES_DIR);
1141
+ function secretsOf(row) {
1142
+ return row.secrets ? box.decrypt(row.secrets) : {};
1143
+ }
1144
+ function problemOf(row, provider, secrets) {
1145
+ for (const f of fieldsOf(provider, slotOf(row.kind, row.id))) {
1146
+ if (!f.required) continue;
1147
+ const have = f.type === "secret" ? Boolean(secrets[f.key]) : row.config[f.key] !== void 0 && row.config[f.key] !== "";
1148
+ if (!have) return `${f.label} is missing`;
1149
+ }
1150
+ if (provider.kind === "storage" && provider.oauth && !secrets.refreshToken) return "Not connected yet. Use the Connect button.";
1151
+ return null;
1152
+ }
1153
+ function view(kind, id) {
1154
+ const slot = slotOf(kind, id);
1155
+ const base = {
1156
+ kind,
1157
+ id,
1158
+ purpose: slot?.purpose ?? null,
1159
+ required: slot?.required ?? false,
1160
+ declared: Boolean(slot),
1161
+ extraFields: slot?.extraFields ?? []
1162
+ };
1163
+ if (kind === "storage" && id === DEFAULT_STORAGE) {
1164
+ return {
1165
+ ...base,
1166
+ label: "This server",
1167
+ purpose: "Files kept by the app on this server. Included in every backup.",
1168
+ builtIn: true,
1169
+ provider: "local",
1170
+ providerLabel: "Folder on this server",
1171
+ config: {},
1172
+ secretsSet: [],
1173
+ enabled: true,
1174
+ status: "ok",
1175
+ problem: null,
1176
+ lastTest: null,
1177
+ inBackup: true
1178
+ };
1179
+ }
1180
+ const row = rows.get(keyOf(kind, id));
1181
+ if (!row) {
1182
+ return { ...base, label: slot?.id ?? id, builtIn: false, provider: null, providerLabel: null, config: {}, secretsSet: [], enabled: false, status: "missing", problem: null, lastTest: null, inBackup: null };
1183
+ }
1184
+ const provider = providerOf(kind, row.provider);
1185
+ let secrets = {};
1186
+ let problem = null;
1187
+ try {
1188
+ secrets = secretsOf(row);
1189
+ if (provider) problem = problemOf(row, provider, secrets);
1190
+ } catch (e) {
1191
+ problem = e.message;
1192
+ }
1193
+ if (!provider) problem = `The provider "${row.provider}" is not available in this version`;
1194
+ const lastTest = row.lastTestAt ? { at: row.lastTestAt.toISOString(), ok: row.lastTestOk === true, message: row.lastTestMessage ?? "" } : null;
1195
+ const status = !row.enabled ? "disabled" : problem ? "incomplete" : !lastTest ? "untested" : lastTest.ok ? "ok" : "failing";
1196
+ return {
1197
+ ...base,
1198
+ label: row.label,
1199
+ builtIn: false,
1200
+ provider: row.provider,
1201
+ providerLabel: provider?.label ?? row.provider,
1202
+ // Secret fields never appear in `config`; they are only reported by name.
1203
+ config: row.config,
1204
+ secretsSet: Object.keys(secrets).filter((k) => k !== "refreshToken" && secrets[k]),
1205
+ enabled: row.enabled,
1206
+ status,
1207
+ problem,
1208
+ lastTest,
1209
+ inBackup: provider?.kind === "storage" ? provider.inBackup ? provider.inBackup({ config: row.config }, config.FILES_DIR) : false : null
1210
+ };
1211
+ }
1212
+ async function list(kind) {
1213
+ await ready();
1214
+ const ids = kind === "storage" ? [DEFAULT_STORAGE] : [];
1215
+ for (const s of allSlots) if (s.kind === kind && !ids.includes(s.id)) ids.push(s.id);
1216
+ const others = [...rows.values()].filter((r) => r.kind === kind && !ids.includes(r.id)).map((r) => r.id).sort();
1217
+ return [...ids, ...others].map((id) => view(kind, id));
1218
+ }
1219
+ function providerViews(kind) {
1220
+ return [...allProviders.values()].filter((p) => p.kind === kind).map((p) => ({ kind, key: p.key, label: p.label, description: p.description ?? null, fields: p.fields, oauth: p.kind === "storage" && Boolean(p.oauth) }));
1221
+ }
1222
+ function cleanConfig(fields, input) {
1223
+ const out = {};
1224
+ for (const f of fields) {
1225
+ if (f.type === "secret") continue;
1226
+ const raw = input[f.key];
1227
+ if (raw === void 0 || raw === null || raw === "") {
1228
+ if (f.default !== void 0 && f.type !== "boolean" && f.required) out[f.key] = f.default;
1229
+ continue;
1230
+ }
1231
+ if (f.type === "number") {
1232
+ const n = Number(raw);
1233
+ if (!Number.isFinite(n)) throw new AuthzError(`${f.label} must be a number`);
1234
+ if (f.min !== void 0 && n < f.min || f.max !== void 0 && n > f.max) throw new AuthzError(`${f.label} must be between ${f.min ?? "-"} and ${f.max ?? "-"}`);
1235
+ out[f.key] = n;
1236
+ } else if (f.type === "boolean") {
1237
+ out[f.key] = raw === true || raw === "true";
1238
+ } else if (f.type === "select") {
1239
+ if (!f.options?.some((o) => o.value === raw)) throw new AuthzError(`${f.label} has an unknown choice`);
1240
+ out[f.key] = raw;
1241
+ } else {
1242
+ out[f.key] = String(raw).trim();
1243
+ }
1244
+ }
1245
+ return out;
1246
+ }
1247
+ async function save(kind, id, input, actor) {
1248
+ await ready();
1249
+ if (!CONNECTION_ID.test(id)) throw new AuthzError("The id must start with a letter and use only lowercase letters, digits and dashes (at most 40 characters)");
1250
+ if (kind === "storage" && id === DEFAULT_STORAGE) throw new AuthzError('The storage "default" is built in and cannot be changed');
1251
+ if (kind === "email" && id !== EMAIL_CONNECTION) throw new AuthzError(`The app sends email through the connection "${EMAIL_CONNECTION}" only`);
1252
+ const provider = providerOf(kind, input.provider);
1253
+ if (!provider) throw new AuthzError("Unknown provider");
1254
+ const slot = slotOf(kind, id);
1255
+ const fields = fieldsOf(provider, slot);
1256
+ const existing = rows.get(keyOf(kind, id));
1257
+ const sameProvider = existing?.provider === provider.key;
1258
+ const cleaned = cleanConfig(fields, input.config ?? {});
1259
+ const previousSecrets = existing && sameProvider ? secretsOf(existing) : {};
1260
+ const secrets = {};
1261
+ const changedSecrets = [];
1262
+ for (const f of fields) {
1263
+ if (f.type !== "secret") continue;
1264
+ const given = input.secrets?.[f.key];
1265
+ if (typeof given === "string" && given.trim() !== "") {
1266
+ secrets[f.key] = given.trim();
1267
+ changedSecrets.push(f.key);
1268
+ } else if (given !== null && previousSecrets[f.key]) secrets[f.key] = previousSecrets[f.key];
1269
+ else if (given === null && previousSecrets[f.key]) changedSecrets.push(f.key);
1270
+ }
1271
+ const sameApp = sameProvider && cleaned.clientId === existing?.config.clientId && !changedSecrets.includes("clientSecret");
1272
+ if (sameApp && previousSecrets.refreshToken) secrets.refreshToken = previousSecrets.refreshToken;
1273
+ if (sameApp && existing?.config.folderId) cleaned.folderId = existing.config.folderId;
1274
+ for (const f of fields) {
1275
+ if (!f.required) continue;
1276
+ const have = f.type === "secret" ? Boolean(secrets[f.key]) : cleaned[f.key] !== void 0;
1277
+ if (!have) throw new AuthzError(`${f.label} is required`);
1278
+ }
1279
+ const message = provider.check?.(cleaned);
1280
+ if (message) throw new AuthzError(message);
1281
+ const values = {
1282
+ kind,
1283
+ id,
1284
+ label: (input.label ?? "").trim() || existing?.label || id,
1285
+ provider: provider.key,
1286
+ config: cleaned,
1287
+ secrets: Object.keys(secrets).length > 0 ? box.encrypt(secrets) : null,
1288
+ enabled: input.enabled ?? existing?.enabled ?? true,
1289
+ lastTestAt: null,
1290
+ lastTestOk: null,
1291
+ lastTestMessage: null,
1292
+ updatedAt: /* @__PURE__ */ new Date(),
1293
+ updatedBy: actor
1294
+ };
1295
+ const [row] = await db.insert(connection).values(values).onConflictDoUpdate({ target: [connection.kind, connection.id], set: values }).returning();
1296
+ rows.set(keyOf(kind, id), row);
1297
+ return { view: view(kind, id), changedSecrets };
1298
+ }
1299
+ async function remove(kind, id) {
1300
+ await ready();
1301
+ if (kind === "storage" && id === DEFAULT_STORAGE) throw new AuthzError('The storage "default" is built in and cannot be removed');
1302
+ if (!rows.has(keyOf(kind, id))) throw new AuthzError("Connection not found", 404);
1303
+ await db.delete(connection).where(and2(eq2(connection.kind, kind), eq2(connection.id, id)));
1304
+ rows.delete(keyOf(kind, id));
1305
+ }
1306
+ const drivers = /* @__PURE__ */ new Map();
1307
+ function contextOf(row, secrets) {
1308
+ return {
1309
+ id: row.id,
1310
+ config: row.config,
1311
+ secrets,
1312
+ fetch: fetchFn,
1313
+ redirectUri: redirectUri(row.kind),
1314
+ async saveConfig(patch) {
1315
+ const current = rows.get(keyOf(row.kind, row.id)) ?? row;
1316
+ const [next] = await db.update(connection).set({ config: { ...current.config, ...patch } }).where(and2(eq2(connection.kind, row.kind), eq2(connection.id, row.id))).returning();
1317
+ if (next) rows.set(keyOf(row.kind, row.id), next);
1318
+ }
1319
+ };
1320
+ }
1321
+ async function driver(kind, id) {
1322
+ await ready();
1323
+ const where = `${KIND_LABEL[kind]} "${id}"`;
1324
+ const row = rows.get(keyOf(kind, id));
1325
+ if (!row) throw new ConnectionError(`${where} is not set up. An Admin can set it up on the Connections page.`);
1326
+ if (!row.enabled) throw new ConnectionError(`${where} is switched off on the Connections page.`);
1327
+ const provider = providerOf(kind, row.provider);
1328
+ if (!provider) throw new ConnectionError(`${where} uses a provider that is not available.`);
1329
+ const stamp2 = row.updatedAt.getTime();
1330
+ const cached = drivers.get(keyOf(kind, id));
1331
+ if (cached && cached.stamp === stamp2) return cached.driver;
1332
+ let secrets;
1333
+ try {
1334
+ secrets = secretsOf(row);
1335
+ } catch (e) {
1336
+ throw new ConnectionError(`${where}: ${e.message}`);
1337
+ }
1338
+ const problem = problemOf(row, provider, secrets);
1339
+ if (problem) throw new ConnectionError(`${where} is not finished: ${problem}.`);
1340
+ const made = provider.create(contextOf(row, secrets));
1341
+ drivers.set(keyOf(kind, id), { stamp: stamp2, driver: made });
1342
+ return made;
1343
+ }
1344
+ function storage(id) {
1345
+ if (id === DEFAULT_STORAGE) return defaultStorage;
1346
+ const use = async () => await driver("storage", id);
1347
+ return {
1348
+ put: async (key, data) => (await use()).put(key, data),
1349
+ putStream: async (key, data, size) => (await use()).putStream(key, data, size),
1350
+ get: async (key) => (await use()).get(key),
1351
+ delete: async (key) => (await use()).delete(key),
1352
+ list: async (prefix) => (await use()).list(prefix),
1353
+ deleteTree: async (prefix) => (await use()).deleteTree(prefix)
1354
+ };
1355
+ }
1356
+ function emailSender(fallback) {
1357
+ return {
1358
+ async send(email) {
1359
+ await ready();
1360
+ if (!rows.get(keyOf("email", EMAIL_CONNECTION))?.enabled) return fallback.send(email);
1361
+ return (await driver("email", EMAIL_CONNECTION)).send(email);
1362
+ }
1363
+ };
1364
+ }
1365
+ async function storageReady(id) {
1366
+ if (id === DEFAULT_STORAGE) return true;
1367
+ return driver("storage", id).then(() => true, () => false);
1368
+ }
1369
+ async function logCall(entry) {
1370
+ await db.insert(llmCall).values({
1371
+ connectionId: entry.connectionId,
1372
+ model: entry.model,
1373
+ inputTokens: entry.usage?.inputTokens ?? null,
1374
+ outputTokens: entry.usage?.outputTokens ?? null,
1375
+ durationMs: Date.now() - entry.startedAt,
1376
+ status: entry.error ? "error" : "ok",
1377
+ error: entry.error?.slice(0, 300) ?? null,
1378
+ userId: entry.userId ?? null,
1379
+ feature: entry.feature ?? null
1380
+ }).catch((e) => console.error("Could not record the LLM call:", e));
1381
+ }
1382
+ function llm2(id, options = {}) {
1383
+ async function prepare(call) {
1384
+ const model = await driver("llm", id);
1385
+ const row = rows.get(keyOf("llm", id));
1386
+ if (options.personalData && row.config.personalDataApproved !== true) {
1387
+ throw new ConnectionError(`AI model "${id}" is not approved for personal data. An Admin can approve it on the Connections page.`);
1388
+ }
1389
+ const modelName = String(row.config.model ?? "");
1390
+ const settings = {
1391
+ model,
1392
+ system: call.system,
1393
+ prompt: call.prompt,
1394
+ maxOutputTokens: call.maxOutputTokens ?? (typeof row.config.maxOutputTokens === "number" ? row.config.maxOutputTokens : void 0),
1395
+ temperature: call.temperature ?? (typeof row.config.temperature === "number" ? row.config.temperature : void 0),
1396
+ abortSignal: AbortSignal.timeout((typeof row.config.timeoutSeconds === "number" ? row.config.timeoutSeconds : 120) * 1e3)
1397
+ };
1398
+ return { settings, modelName };
1399
+ }
1400
+ const usageOf = (u) => ({ inputTokens: u?.inputTokens ?? null, outputTokens: u?.outputTokens ?? null });
1401
+ async function run2(call, go) {
1402
+ const { settings, modelName } = await prepare(call);
1403
+ const startedAt3 = Date.now();
1404
+ try {
1405
+ const { value, usage } = await go(settings);
1406
+ await logCall({ connectionId: id, model: modelName, usage, startedAt: startedAt3, userId: call.userId, feature: call.feature });
1407
+ return { value, usage };
1408
+ } catch (e) {
1409
+ await logCall({ connectionId: id, model: modelName, startedAt: startedAt3, error: e.message, userId: call.userId, feature: call.feature });
1410
+ throw e;
1411
+ }
1412
+ }
1413
+ return {
1414
+ id,
1415
+ async text(call) {
1416
+ const { value, usage } = await run2(call, async (s) => {
1417
+ const r = await generateText(s);
1418
+ return { value: r.text, usage: usageOf(r.usage) };
1419
+ });
1420
+ return { text: value, usage };
1421
+ },
1422
+ async object(call) {
1423
+ const { value, usage } = await run2(call, async (s) => {
1424
+ const r = await generateText({ ...s, output: Output.object({ schema: call.schema }) });
1425
+ return { value: r.output, usage: usageOf(r.usage) };
1426
+ });
1427
+ return { object: value, usage };
1428
+ },
1429
+ async stream(call) {
1430
+ const { settings, modelName } = await prepare(call);
1431
+ const startedAt3 = Date.now();
1432
+ let finish;
1433
+ let fail;
1434
+ const done = new Promise((resolve3, reject) => (finish = resolve3, fail = reject));
1435
+ done.catch(() => void 0);
1436
+ const result = streamText({
1437
+ ...settings,
1438
+ onFinish: async (event) => {
1439
+ const usage = usageOf(event.usage);
1440
+ await logCall({ connectionId: id, model: modelName, usage, startedAt: startedAt3, userId: call.userId, feature: call.feature });
1441
+ finish({ text: event.text, usage });
1442
+ },
1443
+ onError: async ({ error }) => {
1444
+ await logCall({ connectionId: id, model: modelName, startedAt: startedAt3, error: String(error?.message ?? error), userId: call.userId, feature: call.feature });
1445
+ fail(error);
1446
+ }
1447
+ });
1448
+ return { textStream: result.textStream, done };
1449
+ }
1450
+ };
1451
+ }
1452
+ async function test(kind, id, recipient) {
1453
+ await ready();
1454
+ const row = rows.get(keyOf(kind, id));
1455
+ if (!row) throw new AuthzError("Connection not found", 404);
1456
+ let ok = true;
1457
+ let message;
1458
+ let secrets = {};
1459
+ try {
1460
+ secrets = secretsOf(row);
1461
+ const started = Date.now();
1462
+ if (kind === "storage") {
1463
+ const target = await driver("storage", id);
1464
+ const probe = randomBytes2(16);
1465
+ await target.put("appai-connection-test", probe);
1466
+ const back = await target.get("appai-connection-test");
1467
+ await target.delete("appai-connection-test");
1468
+ if (!back || !back.equals(probe)) throw new Error("The test file came back different from what was written");
1469
+ message = `Wrote, read and removed a test file (${((Date.now() - started) / 1e3).toFixed(1)} s).`;
1470
+ } else if (kind === "email") {
1471
+ if (!recipient) throw new Error("There is no address to send the test message to");
1472
+ const target = await driver("email", id);
1473
+ await target.send({ to: recipient, subject: "Test message", text: "This is a test message from the Connections page. If you can read it, the app can send email." });
1474
+ message = `Sent a test message to ${recipient} (${((Date.now() - started) / 1e3).toFixed(1)} s). Check that it arrived, and not in the spam folder.`;
1475
+ } else {
1476
+ const answer = await llm2(id).text({ prompt: "Reply with the single word OK.", maxOutputTokens: 16, feature: "connection-test" });
1477
+ message = `Answered in ${((Date.now() - started) / 1e3).toFixed(1)} s: "${answer.text.trim().slice(0, 60)}"`;
1478
+ }
1479
+ } catch (e) {
1480
+ ok = false;
1481
+ message = redact(e.message, secrets);
1482
+ }
1483
+ const [next] = await db.update(connection).set({ lastTestAt: /* @__PURE__ */ new Date(), lastTestOk: ok, lastTestMessage: message }).where(and2(eq2(connection.kind, kind), eq2(connection.id, id))).returning();
1484
+ if (next) rows.set(keyOf(kind, id), next);
1485
+ return { ok, message };
1486
+ }
1487
+ async function oauthStart(kind, id, userId) {
1488
+ await ready();
1489
+ const row = rows.get(keyOf(kind, id));
1490
+ const provider = row && providerOf(kind, row.provider);
1491
+ if (!row || !provider || provider.kind !== "storage" || !provider.oauth) throw new AuthzError("This connection does not need signing in", 409);
1492
+ const secrets = secretsOf(row);
1493
+ const missing = problemOf({ ...row }, { ...provider, oauth: void 0 }, secrets);
1494
+ if (missing) throw new AuthzError(`Save the connection first: ${missing}`, 409);
1495
+ const state = box.sign({ k: kind, i: id, u: userId, exp: Date.now() + OAUTH_MINUTES * 6e4, n: randomBytes2(8).toString("hex") });
1496
+ return provider.oauth.authorizeUrl(contextOf(row, secrets), state);
1497
+ }
1498
+ async function oauthFinish(kind, userId, code, state) {
1499
+ await ready();
1500
+ const parsed = box.verify(state);
1501
+ if (!parsed || parsed.k !== kind || parsed.u !== userId || parsed.exp < Date.now()) throw new AuthzError("This sign-in link has expired. Start again with the Connect button.");
1502
+ const row = rows.get(keyOf(kind, parsed.i));
1503
+ const provider = row && providerOf(kind, row.provider);
1504
+ if (!row || !provider || provider.kind !== "storage" || !provider.oauth) throw new AuthzError("Connection not found", 404);
1505
+ const secrets = secretsOf(row);
1506
+ const tokens = await provider.oauth.exchange(contextOf(row, secrets), code);
1507
+ const [next] = await db.update(connection).set({ secrets: box.encrypt({ ...secrets, ...tokens }), updatedAt: /* @__PURE__ */ new Date(), lastTestAt: null, lastTestOk: null, lastTestMessage: null }).where(and2(eq2(connection.kind, kind), eq2(connection.id, parsed.i))).returning();
1508
+ rows.set(keyOf(kind, parsed.i), next);
1509
+ return { id: parsed.i, test: await test(kind, parsed.i) };
1510
+ }
1511
+ async function health() {
1512
+ await ready();
1513
+ const problems = [];
1514
+ for (const s of allSlots) {
1515
+ const v = view(s.kind, s.id);
1516
+ if (s.required && (v.status === "missing" || v.status === "incomplete" || v.status === "disabled")) problems.push(`${KIND_LABEL[s.kind]} "${s.id}" is not set up`);
1517
+ }
1518
+ for (const row of rows.values()) {
1519
+ const v = view(row.kind, row.id);
1520
+ if (v.status === "failing") problems.push(`${KIND_LABEL[v.kind]} "${v.id}" failed its last test`);
1521
+ }
1522
+ if (problems.length > 0) return { status: "warn", detail: problems.join("; ") };
1523
+ const used = [...rows.values()].filter((r) => r.enabled).length;
1524
+ return { status: "ok", detail: used === 0 ? "No connections are used yet" : `${used} ${used === 1 ? "connection" : "connections"} set up` };
1525
+ }
1526
+ async function llmUsage(days = 14) {
1527
+ const since = new Date(Date.now() - days * 24 * 60 * 60 * 1e3);
1528
+ const day = sql3`to_char(${llmCall.at}, 'YYYY-MM-DD')`;
1529
+ return db.select({
1530
+ connectionId: llmCall.connectionId,
1531
+ day,
1532
+ calls: sql3`count(*)::float8`,
1533
+ errors: sql3`count(*) filter (where ${llmCall.status} = 'error')::float8`,
1534
+ inputTokens: sql3`coalesce(sum(${llmCall.inputTokens}), 0)::float8`,
1535
+ outputTokens: sql3`coalesce(sum(${llmCall.outputTokens}), 0)::float8`
1536
+ }).from(llmCall).where(gte(llmCall.at, since)).groupBy(llmCall.connectionId, day).orderBy(desc3(day), llmCall.connectionId);
1537
+ }
1538
+ async function backupPassphrase() {
1539
+ await ready();
1540
+ const row = rows.get(keyOf("storage", BACKUP_STORAGE));
1541
+ if (!row) return null;
1542
+ return secretsOf(row).encryptionPassphrase || null;
1543
+ }
1544
+ return {
1545
+ kinds: CONNECTION_KINDS,
1546
+ list,
1547
+ providers: providerViews,
1548
+ save,
1549
+ remove,
1550
+ test,
1551
+ storage,
1552
+ storageReady,
1553
+ emailSender,
1554
+ llm: llm2,
1555
+ oauthStart,
1556
+ oauthFinish,
1557
+ redirectUri,
1558
+ health,
1559
+ llmUsage,
1560
+ backupPassphrase
1561
+ };
1562
+ }
1563
+
1564
+ // src/auth/guard.ts
1565
+ import { createMiddleware } from "hono/factory";
1566
+ import { eq as eq3 } from "drizzle-orm";
1567
+ var API_KEY_HEADER = "x-api-key";
1568
+ var DECLARED = /* @__PURE__ */ Symbol.for("appai.declared");
1569
+ function declare(handler, kind) {
1570
+ return Object.assign(handler, { [DECLARED]: kind });
1571
+ }
1572
+ function scopesFromMap(map) {
1573
+ const out = /* @__PURE__ */ new Set();
1574
+ for (const [resource, actions] of Object.entries(map ?? {})) for (const a of actions) out.add(`${resource}:${a}`);
1575
+ return out;
1576
+ }
1577
+ function scopesToMap(scopes) {
1578
+ const out = {};
1579
+ for (const s of scopes) {
1580
+ const [resource, action] = s.split(":");
1581
+ (out[resource] ??= []).push(action);
1582
+ }
1583
+ return out;
1584
+ }
1585
+ function sessionMiddleware(auth, authz) {
1586
+ return createMiddleware(async (c, next) => {
1587
+ let user2 = null;
1588
+ let apiKey3 = null;
1589
+ const rawKey = c.req.header(API_KEY_HEADER);
1590
+ if (rawKey) {
1591
+ const result = await auth.api.verifyApiKey({ body: { key: rawKey } });
1592
+ if (result.valid && result.key) {
1593
+ const [row] = await authz.db.select({ id: user.id, email: user.email, name: user.name, emailVerified: user.emailVerified }).from(user).where(eq3(user.id, result.key.referenceId)).limit(1);
1594
+ if (row) {
1595
+ user2 = row;
1596
+ apiKey3 = { id: result.key.id, scopes: scopesFromMap(result.key.permissions) };
1597
+ }
1598
+ }
1599
+ } else {
1600
+ const session = await auth.api.getSession({ headers: c.req.raw.headers });
1601
+ user2 = session?.user ?? null;
1602
+ }
1603
+ let problem = null;
1604
+ if (user2) {
1605
+ const access = await authz.accessOf(user2.id);
1606
+ if (!access.active) {
1607
+ problem = access.reason;
1608
+ user2 = null;
1609
+ apiKey3 = null;
1610
+ }
1611
+ }
1612
+ const actor = { userId: user2?.id ?? null, email: user2?.email ?? null, viaKeyId: apiKey3?.id ?? null };
1613
+ c.set("user", user2);
1614
+ c.set("apiKey", apiKey3);
1615
+ c.set("accessProblem", problem);
1616
+ c.set("audit", (action, target, details) => authz.audit.record(actor, action, target, details));
1617
+ await next();
1618
+ });
1619
+ }
1620
+ var notSignedIn = (c) => {
1621
+ const problem = c.get("accessProblem");
1622
+ const error = problem === "expired" ? "Your access has expired" : problem === "deactivated" ? "Your account is deactivated" : "Not signed in";
1623
+ return c.json({ error, code: problem ?? "unauthenticated" }, 401);
1624
+ };
1625
+ function publicRoute() {
1626
+ return declare(createMiddleware(async (_c, next) => next()), "public");
1627
+ }
1628
+ function requireSession() {
1629
+ return declare(
1630
+ createMiddleware(async (c, next) => {
1631
+ if (!c.get("user")) return notSignedIn(c);
1632
+ await next();
1633
+ }),
1634
+ "session"
1635
+ );
1636
+ }
1637
+ function requirePermission(authz, permission) {
1638
+ const names = Array.isArray(permission) ? permission : [permission];
1639
+ for (const name2 of names) {
1640
+ if (!authz.catalog.permissions.has(name2)) throw new Error(`requirePermission: unknown permission "${name2}"`);
1641
+ }
1642
+ return declare(
1643
+ createMiddleware(async (c, next) => {
1644
+ const user2 = c.get("user");
1645
+ if (!user2) return notSignedIn(c);
1646
+ const key = c.get("apiKey");
1647
+ const granted = await authz.permissionsOf(user2.id);
1648
+ const allowed = names.some(
1649
+ (name2) => granted.has(name2) && (!key || !authz.catalog.permissions.get(name2).adminOnly && key.scopes.has(name2))
1650
+ );
1651
+ if (!allowed) return c.json({ error: "Forbidden" }, 403);
1652
+ await next();
1653
+ }),
1654
+ "permission"
1655
+ );
1656
+ }
1657
+ var COMPOSED = "__COMPOSED_HANDLER";
1658
+ function findUndeclaredRoutes(app) {
1659
+ const declared = /* @__PURE__ */ new Map();
1660
+ for (const route of app.routes) {
1661
+ if (route.method === "ALL") continue;
1662
+ const key = `${route.method} ${route.path}`;
1663
+ const handler = route.handler;
1664
+ const inner = handler[COMPOSED] ?? handler;
1665
+ declared.set(key, (declared.get(key) ?? false) || Boolean(inner[DECLARED]));
1666
+ }
1667
+ return [...declared].filter(([, ok]) => !ok).map(([key]) => key);
1668
+ }
1669
+ function assertDefaultDeny(app) {
1670
+ const missing = findUndeclaredRoutes(app);
1671
+ if (missing.length > 0) {
1672
+ throw new Error(
1673
+ `Endpoints without a declared permission (add requirePermission, requireSession or publicRoute):
1674
+ ${missing.join("\n ")}`
1675
+ );
1676
+ }
1677
+ }
1678
+ var companyId;
1679
+ async function getCompanyId(db) {
1680
+ if (companyId) return companyId;
1681
+ const [row] = await db.select({ id: organization.id }).from(organization).limit(1);
1682
+ companyId = row?.id;
1683
+ return companyId;
1684
+ }
1685
+ function resetCompanyCache() {
1686
+ companyId = void 0;
1687
+ }
1688
+
1689
+ // src/auth/auth.ts
1690
+ import { betterAuth } from "better-auth";
1691
+ import { drizzleAdapter } from "better-auth/adapters/drizzle";
1692
+ import { APIError } from "better-auth/api";
1693
+ import { organization as organization2 } from "better-auth/plugins";
1694
+ import { apiKey as apiKey2 } from "@better-auth/api-key";
1695
+ import { and as and3, count as count2, eq as eq4, gt as gt2, sql as sql4 } from "drizzle-orm";
1696
+
1697
+ // src/email/templates.ts
1698
+ function verificationEmail(to, appName, url) {
1699
+ return {
1700
+ to,
1701
+ subject: `Verify your email for ${appName}`,
1702
+ text: `Welcome to ${appName}.
1703
+
1704
+ Please confirm your email address by opening this link:
1705
+ ${url}
1706
+
1707
+ If you did not create an account, you can ignore this message.`
1708
+ };
1709
+ }
1710
+ function passwordResetEmail(to, appName, url) {
1711
+ return {
1712
+ to,
1713
+ subject: `Reset your ${appName} password`,
1714
+ text: `We received a request to reset your ${appName} password.
1715
+
1716
+ Choose a new password here:
1717
+ ${url}
1718
+
1719
+ If you did not ask for this, you can ignore this message.`
1720
+ };
1721
+ }
1722
+ function invitationEmail(to, appName, inviterName, url) {
1723
+ return {
1724
+ to,
1725
+ subject: `${inviterName} invited you to ${appName}`,
1726
+ text: `${inviterName} invited you to ${appName}.
1727
+
1728
+ Create your account using this email address, then you will be added automatically:
1729
+ ${url}
1730
+
1731
+ The invitation expires after a limited time.`
1732
+ };
1733
+ }
1734
+ function alertEmail(to, appName, subject, body) {
1735
+ return {
1736
+ to,
1737
+ subject: `[${appName}] ${subject}`,
1738
+ text: `${body}
1739
+
1740
+ This alert comes from ${appName}. Open the Status page in the app's administration area for details.`
1741
+ };
1742
+ }
1743
+
1744
+ // src/auth/auth.ts
1745
+ var INVITATION_LIFETIME_SECONDS = 7 * 24 * 60 * 60;
1746
+ var API_KEY_PREFIX = "appai_";
1747
+ function invitationIdFrom(callbackURL) {
1748
+ if (!callbackURL) return null;
1749
+ try {
1750
+ return new URL(callbackURL, "http://localhost").searchParams.get("invitation");
1751
+ } catch {
1752
+ return null;
1753
+ }
1754
+ }
1755
+ function createAuth({ db, config, email, authz, appName = () => config.APP_NAME }) {
1756
+ const origins = [config.PUBLIC_URL];
1757
+ if (config.NODE_ENV !== "production") origins.push("http://localhost:5173");
1758
+ const instance = betterAuth({
1759
+ appName: config.APP_NAME,
1760
+ baseURL: config.PUBLIC_URL,
1761
+ basePath: "/api/auth",
1762
+ secret: config.AUTH_SECRET,
1763
+ trustedOrigins: origins,
1764
+ // Slows down password guessing and email flooding. The client address comes from the reverse proxy,
1765
+ // which is the only way to reach the API in the Docker setup.
1766
+ rateLimit: {
1767
+ enabled: true,
1768
+ window: 60,
1769
+ max: 100,
1770
+ customRules: {
1771
+ "/sign-in/email": { window: 60, max: 5 },
1772
+ "/sign-up/email": { window: 60, max: 5 },
1773
+ "/request-password-reset": { window: 60, max: 3 },
1774
+ "/reset-password": { window: 60, max: 5 },
1775
+ "/send-verification-email": { window: 60, max: 3 }
1776
+ }
1777
+ },
1778
+ advanced: { ipAddress: { ipAddressHeaders: ["x-forwarded-for"] } },
1779
+ database: drizzleAdapter(db, { provider: "pg", schema: schema_exports }),
1780
+ emailAndPassword: {
1781
+ enabled: true,
1782
+ requireEmailVerification: true,
1783
+ minPasswordLength: 10,
1784
+ revokeSessionsOnPasswordReset: true,
1785
+ sendResetPassword: async ({ user: user2, url }) => {
1786
+ void email.send(passwordResetEmail(user2.email, appName(), url)).catch(console.error);
1787
+ }
1788
+ },
1789
+ emailVerification: {
1790
+ sendOnSignUp: true,
1791
+ autoSignInAfterVerification: true,
1792
+ // Verifying the address is what proves the invitation reached the right person: join the company now.
1793
+ afterEmailVerification: async (user2) => {
1794
+ await authz.joinPendingInvitation(user2.id);
1795
+ },
1796
+ sendVerificationEmail: async ({ user: user2, url }) => {
1797
+ void email.send(verificationEmail(user2.email, appName(), url)).catch(console.error);
1798
+ }
1799
+ },
1800
+ databaseHooks: {
1801
+ user: {
1802
+ create: {
1803
+ before: async (user2, context) => {
1804
+ const [{ total }] = await db.select({ total: count2() }).from(user);
1805
+ const address = user2.email.toLowerCase();
1806
+ if (total === 0) {
1807
+ if (address !== config.INITIAL_ADMIN_EMAIL?.toLowerCase()) {
1808
+ throw new APIError("FORBIDDEN", {
1809
+ message: "Sign-up is by invitation only."
1810
+ });
1811
+ }
1812
+ return;
1813
+ }
1814
+ const invitationId = invitationIdFrom(context?.body?.callbackURL);
1815
+ const [invite] = await db.select({ id: invitation.id }).from(invitation).where(
1816
+ and3(
1817
+ invitationId ? eq4(invitation.id, invitationId) : sql4`false`,
1818
+ sql4`lower(${invitation.email}) = ${address}`,
1819
+ eq4(invitation.status, "pending"),
1820
+ gt2(invitation.expiresAt, /* @__PURE__ */ new Date())
1821
+ )
1822
+ ).limit(1);
1823
+ if (!invite) {
1824
+ throw new APIError("FORBIDDEN", { message: "Sign-up is by invitation only." });
1825
+ }
1826
+ },
1827
+ after: async (user2) => {
1828
+ const [{ total }] = await db.select({ total: count2() }).from(organization);
1829
+ if (total > 0) return;
1830
+ const organizationId = crypto.randomUUID();
1831
+ await db.insert(organization).values({
1832
+ id: organizationId,
1833
+ name: appName(),
1834
+ slug: "company",
1835
+ createdAt: /* @__PURE__ */ new Date()
1836
+ });
1837
+ await db.insert(member).values({
1838
+ id: crypto.randomUUID(),
1839
+ organizationId,
1840
+ userId: user2.id,
1841
+ role: "owner",
1842
+ createdAt: /* @__PURE__ */ new Date()
1843
+ });
1844
+ }
1845
+ }
1846
+ },
1847
+ session: {
1848
+ create: {
1849
+ after: async (session) => {
1850
+ await authz.joinPendingInvitation(session.userId);
1851
+ const [u] = await db.select({ email: user.email }).from(user).where(eq4(user.id, session.userId)).limit(1);
1852
+ await authz.audit.record({ userId: session.userId, email: u?.email ?? null }, "auth.signed_in");
1853
+ }
1854
+ }
1855
+ }
1856
+ },
1857
+ plugins: [
1858
+ // Invitations are created by our own /api/users/invitations endpoint; the plugin accepts them.
1859
+ organization2({
1860
+ allowUserToCreateOrganization: false,
1861
+ invitationExpiresIn: INVITATION_LIFETIME_SECONDS,
1862
+ organizationHooks: {
1863
+ afterAcceptInvitation: async ({ invitation: invitation2, user: user2 }) => {
1864
+ await authz.onJoined(user2.id, invitation2.role);
1865
+ await authz.audit.record({ userId: user2.id, email: user2.email }, "user.joined", user2.id, { roles: invitation2.role });
1866
+ }
1867
+ }
1868
+ }),
1869
+ apiKey2({
1870
+ defaultPrefix: API_KEY_PREFIX,
1871
+ rateLimit: { enabled: true, timeWindow: 6e4, maxRequests: 120 }
1872
+ })
1873
+ ]
1874
+ });
1875
+ return instance;
1876
+ }
1877
+
1878
+ // src/groups/service.ts
1879
+ import { and as and4, asc, eq as eq5, inArray, isNull, notInArray, or, gt as gt3, sql as sql6 } from "drizzle-orm";
1880
+
1881
+ // src/groups/schema.ts
1882
+ import { sql as sql5 } from "drizzle-orm";
1883
+ import { index as index2, pgTable as pgTable3, primaryKey as primaryKey2, text as text3, timestamp as timestamp3, uniqueIndex, uuid as uuid3 } from "drizzle-orm/pg-core";
1884
+ var userGroup = pgTable3(
1885
+ "user_group",
1886
+ {
1887
+ id: uuid3("id").primaryKey().defaultRandom(),
1888
+ name: text3("name").notNull(),
1889
+ description: text3("description").notNull().default(""),
1890
+ createdAt: timestamp3("created_at").defaultNow().notNull(),
1891
+ updatedAt: timestamp3("updated_at").defaultNow().notNull()
1892
+ },
1893
+ (t) => [uniqueIndex("user_group_name_lower_idx").on(sql5`lower(${t.name})`)]
1894
+ );
1895
+ var userGroupMember = pgTable3(
1896
+ "user_group_member",
1897
+ {
1898
+ groupId: uuid3("group_id").notNull().references(() => userGroup.id, { onDelete: "cascade" }),
1899
+ userId: text3("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
1900
+ addedAt: timestamp3("added_at").defaultNow().notNull()
1901
+ },
1902
+ (t) => [primaryKey2({ columns: [t.groupId, t.userId] }), index2("user_group_member_user_idx").on(t.userId)]
1903
+ );
1904
+
1905
+ // src/groups/service.ts
1906
+ var UNIQUE_VIOLATION = "23505";
1907
+ function isUniqueViolation(error) {
1908
+ const e = error;
1909
+ return e?.code === UNIQUE_VIOLATION || e?.cause?.code === UNIQUE_VIOLATION;
1910
+ }
1911
+ function createGroups({ db }) {
1912
+ async function assertNameFree(name2, exceptId) {
1913
+ const rows = await db.select({ id: userGroup.id }).from(userGroup).where(sql6`lower(${userGroup.name}) = ${name2.toLowerCase()}`);
1914
+ if (rows.some((r) => r.id !== exceptId)) throw new AuthzError("A group with this name already exists", 409);
1915
+ }
1916
+ async function membersOf(groupIds) {
1917
+ if (groupIds.length === 0) return /* @__PURE__ */ new Map();
1918
+ const rows = await db.select({ groupId: userGroupMember.groupId, id: user.id, name: user.name, email: user.email }).from(userGroupMember).innerJoin(user, eq5(user.id, userGroupMember.userId)).where(inArray(userGroupMember.groupId, groupIds)).orderBy(asc(user.name), asc(user.email));
1919
+ const byGroup = /* @__PURE__ */ new Map();
1920
+ for (const { groupId, ...member2 } of rows) byGroup.set(groupId, [...byGroup.get(groupId) ?? [], member2]);
1921
+ return byGroup;
1922
+ }
1923
+ async function view(id) {
1924
+ const [row] = await db.select().from(userGroup).where(eq5(userGroup.id, id)).limit(1);
1925
+ if (!row) throw new AuthzError("Group not found", 404);
1926
+ return { id: row.id, name: row.name, description: row.description, members: (await membersOf([id])).get(id) ?? [] };
1927
+ }
1928
+ async function list() {
1929
+ const rows = await db.select().from(userGroup).orderBy(asc(sql6`lower(${userGroup.name})`));
1930
+ const members = await membersOf(rows.map((r) => r.id));
1931
+ return rows.map((r) => ({ id: r.id, name: r.name, description: r.description, members: members.get(r.id) ?? [] }));
1932
+ }
1933
+ async function create(name2, description2 = "") {
1934
+ await assertNameFree(name2);
1935
+ try {
1936
+ const [row] = await db.insert(userGroup).values({ name: name2, description: description2 }).returning({ id: userGroup.id });
1937
+ return await view(row.id);
1938
+ } catch (error) {
1939
+ if (isUniqueViolation(error)) throw new AuthzError("A group with this name already exists", 409);
1940
+ throw error;
1941
+ }
1942
+ }
1943
+ async function update(id, changes) {
1944
+ await view(id);
1945
+ if (changes.name !== void 0) await assertNameFree(changes.name, id);
1946
+ try {
1947
+ await db.update(userGroup).set({ ...changes.name !== void 0 && { name: changes.name }, ...changes.description !== void 0 && { description: changes.description }, updatedAt: /* @__PURE__ */ new Date() }).where(eq5(userGroup.id, id));
1948
+ } catch (error) {
1949
+ if (isUniqueViolation(error)) throw new AuthzError("A group with this name already exists", 409);
1950
+ throw error;
1951
+ }
1952
+ return view(id);
1953
+ }
1954
+ async function remove(id) {
1955
+ const group = await view(id);
1956
+ await db.delete(userGroup).where(eq5(userGroup.id, id));
1957
+ return group;
1958
+ }
1959
+ async function setMembers(id, userIds) {
1960
+ const before = await view(id);
1961
+ const wanted = [...new Set(userIds)];
1962
+ if (wanted.length > 0) {
1963
+ const known = await db.select({ userId: member.userId }).from(member).where(inArray(member.userId, wanted));
1964
+ const knownIds = new Set(known.map((k) => k.userId));
1965
+ if (wanted.some((u) => !knownIds.has(u))) throw new AuthzError("Some of these people were not found");
1966
+ }
1967
+ await db.transaction(async (tx) => {
1968
+ await tx.delete(userGroupMember).where(and4(eq5(userGroupMember.groupId, id), wanted.length > 0 ? notInArray(userGroupMember.userId, wanted) : void 0));
1969
+ if (wanted.length > 0) await tx.insert(userGroupMember).values(wanted.map((userId) => ({ groupId: id, userId }))).onConflictDoNothing();
1970
+ });
1971
+ const group = await view(id);
1972
+ const had = new Set(before.members.map((m) => m.id));
1973
+ const has = new Set(group.members.map((m) => m.id));
1974
+ return {
1975
+ group,
1976
+ added: group.members.filter((m) => !had.has(m.id)),
1977
+ removed: before.members.filter((m) => !has.has(m.id))
1978
+ };
1979
+ }
1980
+ async function memberIds(groupIds, { includeInactive = false } = {}) {
1981
+ if (groupIds.length === 0) return [];
1982
+ const rows = await db.selectDistinct({ userId: userGroupMember.userId }).from(userGroupMember).leftJoin(userAccess, eq5(userAccess.userId, userGroupMember.userId)).where(
1983
+ and4(
1984
+ inArray(userGroupMember.groupId, groupIds),
1985
+ includeInactive ? void 0 : and4(isNull(userAccess.deactivatedAt), or(isNull(userAccess.expiresAt), gt3(userAccess.expiresAt, /* @__PURE__ */ new Date())))
1986
+ )
1987
+ );
1988
+ return rows.map((r) => r.userId);
1989
+ }
1990
+ async function membershipRows(userId) {
1991
+ return db.select({ userId: userGroupMember.userId, id: userGroup.id, name: userGroup.name }).from(userGroupMember).innerJoin(userGroup, eq5(userGroup.id, userGroupMember.groupId)).where(userId ? eq5(userGroupMember.userId, userId) : void 0).orderBy(asc(sql6`lower(${userGroup.name})`));
1992
+ }
1993
+ async function byUser() {
1994
+ const map = /* @__PURE__ */ new Map();
1995
+ for (const { userId, ...ref } of await membershipRows()) map.set(userId, [...map.get(userId) ?? [], ref]);
1996
+ return map;
1997
+ }
1998
+ async function forUser(userId) {
1999
+ return (await membershipRows(userId)).map(({ id, name: name2 }) => ({ id, name: name2 }));
2000
+ }
2001
+ return { list, create, update, remove, setMembers, memberIds, forUser, byUser };
2002
+ }
2003
+
2004
+ // package.json
2005
+ var package_default = {
2006
+ name: "@kaloma-ai/framework-api",
2007
+ version: "0.6.0",
2008
+ type: "module",
2009
+ exports: {
2010
+ ".": "./src/index.ts",
2011
+ "./schema": "./src/schema.ts",
2012
+ "./testing": "./src/testing.ts"
2013
+ },
2014
+ scripts: {
2015
+ build: "tsup",
2016
+ typecheck: "tsc --noEmit",
2017
+ test: "vitest run",
2018
+ "db:generate": "drizzle-kit generate --name"
2019
+ },
2020
+ dependencies: {
2021
+ "@ai-sdk/anthropic": "^4.0.92",
2022
+ "@ai-sdk/azure": "^4.0.113",
2023
+ "@ai-sdk/google": "^4.0.108",
2024
+ "@ai-sdk/mistral": "^4.0.75",
2025
+ "@ai-sdk/openai": "^4.0.105",
2026
+ "@ai-sdk/openai-compatible": "^3.0.81",
2027
+ "@aws-sdk/client-s3": "^3.1160.0",
2028
+ "@aws-sdk/lib-storage": "^3.1160.0",
2029
+ "@better-auth/api-key": "1.7.14",
2030
+ "@hono/node-server": "^2.1.5",
2031
+ ai: "^7.0.157",
2032
+ "better-auth": "^1.7.14",
2033
+ nodemailer: "^10.2.1",
2034
+ postgres: "^3.4.9"
2035
+ },
2036
+ devDependencies: {
2037
+ "@types/node": "^26.6.5",
2038
+ "@types/nodemailer": "^8.0.2",
2039
+ "drizzle-kit": "^0.31.11",
2040
+ "drizzle-orm": "^0.45.4",
2041
+ hono: "^4.13.14",
2042
+ tsup: "^9.0.0",
2043
+ typescript: "^6.0.3",
2044
+ vitest: "^5.0.5",
2045
+ zod: "^4.6.7"
2046
+ },
2047
+ description: "appai framework: API side (auth, authorization, settings, operations, brand, health)",
2048
+ license: "UNLICENSED",
2049
+ repository: {
2050
+ type: "git",
2051
+ url: "git+https://github.com/kaloma-ai/kaloma-appai.git",
2052
+ directory: "packages/framework-api"
2053
+ },
2054
+ files: [
2055
+ "dist",
2056
+ "drizzle"
2057
+ ],
2058
+ publishConfig: {
2059
+ registry: "https://registry.npmjs.org",
2060
+ access: "public",
2061
+ main: "./dist/index.js",
2062
+ types: "./dist/index.d.ts",
2063
+ exports: {
2064
+ ".": {
2065
+ types: "./dist/index.d.ts",
2066
+ import: "./dist/index.js",
2067
+ default: "./dist/index.js"
2068
+ },
2069
+ "./schema": {
2070
+ types: "./dist/schema.d.ts",
2071
+ import: "./dist/schema.js",
2072
+ default: "./dist/schema.js"
2073
+ },
2074
+ "./testing": {
2075
+ types: "./dist/testing.d.ts",
2076
+ import: "./dist/testing.js",
2077
+ default: "./dist/testing.js"
2078
+ }
2079
+ }
2080
+ },
2081
+ peerDependencies: {
2082
+ "drizzle-orm": "^0.45.4",
2083
+ hono: "^4.13.14",
2084
+ vitest: "^5.0.5",
2085
+ zod: "^4.6.7"
2086
+ },
2087
+ peerDependenciesMeta: {
2088
+ vitest: {
2089
+ optional: true
2090
+ }
2091
+ }
2092
+ };
2093
+
2094
+ // src/version.ts
2095
+ var FRAMEWORK_VERSION = package_default.version;
2096
+
2097
+ // src/brand.ts
2098
+ import { existsSync, readFileSync as readFileSync2 } from "fs";
2099
+ import { extname, join as join3 } from "path";
2100
+ import { Hono } from "hono";
2101
+ import { z as z2 } from "zod";
2102
+ var hex = z2.string().regex(/^#[0-9a-fA-F]{6}$/, "use a 6-digit hex color such as #2563eb");
2103
+ var fileName = z2.string().regex(/^[\w.-]+$/, "use a plain file name inside the brand folder");
2104
+ var profileSchema = z2.object({
2105
+ /** Shown in the header, on sign-in pages and as the page title. Defaults to APP_NAME. */
2106
+ appName: z2.string().min(1).optional(),
2107
+ /** Logo file in the brand folder (svg, png, jpg or webp). */
2108
+ logo: fileName.optional(),
2109
+ colors: z2.object({
2110
+ primary: hex.optional(),
2111
+ secondary: hex.optional(),
2112
+ /** Optional lighter variants used in dark mode. */
2113
+ primaryDark: hex.optional(),
2114
+ secondaryDark: hex.optional()
2115
+ }).default({}),
2116
+ font: z2.object({
2117
+ /** CSS font-family, e.g. "Inter, system-ui, sans-serif". */
2118
+ family: z2.string().min(1),
2119
+ /** Optional font file (woff2) in the brand folder, so no third-party font service is contacted. */
2120
+ file: fileName.optional()
2121
+ }).optional()
2122
+ });
2123
+ var IMAGE_TYPES = {
2124
+ ".svg": "image/svg+xml",
2125
+ ".png": "image/png",
2126
+ ".jpg": "image/jpeg",
2127
+ ".jpeg": "image/jpeg",
2128
+ ".webp": "image/webp"
2129
+ };
2130
+ function contrastOn(color) {
2131
+ const [r, g, b] = [1, 3, 5].map((i) => {
2132
+ const c = parseInt(color.slice(i, i + 2), 16) / 255;
2133
+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
2134
+ });
2135
+ const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
2136
+ return luminance > 0.179 ? "#000000" : "#ffffff";
2137
+ }
2138
+ function loadBrand(dir, defaultAppName) {
2139
+ const file = join3(dir, "brand.json");
2140
+ let profile = { colors: {} };
2141
+ if (existsSync(file)) {
2142
+ let raw;
2143
+ try {
2144
+ raw = JSON.parse(readFileSync2(file, "utf8"));
2145
+ } catch (e) {
2146
+ throw new Error(`Invalid brand profile ${file}: ${e.message}`, { cause: e });
2147
+ }
2148
+ const parsed = profileSchema.safeParse(raw);
2149
+ if (!parsed.success) {
2150
+ const problems = parsed.error.issues.map((i) => ` - ${i.path.join(".") || "(root)"}: ${i.message}`);
2151
+ throw new Error(`Invalid brand profile ${file}:
2152
+ ${problems.join("\n")}`);
2153
+ }
2154
+ profile = parsed.data;
2155
+ }
2156
+ const resolve3 = (name2, what) => {
2157
+ if (!name2) return null;
2158
+ const path = join3(dir, name2);
2159
+ if (!existsSync(path)) throw new Error(`Brand profile: ${what} file "${name2}" not found in ${dir}`);
2160
+ return path;
2161
+ };
2162
+ const logoPath = resolve3(profile.logo, "logo");
2163
+ if (logoPath && !IMAGE_TYPES[extname(logoPath).toLowerCase()]) {
2164
+ throw new Error(`Brand profile: logo must be svg, png, jpg or webp (got "${profile.logo}")`);
2165
+ }
2166
+ const fontPath = resolve3(profile.font?.file, "font");
2167
+ const { primary, secondary, primaryDark, secondaryDark } = profile.colors;
2168
+ return {
2169
+ logoPath,
2170
+ fontPath,
2171
+ brand: {
2172
+ appName: profile.appName ?? defaultAppName,
2173
+ logoUrl: logoPath ? "/api/brand/logo" : null,
2174
+ fontFamily: profile.font?.family ?? null,
2175
+ fontUrl: fontPath ? "/api/brand/font" : null,
2176
+ colors: {
2177
+ primary,
2178
+ primaryContrast: primary ? contrastOn(primary) : void 0,
2179
+ secondary,
2180
+ primaryDark,
2181
+ primaryDarkContrast: primaryDark ? contrastOn(primaryDark) : void 0,
2182
+ secondaryDark
2183
+ }
2184
+ }
2185
+ };
2186
+ }
2187
+ var IMAGE_EXTENSIONS = Object.fromEntries(Object.entries(IMAGE_TYPES).map(([ext, type]) => [type, ext]));
2188
+ function createBrandService({
2189
+ loaded,
2190
+ settings,
2191
+ storage
2192
+ }) {
2193
+ const color = (key) => settings.get(key) ?? void 0;
2194
+ return {
2195
+ brand() {
2196
+ const custom = settings.get("brand.logo");
2197
+ const primary = color("brand.primary");
2198
+ const primaryDark = color("brand.primaryDark");
2199
+ return {
2200
+ ...loaded.brand,
2201
+ appName: settings.get("app.name"),
2202
+ logoUrl: custom ? `/api/brand/logo?v=${custom.version}` : loaded.logoPath ? "/api/brand/logo" : null,
2203
+ colors: {
2204
+ primary,
2205
+ primaryContrast: primary ? contrastOn(primary) : void 0,
2206
+ secondary: color("brand.secondary"),
2207
+ primaryDark,
2208
+ primaryDarkContrast: primaryDark ? contrastOn(primaryDark) : void 0,
2209
+ secondaryDark: color("brand.secondaryDark")
2210
+ }
2211
+ };
2212
+ },
2213
+ async logo() {
2214
+ const custom = settings.get("brand.logo");
2215
+ if (custom) {
2216
+ const data = await storage.get(custom.key);
2217
+ return data ? { data, type: custom.type } : null;
2218
+ }
2219
+ if (!loaded.logoPath) return null;
2220
+ return { data: readFileSync2(loaded.logoPath), type: IMAGE_TYPES[extname(loaded.logoPath).toLowerCase()] };
2221
+ },
2222
+ font: () => loaded.fontPath ? readFileSync2(loaded.fontPath) : null
2223
+ };
2224
+ }
2225
+ function brandRoutes(service) {
2226
+ const app = new Hono();
2227
+ const headers = {
2228
+ // The files are only ever used by <img> and @font-face; this stops an SVG from running anything if opened directly.
2229
+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox"
2230
+ };
2231
+ app.get("/api/brand", publicRoute(), (c) => c.json(service.brand(), 200, { "cache-control": "no-cache" }));
2232
+ app.get("/api/brand/logo", publicRoute(), async (c) => {
2233
+ const logo = await service.logo();
2234
+ if (!logo) return c.json({ error: "Not found" }, 404);
2235
+ const cache = c.req.query("v") ? "public, max-age=31536000, immutable" : "public, max-age=300";
2236
+ return c.body(new Uint8Array(logo.data), 200, { ...headers, "cache-control": cache, "content-type": logo.type });
2237
+ });
2238
+ app.get("/api/brand/font", publicRoute(), (c) => {
2239
+ const font = service.font();
2240
+ if (!font) return c.json({ error: "Not found" }, 404);
2241
+ return c.body(new Uint8Array(font), 200, { ...headers, "cache-control": "public, max-age=300", "content-type": "font/woff2" });
2242
+ });
2243
+ return app;
2244
+ }
2245
+
2246
+ // src/health.ts
2247
+ import { Hono as Hono2 } from "hono";
2248
+ var startedAt = Date.now();
2249
+ function healthRoutes({ appName, checkDatabase }) {
2250
+ const app = new Hono2();
2251
+ app.get("/api/health", publicRoute(), async (c) => {
2252
+ let database = "ok";
2253
+ try {
2254
+ await checkDatabase();
2255
+ } catch {
2256
+ database = "down";
2257
+ }
2258
+ const status = database === "ok" ? "ok" : "degraded";
2259
+ return c.json(
2260
+ {
2261
+ status,
2262
+ app: appName(),
2263
+ frameworkVersion: FRAMEWORK_VERSION,
2264
+ database,
2265
+ uptimeSeconds: Math.round((Date.now() - startedAt) / 1e3)
2266
+ },
2267
+ status === "ok" ? 200 : 503
2268
+ );
2269
+ });
2270
+ return app;
2271
+ }
2272
+
2273
+ // src/app.ts
2274
+ import { Hono as Hono9 } from "hono";
2275
+ import { secureHeaders } from "hono/secure-headers";
2276
+
2277
+ // src/authz/routes.ts
2278
+ import { Hono as Hono3 } from "hono";
2279
+ import { and as and5, desc as desc4, eq as eq6, sql as sql7 } from "drizzle-orm";
2280
+ import { z as z3 } from "zod";
2281
+ var INVITATION_DAYS = 7;
2282
+ var DEFAULT_KEY_DAYS = 90;
2283
+ var emailField = z3.string().trim().toLowerCase().pipe(z3.email());
2284
+ var roleKeys = z3.array(z3.string()).max(20);
2285
+ function authzRoutes({ auth, db, authz, email, appName, publicUrl }) {
2286
+ const app = new Hono3();
2287
+ const need = (permission) => requirePermission(authz, permission);
2288
+ const groups = createGroups({ db });
2289
+ app.get("/api/users", need("user:read"), async (c) => {
2290
+ const rows = await db.select({
2291
+ id: user.id,
2292
+ name: user.name,
2293
+ email: user.email,
2294
+ emailVerified: user.emailVerified,
2295
+ createdAt: user.createdAt,
2296
+ role: member.role,
2297
+ accessExpiresAt: userAccess.expiresAt,
2298
+ deactivatedAt: userAccess.deactivatedAt
2299
+ }).from(user).innerJoin(member, eq6(member.userId, user.id)).leftJoin(userAccess, eq6(userAccess.userId, user.id)).orderBy(user.createdAt);
2300
+ const now = Date.now();
2301
+ const groupsOf = await groups.byUser();
2302
+ const users = rows.map(({ role, accessExpiresAt, deactivatedAt, ...u }) => ({
2303
+ ...u,
2304
+ roles: role ? role.split(",") : [],
2305
+ groups: groupsOf.get(u.id) ?? [],
2306
+ accessExpiresAt,
2307
+ status: deactivatedAt ? "deactivated" : accessExpiresAt && accessExpiresAt.getTime() <= now ? "expired" : "active"
2308
+ }));
2309
+ const invitations = await db.select({ id: invitation.id, email: invitation.email, role: invitation.role, expiresAt: invitation.expiresAt }).from(invitation).where(and5(eq6(invitation.status, "pending"), sql7`${invitation.expiresAt} > now()`)).orderBy(desc4(invitation.createdAt));
2310
+ return c.json({
2311
+ users,
2312
+ invitations: invitations.map((i) => ({ ...i, roles: i.role ? i.role.split(",") : [] }))
2313
+ });
2314
+ });
2315
+ app.post("/api/users/invitations", need("user:invite"), async (c) => {
2316
+ const body = z3.object({ email: emailField, roles: roleKeys.default([]) }).parse(await c.req.json());
2317
+ const roles = await authz.normaliseRoles(body.roles);
2318
+ const [existing] = await db.select({ id: user.id }).from(user).where(sql7`lower(${user.email}) = ${body.email}`).limit(1);
2319
+ if (existing) throw new AuthzError("This person already has an account", 409);
2320
+ const organizationId = await getCompanyId(db);
2321
+ if (!organizationId) throw new AuthzError("The company is not set up yet", 409);
2322
+ await db.update(invitation).set({ status: "canceled" }).where(and5(sql7`lower(${invitation.email}) = ${body.email}`, eq6(invitation.status, "pending")));
2323
+ const inviter = c.get("user");
2324
+ const id = crypto.randomUUID();
2325
+ await db.insert(invitation).values({
2326
+ id,
2327
+ organizationId,
2328
+ email: body.email,
2329
+ role: roles.join(","),
2330
+ status: "pending",
2331
+ expiresAt: new Date(Date.now() + INVITATION_DAYS * 24 * 60 * 60 * 1e3),
2332
+ inviterId: inviter.id
2333
+ });
2334
+ void email.send(invitationEmail(body.email, appName(), inviter.name, `${publicUrl}/signup?invitation=${id}`)).catch(console.error);
2335
+ await c.get("audit")("user.invited", body.email, { roles });
2336
+ return c.json({ id, email: body.email, roles }, 201);
2337
+ });
2338
+ app.delete("/api/users/invitations/:id", need("user:invite"), async (c) => {
2339
+ const [row] = await db.update(invitation).set({ status: "canceled" }).where(and5(eq6(invitation.id, c.req.param("id")), eq6(invitation.status, "pending"))).returning({ email: invitation.email });
2340
+ if (!row) throw new AuthzError("Invitation not found", 404);
2341
+ await c.get("audit")("user.invitation_canceled", row.email);
2342
+ return c.json({ ok: true });
2343
+ });
2344
+ app.put("/api/users/:id/roles", need("user:update"), async (c) => {
2345
+ const { roles } = z3.object({ roles: roleKeys }).parse(await c.req.json());
2346
+ const id = c.req.param("id");
2347
+ const before = await authz.roleKeysOf(id);
2348
+ const after = await authz.setUserRoles(c.get("user").id, id, roles);
2349
+ await c.get("audit")("user.roles_changed", id, { before, after });
2350
+ return c.json({ roles: after });
2351
+ });
2352
+ app.put("/api/users/:id/access", need("user:update"), async (c) => {
2353
+ const { days } = z3.object({ days: z3.number().int().min(1).max(3650).nullable() }).parse(await c.req.json());
2354
+ const id = c.req.param("id");
2355
+ if ((await authz.roleKeysOf(id)).length === 0) throw new AuthzError("User not found", 404);
2356
+ await authz.renewAccess(id, days);
2357
+ await c.get("audit")("user.access_renewed", id, { days });
2358
+ return c.json({ ok: true });
2359
+ });
2360
+ for (const [action, deactivate] of [["deactivate", true], ["reactivate", false]]) {
2361
+ app.post(`/api/users/:id/${action}`, need("user:deactivate"), async (c) => {
2362
+ const id = c.req.param("id");
2363
+ if (id === c.get("user").id) throw new AuthzError("You cannot deactivate yourself", 409);
2364
+ if ((await authz.roleKeysOf(id)).length === 0) throw new AuthzError("User not found", 404);
2365
+ await authz.setDeactivated(id, deactivate);
2366
+ await c.get("audit")(`user.${action}d`, id);
2367
+ return c.json({ ok: true });
2368
+ });
2369
+ }
2370
+ app.get("/api/roles", need(["role:read", "user:invite", "user:update"]), async (c) => {
2371
+ return c.json({
2372
+ roles: await authz.listRoles(),
2373
+ permissions: [...authz.catalog.permissions.values()]
2374
+ });
2375
+ });
2376
+ const roleBody = z3.object({ label: z3.string().trim().min(1).max(60), permissions: z3.array(z3.string()).max(200) });
2377
+ app.post("/api/roles", need("role:create"), async (c) => {
2378
+ const body = roleBody.parse(await c.req.json());
2379
+ const role = await authz.createRole(body.label, body.permissions);
2380
+ await c.get("audit")("role.created", role.key, { permissions: role.permissions });
2381
+ return c.json(role, 201);
2382
+ });
2383
+ app.put("/api/roles/:key", need("role:update"), async (c) => {
2384
+ const body = roleBody.parse(await c.req.json());
2385
+ const key = c.req.param("key");
2386
+ const role = await authz.updateRole(key, body.label, body.permissions);
2387
+ await c.get("audit")("role.updated", key, { permissions: role.permissions });
2388
+ return c.json(role);
2389
+ });
2390
+ app.delete("/api/roles/:key", need("role:delete"), async (c) => {
2391
+ const key = c.req.param("key");
2392
+ await authz.deleteRole(key);
2393
+ await c.get("audit")("role.deleted", key);
2394
+ return c.json({ ok: true });
2395
+ });
2396
+ const keyColumns = {
2397
+ id: apikey.id,
2398
+ name: apikey.name,
2399
+ start: apikey.start,
2400
+ owner: apikey.referenceId,
2401
+ permissions: apikey.permissions,
2402
+ expiresAt: apikey.expiresAt,
2403
+ lastUsedAt: apikey.lastRequest,
2404
+ createdAt: apikey.createdAt
2405
+ };
2406
+ const keyView = (row) => ({
2407
+ ...row,
2408
+ scopes: [...scopesFromMap(row.permissions ? JSON.parse(row.permissions) : null)],
2409
+ permissions: void 0
2410
+ });
2411
+ app.get("/api/api-keys", need("apikey:read"), async (c) => {
2412
+ const rows = await db.select(keyColumns).from(apikey).where(eq6(apikey.referenceId, c.get("user").id)).orderBy(desc4(apikey.createdAt));
2413
+ return c.json({ keys: rows.map(keyView) });
2414
+ });
2415
+ app.get("/api/api-keys/all", need("apikey:manage"), async (c) => {
2416
+ const rows = await db.select({ ...keyColumns, ownerEmail: user.email }).from(apikey).leftJoin(user, eq6(user.id, apikey.referenceId)).orderBy(desc4(apikey.createdAt));
2417
+ return c.json({ keys: rows.map(keyView) });
2418
+ });
2419
+ const presetActions = {
2420
+ read: ["read"],
2421
+ read_create: ["read", "create"],
2422
+ read_create_update: ["read", "create", "update"]
2423
+ };
2424
+ app.post("/api/api-keys", need("apikey:create"), async (c) => {
2425
+ const body = z3.object({
2426
+ name: z3.string().trim().min(1).max(80),
2427
+ preset: z3.enum(["read", "read_create", "read_create_update", "custom"]),
2428
+ scopes: z3.array(z3.string()).max(200).default([]),
2429
+ expiresInDays: z3.number().int().min(1).max(365).default(DEFAULT_KEY_DAYS)
2430
+ }).parse(await c.req.json());
2431
+ const user2 = c.get("user");
2432
+ const granted = await authz.permissionsOf(user2.id);
2433
+ const usable = [...granted].filter((p) => !authz.catalog.permissions.get(p)?.adminOnly);
2434
+ const scopes = body.preset === "custom" ? [...new Set(body.scopes)] : usable.filter((p) => presetActions[body.preset].includes(p.split(":")[1]));
2435
+ const refused = scopes.filter((p) => !usable.includes(p));
2436
+ if (refused.length > 0) throw new AuthzError(`These permissions cannot be given to a key: ${refused.join(", ")}`);
2437
+ if (scopes.length === 0) throw new AuthzError("The key would have no permissions");
2438
+ const created = await auth.api.createApiKey({
2439
+ body: {
2440
+ name: body.name,
2441
+ userId: user2.id,
2442
+ prefix: API_KEY_PREFIX,
2443
+ permissions: scopesToMap(scopes),
2444
+ expiresIn: body.expiresInDays * 24 * 60 * 60
2445
+ }
2446
+ });
2447
+ await c.get("audit")("apikey.created", created.id, { name: body.name, scopes, expiresInDays: body.expiresInDays });
2448
+ return c.json({ id: created.id, key: created.key, scopes }, 201);
2449
+ });
2450
+ app.delete("/api/api-keys/:id", need(["apikey:delete", "apikey:manage"]), async (c) => {
2451
+ const user2 = c.get("user");
2452
+ const id = c.req.param("id");
2453
+ const manage = (await authz.permissionsOf(user2.id)).has("apikey:manage");
2454
+ const [row] = await db.delete(apikey).where(manage ? eq6(apikey.id, id) : and5(eq6(apikey.id, id), eq6(apikey.referenceId, user2.id))).returning({ name: apikey.name, owner: apikey.referenceId });
2455
+ if (!row) throw new AuthzError("Key not found", 404);
2456
+ await c.get("audit")("apikey.revoked", id, { name: row.name, owner: row.owner });
2457
+ return c.json({ ok: true });
2458
+ });
2459
+ app.get("/api/audit", need("audit:read"), async (c) => {
2460
+ const limit = Number(c.req.query("limit") ?? 100);
2461
+ const before = c.req.query("before");
2462
+ const entries = await authz.audit.list(Number.isFinite(limit) ? limit : 100, before ? new Date(before) : void 0);
2463
+ return c.json({ entries });
2464
+ });
2465
+ return app;
2466
+ }
2467
+
2468
+ // src/ops/routes.ts
2469
+ import { Hono as Hono4 } from "hono";
2470
+
2471
+ // src/ops/backup.ts
2472
+ import { spawn } from "child_process";
2473
+ import { createHash } from "crypto";
2474
+ import { createReadStream as createReadStream3, existsSync as existsSync2 } from "fs";
2475
+ import { mkdir as mkdir2, readdir as readdir2, rename, rm as rm2, stat as stat2, writeFile as writeFile2 } from "fs/promises";
2476
+ import { join as join4 } from "path";
2477
+ import { desc as desc5, eq as eq7 } from "drizzle-orm";
2478
+
2479
+ // src/ops/encrypt.ts
2480
+ import { createCipheriv as createCipheriv2, pbkdf2, randomBytes as randomBytes3 } from "crypto";
2481
+ import { createReadStream as createReadStream2, createWriteStream as createWriteStream2 } from "fs";
2482
+ import { pipeline as pipeline2 } from "stream/promises";
2483
+ import { promisify } from "util";
2484
+ var derive = promisify(pbkdf2);
2485
+ var ENCRYPTION_ITERATIONS = 6e5;
2486
+ async function encryptFile(source, target, passphrase) {
2487
+ const salt = randomBytes3(8);
2488
+ const material = await derive(passphrase, salt, ENCRYPTION_ITERATIONS, 48, "sha256");
2489
+ const cipher = createCipheriv2("aes-256-cbc", material.subarray(0, 32), material.subarray(32, 48));
2490
+ const out = createWriteStream2(target);
2491
+ out.write(Buffer.concat([Buffer.from("Salted__"), salt]));
2492
+ await pipeline2(createReadStream2(source), cipher, out);
2493
+ }
2494
+ var decryptHelp = (file) => [
2495
+ "This backup was encrypted before it was copied here.",
2496
+ "Decrypt each .enc file with the backup passphrase (set on the Connections page of the app):",
2497
+ "",
2498
+ ` openssl enc -d -aes-256-cbc -pbkdf2 -iter ${ENCRYPTION_ITERATIONS} -in ${file}.enc -out ${file}`,
2499
+ "",
2500
+ "Then check the files against SHA256SUMS with: sha256sum -c SHA256SUMS",
2501
+ ""
2502
+ ].join("\n");
2503
+
2504
+ // src/ops/schema.ts
2505
+ import { bigint, boolean as boolean2, pgTable as pgTable4, text as text4, timestamp as timestamp4, uuid as uuid4 } from "drizzle-orm/pg-core";
2506
+ var backupRun = pgTable4("backup_run", {
2507
+ id: uuid4("id").primaryKey().defaultRandom(),
2508
+ startedAt: timestamp4("started_at").defaultNow().notNull(),
2509
+ finishedAt: timestamp4("finished_at"),
2510
+ /** running | success | failed */
2511
+ status: text4("status").notNull(),
2512
+ trigger: text4("trigger").notNull(),
2513
+ /** Folder name inside BACKUP_DIR, set on success. */
2514
+ folder: text4("folder"),
2515
+ sizeBytes: bigint("size_bytes", { mode: "number" }),
2516
+ error: text4("error"),
2517
+ /** When the backup was copied to the backup storage (connection "appai-backup"). */
2518
+ uploadedAt: timestamp4("uploaded_at"),
2519
+ /** Whether the copy was encrypted with the backup passphrase. */
2520
+ uploadEncrypted: boolean2("upload_encrypted"),
2521
+ /** Why the last copy attempt failed; cleared by a successful copy. */
2522
+ uploadError: text4("upload_error")
2523
+ });
2524
+
2525
+ // src/ops/backup.ts
2526
+ var BackupError = class extends Error {
2527
+ constructor(message, status = 500) {
2528
+ super(message);
2529
+ this.status = status;
2530
+ }
2531
+ status;
2532
+ };
2533
+ function run(command, args) {
2534
+ return new Promise((resolve3, reject) => {
2535
+ const child = spawn(command, args, { stdio: ["ignore", "ignore", "pipe"] });
2536
+ let stderr = "";
2537
+ child.stderr.on("data", (chunk) => stderr += chunk.toString());
2538
+ child.on("error", (e) => reject(new Error(`${command} could not be started: ${e.message}`, { cause: e })));
2539
+ child.on(
2540
+ "close",
2541
+ (code) => code === 0 ? resolve3() : reject(new Error(`${command} failed (exit ${code}): ${stderr.trim().slice(-500)}`))
2542
+ );
2543
+ });
2544
+ }
2545
+ var pgDump = (url, file) => run("pg_dump", ["--format=custom", `--file=${file}`, `--dbname=${url}`]);
2546
+ var tarGz = (folder, file) => run("tar", ["-czf", file, "-C", folder, "."]);
2547
+ function sha256(file) {
2548
+ return new Promise((resolve3, reject) => {
2549
+ const hash = createHash("sha256");
2550
+ createReadStream3(file).on("data", (chunk) => hash.update(chunk)).on("error", reject).on("end", () => resolve3(hash.digest("hex")));
2551
+ });
2552
+ }
2553
+ var FOLDER2 = /^appai-\d{8}-\d{6}$/;
2554
+ var stamp = (d) => d.toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
2555
+ function redact2(message, databaseUrl) {
2556
+ let out = message;
2557
+ try {
2558
+ const { password } = new URL(databaseUrl);
2559
+ if (password) out = out.split(decodeURIComponent(password)).join("***");
2560
+ } catch {
2561
+ }
2562
+ return out.slice(0, 500);
2563
+ }
2564
+ function nextRunAfter(from, time) {
2565
+ const [hours, minutes] = time.split(":").map(Number);
2566
+ const next = new Date(Date.UTC(from.getUTCFullYear(), from.getUTCMonth(), from.getUTCDate(), hours, minutes));
2567
+ if (next.getTime() <= from.getTime()) next.setUTCDate(next.getUTCDate() + 1);
2568
+ return next;
2569
+ }
2570
+ function createBackups({ db, config, copy, dump = pgDump, archive = tarGz, now = () => /* @__PURE__ */ new Date(), onFinished }) {
2571
+ let running = false;
2572
+ let copying = false;
2573
+ async function prune() {
2574
+ const folders = (await readdir2(config.BACKUP_DIR)).filter((n) => FOLDER2.test(n)).sort().reverse();
2575
+ for (const old of folders.slice(config.BACKUP_KEEP)) await rm2(join4(config.BACKUP_DIR, old), { recursive: true, force: true });
2576
+ }
2577
+ async function recoverInterrupted() {
2578
+ await db.update(backupRun).set({ status: "failed", finishedAt: now(), error: "Interrupted: the app stopped during the backup" }).where(eq7(backupRun.status, "running"));
2579
+ }
2580
+ async function createBackup(trigger) {
2581
+ if (running) throw new BackupError("A backup is already running", 409);
2582
+ running = true;
2583
+ const startedAt3 = now();
2584
+ const [row] = await db.insert(backupRun).values({ startedAt: startedAt3, status: "running", trigger }).returning({ id: backupRun.id });
2585
+ const folder = `appai-${stamp(startedAt3)}`;
2586
+ const partial = join4(config.BACKUP_DIR, `.${folder}.partial`);
2587
+ try {
2588
+ await mkdir2(partial, { recursive: true });
2589
+ const files = [{ name: "db.dump", file: join4(partial, "db.dump") }];
2590
+ await dump(config.DATABASE_URL, files[0].file);
2591
+ if (config.FILES_DIR && existsSync2(config.FILES_DIR)) {
2592
+ files.push({ name: "files.tar.gz", file: join4(partial, "files.tar.gz") });
2593
+ await archive(config.FILES_DIR, files[1].file);
2594
+ }
2595
+ const entries = [];
2596
+ let sizeBytes = 0;
2597
+ for (const { name: name2, file } of files) {
2598
+ const bytes = (await stat2(file)).size;
2599
+ sizeBytes += bytes;
2600
+ entries.push({ name: name2, bytes, sha256: await sha256(file) });
2601
+ }
2602
+ await writeFile2(join4(partial, "manifest.json"), JSON.stringify({ createdAt: startedAt3.toISOString(), frameworkVersion: FRAMEWORK_VERSION, files: entries }, null, 2));
2603
+ await writeFile2(join4(partial, "SHA256SUMS"), entries.map((e) => `${e.sha256} ${e.name}`).join("\n") + "\n");
2604
+ await rename(partial, join4(config.BACKUP_DIR, folder));
2605
+ await db.update(backupRun).set({ status: "success", finishedAt: now(), folder, sizeBytes }).where(eq7(backupRun.id, row.id));
2606
+ await prune().catch((e) => console.error("Backup retention failed:", e));
2607
+ return { folder, sizeBytes };
2608
+ } catch (e) {
2609
+ await rm2(partial, { recursive: true, force: true }).catch(() => void 0);
2610
+ const message = redact2(e.message, config.DATABASE_URL);
2611
+ console.error("Backup failed:", message);
2612
+ await db.update(backupRun).set({ status: "failed", finishedAt: now(), error: message }).where(eq7(backupRun.id, row.id)).catch(() => void 0);
2613
+ throw new BackupError(message);
2614
+ } finally {
2615
+ running = false;
2616
+ onFinished?.();
2617
+ }
2618
+ }
2619
+ async function uploadBackup(folder) {
2620
+ if (!FOLDER2.test(folder)) throw new BackupError("Unknown backup", 404);
2621
+ if (!copy) throw new BackupError("Copying backups is not available", 409);
2622
+ const source = join4(config.BACKUP_DIR, folder);
2623
+ if (!existsSync2(source)) throw new BackupError("That backup is no longer on this server", 409);
2624
+ const storage = await copy.storage();
2625
+ if (!storage) throw new BackupError('The backup storage is not set up. An Admin can set up the storage "appai-backup" on the Connections page.', 409);
2626
+ if (copying) throw new BackupError("A backup is already being copied", 409);
2627
+ copying = true;
2628
+ const staging = join4(config.BACKUP_DIR, `.${folder}.upload`);
2629
+ const [run2] = await db.select().from(backupRun).where(eq7(backupRun.folder, folder)).limit(1);
2630
+ try {
2631
+ const passphrase = await copy.passphrase();
2632
+ const names = (await readdir2(source, { withFileTypes: true })).filter((e) => e.isFile()).map((e) => e.name);
2633
+ const dataFiles = names.filter((n) => n === "db.dump" || n === "files.tar.gz");
2634
+ const expected = /* @__PURE__ */ new Map();
2635
+ await mkdir2(staging, { recursive: true });
2636
+ await storage.deleteTree(`${BACKUP_STORAGE_PREFIX}/${folder}`);
2637
+ for (const name2 of names) {
2638
+ let file = join4(source, name2);
2639
+ let remote = name2;
2640
+ if (passphrase && dataFiles.includes(name2)) {
2641
+ file = join4(staging, `${name2}.enc`);
2642
+ remote = `${name2}.enc`;
2643
+ await encryptFile(join4(source, name2), file, passphrase);
2644
+ }
2645
+ const size = (await stat2(file)).size;
2646
+ await storage.putStream(`${BACKUP_STORAGE_PREFIX}/${folder}/${remote}`, createReadStream3(file), size);
2647
+ expected.set(`${BACKUP_STORAGE_PREFIX}/${folder}/${remote}`, size);
2648
+ }
2649
+ if (passphrase) {
2650
+ const help = Buffer.from(dataFiles.map(decryptHelp).join("\n"));
2651
+ await storage.put(`${BACKUP_STORAGE_PREFIX}/${folder}/DECRYPT.txt`, help);
2652
+ expected.set(`${BACKUP_STORAGE_PREFIX}/${folder}/DECRYPT.txt`, help.length);
2653
+ }
2654
+ const arrived = new Map((await storage.list(`${BACKUP_STORAGE_PREFIX}/${folder}`)).map((f) => [f.key, f.size]));
2655
+ for (const [key, size] of expected) {
2656
+ if (arrived.get(key) !== size) throw new Error(`The copy of ${key.split("/").pop()} is incomplete`);
2657
+ }
2658
+ if (run2) await db.update(backupRun).set({ uploadedAt: now(), uploadEncrypted: Boolean(passphrase), uploadError: null }).where(eq7(backupRun.id, run2.id));
2659
+ await pruneCopies(storage).catch((e) => console.error("Removing old backup copies failed:", e));
2660
+ return { folder, encrypted: Boolean(passphrase), files: expected.size };
2661
+ } catch (e) {
2662
+ const message = redact2(e.message, config.DATABASE_URL);
2663
+ if (run2) await db.update(backupRun).set({ uploadError: message }).where(eq7(backupRun.id, run2.id)).catch(() => void 0);
2664
+ throw new BackupError(message);
2665
+ } finally {
2666
+ copying = false;
2667
+ await rm2(staging, { recursive: true, force: true }).catch(() => void 0);
2668
+ onFinished?.();
2669
+ }
2670
+ }
2671
+ async function pruneCopies(storage) {
2672
+ const names = /* @__PURE__ */ new Set();
2673
+ for (const file of await storage.list(BACKUP_STORAGE_PREFIX)) {
2674
+ const name2 = file.key.split("/")[1];
2675
+ if (name2 && FOLDER2.test(name2)) names.add(name2);
2676
+ }
2677
+ for (const old of [...names].sort().reverse().slice(copy.keep())) await storage.deleteTree(`${BACKUP_STORAGE_PREFIX}/${old}`);
2678
+ }
2679
+ async function backupNow(trigger) {
2680
+ const result = await createBackup(trigger);
2681
+ if (copy?.auto()) await uploadBackup(result.folder).catch((e) => console.error("Copying the backup failed:", e.message));
2682
+ return result;
2683
+ }
2684
+ const recent = (limit = 10) => db.select().from(backupRun).orderBy(desc5(backupRun.startedAt)).limit(limit);
2685
+ async function lastSuccess() {
2686
+ const [row] = await db.select().from(backupRun).where(eq7(backupRun.status, "success")).orderBy(desc5(backupRun.startedAt)).limit(1);
2687
+ return row ?? null;
2688
+ }
2689
+ return { backupNow, uploadBackup, recent, lastSuccess, recoverInterrupted, isRunning: () => running, isCopying: () => copying };
2690
+ }
2691
+
2692
+ // src/ops/routes.ts
2693
+ var startedAt2 = Date.now();
2694
+ function opsRoutes({ authz, ops }) {
2695
+ const app = new Hono4();
2696
+ app.get("/api/status", requirePermission(authz, "status:read"), async (c) => {
2697
+ const checks = await ops.monitor.tick();
2698
+ const next = ops.nextBackupAt();
2699
+ return c.json({
2700
+ status: ops.monitor.overall(checks),
2701
+ checks,
2702
+ backups: await ops.backups.recent(10),
2703
+ backupRunning: ops.backups.isRunning(),
2704
+ nextBackupAt: next,
2705
+ disk: await ops.disk().catch(() => null),
2706
+ uptimeSeconds: Math.round((Date.now() - startedAt2) / 1e3),
2707
+ settings: ops.settings,
2708
+ copy: await ops.copy(),
2709
+ frameworkVersion: FRAMEWORK_VERSION
2710
+ });
2711
+ });
2712
+ app.post("/api/backups", requirePermission(authz, "backup:create"), async (c) => {
2713
+ try {
2714
+ const result = await ops.backups.backupNow("manual");
2715
+ await c.get("audit")("backup.created", result.folder, { sizeBytes: result.sizeBytes });
2716
+ return c.json(result, 201);
2717
+ } catch (e) {
2718
+ if (e instanceof BackupError) {
2719
+ await c.get("audit")("backup.failed", null, { error: e.message });
2720
+ return c.json({ error: e.message }, e.status);
2721
+ }
2722
+ throw e;
2723
+ }
2724
+ });
2725
+ app.post("/api/backups/:folder/upload", requirePermission(authz, "backup:upload"), async (c) => {
2726
+ const folder = c.req.param("folder");
2727
+ try {
2728
+ const result = await ops.backups.uploadBackup(folder);
2729
+ await c.get("audit")("backup.copied", folder, { encrypted: result.encrypted, files: result.files });
2730
+ return c.json(result);
2731
+ } catch (e) {
2732
+ if (e instanceof BackupError) {
2733
+ await c.get("audit")("backup.copy_failed", folder, { error: e.message });
2734
+ return c.json({ error: e.message }, e.status);
2735
+ }
2736
+ throw e;
2737
+ }
2738
+ });
2739
+ return app;
2740
+ }
2741
+
2742
+ // src/app.ts
2743
+ import { ZodError } from "zod";
2744
+
2745
+ // src/auth/routes.ts
2746
+ import { Hono as Hono5 } from "hono";
2747
+ var OPEN_ORGANIZATION_PATHS = /* @__PURE__ */ new Set(["accept-invitation", "get-invitation", "reject-invitation"]);
2748
+ function authRoutes(auth, authz) {
2749
+ const app = new Hono5();
2750
+ app.use("/api/auth/*", async (c, next) => {
2751
+ const path = new URL(c.req.url).pathname.replace("/api/auth/", "");
2752
+ const closed = path.startsWith("api-key") || path.startsWith("organization/") && !OPEN_ORGANIZATION_PATHS.has(path.slice("organization/".length));
2753
+ if (closed) return c.json({ error: "Not found" }, 404);
2754
+ await next();
2755
+ });
2756
+ app.on(["GET", "POST"], "/api/auth/*", publicRoute(), (c) => auth.handler(c.req.raw));
2757
+ app.get("/api/me", requireSession(), async (c) => {
2758
+ const user2 = c.get("user");
2759
+ await authz.joinPendingInvitation(user2.id);
2760
+ const [roles, permissions, access] = await Promise.all([
2761
+ authz.roleKeysOf(user2.id),
2762
+ authz.permissionsOf(user2.id),
2763
+ authz.accessOf(user2.id)
2764
+ ]);
2765
+ return c.json({
2766
+ user: user2,
2767
+ roles,
2768
+ /** Single role string kept for older clients: "owner" means Admin. */
2769
+ role: roles.join(","),
2770
+ permissions: [...permissions],
2771
+ accessExpiresAt: access.active ? access.expiresAt : null
2772
+ });
2773
+ });
2774
+ return app;
2775
+ }
2776
+
2777
+ // src/logging.ts
2778
+ import { logger } from "hono/logger";
2779
+ var QUIET_PATHS = /* @__PURE__ */ new Set(["/api/health", "/api/status"]);
2780
+ function requestLogger(print = console.log) {
2781
+ const normal = logger(print);
2782
+ return async (c, next) => {
2783
+ if (!QUIET_PATHS.has(c.req.path)) return normal(c, next);
2784
+ const started = Date.now();
2785
+ await next();
2786
+ if (c.res.status >= 500) print(`--> ${c.req.method} ${c.req.path} ${c.res.status} ${Date.now() - started}ms`);
2787
+ };
2788
+ }
2789
+
2790
+ // src/security.ts
2791
+ import { createMiddleware as createMiddleware2 } from "hono/factory";
2792
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
2793
+ function crossSiteGuard(trustedOrigins) {
2794
+ const trusted = new Set(trustedOrigins.map((o) => new URL(o).origin));
2795
+ return createMiddleware2(async (c, next) => {
2796
+ if (SAFE_METHODS.has(c.req.method) || c.req.header("x-api-key") || !c.req.header("cookie")) return next();
2797
+ const origin = c.req.header("origin") ?? refererOrigin(c.req.header("referer"));
2798
+ if (!origin || !trusted.has(origin)) return c.json({ error: "Cross-site request refused" }, 403);
2799
+ return next();
2800
+ });
2801
+ }
2802
+ function refererOrigin(referer) {
2803
+ try {
2804
+ return referer ? new URL(referer).origin : void 0;
2805
+ } catch {
2806
+ return void 0;
2807
+ }
2808
+ }
2809
+
2810
+ // src/connections/routes.ts
2811
+ import { Hono as Hono6 } from "hono";
2812
+ import { z as z4 } from "zod";
2813
+ function connectionRoutes({ authz, connections }) {
2814
+ const app = new Hono6();
2815
+ const actor = (c) => c.get("user")?.email ?? "unknown";
2816
+ const body = z4.object({
2817
+ label: z4.string().trim().max(80).optional(),
2818
+ provider: z4.string().min(1).max(40),
2819
+ config: z4.record(z4.string(), z4.unknown()).optional(),
2820
+ secrets: z4.record(z4.string(), z4.string().nullable()).optional(),
2821
+ enabled: z4.boolean().optional()
2822
+ });
2823
+ for (const kind of CONNECTION_KINDS) {
2824
+ const read = requirePermission(authz, `${kind}:read`);
2825
+ const update = requirePermission(authz, `${kind}:update`);
2826
+ app.get(
2827
+ `/api/connections/${kind}`,
2828
+ read,
2829
+ async (c) => c.json({ connections: await connections.list(kind), providers: connections.providers(kind), redirectUri: connections.redirectUri(kind) })
2830
+ );
2831
+ app.put(`/api/connections/${kind}/:id`, update, async (c) => {
2832
+ const id = c.req.param("id");
2833
+ const input = body.parse(await c.req.json());
2834
+ const { view, changedSecrets } = await connections.save(kind, id, input, actor(c));
2835
+ await c.get("audit")("connection.saved", `${kind}:${id}`, { provider: input.provider, enabled: view.enabled, changedSecrets });
2836
+ return c.json(view);
2837
+ });
2838
+ app.delete(`/api/connections/${kind}/:id`, update, async (c) => {
2839
+ const id = c.req.param("id");
2840
+ await connections.remove(kind, id);
2841
+ await c.get("audit")("connection.removed", `${kind}:${id}`);
2842
+ return c.json({ ok: true });
2843
+ });
2844
+ app.post(`/api/connections/${kind}/:id/test`, update, async (c) => {
2845
+ const id = c.req.param("id");
2846
+ const result = await connections.test(kind, id, c.get("user")?.email);
2847
+ await c.get("audit")("connection.tested", `${kind}:${id}`, { ok: result.ok });
2848
+ return c.json(result);
2849
+ });
2850
+ app.post(`/api/connections/${kind}/:id/connect`, update, async (c) => c.json({ url: await connections.oauthStart(kind, c.req.param("id"), c.get("user").id) }));
2851
+ app.get(`/api/connections/${kind}/oauth/callback`, update, async (c) => {
2852
+ const back = (query) => c.redirect(`/connections?${query}`);
2853
+ const error = c.req.query("error");
2854
+ if (error) return back(`error=${encodeURIComponent(c.req.query("error_description") ?? error)}`);
2855
+ const code = c.req.query("code");
2856
+ const state = c.req.query("state");
2857
+ if (!code || !state) throw new AuthzError("The provider did not send a sign-in code");
2858
+ try {
2859
+ const done = await connections.oauthFinish(kind, c.get("user").id, code, state);
2860
+ await c.get("audit")("connection.connected", `${kind}:${done.id}`, { ok: done.test.ok });
2861
+ return back(`connected=${encodeURIComponent(done.id)}`);
2862
+ } catch (e) {
2863
+ return back(`error=${encodeURIComponent(e.message)}`);
2864
+ }
2865
+ });
2866
+ }
2867
+ app.get("/api/llm/usage", requirePermission(authz, "llm:read"), async (c) => c.json({ usage: await connections.llmUsage(14) }));
2868
+ return app;
2869
+ }
2870
+
2871
+ // src/groups/routes.ts
2872
+ import { Hono as Hono7 } from "hono";
2873
+ import { z as z5 } from "zod";
2874
+ var name = z5.string().trim().min(1).max(80);
2875
+ var description = z5.string().trim().max(300);
2876
+ function groupRoutes({ authz, groups }) {
2877
+ const app = new Hono7();
2878
+ const need = (permission) => requirePermission(authz, permission);
2879
+ app.get("/api/groups", need("group:read"), async (c) => c.json({ groups: await groups.list() }));
2880
+ app.post("/api/groups", need("group:create"), async (c) => {
2881
+ const body = z5.object({ name, description: description.optional() }).parse(await c.req.json());
2882
+ const group = await groups.create(body.name, body.description);
2883
+ await c.get("audit")("group.created", group.id, { name: group.name });
2884
+ return c.json(group, 201);
2885
+ });
2886
+ app.patch("/api/groups/:id", need("group:update"), async (c) => {
2887
+ const body = z5.object({ name: name.optional(), description: description.optional() }).parse(await c.req.json());
2888
+ const id = c.req.param("id");
2889
+ const group = await groups.update(id, body);
2890
+ await c.get("audit")("group.updated", id, { name: group.name });
2891
+ return c.json(group);
2892
+ });
2893
+ app.delete("/api/groups/:id", need("group:delete"), async (c) => {
2894
+ const group = await groups.remove(c.req.param("id"));
2895
+ await c.get("audit")("group.deleted", group.id, { name: group.name, members: group.members.length });
2896
+ return c.json({ ok: true });
2897
+ });
2898
+ app.put("/api/groups/:id/members", need("group:update"), async (c) => {
2899
+ const { userIds } = z5.object({ userIds: z5.array(z5.string()).max(5e3) }).parse(await c.req.json());
2900
+ const id = c.req.param("id");
2901
+ const { group, added, removed } = await groups.setMembers(id, userIds);
2902
+ if (added.length > 0 || removed.length > 0) {
2903
+ await c.get("audit")("group.members_changed", id, {
2904
+ name: group.name,
2905
+ added: added.map((m) => m.email),
2906
+ removed: removed.map((m) => m.email)
2907
+ });
2908
+ }
2909
+ return c.json(group);
2910
+ });
2911
+ return app;
2912
+ }
2913
+
2914
+ // src/settings/routes.ts
2915
+ import { createHash as createHash2 } from "crypto";
2916
+ import { Hono as Hono8 } from "hono";
2917
+ import { bodyLimit } from "hono/body-limit";
2918
+ import { z as z6 } from "zod";
2919
+ var MAX_LOGO_BYTES = 1024 * 1024;
2920
+ function imageType(bytes) {
2921
+ const starts = (...sig) => sig.every((b, i) => bytes[i] === b);
2922
+ if (starts(137, 80, 78, 71)) return "image/png";
2923
+ if (starts(255, 216, 255)) return "image/jpeg";
2924
+ if (starts(82, 73, 70, 70) && bytes.subarray(8, 12).toString("latin1") === "WEBP") return "image/webp";
2925
+ const head = bytes.subarray(0, 2048).toString("utf8");
2926
+ if (/<svg[\s>]/i.test(head) && !/<script|\son\w+\s*=/i.test(bytes.toString("utf8"))) return "image/svg+xml";
2927
+ return null;
2928
+ }
2929
+ function settingsRoutes({ authz, settings, brand, storage }) {
2930
+ const app = new Hono8();
2931
+ const actor = (c) => c.get("user")?.email ?? "unknown";
2932
+ app.get(
2933
+ "/api/settings",
2934
+ requirePermission(authz, "settings:read"),
2935
+ (c) => c.json({ settings: settings.describe(), brand: brand.brand() })
2936
+ );
2937
+ app.get("/api/settings/values", requireSession(), (c) => c.json(settings.exposed()));
2938
+ app.put("/api/settings", requirePermission(authz, "settings:update"), async (c) => {
2939
+ const { values } = z6.object({ values: z6.record(z6.string(), z6.unknown()) }).parse(await c.req.json());
2940
+ const changes = await settings.update(values, actor(c));
2941
+ for (const change of changes) {
2942
+ await c.get("audit")(values[change.key] === null ? "settings.reset" : "settings.updated", change.key, { from: change.from, to: change.to });
2943
+ }
2944
+ return c.json({ settings: settings.describe(), brand: brand.brand() });
2945
+ });
2946
+ app.post(
2947
+ "/api/settings/logo",
2948
+ requirePermission(authz, "settings:update"),
2949
+ bodyLimit({ maxSize: MAX_LOGO_BYTES + 100 * 1024, onError: (c) => c.json({ error: "The logo is larger than 1 MB" }, 413) }),
2950
+ async (c) => {
2951
+ const file = (await c.req.parseBody()).logo;
2952
+ if (!(file instanceof File) || file.size === 0) throw new AuthzError("Choose a logo file");
2953
+ if (file.size > MAX_LOGO_BYTES) throw new AuthzError("The logo is larger than 1 MB");
2954
+ const bytes = Buffer.from(await file.arrayBuffer());
2955
+ const type = imageType(bytes);
2956
+ if (!type) throw new AuthzError("The logo must be a PNG, JPG, WebP or SVG image");
2957
+ const version = createHash2("sha256").update(bytes).digest("hex").slice(0, 12);
2958
+ const previous = settings.get("brand.logo");
2959
+ const logo = { key: `brand/logo-${version}${IMAGE_EXTENSIONS[type]}`, type, version };
2960
+ await storage.put(logo.key, bytes);
2961
+ await settings.setManaged("brand.logo", logo, actor(c));
2962
+ if (previous && previous.key !== logo.key) await storage.delete(previous.key).catch(() => void 0);
2963
+ await c.get("audit")("settings.logo_changed", "brand.logo", { type, bytes: bytes.length });
2964
+ return c.json({ brand: brand.brand() });
2965
+ }
2966
+ );
2967
+ app.delete("/api/settings/logo", requirePermission(authz, "settings:update"), async (c) => {
2968
+ const previous = settings.get("brand.logo");
2969
+ if (previous) {
2970
+ await settings.setManaged("brand.logo", null, actor(c));
2971
+ await storage.delete(previous.key).catch(() => void 0);
2972
+ await c.get("audit")("settings.logo_removed", "brand.logo");
2973
+ }
2974
+ return c.json({ brand: brand.brand() });
2975
+ });
2976
+ return app;
2977
+ }
2978
+
2979
+ // src/app.ts
2980
+ function createApp({ auth, db, authz, email, publicUrl, brand, settings, storage, connections, ops, trustedOrigins = [publicUrl], ...health }) {
2981
+ const app = new Hono9();
2982
+ app.use("*", requestLogger());
2983
+ app.use("/api/*", secureHeaders({ strictTransportSecurity: false, xXssProtection: false }));
2984
+ app.use("/api/*", async (c, next) => {
2985
+ await next();
2986
+ if (!c.res.headers.has("cache-control")) c.res.headers.set("cache-control", "no-store");
2987
+ });
2988
+ app.use("/api/*", crossSiteGuard(trustedOrigins));
2989
+ app.use("/api/*", sessionMiddleware(auth, authz));
2990
+ app.route("/", healthRoutes(health));
2991
+ app.route("/", brandRoutes(brand));
2992
+ app.route("/", authRoutes(auth, authz));
2993
+ app.route("/", authzRoutes({ auth, db, authz, email, appName: health.appName, publicUrl }));
2994
+ app.route("/", groupRoutes({ authz, groups: createGroups({ db }) }));
2995
+ app.route("/", opsRoutes({ authz, ops }));
2996
+ app.route("/", settingsRoutes({ authz, settings, brand, storage }));
2997
+ app.route("/", connectionRoutes({ authz, connections }));
2998
+ app.onError((err, c) => {
2999
+ if (err instanceof AuthzError) return c.json({ error: err.message }, err.status);
3000
+ if (err instanceof ZodError) return c.json({ error: "Invalid request", issues: err.issues }, 400);
3001
+ console.error(err);
3002
+ return c.json({ error: "Internal server error" }, 500);
3003
+ });
3004
+ return app;
3005
+ }
3006
+
3007
+ // src/settings/definitions.ts
3008
+ import { z as z7 } from "zod";
3009
+ var KEY2 = /^[a-z][a-zA-Z0-9]*(\.[a-zA-Z][a-zA-Z0-9]*)+$/;
3010
+ function validateValue(def, raw) {
3011
+ const fail = (msg) => {
3012
+ throw new AuthzError(`${def.label}: ${msg}`);
3013
+ };
3014
+ const parse = (schema2, what) => {
3015
+ const r = schema2.safeParse(raw);
3016
+ return r.success ? r.data : fail(what);
3017
+ };
3018
+ switch (def.type) {
3019
+ case "text":
3020
+ return parse(z7.string().trim().min(1).max(def.max ?? 200), `enter text of 1 to ${def.max ?? 200} characters`);
3021
+ case "number": {
3022
+ const n = parse(z7.number().int(), "enter a whole number");
3023
+ if (def.min !== void 0 && n < def.min || def.max !== void 0 && n > def.max) {
3024
+ return fail(`enter a number between ${def.min ?? "any"} and ${def.max ?? "any"}`);
3025
+ }
3026
+ return n;
3027
+ }
3028
+ case "boolean":
3029
+ return parse(z7.boolean(), "must be on or off");
3030
+ case "select":
3031
+ return parse(z7.enum((def.options ?? []).map((o) => o.value)), "choose one of the options");
3032
+ case "numbers": {
3033
+ const list = parse(z7.array(z7.number().int()).max(10), "enter up to 10 whole numbers");
3034
+ if (list.some((n) => def.min !== void 0 && n < def.min || def.max !== void 0 && n > def.max)) {
3035
+ return fail(`each number must be between ${def.min ?? "any"} and ${def.max ?? "any"}`);
3036
+ }
3037
+ return [...new Set(list)].sort((a, b) => b - a);
3038
+ }
3039
+ case "color":
3040
+ return parse(z7.string().regex(/^#[0-9a-fA-F]{6}$/), "use a 6-digit hex color such as #2563eb").toLowerCase();
3041
+ }
3042
+ }
3043
+ function checkDefinitions(defs) {
3044
+ const seen = /* @__PURE__ */ new Set();
3045
+ for (const d of defs) {
3046
+ if (!KEY2.test(d.key)) throw new Error(`Invalid setting key "${d.key}" (use dots and camel case, e.g. policy.reminderDays)`);
3047
+ if (seen.has(d.key)) throw new Error(`Setting "${d.key}" is defined twice`);
3048
+ seen.add(d.key);
3049
+ if (d.type === "select" && !d.options?.length) throw new Error(`Setting "${d.key}" needs options`);
3050
+ if (d.default !== null && !d.managed) validateValue(d, d.default);
3051
+ }
3052
+ }
3053
+ var BACKUPS_GROUP = "Backups";
3054
+ var IDENTITY_GROUP = "Identity";
3055
+ var COLORS_GROUP = "Brand colors";
3056
+ function frameworkSettings({ brand }) {
3057
+ const color = (key, label, description2, value) => ({
3058
+ key,
3059
+ label,
3060
+ description: description2,
3061
+ group: COLORS_GROUP,
3062
+ type: "color",
3063
+ default: value ?? null
3064
+ });
3065
+ return [
3066
+ {
3067
+ key: "app.name",
3068
+ label: "Application name",
3069
+ description: "Shown in the header, on the sign-in pages, in the browser tab and in emails.",
3070
+ group: IDENTITY_GROUP,
3071
+ type: "text",
3072
+ default: brand.appName,
3073
+ max: 60
3074
+ },
3075
+ { key: "brand.logo", label: "Logo", group: IDENTITY_GROUP, type: "text", default: null, managed: true },
3076
+ color("brand.primary", "Primary color", "Buttons, links and highlights.", brand.colors.primary),
3077
+ color("brand.secondary", "Secondary color", "Accents.", brand.colors.secondary),
3078
+ color("brand.primaryDark", "Primary color in dark mode", "A lighter variant that reads well on dark backgrounds. Optional.", brand.colors.primaryDark),
3079
+ color("brand.secondaryDark", "Secondary color in dark mode", "Optional.", brand.colors.secondaryDark),
3080
+ {
3081
+ key: "backup.autoUpload",
3082
+ label: "Copy every backup to the backup storage",
3083
+ description: 'After each backup, copy it to the storage "appai-backup" (set up on the Connections page). Without a copy elsewhere, a lost server means lost backups.',
3084
+ group: BACKUPS_GROUP,
3085
+ type: "boolean",
3086
+ default: false
3087
+ },
3088
+ {
3089
+ key: "backup.remoteKeep",
3090
+ label: "Copies to keep in the backup storage",
3091
+ description: "Older copies are deleted from the backup storage after a new one arrives. Only copies made by this app are deleted.",
3092
+ group: BACKUPS_GROUP,
3093
+ type: "number",
3094
+ default: 14,
3095
+ min: 1,
3096
+ max: 365,
3097
+ unit: "copies"
3098
+ }
3099
+ ];
3100
+ }
3101
+
3102
+ // src/settings/service.ts
3103
+ import { eq as eq8 } from "drizzle-orm";
3104
+
3105
+ // src/settings/schema.ts
3106
+ import { jsonb as jsonb3, pgTable as pgTable5, text as text5, timestamp as timestamp5 } from "drizzle-orm/pg-core";
3107
+ var appSetting = pgTable5("app_setting", {
3108
+ key: text5("key").primaryKey(),
3109
+ value: jsonb3("value").$type().notNull(),
3110
+ updatedAt: timestamp5("updated_at").defaultNow().notNull(),
3111
+ /** Email of the admin who last changed it. */
3112
+ updatedBy: text5("updated_by")
3113
+ });
3114
+
3115
+ // src/settings/service.ts
3116
+ function createSettings({ db, definitions }) {
3117
+ checkDefinitions(definitions);
3118
+ const defs = new Map(definitions.map((d) => [d.key, d]));
3119
+ const stored = /* @__PURE__ */ new Map();
3120
+ const def = (key) => {
3121
+ const d = defs.get(key);
3122
+ if (!d) throw new Error(`Unknown setting "${key}"`);
3123
+ return d;
3124
+ };
3125
+ const read = (d) => stored.has(d.key) ? stored.get(d.key) : d.default;
3126
+ async function write(changes, actor, allowManaged) {
3127
+ const prepared = [];
3128
+ for (const [key, raw] of Object.entries(changes)) {
3129
+ const d = defs.get(key);
3130
+ if (!d) throw new AuthzError(`Unknown setting "${key}"`);
3131
+ if (d.managed && !allowManaged) throw new AuthzError(`${d.label} cannot be changed here`);
3132
+ prepared.push({ d, value: raw === null ? null : d.managed ? raw : validateValue(d, raw) });
3133
+ }
3134
+ const done = [];
3135
+ for (const { d, value } of prepared) {
3136
+ const from = read(d);
3137
+ if (value === null || JSON.stringify(value) === JSON.stringify(d.default)) {
3138
+ await db.delete(appSetting).where(eq8(appSetting.key, d.key));
3139
+ stored.delete(d.key);
3140
+ } else {
3141
+ await db.insert(appSetting).values({ key: d.key, value, updatedBy: actor }).onConflictDoUpdate({ target: appSetting.key, set: { value, updatedAt: /* @__PURE__ */ new Date(), updatedBy: actor } });
3142
+ stored.set(d.key, value);
3143
+ }
3144
+ const to = read(d);
3145
+ if (JSON.stringify(from) !== JSON.stringify(to)) done.push({ key: d.key, from, to });
3146
+ }
3147
+ return done;
3148
+ }
3149
+ return {
3150
+ /** Reads all saved values; call once at startup, after the migrations. */
3151
+ async load() {
3152
+ stored.clear();
3153
+ for (const row of await db.select().from(appSetting)) if (defs.has(row.key)) stored.set(row.key, row.value);
3154
+ },
3155
+ /** The current value (the default until an admin changes it). Cheap: no database access. */
3156
+ get(key) {
3157
+ return read(def(key));
3158
+ },
3159
+ /** For the Settings page: everything an admin can edit, with current values. */
3160
+ describe() {
3161
+ return definitions.filter((d) => !d.managed).map((d) => ({ ...d, value: read(d), isDefault: !stored.has(d.key) }));
3162
+ },
3163
+ /** Values every signed-in user may read (settings marked `expose`). */
3164
+ exposed() {
3165
+ return Object.fromEntries(definitions.filter((d) => d.expose).map((d) => [d.key, read(d)]));
3166
+ },
3167
+ /** Saves values; `null` resets a setting to its default. Returns what actually changed. */
3168
+ update(changes, actor) {
3169
+ return write(changes, actor, false);
3170
+ },
3171
+ /** For code that owns a value (the uploaded logo). */
3172
+ setManaged(key, value, actor) {
3173
+ return write({ [key]: value }, actor, true);
3174
+ }
3175
+ };
3176
+ }
3177
+
3178
+ // src/ops/index.ts
3179
+ import { existsSync as existsSync3 } from "fs";
3180
+
3181
+ // src/ops/monitor.ts
3182
+ import { statfs } from "fs/promises";
3183
+ import { sql as sql8 } from "drizzle-orm";
3184
+ var HOUR = 60 * 60 * 1e3;
3185
+ var BACKUP_MAX_AGE_HOURS = 36;
3186
+ var REALERT_AFTER_MS = 24 * HOUR;
3187
+ var formatBytes = (bytes) => {
3188
+ const units = ["B", "KB", "MB", "GB", "TB"];
3189
+ let value = bytes;
3190
+ let unit = 0;
3191
+ while (value >= 1024 && unit < units.length - 1) {
3192
+ value /= 1024;
3193
+ unit++;
3194
+ }
3195
+ return `${value.toFixed(unit === 0 ? 0 : 1)} ${units[unit]}`;
3196
+ };
3197
+ async function diskUsage(path) {
3198
+ const s = await statfs(path);
3199
+ const total = s.blocks * s.bsize;
3200
+ const free = s.bavail * s.bsize;
3201
+ return { totalBytes: total, freeBytes: free, freePercent: total > 0 ? free / total * 100 : 100 };
3202
+ }
3203
+ function createMonitor({ db, config, backups, alert, now = () => /* @__PURE__ */ new Date(), extraChecks = {} }) {
3204
+ const checks = {
3205
+ database: {
3206
+ label: "Database",
3207
+ run: async () => {
3208
+ await db.execute(sql8`select 1`);
3209
+ return { status: "ok", detail: "Reachable" };
3210
+ }
3211
+ },
3212
+ disk: {
3213
+ label: "Disk space",
3214
+ run: async () => {
3215
+ const usage = await diskUsage(config.BACKUP_DIR).catch(() => diskUsage("."));
3216
+ const detail = `${usage.freePercent.toFixed(0)}% free (${formatBytes(usage.freeBytes)} of ${formatBytes(usage.totalBytes)})`;
3217
+ return { status: usage.freePercent < config.DISK_MIN_FREE_PERCENT ? "fail" : "ok", detail };
3218
+ }
3219
+ },
3220
+ backup: {
3221
+ label: "Backups",
3222
+ run: async () => {
3223
+ if (!config.BACKUP_ENABLED) return { status: "warn", detail: "Automatic backups are switched off" };
3224
+ const [latest2] = await backups.recent(1);
3225
+ const success = await backups.lastSuccess();
3226
+ if (latest2?.status === "failed") return { status: "fail", detail: `The last backup failed: ${latest2.error ?? "unknown error"}` };
3227
+ if (!success) return { status: "warn", detail: "No backup has been made yet" };
3228
+ const hours = (now().getTime() - (success.finishedAt ?? success.startedAt).getTime()) / HOUR;
3229
+ if (hours > BACKUP_MAX_AGE_HOURS) return { status: "fail", detail: `No successful backup for ${Math.floor(hours)} hours` };
3230
+ return { status: "ok", detail: `Last backup ${success.finishedAt?.toISOString() ?? success.startedAt.toISOString()}` };
3231
+ }
3232
+ },
3233
+ ...extraChecks
3234
+ };
3235
+ let latest = [];
3236
+ const state = /* @__PURE__ */ new Map();
3237
+ let ticking = null;
3238
+ async function runChecks() {
3239
+ return Promise.all(
3240
+ Object.entries(checks).map(async ([name2, { label, run: run2 }]) => {
3241
+ try {
3242
+ return { name: name2, label, ...await run2() };
3243
+ } catch (e) {
3244
+ return { name: name2, label, status: "fail", detail: e.message.slice(0, 300) };
3245
+ }
3246
+ })
3247
+ );
3248
+ }
3249
+ async function notify(results) {
3250
+ for (const r of results) {
3251
+ const known = state.get(r.name);
3252
+ if (r.status === "fail") {
3253
+ if (!known) {
3254
+ state.set(r.name, { failingSince: now(), lastAlertAt: now() });
3255
+ await alert(`Problem: ${r.label}`, `${r.label} needs attention.
3256
+
3257
+ ${r.detail}`);
3258
+ } else if (now().getTime() - known.lastAlertAt.getTime() >= REALERT_AFTER_MS) {
3259
+ known.lastAlertAt = now();
3260
+ await alert(`Still a problem: ${r.label}`, `${r.label} has been failing since ${known.failingSince.toISOString()}.
3261
+
3262
+ ${r.detail}`);
3263
+ }
3264
+ } else if (known) {
3265
+ state.delete(r.name);
3266
+ await alert(`Recovered: ${r.label}`, `${r.label} is working again.
3267
+
3268
+ ${r.detail}`);
3269
+ }
3270
+ }
3271
+ }
3272
+ function tick() {
3273
+ ticking ??= (async () => {
3274
+ try {
3275
+ latest = await runChecks();
3276
+ await notify(latest).catch((e) => console.error("Sending alert failed:", e));
3277
+ return latest;
3278
+ } finally {
3279
+ ticking = null;
3280
+ }
3281
+ })();
3282
+ return ticking;
3283
+ }
3284
+ return {
3285
+ tick,
3286
+ current: () => latest,
3287
+ overall: (results = latest) => results.some((r) => r.status === "fail") ? "fail" : results.some((r) => r.status === "warn") ? "warn" : "ok"
3288
+ };
3289
+ }
3290
+
3291
+ // src/ops/index.ts
3292
+ var DAY2 = 24 * 60 * 60 * 1e3;
3293
+ function createOperations({ db, config, email, appName, dump, archive, extraChecks, settings, connections }) {
3294
+ const copy = settings && connections ? {
3295
+ storage: async () => await connections.storageReady(BACKUP_STORAGE) ? connections.storage(BACKUP_STORAGE) : null,
3296
+ passphrase: () => connections.backupPassphrase(),
3297
+ keep: () => settings.get("backup.remoteKeep"),
3298
+ auto: () => settings.get("backup.autoUpload")
3299
+ } : void 0;
3300
+ const backups = createBackups({ db, config, copy, dump, archive, onFinished: () => void monitor.tick() });
3301
+ const copyChecks = {};
3302
+ if (copy && connections) {
3303
+ copyChecks.backupCopy = {
3304
+ label: "Backup copies",
3305
+ run: async () => {
3306
+ if (!await connections.storageReady(BACKUP_STORAGE)) {
3307
+ return { status: "warn", detail: 'Backups exist only on this server. Set up the storage "appai-backup" to keep a copy somewhere else.' };
3308
+ }
3309
+ const latest = await backups.lastSuccess();
3310
+ if (latest?.uploadError) return { status: copy.auto() ? "fail" : "warn", detail: `The last copy failed: ${latest.uploadError}` };
3311
+ if (latest?.uploadedAt) return { status: "ok", detail: `Last copy ${latest.uploadedAt.toISOString()}${latest.uploadEncrypted ? " (encrypted)" : ""}` };
3312
+ return { status: copy.auto() ? "warn" : "ok", detail: copy.auto() ? "The latest backup has not been copied yet" : "Copies are made by hand (automatic copies are off)" };
3313
+ }
3314
+ };
3315
+ copyChecks.connections = { label: "Connections", run: () => connections.health() };
3316
+ }
3317
+ const monitor = createMonitor({
3318
+ db,
3319
+ config,
3320
+ backups,
3321
+ extraChecks: { ...copyChecks, ...extraChecks },
3322
+ alert: async (subject, body) => {
3323
+ for (const to of config.ALERT_EMAILS) {
3324
+ await email.send(alertEmail(to, appName(), subject, body)).catch((e) => console.error(`Alert to ${to} failed:`, e));
3325
+ }
3326
+ }
3327
+ });
3328
+ const timers = [];
3329
+ const nextBackupAt = () => config.BACKUP_ENABLED ? nextRunAfter(/* @__PURE__ */ new Date(), config.BACKUP_TIME) : null;
3330
+ function scheduleBackup() {
3331
+ const at = nextBackupAt();
3332
+ if (!at) return;
3333
+ const timer = setTimeout(() => {
3334
+ void backups.backupNow("scheduled").catch(() => void 0);
3335
+ scheduleBackup();
3336
+ }, at.getTime() - Date.now());
3337
+ timer.unref();
3338
+ timers.push(timer);
3339
+ }
3340
+ async function start() {
3341
+ await backups.recoverInterrupted();
3342
+ if (config.ALERT_EMAILS.length === 0) console.warn("ALERT_EMAILS is not set: nobody will be told about failed backups or outages.");
3343
+ const every = setInterval(() => void monitor.tick(), config.HEALTH_CHECK_SECONDS * 1e3);
3344
+ every.unref();
3345
+ timers.push(every);
3346
+ if (config.BACKUP_ENABLED) {
3347
+ scheduleBackup();
3348
+ const last = await backups.lastSuccess();
3349
+ if (!last || Date.now() - (last.finishedAt ?? last.startedAt).getTime() > DAY2) {
3350
+ const catchUp = setTimeout(() => void backups.backupNow("scheduled").catch(() => void 0), 3e4);
3351
+ catchUp.unref();
3352
+ timers.push(catchUp);
3353
+ }
3354
+ }
3355
+ void monitor.tick();
3356
+ }
3357
+ return {
3358
+ backups,
3359
+ monitor,
3360
+ start,
3361
+ stop: () => timers.splice(0).forEach(clearTimeout),
3362
+ nextBackupAt,
3363
+ settings: {
3364
+ backupEnabled: config.BACKUP_ENABLED,
3365
+ backupTime: config.BACKUP_TIME,
3366
+ backupKeep: config.BACKUP_KEEP,
3367
+ alertRecipients: config.ALERT_EMAILS.length,
3368
+ includesFiles: Boolean(config.FILES_DIR && existsSync3(config.FILES_DIR))
3369
+ },
3370
+ /** For the Status page: whether backups can be copied elsewhere, and how. */
3371
+ copy: async () => copy && connections ? {
3372
+ available: true,
3373
+ ready: await connections.storageReady(BACKUP_STORAGE),
3374
+ auto: copy.auto(),
3375
+ keep: copy.keep(),
3376
+ encrypted: Boolean(await connections.backupPassphrase()),
3377
+ copying: backups.isCopying()
3378
+ } : { available: false, ready: false, auto: false, keep: 0, encrypted: false, copying: false },
3379
+ disk: () => diskUsage(config.BACKUP_DIR).catch(() => diskUsage("."))
3380
+ };
3381
+ }
3382
+
3383
+ // src/authz/catalog.ts
3384
+ var NAME2 = /^[a-z][a-z_]*:[a-z][a-z_]*$/;
3385
+ var admin = (name2, label) => ({ name: name2, label, adminOnly: true });
3386
+ var frameworkPermissions = [
3387
+ admin("user:read", "View users and invitations"),
3388
+ admin("user:invite", "Invite users"),
3389
+ admin("user:update", "Change roles and renew access"),
3390
+ admin("user:deactivate", "Deactivate and reactivate users"),
3391
+ admin("role:read", "View roles"),
3392
+ admin("role:create", "Create roles"),
3393
+ admin("role:update", "Edit roles"),
3394
+ admin("role:delete", "Delete roles"),
3395
+ { name: "group:read", label: "View groups and their members" },
3396
+ admin("group:create", "Create groups"),
3397
+ admin("group:update", "Rename groups and change their members"),
3398
+ admin("group:delete", "Delete groups"),
3399
+ admin("apikey:read", "View own API keys"),
3400
+ admin("apikey:create", "Create own API keys"),
3401
+ admin("apikey:delete", "Revoke own API keys"),
3402
+ admin("apikey:manage", "View and revoke everyone's API keys"),
3403
+ admin("audit:read", "View the audit log"),
3404
+ admin("status:read", "View system status and backups"),
3405
+ admin("backup:create", "Start a backup"),
3406
+ admin("backup:upload", "Copy a backup to the backup storage"),
3407
+ admin("storage:read", "View the storage connections"),
3408
+ admin("storage:update", "Set up, test and remove storage connections"),
3409
+ admin("llm:read", "View the AI model connections and their usage"),
3410
+ admin("llm:update", "Set up, test and remove AI model connections"),
3411
+ admin("email:read", "View the email connection"),
3412
+ admin("email:update", "Set up, test and remove the email connection"),
3413
+ admin("settings:read", "View the settings"),
3414
+ admin("settings:update", "Change the settings, logo and brand colors")
3415
+ ];
3416
+ var ownKeys = ["apikey:read", "apikey:create", "apikey:delete"];
3417
+ var frameworkRoles = [
3418
+ { key: "owner", label: "Admin", permissions: frameworkPermissions.map((p) => p.name) },
3419
+ { key: "member", label: "Member", permissions: ownKeys },
3420
+ { key: "external", label: "External", permissions: [], external: true }
3421
+ ];
3422
+ function buildCatalog(app = {}) {
3423
+ const permissions = /* @__PURE__ */ new Map();
3424
+ for (const p of [...frameworkPermissions, ...app.permissions ?? []]) {
3425
+ if (!NAME2.test(p.name)) throw new Error(`Invalid permission name "${p.name}" (use resource:action)`);
3426
+ if (permissions.has(p.name)) throw new Error(`Permission "${p.name}" is defined twice`);
3427
+ permissions.set(p.name, p);
3428
+ }
3429
+ const roles = /* @__PURE__ */ new Map();
3430
+ for (const r of [...frameworkRoles, ...app.roles ?? []]) {
3431
+ if (roles.has(r.key)) throw new Error(`Role "${r.key}" is defined twice`);
3432
+ roles.set(r.key, { ...r, permissions: [...r.permissions] });
3433
+ }
3434
+ for (const [key, extra] of Object.entries(app.grants ?? {})) {
3435
+ const role = roles.get(key);
3436
+ if (!role) throw new Error(`Grants refer to unknown role "${key}"`);
3437
+ role.permissions.push(...extra);
3438
+ }
3439
+ for (const r of roles.values()) {
3440
+ r.permissions = [...new Set(r.permissions)];
3441
+ for (const p of r.permissions) {
3442
+ if (!permissions.has(p)) throw new Error(`Role "${r.key}" has unknown permission "${p}"`);
3443
+ }
3444
+ }
3445
+ return { permissions, roles };
3446
+ }
3447
+
3448
+ export {
3449
+ loadConfig,
3450
+ createDb,
3451
+ frameworkMigrationsDir,
3452
+ runMigrations,
3453
+ createLocalFileStorage,
3454
+ AuthzError,
3455
+ createAuthz,
3456
+ consoleEmailSender,
3457
+ smtpSender,
3458
+ createEmailSender,
3459
+ BACKUP_STORAGE,
3460
+ EMAIL_CONNECTION,
3461
+ DEFAULT_STORAGE,
3462
+ ConnectionError,
3463
+ createConnections,
3464
+ sessionMiddleware,
3465
+ publicRoute,
3466
+ requireSession,
3467
+ requirePermission,
3468
+ findUndeclaredRoutes,
3469
+ assertDefaultDeny,
3470
+ getCompanyId,
3471
+ resetCompanyCache,
3472
+ createAuth,
3473
+ createGroups,
3474
+ FRAMEWORK_VERSION,
3475
+ contrastOn,
3476
+ loadBrand,
3477
+ createBrandService,
3478
+ brandRoutes,
3479
+ healthRoutes,
3480
+ createApp,
3481
+ frameworkSettings,
3482
+ createSettings,
3483
+ createOperations,
3484
+ frameworkPermissions,
3485
+ buildCatalog
3486
+ };