238 lines
8.6 KiB
TypeScript
238 lines
8.6 KiB
TypeScript
import { randomBytes, timingSafeEqual } from "node:crypto";
|
||
import { type Context, Hono } from "hono";
|
||
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
|
||
import { buildAgenda } from "./agenda.js";
|
||
import { MOCK_REFRESH_TOKEN } from "./google/mock-client.js";
|
||
import { GoogleAuthError, type GoogleClient, GoogleError } from "./google/types.js";
|
||
import { isLocale, type Locale, pickLocale } from "./i18n.js";
|
||
import { reportError } from "./sentry.js";
|
||
import { createConnectionCodec } from "./session.js";
|
||
import { AgendaPage, ConnectPage, MessagePage, NOTICES, type Notice } from "./views.js";
|
||
|
||
export type AppDeps = {
|
||
google: GoogleClient;
|
||
sessionSecret: string | Buffer;
|
||
publicUrl?: string | null;
|
||
now?: () => Date;
|
||
};
|
||
|
||
const CONNECTION_COOKIE = "ea_conn";
|
||
const STATE_COOKIE = "ea_state";
|
||
const LANG_COOKIE = "ea_lang";
|
||
/** Причина и число неудач подряд, «setup:2» (час): после второго раза по той же причине подсказка другая. */
|
||
const FAIL_COOKIE = "ea_fail";
|
||
const HOUR_SECONDS = 60 * 60;
|
||
const YEAR_SECONDS = 365 * 24 * 60 * 60;
|
||
const HOUR_MS = 60 * 60 * 1000;
|
||
const CALLBACK_PATH = "/auth/google/callback";
|
||
|
||
type Env = { Variables: { locale: Locale } };
|
||
|
||
function readFailures(raw: string | undefined): { notice: string | null; count: number } {
|
||
const [notice, count] = (raw ?? "").split(":");
|
||
return { notice: notice || null, count: Number.parseInt(count ?? "", 10) || 0 };
|
||
}
|
||
|
||
function firstHeaderValue(value: string | undefined): string | undefined {
|
||
return value?.split(",")[0]?.trim() || undefined;
|
||
}
|
||
|
||
function isLocalHost(host: string): boolean {
|
||
const name = host.replace(/:\d+$/, "").replace(/^\[|\]$/g, "");
|
||
return name === "localhost" || name === "::1" || /^127(\.\d+){3}$/.test(name);
|
||
}
|
||
|
||
function sameText(a: string, b: string): boolean {
|
||
const left = Buffer.from(a);
|
||
const right = Buffer.from(b);
|
||
return left.length === right.length && timingSafeEqual(left, right);
|
||
}
|
||
|
||
export function createApp(deps: AppDeps) {
|
||
const { google } = deps;
|
||
const now = deps.now ?? (() => new Date());
|
||
const codec = createConnectionCodec(deps.sessionSecret);
|
||
const app = new Hono<Env>();
|
||
|
||
/** Внешний адрес продукта: настройка или адрес запроса (за обратным прокси). */
|
||
function baseUrl(c: Context): string {
|
||
if (deps.publicUrl) return deps.publicUrl;
|
||
const url = new URL(c.req.url);
|
||
const host =
|
||
firstHeaderValue(c.req.header("x-forwarded-host")) ?? c.req.header("host") ?? url.host;
|
||
// Google принимает адрес возврата только по https (кроме localhost), а прокси
|
||
// перед продуктом может не передать, что снаружи адрес https.
|
||
const proto = isLocalHost(host)
|
||
? (firstHeaderValue(c.req.header("x-forwarded-proto")) ?? url.protocol.replace(":", ""))
|
||
: "https";
|
||
return `${proto}://${host}`;
|
||
}
|
||
|
||
function cookieOptions(c: Context, maxAge: number) {
|
||
return {
|
||
path: "/",
|
||
httpOnly: true,
|
||
sameSite: "Lax" as const,
|
||
secure: baseUrl(c).startsWith("https://"),
|
||
maxAge,
|
||
};
|
||
}
|
||
|
||
app.get("/healthz", (c) => c.text("ok"));
|
||
|
||
app.use(async (c, next) => {
|
||
const query = c.req.query("lang");
|
||
const locale = pickLocale({
|
||
query,
|
||
cookie: getCookie(c, LANG_COOKIE),
|
||
acceptLanguage: c.req.header("accept-language"),
|
||
});
|
||
if (isLocale(query)) setCookie(c, LANG_COOKIE, query, cookieOptions(c, YEAR_SECONDS));
|
||
c.set("locale", locale);
|
||
c.header("Cache-Control", "no-store");
|
||
await next();
|
||
});
|
||
|
||
/** Образец списка для экрана подключения (только у мока); без него экран остаётся без образца. */
|
||
async function loadSample() {
|
||
try {
|
||
const moment = now();
|
||
const accessToken = await google.refreshAccessToken(MOCK_REFRESH_TOKEN);
|
||
const { timeZone, events } = await google.listEvents(accessToken, {
|
||
timeMin: new Date(moment.getTime() - 48 * HOUR_MS),
|
||
timeMax: new Date(moment.getTime() + 9 * 24 * HOUR_MS),
|
||
});
|
||
const days = buildAgenda(events, timeZone, moment);
|
||
return days.length > 0 ? { days, timeZone } : null;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
app.get("/", async (c) => {
|
||
const locale = c.get("locale");
|
||
const isMock = google.isMock;
|
||
const connection = codec.open(getCookie(c, CONNECTION_COOKIE));
|
||
|
||
if (!connection) {
|
||
const param = c.req.query("notice");
|
||
const notice = NOTICES.find((name) => name === param) ?? null;
|
||
const last = readFailures(getCookie(c, FAIL_COOKIE));
|
||
const sample = isMock ? await loadSample() : null;
|
||
return c.html(
|
||
<ConnectPage
|
||
locale={locale}
|
||
isMock={isMock}
|
||
notice={notice}
|
||
repeated={notice !== null && last.notice === notice && last.count >= 2}
|
||
sample={sample}
|
||
/>,
|
||
);
|
||
}
|
||
|
||
try {
|
||
const moment = now();
|
||
const accessToken = await google.refreshAccessToken(connection.refreshToken);
|
||
// Запас по краям: «сегодня» в поясе календаря узнаём только из ответа.
|
||
const { timeZone, events } = await google.listEvents(accessToken, {
|
||
timeMin: new Date(moment.getTime() - 48 * HOUR_MS),
|
||
timeMax: new Date(moment.getTime() + 9 * 24 * HOUR_MS),
|
||
});
|
||
const days = buildAgenda(events, timeZone, moment);
|
||
return c.html(<AgendaPage locale={locale} isMock={isMock} days={days} timeZone={timeZone} />);
|
||
} catch (error) {
|
||
if (error instanceof GoogleAuthError) {
|
||
deleteCookie(c, CONNECTION_COOKIE, { path: "/" });
|
||
return c.html(
|
||
<MessagePage
|
||
locale={locale}
|
||
isMock={isMock}
|
||
title="revoked.title"
|
||
message="revoked.message"
|
||
action={{ href: "/connect", label: "reconnect.button" }}
|
||
/>,
|
||
);
|
||
}
|
||
reportError(error);
|
||
return c.html(
|
||
<MessagePage
|
||
locale={locale}
|
||
isMock={isMock}
|
||
title="unavailable.title"
|
||
message="unavailable.message"
|
||
action={{ href: "/", label: "refresh.button" }}
|
||
/>,
|
||
);
|
||
}
|
||
});
|
||
|
||
app.get("/connect", (c) => {
|
||
const state = randomBytes(24).toString("base64url");
|
||
setCookie(c, STATE_COOKIE, state, cookieOptions(c, 600));
|
||
return c.redirect(google.authUrl({ state, redirectUri: `${baseUrl(c)}${CALLBACK_PATH}` }));
|
||
});
|
||
|
||
app.get(CALLBACK_PATH, async (c) => {
|
||
const expected = getCookie(c, STATE_COOKIE);
|
||
deleteCookie(c, STATE_COOKIE, { path: "/" });
|
||
const state = c.req.query("state");
|
||
const code = c.req.query("code");
|
||
|
||
/** Запоминает неудачу и ведёт на главную с причиной; счёт нужен для другой подсказки. */
|
||
const fail = (notice: Notice) => {
|
||
const last = readFailures(getCookie(c, FAIL_COOKIE));
|
||
const count = last.notice === notice ? last.count + 1 : 1;
|
||
setCookie(c, FAIL_COOKIE, `${notice}:${count}`, cookieOptions(c, HOUR_SECONDS));
|
||
return c.redirect(`/?notice=${notice}`);
|
||
};
|
||
|
||
if (!expected || !state || !sameText(expected, state)) return fail("browser");
|
||
const googleError = c.req.query("error");
|
||
if (googleError === "access_denied") return fail("denied");
|
||
if (googleError) return fail("setup");
|
||
if (!code) return fail("failed");
|
||
|
||
try {
|
||
const { refreshToken } = await google.exchangeCode({
|
||
code,
|
||
redirectUri: `${baseUrl(c)}${CALLBACK_PATH}`,
|
||
});
|
||
setCookie(c, CONNECTION_COOKIE, codec.seal({ refreshToken }), cookieOptions(c, YEAR_SECONDS));
|
||
deleteCookie(c, FAIL_COOKIE, { path: "/" });
|
||
return c.redirect("/");
|
||
} catch (error) {
|
||
reportError(error);
|
||
return fail(error instanceof GoogleError && error.kind ? error.kind : "failed");
|
||
}
|
||
});
|
||
|
||
app.notFound((c) =>
|
||
c.html(
|
||
<MessagePage
|
||
locale={c.get("locale") ?? pickLocale({ acceptLanguage: c.req.header("accept-language") })}
|
||
isMock={google.isMock}
|
||
title="notFound.title"
|
||
message="notFound.message"
|
||
action={{ href: "/", label: "notFound.button" }}
|
||
/>,
|
||
404,
|
||
),
|
||
);
|
||
|
||
app.onError((error, c) => {
|
||
reportError(error);
|
||
return c.html(
|
||
<MessagePage
|
||
locale={c.get("locale") ?? pickLocale({ acceptLanguage: c.req.header("accept-language") })}
|
||
isMock={google.isMock}
|
||
title="error.title"
|
||
message="error.message"
|
||
action={{ href: "/", label: "refresh.button" }}
|
||
/>,
|
||
500,
|
||
);
|
||
});
|
||
|
||
return app;
|
||
}
|