mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 09:36:08 +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.
413 lines
14 KiB
TypeScript
413 lines
14 KiB
TypeScript
import NextAuth from 'next-auth';
|
|
import Credentials from 'next-auth/providers/credentials';
|
|
import Google from 'next-auth/providers/google';
|
|
import GitHub from 'next-auth/providers/github';
|
|
import { PrismaAdapter } from '@auth/prisma-adapter';
|
|
import bcrypt from 'bcryptjs';
|
|
import { db } from '@/lib/db';
|
|
import { ProjectMemberRole, WorkspaceMemberRole } from '@prisma/client';
|
|
import { hasBillingAccess } from '@/lib/billing';
|
|
import { isInviteCodeRequired } from '@/lib/feature-flags';
|
|
import { isEmailVerificationEnabled } from '@/lib/email-verification';
|
|
|
|
// Dummy hash for timing-safe comparison when user doesn't exist
|
|
// This prevents user enumeration via timing attacks
|
|
const DUMMY_HASH = '$2a$12$000000000000000000000uGG3k3xK2CVTxXrT7VW2sGd1XrY6Ky';
|
|
|
|
export const { handlers, signIn, signOut, auth } = NextAuth({
|
|
// PrismaAdapter handles OAuth account linking and user creation in DB.
|
|
// JWT strategy is still used for sessions (no DB sessions table needed).
|
|
adapter: PrismaAdapter(db),
|
|
providers: [
|
|
Credentials({
|
|
name: 'credentials',
|
|
credentials: {
|
|
email: { label: 'Email', type: 'email' },
|
|
password: { label: 'Password', type: 'password' },
|
|
},
|
|
async authorize(credentials) {
|
|
if (!credentials?.email || !credentials?.password) {
|
|
return null;
|
|
}
|
|
|
|
const email = credentials.email as string;
|
|
const password = credentials.password as string;
|
|
|
|
// Find user by email
|
|
const user = await db.user.findUnique({
|
|
where: { email: email.toLowerCase() },
|
|
});
|
|
|
|
// Always perform bcrypt comparison to prevent timing attacks
|
|
// If user doesn't exist, compare against dummy hash
|
|
const hashToCompare = user?.password || DUMMY_HASH;
|
|
const isValidPassword = await bcrypt.compare(password, hashToCompare);
|
|
|
|
// Only return user if they exist AND password is valid
|
|
if (!user || !user.password || !isValidPassword) {
|
|
return null;
|
|
}
|
|
|
|
// Block sign-in when email verification is required but not yet completed
|
|
if (isEmailVerificationEnabled() && !user.emailVerified) {
|
|
return null;
|
|
}
|
|
|
|
return {
|
|
id: user.id,
|
|
name: user.name,
|
|
email: user.email,
|
|
image: user.image,
|
|
};
|
|
},
|
|
}),
|
|
...(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET
|
|
? [
|
|
Google({
|
|
clientId: process.env.GOOGLE_CLIENT_ID,
|
|
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
|
|
}),
|
|
]
|
|
: []),
|
|
...(process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET
|
|
? [
|
|
{
|
|
...GitHub({
|
|
clientId: process.env.GITHUB_CLIENT_ID,
|
|
clientSecret: process.env.GITHUB_CLIENT_SECRET,
|
|
}),
|
|
// GitHub sends iss=https://github.com/login/oauth in callbacks (RFC 9207).
|
|
// Auth.js v5 beta defaults to "https://authjs.dev" for OAuth providers, causing
|
|
// a mismatch. Setting the correct issuer here fixes the CallbackRouteError.
|
|
issuer: 'https://github.com/login/oauth',
|
|
},
|
|
]
|
|
: []),
|
|
],
|
|
session: {
|
|
strategy: 'jwt',
|
|
maxAge: 30 * 24 * 60 * 60, // 30 days
|
|
},
|
|
pages: {
|
|
signIn: '/login',
|
|
signOut: '/signout',
|
|
},
|
|
callbacks: {
|
|
async signIn({ account, profile }) {
|
|
// Credentials sign-in is handled by the authorize() function above
|
|
if (account?.provider === 'credentials') return true;
|
|
|
|
// Reject OAuth sign-ins where the provider email is not verified.
|
|
// Google always sets email_verified: true. GitHub does not guarantee it.
|
|
if (profile && profile.email_verified === false) {
|
|
return '/login?error=OAuthEmailNotVerified';
|
|
}
|
|
|
|
// OAuth sign-in: allow existing OAuth accounts regardless of invite setting
|
|
if (account?.providerAccountId && account?.provider) {
|
|
const existingAccount = await db.account.findUnique({
|
|
where: {
|
|
provider_providerAccountId: {
|
|
provider: account.provider,
|
|
providerAccountId: account.providerAccountId,
|
|
},
|
|
},
|
|
select: { id: true },
|
|
});
|
|
if (existingAccount) return true;
|
|
}
|
|
|
|
// New OAuth user: block when invite-only mode is active
|
|
if (isInviteCodeRequired()) {
|
|
return '/login?error=RegistrationClosed';
|
|
}
|
|
|
|
return true;
|
|
},
|
|
async session({ session, token }) {
|
|
if (token.sub && session.user) {
|
|
session.user.id = token.sub;
|
|
session.user.name = token.name || null;
|
|
session.user.isAdmin = token.isAdmin as boolean;
|
|
}
|
|
return session;
|
|
},
|
|
async jwt({ token, user }) {
|
|
if (user) {
|
|
token.sub = user.id;
|
|
token.name = user.name;
|
|
token.email = user.email; // explicitly ensure email is in the token
|
|
}
|
|
|
|
// Check if user is admin based on emails list on EVERY request to ensure env changes are picked up
|
|
if (token.email) {
|
|
const adminEmails = process.env.ADMIN_EMAILS
|
|
? process.env.ADMIN_EMAILS.split(',').map((e: string) => e.trim().toLowerCase())
|
|
: [];
|
|
token.isAdmin = adminEmails.includes((token.email as string).toLowerCase());
|
|
}
|
|
|
|
return token;
|
|
},
|
|
},
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Fast-path: pre-fetch access data alongside any existing DB query so that
|
|
// computeProjectAccess() can resolve the result with zero extra round-trips.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/** Prisma include fragment to attach to any project fetch. */
|
|
export function projectAccessInclude(userId: string | undefined) {
|
|
return {
|
|
workspace: {
|
|
select: {
|
|
id: true,
|
|
ownerId: true,
|
|
owner: {
|
|
select: {
|
|
subscriptionStatus: true,
|
|
trialEndsAt: true,
|
|
stripeCurrentPeriodEnd: true,
|
|
billingAccessEndedAt: true,
|
|
},
|
|
},
|
|
members: userId
|
|
? {
|
|
where: { userId },
|
|
take: 1,
|
|
orderBy: { createdAt: 'asc' as const },
|
|
select: { role: true },
|
|
}
|
|
: { take: 0, select: { role: true } },
|
|
},
|
|
},
|
|
members: userId
|
|
? {
|
|
where: { userId },
|
|
take: 1,
|
|
orderBy: { createdAt: 'asc' as const },
|
|
select: { role: true },
|
|
}
|
|
: { take: 0, select: { role: true } },
|
|
};
|
|
}
|
|
|
|
type ProjectAccessIncludes = ReturnType<typeof projectAccessInclude>;
|
|
type WorkspaceForAccess = ProjectAccessIncludes['workspace']['select'] extends object
|
|
? {
|
|
id: string;
|
|
ownerId: string;
|
|
owner: Parameters<typeof hasBillingAccess>[0] | null;
|
|
members: Array<{ role: WorkspaceMemberRole }>;
|
|
}
|
|
: never;
|
|
|
|
export type EnrichedProjectForAccess = {
|
|
id: string;
|
|
ownerId: string;
|
|
workspaceId: string;
|
|
visibility: string;
|
|
workspace: WorkspaceForAccess;
|
|
members: Array<{ role: ProjectMemberRole }>;
|
|
};
|
|
|
|
/**
|
|
* The project permission formulas, in one place.
|
|
*
|
|
* Two functions resolve the same six inputs by different routes:
|
|
* `computeProjectAccess` reads them off a project that was fetched with
|
|
* `projectAccessInclude()`, and `checkProjectAccess` queries for each relation.
|
|
* They then have to agree on what those inputs mean. Both used to carry a
|
|
* verbatim copy of the three formulas below, which is a silent-divergence
|
|
* hazard rather than a style complaint: change an authorization rule in one
|
|
* copy and not the other and a page renders for somebody the API would refuse.
|
|
*/
|
|
function resolveProjectPermissions(input: {
|
|
isOwner: boolean;
|
|
isPublic: boolean;
|
|
isProjectMember: boolean;
|
|
isProjectAdmin: boolean;
|
|
workspaceRole: WorkspaceMemberRole | 'OWNER' | null;
|
|
ownerBillingActive: boolean;
|
|
}) {
|
|
const { isOwner, isPublic, isProjectMember, isProjectAdmin, workspaceRole, ownerBillingActive } =
|
|
input;
|
|
|
|
const isWorkspaceMember = !!workspaceRole;
|
|
const isWorkspaceAdmin = workspaceRole === WorkspaceMemberRole.ADMIN || workspaceRole === 'OWNER';
|
|
|
|
return {
|
|
isOwner,
|
|
isProjectMember,
|
|
isProjectAdmin,
|
|
isWorkspaceMember,
|
|
isWorkspaceAdmin,
|
|
hasAccess: ownerBillingActive && (isOwner || isProjectMember || isPublic || isWorkspaceMember),
|
|
canEdit: ownerBillingActive && (isOwner || isProjectAdmin || isWorkspaceAdmin),
|
|
canDelete: ownerBillingActive && (isOwner || workspaceRole === 'OWNER'),
|
|
ownerBillingActive,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* The workspace permission formulas. Only one caller today, but it is kept
|
|
* beside its project twin and exported so it can be tested directly rather
|
|
* than only through whichever route happens to exercise it.
|
|
*/
|
|
export function resolveWorkspacePermissions(input: {
|
|
isOwner: boolean;
|
|
isMember: boolean;
|
|
isAdmin: boolean;
|
|
ownerBillingActive: boolean;
|
|
}) {
|
|
const { isOwner, isMember, isAdmin, ownerBillingActive } = input;
|
|
|
|
return {
|
|
isOwner,
|
|
isMember,
|
|
isAdmin,
|
|
hasAccess: ownerBillingActive && (isOwner || isMember),
|
|
canEdit: ownerBillingActive && (isOwner || isAdmin),
|
|
canDelete: ownerBillingActive && isOwner,
|
|
ownerBillingActive,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Pure access computation, no DB queries.
|
|
* Use after fetching a project with `projectAccessInclude(userId)`.
|
|
*/
|
|
export function computeProjectAccess(
|
|
project: EnrichedProjectForAccess,
|
|
userId: string | undefined
|
|
) {
|
|
const isOwner = userId === project.ownerId;
|
|
const isPublic = project.visibility === 'PUBLIC';
|
|
|
|
const projectMember = project.members[0] ?? null;
|
|
const isProjectMember = !!projectMember;
|
|
const isProjectAdmin = projectMember?.role === ProjectMemberRole.ADMIN;
|
|
|
|
const workspaceOwnerBillingAccess = project.workspace.owner
|
|
? hasBillingAccess(project.workspace.owner)
|
|
: false;
|
|
|
|
let workspaceRole: WorkspaceMemberRole | 'OWNER' | null = null;
|
|
if (userId === project.workspace.ownerId) {
|
|
workspaceRole = 'OWNER';
|
|
} else {
|
|
const wsMember = project.workspace.members[0] ?? null;
|
|
if (wsMember) workspaceRole = wsMember.role;
|
|
}
|
|
|
|
return resolveProjectPermissions({
|
|
isOwner,
|
|
isPublic,
|
|
isProjectMember,
|
|
isProjectAdmin,
|
|
workspaceRole,
|
|
ownerBillingActive: workspaceOwnerBillingAccess,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Helper to check project access including workspace membership.
|
|
*
|
|
* This used to take an `intent`, which skipped both workspace queries for an owner at
|
|
* `view` intent. That made it report `isWorkspaceMember: false, isWorkspaceAdmin: false`
|
|
* for the actor computeProjectAccess reports `true, true` for: the project owner who also
|
|
* owns the workspace, which is the shape every real signup produces. The two are meant to
|
|
* answer the same question, so they resolve their inputs the same way now and the option
|
|
* is gone rather than kept as a parameter that changes nothing.
|
|
*/
|
|
export async function checkProjectAccess(
|
|
project: { id: string; ownerId: string; workspaceId: string; visibility: string },
|
|
userId: string | undefined
|
|
) {
|
|
const isOwner = userId === project.ownerId;
|
|
const isPublic = project.visibility === 'PUBLIC';
|
|
|
|
// Get project membership
|
|
const projectMember = userId
|
|
? await db.projectMember.findUnique({
|
|
where: { projectId_userId: { projectId: project.id, userId } },
|
|
})
|
|
: null;
|
|
const isProjectMember = !!projectMember;
|
|
const isProjectAdmin = projectMember?.role === ProjectMemberRole.ADMIN;
|
|
|
|
// The workspace role decides `canEdit`/`isWorkspaceMember`, not just whether the viewer
|
|
// gets in at all, so it is resolved for every signed-in caller, owners included. The two
|
|
// queries run together, so this costs one extra indexed lookup and no extra latency.
|
|
const [wsMember, wsOwner] = await Promise.all([
|
|
userId
|
|
? db.workspaceMember.findUnique({
|
|
where: { workspaceId_userId: { workspaceId: project.workspaceId, userId } },
|
|
})
|
|
: null,
|
|
db.workspace.findUnique({
|
|
where: { id: project.workspaceId },
|
|
select: {
|
|
ownerId: true,
|
|
owner: {
|
|
select: {
|
|
subscriptionStatus: true,
|
|
trialEndsAt: true,
|
|
stripeCurrentPeriodEnd: true,
|
|
billingAccessEndedAt: true,
|
|
},
|
|
},
|
|
},
|
|
}),
|
|
]);
|
|
|
|
let workspaceRole: WorkspaceMemberRole | 'OWNER' | null = null;
|
|
if (userId && wsOwner?.ownerId === userId) {
|
|
workspaceRole = 'OWNER';
|
|
} else if (wsMember) {
|
|
workspaceRole = wsMember.role;
|
|
}
|
|
|
|
const workspaceOwnerBillingAccess = wsOwner?.owner ? hasBillingAccess(wsOwner.owner) : false;
|
|
|
|
return resolveProjectPermissions({
|
|
isOwner,
|
|
isPublic,
|
|
isProjectMember,
|
|
isProjectAdmin,
|
|
workspaceRole,
|
|
ownerBillingActive: workspaceOwnerBillingAccess,
|
|
});
|
|
}
|
|
|
|
// Helper to check workspace access
|
|
export async function checkWorkspaceAccess(
|
|
workspace: { id: string; ownerId: string },
|
|
userId: string | undefined
|
|
) {
|
|
const isOwner = userId === workspace.ownerId;
|
|
|
|
// Get workspace membership
|
|
const workspaceMember = userId
|
|
? await db.workspaceMember.findUnique({
|
|
where: { workspaceId_userId: { workspaceId: workspace.id, userId } },
|
|
})
|
|
: null;
|
|
const isMember = !!workspaceMember;
|
|
const isAdmin = workspaceMember?.role === WorkspaceMemberRole.ADMIN;
|
|
|
|
const owner = await db.user.findUnique({
|
|
where: { id: workspace.ownerId },
|
|
select: {
|
|
subscriptionStatus: true,
|
|
trialEndsAt: true,
|
|
stripeCurrentPeriodEnd: true,
|
|
billingAccessEndedAt: true,
|
|
},
|
|
});
|
|
const ownerBillingActive = owner ? hasBillingAccess(owner) : false;
|
|
|
|
return resolveWorkspacePermissions({ isOwner, isMember, isAdmin, ownerBillingActive });
|
|
}
|