Skip to content
Open
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
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@ All notable changes to the better-auth-telegram plugin will be documented in thi
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- **Opt-in, server-only bot provisioning.** With `botProvisioning: true`, trusted server code can call `auth.api.provisionTelegramUser({ body: { telegramId, firstName, lastName?, username? } })` to create or resolve a user from a Telegram ID it has already verified. The operation is pathless and `SERVER_ONLY`, starts no session, is idempotent by Telegram ID, returns `{ userId }`, and respects `autoCreateUser`. Disabled by default: setups that don't set `botProvisioning` keep their previous schema, endpoints and behavior. Hosts must authenticate their own callers and verify the Telegram update; see [Bot provisioning](docs/bot-provisioning.md).
- **Exported `validateTelegramBotOwnership`** for `user.validateUserInfo`. It refuses an explicit OIDC link when the verified Telegram ID is owned by a provisioned user. Opt-in and separate from `botProvisioning`.

### Changed

- The Telegram identity columns are enabled when the Login Widget, Mini App **or** bot provisioning is on. `user.validateUserInfo` now also receives `source.method: "telegram-bot-provisioning"`. OIDC-only setups that enable `botProvisioning` should run `npx auth@1.7.17 migrate` before upgrading; no new columns are introduced and no data is rewritten.
- Invalid provisioning input now reports the stable codes `BOT_PROVISIONING_ID_REQUIRED` and `BOT_PROVISIONING_NAME_REQUIRED`; server-only calls report `BOT_PROVISIONING_SERVER_ONLY`. With `autoCreateUser: false`, provisioning uses the existing `USER_CREATION_DISABLED` code, like the Login Widget.

## [3.2.2] - 2026-11-05

Safer account changes when cookie caching is enabled, and clearer examples for putting application user IDs and roles into a Telegram session. Upgrade Better Auth and `@better-auth/core` together to **1.7.17 or newer, below 1.8**. No plugin database migration is needed.
Expand Down
7 changes: 5 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ Supporting modules:
- **`src/verify.ts`** -- HMAC-SHA256 verification via Web Crypto API. Login Widget uses `SHA256(botToken)`; Mini App uses `HMAC-SHA256("WebAppData", botToken)`.
- **`src/oidc.ts` and `src/oidc-token.ts`** -- Better Auth 1.7 provider factory (`accountSubject` = `sub`, PKCE, nonce, Basic client authentication) and cached JWKS/token verification, including profile-ID normalization before claims are used.
- **`src/oidc-linking.ts` and `src/oidc-linking-policy.ts`** -- Match a verified OIDC sign-in to an existing Telegram user before Better Auth's account lookup. Require linked identity proof, preserve existing `sub` ownership, and enforce implicit-linking policy and validation hooks.
- **`src/telegram-account.ts`** -- Find-or-create orchestration for Login Widget and Mini App users. `telegram-account-state.ts` owns shared types, lookups, validation and per-instance operation locks; `telegram-account-user.ts` owns provisioning and profile refresh; `telegram-account-link.ts` owns explicit link/unlink. Writes use Better Auth's internal adapter.
- **`src/telegram-account.ts`** -- Find-or-create orchestration for Login Widget, Mini App and bot provisioning users. `telegram-account-state.ts` owns shared types, lookups, validation and per-instance operation locks; `telegram-account-user.ts` owns provisioning and profile refresh; `telegram-account-link.ts` owns explicit link/unlink. Writes use Better Auth's internal adapter.
- **`src/bot-provisioning-endpoints.ts`** -- Optional pathless `SERVER_ONLY` `provisionTelegramUser` operation for server code with an already verified Telegram ID; no session and no caller authentication. `oidc-linking-policy.ts` exports the opt-in `validateTelegramBotOwnership` validator for OIDC links.
- **`src/telegram-session.ts`** -- Creates sessions and renews cookies for Login Widget and Mini App flows.
- **`src/telegram-identity.ts`** -- Installs database hooks. `telegram-identity-state.ts` holds verified request claims; `telegram-identity-sync.ts` copies and reconciles linked identities; `telegram-identity-session.ts` refreshes OIDC session cookies; `telegram-profile.ts` applies mapped profile updates; `telegram-placeholder.ts` reserves placeholder emails and chooses collision-safe OIDC placeholders.
- **`src/testing/harness.ts`** -- Stable test-fixture imports. Implementations live in `testing/auth.ts` (memory/SQLite Better Auth), `http-client.ts` (cookie-aware requests), `signed-data.ts` (Widget/Mini App fixtures), `oidc-server.ts` (fake Telegram), `oidc-flow.ts` (sign-in helpers) and `constants.ts` (independent fixture constants).
Expand All @@ -33,9 +34,11 @@ Supporting modules:
| POST | `/telegram/miniapp/signin` | None | Sign in from Mini App (optional) |
| POST | `/telegram/miniapp/validate` | None | Validate Mini App initData (optional) |

When `botProvisioning: true`, `auth.api.provisionTelegramUser` is also available. It is pathless and `SERVER_ONLY`, has no HTTP route, creates no session, and trusts the caller's asserted Telegram ID; the host must authenticate the caller and verify the update.

OIDC (when `oidc.enabled`) uses Better Auth's built-in social login routes (`POST /sign-in/social` with `provider: "telegram-oidc"`, `GET /callback/telegram-oidc`). The plugin injects a `telegram-oidc` social provider via the `init` hook.

Schema conditionally extends `user` table with `telegramId`, `telegramUsername`, and `telegramPhoneNumber` fields, and `account` table with `telegramId` and `telegramUsername` fields — only when Login Widget or Mini App flows are enabled (default). OIDC-only setups (`loginWidget: false`) skip these fields.
Schema conditionally extends `user` table with `telegramId`, `telegramUsername`, and `telegramPhoneNumber` fields, and `account` table with `telegramId` and `telegramUsername` fields — only when Login Widget, Mini App or bot provisioning is enabled (Login Widget is on by default). OIDC-only setups (`loginWidget: false`, no Mini App, no `botProvisioning`) skip these fields.

## Code Style

Expand Down
1 change: 1 addition & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ src/
schema.ts Conditional user/account schema fields
widget-endpoints.ts /telegram/signin, /telegram/link, /telegram/unlink
miniapp-endpoints.ts /telegram/miniapp/signin, /telegram/miniapp/validate
bot-provisioning-endpoints.ts optional pathless SERVER_ONLY provisioning operation (botProvisioning)
config-endpoint.ts /telegram/config
telegram-account.ts Find-or-create orchestration
telegram-account-state.ts Shared account types, lookups, validation and locks
Expand Down
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,14 +242,26 @@ await authClient.signInWithTelegramOIDC({ callbackURL: "/dashboard" });

Full guide, including phone numbers and limits: [OIDC](docs/oidc.md).

### Bot provisioning (server only)

This is not a way for a browser to sign in. With `botProvisioning: true`, your trusted server code can turn a Telegram ID that your bot already verified into a local user ID:

```ts
const { userId } = await auth.api.provisionTelegramUser({
body: { telegramId: 8_306_595_751, firstName: "Ada" },
});
```

No session is created, and no HTTP route is added. The name refers to the verified bot update, not to a Telegram API call made by the plugin. The operation is server-only, off by default, and does not authenticate its caller: your bot must verify the update and your host must protect the caller. Existing setups that don't set `botProvisioning` are unchanged. Full guide: [Bot provisioning](docs/bot-provisioning.md).

## What the plugin stores

When the Login Widget or Mini App is on (the Login Widget is on by default), the plugin adds five optional columns:
When the Login Widget or Mini App is on (the Login Widget is on by default), or when bot provisioning is enabled, the plugin adds five optional columns:

- `user.telegramId`, `user.telegramUsername`, `user.telegramPhoneNumber`
- `account.telegramId`, `account.telegramUsername`

An OIDC-only setup (`loginWidget: false`, no Mini App) adds no columns.
An OIDC-only setup (`loginWidget: false`, no Mini App, no `botProvisioning`) adds no columns.

New users get a **placeholder email** unless you give them a real one: `<telegram id>@telegram.placeholder.invalid` (Login Widget and Mini App) or `<sub>@telegram-oidc.placeholder.invalid` (OIDC). These addresses are reserved for Telegram sign-in, and `emailVerified` stays `false`. More in [Installation](docs/installation.md#placeholder-emails).

Expand All @@ -262,6 +274,7 @@ New users get a **placeholder email** unless you give them a real one: `<telegra
| Add the Login Widget, link and unlink accounts | [Usage](docs/usage.md) |
| Sign in with OIDC | [OIDC](docs/oidc.md) |
| Sign in inside a Mini App | [Mini Apps](docs/miniapps.md) |
| Provision users from verified bot updates | [Bot provisioning](docs/bot-provisioning.md) |
| See every option | [Configuration](docs/configuration.md) |
| Understand what is checked, and the known limits | [Security](docs/security.md) |
| Fix an error | [Troubleshooting](docs/troubleshooting.md) |
Expand Down
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Welcome. This page tells you where to find each answer, and explains the words t
| How do I show the Login Widget, link or unlink Telegram, handle errors? | [Usage](./usage.md) |
| How do I sign in with OIDC, get phone numbers, link OIDC to an existing user? | [OIDC](./oidc.md) |
| How do I sign users in inside a Mini App? Why are there no cookies in Telegram Web? | [Mini Apps](./miniapps.md) |
| How do I provision a user from a verified bot update without a browser? | [Bot provisioning](./bot-provisioning.md) |
| How do I put server-owned user IDs or roles in a stateless JWT? | [Server-owned fields](./server-owned-fields.md) |
| What does option X do, and what is its default? | [Configuration](./configuration.md) |
| What does the plugin check, and what can it *not* protect against? | [Security](./security.md) |
Expand Down
30 changes: 24 additions & 6 deletions docs/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Everything the package exports, every endpoint, every error code. This page is f
- [Exports](#exports)
- [Server: `telegram(options)`](#server-telegramoptions)
- [Server: `createTelegramOIDCProvider`](#server-createtelegramoidcprovider)
- [Server: bot provisioning](#server-bot-provisioning)
- [Client: `telegramClient()`](#client-telegramclient)
- [Client actions](#client-actions)
- [Types](#types)
Expand All @@ -24,6 +25,7 @@ Everything the package exports, every endpoint, every error code. This page is f
|---|---|
| `telegram` | function: the Better Auth plugin |
| `createTelegramOIDCProvider` | function: the OIDC provider (used internally) |
| `validateTelegramBotOwnership` | `user.validateUserInfo` validator: refuses OIDC links to a Telegram ID owned by a provisioned user |
| `TELEGRAM_ERROR_CODES` | object: error codes |
| `TelegramPluginOptions`, `TelegramOIDCOptions`, `TelegramPluginConfig` | types: options |
| `TelegramAuthData`, `TelegramMiniAppData`, `TelegramMiniAppUser`, `TelegramMiniAppChat`, `TelegramOIDCClaims`, `TelegramAccountRecord` | types: data |
Expand Down Expand Up @@ -58,16 +60,16 @@ The returned plugin has:
|---|---|
| `id` | `"telegram"` |
| `init` | Adds the `telegram-oidc` social provider (when `oidc.enabled`). Installs database hooks: always the placeholder-email guard; with the Telegram columns, also copying verified OIDC details onto their user and re-checking `user.telegramId` whenever a `telegram` or `telegram-oidc` account is deleted. Logs startup warnings. |
| `schema` | The [Telegram columns](#database-schema), only when the Login Widget or Mini App is enabled. |
| `endpoints` | `/telegram/config` always; the three Login Widget endpoints unless `loginWidget: false`; the two Mini App endpoints when `miniApp.enabled`. |
| `schema` | The [Telegram columns](#database-schema), only when the Login Widget, Mini App or `botProvisioning` is enabled. |
| `endpoints` | `/telegram/config` always; the three Login Widget endpoints unless `loginWidget: false`; the two Mini App endpoints when `miniApp.enabled`; the pathless `provisionTelegramUser` when `botProvisioning: true`. |
| `rateLimit` | [Rules](#rate-limits) for the enabled endpoints. |
| `$ERROR_CODES` | [`TELEGRAM_ERROR_CODES`](#error-codes). |

**Type inference.** The Telegram fields are part of the inferred user type on the server (`auth.$Infer.Session`, `auth.api.getSession`) and the client (`useSession`, `$Infer`), as `string | null | undefined`. In OIDC-only mode they exist in the types but are never set.

**Plugin registry.** The package augments Better Auth's `BetterAuthPluginRegistry`, so `ctx.getPlugin("telegram")` is typed.

**Calling endpoints from the server.** They are on `auth.api` (`signInWithTelegram`, `linkTelegram`, `unlinkTelegram`, `getTelegramConfig`, `signInWithMiniApp`, `validateMiniApp`). Because they depend on options, TypeScript types them as possibly `undefined`, and their request bodies are not typed.
**Calling endpoints from the server.** They are on `auth.api` (`signInWithTelegram`, `linkTelegram`, `unlinkTelegram`, `getTelegramConfig`, `signInWithMiniApp`, `validateMiniApp`, and `provisionTelegramUser` when `botProvisioning: true`). Because they depend on options, TypeScript types them as possibly `undefined`. Their request bodies are not typed, except `provisionTelegramUser`, whose body is inferred through `$Infer`.

## Server: `createTelegramOIDCProvider`

Expand All @@ -83,6 +85,16 @@ The `telegram-oidc` provider the plugin adds when `oidc.enabled` is `true`. You

Provider details: id `telegram-oidc`, issuer `https://oauth.telegram.org`, `requiresIdTokenNonce: true`, `accountSubject` = the `sub` claim (account IDs are the same as in v2), an `idToken.verify` that requires the nonce, HTTP Basic client authentication at the token endpoint, and ID-token verification against Telegram's JWKS (RS256, ES256, EdDSA) before any claim is used.

## Server: bot provisioning

With `botProvisioning: true`, `auth.api.provisionTelegramUser` provisions a user from an asserted Telegram ID and returns `{ userId }`. It has no HTTP path, is marked `SERVER_ONLY`, and refuses calls carrying a `Request` with 403. It starts no session and does not verify Telegram data or authenticate the caller.

**Body:** `{ telegramId: number; firstName: string; lastName?: string; username?: string }`. `telegramId` must be a positive safe integer and `firstName` a nonempty string; a malformed body answers 400. Invalid input creates nothing.

Your `databaseHooks` and `user.validateUserInfo` run normally; the latter sees `source.method: "telegram-bot-provisioning"`. `autoCreateUser: false` makes an unknown Telegram ID answer 404 instead of creating a user. Repeating the call for a known ID returns the same user without changing their profile.

Install `validateTelegramBotOwnership` as `user.validateUserInfo` to refuse OIDC links to a Telegram ID already owned by a provisioned user. It is opt-in and does not compose with your own validator for you. Full guide: [Bot provisioning](./bot-provisioning.md).

## Client: `telegramClient()`

```ts
Expand Down Expand Up @@ -194,6 +206,7 @@ Starts OIDC sign-in. Calls `POST /sign-in/social` with `provider: "telegram-oidc
interface TelegramPluginOptions {
botToken?: string;
botUsername?: string;
botProvisioning?: boolean; // default false
loginWidget?: boolean; // default true
allowUserToLink?: boolean; // default true
autoCreateUser?: boolean; // default true
Expand Down Expand Up @@ -398,6 +411,8 @@ Paths are relative to Better Auth's base path (`/api/auth` by default), so `/tel
| POST | `/telegram/miniapp/signin` | no | `miniApp.enabled` |
| POST | `/telegram/miniapp/validate` | no | `miniApp.enabled` |

`provisionTelegramUser` (when `botProvisioning: true`) is not in this table: it has no HTTP path and can only be called through `auth.api` from server code. See [Server: bot provisioning](#server-bot-provisioning).

### `POST /telegram/signin`

Signs in, or creates, a user with Login Widget data. Sets the session cookie.
Expand Down Expand Up @@ -541,7 +556,10 @@ TELEGRAM_ERROR_CODES.CANNOT_UNLINK_LAST_ACCOUNT.code; // "CANNOT_UNLINK_LAST_ACC
| `OIDC_CLIENT_SECRET_REQUIRED` | 500 | Telegram OIDC: oidc.clientSecret is required before starting an OIDC login. It is the Client Secret shown in @BotFather (your bot > Login Widget), not the bot token | OIDC sign-in |
| `INVALID_AUTH_DATA` | 400 | Invalid Telegram auth data | signin, link |
| `INVALID_AUTHENTICATION` | 401 | Invalid Telegram authentication | signin, link |
| `USER_CREATION_DISABLED` | 404 | User not found and auto-create is disabled | signin |
| `BOT_PROVISIONING_ID_REQUIRED` | 400 | Bot provisioning: telegramId must be a positive Telegram user ID | `provisionTelegramUser` |
| `BOT_PROVISIONING_NAME_REQUIRED` | 400 | Bot provisioning: a Telegram first name is required; last name is optional | `provisionTelegramUser` |
| `BOT_PROVISIONING_SERVER_ONLY` | 403 | Bot provisioning: this operation is server-only and cannot be called over HTTP | `provisionTelegramUser` |
| `USER_CREATION_DISABLED` | 404 | User not found and auto-create is disabled | signin, `provisionTelegramUser` |
| `NOT_AUTHENTICATED` | none | Not authenticated | Defined, never returned (a missing session is Better Auth's 401 `UNAUTHORIZED`) |
| `LINKING_DISABLED` | 403 | Linking Telegram accounts is disabled | link |
| `TELEGRAM_ALREADY_LINKED_OTHER` | 409 | This Telegram account is already linked to another user | link |
Expand Down Expand Up @@ -589,13 +607,13 @@ Registered only for enabled endpoints. Enforced by Better Auth's rate limiter, w

## Database schema

Added only when the Login Widget or Mini App is enabled. All fields are optional (nullable) strings, and all must exist in the database.
Added only when the Login Widget, Mini App or bot provisioning is enabled. All fields are optional (nullable) strings, and all must exist in the database.

**`user`**

| Field | Index | `input` | Filled from |
|---|---|---|---|
| `telegramId` | yes | `false` | Login Widget / Mini App user ID; the OIDC `id` claim |
| `telegramId` | yes | `false` | Login Widget / Mini App / bot provisioning user ID; the OIDC `id` claim |
| `telegramUsername` | no | `false` | Telegram username; OIDC `preferred_username`. Refreshed on every sign-in. |
| `telegramPhoneNumber` | no | `false` | OIDC `phone_number` (with `oidc.requestPhone`) |

Expand Down
Loading