|
| 1 | +/** |
| 2 | + * Public REST API (v1), authenticated by a personal API token: `Authorization: Bearer ocl_…`. |
| 3 | + * Lets a user's own scripts/automations list folders, upload files into a folder, and download |
| 4 | + * them — scoped to the token's permissions (read/write) and optional folder restriction. |
| 5 | + * |
| 6 | + * Zero-Knowledge vaults are encrypted in the browser, so the server API cannot read or write |
| 7 | + * them; only normal (SERVER-encrypted) folders are accessible here. |
| 8 | + */ |
| 9 | +import type { FastifyPluginAsync } from 'fastify'; |
| 10 | +import { prisma } from '../db.js'; |
| 11 | +import { decryptServerFile } from '../services/download.js'; |
| 12 | +import { FileTooLargeError, InfectedFileError } from '../services/ingest.js'; |
| 13 | +import { storeUserFile, QuotaExhaustedError } from '../services/upload.js'; |
| 14 | +import { toPublicFile, toPublicFolder } from '../lib/serialize.js'; |
| 15 | +import { audit } from '../services/audit.js'; |
| 16 | + |
| 17 | +export const apiV1Routes: FastifyPluginAsync = async (app) => { |
| 18 | + // A token may be confined to one folder; everything it touches must match (MVP: exact folder). |
| 19 | + const folderAllowed = (req: { apiToken: { folderId: string | null } | null }, folderId: string | null) => |
| 20 | + !req.apiToken?.folderId || req.apiToken.folderId === folderId; |
| 21 | + |
| 22 | + // GET /me — confirm a token works and show what it can do. |
| 23 | + app.get('/me', { preHandler: app.tokenAuth('read') }, async (req) => ({ |
| 24 | + user: { id: req.user!.id, email: req.user!.email }, |
| 25 | + token: { scopes: req.apiToken!.scopes, folderId: req.apiToken!.folderId }, |
| 26 | + })); |
| 27 | + |
| 28 | + // GET /folders — list the user's normal folders. |
| 29 | + app.get('/folders', { preHandler: app.tokenAuth('read') }, async (req) => { |
| 30 | + const folders = await prisma.folder.findMany({ |
| 31 | + where: { ownerId: req.user!.id }, |
| 32 | + orderBy: { name: 'asc' }, |
| 33 | + }); |
| 34 | + return { folders: folders.map(toPublicFolder) }; |
| 35 | + }); |
| 36 | + |
| 37 | + // POST /folders — create a folder ({ name, parentId? }). |
| 38 | + app.post('/folders', { preHandler: app.tokenAuth('write') }, async (req, reply) => { |
| 39 | + const body = (req.body ?? {}) as { name?: unknown; parentId?: unknown }; |
| 40 | + const name = typeof body.name === 'string' ? body.name.trim() : ''; |
| 41 | + if (!name) return reply.code(400).send({ error: 'name is required' }); |
| 42 | + const parentId = typeof body.parentId === 'string' ? body.parentId : null; |
| 43 | + |
| 44 | + if (parentId) { |
| 45 | + const parent = await prisma.folder.findFirst({ where: { id: parentId, ownerId: req.user!.id } }); |
| 46 | + if (!parent) return reply.code(404).send({ error: 'Parent folder not found' }); |
| 47 | + if (parent.isZeroKnowledge) return reply.code(400).send({ error: 'Vault folders are not accessible via the API' }); |
| 48 | + } |
| 49 | + if (!folderAllowed(req, parentId)) return reply.code(403).send({ error: 'Token is restricted to another folder' }); |
| 50 | + |
| 51 | + const folder = await prisma.folder.create({ |
| 52 | + data: { ownerId: req.user!.id, name, parentId, isZeroKnowledge: false }, |
| 53 | + }); |
| 54 | + await audit(req, 'api.folder.create', { actorId: req.user!.id, target: folder.id }); |
| 55 | + return reply.code(201).send({ folder: toPublicFolder(folder) }); |
| 56 | + }); |
| 57 | + |
| 58 | + // GET /files?folderId= — list files in a folder (omit folderId for the account root). |
| 59 | + app.get('/files', { preHandler: app.tokenAuth('read') }, async (req, reply) => { |
| 60 | + const { folderId } = req.query as { folderId?: string }; |
| 61 | + const target = folderId ?? null; |
| 62 | + if (!folderAllowed(req, target)) return reply.code(403).send({ error: 'Token is restricted to another folder' }); |
| 63 | + if (target) { |
| 64 | + const folder = await prisma.folder.findFirst({ where: { id: target, ownerId: req.user!.id } }); |
| 65 | + if (!folder) return reply.code(404).send({ error: 'Folder not found' }); |
| 66 | + } |
| 67 | + const files = await prisma.fileObject.findMany({ |
| 68 | + where: { ownerId: req.user!.id, folderId: target, encMode: 'SERVER', deletedAt: null }, |
| 69 | + orderBy: { name: 'asc' }, |
| 70 | + }); |
| 71 | + return { files: files.map(toPublicFile) }; |
| 72 | + }); |
| 73 | + |
| 74 | + // POST /files?folderId= — upload a single file (multipart/form-data, field "file"). |
| 75 | + app.post('/files', { preHandler: app.tokenAuth('write') }, async (req, reply) => { |
| 76 | + const { folderId } = req.query as { folderId?: string }; |
| 77 | + const target = folderId ?? req.apiToken!.folderId ?? null; |
| 78 | + if (!folderAllowed(req, target)) return reply.code(403).send({ error: 'Token is restricted to another folder' }); |
| 79 | + |
| 80 | + if (target) { |
| 81 | + const folder = await prisma.folder.findFirst({ where: { id: target, ownerId: req.user!.id } }); |
| 82 | + if (!folder) return reply.code(404).send({ error: 'Folder not found' }); |
| 83 | + if (folder.isZeroKnowledge) return reply.code(400).send({ error: 'Vault folders are not accessible via the API' }); |
| 84 | + } |
| 85 | + |
| 86 | + const part = await req.file(); |
| 87 | + if (!part) return reply.code(400).send({ error: 'No file provided (multipart field "file")' }); |
| 88 | + |
| 89 | + try { |
| 90 | + const { file } = await storeUserFile(app.ctx, { |
| 91 | + ownerId: req.user!.id, |
| 92 | + folderId: target, |
| 93 | + stream: part.file, |
| 94 | + filename: part.filename, |
| 95 | + mimetype: part.mimetype, |
| 96 | + }); |
| 97 | + await audit(req, 'api.file.upload', { actorId: req.user!.id, target: file.id }); |
| 98 | + return reply.code(201).send({ file: toPublicFile(file) }); |
| 99 | + } catch (err) { |
| 100 | + if (err instanceof QuotaExhaustedError || err instanceof FileTooLargeError) { |
| 101 | + return reply.code(413).send({ error: 'Upload exceeds your available quota' }); |
| 102 | + } |
| 103 | + if (err instanceof InfectedFileError) { |
| 104 | + return reply.code(422).send({ error: `File rejected: ${err.signature}`, code: 'INFECTED' }); |
| 105 | + } |
| 106 | + throw err; |
| 107 | + } |
| 108 | + }); |
| 109 | + |
| 110 | + // GET /files/:id/download — stream a file's decrypted contents. |
| 111 | + app.get('/files/:id/download', { preHandler: app.tokenAuth('read') }, async (req, reply) => { |
| 112 | + const { id } = req.params as { id: string }; |
| 113 | + const file = await prisma.fileObject.findFirst({ |
| 114 | + where: { id, ownerId: req.user!.id, encMode: 'SERVER', deletedAt: null }, |
| 115 | + }); |
| 116 | + if (!file) return reply.code(404).send({ error: 'File not found' }); |
| 117 | + if (!folderAllowed(req, file.folderId)) return reply.code(403).send({ error: 'Token is restricted to another folder' }); |
| 118 | + |
| 119 | + reply |
| 120 | + .header('Content-Type', file.mimeType) |
| 121 | + .header('Content-Length', Number(file.sizeBytes)) |
| 122 | + .header('Content-Disposition', `attachment; filename="${encodeURIComponent(file.name)}"`); |
| 123 | + return reply.send(decryptServerFile(app.ctx, file)); |
| 124 | + }); |
| 125 | +}; |
0 commit comments