staging-tester / ocean-landing-serve / src/ lib/ live/ github.ts

import { replaceState } from '$app/navigation';
import { page } from '$app/state';
import { ApiFailure, request } from './http.js';
import { needsSecondFactor, completeSecondFactor } from './security.svelte.js';

export type Identity = { provider: string; login: string; createdAt: string };

const messages: Record<string, string> = {
	github_state: 'The GitHub sign-in expired before it finished. Try again.',
	github_denied: 'GitHub did not give Sailfork access, so nothing was connected.',
	github_unavailable: 'Could not reach GitHub. Try again in a moment.',
	github_email_taken: 'An account with that email already exists. Sign in to it, then connect GitHub from your settings.',
	github_email_unverified: 'GitHub has no verified email for that account. Verify one on GitHub, then try again.',
	github_link_session: 'Sign in first, then connect GitHub again.',
	github_other_account: 'A different GitHub account is already connected here. Disconnect it first, then connect the new one.',
	github_taken: 'This GitHub account is already linked to another Sailfork account. Sign in to that account and disconnect it there first.'
};

export const githubError = (code: string | null) => (code ? (messages[code] ?? 'GitHub sign-in failed. Try again.') : null);

// The callback reports how a link went in the query; pages read it once and drop it from the address bar.
export const takeGithubOutcome = (): { linked: boolean; error: string | null } | null => {
	const url = page.url;
	const linked = url.searchParams.get('github') === 'linked';
	const error = githubError(url.searchParams.get('github_error'));
	if (!linked && !error) return null;
	const clean = new URL(url.href);
	clean.searchParams.delete('github');
	clean.searchParams.delete('github_error');
	replaceState(clean, page.state);
	return { linked, error };
};

export const avatarUrl = (login: string) => `https://avatars.githubusercontent.com/${encodeURIComponent(login)}?size=64`;

// A full-page redirect: GitHub's consent screen and the callback both need the browser, not fetch.
export const githubStartUrl = (next: string) => `/api/auth/github/start?next=${encodeURIComponent(next)}`;

export const startGithubSignIn = (next: string) => location.assign(githubStartUrl(next));

// Finishes a GitHub sign-in that stopped for a second factor. Resolves to null once signed in, or the reason it stopped.
export async function finishGithubSecondFactor(): Promise<{ stopped: string | null; next: string | null }> {
	let body: unknown;
	try {
		body = await request<unknown>('GET', '/api/auth/github/pending');
	} catch (err) {
		const stopped = err instanceof ApiFailure && err.status === 404 ? 'That sign-in already finished or expired. Start again.' : 'Could not sign in. Try again in a moment.';
		return { stopped, next: null };
	}
	const next = typeof body === 'object' && body !== null && 'next' in body && typeof body.next === 'string' ? body.next : null;
	if (!needsSecondFactor(body)) return { stopped: 'Could not sign in. Try again in a moment.', next };
	return { stopped: await completeSecondFactor(body), next };
}

export const loadIdentities = () => request<Identity[]>('GET', '/api/me/identities');

// The authorize URL for linking GitHub to the signed-in account; the browser goes there and comes back to `next`.
export const linkGithub = async (next: string) => (await request<{ url: string }>('POST', `/api/me/identities/github/link?next=${encodeURIComponent(next)}`)).url;

export const unlinkGithub = () => request<void>('DELETE', '/api/me/identities/github');

export const installUrl = async () => (await request<{ url: string }>('GET', '/api/github/install-url')).url;

export type Installation = { id: number; accountLogin: string; accountType: string; repositorySelection: string; suspended: boolean };

export const loadInstallations = () => request<Installation[]>('GET', '/api/github/installations');

// GitHub's own page for changing which repositories an installation covers and what it may do.
export const installationSettingsUrl = (i: Installation) =>
	i.accountType === 'Organization'
		? `https://github.com/organizations/${encodeURIComponent(i.accountLogin)}/settings/installations/${i.id}`
		: `https://github.com/settings/installations/${i.id}`;

export const selectionLabel = (i: Installation) => (i.repositorySelection === 'selected' ? 'Selected repositories' : 'All repositories');

export const covering = (list: Installation[], account: string) => list.find((i) => i.accountLogin.toLowerCase() === account.toLowerCase());

// Opens a GitHub page in a new tab and calls `back` once when this tab is focused again.
export const openOnGithub = (url: string, back: () => void) => {
	window.open(url, '_blank', 'noopener');
	whenBack(back);
};

export const whenBack = (back: () => void) => {
	const focus = () => {
		window.removeEventListener('focus', focus);
		back();
	};
	window.addEventListener('focus', focus);
};

// After a GitHub sign-in matched this email: the owner has just signed in with their password and confirms the link.
export const confirmGithubLink = () => request<{ next: string }>('POST', '/api/me/identities/github/confirm');