Implement register and login with Telegram

Add the concept of authentication methods that authenticate an account
where using the telegram login widget is one such method.  If a login is
done with an authentication method that's not associated with any
account the session ends up with the data from the authentication
method in order to allow registering a new account with the
authentication method.

This has to be stored on the session as otherwise it wouldn't be
possible to implement authentication methods such as OAuth2 that takes
the user to a third-party site and then redirects the browser back.
This commit is contained in:
Hornwitser 2025-07-09 15:21:39 +02:00
parent 2d6bcebc5a
commit aaa2faffb1
14 changed files with 357 additions and 8 deletions

View file

@ -33,6 +33,7 @@
</template>
<template v-else>
<NuxtLink to="/login">Log In</NuxtLink>
<NuxtLink to="/register">Register</NuxtLink>
</template>
</div>
</header>

View file

@ -0,0 +1,61 @@
<!--
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
-->
<template>
<div ref="div">
<button
v-if="!loaded"
@click="load"
>
Enable Log in with Telegram
</button>
</div>
</template>
<script lang="ts" setup>
import type { TelegramAuthData } from '~/shared/types/telegram';
const divElement = useTemplateRef("div");
const loaded = ref(false);
const runtimeConfig = useRuntimeConfig();
const sessionStore = useSessionStore();
const route = useRoute();
function load() {
const script = document.createElement("script");
script.async = true;
script.src = "https://telegram.org/js/telegram-widget.js?22";
script.dataset.telegramLogin = runtimeConfig.public.telegramBotUsername;
script.dataset.size = "medium";
script.dataset.onauth = "onTelegramAuth(user)";
script.dataset.requestAccess = "write";
divElement.value?.appendChild(script);
loaded.value = true;
}
async function login(authData: TelegramAuthData) {
const session = await $fetch("/api/auth/ap/telegram-login", {
method: "POST",
body: {
authData,
},
});
sessionStore.update(session);
if (!session.account) {
await navigateTo("/register");
} else if (route.path === "/register") {
await navigateTo("/");
}
}
declare global {
export function onTelegramAuth(user: any): void;
}
onMounted(() => {
// XXX this asumes there's only ever one LogInTelegram component mounted
window.onTelegramAuth = function(authData: TelegramAuthData) {
login(authData).catch(err => alert(err.data?.message ?? err.message));
};
});
</script>

View file

@ -0,0 +1,15 @@
<!--
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
-->
# Authentication
It's possible to configure authentication using a third party Authentication Provider (referred to as AP). Currently only Telegram is supported as an AP.
## Telegram
In order to use Telegram as an AP you need to be hosting Owltide under a domain name over https, using http will not work.
You will also need a bot which can be created by messaging [@BotFather](https://t.me/BotFather), with the domain of the bot set using the `/setdomain` command to the domain Owltide is hosted under.
Once you have the pre-requisites you need to configure `NUXT_TELEGRAM_BOT_TOKEN_FILE` to a path to a file containing the token of the bot with no spaces or new-lines. `NUXT_PUBLIC_TELEGRAM_BOT_USERNAME` to the username of the bot. And finally `NUXT_AUTH_TELEGRAM_ENABLED` to `true` to enable authentication via Telegram.

View file

@ -19,3 +19,21 @@ Time in seconds before a session need to be rotated over into a new session. Whe
Time in seconds before a session is deleted from the client and server, resulting in the user having to authenticate again if the session wasn't rotated over into a new session before this timeout.
This should be several times greater that `NUXT_SESSION_ROTATES_TIMEOUT`.
### NUXT_TELEGRAM_BOT_TOKEN_FILE
Path to a file containing the token for the Telegram bot used for authenticating users via Telegram.
Does nothing if `NUXT_AUTH_TELEGRAM_ENABLED` is not enabled.
### NUXT_PUBLIC_TELEGRAM_BOT_USERNAME
Username of the Telegram bot used for authenticating users via Telegram.
Does nothing if `NUXT_AUTH_TELEGRAM_ENABLED` is not enabled.
### NUXT_AUTH_TELEGRAM_ENABLED
Boolean indicating if authentication via Telegram is enabled or not. Requires `NUXT_PUBLIC_TELEGRAM_BOT_USERNAME` and `NUXT_TELEGRAM_BOT_TOKEN_FILE` to be set in order to work.
Defaults to `false`.

View file

@ -27,9 +27,12 @@ export default defineNuxtConfig({
sessionDiscardTimeout: 14 * oneDaySeconds,
vapidSubject: "",
vapidPrivateKeyFile: "",
telegramBotTokenFile: "",
public: {
defaultTimezone: "Europe/Oslo",
defaultLocale: "en-GB",
authTelegramEnabled: false,
telegramBotUsername: "",
vapidPublicKey: "",
}
},

View file

@ -9,6 +9,7 @@
<input v-model="name" type="text" placeholder="Name" required>
<button type="submit">Log In</button>
</form>
<LogInTelegram v-if="authTelegramEnabled" />
<h2 id="create-account">Create Account</h2>
<p>If you don't have an account you may create one</p>
<form @submit.prevent="createAccount">
@ -38,6 +39,8 @@ useHead({
title: "Login",
});
const runtimeConfig = useRuntimeConfig();
const authTelegramEnabled = runtimeConfig.public.authTelegramEnabled;
const sessionStore = useSessionStore();
const { getSubscription, subscribe } = usePushNotification();

57
pages/register.vue Normal file
View file

@ -0,0 +1,57 @@
<!--
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
-->
<template>
<main>
<h1>Register</h1>
<form @submit.prevent="register">
<h2>User Details</h2>
<p>
<label>
Username
<input type="text" v-model="username">
</label>
</p>
<h2>Authentication Method</h2>
<p v-if="sessionStore.authenticationProvider">
Provider: {{ sessionStore.authenticationProvider }}
<br>Identifier: {{ sessionStore.authenticationName }}
<br><button type="button" @click="clearProvider">Clear Method</button>
</p>
<p v-else>
<LogInTelegram />
</p>
<p>
<button type="submit">Register new account</button>
</p>
</form>
</main>
</template>
<script setup lang="ts">
const sessionStore = useSessionStore();
const username = ref("");
async function clearProvider() {
sessionStore.logOut();
}
async function register() {
let session;
try {
session = await $fetch("/api/auth/account", {
method: "POST",
body: {
name: username.value,
},
});
} catch (err: any) {
alert(err.data?.message ?? err.message);
return;
}
sessionStore.update(session);
if (session.account) {
await navigateTo("/account/settings");
}
}
</script>

View file

@ -2,20 +2,21 @@
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { readUsers, writeUsers, nextUserId, type ServerUser } from "~/server/database";
import { readUsers, writeUsers, nextUserId, type ServerUser, readAuthenticationMethods, nextAuthenticationMethodId, writeAuthenticationMethods } from "~/server/database";
import { broadcastEvent } from "~/server/streams";
import { ApiSession } from "~/shared/types/api";
export default defineEventHandler(async (event) => {
export default defineEventHandler(async (event): Promise<ApiSession> => {
let session = await getServerSession(event, false);
if (session) {
if (session?.accountId !== undefined) {
throw createError({
status: 409,
message: "Cannot create account while having an active session."
message: "Cannot create account while logged in to an account."
});
}
const formData = await readFormData(event);
const name = formData.get("name");
const formData = await readBody(event);
const name = formData.name;
const users = await readUsers();
let user: ServerUser;
@ -54,11 +55,35 @@ export default defineEventHandler(async (event) => {
});
}
if (session?.authenticationProvider) {
const authMethods = await readAuthenticationMethods();
const method = authMethods.find(method => (
method.provider === session.authenticationProvider
&& method.slug === session.authenticationSlug
));
if (method) {
throw createError({
statusCode: 409,
statusMessage: "Conflict",
message: "A user is already associated with the authentication method",
});
}
authMethods.push({
id: await nextAuthenticationMethodId(),
userId: user.id,
provider: session.authenticationProvider,
slug: session.authenticationSlug!,
name: session.authenticationName!,
})
await writeAuthenticationMethods(authMethods);
}
users.push(user);
await writeUsers(users);
await broadcastEvent({
type: "user-update",
data: user,
});
await setServerSession(event, user);
const newSession = await setServerSession(event, user);
return await serverSessionToApi(event, newSession);
})

View file

@ -0,0 +1,100 @@
/*
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import * as fs from "node:fs/promises";
import type { H3Event } from "h3";
import { string, z } from "zod/v4-mini";
import { readAuthenticationMethods, readUsers } from "~/server/database";
import { type TelegramAuthData, telegramAuthDataSchema } from "~/shared/types/telegram";
import { ApiSession } from "~/shared/types/api";
const loginSchema = z.object({
authData: telegramAuthDataSchema,
});
let cachedTelegramConfig:
| undefined
| { enabled: false }
| { enabled: true, botUsername: string, secretKey: CryptoKey }
;
async function useTelegramConfig(event: H3Event) {
if (cachedTelegramConfig)
return cachedTelegramConfig;
const runtimeConfig = useRuntimeConfig(event);
if (!runtimeConfig.public.authTelegramEnabled) {
return cachedTelegramConfig = {
enabled: false,
};
}
if (!runtimeConfig.telegramBotTokenFile) throw new Error("NUXT_TELEGRAM_BOT_TOKEN_FILE not configured");
if (!runtimeConfig.public.telegramBotUsername) throw new Error("NUXT_PUBLIC_TELEGRAM_BOT_USERNAME not configured");
const botToken = await fs.readFile(runtimeConfig.telegramBotTokenFile);
const secretKey = await crypto.subtle.importKey(
"raw",
await crypto.subtle.digest("SHA-256", botToken),
{
name: "HMAC",
hash: "SHA-256",
},
false,
["verify"],
);
return cachedTelegramConfig = {
enabled: true,
botUsername: runtimeConfig.public.telegramBotUsername,
secretKey,
}
}
async function validateTelegramAuthData(authData: TelegramAuthData, key: CryptoKey) {
const { hash, ...checkData } = authData;
const checkString = Object.entries(checkData).map(([key, value]) => `${key}=${value}`).sort().join("\n");
const signature = Buffer.from(hash, "hex");
return await crypto.subtle.verify("HMAC", key, signature, Buffer.from(checkString));
}
export default defineEventHandler(async (event): Promise<ApiSession> => {
const { success, error, data } = loginSchema.safeParse(await readBody(event));
if (!success) {
throw createError({
statusCode: 400,
statusMessage: "Bad Request",
message: z.prettifyError(error),
});
}
const config = await useTelegramConfig(event);
if (!config.enabled) {
throw createError({
statusCode: 403,
statusMessage: "Forbidden",
message: "Telegram authentication is disabled",
});
}
if (!await validateTelegramAuthData(data.authData, config.secretKey)) {
throw createError({
statusCode: 403,
statusMessage: "Forbidden",
message: "Validating authentication data failed",
});
}
const slug = String(data.authData.id);
const authMethods = await readAuthenticationMethods();
const method = authMethods.find(method => method.provider === "telegram" && method.slug === slug);
let session;
if (method) {
const users = await readUsers();
const account = users.find(user => !user.deleted && user.id === method.userId);
session = await setServerSession(event, account);
} else {
const name = data.authData.username ? "@" + data.authData.username : slug;
session = await setServerSession(event, undefined, "telegram", slug, name);
}
return await serverSessionToApi(event, session);
})

View file

@ -10,6 +10,9 @@ export interface ServerSession {
id: Id,
access: ApiUserType,
accountId?: number,
authenticationProvider?: "telegram",
authenticationSlug?: string,
authenticationName?: string,
rotatesAtMs: number,
expiresAtMs?: number,
discardAtMs: number,
@ -28,6 +31,14 @@ export interface ServerUser {
locale?: string,
}
export interface ServerAuthenticationMethod {
id: Id,
provider: "telegram",
slug: string,
name: string,
userId: Id,
}
// For this demo I'm just storing the runtime data in JSON files. When making
// this into proper application this should be replaced with an actual database.
@ -37,6 +48,8 @@ const usersPath = "data/users.json";
const nextUserIdPath = "data/next-user-id.json";
const sessionsPath = "data/sessions.json";
const nextSessionIdPath = "data/next-session-id.json";
const authMethodPath = "data/auth-method.json";
const nextAuthenticationMethodIdPath = "data/auth-method-id.json"
async function remove(path: string) {
try {
@ -137,3 +150,17 @@ export async function readSessions() {
export async function writeSessions(sessions: ServerSession[]) {
await writeFile(sessionsPath, JSON.stringify(sessions, undefined, "\t") + "\n", "utf-8");
}
export async function nextAuthenticationMethodId() {
const nextId = await readJson(nextAuthenticationMethodIdPath, 0);
await writeFile(nextAuthenticationMethodIdPath, String(nextId + 1), "utf-8");
return nextId;
}
export async function readAuthenticationMethods() {
return readJson<ServerAuthenticationMethod[]>(authMethodPath, [])
}
export async function writeAuthenticationMethods(authMethods: ServerAuthenticationMethod[]) {
await writeFile(authMethodPath, JSON.stringify(authMethods, undefined, "\t") + "\n", "utf-8");
}

View file

@ -51,7 +51,13 @@ export async function clearServerSession(event: H3Event) {
deleteCookie(event, "session");
}
export async function setServerSession(event: H3Event, account: ServerUser) {
export async function setServerSession(
event: H3Event,
account: ServerUser | undefined,
authenticationProvider?: "telegram",
authenticationSlug?: string,
authenticationName?: string,
) {
const sessions = await readSessions();
const runtimeConfig = useRuntimeConfig(event);
await clearServerSessionInternal(event, sessions);
@ -60,6 +66,9 @@ export async function setServerSession(event: H3Event, account: ServerUser) {
const newSession: ServerSession = {
access: account?.type ?? "anonymous",
accountId: account?.id,
authenticationProvider,
authenticationSlug,
authenticationName,
rotatesAtMs: now + runtimeConfig.sessionRotatesTimeout * 1000,
discardAtMs: now + runtimeConfig.sessionDiscardTimeout * 1000,
id: await nextSessionId(),
@ -68,6 +77,7 @@ export async function setServerSession(event: H3Event, account: ServerUser) {
sessions.push(newSession);
await writeSessions(sessions);
await setSignedCookie(event, "session", String(newSession.id), runtimeConfig.sessionDiscardTimeout)
return newSession;
}
async function rotateSession(event: H3Event, sessions: ServerSession[], session: ServerSession) {
@ -78,6 +88,7 @@ async function rotateSession(event: H3Event, sessions: ServerSession[], session:
const newSession: ServerSession = {
accountId: account?.id,
access: account?.type ?? "anonymous",
// Authentication provider is removed to avoid possibility of an infinite delay before using it.
rotatesAtMs: now + runtimeConfig.sessionRotatesTimeout * 1000,
discardAtMs: now + runtimeConfig.sessionDiscardTimeout * 1000,
id: await nextSessionId(),
@ -172,6 +183,8 @@ export async function serverSessionToApi(event: H3Event, session: ServerSession)
return {
id: session.id,
account,
authenticationProvider: session.authenticationProvider,
authenticationName: session.authenticationName,
push,
};
}

View file

@ -70,6 +70,8 @@ export type ApiSubscription = z.infer<typeof apiSubscriptionSchema>;
export interface ApiSession {
id: Id,
account?: ApiAccount,
authenticationProvider?: "telegram",
authenticationName?: string,
push: boolean,
}

20
shared/types/telegram.ts Normal file
View file

@ -0,0 +1,20 @@
/*
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { z } from "zod/v4-mini";
export const telegramAuthDataSchema = z.catchall(
z.object({
// These fields are pure speculation as the actual API is undocumented.
auth_date: z.number(),
first_name: z.optional(z.string()),
hash: z.string(),
id: z.number(),
last_name: z.optional(z.string()),
photo_url: z.optional(z.string()),
username: z.optional(z.string()),
}),
z.union([z.string(), z.number()]),
);
export type TelegramAuthData = z.infer<typeof telegramAuthDataSchema>;

View file

@ -26,6 +26,8 @@ const fetchSessionWithCookie = async (event?: H3Event) => {
export const useSessionStore = defineStore("session", () => {
const state = {
account: ref<ApiAccount>(),
authenticationProvider: ref<string>(),
authenticationName: ref<string>(),
id: ref<number>(),
push: ref<boolean>(false),
};
@ -37,6 +39,8 @@ export const useSessionStore = defineStore("session", () => {
},
update(session?: ApiSession) {
state.account.value = session?.account;
state.authenticationProvider.value = session?.authenticationProvider;
state.authenticationName.value = session?.authenticationName;
state.id.value = session?.id;
state.push.value = session?.push ?? false;
},