mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 17:46:06 +00:00
The suite that landed in #43/#44 was written against existing behaviour, so a number of tests pinned bugs rather than asserting correct behaviour. This fixes the production code and moves each of those tests onto the fixed behaviour in the same change. Security: - project-download: derive the archive entry extension from the last path segment and restrict it to a short alphanumeric run, so an extensionless allowlisted url can no longer contribute a path separator; validate the r2 branch against the strict proxy-path pattern instead of a `startsWith`, which let `/api/upload/video/clip.mp4/../../etc/passwd` through verbatim. - rate-limit: hash a key or action wider than its column instead of skipping the query. Both the guard and the failing INSERT used to answer "allowed", so the limit stopped applying entirely. Warn at startup when TRUSTED_PROXY_MODE is unset in production. - video uploads: the file name decides the content type; a client-declared video mime no longer makes `payload.exe` acceptable. - email templates: escape in the helpers rather than relying on every caller, with an explicit `rawEmailHtml()` opt-out for the one call site that builds markup. `escapeHtml` now covers the single quote. - CSP: allow loopback object storage outside production only. - route-access: reach the billing redirect only for the workspace owner. Keying it off the owner's billing status alone made the redirect target an oracle for whose subscription had lapsed, and sent members to a page they cannot act on. - search: carry the same billing condition every other read path carries. - logger: check `err.name` as well as `err.constructor.name`, so a re-thrown, deserialised or minified Prisma error is still redacted. - upload tokens: resolve the signing secret outside the try, so a server booted without one fails loudly instead of reporting every grant as a forgery. - invitations: never downgrade an existing membership, and report a scoped invitation that points at nothing as not_found rather than accepted. - auth: resolve the workspace role for every signed-in caller, so checkProjectAccess and computeProjectAccess stop disagreeing about the owner who also owns the workspace. The `intent` option is gone with it. - r2-media-proxy: validate the object key inside the proxy so the guard travels with the function; delete the unused, unanchored `mediaUrlToR2Key`. - r2: sign the content type into presigned PUT grants. Correctness: - frame rate snapping picks the nearest standard, not the first within tolerance, so 24, 30 and 60 fps are reachable at all. - a version upload registers its Bunny cleanup as soon as bunny-init answers, so a failed tus upload no longer leaves a billed video behind. - deleting videos clears storage before the rows, so a refused DELETE leaves a retryable row rather than an orphaned object. - an expired upload session can be cancelled, which is what releases its quota. - `voice/` joins the delete allowlist, so a voice note can be removed by the module that wrote it. - a failed CORS write propagates instead of being mistaken for an empty config and replacing the bucket's rules. - filtering projects by workspace no longer hides projects the unfiltered call returns. - upload retries skip aborts and permanent 4xx; progress no longer divides by zero. - reply edits no longer clear the comment's tag; optimistic resolve rolls back to the state it replaced; the delete snapshot is captured once. - assorted UI fixes: duplicate React keys, double-click guards reading stale closures, the tag list fetched twice per load, a failed member list rendering as an empty one, a stale "Initializing upload..." beside a failure, and a registration banner pointing at an email that never arrives. Consistency and access: - the two download routes answer 404 for an id belonging to another tenant, as the comment export route already did. A caller who does belong still gets 403. - accessible names for the share-link password field, the guest name gates, the version dialog inputs and the comment-tag controls. Repository health: - the runner image installs production dependencies only. - a setup file for the unit project restores stubbed env centrally. - native tsconfig path resolution replaces vite-tsconfig-paths. - `uploadBytesWithProgress` exists once. - admin stats bill Bunny storage to the workspace owner like every other quota, gate on the configured flag, wire up the single-flight guard and count the statuses that belonged to no bucket. - `r2Client.destroy()` releases the presign client too. - `prepare` tolerates a production install, where husky is absent.
152 lines
5.6 KiB
TypeScript
152 lines
5.6 KiB
TypeScript
import { createHash, randomBytes } from 'crypto';
|
|
import { db } from '@/lib/db';
|
|
import nodemailer from 'nodemailer';
|
|
import {
|
|
brandedEmailTemplate,
|
|
emailButton,
|
|
emailHeading,
|
|
emailRow,
|
|
EMAIL_COLORS,
|
|
} from '@/lib/email-brand';
|
|
import { logError } from '@/lib/logger';
|
|
|
|
// Reduce window to 2 hours — shorter exposure in access logs and backups.
|
|
const TOKEN_EXPIRY_HOURS = 2;
|
|
|
|
/** Hash a raw token before persisting so the DB stores only the digest. */
|
|
function hashToken(token: string): string {
|
|
return createHash('sha256').update(token).digest('hex');
|
|
}
|
|
|
|
/**
|
|
* Returns true when SMTP is fully configured and email sending should be enforced.
|
|
* When SMTP is not configured, email verification is bypassed so self-hosted deployments
|
|
* without a mail server continue to function.
|
|
*/
|
|
export function isEmailVerificationEnabled(): boolean {
|
|
return !!(process.env.SMTP_HOST && process.env.SMTP_USER && process.env.SMTP_PASSWORD);
|
|
}
|
|
|
|
/**
|
|
* Generate a secure random verification token, persist only its SHA-256 digest,
|
|
* and return the raw token (sent to the user via email).
|
|
* Any existing tokens for this email are deleted first (at most one live token).
|
|
*/
|
|
export async function createVerificationToken(email: string): Promise<string> {
|
|
const token = randomBytes(32).toString('hex');
|
|
const tokenHash = hashToken(token);
|
|
const expires = new Date(Date.now() + TOKEN_EXPIRY_HOURS * 60 * 60 * 1000);
|
|
|
|
// Delete existing tokens for this identifier before creating a new one
|
|
await db.verificationToken.deleteMany({ where: { identifier: email } });
|
|
|
|
await db.verificationToken.create({
|
|
data: { identifier: email, token: tokenHash, expires },
|
|
});
|
|
|
|
// Return the raw (unhashed) token — only ever sent to the user, never stored.
|
|
return token;
|
|
}
|
|
|
|
/**
|
|
* Consume a verification token: hash the raw token, look it up, mark the user
|
|
* email as verified, and delete the DB record atomically.
|
|
* Returns the user's email on success, or null on any failure (invalid, expired,
|
|
* already verified, or deleted account).
|
|
*/
|
|
export async function consumeVerificationToken(token: string): Promise<string | null> {
|
|
const tokenHash = hashToken(token);
|
|
const record = await db.verificationToken.findUnique({ where: { token: tokenHash } });
|
|
|
|
if (!record) return null;
|
|
if (record.expires < new Date()) {
|
|
await db.verificationToken.delete({ where: { token: tokenHash } }).catch(() => null);
|
|
return null;
|
|
}
|
|
|
|
// Atomically mark email as verified and delete the token
|
|
const [user] = await db.$transaction([
|
|
db.user.updateMany({
|
|
where: { email: record.identifier, emailVerified: null },
|
|
data: { emailVerified: new Date() },
|
|
}),
|
|
db.verificationToken.delete({ where: { token: tokenHash } }),
|
|
]);
|
|
|
|
// count === 0 means the user was already verified or has been deleted.
|
|
// Return null so a replayed/stale token never produces a misleading success redirect.
|
|
if (user.count === 0) return null;
|
|
|
|
return record.identifier;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Email sending
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function createTransport() {
|
|
const host = process.env.SMTP_HOST;
|
|
const port = Number(process.env.SMTP_PORT || '587');
|
|
const user = process.env.SMTP_USER;
|
|
const pass = process.env.SMTP_PASSWORD;
|
|
if (!host || !user || !pass) return null;
|
|
return nodemailer.createTransport({ host, port, secure: port === 465, auth: { user, pass } });
|
|
}
|
|
|
|
export async function sendVerificationEmail(
|
|
email: string,
|
|
token: string,
|
|
options?: { next?: string }
|
|
): Promise<void> {
|
|
const transporter = createTransport();
|
|
if (!transporter) return;
|
|
|
|
const baseUrl = process.env.NEXTAUTH_URL;
|
|
if (!baseUrl) {
|
|
// A missing NEXTAUTH_URL means the verification link will be malformed and the
|
|
// user will be permanently locked out with no visible failure. Treat as fatal.
|
|
logError(
|
|
'NEXTAUTH_URL is not set — cannot build a valid verification link.',
|
|
new Error('Set NEXTAUTH_URL to your deployment origin (e.g. https://app.example.com).')
|
|
);
|
|
return;
|
|
}
|
|
|
|
// `next` survives the round-trip so an invited user lands back on the invitation
|
|
// (and from there on the shared project) instead of a generic login page.
|
|
const nextParam = options?.next ? `&next=${encodeURIComponent(options.next)}` : '';
|
|
const verifyUrl = `${baseUrl}/api/auth/verify-email?token=${encodeURIComponent(token)}${nextParam}`;
|
|
const from = process.env.SMTP_FROM || process.env.EMAIL_FROM || 'OpenFrame <[email protected]>';
|
|
|
|
const html = brandedEmailTemplate(
|
|
`
|
|
<tr>${emailHeading('✉', 'Verify your email address')}</tr>
|
|
<tr><td style="padding:20px;">
|
|
<table cellpadding="0" cellspacing="0" style="width:100%;margin-bottom:20px;">
|
|
${emailRow('Account', email, true)}
|
|
${emailRow('Expires in', `${TOKEN_EXPIRY_HOURS} hours`)}
|
|
</table>
|
|
<p style="margin:0 0 20px;font-size:14px;color:${EMAIL_COLORS.textSecondary};line-height:1.6;">
|
|
Click the button below to verify your email address and activate your OpenFrame account.
|
|
If you did not create an account, you can safely ignore this email.
|
|
</p>
|
|
${emailButton('Verify Email Address →', verifyUrl)}
|
|
</td></tr>
|
|
`,
|
|
{
|
|
footerText: `This link expires in ${TOKEN_EXPIRY_HOURS} hours.`,
|
|
}
|
|
);
|
|
|
|
try {
|
|
await transporter.sendMail({
|
|
from,
|
|
to: email,
|
|
subject: 'Verify your OpenFrame email address',
|
|
html,
|
|
});
|
|
} catch (err) {
|
|
logError('Failed to send verification email:', err);
|
|
}
|
|
}
|