Skip to content

Commit e6113ba

Browse files
Add automated backup/restore and text-file versioning
Backups: - scripts/backup.sh bundles a pg_dump and the storage (+ quarantine) directories into one timestamped archive, with optional retention (BACKUP_RETENTION). It reads connection details from .env without sourcing it. MASTER_KEY is deliberately excluded and must be kept separately. - scripts/restore.sh restores the database and storage from an archive (guarded by an explicit confirmation). Verified to round-trip end to end. Versioning (text-like files: txt, md, csv, json, log, yaml, …): - Re-uploading a file under the same name in the same folder retains the previous content as a FileVersion instead of creating a duplicate. The old ciphertext blob becomes the version's, so no data is copied. - Endpoints to list, download and restore versions; restore is a metadata swap that preserves the current content as a new version. A bounded number of versions is kept (older ones pruned, blobs + quota released). - Quota accounting covers versions on upload, restore, prune, file delete and folder delete; the orphan GC now treats version blobs as live. - Drive gains a Versions action. Tests: a versioning integration test (create version, download old, restore, quota consistency). Suite now 28 API tests. Docs + checklist updated.
1 parent 15f26c5 commit e6113ba

12 files changed

Lines changed: 496 additions & 12 deletions

File tree

‎TEST-CHECKLIST.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,4 +80,24 @@ Account security lives under your email (top-right) → **Account**.
8080
- [ ] **Revoke session**: revoke another session → it is signed out (its next request fails).
8181
- [ ] **Sign out others**: "Sign out other sessions" keeps only the current device.
8282

83+
## Backups & text-file versioning (lot 3)
84+
85+
Backups (run on the server, needs `pg_dump`/`pg_restore`):
86+
87+
- [ ] **Backup**: `./scripts/backup.sh ./backups` produces a `opencoperlock-<timestamp>.tar.gz`
88+
containing `db.dump` and the storage archive.
89+
- [ ] **Restore**: `./scripts/restore.sh <archive>` (type `restore` to confirm) restores the
90+
database and storage. Verify files still download and decrypt afterwards.
91+
- [ ] **Retention**: `BACKUP_RETENTION=3 ./scripts/backup.sh` keeps only the newest 3 archives.
92+
93+
Versioning (text-like files: txt, md, csv, json, log, yml, …):
94+
95+
- [ ] **Create a version**: upload `notes.txt`, then upload a changed `notes.txt` with the
96+
same name into the same folder → the Drive still shows one file (not two).
97+
- [ ] **List/restore**: the file's **Versions** button lists prior versions; restoring one
98+
makes it current and keeps the previous current content as a new version.
99+
- [ ] **Non-text files are not versioned**: re-uploading e.g. an image with the same name
100+
creates a separate file (no versioning), as before.
101+
- [ ] **Quota**: deleting a versioned file frees the space of the file *and* its versions.
102+
83103
<!-- New features are appended below as they are built. -->
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
-- CreateTable
2+
CREATE TABLE "FileVersion" (
3+
"id" TEXT NOT NULL,
4+
"fileId" TEXT NOT NULL,
5+
"storageKey" TEXT NOT NULL,
6+
"sizeBytes" BIGINT NOT NULL,
7+
"mimeType" TEXT NOT NULL,
8+
"wrappedKey" TEXT NOT NULL,
9+
"iv" TEXT NOT NULL,
10+
"authTag" TEXT NOT NULL,
11+
"sha256" TEXT,
12+
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
13+
14+
CONSTRAINT "FileVersion_pkey" PRIMARY KEY ("id")
15+
);
16+
17+
-- CreateIndex
18+
CREATE UNIQUE INDEX "FileVersion_storageKey_key" ON "FileVersion"("storageKey");
19+
20+
-- CreateIndex
21+
CREATE INDEX "FileVersion_fileId_idx" ON "FileVersion"("fileId");
22+
23+
-- AddForeignKey
24+
ALTER TABLE "FileVersion" ADD CONSTRAINT "FileVersion_fileId_fkey" FOREIGN KEY ("fileId") REFERENCES "FileObject"("id") ON DELETE CASCADE ON UPDATE CASCADE;

‎apps/api/prisma/schema.prisma‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,12 +152,31 @@ model FileObject {
152152
avStatus AvStatus @default(PENDING)
153153
createdAt DateTime @default(now())
154154
155-
shares ShareLink[]
155+
shares ShareLink[]
156+
versions FileVersion[]
156157
157158
@@index([ownerId])
158159
@@index([folderId])
159160
}
160161

162+
// A prior revision of a SERVER-mode file (kept for text-like files). Holds its own
163+
// ciphertext blob and crypto material, so restoring is just a metadata swap.
164+
model FileVersion {
165+
id String @id @default(cuid())
166+
fileId String
167+
file FileObject @relation(fields: [fileId], references: [id], onDelete: Cascade)
168+
storageKey String @unique
169+
sizeBytes BigInt
170+
mimeType String
171+
wrappedKey String
172+
iv String
173+
authTag String
174+
sha256 String?
175+
createdAt DateTime @default(now())
176+
177+
@@index([fileId])
178+
}
179+
161180
model QuickUploadCode {
162181
id String @id @default(cuid())
163182
code String @unique

‎apps/api/src/routes/files.ts‎

Lines changed: 110 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,12 @@ import {
99
ingestPlaintext,
1010
} from '../services/ingest.js';
1111
import { decryptServerFile } from '../services/download.js';
12+
import {
13+
findVersionTarget,
14+
isVersionable,
15+
pruneVersions,
16+
snapshotVersion,
17+
} from '../services/versioning.js';
1218
import { adjustUsage, remainingAllowance } from '../services/quota.js';
1319
import { toPublicFile } from '../lib/serialize.js';
1420
import { audit } from '../services/audit.js';
@@ -52,6 +58,35 @@ export const fileRoutes: FastifyPluginAsync = async (app) => {
5258
try {
5359
const result = await ingestPlaintext(app.ctx, part.file, { maxBytes: allowance, storageKey });
5460

61+
// Versioning: re-uploading a text-like file under the same name keeps the old
62+
// content as a version instead of creating a duplicate row.
63+
const existing = isVersionable(part.filename, part.mimetype)
64+
? await findVersionTarget(req.user!.id, folderId ?? null, part.filename)
65+
: null;
66+
67+
if (existing) {
68+
await snapshotVersion(existing);
69+
const file = await prisma.fileObject.update({
70+
where: { id: existing.id },
71+
data: {
72+
sizeBytes: BigInt(result.sizeBytes),
73+
mimeType: part.mimetype,
74+
storageKey: result.storageKey,
75+
wrappedKey: result.wrappedKey,
76+
iv: result.iv,
77+
authTag: result.authTag,
78+
sha256: result.sha256,
79+
avStatus: result.avStatus,
80+
},
81+
});
82+
// New content adds to usage; the retained version keeps the old size.
83+
await adjustUsage(req.user!.id, result.sizeBytes);
84+
const freed = await pruneVersions(app.ctx, file.id);
85+
if (freed > 0) await adjustUsage(req.user!.id, -freed);
86+
await audit(req, 'file.version', { target: file.id });
87+
return reply.code(201).send({ file: toPublicFile(file) });
88+
}
89+
5590
const file = await prisma.fileObject.create({
5691
data: {
5792
ownerId: req.user!.id,
@@ -139,15 +174,87 @@ export const fileRoutes: FastifyPluginAsync = async (app) => {
139174
return { file: toPublicFile(updated) };
140175
});
141176

142-
// DELETE /files/:id — remove the blob and release quota.
177+
// GET /files/:id/versions — list retained prior versions (newest first).
178+
app.get('/:id/versions', async (req, reply) => {
179+
const { id } = req.params as { id: string };
180+
const file = await prisma.fileObject.findFirst({ where: { id, ownerId: req.user!.id } });
181+
if (!file) return reply.code(404).send({ error: 'File not found' });
182+
const versions = await prisma.fileVersion.findMany({
183+
where: { fileId: id },
184+
orderBy: { createdAt: 'desc' },
185+
select: { id: true, sizeBytes: true, sha256: true, createdAt: true },
186+
});
187+
return {
188+
versions: versions.map((v) => ({
189+
id: v.id,
190+
sizeBytes: Number(v.sizeBytes),
191+
sha256: v.sha256,
192+
createdAt: v.createdAt.toISOString(),
193+
})),
194+
};
195+
});
196+
197+
// GET /files/:id/versions/:versionId/download — decrypt and stream a past version.
198+
app.get('/:id/versions/:versionId/download', async (req, reply) => {
199+
const { id, versionId } = req.params as { id: string; versionId: string };
200+
const file = await prisma.fileObject.findFirst({ where: { id, ownerId: req.user!.id } });
201+
if (!file) return reply.code(404).send({ error: 'File not found' });
202+
const version = await prisma.fileVersion.findFirst({ where: { id: versionId, fileId: id } });
203+
if (!version) return reply.code(404).send({ error: 'Version not found' });
204+
reply
205+
.header('Content-Type', version.mimeType)
206+
.header('Content-Length', Number(version.sizeBytes))
207+
.header('Content-Disposition', `attachment; filename="${encodeURIComponent(file.name)}"`);
208+
return reply.send(decryptServerFile(app.ctx, version));
209+
});
210+
211+
// POST /files/:id/versions/:versionId/restore — make a past version current. The current
212+
// content is first snapshotted as a new version, so nothing is lost (a metadata swap).
213+
app.post('/:id/versions/:versionId/restore', async (req, reply) => {
214+
const { id, versionId } = req.params as { id: string; versionId: string };
215+
const file = await prisma.fileObject.findFirst({ where: { id, ownerId: req.user!.id } });
216+
if (!file) return reply.code(404).send({ error: 'File not found' });
217+
const version = await prisma.fileVersion.findFirst({ where: { id: versionId, fileId: id } });
218+
if (!version) return reply.code(404).send({ error: 'Version not found' });
219+
220+
await snapshotVersion(file);
221+
const updated = await prisma.fileObject.update({
222+
where: { id },
223+
data: {
224+
sizeBytes: version.sizeBytes,
225+
mimeType: version.mimeType,
226+
storageKey: version.storageKey,
227+
wrappedKey: version.wrappedKey,
228+
iv: version.iv,
229+
authTag: version.authTag,
230+
sha256: version.sha256,
231+
},
232+
});
233+
// The restored version's blob is now the live content; remove its version row.
234+
await prisma.fileVersion.delete({ where: { id: versionId } });
235+
// Net usage change is zero: the old current blob becomes a version while the restored
236+
// version's blob becomes current — both blobs remain referenced. Only pruning frees space.
237+
const freed = await pruneVersions(app.ctx, id);
238+
if (freed > 0) await adjustUsage(req.user!.id, -freed);
239+
await audit(req, 'file.version.restore', { target: id });
240+
return { file: toPublicFile(updated) };
241+
});
242+
243+
// DELETE /files/:id — remove the blob, its versions, and release all their quota.
143244
app.delete('/:id', async (req, reply) => {
144245
const { id } = req.params as { id: string };
145246
const file = await prisma.fileObject.findFirst({ where: { id, ownerId: req.user!.id } });
146247
if (!file) return reply.code(404).send({ error: 'File not found' });
147248

249+
const versions = await prisma.fileVersion.findMany({ where: { fileId: id } });
250+
let freed = Number(file.sizeBytes);
148251
await app.ctx.storage.delete(file.storageKey).catch((err) => req.log.warn({ err }, 'blob delete failed'));
149-
await prisma.fileObject.delete({ where: { id: file.id } });
150-
await adjustUsage(req.user!.id, -Number(file.sizeBytes));
252+
for (const v of versions) {
253+
await app.ctx.storage.delete(v.storageKey).catch(() => {});
254+
freed += Number(v.sizeBytes);
255+
}
256+
await prisma.fileObject.delete({ where: { id: file.id } }); // cascades version rows
257+
await adjustUsage(req.user!.id, -freed);
151258
await audit(req, 'file.delete', { target: file.id });
152259
return { ok: true };
153260
});

‎apps/api/src/routes/folders.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,11 +105,17 @@ export const folderRoutes: FastifyPluginAsync = async (app) => {
105105

106106
const ids = await collectSubtree(root.id, req.user!.id);
107107
const files = await prisma.fileObject.findMany({ where: { folderId: { in: ids } } });
108+
const fileIds = files.map((f) => f.id);
109+
const versions = await prisma.fileVersion.findMany({ where: { fileId: { in: fileIds } } });
108110
let freed = 0;
109111
for (const file of files) {
110112
await app.ctx.storage.delete(file.storageKey).catch((err) => req.log.warn({ err }, 'blob delete failed'));
111113
freed += Number(file.sizeBytes);
112114
}
115+
for (const v of versions) {
116+
await app.ctx.storage.delete(v.storageKey).catch(() => {});
117+
freed += Number(v.sizeBytes);
118+
}
113119
await prisma.fileObject.deleteMany({ where: { folderId: { in: ids } } });
114120
if (freed > 0) await adjustUsage(req.user!.id, -freed);
115121
// Deleting the root cascades the subfolder rows (FolderChildren onDelete: Cascade).

‎apps/api/src/services/maintenance.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,15 @@ export async function collectOrphans(
5151
log: FastifyBaseLogger,
5252
): Promise<OrphanResult> {
5353
if (!ctx.storage.list) return { scanned: 0, deleted: 0 };
54-
const known = new Set(
55-
(await prisma.fileObject.findMany({ select: { storageKey: true } })).map((f) => f.storageKey),
56-
);
54+
// Known = live file blobs + retained version blobs. Anything else is an orphan.
55+
const [files, versions] = await Promise.all([
56+
prisma.fileObject.findMany({ select: { storageKey: true } }),
57+
prisma.fileVersion.findMany({ select: { storageKey: true } }),
58+
]);
59+
const known = new Set<string>([
60+
...files.map((f) => f.storageKey),
61+
...versions.map((v) => v.storageKey),
62+
]);
5763
const cutoff = Date.now() - graceHours * 60 * 60 * 1000;
5864
let scanned = 0;
5965
let deleted = 0;
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/**
2+
* Lightweight versioning for text-like files. When a file is re-uploaded under the same
3+
* name in the same folder, its previous content is retained as a `FileVersion` (no blob
4+
* copy — the old ciphertext blob simply becomes the version's). Only a bounded number of
5+
* versions are kept; older ones are pruned and their blobs/quota released.
6+
*/
7+
import type { FileObject } from '@prisma/client';
8+
import { mimeKind } from '@opencoperlock/shared';
9+
import type { AppContext } from '../context.js';
10+
import { prisma } from '../db.js';
11+
12+
const MAX_VERSIONS = 10;
13+
const VERSIONABLE_EXTENSIONS = new Set([
14+
'txt', 'md', 'markdown', 'csv', 'tsv', 'json', 'log', 'xml', 'yml', 'yaml', 'ini', 'conf',
15+
]);
16+
17+
/** Whether a file should be versioned, by MIME kind or a known text extension. */
18+
export function isVersionable(name: string, mime: string): boolean {
19+
if (mimeKind(mime) === 'text') return true;
20+
const ext = name.includes('.') ? name.split('.').pop()!.toLowerCase() : '';
21+
return VERSIONABLE_EXTENSIONS.has(ext);
22+
}
23+
24+
/** The most recent SERVER file with this name in this folder, or null. */
25+
export function findVersionTarget(ownerId: string, folderId: string | null, name: string) {
26+
return prisma.fileObject.findFirst({
27+
where: { ownerId, folderId, name, encMode: 'SERVER' },
28+
orderBy: { createdAt: 'desc' },
29+
});
30+
}
31+
32+
/**
33+
* Snapshot `current`'s existing content as a version (reusing its blob), so the caller can
34+
* then overwrite the FileObject with new content. Returns nothing; the row is created.
35+
*/
36+
export async function snapshotVersion(current: FileObject): Promise<void> {
37+
if (!current.wrappedKey || !current.iv || !current.authTag) return; // not server-encrypted
38+
await prisma.fileVersion.create({
39+
data: {
40+
fileId: current.id,
41+
storageKey: current.storageKey,
42+
sizeBytes: current.sizeBytes,
43+
mimeType: current.mimeType,
44+
wrappedKey: current.wrappedKey,
45+
iv: current.iv,
46+
authTag: current.authTag,
47+
sha256: current.sha256,
48+
},
49+
});
50+
}
51+
52+
/** Delete versions beyond MAX_VERSIONS (oldest first). Returns bytes freed. */
53+
export async function pruneVersions(ctx: AppContext, fileId: string): Promise<number> {
54+
const versions = await prisma.fileVersion.findMany({
55+
where: { fileId },
56+
orderBy: { createdAt: 'desc' },
57+
});
58+
const excess = versions.slice(MAX_VERSIONS);
59+
let freed = 0;
60+
for (const v of excess) {
61+
await ctx.storage.delete(v.storageKey).catch(() => {});
62+
await prisma.fileVersion.delete({ where: { id: v.id } });
63+
freed += Number(v.sizeBytes);
64+
}
65+
return freed;
66+
}
67+
68+
/** Total bytes held by a file's versions (for quota accounting on delete). */
69+
export async function versionsBytes(fileId: string): Promise<number> {
70+
const agg = await prisma.fileVersion.aggregate({
71+
where: { fileId },
72+
_sum: { sizeBytes: true },
73+
});
74+
return Number(agg._sum.sizeBytes ?? 0n);
75+
}

‎apps/api/test/integration.test.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,61 @@ runIf('API integration', () => {
131131
});
132132
});
133133

134+
describe('text file versioning', () => {
135+
it('keeps prior content as versions and restores them', async () => {
136+
const user = await createUser({ email: 'v2@test.local', password: 'correct-horse-battery' });
137+
const auth = await login(app, 'v2@test.local', 'correct-horse-battery');
138+
139+
const up1 = await uploadFile(app, '/files', auth, 'notes.txt', Buffer.from('version one'));
140+
const fileId = up1.json().file.id;
141+
// Re-upload same name -> creates a version, not a duplicate.
142+
await uploadFile(app, '/files', auth, 'notes.txt', Buffer.from('version two!!'));
143+
144+
const list = await app.inject({ method: 'GET', url: `/files`, headers: { cookie: auth.cookie } });
145+
expect(list.json().files).toHaveLength(1); // still one file, not two
146+
147+
const versions = await app.inject({
148+
method: 'GET',
149+
url: `/files/${fileId}/versions`,
150+
headers: { cookie: auth.cookie },
151+
});
152+
expect(versions.json().versions).toHaveLength(1);
153+
const versionId = versions.json().versions[0].id;
154+
155+
// Current content is "version two!!".
156+
const cur = await app.inject({ method: 'GET', url: `/files/${fileId}/download`, headers: { cookie: auth.cookie } });
157+
expect(Buffer.from(cur.rawPayload).toString()).toBe('version two!!');
158+
159+
// The version downloads the old bytes.
160+
const vdl = await app.inject({
161+
method: 'GET',
162+
url: `/files/${fileId}/versions/${versionId}/download`,
163+
headers: { cookie: auth.cookie },
164+
});
165+
expect(Buffer.from(vdl.rawPayload).toString()).toBe('version one');
166+
167+
// Restore the version -> current becomes "version one".
168+
const restore = await app.inject({
169+
method: 'POST',
170+
url: `/files/${fileId}/versions/${versionId}/restore`,
171+
headers: authHeaders(auth),
172+
});
173+
expect(restore.statusCode).toBe(200);
174+
const after = await app.inject({ method: 'GET', url: `/files/${fileId}/download`, headers: { cookie: auth.cookie } });
175+
expect(Buffer.from(after.rawPayload).toString()).toBe('version one');
176+
177+
// Usage reflects current + retained versions (all small, non-zero) and stays consistent.
178+
const u = await prisma.user.findUniqueOrThrow({ where: { id: user.id } });
179+
const current = await prisma.fileObject.findUniqueOrThrow({ where: { id: fileId } });
180+
const versionSum = await prisma.fileVersion.aggregate({
181+
where: { fileId },
182+
_sum: { sizeBytes: true },
183+
});
184+
const expected = Number(current.sizeBytes) + Number(versionSum._sum.sizeBytes ?? 0n);
185+
expect(Number(u.usedBytes)).toBe(expected);
186+
});
187+
});
188+
134189
describe('folders: rename, move, cycle protection', () => {
135190
it('prevents moving a folder into its own subtree', async () => {
136191
await createUser({ email: 'f@test.local', password: 'correct-horse-battery' });

0 commit comments

Comments
 (0)