staging-tester / ocean-landing-serve / src/ routes/ sign-in/ +page.svelte

<script lang="ts">
	import * as z from 'zod';
	import { goto } from '$app/navigation';
	import { page } from '$app/state';
	import AuthShell from '#lib/components/site/AuthShell.svelte';
	import Field from '#lib/components/site/Field.svelte';
	import PasswordInput from '#lib/components/site/PasswordInput.svelte';
	import ProviderSignIn from '#lib/components/site/ProviderSignIn.svelte';
	import { Button } from '#lib/components/ui/button/index.js';
	import { Input } from '#lib/components/ui/input/index.js';
	import { email as emailRule, firstErrors } from '#lib/forms.js';
	import { confirmGithubLink, finishGithubSecondFactor, githubError } from '#lib/live/github.js';
	import { clearBoot } from '#lib/live/boot.js';
	import { landing } from '#lib/live/identity.svelte.js';
	import { ApiFailure, request } from '#lib/live/http.js';
	import { completeSecondFactor, needsSecondFactor, signInWithPasskey } from '#lib/live/security.svelte.js';

	const schema = z.object({ email: emailRule, password: z.string().min(1, 'Enter your password') });

	// Where to land after signing in: ?next= from the page that asked, if it is a path on this site.
	const next = async () => {
		const to = page.url.searchParams.get('next') ?? '';
		return to.startsWith('/') && !to.startsWith('//') && !to.startsWith('/\\') ? to : await landing();
	};

	let email = $state('');
	let password = $state('');
	let errors = $state<Record<string, string>>({});
	let pending = $state(false);

	const linking = $derived(page.url.searchParams.get('link') === 'github');

	// GitHub sends the browser back here: a failure code, a second factor still owed, or a link to confirm.
	$effect(() => {
		const failed = githubError(page.url.searchParams.get('github_error'));
		if (failed) errors = { password: failed };
		else if (linking) errors = { password: 'That GitHub account matches your email. Sign in with your password to connect it.' };
		if (page.url.searchParams.get('second-factor') !== 'github') return;
		void finishGithubSecondFactor().then(async ({ stopped, next: to }) => {
			if (stopped) errors = { password: stopped };
			else {
				clearBoot();
				await goto(to ?? (await next()));
			}
		});
	});

	let passkeyPending = $state(false);
	const passkeySignIn = async () => {
		errors = {};
		passkeyPending = true;
		const stopped = await signInWithPasskey(email);
		if (stopped) {
			errors = { password: stopped };
			passkeyPending = false;
			return;
		}
		clearBoot();
		await goto((linking ? (await confirmGithubLink()).next : null) ?? (await next()));
	};

	const submit = async (event: SubmitEvent) => {
		event.preventDefault();
		const parsed = schema.safeParse({ email, password });
		errors = parsed.success ? {} : firstErrors(parsed.error);
		if (!parsed.success) return;
		pending = true;
		try {
			const signedIn = await request<unknown>('POST', '/api/auth/sign-in', { login: email, password });
			if (needsSecondFactor(signedIn)) {
				const stopped = await completeSecondFactor(signedIn);
				if (stopped) {
					errors = { password: stopped };
					pending = false;
					return;
				}
			}
			// What the app last painted from belongs to whoever signed in before; the next boot waits for this account.
			clearBoot();
			await goto((linking ? (await confirmGithubLink()).next : null) ?? (await next()));
		} catch (err) {
			errors = { password: err instanceof ApiFailure && err.status === 401 ? 'That email and password do not match an account.' : 'Could not sign in. Try again in a moment.' };
			pending = false;
		}
	};
</script>

<svelte:head>
	<title>Sign in to Sailfork</title>
</svelte:head>

<AuthShell title="Sign in" intro="Welcome back. Your repositories are where you left them.">
	<ProviderSignIn verb="Sign in" onpasskey={passkeySignIn} {passkeyPending} />
	<form novalidate class="grid gap-5" onsubmit={submit}>
		<Field id="email" label="Work email" error={errors.email}>
			{#snippet children({ describedBy })}
				<Input
					id="email"
					name="email"
					type="email"
					autocomplete="email"
					required
					bind:value={email}
					aria-invalid={errors.email ? true : undefined}
					aria-describedby={describedBy}
				/>
			{/snippet}
		</Field>
		<Field id="password" label="Password" error={errors.password}>
			{#snippet children({ describedBy })}
				<PasswordInput
					id="password"
					name="password"
					autocomplete="current-password"
					required
					bind:value={password}
					aria-invalid={errors.password ? true : undefined}
					aria-describedby={describedBy}
				/>
			{/snippet}
		</Field>
		<a href="/forgot-password" class="type-small -mt-2 w-fit text-primary underline-offset-4 hover:underline">Forgot your password?</a>
		<Button type="submit" size="lg" class="mt-1 w-full" disabled={pending}>
			{pending ? 'Signing in…' : 'Sign in'}
		</Button>
	</form>

	{#snippet footer()}
		New to Sailfork? <a href="/sign-up" class="text-primary underline-offset-4 hover:underline">Create an account</a>
	{/snippet}
</AuthShell>