Skip to content

Create polished demo videos without editing skills. Mac/Windows/Linux

Recover multipart mismatches and recognize the Workers streaming global

webadderall066ea48c7110
diff --git a/services/recordly-share/worker/src/auth.js b/services/recordly-share/worker/src/auth.js
index 9b84a4a7..e25d3e66 100644
--- a/services/recordly-share/worker/src/auth.js
+++ b/services/recordly-share/worker/src/auth.js
@@ -1,183 +1,219 @@
// Adapted from Voom (MIT), Copyright (c) 2026 Aritro Paul.
// See ../../LICENSE and ../../../../THIRD_PARTY_NOTICES.md for attribution.
-import { generateSalt, sha256Hex, timingSafeEqual, hashRecordingPassword } from './crypto.js';
-import { errorResponse, jsonResponse, parseCookies } from './http.js';
+import { generateSalt, sha256Hex, timingSafeEqual, hashRecordingPassword } from "./crypto.js";
+import { errorResponse, jsonResponse, parseCookies } from "./http.js";
export async function isAuthorized(request, env) {
- const auth = request.headers.get('Authorization');
- if (!auth) return false;
- const match = /^Bearer ([^\s]+)$/.exec(auth);
- if (!match) return false;
- const token = match[1];
- if (token.length > 8192) return false;
- if (
- env.ALLOW_API_SECRET_UPLOADS === 'true' &&
- env.API_SECRET &&
- timingSafeEqual(token, env.API_SECRET)
- ) return true;
- if (!env.SUPABASE_URL || !env.SUPABASE_PUBLISHABLE_KEY || !env.OWNER_USER_ID) return false;
- try {
- const authBase = new URL(env.SUPABASE_URL);
- const isLocal = authBase.hostname === 'localhost' || authBase.hostname === '127.0.0.1';
- if (authBase.protocol !== 'https:' && !(authBase.protocol === 'http:' && isLocal)) return false;
- const userUrl = new URL('/auth/v1/user', authBase);
- const response = await fetch(userUrl, {
- headers: {
- Authorization: `Bearer ${token}`,
- apikey: env.SUPABASE_PUBLISHABLE_KEY,
- },
- });
- if (!response.ok) return false;
- const user = await response.json();
- return typeof user.id === 'string' && timingSafeEqual(user.id, env.OWNER_USER_ID);
- } catch {
- return false;
- }
+ const auth = request.headers.get("Authorization");
+ if (!auth) return false;
+ const match = /^Bearer ([^\s]+)$/.exec(auth);
+ if (!match) return false;
+ const token = match[1];
+ if (token.length > 8192) return false;
+ if (
+ env.ALLOW_API_SECRET_UPLOADS === "true" &&
+ env.API_SECRET &&
+ timingSafeEqual(token, env.API_SECRET)
+ )
+ return true;
+ if (!env.SUPABASE_URL || !env.SUPABASE_PUBLISHABLE_KEY || !env.OWNER_USER_ID) return false;
+ try {
+ const authBase = new URL(env.SUPABASE_URL);
+ const isLocal = authBase.hostname === "localhost" || authBase.hostname === "127.0.0.1";
+ if (authBase.protocol !== "https:" && !(authBase.protocol === "http:" && isLocal))
+ return false;
+ const userUrl = new URL("/auth/v1/user", authBase);
+ const response = await fetch(userUrl, {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ apikey: env.SUPABASE_PUBLISHABLE_KEY,
+ },
+ });
+ if (!response.ok) return false;
+ const user = await response.json();
+ return typeof user.id === "string" && timingSafeEqual(user.id, env.OWNER_USER_ID);
+ } catch {
+ return false;
+ }
}
// Hosted accounts never inherit self-host API-secret or dashboard-cookie access.
export async function hostedUser(request, env) {
- const auth = request.headers.get('Authorization') || '';
- if (!/^Bearer [^\s]+$/.test(auth) || auth.length > 8200) return null;
- if (!env.SUPABASE_URL || !env.SUPABASE_PUBLISHABLE_KEY) return null;
- try {
- const base = new URL(env.SUPABASE_URL);
- if (base.protocol !== 'https:') return null;
- const response = await fetch(new URL('/auth/v1/user', base), {
- headers: { Authorization: auth, apikey: env.SUPABASE_PUBLISHABLE_KEY },
- redirect: 'error',
- signal: AbortSignal.timeout(10000),
- });
- if (!response.ok) return null;
- const user = await response.json();
- if (typeof user.id !== 'string' || !user.id || !user.email || !user.email_confirmed_at || user.is_anonymous) return null;
- if (env.STAGING_ALLOWED_USER_ID && user.id !== env.STAGING_ALLOWED_USER_ID) return null;
- return { id: user.id };
- } catch {
- return null;
- }
+ const auth = request.headers.get("Authorization") || "";
+ if (!/^Bearer [^\s]+$/.test(auth) || auth.length > 8200) return null;
+ if (!env.SUPABASE_URL || !env.SUPABASE_PUBLISHABLE_KEY) return null;
+ try {
+ const base = new URL(env.SUPABASE_URL);
+ if (base.protocol !== "https:") return null;
+ const response = await fetch(new URL("/auth/v1/user", base), {
+ headers: { Authorization: auth, apikey: env.SUPABASE_PUBLISHABLE_KEY },
+ redirect: "error",
+ signal: AbortSignal.timeout(10000),
+ });
+ if (!response.ok) return null;
+ const user = await response.json();
+ if (
+ typeof user.id !== "string" ||
+ !user.id ||
+ !user.email ||
+ !user.email_confirmed_at ||
+ user.is_anonymous
+ )
+ return null;
+ if (env.STAGING_ALLOWED_USER_ID && user.id !== env.STAGING_ALLOWED_USER_ID) return null;
+ return { id: user.id };
+ } catch {
+ return null;
+ }
}
async function generateAuthToken(shareCode, expiresAt, apiSecret) {
- const encoder = new TextEncoder();
- const key = await crypto.subtle.importKey(
- 'raw', encoder.encode(apiSecret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']
- );
- const sig = await crypto.subtle.sign('HMAC', key, encoder.encode(shareCode + expiresAt));
- return Array.from(new Uint8Array(sig), b => b.toString(16).padStart(2, '0')).join('');
+ const encoder = new TextEncoder();
+ const key = await crypto.subtle.importKey(
+ "raw",
+ encoder.encode(apiSecret),
+ { name: "HMAC", hash: "SHA-256" },
+ false,
+ ["sign"],
+ );
+ const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(shareCode + expiresAt));
+ return Array.from(new Uint8Array(sig), (b) => b.toString(16).padStart(2, "0")).join("");
}
export async function verifyPasswordAuth(request, env, shareCode, video) {
- if (!video.password_hash) return true;
- if (!env.API_SECRET) return false;
- const cookies = parseCookies(request.headers.get('Cookie') || '');
- const authToken = cookies[`voom_auth_${shareCode}`];
- if (!authToken) return false;
- const expected = await generateAuthToken(shareCode, video.expires_at, env.API_SECRET);
- return timingSafeEqual(authToken, expected);
+ if (!video.password_hash) return true;
+ if (!env.API_SECRET) return false;
+ const cookies = parseCookies(request.headers.get("Cookie") || "");
+ const authToken = cookies[`voom_auth_${shareCode}`];
+ if (!authToken) return false;
+ const expected = await generateAuthToken(shareCode, video.expires_at, env.API_SECRET);
+ return timingSafeEqual(authToken, expected);
}
// --- Dashboard session helpers ---
export function dashboardPassword(env) {
- return env.DASHBOARD_PASSWORD || env.API_SECRET;
+ return env.DASHBOARD_PASSWORD || env.API_SECRET;
}
-export async function expectedSessionToken(env, expiresAt = Math.floor(Date.now() / 1000) + 604800) {
- const password = dashboardPassword(env);
- if (!password) throw new Error('Dashboard sign-in is not configured');
- const encoder = new TextEncoder();
- const key = await crypto.subtle.importKey(
- 'raw', encoder.encode(password), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']
- );
- const sig = await crypto.subtle.sign('HMAC', key, encoder.encode(`voom-dashboard-v2:${expiresAt}`));
- return `${expiresAt}.` + Array.from(new Uint8Array(sig), b => b.toString(16).padStart(2, '0')).join('');
+export async function expectedSessionToken(
+ env,
+ expiresAt = Math.floor(Date.now() / 1000) + 604800,
+) {
+ const password = dashboardPassword(env);
+ if (!password) throw new Error("Dashboard sign-in is not configured");
+ const encoder = new TextEncoder();
+ const key = await crypto.subtle.importKey(
+ "raw",
+ encoder.encode(password),
+ { name: "HMAC", hash: "SHA-256" },
+ false,
+ ["sign"],
+ );
+ const sig = await crypto.subtle.sign(
+ "HMAC",
+ key,
+ encoder.encode(`voom-dashboard-v2:${expiresAt}`),
+ );
+ return (
+ `${expiresAt}.` +
+ Array.from(new Uint8Array(sig), (b) => b.toString(16).padStart(2, "0")).join("")
+ );
}
export async function isDashboardAuthed(request, env) {
- if (env.HOSTED_MODE === 'true') return false;
- return (await isAuthorized(request, env)) || dashboardCookieAuthed(request, env);
+ if (env.HOSTED_MODE === "true") return false;
+ return (await isAuthorized(request, env)) || dashboardCookieAuthed(request, env);
}
export async function dashboardCookieAuthed(request, env) {
- if (!dashboardPassword(env)) return false;
- const cookies = parseCookies(request.headers.get('Cookie') || '');
- const sessionToken = cookies['voom_session'];
- if (!sessionToken || !/^\d+\.[0-9a-f]{64}$/.test(sessionToken)) return false;
- const expiresAt = Number(sessionToken.split('.')[0]);
- if (!Number.isSafeInteger(expiresAt) || expiresAt <= Math.floor(Date.now() / 1000)) return false;
- return timingSafeEqual(sessionToken, await expectedSessionToken(env, expiresAt));
+ if (!dashboardPassword(env)) return false;
+ const cookies = parseCookies(request.headers.get("Cookie") || "");
+ const sessionToken = cookies["voom_session"];
+ if (!sessionToken || !/^\d+\.[0-9a-f]{64}$/.test(sessionToken)) return false;
+ const expiresAt = Number(sessionToken.split(".")[0]);
+ if (!Number.isSafeInteger(expiresAt) || expiresAt <= Math.floor(Date.now() / 1000))
+ return false;
+ return timingSafeEqual(sessionToken, await expectedSessionToken(env, expiresAt));
}
// best-effort, per-isolate login rate limiter (real protection is the password's entropy)
const _loginAttempts = new Map();
export function checkLoginRateLimit(ip) {
- const now = Date.now();
- const entry = _loginAttempts.get(ip);
- if (entry && now < entry.resetAt) {
- if (entry.count >= 10) return false;
- entry.count++;
- } else {
- _loginAttempts.set(ip, { count: 1, resetAt: now + 5 * 60 * 1000 });
- }
- return true;
+ const now = Date.now();
+ const entry = _loginAttempts.get(ip);
+ if (entry && now < entry.resetAt) {
+ if (entry.count >= 10) return false;
+ entry.count++;
+ } else {
+ _loginAttempts.set(ip, { count: 1, resetAt: now + 5 * 60 * 1000 });
+ }
+ return true;
}
export function clearLoginRateLimit(ip) {
- _loginAttempts.delete(ip);
+ _loginAttempts.delete(ip);
}
// --- Password Verification ---
export async function handleVerifyPassword(request, env, shareCode) {
- const video = await env.DB.prepare(
- "SELECT * FROM videos WHERE share_code = ? AND upload_completed = 1 AND datetime(expires_at) > datetime('now')"
- ).bind(shareCode).first();
-
- if (!video || !video.password_hash) return errorResponse('Not found', 404);
- if (!env.API_SECRET) return errorResponse('Password protection is not configured', 503);
-
- // Brute-force protection: 10 attempts per IP per video per 5 minutes.
- const clientIP = request.headers.get('CF-Connecting-IP') || 'unknown';
- const recent = await env.DB.prepare(
- "SELECT COUNT(*) as cnt FROM password_attempts WHERE video_id = ? AND client_ip = ? AND datetime(attempted_at) > datetime('now', '-5 minutes')"
- ).bind(video.id, clientIP).first();
- if (recent && recent.cnt >= 10) return errorResponse('Too many attempts — try again later', 429);
-
- const body = await request.json();
- const password = body.password || '';
-
- const clientHash = await sha256Hex(password);
- const slowHash = video.password_hash.startsWith('pbkdf2-sha256:210000:');
- const actual = slowHash
- ? await hashRecordingPassword(clientHash, video.password_salt)
- : video.password_salt ? await sha256Hex(video.password_salt + clientHash) : clientHash;
- const matches = timingSafeEqual(actual, video.password_hash);
- if (matches && !slowHash) {
- const salt = generateSalt();
- const upgraded = await hashRecordingPassword(clientHash, salt);
- await env.DB.prepare('UPDATE videos SET password_hash = ?, password_salt = ? WHERE id = ?')
- .bind(upgraded, salt, video.id).run();
- }
-
- if (!matches) {
- await env.DB.prepare(
- 'INSERT INTO password_attempts (video_id, client_ip) VALUES (?, ?)'
- ).bind(video.id, clientIP).run();
- return jsonResponse({ error: 'Incorrect password' }, 403);
- }
-
- // Issue an HMAC session token (never the stored hash).
- const authToken = await generateAuthToken(shareCode, video.expires_at, env.API_SECRET);
- const expires = new Date(video.expires_at + 'Z');
-
- return new Response(JSON.stringify({ ok: true }), {
- status: 200,
- headers: {
- 'Content-Type': 'application/json',
- 'Set-Cookie': `voom_auth_${shareCode}=${authToken}; Path=/; Expires=${expires.toUTCString()}; HttpOnly; SameSite=Lax; Secure`,
- },
- });
+ const video = await env.DB.prepare(
+ "SELECT * FROM videos WHERE share_code = ? AND upload_completed = 1 AND datetime(expires_at) > datetime('now')",
+ )
+ .bind(shareCode)
+ .first();
+
+ if (!video || !video.password_hash) return errorResponse("Not found", 404);
+ if (!env.API_SECRET) return errorResponse("Password protection is not configured", 503);
+
+ // Brute-force protection: 10 attempts per IP per video per 5 minutes.
+ const clientIP = request.headers.get("CF-Connecting-IP") || "unknown";
+ const recent = await env.DB.prepare(
+ "SELECT COUNT(*) as cnt FROM password_attempts WHERE video_id = ? AND client_ip = ? AND datetime(attempted_at) > datetime('now', '-5 minutes')",
+ )
+ .bind(video.id, clientIP)
+ .first();
+ if (recent && recent.cnt >= 10)
+ return errorResponse("Too many attempts — try again later", 429);
+
+ const body = await request.json();
+ const password = body.password || "";
+
+ const clientHash = await sha256Hex(password);
+ const slowHash = video.password_hash.startsWith("pbkdf2-sha256:210000:");
+ const actual = slowHash
+ ? await hashRecordingPassword(clientHash, video.password_salt)
+ : video.password_salt
+ ? await sha256Hex(video.password_salt + clientHash)
+ : clientHash;
+ const matches = timingSafeEqual(actual, video.password_hash);
+ if (matches && !slowHash) {
+ const salt = generateSalt();
+ const upgraded = await hashRecordingPassword(clientHash, salt);
+ await env.DB.prepare("UPDATE videos SET password_hash = ?, password_salt = ? WHERE id = ?")
+ .bind(upgraded, salt, video.id)
+ .run();
+ }
+
+ if (!matches) {
+ await env.DB.prepare("INSERT INTO password_attempts (video_id, client_ip) VALUES (?, ?)")
+ .bind(video.id, clientIP)
+ .run();
+ return jsonResponse({ error: "Incorrect password" }, 403);
+ }
+
+ // Issue an HMAC session token (never the stored hash).
+ const authToken = await generateAuthToken(shareCode, video.expires_at, env.API_SECRET);
+ const expires = new Date(video.expires_at + "Z");
+
+ return new Response(JSON.stringify({ ok: true }), {
+ status: 200,
+ headers: {
+ "Content-Type": "application/json",
+ "Set-Cookie": `voom_auth_${shareCode}=${authToken}; Path=/; Expires=${expires.toUTCString()}; HttpOnly; SameSite=Lax; Secure`,
+ },
+ });
}
diff --git a/services/recordly-share/worker/src/hostedUploads.js b/services/recordly-share/worker/src/hostedUploads.js
index c3a95cc8..fab2ff61 100644
--- a/services/recordly-share/worker/src/hostedUploads.js
+++ b/services/recordly-share/worker/src/hostedUploads.js
@@ -1,155 +1,301 @@
-import { errorResponse, jsonResponse } from './http.js';
-import { handleDelete } from './library.js';
-import { handleMetadata, decodeUploadId } from './uploads.js';
+import { errorResponse, jsonResponse } from "./http.js";
+import { handleDelete } from "./library.js";
+import { handleMetadata, decodeUploadId } from "./uploads.js";
// Match the desktop uploader's chunks. Values are bytes, not client assertions.
export const MAX_RECORDING_BYTES = 1_000_000_000;
export const PART_BYTES = 25 * 1024 * 1024;
const THUMBNAIL_BYTES = 2 * 1024 * 1024;
-const TYPES = new Set(['video/mp4', 'video/webm', 'video/quicktime', 'image/gif']);
+const TYPES = new Set(["video/mp4", "video/webm", "video/quicktime", "image/gif"]);
export async function limitedJson(request, max = 1024 * 1024) {
- const reader = request.body?.getReader();
- if (!reader) throw new Error('INVALID_JSON');
- let size = 0;
- const chunks = [];
- try {
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- size += value.byteLength;
- if (size > max) { await reader.cancel(); throw new Error('BODY_TOO_LARGE'); }
- chunks.push(value);
- }
- } finally { reader.releaseLock(); }
- const bytes = new Uint8Array(size);
- let offset = 0;
- for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
- try {
- const value = JSON.parse(new TextDecoder().decode(bytes));
- if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error();
- return value;
- } catch { throw new Error('INVALID_JSON'); }
+ const reader = request.body?.getReader();
+ if (!reader) throw new Error("INVALID_JSON");
+ let size = 0;
+ const chunks = [];
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ size += value.byteLength;
+ if (size > max) {
+ await reader.cancel();
+ throw new Error("BODY_TOO_LARGE");
+ }
+ chunks.push(value);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ const bytes = new Uint8Array(size);
+ let offset = 0;
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ try {
+ const value = JSON.parse(new TextDecoder().decode(bytes));
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error();
+ return value;
+ } catch {
+ throw new Error("INVALID_JSON");
+ }
}
// Serialize upload/delete/finalize for a recording across Worker isolates. A crash
// leaves a lock for maintenance instead of allowing a competing writer through.
export async function withRecordingLock(env, code, action) {
- const token = crypto.randomUUID();
- const result = await env.DB.prepare('INSERT OR IGNORE INTO recording_locks (share_code, token) VALUES (?, ?)').bind(code, token).run();
- if (!result.meta.changes) return errorResponse('Recording is busy. Try again shortly.', 409);
- try { return await action(); }
- finally { await env.DB.prepare('DELETE FROM recording_locks WHERE share_code = ? AND token = ?').bind(code, token).run(); }
+ const token = crypto.randomUUID();
+ const result = await env.DB.prepare(
+ "INSERT OR IGNORE INTO recording_locks (share_code, token) VALUES (?, ?)",
+ )
+ .bind(code, token)
+ .run();
+ if (!result.meta.changes) return errorResponse("Recording is busy. Try again shortly.", 409);
+ try {
+ return await action();
+ } finally {
+ await env.DB.prepare("DELETE FROM recording_locks WHERE share_code = ? AND token = ?")
+ .bind(code, token)
+ .run();
+ }
}
async function exactUpload(request, length, consume) {
- if (!request.body || request.headers.get('Content-Length') !== String(length)) {
- return errorResponse('Upload length does not match the reserved size', 400);
- }
- // Cloudflare enforces too many AND too few bytes while streaming to R2;
- // never buffer a recording or trust Content-Length alone.
- const stream = new FixedLengthStream(length);
- const results = await Promise.allSettled([request.body.pipeTo(stream.writable, { signal: AbortSignal.timeout(5 * 60 * 1000) }), consume(stream.readable)]);
- if (results[0].status === 'rejected') return errorResponse('Upload body does not match the reserved size', 400);
- if (results[1].status === 'rejected') {
- if (/FixedLengthStream|fixed.length|expected bytes/i.test(String(results[1].reason))) return errorResponse('Upload body does not match the reserved size', 400);
- throw results[1].reason;
- }
- return jsonResponse({ ok: true, ...(results[1].value?.partNumber ? results[1].value : {}) });
+ if (!request.body || request.headers.get("Content-Length") !== String(length)) {
+ return errorResponse("Upload length does not match the reserved size", 400);
+ }
+ // Cloudflare enforces too many AND too few bytes while streaming to R2;
+ // never buffer a recording or trust Content-Length alone.
+ // biome-ignore lint/correctness/noUndeclaredVariables: FixedLengthStream is a Cloudflare Workers runtime global.
+ const stream = new FixedLengthStream(length);
+ const results = await Promise.allSettled([
+ request.body.pipeTo(stream.writable, { signal: AbortSignal.timeout(5 * 60 * 1000) }),
+ consume(stream.readable),
+ ]);
+ if (results[0].status === "rejected")
+ return errorResponse("Upload body does not match the reserved size", 400);
+ if (results[1].status === "rejected") {
+ if (/FixedLengthStream|fixed.length|expected bytes/i.test(String(results[1].reason)))
+ return errorResponse("Upload body does not match the reserved size", 400);
+ throw results[1].reason;
+ }
+ return jsonResponse({ ok: true, ...(results[1].value?.partNumber ? results[1].value : {}) });
}
export async function abortStoredMultipart(env, code) {
- const session = await env.DB.prepare('SELECT upload_id FROM recording_uploads WHERE share_code = ?').bind(code).first();
- if (session) {
- // R2 abort is idempotent. Do not swallow service failures and release quota
- // while parts might still occupy storage.
- await env.VIDEOS_BUCKET.resumeMultipartUpload(`videos/${code}.mp4`, session.upload_id).abort();
- await env.DB.prepare('DELETE FROM recording_uploads WHERE share_code = ?').bind(code).run();
- }
+ const session = await env.DB.prepare(
+ "SELECT upload_id FROM recording_uploads WHERE share_code = ?",
+ )
+ .bind(code)
+ .first();
+ if (session) {
+ // R2 abort is idempotent. Do not swallow service failures and release quota
+ // while parts might still occupy storage.
+ await env.VIDEOS_BUCKET.resumeMultipartUpload(
+ `videos/${code}.mp4`,
+ session.upload_id,
+ ).abort();
+ await env.DB.prepare("DELETE FROM recording_uploads WHERE share_code = ?").bind(code).run();
+ }
}
export async function handleHostedRecording(request, env, ownerId, route, code, rawId, rawPart) {
- const owned = await env.DB.prepare('SELECT id FROM videos WHERE share_code = ? AND owner_id = ?').bind(code, ownerId).first();
- if (!owned) return errorResponse('Video not found', 404);
- return withRecordingLock(env, code, async () => {
- const video = await env.DB.prepare('SELECT * FROM videos WHERE share_code = ? AND owner_id = ?').bind(code, ownerId).first();
- if (!video) return errorResponse('Video not found', 404);
- const key = `videos/${code}.mp4`;
- if (route === 'delete') {
- await abortStoredMultipart(env, code);
- return handleDelete(env, code);
- }
- // A renewal endpoint must not let free accounts bypass their fixed expiry.
- if (route === 'renew') return errorResponse('Free recordings expire after 14 days and cannot be renewed.', 403);
- if (!video.upload_completed && Date.parse(`${video.created_at.replace(' ', 'T')}Z`) < Date.now() - 86400000) {
- return errorResponse('Upload expired. Delete it and start again.', 410);
- }
- if (route === 'metadata') {
- const body = await limitedJson(request);
- const object = await env.VIDEOS_BUCKET.head(key);
- if (!object || object.size !== video.file_size) return errorResponse('Upload the complete recording before publishing', 409);
- if (video.upload_completed) return jsonResponse({ ok: true });
- if ((body.title !== undefined && (typeof body.title !== 'string' || !body.title.trim() || body.title.length > 200)) ||
- (body.summary !== undefined && (typeof body.summary !== 'string' || body.summary.length > 10000)) ||
- (body.isMeeting !== undefined && typeof body.isMeeting !== 'boolean')) return errorResponse('Invalid recording metadata');
- for (const [name, max] of [['segments', 5000], ['chapters', 200]]) {
- if (body[name] !== undefined && (!Array.isArray(body[name]) || body[name].length > max)) return errorResponse('Too much recording metadata');
- }
- if ((body.segments || []).some(s => !s || !Number.isFinite(s.startTime) || !Number.isFinite(s.endTime) || s.startTime < 0 || s.endTime < s.startTime || typeof s.text !== 'string' || s.text.length > 2000 || (s.speaker != null && (typeof s.speaker !== 'string' || s.speaker.length > 100)))) return errorResponse('Invalid transcript');
- if ((body.chapters || []).some(c => !c || !Number.isFinite(c.timestamp) || c.timestamp < 0 || typeof c.title !== 'string' || c.title.length > 200)) return errorResponse('Invalid chapters');
- // A failed metadata attempt may have inserted some chunks. Retry replaces
- // those chunks rather than accumulating duplicates.
- await env.DB.batch([
- env.DB.prepare('DELETE FROM transcript_segments WHERE video_id = ?').bind(video.id),
- env.DB.prepare('DELETE FROM chapters WHERE video_id = ?').bind(video.id),
- ]);
- return handleMetadata(new Request(request.url, { method: 'POST', body: JSON.stringify(body) }), env, code);
- }
- if (route === 'upload-thumbnail') {
- const length = Number(request.headers.get('Content-Length'));
- if (!Number.isSafeInteger(length) || length <= 0 || length > THUMBNAIL_BYTES) return errorResponse('Thumbnail must be at most 2 MB', 413);
- if (request.headers.get('Content-Type') !== 'image/jpeg') return errorResponse('Thumbnail must be JPEG');
- return exactUpload(request, length, stream => env.VIDEOS_BUCKET.put(`thumbnails/${code}.jpg`, stream, { httpMetadata: { contentType: 'image/jpeg' } }));
- }
- // Posters may arrive after metadata publishes the recording. Media remains immutable.
- if (video.upload_completed) return errorResponse('Published recordings cannot be overwritten', 409);
- const session = await env.DB.prepare('SELECT upload_id FROM recording_uploads WHERE share_code = ?').bind(code).first();
- const object = await env.VIDEOS_BUCKET.head(key);
- if (route === 'upload-data') {
- if (session) return errorResponse('A multipart upload is already in progress', 409);
- if (video.file_size > 50 * 1024 * 1024) return errorResponse('Use multipart upload for recordings over 50 MB', 413);
- if (!TYPES.has(request.headers.get('Content-Type'))) return errorResponse('Unsupported recording type');
- if (object) return object.size === video.file_size ? jsonResponse({ ok: true }) : errorResponse('Stored recording size mismatch', 409);
- return exactUpload(request, video.file_size, stream => env.VIDEOS_BUCKET.put(key, stream, { httpMetadata: { contentType: request.headers.get('Content-Type') } }));
- }
- if (route === 'upload-multipart') {
- if (object) return errorResponse('Recording bytes have already been uploaded', 409);
- if (session) return jsonResponse({ uploadId: session.upload_id });
- const upload = await env.VIDEOS_BUCKET.createMultipartUpload(key, { httpMetadata: { contentType: 'video/mp4' } });
- try { await env.DB.prepare('INSERT INTO recording_uploads (share_code, upload_id) VALUES (?, ?)').bind(code, upload.uploadId).run(); }
- catch (error) { await upload.abort(); throw error; }
- return jsonResponse({ uploadId: upload.uploadId });
- }
- const uploadId = decodeUploadId(rawId || '');
- if (!uploadId || !session || session.upload_id !== uploadId) return errorResponse('Upload session not found', 404);
- if (route === 'upload-abort') { await abortStoredMultipart(env, code); return jsonResponse({ ok: true }); }
- if (object) return route === 'upload-complete' && object.size === video.file_size ? jsonResponse({ ok: true }) : errorResponse('Recording bytes have already been uploaded', 409);
- const upload = env.VIDEOS_BUCKET.resumeMultipartUpload(key, uploadId);
- const count = Math.ceil(video.file_size / PART_BYTES);
- if (route === 'upload-part') {
- const number = Number(rawPart);
- if (!Number.isInteger(number) || number < 1 || number > count) return errorResponse('Invalid part number');
- const length = Math.min(PART_BYTES, video.file_size - (number - 1) * PART_BYTES);
- return exactUpload(request, length, stream => upload.uploadPart(number, stream));
- }
- if (route === 'upload-complete') {
- const body = await limitedJson(request, 65536);
- if (!Array.isArray(body.parts) || body.parts.length !== count || body.parts.some((part, i) => !part || part.partNumber !== i + 1 || typeof part.etag !== 'string' || !part.etag || part.etag.length > 200)) return errorResponse('Invalid multipart manifest');
- const result = await upload.complete(body.parts);
- if (result.size !== video.file_size) { await env.VIDEOS_BUCKET.delete(key); return errorResponse('Completed recording size mismatch', 400); }
- // Keep the ID until deletion for retry idempotence and crash recovery.
- return jsonResponse({ ok: true });
- }
- return errorResponse('Not found', 404);
- });
+ const owned = await env.DB.prepare(
+ "SELECT id FROM videos WHERE share_code = ? AND owner_id = ?",
+ )
+ .bind(code, ownerId)
+ .first();
+ if (!owned) return errorResponse("Video not found", 404);
+ return withRecordingLock(env, code, async () => {
+ const video = await env.DB.prepare(
+ "SELECT * FROM videos WHERE share_code = ? AND owner_id = ?",
+ )
+ .bind(code, ownerId)
+ .first();
+ if (!video) return errorResponse("Video not found", 404);
+ const key = `videos/${code}.mp4`;
+ if (route === "delete") {
+ await abortStoredMultipart(env, code);
+ return handleDelete(env, code);
+ }
+ // A renewal endpoint must not let free accounts bypass their fixed expiry.
+ if (route === "renew")
+ return errorResponse(
+ "Free recordings expire after 14 days and cannot be renewed.",
+ 403,
+ );
+ if (
+ !video.upload_completed &&
+ Date.parse(`${video.created_at.replace(" ", "T")}Z`) < Date.now() - 86400000
+ ) {
+ return errorResponse("Upload expired. Delete it and start again.", 410);
+ }
+ if (route === "metadata") {
+ const body = await limitedJson(request);
+ const object = await env.VIDEOS_BUCKET.head(key);
+ if (!object || object.size !== video.file_size)
+ return errorResponse("Upload the complete recording before publishing", 409);
+ if (video.upload_completed) return jsonResponse({ ok: true });
+ if (
+ (body.title !== undefined &&
+ (typeof body.title !== "string" ||
+ !body.title.trim() ||
+ body.title.length > 200)) ||
+ (body.summary !== undefined &&
+ (typeof body.summary !== "string" || body.summary.length > 10000)) ||
+ (body.isMeeting !== undefined && typeof body.isMeeting !== "boolean")
+ )
+ return errorResponse("Invalid recording metadata");
+ for (const [name, max] of [
+ ["segments", 5000],
+ ["chapters", 200],
+ ]) {
+ if (
+ body[name] !== undefined &&
+ (!Array.isArray(body[name]) || body[name].length > max)
+ )
+ return errorResponse("Too much recording metadata");
+ }
+ if (
+ (body.segments || []).some(
+ (s) =>
+ !s ||
+ !Number.isFinite(s.startTime) ||
+ !Number.isFinite(s.endTime) ||
+ s.startTime < 0 ||
+ s.endTime < s.startTime ||
+ typeof s.text !== "string" ||
+ s.text.length > 2000 ||
+ (s.speaker != null &&
+ (typeof s.speaker !== "string" || s.speaker.length > 100)),
+ )
+ )
+ return errorResponse("Invalid transcript");
+ if (
+ (body.chapters || []).some(
+ (c) =>
+ !c ||
+ !Number.isFinite(c.timestamp) ||
+ c.timestamp < 0 ||
+ typeof c.title !== "string" ||
+ c.title.length > 200,
+ )
+ )
+ return errorResponse("Invalid chapters");
+ // A failed metadata attempt may have inserted some chunks. Retry replaces
+ // those chunks rather than accumulating duplicates.
+ await env.DB.batch([
+ env.DB.prepare("DELETE FROM transcript_segments WHERE video_id = ?").bind(video.id),
+ env.DB.prepare("DELETE FROM chapters WHERE video_id = ?").bind(video.id),
+ ]);
+ return handleMetadata(
+ new Request(request.url, { method: "POST", body: JSON.stringify(body) }),
+ env,
+ code,
+ );
+ }
+ if (route === "upload-thumbnail") {
+ const length = Number(request.headers.get("Content-Length"));
+ if (!Number.isSafeInteger(length) || length <= 0 || length > THUMBNAIL_BYTES)
+ return errorResponse("Thumbnail must be at most 2 MB", 413);
+ if (request.headers.get("Content-Type") !== "image/jpeg")
+ return errorResponse("Thumbnail must be JPEG");
+ return exactUpload(request, length, (stream) =>
+ env.VIDEOS_BUCKET.put(`thumbnails/${code}.jpg`, stream, {
+ httpMetadata: { contentType: "image/jpeg" },
+ }),
+ );
+ }
+ // Posters may arrive after metadata publishes the recording. Media remains immutable.
+ if (video.upload_completed)
+ return errorResponse("Published recordings cannot be overwritten", 409);
+ const session = await env.DB.prepare(
+ "SELECT upload_id FROM recording_uploads WHERE share_code = ?",
+ )
+ .bind(code)
+ .first();
+ const object = await env.VIDEOS_BUCKET.head(key);
+ if (route === "upload-data") {
+ if (session) return errorResponse("A multipart upload is already in progress", 409);
+ if (video.file_size > 50 * 1024 * 1024)
+ return errorResponse("Use multipart upload for recordings over 50 MB", 413);
+ if (!TYPES.has(request.headers.get("Content-Type")))
+ return errorResponse("Unsupported recording type");
+ if (object)
+ return object.size === video.file_size
+ ? jsonResponse({ ok: true })
+ : errorResponse("Stored recording size mismatch", 409);
+ return exactUpload(request, video.file_size, (stream) =>
+ env.VIDEOS_BUCKET.put(key, stream, {
+ httpMetadata: { contentType: request.headers.get("Content-Type") },
+ }),
+ );
+ }
+ if (route === "upload-multipart") {
+ if (object) return errorResponse("Recording bytes have already been uploaded", 409);
+ if (session) return jsonResponse({ uploadId: session.upload_id });
+ const upload = await env.VIDEOS_BUCKET.createMultipartUpload(key, {
+ httpMetadata: { contentType: "video/mp4" },
+ });
+ try {
+ await env.DB.prepare(
+ "INSERT INTO recording_uploads (share_code, upload_id) VALUES (?, ?)",
+ )
+ .bind(code, upload.uploadId)
+ .run();
+ } catch (error) {
+ await upload.abort();
+ throw error;
+ }
+ return jsonResponse({ uploadId: upload.uploadId });
+ }
+ const uploadId = decodeUploadId(rawId || "");
+ if (!uploadId || !session || session.upload_id !== uploadId)
+ return errorResponse("Upload session not found", 404);
+ if (route === "upload-abort") {
+ await abortStoredMultipart(env, code);
+ return jsonResponse({ ok: true });
+ }
+ if (object)
+ return route === "upload-complete" && object.size === video.file_size
+ ? jsonResponse({ ok: true })
+ : errorResponse("Recording bytes have already been uploaded", 409);
+ const upload = env.VIDEOS_BUCKET.resumeMultipartUpload(key, uploadId);
+ const count = Math.ceil(video.file_size / PART_BYTES);
+ if (route === "upload-part") {
+ const number = Number(rawPart);
+ if (!Number.isInteger(number) || number < 1 || number > count)
+ return errorResponse("Invalid part number");
+ const length = Math.min(PART_BYTES, video.file_size - (number - 1) * PART_BYTES);
+ return exactUpload(request, length, (stream) => upload.uploadPart(number, stream));
+ }
+ if (route === "upload-complete") {
+ const body = await limitedJson(request, 65536);
+ if (
+ !Array.isArray(body.parts) ||
+ body.parts.length !== count ||
+ body.parts.some(
+ (part, i) =>
+ !part ||
+ part.partNumber !== i + 1 ||
+ typeof part.etag !== "string" ||
+ !part.etag ||
+ part.etag.length > 200,
+ )
+ )
+ return errorResponse("Invalid multipart manifest");
+ const result = await upload.complete(body.parts);
+ if (result.size !== video.file_size) {
+ await env.VIDEOS_BUCKET.delete(key);
+ await env.DB.prepare("DELETE FROM recording_uploads WHERE share_code = ?")
+ .bind(code)
+ .run();
+ return errorResponse("Completed recording size mismatch", 400);
+ }
+ // Keep the ID until deletion for retry idempotence and crash recovery.
+ return jsonResponse({ ok: true });
+ }
+ return errorResponse("Not found", 404);
+ });
}
diff --git a/services/recordly-share/worker/src/index.js b/services/recordly-share/worker/src/index.js
index 6bd5803b..b82ee737 100644
--- a/services/recordly-share/worker/src/index.js
+++ b/services/recordly-share/worker/src/index.js
@@ -1,41 +1,48 @@
// Adapted from Voom (MIT), Copyright (c) 2026 Aritro Paul.
// See ../../LICENSE and ../../../../THIRD_PARTY_NOTICES.md for attribution.
-import { handleRequest } from './router.js';
-import { errorResponse } from './http.js';
-import { ensureSchema } from './schema.js';
-import { cleanupExpired } from './library.js';
+import { handleRequest } from "./router.js";
+import { errorResponse } from "./http.js";
+import { ensureSchema } from "./schema.js";
+import { cleanupExpired } from "./library.js";
export default {
- async fetch(request, env) {
- try {
- return await handleRequest(request, env);
- } catch (e) {
- if (e.message === 'BODY_TOO_LARGE') return errorResponse('Request body is too large', 413);
- if (e.message === 'INVALID_JSON') return errorResponse('Invalid JSON body', 400);
- // D1/R2 transient failures and bugs land here instead of surfacing as
- // opaque Workers runtime errors. Keep the response app-shaped (JSON).
- console.error('unhandled error', request.method, new URL(request.url).pathname, e.message, e.stack);
- return errorResponse('Internal error', 500);
- }
- },
+ async fetch(request, env) {
+ try {
+ return await handleRequest(request, env);
+ } catch (e) {
+ if (e.message === "BODY_TOO_LARGE")
+ return errorResponse("Request body is too large", 413);
+ if (e.message === "INVALID_JSON") return errorResponse("Invalid JSON body", 400);
+ // D1/R2 transient failures and bugs land here instead of surfacing as
+ // opaque Workers runtime errors. Keep the response app-shaped (JSON).
+ console.error(
+ "unhandled error",
+ request.method,
+ new URL(request.url).pathname,
+ e.message,
+ e.stack,
+ );
+ return errorResponse("Internal error", 500);
+ }
+ },
- async scheduled(event, env) {
- try {
- await ensureSchema(env);
- await cleanupExpired(env);
- } catch (e) {
- console.error('cron cleanup failed', e.message, e.stack);
- throw e; // Surface failed runs to Cloudflare monitoring instead of reporting success.
- }
- },
+ async scheduled(event, env) {
+ try {
+ await ensureSchema(env);
+ await cleanupExpired(env);
+ } catch (e) {
+ console.error("cron cleanup failed", e.message, e.stack);
+ throw e; // Surface failed runs to Cloudflare monitoring instead of reporting success.
+ }
+ },
};
// Kept for existing consumers and the Worker integration tests.
-export { __resetSchemaCacheForTests } from './schema.js';
-export { generateShareCode } from './uploads.js';
-export { escapeHTML } from './media.js';
-export { parseCookies } from './http.js';
-export { timingSafeEqual, sha256Hex, generateSalt } from './crypto.js';
-export { formatVTTTime } from './media.js';
-export { expectedSessionToken, dashboardPassword } from './auth.js';
+export { __resetSchemaCacheForTests } from "./schema.js";
+export { generateShareCode } from "./uploads.js";
+export { escapeHTML } from "./media.js";
+export { parseCookies } from "./http.js";
+export { timingSafeEqual, sha256Hex, generateSalt } from "./crypto.js";
+export { formatVTTTime } from "./media.js";
+export { expectedSessionToken, dashboardPassword } from "./auth.js";
diff --git a/services/recordly-share/worker/src/library.js b/services/recordly-share/worker/src/library.js
index a6c97cc1..a9965996 100644
--- a/services/recordly-share/worker/src/library.js
+++ b/services/recordly-share/worker/src/library.js
@@ -1,118 +1,133 @@
// Adapted from Voom (MIT), Copyright (c) 2026 Aritro Paul.
// See ../../LICENSE and ../../../../THIRD_PARTY_NOTICES.md for attribution.
-import { abortStoredMultipart, withRecordingLock } from './hostedUploads.js';
-import { EXPIRY_DAYS } from './video.js';
-import { errorResponse, jsonResponse } from './http.js';
+import { abortStoredMultipart, withRecordingLock } from "./hostedUploads.js";
+import { EXPIRY_DAYS } from "./video.js";
+import { errorResponse, jsonResponse } from "./http.js";
export async function handleRenew(env, shareCode) {
- const newExpiry = new Date(Date.now() + EXPIRY_DAYS * 24 * 60 * 60 * 1000).toISOString();
+ const newExpiry = new Date(Date.now() + EXPIRY_DAYS * 24 * 60 * 60 * 1000).toISOString();
- const result = await env.DB.prepare('UPDATE videos SET expires_at = ? WHERE share_code = ?')
- .bind(newExpiry, shareCode)
- .run();
+ const result = await env.DB.prepare("UPDATE videos SET expires_at = ? WHERE share_code = ?")
+ .bind(newExpiry, shareCode)
+ .run();
- if (result.meta.changes === 0) return errorResponse('Video not found', 404);
+ if (result.meta.changes === 0) return errorResponse("Video not found", 404);
- return jsonResponse({ expiresAt: newExpiry });
+ return jsonResponse({ expiresAt: newExpiry });
}
export async function handleDelete(env, shareCode) {
- const video = await env.DB.prepare('SELECT id FROM videos WHERE share_code = ?').bind(shareCode).first();
- if (!video) return errorResponse('Video not found', 404);
-
- await Promise.all([
- env.VIDEOS_BUCKET.delete(`videos/${shareCode}.mp4`),
- env.VIDEOS_BUCKET.delete(`thumbnails/${shareCode}.jpg`),
- ]);
- await env.DB.batch(deleteVideoStatements(env, video.id));
-
- return jsonResponse({ ok: true });
+ const video = await env.DB.prepare("SELECT id FROM videos WHERE share_code = ?")
+ .bind(shareCode)
+ .first();
+ if (!video) return errorResponse("Video not found", 404);
+
+ await Promise.all([
+ env.VIDEOS_BUCKET.delete(`videos/${shareCode}.mp4`),
+ env.VIDEOS_BUCKET.delete(`thumbnails/${shareCode}.jpg`),
+ ]);
+ await env.DB.batch(deleteVideoStatements(env, video.id));
+
+ return jsonResponse({ ok: true });
}
// One round-trip delete of a video and all child rows. Explicit child deletes
// rather than relying on ON DELETE CASCADE: legacy self-host databases were
// created from a base schema without cascade on every table.
function deleteVideoStatements(env, videoId) {
- return [
- env.DB.prepare('DELETE FROM chapters WHERE video_id = ?').bind(videoId),
- env.DB.prepare('DELETE FROM reactions WHERE video_id = ?').bind(videoId),
- env.DB.prepare('DELETE FROM comments WHERE video_id = ?').bind(videoId),
- env.DB.prepare('DELETE FROM transcript_segments WHERE video_id = ?').bind(videoId),
- env.DB.prepare('DELETE FROM password_attempts WHERE video_id = ?').bind(videoId),
- env.DB.prepare('DELETE FROM videos WHERE id = ?').bind(videoId),
- ];
+ return [
+ env.DB.prepare("DELETE FROM chapters WHERE video_id = ?").bind(videoId),
+ env.DB.prepare("DELETE FROM reactions WHERE video_id = ?").bind(videoId),
+ env.DB.prepare("DELETE FROM comments WHERE video_id = ?").bind(videoId),
+ env.DB.prepare("DELETE FROM transcript_segments WHERE video_id = ?").bind(videoId),
+ env.DB.prepare("DELETE FROM password_attempts WHERE video_id = ?").bind(videoId),
+ env.DB.prepare("DELETE FROM videos WHERE id = ?").bind(videoId),
+ ];
}
// --- Cron Cleanup ---
export async function cleanupExpired(env) {
- if (env.HOSTED_MODE === 'true') {
- // Release only crash locks older than a full day; live requests cannot run
- // this long. Then use the same per-recording lock as interactive mutations.
- await env.DB.prepare("DELETE FROM recording_locks WHERE datetime(created_at) < datetime('now', '-1 day')").run();
- const stale = await env.DB.prepare("SELECT share_code FROM videos WHERE owner_id IS NOT NULL AND (datetime(expires_at) < datetime('now') OR (upload_completed = 0 AND datetime(created_at) < datetime('now', '-1 day'))) LIMIT 100").all();
- for (const row of stale.results || []) {
- await withRecordingLock(env, row.share_code, async () => {
- const eligible = await env.DB.prepare("SELECT id FROM videos WHERE share_code = ? AND (datetime(expires_at) < datetime('now') OR (upload_completed = 0 AND datetime(created_at) < datetime('now', '-1 day')))").bind(row.share_code).first();
- if (!eligible) return;
- await abortStoredMultipart(env, row.share_code);
- await handleDelete(env, row.share_code);
- });
- }
- return;
- }
- const expired = await env.DB.prepare(
- "SELECT id, share_code FROM videos WHERE datetime(expires_at) < datetime('now')"
- ).all();
-
- for (const video of expired.results || []) {
- await Promise.all([
- env.VIDEOS_BUCKET.delete(`videos/${video.share_code}.mp4`),
- env.VIDEOS_BUCKET.delete(`thumbnails/${video.share_code}.jpg`),
- ]);
- await env.DB.batch(deleteVideoStatements(env, video.id));
- }
-
- // Drop stale password rate-limit rows so the table can't grow unboundedly.
- await env.DB.prepare(
- "DELETE FROM password_attempts WHERE datetime(attempted_at) < datetime('now', '-1 day')"
- ).run();
- await env.DB.prepare(
- "DELETE FROM comment_sessions WHERE datetime(expires_at) < datetime('now')"
- ).run();
+ if (env.HOSTED_MODE === "true") {
+ // Release only crash locks older than a full day; live requests cannot run
+ // this long. Then use the same per-recording lock as interactive mutations.
+ await env.DB.prepare(
+ "DELETE FROM recording_locks WHERE datetime(created_at) < datetime('now', '-1 day')",
+ ).run();
+ const stale = await env.DB.prepare(
+ "SELECT share_code FROM videos WHERE owner_id IS NOT NULL AND (datetime(expires_at) < datetime('now') OR (upload_completed = 0 AND datetime(created_at) < datetime('now', '-1 day'))) LIMIT 100",
+ ).all();
+ for (const row of stale.results || []) {
+ await withRecordingLock(env, row.share_code, async () => {
+ const eligible = await env.DB.prepare(
+ "SELECT id FROM videos WHERE share_code = ? AND (datetime(expires_at) < datetime('now') OR (upload_completed = 0 AND datetime(created_at) < datetime('now', '-1 day')))",
+ )
+ .bind(row.share_code)
+ .first();
+ if (!eligible) return;
+ await abortStoredMultipart(env, row.share_code);
+ await handleDelete(env, row.share_code);
+ });
+ }
+ return;
+ }
+ const expired = await env.DB.prepare(
+ "SELECT id, share_code FROM videos WHERE datetime(expires_at) < datetime('now')",
+ ).all();
+
+ for (const video of expired.results || []) {
+ await Promise.all([
+ env.VIDEOS_BUCKET.delete(`videos/${video.share_code}.mp4`),
+ env.VIDEOS_BUCKET.delete(`thumbnails/${video.share_code}.jpg`),
+ ]);
+ await env.DB.batch(deleteVideoStatements(env, video.id));
+ }
+
+ // Drop stale password rate-limit rows so the table can't grow unboundedly.
+ await env.DB.prepare(
+ "DELETE FROM password_attempts WHERE datetime(attempted_at) < datetime('now', '-1 day')",
+ ).run();
+ await env.DB.prepare(
+ "DELETE FROM comment_sessions WHERE datetime(expires_at) < datetime('now')",
+ ).run();
}
// --- Check Views (authenticated) ---
export async function handleCheckViews(request, env, ownerId = null) {
- const body = await request.json();
- const { shareCodes } = body;
- if (!Array.isArray(shareCodes) || shareCodes.length === 0) return errorResponse('shareCodes required');
- if (shareCodes.length > 90) return errorResponse('Too many shareCodes (max 90)');
-
- const placeholders = shareCodes.map(() => '?').join(',');
- const results = await env.DB.prepare(
- `SELECT share_code, view_count FROM videos WHERE share_code IN (${placeholders}) AND (? IS NULL OR owner_id = ?)`
- ).bind(...shareCodes, ownerId, ownerId).all();
-
- const views = {};
- for (const row of results.results || []) {
- views[row.share_code] = row.view_count || 0;
- }
-
- return jsonResponse({ views });
+ const body = await request.json();
+ const { shareCodes } = body;
+ if (!Array.isArray(shareCodes) || shareCodes.length === 0)
+ return errorResponse("shareCodes required");
+ if (shareCodes.length > 90) return errorResponse("Too many shareCodes (max 90)");
+
+ const placeholders = shareCodes.map(() => "?").join(",");
+ const results = await env.DB.prepare(
+ `SELECT share_code, view_count FROM videos WHERE share_code IN (${placeholders}) AND (? IS NULL OR owner_id = ?)`,
+ )
+ .bind(...shareCodes, ownerId, ownerId)
+ .all();
+
+ const views = {};
+ for (const row of results.results || []) {
+ views[row.share_code] = row.view_count || 0;
+ }
+
+ return jsonResponse({ views });
}
// --- Library: list all shared videos (dashboard) ---
export async function handleListVideos(env, ownerId = null) {
- const rows = await env.DB.prepare(
- `SELECT share_code, title, duration, width, height, file_size, created_at, expires_at,
+ const rows = await env.DB.prepare(
+ `SELECT share_code, title, duration, width, height, file_size, created_at, expires_at,
view_count, is_meeting, summary, upload_completed, (password_hash IS NOT NULL) AS is_protected
FROM videos
WHERE (upload_completed = 1 OR ? IS NOT NULL) AND (? IS NULL OR owner_id = ?)
- ORDER BY datetime(created_at) DESC`
- ).bind(ownerId, ownerId, ownerId).all();
- return jsonResponse({ videos: rows.results || [] });
+ ORDER BY datetime(created_at) DESC`,
+ )
+ .bind(ownerId, ownerId, ownerId)
+ .all();
+ return jsonResponse({ videos: rows.results || [] });
}
diff --git a/services/recordly-share/worker/src/router.js b/services/recordly-share/worker/src/router.js
index 18a1efac..99e5546e 100644
--- a/services/recordly-share/worker/src/router.js
+++ b/services/recordly-share/worker/src/router.js
@@ -1,314 +1,397 @@
// Adapted from Voom (MIT), Copyright (c) 2026 Aritro Paul.
// See ../../LICENSE and ../../../../THIRD_PARTY_NOTICES.md for attribution.
-import { handleHostedRecording, limitedJson } from './hostedUploads.js';
-import { ensureSchema } from './schema.js';
-import { commentViewer, handleCommentLogin, handleCommentLogout, handleCommentRegister } from './accounts.js';
-import { errorResponse, jsonResponse } from './http.js';
-import { checkLoginRateLimit, clearLoginRateLimit, dashboardCookieAuthed, dashboardPassword, expectedSessionToken, handleVerifyPassword, hostedUser, isAuthorized, isDashboardAuthed, verifyPasswordAuth } from './auth.js';
-import { timingSafeEqual } from './crypto.js';
-import { handleCheckViews, handleDelete, handleListVideos, handleRenew } from './library.js';
-import { decodeUploadId, handleMetadata, handleMultipartAbort, handleMultipartComplete, handleMultipartPart, handleMultipartStart, handleUpload, handleUploadData, handleUploadThumbnail } from './uploads.js';
-import { handleOGImage, handleOGPage, handleShareData, handleVTT, handleVideoStream } from './media.js';
-import { handleComment, handleGetComments, handleGetReactions, handleReact } from './feedback.js';
+import { handleHostedRecording, limitedJson } from "./hostedUploads.js";
+import { ensureSchema } from "./schema.js";
+import {
+ commentViewer,
+ handleCommentLogin,
+ handleCommentLogout,
+ handleCommentRegister,
+} from "./accounts.js";
+import { errorResponse, jsonResponse } from "./http.js";
+import {
+ checkLoginRateLimit,
+ clearLoginRateLimit,
+ dashboardCookieAuthed,
+ dashboardPassword,
+ expectedSessionToken,
+ handleVerifyPassword,
+ hostedUser,
+ isAuthorized,
+ isDashboardAuthed,
+ verifyPasswordAuth,
+} from "./auth.js";
+import { timingSafeEqual } from "./crypto.js";
+import { handleCheckViews, handleDelete, handleListVideos, handleRenew } from "./library.js";
+import {
+ decodeUploadId,
+ handleMetadata,
+ handleMultipartAbort,
+ handleMultipartComplete,
+ handleMultipartPart,
+ handleMultipartStart,
+ handleUpload,
+ handleUploadData,
+ handleUploadThumbnail,
+} from "./uploads.js";
+import {
+ handleOGImage,
+ handleOGPage,
+ handleShareData,
+ handleVTT,
+ handleVideoStream,
+} from "./media.js";
+import { handleComment, handleGetComments, handleGetReactions, handleReact } from "./feedback.js";
export async function handleRequest(request, env) {
- const url = new URL(request.url);
- const path = url.pathname;
-
- const hosted = env.HOSTED_MODE === 'true';
- if (hosted) {
- if (!env.REQUEST_RATE_LIMIT || !env.ACCOUNT_RATE_LIMIT) return errorResponse('Hosted rate limits are not configured', 503);
- const { success } = await env.REQUEST_RATE_LIMIT.limit({ key: request.headers.get('CF-Connecting-IP') || 'local' });
- if (!success) return errorResponse('Too many requests. Try again in a minute.', 429);
- }
- await ensureSchema(env);
- // The shared-password dashboard and legacy comment accounts are self-host only.
- if (hosted && (path.startsWith('/library') || path.startsWith('/auth/'))) {
- return errorResponse('Not found', 404);
- }
-
- if (path === '/auth/session' && request.method === 'GET') {
- const viewer = await commentViewer(request, env);
- return jsonResponse({
- user: viewer ? { email: viewer.email, displayName: viewer.display_name } : null,
- });
- }
- if (path === '/auth/register' && request.method === 'POST') {
- return handleCommentRegister(request, env);
- }
- if (path === '/auth/login' && request.method === 'POST') {
- return handleCommentLogin(request, env);
- }
- if (path === '/auth/logout' && request.method === 'POST') {
- return handleCommentLogout(request, env);
- }
-
- // Library login (public — no bearer required; form POST)
- if (path === '/library/login' && request.method === 'POST') {
- const ip = request.headers.get('CF-Connecting-IP') || 'unknown';
- if (!checkLoginRateLimit(ip)) {
- return new Response('Too many attempts — try again later', { status: 429 });
- }
- const form = await request.formData();
- const password = form.get('password') || '';
- if (timingSafeEqual(password, dashboardPassword(env))) {
- clearLoginRateLimit(ip);
- const token = await expectedSessionToken(env);
- return new Response(null, {
- status: 302,
- headers: {
- 'Location': '/library',
- 'Set-Cookie': `voom_session=${token}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=604800`,
- },
- });
- }
- return new Response(null, { status: 302, headers: { 'Location': '/library/login?error=1' } });
- }
-
- // Library logout
- if (path === '/library/logout' && request.method === 'GET') {
- return new Response(null, {
- status: 302,
- headers: {
- 'Location': '/library/login',
- 'Set-Cookie': 'voom_session=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0',
- },
- });
- }
-
- // Library dashboard (auth-gated)
- // Internal asset is /lib.html (not /library.html) so the ASSETS binding
- // does not auto-serve it before the worker runs (no run_worker_first needed).
- if (path === '/library' && request.method === 'GET') {
- if (!(await isDashboardAuthed(request, env))) {
- return new Response(null, { status: 302, headers: { 'Location': '/library/login' } });
- }
- return env.ASSETS.fetch(new Request(new URL('/lib', url), request));
- }
-
- // Library login page (public)
- if (path === '/library/login' && request.method === 'GET') {
- return env.ASSETS.fetch(new Request(new URL('/lib-login', url), request));
- }
-
- // API routes (authenticated)
- if (path.startsWith('/api/')) {
- if (request.method === 'OPTIONS') {
- return new Response(null, {
- headers: {
- 'Access-Control-Allow-Origin': '*',
- 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
- 'Access-Control-Allow-Headers': 'Authorization, Content-Type',
- },
- });
- }
-
- let ownerId = null;
- if (hosted) {
- const user = await hostedUser(request, env);
- if (!user) return errorResponse('Verified sign-in required', 401);
- ownerId = user.id;
- if (!(await env.ACCOUNT_RATE_LIMIT.limit({ key: ownerId })).success) return errorResponse('Too many account requests. Try again in a minute.', 429);
- if (!['/api/health', '/api/videos', '/api/upload', '/api/check-views'].includes(path)) {
- const route = path.match(/^\/api\/(upload-data|upload-thumbnail|upload-multipart|upload-part|upload-complete|upload-abort|metadata|renew|delete)\/([a-z0-9]+)(?:\/([^/]+)(?:\/(\d+))?)?$/);
- if (!route) return errorResponse('Not found', 404);
- const expected = { 'upload-data': 'PUT', 'upload-thumbnail': 'PUT', 'upload-part': 'PUT', delete: 'DELETE' }[route[1]] || 'POST';
- if (request.method !== expected || (route[1] === 'upload-part' ? !route[4] : route[4] !== undefined) || (['upload-part', 'upload-complete', 'upload-abort'].includes(route[1]) ? !route[3] : route[3] !== undefined)) return errorResponse('Not found', 404);
- return handleHostedRecording(request, env, ownerId, ...route.slice(1));
- }
- } else if (!(await isAuthorized(request, env)) && !(await dashboardCookieAuthed(request, env))) {
- return errorResponse('Unauthorized', 401);
- }
-
- // Connection check used by the desktop app to validate a worker URL + secret.
- if (path === '/api/health' && request.method === 'GET') {
- return jsonResponse({ ok: true, app: 'recordly' });
- }
-
- if (path === '/api/videos' && request.method === 'GET') {
- return handleListVideos(env, ownerId);
- }
-
- if (path === '/api/upload' && request.method === 'POST') {
- return handleUpload(request, env, ownerId);
- }
-
- const uploadDataMatch = path.match(/^\/api\/upload-data\/([a-z0-9]+)$/);
- if (uploadDataMatch && request.method === 'PUT') {
- return handleUploadData(request, env, uploadDataMatch[1]);
- }
-
- const thumbnailMatch = path.match(/^\/api\/upload-thumbnail\/([a-z0-9]+)$/);
- if (thumbnailMatch && request.method === 'PUT') {
- return handleUploadThumbnail(request, env, thumbnailMatch[1]);
- }
-
- const multipartStartMatch = path.match(/^\/api\/upload-multipart\/([a-z0-9]+)$/);
- if (multipartStartMatch && request.method === 'POST') {
- return handleMultipartStart(request, env, multipartStartMatch[1]);
- }
-
- const multipartPartMatch = path.match(/^\/api\/upload-part\/([a-z0-9]+)\/(.+?)\/(\d+)$/);
- if (multipartPartMatch && request.method === 'PUT') {
- const multipartUploadId = decodeUploadId(multipartPartMatch[2]);
- if (!multipartUploadId) return errorResponse('Invalid multipart upload ID');
- return handleMultipartPart(request, env, multipartPartMatch[1], multipartUploadId, parseInt(multipartPartMatch[3], 10));
- }
-
- const multipartCompleteMatch = path.match(/^\/api\/upload-complete\/([a-z0-9]+)\/(.+)$/);
- if (multipartCompleteMatch && request.method === 'POST') {
- const multipartUploadId = decodeUploadId(multipartCompleteMatch[2]);
- if (!multipartUploadId) return errorResponse('Invalid multipart upload ID');
- return handleMultipartComplete(request, env, multipartCompleteMatch[1], multipartUploadId);
- }
-
- const multipartAbortMatch = path.match(/^\/api\/upload-abort\/([a-z0-9]+)\/(.+)$/);
- if (multipartAbortMatch && request.method === 'POST') {
- const multipartUploadId = decodeUploadId(multipartAbortMatch[2]);
- if (!multipartUploadId) return errorResponse('Invalid multipart upload ID');
- return handleMultipartAbort(request, env, multipartAbortMatch[1], multipartUploadId);
- }
-
- const metadataMatch = path.match(/^\/api\/metadata\/([a-z0-9]+)$/);
- if (metadataMatch && request.method === 'POST') {
- return handleMetadata(request, env, metadataMatch[1]);
- }
-
- const renewMatch = path.match(/^\/api\/renew\/([a-z0-9]+)$/);
- if (renewMatch && request.method === 'POST') {
- return handleRenew(env, renewMatch[1]);
- }
-
- const deleteMatch = path.match(/^\/api\/delete\/([a-z0-9]+)$/);
- if (deleteMatch && request.method === 'DELETE') {
- return handleDelete(env, deleteMatch[1]);
- }
-
- if (path === '/api/check-views' && request.method === 'POST') {
- return handleCheckViews(hosted ? new Request(request.url, { method: 'POST', body: JSON.stringify(await limitedJson(request, 16384)) }) : request, env, ownerId);
- }
-
- return errorResponse('Not found', 404);
- }
-
- // CORS preflight for public endpoints
- if (request.method === 'OPTIONS') {
- return new Response(null, {
- headers: {
- 'Access-Control-Allow-Origin': '*',
- 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
- 'Access-Control-Allow-Headers': 'Content-Type',
- },
- });
- }
-
- if (hosted && request.method === 'POST') {
- request = new Request(request, { body: JSON.stringify(await limitedJson(request, 16384)) });
- }
-
- // Password verification (public)
- const verifyMatch = path.match(/^\/s\/([a-z0-9]+)\/verify-password$/);
- if (verifyMatch && request.method === 'POST') {
- return handleVerifyPassword(request, env, verifyMatch[1]);
- }
-
- // Share data endpoint (public, for SPA)
- const dataMatch = path.match(/^\/s\/([a-z0-9]+)\/data$/);
- if (dataMatch && request.method === 'GET') {
- return handleShareData(request, env, dataMatch[1]);
- }
-
- // Reactions (public)
- const reactMatch = path.match(/^\/s\/([a-z0-9]+)\/react$/);
- if (reactMatch && request.method === 'POST') {
- return handleReact(request, env, reactMatch[1]);
- }
- const reactGetMatch = path.match(/^\/s\/([a-z0-9]+)\/reactions$/);
- if (reactGetMatch && request.method === 'GET') {
- return handleGetReactions(request, env, reactGetMatch[1]);
- }
-
- // Comments (public)
- const commentMatch = path.match(/^\/s\/([a-z0-9]+)\/comment$/);
- if (commentMatch && request.method === 'POST') {
- return handleComment(request, env, commentMatch[1]);
- }
- const commentGetMatch = path.match(/^\/s\/([a-z0-9]+)\/comments$/);
- if (commentGetMatch && request.method === 'GET') {
- return handleGetComments(request, env, commentGetMatch[1]);
- }
-
- // VTT captions
- const vttMatch = path.match(/^\/vtt\/([a-z0-9]+)$/);
- if (vttMatch && request.method === 'GET') {
- return handleVTT(request, env, vttMatch[1]);
- }
-
- // Share page — serve Astro SPA or OG for bots
- const shareMatch = path.match(/^\/s\/([a-z0-9]+)$/);
- if (shareMatch && request.method === 'GET') {
- const shareCode = shareMatch[1];
- const ua = request.headers.get('User-Agent') || '';
- if (/bot|crawl|spider|facebook|twitter|slack|discord|telegram|whatsapp|linkedin/i.test(ua)) {
- return handleOGPage(request, env, shareCode);
- }
- return env.ASSETS.fetch(new Request(new URL('/share', url), request));
- }
-
- // Video streaming
- const videoMatch = path.match(/^\/v\/([a-z0-9]+)$/);
- if (videoMatch && request.method === 'GET') {
- return handleVideoStream(request, env, videoMatch[1]);
- }
-
- // OG image
- const ogMatch = path.match(/^\/og\/([a-z0-9]+)$/);
- if (ogMatch && request.method === 'GET') {
- return handleOGImage(env, ogMatch[1]);
- }
-
- // Embed player — serve Astro embed page
- const embedMatch = path.match(/^\/embed\/([a-z0-9]+)$/);
- if (embedMatch && request.method === 'GET') {
- return env.ASSETS.fetch(new Request(new URL('/embed', url), request));
- }
-
- // Thumbnail (high-res poster) — gated like the OG image: the poster frame
- // of a password-protected or expired video may itself be sensitive.
- const thumbMatch = path.match(/^\/thumb\/([a-z0-9]+)$/);
- if (thumbMatch && request.method === 'GET') {
- const video = await env.DB.prepare(
- "SELECT password_hash, expires_at FROM videos WHERE share_code = ? AND datetime(expires_at) > datetime('now')"
- ).bind(thumbMatch[1]).first();
- if (!video) return new Response('Not found', { status: 404 });
- if (!(await verifyPasswordAuth(request, env, thumbMatch[1], video))) {
- return new Response('Not found', { status: 404 });
- }
- const thumb = await env.VIDEOS_BUCKET.get(`thumbnails/${thumbMatch[1]}.jpg`);
- if (thumb) {
- return new Response(thumb.body, {
- // Recheck the unlock cookie on every protected poster request.
- headers: { 'Content-Type': 'image/jpeg', 'Cache-Control': video.password_hash ? 'private, no-store' : 'public, max-age=86400' },
- });
- }
- return new Response('Not found', { status: 404 });
- }
-
- // Static assets from R2
- if (path === '/icon-64.png' && request.method === 'GET') {
- const obj = await env.VIDEOS_BUCKET.get('static/icon-64.png');
- if (obj) {
- return new Response(obj.body, {
- headers: { 'Content-Type': 'image/png', 'Cache-Control': 'public, max-age=604800' },
- });
- }
- }
-
- if (path === '/') {
- return new Response('Recordly Share', { status: 200 });
- }
-
- // Fall through to static assets
- return env.ASSETS.fetch(request);
+ const url = new URL(request.url);
+ const path = url.pathname;
+
+ const hosted = env.HOSTED_MODE === "true";
+ if (hosted) {
+ if (!env.REQUEST_RATE_LIMIT || !env.ACCOUNT_RATE_LIMIT)
+ return errorResponse("Hosted rate limits are not configured", 503);
+ const { success } = await env.REQUEST_RATE_LIMIT.limit({
+ key: request.headers.get("CF-Connecting-IP") || "local",
+ });
+ if (!success) return errorResponse("Too many requests. Try again in a minute.", 429);
+ }
+ await ensureSchema(env);
+ // The shared-password dashboard and legacy comment accounts are self-host only.
+ if (hosted && (path.startsWith("/library") || path.startsWith("/auth/"))) {
+ return errorResponse("Not found", 404);
+ }
+
+ if (path === "/auth/session" && request.method === "GET") {
+ const viewer = await commentViewer(request, env);
+ return jsonResponse({
+ user: viewer ? { email: viewer.email, displayName: viewer.display_name } : null,
+ });
+ }
+ if (path === "/auth/register" && request.method === "POST") {
+ return handleCommentRegister(request, env);
+ }
+ if (path === "/auth/login" && request.method === "POST") {
+ return handleCommentLogin(request, env);
+ }
+ if (path === "/auth/logout" && request.method === "POST") {
+ return handleCommentLogout(request, env);
+ }
+
+ // Library login (public — no bearer required; form POST)
+ if (path === "/library/login" && request.method === "POST") {
+ const ip = request.headers.get("CF-Connecting-IP") || "unknown";
+ if (!checkLoginRateLimit(ip)) {
+ return new Response("Too many attempts — try again later", { status: 429 });
+ }
+ const form = await request.formData();
+ const password = form.get("password") || "";
+ if (timingSafeEqual(password, dashboardPassword(env))) {
+ clearLoginRateLimit(ip);
+ const token = await expectedSessionToken(env);
+ return new Response(null, {
+ status: 302,
+ headers: {
+ Location: "/library",
+ "Set-Cookie": `voom_session=${token}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=604800`,
+ },
+ });
+ }
+ return new Response(null, { status: 302, headers: { Location: "/library/login?error=1" } });
+ }
+
+ // Library logout
+ if (path === "/library/logout" && request.method === "GET") {
+ return new Response(null, {
+ status: 302,
+ headers: {
+ Location: "/library/login",
+ "Set-Cookie": "voom_session=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0",
+ },
+ });
+ }
+
+ // Library dashboard (auth-gated)
+ // Internal asset is /lib.html (not /library.html) so the ASSETS binding
+ // does not auto-serve it before the worker runs (no run_worker_first needed).
+ if (path === "/library" && request.method === "GET") {
+ if (!(await isDashboardAuthed(request, env))) {
+ return new Response(null, { status: 302, headers: { Location: "/library/login" } });
+ }
+ return env.ASSETS.fetch(new Request(new URL("/lib", url), request));
+ }
+
+ // Library login page (public)
+ if (path === "/library/login" && request.method === "GET") {
+ return env.ASSETS.fetch(new Request(new URL("/lib-login", url), request));
+ }
+
+ // API routes (authenticated)
+ if (path.startsWith("/api/")) {
+ if (request.method === "OPTIONS") {
+ return new Response(null, {
+ headers: {
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
+ "Access-Control-Allow-Headers": "Authorization, Content-Type",
+ },
+ });
+ }
+
+ let ownerId = null;
+ if (hosted) {
+ const user = await hostedUser(request, env);
+ if (!user) return errorResponse("Verified sign-in required", 401);
+ ownerId = user.id;
+ if (!(await env.ACCOUNT_RATE_LIMIT.limit({ key: ownerId })).success)
+ return errorResponse("Too many account requests. Try again in a minute.", 429);
+ if (!["/api/health", "/api/videos", "/api/upload", "/api/check-views"].includes(path)) {
+ const route = path.match(
+ /^\/api\/(upload-data|upload-thumbnail|upload-multipart|upload-part|upload-complete|upload-abort|metadata|renew|delete)\/([a-z0-9]+)(?:\/([^/]+)(?:\/(\d+))?)?$/,
+ );
+ if (!route) return errorResponse("Not found", 404);
+ const expected =
+ {
+ "upload-data": "PUT",
+ "upload-thumbnail": "PUT",
+ "upload-part": "PUT",
+ delete: "DELETE",
+ }[route[1]] || "POST";
+ if (
+ request.method !== expected ||
+ (route[1] === "upload-part" ? !route[4] : route[4] !== undefined) ||
+ (["upload-part", "upload-complete", "upload-abort"].includes(route[1])
+ ? !route[3]
+ : route[3] !== undefined)
+ )
+ return errorResponse("Not found", 404);
+ return handleHostedRecording(request, env, ownerId, ...route.slice(1));
+ }
+ } else if (
+ !(await isAuthorized(request, env)) &&
+ !(await dashboardCookieAuthed(request, env))
+ ) {
+ return errorResponse("Unauthorized", 401);
+ }
+
+ // Connection check used by the desktop app to validate a worker URL + secret.
+ if (path === "/api/health" && request.method === "GET") {
+ return jsonResponse({ ok: true, app: "recordly" });
+ }
+
+ if (path === "/api/videos" && request.method === "GET") {
+ return handleListVideos(env, ownerId);
+ }
+
+ if (path === "/api/upload" && request.method === "POST") {
+ return handleUpload(request, env, ownerId);
+ }
+
+ const uploadDataMatch = path.match(/^\/api\/upload-data\/([a-z0-9]+)$/);
+ if (uploadDataMatch && request.method === "PUT") {
+ return handleUploadData(request, env, uploadDataMatch[1]);
+ }
+
+ const thumbnailMatch = path.match(/^\/api\/upload-thumbnail\/([a-z0-9]+)$/);
+ if (thumbnailMatch && request.method === "PUT") {
+ return handleUploadThumbnail(request, env, thumbnailMatch[1]);
+ }
+
+ const multipartStartMatch = path.match(/^\/api\/upload-multipart\/([a-z0-9]+)$/);
+ if (multipartStartMatch && request.method === "POST") {
+ return handleMultipartStart(request, env, multipartStartMatch[1]);
+ }
+
+ const multipartPartMatch = path.match(/^\/api\/upload-part\/([a-z0-9]+)\/(.+?)\/(\d+)$/);
+ if (multipartPartMatch && request.method === "PUT") {
+ const multipartUploadId = decodeUploadId(multipartPartMatch[2]);
+ if (!multipartUploadId) return errorResponse("Invalid multipart upload ID");
+ return handleMultipartPart(
+ request,
+ env,
+ multipartPartMatch[1],
+ multipartUploadId,
+ parseInt(multipartPartMatch[3], 10),
+ );
+ }
+
+ const multipartCompleteMatch = path.match(/^\/api\/upload-complete\/([a-z0-9]+)\/(.+)$/);
+ if (multipartCompleteMatch && request.method === "POST") {
+ const multipartUploadId = decodeUploadId(multipartCompleteMatch[2]);
+ if (!multipartUploadId) return errorResponse("Invalid multipart upload ID");
+ return handleMultipartComplete(
+ request,
+ env,
+ multipartCompleteMatch[1],
+ multipartUploadId,
+ );
+ }
+
+ const multipartAbortMatch = path.match(/^\/api\/upload-abort\/([a-z0-9]+)\/(.+)$/);
+ if (multipartAbortMatch && request.method === "POST") {
+ const multipartUploadId = decodeUploadId(multipartAbortMatch[2]);
+ if (!multipartUploadId) return errorResponse("Invalid multipart upload ID");
+ return handleMultipartAbort(request, env, multipartAbortMatch[1], multipartUploadId);
+ }
+
+ const metadataMatch = path.match(/^\/api\/metadata\/([a-z0-9]+)$/);
+ if (metadataMatch && request.method === "POST") {
+ return handleMetadata(request, env, metadataMatch[1]);
+ }
+
+ const renewMatch = path.match(/^\/api\/renew\/([a-z0-9]+)$/);
+ if (renewMatch && request.method === "POST") {
+ return handleRenew(env, renewMatch[1]);
+ }
+
+ const deleteMatch = path.match(/^\/api\/delete\/([a-z0-9]+)$/);
+ if (deleteMatch && request.method === "DELETE") {
+ return handleDelete(env, deleteMatch[1]);
+ }
+
+ if (path === "/api/check-views" && request.method === "POST") {
+ return handleCheckViews(
+ hosted
+ ? new Request(request.url, {
+ method: "POST",
+ body: JSON.stringify(await limitedJson(request, 16384)),
+ })
+ : request,
+ env,
+ ownerId,
+ );
+ }
+
+ return errorResponse("Not found", 404);
+ }
+
+ // CORS preflight for public endpoints
+ if (request.method === "OPTIONS") {
+ return new Response(null, {
+ headers: {
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
+ "Access-Control-Allow-Headers": "Content-Type",
+ },
+ });
+ }
+
+ if (hosted && request.method === "POST") {
+ request = new Request(request, { body: JSON.stringify(await limitedJson(request, 16384)) });
+ }
+
+ // Password verification (public)
+ const verifyMatch = path.match(/^\/s\/([a-z0-9]+)\/verify-password$/);
+ if (verifyMatch && request.method === "POST") {
+ return handleVerifyPassword(request, env, verifyMatch[1]);
+ }
+
+ // Share data endpoint (public, for SPA)
+ const dataMatch = path.match(/^\/s\/([a-z0-9]+)\/data$/);
+ if (dataMatch && request.method === "GET") {
+ return handleShareData(request, env, dataMatch[1]);
+ }
+
+ // Reactions (public)
+ const reactMatch = path.match(/^\/s\/([a-z0-9]+)\/react$/);
+ if (reactMatch && request.method === "POST") {
+ return handleReact(request, env, reactMatch[1]);
+ }
+ const reactGetMatch = path.match(/^\/s\/([a-z0-9]+)\/reactions$/);
+ if (reactGetMatch && request.method === "GET") {
+ return handleGetReactions(request, env, reactGetMatch[1]);
+ }
+
+ // Comments (public)
+ const commentMatch = path.match(/^\/s\/([a-z0-9]+)\/comment$/);
+ if (commentMatch && request.method === "POST") {
+ return handleComment(request, env, commentMatch[1]);
+ }
+ const commentGetMatch = path.match(/^\/s\/([a-z0-9]+)\/comments$/);
+ if (commentGetMatch && request.method === "GET") {
+ return handleGetComments(request, env, commentGetMatch[1]);
+ }
+
+ // VTT captions
+ const vttMatch = path.match(/^\/vtt\/([a-z0-9]+)$/);
+ if (vttMatch && request.method === "GET") {
+ return handleVTT(request, env, vttMatch[1]);
+ }
+
+ // Share page — serve Astro SPA or OG for bots
+ const shareMatch = path.match(/^\/s\/([a-z0-9]+)$/);
+ if (shareMatch && request.method === "GET") {
+ const shareCode = shareMatch[1];
+ const ua = request.headers.get("User-Agent") || "";
+ if (
+ /bot|crawl|spider|facebook|twitter|slack|discord|telegram|whatsapp|linkedin/i.test(ua)
+ ) {
+ return handleOGPage(request, env, shareCode);
+ }
+ return env.ASSETS.fetch(new Request(new URL("/share", url), request));
+ }
+
+ // Video streaming
+ const videoMatch = path.match(/^\/v\/([a-z0-9]+)$/);
+ if (videoMatch && request.method === "GET") {
+ return handleVideoStream(request, env, videoMatch[1]);
+ }
+
+ // OG image
+ const ogMatch = path.match(/^\/og\/([a-z0-9]+)$/);
+ if (ogMatch && request.method === "GET") {
+ return handleOGImage(env, ogMatch[1]);
+ }
+
+ // Embed player — serve Astro embed page
+ const embedMatch = path.match(/^\/embed\/([a-z0-9]+)$/);
+ if (embedMatch && request.method === "GET") {
+ return env.ASSETS.fetch(new Request(new URL("/embed", url), request));
+ }
+
+ // Thumbnail (high-res poster) — gated like the OG image: the poster frame
+ // of a password-protected or expired video may itself be sensitive.
+ const thumbMatch = path.match(/^\/thumb\/([a-z0-9]+)$/);
+ if (thumbMatch && request.method === "GET") {
+ const video = await env.DB.prepare(
+ "SELECT password_hash, expires_at FROM videos WHERE share_code = ? AND datetime(expires_at) > datetime('now')",
+ )
+ .bind(thumbMatch[1])
+ .first();
+ if (!video) return new Response("Not found", { status: 404 });
+ if (!(await verifyPasswordAuth(request, env, thumbMatch[1], video))) {
+ return new Response("Not found", { status: 404 });
+ }
+ const thumb = await env.VIDEOS_BUCKET.get(`thumbnails/${thumbMatch[1]}.jpg`);
+ if (thumb) {
+ return new Response(thumb.body, {
+ // Recheck the unlock cookie on every protected poster request.
+ headers: {
+ "Content-Type": "image/jpeg",
+ "Cache-Control": video.password_hash
+ ? "private, no-store"
+ : "public, max-age=86400",
+ },
+ });
+ }
+ return new Response("Not found", { status: 404 });
+ }
+
+ // Static assets from R2
+ if (path === "/icon-64.png" && request.method === "GET") {
+ const obj = await env.VIDEOS_BUCKET.get("static/icon-64.png");
+ if (obj) {
+ return new Response(obj.body, {
+ headers: { "Content-Type": "image/png", "Cache-Control": "public, max-age=604800" },
+ });
+ }
+ }
+
+ if (path === "/") {
+ return new Response("Recordly Share", { status: 200 });
+ }
+
+ // Fall through to static assets
+ return env.ASSETS.fetch(request);
}
diff --git a/services/recordly-share/worker/src/schema.js b/services/recordly-share/worker/src/schema.js
index cd50b1f4..d670f441 100644
--- a/services/recordly-share/worker/src/schema.js
+++ b/services/recordly-share/worker/src/schema.js
@@ -1,8 +1,6 @@
// Adapted from Voom (MIT), Copyright (c) 2026 Aritro Paul.
// See ../../LICENSE and ../../../../THIRD_PARTY_NOTICES.md for attribution.
-
-
// --- Self-bootstrap: runtime schema migration ---
// When deployed via the "Deploy to Cloudflare" button, D1 is auto-provisioned
// empty, so the worker migrates its own schema at runtime on first request.
@@ -14,10 +12,10 @@ const SCHEMA_VERSION = 5;
// statements are idempotent, so this is safe on both fresh (button-deployed)
// and existing (token-deployed) databases.
const SCHEMA_STATEMENTS = [
- `CREATE TABLE IF NOT EXISTS recording_uploads (share_code TEXT PRIMARY KEY REFERENCES videos(share_code) ON DELETE CASCADE, upload_id TEXT NOT NULL)`,
- `CREATE TABLE IF NOT EXISTS recording_locks (share_code TEXT PRIMARY KEY, token TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT (datetime('now')))`,
+ `CREATE TABLE IF NOT EXISTS recording_uploads (share_code TEXT PRIMARY KEY REFERENCES videos(share_code) ON DELETE CASCADE, upload_id TEXT NOT NULL)`,
+ `CREATE TABLE IF NOT EXISTS recording_locks (share_code TEXT PRIMARY KEY, token TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT (datetime('now')))`,
- `CREATE TABLE IF NOT EXISTS videos (
+ `CREATE TABLE IF NOT EXISTS videos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
share_code TEXT UNIQUE NOT NULL,
title TEXT NOT NULL,
@@ -39,10 +37,10 @@ const SCHEMA_STATEMENTS = [
password_salt TEXT,
owner_id TEXT
)`,
- `CREATE INDEX IF NOT EXISTS idx_videos_owner ON videos(owner_id)`,
- `CREATE INDEX IF NOT EXISTS idx_videos_share_code ON videos(share_code)`,
- `CREATE INDEX IF NOT EXISTS idx_videos_expires_at ON videos(expires_at)`,
- `CREATE TABLE IF NOT EXISTS transcript_segments (
+ `CREATE INDEX IF NOT EXISTS idx_videos_owner ON videos(owner_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_videos_share_code ON videos(share_code)`,
+ `CREATE INDEX IF NOT EXISTS idx_videos_expires_at ON videos(expires_at)`,
+ `CREATE TABLE IF NOT EXISTS transcript_segments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
video_id INTEGER NOT NULL REFERENCES videos(id) ON DELETE CASCADE,
start_time REAL NOT NULL,
@@ -50,8 +48,8 @@ const SCHEMA_STATEMENTS = [
text TEXT NOT NULL,
speaker TEXT
)`,
- `CREATE INDEX IF NOT EXISTS idx_transcript_video_id ON transcript_segments(video_id)`,
- `CREATE TABLE IF NOT EXISTS reactions (
+ `CREATE INDEX IF NOT EXISTS idx_transcript_video_id ON transcript_segments(video_id)`,
+ `CREATE TABLE IF NOT EXISTS reactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
video_id INTEGER NOT NULL REFERENCES videos(id) ON DELETE CASCADE,
timestamp REAL NOT NULL,
@@ -59,9 +57,9 @@ const SCHEMA_STATEMENTS = [
client_ip TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)`,
- `CREATE INDEX IF NOT EXISTS idx_reactions_video_id ON reactions(video_id)`,
- `CREATE INDEX IF NOT EXISTS idx_reactions_ip ON reactions(video_id, client_ip)`,
- `CREATE TABLE IF NOT EXISTS comments (
+ `CREATE INDEX IF NOT EXISTS idx_reactions_video_id ON reactions(video_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_reactions_ip ON reactions(video_id, client_ip)`,
+ `CREATE TABLE IF NOT EXISTS comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
video_id INTEGER NOT NULL REFERENCES videos(id) ON DELETE CASCADE,
timestamp REAL NOT NULL,
@@ -70,22 +68,22 @@ const SCHEMA_STATEMENTS = [
created_at TEXT NOT NULL DEFAULT (datetime('now')),
client_ip TEXT NOT NULL DEFAULT ''
)`,
- `CREATE INDEX IF NOT EXISTS idx_comments_video_id ON comments(video_id)`,
- `CREATE TABLE IF NOT EXISTS chapters (
+ `CREATE INDEX IF NOT EXISTS idx_comments_video_id ON comments(video_id)`,
+ `CREATE TABLE IF NOT EXISTS chapters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
video_id INTEGER NOT NULL REFERENCES videos(id) ON DELETE CASCADE,
timestamp REAL NOT NULL,
title TEXT NOT NULL
)`,
- `CREATE INDEX IF NOT EXISTS idx_chapters_video_id ON chapters(video_id)`,
- `CREATE TABLE IF NOT EXISTS password_attempts (
+ `CREATE INDEX IF NOT EXISTS idx_chapters_video_id ON chapters(video_id)`,
+ `CREATE TABLE IF NOT EXISTS password_attempts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
video_id INTEGER NOT NULL,
client_ip TEXT NOT NULL,
attempted_at TEXT NOT NULL DEFAULT (datetime('now'))
)`,
- `CREATE INDEX IF NOT EXISTS idx_password_attempts ON password_attempts(video_id, client_ip, attempted_at)`,
- `CREATE TABLE IF NOT EXISTS comment_users (
+ `CREATE INDEX IF NOT EXISTS idx_password_attempts ON password_attempts(video_id, client_ip, attempted_at)`,
+ `CREATE TABLE IF NOT EXISTS comment_users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
display_name TEXT NOT NULL,
@@ -93,14 +91,14 @@ const SCHEMA_STATEMENTS = [
password_salt TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)`,
- `CREATE TABLE IF NOT EXISTS comment_sessions (
+ `CREATE TABLE IF NOT EXISTS comment_sessions (
token_hash TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES comment_users(id) ON DELETE CASCADE,
expires_at TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)`,
- `CREATE INDEX IF NOT EXISTS idx_comment_sessions_user ON comment_sessions(user_id)`,
- `CREATE INDEX IF NOT EXISTS idx_comment_sessions_expiry ON comment_sessions(expires_at)`,
+ `CREATE INDEX IF NOT EXISTS idx_comment_sessions_user ON comment_sessions(user_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_comment_sessions_expiry ON comment_sessions(expires_at)`,
];
// Incremental migrations for databases that are already at an older version.
@@ -108,27 +106,27 @@ const SCHEMA_STATEMENTS = [
// cannot add columns to existing tables), so any change that ALTERs an
// existing table MUST appear here under a bumped SCHEMA_VERSION.
const SCHEMA_MIGRATIONS = {
- 5: [
- `CREATE TABLE IF NOT EXISTS recording_uploads (share_code TEXT PRIMARY KEY REFERENCES videos(share_code) ON DELETE CASCADE, upload_id TEXT NOT NULL)`,
- `CREATE TABLE IF NOT EXISTS recording_locks (share_code TEXT PRIMARY KEY, token TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT (datetime('now')))`,
- ],
- 4: [
- `ALTER TABLE videos ADD COLUMN owner_id TEXT`,
- `CREATE INDEX IF NOT EXISTS idx_videos_owner ON videos(owner_id)`,
- ],
- 2: [
- `CREATE INDEX IF NOT EXISTS idx_chapters_video_id ON chapters(video_id)`,
- `ALTER TABLE videos ADD COLUMN password_salt TEXT`,
- `CREATE TABLE IF NOT EXISTS password_attempts (
+ 5: [
+ `CREATE TABLE IF NOT EXISTS recording_uploads (share_code TEXT PRIMARY KEY REFERENCES videos(share_code) ON DELETE CASCADE, upload_id TEXT NOT NULL)`,
+ `CREATE TABLE IF NOT EXISTS recording_locks (share_code TEXT PRIMARY KEY, token TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT (datetime('now')))`,
+ ],
+ 4: [
+ `ALTER TABLE videos ADD COLUMN owner_id TEXT`,
+ `CREATE INDEX IF NOT EXISTS idx_videos_owner ON videos(owner_id)`,
+ ],
+ 2: [
+ `CREATE INDEX IF NOT EXISTS idx_chapters_video_id ON chapters(video_id)`,
+ `ALTER TABLE videos ADD COLUMN password_salt TEXT`,
+ `CREATE TABLE IF NOT EXISTS password_attempts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
video_id INTEGER NOT NULL,
client_ip TEXT NOT NULL,
attempted_at TEXT NOT NULL DEFAULT (datetime('now'))
)`,
- `CREATE INDEX IF NOT EXISTS idx_password_attempts ON password_attempts(video_id, client_ip, attempted_at)`,
- ],
- 3: [
- `CREATE TABLE IF NOT EXISTS comment_users (
+ `CREATE INDEX IF NOT EXISTS idx_password_attempts ON password_attempts(video_id, client_ip, attempted_at)`,
+ ],
+ 3: [
+ `CREATE TABLE IF NOT EXISTS comment_users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
display_name TEXT NOT NULL,
@@ -136,15 +134,15 @@ const SCHEMA_MIGRATIONS = {
password_salt TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)`,
- `CREATE TABLE IF NOT EXISTS comment_sessions (
+ `CREATE TABLE IF NOT EXISTS comment_sessions (
token_hash TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES comment_users(id) ON DELETE CASCADE,
expires_at TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)`,
- `CREATE INDEX IF NOT EXISTS idx_comment_sessions_user ON comment_sessions(user_id)`,
- `CREATE INDEX IF NOT EXISTS idx_comment_sessions_expiry ON comment_sessions(expires_at)`,
- ],
+ `CREATE INDEX IF NOT EXISTS idx_comment_sessions_user ON comment_sessions(user_id)`,
+ `CREATE INDEX IF NOT EXISTS idx_comment_sessions_expiry ON comment_sessions(expires_at)`,
+ ],
};
let schemaReady = false;
@@ -152,67 +150,73 @@ let schemaReady = false;
// Test-only: lets the vitest suite force ensureSchema to re-run after it
// rebuilds the database into an older shape. Never called in production.
export function __resetSchemaCacheForTests() {
- schemaReady = false;
+ schemaReady = false;
}
export async function ensureSchema(env) {
- if (schemaReady) return;
- await env.DB.prepare(`CREATE TABLE IF NOT EXISTS _meta (key TEXT PRIMARY KEY, value TEXT)`).run();
- const row = await env.DB.prepare(`SELECT value FROM _meta WHERE key = 'schema_version'`).first();
- let current = row ? parseInt(row.value, 10) : 0;
+ if (schemaReady) return;
+ await env.DB.prepare(
+ `CREATE TABLE IF NOT EXISTS _meta (key TEXT PRIMARY KEY, value TEXT)`,
+ ).run();
+ const row = await env.DB.prepare(
+ `SELECT value FROM _meta WHERE key = 'schema_version'`,
+ ).first();
+ let current = row ? parseInt(row.value, 10) : 0;
- if (current === 0) {
- // No version stamp ≠ fresh: databases created before versioning existed
- // have tables but no _meta row. Treating one as fresh would skip the
- // ALTERs (CREATE TABLE IF NOT EXISTS no-ops on existing tables).
- const videos = await env.DB.prepare(
- `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'videos'`
- ).first();
- if (videos) current = 1;
- }
+ if (current === 0) {
+ // No version stamp ≠ fresh: databases created before versioning existed
+ // have tables but no _meta row. Treating one as fresh would skip the
+ // ALTERs (CREATE TABLE IF NOT EXISTS no-ops on existing tables).
+ const videos = await env.DB.prepare(
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'videos'`,
+ ).first();
+ if (videos) current = 1;
+ }
- if (current >= 2) {
- // Repair pass: v4.1.0 stamped pre-versioning databases as current without
- // running the v2 ALTERs. If anything v2 introduced is missing, rewind so
- // the migration loop below re-runs (its statements tolerate re-application).
- const cols = await env.DB.prepare(`PRAGMA table_info(videos)`).all();
- const attempts = await env.DB.prepare(
- `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'password_attempts'`
- ).first();
- if (!(cols.results || []).some(c => c.name === 'password_salt') || !attempts) current = 1;
- }
+ if (current >= 2) {
+ // Repair pass: v4.1.0 stamped pre-versioning databases as current without
+ // running the v2 ALTERs. If anything v2 introduced is missing, rewind so
+ // the migration loop below re-runs (its statements tolerate re-application).
+ const cols = await env.DB.prepare(`PRAGMA table_info(videos)`).all();
+ const attempts = await env.DB.prepare(
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'password_attempts'`,
+ ).first();
+ if (!(cols.results || []).some((c) => c.name === "password_salt") || !attempts) current = 1;
+ }
- if (current >= 3) {
- const commentUsers = await env.DB.prepare(
- `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'comment_users'`
- ).first();
- const commentSessions = await env.DB.prepare(
- `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'comment_sessions'`
- ).first();
- if (!commentUsers || !commentSessions) current = 2;
- }
+ if (current >= 3) {
+ const commentUsers = await env.DB.prepare(
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'comment_users'`,
+ ).first();
+ const commentSessions = await env.DB.prepare(
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'comment_sessions'`,
+ ).first();
+ if (!commentUsers || !commentSessions) current = 2;
+ }
- if (current < SCHEMA_VERSION) {
- if (current === 0) {
- // Fresh database: the consolidated schema already reflects every migration.
- await env.DB.batch(SCHEMA_STATEMENTS.map(sql => env.DB.prepare(sql)));
- } else {
- // Existing database: apply each migration step in order. ALTER TABLE
- // is not idempotent, so tolerate duplicate-column errors from re-runs.
- for (let v = current + 1; v <= SCHEMA_VERSION; v++) {
- for (const sql of SCHEMA_MIGRATIONS[v] || []) {
- try {
- await env.DB.prepare(sql).run();
- } catch (e) {
- if (!/duplicate column|already exists/i.test(e.message || '')) throw e;
- }
- }
- }
- }
- await env.DB.prepare(
- `INSERT INTO _meta (key, value) VALUES ('schema_version', ?)
- ON CONFLICT(key) DO UPDATE SET value = excluded.value`
- ).bind(String(SCHEMA_VERSION)).run();
- }
- schemaReady = true;
+ if (current < SCHEMA_VERSION) {
+ if (current === 0) {
+ // Fresh database: the consolidated schema already reflects every migration.
+ await env.DB.batch(SCHEMA_STATEMENTS.map((sql) => env.DB.prepare(sql)));
+ } else {
+ // Existing database: apply each migration step in order. ALTER TABLE
+ // is not idempotent, so tolerate duplicate-column errors from re-runs.
+ for (let v = current + 1; v <= SCHEMA_VERSION; v++) {
+ for (const sql of SCHEMA_MIGRATIONS[v] || []) {
+ try {
+ await env.DB.prepare(sql).run();
+ } catch (e) {
+ if (!/duplicate column|already exists/i.test(e.message || "")) throw e;
+ }
+ }
+ }
+ }
+ await env.DB.prepare(
+ `INSERT INTO _meta (key, value) VALUES ('schema_version', ?)
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
+ )
+ .bind(String(SCHEMA_VERSION))
+ .run();
+ }
+ schemaReady = true;
}
diff --git a/services/recordly-share/worker/src/uploads.js b/services/recordly-share/worker/src/uploads.js
index 116fbad7..94162bf0 100644
--- a/services/recordly-share/worker/src/uploads.js
+++ b/services/recordly-share/worker/src/uploads.js
@@ -1,206 +1,277 @@
// Adapted from Voom (MIT), Copyright (c) 2026 Aritro Paul.
// See ../../LICENSE and ../../../../THIRD_PARTY_NOTICES.md for attribution.
-import { limitedJson, MAX_RECORDING_BYTES } from './hostedUploads.js';
-import { errorResponse, jsonResponse } from './http.js';
-import { EXPIRY_DAYS, FREE_EXPIRY_DAYS, finiteNonnegative } from './video.js';
-import { generateSalt, hashRecordingPassword } from './crypto.js';
+import { limitedJson, MAX_RECORDING_BYTES } from "./hostedUploads.js";
+import { errorResponse, jsonResponse } from "./http.js";
+import { EXPIRY_DAYS, FREE_EXPIRY_DAYS, finiteNonnegative } from "./video.js";
+import { generateSalt, hashRecordingPassword } from "./crypto.js";
export function generateShareCode() {
- const bytes = new Uint8Array(32);
- crypto.getRandomValues(bytes);
- return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
+ const bytes = new Uint8Array(32);
+ crypto.getRandomValues(bytes);
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
}
export async function handleUpload(request, env, ownerId = null) {
- const body = ownerId ? await limitedJson(request, 16384) : await request.json();
- const { title, duration, width, height, hasWebcam, fileSize, password_hash, cta_url, cta_text } = body;
-
- if (ownerId && (!Number.isSafeInteger(fileSize) || fileSize <= 0 || fileSize > MAX_RECORDING_BYTES)) return errorResponse('Free recordings must be between 1 byte and 1 GB', 413);
- if (ownerId && (typeof title !== 'string' || !title.trim() || title.length > 200)) return errorResponse('Title must be between 1 and 200 characters');
- if (ownerId && ((cta_url && (typeof cta_url !== 'string' || cta_url.length > 2048)) || (cta_text && (typeof cta_text !== 'string' || cta_text.length > 200)) || (password_hash && (typeof password_hash !== 'string' || !/^[a-f0-9]{64}$/.test(password_hash))))) return errorResponse('Invalid recording options');
- if (!title) return errorResponse('title is required');
- if (password_hash && !env.API_SECRET) return errorResponse('Password protection is not configured', 503);
-
- // CTA links render as <a href> on the share page — only allow web URLs so a
- // stored javascript:/data: URL can never reach that sink.
- if (cta_url && !/^https?:\/\//i.test(cta_url)) {
- return errorResponse('cta_url must be an http(s) URL');
- }
-
- const shareCode = generateShareCode();
- const expiresAt = new Date(Date.now() + (ownerId ? FREE_EXPIRY_DAYS : EXPIRY_DAYS) * 24 * 60 * 60 * 1000).toISOString();
-
- // Versioned slow hash of the client digest, with a unique per-record salt.
- let storedHash = null;
- let salt = null;
- if (password_hash) {
- salt = generateSalt();
- storedHash = await hashRecordingPassword(password_hash, salt);
- }
-
- const inserted = await env.DB.prepare(
- `INSERT INTO videos (share_code, title, duration, width, height, has_webcam, file_size, expires_at, password_hash, password_salt, cta_url, cta_text, owner_id)
+ const body = ownerId ? await limitedJson(request, 16384) : await request.json();
+ const {
+ title,
+ duration,
+ width,
+ height,
+ hasWebcam,
+ fileSize,
+ password_hash,
+ cta_url,
+ cta_text,
+ } = body;
+
+ if (
+ ownerId &&
+ (!Number.isSafeInteger(fileSize) || fileSize <= 0 || fileSize > MAX_RECORDING_BYTES)
+ )
+ return errorResponse("Free recordings must be between 1 byte and 1 GB", 413);
+ if (ownerId && (typeof title !== "string" || !title.trim() || title.length > 200))
+ return errorResponse("Title must be between 1 and 200 characters");
+ if (
+ ownerId &&
+ ((cta_url && (typeof cta_url !== "string" || cta_url.length > 2048)) ||
+ (cta_text && (typeof cta_text !== "string" || cta_text.length > 200)) ||
+ (password_hash &&
+ (typeof password_hash !== "string" || !/^[a-f0-9]{64}$/.test(password_hash))))
+ )
+ return errorResponse("Invalid recording options");
+ if (!title) return errorResponse("title is required");
+ if (password_hash && !env.API_SECRET)
+ return errorResponse("Password protection is not configured", 503);
+
+ // CTA links render as <a href> on the share page — only allow web URLs so a
+ // stored javascript:/data: URL can never reach that sink.
+ if (cta_url && !/^https?:\/\//i.test(cta_url)) {
+ return errorResponse("cta_url must be an http(s) URL");
+ }
+
+ const shareCode = generateShareCode();
+ const expiresAt = new Date(
+ Date.now() + (ownerId ? FREE_EXPIRY_DAYS : EXPIRY_DAYS) * 24 * 60 * 60 * 1000,
+ ).toISOString();
+
+ // Versioned slow hash of the client digest, with a unique per-record salt.
+ let storedHash = null;
+ let salt = null;
+ if (password_hash) {
+ salt = generateSalt();
+ storedHash = await hashRecordingPassword(password_hash, salt);
+ }
+
+ const inserted = await env.DB.prepare(
+ `INSERT INTO videos (share_code, title, duration, width, height, has_webcam, file_size, expires_at, password_hash, password_salt, cta_url, cta_text, owner_id)
SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
- WHERE ? IS NULL OR (SELECT COUNT(*) FROM videos WHERE owner_id = ?) < 5`
- )
- .bind(shareCode, title, finiteNonnegative(duration), finiteNonnegative(width), finiteNonnegative(height), hasWebcam ? 1 : 0, finiteNonnegative(fileSize), expiresAt, storedHash, salt, cta_url || null, cta_text || null, ownerId, ownerId, ownerId)
- .run();
-
- // The count and reservation are one SQLite statement: parallel requests cannot
- // claim the sixth slot. Pending and expired rows count until explicitly deleted.
- if (inserted.meta.changes === 0) return errorResponse('Free accounts can store up to 5 recordings. Delete one before uploading another.', 409);
-
- const baseUrl = new URL(request.url).origin;
-
- return jsonResponse({
- shareCode,
- uploadURL: `${baseUrl}/api/upload-data/${shareCode}`,
- shareURL: `${baseUrl}/s/${shareCode}`,
- expiresAt,
- });
+ WHERE ? IS NULL OR (SELECT COUNT(*) FROM videos WHERE owner_id = ?) < 5`,
+ )
+ .bind(
+ shareCode,
+ title,
+ finiteNonnegative(duration),
+ finiteNonnegative(width),
+ finiteNonnegative(height),
+ hasWebcam ? 1 : 0,
+ finiteNonnegative(fileSize),
+ expiresAt,
+ storedHash,
+ salt,
+ cta_url || null,
+ cta_text || null,
+ ownerId,
+ ownerId,
+ ownerId,
+ )
+ .run();
+
+ // The count and reservation are one SQLite statement: parallel requests cannot
+ // claim the sixth slot. Pending and expired rows count until explicitly deleted.
+ if (inserted.meta.changes === 0)
+ return errorResponse(
+ "Free accounts can store up to 5 recordings. Delete one before uploading another.",
+ 409,
+ );
+
+ const baseUrl = new URL(request.url).origin;
+
+ return jsonResponse({
+ shareCode,
+ uploadURL: `${baseUrl}/api/upload-data/${shareCode}`,
+ shareURL: `${baseUrl}/s/${shareCode}`,
+ expiresAt,
+ });
}
export async function handleUploadData(request, env, shareCode) {
- const video = await env.DB.prepare('SELECT id FROM videos WHERE share_code = ?').bind(shareCode).first();
- if (!video) return errorResponse('Video not found', 404);
+ const video = await env.DB.prepare("SELECT id FROM videos WHERE share_code = ?")
+ .bind(shareCode)
+ .first();
+ if (!video) return errorResponse("Video not found", 404);
- const contentType = request.headers.get('Content-Type') || 'video/mp4';
+ const contentType = request.headers.get("Content-Type") || "video/mp4";
- await env.VIDEOS_BUCKET.put(`videos/${shareCode}.mp4`, request.body, {
- httpMetadata: { contentType },
- });
+ await env.VIDEOS_BUCKET.put(`videos/${shareCode}.mp4`, request.body, {
+ httpMetadata: { contentType },
+ });
- return jsonResponse({ ok: true });
+ return jsonResponse({ ok: true });
}
export async function handleUploadThumbnail(request, env, shareCode) {
- const video = await env.DB.prepare('SELECT id FROM videos WHERE share_code = ?').bind(shareCode).first();
- if (!video) return errorResponse('Video not found', 404);
+ const video = await env.DB.prepare("SELECT id FROM videos WHERE share_code = ?")
+ .bind(shareCode)
+ .first();
+ if (!video) return errorResponse("Video not found", 404);
- const contentType = request.headers.get('Content-Type') || 'image/jpeg';
+ const contentType = request.headers.get("Content-Type") || "image/jpeg";
- await env.VIDEOS_BUCKET.put(`thumbnails/${shareCode}.jpg`, request.body, {
- httpMetadata: { contentType },
- });
+ await env.VIDEOS_BUCKET.put(`thumbnails/${shareCode}.jpg`, request.body, {
+ httpMetadata: { contentType },
+ });
- return jsonResponse({ ok: true });
+ return jsonResponse({ ok: true });
}
export async function handleMultipartStart(request, env, shareCode) {
- const video = await env.DB.prepare('SELECT id FROM videos WHERE share_code = ?').bind(shareCode).first();
- if (!video) return errorResponse('Video not found', 404);
+ const video = await env.DB.prepare("SELECT id FROM videos WHERE share_code = ?")
+ .bind(shareCode)
+ .first();
+ if (!video) return errorResponse("Video not found", 404);
- const key = `videos/${shareCode}.mp4`;
- const multipartUpload = await env.VIDEOS_BUCKET.createMultipartUpload(key, {
- httpMetadata: { contentType: 'video/mp4' },
- });
+ const key = `videos/${shareCode}.mp4`;
+ const multipartUpload = await env.VIDEOS_BUCKET.createMultipartUpload(key, {
+ httpMetadata: { contentType: "video/mp4" },
+ });
- return jsonResponse({ uploadId: multipartUpload.uploadId });
+ return jsonResponse({ uploadId: multipartUpload.uploadId });
}
export function decodeUploadId(value) {
- try {
- const decoded = decodeURIComponent(value);
- return decoded && decoded.length <= 2048 ? decoded : null;
- } catch {
- return null;
- }
+ try {
+ const decoded = decodeURIComponent(value);
+ return decoded && decoded.length <= 2048 ? decoded : null;
+ } catch {
+ return null;
+ }
}
export async function handleMultipartPart(request, env, shareCode, uploadId, partNumber) {
- const video = await env.DB.prepare('SELECT id FROM videos WHERE share_code = ?').bind(shareCode).first();
- if (!video) return errorResponse('Video not found', 404);
- if (!Number.isInteger(partNumber) || partNumber < 1 || partNumber > 10000) {
- return errorResponse('Invalid multipart part number');
- }
+ const video = await env.DB.prepare("SELECT id FROM videos WHERE share_code = ?")
+ .bind(shareCode)
+ .first();
+ if (!video) return errorResponse("Video not found", 404);
+ if (!Number.isInteger(partNumber) || partNumber < 1 || partNumber > 10000) {
+ return errorResponse("Invalid multipart part number");
+ }
- const key = `videos/${shareCode}.mp4`;
- const multipartUpload = env.VIDEOS_BUCKET.resumeMultipartUpload(key, uploadId);
+ const key = `videos/${shareCode}.mp4`;
+ const multipartUpload = env.VIDEOS_BUCKET.resumeMultipartUpload(key, uploadId);
- const part = await multipartUpload.uploadPart(partNumber, request.body);
+ const part = await multipartUpload.uploadPart(partNumber, request.body);
- return jsonResponse({ partNumber: part.partNumber, etag: part.etag });
+ return jsonResponse({ partNumber: part.partNumber, etag: part.etag });
}
export async function handleMultipartAbort(request, env, shareCode, uploadId) {
- const key = `videos/${shareCode}.mp4`;
- try {
- const multipartUpload = env.VIDEOS_BUCKET.resumeMultipartUpload(key, uploadId);
- await multipartUpload.abort();
- } catch (_e) {
- // Ignore errors — upload may already be completed or expired
- }
- return jsonResponse({ ok: true });
+ const key = `videos/${shareCode}.mp4`;
+ try {
+ const multipartUpload = env.VIDEOS_BUCKET.resumeMultipartUpload(key, uploadId);
+ await multipartUpload.abort();
+ } catch (_e) {
+ // Ignore errors — upload may already be completed or expired
+ }
+ return jsonResponse({ ok: true });
}
export async function handleMultipartComplete(request, env, shareCode, uploadId) {
- const video = await env.DB.prepare('SELECT id FROM videos WHERE share_code = ?').bind(shareCode).first();
- if (!video) return errorResponse('Video not found', 404);
-
- const key = `videos/${shareCode}.mp4`;
- const multipartUpload = env.VIDEOS_BUCKET.resumeMultipartUpload(key, uploadId);
-
- const body = await request.json();
- const parts = body.parts; // [{ partNumber, etag }, ...]
- if (!Array.isArray(parts) || parts.length === 0 || parts.length > 10000) {
- return errorResponse('Invalid multipart parts');
- }
- if (parts.some(part =>
- !part ||
- !Number.isInteger(part.partNumber) ||
- part.partNumber < 1 ||
- part.partNumber > 10000 ||
- typeof part.etag !== 'string' ||
- !part.etag
- )) {
- return errorResponse('Invalid multipart parts');
- }
-
- await multipartUpload.complete(parts);
-
- return jsonResponse({ ok: true });
+ const video = await env.DB.prepare("SELECT id FROM videos WHERE share_code = ?")
+ .bind(shareCode)
+ .first();
+ if (!video) return errorResponse("Video not found", 404);
+
+ const key = `videos/${shareCode}.mp4`;
+ const multipartUpload = env.VIDEOS_BUCKET.resumeMultipartUpload(key, uploadId);
+
+ const body = await request.json();
+ const parts = body.parts; // [{ partNumber, etag }, ...]
+ if (!Array.isArray(parts) || parts.length === 0 || parts.length > 10000) {
+ return errorResponse("Invalid multipart parts");
+ }
+ if (
+ parts.some(
+ (part) =>
+ !part ||
+ !Number.isInteger(part.partNumber) ||
+ part.partNumber < 1 ||
+ part.partNumber > 10000 ||
+ typeof part.etag !== "string" ||
+ !part.etag,
+ )
+ ) {
+ return errorResponse("Invalid multipart parts");
+ }
+
+ await multipartUpload.complete(parts);
+
+ return jsonResponse({ ok: true });
}
export async function handleMetadata(request, env, shareCode) {
- const video = await env.DB.prepare('SELECT id FROM videos WHERE share_code = ?').bind(shareCode).first();
- if (!video) return errorResponse('Video not found', 404);
-
- const body = await request.json();
- const { segments, title, summary, chapters, isMeeting } = body;
-
- // Chunk inserts so a multi-hour transcript can't exceed D1 batch limits.
- const BATCH_CHUNK = 100;
- if (segments && segments.length > 0) {
- const stmt = env.DB.prepare(
- 'INSERT INTO transcript_segments (video_id, start_time, end_time, text, speaker) VALUES (?, ?, ?, ?, ?)'
- );
- const batch = segments.map(seg => stmt.bind(video.id, seg.startTime, seg.endTime, seg.text, seg.speaker || null));
- for (let i = 0; i < batch.length; i += BATCH_CHUNK) {
- await env.DB.batch(batch.slice(i, i + BATCH_CHUNK));
- }
- }
-
- if (chapters && chapters.length > 0) {
- const stmt = env.DB.prepare(
- 'INSERT INTO chapters (video_id, timestamp, title) VALUES (?, ?, ?)'
- );
- const batch = chapters.map(ch => stmt.bind(video.id, ch.timestamp, ch.title));
- for (let i = 0; i < batch.length; i += BATCH_CHUNK) {
- await env.DB.batch(batch.slice(i, i + BATCH_CHUNK));
- }
- }
-
- // Update title, summary, is_meeting, and mark upload complete
- const updateFields = ['upload_completed = 1'];
- const updateBinds = [];
- if (title) { updateFields.push('title = ?'); updateBinds.push(title); }
- if (summary !== undefined) { updateFields.push('summary = ?'); updateBinds.push(summary || null); }
- if (isMeeting !== undefined) { updateFields.push('is_meeting = ?'); updateBinds.push(isMeeting ? 1 : 0); }
- updateBinds.push(shareCode);
- await env.DB.prepare(
- `UPDATE videos SET ${updateFields.join(', ')} WHERE share_code = ?`
- ).bind(...updateBinds).run();
-
- return jsonResponse({ ok: true });
+ const video = await env.DB.prepare("SELECT id FROM videos WHERE share_code = ?")
+ .bind(shareCode)
+ .first();
+ if (!video) return errorResponse("Video not found", 404);
+
+ const body = await request.json();
+ const { segments, title, summary, chapters, isMeeting } = body;
+
+ // Chunk inserts so a multi-hour transcript can't exceed D1 batch limits.
+ const BATCH_CHUNK = 100;
+ if (segments && segments.length > 0) {
+ const stmt = env.DB.prepare(
+ "INSERT INTO transcript_segments (video_id, start_time, end_time, text, speaker) VALUES (?, ?, ?, ?, ?)",
+ );
+ const batch = segments.map((seg) =>
+ stmt.bind(video.id, seg.startTime, seg.endTime, seg.text, seg.speaker || null),
+ );
+ for (let i = 0; i < batch.length; i += BATCH_CHUNK) {
+ await env.DB.batch(batch.slice(i, i + BATCH_CHUNK));
+ }
+ }
+
+ if (chapters && chapters.length > 0) {
+ const stmt = env.DB.prepare(
+ "INSERT INTO chapters (video_id, timestamp, title) VALUES (?, ?, ?)",
+ );
+ const batch = chapters.map((ch) => stmt.bind(video.id, ch.timestamp, ch.title));
+ for (let i = 0; i < batch.length; i += BATCH_CHUNK) {
+ await env.DB.batch(batch.slice(i, i + BATCH_CHUNK));
+ }
+ }
+
+ // Update title, summary, is_meeting, and mark upload complete
+ const updateFields = ["upload_completed = 1"];
+ const updateBinds = [];
+ if (title) {
+ updateFields.push("title = ?");
+ updateBinds.push(title);
+ }
+ if (summary !== undefined) {
+ updateFields.push("summary = ?");
+ updateBinds.push(summary || null);
+ }
+ if (isMeeting !== undefined) {
+ updateFields.push("is_meeting = ?");
+ updateBinds.push(isMeeting ? 1 : 0);
+ }
+ updateBinds.push(shareCode);
+ await env.DB.prepare(`UPDATE videos SET ${updateFields.join(", ")} WHERE share_code = ?`)
+ .bind(...updateBinds)
+ .run();
+
+ return jsonResponse({ ok: true });
}
diff --git a/services/recordly-share/worker/src/video.js b/services/recordly-share/worker/src/video.js
index 3066f63b..58a1a111 100644
--- a/services/recordly-share/worker/src/video.js
+++ b/services/recordly-share/worker/src/video.js
@@ -6,6 +6,6 @@ export const EXPIRY_DAYS = 30;
export const FREE_EXPIRY_DAYS = 14;
export function finiteNonnegative(value) {
- const number = Number(value);
- return Number.isFinite(number) && number >= 0 ? number : 0;
+ const number = Number(value);
+ return Number.isFinite(number) && number >= 0 ? number : 0;
}
diff --git a/services/recordly-share/worker/test/hosted.test.js b/services/recordly-share/worker/test/hosted.test.js
index 1399971d..f3cf1762 100644
--- a/services/recordly-share/worker/test/hosted.test.js
+++ b/services/recordly-share/worker/test/hosted.test.js
@@ -1,244 +1,479 @@
-import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-import { env } from 'cloudflare:test';
-import worker from '../src/index.js';
-import { ensureSchema } from '../src/schema.js';
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { env } from "cloudflare:test";
+import worker from "../src/index.js";
+import { ensureSchema } from "../src/schema.js";
-const config = { ...env, HOSTED_MODE: 'true', REQUEST_RATE_LIMIT: { limit: async () => ({ success: true }) }, ACCOUNT_RATE_LIMIT: { limit: async () => ({ success: true }) }, SUPABASE_URL: 'https://auth.example.test', SUPABASE_PUBLISHABLE_KEY: 'public-key' };
+const config = {
+ ...env,
+ HOSTED_MODE: "true",
+ REQUEST_RATE_LIMIT: { limit: async () => ({ success: true }) },
+ ACCOUNT_RATE_LIMIT: { limit: async () => ({ success: true }) },
+ SUPABASE_URL: "https://auth.example.test",
+ SUPABASE_PUBLISHABLE_KEY: "public-key",
+};
let owner;
beforeEach(async () => {
- await ensureSchema(env);
- owner = crypto.randomUUID();
- vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, options) => {
- const id = options.headers.Authorization.slice(7);
- return Response.json({ id, email: `${id}@example.test`, email_confirmed_at: '2026-09-23T00:00:00Z', is_anonymous: false });
- });
+ await ensureSchema(env);
+ owner = crypto.randomUUID();
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, options) => {
+ const id = options.headers.Authorization.slice(7);
+ return Response.json({
+ id,
+ email: `${id}@example.test`,
+ email_confirmed_at: "2026-09-23T00:00:00Z",
+ is_anonymous: false,
+ });
+ });
});
afterEach(() => vi.restoreAllMocks());
-const call = (path, method = 'GET', body, account = owner, headers = {}) => worker.fetch(new Request(`https://share.test${path}`, {
- method, headers: { Authorization: `Bearer ${account}`, 'Content-Type': 'application/json', ...headers },
- ...(body === undefined ? {} : { body: JSON.stringify(body) }),
-}), config);
+const call = (path, method = "GET", body, account = owner, headers = {}) =>
+ worker.fetch(
+ new Request(`https://share.test${path}`, {
+ method,
+ headers: {
+ Authorization: `Bearer ${account}`,
+ "Content-Type": "application/json",
+ ...headers,
+ },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ }),
+ config,
+ );
async function create(account = owner) {
- const response = await call('/api/upload', 'POST', { title: 'Owned recording', fileSize: 8, owner_id: 'spoofed' }, account);
- expect(response.status).toBe(200);
- return (await response.json()).shareCode;
+ const response = await call(
+ "/api/upload",
+ "POST",
+ { title: "Owned recording", fileSize: 8, owner_id: "spoofed" },
+ account,
+ );
+ expect(response.status).toBe(200);
+ return (await response.json()).shareCode;
}
-it('enforces fourteen-day free expiry and rejects renewal or client-claimed paid plans', async () => {
- const started = Date.now();
- const response = await call('/api/upload', 'POST', {
- title: 'Free expiry', fileSize: 8, plan: 'paid', expiresAt: '2099-01-01T00:00:00Z',
- });
- expect(response.status).toBe(200);
- const ticket = await response.json();
- const expiry = Date.parse(ticket.expiresAt);
- const fortnight = 14 * 86400000;
- expect(expiry).toBeGreaterThanOrEqual(started + fortnight);
- expect(expiry).toBeLessThanOrEqual(Date.now() + fortnight);
- expect((await call(`/api/renew/${ticket.shareCode}`, 'POST', {})).status).toBe(403);
- const row = await env.DB.prepare('SELECT expires_at FROM videos WHERE share_code = ?').bind(ticket.shareCode).first();
- expect(row.expires_at).toBe(ticket.expiresAt);
-
- await put(ticket.shareCode, new Uint8Array(8));
- expect((await call(`/api/metadata/${ticket.shareCode}`, 'POST', {})).status).toBe(200);
- expect((await call(`/v/${ticket.shareCode}`)).status).toBe(200);
- await env.DB.prepare("UPDATE videos SET expires_at = datetime('now', '-1 second') WHERE share_code = ?").bind(ticket.shareCode).run();
- expect((await call(`/v/${ticket.shareCode}`)).status).toBe(404);
- expect((await call(`/s/${ticket.shareCode}/data`)).status).toBe(404);
- expect((await call(`/api/renew/${ticket.shareCode}`, 'POST', {})).status).toBe(403);
-});
-
-it('requires a verified non-anonymous identity and never accepts a shared secret or cookie', async () => {
- for (const user of [{ id: owner }, { id: owner, email: '[email protected]', email_confirmed_at: 'now', is_anonymous: true }]) {
- fetch.mockResolvedValueOnce(Response.json(user));
- expect((await call('/api/health')).status).toBe(401);
- }
- fetch.mockResolvedValueOnce(new Response('', { status: 401 }));
- expect((await call('/api/health', 'GET', undefined, 'test-secret')).status).toBe(401);
- expect((await worker.fetch(new Request('https://share.test/api/videos', { headers: { Cookie: 'voom_session=anything' } }), config)).status).toBe(401);
-});
-
-it('isolates every recording mutation before its handler can touch storage', async () => {
- const code = await create();
- const other = crypto.randomUUID();
- for (const [method, path] of [
- ['PUT', `upload-data/${code}`], ['PUT', `upload-thumbnail/${code}`],
- ['POST', `upload-multipart/${code}`], ['PUT', `upload-part/${code}/fake/1`],
- ['POST', `upload-complete/${code}/fake`], ['POST', `upload-abort/${code}/fake`],
- ['POST', `metadata/${code}`], ['POST', `renew/${code}`], ['DELETE', `delete/${code}`],
- ]) expect((await call(`/api/${path}`, method, {}, other)).status).toBe(404);
- const row = await env.DB.prepare('SELECT owner_id FROM videos WHERE share_code = ?').bind(code).first();
- expect(row.owner_id).toBe(owner);
-});
-
-it('scopes list and view queries and hides legacy unowned rows', async () => {
- const mine = await create();
- const theirs = await create(crypto.randomUUID());
- const legacy = await create();
- await env.DB.prepare('UPDATE videos SET upload_completed = 1 WHERE share_code IN (?, ?, ?)').bind(mine, theirs, legacy).run();
- await env.DB.prepare('UPDATE videos SET owner_id = NULL WHERE share_code = ?').bind(legacy).run();
- const list = await (await call('/api/videos')).json();
- expect(list.videos.map(v => v.share_code)).toEqual([mine]);
- const views = await (await call('/api/check-views', 'POST', { shareCodes: [mine, theirs, legacy] })).json();
- expect(Object.keys(views.views)).toEqual([mine]);
- expect((await call(`/api/delete/${legacy}`, 'DELETE')).status).toBe(404);
-});
-
-it('allows exactly five concurrent reservations and releases a slot after owner deletion', async () => {
- const responses = await Promise.all(Array.from({ length: 9 }, () => call('/api/upload', 'POST', { title: 'Concurrent', fileSize: 8 })));
- expect(responses.filter(r => r.status === 200)).toHaveLength(5);
- expect(responses.filter(r => r.status === 409)).toHaveLength(4);
- const row = await env.DB.prepare('SELECT share_code FROM videos WHERE owner_id = ? LIMIT 1').bind(owner).first();
- await env.DB.prepare("UPDATE videos SET expires_at = datetime('now', '-1 day') WHERE owner_id = ?").bind(owner).run();
- expect((await call('/api/upload', 'POST', { title: 'Expired still occupies storage', fileSize: 8 })).status).toBe(409);
- expect((await call(`/api/delete/${row.share_code}`, 'DELETE')).status).toBe(200);
- await create();
-});
-
-it('disables the self-host shared-password dashboard and comment-account routes', async () => {
- expect((await call('/library')).status).toBe(404);
- expect((await call('/library/login', 'POST', {})).status).toBe(404);
- expect((await call('/auth/register', 'POST', {})).status).toBe(404);
-});
-
-const put = (code, bytes, extra = {}, path = 'upload-data') => worker.fetch(new Request(`https://share.test/api/${path}/${code}`, {
- method: 'PUT', headers: { Authorization: `Bearer ${owner}`, 'Content-Type': 'video/mp4', 'Content-Length': String(bytes.length), ...extra }, body: bytes,
-}), config);
-
-it('rejects invalid reservations and refuses publication without matching bytes', async () => {
- for (const size of [0, -1, 0.5, 1_000_000_001, '8', null]) {
- expect((await call('/api/upload', 'POST', { title: 'Invalid', fileSize: size })).status).toBe(413);
- }
- const code = await create();
- expect((await call(`/api/metadata/${code}`, 'POST', {})).status).toBe(409);
- expect((await put(code, new Uint8Array(9))).status).toBe(400);
- expect(await env.VIDEOS_BUCKET.head(`videos/${code}.mp4`)).toBeNull();
-});
-
-it('validates actual streamed bytes even when Content-Length lies', async () => {
- for (const size of [7, 9]) {
- const code = await create();
- expect((await put(code, new Uint8Array(size), { 'Content-Length': '8' })).status).toBe(400);
- expect(await env.VIDEOS_BUCKET.head(`videos/${code}.mp4`)).toBeNull();
- }
-});
-
-it('uploads, publishes, retries metadata safely, serves playback, and deletes', async () => {
- const code = await create();
- expect((await put(code, new Uint8Array(8))).status).toBe(200);
- const metadata = { title: 'Ready', segments: [{ startTime: 0, endTime: 1, text: 'Hello' }] };
- expect((await call(`/api/metadata/${code}`, 'POST', metadata)).status).toBe(200);
- expect((await call(`/api/metadata/${code}`, 'POST', metadata)).status).toBe(200);
- const segments = await env.DB.prepare('SELECT COUNT(*) AS total FROM transcript_segments WHERE video_id = (SELECT id FROM videos WHERE share_code = ?)').bind(code).first();
- expect(segments.total).toBe(1);
- expect((await put(code, new Uint8Array(8))).status).toBe(409);
- expect((await worker.fetch(new Request(`https://share.test/v/${code}`), config)).status).toBe(200);
- expect((await call(`/api/delete/${code}`, 'DELETE')).status).toBe(200);
- expect(await env.VIDEOS_BUCKET.head(`videos/${code}.mp4`)).toBeNull();
-});
-
-it('reuses one multipart session, enforces part sizes, and completes exactly once', async () => {
- const code = await create();
- const start = await (await call(`/api/upload-multipart/${code}`, 'POST')).json();
- const retry = await (await call(`/api/upload-multipart/${code}`, 'POST')).json();
- expect(retry.uploadId).toBe(start.uploadId);
- const id = encodeURIComponent(start.uploadId);
- expect((await call(`/api/upload-abort/${code}/wrong`, 'POST')).status).toBe(404);
- const part = await worker.fetch(new Request(`https://share.test/api/upload-part/${code}/${id}/1`, {
- method: 'PUT', headers: { Authorization: `Bearer ${owner}`, 'Content-Length': '8' }, body: new Uint8Array(8),
- }), config);
- expect(part.status).toBe(200);
- const manifest = { parts: [await part.json()] };
- expect((await call(`/api/upload-complete/${code}/${id}`, 'POST', { parts: [] })).status).toBe(400);
- expect((await call(`/api/upload-complete/${code}/${id}`, 'POST', manifest)).status).toBe(200);
- expect((await call(`/api/upload-complete/${code}/${id}`, 'POST', manifest)).status).toBe(200);
- expect((await call(`/api/metadata/${code}`, 'POST', {})).status).toBe(200);
- expect((await call(`/api/delete/${code}`, 'DELETE')).status).toBe(200);
-});
-
-it('aborts abandoned multipart uploads and frees only stale slots', async () => {
- const { cleanupExpired } = await import('../src/library.js');
- const stale = await create();
- const active = await create();
- await call(`/api/upload-multipart/${stale}`, 'POST');
- await env.DB.prepare("UPDATE videos SET created_at = datetime('now', '-2 days') WHERE share_code = ?").bind(stale).run();
- await cleanupExpired(config);
- expect(await env.DB.prepare('SELECT id FROM videos WHERE share_code = ?').bind(stale).first()).toBeNull();
- expect(await env.DB.prepare('SELECT upload_id FROM recording_uploads WHERE share_code = ?').bind(stale).first()).toBeNull();
- expect(await env.DB.prepare('SELECT id FROM videos WHERE share_code = ?').bind(active).first()).not.toBeNull();
-});
-
-it('bounds control payloads and thumbnail bytes', async () => {
- expect((await call('/api/upload', 'POST', { title: 'x'.repeat(17000), fileSize: 8 })).status).toBe(413);
- const code = await create();
- expect((await put(code, new Uint8Array(1), { 'Content-Type': 'image/jpeg', 'Content-Length': String(3 * 1024 * 1024) }, 'upload-thumbnail')).status).toBe(413);
-});
-
-it('limits staging to its explicitly allowed account', async () => {
- const restricted = { ...config, STAGING_ALLOWED_USER_ID: owner };
- expect((await worker.fetch(new Request('https://share.test/api/health', { headers: { Authorization: `Bearer ${owner}` } }), restricted)).status).toBe(200);
- expect((await worker.fetch(new Request('https://share.test/api/health', { headers: { Authorization: 'Bearer different-user' } }), restricted)).status).toBe(401);
-});
-
-it('leaves quota occupied when R2 cleanup fails, then succeeds on retry', async () => {
- const code = await create();
- await call(`/api/upload-multipart/${code}`, 'POST');
- const failing = { ...config, VIDEOS_BUCKET: { resumeMultipartUpload: () => ({ abort: async () => { throw new Error('Storage unavailable'); } }) } };
- expect((await worker.fetch(new Request(`https://share.test/api/delete/${code}`, { method: 'DELETE', headers: { Authorization: `Bearer ${owner}` } }), failing)).status).toBe(500);
- expect(await env.DB.prepare('SELECT id FROM videos WHERE share_code = ?').bind(code).first()).not.toBeNull();
- expect((await call(`/api/delete/${code}`, 'DELETE')).status).toBe(200);
-});
-
-it('blocks competing mutations and preserves another account’s locks', async () => {
- const code = await create();
- await env.DB.prepare('INSERT INTO recording_locks (share_code, token) VALUES (?, ?)').bind(code, 'held-by-upload').run();
- expect((await call(`/api/delete/${code}`, 'DELETE')).status).toBe(409);
- expect((await call(`/api/delete/${code}`, 'DELETE', undefined, crypto.randomUUID())).status).toBe(404);
- expect((await env.DB.prepare('SELECT token FROM recording_locks WHERE share_code = ?').bind(code).first()).token).toBe('held-by-upload');
-});
-
-it('fails closed without rate limits and throttles before expensive auth/storage work', async () => {
- const request = () => new Request('https://share.test/api/health', { headers: { Authorization: `Bearer ${owner}` } });
- expect((await worker.fetch(request(), { ...config, REQUEST_RATE_LIMIT: undefined })).status).toBe(503);
- const denied = { limit: async () => ({ success: false }) };
- fetch.mockClear();
- expect((await worker.fetch(request(), { ...config, REQUEST_RATE_LIMIT: denied })).status).toBe(429);
- expect(fetch).not.toHaveBeenCalled();
- expect((await worker.fetch(request(), { ...config, ACCOUNT_RATE_LIMIT: denied })).status).toBe(429);
-});
-
-
-it('accepts the full 1 GB allowance while rejecting the next byte', async () => {
- const accepted = await call('/api/upload', 'POST', { title: 'Full allowance', fileSize: 1_000_000_000 });
- expect(accepted.status).toBe(200);
- const rejected = await call('/api/upload', 'POST', { title: 'Over allowance', fileSize: 1_000_000_001 });
- expect(rejected.status).toBe(413);
-});
-
-
-it('scheduled cleanup removes expired completed objects and preserves active recordings', async () => {
- const expired = await create();
- const active = await create();
- for (const code of [expired, active]) {
- await put(code, new Uint8Array(8));
- await call(`/api/metadata/${code}`, 'POST', {});
- }
- await env.DB.prepare("UPDATE videos SET expires_at = datetime('now', '-1 second') WHERE share_code = ?").bind(expired).run();
- await worker.scheduled({}, config);
- expect(await env.VIDEOS_BUCKET.head(`videos/${expired}.mp4`)).toBeNull();
- expect(await env.DB.prepare('SELECT id FROM videos WHERE share_code = ?').bind(expired).first()).toBeNull();
- expect(await env.VIDEOS_BUCKET.head(`videos/${active}.mp4`)).not.toBeNull();
- expect(await env.DB.prepare('SELECT id FROM videos WHERE share_code = ?').bind(active).first()).not.toBeNull();
-});
-
-it('accepts the owner poster after publication without allowing media replacement', async () => {
- const code = await create();
- expect((await put(code, new Uint8Array(8))).status).toBe(200);
- expect((await call(`/api/metadata/${code}`, 'POST', {})).status).toBe(200);
- const thumbnail = new Uint8Array([0xff, 0xd8, 0xff, 0xd9]);
- expect((await put(code, thumbnail, { 'Content-Type': 'image/jpeg' }, 'upload-thumbnail')).status).toBe(200);
- const poster = await env.VIDEOS_BUCKET.get(`thumbnails/${code}.jpg`);
- expect(new Uint8Array(await poster.arrayBuffer())).toEqual(thumbnail);
- expect((await put(code, new Uint8Array(8))).status).toBe(409);
- expect((await call(`/api/upload-thumbnail/${code}`, 'PUT', {}, crypto.randomUUID())).status).toBe(404);
+it("enforces fourteen-day free expiry and rejects renewal or client-claimed paid plans", async () => {
+ const started = Date.now();
+ const response = await call("/api/upload", "POST", {
+ title: "Free expiry",
+ fileSize: 8,
+ plan: "paid",
+ expiresAt: "2099-01-01T00:00:00Z",
+ });
+ expect(response.status).toBe(200);
+ const ticket = await response.json();
+ const expiry = Date.parse(ticket.expiresAt);
+ const fortnight = 14 * 86400000;
+ expect(expiry).toBeGreaterThanOrEqual(started + fortnight);
+ expect(expiry).toBeLessThanOrEqual(Date.now() + fortnight);
+ expect((await call(`/api/renew/${ticket.shareCode}`, "POST", {})).status).toBe(403);
+ const row = await env.DB.prepare("SELECT expires_at FROM videos WHERE share_code = ?")
+ .bind(ticket.shareCode)
+ .first();
+ expect(row.expires_at).toBe(ticket.expiresAt);
+
+ await put(ticket.shareCode, new Uint8Array(8));
+ expect((await call(`/api/metadata/${ticket.shareCode}`, "POST", {})).status).toBe(200);
+ expect((await call(`/v/${ticket.shareCode}`)).status).toBe(200);
+ await env.DB.prepare(
+ "UPDATE videos SET expires_at = datetime('now', '-1 second') WHERE share_code = ?",
+ )
+ .bind(ticket.shareCode)
+ .run();
+ expect((await call(`/v/${ticket.shareCode}`)).status).toBe(404);
+ expect((await call(`/s/${ticket.shareCode}/data`)).status).toBe(404);
+ expect((await call(`/api/renew/${ticket.shareCode}`, "POST", {})).status).toBe(403);
+});
+
+it("requires a verified non-anonymous identity and never accepts a shared secret or cookie", async () => {
+ for (const user of [
+ { id: owner },
+ { id: owner, email: "[email protected]", email_confirmed_at: "now", is_anonymous: true },
+ ]) {
+ fetch.mockResolvedValueOnce(Response.json(user));
+ expect((await call("/api/health")).status).toBe(401);
+ }
+ fetch.mockResolvedValueOnce(new Response("", { status: 401 }));
+ expect((await call("/api/health", "GET", undefined, "test-secret")).status).toBe(401);
+ expect(
+ (
+ await worker.fetch(
+ new Request("https://share.test/api/videos", {
+ headers: { Cookie: "voom_session=anything" },
+ }),
+ config,
+ )
+ ).status,
+ ).toBe(401);
+});
+
+it("isolates every recording mutation before its handler can touch storage", async () => {
+ const code = await create();
+ const other = crypto.randomUUID();
+ for (const [method, path] of [
+ ["PUT", `upload-data/${code}`],
+ ["PUT", `upload-thumbnail/${code}`],
+ ["POST", `upload-multipart/${code}`],
+ ["PUT", `upload-part/${code}/fake/1`],
+ ["POST", `upload-complete/${code}/fake`],
+ ["POST", `upload-abort/${code}/fake`],
+ ["POST", `metadata/${code}`],
+ ["POST", `renew/${code}`],
+ ["DELETE", `delete/${code}`],
+ ])
+ expect((await call(`/api/${path}`, method, {}, other)).status).toBe(404);
+ const row = await env.DB.prepare("SELECT owner_id FROM videos WHERE share_code = ?")
+ .bind(code)
+ .first();
+ expect(row.owner_id).toBe(owner);
+});
+
+it("scopes list and view queries and hides legacy unowned rows", async () => {
+ const mine = await create();
+ const theirs = await create(crypto.randomUUID());
+ const legacy = await create();
+ await env.DB.prepare("UPDATE videos SET upload_completed = 1 WHERE share_code IN (?, ?, ?)")
+ .bind(mine, theirs, legacy)
+ .run();
+ await env.DB.prepare("UPDATE videos SET owner_id = NULL WHERE share_code = ?")
+ .bind(legacy)
+ .run();
+ const list = await (await call("/api/videos")).json();
+ expect(list.videos.map((v) => v.share_code)).toEqual([mine]);
+ const views = await (
+ await call("/api/check-views", "POST", { shareCodes: [mine, theirs, legacy] })
+ ).json();
+ expect(Object.keys(views.views)).toEqual([mine]);
+ expect((await call(`/api/delete/${legacy}`, "DELETE")).status).toBe(404);
+});
+
+it("allows exactly five concurrent reservations and releases a slot after owner deletion", async () => {
+ const responses = await Promise.all(
+ Array.from({ length: 9 }, () =>
+ call("/api/upload", "POST", { title: "Concurrent", fileSize: 8 }),
+ ),
+ );
+ expect(responses.filter((r) => r.status === 200)).toHaveLength(5);
+ expect(responses.filter((r) => r.status === 409)).toHaveLength(4);
+ const row = await env.DB.prepare("SELECT share_code FROM videos WHERE owner_id = ? LIMIT 1")
+ .bind(owner)
+ .first();
+ await env.DB.prepare(
+ "UPDATE videos SET expires_at = datetime('now', '-1 day') WHERE owner_id = ?",
+ )
+ .bind(owner)
+ .run();
+ expect(
+ (
+ await call("/api/upload", "POST", {
+ title: "Expired still occupies storage",
+ fileSize: 8,
+ })
+ ).status,
+ ).toBe(409);
+ expect((await call(`/api/delete/${row.share_code}`, "DELETE")).status).toBe(200);
+ await create();
+});
+
+it("disables the self-host shared-password dashboard and comment-account routes", async () => {
+ expect((await call("/library")).status).toBe(404);
+ expect((await call("/library/login", "POST", {})).status).toBe(404);
+ expect((await call("/auth/register", "POST", {})).status).toBe(404);
+});
+
+const put = (code, bytes, extra = {}, path = "upload-data") =>
+ worker.fetch(
+ new Request(`https://share.test/api/${path}/${code}`, {
+ method: "PUT",
+ headers: {
+ Authorization: `Bearer ${owner}`,
+ "Content-Type": "video/mp4",
+ "Content-Length": String(bytes.length),
+ ...extra,
+ },
+ body: bytes,
+ }),
+ config,
+ );
+
+it("rejects invalid reservations and refuses publication without matching bytes", async () => {
+ for (const size of [0, -1, 0.5, 1_000_000_001, "8", null]) {
+ expect(
+ (await call("/api/upload", "POST", { title: "Invalid", fileSize: size })).status,
+ ).toBe(413);
+ }
+ const code = await create();
+ expect((await call(`/api/metadata/${code}`, "POST", {})).status).toBe(409);
+ expect((await put(code, new Uint8Array(9))).status).toBe(400);
+ expect(await env.VIDEOS_BUCKET.head(`videos/${code}.mp4`)).toBeNull();
+});
+
+it("validates actual streamed bytes even when Content-Length lies", async () => {
+ for (const size of [7, 9]) {
+ const code = await create();
+ expect((await put(code, new Uint8Array(size), { "Content-Length": "8" })).status).toBe(400);
+ expect(await env.VIDEOS_BUCKET.head(`videos/${code}.mp4`)).toBeNull();
+ }
+});
+
+it("uploads, publishes, retries metadata safely, serves playback, and deletes", async () => {
+ const code = await create();
+ expect((await put(code, new Uint8Array(8))).status).toBe(200);
+ const metadata = { title: "Ready", segments: [{ startTime: 0, endTime: 1, text: "Hello" }] };
+ expect((await call(`/api/metadata/${code}`, "POST", metadata)).status).toBe(200);
+ expect((await call(`/api/metadata/${code}`, "POST", metadata)).status).toBe(200);
+ const segments = await env.DB.prepare(
+ "SELECT COUNT(*) AS total FROM transcript_segments WHERE video_id = (SELECT id FROM videos WHERE share_code = ?)",
+ )
+ .bind(code)
+ .first();
+ expect(segments.total).toBe(1);
+ expect((await put(code, new Uint8Array(8))).status).toBe(409);
+ expect((await worker.fetch(new Request(`https://share.test/v/${code}`), config)).status).toBe(
+ 200,
+ );
+ expect((await call(`/api/delete/${code}`, "DELETE")).status).toBe(200);
+ expect(await env.VIDEOS_BUCKET.head(`videos/${code}.mp4`)).toBeNull();
+});
+
+it("reuses one multipart session, enforces part sizes, and completes exactly once", async () => {
+ const code = await create();
+ const start = await (await call(`/api/upload-multipart/${code}`, "POST")).json();
+ const retry = await (await call(`/api/upload-multipart/${code}`, "POST")).json();
+ expect(retry.uploadId).toBe(start.uploadId);
+ const id = encodeURIComponent(start.uploadId);
+ expect((await call(`/api/upload-abort/${code}/wrong`, "POST")).status).toBe(404);
+ const part = await worker.fetch(
+ new Request(`https://share.test/api/upload-part/${code}/${id}/1`, {
+ method: "PUT",
+ headers: { Authorization: `Bearer ${owner}`, "Content-Length": "8" },
+ body: new Uint8Array(8),
+ }),
+ config,
+ );
+ expect(part.status).toBe(200);
+ const manifest = { parts: [await part.json()] };
+ expect((await call(`/api/upload-complete/${code}/${id}`, "POST", { parts: [] })).status).toBe(
+ 400,
+ );
+ expect((await call(`/api/upload-complete/${code}/${id}`, "POST", manifest)).status).toBe(200);
+ expect((await call(`/api/upload-complete/${code}/${id}`, "POST", manifest)).status).toBe(200);
+ expect((await call(`/api/metadata/${code}`, "POST", {})).status).toBe(200);
+ expect((await call(`/api/delete/${code}`, "DELETE")).status).toBe(200);
+});
+
+it("aborts abandoned multipart uploads and frees only stale slots", async () => {
+ const { cleanupExpired } = await import("../src/library.js");
+ const stale = await create();
+ const active = await create();
+ await call(`/api/upload-multipart/${stale}`, "POST");
+ await env.DB.prepare(
+ "UPDATE videos SET created_at = datetime('now', '-2 days') WHERE share_code = ?",
+ )
+ .bind(stale)
+ .run();
+ await cleanupExpired(config);
+ expect(
+ await env.DB.prepare("SELECT id FROM videos WHERE share_code = ?").bind(stale).first(),
+ ).toBeNull();
+ expect(
+ await env.DB.prepare("SELECT upload_id FROM recording_uploads WHERE share_code = ?")
+ .bind(stale)
+ .first(),
+ ).toBeNull();
+ expect(
+ await env.DB.prepare("SELECT id FROM videos WHERE share_code = ?").bind(active).first(),
+ ).not.toBeNull();
+});
+
+it("bounds control payloads and thumbnail bytes", async () => {
+ expect(
+ (await call("/api/upload", "POST", { title: "x".repeat(17000), fileSize: 8 })).status,
+ ).toBe(413);
+ const code = await create();
+ expect(
+ (
+ await put(
+ code,
+ new Uint8Array(1),
+ { "Content-Type": "image/jpeg", "Content-Length": String(3 * 1024 * 1024) },
+ "upload-thumbnail",
+ )
+ ).status,
+ ).toBe(413);
+});
+
+it("limits staging to its explicitly allowed account", async () => {
+ const restricted = { ...config, STAGING_ALLOWED_USER_ID: owner };
+ expect(
+ (
+ await worker.fetch(
+ new Request("https://share.test/api/health", {
+ headers: { Authorization: `Bearer ${owner}` },
+ }),
+ restricted,
+ )
+ ).status,
+ ).toBe(200);
+ expect(
+ (
+ await worker.fetch(
+ new Request("https://share.test/api/health", {
+ headers: { Authorization: "Bearer different-user" },
+ }),
+ restricted,
+ )
+ ).status,
+ ).toBe(401);
+});
+
+it("leaves quota occupied when R2 cleanup fails, then succeeds on retry", async () => {
+ const code = await create();
+ await call(`/api/upload-multipart/${code}`, "POST");
+ const failing = {
+ ...config,
+ VIDEOS_BUCKET: {
+ resumeMultipartUpload: () => ({
+ abort: async () => {
+ throw new Error("Storage unavailable");
+ },
+ }),
+ },
+ };
+ expect(
+ (
+ await worker.fetch(
+ new Request(`https://share.test/api/delete/${code}`, {
+ method: "DELETE",
+ headers: { Authorization: `Bearer ${owner}` },
+ }),
+ failing,
+ )
+ ).status,
+ ).toBe(500);
+ expect(
+ await env.DB.prepare("SELECT id FROM videos WHERE share_code = ?").bind(code).first(),
+ ).not.toBeNull();
+ expect((await call(`/api/delete/${code}`, "DELETE")).status).toBe(200);
+});
+
+it("blocks competing mutations and preserves another account’s locks", async () => {
+ const code = await create();
+ await env.DB.prepare("INSERT INTO recording_locks (share_code, token) VALUES (?, ?)")
+ .bind(code, "held-by-upload")
+ .run();
+ expect((await call(`/api/delete/${code}`, "DELETE")).status).toBe(409);
+ expect(
+ (await call(`/api/delete/${code}`, "DELETE", undefined, crypto.randomUUID())).status,
+ ).toBe(404);
+ expect(
+ (
+ await env.DB.prepare("SELECT token FROM recording_locks WHERE share_code = ?")
+ .bind(code)
+ .first()
+ ).token,
+ ).toBe("held-by-upload");
+});
+
+it("fails closed without rate limits and throttles before expensive auth/storage work", async () => {
+ const request = () =>
+ new Request("https://share.test/api/health", {
+ headers: { Authorization: `Bearer ${owner}` },
+ });
+ expect(
+ (await worker.fetch(request(), { ...config, REQUEST_RATE_LIMIT: undefined })).status,
+ ).toBe(503);
+ const denied = { limit: async () => ({ success: false }) };
+ fetch.mockClear();
+ expect((await worker.fetch(request(), { ...config, REQUEST_RATE_LIMIT: denied })).status).toBe(
+ 429,
+ );
+ expect(fetch).not.toHaveBeenCalled();
+ expect((await worker.fetch(request(), { ...config, ACCOUNT_RATE_LIMIT: denied })).status).toBe(
+ 429,
+ );
+});
+
+it("accepts the full 1 GB allowance while rejecting the next byte", async () => {
+ const accepted = await call("/api/upload", "POST", {
+ title: "Full allowance",
+ fileSize: 1_000_000_000,
+ });
+ expect(accepted.status).toBe(200);
+ const rejected = await call("/api/upload", "POST", {
+ title: "Over allowance",
+ fileSize: 1_000_000_001,
+ });
+ expect(rejected.status).toBe(413);
+});
+
+it("scheduled cleanup removes expired completed objects and preserves active recordings", async () => {
+ const expired = await create();
+ const active = await create();
+ for (const code of [expired, active]) {
+ await put(code, new Uint8Array(8));
+ await call(`/api/metadata/${code}`, "POST", {});
+ }
+ await env.DB.prepare(
+ "UPDATE videos SET expires_at = datetime('now', '-1 second') WHERE share_code = ?",
+ )
+ .bind(expired)
+ .run();
+ await worker.scheduled({}, config);
+ expect(await env.VIDEOS_BUCKET.head(`videos/${expired}.mp4`)).toBeNull();
+ expect(
+ await env.DB.prepare("SELECT id FROM videos WHERE share_code = ?").bind(expired).first(),
+ ).toBeNull();
+ expect(await env.VIDEOS_BUCKET.head(`videos/${active}.mp4`)).not.toBeNull();
+ expect(
+ await env.DB.prepare("SELECT id FROM videos WHERE share_code = ?").bind(active).first(),
+ ).not.toBeNull();
+});
+
+it("accepts the owner poster after publication without allowing media replacement", async () => {
+ const code = await create();
+ expect((await put(code, new Uint8Array(8))).status).toBe(200);
+ expect((await call(`/api/metadata/${code}`, "POST", {})).status).toBe(200);
+ const thumbnail = new Uint8Array([0xff, 0xd8, 0xff, 0xd9]);
+ expect(
+ (await put(code, thumbnail, { "Content-Type": "image/jpeg" }, "upload-thumbnail")).status,
+ ).toBe(200);
+ const poster = await env.VIDEOS_BUCKET.get(`thumbnails/${code}.jpg`);
+ expect(new Uint8Array(await poster.arrayBuffer())).toEqual(thumbnail);
+ expect((await put(code, new Uint8Array(8))).status).toBe(409);
+ expect(
+ (await call(`/api/upload-thumbnail/${code}`, "PUT", {}, crypto.randomUUID())).status,
+ ).toBe(404);
+});
+
+it("clears a completed size-mismatch session so a fresh multipart upload can start", async () => {
+ const code = await create();
+ const start = await (await call(`/api/upload-multipart/${code}`, "POST")).json();
+ const brokenStorage = {
+ ...config,
+ VIDEOS_BUCKET: {
+ head: (...args) => env.VIDEOS_BUCKET.head(...args),
+ delete: (...args) => env.VIDEOS_BUCKET.delete(...args),
+ resumeMultipartUpload: () => ({ complete: async () => ({ size: 7 }) }),
+ },
+ };
+ const response = await worker.fetch(
+ new Request(
+ `https://share.test/api/upload-complete/${code}/${encodeURIComponent(start.uploadId)}`,
+ {
+ method: "POST",
+ headers: { Authorization: `Bearer ${owner}`, "Content-Type": "application/json" },
+ body: JSON.stringify({ parts: [{ partNumber: 1, etag: "fixture" }] }),
+ },
+ ),
+ brokenStorage,
+ );
+ expect(response.status).toBe(400);
+ expect(
+ await env.DB.prepare("SELECT upload_id FROM recording_uploads WHERE share_code = ?")
+ .bind(code)
+ .first(),
+ ).toBeNull();
+ const retry = await (await call(`/api/upload-multipart/${code}`, "POST")).json();
+ expect(retry.uploadId).not.toBe(start.uploadId);
+ // The fake storage above cannot actually complete the original R2 session.
+ await env.VIDEOS_BUCKET.resumeMultipartUpload(`videos/${code}.mp4`, start.uploadId).abort();
});
diff --git a/services/recordly-share/worker/test/migration.test.js b/services/recordly-share/worker/test/migration.test.js
index f2bbf75d..875a6fe3 100644
--- a/services/recordly-share/worker/test/migration.test.js
+++ b/services/recordly-share/worker/test/migration.test.js
@@ -4,17 +4,17 @@
// ALTER never ran, and every INSERT touching password_salt threw a 500.
// These tests rebuild the database into each historical shape and verify
// uploads work afterward.
-import { describe, it, expect, beforeEach, afterAll } from 'vitest';
-import { env, SELF } from 'cloudflare:test';
-import { __resetSchemaCacheForTests } from '../src/index.js';
+import { describe, it, expect, beforeEach, afterAll } from "vitest";
+import { env, SELF } from "cloudflare:test";
+import { __resetSchemaCacheForTests } from "../src/index.js";
-const AUTH = { Authorization: 'Bearer test-secret' };
-const BASE = 'https://share.test';
+const AUTH = { Authorization: "Bearer test-secret" };
+const BASE = "https://share.test";
// The videos table exactly as production had it before migration 0006
// (base schema + migrations 0002–0005): no password_salt column.
const V1_STATEMENTS = [
- `CREATE TABLE videos (
+ `CREATE TABLE videos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
share_code TEXT UNIQUE NOT NULL,
title TEXT NOT NULL,
@@ -34,7 +34,7 @@ const V1_STATEMENTS = [
is_meeting INTEGER NOT NULL DEFAULT 0,
summary TEXT
)`,
- `CREATE TABLE transcript_segments (
+ `CREATE TABLE transcript_segments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
video_id INTEGER NOT NULL REFERENCES videos(id) ON DELETE CASCADE,
start_time REAL NOT NULL,
@@ -42,7 +42,7 @@ const V1_STATEMENTS = [
text TEXT NOT NULL,
speaker TEXT
)`,
- `CREATE TABLE reactions (
+ `CREATE TABLE reactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
video_id INTEGER NOT NULL REFERENCES videos(id) ON DELETE CASCADE,
timestamp REAL NOT NULL,
@@ -50,7 +50,7 @@ const V1_STATEMENTS = [
client_ip TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)`,
- `CREATE TABLE comments (
+ `CREATE TABLE comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
video_id INTEGER NOT NULL REFERENCES videos(id) ON DELETE CASCADE,
timestamp REAL NOT NULL,
@@ -59,7 +59,7 @@ const V1_STATEMENTS = [
created_at TEXT NOT NULL DEFAULT (datetime('now')),
client_ip TEXT NOT NULL DEFAULT ''
)`,
- `CREATE TABLE chapters (
+ `CREATE TABLE chapters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
video_id INTEGER NOT NULL REFERENCES videos(id) ON DELETE CASCADE,
timestamp REAL NOT NULL,
@@ -68,113 +68,119 @@ const V1_STATEMENTS = [
];
async function dropAllTables() {
- const { results } = await env.DB.prepare(
- `SELECT name FROM sqlite_master WHERE type = 'table'
- AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' AND name NOT LIKE '\\_cf\\_%' ESCAPE '\\'`
- ).all();
- for (const { name } of results) {
- await env.DB.prepare(`DROP TABLE IF EXISTS "${name}"`).run();
- }
+ const { results } = await env.DB.prepare(
+ `SELECT name FROM sqlite_master WHERE type = 'table'
+ AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' AND name NOT LIKE '\\_cf\\_%' ESCAPE '\\'`,
+ ).all();
+ for (const { name } of results) {
+ await env.DB.prepare(`DROP TABLE IF EXISTS "${name}"`).run();
+ }
}
async function createV1Schema() {
- for (const sql of V1_STATEMENTS) {
- await env.DB.prepare(sql).run();
- }
+ for (const sql of V1_STATEMENTS) {
+ await env.DB.prepare(sql).run();
+ }
}
async function videoColumns() {
- const { results } = await env.DB.prepare(`PRAGMA table_info(videos)`).all();
- return results.map(c => c.name);
+ const { results } = await env.DB.prepare(`PRAGMA table_info(videos)`).all();
+ return results.map((c) => c.name);
}
async function upload() {
- return SELF.fetch(`${BASE}/api/upload`, {
- method: 'POST',
- headers: { ...AUTH, 'Content-Type': 'application/json' },
- body: JSON.stringify({ title: 'Migration Test', duration: 3 }),
- });
+ return SELF.fetch(`${BASE}/api/upload`, {
+ method: "POST",
+ headers: { ...AUTH, "Content-Type": "application/json" },
+ body: JSON.stringify({ title: "Migration Test", duration: 3 }),
+ });
}
-describe('schema migration paths', () => {
- beforeEach(async () => {
- await dropAllTables();
- __resetSchemaCacheForTests();
- });
-
- // Leave a clean, fully-migrated database for any test file that runs after.
- afterAll(async () => {
- await dropAllTables();
- __resetSchemaCacheForTests();
- });
-
- it('migrates a pre-versioning database (tables exist, no _meta)', async () => {
- await createV1Schema();
-
- const res = await upload();
- expect(res.status).toBe(200);
- const body = await res.json();
- expect(body.shareCode).toBeTruthy();
-
- expect(await videoColumns()).toContain('password_salt');
- const meta = await env.DB.prepare(`SELECT value FROM _meta WHERE key = 'schema_version'`).first();
- expect(meta.value).toBe('5');
- expect(await videoColumns()).toContain('owner_id');
- });
-
- it('repairs a database mis-stamped as current without the v2 columns', async () => {
- // The exact state v4.1.0 left production in: v1 tables, _meta says 2.
- await createV1Schema();
- await env.DB.prepare(`CREATE TABLE _meta (key TEXT PRIMARY KEY, value TEXT)`).run();
- await env.DB.prepare(`INSERT INTO _meta (key, value) VALUES ('schema_version', '2')`).run();
-
- const res = await upload();
- expect(res.status).toBe(200);
-
- expect(await videoColumns()).toContain('password_salt');
- });
-
- it('re-running migrations on an already-migrated database is a no-op', async () => {
- await createV1Schema();
- expect((await upload()).status).toBe(200); // migrates
-
- __resetSchemaCacheForTests(); // simulate a new isolate cold start
- expect((await upload()).status).toBe(200); // must not throw duplicate-column
- });
-
- it('bootstraps a truly fresh database with the consolidated schema', async () => {
- const res = await upload();
- expect(res.status).toBe(200);
-
- const cols = await videoColumns();
- expect(cols).toContain('password_salt');
- const tables = await env.DB.prepare(
- `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'password_attempts'`
- ).first();
- expect(tables).toBeTruthy();
- expect(await env.DB.prepare(
- `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'comment_users'`
- ).first()).toBeTruthy();
- });
-
- it('password flow works end-to-end on a migrated pre-versioning database', async () => {
- await createV1Schema();
-
- const hash = '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'; // sha256("hello")
- const res = await SELF.fetch(`${BASE}/api/upload`, {
- method: 'POST',
- headers: { ...AUTH, 'Content-Type': 'application/json' },
- body: JSON.stringify({ title: 'Protected', duration: 3, password_hash: hash }),
- });
- expect(res.status).toBe(200);
- const { shareCode } = await res.json();
- await env.DB.prepare(`UPDATE videos SET upload_completed = 1 WHERE share_code = ?`).bind(shareCode).run();
-
- const verify = await SELF.fetch(`${BASE}/s/${shareCode}/verify-password`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ password: 'hello' }),
- });
- expect(verify.status).toBe(200);
- });
+describe("schema migration paths", () => {
+ beforeEach(async () => {
+ await dropAllTables();
+ __resetSchemaCacheForTests();
+ });
+
+ // Leave a clean, fully-migrated database for any test file that runs after.
+ afterAll(async () => {
+ await dropAllTables();
+ __resetSchemaCacheForTests();
+ });
+
+ it("migrates a pre-versioning database (tables exist, no _meta)", async () => {
+ await createV1Schema();
+
+ const res = await upload();
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.shareCode).toBeTruthy();
+
+ expect(await videoColumns()).toContain("password_salt");
+ const meta = await env.DB.prepare(
+ `SELECT value FROM _meta WHERE key = 'schema_version'`,
+ ).first();
+ expect(meta.value).toBe("5");
+ expect(await videoColumns()).toContain("owner_id");
+ });
+
+ it("repairs a database mis-stamped as current without the v2 columns", async () => {
+ // The exact state v4.1.0 left production in: v1 tables, _meta says 2.
+ await createV1Schema();
+ await env.DB.prepare(`CREATE TABLE _meta (key TEXT PRIMARY KEY, value TEXT)`).run();
+ await env.DB.prepare(`INSERT INTO _meta (key, value) VALUES ('schema_version', '2')`).run();
+
+ const res = await upload();
+ expect(res.status).toBe(200);
+
+ expect(await videoColumns()).toContain("password_salt");
+ });
+
+ it("re-running migrations on an already-migrated database is a no-op", async () => {
+ await createV1Schema();
+ expect((await upload()).status).toBe(200); // migrates
+
+ __resetSchemaCacheForTests(); // simulate a new isolate cold start
+ expect((await upload()).status).toBe(200); // must not throw duplicate-column
+ });
+
+ it("bootstraps a truly fresh database with the consolidated schema", async () => {
+ const res = await upload();
+ expect(res.status).toBe(200);
+
+ const cols = await videoColumns();
+ expect(cols).toContain("password_salt");
+ const tables = await env.DB.prepare(
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'password_attempts'`,
+ ).first();
+ expect(tables).toBeTruthy();
+ expect(
+ await env.DB.prepare(
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'comment_users'`,
+ ).first(),
+ ).toBeTruthy();
+ });
+
+ it("password flow works end-to-end on a migrated pre-versioning database", async () => {
+ await createV1Schema();
+
+ const hash = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"; // sha256("hello")
+ const res = await SELF.fetch(`${BASE}/api/upload`, {
+ method: "POST",
+ headers: { ...AUTH, "Content-Type": "application/json" },
+ body: JSON.stringify({ title: "Protected", duration: 3, password_hash: hash }),
+ });
+ expect(res.status).toBe(200);
+ const { shareCode } = await res.json();
+ await env.DB.prepare(`UPDATE videos SET upload_completed = 1 WHERE share_code = ?`)
+ .bind(shareCode)
+ .run();
+
+ const verify = await SELF.fetch(`${BASE}/s/${shareCode}/verify-password`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ password: "hello" }),
+ });
+ expect(verify.status).toBe(200);
+ });
});