Skip to content

Commit 0c75f31

Browse files
Add share links (file & folder) with preview pages and access modes
Recipients can open a share without an account (a session is honoured for account-restricted links). Model & API: - ShareLink (file or folder target; ZK targets refused). View types RAW (direct file) and PAGE (preview/landing). Access modes PUBLIC, CODE (argon2-hashed), AUTHENTICATED. Optional expiry, max-downloads (atomic, concurrency-safe) and a view-only (download-disabled) flag. - Owner endpoints: POST/GET/DELETE /shares. - Public endpoints under /s: GET /s/:token (metadata + access decision) and GET /s/:token/file/:fileId (stream; inline previews don't count toward the cap). Access policy enforced identically for metadata and bytes. Web: - /s/[token] recipient page with image/PDF/text/audio/video preview, code and sign-in prompts, expiry/exhaustion states, and a folder listing. - Share action on Drive rows; a Shares management tab (copy/open/revoke). - CSP widened to allow previews streamed from the API origin. Tests: 5 integration tests (public, code, authenticated, max-downloads + revoke, ZK guard). Suite now 16 API tests; checklist updated.
1 parent a43d2de commit 0c75f31

20 files changed

Lines changed: 958 additions & 4 deletions

File tree

‎TEST-CHECKLIST.md‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# OpenCoperLock — manual test checklist
2+
3+
This sheet tracks what to verify after the current round of work. It is filled in as
4+
features land. Branch: `claude/opencoplerlock-cloud-toolkit-ofdqng`.
5+
6+
How to run locally:
7+
8+
```bash
9+
pnpm install
10+
# Postgres reachable via DATABASE_URL, then:
11+
pnpm --filter @opencoperlock/api prisma:migrate
12+
pnpm --filter @opencoperlock/api db:seed
13+
pnpm dev # web on :3000, api on :4000
14+
```
15+
16+
Automated gates (should all pass):
17+
18+
```bash
19+
pnpm -r typecheck && pnpm -r lint
20+
DATABASE_URL=postgresql://… pnpm -r test # 40 shared + integration suite
21+
```
22+
23+
---
24+
25+
## Already shipped (earlier rounds)
26+
27+
- [ ] **Drive**: upload, download (bytes match), delete frees quota, folders, breadcrumb.
28+
- [ ] **Encryption at rest**: uploaded file on disk is ciphertext (no plaintext leak).
29+
- [ ] **Quick-Upload**: admin creates a code; guest at `/q` uploads without login.
30+
- [ ] **Remote-Upload**: paste a public URL → file appears; a private/localhost URL is rejected.
31+
- [ ] **Zero-Knowledge vault**: create vault, upload (encrypted in browser), download round-trips.
32+
- [ ] **Admin**: create user, set quota, global cap, audit log.
33+
- [ ] **Login throttle**: 5 wrong passwords → account locked (429) with backoff.
34+
- [ ] **Quick-Upload ban**: repeated wrong code passwords from one IP → temporary ban.
35+
- [ ] **Rename / move**: rename and move files and folders; moving a folder into its own
36+
subtree is rejected.
37+
- [ ] **Health**: `GET /ready` returns 200 when DB+storage ok; if antivirus is enabled but
38+
down, signed-in users see a banner.
39+
- [ ] **Maintenance**: `POST /admin/maintenance` reconciles quota usage and prunes logs.
40+
41+
---
42+
43+
## Share links (lot 1)
44+
45+
Create from the Drive: each file and folder row has a **Share** button. It asks for the
46+
access mode, view type (preview page vs raw file), an optional code, and an optional expiry,
47+
then copies the link. Manage them under the **Shares** tab.
48+
49+
- [ ] **Public file share, preview page**: open the link in a private window (no login) →
50+
see the file name, size and a preview (image/PDF/text/audio/video), plus Download.
51+
- [ ] **Raw file link**: choosing "raw" makes the link open the file directly (image/PDF
52+
shows inline; other types download).
53+
- [ ] **Code-protected share**: the recipient is asked for the code; wrong code is refused;
54+
correct code reveals the file and allows download.
55+
- [ ] **Account-only share**: a signed-out recipient is told to sign in; a signed-in user
56+
of the instance can open it.
57+
- [ ] **Folder share**: the recipient page lists the folder's files, each downloadable.
58+
- [ ] **Expiry**: a link past its expiry shows "Link expired".
59+
- [ ] **Max downloads**: after the limit, further downloads return "expired" (inline
60+
previews don't count toward the limit).
61+
- [ ] **Revoke**: revoking in the Shares tab makes the link 404 immediately.
62+
- [ ] **ZK guard**: a vault file/folder cannot be shared (the Share action errors).
63+
64+
<!-- New features are appended below as they are built. -->
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
-- CreateEnum
2+
CREATE TYPE "ShareViewType" AS ENUM ('RAW', 'PAGE');
3+
4+
-- CreateEnum
5+
CREATE TYPE "ShareAccess" AS ENUM ('PUBLIC', 'CODE', 'AUTHENTICATED');
6+
7+
-- CreateTable
8+
CREATE TABLE "ShareLink" (
9+
"id" TEXT NOT NULL,
10+
"token" TEXT NOT NULL,
11+
"ownerId" TEXT NOT NULL,
12+
"fileId" TEXT,
13+
"folderId" TEXT,
14+
"viewType" "ShareViewType" NOT NULL DEFAULT 'PAGE',
15+
"access" "ShareAccess" NOT NULL DEFAULT 'PUBLIC',
16+
"codeHash" TEXT,
17+
"allowDownload" BOOLEAN NOT NULL DEFAULT true,
18+
"expiresAt" TIMESTAMP(3),
19+
"maxDownloads" INTEGER,
20+
"downloadCount" INTEGER NOT NULL DEFAULT 0,
21+
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
22+
23+
CONSTRAINT "ShareLink_pkey" PRIMARY KEY ("id")
24+
);
25+
26+
-- CreateIndex
27+
CREATE UNIQUE INDEX "ShareLink_token_key" ON "ShareLink"("token");
28+
29+
-- CreateIndex
30+
CREATE INDEX "ShareLink_ownerId_idx" ON "ShareLink"("ownerId");
31+
32+
-- CreateIndex
33+
CREATE INDEX "ShareLink_token_idx" ON "ShareLink"("token");
34+
35+
-- AddForeignKey
36+
ALTER TABLE "ShareLink" ADD CONSTRAINT "ShareLink_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
37+
38+
-- AddForeignKey
39+
ALTER TABLE "ShareLink" ADD CONSTRAINT "ShareLink_fileId_fkey" FOREIGN KEY ("fileId") REFERENCES "FileObject"("id") ON DELETE CASCADE ON UPDATE CASCADE;
40+
41+
-- AddForeignKey
42+
ALTER TABLE "ShareLink" ADD CONSTRAINT "ShareLink_folderId_fkey" FOREIGN KEY ("folderId") REFERENCES "Folder"("id") ON DELETE CASCADE ON UPDATE CASCADE;

‎apps/api/prisma/schema.prisma‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,17 @@ enum JobStatus {
3434
FAILED
3535
}
3636

37+
enum ShareViewType {
38+
RAW
39+
PAGE
40+
}
41+
42+
enum ShareAccess {
43+
PUBLIC
44+
CODE
45+
AUTHENTICATED
46+
}
47+
3748
model User {
3849
id String @id @default(cuid())
3950
email String @unique
@@ -53,6 +64,7 @@ model User {
5364
quickCodes QuickUploadCode[]
5465
remoteJobs RemoteUploadJob[]
5566
auditLogs AuditLog[]
67+
shares ShareLink[]
5668
5769
@@index([email])
5870
}
@@ -81,7 +93,8 @@ model Folder {
8193
isZeroKnowledge Boolean @default(false)
8294
createdAt DateTime @default(now())
8395
84-
files FileObject[]
96+
files FileObject[]
97+
shares ShareLink[]
8598
8699
@@unique([ownerId, parentId, name])
87100
@@index([ownerId])
@@ -120,6 +133,8 @@ model FileObject {
120133
avStatus AvStatus @default(PENDING)
121134
createdAt DateTime @default(now())
122135
136+
shares ShareLink[]
137+
123138
@@index([ownerId])
124139
@@index([folderId])
125140
}
@@ -204,3 +219,28 @@ model Setting {
204219
globalStorageCapBytes BigInt @default(0)
205220
updatedAt DateTime @updatedAt
206221
}
222+
223+
// A shareable link to a SERVER-mode file or folder. ZK targets can't be shared (the
224+
// server can't decrypt them). The opaque `token` is the URL slug.
225+
model ShareLink {
226+
id String @id @default(cuid())
227+
token String @unique
228+
ownerId String
229+
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
230+
fileId String?
231+
file FileObject? @relation(fields: [fileId], references: [id], onDelete: Cascade)
232+
folderId String?
233+
folder Folder? @relation(fields: [folderId], references: [id], onDelete: Cascade)
234+
viewType ShareViewType @default(PAGE)
235+
access ShareAccess @default(PUBLIC)
236+
// argon2 hash of the code, when access = CODE
237+
codeHash String?
238+
allowDownload Boolean @default(true)
239+
expiresAt DateTime?
240+
maxDownloads Int?
241+
downloadCount Int @default(0)
242+
createdAt DateTime @default(now())
243+
244+
@@index([ownerId])
245+
@@index([token])
246+
}

‎apps/api/src/lib/serialize.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,15 @@ import type {
88
Folder,
99
QuickUploadCode,
1010
RemoteUploadJob,
11+
ShareLink,
1112
User,
1213
} from '@prisma/client';
1314
import type {
1415
PublicFile,
1516
PublicFolder,
1617
PublicQuickCode,
1718
PublicRemoteJob,
19+
PublicShare,
1820
PublicUser,
1921
} from '@opencoperlock/shared';
2022

@@ -69,6 +71,23 @@ export function toPublicQuickCode(c: QuickUploadCode): PublicQuickCode {
6971
};
7072
}
7173

74+
export function toPublicShare(s: ShareLink, targetName: string): PublicShare {
75+
return {
76+
id: s.id,
77+
token: s.token,
78+
fileId: s.fileId,
79+
folderId: s.folderId,
80+
targetName,
81+
viewType: s.viewType,
82+
access: s.access,
83+
allowDownload: s.allowDownload,
84+
expiresAt: s.expiresAt ? s.expiresAt.toISOString() : null,
85+
maxDownloads: s.maxDownloads,
86+
downloadCount: s.downloadCount,
87+
createdAt: s.createdAt.toISOString(),
88+
};
89+
}
90+
7291
export function toPublicRemoteJob(j: RemoteUploadJob): PublicRemoteJob {
7392
return {
7493
id: j.id,
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/**
2+
* Public recipient endpoints for share links (no authentication required, though an
3+
* authenticated session is honoured for AUTHENTICATED-mode shares). Mounted under /s.
4+
*
5+
* Access policy (expiry, code, sign-in, download cap, download-disabled) is enforced
6+
* identically here for both metadata and bytes via services/share.ts. A `code` is passed
7+
* as a query parameter so these stay simple GETs (no CSRF surface).
8+
*/
9+
import type { FastifyPluginAsync } from 'fastify';
10+
import type { PublicShareView } from '@opencoperlock/shared';
11+
import { prisma } from '../db.js';
12+
import { decideAccess, isExhausted, isExpired, shareEntries, shareFile } from '../services/share.js';
13+
import { decryptServerFile } from '../services/download.js';
14+
import { audit } from '../services/audit.js';
15+
16+
export const sharePublicRoutes: FastifyPluginAsync = async (app) => {
17+
// GET /s/:token — recipient metadata. Returns entries only once access is granted.
18+
app.get('/:token', async (req, reply) => {
19+
const { token } = req.params as { token: string };
20+
const { code } = req.query as { code?: string };
21+
const share = await prisma.shareLink.findUnique({ where: { token } });
22+
if (!share) return reply.code(404).send({ error: 'Link not found' });
23+
24+
const base: PublicShareView = {
25+
token: share.token,
26+
viewType: share.viewType,
27+
access: share.access,
28+
allowDownload: share.allowDownload,
29+
isFolder: share.folderId !== null,
30+
};
31+
32+
if (isExpired(share) || isExhausted(share)) {
33+
return { ...base, expired: true };
34+
}
35+
36+
const decision = await decideAccess(share, { code, userId: req.user?.id ?? null });
37+
if (!decision.allowed) {
38+
return { ...base, requiresCode: decision.requiresCode, requiresAuth: decision.requiresAuth };
39+
}
40+
41+
const entries = await shareEntries(share);
42+
return share.folderId ? { ...base, entries } : { ...base, file: entries[0] };
43+
});
44+
45+
// GET /s/:token/file/:fileId — stream a shared file. `inline=1` previews without
46+
// counting against the download cap; otherwise it's an attachment and is counted.
47+
app.get('/:token/file/:fileId', async (req, reply) => {
48+
const { token, fileId } = req.params as { token: string; fileId: string };
49+
const { code, inline } = req.query as { code?: string; inline?: string };
50+
const isInline = inline === '1';
51+
52+
const share = await prisma.shareLink.findUnique({ where: { token } });
53+
if (!share) return reply.code(404).send({ error: 'Link not found' });
54+
if (isExpired(share) || isExhausted(share)) return reply.code(410).send({ error: 'Link expired' });
55+
56+
const decision = await decideAccess(share, { code, userId: req.user?.id ?? null });
57+
if (!decision.allowed) {
58+
return reply.code(decision.requiresAuth ? 401 : 403).send({ error: 'Access denied' });
59+
}
60+
if (!share.allowDownload && !isInline) {
61+
return reply.code(403).send({ error: 'Downloads are disabled for this link' });
62+
}
63+
64+
const file = await shareFile(share, fileId);
65+
if (!file) return reply.code(404).send({ error: 'File not found' });
66+
if (file.encMode === 'ZK') return reply.code(400).send({ error: 'Unsupported' });
67+
68+
if (!isInline) {
69+
// Count the download atomically and respect the cap under concurrency.
70+
const claimed = await prisma.shareLink.updateMany({
71+
where: {
72+
id: share.id,
73+
OR: [{ maxDownloads: null }, { downloadCount: { lt: share.maxDownloads ?? 0 } }],
74+
},
75+
data: { downloadCount: { increment: 1 } },
76+
});
77+
if (claimed.count === 0) return reply.code(410).send({ error: 'Link expired' });
78+
await audit(req, 'share.download', { actorId: null, target: share.id });
79+
}
80+
81+
const disposition = isInline ? 'inline' : 'attachment';
82+
reply
83+
.header('Content-Type', file.mimeType)
84+
.header('Content-Length', Number(file.sizeBytes))
85+
.header('Content-Disposition', `${disposition}; filename="${encodeURIComponent(file.name)}"`);
86+
return reply.send(decryptServerFile(app.ctx, file));
87+
});
88+
};

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

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/**
2+
* Owner-facing share management. Create a link to a SERVER-mode file or folder, list your
3+
* links, and revoke them. ZK targets are refused because the server cannot serve their
4+
* plaintext. The public recipient endpoints live in routes/share-public.ts.
5+
*/
6+
import type { FastifyPluginAsync } from 'fastify';
7+
import { createShareSchema, randomToken } from '@opencoperlock/shared';
8+
import { prisma } from '../db.js';
9+
import { parseOr400 } from '../lib/validate.js';
10+
import { toPublicShare } from '../lib/serialize.js';
11+
import { hashPassword } from '../services/password.js';
12+
import { audit } from '../services/audit.js';
13+
14+
export const shareRoutes: FastifyPluginAsync = async (app) => {
15+
app.addHook('preHandler', app.requireAuth);
16+
17+
// GET /shares — the user's links, with the target's display name.
18+
app.get('/', async (req) => {
19+
const shares = await prisma.shareLink.findMany({
20+
where: { ownerId: req.user!.id },
21+
orderBy: { createdAt: 'desc' },
22+
include: { file: { select: { name: true } }, folder: { select: { name: true } } },
23+
});
24+
return {
25+
shares: shares.map((s) =>
26+
toPublicShare(s, s.file?.name ?? s.folder?.name ?? '(deleted)'),
27+
),
28+
};
29+
});
30+
31+
// POST /shares — create a share for a file or folder.
32+
app.post('/', async (req, reply) => {
33+
const body = parseOr400(reply, createShareSchema, req.body);
34+
if (!body) return;
35+
36+
let targetName: string;
37+
if (body.fileId) {
38+
const file = await prisma.fileObject.findFirst({
39+
where: { id: body.fileId, ownerId: req.user!.id },
40+
});
41+
if (!file) return reply.code(404).send({ error: 'File not found' });
42+
if (file.encMode === 'ZK') {
43+
return reply.code(400).send({ error: 'Zero-knowledge files cannot be shared' });
44+
}
45+
targetName = file.name;
46+
} else {
47+
const folder = await prisma.folder.findFirst({
48+
where: { id: body.folderId!, ownerId: req.user!.id },
49+
});
50+
if (!folder) return reply.code(404).send({ error: 'Folder not found' });
51+
if (folder.isZeroKnowledge) {
52+
return reply.code(400).send({ error: 'Vault folders cannot be shared' });
53+
}
54+
targetName = folder.name;
55+
}
56+
57+
const share = await prisma.shareLink.create({
58+
data: {
59+
token: randomToken(18),
60+
ownerId: req.user!.id,
61+
fileId: body.fileId ?? null,
62+
folderId: body.folderId ?? null,
63+
viewType: body.viewType,
64+
access: body.accessMode,
65+
codeHash: body.accessMode === 'CODE' && body.code ? await hashPassword(body.code) : null,
66+
allowDownload: body.allowDownload ?? true,
67+
expiresAt: body.expiresAt ?? null,
68+
maxDownloads: body.maxDownloads ?? null,
69+
},
70+
});
71+
await audit(req, 'share.create', { target: share.id });
72+
return reply.code(201).send({ share: toPublicShare(share, targetName) });
73+
});
74+
75+
// DELETE /shares/:id — revoke a link.
76+
app.delete('/:id', async (req, reply) => {
77+
const { id } = req.params as { id: string };
78+
const share = await prisma.shareLink.findFirst({ where: { id, ownerId: req.user!.id } });
79+
if (!share) return reply.code(404).send({ error: 'Share not found' });
80+
await prisma.shareLink.delete({ where: { id } });
81+
await audit(req, 'share.delete', { target: id });
82+
return { ok: true };
83+
});
84+
};

0 commit comments

Comments
 (0)