Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion apps/web/src/app/api/auth/apple/callback/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,9 @@ export async function POST(req: Request) {
const provisionedDrive = await provisionGettingStartedDriveIfNeeded(user.id);
if (provisionedDrive.created) {
isNewlyProvisioned = true;
returnUrl = `/dashboard/${provisionedDrive.driveId}`;
if (!returnUrl.startsWith('/s/')) {
returnUrl = `/dashboard/${provisionedDrive.driveId}`;
}
}
} catch (provisionError) {
loggers.auth.error('Failed to provision Getting Started drive', provisionError as Error, {
Expand Down
7 changes: 5 additions & 2 deletions apps/web/src/app/api/auth/apple/native/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { maskEmail } from '@pagespace/lib/audit/mask-email';
import { trackAuthEvent } from '@pagespace/lib/monitoring/activity-tracker';
import { z } from 'zod/v4';
import { provisionGettingStartedDriveIfNeeded } from '@/lib/onboarding/getting-started-drive';
import { getClientIP } from '@/lib/auth';
import { getClientIP, isSafeReturnUrl } from '@/lib/auth';
import { appendSessionCookie } from '@/lib/auth/cookie-config';
import {
checkDistributedRateLimit,
Expand All @@ -34,6 +34,7 @@ const nativeAuthSchema = z.object({
givenName: z.string().optional(),
familyName: z.string().optional(),
inviteToken: z.string().min(1).max(INVITE_TOKEN_MAX_LENGTH).optional(),
returnUrl: z.string().max(2048).optional(),
});

/**
Expand Down Expand Up @@ -74,7 +75,8 @@ export async function POST(req: Request) {
);
}

const { idToken, platform, deviceId, deviceName, givenName, familyName, inviteToken } = validation.data;
const { idToken, platform, deviceId, deviceName, givenName, familyName, inviteToken, returnUrl: rawReturnUrl } = validation.data;
const returnUrl = rawReturnUrl && isSafeReturnUrl(rawReturnUrl) ? rawReturnUrl : undefined;

// Validate required environment variables
if (!process.env.APPLE_CLIENT_ID) {
Expand Down Expand Up @@ -255,6 +257,7 @@ export async function POST(req: Request) {
invitedPageId: inviteResult.invitedPageId,
invitedConnectionId: inviteResult.connectionId,
...(inviteResult.inviteError && { inviteError: inviteResult.inviteError }),
...(returnUrl && { returnUrl }),
user: {
id: user.id,
name: user.name,
Expand Down
4 changes: 3 additions & 1 deletion apps/web/src/app/api/auth/google/callback/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,9 @@ export async function GET(req: Request) {
const provisionedDrive = await provisionGettingStartedDriveIfNeeded(user.id);
if (provisionedDrive.created) {
isNewlyProvisioned = true;
returnUrl = `/dashboard/${provisionedDrive.driveId}`;
if (!returnUrl.startsWith('/s/')) {
returnUrl = `/dashboard/${provisionedDrive.driveId}`;
}
}
} catch (error) {
loggers.auth.error('Failed to provision Getting Started drive', error as Error, {
Expand Down
7 changes: 5 additions & 2 deletions apps/web/src/app/api/auth/google/native/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { maskEmail } from '@pagespace/lib/audit/mask-email';
import { trackAuthEvent } from '@pagespace/lib/monitoring/activity-tracker';
import { z } from 'zod/v4';
import { provisionGettingStartedDriveIfNeeded } from '@/lib/onboarding/getting-started-drive';
import { getClientIP } from '@/lib/auth';
import { getClientIP, isSafeReturnUrl } from '@/lib/auth';
import { appendSessionCookie } from '@/lib/auth/cookie-config';
import { resolveGoogleAvatarImage } from '@/lib/auth/google-avatar';
import {
Expand All @@ -33,6 +33,7 @@ const nativeAuthSchema = z.object({
deviceId: z.string().min(1, 'Device ID is required'),
deviceName: z.string().optional(),
inviteToken: z.string().min(1).max(INVITE_TOKEN_MAX_LENGTH).optional(),
returnUrl: z.string().max(2048).optional(),
});

/**
Expand Down Expand Up @@ -73,7 +74,8 @@ export async function POST(req: Request) {
);
}

const { idToken, platform, deviceId, deviceName, inviteToken } = validation.data;
const { idToken, platform, deviceId, deviceName, inviteToken, returnUrl: rawReturnUrl } = validation.data;
const returnUrl = rawReturnUrl && isSafeReturnUrl(rawReturnUrl) ? rawReturnUrl : undefined;

// Validate required environment variables
if (!process.env.GOOGLE_OAUTH_CLIENT_ID || !process.env.GOOGLE_OAUTH_IOS_CLIENT_ID) {
Expand Down Expand Up @@ -278,6 +280,7 @@ export async function POST(req: Request) {
invitedPageId: inviteResult.invitedPageId,
invitedConnectionId: inviteResult.connectionId,
...(inviteResult.inviteError && { inviteError: inviteResult.inviteError }),
...(returnUrl && { returnUrl }),
user: {
id: user.id,
name: user.name,
Expand Down
7 changes: 5 additions & 2 deletions apps/web/src/app/auth/signin/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@ function SignInForm() {
isWaitingForExternalAuth,
waitingProvider,
cancelExternalAuth,
} = useOAuthSignIn(inviteToken ? { inviteToken } : {});
} = useOAuthSignIn({
...(inviteToken && { inviteToken }),
...(nextPath && { returnUrl: nextPath }),
});
const onPrem = isOnPrem();

useEffect(() => {
Expand Down Expand Up @@ -236,7 +239,7 @@ function SignInForm() {
<p className="text-sm text-muted-foreground">
Don&apos;t have an account?{" "}
<Link
href="/auth/signup"
href={nextPath ? `/auth/signup?next=${encodeURIComponent(nextPath)}` : '/auth/signup'}
className="font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300"
>
Sign up
Expand Down
11 changes: 7 additions & 4 deletions apps/web/src/app/auth/signup/SignUpClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ import type { InviteContextData } from '@/lib/auth/invite-resolver';
interface SignUpClientProps {
inviteToken?: string;
inviteContext?: InviteContextData;
returnUrl?: string;
}

export function SignUpClient({ inviteToken, inviteContext }: SignUpClientProps) {
export function SignUpClient({ inviteToken, inviteContext, returnUrl }: SignUpClientProps) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
const [error, setError] = useState<string | null>(null);
const [showMagicLink, setShowMagicLink] = useState(false);
const router = useRouter();
Expand All @@ -41,6 +42,7 @@ export function SignUpClient({ inviteToken, inviteContext }: SignUpClientProps)
onStart: () => setError(null),
onError: (msg) => setError(msg),
...(inviteToken && { inviteToken }),
...(returnUrl && { returnUrl }),
});

const isAnyLoading = isGoogleLoading || isAppleLoading || passkeyLoading;
Expand Down Expand Up @@ -115,12 +117,13 @@ export function SignUpClient({ inviteToken, inviteContext }: SignUpClientProps)
csrfToken={csrfToken}
refreshToken={refreshToken}
onEmailExists={() => {
router.push('/auth/signin');
router.push(returnUrl ? `/auth/signin?next=${encodeURIComponent(returnUrl)}` : '/auth/signin');
}}
onLoadingChange={setPasskeyLoading}
disabled={isAnyLoading}
inviteToken={inviteToken}
lockedEmail={inviteContext?.email}
{...(returnUrl && { nextPath: returnUrl })}
/>
</motion.div>
)}
Expand Down Expand Up @@ -153,7 +156,7 @@ export function SignUpClient({ inviteToken, inviteContext }: SignUpClientProps)
>
{showMagicLink ? (
<div id="magic-link-form" className="mt-2">
<MagicLinkForm {...(inviteToken && { inviteToken })} />
<MagicLinkForm {...(inviteToken && { inviteToken })} {...(returnUrl && { nextPath: returnUrl })} />
</div>
) : (
<button
Expand All @@ -178,7 +181,7 @@ export function SignUpClient({ inviteToken, inviteContext }: SignUpClientProps)
<p className="text-sm text-muted-foreground">
Already have an account?{' '}
<Link
href="/auth/signin"
href={returnUrl ? `/auth/signin?next=${encodeURIComponent(returnUrl)}` : '/auth/signin'}
className="font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300"
>
Log in
Expand Down
12 changes: 8 additions & 4 deletions apps/web/src/app/auth/signup/page.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { redirect } from 'next/navigation';
import { resolveInviteContext } from '@/lib/auth/invite-resolver';
import { isOnPrem } from '@/lib/deployment-mode';
import { isSafeNextPath, SIGNIN_NEXT_ALLOWED_PREFIXES } from '@/lib/auth/auth-helpers';
import { SignUpClient } from './SignUpClient';

interface SignUpPageProps {
searchParams: Promise<{ invite?: string }>;
searchParams: Promise<{ invite?: string; next?: string }>;
}

export default async function SignUp({ searchParams }: SignUpPageProps) {
Expand All @@ -13,10 +14,13 @@ export default async function SignUp({ searchParams }: SignUpPageProps) {
redirect('/auth/signin?onprem=contact_admin');
}

const { invite } = await searchParams;
const { invite, next } = await searchParams;
const safeNext = next && isSafeNextPath({ path: next, allowedPrefixes: SIGNIN_NEXT_ALLOWED_PREFIXES })
? next
: undefined;

if (!invite) {
return <SignUpClient />;
return <SignUpClient {...(safeNext && { returnUrl: safeNext })} />;
}

const resolution = await resolveInviteContext({ token: invite, now: new Date() });
Expand All @@ -27,5 +31,5 @@ export default async function SignUp({ searchParams }: SignUpPageProps) {
redirect(`/invite/${encodeURIComponent(invite)}`);
}

return <SignUpClient inviteToken={invite} inviteContext={resolution.data} />;
return <SignUpClient inviteToken={invite} inviteContext={resolution.data} {...(safeNext && { returnUrl: safeNext })} />;
}
159 changes: 97 additions & 62 deletions apps/web/src/app/s/[token]/DriveShareAccept.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client';

import { useState } from 'react';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
Expand All @@ -17,81 +17,116 @@ interface DriveShareAcceptProps {
export function DriveShareAccept({ token, info }: DriveShareAcceptProps) {
const router = useRouter();
const { isAuthenticated, isLoading: authLoading } = useAuth();
const { csrfToken } = useCSRFToken();
const { csrfToken, isLoading: csrfLoading, error: csrfError } = useCSRFToken();
const [isPending, setIsPending] = useState(false);
const [error, setError] = useState<string | null>(null);

async function handleJoin() {
if (!isAuthenticated) {
router.push(`/auth/signin?next=/s/${token}`);
return;
}
if (!csrfToken) return;
setIsPending(true);
setError(null);
useEffect(() => {
if (!isAuthenticated || !csrfToken) return;

Comment thread
coderabbitai[bot] marked this conversation as resolved.
try {
const res = await fetch(`/api/share/${token}/accept`, {
method: 'POST',
headers: { 'x-csrf-token': csrfToken },
credentials: 'include',
});
const controller = new AbortController();

if (!res.ok) {
const body = await res.json().catch(() => ({}));
setError((body as { error?: string }).error ?? 'Failed to join. Please try again.');
return;
}
async function accept() {
setIsPending(true);
try {
const res = await fetch(`/api/share/${token}/accept`, {
method: 'POST',
headers: { 'x-csrf-token': csrfToken! },
credentials: 'include',
signal: controller.signal,
});

if (!res.ok) {
const body = await res.json().catch(() => ({}));
setError((body as { error?: string }).error ?? 'Failed to join. Please try again.');
return;
}

const data = (await res.json()) as { type: string; driveId: string };
router.push(`/dashboard/${data.driveId}`);
} catch {
setError('Something went wrong. Please try again.');
} finally {
setIsPending(false);
const data = (await res.json()) as { type: string; driveId: string };
router.push(`/dashboard/${data.driveId}`);
} catch (err) {
if ((err as Error).name === 'AbortError') return;
setError('Something went wrong. Please try again.');
} finally {
setIsPending(false);
}
}
}

return (
<div className="space-y-6">
<div className="text-center">
<h1 className="text-2xl font-bold tracking-tight text-gray-900 dark:text-white">
Join{' '}
<span className="text-blue-600 dark:text-blue-400">
{info.driveName ?? 'this workspace'}
accept();
return () => controller.abort();
}, [isAuthenticated, csrfToken, token, router]);

if (authLoading || (isAuthenticated && (csrfLoading || isPending) && !error)) {
return (
<div className="text-center space-y-4">
<p className="text-sm text-muted-foreground">
Joining{' '}
<span className="font-medium text-gray-900 dark:text-gray-100">
{info.driveName ?? 'workspace'}
</span>
</h1>
<p className="mt-3 text-sm text-muted-foreground">
<span className="font-medium text-gray-900 dark:text-gray-100">{info.creatorName}</span>
{' '}shared an invite link.{' '}
You&apos;ll join as a{' '}
<Badge variant="secondary" className="text-xs">
{info.role ?? 'Member'}
</Badge>
.
…
</p>
<div className="flex justify-center">
<div className="h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
</div>
</div>
);
}

if (!isAuthenticated) {
return (
<div className="space-y-6">
<div className="text-center">
<h1 className="text-2xl font-bold tracking-tight text-gray-900 dark:text-white">
Join{' '}
<span className="text-blue-600 dark:text-blue-400">
{info.driveName ?? 'this workspace'}
</span>
</h1>
<p className="mt-3 text-sm text-muted-foreground">
<span className="font-medium text-gray-900 dark:text-gray-100">{info.creatorName}</span>
{' '}shared an invite link.{' '}
You&apos;ll join as a{' '}
<Badge variant="secondary" className="text-xs">
{info.role ?? 'Member'}
</Badge>
.
</p>
</div>

{error && (
<p className="text-sm text-destructive text-center">{error}</p>
)}
<Button className="w-full" onClick={() => router.push(`/auth/signin?next=${encodeURIComponent(`/s/${token}`)}`)}>
Sign in to join
</Button>

<Button
className="w-full"
onClick={handleJoin}
disabled={isPending || authLoading || (isAuthenticated && !csrfToken)}
>
{isPending ? 'Joining…' : `Join ${info.driveName ?? 'workspace'}`}
</Button>
<div className="text-center">
<Link
href="/dashboard"
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
>
Not now
</Link>
</div>
</div>
);
}

<div className="text-center">
<Link
href="/dashboard"
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
>
Not now
if (csrfError || error) {
return (
<div className="text-center space-y-6">
<div>
<h1 className="text-2xl font-bold tracking-tight text-gray-900 dark:text-white">
Something went wrong
</h1>
<p className="mt-3 text-sm text-muted-foreground">
{error ?? 'Something went wrong. Please try again.'}
</p>
</div>
<Link href="/dashboard">
<Button variant="outline" className="w-full">Go to dashboard</Button>
</Link>
</div>
</div>
);
);
}

return null;
Comment thread
2witstudios marked this conversation as resolved.
}
Loading
Loading