mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
Merge branch 'feat/v1463-restore' into release/v1.46.3
This commit is contained in:
commit
00d129ad42
28 files changed
+2504
-154
No files matched your search
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* `rewriteBackupOwner` must change the top-level `userId` and nothing else,
|
||||
* over any chunk boundaries: the output parses to the input with that one
|
||||
* member replaced, and is byte-identical to it everywhere outside the value.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { BackupJsonError } from "../backup-json-scan";
|
||||
import {
|
||||
BackupOwnerRewriteError,
|
||||
rewriteBackupOwner,
|
||||
} from "../backup-owner-rewrite";
|
||||
|
||||
async function* chunked(text: string, sizes: number[]) {
|
||||
const bytes = Buffer.from(text, "utf8");
|
||||
let at = 0;
|
||||
let i = 0;
|
||||
while (at < bytes.length) {
|
||||
const size = sizes[i++ % sizes.length]!;
|
||||
yield bytes.subarray(at, at + size);
|
||||
at += size;
|
||||
}
|
||||
}
|
||||
|
||||
async function run(text: string, target: string, sizes: number[] = [7]) {
|
||||
const rewrite = rewriteBackupOwner(chunked(text, sizes), target);
|
||||
const parts: Buffer[] = [];
|
||||
for await (const part of rewrite.bytes) parts.push(part);
|
||||
return {
|
||||
text: Buffer.concat(parts).toString("utf8"),
|
||||
declared: rewrite.declaredOwner(),
|
||||
};
|
||||
}
|
||||
|
||||
const NESTED = {
|
||||
schemaVersion: "2",
|
||||
exportedAt: "2026-10-01T00:00:00.000Z",
|
||||
userId: "cerased0000000000000000",
|
||||
measurements: [
|
||||
{ id: "m1", userId: "cerased0000000000000000", note: 'a "userId": x' },
|
||||
],
|
||||
profile: { userId: "cerased0000000000000000", name: "ä ö ü 🫀 } ] , :" },
|
||||
notes: ["userId", "brackets ] } [ {"],
|
||||
};
|
||||
|
||||
describe("rewriteBackupOwner", () => {
|
||||
it("replaces only the top-level owner, at every chunk size", async () => {
|
||||
const text = JSON.stringify(NESTED, null, 1);
|
||||
for (const sizes of [[1], [2], [3], [5, 1, 9], [64], [text.length]]) {
|
||||
const out = await run(text, "ctarget0000000000000000", sizes);
|
||||
expect(out.declared).toBe("cerased0000000000000000");
|
||||
expect(JSON.parse(out.text)).toEqual({
|
||||
...NESTED,
|
||||
userId: "ctarget0000000000000000",
|
||||
});
|
||||
// Outside the value, the bytes are the input's.
|
||||
expect(out.text).toBe(
|
||||
text.replace(
|
||||
'"userId": "cerased0000000000000000"',
|
||||
'"userId": "ctarget0000000000000000"',
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("reads an escaped spelling of the key as the key", async () => {
|
||||
const text = '{"user\\u0049d":"cold","a":[1,{"userId":"keep"}]}';
|
||||
const out = await run(text, "cnew", [1]);
|
||||
expect(out.declared).toBe("cold");
|
||||
expect(JSON.parse(out.text)).toEqual({
|
||||
userId: "cnew",
|
||||
a: [1, { userId: "keep" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("replaces every top-level owner and declares the last, as JSON.parse keeps it", async () => {
|
||||
const text = '{"userId":"first","x":1,"userId":"second"}';
|
||||
const out = await run(text, "cnew", [4]);
|
||||
expect(out.declared).toBe(JSON.parse(text).userId);
|
||||
expect(out.text).toBe('{"userId":"cnew","x":1,"userId":"cnew"}');
|
||||
});
|
||||
|
||||
it("leaves a file without an owner unchanged and declares none", async () => {
|
||||
const text = '{"schemaVersion":"2","rows":[{"userId":"nested"}]}';
|
||||
const out = await run(text, "cnew", [3]);
|
||||
expect(out.declared).toBeNull();
|
||||
expect(out.text).toBe(text);
|
||||
});
|
||||
|
||||
it("leaves a value that is a string elsewhere, or not a string, alone", async () => {
|
||||
const text = '{"name":"userId","userId":42}';
|
||||
const out = await run(text, "cnew", [2]);
|
||||
expect(out.declared).toBeNull();
|
||||
expect(out.text).toBe(text);
|
||||
});
|
||||
|
||||
it("leaves a top-level array alone", async () => {
|
||||
const text = '["userId","x"]';
|
||||
const out = await run(text, "cnew");
|
||||
expect(out.declared).toBeNull();
|
||||
expect(out.text).toBe(text);
|
||||
});
|
||||
|
||||
it("refuses an owner too long to be an id", async () => {
|
||||
const text = JSON.stringify({ userId: "x".repeat(4096) });
|
||||
await expect(run(text, "cnew", [100])).rejects.toBeInstanceOf(
|
||||
BackupOwnerRewriteError,
|
||||
);
|
||||
});
|
||||
|
||||
it("refuses a top-level key that is not valid JSON", async () => {
|
||||
await expect(run('{"bad\\q":1}', "cnew")).rejects.toBeInstanceOf(
|
||||
BackupJsonError,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* The emptiness check behind restoring an erased account's copy into another
|
||||
* account reads every backed-up model by its `userId`, except the children
|
||||
* that have none, which it reaches through their parent. Both halves are held
|
||||
* to `prisma/schema.prisma` here, so a backed-up model added later is either
|
||||
* checked or fails this file; it cannot be skipped and read as empty.
|
||||
*
|
||||
* Mutation check: drop a model from `BACKED_UP_CHILD_MODELS` and the first
|
||||
* case names it (no `userId`); add an owned model to it and the second does.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseWipeSchema } from "@/__tests__/helpers/wipe-schema-shape";
|
||||
import { BACKED_UP_MODELS } from "@/lib/export/backup-plan";
|
||||
import {
|
||||
BACKED_UP_CHILD_MODELS,
|
||||
RESTORE_TARGET_OWNED_MODELS,
|
||||
} from "@/lib/export/restore-target";
|
||||
|
||||
const models = parseWipeSchema();
|
||||
|
||||
describe("restore target models", () => {
|
||||
it("reads every owned backed-up model by its userId", () => {
|
||||
const missing = RESTORE_TARGET_OWNED_MODELS.filter(
|
||||
(model) => !models.get(model)?.scalars.includes("userId"),
|
||||
);
|
||||
expect(missing).toEqual([]);
|
||||
expect(RESTORE_TARGET_OWNED_MODELS.length).toBeGreaterThan(60);
|
||||
});
|
||||
|
||||
it("reaches each child through a required cascade to an owned parent", () => {
|
||||
for (const [child, parent] of Object.entries(BACKED_UP_CHILD_MODELS)) {
|
||||
expect(BACKED_UP_MODELS, child).toContain(child);
|
||||
const shape = models.get(child);
|
||||
expect(shape?.scalars, child).not.toContain("userId");
|
||||
expect(
|
||||
shape?.relations.some(
|
||||
(r) => r.target === parent && r.cascade && !r.optional,
|
||||
),
|
||||
`${child} -> ${parent}`,
|
||||
).toBe(true);
|
||||
expect(RESTORE_TARGET_OWNED_MODELS, parent).toContain(parent);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* Point a backup file at another account, on its way in.
|
||||
*
|
||||
* A backup names its owner once, in the top-level `userId` member. The restore
|
||||
* takes the account it writes from there and from nowhere else
|
||||
* (`checkOwnership` in `restore-preflight.ts`), and every domain writes its
|
||||
* rows under that account (`ctx.ownerId`), never under an id read from a row.
|
||||
* So the copy of an account that has since been erased goes into another
|
||||
* account by changing that one member, and nothing else in the file: the copy
|
||||
* stored is then that account's copy in every respect (its preview, its
|
||||
* download, its restore), and the erased id is stored nowhere, not even inside
|
||||
* the encrypted copy.
|
||||
*
|
||||
* This rewrites the member as the bytes stream past, without holding the
|
||||
* document (a disaster-recovery file can be longer than any string V8 can
|
||||
* hold, see `backup-json-scan.ts`). It tracks only string and nesting state,
|
||||
* and parses only the top-level keys and the one value it replaces. A key is
|
||||
* compared after `JSON.parse`, so an escaped spelling of `userId` is the same
|
||||
* key, exactly as the reader behind it sees it; a `userId` nested anywhere
|
||||
* below the top level is left alone. Every other byte passes through
|
||||
* unchanged.
|
||||
*/
|
||||
|
||||
import { BackupJsonError } from "@/lib/export/backup-json-scan";
|
||||
|
||||
const QUOTE = 0x22;
|
||||
const BACKSLASH = 0x5c;
|
||||
const OPEN_BRACE = 0x7b;
|
||||
const CLOSE_BRACE = 0x7d;
|
||||
const OPEN_BRACKET = 0x5b;
|
||||
const CLOSE_BRACKET = 0x5d;
|
||||
const COMMA = 0x2c;
|
||||
|
||||
/** Longer than any top-level key a backup carries. */
|
||||
const MAX_KEY_BYTES = 256;
|
||||
/** Far longer than any account id; a longer owner is not an id. */
|
||||
const MAX_OWNER_BYTES = 1024;
|
||||
|
||||
/** The file's owner member is not something this can rewrite. */
|
||||
export class BackupOwnerRewriteError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "BackupOwnerRewriteError";
|
||||
}
|
||||
}
|
||||
|
||||
type StringRole = "key" | "owner" | "other";
|
||||
|
||||
export interface BackupOwnerRewrite {
|
||||
/** The bytes, with every top-level `userId` string set to the target. */
|
||||
bytes: AsyncGenerator<Buffer>;
|
||||
/**
|
||||
* The owner the file declared, once the stream has passed it: the last
|
||||
* top-level `userId` string, which is the one `JSON.parse` keeps. Null when
|
||||
* the file has none.
|
||||
*/
|
||||
declaredOwner(): string | null;
|
||||
}
|
||||
|
||||
export function rewriteBackupOwner(
|
||||
source: AsyncIterable<Uint8Array>,
|
||||
targetId: string,
|
||||
): BackupOwnerRewrite {
|
||||
const replacement = Buffer.from(JSON.stringify(targetId), "utf8");
|
||||
let declared: string | null = null;
|
||||
|
||||
async function* bytes(): AsyncGenerator<Buffer> {
|
||||
let depth = 0;
|
||||
let topIsObject = false;
|
||||
let expectKey = false;
|
||||
let lastKey: string | null = null;
|
||||
let inString = false;
|
||||
let escaped = false;
|
||||
let role: StringRole = "other";
|
||||
// The key or owner string being collected, across chunks.
|
||||
let collected: Buffer[] = [];
|
||||
let collectedBytes = 0;
|
||||
|
||||
for await (const raw of source) {
|
||||
const chunk = Buffer.isBuffer(raw)
|
||||
? raw
|
||||
: Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength);
|
||||
const out: Buffer[] = [];
|
||||
// Where the bytes passed through unchanged start in this chunk; -1
|
||||
// while the owner value is being withheld.
|
||||
let passFrom = role === "owner" && inString ? -1 : 0;
|
||||
// Where the string being collected starts in this chunk.
|
||||
let collectFrom = 0;
|
||||
|
||||
const collect = (to: number) => {
|
||||
if (to > collectFrom) {
|
||||
collected.push(chunk.subarray(collectFrom, to));
|
||||
collectedBytes += to - collectFrom;
|
||||
}
|
||||
if (role === "key" && collectedBytes > MAX_KEY_BYTES) {
|
||||
// Not a key this rewrite cares about; stop collecting it.
|
||||
role = "other";
|
||||
collected = [];
|
||||
collectedBytes = 0;
|
||||
}
|
||||
if (role === "owner" && collectedBytes > MAX_OWNER_BYTES) {
|
||||
throw new BackupOwnerRewriteError(
|
||||
"The file's owner is too long to be an account id",
|
||||
);
|
||||
}
|
||||
};
|
||||
const take = (): string => {
|
||||
const text = Buffer.concat(collected, collectedBytes).toString("utf8");
|
||||
collected = [];
|
||||
collectedBytes = 0;
|
||||
try {
|
||||
return JSON.parse(text) as string;
|
||||
} catch {
|
||||
throw new BackupJsonError(
|
||||
"A top-level string in the file is not valid JSON",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
for (let i = 0; i < chunk.length; i++) {
|
||||
const byte = chunk[i]!;
|
||||
if (inString) {
|
||||
if (escaped) escaped = false;
|
||||
else if (byte === BACKSLASH) escaped = true;
|
||||
else if (byte === QUOTE) {
|
||||
inString = false;
|
||||
if (role === "key") {
|
||||
collect(i + 1);
|
||||
lastKey = role === "key" ? take() : null;
|
||||
expectKey = false;
|
||||
} else if (role === "owner") {
|
||||
collect(i + 1);
|
||||
declared = take();
|
||||
out.push(replacement);
|
||||
passFrom = i + 1;
|
||||
}
|
||||
role = "other";
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (byte === QUOTE) {
|
||||
inString = true;
|
||||
if (depth === 1 && topIsObject && expectKey) {
|
||||
role = "key";
|
||||
collectFrom = i;
|
||||
} else if (depth === 1 && topIsObject && lastKey === "userId") {
|
||||
role = "owner";
|
||||
collectFrom = i;
|
||||
if (passFrom >= 0) out.push(chunk.subarray(passFrom, i));
|
||||
passFrom = -1;
|
||||
} else {
|
||||
role = "other";
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (byte === OPEN_BRACE || byte === OPEN_BRACKET) {
|
||||
depth += 1;
|
||||
if (depth === 1) {
|
||||
topIsObject = byte === OPEN_BRACE;
|
||||
expectKey = topIsObject;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (byte === CLOSE_BRACE || byte === CLOSE_BRACKET) {
|
||||
depth -= 1;
|
||||
continue;
|
||||
}
|
||||
if (byte === COMMA && depth === 1) {
|
||||
expectKey = topIsObject;
|
||||
lastKey = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (inString && (role === "key" || role === "owner")) {
|
||||
collect(chunk.length);
|
||||
}
|
||||
if (passFrom >= 0) out.push(chunk.subarray(passFrom));
|
||||
const piece = out.length === 1 ? out[0]! : Buffer.concat(out);
|
||||
if (piece.byteLength > 0) yield piece;
|
||||
}
|
||||
}
|
||||
|
||||
return { bytes: bytes(), declaredOwner: () => declared };
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* Which account the copy of an erased account may be restored into.
|
||||
*
|
||||
* A restore replaces: every row of the account in a section the copy carries
|
||||
* is deleted and the copy's rows are written in their place
|
||||
* (`docs/ops/backup-restore.md`). There is no merge. So putting the record of
|
||||
* an account that no longer exists into another account is only safe when
|
||||
* that account holds none of those rows, and the check is exactly that: a row
|
||||
* of any model the backup carries ({@link BACKED_UP_MODELS}) under the
|
||||
* account refuses it. Everything a restore leaves alone (credentials,
|
||||
* sessions, devices, grants) does not count.
|
||||
*
|
||||
* The other two refusals keep the account rules intact. A managed profile is
|
||||
* its Guardians' record, which an admin does not write into (the users list
|
||||
* offers no admin deletion on one for the same reason). An account pending
|
||||
* deletion is locked and will be erased, with whatever was restored into it.
|
||||
* Neither the restore nor this check touches the role, so the last-admin rule
|
||||
* is not in play.
|
||||
*/
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
import { BACKED_UP_MODELS } from "@/lib/export/backup-plan";
|
||||
|
||||
/**
|
||||
* The backed-up models with no owner column of their own, each with the owned
|
||||
* model it hangs off through a required cascade. A row of one cannot exist
|
||||
* without a row of its parent, so checking the parent checks it.
|
||||
* `restore-target-models.test.ts` holds this list to the schema.
|
||||
*/
|
||||
export const BACKED_UP_CHILD_MODELS: Readonly<Record<string, string>> = {
|
||||
MedicationSchedule: "Medication",
|
||||
MedicationScheduleRevision: "Medication",
|
||||
MedicationDoseChange: "Medication",
|
||||
MedicationEfficacyTarget: "Medication",
|
||||
MedicationInventoryEvent: "Medication",
|
||||
MedicationCategoryAssignment: "Medication",
|
||||
ReminderPhaseConfig: "Medication",
|
||||
MoodEntryTagLink: "MoodEntry",
|
||||
IllnessSymptomLink: "IllnessDayLog",
|
||||
CycleSymptomLink: "CycleDayLog",
|
||||
WorkoutRoute: "Workout",
|
||||
WorkoutSamples: "Workout",
|
||||
CoachMessage: "CoachConversation",
|
||||
CoachConversationDocument: "CoachConversation",
|
||||
};
|
||||
|
||||
/** Every backed-up model that carries `userId`, in the plan's order. */
|
||||
export const RESTORE_TARGET_OWNED_MODELS: readonly string[] =
|
||||
BACKED_UP_MODELS.filter((model) => !(model in BACKED_UP_CHILD_MODELS));
|
||||
|
||||
interface OwnedDelegate {
|
||||
findFirst(args: {
|
||||
where: { userId: string };
|
||||
select: { userId: true };
|
||||
}): Promise<unknown>;
|
||||
}
|
||||
|
||||
function ownedDelegate(db: object, model: string): OwnedDelegate {
|
||||
const key = model.charAt(0).toLowerCase() + model.slice(1);
|
||||
const delegate = (db as Record<string, OwnedDelegate | undefined>)[key];
|
||||
if (!delegate || typeof delegate.findFirst !== "function") {
|
||||
// Never narrower than the plan: a model this cannot read is a model it
|
||||
// would otherwise call empty.
|
||||
throw new Error(`No Prisma delegate for backed-up model "${model}"`);
|
||||
}
|
||||
return delegate;
|
||||
}
|
||||
|
||||
/** The backed-up models under which `userId` holds at least one row. */
|
||||
export async function modelsHoldingRecords(
|
||||
db: Prisma.TransactionClient,
|
||||
userId: string,
|
||||
): Promise<string[]> {
|
||||
const held: string[] = [];
|
||||
for (const model of RESTORE_TARGET_OWNED_MODELS) {
|
||||
const row = await ownedDelegate(db, model).findFirst({
|
||||
where: { userId },
|
||||
select: { userId: true },
|
||||
});
|
||||
if (row) held.push(model);
|
||||
}
|
||||
return held;
|
||||
}
|
||||
|
||||
export type RestoreTargetRefusal =
|
||||
"not_found" | "managed_profile" | "pending_deletion" | "holds_records";
|
||||
|
||||
export type RestoreTargetVerdict =
|
||||
| { ok: true; target: { id: string; username: string } }
|
||||
| {
|
||||
ok: false;
|
||||
reason: RestoreTargetRefusal;
|
||||
target: { id: string; username: string } | null;
|
||||
/** For `holds_records`: the models that hold rows, in plan order. */
|
||||
models: string[];
|
||||
};
|
||||
|
||||
/** Whether the copy of an erased account may go into `userId`. */
|
||||
export async function checkRestoreTarget(
|
||||
db: Prisma.TransactionClient,
|
||||
userId: string,
|
||||
): Promise<RestoreTargetVerdict> {
|
||||
const row = await db.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
managedProfileAt: true,
|
||||
deletionRequestedAt: true,
|
||||
},
|
||||
});
|
||||
if (!row) {
|
||||
return { ok: false, reason: "not_found", target: null, models: [] };
|
||||
}
|
||||
const target = { id: row.id, username: row.username };
|
||||
if (row.managedProfileAt) {
|
||||
return { ok: false, reason: "managed_profile", target, models: [] };
|
||||
}
|
||||
if (row.deletionRequestedAt) {
|
||||
return { ok: false, reason: "pending_deletion", target, models: [] };
|
||||
}
|
||||
const models = await modelsHoldingRecords(db, row.id);
|
||||
if (models.length > 0) {
|
||||
return { ok: false, reason: "holds_records", target, models };
|
||||
}
|
||||
return { ok: true, target };
|
||||
}
|
||||
|
||||
/** The wire code of each refusal. */
|
||||
export const BACKUP_TARGET_REFUSAL_CODES = {
|
||||
not_found: "backup.target.not_found",
|
||||
managed_profile: "backup.target.managed_profile",
|
||||
pending_deletion: "backup.target.pending_deletion",
|
||||
holds_records: "backup.target.holds_records",
|
||||
} as const satisfies Record<RestoreTargetRefusal, string>;
|
||||
|
||||
/** The status and stable code each refusal answers with. */
|
||||
export const RESTORE_TARGET_REFUSALS: Readonly<
|
||||
Record<
|
||||
RestoreTargetRefusal,
|
||||
{ status: number; code: string; message: string }
|
||||
>
|
||||
> = {
|
||||
not_found: {
|
||||
status: 404,
|
||||
code: BACKUP_TARGET_REFUSAL_CODES.not_found,
|
||||
message: "The chosen account does not exist.",
|
||||
},
|
||||
managed_profile: {
|
||||
status: 409,
|
||||
code: BACKUP_TARGET_REFUSAL_CODES.managed_profile,
|
||||
message:
|
||||
"The chosen account is a managed profile. Its Guardians run it, so a copy cannot be restored into it.",
|
||||
},
|
||||
pending_deletion: {
|
||||
status: 409,
|
||||
code: BACKUP_TARGET_REFUSAL_CODES.pending_deletion,
|
||||
message:
|
||||
"The chosen account is pending deletion. Undo the deletion first, or choose another account.",
|
||||
},
|
||||
holds_records: {
|
||||
status: 409,
|
||||
code: BACKUP_TARGET_REFUSAL_CODES.holds_records,
|
||||
message:
|
||||
"The chosen account already holds records, and a restore replaces them rather than adding to them. Choose an empty account or create a new one.",
|
||||
},
|
||||
};
|
||||
@@ -100,9 +100,17 @@ export const ERROR_CODE_CATALOGUE: Readonly<Record<string, readonly string[]>> =
|
||||
backup: [
|
||||
"backup.foreign_reference",
|
||||
"backup.key.missing",
|
||||
"backup.owner.exists",
|
||||
"backup.owner.missing",
|
||||
"backup.payload.undecryptable",
|
||||
"backup.restore.active",
|
||||
"backup.section.missing",
|
||||
"backup.target.holds_records",
|
||||
"backup.target.managed_profile",
|
||||
"backup.target.not_found",
|
||||
"backup.target.pending_deletion",
|
||||
"backup.target.unconfirmed",
|
||||
"backup.target.username_taken",
|
||||
"backup.upload.too_large",
|
||||
],
|
||||
biomarkers: ["biomarkers.unit.locked"],
|
||||
|
||||
@@ -218,7 +218,26 @@ export const adminBackupPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Admin"],
|
||||
summary: "Store an uploaded backup file as a new copy",
|
||||
description:
|
||||
"Reads a backup file, checks it, and stores it encrypted as a new copy beside the weekly one; it does NOT restore anything. Restoring is the separate `POST /api/admin/backups/{id}/restore`, so an operator can review what was uploaded first. The file goes up as the raw request body, plain JSON or gzip-compressed JSON (sniffed from the bytes, not the content type), up to 512 MB as sent; or, for a file up to 10 MB, as `multipart/form-data` with one `file` field. It is read as a stream, checked as it arrives, and stored in the same pass; a file that fails any check leaves nothing behind. It is refused when it is not valid JSON, fails the backup schema, was written by a newer schema version than this server reads, needs an encryption key this server does not hold (`meta.errorCode` = `backup.key.missing`, `meta.keyIds` naming them), or belongs to an account that does not exist here. Three uploads a minute per administrator. Admin session cookie required; Bearer tokens cannot reach admin endpoints. A browser session needs a fresh proof as well as a live one: a sign-in or `POST /api/auth/reproof` within the last five minutes (with a second factor, on an account that has one). Without it the answer is 401 `auth.reproof.required`, with `meta.methods` naming the proofs the account can give.",
|
||||
"Reads a backup file, checks it, and stores it encrypted as a new copy beside the weekly one; it does NOT restore anything. Restoring is the separate `POST /api/admin/backups/{id}/restore`, so an operator can review what was uploaded first. The file goes up as the raw request body, plain JSON or gzip-compressed JSON (sniffed from the bytes, not the content type), up to 512 MB as sent; or, for a file up to 10 MB, as `multipart/form-data` with one `file` field. It is read as a stream, checked as it arrives, and stored in the same pass; a file that fails any check leaves nothing behind. It is refused when it is not valid JSON, fails the backup schema, was written by a newer schema version than this server reads, needs an encryption key this server does not hold (`meta.errorCode` = `backup.key.missing`, `meta.keyIds` naming them), or belongs to an account that does not exist here (`meta.errorCode` = `backup.owner.missing`). A file of an account that no longer exists here (erased, say) can be sent again with a target in the query: `into=existing&userId=<id>&confirm=<username>` for an account that holds no records yet, or `into=new&username=<name>` for a new account created for the copy, with no password and no email (an admin sets its first password with the existing password reset). The file's owner is rewritten to that account as it is read, so the stored copy is that account's copy and restores like any other; the erased account's id is not stored. A target is refused before the file is read when the account does not exist, is a managed profile, is pending deletion, or holds records (a restore replaces records, it does not merge them); a file whose own account is still here is refused with a target (`backup.owner.exists`). Three uploads a minute per administrator. Admin session cookie required; Bearer tokens cannot reach admin endpoints. A browser session needs a fresh proof as well as a live one: a sign-in or `POST /api/auth/reproof` within the last five minutes (with a second factor, on an account that has one). Without it the answer is 401 `auth.reproof.required`, with `meta.methods` naming the proofs the account can give.",
|
||||
requestParams: {
|
||||
query: z.object({
|
||||
into: z.enum(["existing", "new"]).optional().meta({
|
||||
description:
|
||||
"Where the copy goes when the account the file names does not exist here. Absent: the file's own account, which has to exist.",
|
||||
}),
|
||||
userId: z.string().max(64).optional().meta({
|
||||
description: "With `into=existing`: the account's id.",
|
||||
}),
|
||||
confirm: z.string().max(64).optional().meta({
|
||||
description:
|
||||
"With `into=existing`: the account's username, typed by the operator.",
|
||||
}),
|
||||
username: z.string().min(3).max(30).optional().meta({
|
||||
description:
|
||||
"With `into=new`: the new account's username (letters, digits, `_` and `-`).",
|
||||
}),
|
||||
}),
|
||||
},
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
@@ -261,6 +280,16 @@ export const adminBackupPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
"No session (`auth.missing`), or a session without a recent proof (`auth.reproof.required`, with `meta.methods`). A Bearer token lands here too: the admin gate reads only the session cookie.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"404": {
|
||||
description:
|
||||
"The account chosen with `into=existing` does not exist (`backup.target.not_found`). Nothing was stored.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"409": {
|
||||
description:
|
||||
"The chosen target cannot take the copy, and nothing was stored: a managed profile (`backup.target.managed_profile`), an account pending deletion (`backup.target.pending_deletion`), an account that already holds records (`backup.target.holds_records`, `meta.models` naming them), a username already taken (`backup.target.username_taken`), or a file whose own account is still here (`backup.owner.exists`).",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"413": {
|
||||
description:
|
||||
"Too large: over 512 MB as sent (10 MB in a form), a gzip file that expands past what any backup this server wrote does, or larger than the stored-copy limit once encrypted (`meta.errorCode` = `backup.upload.too_large`, the numbers and the setting in the message). Nothing was stored.",
|
||||
@@ -268,7 +297,7 @@ export const adminBackupPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
"422": {
|
||||
description:
|
||||
"The file was refused and nothing was stored: no file in the request, not valid JSON or not readable as gzip, failed the backup schema (`meta.issues`), an unsupported schema version, a key this server does not hold (`meta.errorCode` = `backup.key.missing`, `meta.keyIds`), or an owner account that does not exist here.",
|
||||
"The file was refused and nothing was stored: no file in the request, not valid JSON or not readable as gzip, failed the backup schema (`meta.issues`), an unsupported schema version, a key this server does not hold (`meta.errorCode` = `backup.key.missing`, `meta.keyIds`), an owner account that does not exist here (`backup.owner.missing`), a target query that does not parse (`details.issues`), or an `into=existing` whose `confirm` is not the account's username (`backup.target.unconfirmed`).",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
"429": {
|
||||
|
||||
@@ -44,6 +44,12 @@ export const adminKeys = {
|
||||
/** v1.37.20 — restore preview: the counts a stored backup file carries. */
|
||||
adminBackupSummary: (id: string) =>
|
||||
["admin", "backups", id, "summary"] as const,
|
||||
/**
|
||||
* Whether an account can take the copy of an erased account. Under the
|
||||
* backup list's prefix, so a new copy refetches it.
|
||||
*/
|
||||
adminBackupTarget: (userId: string) =>
|
||||
["admin", "backups", "target", userId] as const,
|
||||
/**
|
||||
* v1.39.1 — the restore jobs the backups console shows. Its own prefix, so
|
||||
* invalidating the backup list does not refetch the poll and vice versa.
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Where an uploaded backup goes when the account it names no longer exists.
|
||||
*
|
||||
* The upload's body is the file itself, so the choice rides in the query:
|
||||
*
|
||||
* - `into=existing&userId=<id>&confirm=<username>`: an existing account,
|
||||
* confirmed by typing its username, since the restore writes into it;
|
||||
* - `into=new&username=<name>`: a new account created for the copy.
|
||||
*
|
||||
* No query at all is the upload as it always was: the copy goes to the
|
||||
* account the file names, which has to exist.
|
||||
*/
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { accountUsernameSchema } from "@/lib/validations/auth";
|
||||
|
||||
/** The upload's refusal when the file's own account is not on this server. */
|
||||
export const BACKUP_OWNER_MISSING_CODE = "backup.owner.missing";
|
||||
/** The upload's refusal when a target was chosen for a file whose account exists. */
|
||||
export const BACKUP_OWNER_EXISTS_CODE = "backup.owner.exists";
|
||||
/** The typed username does not match the chosen account. */
|
||||
export const BACKUP_TARGET_UNCONFIRMED_CODE = "backup.target.unconfirmed";
|
||||
/** The username asked for a new account is taken. */
|
||||
export const BACKUP_TARGET_USERNAME_TAKEN_CODE = "backup.target.username_taken";
|
||||
|
||||
export const backupUploadTargetSchema = z.discriminatedUnion("into", [
|
||||
z
|
||||
.object({
|
||||
into: z.literal("existing"),
|
||||
userId: z.string().min(1).max(64),
|
||||
confirm: z.string().max(64),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
into: z.literal("new"),
|
||||
username: accountUsernameSchema,
|
||||
})
|
||||
.strict(),
|
||||
]);
|
||||
|
||||
export type BackupUploadTarget = z.infer<typeof backupUploadTargetSchema>;
|
||||
|
||||
const TARGET_PARAMS = ["into", "userId", "confirm", "username"] as const;
|
||||
|
||||
/**
|
||||
* Read the target from the upload's query. Null when the query names none of
|
||||
* its parameters; a query that names any of them is held to the schema whole.
|
||||
*/
|
||||
export function parseBackupUploadTarget(
|
||||
params: URLSearchParams,
|
||||
):
|
||||
| { success: true; data: BackupUploadTarget | null }
|
||||
| { success: false; error: z.ZodError } {
|
||||
if (!TARGET_PARAMS.some((name) => params.has(name))) {
|
||||
return { success: true, data: null };
|
||||
}
|
||||
const parsed = backupUploadTargetSchema.safeParse(
|
||||
Object.fromEntries(params.entries()),
|
||||
);
|
||||
return parsed.success
|
||||
? { success: true, data: parsed.data }
|
||||
: { success: false, error: parsed.error };
|
||||
}
|
||||
|
||||
/** The query string for a target, as the admin console sends it. */
|
||||
export function backupUploadTargetQuery(target: BackupUploadTarget): string {
|
||||
const params = new URLSearchParams(
|
||||
target.into === "existing"
|
||||
? { into: "existing", userId: target.userId, confirm: target.confirm }
|
||||
: { into: "new", username: target.username },
|
||||
);
|
||||
return params.toString();
|
||||
}
|
||||
Reference in new issue
Block a user