Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .agents/skills/testing-patterns/references/repository.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Default tests use happy-dom unless their file selects Node. `*.adapter.test.ts`
excluded from `npm test`; a passing default suite is not adapter evidence. Coverage
floors remain 90% lines/statements/branches and 80% functions. Broad/release CI also
requires lint, type checks, runtime dependency audit, package validation, Node 24.0.0,
current Node 24/26, the complete minimum Better Auth 1.7.12 family, Bun 1.4.4 and real
current Node 24/26, the complete minimum Better Auth 1.7.17 family, Bun 1.4.4 and real
adapters. Do not infer a release pass from one local lane or bypass required checks.

Documentation/skill-only changes normally need readback, link/frontmatter validation
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ jobs:
- node: 26.x
better-auth: locked
- node: 24.x
better-auth: 1.7.12
better-auth: 1.7.17
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,6 @@ coverage/
voice-tone.md
# Release tarballs generated by test:package
*.tgz

# Local device recordings and live acceptance logs
/artifacts/
22 changes: 22 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,28 @@ 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).

## [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.

### Fixed

- **Revoked sessions cannot change Telegram account links.** Link and unlink now check server-side session storage before accepting a cached cookie. Unlink still requires a recent sign-in.
- **OIDC account revocation is checked before issuing a session.** Removing or reassigning the account during application validation, changing a new account binding in a hook, or removing a newly created account can no longer leave that attempt signed in without its original account proof.
- **Generated client unlink calls use POST.** `authClient.telegram.unlink()` works without a dummy request body.
- **Widgets support global throwing fetch options.** `fetchOptions.throw: true` no longer breaks a successful widget configuration request.

### Changed

- **Requires Better Auth and `@better-auth/core` 1.7.17 or newer, below 1.8.** Earlier supported versions can link an OAuth account using a revoked cached session or finish linking after the initiating session was revoked. Upgrade the Better Auth packages together. No plugin database migration is required.
- Added a tested [server-owned fields recipe](docs/server-owned-fields.md) for the follow-up in [#53](https://github.com/vcode-sh/better-auth-telegram/issues/53). It populates creation-time user fields or fresh per-sign-in session claims through validation and trusted database hooks, without `customSession` or allowing clients to edit authorization fields. Live device testing also documents the returning-user behavior of Better Auth's in-memory store. Mappers continue to respect `input: false`.

### Verification

- Exercised OIDC, Login Widget and Mini App sign-in through the real Telegram app on a physical Android phone, including JWT readback, rejected field edits, logout and account revocation. Added focused regressions for returning-user session claims and kept the live acceptance harness reusable.

Thanks to [@parmetra](https://github.com/parmetra) for the detailed configuration and follow-ups in [#53](https://github.com/vcode-sh/better-auth-telegram/issues/53). They helped uncover the async-mapper issue in earlier patches and prompted this deeper review of server-owned fields and session behavior.

## [3.2.1] - 2026-11-04

More reliable sign-in when widgets load out of order, OIDC identifiers have unusual formats, or application hooks change an account during login. No database migration or configuration change is required.
Expand Down
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ Single test file: `npx vitest run src/verify.test.ts`

## Dependencies

**Runtime (peer):** `better-auth`, `@better-auth/core` (`>=1.7.12 <1.8.0`; 1.7.7 fixed GHSA-965c-763c-88jm, 1.7.12 made every OAuth callback route — including oauth-proxy — enforce the ID token nonce)
**Runtime (peer):** `better-auth`, `@better-auth/core` (`>=1.7.17 <1.8.0`; 1.7.7 fixed GHSA-965c-763c-88jm, 1.7.12 enforced ID-token nonces across callbacks; 1.7.17 includes live-session checks for OAuth linking)

**Runtime (dependency):** `jose`

Expand All @@ -93,7 +93,7 @@ Single test file: `npx vitest run src/verify.test.ts`
- All endpoints use `createAuthEndpoint()` from `better-auth/api`. Follow that pattern.
- Write users/accounts through `ctx.context.internalAdapter`, never raw `ctx.context.adapter.create` (that skips `databaseHooks` and `validateUserInfo`). Reads via `adapter.findOne` are fine.
- Telegram facts verified live (2026-10-29): OIDC `sub` is per bot (use the `id` claim for the Telegram user id; the plugin normalizes verified numeric or string IDs to strings before exposing claims); switching a bot to OIDC permanently disables its legacy Login Widget; BotFather rejects localhost redirect URIs; ID tokens live 30 s; token errors come back as HTTP 200; declining the OIDC login in the Telegram app sends no callback at all (oauth.telegram.org shows its account picker again).
- Session-protected endpoints use `sessionMiddleware`. Don't forget it for authenticated routes.
- Account link/unlink endpoints use `sensitiveSessionMiddleware` to reject revoked sessions even with cookie caching. Unlink also uses `freshSessionMiddleware`.
- Type guards (`validateTelegramAuthData`, `validateMiniAppData`) run before processing. Don't skip validation.
- Mini App endpoints are conditionally registered (`miniApp.enabled`). Test both enabled and disabled paths.
- OIDC provider is conditionally injected via `init` hook (`oidc.enabled`). JWT verification in `oidc-token.ts` uses `jose` library -- changes to JWKS fetching or token validation need scrutiny.
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ There is one. It's in [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md). The short versio

## CI and releases

Node.js 24 is the minimum. The required `CI` check collects package validation, Node 24.0.0 and current 24/26 tests, the complete Better Auth 1.7.12 family, forced Bun 1.4.4 tests and real database adapters. A failed or skipped required lane fails the gate. Fork PRs run with read-only permissions.
Node.js 24 is the minimum. The required `CI` check collects package validation, Node 24.0.0 and current 24/26 tests, the complete Better Auth 1.7.17 family, forced Bun 1.4.4 tests and real database adapters. A failed or skipped required lane fails the gate. Fork PRs run with read-only permissions.

`npm run build` checks the bundles and declarations with publint and Are The Types Wrong. `npm run test:package` packs the result, installs it outside the checkout, checks its consumer types, exercises ESM authentication configuration and loads both CommonJS exports. It leaves `better-auth-telegram-<version>.tgz` for inspection. CI uploads that tarball.

Expand Down
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ New words? The [glossary](docs/README.md#glossary) explains bots, BotFather, OID
## Requirements

- **Node.js 24 or newer** (Bun works too).
- **Better Auth 1.7.12 or newer, below 1.8**: `better-auth` and `@better-auth/core` `>=1.7.12 <1.8.0`. Better Auth 1.6 is not supported, because it has a critical security issue with no 1.6 fix ([details](docs/migration-v2-to-v3.md#why-upgrade)).
- **Better Auth 1.7.17 or newer, below 1.8**: `better-auth` and `@better-auth/core` `>=1.7.17 <1.8.0`. Better Auth 1.6 is not supported, because it has a critical security issue with no 1.6 fix ([details](docs/migration-v2-to-v3.md#why-upgrade)).
- **A Telegram account**, to create a bot.
- **A public HTTPS address** for your app. Telegram does not work with `localhost`. During development, a tunnel such as [ngrok](https://ngrok.com) gives your local server a public HTTPS address.

Expand Down Expand Up @@ -136,11 +136,11 @@ Using something else? Better Auth has a page for [each framework](https://www.be
### 6. Create the database tables

```bash
npx auth@1.7.14 migrate
npx auth@1.7.14 check schema
npx auth@1.7.17 migrate
npx auth@1.7.17 check schema
```

The first command creates Better Auth's tables plus the plugin's Telegram columns. The second should print `Schema check passed against the live database.` Using Prisma or Drizzle? Run `npx auth@1.7.14 generate` instead of `migrate`, then your ORM's own migration ([details](docs/installation.md#3-update-your-database)).
The first command creates Better Auth's tables plus the plugin's Telegram columns. The second should print `Schema check passed against the live database.` Using Prisma or Drizzle? Run `npx auth@1.7.17 generate` instead of `migrate`, then your ORM's own migration ([details](docs/installation.md#3-update-your-database)).

> **Don't skip this step.** Better Auth refuses to answer any auth request (HTTP 500, "schema mismatch") until the database has every column it expects.

Expand Down Expand Up @@ -274,7 +274,7 @@ Example code: [`examples/nextjs-app/`](examples/nextjs-app) has components for a

v3 supports Better Auth 1.7 and drops Better Auth 1.6. Upgrade because Better Auth below 1.7.7 has a critical account-takeover issue ([GHSA-965c-763c-88jm](https://github.com/better-auth/better-auth/security/advisories/GHSA-965c-763c-88jm)) that is not fixed in 1.6.

In short: upgrade Better Auth to 1.7.12 or newer, update your database schema, set `oidc.clientSecret` if you use OIDC, and check your unlink UI and database hooks. The [migration guide](docs/migration-v2-to-v3.md) walks through every step and every breaking change. Older upgrade notes (v0.x to v2) are in the [changelog](CHANGELOG.md).
In short: upgrade Better Auth to 1.7.17 or newer, update your database schema, set `oidc.clientSecret` if you use OIDC, and check your unlink UI and database hooks. The [migration guide](docs/migration-v2-to-v3.md) walks through every step and every breaking change. Older upgrade notes (v0.x to v2) are in the [changelog](CHANGELOG.md).

## Links

Expand Down
3 changes: 2 additions & 1 deletion 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 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) |
| I get an error, or something doesn't happen. | [Troubleshooting](./troubleshooting.md) (organized by symptom) |
Expand Down Expand Up @@ -59,7 +60,7 @@ Welcome. This page tells you where to find each answer, and explains the words t

**Tunnel.** A tool such as [ngrok](https://ngrok.com) that gives your local development server a public HTTPS address. Telegram doesn't accept `localhost`, so you need one during development.

**Migration (database).** Changing your database tables to match what your code expects. Better Auth's CLI does this for you: `npx auth@1.7.14 migrate` or `npx auth@1.7.14 generate`.
**Migration (database).** Changing your database tables to match what your code expects. Better Auth's CLI does this for you: `npx auth@1.7.17 migrate` or `npx auth@1.7.17 generate`.

## Links

Expand Down
2 changes: 1 addition & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ Rules, so there are no surprises:
- **Mappers may be async**, so they can look the user up in your own data. Throw an `APIError` from `better-auth/api` to refuse the sign-in: nothing is created and the endpoint answers with the error's status. For OIDC that answer comes from the callback URL instead of a redirect to `errorCallbackURL`, as with Better Auth's built-in providers. See the [OIDC example](./oidc.md#what-gets-stored).
- **Mappers run on every sign-in attempt.** Keep them safe to call again. Their mapped profile values are stored when a user is created; returning users keep their name, image and email. Verified Telegram identity fields are refreshed separately. For OIDC, `oidc.updateUserInfoOnSignIn: true` writes the name, image and mapped fields onto returning users too (never the email).
- **Only known fields are kept.** Mapper output is filtered like a Better Auth OAuth profile: fields that aren't in your user schema, or that users may not set (`input: false`), are dropped. That includes the plugin's own `telegramId`, `telegramUsername` and `telegramPhoneNumber`, which the plugin fills itself.
- **Keep authorization fields server-owned.** Do not enable input for roles, membership, or an internal user ID just to save it through a mapper: the same setting also accepts values from generic user-update requests. Keep those fields at `input: false` and write them through your application's trusted server code. A mapper can still refuse sign-in by throwing an `APIError`. See [Better Auth's guidance](https://better-auth.com/docs/concepts/oauth#server-owned-fields-and-authorization-claims).
- **Keep authorization fields server-owned.** Do not enable input for roles, membership, or an internal user ID just to save it through a mapper: the same setting also accepts values from generic user-update requests. Keep those fields at `input: false` and write them through your application's trusted server code. The [server-owned fields guide](./server-owned-fields.md) shows creation-time user fields and fresh per-sign-in session claims without `customSession`. A mapper can still refuse sign-in by throwing an `APIError`. See [Better Auth's guidance](https://better-auth.com/docs/concepts/oauth#server-owned-fields-and-authorization-claims).
- **The Login Widget and Mini App mappers can't set `id` or `emailVerified`.** An email from a mapper is stored as unverified, because Telegram didn't verify it.
- **The OIDC mapper can't set `id` or `emailVerified`** (both are ignored). Telegram verifies no email, and Better Auth links a sign-in to an existing user when the email is marked verified, so a mapper must not be able to vouch for one.
- **A Login Widget or Mini App mapper email that another user already has** is refused with 422 `USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL`. OIDC follows Better Auth's OAuth linking rules: by default an email collision gives `account_not_linked`; deliberately trusting a provider for email linking changes that policy. Keep the default placeholder unless you have independently established who owns an email.
Expand Down
10 changes: 5 additions & 5 deletions docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ npm install better-auth-telegram better-auth

pnpm, yarn and bun work the same way (`pnpm add`, `yarn add`, `bun add`).

- `better-auth-telegram` v3 needs `better-auth` and `@better-auth/core` version `>=1.7.12 <1.8.0`. `@better-auth/core` is installed together with `better-auth`.
- `better-auth-telegram` v3 needs `better-auth` and `@better-auth/core` version `>=1.7.17 <1.8.0`. `@better-auth/core` is installed together with `better-auth`.
- The plugin's only other dependency is [`jose`](https://github.com/panva/jose), which checks OIDC tokens. Your package manager installs it automatically.

## 2. Configure the server
Expand Down Expand Up @@ -86,13 +86,13 @@ Let Better Auth's CLI do the work. Which command depends on how you connect to t

```bash
# Built-in Kysely adapter (a pg/mysql2 pool, SQLite): applies the changes directly
npx auth@1.7.14 migrate
npx auth@1.7.17 migrate

# Prisma or Drizzle: writes the schema file, then run your ORM's migration
npx auth@1.7.14 generate
npx auth@1.7.17 generate

# Everyone: confirm the database matches
npx auth@1.7.14 check schema
npx auth@1.7.17 check schema
```

`check schema` should print `Schema check passed against the live database.`
Expand Down Expand Up @@ -175,7 +175,7 @@ Free ngrok addresses change every time ngrok restarts. When that happens, repeat

## Check that it works

1. `npx auth@1.7.14 check schema` passes.
1. `npx auth@1.7.17 check schema` passes.
2. The server starts without `[better-auth-telegram]` warnings.
3. `https://<your domain>/api/auth/telegram/config` returns your bot's username, for example `{"botUsername":"my_app_login_bot","loginWidgetEnabled":true,...}`.
4. Your sign-in button appears and signing in creates a user with a `telegramId`.
Expand Down
Loading
Loading