diff --git a/.agents/skills/testing-patterns/references/repository.md b/.agents/skills/testing-patterns/references/repository.md index d822075..d4871e8 100644 --- a/.agents/skills/testing-patterns/references/repository.md +++ b/.agents/skills/testing-patterns/references/repository.md @@ -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 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 866a0fc..b8e41aa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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: diff --git a/.gitignore b/.gitignore index e3b09c4..2f744cb 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,6 @@ coverage/ voice-tone.md # Release tarballs generated by test:package *.tgz + +# Local device recordings and live acceptance logs +/artifacts/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 6705b81..616902b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/CLAUDE.md b/CLAUDE.md index 0f8be07..0ccc442 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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` @@ -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. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 85c31f2..1745816 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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-.tgz` for inspection. CI uploads that tarball. diff --git a/README.md b/README.md index c7af9ae..ee5c714 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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. @@ -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 diff --git a/docs/README.md b/docs/README.md index 0539f1d..45cca27 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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) | @@ -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 diff --git a/docs/configuration.md b/docs/configuration.md index a3d81f7..4bad97c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -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. diff --git a/docs/installation.md b/docs/installation.md index 8dcab73..45f82e3 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -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 @@ -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.` @@ -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:///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`. diff --git a/docs/issue-53-challenge-2026-11-05.md b/docs/issue-53-challenge-2026-11-05.md new file mode 100644 index 0000000..08c48bf --- /dev/null +++ b/docs/issue-53-challenge-2026-11-05.md @@ -0,0 +1,113 @@ +# Issue #53: authentication flow challenge and repairs + +Date: 2026-11-05. Starting commit: `2c8f39ef87afd1b7e7fcfcdc7cc9035ca49f4f4f`. +The issue and all comments were read, including the reporter's latest +[`input: false` follow-up](https://github.com/vcode-sh/better-auth-telegram/issues/53#issuecomment-6652246775). +This report describes the initial local changes and checks, before the subsequent live device acceptance. See [the live follow-up](live-acceptance-2026-11-05.md) for actual Telegram callbacks, recordings and the corrected distinction between creation-time user fields and per-sign-in session claims. No release was published. + +## The latest report has a different cause + +The reporter confirmed the async mapper fix works in 3.1.1 and 3.2.1. Their new +configuration marks application fields as `input: false`. Better Auth deliberately +filters those values out of provider mapper results, including in stateless mode. +`returned: true` exposes an already stored value; it does not populate the field. +The same rule exists in the inspected 1.7.12, 1.7.14 and 1.7.17 sources. + +Changing the mapper to bypass this rule, or enabling client input for application +IDs and roles, would undermine the documented boundary. The repair to our guidance +is a complete [trusted-field recipe](server-owned-fields.md), with an application +lookup in `validateUserInfo`, request-local state, and a `user.create.before` hook. +No `customSession` is needed. Required server-owned fields must not be rejected by +the earlier provider parser before that hook can supply them. + +The executable example checks the JWT itself and session readback on a second +auth instance, rejects generic user updates, refuses unknown members, and separates +two overlapping sign-ins at a controlled creation-hook barrier. It also explicitly +disables stateless rolling refresh and verifies the session expires: Better Auth +otherwise enables cookie refresh by default without a database, without repeating +the application membership lookup. + +## Confirmed defects and fixes + +| Reachable failure | Fix | Discriminating evidence | +| --- | --- | --- | +| A revoked session remained in cookie cache and could link or unlink Telegram. | Authoritative session middleware for both routes; freshness still enforced for unlink. | SQLite, a second device revoking the session, a still-readable cached session, then 401 and unchanged accounts. Both operations returned 200 before the fix. | +| Better Auth 1.7.14 allowed OIDC linking from revoked cached sessions, and completed a redirect after its initiating session was revoked. | Raise both peers and the complete development family to 1.7.17; update CI minimum and installation instructions. | Three failing cases on 1.7.14, all four cases including the live-session control passing on isolated 1.7.17. | +| Returning OIDC login could issue a session after validation or profile-update hooks removed its account; a creation hook could remove a new account with the same result. | Remember the expected account owner in request state and recheck its proof after hooks, before session storage. Apply in OIDC-only mode too. | Failing-first callback/direct-token cases, first-sign-in and profile-hook cases; real-adapter creation-hook regression. Unrelated nested sessions still succeed. | +| The new ownership snapshot initially moved duplicate-account failure outside Better Auth's redirect error handling. | Snapshot only an unambiguous owner and let Better Auth perform its authoritative duplicate rejection. | Existing duplicate-account test caught 500 instead of 302; it passes with no session or new account after repair. | +| A widget failed to initialize with global `fetchOptions.throw: true`. | Request an explicit response envelope for the widget's internal config fetch. | Real Better Auth client and server in a DOM test: successful config previously still threw. | +| Generated `authClient.telegram.unlink()` sent GET to a POST-only endpoint. | Declare the client's route method. | Generated client call previously returned 404; it now removes the link without a dummy body. | + +The server-owned mapper filter itself remains unchanged. Public package entrypoints +remain unchanged. There is no plugin schema migration. Consumers must upgrade +`better-auth` and `@better-auth/core` together to `>=1.7.17 <1.8.0`. + +## Scope inspected + +Three independent review lanes and central integration covered: + +- OIDC token verification, claim normalization, nonce, issuer/audience/subject, + algorithms, JWKS caching and rotation, token exchange, provider mapping, + registration, configuration and public types. +- Account creation and lookup, ownership, explicit and implicit linking, + placeholder collisions, hook vetoes, revocation, identity reconciliation, + database adapter boundaries, session issuance and cookie refresh. +- Widget and Mini App canonicalization, freshness, input structure, CSRF, + conditional endpoints, mapper awaiting, client notifications, generated routes, + widget replacement races and teardown. +- Documentation and dependency contracts against current official sources and + installed/tagged Better Auth implementation. Existing historical audit reports + were retained as historical evidence, not rewritten as current guarantees. + +## Verification + +| Check | Observed result | +| --- | --- | +| Node 26.13.0 full suite with coverage | 357 passed; thresholds passed: 98.69% lines, 96% branches, 100% functions. | +| Node 24.0.0, Node 24.22.2, Bun 1.4.4 full suites | 356 passed in each lane on the same final runtime implementation. The subsequently added recipe-expiry test and final recipe fixture were also checked on Node 26.13.0, Node 24.22.2 and Bun: 5 recipe tests passed per lane. | +| Real adapters | 103 passed, 7 pre-existing capability-dependent skips. PostgreSQL 18/Kysely, MySQL 8.4/Kysely, MongoDB 8.2 replica set, Drizzle/PostgreSQL and Prisma/PostgreSQL. | +| Type checks | Source plus built bundler/Node16 consumers passed, including the new documented recipe. | +| Lint and whitespace | Passed. | +| Build and package shape | ESM/CJS build, declaration output, publint and Are The Types Wrong passed. | +| Installed tarball | Isolated ESM/CommonJS consumers, signed login and consumer types passed. | +| Dependency graph/audit | Complete Better Auth 1.7.17 family verified; runtime audit reported zero vulnerabilities. | + +The adapter skips are existing exclusions for unsupported two-server and generated-ID +fixture capabilities, not missing database URLs. The new account-revocation case +ran in every adapter lane. Both sets of disposable database containers, temporary +runtime downloads, the dependency comparison fixture, generated adapter resources +and installed-package consumers were cleaned up. Shared databases were not used. + +The attempted `npm exec --package=node@24` invocation was discovered to resolve the +host Node 26 binary with the installed npm 12.2.1. It was not counted as Node 24 +evidence: the actual lanes used the explicit installed Node 24.22.2 binary and an +SHA-256-checked official Node 24.0.0 download, printing their versions first. + +## Limits + +This is a source and executable behavior review, not proof that no defects remain. +The Telegram issuer is a signed local fixture; live Telegram/BotFather consent, +actual browser rendering and third-party iframe cookies were not exercised. + +The ownership recheck closes the reproduced application-hook windows. It does not +make account revocation and session creation a distributed atomic transaction. +Existing limits around cross-instance identity uniqueness, nontransactional +partial writes, previously issued sessions and cache freshness remain documented +in [Security](security.md). Stateless JWT claims remain snapshots, so immediate +permission revocation belongs in the application's current authorization checks. + +No commit, push, publication or GitHub comment was made. Pre-existing AGENTS.md, +CLAUDE.md and `.entire/` work was preserved; CLAUDE.md additionally received the +current dependency baseline and authoritative-session guidance. + +## Primary references + +- [Better Auth provider mapping and server-owned fields](https://better-auth.com/docs/concepts/oauth#server-owned-fields-and-authorization-claims) +- [Better Auth database hooks](https://better-auth.com/docs/concepts/database#database-hooks) +- [Better Auth 1.7.16 release](https://github.com/better-auth/better-auth/releases/tag/v1.7.16) +- [Better Auth 1.7.17 release](https://github.com/better-auth/better-auth/releases/tag/v1.7.17) +- [Better Auth changes from 1.7.14 to 1.7.17](https://github.com/better-auth/better-auth/compare/v1.7.14...v1.7.17) +- [Better Auth client fetch options](https://better-auth.com/docs/concepts/client#fetch-options) +- [Telegram OIDC](https://core.telegram.org/bots/telegram-login) +- [Telegram legacy Login Widget verification](https://core.telegram.org/widgets/login-legacy#checking-authorization) +- [Telegram Mini App verification](https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app) diff --git a/docs/live-acceptance-2026-11-05.md b/docs/live-acceptance-2026-11-05.md new file mode 100644 index 0000000..716fbca --- /dev/null +++ b/docs/live-acceptance-2026-11-05.md @@ -0,0 +1,164 @@ +# Live Telegram acceptance: issue #53 and account safety + +Date: 2026-11-05. This follows the [source and behavior challenge](issue-53-challenge-2026-11-05.md). +The real Telegram app on a physical Google Pixel 10 Pro (Android 17), Chrome 155 +on that phone, a shared desktop browser, and two disposable Telegram bots were +used. The local built plugin ran against Better Auth 1.7.17 behind a temporary +HTTPS tunnel. The database scenarios used test-owned in-memory SQLite. + +## Result + +The real OIDC callback, legacy Widget and Mini App completed successfully. The +previous fixes rejected revoked-session account changes and rejected OIDC session +creation after application hooks revoked its account. The follow-up also found +and corrected a documentation gap about returning users without a database, and a +cookie-selection bug in the diagnostic harness. No additional production runtime +change was needed during this live follow-up. + +## Evidence + +Local evidence is kept outside version control in +`artifacts/live-issue53-2026-11-05/`. These are private local paths from this run; +a fresh clone contains the report and harness, not the evidence files: + +- Structured event log (`artifacts/live-issue53-2026-11-05/events.jsonl`): 289 events, including the diagnostic correction annotation. +- Manifest and SHA-256 hashes (`artifacts/live-issue53-2026-11-05/manifest.json`). +- Successful mobile OIDC recording (`artifacts/live-issue53-2026-11-05/oidc-device-success.mp4`). +- Mini App and generated unlink recording (`artifacts/live-issue53-2026-11-05/miniapp-device.mp4`). +- Revoked-session recording (`artifacts/live-issue53-2026-11-05/revoked-session-device.mp4`). +- Mobile JWT evidence (`artifacts/live-issue53-2026-11-05/trusted-mobile-jwt.png`), fresh session claims (`artifacts/live-issue53-2026-11-05/fresh-session-claims.png`), Mini App session (`artifacts/live-issue53-2026-11-05/miniapp-session.png`), rejected unlink (`artifacts/live-issue53-2026-11-05/revoked-unlink.png`), and bot deletion readback (`artifacts/live-issue53-2026-11-05/bots-deleted.png`). + +The directory also retains the initial UI attempts and touch telemetry. The first +long recording is split into two files because Android screenrecord limits each +chunk to 180 seconds. Short recordings can end at the last changing frame rather +than the exact recording stop time; the device tool disclosed that limit. + +The JSONL contains request paths/statuses, callback parameter **names**, real token +endpoint/JWKS response metadata, verified claim types, application decisions, +hooks and pseudonymized session/JWT fields. It omits raw credentials, codes, state, +nonce, cookies, JWTs, initData and Telegram profile details. Recordings may show +normal device UI and notification banners; keep them private. All evidence files +are mode 0600, and `/artifacts/` is ignored by Git. + +## Executed scenarios + +Times below are UTC and refer to `events.jsonl`. + +| Scenario | Observed result and evidence | +| --- | --- | +| Real OIDC with creation-time server-owned user fields | Mobile callback at 08:37:24 returned 302 after a real `/token` exchange and JWKS verification. Both session API and JWT contained `user_id:42`, fixture name/nick and role `member`. | +| Reported mapper configuration with `input:false` | At 08:35:20 the real mapper-mode callback succeeded, but protected user fields were absent; the input-allowed nickname was present. This matches Better Auth's documented filter. | +| Generic user-field edit | `/trusted/api/auth/update-user` returned 400 `FIELD_NOT_ALLOWED`; subsequent read retained the original member values. | +| Logout | After mobile sign-out, session evidence returned `authenticated:false`, with no user/session/JWT evidence. | +| Application denies a returning identity | At 08:39:48 the real profile verified, validation returned `not_a_member`, the callback showed that error, and a subsequent read returned no session. No `session_created` event followed that rejected attempt. | +| Persistent returning-user profile refresh | The same SQLite user fingerprint was retained between 08:40:37 and 08:41:19. Its nickname changed from `profile-v1` to `profile-v2`; protected user role remained its stored value. | +| Account revoked during returning validation, default upstream token update | At 08:42:18 validation deleted the account. Better Auth rejected earlier with `unable_to_update_account`; no session was issued. This is not evidence of the plugin's final guard by itself. | +| New account revoked in its creation hook | At 08:45:14 a new account was created and then deleted by the hook. The callback returned `ACCOUNT_NOT_LINKED`, and session readback was null. | +| Fresh claims on repeated stateless sign-in | At 08:59:12 and 08:59:51 the same in-memory user fingerprint was retained. User role stayed `member`; the new session and JWT.session changed to role `editor` and nick `member-v2`. | +| Generic session-field edit | At 08:59:33 `/trusted/api/auth/update-session` returned 400 `FIELD_NOT_ALLOWED`. | +| Real Mini App launch | At 08:56:50 the bot's menu launched the page inside Telegram, supplied real signed initData, and `/telegram/miniapp/signin` returned 200 with a session. | +| Generated unlink route | At 08:57:32 `authClient.telegram.unlink()` sent POST without a dummy body and returned 200. The same user's Telegram identity was cleared from the session. A later signed Mini App sign-in created a new auth user after the previous account had been unlinked, as documented. | +| Real legacy Login Widget | At 09:02:03 the Widget completed Telegram's consent popup and `/telegram/signin` returned 200. It reached the same user fingerprint as the preceding Mini App login. The widget initialized with global `fetchOptions.throw:true`. | +| Revoked cached session cannot link | At 09:02:15 the test action deleted only the current stored session and retained the browser cache. At 09:03:05 `/telegram/link` returned 401. | +| Revoked cached session cannot unlink, independent attempt | A fresh Widget sign-in succeeded at 09:03:59. The session was revoked at 09:04:12; unlink was the first protected mutation after that revocation and returned 401 at 09:04:13, before its original expiry. | +| Returning account revoked with upstream token updates disabled | With `account.updateAccountOnSignIn:false`, the 09:06:03 validation hook revoked the account. The plugin's final ownership guard returned `ACCOUNT_NOT_LINKED`; readback showed no session. | +| Expired stateless session | The session issued at 08:59:51 expired at 09:04:51. Reading the trusted page at 09:06 returned `authenticated:false` without a new sign-in. | + +The legacy revoke action is test-only, Origin checked and authenticated against +current server storage. It accepts no arbitrary user/session ID and revokes only +the caller's own session. The valid unlink and the revoked-session unlink were +separate attempts, so a preceding 401 could not make the latter vacuous by already +clearing its cookie. + +## Corrections discovered by live testing + +### Creation-time user fields do not refresh automatically + +Better Auth's no-database setup still has a memory adapter per auth instance. +Users and accounts survive while that instance is running. A returning OAuth +login reruns validation but skips `user.create.before`, so fresh request-local +lookup data does not replace the stored user fields. The earlier statement that +a new sign-in alone refreshes those values was incomplete. + +The [server-owned fields guide](server-owned-fields.md) now distinguishes: + +- creation-time values in `user.additionalFields`; +- fresh per-sign-in values in `session.additionalFields`, supplied by + `databaseHooks.session.create.before`. + +The latter values live under `session`, including in the decoded JWT. The guide +states that path explicitly and includes a complete compiled example. It does +not bypass `input:false`, duplicate cookie-writing code, or require `customSession`. +Already issued claims remain snapshots; immediate permission revocation still +requires checking current application authorization. + +Four additional integration tests protect same-instance repeated login, JWT +readback on another instance, forbidden generic edits, and rejected admission. + +### The diagnostic reader must select the mode's exact cookie + +One diagnostic `session_read` at **09:02:03.778** correctly read the legacy session +through Better Auth, but its separately decoded `jwt` subsection selected the +trusted mode's earlier cookie. The original JSONL entry remains for traceability; +a final `diagnostic_correction` event marks that subsection invalid. Do not use it +as JWT evidence. + +The reader now obtains `authCookies.sessionData.name` from the selected auth +instance and selects that exact cookie. The repeated real Widget sign-in at +**09:03:59.290**, while the other mode's cookie was still valid, shows matching +legacy user/session fingerprints in both API and JWT evidence. Earlier isolated +Mini App and trusted-mode reads were not affected by this ordering mistake. + +Some initial native-popup taps dismissed the prompt without completing approval. +A screenshot-guided tap on the visible Log In area completed it and returned the +callback. This was a device-automation interaction issue, not a reproduced plugin +failure. Superseded attempts also produced a `state_mismatch`; successful and +intentional refusal scenarios above are identified separately by time. + +## Verification and cleanup + +After the follow-up changes, the default suite passed **361 tests** with unchanged +coverage gates (98.69% lines, 96% branches, 100% functions). Source types, both +built consumer type modes, lint and whitespace checks passed. The four new +session-claim tests also passed on Bun 1.4.4 and Node 24.22.2. The live harness was +bundled and executed; its mode configuration and helper modules received focused +type checks during authoring. + +The prior 103-pass real-adapter lane and installed ESM/CommonJS package checks +remain evidence for the unchanged production runtime. They were not rerun merely +for this documentation/test-harness follow-up. + +Both newly created bots were deleted and BotFather read back `You have currently +no bots`. A supplementary direct Bot API deletion probe encountered a connection +reset before an HTTP response, so it supplies no additional deletion evidence. +The test server and tunnel were stopped, owned SQLite handles were released, +three newly opened mobile Chrome tabs were closed (the original five remain), the +new Mini App tab and shared preview tab were closed, and private local credentials +and raw device diagnostic output were removed. The phone was not shut down. + +## Scope limits + +The provider, consent UI, signatures, callback and Better Auth processing were +real. The application membership lookup intentionally returned fixture member +records; the reporter's external SQL database was not accessed. This run does not +establish iOS behavior, Telegram Web iframe cookie behavior, load/concurrency +across independent servers, or compatibility with every application hook. Those +boundaries retain the limits documented in [Security](security.md). + +No commit, push, npm publication or GitHub reply was made. + + +## Subsequent 3.2.2 release review + +The final release review additionally found that an application account-creation +hook could change a fresh OIDC binding before the earlier guard remembered its +owner. The release now pins the original owner before application hooks and +rejects a changed owner before identity synchronization. Changes to account key +or provider also prevent that sign-in from creating a session. + +Six focused cases (owner, account key and provider, with and without legacy +identity fields) reproduced the gap before the fix and passed afterward. The +final default suite has 367 tests. This delta was checked through the real Better +Auth integration boundary and the release gates; the device recordings above +remain evidence for the preceding live-tested tree, as recorded by their manifest. +The OIDC protocol and browser interactions were not changed by this delta. diff --git a/docs/migration-v2-to-v3.md b/docs/migration-v2-to-v3.md index 5b156e4..6eb04b5 100644 --- a/docs/migration-v2-to-v3.md +++ b/docs/migration-v2-to-v3.md @@ -18,7 +18,7 @@ This guide takes you from `better-auth-telegram` v2.x to v3. Most apps need four v2 requires Better Auth 1.6. Better Auth 1.6 is affected by [GHSA-965c-763c-88jm](https://github.com/better-auth/better-auth/security/advisories/GHSA-965c-763c-88jm), a critical account-takeover issue (CVSS 9.1): in Better Auth from 1.4.0-beta.18 up to (not including) 1.7.7, an OAuth sign-in `state` value could be used as a Magic Link token, letting an attacker who knows a user's email sign in as that user. It affects apps that use Magic Link together with a social or OAuth sign-in (such as Telegram OIDC), with OAuth state stored in the database (the default when you have a database). It is fixed **only in 1.7.7**; there is no 1.6 fix, and Better Auth supports only its latest version. -v3 therefore requires Better Auth **1.7.12 or newer** (below 1.8). 1.7.12 is the first release in which every OAuth callback route, including Better Auth's `oauth-proxy` plugin, checks the ID-token nonce. +v3 therefore requires Better Auth **1.7.17 or newer** (below 1.8). The original v3 baseline was 1.7.12 for ID-token nonce enforcement on every OAuth callback route. The current baseline is 1.7.17, which also verifies the live initiating session when linking an OAuth account, including after the redirect. Older versions can accept a revoked session from the cookie cache. v3 also fixes real bugs (Login Widget and Mini App sign-up failed on SQL databases, OIDC ID tokens weren't verified on the callback, unlinking didn't stop Telegram sign-in) and brings stricter, Better-Auth-consistent rules. The [changelog](../CHANGELOG.md) lists every change. @@ -43,7 +43,7 @@ npm install better-auth-telegram@3 better-auth@1.7 npm install @better-auth/core@1.7 ``` -Check the result: `npm ls better-auth-telegram better-auth @better-auth/core` should show `better-auth-telegram` 3.x and Better Auth 1.7.12 or newer, all Better Auth packages on the same version. +Check the result: `npm ls better-auth-telegram better-auth @better-auth/core` should show `better-auth-telegram` 3.x and Better Auth 1.7.17 or newer, all Better Auth packages on the same version. ### 2. Apply Better Auth's own 1.7 changes (everyone) @@ -53,12 +53,12 @@ Follow the [Better Auth 1.7 upgrade guide](https://www.better-auth.com/docs/guid First check for duplicate `(providerId, accountId)` pairs, as Better Auth's [upgrade guide](https://www.better-auth.com/docs/guides/1-7-upgrade-guide#check-for-duplicate-account-keys) requires. Keep different users separate when resolving them. If you briefly ran Better Auth 1.7.0–1.7.2, also follow its steps for the retired `account.issuer` column before applying migrations. -Use the CLI version matching Better Auth. These examples use the tested 1.7.14 release: +Use the CLI version matching Better Auth. These examples use the tested 1.7.17 release: ```bash -npx auth@1.7.14 migrate # built-in Kysely adapter (pg, mysql2, SQLite) -npx auth@1.7.14 generate # Prisma or Drizzle; then run your ORM's migration -npx auth@1.7.14 check schema # must print "Schema check passed against the live database." +npx auth@1.7.17 migrate # built-in Kysely adapter (pg, mysql2, SQLite) +npx auth@1.7.17 generate # Prisma or Drizzle; then run your ORM's migration +npx auth@1.7.17 check schema # must print "Schema check passed against the live database." ``` Why: Better Auth 1.7.3 and newer answers **every** request with HTTP 500 until the database matches the schema. v3 adds an index on `user.telegramId` (it makes every Login Widget and Mini App sign-in faster). The five Telegram columns are the same as in v2. @@ -256,7 +256,7 @@ These still work, but you can remove them: | What changed | What breaks | What to do | |---|---|---| -| Better Auth `>=1.7.12 <1.8.0` (was `>=1.6.22 <1.7.0`); `@better-auth/core` is now a peer too | Installing next to Better Auth 1.6 fails | [Step 1](#1-update-the-packages-everyone), [step 2](#2-apply-better-auths-own-17-changes-everyone) | +| Better Auth `>=1.7.17 <1.8.0` (was `>=1.6.22 <1.7.0`); `@better-auth/core` is now a peer too | Installing next to Better Auth 1.6 fails | [Step 1](#1-update-the-packages-everyone), [step 2](#2-apply-better-auths-own-17-changes-everyone) | | Better Auth checks the schema; `user.telegramId` is indexed | Every request answers 500 until migrated | [Step 3](#3-update-the-database-everyone) | | Login Widget and Mini App go through Better Auth's internal adapter | Your `databaseHooks` and `user.validateUserInfo` now see Telegram users, and can block them | [Step 10](#10-review-your-hooks-if-you-use-databasehooks-or-uservalidateuserinfo) | | `/telegram/unlink` needs a fresh session and keeps the last sign-in method | New 403 `SESSION_NOT_FRESH` and 400 `CANNOT_UNLINK_LAST_ACCOUNT` | [Step 12](#12-update-your-unlink-ui-if-you-offer-unlink-telegram) | @@ -277,8 +277,8 @@ These still work, but you can remove them: ## Check that the upgrade worked -1. `npm ls better-auth-telegram better-auth` shows 3.x and 1.7.12 or newer. -2. `npx auth@1.7.14 check schema` prints `Schema check passed against the live database.` +1. `npm ls better-auth-telegram better-auth` shows 3.x and 1.7.17 or newer. +2. `npx auth@1.7.17 check schema` prints `Schema check passed against the live database.` 3. The server starts without `[better-auth-telegram]` warnings ([what they mean](./configuration.md#startup-warnings)). 4. `GET /api/auth/telegram/config` lists the methods you expect as enabled. 5. Sign in once with each method you use. A **new** Telegram user gets an email ending in `.placeholder.invalid`; existing users keep theirs. diff --git a/docs/miniapps.md b/docs/miniapps.md index 331b657..32d4ccc 100644 --- a/docs/miniapps.md +++ b/docs/miniapps.md @@ -41,7 +41,7 @@ export const auth = betterAuth({ }); ``` -Then update the database: `npx auth@1.7.14 migrate` (or `generate` for Prisma and Drizzle) and `npx auth@1.7.14 check schema`. The Mini App needs the [five Telegram columns](./installation.md#3-update-your-database). +Then update the database: `npx auth@1.7.17 migrate` (or `generate` for Prisma and Drizzle) and `npx auth@1.7.17 check schema`. The Mini App needs the [five Telegram columns](./installation.md#3-update-your-database). Mini App options (all optional): diff --git a/docs/oidc.md b/docs/oidc.md index 3e31f1f..ccd878b 100644 --- a/docs/oidc.md +++ b/docs/oidc.md @@ -93,7 +93,7 @@ All OIDC options are in [Configuration: OIDC](./configuration.md#oidc-options). ### 3. Update the database -Run `npx auth@1.7.14 migrate` (or `generate` for Prisma and Drizzle), then `npx auth@1.7.14 check schema`, as in [Installation](./installation.md#3-update-your-database). An OIDC-only setup adds no columns of its own, but Better Auth's own tables must exist. +Run `npx auth@1.7.17 migrate` (or `generate` for Prisma and Drizzle), then `npx auth@1.7.17 check schema`, as in [Installation](./installation.md#3-update-your-database). An OIDC-only setup adds no columns of its own, but Better Auth's own tables must exist. ## Add the sign-in button diff --git a/docs/security.md b/docs/security.md index faaa56e..1085fc5 100644 --- a/docs/security.md +++ b/docs/security.md @@ -60,10 +60,12 @@ What this prevents: forged tokens (only Telegram has the private key), tokens is **Telegram fields can't be edited by users.** `user.telegramId`, `telegramUsername` and `telegramPhoneNumber` are marked `input: false`, so Better Auth's update endpoints ignore them. Only the plugin sets them, from verified Telegram data. -Widget and Mini App account lookups tolerate duplicate rows for the same owner, but reject a key belonging to different users with `TELEGRAM_ALREADY_LINKED_OTHER`. Returning sign-ins recheck account ownership after application validation and profile-update hooks before continuing to session creation. These checks are not a distributed transaction or a way to revoke existing sessions. +Widget and Mini App account lookups tolerate duplicate rows for the same owner, but reject a key belonging to different users with `TELEGRAM_ALREADY_LINKED_OTHER`. Returning Widget, Mini App and OIDC sign-ins recheck account ownership after application validation and profile-update hooks before continuing to session creation. OIDC also rechecks newly created accounts after creation hooks. These checks are not a distributed transaction or a way to revoke existing sessions. **Unlinking revokes the account's sign-in access.** Whenever a `telegram` or `telegram-oidc` account is removed through Better Auth, a database hook re-checks the user. `user.telegramId` stays only if a remaining Telegram account proves it; otherwise it switches to one that does, or is cleared along with `telegramUsername` and `telegramPhoneNumber`. Sign-in independently checks that a linked account proves the profile's Telegram ID, so a stale field left by a vetoed update cannot restore access. Direct SQL deletion does not run hooks; clear the profile fields yourself to keep displayed data accurate. Existing Better Auth sessions remain active; revoke those separately when your policy requires it. +**Account changes require a live session.** `/telegram/link` and `/telegram/unlink` check server-side session storage when configured, so a valid cookie cache cannot authorize a change after session revocation. OIDC linking relies on the equivalent checks in Better Auth 1.7.17+, including revalidation of the initiating session after the redirect. + **Unlinking needs a recent sign-in, and never strands the user.** `/telegram/unlink` requires a session younger than `session.freshAge` (403 `SESSION_NOT_FRESH`), so an old stolen session can't remove the owner's Telegram login. It refuses to remove the last sign-in method (400 `CANNOT_UNLINK_LAST_ACCOUNT`) unless you set `account.accountLinking.allowUnlinkingAll: true`. **Placeholder emails are reserved.** Addresses ending in `@telegram.placeholder.invalid` can only be created by the Login Widget or Mini App sign-in for that exact Telegram ID, and `@telegram-oidc.placeholder.invalid` only by the OIDC sign-in for that `sub`. No user's email can be changed to one (400 `PLACEHOLDER_EMAIL_RESERVED`). Otherwise someone could register a Telegram user's placeholder address with a password and block or take over that account. `.invalid` addresses can't receive mail, so password-reset and magic-link emails can never reach them. @@ -76,7 +78,7 @@ Widget and Mini App account lookups tolerate duplicate rows for the same owner, The plugin creates users, accounts and sessions through Better Auth's internal adapter, so your Better Auth hooks see them: -- **`databaseHooks`** run for user, account and session changes. A refused new user gives 403 `USER_CREATION_REJECTED`; a refused account creation gives 403 `ACCOUNT_CREATION_REJECTED`; a refused session gives 401 `FAILED_TO_CREATE_SESSION`. Required identity updates and account removals also fail explicitly (`IDENTITY_UPDATE_REJECTED`, `ACCOUNT_UNLINK_REJECTED`). The plugin uses transactions for sign-up, link and unlink; rollback requires transaction support in your adapter (enable `transaction: true` for Drizzle or Prisma). On a nontransactional adapter, a refused later write can leave earlier writes in place. Inspect the error and stored accounts before retrying. +- **`databaseHooks`** run for user, account and session changes. A refused new user gives 403 `USER_CREATION_REJECTED`; a refused account creation gives 403 `ACCOUNT_CREATION_REJECTED`; a refused session gives 401 `FAILED_TO_CREATE_SESSION`. Required identity updates and account removals also fail explicitly (`IDENTITY_UPDATE_REJECTED`, `ACCOUNT_UNLINK_REJECTED`). The plugin uses transactions for sign-up, link and unlink; rollback requires transaction support in your adapter (enable `transaction: true` for Drizzle or Prisma). On a nontransactional adapter, a refused later write can leave earlier writes in place. After hooks can also run after a transaction commits; a rejected session does not undo those application changes. Inspect the error and stored accounts before retrying. - **`user.validateUserInfo`** is called for every Login Widget and Mini App step, with `source.method` set to `"telegram-login-widget"` or `"telegram-mini-app"` and `source.action` set to: - `"create-user"` for a new user, - `"sign-in"` for a returning user, @@ -140,8 +142,8 @@ When Telegram starts signing ID tokens with a new key, OIDC sign-ins can fail fo ## Production checklist -- [ ] Better Auth is 1.7.12 or newer (`npm ls better-auth`). -- [ ] `npx auth@1.7.14 check schema` passes against the production database. +- [ ] Better Auth is 1.7.17 or newer (`npm ls better-auth`). +- [ ] `npx auth@1.7.17 check schema` passes against the production database. - [ ] The server starts without `[better-auth-telegram]` warnings. - [ ] Secrets are in environment variables, not in code or git. - [ ] Your site uses HTTPS, and Better Auth's cookies are secure (the default in production). diff --git a/docs/server-owned-fields.md b/docs/server-owned-fields.md new file mode 100644 index 0000000..a6212eb --- /dev/null +++ b/docs/server-owned-fields.md @@ -0,0 +1,226 @@ +# Server-owned fields in an OIDC session + +`input: false` prevents both API requests and provider mappers from setting a +field. `returned: true` includes its **stored** value in the user response and +session cookie; it does not populate it. This is Better Auth's documented +[provider mapping contract](https://better-auth.com/docs/concepts/oauth#server-owned-fields-and-authorization-claims), +including stateless authentication. Setting `input: true` for a role or your +application's user ID would also let a user submit that field to `/update-user`. + +You do not need `customSession` to include stored fields in the JWT. You need a +trusted write before Better Auth builds the session. + +## Stateless OIDC with an application user lookup + +This example covers the setup in [issue #53](https://github.com/vcode-sh/better-auth-telegram/issues/53): +Better Auth has no database, while your application looks up members in its own +database. The validation callback receives the verified Telegram profile. It +rejects unknown users and keeps the selected member in request-local state. A +[database hook](https://better-auth.com/docs/concepts/database#database-hooks) +then supplies the server-owned fields when Better Auth creates a user. This also +works without a configured database, but it is a **creation hook**, not a hook that +updates user fields on every sign-in. The same running Better Auth instance keeps +an in-memory user/account store, and a returning user skips creation. See the +per-sign-in session fields below when values must be refreshed at each login. + +```ts +import { defineRequestState } from "@better-auth/core/context"; +import { betterAuth } from "better-auth"; +import { telegram } from "better-auth-telegram"; +import { findMemberByTelegramId } from "./members"; + +interface Member { + user_id: number; + user_name: string; + user_nick: string; + role: string; +} + +// A separate value for each request, including concurrent sign-ins. +const verifiedMember = defineRequestState(() => null); + +export const auth = betterAuth({ + baseURL: process.env.BETTER_AUTH_URL, + secret: process.env.BETTER_AUTH_SECRET, + session: { + expiresIn: 300, + cookieCache: { enabled: true, strategy: "jwt", maxAge: 300, refreshCache: false }, + }, + account: { storeStateStrategy: "cookie", storeAccountCookie: true }, + user: { + additionalFields: { + user_id: { type: "number", required: false, input: false, returned: true }, + user_name: { type: "string", required: false, input: false, returned: true }, + user_nick: { type: "string", required: false, input: false, returned: true }, + role: { type: "string", required: false, input: false, returned: true }, + }, + async validateUserInfo({ source }) { + const telegramId = source.oauth?.profile?.id; + if (source.oauth?.providerId !== "telegram-oidc" || typeof telegramId !== "string") { + return { error: "telegram_required" }; + } + // Implement this with your application's parameterized query. + const member: Member | null = await findMemberByTelegramId(telegramId); + if (!member) { + return { error: "not_a_member" }; + } + await verifiedMember.set(member); + }, + }, + databaseHooks: { + user: { + create: { + async before() { + const member = await verifiedMember.get(); + if (!member) { + return false; + } + return { + data: { + user_id: member.user_id, + user_name: member.user_name, + user_nick: member.user_nick, + role: member.role, + }, + }; + }, + }, + }, + }, + plugins: [ + telegram({ + loginWidget: false, + oidc: { + enabled: true, + clientId: process.env.TELEGRAM_OIDC_CLIENT_ID, + clientSecret: process.env.TELEGRAM_OIDC_CLIENT_SECRET, + }, + }), + ], +}); +``` + +`findMemberByTelegramId` must return a member from your application database or +`null`. Use the verified `id` claim, not the bot-specific `sub`, a username, or a +field supplied in the HTTP request. Do not keep the current member in a shared +variable. Only copy the intended fields from the database result. + +The fields are `required: false` because Better Auth parses provider input before +running the validation callback and database hook. The callback and hook enforce +the application requirement instead: an unknown member cannot obtain a session. +A required server-owned field without a default fails earlier with `MISSING_FIELD`. + +This sample allows only Telegram OIDC to create users. If your configuration +supports other providers, define their validation and trusted field population +explicitly. `account` belongs beside `session`; JWT cookie encoding is selected by +`session.cookieCache.strategy`, not `session.strategy`. + +## Returning users and changes to permissions + +The creation hook runs only for new users, including when a configuration without +a database reuses its in-memory user in the same process. Validation still runs on +returning sign-ins and can deny admission, but setting request-local member data +does not update the existing user. With persistent storage, backfill existing +users and update server-owned values through your application's trusted database +layer. `oidc.updateUserInfoOnSignIn` refreshes input-allowed +profile fields; it does not bypass `input: false`. + +A JWT contains the values at issuance. Better Auth enables rolling cookie refresh +by default without a database; this sample explicitly sets `refreshCache: false` +so activity does not keep extending those claims. Reading or refreshing its cookie does not +repeat the application lookup. Choose its lifetime accordingly. A new sign-in repeats validation, but only +updates values if your trusted write path also handles returning users. Check +current permissions in your application for operations that need immediate +revocation. A long-lived cookie is not a live +membership check. + +The regression suite exercises this recipe with real Better Auth, a signed test +OIDC issuer, a decoded JWT, a second auth instance reading that cookie, rejected +`/update-user` attempts, and a rejected subsequent sign-in. It does not require +`customSession`. + + +## Fresh claims on every sign-in + +For values that must follow the application lookup at **each accepted sign-in**, +use `session.additionalFields` and `databaseHooks.session.create.before`. Every +new session runs that hook, including a returning user in the same process. +These values live under `session.user_id` and `session.role` in the JWT and +`getSession` result, rather than under `user`. Update consumers to read that path. + +This is a complete alternative to the creation-only user-field example above: + +```ts +import { defineRequestState } from "@better-auth/core/context"; +import { betterAuth } from "better-auth"; +import { telegram } from "better-auth-telegram"; +import { findMemberByTelegramId } from "./members"; + +interface Member { + user_id: number; + role: string; +} + +const verifiedMember = defineRequestState(() => null); + +export const auth = betterAuth({ + baseURL: process.env.BETTER_AUTH_URL, + secret: process.env.BETTER_AUTH_SECRET, + account: { storeStateStrategy: "cookie", storeAccountCookie: true }, + user: { + async validateUserInfo({ source }) { + const telegramId = source.oauth?.profile?.id; + if (source.oauth?.providerId !== "telegram-oidc" || typeof telegramId !== "string") { + return { error: "telegram_required" }; + } + const member: Member | null = await findMemberByTelegramId(telegramId); + if (!member) { + return { error: "not_a_member" }; + } + await verifiedMember.set(member); + }, + }, + session: { + expiresIn: 300, + cookieCache: { enabled: true, strategy: "jwt", maxAge: 300, refreshCache: false }, + additionalFields: { + user_id: { type: "number", required: false, input: false, returned: true }, + role: { type: "string", required: false, input: false, returned: true }, + }, + }, + databaseHooks: { + session: { + create: { + async before() { + const member = await verifiedMember.get(); + if (!member) { + return false; + } + return { data: { user_id: member.user_id, role: member.role } }; + }, + }, + }, + }, + plugins: [ + telegram({ + loginWidget: false, + oidc: { + enabled: true, + clientId: process.env.TELEGRAM_OIDC_CLIENT_ID, + clientSecret: process.env.TELEGRAM_OIDC_CLIENT_SECRET, + }, + }), + ], +}); +``` + +The example still allows only Telegram OIDC. Adapt the admission policy and claim +population explicitly if you enable another sign-in method. A refused application +lookup creates no session. Generic `/update-session` requests cannot change the +server-owned fields. + +This refreshes claims at sign-in, not while an existing cookie is being read. A +role changed after issuance remains a snapshot until a new sign-in or expiration; +check current application permissions when immediate revocation is required. +The same-instance returning-user regression checks the new role in both the +session API and decoded JWT, with no `customSession`. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index d69d6a4..315271c 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -45,9 +45,9 @@ Find what you see, then follow the fix. Each entry is: **what you see**, why it **Fix:** ```bash -npx auth@1.7.14 migrate # built-in Kysely adapter (pg, mysql2, SQLite) -npx auth@1.7.14 generate # Prisma or Drizzle; then run your ORM's migration -npx auth@1.7.14 check schema # should print "Schema check passed against the live database." +npx auth@1.7.17 migrate # built-in Kysely adapter (pg, mysql2, SQLite) +npx auth@1.7.17 generate # Prisma or Drizzle; then run your ORM's migration +npx auth@1.7.17 check schema # should print "Schema check passed against the live database." ``` Upgrading from v2? Run it anyway: v3 adds an index on `user.telegramId`. In OIDC-only mode the plugin adds no columns, so a mismatch there comes from Better Auth's own tables. More: [Installation: database](./installation.md#3-update-your-database). @@ -358,7 +358,7 @@ Check these: 1. **The user existed before.** Mapped values are stored when the user is created. Set `oidc.updateUserInfoOnSignIn: true` to also write them at every sign-in. 2. **The field is declared on the server**, in `betterAuth({ user: { additionalFields } })`. Declaring it only on the client (`inferAdditionalFields`) isn't enough: Better Auth drops unknown fields. -3. **The field accepts input.** Fields with `input: false` are dropped, like on any OAuth sign-up. Keep roles, membership and other authorization fields server-owned; do not enable input just to populate them from a mapper. See [Custom user data](./configuration.md#custom-user-data). +3. **The field accepts input.** Fields with `input: false` are dropped, like on any OAuth sign-up. Keep roles, membership and other authorization fields server-owned; do not enable input just to populate them from a mapper. Use the [server-owned fields recipe](./server-owned-fields.md) for a trusted application lookup without `customSession`. `returned: true` includes a stored value; it does not fill it. 4. **`oidc.overrideUserInfoOnSignIn` is ignored** (the plugin warns at startup). Use `updateUserInfoOnSignIn`. 5. **The mapper is async and the plugin is older than 3.1.1.** Before 3.1.1 an async mapper (OIDC, Login Widget or Mini App) lost every field it returned, and an error it threw didn't stop the sign-in. Upgrade. diff --git a/examples/nextjs-app/auth.ts b/examples/nextjs-app/auth.ts index 5c9cbc6..f6650ed 100644 --- a/examples/nextjs-app/auth.ts +++ b/examples/nextjs-app/auth.ts @@ -6,7 +6,7 @@ import { telegram } from "better-auth-telegram"; import { Pool } from "pg"; export const auth = betterAuth({ - // Better Auth's built-in Kysely adapter; run `npx auth@1.7.14 migrate`. + // Better Auth's built-in Kysely adapter; run `npx auth@1.7.17 migrate`. database: new Pool({ connectionString: process.env.DATABASE_URL }), plugins: [ diff --git a/package-lock.json b/package-lock.json index 69e7420..1f8b12c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,23 +1,23 @@ { "name": "better-auth-telegram", - "version": "3.2.1", + "version": "3.2.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "better-auth-telegram", - "version": "3.2.1", + "version": "3.2.2", "license": "MIT", "dependencies": { "jose": "^6.2.14" }, "devDependencies": { "@arethetypeswrong/core": "0.18.5", - "@better-auth/core": "1.7.14", - "@better-auth/drizzle-adapter": "1.7.14", - "@better-auth/kysely-adapter": "1.7.14", - "@better-auth/mongo-adapter": "1.7.14", - "@better-auth/prisma-adapter": "1.7.14", + "@better-auth/core": "1.7.17", + "@better-auth/drizzle-adapter": "1.7.17", + "@better-auth/kysely-adapter": "1.7.17", + "@better-auth/mongo-adapter": "1.7.17", + "@better-auth/prisma-adapter": "1.7.17", "@biomejs/biome": "2.6.4", "@prisma/adapter-pg": "7.10.1", "@prisma/client": "7.10.1", @@ -25,8 +25,8 @@ "@types/pg": "8.23.1", "@vitest/coverage-v8": "5.0.5", "@vitest/ui": "5.0.5", - "auth": "1.7.14", - "better-auth": "1.7.14", + "auth": "1.7.17", + "better-auth": "1.7.17", "drizzle-kit": "0.31.11", "drizzle-orm": "0.45.4", "happy-dom": "21.0.4", @@ -45,8 +45,8 @@ "node": ">=24.0.0" }, "peerDependencies": { - "@better-auth/core": ">=1.7.12 <1.8.0", - "better-auth": ">=1.7.12 <1.8.0" + "@better-auth/core": ">=1.7.17 <1.8.0", + "better-auth": ">=1.7.17 <1.8.0" } }, "node_modules/@andrewbranch/untar.js": { @@ -671,9 +671,9 @@ } }, "node_modules/@better-auth/core": { - "version": "1.7.14", - "resolved": "https://registry.npmjs.org/@better-auth/core/-/core-1.7.14.tgz", - "integrity": "sha512-ByhdrGVwp/el+hoTYKSVOHIH23/lQj9TQ1txdGcWOg22tnfr3hJ6ukzySooeYj/R36XsQgBhkJqIp8mKsNeErA==", + "version": "1.7.17", + "resolved": "https://registry.npmjs.org/@better-auth/core/-/core-1.7.17.tgz", + "integrity": "sha512-GB3OtOjNfeOKxKOQByXLdj3CNNDbZ65HdbfHSZhoLI6VzlURlb2VXMFnf05NE8fhDoytXY+zlbqTcwaWKTS7/g==", "dev": true, "license": "MIT", "dependencies": { @@ -684,7 +684,7 @@ "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.3", "@opentelemetry/api": "^1.9.0", - "better-call": "1.4.4", + "better-call": "1.4.5", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" @@ -696,13 +696,13 @@ } }, "node_modules/@better-auth/drizzle-adapter": { - "version": "1.7.14", - "resolved": "https://registry.npmjs.org/@better-auth/drizzle-adapter/-/drizzle-adapter-1.7.14.tgz", - "integrity": "sha512-5RC8Ec5Ur15FWsS4As9/VrlRbB3+9EfShxIpA5A1FcD6IgPxFvzQNkAm2+FYx9LUSqx47NPf9hBTG2GUCMP9Ig==", + "version": "1.7.17", + "resolved": "https://registry.npmjs.org/@better-auth/drizzle-adapter/-/drizzle-adapter-1.7.17.tgz", + "integrity": "sha512-A63iAB9tZLw/HU2bwf+FNwd3Hm5dzoNULOJckzPVMnddf0hO/gnjM94D/yVuu7w9cg8QTVAV7Zu3ehz1lKnX9A==", "dev": true, "license": "MIT", "peerDependencies": { - "@better-auth/core": "^1.7.14", + "@better-auth/core": "^1.7.17", "@better-auth/utils": "^0.4.2 || ^0.5.0", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0" }, @@ -713,13 +713,13 @@ } }, "node_modules/@better-auth/kysely-adapter": { - "version": "1.7.14", - "resolved": "https://registry.npmjs.org/@better-auth/kysely-adapter/-/kysely-adapter-1.7.14.tgz", - "integrity": "sha512-4wkqj8a8JVpWDYLlgzfbk7eOaWCFkL6HHQd6CLamFKaC8vNsXew1x4v5dE5O6dGr8j4g5qMISS+BAvOuIvBevg==", + "version": "1.7.17", + "resolved": "https://registry.npmjs.org/@better-auth/kysely-adapter/-/kysely-adapter-1.7.17.tgz", + "integrity": "sha512-YPBdzMtwky0p3Jwbp6FmO7CnREOkxXJklwJsm2Hl6MN4qF+AY7T61Wq3IZ784BP7fmW7AaSPjkTe4+OGrFz1mQ==", "dev": true, "license": "MIT", "peerDependencies": { - "@better-auth/core": "^1.7.14", + "@better-auth/core": "^1.7.17", "@better-auth/utils": "^0.4.2 || ^0.5.0", "kysely": "^0.28.17 || ^0.29.0" }, @@ -730,24 +730,24 @@ } }, "node_modules/@better-auth/memory-adapter": { - "version": "1.7.14", - "resolved": "https://registry.npmjs.org/@better-auth/memory-adapter/-/memory-adapter-1.7.14.tgz", - "integrity": "sha512-Ojv9BcmFyHuTHha9ZM/NUW1ut9J84wLngta+07Es0Ejn8kekqP5aHBpZd5Z8AvADs5iJUOWvQGFmGlPWAKJgBg==", + "version": "1.7.17", + "resolved": "https://registry.npmjs.org/@better-auth/memory-adapter/-/memory-adapter-1.7.17.tgz", + "integrity": "sha512-nEFRisxbSy1i3nmP0mqR5kwtNpYWSOqcdT+0axcPHeGK7DIeN6lpc5bEoPIkxPcSTyDzv0K67jlt1A60wGUY4g==", "dev": true, "license": "MIT", "peerDependencies": { - "@better-auth/core": "^1.7.14", + "@better-auth/core": "^1.7.17", "@better-auth/utils": "^0.4.2 || ^0.5.0" } }, "node_modules/@better-auth/mongo-adapter": { - "version": "1.7.14", - "resolved": "https://registry.npmjs.org/@better-auth/mongo-adapter/-/mongo-adapter-1.7.14.tgz", - "integrity": "sha512-6IA0RSPZFMdRwwnLZ9oWnDIiD0y0o0azTHUfa01BNU2AFJgMDkeiASUV3bKcJBskzQoyQrff74eFYTsTSeeVUQ==", + "version": "1.7.17", + "resolved": "https://registry.npmjs.org/@better-auth/mongo-adapter/-/mongo-adapter-1.7.17.tgz", + "integrity": "sha512-Pu6rutW9h3K+pUiiDCtedjdPgD/62cYScKCM04az8g7SGVDJVAWF73ly3cN2EflYnLs96yp68e4zAnr0XJDgsQ==", "dev": true, "license": "MIT", "peerDependencies": { - "@better-auth/core": "^1.7.14", + "@better-auth/core": "^1.7.17", "@better-auth/utils": "^0.4.2 || ^0.5.0", "mongodb": "^6.0.0 || ^7.0.0" }, @@ -758,13 +758,13 @@ } }, "node_modules/@better-auth/prisma-adapter": { - "version": "1.7.14", - "resolved": "https://registry.npmjs.org/@better-auth/prisma-adapter/-/prisma-adapter-1.7.14.tgz", - "integrity": "sha512-mF6t5xqeZNWzUe0ErmrSdzQmtslJscmu9X8Mp5QmROlpnnAzvSc70RILu8lHms8CePt7N34+KRH1QvYjGFrVGQ==", + "version": "1.7.17", + "resolved": "https://registry.npmjs.org/@better-auth/prisma-adapter/-/prisma-adapter-1.7.17.tgz", + "integrity": "sha512-gxowKIc8X8fUDPikuN+kWtfcGjXcy6CY/dpxJecSBDCn61g+T0AJdQpUzu7KhkjfYyw/ADxk7xtAc00tR7BoFA==", "dev": true, "license": "MIT", "peerDependencies": { - "@better-auth/core": "^1.7.14", + "@better-auth/core": "^1.7.17", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" @@ -779,13 +779,13 @@ } }, "node_modules/@better-auth/telemetry": { - "version": "1.7.14", - "resolved": "https://registry.npmjs.org/@better-auth/telemetry/-/telemetry-1.7.14.tgz", - "integrity": "sha512-PtKFzsH7gje/WJuUPDjckOoNFazsq8NMt3AdiXIPzHl7tZULcNGTKAX8K7+yn0rG6cO/4mtMgpOjhtilElOnmg==", + "version": "1.7.17", + "resolved": "https://registry.npmjs.org/@better-auth/telemetry/-/telemetry-1.7.17.tgz", + "integrity": "sha512-VhBBYBBtSK6tZlEdc5MwV6L/8HHjuGIns9QmlhqxiCk2xA4ILAVXo7O9S1iltxqe+H8gUKh5jbpY9hriW88MeQ==", "dev": true, "license": "MIT", "peerDependencies": { - "@better-auth/core": "^1.7.14", + "@better-auth/core": "^1.7.17", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.3" } @@ -4089,21 +4089,21 @@ } }, "node_modules/auth": { - "version": "1.7.14", - "resolved": "https://registry.npmjs.org/auth/-/auth-1.7.14.tgz", - "integrity": "sha512-a3g2oaGjzq/fG9jGEMjQGcDzSM9oyhmGFL+ZbsPDT31WQ3BjZLlNkgGJpTYwwZE8pLDGa6N8sAiKQ8WGTzdfiQ==", + "version": "1.7.17", + "resolved": "https://registry.npmjs.org/auth/-/auth-1.7.17.tgz", + "integrity": "sha512-jbK37gqqscPdoDzIwbjLhja03bx2w4ky5871uy2IitTDWJx2U+KXCnBeISP74TIjXldK4jWUgjGRxZeSYVlRcg==", "dev": true, "license": "MIT", "dependencies": { "@babel/core": "^7.29.7", "@babel/preset-react": "^7.28.5", "@babel/preset-typescript": "^7.28.5", - "@better-auth/core": "1.7.14", - "@better-auth/telemetry": "1.7.14", + "@better-auth/core": "1.7.17", + "@better-auth/telemetry": "1.7.17", "@better-auth/utils": "0.5.1", "@clack/prompts": "^1.6.0", "@mrleebo/prisma-ast": "^0.16.0", - "better-auth": "1.7.14", + "better-auth": "1.7.17", "c12": "^4.0.0-beta.5", "chalk": "^5.6.2", "commander": "^15.0.0", @@ -4162,24 +4162,24 @@ } }, "node_modules/better-auth": { - "version": "1.7.14", - "resolved": "https://registry.npmjs.org/better-auth/-/better-auth-1.7.14.tgz", - "integrity": "sha512-QxDCI0pOCCHDYmruisKhKyrvOJ6Icv9xg0RA6ZUysfKFXENYwhNNpwUlkE/NmViH2nDMgkKcymmLr55pnpR9vw==", + "version": "1.7.17", + "resolved": "https://registry.npmjs.org/better-auth/-/better-auth-1.7.17.tgz", + "integrity": "sha512-jLPt758k4R3kzCE2ie5BV2FXiLtpbINyC6e/OkcZK0aQOAnZdE2oLZofK1cZg3oXVd2GCFo47gnMy7sgykfUhQ==", "dev": true, "license": "MIT", "dependencies": { - "@better-auth/core": "1.7.14", - "@better-auth/drizzle-adapter": "1.7.14", - "@better-auth/kysely-adapter": "1.7.14", - "@better-auth/memory-adapter": "1.7.14", - "@better-auth/mongo-adapter": "1.7.14", - "@better-auth/prisma-adapter": "1.7.14", - "@better-auth/telemetry": "1.7.14", + "@better-auth/core": "1.7.17", + "@better-auth/drizzle-adapter": "1.7.17", + "@better-auth/kysely-adapter": "1.7.17", + "@better-auth/memory-adapter": "1.7.17", + "@better-auth/mongo-adapter": "1.7.17", + "@better-auth/prisma-adapter": "1.7.17", + "@better-auth/telemetry": "1.7.17", "@better-auth/utils": "0.5.1", "@better-fetch/fetch": "1.3.3", "@noble/ciphers": "^2.2.0", "@noble/hashes": "^2.2.0", - "better-call": "1.4.4", + "better-call": "1.4.5", "defu": "^6.1.4", "jose": "^6.2.3", "kysely": "^0.28.17 || ^0.29.0", @@ -4264,9 +4264,9 @@ } }, "node_modules/better-call": { - "version": "1.4.4", - "resolved": "https://registry.npmjs.org/better-call/-/better-call-1.4.4.tgz", - "integrity": "sha512-Gq4XdGFy4dmUxFEAX2nj0ycFcFbD9ZWh8YROouZoyXeF1M11TpYbplk0pDByTFF8Wz+MYa6W9052c9m7dD+mfw==", + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/better-call/-/better-call-1.4.5.tgz", + "integrity": "sha512-GVOWfn3pjEfUXn6GrfGf2h7tPAqj1oMLFBWBEswJrSkDKcLk6TIcjV0zexibcZZ0c5N1mkLMsPFopXWzWj/gDQ==", "dev": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index fc910f9..f798c10 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "better-auth-telegram", - "version": "3.2.1", + "version": "3.2.2", "description": "Telegram authentication plugin for Better Auth", "keywords": [ "better-auth", @@ -79,11 +79,11 @@ }, "devDependencies": { "@arethetypeswrong/core": "0.18.5", - "@better-auth/core": "1.7.14", - "@better-auth/drizzle-adapter": "1.7.14", - "@better-auth/kysely-adapter": "1.7.14", - "@better-auth/mongo-adapter": "1.7.14", - "@better-auth/prisma-adapter": "1.7.14", + "@better-auth/core": "1.7.17", + "@better-auth/drizzle-adapter": "1.7.17", + "@better-auth/kysely-adapter": "1.7.17", + "@better-auth/mongo-adapter": "1.7.17", + "@better-auth/prisma-adapter": "1.7.17", "@biomejs/biome": "2.6.4", "@prisma/adapter-pg": "7.10.1", "@prisma/client": "7.10.1", @@ -91,8 +91,8 @@ "@types/pg": "8.23.1", "@vitest/coverage-v8": "5.0.5", "@vitest/ui": "5.0.5", - "auth": "1.7.14", - "better-auth": "1.7.14", + "auth": "1.7.17", + "better-auth": "1.7.17", "drizzle-kit": "0.31.11", "drizzle-orm": "0.45.4", "happy-dom": "21.0.4", @@ -108,8 +108,8 @@ "vitest": "5.0.5" }, "peerDependencies": { - "@better-auth/core": ">=1.7.12 <1.8.0", - "better-auth": ">=1.7.12 <1.8.0" + "@better-auth/core": ">=1.7.17 <1.8.0", + "better-auth": ">=1.7.17 <1.8.0" }, "engines": { "node": ">=24.0.0" diff --git a/src/better-auth-config.integration.test.ts b/src/better-auth-config.integration.test.ts index 458a3ed..bbb6fd8 100644 --- a/src/better-auth-config.integration.test.ts +++ b/src/better-auth-config.integration.test.ts @@ -237,6 +237,59 @@ describe("session.cookieCache", () => { expect(linked.json.user.telegramId).toBe("42"); expect(unlinked.json.user.telegramId ?? null).toBeNull(); }); + + it.each(["link", "unlink"] as const)( + "refuses to %s using a revoked session's still-valid cookie cache", + async (action) => { + const { auth, client, rows } = await createSqliteAuth({}, cached); + const signUpResponse = await client.post("/sign-up/email", { + email: "ann@example.com", + password: "correct-horse-battery", + name: "Ann", + }); + expect(signUpResponse.status).toBe(200); + if (action === "unlink") { + const initialLink = await client.post( + "/telegram/link", + await signWidgetData({ id: 42 }) + ); + if (initialLink.status !== 200) { + throw new Error(`Initial link failed: ${initialLink.status}`); + } + } + const otherDevice = createClient(auth); + const signIn = await otherDevice.post("/sign-in/email", { + email: "ann@example.com", + password: "correct-horse-battery", + }); + expect(signIn.status).toBe(200); + const revoke = await otherDevice.post("/revoke-session", { + token: signUpResponse.json.token, + }); + expect(revoke.status).toBe(200); + expect(rows("session").map((session) => session.token)).not.toContain( + signUpResponse.json.token + ); + // Ordinary reads can still use the cache; changing logins must check storage. + const staleSession = await client.get("/get-session"); + expect(staleSession.json.user.id).toBe(signUpResponse.json.user.id); + + const change = await client.post( + `/telegram/${action}`, + action === "link" ? await signWidgetData({ id: 42 }) : {} + ); + + expect(change.status).toBe(401); + expect(change.json.code).toBe("UNAUTHORIZED"); + expect(rows("account").map((account) => account.providerId)).toEqual([ + "credential", + ...(action === "unlink" ? ["telegram"] : []), + ]); + expect(rows("user")[0]!.telegramId).toBe( + action === "unlink" ? "42" : null + ); + } + ); }); describe("custom table and column names", () => { diff --git a/src/client-lifecycle.integration.test.ts b/src/client-lifecycle.integration.test.ts index 2440db3..74a14c5 100644 --- a/src/client-lifecycle.integration.test.ts +++ b/src/client-lifecycle.integration.test.ts @@ -1,9 +1,12 @@ // @vitest-environment happy-dom +import { createAuthClient } from "better-auth/client"; import { afterEach, expect, it as test, vi } from "vitest"; +import { telegramClient } from "./client"; import { createTelegramWidgetActions, type TelegramWidget, } from "./client-widget"; +import { BASE_URL, createMemoryAuth } from "./testing/harness"; import type { TelegramAuthData } from "./types"; const handles: TelegramWidget[] = []; @@ -37,6 +40,37 @@ afterEach(() => { vi.unstubAllGlobals(); }); +test("renders the widget when the auth client uses throwing fetch responses", async () => { + (window as any).Telegram = { Login: {} }; + const host = document.createElement("div"); + document.body.appendChild(host); + const { auth } = createMemoryAuth(); + const client = createAuthClient({ + baseURL: BASE_URL, + plugins: [telegramClient()], + fetchOptions: { + throw: true, + customFetchImpl: (input, init) => auth.handler(new Request(input, init)), + }, + }); + const onAuth = vi.fn(); + + const widget = await client.initTelegramWidget(host, {}, onAuth); + handles.push(widget); + const user: TelegramAuthData = { + id: 42, + first_name: "Ann", + auth_date: 1, + hash: "x", + }; + await callbackFrom(host)(user); + + expect(onAuth).toHaveBeenCalledExactlyOnceWith(user); + expect( + host.querySelector("script")!.getAttribute("data-telegram-login") + ).toBe("test_bot"); +}); + test.each(["callback", "redirect"] as const)( "keeps the newest requested widget when an older %s configuration arrives last", async (mode) => { diff --git a/src/client-widget.ts b/src/client-widget.ts index 757474c..e598259 100644 --- a/src/client-widget.ts +++ b/src/client-widget.ts @@ -127,7 +127,9 @@ async function renderWidget( const configResponse = await $fetch( "/telegram/config", - { method: "GET" } + // The renderer handles errors itself and needs the response envelope, + // even when the auth client defaults to `throw: true`. + { method: "GET", throw: false } ); if (pendingRenders.get(element) !== request) { return null; diff --git a/src/client.integration.test.ts b/src/client.integration.test.ts index 7c71520..7eadc10 100644 --- a/src/client.integration.test.ts +++ b/src/client.integration.test.ts @@ -107,6 +107,22 @@ describe("client actions against the real server", () => { expect(error?.code).toBe("CANNOT_UNLINK_LAST_ACCOUNT"); }); + it("the generated unlink route sends POST even without a request body", async () => { + const { client, db, requests, signUp } = setup(); + await signUp(); + await client.linkTelegram((await signWidgetData({ id: 42 })) as any); + + const response = await (client as any).telegram.unlink(); + + expect(response.error).toBeNull(); + expect(response.data.success).toBe(true); + expect(requests.at(-1)!.method).toBe("POST"); + expect(db.account.map((account) => account.providerId)).toEqual([ + "credential", + ]); + expect(db.user[0]!.telegramId).toBeNull(); + }); + it("getTelegramConfig returns the server's bot username", async () => { const { client } = setup(); diff --git a/src/client.ts b/src/client.ts index 3a53d86..8bccc53 100644 --- a/src/client.ts +++ b/src/client.ts @@ -63,6 +63,10 @@ export const telegramClient = () => { $InferServerPlugin: {} as ReturnType, $ERROR_CODES: TELEGRAM_ERROR_CODES, + pathMethods: { + "/telegram/unlink": "POST", + }, + // Refreshes `useSession` after the generated routes // (`authClient.telegram.signin(...)`), like Better Auth's own plugins. atomListeners: [ diff --git a/src/identity-transitions.adapter.test.ts b/src/identity-transitions.adapter.test.ts index 47d33eb..cb09a50 100644 --- a/src/identity-transitions.adapter.test.ts +++ b/src/identity-transitions.adapter.test.ts @@ -1,7 +1,12 @@ // @vitest-environment node import { afterEach, describe, expect, it as test } from "vitest"; import { type AdapterAuth, adapterLanes } from "./testing/adapters"; -import { signInitData, signWidgetData } from "./testing/harness"; +import { + mockTelegramOIDC, + signInitData, + signInWithTelegramOIDC, + signWidgetData, +} from "./testing/harness"; describe.each(adapterLanes())("$name identity authority", (lane) => { let fixture: AdapterAuth | undefined; @@ -11,6 +16,39 @@ describe.each(adapterLanes())("$name identity authority", (lane) => { }); describe.skipIf(!lane.url)("persisted account proof", () => { + test("does not issue an OIDC session after a creation hook revokes the committed account", async () => { + const provider = await mockTelegramOIDC(); + try { + fixture = await lane.create( + { + loginWidget: false, + oidc: { enabled: true, clientSecret: provider.clientSecret }, + }, + { + databaseHooks: { + account: { + create: { + after: async (account, ctx) => { + await ctx!.context.internalAdapter.deleteAccount( + account.id + ); + }, + }, + }, + }, + } + ); + const { client, rows } = fixture; + const { location } = await signInWithTelegramOIDC(client, provider); + expect(location).toContain("error=ACCOUNT_NOT_LINKED"); + expect(await rows("account")).toHaveLength(0); + expect(await rows("session")).toHaveLength(0); + expect(client.hasSession()).toBe(false); + } finally { + provider.restore(); + } + }); + test("refuses conflicting owners beyond same-owner duplicate rows", async () => { fixture = await lane.create({ miniApp: { enabled: true } }); const { auth, client, rows } = fixture; diff --git a/src/identity.integration.test.ts b/src/identity.integration.test.ts index a3c1388..aaeb11e 100644 --- a/src/identity.integration.test.ts +++ b/src/identity.integration.test.ts @@ -182,10 +182,17 @@ describe("verified OIDC claims only apply to the user they prove", () => { await signUp(bobClient, "bob@example.com"); state.bob = db.user.find((user) => user.email === "bob@example.com")!.id; client.clearCookies(); + const bobSessionsBefore = db.session.filter( + (session) => session.userId === state.bob + ).length; - await signInWithTelegramOIDC(client, telegramMock); + const { location } = await signInWithTelegramOIDC(client, telegramMock); + expect(location).toBe("/dashboard"); expect(state.done).toBe(true); + expect( + db.session.filter((session) => session.userId === state.bob) + ).toHaveLength(bobSessionsBefore + 1); const bob = db.user.find((user) => user.id === state.bob)!; expect(bob.telegramId ?? null).toBeNull(); }); diff --git a/src/index.ts b/src/index.ts index 4a5d3fa..d2713bd 100644 --- a/src/index.ts +++ b/src/index.ts @@ -71,9 +71,10 @@ export const telegram = (options: TelegramPluginOptions) => { ? { context: { socialProviders: [ - config.widgetEnabled || config.miniAppEnabled - ? withTelegramIdentityLinking(provider) - : provider, + withTelegramIdentityLinking( + provider, + config.widgetEnabled || config.miniAppEnabled + ), ...ctx.socialProviders, ], }, diff --git a/src/oidc-linking.ts b/src/oidc-linking.ts index a0e2c66..dd1419b 100644 --- a/src/oidc-linking.ts +++ b/src/oidc-linking.ts @@ -14,6 +14,7 @@ import { validateTelegramOIDCLink, } from "./oidc-linking-policy"; import { withTelegramOperation } from "./telegram-account"; +import { currentSignIn } from "./telegram-identity-state"; import type { TelegramOIDCClaims } from "./types"; async function linkVerifiedIdentity( @@ -136,7 +137,8 @@ async function linkVerifiedIdentity( * explicit linkSocial and account-info requests retain their native behavior. */ export function withTelegramIdentityLinking( - provider: OAuthProvider + provider: OAuthProvider, + identityFields: boolean ): OAuthProvider { return { ...provider, @@ -154,12 +156,31 @@ export function withTelegramIdentityLinking( current.body?.provider === TELEGRAM_OIDC_PROVIDER_ID && !!current.body?.idToken; if ((isCallback && !(await getOAuthState())?.link) || isTokenSignIn) { - await linkVerifiedIdentity( - current as GenericEndpointContext, - result.data, - result.user, - tokens - ); + if (identityFields) { + await linkVerifiedIdentity( + current as GenericEndpointContext, + result.data, + result.user, + tokens + ); + } + const signIn = await currentSignIn(); + if (signIn) { + // Snapshot an unambiguous owner; Better Auth's own lookup rejects + // duplicate identities through its normal callback error handling. + const accounts = await ( + await getCurrentAdapter(current.context.adapter) + ).findMany({ + model: "account", + where: [ + { field: "providerId", value: TELEGRAM_OIDC_PROVIDER_ID }, + { field: "accountId", value: result.data.sub }, + ], + limit: 2, + }); + signIn.expectedUserId ??= + accounts.length === 1 ? accounts[0]!.userId : undefined; + } } return result; }, diff --git a/src/oidc-revocation.integration.test.ts b/src/oidc-revocation.integration.test.ts new file mode 100644 index 0000000..cfcc91b --- /dev/null +++ b/src/oidc-revocation.integration.test.ts @@ -0,0 +1,209 @@ +// @vitest-environment node +import { afterEach, beforeEach, expect, it as test } from "vitest"; +import { + createMemoryAuth, + mockTelegramOIDC, + signInWithTelegramOIDC, + type TelegramOIDCMock, + type TestClient, + telegramClaims, +} from "./testing/harness"; + +let provider: TelegramOIDCMock; +beforeEach(async () => { + provider = await mockTelegramOIDC(); +}); +afterEach(() => provider.restore()); + +async function attemptSignIn(client: TestClient, method: string) { + if (method === "redirect") { + const { callback, location } = await signInWithTelegramOIDC( + client, + provider + ); + return { + status: callback.status, + error: new URL(location!, "https://example.test").searchParams.get( + "error" + ), + }; + } + const token = await provider.sign({ + sub: "12224742808376279442", + nonce: "n-1", + }); + const response = await client.post("/sign-in/social", { + provider: "telegram-oidc", + idToken: { token, nonce: "n-1" }, + }); + return { status: response.status, error: response.json.code }; +} + +test.each([ + { loginWidget: false, method: "redirect", status: 302 }, + { loginWidget: true, method: "redirect", status: 302 }, + { loginWidget: false, method: "idToken", status: 401 }, + { loginWidget: true, method: "idToken", status: 401 }, +])( + "refuses a revoked OIDC account: $method, loginWidget=$loginWidget", + async ({ loginWidget, method, status }) => { + const { client, db } = createMemoryAuth( + { + loginWidget, + oidc: { enabled: true, clientSecret: provider.clientSecret }, + }, + { + account: { updateAccountOnSignIn: false }, + user: { + validateUserInfo: async ({ user, source }, ctx) => { + if (source.method === "oauth" && source.action === "sign-in") { + const accounts = await ctx.context.internalAdapter.findAccounts( + user.id! + ); + const account = accounts.find( + (candidate) => candidate.providerId === "telegram-oidc" + )!; + await ctx.context.internalAdapter.deleteAccount(account.id); + } + }, + }, + } + ); + const first = await signInWithTelegramOIDC(client, provider); + expect(first.location).toBe("/dashboard"); + client.clearCookies(); + const sessionCount = db.session.length; + const outcome = await attemptSignIn(client, method); + + expect(outcome).toEqual({ status, error: "ACCOUNT_NOT_LINKED" }); + expect(db.account).toHaveLength(0); + expect(db.session).toHaveLength(sessionCount); + expect(client.hasSession()).toBe(false); + } +); + +test("does not issue a first OIDC session after an account creation hook revokes the account", async () => { + const { client, db } = createMemoryAuth( + { + loginWidget: false, + oidc: { enabled: true, clientSecret: provider.clientSecret }, + }, + { + databaseHooks: { + account: { + create: { + after: async (account, ctx) => { + await ctx!.context.internalAdapter.deleteAccount(account.id); + }, + }, + }, + }, + } + ); + await signInWithTelegramOIDC(client, provider); + expect(db.account).toHaveLength(0); + expect(db.session).toHaveLength(0); + expect(client.hasSession()).toBe(false); +}); + +test("refuses a revoked OIDC account after an optional profile update", async () => { + const { client, db } = createMemoryAuth( + { + loginWidget: false, + oidc: { + enabled: true, + clientSecret: provider.clientSecret, + updateUserInfoOnSignIn: true, + }, + }, + { + databaseHooks: { + user: { + update: { + before: async (_user, ctx) => { + const account = + await ctx!.context.internalAdapter.findAccountByKey({ + providerId: "telegram-oidc", + accountId: "12224742808376279442", + }); + await ctx!.context.internalAdapter.deleteAccount(account!.id); + return false; + }, + }, + }, + }, + } + ); + expect((await signInWithTelegramOIDC(client, provider)).location).toBe( + "/dashboard" + ); + client.clearCookies(); + const sessionsBefore = structuredClone(db.session); + const { location } = await signInWithTelegramOIDC( + client, + provider, + telegramClaims({ name: "Updated name" }) + ); + expect(db.account).toHaveLength(0); + expect(db.session).toEqual(sessionsBefore); + expect(client.hasSession()).toBe(false); + expect(location).toContain("error=ACCOUNT_NOT_LINKED"); +}); + +test.each([ + { loginWidget: false, field: "userId" }, + { loginWidget: true, field: "userId" }, + { loginWidget: false, field: "accountId" }, + { loginWidget: true, field: "accountId" }, + { loginWidget: false, field: "providerId" }, + { loginWidget: true, field: "providerId" }, +])( + "refuses a new OIDC binding changed by an account hook: $field, loginWidget=$loginWidget", + async ({ loginWidget, field }) => { + let otherUserId: string; + const { auth, client, db } = createMemoryAuth( + { + loginWidget, + oidc: { enabled: true, clientSecret: provider.clientSecret }, + }, + { + databaseHooks: { + account: { + create: { + before: (account) => + Promise.resolve( + account.providerId === "telegram-oidc" + ? { + data: { + [field]: + field === "userId" ? otherUserId : "another-key", + }, + } + : undefined + ), + }, + }, + }, + } + ); + const other = await (await auth.$context).internalAdapter.createUser( + { + name: "Other user", + email: "other@example.com", + emailVerified: false, + }, + { method: "email-password" } + ); + otherUserId = other.id; + const otherBefore = structuredClone(db.user[0]); + + const { location } = await signInWithTelegramOIDC(client, provider); + + expect(location).toContain("error=ACCOUNT_NOT_LINKED"); + expect(client.hasSession()).toBe(false); + expect(db.session).toHaveLength(0); + expect(db.user.find((user) => user.id === otherUserId)).toEqual( + otherBefore + ); + } +); diff --git a/src/oidc-server-owned.integration.test.ts b/src/oidc-server-owned.integration.test.ts new file mode 100644 index 0000000..a39c7bd --- /dev/null +++ b/src/oidc-server-owned.integration.test.ts @@ -0,0 +1,236 @@ +// @vitest-environment node +import { defineRequestState } from "@better-auth/core/context"; +import { betterAuth } from "better-auth"; +import { decodeJwt } from "jose"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + type AuthOptions, + baseOptions, + createClient, + mockTelegramOIDC, + signInWithTelegramOIDC, + type TelegramOIDCMock, + telegramClaims, +} from "./testing/harness"; + +let telegramMock: TelegramOIDCMock; +beforeEach(async () => { + telegramMock = await mockTelegramOIDC(); +}); +afterEach(() => telegramMock.restore()); + +const member = { + user_id: 42, + user_name: "Ann", + user_nick: "ann", + role: "member", +}; +type Member = typeof member; +const fields = { + user_id: { type: "number", required: false, input: false, returned: true }, + user_name: { type: "string", required: false, input: false, returned: true }, + user_nick: { type: "string", required: false, input: false, returned: true }, + role: { type: "string", required: false, input: false, returned: true }, +} as const; + +// docs/server-owned-fields.md: lookup from verified provider data, then a +// trusted database hook. The mapper must retain Better Auth's input boundary. +function memberOptions(lookup: (telegramId: string) => Promise) { + const verifiedMember = defineRequestState(() => null); + return { + user: { + additionalFields: fields, + async validateUserInfo({ source }) { + const telegramId = source.oauth?.profile?.id; + if ( + source.oauth?.providerId !== "telegram-oidc" || + typeof telegramId !== "string" + ) { + return { error: "telegram_required" }; + } + const found = await lookup(telegramId); + if (!found) { + return { error: "not_a_member" }; + } + await verifiedMember.set(found); + }, + }, + databaseHooks: { + user: { + create: { + async before() { + const found = await verifiedMember.get(); + if (!found) { + return false; + } + return { + data: { + user_id: found.user_id, + user_name: found.user_name, + user_nick: found.user_nick, + role: found.role, + }, + }; + }, + }, + }, + }, + } satisfies Partial; +} + +function authWith(extra: Partial) { + return betterAuth( + baseOptions( + { + loginWidget: false, + oidc: { + enabled: true, + clientSecret: telegramMock.clientSecret, + mapOIDCProfileToUser: async () => ({ role: "admin", user_id: 999 }), + }, + }, + { + ...extra, + session: { + expiresIn: 300, + cookieCache: { + enabled: true, + strategy: "jwt", + maxAge: 300, + refreshCache: false, + }, + }, + } + ) + ); +} + +describe("server-owned user fields in stateless OIDC (issue #53)", () => { + it("ignores mapper values for input:false, even with returned:true", async () => { + const client = createClient( + authWith({ user: { additionalFields: fields } }) + ); + const { location } = await signInWithTelegramOIDC(client, telegramMock); + expect(location).toBe("/dashboard"); + const session = await client.get("/get-session"); + expect(session.json.user).not.toHaveProperty("role"); + expect(session.json.user).not.toHaveProperty("user_id"); + }); + + it("carries trusted hook values in the JWT across instances and refuses client edits", async () => { + const lookup = vi.fn(async () => member); + const options = memberOptions(lookup); + const client = createClient(authWith(options)); + const { callback, location } = await signInWithTelegramOIDC( + client, + telegramMock + ); + expect(location).toBe("/dashboard"); + expect(lookup).toHaveBeenCalledExactlyOnceWith("8306595751"); + const cookies = callback.headers + .getSetCookie() + .map((cookie) => cookie.split(";")[0]!); + const jwt = cookies.find((cookie) => + cookie.startsWith("better-auth.session_data=") + )!; + expect( + decodeJwt(decodeURIComponent(jwt.slice(jwt.indexOf("=") + 1))).user + ).toMatchObject(member); + + const restarted = createClient(authWith(options)); + const session = await restarted.request("/get-session", { + headers: { cookie: cookies.join("; ") }, + }); + expect(session.json.user).toMatchObject(member); + const edit = await client.post("/update-user", { + role: "admin", + user_id: 999, + }); + expect(edit.status).toBe(400); + expect(edit.json.code).toBe("FIELD_NOT_ALLOWED"); + expect((await client.get("/get-session")).json.user).toMatchObject(member); + }); + + it("refuses an unknown application user before issuing a session", async () => { + const lookup = vi.fn(async (id: string) => + id === "8306595751" ? member : null + ); + const auth = authWith(memberOptions(lookup)); + const accepted = createClient(auth); + expect( + (await signInWithTelegramOIDC(accepted, telegramMock)).location + ).toBe("/dashboard"); + const rejected = createClient(auth); + const result = await signInWithTelegramOIDC( + rejected, + telegramMock, + telegramClaims({ sub: "another-subject", id: "456" }) + ); + expect(result.location).toContain("error=not_a_member"); + expect(rejected.hasSession()).toBe(false); + expect((await rejected.get("/get-session")).json).toBeNull(); + }); + + it("requires a new sign-in instead of rolling old member claims forward", async () => { + const lookup = vi.fn(async () => member); + const client = createClient(authWith(memberOptions(lookup))); + expect((await signInWithTelegramOIDC(client, telegramMock)).location).toBe( + "/dashboard" + ); + const issuedAt = Date.now(); + vi.useFakeTimers({ toFake: ["Date"] }); + try { + vi.setSystemTime(issuedAt + 250_000); + expect((await client.get("/get-session")).json.user).toMatchObject( + member + ); + vi.setSystemTime(issuedAt + 301_000); + expect((await client.get("/get-session")).json).toBeNull(); + expect(lookup).toHaveBeenCalledTimes(1); + } finally { + vi.useRealTimers(); + } + }); + + it("keeps trusted member fields separate across overlapping sign-ins", async () => { + const otherMember = { ...member, user_id: 84, role: "editor" }; + const options = memberOptions(async (id) => + id === "8306595751" ? member : otherMember + ); + const populate = options.databaseHooks.user.create.before; + let release!: () => void; + const bothValidated = new Promise((resolve) => { + release = resolve; + }); + let arrivals = 0; + options.databaseHooks.user.create.before = async () => { + arrivals += 1; + if (arrivals === 2) { + release(); + } + // Both validation callbacks have stored their member before either + // creation hook reads it. A shared mutable variable would mix them up. + await bothValidated; + return populate(); + }; + const auth = authWith(options); + const ann = createClient(auth); + const other = createClient(auth); + const results = await Promise.all([ + signInWithTelegramOIDC(ann, telegramMock), + signInWithTelegramOIDC( + other, + telegramMock, + telegramClaims({ sub: "another-subject", id: "456" }) + ), + ]); + expect(results.map((result) => result.location)).toEqual([ + "/dashboard", + "/dashboard", + ]); + expect((await ann.get("/get-session")).json.user).toMatchObject(member); + expect((await other.get("/get-session")).json.user).toMatchObject( + otherMember + ); + }); +}); diff --git a/src/oidc-session-claims.integration.test.ts b/src/oidc-session-claims.integration.test.ts new file mode 100644 index 0000000..a7a82b1 --- /dev/null +++ b/src/oidc-session-claims.integration.test.ts @@ -0,0 +1,178 @@ +// @vitest-environment node +import { defineRequestState } from "@better-auth/core/context"; +import { betterAuth } from "better-auth"; +import { decodeJwt } from "jose"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { + baseOptions, + createClient, + mockTelegramOIDC, + signInWithTelegramOIDC, + type TelegramOIDCMock, +} from "./testing/harness"; + +let provider: TelegramOIDCMock; +beforeEach(async () => { + provider = await mockTelegramOIDC(); +}); +afterEach(() => provider.restore()); + +const fields = { + role: { type: "string", required: false, input: false, returned: true }, + user_id: { type: "number", required: false, input: false, returned: true }, +} as const; + +function setup() { + const member = defineRequestState<{ role: string; user_id: number } | null>( + () => null + ); + const application = { role: "member", denied: false }; + const options = baseOptions( + { + loginWidget: false, + oidc: { enabled: true, clientSecret: provider.clientSecret }, + }, + { + user: { + additionalFields: fields, + async validateUserInfo({ source }) { + if ( + source.oauth?.providerId !== "telegram-oidc" || + typeof source.oauth.profile?.id !== "string" || + application.denied + ) { + return { error: "not_a_member" }; + } + await member.set({ role: application.role, user_id: 42 }); + }, + }, + session: { + cookieCache: { enabled: true, strategy: "jwt", refreshCache: false }, + additionalFields: fields, + }, + databaseHooks: { + user: { + create: { + async before() { + const found = await member.get(); + if (!found) { + return false; + } + return { data: { role: found.role, user_id: found.user_id } }; + }, + }, + }, + session: { + create: { + async before() { + const found = await member.get(); + if (!found) { + return false; + } + return { data: { role: found.role, user_id: found.user_id } }; + }, + }, + }, + }, + } + ); + const auth = betterAuth(options); + return { auth, application, client: createClient(auth), options }; +} + +function jwtCookie(headers: Headers) { + const cookies = headers + .getSetCookie() + .map((rawCookie) => rawCookie.split(";")[0]!); + const cookie = cookies.find((value) => + value.startsWith("better-auth.session_data=") + )!; + return { + cookies, + payload: decodeJwt( + decodeURIComponent(cookie.slice(cookie.indexOf("=") + 1)) + ), + }; +} + +describe("fresh server-owned session claims without a database", () => { + it("refreshes per-login claims while the same user's creation snapshot stays unchanged", async () => { + const { client, application } = setup(); + expect((await signInWithTelegramOIDC(client, provider)).location).toBe( + "/dashboard" + ); + const first = (await client.get("/get-session")).json; + expect(first.user).toMatchObject({ role: "member", user_id: 42 }); + expect(first.session).toMatchObject({ role: "member", user_id: 42 }); + client.clearCookies(); + application.role = "editor"; + + const second = await signInWithTelegramOIDC(client, provider); + const current = (await client.get("/get-session")).json; + expect(second.location).toBe("/dashboard"); + expect(current.user).toMatchObject({ + id: first.user.id, + role: "member", + user_id: 42, + }); + expect(current.session).toMatchObject({ role: "editor", user_id: 42 }); + const { payload } = jwtCookie(second.callback.headers); + expect(payload.user).toMatchObject({ + id: first.user.id, + role: "member", + user_id: 42, + }); + expect(payload.session).toMatchObject({ role: "editor", user_id: 42 }); + }); + + it("keeps the issued session claims readable on another auth instance", async () => { + const { client, options } = setup(); + const result = await signInWithTelegramOIDC(client, provider); + expect(result.location).toBe("/dashboard"); + const { cookies } = jwtCookie(result.callback.headers); + const reader = createClient(betterAuth(options)); + const response = await reader.request("/get-session", { + headers: { cookie: cookies.join("; ") }, + }); + expect(response.json.session).toMatchObject({ + role: "member", + user_id: 42, + }); + }); + + it("refuses generic API edits of the server-owned user and session fields", async () => { + const { client } = setup(); + expect((await signInWithTelegramOIDC(client, provider)).location).toBe( + "/dashboard" + ); + const edits = await Promise.all( + ["/update-session", "/update-user"].map((endpoint) => + client.post(endpoint, { role: "admin", user_id: 999 }) + ) + ); + for (const edit of edits) { + expect(edit.status).toBe(400); + expect(edit.json.code).toBe("FIELD_NOT_ALLOWED"); + } + const current = (await client.get("/get-session")).json; + expect(current.user).toMatchObject({ role: "member", user_id: 42 }); + expect(current.session).toMatchObject({ role: "member", user_id: 42 }); + }); + + it("creates no new session when the returning user is refused by the application", async () => { + const { auth, client, application } = setup(); + expect((await signInWithTelegramOIDC(client, provider)).location).toBe( + "/dashboard" + ); + const ctx = await auth.$context; + const before = await ctx.adapter.count({ model: "session" }); + client.clearCookies(); + application.denied = true; + + const refused = await signInWithTelegramOIDC(client, provider); + expect(refused.location).toContain("error=not_a_member"); + expect(await ctx.adapter.count({ model: "session" })).toBe(before); + expect(client.hasSession()).toBe(false); + expect((await client.get("/get-session")).json).toBeNull(); + }); +}); diff --git a/src/oidc-session-revocation.integration.test.ts b/src/oidc-session-revocation.integration.test.ts new file mode 100644 index 0000000..fb81f03 --- /dev/null +++ b/src/oidc-session-revocation.integration.test.ts @@ -0,0 +1,123 @@ +// @vitest-environment node +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { + createMemoryAuth, + mockTelegramOIDC, + type TelegramOIDCMock, + telegramClaims, +} from "./testing/harness"; + +let issuer: TelegramOIDCMock; +beforeEach(async () => { + issuer = await mockTelegramOIDC(); +}); +afterEach(() => issuer.restore()); + +async function signedInUser() { + const fixture = createMemoryAuth( + { + loginWidget: false, + oidc: { enabled: true, clientSecret: issuer.clientSecret }, + }, + { + emailAndPassword: { enabled: true }, + session: { cookieCache: { enabled: true, maxAge: 300 } }, + account: { + accountLinking: { + trustedProviders: ["telegram-oidc"], + allowDifferentEmails: true, + }, + }, + } + ); + const signup = await fixture.client.post("/sign-up/email", { + email: "ann@example.com", + password: "correct-horse-battery", + name: "Ann", + }); + if (signup.status !== 200) { + throw new Error(`Sign-up failed: ${signup.status} ${signup.text}`); + } + const session = await fixture.client.get("/get-session"); + if (session.json?.user.id !== fixture.db.user[0]!.id) { + throw new Error("Sign-up did not establish the expected session"); + } + const ctx = await fixture.auth.$context; + return { + ...fixture, + revoke: () => ctx.internalAdapter.deleteSession(session.json.session.token), + }; +} + +describe("Telegram OIDC links require a live initiating session", () => { + it.each(["redirect", "id token"] as const)( + "refuses %s linking from a revoked session still in the cookie cache", + async (flow) => { + const { client, db, revoke } = await signedInUser(); + const before = structuredClone(db.account); + await revoke(); + expect(db.session).toHaveLength(0); + + const response = await client.post("/link-social", { + provider: "telegram-oidc", + callbackURL: "/settings", + ...(flow === "id token" + ? { + idToken: { + token: await issuer.sign({ ...telegramClaims(), nonce: "n" }), + nonce: "n", + }, + } + : {}), + }); + + expect(response.status).toBe(401); + expect(db.account).toEqual(before); + expect(db.session).toHaveLength(0); + expect(issuer.tokenRequests).toHaveLength(0); + } + ); + + it.each([ + [false, "/settings", 1], + [true, "error=unable_to_link_account", 0], + ] as const)( + "only completes a redirect link while its initiating session is live (revoked: %s)", + async (revoked, location, linkedAccounts) => { + const { client, db, revoke } = await signedInUser(); + const before = structuredClone(db.account); + const start = await client.post("/link-social", { + provider: "telegram-oidc", + callbackURL: "/settings", + }); + expect(start.status).toBe(200); + const callbackURL = issuer.authorize(start.json.url, telegramClaims()); + if (revoked) { + await revoke(); + } + + const callback = await client.get(callbackURL); + + expect(callback.headers.get("location")).toContain(location); + expect(db.account).toHaveLength(before.length + linkedAccounts); + expect( + db.account.filter((account) => account.providerId !== "telegram-oidc") + ).toEqual(before); + expect( + db.account + .filter((account) => account.providerId === "telegram-oidc") + .map(({ accountId, userId }) => ({ accountId, userId })) + ).toEqual( + revoked + ? [] + : [ + { + accountId: "12224742808376279442", + userId: db.user[0]!.id, + }, + ] + ); + expect(db.session).toHaveLength(revoked ? 0 : 1); + } + ); +}); diff --git a/src/telegram-identity-state.ts b/src/telegram-identity-state.ts index 0fcd04d..1a20ac2 100644 --- a/src/telegram-identity-state.ts +++ b/src/telegram-identity-state.ts @@ -5,6 +5,8 @@ interface VerifiedSignIn { /** Users this request changed after Better Auth read them. */ changedUserIds: Set; claims: TelegramOIDCClaims; + /** Account owner before Better Auth awaits application sign-in validation. */ + expectedUserId?: string | undefined; /** The user info `getUserInfo` gave Better Auth (mapper output included). */ userInfo: Record; } diff --git a/src/telegram-identity.ts b/src/telegram-identity.ts index e0a3b54..7fc6e07 100644 --- a/src/telegram-identity.ts +++ b/src/telegram-identity.ts @@ -1,7 +1,7 @@ import type { AuthContext, BetterAuthOptions } from "@better-auth/core"; import { APIError } from "better-auth/api"; import { ERROR_CODES, PLUGIN_ID, TELEGRAM_OIDC_PROVIDER_ID } from "./constants"; -import { currentClaims, currentSignIn } from "./telegram-identity-state"; +import { currentSignIn } from "./telegram-identity-state"; import { accountProvenByClaims, reconcileTelegramIdentity, @@ -75,10 +75,7 @@ export function telegramIdentityHooks( session.userId, signIn.claims ); - if (!account) { - return; - } - if (options.identityFields) { + if (account && options.identityFields) { // A refused identity update stops the sign-in. await syncTelegramIdentity( ctx, @@ -87,37 +84,66 @@ export function telegramIdentityHooks( account ); } - if (options.updateUserInfo) { + if (account && options.updateUserInfo) { await updateUserInfo(ctx, session.userId, signIn.userInfo); } + // Application validation and profile hooks may await a concurrent unlink. + if ( + signIn.expectedUserId === session.userId && + !(await accountProvenByClaims(ctx, session.userId, signIn.claims)) + ) { + throw APIError.from("UNAUTHORIZED", ERROR_CODES.ACCOUNT_NOT_LINKED); + } }, }, }; - if (!options.identityFields) { - return options.updateUserInfo - ? { ...placeholderGuard, session: sessionHooks } - : placeholderGuard; - } - return { ...placeholderGuard, session: sessionHooks, account: { create: { + async before(account) { + const signIn = await currentSignIn(); + if ( + signIn && + account.providerId === TELEGRAM_OIDC_PROVIDER_ID && + account.accountId === signIn.claims.sub + ) { + // Plugin hooks precede application hooks. Pin the intended owner + // before an application hook can change the new account binding. + signIn.expectedUserId ??= account.userId; + } + }, async after(account) { if (account.providerId !== TELEGRAM_OIDC_PROVIDER_ID) { return; } - const claims = await currentClaims(); - if (claims && account.accountId === claims.sub) { - await syncTelegramIdentity(ctx, account.userId, claims, account); + const signIn = await currentSignIn(); + if (signIn && account.accountId === signIn.claims.sub) { + if (signIn.expectedUserId !== account.userId) { + throw APIError.from( + "UNAUTHORIZED", + ERROR_CODES.ACCOUNT_NOT_LINKED + ); + } + if (options.identityFields) { + await syncTelegramIdentity( + ctx, + account.userId, + signIn.claims, + account + ); + } } }, }, delete: { async after(account) { - if (TELEGRAM_PROVIDERS.has(account.providerId)) { + if ( + options.identityFields && + TELEGRAM_PROVIDERS.has(account.providerId) + ) { await reconcileTelegramIdentity(ctx, account.userId); } }, diff --git a/src/widget-endpoints.ts b/src/widget-endpoints.ts index 4b2737c..d63ba80 100644 --- a/src/widget-endpoints.ts +++ b/src/widget-endpoints.ts @@ -3,7 +3,7 @@ import { createAuthEndpoint, formCsrfMiddleware, freshSessionMiddleware, - sessionMiddleware, + sensitiveSessionMiddleware, } from "better-auth/api"; import { ERROR_CODES, SUCCESS_MESSAGES } from "./constants"; import type { TelegramPluginConfig } from "./plugin-config"; @@ -83,7 +83,7 @@ export function createWidgetEndpoints(config: TelegramPluginConfig) { "/telegram/link", { method: "POST", - use: [sessionMiddleware], + use: [sensitiveSessionMiddleware], }, async (ctx) => { if ( @@ -108,8 +108,8 @@ export function createWidgetEndpoints(config: TelegramPluginConfig) { "/telegram/unlink", { method: "POST", - // Same as Better Auth's /unlink-account: a recent sign-in. - use: [freshSessionMiddleware], + // Check revocation in storage before enforcing the recent-sign-in rule. + use: [sensitiveSessionMiddleware, freshSessionMiddleware], }, async (ctx) => { await unlinkTelegramAccount(ctx, ctx.context.session.user.id); diff --git a/test-d/server-owned-fields.ts b/test-d/server-owned-fields.ts new file mode 100644 index 0000000..7e49c93 --- /dev/null +++ b/test-d/server-owned-fields.ts @@ -0,0 +1,101 @@ +// docs/server-owned-fields.md: compiled against the public package. +import { defineRequestState } from "@better-auth/core/context"; +import { betterAuth } from "better-auth"; +import { telegram } from "better-auth-telegram"; + +declare function findMemberByTelegramId( + telegramId: string +): Promise; + +interface Member { + role: string; + user_id: number; + user_name: string; + user_nick: string; +} + +// A separate value for each request, including concurrent sign-ins. +const verifiedMember = defineRequestState(() => null); + +export const auth = betterAuth({ + baseURL: process.env.BETTER_AUTH_URL, + secret: process.env.BETTER_AUTH_SECRET, + session: { + expiresIn: 300, + cookieCache: { + enabled: true, + strategy: "jwt", + maxAge: 300, + refreshCache: false, + }, + }, + account: { storeStateStrategy: "cookie", storeAccountCookie: true }, + user: { + additionalFields: { + user_id: { + type: "number", + required: false, + input: false, + returned: true, + }, + user_name: { + type: "string", + required: false, + input: false, + returned: true, + }, + user_nick: { + type: "string", + required: false, + input: false, + returned: true, + }, + role: { type: "string", required: false, input: false, returned: true }, + }, + async validateUserInfo({ source }) { + const telegramId = source.oauth?.profile?.id; + if ( + source.oauth?.providerId !== "telegram-oidc" || + typeof telegramId !== "string" + ) { + return { error: "telegram_required" }; + } + // Implement this with your application's parameterized query. + const member: Member | null = await findMemberByTelegramId(telegramId); + if (!member) { + return { error: "not_a_member" }; + } + await verifiedMember.set(member); + }, + }, + databaseHooks: { + user: { + create: { + async before() { + const member = await verifiedMember.get(); + if (!member) { + return false; + } + return { + data: { + user_id: member.user_id, + user_name: member.user_name, + user_nick: member.user_nick, + role: member.role, + }, + }; + }, + }, + }, + }, + plugins: [ + telegram({ + loginWidget: false, + oidc: { + enabled: true, + clientId: process.env.TELEGRAM_OIDC_CLIENT_ID, + clientSecret: process.env.TELEGRAM_OIDC_CLIENT_SECRET, + }, + }), + ], +}); diff --git a/test-d/server-owned-session-fields.ts b/test-d/server-owned-session-fields.ts new file mode 100644 index 0000000..ea0bf47 --- /dev/null +++ b/test-d/server-owned-session-fields.ts @@ -0,0 +1,78 @@ +// docs/server-owned-fields.md: per-sign-in session claims. +import { defineRequestState } from "@better-auth/core/context"; +import { betterAuth } from "better-auth"; +import { telegram } from "better-auth-telegram"; + +declare function findMemberByTelegramId( + telegramId: string +): Promise; + +interface Member { + role: string; + user_id: number; +} + +const verifiedMember = defineRequestState(() => null); + +export const auth = betterAuth({ + baseURL: process.env.BETTER_AUTH_URL, + secret: process.env.BETTER_AUTH_SECRET, + account: { storeStateStrategy: "cookie", storeAccountCookie: true }, + user: { + async validateUserInfo({ source }) { + const telegramId = source.oauth?.profile?.id; + if ( + source.oauth?.providerId !== "telegram-oidc" || + typeof telegramId !== "string" + ) { + return { error: "telegram_required" }; + } + const member: Member | null = await findMemberByTelegramId(telegramId); + if (!member) { + return { error: "not_a_member" }; + } + await verifiedMember.set(member); + }, + }, + session: { + expiresIn: 300, + cookieCache: { + enabled: true, + strategy: "jwt", + maxAge: 300, + refreshCache: false, + }, + additionalFields: { + user_id: { + type: "number", + required: false, + input: false, + returned: true, + }, + role: { type: "string", required: false, input: false, returned: true }, + }, + }, + databaseHooks: { + session: { + create: { + async before() { + const member = await verifiedMember.get(); + if (!member) { + return false; + } + return { data: { user_id: member.user_id, role: member.role } }; + }, + }, + }, + }, + plugins: [ + telegram({ + loginWidget: false, + oidc: { + enabled: true, + clientId: process.env.TELEGRAM_OIDC_CLIENT_ID, + clientSecret: process.env.TELEGRAM_OIDC_CLIENT_SECRET, + }, + }), + ], +}); diff --git a/test-d/tsconfig.json b/test-d/tsconfig.json index 0ebbf85..504aaa4 100644 --- a/test-d/tsconfig.json +++ b/test-d/tsconfig.json @@ -9,5 +9,10 @@ "noEmit": true, "skipLibCheck": true }, - "files": ["consumer.ts", "snippets.ts"] + "files": [ + "consumer.ts", + "snippets.ts", + "server-owned-fields.ts", + "server-owned-session-fields.ts" + ] } diff --git a/test-d/tsconfig.node16.json b/test-d/tsconfig.node16.json index 239ad9f..01e7f2b 100644 --- a/test-d/tsconfig.node16.json +++ b/test-d/tsconfig.node16.json @@ -4,5 +4,11 @@ "module": "Node16", "moduleResolution": "Node16" }, - "files": ["consumer.ts", "snippets.ts", "commonjs.cts"] + "files": [ + "consumer.ts", + "snippets.ts", + "commonjs.cts", + "server-owned-fields.ts", + "server-owned-session-fields.ts" + ] } diff --git a/test/live-acceptance/README.md b/test/live-acceptance/README.md new file mode 100644 index 0000000..d87ab8a --- /dev/null +++ b/test/live-acceptance/README.md @@ -0,0 +1,88 @@ +# Live Telegram acceptance harness + +Runs the locally built package against the real Telegram OIDC issuer, legacy Login +Widget and Mini App. It has no +production database: the database mode owns an in-memory SQLite database and the +two stateless modes have no Better Auth database. Stop the process to discard it. + +From the repository root, build the current package, then supply private files: + +```sh +npm run build +BAT_LIVE_BASE_URL=https://your-public-tunnel.example \ +BAT_LIVE_CREDENTIALS_FILE=/private/credentials.json \ +BAT_LIVE_LOG_FILE=/private/events.jsonl \ +BAT_LIVE_CONTROL_FILE=/private/control.json \ +bun run test/live-acceptance/server.ts +``` + +The credentials JSON requires `oidcClientId` and `oidcClientSecret` from a disposable +OIDC bot. Optional `legacyBotToken` and `legacyBotUsername` enable `/legacy` using +a separate bot whose legacy Widget remains enabled. Never commit credentials, +control files, databases or raw authentication data. Use file permissions 0600. + +Register all three callback URLs in BotFather: + +- `https://your-public-tunnel.example/trusted/api/auth/callback/telegram-oidc` +- `https://your-public-tunnel.example/mapper/api/auth/callback/telegram-oidc` +- `https://your-public-tunnel.example/database/api/auth/callback/telegram-oidc` + +Register the public origin as a trusted origin in BotFather. Start a tunnel to +127.0.0.1:3417. Open `/trusted`, `/mapper` or `/database` on the device. The optional +`BAT_LIVE_AUTH_SECRET` keeps stateless sessions readable across harness restarts; +otherwise a new random secret is generated at each start. + +The browser uses a bundle of the current local client plugin and Better Auth +client. Trusted mode keeps a creation-only user snapshot and also puts freshly +looked-up fields under `session` at each accepted sign-in. The readonly user and +session API update attempts can be exercised separately. It can start sign-in, show sanitized session/JWT evidence, attempt a +forbidden role update and sign out. The fixture member values are deliberate: +`user_id: 42`, role `member` and fixed nonpersonal labels. The mapper tries to write +`user_id: 999` and role `admin`; those `input:false` values must remain absent in +mapper mode and must not override the trusted creation hook in trusted mode. + +The optional control JSON is read on every sign-in attempt: + +```json +{"deny": false, "profileVersion": 1, "revokeOnValidation": false, "revokeOnCreate": false} +``` + +`deny:true` refuses sign-in before a session. `profileVersion:2` changes trusted +stateless fixture values to role `editor` and maps `nickname:profile-v2`; database +mode updates the input-allowed nickname on returning sign-in. The two revoke +switches remove the owned OIDC account through Better Auth's internal adapter +during validation of a returning sign-in or after account creation. They should +prevent the attempted login from issuing a session. Disable each switch before +the next unrelated case. Changes to this local file have no public HTTP endpoint. + +The JSONL log records method/path/status, callback query parameter names, provider +HTTP status/timing and token response shape (never its contents), allowlisted +redirect paths and error codes (no full URL or error description), verified +claim types, hashed identities, application decisions, hook execution and sanitized +session fields. It omits auth codes, state, nonce, JWT/cookie/session tokens, raw +initData, credentials, Telegram names, email and phone. Browser display is similarly +sanitized. The log is mode 0600. Keep screen recordings away from BotFather's secret +screens; the browser's address bar may temporarily contain an OAuth code. + +A signed local OIDC fixture can smoke-test the harness without a Telegram account; +that does not establish live Telegram acceptance. The live evidence must come from +the lead agent's actual device flow and matching structured callback/session log. + +## Legacy Widget and Mini App + +Register the tunnel host with `/setdomain` for the legacy bot and configure its +Mini App/menu launch URL as `https://your-public-tunnel.example/legacy`. Open it in +Telegram to supply real signed initData. The SDK and the local plugin perform +auto-sign-in when initData is available; the manual button can repeat it. + +The legacy page sets global `fetchOptions.throw: true`, initializes the real Login +Widget, uses `authClient.telegram.unlink()` without a dummy body, and can relink +using the last signed Widget payload held only in page memory. It permits removal +of the test user's last account so the generated unlink route can be exercised. + +The page's revoke button calls a test-only `POST /legacy/revoke`. It requires the +configured Origin and a currently live session checked without cookie cache. It +revokes only that request's own server-side session, retains its browser cache, +and accepts no user identifier or token in its body. Link/unlink must then refuse +the cached session even if session evidence is still readable until cache expiry. +There is no route to revoke another user's session. diff --git a/test/live-acceptance/auth.ts b/test/live-acceptance/auth.ts new file mode 100644 index 0000000..3e12aa8 --- /dev/null +++ b/test/live-acceptance/auth.ts @@ -0,0 +1,170 @@ +import { DatabaseSync } from "node:sqlite"; +import { randomBytes } from "node:crypto"; +import { betterAuth, type BetterAuthOptions } from "better-auth"; +import { getMigrations } from "better-auth/db/migration"; +import { telegram } from "../../dist/index.js"; +import { fingerprint, readControl } from "./log"; +import { createMemberPolicy, serverOwnedFields } from "./member"; +import { legacyOptions } from "./legacy"; + +type Log = (event: string, details?: Record) => void; +export interface Credentials { + oidcClientId: string; + oidcClientSecret: string; + legacyBotToken?: string; + legacyBotUsername?: string; +} +export const modes = ["trusted", "mapper", "database", "legacy"] as const; +export type Mode = (typeof modes)[number]; + +export async function createModes( + baseURL: string, + credentials: Credentials, + log: Log +) { + const secret = + process.env.BAT_LIVE_AUTH_SECRET ?? randomBytes(32).toString("hex"); + const close: (() => void)[] = []; + const instances = new Map>(); + try { + for (const mode of modes) { + if ( + mode === "legacy" && + !(credentials.legacyBotToken && credentials.legacyBotUsername) + ) + continue; + const policy = createMemberPolicy(mode, log); + const sqlite = + mode === "database" || mode === "legacy" + ? new DatabaseSync(":memory:") + : undefined; + if (sqlite) + close.push(() => { + if (sqlite.isOpen) sqlite.close(); + }); + if (mode === "legacy") { + const options = legacyOptions( + baseURL, + secret, + sqlite!, + credentials, + log + ); + await (await getMigrations(options)).runMigrations(); + instances.set(mode, betterAuth(options)); + continue; + } + const options: BetterAuthOptions = { + baseURL, + basePath: `/${mode}/api/auth`, + secret, + trustedOrigins: [baseURL], + database: sqlite, + logger: { + log(level: string, _message: string, ..._args: unknown[]) { + log("auth_diagnostic", { mode, level }); + }, + }, + advanced: { cookiePrefix: `bat_live_${mode}` }, + account: { + storeStateStrategy: "cookie", + storeAccountCookie: true, + updateAccountOnSignIn: mode !== "database", + }, + session: { + expiresIn: 300, + ...(mode === "trusted" + ? { additionalFields: serverOwnedFields } + : {}), + cookieCache: { + enabled: true, + strategy: "jwt", + maxAge: 300, + refreshCache: false, + }, + }, + user: { + additionalFields: { + ...serverOwnedFields, + nickname: { type: "string", required: false }, + }, + validateUserInfo: policy.validateUserInfo, + }, + databaseHooks: { + user: { + create: { + async before() { + if (mode === "mapper") return; + return policy.fieldsForCreation("user"); + }, + }, + }, + account: { + create: { + async after(account: any, ctx: any) { + log("account_created", { + mode, + providerId: account.providerId, + userFingerprint: fingerprint(account.userId), + }); + if ( + readControl(process.env.BAT_LIVE_CONTROL_FILE).revokeOnCreate + ) { + await ctx.context.internalAdapter.deleteAccount(account.id); + log("account_revoked_in_create_hook", { mode }); + } + }, + }, + }, + session: { + create: { + async before() { + if (mode === "trusted") + return policy.fieldsForCreation("session"); + }, + async after() { + log("session_created", { mode }); + }, + }, + }, + }, + plugins: [ + telegram({ + loginWidget: false, + oidc: { + enabled: true, + clientId: credentials.oidcClientId, + clientSecret: credentials.oidcClientSecret, + updateUserInfoOnSignIn: mode === "database", + async mapOIDCProfileToUser(claims) { + const control = readControl(process.env.BAT_LIVE_CONTROL_FILE); + log("verified_oidc_profile", { + mode, + idType: typeof claims.id, + subjectType: typeof claims.sub, + audienceType: typeof claims.aud, + hasPhone: claims.phone_number !== undefined, + telegramFingerprint: fingerprint(claims.id), + }); + await Promise.resolve(); + return { + user_id: 999, + user_name: "Mapper Test", + user_nick: "mapper", + role: "admin", + nickname: `profile-v${control.profileVersion}`, + }; + }, + }, + }), + ], + }; + if (sqlite) await (await getMigrations(options)).runMigrations(); + instances.set(mode, betterAuth(options)); + } + return { instances, close: () => close.forEach((fn) => fn()) }; + } catch (error) { + close.forEach((fn) => fn()); + throw error; + } +} diff --git a/test/live-acceptance/browser.ts b/test/live-acceptance/browser.ts new file mode 100644 index 0000000..6c778ef --- /dev/null +++ b/test/live-acceptance/browser.ts @@ -0,0 +1,55 @@ +import { createAuthClient } from "better-auth/client"; +import { telegramClient } from "../../dist/client.js"; +import { startLegacy } from "./legacy-browser"; + +const mode = document.body.dataset.mode!; +const basePath = `/${mode}/api/auth`; +const client = createAuthClient({ + baseURL: location.origin, + basePath, + fetchOptions: { throw: mode === "legacy" }, + plugins: [telegramClient()], +}); +const output = document.querySelector("pre")!; +const result = (value: unknown) => { + output.textContent = JSON.stringify(value, null, 2); +}; +async function readSession() { + const response = await fetch(`/${mode}/evidence`, { + credentials: "same-origin", + cache: "no-store", + }); + result(await response.json()); +} +document.querySelector("#signin")?.addEventListener("click", async () => { + const { error } = await client.signInWithTelegramOIDC({ + callbackURL: `${location.origin}/${mode}`, + errorCallbackURL: `${location.origin}/${mode}`, + }); + if (error) result({ error: error.code, status: error.status }); +}); +document.querySelector("#session")!.addEventListener("click", readSession); +document.querySelector("#logout")!.addEventListener("click", async () => { + await client.signOut(); + await readSession(); +}); +async function attemptUpdate(target: "user" | "session") { + const response = await fetch(`${basePath}/update-${target}`, { + method: "POST", + credentials: "same-origin", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ user_id: 999, role: "admin" }), + }); + const body = await response.json(); + result({ target, status: response.status, error: body.code }); +} +document + .querySelector("#tamper") + ?.addEventListener("click", () => attemptUpdate("user")); +document + .querySelector("#tamper-session") + ?.addEventListener("click", () => attemptUpdate("session")); +const error = new URLSearchParams(location.search).get("error"); +if (error) result({ callbackError: error }); +else await readSession(); +if (mode === "legacy") await startLegacy(client, readSession, result); diff --git a/test/live-acceptance/legacy-browser.ts b/test/live-acceptance/legacy-browser.ts new file mode 100644 index 0000000..56b84b2 --- /dev/null +++ b/test/live-acceptance/legacy-browser.ts @@ -0,0 +1,75 @@ +import type { TelegramAuthData } from "../../dist/index.js"; + +export async function startLegacy( + client: any, + readSession: () => Promise, + show: (value: unknown) => void +) { + let lastWidgetData: TelegramAuthData | undefined; + async function run(action: string, task: () => Promise) { + try { + const response = await task(); + if (response?.error) { + show({ + action, + status: response.error.status, + error: response.error.code, + }); + } else { + await readSession(); + } + } catch (error: any) { + show({ + action, + status: error.status, + error: error.error?.code ?? error.code ?? error.name, + }); + } + } + document + .querySelector("#miniapp")! + .addEventListener("click", () => + run("miniapp", () => client.autoSignInFromMiniApp({ throw: false })) + ); + document + .querySelector("#generated-unlink")! + .addEventListener("click", () => + run("generated_unlink", () => client.telegram.unlink()) + ); + document.querySelector("#link-last")!.addEventListener("click", () => { + if (!lastWidgetData) return show({ error: "widget_data_not_available" }); + return run("link", () => + client.linkTelegram(lastWidgetData, { throw: false }) + ); + }); + document.querySelector("#revoke")!.addEventListener("click", async () => { + const response = await fetch("/legacy/revoke", { + method: "POST", + credentials: "same-origin", + }); + show({ status: response.status, ...(await response.json()) }); + }); + const status = document.querySelector("#widget-status")!; + try { + await client.initTelegramWidget( + "widget", + { size: "large", showUserPhoto: false }, + async (data: TelegramAuthData) => { + lastWidgetData = data; + await run("widget_signin", () => + client.signInWithTelegram(data, { throw: false }) + ); + } + ); + status.textContent = "Widget ready with global fetchOptions.throw: true"; + } catch { + status.textContent = "Widget initialization failed"; + } + const webApp = (window as any).Telegram?.WebApp; + if (webApp?.initData) { + webApp.ready(); + await run("miniapp_auto", () => + client.autoSignInFromMiniApp({ throw: false }) + ); + } +} diff --git a/test/live-acceptance/legacy.ts b/test/live-acceptance/legacy.ts new file mode 100644 index 0000000..e4fdde1 --- /dev/null +++ b/test/live-acceptance/legacy.ts @@ -0,0 +1,86 @@ +import type { DatabaseSync } from "node:sqlite"; +import type { BetterAuthOptions } from "better-auth"; +import { telegram } from "../../dist/index.js"; + +export function legacyOptions( + baseURL: string, + secret: string, + database: DatabaseSync, + credentials: { legacyBotToken?: string; legacyBotUsername?: string }, + log: (event: string, data?: Record) => void +): BetterAuthOptions { + return { + baseURL, + basePath: "/legacy/api/auth", + secret, + database, + trustedOrigins: [baseURL], + advanced: { cookiePrefix: "bat_live_legacy" }, + logger: { + log(level) { + log("auth_diagnostic", { mode: "legacy", level }); + }, + }, + session: { + expiresIn: 300, + cookieCache: { + enabled: true, + strategy: "jwt", + maxAge: 300, + refreshCache: false, + }, + }, + account: { accountLinking: { allowUnlinkingAll: true } }, + plugins: [ + telegram({ + botToken: credentials.legacyBotToken, + botUsername: credentials.legacyBotUsername, + miniApp: { enabled: true }, + }), + ], + databaseHooks: { + account: { + create: { + async after(account) { + log("account_created", { + mode: "legacy", + providerId: account.providerId, + }); + }, + }, + }, + session: { + create: { + async after() { + log("session_created", { mode: "legacy" }); + }, + }, + }, + }, + }; +} + +export async function revokeOwnSession( + request: Request, + auth: any, + baseURL: string, + log: (event: string, data: Record) => void +) { + if (request.method !== "POST" || request.headers.get("origin") !== baseURL) { + return Response.json( + { error: "invalid_origin_or_method" }, + { status: 403 } + ); + } + const session = await auth.api.getSession({ + headers: request.headers, + query: { disableCookieCache: true }, + }); + if (!session) + return Response.json({ error: "unauthorized" }, { status: 401 }); + await (await auth.$context).internalAdapter.deleteSession( + session.session.token + ); + log("own_session_revoked", { mode: "legacy", cookieCachePreserved: true }); + return Response.json({ revoked: true, cookieCachePreserved: true }); +} diff --git a/test/live-acceptance/log.ts b/test/live-acceptance/log.ts new file mode 100644 index 0000000..c9e6a4c --- /dev/null +++ b/test/live-acceptance/log.ts @@ -0,0 +1,68 @@ +import { appendFileSync, chmodSync, readFileSync } from "node:fs"; +import { createHash } from "node:crypto"; + +export function fingerprint(value: unknown) { + return typeof value === "string" + ? createHash("sha256").update(value).digest("hex").slice(0, 12) + : null; +} + +export function createLog(path: string) { + appendFileSync(path, "", { mode: 0o600 }); + chmodSync(path, 0o600); + return (event: string, details: Record = {}) => { + appendFileSync( + path, + `${JSON.stringify({ at: new Date().toISOString(), event, ...details })}\n` + ); + }; +} + +export function readControl(path?: string) { + if (!path) + return { + deny: false, + profileVersion: 1, + revokeOnValidation: false, + revokeOnCreate: false, + }; + const value = JSON.parse(readFileSync(path, "utf8")); + return { + deny: value.deny === true, + profileVersion: value.profileVersion === 2 ? 2 : 1, + revokeOnValidation: value.revokeOnValidation === true, + revokeOnCreate: value.revokeOnCreate === true, + }; +} + +export const memberFields = [ + "user_id", + "user_name", + "user_nick", + "role", + "nickname", +]; +export function safeUser(user: Record | null | undefined) { + if (!user) return null; + return { + userFingerprint: fingerprint(user.id), + telegramFingerprint: fingerprint(user.telegramId), + hasTelegramUsername: !!user.telegramUsername, + hasTelegramPhone: !!user.telegramPhoneNumber, + ...Object.fromEntries(memberFields.map((key) => [key, user[key] ?? null])), + }; +} + +export function safeSession( + session: Record | null | undefined +) { + if (!session) return null; + return { + userFingerprint: fingerprint(session.userId), + createdAt: session.createdAt, + expiresAt: session.expiresAt, + ...Object.fromEntries( + memberFields.map((key) => [key, session[key] ?? null]) + ), + }; +} diff --git a/test/live-acceptance/member.ts b/test/live-acceptance/member.ts new file mode 100644 index 0000000..a14fc77 --- /dev/null +++ b/test/live-acceptance/member.ts @@ -0,0 +1,65 @@ +import { defineRequestState } from "@better-auth/core/context"; +import { fingerprint, readControl } from "./log"; + +type Log = (event: string, details?: Record) => void; +export const serverOwnedFields = { + user_id: { type: "number", required: false, input: false, returned: true }, + user_name: { type: "string", required: false, input: false, returned: true }, + user_nick: { type: "string", required: false, input: false, returned: true }, + role: { type: "string", required: false, input: false, returned: true }, +} as const; + +export function createMemberPolicy(mode: string, log: Log) { + const state = defineRequestState | null>(() => null); + return { + async validateUserInfo({ user, source }: any, ctx: any) { + const profile = source.oauth?.profile; + const control = readControl(process.env.BAT_LIVE_CONTROL_FILE); + const valid = + source.oauth?.providerId === "telegram-oidc" && + typeof profile?.id === "string"; + log("application_validation", { + mode, + action: source.action, + valid, + denied: control.deny, + telegramFingerprint: fingerprint(profile?.id), + }); + if (!valid || control.deny) return { error: "not_a_member" }; + if (source.action === "sign-in" && control.revokeOnValidation) { + const accounts = await ctx.context.internalAdapter.findAccounts( + user.id + ); + for (const account of accounts.filter( + (row: any) => row.providerId === "telegram-oidc" + )) { + await ctx.context.internalAdapter.deleteAccount(account.id); + } + log("account_revoked_in_validation", { mode }); + } + await state.set({ + user_id: 42, + user_name: "Live Test Member", + user_nick: `member-v${control.profileVersion}`, + role: control.profileVersion === 2 ? "editor" : "member", + }); + }, + async fieldsForCreation(target: "user" | "session") { + const member = await state.get(); + if (!member) return false; + log("trusted_fields_supplied", { + mode, + target, + keys: Object.keys(member), + }); + return { + data: { + user_id: member.user_id, + user_name: member.user_name, + user_nick: member.user_nick, + role: member.role, + }, + }; + }, + }; +} diff --git a/test/live-acceptance/network.ts b/test/live-acceptance/network.ts new file mode 100644 index 0000000..ae43478 --- /dev/null +++ b/test/live-acceptance/network.ts @@ -0,0 +1,49 @@ +/** Provider transport metadata only; bodies, credentials and URL queries are omitted. */ +export function observeProviderFetch( + log: (event: string, data: Record) => void +) { + const original = globalThis.fetch; + globalThis.fetch = async (input, init) => { + const url = new URL(input instanceof Request ? input.url : String(input)); + if (url.hostname !== "oauth.telegram.org") return original(input, init); + const started = performance.now(); + const headers = new Headers( + init?.headers ?? (input instanceof Request ? input.headers : undefined) + ); + try { + const response = await original(input, init); + let tokenShape: Record | undefined; + if (url.pathname.endsWith("/token")) { + try { + const value = await response.clone().json(); + tokenShape = { + hasIdToken: typeof value.id_token === "string", + hasError: !!value.error, + }; + } catch { + tokenShape = { invalidJSON: true }; + } + } + log("provider_http", { + host: url.hostname, + path: url.pathname, + method: init?.method ?? "GET", + hasAuthorization: headers.has("authorization"), + status: response.status, + durationMs: Math.round(performance.now() - started), + tokenShape, + }); + return response; + } catch (error) { + log("provider_transport_error", { + host: url.hostname, + path: url.pathname, + errorType: error instanceof Error ? error.name : "unknown", + }); + throw error; + } + }; + return () => { + globalThis.fetch = original; + }; +} diff --git a/test/live-acceptance/response-log.ts b/test/live-acceptance/response-log.ts new file mode 100644 index 0000000..c2a28d3 --- /dev/null +++ b/test/live-acceptance/response-log.ts @@ -0,0 +1,61 @@ +import { TELEGRAM_ERROR_CODES } from "../../dist/index.js"; + +const safeCodes = new Set([ + ...Object.keys(TELEGRAM_ERROR_CODES), + "not_a_member", + "telegram_required", + "unable_to_get_user_info", + "unable_to_update_account", + "unable_to_create_user", + "unable_to_link_account", + "account_not_linked", + "internal_server_error", + "FIELD_NOT_ALLOWED", + "UNAUTHORIZED", + "SESSION_NOT_FRESH", + "FAILED_TO_CREATE_SESSION", + "FIELD_NOT_ALLOWED", + "invalid_origin_or_method", + "unauthorized", + "request_failed", + "mode_not_configured", +]); +function errorCode(value: unknown) { + return typeof value === "string" && + /^[A-Za-z0-9_-]{1,80}$/.test(value) && + safeCodes.has(value) + ? value + : undefined; +} + +export async function responseMetadata(response: Response, baseURL: string) { + const result: { redirectPath?: string; errorCode?: string } = {}; + const location = response.headers.get("location"); + if (location) { + try { + const redirect = new URL(location, baseURL); + result.redirectPath = + /^\/(trusted|mapper|database|legacy)(\/api\/auth\/(error|callback\/telegram-oidc))?$/.test( + redirect.pathname + ) + ? redirect.pathname + : "other"; + result.errorCode = errorCode(redirect.searchParams.get("error")); + } catch { + /* Malformed locations are represented only by HTTP status. */ + } + } + if ( + response.status >= 400 && + response.headers.get("content-type")?.includes("application/json") + ) { + try { + const value = await response.clone().json(); + result.errorCode = + errorCode(value.code) ?? errorCode(value.error) ?? result.errorCode; + } catch { + /* Non-JSON errors must not leak their body into the log. */ + } + } + return result; +} diff --git a/test/live-acceptance/server.ts b/test/live-acceptance/server.ts new file mode 100644 index 0000000..7bb5a74 --- /dev/null +++ b/test/live-acceptance/server.ts @@ -0,0 +1,145 @@ +import { readFileSync } from "node:fs"; +import { decodeJwt } from "jose"; +import { createModes, modes, type Credentials } from "./auth"; +import { createLog, safeSession, safeUser } from "./log"; +import { page } from "./ui"; +import { observeProviderFetch } from "./network"; +import { revokeOwnSession } from "./legacy"; +import { responseMetadata } from "./response-log"; + +const baseURL = process.env.BAT_LIVE_BASE_URL; +const credentialsPath = process.env.BAT_LIVE_CREDENTIALS_FILE; +const logPath = process.env.BAT_LIVE_LOG_FILE; +if (!baseURL || !credentialsPath || !logPath) + throw new Error( + "Set BAT_LIVE_BASE_URL, BAT_LIVE_CREDENTIALS_FILE and BAT_LIVE_LOG_FILE" + ); +const credentials: Credentials = JSON.parse( + readFileSync(credentialsPath, "utf8") +); +if (!credentials.oidcClientId || !credentials.oidcClientSecret) + throw new Error("OIDC credentials are missing"); +const log = createLog(logPath); +const restoreFetch = observeProviderFetch(log); +const { instances, close } = await createModes(baseURL, credentials, log); +const bundle = await Bun.build({ + entrypoints: [new URL("./browser.ts", import.meta.url).pathname], + target: "browser", + minify: false, +}); +if (!bundle.success) throw new Error("Client bundle failed"); +const clientJS = await bundle.outputs[0]!.text(); + +function jwtEvidence(request: Request, cookieName: string) { + const cookies = request.headers.get("cookie")?.split(/;\s*/) ?? []; + const cookie = cookies.find((part) => part.split("=")[0] === cookieName); + if (!cookie) return null; + try { + const payload = decodeJwt( + decodeURIComponent(cookie.slice(cookie.indexOf("=") + 1)) + ); + return { + user: safeUser(payload.user as Record), + session: safeSession(payload.session as Record), + issuedAt: payload.iat, + expiresAt: payload.exp, + }; + } catch { + return { decodeFailed: true }; + } +} + +const server = Bun.serve({ + hostname: "127.0.0.1", + port: Number(process.env.BAT_LIVE_PORT ?? 3417), + async fetch(request) { + const started = performance.now(); + const url = new URL(request.url); + const mode = modes.find( + (name) => + url.pathname === `/${name}` || url.pathname.startsWith(`/${name}/`) + ); + let response: Response; + try { + if (mode && !instances.has(mode)) { + response = Response.json( + { error: "mode_not_configured" }, + { status: 503 } + ); + } else if (mode === "legacy" && url.pathname === "/legacy/revoke") { + response = await revokeOwnSession( + request, + instances.get(mode)!, + baseURL, + log + ); + } else if (url.pathname === "/assets/browser.js") { + response = new Response(clientJS, { + headers: { "content-type": "text/javascript" }, + }); + } else if (mode && url.pathname.startsWith(`/${mode}/api/auth/`)) { + response = await instances.get(mode)!.handler(request); + } else if (mode && url.pathname === `/${mode}/evidence`) { + const session = await instances + .get(mode)! + .api.getSession({ headers: request.headers }); + const evidence = { + mode, + authenticated: !!session, + user: safeUser(session?.user), + session: safeSession(session?.session), + jwt: session + ? jwtEvidence( + request, + (await instances.get(mode)!.$context).authCookies.sessionData + .name + ) + : null, + }; + log("session_read", evidence); + response = Response.json(evidence); + } else if (url.pathname === "/health") { + response = Response.json({ ok: true, modes: [...instances.keys()] }); + } else if ( + url.pathname === "/" || + (mode && url.pathname === `/${mode}`) + ) { + response = new Response(page(mode), { + headers: { "content-type": "text/html; charset=utf-8" }, + }); + } else response = new Response("Not found", { status: 404 }); + } catch (error) { + log("request_error", { + mode, + errorType: error instanceof Error ? error.name : "unknown", + }); + response = Response.json({ error: "request_failed" }, { status: 500 }); + } + log("http_response", { + mode, + method: request.method, + path: url.pathname, + status: response.status, + queryKeys: [...new Set(url.searchParams.keys())].sort(), + durationMs: Math.round(performance.now() - started), + setsCookie: response.headers.has("set-cookie"), + ...(await responseMetadata(response, baseURL)), + }); + response.headers.set("cache-control", "no-store"); + response.headers.set("referrer-policy", "no-referrer"); + response.headers.set("x-content-type-options", "nosniff"); + return response; + }, +}); +log("server_started", { modes, baseURL, port: server.port }); +console.log( + `Live acceptance listening on 127.0.0.1:${server.port}; structured events at configured private log path.` +); +function shutdown() { + server.stop(true); + close(); + restoreFetch(); + process.exit(0); +} +process.on("SIGINT", shutdown); +process.on("SIGTERM", shutdown); diff --git a/test/live-acceptance/ui.ts b/test/live-acceptance/ui.ts new file mode 100644 index 0000000..cfa950e --- /dev/null +++ b/test/live-acceptance/ui.ts @@ -0,0 +1,15 @@ +import { modes, type Mode } from "./auth"; + +export function page(mode?: Mode) { + return `Telegram live acceptance + +

Telegram live acceptance

+${ + mode + ? `

${mode}

${mode === "legacy" ? "Login Widget and native Mini App, with global fetchOptions.throw:true." : mode === "mapper" ? "Provider mapper output for input:false is intentionally ignored." : mode === "trusted" ? "Stateless JWT: user fields are a creation snapshot; session fields refresh at every accepted login." : "SQLite-backed OIDC with profile updates on returning sign-in."}

+${mode === "legacy" ? `

Loading widget...

` : ``}${mode === "trusted" ? `` : ""}
Loading session evidence...
+The display contains fixture member fields and hashed identities. Raw tokens and Telegram personal details are omitted.` + : "

Choose a mode, then approve the real Telegram login. Each mode uses a separate session cookie.

" +} +`; +} diff --git a/test/package.json b/test/package.json index 060e365..7debfe0 100644 --- a/test/package.json +++ b/test/package.json @@ -13,7 +13,7 @@ }, "dependencies": { "@prisma/client": "^6.19.2", - "better-auth": ">=1.7.12 <1.8.0", + "better-auth": ">=1.7.17 <1.8.0", "better-auth-telegram": "file:..", "better-sqlite3": "^12.6.2", "next": "^16.1.6",