Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
419a50b95b | ||
|
|
c4c86fc66b |
@@ -54,7 +54,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
|
||||
### Auth
|
||||
|
||||
- **Guard:** `src/pages/__root.server.ts` on every request. No public pages: anything outside `AdminSections` (`src/dict/admin-sections-dict.ts`) and `/auth` redirects to `/admin/bots`. No users -> `/auth/signup` (first-run super admin only, which then opens the skippable guided setup `/admin/settings/setup`: app name, provider, models, where to go next; it stays under Settings); unauthenticated `/admin/*` -> `/auth/login`; authenticated `/auth/*` (not logout) -> `/admin/bots`; unknown `/admin/settings/*` -> `/admin/settings/general`.
|
||||
- **Guard:** `src/pages/__root.server.ts` on every request. No public pages: anything outside `AdminSections` (`src/dict/admin-sections-dict.ts`) and `/auth` redirects to `/admin/bots`. No users -> `/auth/signup` (first-run super admin only, which then opens the skippable guided setup `/admin/settings/setup`: app name, provider, models, where to go next; it stays under Settings; or Restore from a backup: another install's database file or data archive, told apart by their bytes, through public `api/auth/bootstrap-restore`, refused once any user exists or for a database with no users, restored like Settings > Backups and then the app restarts, the page polling `bootstrap-status` and going to the login); unauthenticated `/admin/*` -> `/auth/login`; authenticated `/auth/*` (not logout) -> `/admin/bots`; unknown `/admin/settings/*` -> `/admin/settings/general`.
|
||||
- **Session:** AES-256-GCM cookie (key from `ENCRYPTION_KEY`/`ENCRYPTION_SALT`) plus CSRF cookie, `Secure` only over HTTPS (`isSecureRequest`, honours `X-Forwarded-Proto`). `userAuth` (`src/functions/backend/auth/user-auth.ts`) checks expiry (60 days), CSRF (constant-time) and re-reads `user_types` every request.
|
||||
- **Login:** email/username + password (`api/auth/password-login.ts`, rate limited). No emailed codes or resets. Google login only for existing accounts, when `GOOGLE_CLIENT_ID` is set. Sessions issued by `login-user.ts`.
|
||||
- **Passwords:** bcrypt in `user_passwords` (never in `users`; blocked from CRUD via `src/dict/private-tables.ts`).
|
||||
@@ -242,7 +242,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **Rail pages** (`src/dict/rail-pages-dict.ts`): Routines, Files, Usage (crew managers), Activity (`/admin/logs`, super admin), Help (`(data)/help-topics.ts`). Visibility via `canSeeRailItem` for both the popover and the aside.
|
||||
- **Settings** (`src/dict/settings-pages-dict.ts`; add a sub page = folder + dict entry): `general` (theme per device, plus super-admin app settings: prompt append, run limits, skill limits; crew-manager storage quota; running version), `setup` (super admin; shares the Models page's server props and `useModelsOverview`), `profile`, `notifications`, `change-password`, `secrets`, `browsers`, `models`, `environment`, `backups` and `database` (super admin), `bots`, `workspaces`, `computers`, `mcps`, `tools`, `skills`, `knowledgebases` (crew managers), `users` (`canListUsers`).
|
||||
- Settings pages use `SettingsShell` (breadcrumbs via `admin-breadcrumbs.tsx`), `SettingsGroup` blocks (no cards) and the sticky `SettingsSaveBar`. Saves don't reload. Keep save notices in component state (`useFormInit` clears `status` on change). Lists share `SettingsList`/`SettingsListRow`/`SettingsRowAction`. Row actions are icon-only (`RowIconButton`).
|
||||
- **Backups:** DB snapshots (synchronous) and whole-data archives of `DATA_DIR` into `BACKUP_ARCHIVE_DIR`. Archives and restores outlast a request, so the route only starts the run (`startDataBackupRun`, which holds `with-backup-run-lock.ts`) and the page polls `data-status`. A restore takes a safety archive first, then restarts the process.
|
||||
- **Backups:** DB snapshots (synchronous) and whole-data archives of `DATA_DIR` into `BACKUP_ARCHIVE_DIR`. Archives and restores outlast a request, so the route only starts the run (`startDataBackupRun`, which holds `with-backup-run-lock.ts`) and the page polls `data-status`. A restore takes a safety archive first, then restarts the process. **A database snapshot restore restarts too** (also a background run, `db_restore`): `bun-sqlite import` swaps in a new file from another process, and this process's handle would stay on the old one, so nothing may be written to the database between a restore and the restart (log entries go through `queueBootLog`, written by `flushBootLogs` at boot).
|
||||
- **Database browser:** strictly read-only; values cut in SQL; state in the address via `databaseHref`.
|
||||
- Add flow (`(partials)/add-flow.tsx`) from the rail's Add icon: bot, workspace, computer (super admin). Page heroes use `AdminHero`.
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.16.3",
|
||||
"version": "0.17.0",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
+3
-2
@@ -42,8 +42,9 @@ type Props = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Picks one file and sends it for a restore: shared by the database upload
|
||||
* and the data archive upload, which differ only in what they accept.
|
||||
* Picks one file and sends it for a restore: shared by the database upload,
|
||||
* the data archive upload and the restore at first-run setup, which differ
|
||||
* only in what they accept.
|
||||
*/
|
||||
export default function UploadRestoreFields({
|
||||
label,
|
||||
@@ -960,6 +960,12 @@ export const AppData = {
|
||||
*/
|
||||
DataBackupNamePrefix: "cobble-data-",
|
||||
DataBackupsKept: 5,
|
||||
/**
|
||||
* Log entries a restore leaves in `DATA_DIR` for the next boot to
|
||||
* write (`queueBootLog`): written before the restart they would land
|
||||
* in the replaced database, which the process still has open.
|
||||
*/
|
||||
PendingBootLogsFile: ".pending-boot-logs.json",
|
||||
/**
|
||||
* How often the backups page asks how a whole-data archive or restore
|
||||
* is going, and how long it waits for the app to come back after a
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { afterAll, describe, expect, test } from "bun:test";
|
||||
import { Database } from "bun:sqlite";
|
||||
import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import assertDbHasUsers from "./assert-db-has-users";
|
||||
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-bootstrap-db-"));
|
||||
|
||||
type Params = {
|
||||
name: string;
|
||||
sql: string;
|
||||
};
|
||||
|
||||
function makeDb({ name, sql }: Params) {
|
||||
const db_path = path.join(dir, name);
|
||||
const db = new Database(db_path, { create: true });
|
||||
db.run(sql);
|
||||
db.close();
|
||||
return db_path;
|
||||
}
|
||||
|
||||
afterAll(() => {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("assertDbHasUsers", () => {
|
||||
test("passes a database with an account", () => {
|
||||
const db_path = makeDb({
|
||||
name: "with-user.db",
|
||||
sql: `CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT); INSERT INTO users (email) VALUES ('[email protected]');`,
|
||||
});
|
||||
|
||||
expect(() => assertDbHasUsers({ db_path })).not.toThrow();
|
||||
});
|
||||
|
||||
test("refuses a database with no accounts", () => {
|
||||
const db_path = makeDb({
|
||||
name: "empty-users.db",
|
||||
sql: `CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);`,
|
||||
});
|
||||
|
||||
expect(() => assertDbHasUsers({ db_path })).toThrow(/no accounts/);
|
||||
});
|
||||
|
||||
test("refuses a database without a users table", () => {
|
||||
const db_path = makeDb({
|
||||
name: "other.db",
|
||||
sql: `CREATE TABLE notes (id INTEGER PRIMARY KEY);`,
|
||||
});
|
||||
|
||||
expect(() => assertDbHasUsers({ db_path })).toThrow(/no users table/);
|
||||
});
|
||||
|
||||
test("leaves the file unchanged", () => {
|
||||
const db_path = makeDb({
|
||||
name: "unchanged.db",
|
||||
sql: `CREATE TABLE users (id INTEGER PRIMARY KEY); INSERT INTO users DEFAULT VALUES;`,
|
||||
});
|
||||
const before = fs.readFileSync(db_path);
|
||||
|
||||
assertDbHasUsers({ db_path });
|
||||
|
||||
expect(fs.readFileSync(db_path).equals(before)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import { SiteData } from "@/src/data/site-data";
|
||||
|
||||
type Params = {
|
||||
db_path: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Refuses a database file that holds no accounts: restoring it would
|
||||
* only send the install back to first-run setup. Opened read-only, so
|
||||
* the file is never changed by the look.
|
||||
*/
|
||||
export default function assertDbHasUsers({ db_path }: Params) {
|
||||
let db: Database | undefined;
|
||||
|
||||
try {
|
||||
db = new Database(db_path, { readonly: true });
|
||||
|
||||
const row = db
|
||||
.query<{ id: number }, []>(`SELECT id FROM users LIMIT 1`)
|
||||
.get();
|
||||
|
||||
if (!row?.id) {
|
||||
throw new AppError(
|
||||
`That database has no accounts, so there is nothing to sign in with`,
|
||||
);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof AppError) throw error;
|
||||
|
||||
throw new AppError(
|
||||
`That file isn't a ${SiteData["SiteName"]} database (it has no users table)`,
|
||||
);
|
||||
} finally {
|
||||
db?.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import grabDirNames from "@/src/utils/grab-dir-names";
|
||||
import logEvent, { type LogEventParams } from "@/src/functions/backend/logger";
|
||||
|
||||
/**
|
||||
* Writes the log entries a restore queued before the restart
|
||||
* (`queueBootLog`) into the database the app came back up on, once. The
|
||||
* file is moved aside first, so a second process starting at the same
|
||||
* time never writes them twice.
|
||||
*/
|
||||
export default async function flushBootLogs() {
|
||||
const { DATA_DIR } = grabDirNames();
|
||||
const file_path = path.join(DATA_DIR, AppData.PendingBootLogsFile);
|
||||
const claimed_path = `${file_path}.${process.pid}`;
|
||||
|
||||
try {
|
||||
fs.renameSync(file_path, claimed_path);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(claimed_path, "utf-8"));
|
||||
const entries: LogEventParams[] = Array.isArray(parsed) ? parsed : [];
|
||||
|
||||
for (const entry of entries) {
|
||||
await logEvent(entry);
|
||||
}
|
||||
} catch {
|
||||
// A broken file is dropped: these are only log entries.
|
||||
} finally {
|
||||
fs.rmSync(claimed_path, { force: true });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
||||
import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import queueBootLog from "./queue-boot-log";
|
||||
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-boot-log-"));
|
||||
const previous = process.env.DATA_DIR;
|
||||
const file_path = path.join(dir, AppData.PendingBootLogsFile);
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.DATA_DIR = dir;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
if (previous === undefined) delete process.env.DATA_DIR;
|
||||
else process.env.DATA_DIR = previous;
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("queueBootLog", () => {
|
||||
test("keeps entries in order across calls", () => {
|
||||
queueBootLog({
|
||||
entry: { title: "One", category: "system", plain_text: "first" },
|
||||
});
|
||||
queueBootLog({
|
||||
entry: { title: "Two", category: "system", plain_text: "second" },
|
||||
});
|
||||
|
||||
const entries = JSON.parse(fs.readFileSync(file_path, "utf-8"));
|
||||
|
||||
expect(entries.map((entry: { title: string }) => entry.title)).toEqual([
|
||||
"One",
|
||||
"Two",
|
||||
]);
|
||||
});
|
||||
|
||||
test("starts over from a broken file", () => {
|
||||
fs.writeFileSync(file_path, "{not json");
|
||||
|
||||
queueBootLog({
|
||||
entry: { title: "Three", category: "system", plain_text: "third" },
|
||||
});
|
||||
|
||||
const entries = JSON.parse(fs.readFileSync(file_path, "utf-8"));
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0].title).toBe("Three");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import grabDirNames from "@/src/utils/grab-dir-names";
|
||||
import type { LogEventParams } from "@/src/functions/backend/logger";
|
||||
|
||||
type Params = {
|
||||
entry: LogEventParams;
|
||||
};
|
||||
|
||||
/**
|
||||
* Keeps a log entry for the next boot to write (`flushBootLogs`). For
|
||||
* what happens right before the app restarts onto a replaced database:
|
||||
* the process still has the old file open, so a `logEvent` now would
|
||||
* land in a file nothing reads again. Call it after the data is in place
|
||||
* (a whole-data restore empties `DATA_DIR` first).
|
||||
*/
|
||||
export default function queueBootLog({ entry }: Params) {
|
||||
const { DATA_DIR } = grabDirNames();
|
||||
const file_path = path.join(DATA_DIR, AppData.PendingBootLogsFile);
|
||||
|
||||
let entries: LogEventParams[] = [];
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(file_path, "utf-8"));
|
||||
if (Array.isArray(parsed)) entries = parsed;
|
||||
} catch {
|
||||
// Nothing queued yet, or a broken file: start over.
|
||||
}
|
||||
|
||||
fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
fs.writeFileSync(file_path, JSON.stringify([...entries, entry]));
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import restoreDbBackup from "./restore-db-backup";
|
||||
import restoreDataBackup from "./restore-data-backup";
|
||||
import restartApp from "./restart-app";
|
||||
import queueBootLog from "./queue-boot-log";
|
||||
import type { BootstrapUpload } from "./save-bootstrap-upload";
|
||||
import type { LogEventParams } from "@/src/functions/backend/logger";
|
||||
|
||||
type Params = {
|
||||
upload: BootstrapUpload;
|
||||
/**
|
||||
* What the restored install's log should say about it, written once
|
||||
* the app is back up.
|
||||
*/
|
||||
log_entry: LogEventParams;
|
||||
};
|
||||
|
||||
/**
|
||||
* Puts a saved bootstrap upload in place, then restarts the app: a
|
||||
* database file replaces the database (`bun-sqlite import`, as Settings >
|
||||
* Backups does), a data archive replaces the whole data volume. Either
|
||||
* way the open SQLite handle still points at the old file, so the process
|
||||
* comes back up on the new one (and the entrypoint brings an older
|
||||
* database's schema up to date).
|
||||
*
|
||||
* Runs only inside `startDataBackupRun`, which holds the backup run lock.
|
||||
* Resolves to the name restored.
|
||||
*/
|
||||
export default async function restoreBootstrapUpload({
|
||||
upload,
|
||||
log_entry,
|
||||
}: Params) {
|
||||
if (upload.kind == "database") {
|
||||
await restoreDbBackup({ backup_name: upload.backup_name });
|
||||
} else {
|
||||
await restoreDataBackup({ backup_name: upload.backup_name });
|
||||
}
|
||||
|
||||
queueBootLog({ entry: log_entry });
|
||||
restartApp();
|
||||
|
||||
return upload.backup_name;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import resolveDbBackupPath from "./resolve-db-backup-path";
|
||||
import runBunSQLiteCommand from "./run-bun-sqlite-command";
|
||||
import spawnBunSQLiteCommand from "./spawn-bun-sqlite-command";
|
||||
|
||||
type Params = {
|
||||
backup_name?: string;
|
||||
@@ -8,10 +8,19 @@ type Params = {
|
||||
/**
|
||||
* Restores a database snapshot from the backups directory. `bun-sqlite
|
||||
* restore` is an interactive picker, so this uses its non-interactive
|
||||
* equivalent, `bun-sqlite import <file>`.
|
||||
* equivalent, `bun-sqlite import <file>`, which snapshots the current
|
||||
* database first.
|
||||
*
|
||||
* The import runs in its own process and swaps in a new file, so this
|
||||
* process's open SQLite handle still points at the old one: the caller
|
||||
* restarts the app afterwards (`restartApp`), and nothing may be written
|
||||
* in between (a log entry goes through `queueBootLog`).
|
||||
*
|
||||
* Runs only inside `startDataBackupRun`, which holds the backup run lock
|
||||
* for it.
|
||||
*/
|
||||
export default async function restoreDbBackup({ backup_name }: Params) {
|
||||
const backup_path = resolveDbBackupPath({ backup_name });
|
||||
|
||||
return await runBunSQLiteCommand({ args: ["import", backup_path] });
|
||||
return await spawnBunSQLiteCommand({ args: ["import", backup_path] });
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import withBackupRunLock from "./with-backup-run-lock";
|
||||
import spawnBunSQLiteCommand from "./spawn-bun-sqlite-command";
|
||||
|
||||
type Params = {
|
||||
args: string[];
|
||||
@@ -11,33 +12,6 @@ type Params = {
|
||||
*/
|
||||
export default async function runBunSQLiteCommand({ args }: Params) {
|
||||
return await withBackupRunLock({
|
||||
task: async () => {
|
||||
const proc = Bun.spawn(
|
||||
[process.execPath, "x", "bun-sqlite", ...args],
|
||||
{
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
stdin: "ignore",
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
},
|
||||
);
|
||||
|
||||
const [stdout, stderr, exit_code] = await Promise.all([
|
||||
new Response(proc.stdout).text(),
|
||||
new Response(proc.stderr).text(),
|
||||
proc.exited,
|
||||
]);
|
||||
|
||||
if (exit_code !== 0) {
|
||||
throw new Error(
|
||||
stderr.trim() ||
|
||||
stdout.trim() ||
|
||||
`bun-sqlite ${args[0]} failed (exit ${exit_code})`,
|
||||
);
|
||||
}
|
||||
|
||||
return { stdout };
|
||||
},
|
||||
task: () => spawnBunSQLiteCommand({ args }),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import path from "path";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import grabDbBackupDir from "./grab-db-backup-dir";
|
||||
import saveUploadedDbBackup from "./save-uploaded-db-backup";
|
||||
import saveUploadedDataBackup from "./save-uploaded-data-backup";
|
||||
import assertDbHasUsers from "./assert-db-has-users";
|
||||
import deleteDbBackup from "./delete-db-backup";
|
||||
|
||||
type Params = {
|
||||
file: File;
|
||||
};
|
||||
|
||||
export type BootstrapUploadKind = "database" | "archive";
|
||||
|
||||
export type BootstrapUpload = {
|
||||
kind: BootstrapUploadKind;
|
||||
/**
|
||||
* The name it was saved under: a database snapshot, or a data
|
||||
* archive.
|
||||
*/
|
||||
backup_name: string;
|
||||
};
|
||||
|
||||
const SQLITE_HEADER = "SQLite format 3\0";
|
||||
|
||||
/**
|
||||
* Saves the file a new install is bootstrapped from, telling the two
|
||||
* kinds apart by their first bytes rather than the file name: a SQLite
|
||||
* database (a snapshot downloaded from Settings > Backups) goes to the
|
||||
* database snapshots, a gzip (a whole-data archive) to the archives. A
|
||||
* database with no accounts is refused and removed again. Anything else
|
||||
* is refused before it's written.
|
||||
*/
|
||||
export default async function saveBootstrapUpload({
|
||||
file,
|
||||
}: Params): Promise<BootstrapUpload> {
|
||||
if (!file.size) {
|
||||
throw new AppError(`The uploaded file is empty`);
|
||||
}
|
||||
|
||||
const head = await file.slice(0, SQLITE_HEADER.length).text();
|
||||
|
||||
if (head === SQLITE_HEADER) {
|
||||
const backup_name = await saveUploadedDbBackup({ file });
|
||||
|
||||
try {
|
||||
assertDbHasUsers({
|
||||
db_path: path.join(grabDbBackupDir(), backup_name),
|
||||
});
|
||||
} catch (error) {
|
||||
deleteDbBackup({ backup_name });
|
||||
throw error;
|
||||
}
|
||||
|
||||
return { kind: "database", backup_name };
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(await file.slice(0, 2).arrayBuffer());
|
||||
|
||||
if (bytes[0] == 0x1f && bytes[1] == 0x8b) {
|
||||
return {
|
||||
kind: "archive",
|
||||
backup_name: await saveUploadedDataBackup({ file }),
|
||||
};
|
||||
}
|
||||
|
||||
throw new AppError(
|
||||
`Only a SQLite database file or a whole-data .tar.gz archive can be restored`,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
type Params = {
|
||||
args: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Runs a `bun-sqlite` CLI command (same as `bunx bun-sqlite ...`) without
|
||||
* taking the backup run lock: only for a caller that already holds it
|
||||
* (a task inside `startDataBackupRun`). Everyone else goes through
|
||||
* `runBunSQLiteCommand`.
|
||||
*/
|
||||
export default async function spawnBunSQLiteCommand({ args }: Params) {
|
||||
const proc = Bun.spawn([process.execPath, "x", "bun-sqlite", ...args], {
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
stdin: "ignore",
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
});
|
||||
|
||||
const [stdout, stderr, exit_code] = await Promise.all([
|
||||
new Response(proc.stdout).text(),
|
||||
new Response(proc.stderr).text(),
|
||||
proc.exited,
|
||||
]);
|
||||
|
||||
if (exit_code !== 0) {
|
||||
throw new Error(
|
||||
stderr.trim() ||
|
||||
stdout.trim() ||
|
||||
`bun-sqlite ${args[0]} failed (exit ${exit_code})`,
|
||||
);
|
||||
}
|
||||
|
||||
return { stdout };
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from "react";
|
||||
import type { DataBackupRun } from "@/src/types";
|
||||
import type { DataBackupRun, DataBackupRunKind } from "@/src/types";
|
||||
|
||||
export type DataBackupRunState = {
|
||||
/**
|
||||
@@ -10,6 +10,11 @@ export type DataBackupRunState = {
|
||||
* Why the last run failed.
|
||||
*/
|
||||
error?: string;
|
||||
/**
|
||||
* What the run that failed was doing, so its section shows why
|
||||
* (none for a run that couldn't start).
|
||||
*/
|
||||
error_kind?: DataBackupRunKind;
|
||||
/**
|
||||
* Follows a run a request just started until it ends.
|
||||
*/
|
||||
@@ -21,9 +26,9 @@ export type DataBackupRunState = {
|
||||
};
|
||||
|
||||
/**
|
||||
* The whole-data run the backups page is waiting on, shared by the list's
|
||||
* actions, every archive row and the upload modal, so none of them starts
|
||||
* another while one is going.
|
||||
* The background run the backups page is waiting on (an archive, or a
|
||||
* restore of either kind), shared by both lists' actions, every row and
|
||||
* the upload modals, so none of them starts another while one is going.
|
||||
*/
|
||||
export const DataBackupRunContext = React.createContext<DataBackupRunState>({
|
||||
track: () => {},
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import adminFetchHandler from "@/src/functions/frontend/admin-fetch-handler";
|
||||
import type { DbBackup } from "@/src/types";
|
||||
import type { DataBackupRun, DbBackup } from "@/src/types";
|
||||
import dayjs from "dayjs";
|
||||
|
||||
type Params = {
|
||||
backup: DbBackup;
|
||||
};
|
||||
|
||||
/**
|
||||
* Starts restoring a snapshot. The server restores it in the background
|
||||
* and restarts, so this hands back the run for the page to follow.
|
||||
*/
|
||||
export default async function restoreBackup({ backup }: Params) {
|
||||
const confirm_msg = `Restore the database from the backup of ${dayjs(backup.created_at).format("MMM D, YYYY HH:mm:ss")}?\n\nAll current data will be replaced with the data in this backup. This cannot be undone. Consider creating a fresh backup first.`;
|
||||
const confirm_msg = `Restore the database from the backup of ${dayjs(backup.created_at).format("MMM D, YYYY HH:mm:ss")}?\n\nAll current data will be replaced with the data in this backup, and the app restarts. A snapshot of the current database is taken first.`;
|
||||
|
||||
if (!window.confirm(confirm_msg)) {
|
||||
return { success: false, cancelled: true };
|
||||
@@ -24,5 +28,6 @@ export default async function restoreBackup({ backup }: Params) {
|
||||
return {
|
||||
success: Boolean(res.success),
|
||||
msg: res.success ? undefined : res.msg || `Couldn't restore backup`,
|
||||
run: res.success ? (res.singleRes as DataBackupRun | undefined) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { DataBackupRun } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
file: File;
|
||||
};
|
||||
@@ -5,10 +7,11 @@ type Params = {
|
||||
/**
|
||||
* Sends the file as multipart form data (not base64 JSON) so large dumps
|
||||
* aren't inflated. The server saves it into the snapshots list, then
|
||||
* restores it.
|
||||
* restores it in the background and restarts, so this hands back the run
|
||||
* for the page to follow.
|
||||
*/
|
||||
export default async function uploadRestoreBackup({ file }: Params) {
|
||||
const confirm_msg = `Restore the database from "${file.name}"?\n\nAll current data will be replaced with the data in this file. This cannot be undone. Consider creating a fresh backup first.`;
|
||||
const confirm_msg = `Restore the database from "${file.name}"?\n\nAll current data will be replaced with the data in this file, and the app restarts. A snapshot of the current database is taken first.`;
|
||||
|
||||
if (!window.confirm(confirm_msg)) {
|
||||
return { success: false, cancelled: true };
|
||||
@@ -28,6 +31,7 @@ export default async function uploadRestoreBackup({ file }: Params) {
|
||||
return {
|
||||
success: Boolean(json.success),
|
||||
msg: json.success ? undefined : json.msg || `Couldn't restore backup`,
|
||||
run: json.success ? (json.singleRes as DataBackupRun | undefined) : undefined,
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
|
||||
@@ -2,12 +2,12 @@ import { useContext, useEffect, useState } from "react";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import adminFetchHandler from "@/src/functions/frontend/admin-fetch-handler";
|
||||
import type { DataBackupRun, DataBackupStatus } from "@/src/types";
|
||||
import type { DataBackupRun, DataBackupRunKind, DataBackupStatus } from "@/src/types";
|
||||
import type { DataBackupRunState } from "../(data)/data-backup-run-context";
|
||||
|
||||
/**
|
||||
* Follows a whole-data archive or restore, which runs in the background
|
||||
* on the server, by polling `data-status` every `AppData.DataBackupPollMs`.
|
||||
* Follows a whole-data archive or restore, or a database snapshot
|
||||
* restore, which run in the background on the server, by polling `data-status` every `AppData.DataBackupPollMs`.
|
||||
* An archive reloads the page once it is written. A restore restarts the
|
||||
* app, so failed polls are expected and the page reloads once the status
|
||||
* comes from a new boot (or after `AppData.DataRestoreWaitMs` anyway).
|
||||
@@ -20,6 +20,7 @@ export default function useDataBackupRun(): DataBackupRunState {
|
||||
initial?.status == "running" ? initial : undefined,
|
||||
);
|
||||
const [error, setError] = useState<string>();
|
||||
const [error_kind, setErrorKind] = useState<DataBackupRunKind>();
|
||||
|
||||
useEffect(() => {
|
||||
if (run?.status != "running") return;
|
||||
@@ -32,6 +33,7 @@ export default function useDataBackupRun(): DataBackupRunState {
|
||||
|
||||
const fail = (msg: string) => {
|
||||
setError(msg);
|
||||
setErrorKind(active.kind);
|
||||
setRun(undefined);
|
||||
};
|
||||
|
||||
@@ -49,14 +51,19 @@ export default function useDataBackupRun(): DataBackupRunState {
|
||||
current && current.boot_id != active.boot_id,
|
||||
);
|
||||
|
||||
if (active.kind == "restore") {
|
||||
if (active.kind != "archive") {
|
||||
if (restarted || Date.now() > deadline) {
|
||||
window.location.reload();
|
||||
return;
|
||||
}
|
||||
|
||||
if (current?.status == "failed") {
|
||||
fail(current.error || `Couldn't restore archive`);
|
||||
fail(
|
||||
current.error ||
|
||||
(active.kind == "db_restore"
|
||||
? `Couldn't restore the database`
|
||||
: `Couldn't restore archive`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
} else if (current) {
|
||||
@@ -90,10 +97,15 @@ export default function useDataBackupRun(): DataBackupRunState {
|
||||
return {
|
||||
run,
|
||||
error,
|
||||
error_kind,
|
||||
track: (next) => {
|
||||
setError(undefined);
|
||||
setErrorKind(undefined);
|
||||
setRun(next);
|
||||
},
|
||||
report: setError,
|
||||
report: (next) => {
|
||||
setError(next);
|
||||
setErrorKind(undefined);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -5,7 +5,8 @@ import Row from "@moduletrace/twui/layout/Row";
|
||||
import useStatus from "@moduletrace/twui/hooks/useStatus";
|
||||
import createBackup from "../(functions)/create-backup";
|
||||
import UploadRestoreModal from "../(partials)/upload-restore-modal";
|
||||
import { useState } from "react";
|
||||
import { useContext, useState } from "react";
|
||||
import { DataBackupRunContext } from "../(data)/data-backup-run-context";
|
||||
|
||||
/**
|
||||
* The database snapshot list's two ways in: make a fresh snapshot, or
|
||||
@@ -14,6 +15,7 @@ import { useState } from "react";
|
||||
export default function BackupListActions() {
|
||||
const { loading, setLoading, status, setStatus } = useStatus();
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const { run } = useContext(DataBackupRunContext);
|
||||
|
||||
const create_backup = async () => {
|
||||
setStatus(undefined);
|
||||
@@ -41,6 +43,7 @@ export default function BackupListActions() {
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
beforeIcon={<Upload />}
|
||||
disabled={Boolean(run)}
|
||||
onClick={() => {
|
||||
setUploading(true);
|
||||
}}
|
||||
@@ -51,6 +54,7 @@ export default function BackupListActions() {
|
||||
title="Create Backup"
|
||||
beforeIcon={<DatabaseBackup />}
|
||||
loading={loading}
|
||||
disabled={Boolean(run)}
|
||||
onClick={() => {
|
||||
create_backup();
|
||||
}}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { PropsWithChildren } from "react";
|
||||
import { DataBackupRunContext } from "../(data)/data-backup-run-context";
|
||||
import useDataBackupRun from "../(hooks)/use-data-backup-run";
|
||||
|
||||
/**
|
||||
* Follows the background run going on the server (`useDataBackupRun`)
|
||||
* for the whole page, so both lists see it and neither starts another.
|
||||
*/
|
||||
export default function BackupRunProvider({ children }: PropsWithChildren) {
|
||||
const data_backup_run = useDataBackupRun();
|
||||
|
||||
return (
|
||||
<DataBackupRunContext.Provider value={data_backup_run}>
|
||||
{children}
|
||||
</DataBackupRunContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,24 +1,36 @@
|
||||
import { useContext } from "react";
|
||||
import Tag from "@moduletrace/twui/elements/Tag";
|
||||
import { DataBackupRunContext } from "../(data)/data-backup-run-context";
|
||||
import type { DataBackupRunKind } from "@/src/types";
|
||||
|
||||
type Props = {
|
||||
/**
|
||||
* True under the database snapshots, which show only a snapshot
|
||||
* restore; the data archives show the rest.
|
||||
*/
|
||||
database?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* One line under the data archives' actions: the archive or restore
|
||||
* running now, else why the last one failed. Nothing when neither, so the
|
||||
* actions row keeps its layout either way.
|
||||
* One line under a list's actions: the run of its own kind going now,
|
||||
* else why the last one failed. Nothing when neither, so the actions row
|
||||
* keeps its layout either way.
|
||||
*/
|
||||
export default function DataBackupRunNotice() {
|
||||
const { run, error } = useContext(DataBackupRunContext);
|
||||
export default function DataBackupRunNotice({ database }: Props) {
|
||||
const { run, error, error_kind } = useContext(DataBackupRunContext);
|
||||
|
||||
if (run?.kind == "archive") {
|
||||
return <Tag color="gray">Archiving, this can take a while...</Tag>;
|
||||
}
|
||||
const isMine = (kind?: DataBackupRunKind) =>
|
||||
database ? kind == "db_restore" : kind != "db_restore";
|
||||
|
||||
if (run && isMine(run.kind)) {
|
||||
if (run.kind == "archive") {
|
||||
return <Tag color="gray">Archiving, this can take a while...</Tag>;
|
||||
}
|
||||
|
||||
if (run?.kind == "restore") {
|
||||
return <Tag color="warning">Restoring, the app restarts soon...</Tag>;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
if (error && isMine(error_kind)) {
|
||||
return <Tag color="error">{error}</Tag>;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,11 +2,13 @@ import Button from "@moduletrace/twui/layout/Button";
|
||||
import Tag from "@moduletrace/twui/elements/Tag";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import useStatus from "@moduletrace/twui/hooks/useStatus";
|
||||
import type { DbBackup } from "@/src/types";
|
||||
import type { DataBackupRun, DbBackup } from "@/src/types";
|
||||
import restoreBackup from "../(functions)/restore-backup";
|
||||
import deleteDbBackup from "../(functions)/delete-db-backup";
|
||||
import RowIconButton from "@/src/components/general/row-icon-button";
|
||||
import { ArchiveRestore, Download, Trash2 } from "lucide-react";
|
||||
import { useContext } from "react";
|
||||
import { DataBackupRunContext } from "../(data)/data-backup-run-context";
|
||||
|
||||
type Props = {
|
||||
backup: DbBackup;
|
||||
@@ -14,17 +16,28 @@ type Props = {
|
||||
|
||||
/**
|
||||
* One database snapshot's icon actions: restore, download or delete, with
|
||||
* their own one-line status.
|
||||
* their own one-line status. A restore runs in the background and restarts
|
||||
* the app, so its run goes to the page to follow.
|
||||
*/
|
||||
export default function DbBackupRowActions({ backup }: Props) {
|
||||
const { loading, setLoading, status, setStatus } = useStatus();
|
||||
const { run: running, track } = useContext(DataBackupRunContext);
|
||||
const busy = loading || Boolean(running);
|
||||
|
||||
const run = async (task: () => Promise<{ success: boolean; msg?: string }>) => {
|
||||
const run = async (
|
||||
task: () => Promise<{ success: boolean; msg?: string; run?: DataBackupRun }>,
|
||||
) => {
|
||||
setStatus(undefined);
|
||||
setLoading(true);
|
||||
|
||||
const res = await task();
|
||||
|
||||
if (res.success && res.run) {
|
||||
setLoading(false);
|
||||
track(res.run);
|
||||
return;
|
||||
}
|
||||
|
||||
if (res.success) {
|
||||
window.location.reload();
|
||||
return;
|
||||
@@ -43,7 +56,7 @@ export default function DbBackupRowActions({ backup }: Props) {
|
||||
<RowIconButton
|
||||
icon={ArchiveRestore}
|
||||
title="Restore this snapshot"
|
||||
disabled={loading}
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
run(() => restoreBackup({ backup }));
|
||||
}}
|
||||
@@ -64,7 +77,7 @@ export default function DbBackupRowActions({ backup }: Props) {
|
||||
<RowIconButton
|
||||
icon={Trash2}
|
||||
title="Delete this snapshot"
|
||||
disabled={loading}
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
run(() => deleteDbBackup({ backup }));
|
||||
}}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
|
||||
import UploadRestoreFields from "./upload-restore-fields";
|
||||
import UploadRestoreFields from "@/src/components/general/upload-restore-fields";
|
||||
import uploadRestoreBackup from "../(functions)/upload-restore-backup";
|
||||
import uploadRestoreDataBackup from "../(functions)/upload-restore-data-backup";
|
||||
import { DataBackupRunContext } from "../(data)/data-backup-run-context";
|
||||
@@ -10,22 +10,23 @@ type Props = {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
/**
|
||||
* True for an upload listing a data archive, which restarts the app.
|
||||
* True for a data archive upload, false for a database file.
|
||||
*/
|
||||
is_data?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Uploading a file and restoring it, in a modal over the list it came
|
||||
* from. A database file is restored in place; a data archive replaces the
|
||||
* whole data volume in the background, so the modal closes and the
|
||||
* section follows the run until the app is back from its restart.
|
||||
* from. Either restore runs in the background (a database file replaces
|
||||
* the database, a data archive the whole data volume), so the modal
|
||||
* closes and the page follows the run until the app is back from its
|
||||
* restart.
|
||||
*/
|
||||
export default function UploadRestoreModal({ open, onClose, is_data }: Props) {
|
||||
const { track } = useContext(DataBackupRunContext);
|
||||
|
||||
const done = ({ run }: { run?: DataBackupRun }) => {
|
||||
if (!is_data || !run) {
|
||||
if (!run) {
|
||||
window.location.reload();
|
||||
return;
|
||||
}
|
||||
@@ -42,7 +43,7 @@ export default function UploadRestoreModal({ open, onClose, is_data }: Props) {
|
||||
description={
|
||||
is_data
|
||||
? "Upload a whole-data tar.gz archive. It replaces every folder and the database snapshots, a safety archive is made first, and the app restarts."
|
||||
: "Upload a SQLite database file. It is saved to the snapshots list, then restored."
|
||||
: "Upload a SQLite database file. It is saved to the snapshots list, then restored, and the app restarts."
|
||||
}
|
||||
>
|
||||
{open ? (
|
||||
|
||||
@@ -5,10 +5,13 @@ import SettingsGroup from "../../(partials)/settings-group";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import BackupListActions from "../(partials)/backup-list-actions";
|
||||
import BackupsTable from "../(partials)/backups-table";
|
||||
import DataBackupRunNotice from "../(partials)/data-backup-run-notice";
|
||||
|
||||
/**
|
||||
* The database snapshots, newest first. Each row restores, downloads or
|
||||
* deletes, and a fresh one can be made or uploaded. These are the
|
||||
* deletes, and a fresh one can be made or uploaded. A restore runs in the
|
||||
* background and restarts the app, followed by the page's
|
||||
* `BackupRunProvider`. These are the
|
||||
* bun-sqlite snapshots in `db/.backups`, not the whole-data archives.
|
||||
*/
|
||||
export default function BackupsListSection() {
|
||||
@@ -26,6 +29,7 @@ export default function BackupsListSection() {
|
||||
</Span>
|
||||
<BackupListActions />
|
||||
</Row>
|
||||
<DataBackupRunNotice database />
|
||||
{backups[0] ? (
|
||||
<BackupsTable backups={backups} />
|
||||
) : (
|
||||
|
||||
@@ -6,43 +6,38 @@ import { AppContext } from "@/src/pages/__root";
|
||||
import DataBackupListActions from "../(partials)/data-backup-list-actions";
|
||||
import DataBackupRunNotice from "../(partials)/data-backup-run-notice";
|
||||
import DataBackupsTable from "../(partials)/data-backups-table";
|
||||
import { DataBackupRunContext } from "../(data)/data-backup-run-context";
|
||||
import useDataBackupRun from "../(hooks)/use-data-backup-run";
|
||||
|
||||
/**
|
||||
* The tar.gz archives of the whole data volume, newest first. Each one
|
||||
* restores (replacing every folder and the database snapshots with the
|
||||
* archive's own, then the app restarts), downloads or deletes; the newest
|
||||
* `AppData.DataBackupsKept` are kept and older ones pruned. Archives and
|
||||
* restores run in the background on the server; the section follows the
|
||||
* one running (`useDataBackupRun`) for every control in it.
|
||||
* restores run in the background on the server; the page follows the one
|
||||
* running (`BackupRunProvider`) for every control on it.
|
||||
*/
|
||||
export default function DataBackupsSection() {
|
||||
const { pageProps } = useContext(AppContext);
|
||||
const backups = pageProps?.data_backups || [];
|
||||
const data_backup_run = useDataBackupRun();
|
||||
|
||||
return (
|
||||
<DataBackupRunContext.Provider value={data_backup_run}>
|
||||
<SettingsGroup
|
||||
title="Data archives"
|
||||
description="One tar.gz of the whole data volume, under a single folder named after the archive: the database, media, computer homes, every bot and workspace file, and the database snapshots. They live outside the data volume, and the newest few are kept."
|
||||
>
|
||||
<Row className="w-full items-center justify-between gap-2! flex-wrap">
|
||||
<Span size="small" variant="faded">
|
||||
{`${backups.length} archive${backups.length == 1 ? "" : "s"}`}
|
||||
</Span>
|
||||
<DataBackupListActions />
|
||||
</Row>
|
||||
<DataBackupRunNotice />
|
||||
{backups[0] ? (
|
||||
<DataBackupsTable backups={backups} />
|
||||
) : (
|
||||
<Span size="small" variant="faded">
|
||||
No archives yet.
|
||||
</Span>
|
||||
)}
|
||||
</SettingsGroup>
|
||||
</DataBackupRunContext.Provider>
|
||||
<SettingsGroup
|
||||
title="Data archives"
|
||||
description="One tar.gz of the whole data volume, under a single folder named after the archive: the database, media, computer homes, every bot and workspace file, and the database snapshots. They live outside the data volume, and the newest few are kept."
|
||||
>
|
||||
<Row className="w-full items-center justify-between gap-2! flex-wrap">
|
||||
<Span size="small" variant="faded">
|
||||
{`${backups.length} archive${backups.length == 1 ? "" : "s"}`}
|
||||
</Span>
|
||||
<DataBackupListActions />
|
||||
</Row>
|
||||
<DataBackupRunNotice />
|
||||
{backups[0] ? (
|
||||
<DataBackupsTable backups={backups} />
|
||||
) : (
|
||||
<Span size="small" variant="faded">
|
||||
No archives yet.
|
||||
</Span>
|
||||
)}
|
||||
</SettingsGroup>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import BackupsListSection from "./(sections)/backups-list-section";
|
||||
import DataBackupsSection from "./(sections)/data-backups-section";
|
||||
import SettingsShell from "../(partials)/settings-shell";
|
||||
import settingsPageMeta from "../(functions)/settings-page-meta";
|
||||
import BackupRunProvider from "./(partials)/backup-run-provider";
|
||||
|
||||
export default function AdminSettingsBackupsPage() {
|
||||
return (
|
||||
@@ -10,8 +11,10 @@ export default function AdminSettingsBackupsPage() {
|
||||
description="Database snapshots and whole-data archives: make them, restore from one, and delete them."
|
||||
wide
|
||||
>
|
||||
<BackupsListSection />
|
||||
<DataBackupsSection />
|
||||
<BackupRunProvider>
|
||||
<BackupsListSection />
|
||||
<DataBackupsSection />
|
||||
</BackupRunProvider>
|
||||
</SettingsShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,8 @@ import grabSuperAdminUser from "@/src/functions/backend/backups/grab-super-admin
|
||||
import restoreDataBackup from "@/src/functions/backend/backups/restore-data-backup";
|
||||
import { startDataBackupRun } from "@/src/functions/backend/backups/data-backup-run";
|
||||
import restartApp from "@/src/functions/backend/backups/restart-app";
|
||||
import logEvent, { grabRequestIP, logError } from "@/src/functions/backend/logger";
|
||||
import { grabRequestIP, logError } from "@/src/functions/backend/logger";
|
||||
import queueBootLog from "@/src/functions/backend/backups/queue-boot-log";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { ApiReqParams, DataBackupRun } from "@/src/types";
|
||||
import type {
|
||||
@@ -13,7 +14,8 @@ import type {
|
||||
/**
|
||||
* Starts replacing the whole data volume with a saved archive and answers
|
||||
* at once. Once it is in, the app restarts so it opens the restored
|
||||
* database; the page polls `data-status` until it is back.
|
||||
* database; the page polls `data-status` until it is back. Its log entry
|
||||
* is written by the next boot (`queueBootLog`), into the restored database.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<
|
||||
APIResponseObject<DataBackupRun>
|
||||
@@ -37,16 +39,18 @@ export const handler: BunextAPIRouteHandler<
|
||||
try {
|
||||
const result = await restoreDataBackup({ backup_name });
|
||||
|
||||
await logEvent({
|
||||
title: "Data restored",
|
||||
category: "system",
|
||||
user_id: user.id,
|
||||
plain_text: `User #${user.id} restored the data volume from archive ${result.restored_name} (safety copy ${result.safety_name}). The app restarted.`,
|
||||
metadata: {
|
||||
backup_name: result.restored_name,
|
||||
safety_name: result.safety_name,
|
||||
queueBootLog({
|
||||
entry: {
|
||||
title: "Data restored",
|
||||
category: "system",
|
||||
user_id: user.id,
|
||||
plain_text: `User #${user.id} restored the data volume from archive ${result.restored_name} (safety copy ${result.safety_name}). The app restarted.`,
|
||||
metadata: {
|
||||
backup_name: result.restored_name,
|
||||
safety_name: result.safety_name,
|
||||
},
|
||||
ip_address,
|
||||
},
|
||||
ip_address,
|
||||
});
|
||||
|
||||
restartApp();
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
import grabSuperAdminUser from "@/src/functions/backend/backups/grab-super-admin-user";
|
||||
import restoreDbBackup from "@/src/functions/backend/backups/restore-db-backup";
|
||||
import logEvent, { grabRequestIP, logError } from "@/src/functions/backend/logger";
|
||||
import type { ApiReqParams } from "@/src/types";
|
||||
import resolveDbBackupPath from "@/src/functions/backend/backups/resolve-db-backup-path";
|
||||
import { startDataBackupRun } from "@/src/functions/backend/backups/data-backup-run";
|
||||
import queueBootLog from "@/src/functions/backend/backups/queue-boot-log";
|
||||
import restartApp from "@/src/functions/backend/backups/restart-app";
|
||||
import { grabRequestIP, logError } from "@/src/functions/backend/logger";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { ApiReqParams, DataBackupRun } from "@/src/types";
|
||||
import type {
|
||||
APIResponseObject,
|
||||
BunextAPIRouteHandler,
|
||||
} from "@moduletrace/bunext/types";
|
||||
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
|
||||
req,
|
||||
body,
|
||||
}) => {
|
||||
/**
|
||||
* Starts restoring a database snapshot and answers at once. The import
|
||||
* swaps in a new database file, which this process can't follow (its
|
||||
* handle stays on the old one), so the app restarts once it's in; the
|
||||
* page polls `data-status` until it's back. The log entry is written by
|
||||
* the next boot, into the restored database.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<
|
||||
APIResponseObject<DataBackupRun>
|
||||
> = async ({ req, body }) => {
|
||||
const user = await grabSuperAdminUser({ req });
|
||||
|
||||
if (!user?.id) {
|
||||
@@ -21,42 +33,54 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
|
||||
}
|
||||
|
||||
const backup_name = (body as ApiReqParams | undefined)?.backup_name;
|
||||
const ip_address = grabRequestIP(req);
|
||||
|
||||
try {
|
||||
await restoreDbBackup({ backup_name });
|
||||
try {
|
||||
resolveDbBackupPath({ backup_name });
|
||||
} catch {
|
||||
throw new AppError(`Backup not found`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logged after the restore so the entry lands in the restored
|
||||
* `logs` table.
|
||||
*/
|
||||
await logEvent({
|
||||
title: "Database restored",
|
||||
category: "system",
|
||||
user_id: user.id,
|
||||
plain_text: `User #${user.id} restored the database from backup ${backup_name}.`,
|
||||
metadata: {
|
||||
backup_name,
|
||||
const run = startDataBackupRun({
|
||||
kind: "db_restore",
|
||||
task: async () => {
|
||||
try {
|
||||
await restoreDbBackup({ backup_name });
|
||||
|
||||
queueBootLog({
|
||||
entry: {
|
||||
title: "Database restored",
|
||||
category: "system",
|
||||
user_id: user.id,
|
||||
plain_text: `User #${user.id} restored the database from backup ${backup_name}. The app restarted.`,
|
||||
metadata: { backup_name },
|
||||
ip_address,
|
||||
},
|
||||
});
|
||||
|
||||
restartApp();
|
||||
|
||||
return String(backup_name);
|
||||
} catch (error: unknown) {
|
||||
await logError({
|
||||
title: "Database restore failed",
|
||||
error,
|
||||
user_id: user.id,
|
||||
metadata: { backup_name },
|
||||
ip_address,
|
||||
});
|
||||
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
ip_address: grabRequestIP(req),
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
singleRes: run,
|
||||
};
|
||||
} catch (error: any) {
|
||||
await logError({
|
||||
title: "Database restore failed",
|
||||
error,
|
||||
user_id: user.id,
|
||||
metadata: {
|
||||
backup_name,
|
||||
},
|
||||
ip_address: grabRequestIP(req),
|
||||
});
|
||||
|
||||
return {
|
||||
success: false,
|
||||
msg: error.message,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -4,7 +4,8 @@ import { startDataBackupRun } from "@/src/functions/backend/backups/data-backup-
|
||||
import { isBackupRunning } from "@/src/functions/backend/backups/with-backup-run-lock";
|
||||
import restartApp from "@/src/functions/backend/backups/restart-app";
|
||||
import saveUploadedDataBackup from "@/src/functions/backend/backups/save-uploaded-data-backup";
|
||||
import logEvent, { grabRequestIP, logError } from "@/src/functions/backend/logger";
|
||||
import { grabRequestIP, logError } from "@/src/functions/backend/logger";
|
||||
import queueBootLog from "@/src/functions/backend/backups/queue-boot-log";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { DataBackupRun } from "@/src/types";
|
||||
@@ -78,17 +79,19 @@ export const handler: BunextAPIRouteHandler<
|
||||
backup_name: saved_name,
|
||||
});
|
||||
|
||||
await logEvent({
|
||||
title: "Data restored from upload",
|
||||
category: "system",
|
||||
user_id: user.id,
|
||||
plain_text: `User #${user.id} restored the data volume from uploaded archive ${file_name} (saved as ${result.restored_name}, safety copy ${result.safety_name}). The app restarted.`,
|
||||
metadata: {
|
||||
file_name,
|
||||
backup_name: result.restored_name,
|
||||
safety_name: result.safety_name,
|
||||
queueBootLog({
|
||||
entry: {
|
||||
title: "Data restored from upload",
|
||||
category: "system",
|
||||
user_id: user.id,
|
||||
plain_text: `User #${user.id} restored the data volume from uploaded archive ${file_name} (saved as ${result.restored_name}, safety copy ${result.safety_name}). The app restarted.`,
|
||||
metadata: {
|
||||
file_name,
|
||||
backup_name: result.restored_name,
|
||||
safety_name: result.safety_name,
|
||||
},
|
||||
ip_address,
|
||||
},
|
||||
ip_address,
|
||||
});
|
||||
|
||||
restartApp();
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import grabSuperAdminUser from "@/src/functions/backend/backups/grab-super-admin-user";
|
||||
import saveUploadedDbBackup from "@/src/functions/backend/backups/save-uploaded-db-backup";
|
||||
import restoreDbBackup from "@/src/functions/backend/backups/restore-db-backup";
|
||||
import logEvent, { grabRequestIP, logError } from "@/src/functions/backend/logger";
|
||||
import { startDataBackupRun } from "@/src/functions/backend/backups/data-backup-run";
|
||||
import { isBackupRunning } from "@/src/functions/backend/backups/with-backup-run-lock";
|
||||
import queueBootLog from "@/src/functions/backend/backups/queue-boot-log";
|
||||
import restartApp from "@/src/functions/backend/backups/restart-app";
|
||||
import { grabRequestIP, logError } from "@/src/functions/backend/logger";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import type { DataBackupRun } from "@/src/types";
|
||||
import type {
|
||||
APIResponseObject,
|
||||
BunextAPIRouteHandler,
|
||||
@@ -14,11 +20,14 @@ export const config: BunextServerRouteConfig = {
|
||||
|
||||
/**
|
||||
* Multipart upload (`file` field) of a SQLite database file. The file is
|
||||
* saved into the backups directory, then restored.
|
||||
* saved into the backups directory within the request, then the restore
|
||||
* starts in the background and the request answers: the app restarts
|
||||
* once it's in (this process's handle stays on the replaced file), and
|
||||
* the page polls `data-status` until it's back.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
|
||||
req,
|
||||
}) => {
|
||||
export const handler: BunextAPIRouteHandler<
|
||||
APIResponseObject<DataBackupRun>
|
||||
> = async ({ req }) => {
|
||||
const user = await grabSuperAdminUser({ req });
|
||||
|
||||
if (!user?.id) {
|
||||
@@ -28,37 +37,11 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
|
||||
};
|
||||
}
|
||||
|
||||
const ip_address = grabRequestIP(req);
|
||||
let file_name: string | undefined;
|
||||
let backup_name: string | undefined;
|
||||
|
||||
try {
|
||||
const file = (await req.formData()).get("file");
|
||||
|
||||
if (!(file instanceof File)) {
|
||||
throw new Error(`No backup file uploaded`);
|
||||
}
|
||||
|
||||
file_name = file.name;
|
||||
backup_name = await saveUploadedDbBackup({ file });
|
||||
|
||||
await restoreDbBackup({ backup_name });
|
||||
|
||||
await logEvent({
|
||||
title: "Database restored from upload",
|
||||
category: "system",
|
||||
user_id: user.id,
|
||||
plain_text: `User #${user.id} restored the database from uploaded file ${file_name} (saved as ${backup_name}).`,
|
||||
metadata: {
|
||||
file_name,
|
||||
backup_name,
|
||||
},
|
||||
ip_address: grabRequestIP(req),
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
};
|
||||
} catch (error: any) {
|
||||
const logFailure = async (error: unknown) => {
|
||||
await logError({
|
||||
title: "Database restore from upload failed",
|
||||
error,
|
||||
@@ -67,12 +50,68 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
|
||||
file_name,
|
||||
backup_name,
|
||||
},
|
||||
ip_address: grabRequestIP(req),
|
||||
ip_address,
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
if (isBackupRunning()) {
|
||||
throw new AppError(`Another backup or restore is already running`);
|
||||
}
|
||||
|
||||
const file = (await req.formData()).get("file");
|
||||
|
||||
if (!(file instanceof File)) {
|
||||
throw new AppError(`No backup file uploaded`);
|
||||
}
|
||||
|
||||
file_name = file.name;
|
||||
backup_name = await saveUploadedDbBackup({ file });
|
||||
|
||||
const saved_name = backup_name;
|
||||
|
||||
const run = startDataBackupRun({
|
||||
kind: "db_restore",
|
||||
task: async () => {
|
||||
try {
|
||||
await restoreDbBackup({ backup_name: saved_name });
|
||||
|
||||
queueBootLog({
|
||||
entry: {
|
||||
title: "Database restored from upload",
|
||||
category: "system",
|
||||
user_id: user.id,
|
||||
plain_text: `User #${user.id} restored the database from uploaded file ${file_name} (saved as ${saved_name}). The app restarted.`,
|
||||
metadata: {
|
||||
file_name,
|
||||
backup_name: saved_name,
|
||||
},
|
||||
ip_address,
|
||||
},
|
||||
});
|
||||
|
||||
restartApp();
|
||||
|
||||
return saved_name;
|
||||
} catch (error: unknown) {
|
||||
await logFailure(error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
singleRes: run,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
if (!(error instanceof AppError)) {
|
||||
await logFailure(error);
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
msg: error.message,
|
||||
msg: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import grabHasUsers from "@/src/functions/backend/auth/grab-has-users";
|
||||
import { startDataBackupRun } from "@/src/functions/backend/backups/data-backup-run";
|
||||
import { isBackupRunning } from "@/src/functions/backend/backups/with-backup-run-lock";
|
||||
import saveBootstrapUpload, {
|
||||
type BootstrapUpload,
|
||||
} from "@/src/functions/backend/backups/save-bootstrap-upload";
|
||||
import restoreBootstrapUpload from "@/src/functions/backend/backups/restore-bootstrap-upload";
|
||||
import { grabRequestIP, logError } from "@/src/functions/backend/logger";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import rateLimit from "@/src/utils/rate-limit";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { DataBackupRun } from "@/src/types";
|
||||
import type {
|
||||
APIResponseObject,
|
||||
BunextAPIRouteHandler,
|
||||
BunextServerRouteConfig,
|
||||
} from "@moduletrace/bunext/types";
|
||||
|
||||
export const config: BunextServerRouteConfig = {
|
||||
max_request_body_mb: 500,
|
||||
};
|
||||
|
||||
/**
|
||||
* First-run setup's other way in: instead of creating a super admin, a
|
||||
* new install takes the database file or whole-data archive of another
|
||||
* one (multipart, `file` field). Public like signup and, like signup,
|
||||
* refused once any account exists, so it can only ever replace an empty
|
||||
* install. The file is saved within the request, the restore runs in the
|
||||
* background and the app restarts once it's in; the page polls
|
||||
* `bootstrap-status` until it's back and then sends the user to log in
|
||||
* with an account from the backup.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<
|
||||
APIResponseObject<DataBackupRun>
|
||||
> = async ({ req }) => {
|
||||
const ip_address = grabRequestIP(req);
|
||||
let file_name: string | undefined;
|
||||
let upload: BootstrapUpload | undefined;
|
||||
|
||||
const logFailure = (error: unknown) =>
|
||||
logError({
|
||||
title: "Restore at setup failed",
|
||||
error,
|
||||
metadata: { file_name, ...upload },
|
||||
ip_address,
|
||||
}).catch(() => {});
|
||||
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const ip_limit = rateLimit({
|
||||
key: `bootstrap-restore:ip:${ip_address || "unknown"}`,
|
||||
limit: AppData["PasswordAttemptLimit"],
|
||||
window_ms: AppData["RateLimitWindowMinutes"] * 60 * 1000,
|
||||
});
|
||||
|
||||
if (!ip_limit.allowed) {
|
||||
throw new AppError(`Too many requests. Please try again later.`);
|
||||
}
|
||||
|
||||
if (await grabHasUsers()) {
|
||||
throw new AppError(`This install has already been set up.`);
|
||||
}
|
||||
|
||||
if (isBackupRunning()) {
|
||||
throw new AppError(`A restore is already running`);
|
||||
}
|
||||
|
||||
const file = (await req.formData()).get("file");
|
||||
|
||||
if (!(file instanceof File)) {
|
||||
throw new AppError(`No backup uploaded`);
|
||||
}
|
||||
|
||||
file_name = file.name;
|
||||
upload = await saveBootstrapUpload({ file });
|
||||
|
||||
const saved = upload;
|
||||
|
||||
const run = startDataBackupRun({
|
||||
kind: saved.kind == "database" ? "db_restore" : "restore",
|
||||
task: async () => {
|
||||
try {
|
||||
return await restoreBootstrapUpload({
|
||||
upload: saved,
|
||||
log_entry: {
|
||||
title: "Install restored at setup",
|
||||
category: "system",
|
||||
plain_text: `First-run setup restored this install from ${saved.kind == "database" ? "database file" : "data archive"} ${file_name} (saved as ${saved.backup_name}). The app restarted.`,
|
||||
metadata: { file_name, ...saved },
|
||||
ip_address,
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
await logFailure(error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
singleRes: run,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
if (!(error instanceof AppError)) {
|
||||
await logFailure(error);
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
msg: safeErrorMessage({ error, log: false }),
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
import grabHasUsers from "@/src/functions/backend/auth/grab-has-users";
|
||||
import { grabDataBackupRun } from "@/src/functions/backend/backups/data-backup-run";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { BootstrapStatus } from "@/src/types";
|
||||
import type {
|
||||
APIResponseObject,
|
||||
BunextAPIRouteHandler,
|
||||
} from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* What the first-run page polls while a restore it started runs: whether
|
||||
* the app restarted (`boot_id`), whether accounts exist yet, and while
|
||||
* none do, how the restore stands. Public, like the setup page.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<
|
||||
APIResponseObject<BootstrapStatus>
|
||||
> = async ({ req }) => {
|
||||
try {
|
||||
if (req.method != "GET") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const run = grabDataBackupRun();
|
||||
const has_users = await grabHasUsers();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
singleRes: has_users
|
||||
? { has_users, boot_id: run.boot_id, status: "idle" }
|
||||
: {
|
||||
has_users,
|
||||
boot_id: run.boot_id,
|
||||
status: run.status,
|
||||
error: run.error,
|
||||
},
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { DataBackupRun } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
file: File;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sends the backup a new install starts from as multipart form data (not
|
||||
* base64 JSON), so a large archive isn't inflated. The server restores it
|
||||
* in the background and restarts, so this hands back the run for the page
|
||||
* to follow.
|
||||
*/
|
||||
export default async function uploadBootstrapRestore({ file }: Params) {
|
||||
const confirm_msg = `Set this install up from "${file.name}"?\n\nIts accounts, bots, workspaces and settings become this install's, and the app restarts. You then log in with an account from the backup.`;
|
||||
|
||||
if (!window.confirm(confirm_msg)) {
|
||||
return { success: false, cancelled: true };
|
||||
}
|
||||
|
||||
try {
|
||||
const form_data = new FormData();
|
||||
form_data.append("file", file);
|
||||
|
||||
const res = await fetch("/api/auth/bootstrap-restore", {
|
||||
method: "POST",
|
||||
body: form_data,
|
||||
});
|
||||
|
||||
const json = await res.json();
|
||||
|
||||
return {
|
||||
success: Boolean(json.success),
|
||||
msg: json.success ? undefined : json.msg || `Couldn't restore the backup`,
|
||||
run: json.success ? (json.singleRes as DataBackupRun | undefined) : undefined,
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
success: false,
|
||||
msg: error.message || `Couldn't restore the backup`,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { BootstrapStatus, DataBackupRun } from "@/src/types";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
|
||||
const LoginPath = "/auth/login";
|
||||
|
||||
/**
|
||||
* Follows a restore started from first-run setup by polling
|
||||
* `bootstrap-status` every `AppData.DataBackupPollMs`. The app restarts
|
||||
* once the backup is in, so failed polls are expected; the page goes to
|
||||
* the login once the status comes from a new boot or accounts exist (or
|
||||
* after `AppData.DataRestoreWaitMs` anyway, where the guard sends it back
|
||||
* to setup if nothing was restored).
|
||||
*/
|
||||
export default function useBootstrapRestore() {
|
||||
const [run, setRun] = useState<DataBackupRun>();
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
useEffect(() => {
|
||||
if (run?.status != "running") return;
|
||||
|
||||
const active = run;
|
||||
const deadline = Date.now() + AppData.DataRestoreWaitMs;
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
let stopped = false;
|
||||
|
||||
const poll = async () => {
|
||||
const res = await fetchApi<{}, APIResponseObject<BootstrapStatus>>(
|
||||
`/api/auth/bootstrap-status`,
|
||||
{ method: "GET" },
|
||||
).catch(() => undefined);
|
||||
|
||||
if (stopped) return;
|
||||
|
||||
const current = res?.success ? res.singleRes : undefined;
|
||||
const restarted = Boolean(
|
||||
current && current.boot_id != active.boot_id,
|
||||
);
|
||||
|
||||
if (current?.has_users || restarted || Date.now() > deadline) {
|
||||
window.location.pathname = LoginPath;
|
||||
return;
|
||||
}
|
||||
|
||||
if (current?.status == "failed") {
|
||||
setError(current.error || `Couldn't restore the backup`);
|
||||
setRun(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
timeout = setTimeout(poll, AppData.DataBackupPollMs);
|
||||
};
|
||||
|
||||
timeout = setTimeout(poll, AppData.DataBackupPollMs);
|
||||
|
||||
return () => {
|
||||
stopped = true;
|
||||
if (timeout) clearTimeout(timeout);
|
||||
};
|
||||
}, [run]);
|
||||
|
||||
return {
|
||||
restoring: run?.status == "running",
|
||||
error,
|
||||
track: (next: DataBackupRun) => {
|
||||
setError(undefined);
|
||||
setRun(next);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
|
||||
import UploadRestoreFields from "@/src/components/general/upload-restore-fields";
|
||||
import uploadBootstrapRestore from "../(functions)/upload-bootstrap-restore";
|
||||
import type { DataBackupRun } from "@/src/types";
|
||||
|
||||
type Props = {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
/**
|
||||
* Hands the restore the upload started to the page to follow.
|
||||
*/
|
||||
onStarted: (run: DataBackupRun) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Setting a new install up from another one's backup: a database file
|
||||
* downloaded from Settings > Backups, or a whole-data archive.
|
||||
*/
|
||||
export default function BootstrapRestoreModal({ open, onClose, onStarted }: Props) {
|
||||
return (
|
||||
<AddModalShell
|
||||
open={open}
|
||||
setOpen={(next) => !next && onClose()}
|
||||
title="Restore from a backup"
|
||||
description="Upload a database file or a whole-data .tar.gz archive from Settings > Backups of another install. Its accounts, bots and settings become this install's, and the app restarts."
|
||||
>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
Provider keys, environment values and secrets open only with
|
||||
the old install's ENCRYPTION_KEY and ENCRYPTION_SALT. Copy
|
||||
both into this install's .env before you restore (the
|
||||
restart picks them up), or enter those values again after.
|
||||
</Span>
|
||||
{open ? (
|
||||
<UploadRestoreFields
|
||||
label="Click or drop a database file or data archive"
|
||||
accept=".db,.sqlite,.sqlite3,.tar.gz,.tgz,application/gzip"
|
||||
action_label="Upload & restore"
|
||||
upload={uploadBootstrapRestore}
|
||||
onDone={({ run }) => {
|
||||
if (run) onStarted(run);
|
||||
onClose();
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</AddModalShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useState } from "react";
|
||||
import { ArchiveRestore } from "lucide-react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Tag from "@moduletrace/twui/elements/Tag";
|
||||
import useBootstrapRestore from "../(hooks)/use-bootstrap-restore";
|
||||
import BootstrapRestoreModal from "./bootstrap-restore-modal";
|
||||
|
||||
/**
|
||||
* The other way through first-run setup: instead of a new super admin,
|
||||
* the install takes another one's backup. Shows the restore while it
|
||||
* runs, then the page goes to the login.
|
||||
*/
|
||||
export default function SignupRestoreOption() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { restoring, error, track } = useBootstrapRestore();
|
||||
|
||||
return (
|
||||
<Stack className="w-full items-center gap-3!">
|
||||
<Span className="text-sm text-ink-secondary">
|
||||
Moving from another install?
|
||||
</Span>
|
||||
<Button
|
||||
title="Restore from a backup"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
beforeIcon={<ArchiveRestore />}
|
||||
loading={restoring}
|
||||
disabled={restoring}
|
||||
onClick={() => {
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
Restore from a backup
|
||||
</Button>
|
||||
{restoring ? (
|
||||
<Tag color="warning">Restoring, the app restarts soon...</Tag>
|
||||
) : null}
|
||||
{error ? <Tag color="error">{error}</Tag> : null}
|
||||
<BootstrapRestoreModal
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
onStarted={track}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -4,9 +4,11 @@ import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import AuthHero from "@/src/components/general/auth-hero";
|
||||
import { SiteData } from "@/src/data/site-data";
|
||||
import SignupForm from "../(partials)/signup-form";
|
||||
import SignupRestoreOption from "../(partials)/signup-restore-option";
|
||||
|
||||
/**
|
||||
* First-run setup. Only reachable while no account exists.
|
||||
* First-run setup. Only reachable while no account exists: create the
|
||||
* super admin, or restore another install's backup.
|
||||
*/
|
||||
export default function SignupFormSection() {
|
||||
return (
|
||||
@@ -19,6 +21,7 @@ export default function SignupFormSection() {
|
||||
description={`This is the first account on this ${SiteData["SiteName"]} install. It can add everyone else.`}
|
||||
/>
|
||||
<SignupForm />
|
||||
<SignupRestoreOption />
|
||||
</Stack>
|
||||
</Container>
|
||||
</Section>
|
||||
|
||||
@@ -8,5 +8,5 @@ export default function SignupPage() {
|
||||
|
||||
export const meta: BunextPageModuleMeta = {
|
||||
title: `Set Up | ${SiteData["SiteName"]}`,
|
||||
description: `Create the super admin for this ${SiteData["SiteName"]} install.`,
|
||||
description: `Create the super admin for this ${SiteData["SiteName"]} install, or restore it from a backup.`,
|
||||
};
|
||||
|
||||
@@ -13,6 +13,7 @@ import migrateBotTypes from "./functions/backend/db/bot-types/migrate-bot-types"
|
||||
import clearImplicitSessionLinks from "./functions/backend/db/bot-sessions/clear-implicit-session-links";
|
||||
import dropStoredFileText from "./functions/backend/db/stored-text/drop-stored-file-text";
|
||||
import syncKnowledgebaseFts from "./functions/backend/db/knowledgebases/fts/sync-knowledgebase-fts";
|
||||
import flushBootLogs from "./functions/backend/backups/flush-boot-logs";
|
||||
import handleComputerProxy from "./functions/server/computers/handle-computer-proxy";
|
||||
import handleGraphicsRequest from "./functions/server/graphics/handle-graphics-request";
|
||||
import handlePwaFile from "./functions/server/pwa/handle-pwa-file";
|
||||
@@ -36,6 +37,7 @@ const development = process.env.NODE_ENV == "development";
|
||||
const port = process.env.PORT || 7227;
|
||||
|
||||
await enableForeignKeys();
|
||||
await flushBootLogs().catch(() => {});
|
||||
await migrateBotTypes().catch((error) =>
|
||||
logError({ title: "Could not migrate bot types", error }).catch(() => {}),
|
||||
);
|
||||
|
||||
+18
-1
@@ -1909,7 +1909,12 @@ export type DataBackup = {
|
||||
size: number;
|
||||
};
|
||||
|
||||
export type DataBackupRunKind = "archive" | "restore";
|
||||
/**
|
||||
* What a background backup run does: write a whole-data archive, restore
|
||||
* one (`restore`), or restore a database snapshot (`db_restore`). Both
|
||||
* restores end in a restart.
|
||||
*/
|
||||
export type DataBackupRunKind = "archive" | "restore" | "db_restore";
|
||||
|
||||
/**
|
||||
* The whole-data archive or restore this process last started
|
||||
@@ -1935,6 +1940,18 @@ export type DataBackupStatus = {
|
||||
data_backups: DataBackup[];
|
||||
};
|
||||
|
||||
/**
|
||||
* How a restore started from first-run setup is going (public, so only
|
||||
* this much). `boot_id` changes when the app restarts on the restored
|
||||
* data; once any account exists only that and `has_users` are told.
|
||||
*/
|
||||
export type BootstrapStatus = {
|
||||
has_users: boolean;
|
||||
boot_id: string;
|
||||
status: DataBackupRun["status"];
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type BotVoicePayload = {
|
||||
transcription: boolean;
|
||||
speech: boolean;
|
||||
|
||||
Reference in New Issue
Block a user