diff --git a/CHANGELOG.md b/CHANGELOG.md index 616902b..e628d7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/CLAUDE.md b/CLAUDE.md index 0ccc442..8b052d3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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). @@ -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 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1745816..715257b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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 diff --git a/README.md b/README.md index ee5c714..467387a 100644 --- a/README.md +++ b/README.md @@ -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.placeholder.invalid` (Login Widget and Mini App) or `@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). @@ -262,6 +274,7 @@ New users get a **placeholder email** unless you give them a real one: ` 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 | @@ -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`) | diff --git a/docs/bot-provisioning.md b/docs/bot-provisioning.md new file mode 100644 index 0000000..ac9c98b --- /dev/null +++ b/docs/bot-provisioning.md @@ -0,0 +1,84 @@ +# Bot provisioning (server only) + +This is **not** a browser sign-in method. It lets trusted server code create or resolve a Better Auth user from a Telegram ID that your bot already proved, then use OIDC to sign that user in. Use it when your bot receives a Telegram update (for example through a webhook or long polling) and needs a local user ID before the user ever opens your website. + +The name refers to the source of the verified update — your Telegram bot — not a call made by this plugin. The plugin never talks to Telegram in this flow; it trusts the ID your code has already proved. + +The feature is **off by default**. With no `botProvisioning` option, nothing described here is registered, and existing setups behave exactly as before. + +## Enable it + +```ts +import { telegram } from "better-auth-telegram"; + +export const telegramPlugin = telegram({ + botProvisioning: true, + loginWidget: false, // optional; keep the widget if you use it on another bot + oidc: { enabled: true, clientSecret: process.env.TELEGRAM_OIDC_CLIENT_SECRET }, +}); +``` + +`botProvisioning: true` adds one server-only operation, `auth.api.provisionTelegramUser`, and makes the plugin add the same five optional Telegram columns that the Login Widget and Mini App use. Call the operation from your own trusted server code: + +```ts +const { userId } = await auth.api.provisionTelegramUser({ + body: { + telegramId: 8_306_595_751, // number, from the verified Telegram update + firstName: "Ada", + lastName: "Lovelace", // optional + username: "ada", // optional, 1-32 letters/digits/underscores + }, +}); +``` + +It returns `{ userId }` and **does not create a session**. The call is idempotent by Telegram ID: repeating it for the same user returns the same ID, without overwriting their name. It respects `autoCreateUser`: with `false`, an unknown Telegram user is refused instead of created. Your `databaseHooks` and `user.validateUserInfo` still run; the latter sees `source.method: "telegram-bot-provisioning"`. + +The endpoint is pathless and marked `SERVER_ONLY`, so Better Auth does not create an HTTP route for it. A call that carries a `Request` is refused with 403. + +## You own the trust boundary + +**The plugin does not verify the Telegram update or authenticate the caller.** It receives an asserted Telegram ID and name and provisions that identity. Before calling it, your bot must verify the update came from Telegram, and your host must authenticate the service that calls `provisionTelegramUser` (for example, a shared secret held in your secret manager). Do not put this call behind an unauthenticated route. `SERVER_ONLY` stops Better Auth from exposing the endpoint; it is not caller authentication. + +## Protect OIDC linking + +If you also use OIDC, a signed-in user could otherwise attach the `telegram-oidc` identity of a user already provisioned from a bot update. Install the exported validator to refuse that: + +```ts +import { telegram, validateTelegramBotOwnership } from "better-auth-telegram"; + +const auth = betterAuth({ + user: { validateUserInfo: validateTelegramBotOwnership }, + plugins: [telegramPlugin], +}); +``` + +It applies only to OIDC `link-account` requests whose verified Telegram ID belongs to another user. It does not change ordinary sign-in, and it is **not** installed automatically when `botProvisioning: true`. If your app already has a `user.validateUserInfo` function, compose both checks in one function yourself; Better Auth accepts a single validator. + +## Database and upgrading + +Enabling `botProvisioning` activates the existing optional columns `user.telegramId`, `user.telegramUsername`, `user.telegramPhoneNumber`, `account.telegramId` and `account.telegramUsername`. If your app was OIDC-only (`loginWidget: false`, no Mini App), it had no columns: run `npx auth@1.7.17 migrate` before starting the new build. No new columns are added, so no data is rewritten. Disabling the feature later does not remove them. + +## The whole flow + +```ts +// 1. Your bot verifies the update came from Telegram (your code, not the plugin). +// 2. Your HTTP endpoint authenticates the calling bot service (your code). +// 3. Only then does the plugin provision the user: +const { userId } = await auth.api.provisionTelegramUser({ + body: { + telegramId: sender.id, + firstName: sender.first_name, + lastName: sender.last_name, + username: sender.username, + }, +}); +// 4. Later, the user signs in with OIDC as usual and gets the same userId. +``` + +Steps 1 and 2 are the host's responsibility. Skipping them lets anyone claim any Telegram ID. + +## Limits + +- Provisioning locks are per Better Auth instance, not distributed. The Telegram columns are not a database-wide uniqueness constraint. If several servers can provision the same new ID simultaneously, test that boundary in your deployment. +- No session, cookie or bot token is returned or needed by the caller. Keep the bot token on the server as usual. +- Rate limits apply to Better Auth's HTTP routes; this pathless operation has none. Limit calls at your own boundary. diff --git a/docs/configuration.md b/docs/configuration.md index 4bad97c..9a939d9 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -8,6 +8,7 @@ Every option of the plugin, with its default, plus the Better Auth options that - [Plugin options](#plugin-options) - [Mini App options](#mini-app-options) - [OIDC options](#oidc-options) +- [Bot provisioning](#bot-provisioning) - [Custom user data](#custom-user-data) - [Better Auth options that affect Telegram sign-in](#better-auth-options-that-affect-telegram-sign-in) - [Startup warnings](#startup-warnings) @@ -81,7 +82,8 @@ For OIDC, the matching switch is `oidc.disableSignUp: true`. To block automatic |---|---|---|---| | `botToken` | `string` | none | The bot token from BotFather. Needed for the Login Widget and the Mini App, which use it to check Telegram's signature. Without it, those endpoints answer 500 `BOT_TOKEN_REQUIRED`. Also provides the default OIDC client ID. Spaces and newlines around it are removed (with a warning). | | `botUsername` | `string` | none | The bot's username, without `@` (a leading `@` is removed, with a warning). Needed to show the Login Widget. | -| `loginWidget` | `boolean` | `true` | Turns on the Login Widget endpoints (`/telegram/signin`, `/telegram/link`, `/telegram/unlink`). Set `false` if you don't use the widget. With `false` and no Mini App, the plugin adds no database columns. | +| `botProvisioning` | `boolean` | `false` | Registers the server-only `auth.api.provisionTelegramUser` operation and the Telegram columns. Off by default, so existing setups are unchanged. See [Bot provisioning](./bot-provisioning.md). | +| `loginWidget` | `boolean` | `true` | Turns on the Login Widget endpoints (`/telegram/signin`, `/telegram/link`, `/telegram/unlink`). Set `false` if you don't use the widget. With `false`, no Mini App and no `botProvisioning`, the plugin adds no database columns. | | `autoCreateUser` | `boolean` | `true` | Create a new user when someone signs in with the Login Widget or Mini App for the first time. With `false`, unknown Telegram users get 404. Doesn't affect OIDC (use `oidc.disableSignUp`). | | `allowUserToLink` | `boolean` | `true` | Let signed-in users link a Telegram account with `/telegram/link`. With `false`, linking answers 403 `LINKING_DISABLED`. | | `maxAuthAge` | `number` (seconds) | `86400` (24 hours) | How old Login Widget data and Mini App `initData` may be. Older data is refused (401). Shorter is safer, see [Security](./security.md#replay-within-maxauthage). | @@ -108,13 +110,17 @@ For OIDC, the matching switch is `oidc.disableSignUp: true`. To block automatic | `oidc.clientSecret` | `string` | none, **required** | The Client Secret from BotFather (bot > Login Widget). **Not the bot token.** Without it, OIDC sign-in answers 500 `OIDC_CLIENT_SECRET_REQUIRED`. | | `oidc.scopes` | `string[]` | `[]` | Extra scopes, added to the defaults `openid` and `profile`. | | `oidc.disableDefaultScope` | `boolean` | `false` | Don't request `profile` (`openid` is always sent). The ID token then has no Telegram ID, name or username, so `telegramId` is not stored. | -| `oidc.requestPhone` | `boolean` | `false` | Adds the `phone` scope. The number is stored in `user.telegramPhoneNumber` when that column exists (Login Widget or Mini App enabled). See [OIDC: phone numbers](./oidc.md#phone-numbers). | +| `oidc.requestPhone` | `boolean` | `false` | Adds the `phone` scope. The number is stored in `user.telegramPhoneNumber` when that column exists (Login Widget, Mini App or `botProvisioning` enabled). See [OIDC: phone numbers](./oidc.md#phone-numbers). | | `oidc.requestBotAccess` | `boolean` | `false` | Adds the `telegram:bot_access` scope: asks the user to let your bot message them. | | `oidc.disableSignUp` | `boolean` | `false` | Only existing users can sign in with OIDC; others are redirected with `error=signup_disabled`. | | `oidc.disableIdTokenSignIn` | `boolean` | `false` | Refuse ID tokens sent directly to `/sign-in/social` and `/link-social`, leaving only the redirect flow. See [OIDC: ID tokens](./oidc.md#sign-in-with-an-id-token-you-already-have). | | `oidc.mapOIDCProfileToUser` | function | none | Changes the data a new OIDC user is created with. See [Custom user data](#custom-user-data). | | `oidc.updateUserInfoOnSignIn` | `boolean` | `false` | Also write `name`, `image` and the mapper's fields onto returning users at every OIDC sign-in. Never changes the email or its verification. | +## Bot provisioning + +`botProvisioning: true` adds the pathless, server-only `auth.api.provisionTelegramUser` operation. It creates or resolves a user from a Telegram ID asserted by your own trusted code and returns `{ userId }` without starting a session. It does **not** verify the Telegram update or authenticate the caller; that is your host's job. The optional ownership validator `validateTelegramBotOwnership` must be installed separately under `user.validateUserInfo` if you use OIDC explicit linking. Details, an example and the upgrade steps are in [Bot provisioning](./bot-provisioning.md). + ## Custom user data When a Telegram user signs up, the plugin creates the user with these values: @@ -182,7 +188,7 @@ The plugin follows Better Auth's own settings, so these options apply to Telegra | `account.accountLinking.trustedProviders`, `allowDifferentEmails` | Needed to link OIDC with `linkSocial`. See [OIDC: linking](./oidc.md#link-telegram-oidc-to-a-signed-in-user). | | `session.freshAge` (default 1 day) | `/telegram/unlink` needs a session younger than this (403 `SESSION_NOT_FRESH`). | | `databaseHooks` | Run for users, accounts and sessions created by Telegram sign-in. A hook that refuses a new user gives 403 `USER_CREATION_REJECTED`; one that refuses the session gives 401 `FAILED_TO_CREATE_SESSION`. | -| `user.validateUserInfo` | Called for every Login Widget and Mini App sign-up, sign-in and link, with `source.method` `"telegram-login-widget"` or `"telegram-mini-app"`. Details in [Security](./security.md#your-hooks-run-for-telegram-users). | +| `user.validateUserInfo` | Called for every Login Widget, Mini App and bot provisioning step, with `source.method` `"telegram-login-widget"`, `"telegram-mini-app"` or `"telegram-bot-provisioning"`. To refuse OIDC links to a provisioned Telegram ID, install the exported `validateTelegramBotOwnership`. Details in [Security](./security.md#your-hooks-run-for-telegram-users). | | `rateLimit` | Turns the plugin's rate limits on or off. Better Auth enables rate limiting in production only, by default. | | `advanced.defaultCookieAttributes` | Needed for Mini Apps in Telegram Web. See [Mini Apps: cookies](./miniapps.md#inside-telegram-web-cookies-in-an-iframe). | diff --git a/docs/security.md b/docs/security.md index 1085fc5..9b0b8a7 100644 --- a/docs/security.md +++ b/docs/security.md @@ -54,6 +54,12 @@ If any check fails, Better Auth redirects with `error=unable_to_get_user_info` a What this prevents: forged tokens (only Telegram has the private key), tokens issued to another app (audience check), stolen authorization codes (useless without the PKCE verifier), and cross-site requests to the callback (the `state` check). +### Bot provisioning + +With `botProvisioning: true`, `auth.api.provisionTelegramUser` provisions a user from a Telegram ID asserted by your own server code. It has no HTTP path and refuses calls carrying a `Request` (403), so it cannot be reached from a browser. **The plugin does not verify the update or authenticate your caller.** If your bot wrapper accepts unauthenticated requests, anyone can provision users for arbitrary Telegram IDs. Verify the update with Telegram and protect the calling service with your own secret before using this feature. See [Bot provisioning](./bot-provisioning.md). + +Explicit OIDC linking can attach an identity owned by a provisioned user to a different signed-in user unless you install the exported `validateTelegramBotOwnership` under `user.validateUserInfo`. It is opt-in and is not installed by `botProvisioning: true`. + ## Account safety rules **The Login Widget link route accepts one Telegram identity per user.** `/telegram/link` refuses an identity belonging to someone else (409 `TELEGRAM_ALREADY_LINKED_OTHER`), including a Telegram ID already on another user's profile. A second, different identity gives 409 `DIFFERENT_TELEGRAM_ACCOUNT_LINKED`. Better Auth's separate OIDC linking route can attach another OIDC identity; it does not overwrite the user's existing `telegramId`. These checks do not create a database-wide uniqueness constraint. @@ -84,7 +90,7 @@ The plugin creates users, accounts and sessions through Better Auth's internal a - `"sign-in"` for a returning user, - `"link-account"` when a sign-in links to an existing user by `telegramId`, and on `/telegram/link`. - Return `{ error: "your_code" }` to refuse: the client gets 403 with `your_code`. If the function throws, the request fails with 403 `validation_failed` (fail closed). OIDC sign-ins go through Better Auth's own OAuth handling, with `source.method: "oauth"`. + Return `{ error: "your_code" }` to refuse: the client gets 403 with `your_code`. If the function throws, the request fails with 403 `validation_failed` (fail closed). OIDC sign-ins go through Better Auth's own OAuth handling, with `source.method: "oauth"`. Bot provisioning also calls it, with `source.method: "telegram-bot-provisioning"`. ### Two-factor authentication @@ -128,6 +134,7 @@ When Telegram starts signing ID tokens with a new key, OIDC sign-ins can fail fo ### Other known gaps +- Bot provisioning trusts the caller's asserted Telegram ID and has no caller authentication or rate limit of its own ([above](#bot-provisioning)). Its per-instance locks are not distributed. - Two-factor authentication is skipped for Telegram sign-ins ([above](#two-factor-authentication)). - Third-party Ed25519 validation of Mini App `initData` is not implemented ([above](#mini-app)). - Users already split across separate OIDC and Widget/Mini App accounts are not automatically merged. [Matching across methods](./oidc.md#use-one-user-across-sign-in-methods) keeps an existing OIDC account attached to its current owner. @@ -139,6 +146,7 @@ When Telegram starts signing ID tokens with a new key, OIDC sign-ins can fail fo - Use separate bots for development and production, so a leaked development token can't touch production users. - Generate `BETTER_AUTH_SECRET` with `openssl rand -base64 32`. - Don't log request bodies of the Telegram endpoints in production; they contain sign-in data that can be replayed (see above). +- If you use bot provisioning, keep the secret that authenticates calls to `provisionTelegramUser` in your secret manager, and never expose the operation through an unauthenticated route. ## Production checklist @@ -153,6 +161,7 @@ When Telegram starts signing ID tokens with a new key, OIDC sign-ins can fail fo - [ ] `maxAuthAge` is as short as your users can accept. - [ ] The OIDC bot signs with RS256 or ES256. - [ ] `oidc.disableIdTokenSignIn: true` if you don't use ID-token sign-in. +- [ ] If `botProvisioning: true`: the bot verifies each update, the provisioning caller is authenticated, and `validateTelegramBotOwnership` is installed when OIDC linking is used. - [ ] Rate limiting uses shared storage if you run more than one server. - [ ] Development and production use different bots. diff --git a/src/bot-provisioning-endpoints.ts b/src/bot-provisioning-endpoints.ts new file mode 100644 index 0000000..c359fb0 --- /dev/null +++ b/src/bot-provisioning-endpoints.ts @@ -0,0 +1,84 @@ +import { APIError, createAuthEndpoint } from "better-auth/api"; +import { ERROR_CODES } from "./constants"; +import type { TelegramPluginConfig } from "./plugin-config"; +import { findOrCreateTelegramUser } from "./telegram-account"; + +/** + * Creates the optional pathless server-only provisioning operation. The host + * verifies the Telegram update and authenticates the caller; this operation + * only creates or resolves the local user for an already proven Telegram ID. + */ +export function createBotProvisioningEndpoints(config: TelegramPluginConfig) { + return { + provisionTelegramUser: createAuthEndpoint( + { + method: "POST", + metadata: { + SERVER_ONLY: true, + $Infer: { + body: {} as { + telegramId: number; + username?: string; + firstName: string; + lastName?: string; + }, + }, + }, + }, + async (ctx) => { + // This pathless endpoint is called only after the host has + // authenticated the bot service and verified the update's sender. + if (ctx.request) { + throw APIError.from( + "FORBIDDEN", + ERROR_CODES.BOT_PROVISIONING_SERVER_ONLY + ); + } + const body: unknown = ctx.body; + if ( + typeof body !== "object" || + body === null || + !("telegramId" in body) || + typeof body.telegramId !== "number" || + !Number.isSafeInteger(body.telegramId) || + body.telegramId <= 0 + ) { + throw APIError.from( + "BAD_REQUEST", + ERROR_CODES.BOT_PROVISIONING_ID_REQUIRED + ); + } + const lastName = "lastName" in body ? body.lastName : undefined; + if ( + !("firstName" in body) || + typeof body.firstName !== "string" || + !body.firstName.trim() || + (lastName !== undefined && typeof lastName !== "string") + ) { + throw APIError.from( + "BAD_REQUEST", + ERROR_CODES.BOT_PROVISIONING_NAME_REQUIRED + ); + } + + const username = + "username" in body && + typeof body.username === "string" && + /^[A-Za-z0-9_]{1,32}$/u.test(body.username) + ? body.username + : undefined; + const user = await findOrCreateTelegramUser(ctx, { + identity: { telegramId: String(body.telegramId), username }, + userData: { + name: lastName ? `${body.firstName} ${lastName}` : body.firstName, + }, + method: "telegram-bot-provisioning", + allowCreate: config.autoCreateUser, + notFound: ERROR_CODES.USER_CREATION_DISABLED, + }); + + return ctx.json({ userId: user.id }); + } + ), + }; +} diff --git a/src/bot-provisioning.integration.test.ts b/src/bot-provisioning.integration.test.ts new file mode 100644 index 0000000..565ec4c --- /dev/null +++ b/src/bot-provisioning.integration.test.ts @@ -0,0 +1,223 @@ +// @vitest-environment node +import { betterAuth } from "better-auth"; +import { memoryAdapter } from "better-auth/adapters/memory"; +import { expect, onTestFinished, it as test } from "vitest"; +import { telegram, validateTelegramBotOwnership } from "./index"; +import { BASE_URL, BOT_TOKEN } from "./testing/constants"; +import { + createClient, + createMemoryAuth, + type MemoryDB, + mockTelegramOIDC, + signInWithTelegramOIDC, + telegramClaims, +} from "./testing/harness"; + +const telegramId = 8_306_595_751; +const subject = "12224742808376279442"; + +function createBotAuth(clientSecret: string) { + const db: MemoryDB = { user: [], account: [], session: [], verification: [] }; + const auth = betterAuth({ + baseURL: BASE_URL, + secret: "better-auth-telegram-test-secret-0123456789abcdef", + database: memoryAdapter(db), + emailAndPassword: { enabled: true }, + user: { validateUserInfo: validateTelegramBotOwnership }, + account: { + accountLinking: { + trustedProviders: ["telegram-oidc"], + allowDifferentEmails: true, + }, + }, + plugins: [ + telegram({ + botProvisioning: true, + botToken: BOT_TOKEN, + loginWidget: false, + oidc: { enabled: true, clientSecret }, + }), + ], + }); + const provision = auth.api.provisionTelegramUser; + if (!provision) { + throw new Error("Bot provisioning is unavailable"); + } + return { provision, client: createClient(auth), db }; +} + +function createBotOnlyAuth(autoCreateUser = true) { + const db: MemoryDB = { user: [], account: [], session: [], verification: [] }; + const auth = betterAuth({ + baseURL: BASE_URL, + secret: "better-auth-telegram-test-secret-0123456789abcdef", + database: memoryAdapter(db), + plugins: [ + telegram({ + botProvisioning: true, + autoCreateUser, + botToken: BOT_TOKEN, + loginWidget: false, + }), + ], + }); + const provision = auth.api.provisionTelegramUser; + if (!provision) { + throw new Error("Bot provisioning is unavailable"); + } + return { provision, auth, db }; +} + +test("provisions once without a session and signs in through OIDC as the same user", async () => { + const provider = await mockTelegramOIDC(); + onTestFinished(() => provider.restore()); + const { provision, client, db } = createBotAuth(provider.clientSecret); + + const first = await provision({ + body: { telegramId, firstName: "Ann", lastName: "Example" }, + }); + expect( + await provision({ body: { telegramId, firstName: "Updated" } }) + ).toEqual(first); + expect(db.user).toHaveLength(1); + expect(db.user[0]?.name).toBe("Ann Example"); + expect(db.session).toHaveLength(0); + expect(db.account).toMatchObject([ + { + providerId: "telegram", + accountId: String(telegramId), + userId: first.userId, + }, + ]); + + const { location } = await signInWithTelegramOIDC(client, provider); + expect(location).toBe("/dashboard"); + expect((await client.get("/get-session")).json.user.id).toBe(first.userId); + expect(db.user[0]?.name).toBe("Ann Example"); + expect(db.user).toHaveLength(1); + expect(db.account).toHaveLength(2); + expect(db.account).toContainEqual( + expect.objectContaining({ + providerId: "telegram-oidc", + accountId: subject, + userId: first.userId, + }) + ); +}); + +test("does not let a signed-in user link a Telegram identity owned by a bot user", async () => { + const provider = await mockTelegramOIDC(); + onTestFinished(() => provider.restore()); + const { provision, client, db } = createBotAuth(provider.clientSecret); + const owner = await provision({ body: { telegramId, firstName: "Ann" } }); + expect(db.user[0]?.name).toBe("Ann"); + const signup = await client.post("/sign-up/email", { + email: "other@example.com", + password: "correct-horse-battery", + name: "Other", + }); + expect(signup.status).toBe(200); + expect(signup.json.user.id).not.toBe(owner.userId); + + const link = await client.post("/link-social", { + provider: "telegram-oidc", + callbackURL: "/settings", + }); + expect(link.status).toBe(200); + const callback = await client.get( + provider.authorize(link.json.url, telegramClaims()) + ); + expect(callback.headers.get("location")).toContain( + "TELEGRAM_ALREADY_LINKED_OTHER" + ); + expect( + db.account.some((account) => account.providerId === "telegram-oidc") + ).toBe(false); + + const retry = await client.post("/link-social", { + provider: "telegram-oidc", + callbackURL: "/settings", + }); + expect(retry.status).toBe(200); + const unusedTelegramId = 8_306_595_752; + const allowed = await client.get( + provider.authorize( + retry.json.url, + telegramClaims({ + sub: "12224742808376279443", + id: String(unusedTelegramId), + }) + ) + ); + expect(allowed.headers.get("location")).toBe("/settings"); + expect( + await provision({ + body: { telegramId: unusedTelegramId, firstName: "Telegram name" }, + }) + ).toEqual({ userId: signup.json.user.id }); + expect(db.user).toHaveLength(2); + expect((await client.get("/get-session")).json.user.email).toBe( + "other@example.com" + ); + expect((await client.get("/get-session")).json.user.name).toBe("Other"); +}); + +test("leaves the provisioning endpoint unregistered when botProvisioning is off", () => { + const { auth } = createMemoryAuth(); + expect( + (auth.api as Record).provisionTelegramUser + ).toBeUndefined(); +}); + +test("rejects malformed provisioning data without writing anything", async () => { + const { provision, db } = createBotOnlyAuth(); + + await Promise.all( + [0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1, "7"].map((badId) => + expect( + provision({ body: { telegramId: badId, firstName: "Ann" } as never }) + ).rejects.toMatchObject({ + body: { code: "BOT_PROVISIONING_ID_REQUIRED" }, + }) + ) + ); + await Promise.all( + [ + { telegramId }, + { telegramId, firstName: " " }, + { telegramId, firstName: 42 }, + { telegramId, firstName: "Ann", lastName: 42 }, + ].map((body) => + expect(provision({ body: body as never })).rejects.toMatchObject({ + body: { code: "BOT_PROVISIONING_NAME_REQUIRED" }, + }) + ) + ); + expect(db.user).toHaveLength(0); + expect(db.account).toHaveLength(0); +}); + +test("refuses a provisioning call that carries a request", async () => { + const { provision, db } = createBotOnlyAuth(); + + const response = await provision({ + body: { telegramId, firstName: "Ann" }, + request: new Request("https://example.com/provision"), + } as never); + expect(response).toHaveProperty("status", 403); + expect(await (response as unknown as Response).json()).toMatchObject({ + code: "BOT_PROVISIONING_SERVER_ONLY", + }); + expect(db.user).toHaveLength(0); + expect(db.account).toHaveLength(0); +}); + +test("does not create a user when autoCreateUser is false", async () => { + const { provision, db } = createBotOnlyAuth(false); + + await expect( + provision({ body: { telegramId, firstName: "Ann" } }) + ).rejects.toMatchObject({ body: { code: "USER_CREATION_DISABLED" } }); + expect(db.user).toHaveLength(0); + expect(db.account).toHaveLength(0); +}); diff --git a/src/error-codes.ts b/src/error-codes.ts index 8c6e043..b4d4fec 100644 --- a/src/error-codes.ts +++ b/src/error-codes.ts @@ -14,6 +14,12 @@ export const TELEGRAM_ERROR_CODES = defineErrorCodes({ "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", INVALID_AUTH_DATA: "Invalid Telegram auth data", INVALID_AUTHENTICATION: "Invalid Telegram authentication", + BOT_PROVISIONING_ID_REQUIRED: + "Bot provisioning: telegramId must be a positive Telegram user ID", + BOT_PROVISIONING_NAME_REQUIRED: + "Bot provisioning: a Telegram first name is required; last name is optional", + BOT_PROVISIONING_SERVER_ONLY: + "Bot provisioning: this operation is server-only and cannot be called over HTTP", USER_CREATION_DISABLED: "User not found and auto-create is disabled", NOT_AUTHENTICATED: "Not authenticated", LINKING_DISABLED: "Linking Telegram accounts is disabled", diff --git a/src/index.ts b/src/index.ts index d2713bd..7189458 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,5 @@ import type { BetterAuthPlugin } from "better-auth"; +import { createBotProvisioningEndpoints } from "./bot-provisioning-endpoints"; import { createConfigEndpoint } from "./config-endpoint"; import { ERROR_CODES, PLUGIN_ID } from "./constants"; import { @@ -19,6 +20,7 @@ import { createWidgetEndpoints, getWidgetRateLimits } from "./widget-endpoints"; // biome-ignore lint/performance/noBarrelFile: Public API re-export export { TELEGRAM_ERROR_CODES } from "./error-codes"; export { createTelegramOIDCProvider } from "./oidc"; +export { validateTelegramBotOwnership } from "./oidc-linking-policy"; export type { TelegramPluginConfig } from "./plugin-config"; export type { TelegramAccountRecord, @@ -71,10 +73,7 @@ export const telegram = (options: TelegramPluginOptions) => { ? { context: { socialProviders: [ - withTelegramIdentityLinking( - provider, - config.widgetEnabled || config.miniAppEnabled - ), + withTelegramIdentityLinking(provider, config.identityFields), ...ctx.socialProviders, ], }, @@ -82,7 +81,7 @@ export const telegram = (options: TelegramPluginOptions) => { : {}), options: { databaseHooks: telegramIdentityHooks(ctx, { - identityFields: config.widgetEnabled || config.miniAppEnabled, + identityFields: config.identityFields, updateUserInfo: config.oidcEnabled && !!config.oidc?.updateUserInfoOnSignIn, }), @@ -95,6 +94,9 @@ export const telegram = (options: TelegramPluginOptions) => { schema: createTelegramSchema(config) as TelegramSchema, endpoints: { + ...(config.botProvisioningEnabled + ? createBotProvisioningEndpoints(config) + : {}), ...(config.widgetEnabled ? createWidgetEndpoints(config) : {}), ...(config.miniAppEnabled ? createMiniAppEndpoints(config) : {}), ...createConfigEndpoint(config), diff --git a/src/oidc-linking-policy.ts b/src/oidc-linking-policy.ts index 2b3a6fa..19f3e0a 100644 --- a/src/oidc-linking-policy.ts +++ b/src/oidc-linking-policy.ts @@ -1,10 +1,42 @@ -import type { GenericEndpointContext } from "@better-auth/core"; +import type { + BetterAuthOptions, + GenericEndpointContext, +} from "@better-auth/core"; import { getCurrentAdapter } from "@better-auth/core/context"; import type { Account, User } from "better-auth"; import { APIError } from "better-auth/api"; import { ERROR_CODES, PLUGIN_ID, TELEGRAM_OIDC_PROVIDER_ID } from "./constants"; +import { currentClaims } from "./telegram-identity-state"; import type { TelegramOIDCClaims } from "./types"; +/** + * Opt-in `user.validateUserInfo` gate: refuses an OIDC link when the verified + * Telegram ID is owned by a different user. It reads the ID from this plugin's + * request state, not from Better Auth's `source.oauth.profile`. Better Auth + * accepts one validator, so compose it with your own if both are needed. + */ +export const validateTelegramBotOwnership: NonNullable< + NonNullable["validateUserInfo"] +> = async ({ source, user }, ctx) => { + if ( + source.action !== "link-account" || + source.oauth?.providerId !== TELEGRAM_OIDC_PROVIDER_ID + ) { + return; + } + const telegramId = (await currentClaims())?.id; + if (!(telegramId && user.id)) { + return { error: "TELEGRAM_ID_REQUIRED" }; + } + const owner = await findProvenTelegramUser(ctx, telegramId); + if (owner && owner.id !== user.id) { + return { + error: "TELEGRAM_ALREADY_LINKED_OTHER", + errorDescription: ERROR_CODES.TELEGRAM_ALREADY_LINKED_OTHER.message, + }; + } +}; + /** Only a surviving linked account can authorize another Telegram login. */ export async function findProvenTelegramUser( ctx: GenericEndpointContext, diff --git a/src/plugin-config.ts b/src/plugin-config.ts index 1d9c8fb..3b3af74 100644 --- a/src/plugin-config.ts +++ b/src/plugin-config.ts @@ -8,8 +8,10 @@ import type { TelegramOIDCOptions, TelegramPluginOptions } from "./types"; export interface TelegramPluginConfig { allowUserToLink: boolean; autoCreateUser: boolean; + botProvisioningEnabled: boolean; botToken: string; botUsername: string; + identityFields: boolean; mapMiniAppDataToUser?: NonNullable< TelegramPluginOptions["miniApp"] >["mapMiniAppDataToUser"]; @@ -54,7 +56,9 @@ export function createPluginConfig( const widgetEnabled = loginWidget !== false; const miniAppEnabled = miniApp?.enabled ?? false; const oidcEnabled = oidc?.enabled ?? false; - const identityColumns = widgetEnabled || miniAppEnabled; + const botProvisioningEnabled = options.botProvisioning === true; + const identityFields = + widgetEnabled || miniAppEnabled || botProvisioningEnabled; const warnings: string[] = []; const warn = (message: string) => warnings.push(`[better-auth-telegram] ${message}`); @@ -121,9 +125,9 @@ export function createPluginConfig( ); } - if (oidcEnabled && oidc?.requestPhone && !identityColumns) { + if (oidcEnabled && oidc?.requestPhone && !identityFields) { warn( - "OIDC: requestPhone is set, but with the Login Widget and Mini App off there is no telegramPhoneNumber column, so the phone number is not stored. Enable the Mini App (or the Login Widget) to get the Telegram columns, or read phone_number from mapOIDCProfileToUser into your own field." + "OIDC: requestPhone is set, but no flow enabling the Telegram identity fields is configured, so the phone number is not stored. Enable bot provisioning, Mini App or Login Widget, or read phone_number from mapOIDCProfileToUser into your own field." ); } @@ -144,6 +148,8 @@ export function createPluginConfig( } return { + botProvisioningEnabled, + identityFields, botToken: resolvedBotToken, botUsername: resolvedBotUsername, widgetEnabled, diff --git a/src/schema.ts b/src/schema.ts index a917be7..a80f9fe 100644 --- a/src/schema.ts +++ b/src/schema.ts @@ -57,14 +57,15 @@ export type TelegramSchema = ReturnType; * * Adds `telegramId`, `telegramUsername`, `telegramPhoneNumber` to the `user` table * and `telegramId`, `telegramUsername` to the `account` table — but only when - * Login Widget or Mini App flows are enabled. OIDC-only setups skip these fields. + * Login Widget, Mini App or bot provisioning is enabled. OIDC-only setups + * skip these fields. * The type always carries them: they are optional, and simply never set in * OIDC-only mode. */ export function createTelegramSchema( config: TelegramPluginConfig ): TelegramSchema | undefined { - if (!(config.widgetEnabled || config.miniAppEnabled)) { + if (!config.identityFields) { return; } return telegramSchema(); diff --git a/src/telegram-account-state.ts b/src/telegram-account-state.ts index 7c06811..40a9a4f 100644 --- a/src/telegram-account-state.ts +++ b/src/telegram-account-state.ts @@ -4,7 +4,7 @@ import type { Account, User } from "better-auth"; import { APIError } from "better-auth/api"; import { ERROR_CODES, PLUGIN_ID, TELEGRAM_OIDC_PROVIDER_ID } from "./constants"; -/** A Telegram user proven by a verified Login Widget or Mini App payload. */ +/** A Telegram user proven by a verified payload or a trusted bot provisioning caller. */ export interface TelegramIdentity { /** Telegram user id as a string. */ telegramId: string; @@ -13,6 +13,7 @@ export interface TelegramIdentity { /** Provisioning method reported to `user.validateUserInfo`. */ export type TelegramProvisioningMethod = + | "telegram-bot-provisioning" | "telegram-login-widget" | "telegram-mini-app"; diff --git a/src/types.ts b/src/types.ts index adc4611..5c3dbe0 100644 --- a/src/types.ts +++ b/src/types.ts @@ -210,6 +210,13 @@ export interface TelegramPluginOptions { * @default true */ autoCreateUser?: boolean; + /** + * Enable server-only provisioning for users proven by a trusted bot provisioning + * service. The host must authenticate the caller; this does not expose an + * HTTP endpoint or create a browser session. + * @default false + */ + botProvisioning?: boolean; /** * Bot token obtained from @BotFather * Used for verifying authentication data