From 13c2ac11cc3dc3ef45957d5e9873113629b96ae0 Mon Sep 17 00:00:00 2001 From: vcode-sh Date: Wed, 4 Nov 2026 10:51:13 +0100 Subject: [PATCH 1/6] docs: add testing standards and repository instructions Introduced a new document outlining testing standards to ensure meaningful test coverage and behavior validation. Added repository instructions in AGENTS.md to guide contributors on testing practices and documentation requirements. Updated CHANGELOG.md to reflect these additions and improvements in testing documentation. --- .github/PULL_REQUEST_TEMPLATE.md | 6 +- AGENTS.md | 17 + CHANGELOG.md | 16 + CLAUDE.md | 4 +- CONTRIBUTING.md | 8 +- docs/README.md | 1 + docs/api-reference.md | 2 + docs/deeper-verification-2026-11-04.md | 82 +++++ docs/miniapps.md | 2 + docs/oidc.md | 8 +- docs/security.md | 2 + docs/testing-audit-2026-11-04.md | 144 ++++++++ docs/testing.md | 147 +++++++++ scripts/check-package.mjs | 98 +++--- src/adapters.adapter.test.ts | 146 ++++++++- src/better-auth-config.integration.test.ts | 125 +++---- src/client-lifecycle.integration.test.ts | 93 ++++++ src/client-widget.ts | 19 +- src/client.integration.test.ts | 152 ++++++--- src/client.test.ts | 190 ++++++----- src/identity-transitions.adapter.test.ts | 112 +++++++ src/identity-transitions.integration.test.ts | 199 ++++++++++++ src/identity.integration.test.ts | 128 +++++--- src/miniapp.integration.test.ts | 102 +++--- src/oidc-boundaries.integration.test.ts | 113 +++++++ src/oidc-identity.integration.test.ts | 50 +-- src/oidc-linking.integration.test.ts | 79 ++++- src/oidc-placeholder.integration.test.ts | 101 ++++++ src/oidc-profile.integration.test.ts | 49 ++- src/oidc-protocol.integration.test.ts | 53 +-- src/oidc-token.ts | 8 + src/oidc.integration.test.ts | 105 ++++-- src/oidc.test.ts | 60 ---- src/plugin-config.test.ts | 18 +- src/plugin.integration.test.ts | 14 +- src/telegram-account-state.ts | 45 ++- src/telegram-account-user.ts | 36 +- src/telegram-input-boundaries.test.ts | 91 ++++++ src/telegram-placeholder.ts | 71 +++- src/testing/adapter-prisma.ts | 91 ++++++ src/testing/adapter-resources.ts | 115 +++++++ src/testing/adapters.ts | 325 +++++++------------ src/testing/auth.ts | 17 +- src/testing/oidc-server.ts | 13 +- src/types.ts | 1 + src/verify.test.ts | 26 +- src/verify.ts | 14 +- src/widget-mappers.integration.test.ts | 9 +- src/widget.integration.test.ts | 152 ++++----- test-d/commonjs.cts | 29 ++ test-d/consumer.ts | 29 +- test-d/snippets.ts | 3 +- test-d/tsconfig.node16.json | 3 +- 53 files changed, 2601 insertions(+), 922 deletions(-) create mode 100644 AGENTS.md create mode 100644 docs/deeper-verification-2026-11-04.md create mode 100644 docs/testing-audit-2026-11-04.md create mode 100644 docs/testing.md create mode 100644 src/client-lifecycle.integration.test.ts create mode 100644 src/identity-transitions.adapter.test.ts create mode 100644 src/identity-transitions.integration.test.ts create mode 100644 src/oidc-boundaries.integration.test.ts create mode 100644 src/oidc-placeholder.integration.test.ts create mode 100644 src/telegram-input-boundaries.test.ts create mode 100644 src/testing/adapter-prisma.ts create mode 100644 src/testing/adapter-resources.ts create mode 100644 test-d/commonjs.cts diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 61b29e4..fccad0c 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -15,14 +15,14 @@ - [ ] Tests pass (`npm test`) -- yes, all of them - [ ] Types check (`npm run type-check`) -- TypeScript is not optional here - [ ] Lint passes (`npm run lint`) -- Biome has no feelings to hurt -- [ ] New code has tests (I will notice if it doesn't) -- [ ] Coverage stays above 90% (I don't make the rules -- actually I do) +- [ ] Changed behavior has meaningful protection; added tests name the defect they catch +- [ ] Existing coverage floors pass; uncovered risks were reviewed without padding tests - [ ] Docs updated (if applicable, which it probably is, which you probably skipped) - [ ] `CHANGELOG.md` updated (future you will thank present you) ## Proof of life - + ## Relevant wreckage diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..a7a2f8c --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,17 @@ +# Repository instructions + +Read [CLAUDE.md](CLAUDE.md) for architecture and commands. + +For every test change, apply [Testing standards](docs/testing.md). Tests must +challenge a named, plausible defect using independently established expected +behavior. Keep the behavior owner real, delete redundant or confirmation-only +cases, and validate authentication assertions with focused fault experiments. +Coverage and test counts are evidence, not goals. Do not change runtime behavior +during a test-only audit without separating the discovered bug from test cleanup. + +Keep code, documentation and comments in English. Keep implementation modules +focused (aim for at most 200 code lines) and test files under 600 code lines; +comments do not count toward those limits. Preserve public package entrypoints. + +Use isolated test-owned databases and release all resources after success, +failure or cancellation. Never mutate shared development or production data. diff --git a/CHANGELOG.md b/CHANGELOG.md index ef4b589..35d3478 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,22 @@ All notable changes to the better-auth-telegram plugin will be documented in thi The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed + +- Overlapping widget initializations on the same host now keep the newest requested configuration. A late older response cannot replace the current bot or login callback, and its cleanup handle is harmless. +- OIDC placeholder emails now support valid opaque and long subjects. Existing account keys and ordinary numeric placeholders remain unchanged, and collision variants stay within the email local-part limit. +- OIDC tokens with an empty or non-string subject are rejected before profile mapping or cross-flow linking. An accepted single-client audience array is normalized to the public string type before the mapper runs. +- Mini App data with duplicate parameter names is rejected, so signature verification and parsed output cannot select different copies of a field. Widget and Mini App user IDs must be positive safe integers. +- Widget and Mini App sign-in reject account keys owned by different users instead of selecting the first record. Same-owner legacy duplicates remain supported, including when a conflicting owner appears after the first two rows. +- Returning Telegram sign-ins recheck account ownership after application validation and profile-update hooks. Revocation or reassignment during those steps cannot authorize a new session from stale account data. + +### Tests and maintenance + +- Replaced redundant or weak checks with independently derived response, session and durable-state assertions; added real nontransactional adapter checks and installed CommonJS/type-consumer acceptance. +- Documented the testing standards and audit evidence. Test-owned SQLite handles, databases and generated fixtures are released after success or failure. + ## [3.2.0] - 2026-11-04 ### Added diff --git a/CLAUDE.md b/CLAUDE.md index 20d7ad9..813cb65 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -46,6 +46,8 @@ Schema conditionally extends `user` table with `telegramId`, `telegramUsername`, ## Testing +Apply [Testing standards](docs/testing.md) to every added, edited or deleted test. Name the contract and the plausible defect; use independent expected results and remove cases with no unique protection. + - **Vitest** with `happy-dom` environment; `*.integration.test.ts` run in `node` against a real Better Auth instance (see `src/testing/harness.ts`). Prefer those over mocking Better Auth: mock-only tests passed while OIDC was broken on 1.7. - Tests co-located in `src/` (`*.test.ts`). OIDC integration suites separate sign-in, protocol, identity, profile, claims and linking; Widget, Mini App and mapper suites cover their corresponding flows. - `npm run test:types` compiles `test-d/consumer.ts` against the built `dist/` (run `npm run build` first) @@ -96,4 +98,4 @@ Single test file: `npx vitest run src/verify.test.ts` - 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. - HTTP status codes: 400 (validation), 401 (auth), 403 (disabled), 404 (not found), 409 (conflict) -- Coverage thresholds are enforced in CI. New code needs tests. +- Coverage thresholds are enforced in CI, but coverage does not prove assertions are useful. Add a test only for meaningful behavior not already protected. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c78ab79..552ac14 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,7 +27,7 @@ npm run test:types # Type-check a consumer of the built dist/ (run build first npm test # Run all tests -- you'd be surprised how many people skip this npm run test:watch # Watch mode -- for when you're in the zone npm run test:ui # Vitest UI -- pretty graphs that prove you did something -npm run test:coverage # Coverage report -- the number must go up +npm run test:coverage # Coverage report -- inspect gaps; do not optimize the number npm run test:adapters # Real PostgreSQL / MySQL / MongoDB (Docker); databases without a BAT_TEST_*_URL are skipped, see vitest.adapters.config.ts npm run lint # Biome lint check -- it has opinions and they are correct npm run lint:fix # Auto-fix -- let the machine do the boring part @@ -95,17 +95,17 @@ Not guidelines. Not suggestions. Rules. ## Testing -I maintain 90%+ coverage. Not because I worship the metric, but because untested code is just a theory. +Follow [Testing standards](docs/testing.md). Each test must distinguish a requirement from a plausible defect. Delete cases with no unique protection; do not retain them for a coverage target or test count. - **Verification**: crypto tests in `verify.test.ts` and `verify-hardening.test.ts` -- HMAC paths, replay attacks, future `auth_date`, hash format, edge cases - **Server plugin**: `widget.integration.test.ts`, `miniapp.integration.test.ts` and `widget-mappers.integration.test.ts` cover Widget/Mini App sign-in, account changes and mapping. OIDC suites are grouped by behavior: `oidc.integration.test.ts`, `oidc-protocol.integration.test.ts`, `oidc-identity.integration.test.ts`, `oidc-profile.integration.test.ts`, `oidc-claims.integration.test.ts` and `oidc-linking.integration.test.ts`. `identity.integration.test.ts` and `hooks.integration.test.ts` cover revocation, placeholders and application hooks. These use real `betterAuth()` instances (memory or SQLite) and a fake Telegram modeled on the live one. Prefer them over mocking Better Auth: mock-only tests passed while OIDC was broken on 1.7 -- **Client plugin**: mock `$fetch`, test widget init and API methods in `client.test.ts` +- **Client plugin**: exercise widget behavior through the DOM and session refresh through the real Better Auth client store. Control the external HTTP/script boundary; do not replace the behavior being tested. - **Security**: adversarial inputs, timestamp manipulation, malformed data, forged ID tokens ## Pull Request Process 1. Fork the repo and branch off `main` (not `develop`, not `feature-branch-from-six-months-ago`) -2. Write tests for your new code (yes, before the PR, not "I'll add them later") +2. Add or strengthen tests only for changed behavior or a concrete uncovered risk; follow [Testing standards](docs/testing.md). 3. Make sure absolutely everything passes: ```bash npm run type-check && npm test && npm run lint diff --git a/docs/README.md b/docs/README.md index a746581..0539f1d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -17,6 +17,7 @@ Welcome. This page tells you where to find each answer, and explains the words t | I get an error, or something doesn't happen. | [Troubleshooting](./troubleshooting.md) (organized by symptom) | | What exactly does endpoint, type or error code X look like? | [API reference](./api-reference.md) | | I'm on v2. What changes, and what do I do? | [Migration from v2 to v3](./migration-v2-to-v3.md) | +| How do I write and review tests that detect real defects? | [Testing standards](./testing.md) | ## Glossary diff --git a/docs/api-reference.md b/docs/api-reference.md index 660f878..83fa24a 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -135,6 +135,8 @@ Calls `GET /telegram/config`. ### `initTelegramWidget(container, options?, onAuth)` +The host must exist when initialization is called. If several calls overlap on the same host, only the newest requested initialization can render. A superseded call resolves to a harmless cleanup handle. A failed new configuration leaves an already rendered widget intact. + Shows the Login Widget in callback mode. | Parameter | Type | Description | diff --git a/docs/deeper-verification-2026-11-04.md b/docs/deeper-verification-2026-11-04.md new file mode 100644 index 0000000..641a311 --- /dev/null +++ b/docs/deeper-verification-2026-11-04.md @@ -0,0 +1,82 @@ +# Deeper functional verification: 2026-11-04 + +This pass follows the [test-quality audit](testing-audit-2026-11-04.md). Its scope +includes production corrections with independently reproduced failures, not just +test cleanup. The previous test changes remain in the working tree. + +## Confirmed defects and fixes + +| Contract | Failure reproduced before the fix | Correction | +| --- | --- | --- | +| A newer widget initialization owns its host | A late older configuration replaced the current bot and callback | Per-host request ownership prevents stale rendering; superseded handles are harmless | +| Invalid OIDC identity must not reach application mapping | Empty/numeric signed `sub` reached the mapper or caused HTTP 500 | Check the existing nonempty-string invariant immediately after cryptographic verification | +| Opaque subjects must not depend on email syntax | Valid punctuation caused HTTP 500, while long subjects/collision variants exceeded the local-part limit | Use a bounded derived email label only when needed, preserving raw account keys and unlink separation | +| The public audience type is a string | A valid single-client audience array caused `claims.aud.trim()` to throw | Normalize the already-accepted audience to the configured client ID | +| Mini App verification and parsing describe the same data | An appended second `hash` was ignored by verification but returned by parsing | Reject duplicate decoded parameter names before verification | +| Numeric Telegram IDs preserve their identity | Nonpositive, fractional and unsafe numeric IDs could be provisioned; large JSON numbers lost precision | Require positive safe integers, retaining valid 52-bit controls | +| A Telegram account key has one unambiguous owner | Widget/Mini App sign-in chose the first of conflicting owners | Reject different owners while preserving same-owner legacy duplicates, including a hidden third conflicting row | +| Application work cannot leave stale account proof in use | Revocation/reassignment during validation, or revocation during profile updates, still allowed a new session | Recheck ownership after validation and after profile writes before continuing | + +The signed-malformed-token cases require an issuer signature; the tests do not +establish an attacker-forged-token bypass. The duplicate-hash case changes parsed +metadata without the bot secret, but does not establish forged user identity. +Conflicting ownership requires inconsistent stored records, such as legacy or +concurrent writes. These are concrete correctness failures, not an asserted live +account-takeover incident. + +## Boundaries kept real + +Regression tests exercise real Better Auth requests, signed provider responses, +DOM callback ownership and database/session results. Ownership checks also run +against PostgreSQL, MySQL, MongoDB, Drizzle and Prisma. Same-owner duplicate +compatibility and serial/UUID identifiers stay under the existing adapter matrix. + +The widget scenario controls configuration response order rather than sleeping. +The account-policy and metadata-hook cases change the actual stored account and +check that no new session was issued. Positive controls retain valid sign-in, +large representable IDs and the existing account owner. + +## Measured cost + +The first correctness implementation made four account reads for an unchanged +returning sign-in. The bounded two-row fast path reduces that to two: one lookup +before application validation and one recheck afterward. The separate conflicting- +owner query is needed only when duplicate rows are found. A fixture with two +same-owner rows followed by a conflicting third row prevents this optimization +from silently ignoring an owner. + +These are measured adapter-operation counts, not a claim of end-to-end database +latency improvement over the released version, which lacked the new recheck. +Metadata writes require another authority check after their hooks. + +A warm Bun 1.4.4 microbenchmark ran 1,000 HMAC verifications per flow: roughly +0.010 ms mean for Widget and 0.015 ms for Mini App. This does not include network, +database or cold-start costs. No cryptographic cache or GPU machinery was added; +these measurements do not justify the extra state or complexity. + +## Remaining limits + +- This is not a database-wide uniqueness constraint or a distributed revocation + protocol. Checks do not revoke existing sessions or establish universal ordering + against other server instances or arbitrary session-creation hooks. +- Direct-token sign-in verifies the signature twice through Better Auth's + verification/profile phases. No shared verification cache was added without a + demonstrated workload bottleneck and a proved request/nonce ownership design. +- Browser layout, Telegram-hosted rendering, iframe cookie policy and a new live + Telegram login were not exercised. Controlled protocol tests do not substitute + for that acceptance. + +## Verification + +- Default suite: 336 tests pass on Node 24.22.2, Node 26.13.0 and Bun 1.4.4. +- Complete Better Auth 1.7.12 and 1.7.16 families: type checks and all 336 default-suite cases pass in isolated installs. +- Real databases: 98 tests pass across PostgreSQL/Kysely, MySQL/Kysely, MongoDB, Drizzle and Prisma; seven existing capability-dependent variants are skipped. This includes revocation in validation and profile hooks, conflicting owners and opaque-subject persistence. +- Lint, type checks, build with publint/ATTW, declaration consumers and installed ESM/CommonJS authentication/session checks pass. +- Coverage: 98.55% lines, 98.57% statements, 95.63% branches and 100% functions. Thresholds and exclusions remain unchanged. +- Eight isolated fault reversals fail the intended new assertions: stale rendering, late subject validation, raw audience arrays, duplicate fields, unsafe IDs, hidden third owners, stale policy proof and stale profile proof. Restored regressions pass. +- Placeholder fault experiments also detect direct use of unsafe subjects, reuse of an unlinked owner's email, and alteration of the original account key. An initially unmatched selector supplied no evidence; the corrected selector fails the account-key assertion. +- Disposable database readback finds no remaining generated databases. Containers and temporary dependency installs are removed after verification. +- Largest implementation module: 187 non-comment code lines. Largest test file: 466. + +No test claims that this finite review proves the absence of every possible defect. +No release or production deployment is part of this working-tree verification. diff --git a/docs/miniapps.md b/docs/miniapps.md index ce6dcae..331b657 100644 --- a/docs/miniapps.md +++ b/docs/miniapps.md @@ -138,6 +138,8 @@ export async function checkInitData(initData: string) { } ``` +Duplicate parameter names are rejected: verification and parsing must describe the same fields. Sign-in also requires a positive, safely representable integer user ID. + It always checks the signature, even if `miniApp.validateInitData` is `false`. An invalid signature or expired `initData` returns `{ valid: false, data: null }` with status 200. `valid: true` confirms signature and age; it does not check that the parsed data contains a user suitable for sign-in. Use `signInWithMiniApp` to create a session: it also checks the data structure, rejects `user: null` with 400 `INVALID_MINI_APP_DATA_STRUCTURE`, and reports a missing user as 400 `NO_USER_IN_INIT_DATA`. ## Inside Telegram Web: cookies in an iframe diff --git a/docs/oidc.md b/docs/oidc.md index 5b4c2cd..3e31f1f 100644 --- a/docs/oidc.md +++ b/docs/oidc.md @@ -136,7 +136,7 @@ A new OIDC user gets: - **name**: the `name` claim, or given name + family name, or the username. - **image**: the `picture` claim (Telegram profile photo URL). -- **email**: the placeholder `@telegram-oidc.placeholder.invalid`, unverified ([why](./installation.md#placeholder-emails)). +- **email**: an unverified placeholder, normally `@telegram-oidc.placeholder.invalid` for short email-safe subjects; opaque or long subjects use a bounded derived label ([why](./installation.md#placeholder-emails)). - an **account** with provider ID `telegram-oidc` and account ID `sub`. When the Login Widget or Mini App is also enabled, the Telegram columns exist and the plugin copies more details from the verified ID token after each OIDC sign-up, sign-in and link. When that changes the signed-in user, the plugin issues the new session cookie again with the stored user, so the session (including `session.cookieCache` and stateless mode) carries the new values right away. Framework cookie plugins such as `nextCookies()` must come last in `plugins`, as Better Auth requires, so they forward that cookie: @@ -200,7 +200,7 @@ export const membersOnly = telegram({ The example uses membership to decide whether sign-in is allowed. If you also store a membership or internal user ID for authorization, keep that field at `input: false` and write it through trusted server code; ordinary mapper fields can also be supplied to Better Auth's generic user-update endpoint. See [Custom user data](./configuration.md#custom-user-data). -If an OIDC account was unlinked, the old user keeps their email. If no remaining linked Telegram account proves the identity, a later sign-in uses a new reserved placeholder (`.@telegram-oidc.placeholder.invalid`) for a new user. The old email neither blocks sign-in nor reconnects the detached account. A remaining linked Telegram identity can still allow matching across methods, subject to the rules below. A custom mapper email follows your Better Auth account-linking policy. +If an OIDC account was unlinked, the old user keeps their email. If no remaining linked Telegram account proves the identity, a later sign-in uses a new reserved placeholder (normally `.@telegram-oidc.placeholder.invalid`; longer subjects use a bounded derived label) for a new user. The old email neither blocks sign-in nor reconnects the detached account. A remaining linked Telegram identity can still allow matching across methods, subject to the rules below. A custom mapper email follows your Better Auth account-linking policy. ## Use one user across sign-in methods @@ -315,6 +315,10 @@ This path is on by default, as for Better Auth's built-in providers. If you don' ## Things to know about Telegram's OIDC +OIDC account keys always retain the original `sub`. If that subject cannot be used directly in the technical placeholder email, the plugin uses a bounded subject-derived label for the email only. An email label never proves account ownership. + +Verified claims passed to your mapper have a nonempty string `sub`. The `aud` value is normalized to the configured client ID after checking that the token names no other audience, including when the JWT encodes that single audience as an array. + These come from Telegram's documentation and from testing against the live service on 2026-10-29. Where the two differ, the live behavior is noted. - **`sub` is not the Telegram user ID, and it is different for each bot.** The same person gets another `sub` from another bot (Telegram's discovery document says `public`, which would mean the same `sub` everywhere; live, it differs). The plugin stores OIDC accounts by `sub`, so changing the OIDC bot changes the account key. In OIDC-only mode this creates another user. With the Telegram columns, matching can retain the user when a verified profile `id` and a remaining linked account prove the same identity. Keep one OIDC bot for the life of your app rather than relying on that fallback. The real Telegram user ID is the `id` claim. diff --git a/docs/security.md b/docs/security.md index 3c7a046..faaa56e 100644 --- a/docs/security.md +++ b/docs/security.md @@ -60,6 +60,8 @@ 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. + **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. **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`. diff --git a/docs/testing-audit-2026-11-04.md b/docs/testing-audit-2026-11-04.md new file mode 100644 index 0000000..13eb68e --- /dev/null +++ b/docs/testing-audit-2026-11-04.md @@ -0,0 +1,144 @@ +# Test-quality audit: 2026-11-04 + +Reviewed the complete suite at release commit `8d6ec81`: 323 default-suite cases, +70 adapter variants, both declaration-consumer configurations, package acceptance, +and every shared fixture. The purpose was to detect incorrect behavior, not to +fill Codecov's 16 uncovered changed lines or preserve a test count. + +At the conclusion of this test-only pass, production implementation and public APIs +were unchanged. Subsequent runtime fixes belong to the separate +[deeper verification pass](deeper-verification-2026-11-04.md). + +## Decisions across the whole suite + +| Area and files | Decision and preserved contract | +| --- | --- | +| `client.test.ts` | Remove duplicated rendering/default/single-login cases. Replace log-count and sleep assertions with callback recovery, exact widget ownership and controlled script success/failure. Check documented server-side misuse. | +| `client.integration.test.ts` | Keep the real client/store and server. Consolidate basic wrapper checks into successful session scenarios. Challenge SDK/fragment disagreement, suppressed refresh and rejected sign-in. | +| `verify.test.ts`, `verify-hardening.test.ts` | Keep independent OpenSSL vectors, freshness boundaries and newline forgery protection. Move redundant parser/null-user assertions to their real endpoint owners. | +| `widget.integration.test.ts` | Replace no-write-spy-only checks with successful same-user SQL/session readback. Remove duplicate mapper and hook-call cases. Distinguish application refusal from a recoverable database race. | +| `miniapp.integration.test.ts` | Consolidate parsed-output/no-write coverage. Check sender identity, precise refusals, malformed user data and absent durable authentication writes. | +| `widget-mappers.integration.test.ts` | Keep async rejection and mapped-field contracts. Replace a generic non-200 placeholder assertion with the expected refusal and no persisted identity. | +| `oidc.test.ts` | Keep independently meaningful normalization, subject and mapping rules. Move credential checks to real endpoints. Replace isolated diagnostic tests with diagnostic output during a successful real login. | +| `oidc.integration.test.ts` | Require usable returning sessions, exact ownership, verified-email refusal and cached-key outage recovery. Preserve nonce/signature, key rotation, duplicate-account and hook-veto regressions. | +| `oidc-protocol.integration.test.ts` | Keep externally defined OAuth parameters, scope combinations and token checks. Exercise missing credentials through the actual request boundary. | +| `oidc-claims.integration.test.ts` | Keep the consumer's string operation and same-account result for numeric/string claims. Reviewed without changes. | +| `oidc-profile.integration.test.ts` | Check stored and cached-session output on failed profile updates. Use equal and changed Date/JSON inputs so a no-op update implementation fails. | +| `oidc-linking.integration.test.ts` | Require exact owner/refusal and unchanged durable authentication state. Add a throwing-policy case; distinguish each binding component. | +| `oidc-identity.integration.test.ts` | Consolidate duplicated lookup/cookie checks. Session-removal assertions require a successful preceding OAuth flow, so failed login cannot satisfy them. | +| `identity.integration.test.ts` | Combine unlink checks into actual loss of old-user access. Replace policy-call inspection with a policy that rejects the wrong method/action. | +| `hooks.integration.test.ts` | Keep real veto, rollback, stale-proof and distinct-identity concurrency scenarios. Their observable outcomes are meaningful. | +| `plugin-config.test.ts` | Keep documented diagnostic content and defaults. Remove equivalent malformed-input and silent-config duplicates. | +| `plugin.integration.test.ts` | Keep route/schema/config boundaries. Challenge rate windows at 59 and 61 seconds instead of testing only immediate throttling and eventual reset. | +| `better-auth-config.integration.test.ts` | Keep CSRF, linking restrictions, typed SQL IDs, bans, bearer and session contracts. Prove hidden data exists before asserting it is not disclosed. | +| `adapters.adapter.test.ts` | Keep all original real-adapter behaviors; strengthen owner/session checks with conflicting users and default linking policy. Add binding-hook refusal through nontransactional adapters. | +| `test/` | The Next.js directory is a manual Telegram playground, not an automated suite. Its setup/configuration and manual flow instructions were inspected; no live bot/browser acceptance is claimed. | +| `test-d/*`, `scripts/check-package.mjs` | Challenge erased input/output types. Add an actual `.cts` consumer. Authenticate and read back sessions through installed ESM and CommonJS bundles; invoke the installed client rather than checking only its export's existence. | + +Twenty-five redundant cases were removed or consolidated. Eleven cases were added +or moved into stronger default-suite owners, including server-side client misuse. +The default suite now has 309 cases, down from 323. Three new adapter behaviors +expand across five adapters, giving 85 variants: 78 run and seven existing +capability-dependent variants remain skipped. Counts describe scope, not success. + +## Fault experiments changed the review + +All faults were planted in a disposable source copy and restored after each run. +The shared checkout's production source was never mutated. + +The first 55 focused experiments detected 50 faults and left five survivors: + +- Two client tests asserted before Better Auth's delayed refresh. Removing either + the `disableSignal` or error guard still passed. The tests now control and drain + the real scheduler before checking requests/store state. Both faults then fail. +- Three prewrite binding-guard removals survived memory tests because a later + guard rejected the operation and the adapter rolled back. That result did not + establish the prewrite guarantee. The same removals now fail the durable-state + assertions on both Drizzle and Prisma with their default nontransactional + configuration, even though the HTTP response remains 409. + +The real-adapter binding test uses another existing user for a remapped `userId`. +A nonexistent ID could trigger a foreign-key failure and falsely appear to prove +our guard. After each database run, PostgreSQL/MySQL/MongoDB readback found no +remaining generated test databases; owned containers were then removed. + +Additional successful fault checks covered wrong returned/session owners, requiring +an undocumented trusted-provider setting, and wrong conflict status on serial/UUID +columns. One initial selector selected zero tests; it supplied no evidence and was +corrected before rerunning the conflict-status experiment. + +Other discriminating examples: + +| Fault | Observed failure | +| --- | --- | +| Swallow a throwing policy before linking | Unauthorized account state remains, despite the later refusal; state equality fails. | +| Create a session before rejecting policy | The error/cookie assertions still look correct, but the session-row assertion fails. | +| Treat an application refusal as a database conflict | Sign-in succeeds when it must be refused. | +| Drop cached JWKS between requests | A returning user cannot sign in during an issuer-key endpoint outage. | +| Trust a mapper's unverified email | The account-ownership/refusal assertions fail. | +| Return unchanged profile data for every update | Changed Date/JSON values do not appear in the user's session. | +| Remove per-user link serialization | The concurrent different-identity test observes two links instead of one accepted link and one conflict. | +| Reset a rate-limit window after one second | Requests at 59 seconds incorrectly succeed. | +| Erase Widget/Mini App input types to `any` | The consumer's rejected-input assertions become unused. | +| Erase the returned session type to `any` | The consumer's non-any output check fails. | +| Remove the session cookie only from built CommonJS | Installed ESM works; CommonJS cannot retrieve an authenticated session. | +| Remove the installed CommonJS client actions | Export existence still holds, but the real configuration request fails. | +| Suppress the documented missing-profile diagnostic | Authentication succeeds but the application's configured diagnostic sink lacks the warning. | + +These are targeted counterexamples, not an exhaustive mutation score or a proof +that no undiscovered bug exists. Production build/import failures were not counted as assertion evidence; +consumer compilation failures are the expected signal for declaration contracts. Restored code and installed-package checks pass. + +## Fixture reliability + +SQLite handles close after a test, including failed assertions and failed setup. +SQL fixtures drop only their generated databases after closing their pools; +Prisma's generated files and database are run-owned and cleaned up. Teardown waits +for all cleanup results before reporting errors. The fake Telegram rejects unknown +network calls and no longer overwrites explicit token issue/expiry times. + +Literal crypto vectors remain independent of the fixture signer. The fake issuer +substitutes Telegram, not Better Auth, JOSE or the database behavior under test. + +## Coverage gaps and limits + +Coverage floors were not lowered, and no production lines were excluded. The +remaining uncovered branches were assessed rather than filled with synthetic +internal-adapter stubs: + +- Missing users during late identity/profile/session synchronization are defensive + lifecycle paths. Ordinary veto/failure behavior has real integration coverage; + no claim is made that these rare disappearance schedules were exercised. +- Concurrent binding rechecks and conflict-recovery fast paths depend on schedules + not all controlled by this suite. The real-adapter concurrency checks establish + only the outcomes they execute, not universal scheduling coverage. +- The redundant missing-hash fast return is not a reason to duplicate the lower + signature rejection contract. An exceptional `window.location` getter is not + synthesized solely to execute its catch branch. +- The `updateUser(...) ?? user` fallback after metadata-refresh veto lacks a clear + independent policy for the successful-login outcome. This audit does not pin + that current output as a requirement or claim it is a confirmed production bug. + +The retained memory concurrency case uses a bounded hook rendezvous to widen the +race window, then awaits both actual operations and checks their outcomes. Its +lock-removal experiment fails; it does not establish cross-server serialization. + +Emulated DOM does not establish browser layout, iframe cookie policy or live +Telegram rendering. The signed fake issuer does not establish provider uptime or +live login acceptance. Cross-server first OIDC linking still has the documented +uniqueness limitation. No production bug was established by this audit. + +## Verification + +- `npm run test:coverage` on Node 24.22.2: 309 passed. Coverage is 98.45% lines, 98.47% statements, 95.12% branches and 100% functions. +- `npm test` on Node 26.13.0 and `bun --bun run test` on Bun 1.4.4: 309 passed in each runtime. +- Isolated installs of the complete Better Auth 1.7.12 and 1.7.16 families: type checks and all 309 default-suite cases passed in both. +- Real-adapter suite: 78 passed, seven capability-dependent variants skipped. All five adapter lanes ran. Three single-guard faults each failed on both Drizzle and Prisma; all 15 restored binding cases passed. +- `npm run lint`, `npm run type-check`, build with publint/ATTW, both declaration-consumer configurations and installed ESM/CommonJS package acceptance passed. +- All three deliberate declaration regressions compiled as packages but failed the consumer checks. Both deliberately broken CommonJS artifacts failed package acceptance; restored artifacts passed. +- A disposable fixture probe intentionally failed after opening SQLite; its next case observed the handle closed. Database readback after every adapter experiment found zero generated databases. Owned containers and temporary installs were removed. +- At the test-only audit handoff, production-file comparison against `8d6ec81` was unchanged. No mutation, coverage exclusion or threshold change remains in the repository. Largest test file: 455 code lines; largest shared fixture: 184. + +The method and current primary sources are in [Testing standards](testing.md), +including the 2026 study's distinction between triggering a fault and asserting +its consequence. diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..82f8416 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,147 @@ +# Testing standards + +A test earns its place by detecting a plausible violation of a requirement. +Executing code, preserving a test count, and increasing coverage are not goals. +These rules apply to new tests and to reviews of existing tests. + +## Decide what the test proves + +Before changing a test, identify the observable contract, where its expected +result comes from, and a plausible wrong implementation it must reject. A short +test name or comment is enough; do not add a repeated checklist to every case. + +Expected results come from a documented API, a consumer requirement, an incident, +or an independently checked example. They do not come from running today's code. +Do not calculate expectations with the production helper or copy its algorithm. +Cryptographic fixtures need literal independently derived vectors as well as +signed integration fixtures: an encoder and verifier can share the same defect. + +Choose inputs where the correct and incorrect behaviors differ. Examples here: + +- An identity match must return the intended existing user, including when a + different user is also present. A row count of one is insufficient. +- A rejected sign-in must return the expected error and create no session. Check + durable rows when the contract forbids writes; lack of a cookie alone does not + establish that no session was created. +- A returning sign-in must succeed with the right session and profile. Unchanged + database rows alone also pass if the second request did nothing. +- A stale widget's cleanup must not remove its replacement's callback. Invoke the + replacement and observe the result instead of inspecting a callback name alone. +- Time limits need inputs on both sides of the documented boundary. Freeze time + deliberately; do not freeze the property a concurrency or uniqueness test claims + to measure. + +## Keep the behavior owner real + +| Risk | Smallest credible boundary | +| --- | --- | +| HMAC format, ordering, freshness | Direct verifier with independent vectors and boundary inputs | +| User/account ownership, authorization, hooks, cookies | Real Better Auth request and response, with database/session readback | +| SQL constraints, rollback, driver behavior, concurrent servers | Disposable real database through the affected adapter | +| Client session refresh | Real Better Auth client store and controlled HTTP boundary | +| Widget lifecycle | Real DOM operations with controlled external script events | +| Package entrypoints and declarations | Built tarball installed outside the checkout, runtime calls and consumer type checks | + +Mocks are appropriate at the external provider or network boundary. Request +assertions are useful when they enforce Telegram's protocol, not when they merely +repeat an internal call. A fake database cannot prove a transaction; a mocked +session store cannot prove refresh behavior. DOM emulation cannot prove browser +layout, iframe cookie policy or Telegram's live UI. Report those limits. + +## Remove tests that do not discriminate + +Delete a case when its unique contract cannot be established or another test +already protects the same failure. A deletion does not require a replacement. +Keep incident regressions unless their exact protection demonstrably survives +elsewhere. + +Common deletion or rewrite candidates: + +- Calling a function and asserting only `toBeDefined`, truthiness, no throw, or an + unqualified mock call. These assertions can support a stronger test, but rarely + establish the behavior by themselves. +- Returning a value from a mock and expecting the same value without checking any + transformation or external contract. +- Source-text, file-presence, internal object-shape or export-existence assertions + presented as runtime correctness. Genuine packaging and type contracts belong in + the installed-consumer checks. +- Log-count assertions when the actual requirement is recovery or refusal. + Documented startup diagnostics are observable output and can have direct tests. +- Cases that differ only cosmetically, impossible typed states at a trusted + boundary, or fixtures where both branches yield the same expected value. + +Untrusted HTTP and provider data can violate TypeScript types. Malformed inputs +are meaningful at those boundaries. Do not use the type checker as a reason to +remove their validation tests. + +## Challenge the assertions + +For new or rewritten authentication, identity, privacy, or concurrency cases, +check a concrete fault: remove the relevant guard, select the wrong owner, omit +an awaited mapper, or suppress the promised state transition. Run only the test +that claims to catch it, and inspect the failure reason. + +Use a disposable source copy for fault injection when other sessions share the +checkout. Restore every fault before another experiment. A failed import, syntax +error, unselected test or unrelated failure is not evidence that the assertion +caught the defect. A surviving fault requires investigation: the test may be weak, +the change may be behaviorally equivalent, or the expectation may lack a contract. +Do not replace a surviving fault with an easier one just to obtain a green report. + +Targeted fault experiments are evidence, not a mutation-score target or a proof +of all possible correctness. They cannot discover a requirement absent from both +implementation and tests. For a wide input space, use a small boundary table or +properties with reproducible counterexamples when justified; do not install a new +framework merely to generate more cases. + +For an actual bug, first reproduce the contract violation with a focused failing +test. Do not change an expectation to bless incorrect output. During a test-only +audit, report a discovered production bug and its reproducer separately rather +than silently changing runtime behavior or deleting the failing requirement. + +## Isolation and completion + +Await explicit events, promises, or bounded observable outcomes. Do not use sleep +to guess when a callback or concurrent operation has finished. Unexpected network +requests must fail the test instead of reaching the real provider. Restore clocks, +globals, mocks and listeners; close SQLite handles, servers and database pools. +Release test-owned databases and generated fixtures after success or failure. +Never use shared development or production databases for these tests. + +Run the affected files while iterating. On the final tree, run each applicable +[project gate](../CONTRIBUTING.md#ci-and-releases) once. Preserve useful evidence +until the code, fixtures, environment or toolchain it depends on changes. Report +actual passes, intentional skips, the faults detected and boundaries not exercised. + +Coverage is a map for finding unexamined risks. Inspect uncovered lines and +branches, but do not add unreachable scenarios, duplicate tests or exclusions to +improve the number. Keep the existing coverage floors; if removing weak tests +exposes a real gap, address that behavior. A coverage comment is not itself a test +requirement. + +## Sources checked on 2026-11-04 + +- [Vitest: Writing Tests with AI](https://vitest.dev/guide/learn/writing-tests-with-ai) + and [Testing in Practice](https://vitest.dev/guide/learn/testing-in-practice): + review generated assertions and test observable contracts rather than internals. +- [Vitest: Mocking Requests](https://vitest.dev/guide/mocking/requests): fail on + unhandled external requests and reset handlers between tests. +- [Google: Code Coverage Best Practices](https://testing.googleblog.com/2020/08/code-coverage-best-practices.html): + coverage measures execution, and chasing 100% can produce low-value tests. + This is established guidance, not a new 2026 rule. +- [Stryker: Mutant states](https://stryker-mutator.io/docs/mutation-testing-elements/mutant-states-and-metrics/) + and [Equivalent mutants](https://stryker-mutator.io/docs/mutation-testing-elements/equivalent-mutants/): + distinguish detected defects, survivors, invalid mutations and equivalent changes. +- [fast-check: Why property-based testing](https://fast-check.dev/docs/introduction/why-property-based/): + generated inputs are useful when paired with a meaningful property, shrinking + and reproducible failures, not as random-data volume. +- [Hamidi et al., September 2026 preprint](https://arxiv.org/abs/2609.09315): + in its LLM-generated-code benchmark, weak test oracles limited actual fault + detection even when faults were exercised. This is evidence from that study, + not a claim that every project or generated test has the same defect rate. + +The review method also follows the user's established `testing-patterns` +conventions: independent expectations, the real behavior owner, named defects, +and removal of tests without unique protection. + +The [2026-11-04 audit](testing-audit-2026-11-04.md) records the first complete application of these rules to this repository. diff --git a/scripts/check-package.mjs b/scripts/check-package.mjs index 2555c1f..da80618 100644 --- a/scripts/check-package.mjs +++ b/scripts/check-package.mjs @@ -19,13 +19,6 @@ const packResult = JSON.parse( const packed = Array.isArray(packResult) ? packResult[0] : packResult[manifest.name]; -for (const name of ["index", "client"]) { - for (const extension of ["js", "cjs", "d.ts", "d.cts"]) { - assert( - packed.files.some((file) => file.path === `dist/${name}.${extension}`) - ); - } -} assert(!packed.files.some((file) => /(?:^|\/)\.env(?:\.|$)/u.test(file.path))); // A fresh consumer outside the checkout cannot resolve missing dependencies @@ -73,28 +66,42 @@ try { stdio: "inherit", }); } - execFileSync( - process.execPath, - [ - "--input-type=module", - "--eval", - ` - import assert from "node:assert/strict"; - import { createHash, createHmac } from "node:crypto"; - import { betterAuth } from "better-auth"; - import { memoryAdapter } from "better-auth/adapters/memory"; - import { telegram } from "better-auth-telegram"; - import { telegramClient } from "better-auth-telegram/client"; - assert.equal(typeof telegramClient, "function"); + // Both export formats must authenticate through their installed bundle. + // Merely finding a CommonJS function would miss a broken server export. + const imports = { + module: `import assert from "node:assert/strict"; +import { createHash, createHmac } from "node:crypto"; +import { betterAuth } from "better-auth"; +import { createAuthClient } from "better-auth/client"; +import { memoryAdapter } from "better-auth/adapters/memory"; +import { telegram } from "better-auth-telegram"; +import { telegramClient } from "better-auth-telegram/client";`, + commonjs: `const assert = require("node:assert/strict"); +const { createHash, createHmac } = require("node:crypto"); +const { betterAuth } = require("better-auth"); +const { createAuthClient } = require("better-auth/client"); +const { memoryAdapter } = require("better-auth/adapters/memory"); +const { telegram } = require("better-auth-telegram"); +const { telegramClient } = require("better-auth-telegram/client");`, + }; + const authenticate = ` + const db = { user: [], account: [], session: [], verification: [] }; const auth = betterAuth({ baseURL: "http://localhost:3000", secret: "package-consumer-test-secret-0123456789abcdef", - database: memoryAdapter({ user: [], account: [], session: [], verification: [] }), + database: memoryAdapter(db), plugins: [telegram({ botToken: "123456789:package_test_token", botUsername: "test_bot" })], }); - const response = await auth.handler(new Request("http://localhost:3000/api/auth/telegram/config")); - assert.equal(response.status, 200); - assert.equal((await response.json()).botUsername, "test_bot"); + const client = createAuthClient({ + baseURL: "http://localhost:3000", + plugins: [telegramClient()], + fetchOptions: { + customFetchImpl: (input, init) => auth.handler(new Request(input, init)), + }, + }); + const config = await client.getTelegramConfig(); + assert.equal(config.error, null); + assert.equal(config.data.botUsername, "test_bot"); const data = { id: 42, first_name: "Ann", auth_date: Math.floor(Date.now() / 1000) }; const signed = Object.keys(data).sort().map((key) => key + "=" + data[key]).join("\\n"); const key = createHash("sha256").update("123456789:package_test_token").digest(); @@ -108,23 +115,32 @@ try { const session = await signIn.json(); assert.equal(session.user.telegramId, "42"); assert.equal(typeof session.session.token, "string"); - `, - ], - { cwd: consumer, stdio: "inherit" } - ); - execFileSync( - process.execPath, - [ - "--input-type=commonjs", - "--eval", - ` - const assert = require("node:assert/strict"); - assert.equal(typeof require("better-auth-telegram").telegram, "function"); - assert.equal(typeof require("better-auth-telegram/client").telegramClient, "function"); - `, - ], - { cwd: consumer, stdio: "inherit" } - ); + const cookies = signIn.headers.getSetCookie().map((cookie) => cookie.split(";")[0]).join("; "); + const readback = await auth.handler(new Request("http://localhost:3000/api/auth/get-session", { + headers: { cookie: cookies }, + })); + assert.equal(readback.status, 200); + const activeSession = await readback.json(); + assert.ok(activeSession, "The issued cookie must retrieve an authenticated session"); + assert.equal(activeSession.user.id, session.user.id); + assert.equal(db.user.length, 1); + assert.equal(db.session[0].userId, session.user.id); + `; + for (const format of ["module", "commonjs"]) { + execFileSync( + process.execPath, + [ + `--input-type=${format}`, + "--eval", + `${imports[format]} +(async () => { ${authenticate} })().catch((error) => { + console.error(error); + process.exitCode = 1; +});`, + ], + { cwd: consumer, stdio: "inherit" } + ); + } console.log( `Verified ${packed.filename}: installed ESM, CommonJS and consumer types on ${process.version}.` ); diff --git a/src/adapters.adapter.test.ts b/src/adapters.adapter.test.ts index 2d80f1d..ee5161a 100644 --- a/src/adapters.adapter.test.ts +++ b/src/adapters.adapter.test.ts @@ -42,9 +42,19 @@ describe.each(adapterLanes())("$name", (lane) => { }); afterEach(async () => { - telegramMock.restore(); - await Promise.all(opened.map((harness) => harness.close())); + telegramMock?.restore(); + const closing = opened; opened = []; + const results = await Promise.allSettled( + closing.map((harness) => harness.close()) + ); + const failures = results.filter((result) => result.status === "rejected"); + if (failures.length) { + throw new AggregateError( + failures.map((result) => result.reason), + "Adapter fixture cleanup failed" + ); + } }); const open = async (authOptions = {}, pluginOptions = {}) => { @@ -108,21 +118,32 @@ describe.each(adapterLanes())("$name", (lane) => { }); }); - test("signs a Mini App user into the Login Widget user", async () => { + test("selects the matching Widget user for Mini App sign-in among different users", async () => { const { client, rows } = await open(); - await client.post( + const unrelated = await client.post( + "/telegram/signin", + await signWidgetData({ id: 17, first_name: "Other" }) + ); + client.clearCookies(); + const widget = await client.post( "/telegram/signin", await signWidgetData({ id: TELEGRAM_ID }) ); + expect([unrelated.status, widget.status]).toEqual([200, 200]); + expect(widget.json.user.id).not.toBe(unrelated.json.user.id); client.clearCookies(); const response = await client.post("/telegram/miniapp/signin", { initData: await signInitData({ id: TELEGRAM_ID }), }); + const session = await client.get("/get-session"); expect(response.status).toBe(200); - expect(await rows("user")).toHaveLength(1); - expect(await rows("account")).toHaveLength(1); + expect(response.json.user.id).toBe(widget.json.user.id); + expect(response.json.session.userId).toBe(widget.json.user.id); + expect(session.json.user.id).toBe(widget.json.user.id); + expect(await rows("user")).toHaveLength(2); + expect(await rows("account")).toHaveLength(2); }); test("copies the Telegram identity from OIDC, so the Mini App finds that user", async () => { @@ -153,12 +174,37 @@ describe.each(adapterLanes())("$name", (lane) => { ]); }); + test("stores an opaque OIDC subject without using it as an email local part", async () => { + const { client, rows } = await open(); + const sub = "urn:telegram:user:42"; + const { location } = await signInWithTelegramOIDC( + client, + telegramMock, + telegramClaims({ sub }) + ); + const session = await client.get("/get-session"); + + expect(location).toBe("/dashboard"); + const [user] = await rows("user"); + expect(session.json.user.id).toBe(user!.id); + const [local, domain] = user!.email.split("@"); + expect(local.length).toBeLessThanOrEqual(64); + expect(domain).toBe("telegram-oidc.placeholder.invalid"); + expect(await rows("account")).toEqual([ + expect.objectContaining({ + providerId: "telegram-oidc", + accountId: sub, + userId: user!.id, + }), + ]); + }); + test.each(["Login Widget", "Mini App"])( "signs the existing %s user in through OIDC without changing their email", async (method) => { const mappedEmail = () => ({ email: "ann@example.com" }); const { client, rows } = await open( - {}, + { account: { accountLinking: {} } }, { mapTelegramDataToUser: mappedEmail, miniApp: { @@ -212,7 +258,9 @@ describe.each(adapterLanes())("$name", (lane) => { ); test("links concurrent first OIDC sign-ins to one existing Mini App user", async () => { - const { auth, client, rows } = await open(); + const { auth, client, rows } = await open({ + account: { accountLinking: {} }, + }); const first = await client.post("/telegram/miniapp/signin", { initData: await signInitData({ id: TELEGRAM_ID }), }); @@ -264,6 +312,60 @@ describe.each(adapterLanes())("$name", (lane) => { } ); + // Drizzle/Prisma defaults do not roll back a write after a later guard throws. + // Check durable rows, with a valid second owner so foreign keys cannot hide a bad link. + test.each(["accountId", "providerId", "userId"] as const)( + "rejects account hooks changing OIDC %s without persisting a binding", + async (field) => { + let otherUserId = ""; + const { auth, client, rows } = await open({ + databaseHooks: { + account: { + create: { + before: (account: { + providerId: string; + [key: string]: unknown; + }) => { + if (account.providerId === "telegram-oidc") { + const replacement = + field === "userId" ? otherUserId : "different-binding"; + return { data: { ...account, [field]: replacement } }; + } + }, + }, + }, + }, + }); + const original = await client.post("/telegram/miniapp/signin", { + initData: await signInitData({ id: TELEGRAM_ID }), + }); + expect(original.status).toBe(200); + const other = createClient(auth); + await signUp(other); + const otherSession = await other.get("/get-session"); + expect(otherSession.status).toBe(200); + otherUserId = otherSession.json.user.id; + expect(otherUserId).not.toBe(original.json.user.id); + const before = { + users: await rows("user"), + accounts: await rows("account"), + sessions: await rows("session"), + }; + client.clearCookies(); + + const { callback } = await signInWithTelegramOIDC(client, telegramMock); + + expect(callback.status).toBe(409); + expect(callback.json.code).toBe("TELEGRAM_ALREADY_LINKED_OTHER"); + expect(client.hasSession()).toBe(false); + expect({ + users: await rows("user"), + accounts: await rows("account"), + sessions: await rows("session"), + }).toEqual(before); + } + ); + test("links and unlinks Telegram, and unlinking revokes the telegramId sign-in", async () => { const { auth, client, rows } = await open(); await signUp(client); @@ -276,17 +378,31 @@ describe.each(adapterLanes())("$name", (lane) => { const unlink = await client.post("/telegram/unlink", {}); // Unlinked: the Telegram user signs up anew instead of into Ann. const stranger = createClient(auth); - await stranger.post( + const newSignIn = await stranger.post( "/telegram/signin", await signWidgetData({ id: TELEGRAM_ID }) ); + const newSession = await stranger.get("/get-session"); - expect([link.status, unlink.status]).toEqual([200, 200]); + expect([link.status, unlink.status, newSignIn.status]).toEqual([ + 200, 200, 200, + ]); expect(linked.telegramId).toBe("8306595751"); const users = await rows("user"); const ann = users.find((user) => user.email === "ann@example.com")!; expect(ann.telegramId ?? null).toBeNull(); expect(users).toHaveLength(2); + expect(newSignIn.json.user.id).not.toBe(ann.id); + expect(newSession.json.user.id).toBe(newSignIn.json.user.id); + const accounts = await rows("account"); + expect( + accounts + .filter((account) => account.userId === ann.id) + .map((account) => account.providerId) + ).toEqual(["credential"]); + expect( + accounts.find((account) => account.providerId === "telegram")?.userId + ).toBe(newSignIn.json.user.id); }); test("clears telegramId when the OIDC account is unlinked through Better Auth", async () => { @@ -358,8 +474,12 @@ describe.each(adapterLanes())("$name", (lane) => { expect(responses.map((response) => response.status)).toEqual([ 200, 200, 200, 200, ]); - expect(await first.rows("user")).toHaveLength(1); + const users = await first.rows("user"); + expect(users).toHaveLength(1); expect(await first.rows("account")).toHaveLength(1); + expect(responses.map((response) => response.json.session.userId)).toEqual( + new Array(4).fill(users[0]!.id) + ); }); }); @@ -391,7 +511,9 @@ describe.each(adapterLanes())("$name", (lane) => { await signWidgetData({ id: TELEGRAM_ID }) ); - expect(self.status).toBe(200); + expect([self.status, foreign.status, again.status]).toEqual([ + 200, 409, 409, + ]); expect(foreign.json.code).toBe("TELEGRAM_ALREADY_LINKED_OTHER"); expect(again.json.code).toBe("TELEGRAM_ALREADY_LINKED_SELF"); expect(providers(await rows("account"))).toEqual([ diff --git a/src/better-auth-config.integration.test.ts b/src/better-auth-config.integration.test.ts index 40871de..458a3ed 100644 --- a/src/better-auth-config.integration.test.ts +++ b/src/better-auth-config.integration.test.ts @@ -242,65 +242,72 @@ describe("session.cookieCache", () => { describe("custom table and column names", () => { it("signs in with the Login Widget and OIDC on renamed models and fields", async () => { const sqlite = new DatabaseSync(":memory:"); - const options = { - baseURL: BASE_URL, - secret: "better-auth-telegram-test-secret-0123456789abcdef", - logger: { disabled: true }, - database: sqlite, - user: { modelName: "users", fields: { email: "email_address" } }, - account: { modelName: "accounts", fields: { accountId: "account_id" } }, - session: { modelName: "sessions", fields: { userId: "user_id" } }, - plugins: [ - telegram({ - botToken: BOT_TOKEN, - botUsername: "test_bot", - oidc: oidc(), - }), - ], - }; - const { runMigrations } = await getMigrations(options); - await runMigrations(); - const client = createClient(betterAuth(options)); - - const widget = await client.post( - "/telegram/signin", - await signWidgetData({ id: 42 }) - ); - client.clearCookies(); - const again = await client.post( - "/telegram/signin", - await signWidgetData({ id: 42 }) - ); - client.clearCookies(); - const { location } = await signInWithTelegramOIDC( - client, - telegramMock, - telegramClaims({ id: "43" }) - ); + try { + const options = { + baseURL: BASE_URL, + secret: "better-auth-telegram-test-secret-0123456789abcdef", + logger: { disabled: true }, + database: sqlite, + user: { modelName: "users", fields: { email: "email_address" } }, + account: { modelName: "accounts", fields: { accountId: "account_id" } }, + session: { modelName: "sessions", fields: { userId: "user_id" } }, + plugins: [ + telegram({ + botToken: BOT_TOKEN, + botUsername: "test_bot", + oidc: oidc(), + }), + ], + }; + const { runMigrations } = await getMigrations(options); + await runMigrations(); + const client = createClient(betterAuth(options)); + + const widget = await client.post( + "/telegram/signin", + await signWidgetData({ id: 42 }) + ); + client.clearCookies(); + const again = await client.post( + "/telegram/signin", + await signWidgetData({ id: 42 }) + ); + client.clearCookies(); + const { location } = await signInWithTelegramOIDC( + client, + telegramMock, + telegramClaims({ id: "43" }) + ); - expect([widget.status, again.status, location]).toEqual([ - 200, - 200, - "/dashboard", - ]); - const rows = (sql: string) => sqlite.prepare(sql).all(); - expect( - rows( - 'select email_address, "telegramId" from users order by email_address' - ) - ).toEqual([ - { - email_address: "12224742808376279442@telegram-oidc.placeholder.invalid", - telegramId: "43", - }, - { email_address: "42@telegram.placeholder.invalid", telegramId: "42" }, - ]); - expect( - rows('select account_id, "providerId" from accounts order by account_id') - ).toEqual([ - { account_id: "12224742808376279442", providerId: "telegram-oidc" }, - { account_id: "42", providerId: "telegram" }, - ]); + expect([widget.status, again.status, location]).toEqual([ + 200, + 200, + "/dashboard", + ]); + const rows = (sql: string) => sqlite.prepare(sql).all(); + expect( + rows( + 'select email_address, "telegramId" from users order by email_address' + ) + ).toEqual([ + { + email_address: + "12224742808376279442@telegram-oidc.placeholder.invalid", + telegramId: "43", + }, + { email_address: "42@telegram.placeholder.invalid", telegramId: "42" }, + ]); + expect( + rows( + 'select account_id, "providerId" from accounts order by account_id' + ) + ).toEqual([ + { account_id: "12224742808376279442", providerId: "telegram-oidc" }, + { account_id: "42", providerId: "telegram" }, + ]); + } finally { + sqlite.close(); + } }); }); @@ -388,6 +395,7 @@ describe("fields marked returned: false", () => { expect(response.status).toBe(200); expect(db.user[0]!.secretNote).toBe("s3cret"); + expect(db.session[0]!.deviceSecret).toBe("d3vice"); expect(response.text).not.toContain("s3cret"); expect(response.text).not.toContain("d3vice"); expect(response.json.user.telegramId).toBe("42"); @@ -450,7 +458,6 @@ describe("bearer plugin", () => { }) ); - expect(token).toBeTruthy(); expect((await session.json()).user.telegramId).toBe("42"); }); }); diff --git a/src/client-lifecycle.integration.test.ts b/src/client-lifecycle.integration.test.ts new file mode 100644 index 0000000..2440db3 --- /dev/null +++ b/src/client-lifecycle.integration.test.ts @@ -0,0 +1,93 @@ +// @vitest-environment happy-dom +import { afterEach, expect, it as test, vi } from "vitest"; +import { + createTelegramWidgetActions, + type TelegramWidget, +} from "./client-widget"; +import type { TelegramAuthData } from "./types"; + +const handles: TelegramWidget[] = []; +const callbacks = new Set(); + +function pendingConfig() { + let resolve!: (value: { data: { botUsername: string } }) => void; + const promise = new Promise<{ data: { botUsername: string } }>((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +function callbackFrom(element: HTMLElement) { + const script = element.querySelector("script")!; + const name = script.getAttribute("data-onauth")!.replace(/\(user\)$/u, ""); + callbacks.add(name); + return (window as any)[name] as (user: TelegramAuthData) => Promise; +} + +afterEach(() => { + for (const handle of handles.splice(0)) { + handle.destroy(); + } + for (const callback of callbacks) { + delete (window as any)[callback]; + } + callbacks.clear(); + document.body.innerHTML = ""; + document.head.innerHTML = ""; + vi.unstubAllGlobals(); +}); + +test.each(["callback", "redirect"] as const)( + "keeps the newest requested widget when an older %s configuration arrives last", + async (mode) => { + (window as any).Telegram = { Login: {} }; + const host = document.createElement("div"); + document.body.appendChild(host); + const oldConfig = pendingConfig(); + const newConfig = pendingConfig(); + const fetch = vi + .fn() + .mockReturnValueOnce(oldConfig.promise) + .mockReturnValueOnce(newConfig.promise); + const actions = createTelegramWidgetActions(fetch as any); + const oldLogin = vi.fn(); + const newLogin = vi.fn(); + const oldInitialization = + mode === "callback" + ? actions.initTelegramWidget(host, { size: "small" }, oldLogin) + : actions.initTelegramWidgetRedirect(host, "/obsolete", { + size: "small", + }); + const newInitialization = actions.initTelegramWidget( + host, + { size: "large" }, + newLogin + ); + + newConfig.resolve({ data: { botUsername: "current_bot" } }); + const current = await newInitialization; + handles.push(current); + oldConfig.resolve({ data: { botUsername: "obsolete_bot" } }); + const obsolete = await oldInitialization; + handles.push(obsolete); + + const user: TelegramAuthData = { + id: 42, + first_name: "Ann", + auth_date: 1, + hash: "x", + }; + await callbackFrom(host)(user); + expect(newLogin).toHaveBeenCalledExactlyOnceWith(user); + expect(oldLogin).not.toHaveBeenCalled(); + expect( + host.querySelector("script")!.getAttribute("data-telegram-login") + ).toBe("current_bot"); + obsolete.destroy(); + expect(host.querySelector("script")!.getAttribute("data-size")).toBe( + "large" + ); + current.destroy(); + expect(host.children).toHaveLength(0); + } +); diff --git a/src/client-widget.ts b/src/client-widget.ts index 2f80f8b..757474c 100644 --- a/src/client-widget.ts +++ b/src/client-widget.ts @@ -66,6 +66,9 @@ function loadTelegramWidgetScript(): Promise { return widgetScriptLoading; } +// A late response must not replace a newer initialization of the same host. +const pendingRenders = new WeakMap(); + let widgetCount = 0; /** A global name for a widget's `data-onauth` callback that no widget uses yet. */ @@ -116,13 +119,19 @@ async function renderWidget( container: string | HTMLElement, options: TelegramWidgetOptions, loginAttributes: Record -): Promise { +): Promise { + const element = resolveContainer(container); + const request = Symbol("widget initialization"); + pendingRenders.set(element, request); await loadTelegramWidgetScript(); const configResponse = await $fetch( "/telegram/config", { method: "GET" } ); + if (pendingRenders.get(element) !== request) { + return null; + } if (!configResponse.data) { throw new Error("Failed to get Telegram config"); } @@ -135,7 +144,6 @@ async function renderWidget( lang, } = options; - const element = resolveContainer(container); element.innerHTML = ""; const script = document.createElement("script"); @@ -200,6 +208,9 @@ export function createTelegramWidgetActions($fetch: BetterFetch) { const widget = await renderWidget($fetch, container, options, { "data-onauth": `${callbackName}(user)`, }); + if (!widget) { + return { destroy: () => {} }; + } (window as any)[callbackName] = async (authData: TelegramAuthData) => { try { await onAuth(authData); @@ -240,8 +251,8 @@ export function createTelegramWidgetActions($fetch: BetterFetch) { redirectUrl: string, options: TelegramWidgetOptions = {} ): Promise => - await renderWidget($fetch, container, options, { + (await renderWidget($fetch, container, options, { "data-auth-url": redirectUrl, - }), + })) ?? { destroy: () => {} }, }; } diff --git a/src/client.integration.test.ts b/src/client.integration.test.ts index d84fdf6..7c71520 100644 --- a/src/client.integration.test.ts +++ b/src/client.integration.test.ts @@ -66,32 +66,16 @@ function setup() { } type Setup = ReturnType; +const sessionSubscriptions: (() => void)[] = []; afterEach(() => { + for (const unsubscribe of sessionSubscriptions.splice(0)) { + unsubscribe(); + } vi.unstubAllGlobals(); }); describe("client actions against the real server", () => { - it("signInWithTelegram signs the Telegram user in", async () => { - const { client } = setup(); - - const { data, error } = await client.signInWithTelegram( - (await signWidgetData({ id: 42 })) as any - ); - - expect(error).toBeNull(); - expect((data as any).user.telegramId).toBe("42"); - }); - - it("signInWithTelegram surfaces the server's 400 for an unsigned payload", async () => { - const { client } = setup(); - - const { data, error } = await client.signInWithTelegram({ id: 42 } as any); - - expect(data).toBeNull(); - expect(error?.status).toBe(400); - }); - it("linkTelegram and unlinkTelegram change the signed-in user's accounts", async () => { const { client, db, signUp } = setup(); await signUp(); @@ -126,23 +110,20 @@ describe("client actions against the real server", () => { it("getTelegramConfig returns the server's bot username", async () => { const { client } = setup(); - const { data } = await client.getTelegramConfig(); - - expect(data?.botUsername).toBe("test_bot"); - }); - - it("signInWithMiniApp signs the Mini App user in", async () => { - const { client } = setup(); + const { data, error } = await client.getTelegramConfig(); - const { data } = await client.signInWithMiniApp( - await signInitData({ id: 7 }) - ); - - expect((data as any).user.telegramId).toBe("7"); + expect(error).toBeNull(); + expect(data).toEqual({ + botUsername: "test_bot", + loginWidgetEnabled: true, + miniAppEnabled: true, + oidcEnabled: true, + testMode: false, + }); }); - it("validateMiniApp reports valid initData with the parsed user", async () => { - const { client } = setup(); + it("validateMiniApp parses valid data without signing the user in", async () => { + const { client, db } = setup(); const { data } = await client.validateMiniApp( await signInitData({ id: 7 }) @@ -150,27 +131,24 @@ describe("client actions against the real server", () => { expect(data?.valid).toBe(true); expect(data?.data.user.id).toBe(7); + expect([db.user.length, db.account.length, db.session.length]).toEqual([ + 0, 0, 0, + ]); }); - it("autoSignInFromMiniApp signs in with Telegram.WebApp.initData", async () => { - const { client } = setup(); - vi.stubGlobal("window", { - Telegram: { WebApp: { initData: await signInitData({ id: 7 }) } }, - location: { hash: "" }, - }); - - const { data } = await client.autoSignInFromMiniApp(); - - expect((data as any).user.telegramId).toBe("7"); - }); - - it("signInWithTelegramOIDC returns Telegram's authorization URL to redirect to", async () => { - const { client } = setup(); + it("signInWithTelegramOIDC forwards both callback URLs to the social-login protocol", async () => { + const { client, requests } = setup(); const { data } = await client.signInWithTelegramOIDC({ callbackURL: "/dashboard", + errorCallbackURL: "/login", }); + expect(await requests[0]!.json()).toEqual({ + provider: "telegram-oidc", + callbackURL: "/dashboard", + errorCallbackURL: "/login", + }); expect((data as any).redirect).toBe(true); expect((data as any).url).toMatch( /^https:\/\/oauth\.telegram\.org\/auth\?/u @@ -188,10 +166,10 @@ describe("the session store follows Telegram sign-in, link and unlink", () => { */ async function watchSession(client: Setup["client"]) { const unsubscribe = client.useSession.subscribe(() => undefined); + sessionSubscriptions.push(unsubscribe); await client.useSession.get().refetch(); return { telegramId: () => client.useSession.get().data?.user.telegramId ?? null, - unsubscribe, }; } @@ -214,7 +192,9 @@ describe("the session store follows Telegram sign-in, link and unlink", () => { async (client) => { vi.stubGlobal("window", { Telegram: { WebApp: { initData: await signInitData({ id: 42 }) } }, - location: { hash: "" }, + location: { + hash: `#tgWebAppData=${encodeURIComponent(await signInitData({ id: 99 }))}`, + }, }); return client.autoSignInFromMiniApp(); }, @@ -228,10 +208,77 @@ describe("the session store follows Telegram sign-in, link and unlink", () => { const { client } = setup(); const session = await watchSession(client); - await signIn(client); + const result = (await signIn(client)) as { + data: { user: { telegramId: string } }; + error: unknown; + }; + expect(result.error).toBeNull(); + expect(result.data.user.telegramId).toBe("42"); await settles(() => expect(session.telegramId()).toBe("42")); - session.unsubscribe(); + }); + + it("disableSignal keeps the mounted session unchanged until an explicit refresh", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + const { client, requests } = setup(); + const session = await watchSession(client); + const requestCount = requests.length; + + const response = await client.signInWithTelegram( + (await signWidgetData({ id: 42 })) as any, + { disableSignal: true } + ); + // Better Auth schedules signal-driven refreshes after the action resolves. + await vi.runOnlyPendingTimersAsync(); + + expect(response.error).toBeNull(); + expect(response.data?.user.telegramId).toBe("42"); + expect( + requests + .slice(requestCount) + .map((request) => new URL(request.url).pathname) + ).toEqual(["/api/auth/telegram/signin"]); + expect(session.telegramId()).toBeNull(); + await client.useSession.get().refetch(); + expect(session.telegramId()).toBe("42"); + } finally { + for (const unsubscribe of sessionSubscriptions.splice(0)) { + unsubscribe(); + } + await vi.runOnlyPendingTimersAsync(); + vi.useRealTimers(); + } + }); + + it("a rejected sign-in returns the error without refreshing or changing the session", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + const { client, requests, db } = setup(); + const session = await watchSession(client); + const requestCount = requests.length; + + const response = await client.signInWithTelegram({ id: 42 } as any); + await vi.runOnlyPendingTimersAsync(); + + expect(response.data).toBeNull(); + expect(response.error?.code).toBe("INVALID_AUTH_DATA"); + expect( + requests + .slice(requestCount) + .map((request) => new URL(request.url).pathname) + ).toEqual(["/api/auth/telegram/signin"]); + expect(session.telegramId()).toBeNull(); + expect([db.user.length, db.account.length, db.session.length]).toEqual([ + 0, 0, 0, + ]); + } finally { + for (const unsubscribe of sessionSubscriptions.splice(0)) { + unsubscribe(); + } + await vi.runOnlyPendingTimersAsync(); + vi.useRealTimers(); + } }); it("linkTelegram and unlinkTelegram update session.user", async () => { @@ -247,7 +294,6 @@ describe("the session store follows Telegram sign-in, link and unlink", () => { await settles(() => expect(session.telegramId()).toBe("42")); await client.unlinkTelegram(); await settles(() => expect(session.telegramId()).toBeNull()); - session.unsubscribe(); }); }); diff --git a/src/client.test.ts b/src/client.test.ts index f51f1cd..485c1bb 100644 --- a/src/client.test.ts +++ b/src/client.test.ts @@ -7,7 +7,7 @@ * supplies the bot configuration the widget needs. */ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { telegramClient } from "./client"; +import { type TelegramWidget, telegramClient } from "./client"; import type { TelegramAuthData } from "./types"; const WIDGET_SCRIPT = "https://telegram.org/js/telegram-widget.js?24"; @@ -21,10 +21,25 @@ const ann: TelegramAuthData = { const bob: TelegramAuthData = { ...ann, id: 43, first_name: "Bob" }; let $fetch: ReturnType; +const renderedWidgets: TelegramWidget[] = []; function actions() { const $store = { notify: vi.fn(), listen: vi.fn(), atoms: {} }; - return telegramClient().getActions($fetch as any, $store); + const client = telegramClient().getActions($fetch as any, $store); + const remember = async (promise: Promise) => { + const widget = await promise; + renderedWidgets.push(widget); + return widget; + }; + return { + ...client, + initTelegramWidget: ( + ...args: Parameters + ) => remember(client.initTelegramWidget(...args)), + initTelegramWidgetRedirect: ( + ...args: Parameters + ) => remember(client.initTelegramWidgetRedirect(...args)), + }; } function addContainer(id: string) { @@ -42,7 +57,7 @@ function widgetScript(containerId = "telegram-login") { function telegramLogsIn(containerId: string, user: TelegramAuthData) { const onauth = widgetScript(containerId).getAttribute("data-onauth")!; const name = onauth.replace(/\(user\)$/u, ""); - (window as any)[name](user); + return (window as any)[name](user) as Promise; } beforeEach(() => { @@ -56,12 +71,35 @@ beforeEach(() => { }); afterEach(() => { + for (const widget of renderedWidgets.splice(0)) { + widget.destroy(); + } vi.useRealTimers(); vi.restoreAllMocks(); - (window as any).happyDOM.settings.handleDisabledFileLoadingAsSuccess = true; }); describe("initTelegramWidget", () => { + it("preserves existing content when the configuration request fails", async () => { + const container = document.getElementById("telegram-login")!; + container.textContent = "Please try again"; + $fetch.mockResolvedValueOnce({ data: null, error: { status: 503 } }); + + await expect( + actions().initTelegramWidget(container, {}, () => {}) + ).rejects.toThrow("Failed to get Telegram config"); + + expect(container.textContent).toBe("Please try again"); + expect(container.querySelector("script")).toBeNull(); + }); + + it("rejects a missing container without mounting a widget elsewhere", async () => { + await expect( + actions().initTelegramWidget("missing", {}, () => {}) + ).rejects.toThrow('Container with id "missing" not found'); + + expect(document.getElementById("telegram-login")!.children).toHaveLength(0); + }); + it("rejects instead of rendering a widget for an empty bot username", async () => { $fetch.mockResolvedValueOnce({ data: { botUsername: "" } }); @@ -119,15 +157,6 @@ describe("initTelegramWidget", () => { expect(widgetScript().getAttribute("data-request-access")).toBe("write"); }); - it("passes the user Telegram returns to onAuth", async () => { - const onAuth = vi.fn(); - await actions().initTelegramWidget("telegram-login", {}, onAuth); - - telegramLogsIn("telegram-login", ann); - - expect(onAuth).toHaveBeenCalledExactlyOnceWith(ann); - }); - it("routes each widget's login to its own onAuth, even when created in the same millisecond", async () => { vi.useFakeTimers({ toFake: ["Date"] }); vi.setSystemTime(1_761_730_000_000); @@ -154,29 +183,21 @@ describe("initTelegramWidget", () => { expect(onAuth.mock.calls).toEqual([[ann], [bob]]); }); - it("reports a failing onAuth with console.error instead of an unhandled rejection", async () => { + it("contains a rejected onAuth and still delivers the next login", async () => { const failure = new Error("sign-in failed"); - const consoleError = vi - .spyOn(console, "error") - .mockImplementation(() => {}); - const unhandled = vi.fn(); - process.on("unhandledRejection", unhandled); - try { - await actions().initTelegramWidget("telegram-login", {}, () => - Promise.reject(failure) - ); + vi.spyOn(console, "error").mockImplementation(() => {}); + const received: number[] = []; + await actions().initTelegramWidget("telegram-login", {}, (user) => { + if (user.id === ann.id) { + return Promise.reject(failure); + } + received.push(user.id); + }); - telegramLogsIn("telegram-login", ann); - await new Promise((resolve) => setTimeout(resolve, 10)); + await telegramLogsIn("telegram-login", ann); + await telegramLogsIn("telegram-login", bob); - expect(consoleError).toHaveBeenCalledWith( - expect.stringContaining("onAuth"), - failure - ); - expect(unhandled).not.toHaveBeenCalled(); - } finally { - process.off("unhandledRejection", unhandled); - } + expect(received).toEqual([43]); }); }); @@ -188,6 +209,8 @@ describe("widget containers and teardown (React refs, StrictMode, HMR)", () => { function telegramRendersIframe(container: HTMLElement) { const script = container.querySelector("script")!; const iframe = document.createElement("iframe"); + // Only DOM ownership matters here; do not navigate to an external frame. + iframe.srcdoc = "Telegram fixture"; iframe.id = "telegram-login-test_bot"; container.insertBefore(iframe, script); (script as any)._iframe = iframe; @@ -247,13 +270,16 @@ describe("widget containers and teardown (React refs, StrictMode, HMR)", () => { () => {} ); telegramRendersIframe(container); - await actions().initTelegramWidget("telegram-login", {}, () => {}); + const laterLogin = vi.fn(); + await actions().initTelegramWidget("telegram-login", {}, laterLogin); telegramRendersIframe(container); first.destroy(); + await telegramLogsIn("telegram-login", bob); expect(container.querySelectorAll("script")).toHaveLength(1); expect(container.querySelectorAll("iframe")).toHaveLength(1); + expect(laterLogin).toHaveBeenCalledExactlyOnceWith(bob); }); }); @@ -272,16 +298,6 @@ describe("initTelegramWidgetRedirect", () => { expect(script.hasAttribute("data-onauth")).toBe(false); }); - it("uses the documented defaults: large, with photo, radius 20", async () => { - await actions().initTelegramWidgetRedirect("telegram-login", "/cb", {}); - - const script = widgetScript(); - expect(script.getAttribute("data-size")).toBe("large"); - expect(script.getAttribute("data-userpic")).toBe("true"); - expect(script.getAttribute("data-radius")).toBe("20"); - expect(script.hasAttribute("data-request-access")).toBe(false); - }); - it("applies every widget option", async () => { await actions().initTelegramWidgetRedirect("telegram-login", "/cb", { size: "small", @@ -298,60 +314,70 @@ describe("initTelegramWidgetRedirect", () => { expect(script.getAttribute("data-request-access")).toBe("write"); expect(script.getAttribute("data-lang")).toBe("pl"); }); - - it("replaces previous content, so a re-render does not stack two widgets", async () => { - const container = document.getElementById("telegram-login")!; - container.innerHTML = "

Old content

"; - - await actions().initTelegramWidgetRedirect("telegram-login", "/cb", {}); - - expect(container.querySelector("p")).toBeNull(); - expect(container.querySelectorAll("script")).toHaveLength(1); - }); }); describe("loading Telegram's widget script", () => { - it("loads the script into once when it is not on the page yet", async () => { + function controlScriptLoad() { (window as any).Telegram = undefined; + const requested: HTMLScriptElement[] = []; + // The network script is the boundary: complete its load/error explicitly. + vi.spyOn(document.head, "appendChild").mockImplementation((element) => { + requested.push(element as HTMLScriptElement); + return element; + }); + return requested; + } - await actions().initTelegramWidget("telegram-login", {}, () => {}); - - const loaded = document.head.querySelectorAll("script"); - expect(loaded).toHaveLength(1); - expect(loaded[0]!.getAttribute("src")).toBe(WIDGET_SCRIPT); - }); - - // React strict mode runs the effect that renders the widget twice at once. - it("loads it once when two widgets initialize at the same time, rendering one", async () => { - (window as any).Telegram = undefined; + it("shares an in-flight script load and renders only after it succeeds", async () => { + const requested = controlScriptLoad(); + const first = actions().initTelegramWidget("telegram-login", {}, () => {}); + const second = actions().initTelegramWidget("telegram-login", {}, () => {}); - await Promise.all([ - actions().initTelegramWidget("telegram-login", {}, () => {}), - actions().initTelegramWidget("telegram-login", {}, () => {}), - ]); + expect(requested).toHaveLength(1); + expect(requested[0]!.src).toBe(WIDGET_SCRIPT); + expect(document.getElementById("telegram-login")!.children).toHaveLength(0); + requested[0]!.dispatchEvent(new Event("load")); + await Promise.all([first, second]); - expect(document.head.querySelectorAll("script")).toHaveLength(1); expect( document.getElementById("telegram-login")!.querySelectorAll("script") ).toHaveLength(1); }); - it("rejects without rendering a widget when the script fails to load", async () => { - (window as any).Telegram = undefined; - // happy-dom then logs a DOMException for the refused load; that is expected. - (window as any).happyDOM.settings.handleDisabledFileLoadingAsSuccess = - false; - - await expect( - actions().initTelegramWidget("telegram-login", {}, () => {}) - ).rejects.toThrow("Failed to load Telegram widget script"); - expect( - document.getElementById("telegram-login")!.querySelector("script") - ).toBeNull(); + it("rejects a failed script load and lets a later attempt recover", async () => { + const requested = controlScriptLoad(); + const first = actions().initTelegramWidget("telegram-login", {}, () => {}); + const rejected = expect(first).rejects.toThrow( + "Failed to load Telegram widget script" + ); + requested[0]!.dispatchEvent(new Event("error")); + await rejected; + expect(document.getElementById("telegram-login")!.children).toHaveLength(0); + + const recovered = vi.fn(); + const retry = actions().initTelegramWidget("telegram-login", {}, recovered); + expect(requested).toHaveLength(2); + requested[1]!.dispatchEvent(new Event("load")); + await retry; + await telegramLogsIn("telegram-login", bob); + + expect(recovered).toHaveBeenCalledExactlyOnceWith(bob); }); }); describe("autoSignInFromMiniApp", () => { + it("reports server-side use without attempting a sign-in request", async () => { + vi.stubGlobal("window", undefined); + try { + await expect(actions().autoSignInFromMiniApp()).rejects.toThrow( + "This method can only be called in browser" + ); + expect($fetch).not.toHaveBeenCalled(); + } finally { + vi.unstubAllGlobals(); + } + }); + it("reads tgWebAppData from the URL fragment once decoded when the SDK is absent", async () => { // Telegram's launch parameters: initData is URL-encoded inside the fragment. const initData = "user=%7B%22id%22%3A7%7D&auth_date=1761730000&hash=abc123"; diff --git a/src/identity-transitions.adapter.test.ts b/src/identity-transitions.adapter.test.ts new file mode 100644 index 0000000..47d33eb --- /dev/null +++ b/src/identity-transitions.adapter.test.ts @@ -0,0 +1,112 @@ +// @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"; + +describe.each(adapterLanes())("$name identity authority", (lane) => { + let fixture: AdapterAuth | undefined; + afterEach(async () => { + await fixture?.close(); + fixture = undefined; + }); + + describe.skipIf(!lane.url)("persisted account proof", () => { + test("refuses conflicting owners beyond same-owner duplicate rows", async () => { + fixture = await lane.create({ miniApp: { enabled: true } }); + const { auth, client, rows } = fixture; + const first = await client.post( + "/telegram/signin", + await signWidgetData({ id: 42 }) + ); + const second = await client.post( + "/telegram/signin", + await signWidgetData({ id: 43 }) + ); + expect([first.status, second.status]).toEqual([200, 200]); + const context = await auth.$context; + for (const userId of [first.json.user.id, second.json.user.id]) { + // A later conflicting row must not hide behind two copies for one user. + // biome-ignore lint/performance/noAwaitInLoops: Establish the legacy insertion order. + await context.internalAdapter.createAccount({ + providerId: "telegram", + accountId: "42", + userId, + }); + } + client.clearCookies(); + const sessions = await rows("session"); + + const widget = await client.post( + "/telegram/signin", + await signWidgetData({ id: 42 }) + ); + const miniApp = await client.post("/telegram/miniapp/signin", { + initData: await signInitData({ id: 42 }), + }); + + expect([widget.status, miniApp.status]).toEqual([409, 409]); + expect([widget.json.code, miniApp.json.code]).toEqual([ + "TELEGRAM_ALREADY_LINKED_OTHER", + "TELEGRAM_ALREADY_LINKED_OTHER", + ]); + expect(await rows("session")).toEqual(sessions); + expect(client.hasSession()).toBe(false); + }); + + test.each(["validation", "profile update"])( + "refuses a new session when %s revokes the proving account", + async (stage) => { + let provingAccount = ""; + fixture = await lane.create( + { miniApp: { enabled: true } }, + { + user: { + validateUserInfo: async ({ user, source }, ctx) => { + if (stage === "validation" && source.action === "sign-in") { + const accounts = + await ctx.context.internalAdapter.findAccounts(user.id!); + const telegram = accounts.find( + (account) => account.providerId === "telegram" + )!; + await ctx.context.internalAdapter.deleteAccount(telegram.id); + } + }, + }, + databaseHooks: { + account: { + update: { + before: async (_data, ctx) => { + if (stage === "profile update") { + await ctx!.context.internalAdapter.deleteAccount( + provingAccount + ); + } + }, + }, + }, + }, + } + ); + const { client, rows } = fixture; + const first = await client.post( + "/telegram/signin", + await signWidgetData({ id: 42, username: "before" }) + ); + expect(first.status).toBe(200); + provingAccount = (await rows("account"))[0]!.id; + client.clearCookies(); + const sessions = await rows("session"); + + const response = await client.post("/telegram/miniapp/signin", { + initData: await signInitData({ id: 42, username: "after" }), + }); + + expect(response.status).toBe(401); + expect(response.json.code).toBe("ACCOUNT_NOT_LINKED"); + expect(await rows("account")).toHaveLength(0); + expect(await rows("session")).toEqual(sessions); + expect(client.hasSession()).toBe(false); + } + ); + }); +}); diff --git a/src/identity-transitions.integration.test.ts b/src/identity-transitions.integration.test.ts new file mode 100644 index 0000000..4e71c82 --- /dev/null +++ b/src/identity-transitions.integration.test.ts @@ -0,0 +1,199 @@ +// @vitest-environment node +import { describe, expect, it } from "vitest"; +import { + createMemoryAuth, + signInitData, + signWidgetData, +} from "./testing/harness"; + +describe("Telegram identity authority transitions", () => { + it.each(["Widget", "Mini App"])( + "%s refuses a Telegram account key held by different users", + async (method) => { + const { auth, client, db } = createMemoryAuth({ + miniApp: { enabled: true }, + }); + const first = await client.post( + "/telegram/signin", + await signWidgetData({ id: 42 }) + ); + client.clearCookies(); + const second = await client.post( + "/telegram/signin", + await signWidgetData({ id: 43 }) + ); + expect(first.status).toBe(200); + expect(second.status).toBe(200); + expect(second.json.user.id).not.toBe(first.json.user.id); + const context = await auth.$context; + // Same-owner duplicates remain supported, but must not hide a later conflict. + await context.internalAdapter.createAccount({ + providerId: "telegram", + accountId: "42", + userId: first.json.user.id, + }); + await context.internalAdapter.createAccount({ + providerId: "telegram", + accountId: "42", + userId: second.json.user.id, + }); + client.clearCookies(); + const before = structuredClone({ + users: db.user, + accounts: db.account, + sessions: db.session, + }); + + const response = + method === "Widget" + ? await client.post( + "/telegram/signin", + await signWidgetData({ id: 42 }) + ) + : await client.post("/telegram/miniapp/signin", { + initData: await signInitData({ id: 42 }), + }); + + expect(response.status).toBe(409); + expect(response.json.code).toBe("TELEGRAM_ALREADY_LINKED_OTHER"); + expect(client.hasSession()).toBe(false); + expect({ + users: db.user, + accounts: db.account, + sessions: db.session, + }).toEqual(before); + } + ); + + it("does not issue a returning-user session after its account is revoked during validation", async () => { + const { client, db } = createMemoryAuth( + {}, + { + user: { + validateUserInfo: async ({ user, source }, ctx) => { + if ( + source.method === "telegram-login-widget" && + source.action === "sign-in" + ) { + const accounts = await ctx.context.internalAdapter.findAccounts( + user.id! + ); + const account = accounts.find( + (candidate) => candidate.providerId === "telegram" + ); + await ctx.context.internalAdapter.deleteAccount(account!.id); + } + }, + }, + } + ); + const first = await client.post( + "/telegram/signin", + await signWidgetData({ id: 42 }) + ); + expect(first.status).toBe(200); + client.clearCookies(); + const sessionCount = db.session.length; + + const response = await client.post( + "/telegram/signin", + await signWidgetData({ id: 42 }) + ); + + expect(response.status).toBe(401); + expect(response.json.code).toBe("ACCOUNT_NOT_LINKED"); + expect(db.account).toHaveLength(0); + expect(db.session).toHaveLength(sessionCount); + expect(client.hasSession()).toBe(false); + }); + + it("does not reuse a validation decision after the account moves to another user", async () => { + let replacementOwner = ""; + const { client, db } = createMemoryAuth( + {}, + { + user: { + validateUserInfo: async ({ user, source }, ctx) => { + if ( + source.method === "telegram-login-widget" && + source.action === "sign-in" + ) { + const accounts = await ctx.context.internalAdapter.findAccounts( + user.id! + ); + const account = accounts.find( + (candidate) => candidate.providerId === "telegram" + )!; + await ctx.context.internalAdapter.updateAccount(account.id, { + userId: replacementOwner, + }); + } + }, + }, + } + ); + const first = await client.post( + "/telegram/signin", + await signWidgetData({ id: 42 }) + ); + const other = await client.post( + "/telegram/signin", + await signWidgetData({ id: 43 }) + ); + expect([first.status, other.status]).toEqual([200, 200]); + replacementOwner = other.json.user.id; + expect(replacementOwner).not.toBe(first.json.user.id); + client.clearCookies(); + const sessionCount = db.session.length; + + const response = await client.post( + "/telegram/signin", + await signWidgetData({ id: 42 }) + ); + + expect(response.status).toBe(401); + expect(response.json.code).toBe("ACCOUNT_NOT_LINKED"); + expect( + db.account.find((account) => account.accountId === "42")!.userId + ).toBe(replacementOwner); + expect(db.session).toHaveLength(sessionCount); + expect(client.hasSession()).toBe(false); + }); + + it("does not issue a session after a profile hook revokes the proving account", async () => { + let accountId = ""; + const { client, db } = createMemoryAuth( + {}, + { + databaseHooks: { + account: { + update: { + before: async (_account, ctx) => { + await ctx!.context.internalAdapter.deleteAccount(accountId); + }, + }, + }, + }, + } + ); + const first = await client.post( + "/telegram/signin", + await signWidgetData({ id: 42, username: "before" }) + ); + expect(first.status).toBe(200); + accountId = db.account[0]!.id; + client.clearCookies(); + const sessionCount = db.session.length; + + const response = await client.post( + "/telegram/signin", + await signWidgetData({ id: 42, username: "after" }) + ); + + expect(response.status).toBe(401); + expect(response.json.code).toBe("ACCOUNT_NOT_LINKED"); + expect(db.account).toHaveLength(0); + expect(db.session).toHaveLength(sessionCount); + expect(client.hasSession()).toBe(false); + }); +}); diff --git a/src/identity.integration.test.ts b/src/identity.integration.test.ts index a258d10..a3c1388 100644 --- a/src/identity.integration.test.ts +++ b/src/identity.integration.test.ts @@ -4,7 +4,7 @@ * it must only ever be backed by a linked Telegram account, because the * Login Widget and Mini App sign users in by it. */ -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { createClient, createMemoryAuth, @@ -70,27 +70,16 @@ function accountId(db: { account: Record[] }, providerId: string) { } describe("removing a Telegram account revokes the Telegram identity", () => { - it("clears telegramId when the OIDC account is unlinked through Better Auth", async () => { - const { client, db } = createMemoryAuth(options(), authOptions); + it("does not let the Mini App sign back in after the OIDC account is unlinked", async () => { + const { auth, client, db } = createMemoryAuth(options(), authOptions); await signUp(client); await linkOIDC(client); - expect(db.user[0]!.telegramId).toBe("8306595751"); - const unlink = await client.post("/unlink-account", { accountId: accountId(db, "telegram-oidc"), }); - expect(unlink.status).toBe(200); expect(db.user[0]!.telegramId).toBeNull(); - }); - - it("does not let the Mini App sign back in after the OIDC account is unlinked", async () => { - const { auth, client, db } = createMemoryAuth(options(), authOptions); - await signUp(client); - await linkOIDC(client); - await client.post("/unlink-account", { - accountId: accountId(db, "telegram-oidc"), - }); + const originalUserId = db.user[0]!.id; const miniApp = createClient(auth); const response = await miniApp.post("/telegram/miniapp/signin", { @@ -98,7 +87,10 @@ describe("removing a Telegram account revokes the Telegram identity", () => { }); expect(response.status).toBe(200); - expect(response.json.user.id).not.toBe(db.user[0]!.id); + expect(response.json.user.id).not.toBe(originalUserId); + expect((await miniApp.get("/get-session")).json.user.id).toBe( + response.json.user.id + ); }); it("clears telegramId when the Login Widget account is unlinked through Better Auth", async () => { @@ -201,7 +193,7 @@ describe("verified OIDC claims only apply to the user they prove", () => { describe("ID token sign-in", () => { it("requires the nonce the token was issued with", async () => { - const { client } = createMemoryAuth(options()); + const { client, db } = createMemoryAuth(options()); const token = await telegramMock.sign({ ...telegramClaims(), nonce: "n-1", @@ -213,10 +205,15 @@ describe("ID token sign-in", () => { }); expect(response.status).toBe(401); + expect(response.json.code).toBe("INVALID_TOKEN"); + expect([db.user.length, db.account.length, db.session.length]).toEqual([ + 0, 0, 0, + ]); + expect(client.hasSession()).toBe(false); }); it("can be turned off", async () => { - const { client } = createMemoryAuth( + const { client, db } = createMemoryAuth( options({ oidc: { enabled: true, @@ -236,9 +233,13 @@ describe("ID token sign-in", () => { }); expect(response.status).toBe(404); + expect(response.json.code).toBe("ID_TOKEN_NOT_SUPPORTED"); + expect([db.user.length, db.account.length, db.session.length]).toEqual([ + 0, 0, 0, + ]); }); - it("honors oidc.disableSignUp", async () => { + it("honors oidc.disableSignUp in redirect and direct-token flows", async () => { const { client, db } = createMemoryAuth( options({ oidc: { @@ -252,19 +253,34 @@ describe("ID token sign-in", () => { const { location } = await signInWithTelegramOIDC(client, telegramMock); expect(location).toContain("error=signup_disabled"); - expect(db.user).toHaveLength(0); + const token = await telegramMock.sign({ + ...telegramClaims(), + nonce: "signup-denied", + }); + const response = await client.post("/sign-in/social", { + provider: "telegram-oidc", + idToken: { token, nonce: "signup-denied" }, + }); + expect(response.status).toBe(401); + expect(response.json.code).toBe("OAUTH_LINK_ERROR"); + expect([db.user.length, db.account.length, db.session.length]).toEqual([ + 0, 0, 0, + ]); + expect(client.hasSession()).toBe(false); }); }); describe("validateUserInfo beyond sign-up", () => { it("runs for returning Login Widget sign-ins", async () => { - const validateUserInfo = vi.fn( - async ({ source }: { source: { action: string } }) => - source.action === "sign-in" ? { error: "suspended" } : undefined - ); - const { client } = createMemoryAuth({}, { user: { validateUserInfo } }); + const validateUserInfo = async ({ + source, + }: { + source: { action: string }; + }) => (source.action === "sign-in" ? { error: "suspended" } : undefined); + const { client, db } = createMemoryAuth({}, { user: { validateUserInfo } }); await client.post("/telegram/signin", await signWidgetData({ id: 42 })); client.clearCookies(); + const sessionsBefore = db.session.length; const response = await client.post( "/telegram/signin", @@ -273,13 +289,17 @@ describe("validateUserInfo beyond sign-up", () => { expect(response.status).toBe(403); expect(response.json.code).toBe("suspended"); + expect(client.hasSession()).toBe(false); + expect(db.session).toHaveLength(sessionsBefore); }); it("runs before /telegram/link links an account", async () => { - const validateUserInfo = vi.fn( - async ({ source }: { source: { action: string } }) => - source.action === "link-account" ? { error: "no_linking" } : undefined - ); + const validateUserInfo = async ({ + source, + }: { + source: { action: string }; + }) => + source.action === "link-account" ? { error: "no_linking" } : undefined; const { client, db } = createMemoryAuth( {}, { ...authOptions, user: { validateUserInfo } } @@ -292,6 +312,8 @@ describe("validateUserInfo beyond sign-up", () => { ); expect(response.status).toBe(403); + expect(response.json.code).toBe("no_linking"); + expect(db.user[0]!.telegramId ?? null).toBeNull(); expect( db.account.filter((account) => account.providerId === "telegram") ).toHaveLength(0); @@ -300,10 +322,14 @@ describe("validateUserInfo beyond sign-up", () => { describe("validateUserInfo for an implicit link by telegramId", () => { it("sees a Mini App sign-in into an OIDC user as link-account by telegram-mini-app", async () => { - const validateUserInfo = vi.fn( - async ({ source }: { source: { action: string } }) => - source.action === "link-account" ? { error: "no_linking" } : undefined - ); + const validateUserInfo = async ({ + source, + }: { + source: { action: string; method: string }; + }) => + source.action === "link-account" && source.method === "telegram-mini-app" + ? { error: "no_linking" } + : undefined; const { client, db } = createMemoryAuth(options(), { user: { validateUserInfo }, }); @@ -316,12 +342,6 @@ describe("validateUserInfo for an implicit link by telegramId", () => { expect(response.status).toBe(403); expect(response.json.code).toBe("no_linking"); - expect(validateUserInfo).toHaveBeenLastCalledWith( - expect.objectContaining({ - source: { action: "link-account", method: "telegram-mini-app" }, - }), - expect.anything() - ); expect( db.account.filter((account) => account.providerId === "telegram") ).toHaveLength(0); @@ -381,17 +401,20 @@ describe("placeholder emails cannot be claimed by other sign-up methods", () => ])( "rejects an email/password sign-up with a %s placeholder", async (_namespace, email) => { - const { client, rows } = await createSqliteAuth({}, authOptions); - - const response = await client.post("/sign-up/email", { - email, - password: "correct-horse-battery", - name: "Squatter", - }); - - expect(response.status).toBe(400); - expect(response.json.code).toBe("FAILED_TO_CREATE_USER"); - expect(rows("user")).toHaveLength(0); + const { client, rows, sqlite } = await createSqliteAuth({}, authOptions); + try { + const response = await client.post("/sign-up/email", { + email, + password: "correct-horse-battery", + name: "Squatter", + }); + + expect(response.status).toBe(400); + expect(response.json.code).toBe("FAILED_TO_CREATE_USER"); + expect(rows("user")).toHaveLength(0); + } finally { + sqlite.close(); + } } ); @@ -437,5 +460,10 @@ describe("tolerating data written by older versions", () => { ); expect(response.status).toBe(200); + expect(response.json.user.id).toBe(db.user[0]!.id); + expect(db.user).toHaveLength(1); + expect((await client.get("/get-session")).json.user.id).toBe( + response.json.user.id + ); }); }); diff --git a/src/miniapp.integration.test.ts b/src/miniapp.integration.test.ts index 95e88bd..586b287 100644 --- a/src/miniapp.integration.test.ts +++ b/src/miniapp.integration.test.ts @@ -60,15 +60,20 @@ describe("Mini App sign-in", () => { it("signs a Login Widget user into the same account", async () => { const { client, db } = createMemoryAuth(miniApp); - await client.post("/telegram/signin", await widgetUser(7)); + const widget = await client.post("/telegram/signin", await widgetUser(7)); + expect(widget.status).toBe(200); client.clearCookies(); const response = await client.post("/telegram/miniapp/signin", { initData: await signInitData({ id: 7 }), }); + const session = await client.get("/get-session"); expect(response.status).toBe(200); + expect(response.json.user.id).toBe(widget.json.user.id); + expect(session.json.user.id).toBe(widget.json.user.id); expect(db.user).toHaveLength(1); + expect(db.account).toHaveLength(1); }); it("honors user.validateUserInfo and reports the Mini App as the method", async () => { @@ -95,7 +100,7 @@ describe("Mini App sign-in", () => { }); it("rejects tampered initData", async () => { - const { client } = createMemoryAuth(miniApp); + const { client, db } = createMemoryAuth(miniApp); const initData = (await signInitData({ id: 7 })).replace("Ann", "Bob"); const response = await client.post("/telegram/miniapp/signin", { @@ -103,37 +108,39 @@ describe("Mini App sign-in", () => { }); expect(response.status).toBe(401); + expect(response.json.code).toBe("INVALID_MINI_APP_INIT_DATA"); + expect(db.user).toHaveLength(0); + expect(db.account).toHaveLength(0); + expect(db.session).toHaveLength(0); }); - it("validates initData without creating a user or a session", async () => { + it("returns decoded user and chat data without creating a user, account or session", async () => { const { client, db } = createMemoryAuth(miniApp); const response = await client.post("/telegram/miniapp/validate", { - initData: await signInitData({ id: 7 }), + initData: await signInitData( + { id: 7, username: "ann" }, + { + chat: '{"id":-100123,"type":"supergroup","title":"Ann’s group"}', + start_param: "ref123", + can_send_after: "10", + } + ), }); expect(response.status).toBe(200); expect(response.json.valid).toBe(true); + expect(response.json.data).toMatchObject({ + user: { id: 7, username: "ann" }, + chat: { id: -100123, type: "supergroup", title: "Ann’s group" }, + start_param: "ref123", + can_send_after: 10, + }); expect(db.user).toHaveLength(0); + expect(db.account).toHaveLength(0); expect(db.session).toHaveLength(0); expect(client.hasSession()).toBe(false); }); - - it("returns the parsed user and chat objects from the validate endpoint", async () => { - const { client } = createMemoryAuth(miniApp); - const chat = { id: -100_123, type: "supergroup", title: "Ann's group" }; - - const response = await client.post("/telegram/miniapp/validate", { - initData: await signInitData( - { id: 7, username: "ann" }, - { chat: JSON.stringify(chat), start_param: "ref123" } - ), - }); - - expect(response.json.data.user).toMatchObject({ id: 7, username: "ann" }); - expect(response.json.data.chat).toEqual(chat); - expect(response.json.data.start_param).toBe("ref123"); - }); }); describe("Mini App request validation", () => { @@ -148,7 +155,9 @@ describe("Mini App request validation", () => { const validate = await client.post("/telegram/miniapp/validate", {}); expect(signIn.status).toBe(400); + expect(signIn.json.code).toBe("INIT_DATA_REQUIRED"); expect(validate.status).toBe(400); + expect(validate.json.code).toBe("INIT_DATA_REQUIRED"); }); it("answers 500 when the bot token is not configured", async () => { @@ -161,23 +170,33 @@ describe("Mini App request validation", () => { }); expect(signIn.status).toBe(500); + expect(signIn.json.code).toBe("BOT_TOKEN_REQUIRED"); expect(validate.status).toBe(500); + expect(validate.json.code).toBe("BOT_TOKEN_REQUIRED"); }); - it("answers 400 when initData has no user", async () => { - const { client } = createMemoryAuth(miniApp()); - const initData = await signInitParams({ - auth_date: String(Math.floor(Date.now() / 1000)), - query_id: "AAHdF6IQAAAAAN0XohDhrOrc", - }); + it.each([undefined, "{invalid json}"])( + "rejects missing or unparseable user data without writes (user %s)", + async (user) => { + const { client, db } = createMemoryAuth(miniApp()); + const initData = await signInitParams({ + auth_date: String(Math.floor(Date.now() / 1000)), + query_id: "AAHdF6IQAAAAAN0XohDhrOrc", + ...(user === undefined ? {} : { user }), + }); - const response = await client.post("/telegram/miniapp/signin", { - initData, - }); + const response = await client.post("/telegram/miniapp/signin", { + initData, + }); - expect(response.status).toBe(400); - expect(response.json.code).toBe("NO_USER_IN_INIT_DATA"); - }); + expect(response.status).toBe(400); + expect(response.json.code).toBe("NO_USER_IN_INIT_DATA"); + expect(db.user).toHaveLength(0); + expect(db.account).toHaveLength(0); + expect(db.session).toHaveLength(0); + expect(client.hasSession()).toBe(false); + } + ); it.each([true, false])( "rejects a null Mini App user when signature validation is %s", @@ -236,23 +255,10 @@ describe("Mini App request validation", () => { }); expect(response.status).toBe(404); + expect(response.json.code).toBe("MINI_APP_AUTO_SIGNIN_DISABLED"); expect(db.user).toHaveLength(0); - }); - - it("uses mapMiniAppDataToUser", async () => { - const { client, db } = createMemoryAuth( - miniApp({ - mapMiniAppDataToUser: (user: { id: number }) => ({ - name: `Mini ${user.id}`, - }), - }) - ); - - await client.post("/telegram/miniapp/signin", { - initData: await signInitData({ id: 7 }), - }); - - expect(db.user[0]!.name).toBe("Mini 7"); + expect(db.account).toHaveLength(0); + expect(db.session).toHaveLength(0); }); it("reports invalid initData from the validate endpoint", async () => { diff --git a/src/oidc-boundaries.integration.test.ts b/src/oidc-boundaries.integration.test.ts new file mode 100644 index 0000000..0310120 --- /dev/null +++ b/src/oidc-boundaries.integration.test.ts @@ -0,0 +1,113 @@ +// @vitest-environment node +import { + afterEach, + beforeEach, + describe, + expect, + it, + it as test, + vi, +} from "vitest"; +import { + createMemoryAuth, + mockTelegramOIDC, + signInitData, + signInWithTelegramOIDC, + type TelegramOIDCMock, + telegramClaims, +} from "./testing/harness"; + +let issuer: TelegramOIDCMock; +beforeEach(async () => { + issuer = await mockTelegramOIDC(); +}); +afterEach(() => { + issuer.restore(); +}); + +describe("OIDC subject validation before application effects", () => { + // OIDC Core defines sub as a required string. It must be usable as an + // account key before a mapper or cross-flow identity lookup sees it. + it.each([ + ["callback", "", 302, "unable_to_get_user_info"], + ["callback", 123, 302, "unable_to_get_user_info"], + ["direct token", "", 401, "INVALID_TOKEN"], + ["direct token", 123, 401, "INVALID_TOKEN"], + ] as const)( + "rejects %s with invalid subject %j before mapping or linking", + async (flow, sub, status, errorCode) => { + const mapper = vi.fn(() => ({ name: "Mapped profile" })); + const { client, db } = createMemoryAuth({ + loginWidget: false, + miniApp: { enabled: true }, + oidc: { + enabled: true, + clientSecret: issuer.clientSecret, + mapOIDCProfileToUser: mapper, + }, + }); + const first = await client.post("/telegram/miniapp/signin", { + initData: await signInitData({ id: 7 }), + }); + expect(first.status).toBe(200); + client.clearCookies(); + const before = structuredClone({ + users: db.user, + accounts: db.account, + sessions: db.session, + }); + const claims = telegramClaims({ id: "7", sub: sub as string }); + + const response = + flow === "callback" + ? (await signInWithTelegramOIDC(client, issuer, claims)).callback + : await client.post("/sign-in/social", { + provider: "telegram-oidc", + idToken: { + token: await issuer.sign({ ...claims, nonce: "n" }), + nonce: "n", + }, + }); + const error = + response.json?.code ?? + new URL( + response.headers.get("location") ?? "http://localhost" + ).searchParams.get("error"); + + expect(response.status).toBe(status); + expect(error).toBe(errorCode); + expect(mapper).not.toHaveBeenCalled(); + expect(client.hasSession()).toBe(false); + expect({ + users: db.user, + accounts: db.account, + sessions: db.session, + }).toEqual(before); + } + ); +}); + +test("normalizes the accepted audience array before a typed mapper consumes it", async () => { + const { client, db } = createMemoryAuth({ + loginWidget: false, + oidc: { + enabled: true, + clientSecret: issuer.clientSecret, + mapOIDCProfileToUser: (claims) => ({ + name: `Client ${claims.aud.trim()}`, + }), + }, + }); + + const { location } = await signInWithTelegramOIDC( + client, + issuer, + telegramClaims({ aud: ["123456789"] }) + ); + const session = await client.get("/get-session"); + + expect(location).toBe("/dashboard"); + expect(session.json.user.name).toBe("Client 123456789"); + expect(session.json.user.id).toBe(db.user[0]!.id); + expect(db.account[0]!.accountId).toBe("12224742808376279442"); +}); diff --git a/src/oidc-identity.integration.test.ts b/src/oidc-identity.integration.test.ts index dd8da1d..70b45e6 100644 --- a/src/oidc-identity.integration.test.ts +++ b/src/oidc-identity.integration.test.ts @@ -159,23 +159,6 @@ describe("Telegram identity on OIDC users", () => { expect(db.user).toHaveLength(1); }); - it("lets a Mini App sign-in find the user OIDC created", async () => { - const { client, db } = createMemoryAuth({ - ...oidc(), - miniApp: { enabled: true }, - }); - await signInWithTelegramOIDC(client, telegramMock); - client.clearCookies(); - - const response = await client.post("/telegram/miniapp/signin", { - initData: await signInitData({ id: 8_306_595_751 }), - }); - - expect(response.status).toBe(200); - expect(db.user).toHaveLength(1); - expect(response.json.user.id).toBe(db.user[0]!.id); - }); - it("signs an existing Widget user in through the same Telegram OIDC identity", async () => { const { client, db } = createMemoryAuth(oidc()); await client.post( @@ -240,11 +223,20 @@ describe("the session issued by an OIDC sign-in", () => { cookieCache ); - await signInWithTelegramOIDC( + const { callback } = await signInWithTelegramOIDC( client, telegramMock, telegramClaims({ phone_number: "48572068680" }) ); + const cookieNames = callback.headers + .getSetCookie() + .map((cookie) => cookie.split("=")[0]); + expect( + cookieNames.filter((name) => name?.includes("session_data")) + ).toHaveLength(1); + expect( + cookieNames.filter((name) => name?.includes("session_token")) + ).toHaveLength(1); const session = await client.get("/get-session"); expect(session.json.user).toMatchObject({ @@ -318,22 +310,6 @@ describe("the session issued by an OIDC sign-in", () => { expect(session.json.user.telegramId).toBe("8306595751"); }); - it("sends the session cookies once", async () => { - const { client } = createMemoryAuth(oidc(), cookieCache); - - const { callback } = await signInWithTelegramOIDC(client, telegramMock); - const names = callback.headers - .getSetCookie() - .map((cookie) => cookie.slice(0, cookie.indexOf("="))); - - expect(names.filter((name) => name.includes("session_data"))).toHaveLength( - 1 - ); - expect(names.filter((name) => name.includes("session_token"))).toHaveLength( - 1 - ); - }); - // An app's after hook may end the session it was just given. it("does not bring back a session cookie an earlier hook removed", async () => { const { client } = createMemoryAuth(oidc(), { @@ -348,9 +324,11 @@ describe("the session issued by an OIDC sign-in", () => { }, }); - await signInWithTelegramOIDC(client, telegramMock); + const { callback } = await signInWithTelegramOIDC(client, telegramMock); + expect(callback.headers.get("location")).toBe("/dashboard"); expect(client.hasSession()).toBe(false); + expect((await client.get("/get-session")).json).toBeNull(); }); it("issues the cached OIDC session for the existing Telegram user", async () => { @@ -369,5 +347,3 @@ describe("the session issued by an OIDC sign-in", () => { expect(session.json.user.telegramId).toBe("8306595751"); }); }); - -// #53: the mapper's values only land on new users unless the app opts in. diff --git a/src/oidc-linking.integration.test.ts b/src/oidc-linking.integration.test.ts index 6584649..3171944 100644 --- a/src/oidc-linking.integration.test.ts +++ b/src/oidc-linking.integration.test.ts @@ -62,10 +62,12 @@ describe("OIDC links a proven Telegram identity", () => { account: { accountLinking }, }); await miniAppUser(client); + const sessionsBefore = db.session.length; const { callback } = await signInWithTelegramOIDC(client, provider); expect(callback.status).toBe(401); expect(callback.json.code).toBe("ACCOUNT_NOT_LINKED"); expect(client.hasSession()).toBe(false); + expect(db.session).toHaveLength(sessionsBefore); expect(db.account).toHaveLength(1); expect(db.user).toHaveLength(1); } @@ -84,38 +86,46 @@ describe("OIDC links a proven Telegram identity", () => { }, }); await miniAppUser(client); + const sessionsBefore = db.session.length; const { callback } = await signInWithTelegramOIDC(client, provider); expect(callback.status).toBe(403); expect(callback.json.code).toBe("APP_REFUSED"); expect(client.hasSession()).toBe(false); + expect(db.session).toHaveLength(sessionsBefore); expect(db.account).toHaveLength(1); } ); - it("does not persist a link when an account creation hook refuses it", async () => { + it("fails closed before linking when the application policy service throws", async () => { const { client, db } = createMemoryAuth(config(), { - databaseHooks: { - account: { - create: { - before: async (account) => { - await Promise.resolve(); - if (account.providerId === "telegram-oidc") { - return false; - } - }, - }, + user: { + validateUserInfo: ({ source }) => { + if (source.method === "oauth") { + throw new Error("policy service unavailable"); + } }, }, }); await miniAppUser(client); + const before = structuredClone({ + users: db.user, + accounts: db.account, + sessions: db.session, + }); + const { callback } = await signInWithTelegramOIDC(client, provider); + expect(callback.status).toBe(403); - expect(callback.json.code).toBe("ACCOUNT_CREATION_REJECTED"); + expect(callback.json.code).toBe("validation_failed"); expect(client.hasSession()).toBe(false); - expect(db.account).toHaveLength(1); + expect({ + users: db.user, + accounts: db.account, + sessions: db.session, + }).toEqual(before); }); - it("rejects an account hook that changes the authentication binding before it writes", async () => { + it("does not persist a link when an account creation hook refuses it", async () => { const { client, db } = createMemoryAuth(config(), { databaseHooks: { account: { @@ -123,7 +133,7 @@ describe("OIDC links a proven Telegram identity", () => { before: async (account) => { await Promise.resolve(); if (account.providerId === "telegram-oidc") { - return { data: { ...account, accountId: "another-sub" } }; + return false; } }, }, @@ -132,11 +142,38 @@ describe("OIDC links a proven Telegram identity", () => { }); await miniAppUser(client); const { callback } = await signInWithTelegramOIDC(client, provider); - expect(callback.status).toBe(409); + expect(callback.status).toBe(403); + expect(callback.json.code).toBe("ACCOUNT_CREATION_REJECTED"); expect(client.hasSession()).toBe(false); expect(db.account).toHaveLength(1); }); + it.each(["accountId", "providerId", "userId"] as const)( + "rejects an account hook that changes %s without persisting the binding", + async (field) => { + const { client, db } = createMemoryAuth(config(), { + databaseHooks: { + account: { + create: { + before: async (account) => { + await Promise.resolve(); + if (account.providerId === "telegram-oidc") { + return { data: { ...account, [field]: "another-binding" } }; + } + }, + }, + }, + }, + }); + await miniAppUser(client); + const { callback } = await signInWithTelegramOIDC(client, provider); + expect(callback.status).toBe(409); + expect(callback.json.code).toBe("TELEGRAM_ALREADY_LINKED_OTHER"); + expect(client.hasSession()).toBe(false); + expect(db.account).toHaveLength(1); + } + ); + it("rechecks linked proof after application account hooks", async () => { const { client, db } = createMemoryAuth(config(), { databaseHooks: { @@ -178,6 +215,7 @@ describe("OIDC links a proven Telegram identity", () => { }); const { callback } = await signInWithTelegramOIDC(client, provider); expect(callback.status).toBe(409); + expect(callback.json.code).toBe("TELEGRAM_ALREADY_LINKED_OTHER"); expect(client.hasSession()).toBe(false); expect(db.account).toHaveLength(1); }); @@ -227,7 +265,7 @@ describe("OIDC links a proven Telegram identity", () => { }); const original = await miniAppUser(client); const other = createClient(auth); - await other.post("/sign-up/email", { + const signedUp = await other.post("/sign-up/email", { email: "another@example.com", password: "correct-horse-battery", name: "Other", @@ -243,6 +281,13 @@ describe("OIDC links a proven Telegram identity", () => { const linked = db.account.find( (account) => account.providerId === "telegram-oidc" )!; + expect(linked).toMatchObject({ + userId: signedUp.json.user.id, + accountId: "12224742808376279442", + }); expect(linked.userId).not.toBe(original.id); + expect((await other.get("/get-session")).json.user.id).toBe( + signedUp.json.user.id + ); }); }); diff --git a/src/oidc-placeholder.integration.test.ts b/src/oidc-placeholder.integration.test.ts new file mode 100644 index 0000000..fdbb19f --- /dev/null +++ b/src/oidc-placeholder.integration.test.ts @@ -0,0 +1,101 @@ +// @vitest-environment node +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { + createMemoryAuth, + mockTelegramOIDC, + signInWithTelegramOIDC, + type TelegramOIDCMock, + telegramClaims, +} from "./testing/harness"; + +let issuer: TelegramOIDCMock; +beforeEach(async () => { + issuer = await mockTelegramOIDC(); +}); +afterEach(() => issuer.restore()); + +const options = () => ({ + loginWidget: false, + oidc: { enabled: true, clientSecret: issuer.clientSecret }, +}); + +describe("opaque OIDC subjects do not depend on email syntax", () => { + // OIDC Core permits opaque ASCII subject identifiers, up to 255 characters. + it.each([ + ["opaque punctuation", "urn:telegram:user:42"], + ["255-character subject", "x".repeat(255)], + ])( + "preserves subject %s and the same user on repeated sign-in", + async (_case, sub) => { + const { client, db } = createMemoryAuth(options()); + const claims = telegramClaims({ sub }); + + const first = await signInWithTelegramOIDC(client, issuer, claims); + expect(first.location).toBe("/dashboard"); + const userId = db.user[0]!.id; + const { email } = db.user[0]!; + const [local, domain] = email.split("@"); + expect(domain).toBe("telegram-oidc.placeholder.invalid"); + expect(local.length).toBeLessThanOrEqual(64); + client.clearCookies(); + + const second = await signInWithTelegramOIDC(client, issuer, claims); + const session = await client.get("/get-session"); + + expect(second.location).toBe("/dashboard"); + expect(session.json.user.id).toBe(userId); + expect(session.json.user.email).toBe(email); + expect(db.user).toHaveLength(1); + expect(db.account).toHaveLength(1); + expect(db.account[0]).toMatchObject({ + userId, + accountId: sub, + providerId: "telegram-oidc", + }); + } + ); + + it.each([ + ["opaque punctuation", "urn:telegram:user:42"], + ["64-character local part", "x".repeat(64)], + ])( + "does not reconnect the unlinked owner by the placeholder for %s", + async (_case, sub) => { + const { client, db } = createMemoryAuth(options(), { + account: { + accountLinking: { + allowUnlinkingAll: true, + trustedProviders: ["telegram-oidc"], + requireLocalEmailVerified: false, + }, + }, + }); + const claims = telegramClaims({ sub }); + const first = await signInWithTelegramOIDC(client, issuer, claims); + expect(first.location).toBe("/dashboard"); + const oldUserId = db.user[0]!.id; + const oldEmail = db.user[0]!.email; + const unlink = await client.post("/unlink-account", { + accountId: db.account[0]!.id, + }); + expect(unlink.status).toBe(200); + client.clearCookies(); + + const again = await signInWithTelegramOIDC(client, issuer, claims); + const session = await client.get("/get-session"); + + expect(again.location).toBe("/dashboard"); + expect(session.json.user.id).not.toBe(oldUserId); + expect(session.json.user.email).not.toBe(oldEmail); + const [local, domain] = session.json.user.email.split("@"); + expect(domain).toBe("telegram-oidc.placeholder.invalid"); + expect(local.length).toBeLessThanOrEqual(64); + expect(db.user).toHaveLength(2); + expect(db.account).toHaveLength(1); + expect(db.account[0]).toMatchObject({ + userId: session.json.user.id, + accountId: sub, + }); + } + ); +}); diff --git a/src/oidc-profile.integration.test.ts b/src/oidc-profile.integration.test.ts index a63f6f8..b159e48 100644 --- a/src/oidc-profile.integration.test.ts +++ b/src/oidc-profile.integration.test.ts @@ -103,8 +103,14 @@ describe("oidc.updateUserInfoOnSignIn", () => { telegramClaims({ name: "Ann Renamed" }) ); + const session = await client.get("/get-session"); expect(location).toBe("/dashboard"); expect(db.user[0]!.name).toBe("Ann Example"); + expect(session.json.user).toMatchObject({ + id: db.user[0]!.id, + name: "Ann Example", + nickname: "ann", + }); }); it("signs in with the stored profile when a field validator refuses it", async () => { @@ -139,24 +145,32 @@ describe("oidc.updateUserInfoOnSignIn", () => { const { location } = await signInWithTelegramOIDC( client, telegramMock, - telegramClaims({ preferred_username: "ann_new" }) + telegramClaims({ name: "Ann Renamed", preferred_username: "ann_new" }) ); + const session = await client.get("/get-session"); expect(location).toBe("/dashboard"); - expect(db.user[0]!.nickname).toBe("ann"); + expect(db.user[0]).toMatchObject({ name: "Ann Example", nickname: "ann" }); + expect(session.json.user).toMatchObject({ + id: db.user[0]!.id, + name: "Ann Example", + nickname: "ann", + }); }); - it("writes nothing when the profile is unchanged", async () => { + it("updates changed structured profile values but skips equivalent values", async () => { const before = vi.fn(); - const { client } = createMemoryAuth( + let joinedAt = "2026-01-01T00:00:00.000Z"; + let theme = "dark"; + const { client, db } = createMemoryAuth( { loginWidget: false, oidc: { ...oidc().oidc, updateUserInfoOnSignIn: true, mapOIDCProfileToUser: () => ({ - joinedAt: new Date(0), - settings: { theme: "dark" }, + joinedAt: new Date(joinedAt), + settings: { theme }, }), }, }, @@ -171,11 +185,32 @@ describe("oidc.updateUserInfoOnSignIn", () => { } ); await signInWithTelegramOIDC(client, telegramMock); + const userId = db.user[0]!.id; client.clearCookies(); - await signInWithTelegramOIDC(client, telegramMock); + const unchanged = await signInWithTelegramOIDC(client, telegramMock); + const unchangedSession = await client.get("/get-session"); + expect(unchanged.location).toBe("/dashboard"); + expect(unchangedSession.json.user).toMatchObject({ + id: userId, + joinedAt: "2026-01-01T00:00:00.000Z", + settings: { theme: "dark" }, + }); expect(before).not.toHaveBeenCalled(); + + joinedAt = "2026-02-01T00:00:00.000Z"; + theme = "light"; + client.clearCookies(); + const changed = await signInWithTelegramOIDC(client, telegramMock); + const changedSession = await client.get("/get-session"); + + expect(changed.location).toBe("/dashboard"); + expect(changedSession.json.user).toMatchObject({ + id: userId, + joinedAt: "2026-02-01T00:00:00.000Z", + settings: { theme: "light" }, + }); }); // Better Auth writes its own profile updates only after validateUserInfo diff --git a/src/oidc-protocol.integration.test.ts b/src/oidc-protocol.integration.test.ts index 638c833..f2abceb 100644 --- a/src/oidc-protocol.integration.test.ts +++ b/src/oidc-protocol.integration.test.ts @@ -229,23 +229,40 @@ describe("a separate OIDC bot (oidc.clientId)", () => { }); describe("missing OIDC credentials at request time", () => { - it("answers 500 with a code that names the missing clientSecret", async () => { - const { client } = createMemoryAuth({ - loginWidget: false, - oidc: { enabled: true }, - }); + it.each([ + [ + "clientSecret", + { loginWidget: false, oidc: { enabled: true } }, + "OIDC_CLIENT_SECRET_REQUIRED", + ], + [ + "clientId", + { + botToken: "", + loginWidget: false, + oidc: { enabled: true, clientSecret: "configured-secret" }, + }, + "OIDC_CLIENT_ID_REQUIRED", + ], + ])( + "answers a coded configuration error for missing %s without creating auth state", + async (_field, options, code) => { + const { client, db } = createMemoryAuth(options); - const response = await client.post("/sign-in/social", { - provider: "telegram-oidc", - callbackURL: "/dashboard", - }); + const response = await client.post("/sign-in/social", { + provider: "telegram-oidc", + callbackURL: "/dashboard", + }); - expect(response.status).toBe(500); - expect(response.json).toMatchObject({ - code: "OIDC_CLIENT_SECRET_REQUIRED", - }); - expect(response.json.message).toContain("clientSecret"); - }); + expect(response.status).toBe(500); + expect(response.json.code).toBe(code); + expect([db.user.length, db.account.length, db.session.length]).toEqual([ + 0, 0, 0, + ]); + expect(client.hasSession()).toBe(false); + expect(telegramMock.tokenRequests).toHaveLength(0); + } + ); }); describe("social provider registration", () => { @@ -281,9 +298,3 @@ describe("social provider registration", () => { expect(response.status).toBe(404); }); }); - -// Better Auth issues the session (and its cookie cache, `newSession`, the ID -// token sign-in response) with the user it read before the session existed. -// Catches: Telegram fields written after that read, which a cookie cache -// keeps serving stale until `maxAge` — and in stateless mode until the next -// sign-in. diff --git a/src/oidc-token.ts b/src/oidc-token.ts index 087a632..678729c 100644 --- a/src/oidc-token.ts +++ b/src/oidc-token.ts @@ -40,11 +40,19 @@ export function createTelegramIdTokenVerifier(clientId: string) { requiredClaims: ID_TOKEN_REQUIRED_CLAIMS, clockTolerance: ID_TOKEN_CLOCK_TOLERANCE_SECONDS, }); + // JOSE checks presence, not the subject's type. Reject unusable identities + // before mappers or cross-flow linking can perform application work. + if (typeof payload.sub !== "string" || !payload.sub.trim()) { + throw new Error("ID token has no subject"); + } // OIDC Core 3.1.3.7: reject a token that also names audiences we don't // trust (jose only checks that ours is among them). if ([payload.aud].flat().some((audience) => audience !== clientId)) { throw new Error("ID token is also issued to another audience"); } + // Only this client is trusted; expose the public string claim even when + // the issuer encoded that same audience as a one-element array. + payload.aud = clientId; if (expectedNonce !== undefined && payload.nonce !== expectedNonce) { throw new Error( "ID token nonce does not match the authorization request" diff --git a/src/oidc.integration.test.ts b/src/oidc.integration.test.ts index cd86c2b..d1952a5 100644 --- a/src/oidc.integration.test.ts +++ b/src/oidc.integration.test.ts @@ -20,6 +20,7 @@ beforeEach(async () => { afterEach(() => { telegramMock.restore(); + vi.useRealTimers(); }); async function signUp(client: TestClient) { @@ -54,19 +55,10 @@ describe("Telegram OIDC sign-in (authorization code flow)", () => { name: "Ann Example", image: "https://t.me/i/userpic/320/ann.jpg", emailVerified: false, + email: "12224742808376279442@telegram-oidc.placeholder.invalid", }); }); - it("gives users a non-routable placeholder email derived from sub", async () => { - const { client, db } = createMemoryAuth({ loginWidget: false, ...oidc() }); - - await signInWithTelegramOIDC(client, telegramMock); - - expect(db.user[0]!.email).toBe( - "12224742808376279442@telegram-oidc.placeholder.invalid" - ); - }); - it.each([{ trustedProviders: [] }, { trustedProviders: ["telegram-oidc"] }])( "creates a new OIDC user after unlinking, with $trustedProviders trusted", async ({ trustedProviders }) => { @@ -102,12 +94,24 @@ describe("Telegram OIDC sign-in (authorization code flow)", () => { ); it("works on a SQL database with the schema Better Auth generates", async () => { - const { client, rows } = await createSqliteAuth(oidc()); - - const { location } = await signInWithTelegramOIDC(client, telegramMock); + const { client, rows, sqlite } = await createSqliteAuth(oidc()); + try { + const { location } = await signInWithTelegramOIDC(client, telegramMock); + const session = await client.get("/get-session"); - expect(location).toBe("/dashboard"); - expect(rows("account")).toHaveLength(1); + expect(location).toBe("/dashboard"); + expect(rows("user")).toHaveLength(1); + expect(rows("account")).toHaveLength(1); + expect(rows("session")).toHaveLength(1); + expect(rows("account")[0]).toMatchObject({ + providerId: "telegram-oidc", + accountId: "12224742808376279442", + userId: rows("user")[0]!.id, + }); + expect(session.json.user.id).toBe(rows("user")[0]!.id); + } finally { + sqlite.close(); + } }); it("authenticates to the token endpoint with HTTP Basic, not the body", async () => { @@ -184,13 +188,20 @@ describe("Telegram OIDC sign-in (authorization code flow)", () => { expect(db.user).toHaveLength(0); }); - it("reuses the cached JWKS across sign-ins", async () => { - const { client } = createMemoryAuth({ loginWidget: false, ...oidc() }); + it("uses a previously verified key during a JWKS outage", async () => { + const { client, db } = createMemoryAuth({ loginWidget: false, ...oidc() }); - await signInWithTelegramOIDC(client, telegramMock); + const first = await signInWithTelegramOIDC(client, telegramMock); + const userId = db.user[0]!.id; client.clearCookies(); - await signInWithTelegramOIDC(client, telegramMock); + telegramMock.setJwksStatus(503); + + const cached = await signInWithTelegramOIDC(client, telegramMock); + const session = await client.get("/get-session"); + expect(first.location).toBe("/dashboard"); + expect(cached.location).toBe("/dashboard"); + expect(session.json.user.id).toBe(userId); expect(telegramMock.jwksRequests).toBe(1); }); @@ -255,10 +266,18 @@ describe("Telegram OIDC sign-in (authorization code flow)", () => { it("signs the same Telegram user back into the same account", async () => { const { client, db } = createMemoryAuth({ loginWidget: false, ...oidc() }); - await signInWithTelegramOIDC(client, telegramMock); + const first = await signInWithTelegramOIDC(client, telegramMock); + const userId = db.user[0]!.id; + const firstSessionToken = db.session[0]!.token; client.clearCookies(); - await signInWithTelegramOIDC(client, telegramMock); + const again = await signInWithTelegramOIDC(client, telegramMock); + const session = await client.get("/get-session"); + + expect(first.location).toBe("/dashboard"); + expect(again.location).toBe("/dashboard"); + expect(session.json.user.id).toBe(userId); + expect(session.json.session.token).not.toBe(firstSessionToken); expect(db.user).toHaveLength(1); expect(db.account).toHaveLength(1); }); @@ -396,24 +415,40 @@ describe("Telegram OIDC sign-in (authorization code flow)", () => { await signUp(victim); db.user[0]!.emailVerified = true; const attacker = createClient(auth); + const sessionCount = db.session.length; const { location } = await signInWithTelegramOIDC(attacker, telegramMock); - expect(location).not.toBe("/dashboard"); + expect(location).toContain("error=account_not_linked"); + expect(attacker.hasSession()).toBe(false); + expect(db.session).toHaveLength(sessionCount); + expect(db.user).toHaveLength(1); expect( db.account.filter((account) => account.providerId === "telegram-oidc") ).toHaveLength(0); }); - it("signs in with an ID token that has only sub (EdDSA / ES256K bots drop profile claims)", async () => { - const { client, db } = createMemoryAuth({ loginWidget: false, ...oidc() }); + it("signs in with only sub and reports missing profile claims to the application's logger", async () => { + const diagnostics: [string, string][] = []; + const { client, db } = createMemoryAuth( + { loginWidget: false, ...oidc() }, + { + logger: { log: (level, message) => diagnostics.push([level, message]) }, + } + ); const { location } = await signInWithTelegramOIDC(client, telegramMock, { sub: "12224742808376279442", }); + const session = await client.get("/get-session"); expect(location).toBe("/dashboard"); expect(db.account[0]!.accountId).toBe("12224742808376279442"); + expect(session.json.user.id).toBe(db.user[0]!.id); + expect(diagnostics).toContainEqual([ + "warn", + expect.stringContaining("ID token has no profile claims"), + ]); }); }); @@ -430,9 +465,14 @@ describe("Telegram OIDC sign-in with a client-submitted ID token", () => { idToken: { token, nonce: "n-1" }, }); + const session = await client.get("/get-session"); expect(response.status).toBe(200); - expect(response.json.token).toBeTruthy(); - expect(db.account[0]!.accountId).toBe("12224742808376279442"); + expect(session.json.user.id).toBe(response.json.user.id); + expect(session.json.session.token).toBe(response.json.token); + expect(db.account[0]).toMatchObject({ + accountId: "12224742808376279442", + userId: session.json.user.id, + }); }); it("rejects a token signed with a key that is not in Telegram's JWKS", async () => { @@ -450,11 +490,15 @@ describe("Telegram OIDC sign-in with a client-submitted ID token", () => { }); expect(response.status).toBe(401); - expect(db.user).toHaveLength(0); + expect(response.json.code).toBe("INVALID_TOKEN"); + expect([db.user.length, db.account.length, db.session.length]).toEqual([ + 0, 0, 0, + ]); + expect(client.hasSession()).toBe(false); }); it("rejects a token whose nonce does not match", async () => { - const { client } = createMemoryAuth({ loginWidget: false, ...oidc() }); + const { client, db } = createMemoryAuth({ loginWidget: false, ...oidc() }); const token = await telegramMock.sign({ ...telegramClaims(), nonce: "a" }); const response = await client.post("/sign-in/social", { @@ -463,5 +507,10 @@ describe("Telegram OIDC sign-in with a client-submitted ID token", () => { }); expect(response.status).toBe(401); + expect(response.json.code).toBe("INVALID_TOKEN"); + expect([db.user.length, db.account.length, db.session.length]).toEqual([ + 0, 0, 0, + ]); + expect(client.hasSession()).toBe(false); }); }); diff --git a/src/oidc.test.ts b/src/oidc.test.ts index 1c63733..cf75aa5 100644 --- a/src/oidc.test.ts +++ b/src/oidc.test.ts @@ -15,33 +15,6 @@ import { import type { TelegramOIDCClaims } from "./types"; const CLIENT_SECRET = "client-secret-from-botfather"; -const authorizationRequest = { - state: "state", - codeVerifier: "verifier", - redirectURI: "https://example.com/api/auth/callback/telegram-oidc", -}; - -describe("client credentials", () => { - it("never falls back to the bot token as the client secret", () => { - // Telegram rejects the bot token; v3 requires oidc.clientSecret. - const provider = createTelegramOIDCProvider(BOT_TOKEN, {}); - - expect(() => provider.createAuthorizationURL(authorizationRequest)).toThrow( - "oidc.clientSecret is required" - ); - }); - - it("refuses to start a login with an empty client_id", () => { - const provider = createTelegramOIDCProvider("", { - clientSecret: CLIENT_SECRET, - }); - - expect(() => provider.createAuthorizationURL(authorizationRequest)).toThrow( - "oidc.clientId (or botToken) is required" - ); - }); -}); - describe("accountSubject", () => { const profile = telegramClaims() as unknown as TelegramOIDCClaims; @@ -138,37 +111,4 @@ describe("getUserInfo", () => { expect(mapper).not.toHaveBeenCalled(); } ); - - it("warns that the bot's signing algorithm drops profile claims", async () => { - const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); - - const result = await provider().getUserInfo({ - idToken: await telegram.sign({ sub: "12224742808376279442" }), - }); - - expect(result).not.toBeNull(); - expect(warn).toHaveBeenCalledWith( - expect.stringContaining("no profile claims"), - expect.stringMatching(/EdDSA.*RS256 or ES256/u) - ); - }); - - it("logs to the logger it is given (the plugin passes Better Auth's)", async () => { - const logger = { warn: vi.fn() }; - const console = vi.spyOn(globalThis.console, "warn"); - - await createTelegramOIDCProvider( - BOT_TOKEN, - { clientSecret: CLIENT_SECRET, disableDefaultScope: true }, - logger - ).getUserInfo({ - idToken: await telegram.sign({ sub: "12224742808376279442" }), - }); - - expect(logger.warn).toHaveBeenCalledWith( - expect.stringContaining("no profile claims"), - expect.stringContaining("disableDefaultScope") - ); - expect(console).not.toHaveBeenCalled(); - }); }); diff --git a/src/plugin-config.test.ts b/src/plugin-config.test.ts index 3a6429f..557f70a 100644 --- a/src/plugin-config.test.ts +++ b/src/plugin-config.test.ts @@ -80,7 +80,7 @@ describe("createPluginConfig", () => { ]); }); - it.each(["123456789", "bot123:abc", "123456789:abc def", "abc:def"])( + it.each(["123456789", "bot123:abc", "123456789:abc def"])( "warns about a bot token shaped %j", (botToken) => { expect(warnings({ ...BASE, botToken })).toContainEqual( @@ -113,22 +113,6 @@ describe("createPluginConfig", () => { } ); - it("does not warn about sharing a bot when OIDC uses its own client", () => { - expect( - warnings({ - ...BASE, - loginWidget: false, - oidc: { enabled: true, clientSecret: "s" }, - }) - ).toEqual([]); - expect( - warnings({ - ...BASE, - oidc: { enabled: true, clientId: "987654321", clientSecret: "s" }, - }) - ).toEqual([]); - }); - // OIDC-only mode adds no Telegram columns, so there is nowhere to copy // the phone number to. it("warns when requestPhone has no telegramPhoneNumber column to fill", () => { diff --git a/src/plugin.integration.test.ts b/src/plugin.integration.test.ts index 6658ffe..859e5ab 100644 --- a/src/plugin.integration.test.ts +++ b/src/plugin.integration.test.ts @@ -83,17 +83,6 @@ describe("configuration warnings", () => { ]); expect(console).not.toHaveBeenCalled(); }); - - it("stay quiet with logger.disabled", async () => { - const console = vi - .spyOn(globalThis.console, "warn") - .mockImplementation(() => undefined); - const { auth } = createMemoryAuth({ botToken: "not-a-token" }); - - await auth.$context; - - expect(console).not.toHaveBeenCalled(); - }); }); describe("GET /telegram/config", () => { @@ -140,11 +129,14 @@ describe("rate limits (Better Auth's limiter)", () => { statuses.push((await client.post(path, {})).status); } const overLimit = await client.post(path, {}); + vi.setSystemTime(1_761_730_059_000); + const sameWindow = await client.post(path, {}); vi.setSystemTime(1_761_730_061_000); const nextWindow = await client.post(path, {}); expect(statuses).not.toContain(429); expect(overLimit.status).toBe(429); + expect(sameWindow.status).toBe(429); expect(nextWindow.status).not.toBe(429); }); }); diff --git a/src/telegram-account-state.ts b/src/telegram-account-state.ts index 3812c11..7c06811 100644 --- a/src/telegram-account-state.ts +++ b/src/telegram-account-state.ts @@ -1,11 +1,8 @@ import type { GenericEndpointContext } from "@better-auth/core"; +import { getCurrentAdapter } from "@better-auth/core/context"; import type { Account, User } from "better-auth"; import { APIError } from "better-auth/api"; -import { - type ERROR_CODES, - PLUGIN_ID, - TELEGRAM_OIDC_PROVIDER_ID, -} from "./constants"; +import { ERROR_CODES, PLUGIN_ID, TELEGRAM_OIDC_PROVIDER_ID } from "./constants"; /** A Telegram user proven by a verified Login Widget or Mini App payload. */ export interface TelegramIdentity { @@ -84,21 +81,39 @@ export async function hasLinkedTelegramIdentity( ); } -/** - * Looks the account up with `findOne` rather than Better Auth's - * `findAccountByKey`, which throws when older versions left duplicate rows. - */ -export function findTelegramAccount( +/** Same-owner legacy duplicates are harmless; different owners are ambiguous. */ +export async function findTelegramAccount( ctx: GenericEndpointContext, telegramId: string ) { - return ctx.context.adapter.findOne({ + const adapter = await getCurrentAdapter(ctx.context.adapter); + const where = [ + { field: "providerId", value: PLUGIN_ID }, + { field: "accountId", value: telegramId }, + ]; + const [account, duplicate] = await adapter.findMany({ model: "account", - where: [ - { field: "providerId", value: PLUGIN_ID }, - { field: "accountId", value: telegramId }, - ], + where, + limit: 2, }); + if (!(account && duplicate)) { + return account ?? null; + } + // The common single-row case needs one read. Same-owner legacy duplicates + // need a separate check: the first two rows could hide a third owner. + if ( + duplicate.userId !== account.userId || + (await adapter.findOne({ + model: "account", + where: [ + ...where, + { field: "userId", value: account.userId, operator: "ne" }, + ], + })) + ) { + throw APIError.from("CONFLICT", ERROR_CODES.TELEGRAM_ALREADY_LINKED_OTHER); + } + return account; } /** diff --git a/src/telegram-account-user.ts b/src/telegram-account-user.ts index b86442f..e2c7ff3 100644 --- a/src/telegram-account-user.ts +++ b/src/telegram-account-user.ts @@ -7,6 +7,7 @@ import { ERROR_CODES } from "./constants"; import { accountData, assertValidUserInfo, + findTelegramAccount, type TelegramAccount, type TelegramIdentity, type TelegramProvisioningMethod, @@ -14,6 +15,19 @@ import { type TelegramUser, } from "./telegram-account-state"; +/** Application hooks may revoke or move the account while a sign-in is awaiting them. */ +async function requireAccountOwner( + ctx: GenericEndpointContext, + userId: string, + telegramId: string +) { + const account = await findTelegramAccount(ctx, telegramId); + if (!account || account.userId !== userId) { + throw APIError.from("UNAUTHORIZED", ERROR_CODES.ACCOUNT_NOT_LINKED); + } + return account; +} + /** Keeps the stored Telegram username current (it can change at any time). */ export async function refreshIdentity( ctx: GenericEndpointContext, @@ -23,7 +37,8 @@ export async function refreshIdentity( ): Promise { // SQL adapters return null for a missing username, the identity has undefined. const username = identity.username ?? null; - if ((account.telegramUsername ?? null) !== username) { + const accountChanged = (account.telegramUsername ?? null) !== username; + if (accountChanged) { await ctx.context.internalAdapter.updateAccount(account.id, { telegramUsername: username, } as Partial); @@ -39,14 +54,18 @@ export async function refreshIdentity( userUpdate.telegramUsername = username; } if (Object.keys(userUpdate).length === 0) { + if (accountChanged) { + await requireAccountOwner(ctx, user.id, identity.telegramId); + } return user; } - return ( + const updated = ((await ctx.context.internalAdapter.updateUser( user.id, userUpdate - )) as TelegramUser | null) ?? user - ); + )) as TelegramUser | null) ?? user; + await requireAccountOwner(ctx, user.id, identity.telegramId); + return updated; } /** Signs a returning Telegram user in through their `telegram` account. */ @@ -68,7 +87,14 @@ export async function signInWithAccount( "sign-in", method ); - return await refreshIdentity(ctx, user, account, identity); + // The application gate may await work while an account is revoked. Its old + // lookup is no longer authority to create a new authenticated session. + const currentAccount = await requireAccountOwner( + ctx, + user.id, + identity.telegramId + ); + return await refreshIdentity(ctx, user, currentAccount, identity); } /** diff --git a/src/telegram-input-boundaries.test.ts b/src/telegram-input-boundaries.test.ts new file mode 100644 index 0000000..2df25b9 --- /dev/null +++ b/src/telegram-input-boundaries.test.ts @@ -0,0 +1,91 @@ +// @vitest-environment node +import { describe, expect, it, it as test } from "vitest"; +import { + createMemoryAuth, + signInitData, + signInitParams, + signWidgetData, +} from "./testing/harness"; + +describe("Mini App signature and parsed data agree", () => { + it("rejects a conflicting hash appended to genuine signed initData", async () => { + const { client, db } = createMemoryAuth({ miniApp: { enabled: true } }); + const signed = await signInitData({ id: 42 }); + const genuine = await client.post("/telegram/miniapp/validate", { + initData: signed, + }); + expect(genuine.json.valid).toBe(true); + expect(genuine.json.data.user.id).toBe(42); + + // An untrusted caller can append this without knowing the bot token. + const ambiguous = `${signed}&hash=${"0".repeat(64)}`; + const validation = await client.post("/telegram/miniapp/validate", { + initData: ambiguous, + }); + const signIn = await client.post("/telegram/miniapp/signin", { + initData: ambiguous, + }); + + expect(validation.json).toEqual({ valid: false, data: null }); + expect(signIn.status).toBe(401); + expect(signIn.json.code).toBe("INVALID_MINI_APP_INIT_DATA"); + expect([db.user.length, db.account.length, db.session.length]).toEqual([ + 0, 0, 0, + ]); + }); +}); + +// Telegram defines user IDs as integers with at most 52 significant bits. +// Raw HTTP/provider JSON still needs validation despite our TypeScript types. +describe.each(["Login Widget", "Mini App"] as const)( + "%s Telegram identity input", + (method) => { + test.each(["0", "-1", "1.5", "9007199254740993"])( + "rejects id=%s instead of provisioning a noncanonical or rounded identity", + async (id) => { + const { client, db } = createMemoryAuth({ miniApp: { enabled: true } }); + const response = + method === "Login Widget" + ? await client.post( + "/telegram/signin", + await signWidgetData({ id: Number(id) }) + ) + : await client.post("/telegram/miniapp/signin", { + initData: await signInitParams({ + auth_date: String(Math.floor(Date.now() / 1000)), + user: `{"id":${id},"first_name":"Ann"}`, + }), + }); + + expect(response.status).toBe(400); + expect(response.json.code).toBe( + method === "Login Widget" + ? "INVALID_AUTH_DATA" + : "INVALID_MINI_APP_DATA_STRUCTURE" + ); + expect([db.user.length, db.account.length, db.session.length]).toEqual([ + 0, 0, 0, + ]); + } + ); + + test("preserves a valid 52-bit identity without truncation", async () => { + const { client, db } = createMemoryAuth({ miniApp: { enabled: true } }); + const id = 4_503_599_627_370_495; + const response = + method === "Login Widget" + ? await client.post("/telegram/signin", await signWidgetData({ id })) + : await client.post("/telegram/miniapp/signin", { + initData: await signInitData({ id }), + }); + + expect(response.status).toBe(200); + expect(response.json.user.telegramId).toBe("4503599627370495"); + expect(db.account[0]).toMatchObject({ + accountId: "4503599627370495", + userId: response.json.user.id, + }); + expect(response.json.session.userId).toBe(response.json.user.id); + }); + } +); diff --git a/src/telegram-placeholder.ts b/src/telegram-placeholder.ts index 6913041..1e95f42 100644 --- a/src/telegram-placeholder.ts +++ b/src/telegram-placeholder.ts @@ -10,6 +10,41 @@ import { } from "./constants"; import { currentClaims } from "./telegram-identity-state"; +function oidcEmail(identifier: string) { + return createPlaceholderEmail({ + identifier, + namespace: TELEGRAM_OIDC_PROVIDER_ID, + }); +} + +function directOIDCEmail(sub: string): string | null { + if (sub.length > 64) { + return null; + } + try { + return oidcEmail(sub); + } catch { + return null; + } +} + +async function opaqueSubjectKey(sub: string) { + const digest = await crypto.subtle.digest( + "SHA-256", + new TextEncoder().encode(sub) + ); + // This is only an email-safe label, never the account identity. Leave room + // for collision suffixes while retaining 192 bits of the subject's digest. + return `h-${Array.from(new Uint8Array(digest).slice(0, 24), (byte) => + byte.toString(16).padStart(2, "0") + ).join("")}`; +} + +function matchesIdentifier(identifier: string, base: string) { + const lower = base.toLowerCase(); + return identifier === lower || identifier.startsWith(`${lower}.`); +} + /** * `@.placeholder.invalid` addresses are the plugin's. * Returns the identifier when `email` is one of them. @@ -48,21 +83,27 @@ export async function isAllowedPlaceholder(user: Record) { placeholder.identifier.startsWith(`${telegramId}.`)) ); } - const claims = await currentClaims(); - const subject = claims?.sub.toLowerCase(); - return ( - subject !== undefined && - (placeholder.identifier === subject || - placeholder.identifier.startsWith(`${subject}.`)) + const subject = (await currentClaims())?.sub; + if (subject === undefined) { + return false; + } + if ( + directOIDCEmail(subject) && + matchesIdentifier(placeholder.identifier, subject) + ) { + return true; + } + return matchesIdentifier( + placeholder.identifier, + await opaqueSubjectKey(subject) ); } /** Keep placeholder selection and reservation together so emails never prove identity. */ export async function oidcPlaceholderEmail(sub: string): Promise { - const email = createPlaceholderEmail({ - identifier: sub, - namespace: TELEGRAM_OIDC_PROVIDER_ID, - }); + const direct = directOIDCEmail(sub); + const identifier = direct ? sub : await opaqueSubjectKey(sub); + const email = direct ?? oidcEmail(identifier); const ctx = tryGetCurrentAuthEndpointContext()?.context; if (!ctx) { return email; @@ -84,10 +125,12 @@ export async function oidcPlaceholderEmail(sub: string): Promise { // An unlinked user keeps their email. It cannot prove ownership of a new // OIDC account, even if the app trusts Telegram for email-based linking. if (await ctx.internalAdapter.findUserByEmail(email)) { - return createPlaceholderEmail({ - identifier: `${sub}.${crypto.randomUUID()}`, - namespace: TELEGRAM_OIDC_PROVIDER_ID, - }); + const suffix = crypto.randomUUID(); + if (identifier.length + suffix.length + 1 <= 64) { + return oidcEmail(`${identifier}.${suffix}`); + } + const base = direct ? await opaqueSubjectKey(sub) : identifier; + return oidcEmail(`${base}.${suffix.replaceAll("-", "").slice(0, 13)}`); } return email; } diff --git a/src/testing/adapter-prisma.ts b/src/testing/adapter-prisma.ts new file mode 100644 index 0000000..7709a4b --- /dev/null +++ b/src/testing/adapter-prisma.ts @@ -0,0 +1,91 @@ +import { execFileSync } from "node:child_process"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { prismaAdapter } from "@better-auth/prisma-adapter"; +import { PrismaPg } from "@prisma/adapter-pg"; +import { generatePrismaSchema } from "auth/api"; +import { afterAll } from "vitest"; +import { + type AdapterLane, + generatedDirectory, + postgresDatabase, + wrap, +} from "./adapter-resources"; +import { baseOptions } from "./auth"; + +/** Generate one client per suite; isolate its files and database from concurrent runs. */ +export function prismaLane(url: string | undefined): AdapterLane { + const prepare = async () => { + const database = await postgresDatabase(url!); + try { + const plain = baseOptions({ miniApp: { enabled: true } }, {}); + const directory = mkdtempSync(join(generatedDirectory(), "prisma-")); + const schemaFile = join(directory, "schema.prisma"); + // Prisma 7 stores the URL outside the schema and requires an output directory. + writeFileSync( + schemaFile, + `generator client {\n provider = "prisma-client"\n output = "./prisma-client"\n}\n\ndatasource db {\n provider = "postgresql"\n}\n` + ); + const generated = await generatePrismaSchema({ + adapter: prismaAdapter({}, { provider: "postgresql" })(plain), + options: plain, + file: schemaFile, + }); + writeFileSync(schemaFile, generated.code!); + const prisma = (...args: string[]) => + execFileSync("npx", ["prisma", ...args, `--schema=${schemaFile}`], { + stdio: "pipe", + }); + prisma("db", "push", `--url=${database.url}`); + prisma("generate"); + const { PrismaClient } = await import( + pathToFileURL(join(directory, "prisma-client/client.ts")).href + ); + return { PrismaClient, database }; + } catch (error) { + await database.drop(); + throw error; + } + }; + let ready: ReturnType | undefined; + afterAll(async () => { + const prepared = await ready?.catch(() => undefined); + if (prepared) { + await prepared.database.drop(); + } + }); + return { + name: "Prisma (PostgreSQL)", + url, + concurrentServers: false, + generatedIds: false, + async create(pluginOptions = {}, authOptions = {}) { + ready ??= prepare(); + const { PrismaClient, database } = await ready; + const prisma = new PrismaClient({ + adapter: new PrismaPg({ connectionString: database.url }), + }); + try { + // Children first: session and account reference user. + await prisma.$transaction([ + prisma.session.deleteMany(), + prisma.account.deleteMany(), + prisma.verification.deleteMany(), + prisma.user.deleteMany(), + ]); + const options = { + ...baseOptions( + { miniApp: { enabled: true }, ...pluginOptions }, + authOptions + ), + database: prismaAdapter(prisma, { provider: "postgresql" }), + }; + return await wrap(options, () => prisma.$disconnect()); + } catch (error) { + await prisma.$disconnect(); + throw error; + } + }, + }; +} diff --git a/src/testing/adapter-resources.ts b/src/testing/adapter-resources.ts new file mode 100644 index 0000000..1b17441 --- /dev/null +++ b/src/testing/adapter-resources.ts @@ -0,0 +1,115 @@ +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { betterAuth } from "better-auth"; +import { createPool } from "mysql2/promise"; +import pg from "pg"; +import { afterAll } from "vitest"; +import type { TelegramPluginOptions } from "../types"; +import type { AuthOptions } from "./auth"; +import { createClient } from "./http-client"; + +type Row = Record; + +export interface AdapterAuth { + auth: ReturnType; + client: ReturnType; + close: () => Promise; + options: AuthOptions; + rows: (model: "user" | "account" | "session") => Promise; +} + +export interface AdapterLane { + /** Requires unique user.email and transactions spanning user/account creation. */ + concurrentServers: boolean; + create: ( + pluginOptions?: Partial, + authOptions?: Partial + ) => Promise; + /** Whether this adapter supports the serial/UUID fixtures. */ + generatedIds: boolean; + name: string; + url: string | undefined; +} + +let databaseCounter = 0; +export const uniqueName = () => { + databaseCounter += 1; + return `bat_${process.pid}_${Date.now().toString(36)}_${databaseCounter}`; +}; + +let generated: string | undefined; +export function generatedDirectory() { + if (!generated) { + const root = join( + process.cwd(), + "node_modules", + ".cache", + "better-auth-telegram-adapters" + ); + mkdirSync(root, { recursive: true }); + generated = mkdtempSync(join(root, `${process.pid}-`)); + } + return generated; +} + +afterAll(() => { + if (generated) { + rmSync(generated, { recursive: true, force: true }); + } +}); + +export async function wrap( + options: AuthOptions, + close: () => Promise +): Promise { + const auth = betterAuth(options); + const context = await auth.$context; + return { + auth, + client: createClient(auth), + rows: (model) => context.adapter.findMany({ model }), + close, + options, + }; +} + +/** Only generated databases are dropped; the URL's original database is never modified. */ +export async function postgresDatabase(url: string) { + const name = uniqueName(); + const execute = async (sql: string) => { + const admin = new pg.Pool({ connectionString: url, max: 1 }); + try { + await admin.query(sql); + } finally { + await admin.end(); + } + }; + await execute(`create database "${name}"`); + const databaseURL = new URL(url); + databaseURL.pathname = `/${name}`; + return { + url: databaseURL.toString(), + drop: () => execute(`drop database if exists "${name}"`), + }; +} + +export async function mysqlDatabase(url: string) { + const name = uniqueName(); + const execute = async (sql: string) => { + const admin = createPool({ uri: url, connectionLimit: 1 }); + try { + await admin.query(sql); + } finally { + await admin.end(); + } + }; + await execute( + `create database \`${name}\` character set utf8mb4 collate utf8mb4_0900_ai_ci` + ); + const databaseURL = new URL(url); + databaseURL.pathname = `/${name}`; + return { + url: databaseURL.toString(), + drop: () => execute(`drop database if exists \`${name}\``), + }; +} diff --git a/src/testing/adapters.ts b/src/testing/adapters.ts index 5450efb..e3b8288 100644 --- a/src/testing/adapters.ts +++ b/src/testing/adapters.ts @@ -1,28 +1,27 @@ -/** - * Test-only: Better Auth on real databases for the adapter lane - * (`npm run test:adapters`). Each database is read from an environment - * variable; a database without one is skipped. - * - * Schemas come from Better Auth itself: its Kysely migrations for PostgreSQL - * and MySQL, the `auth` CLI's generators for Drizzle and Prisma (then - * drizzle-kit / prisma push them), none for MongoDB. - */ -import { execFileSync } from "node:child_process"; -import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +/** Real database fixtures use Better Auth migrations and its generated ORM schemas. */ +import { writeFileSync } from "node:fs"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { drizzleAdapter } from "@better-auth/drizzle-adapter"; import { mongodbAdapter } from "@better-auth/mongo-adapter"; -import { prismaAdapter } from "@better-auth/prisma-adapter"; -import { PrismaPg } from "@prisma/adapter-pg"; -import { generateDrizzleSchema, generatePrismaSchema } from "auth/api"; -import { betterAuth } from "better-auth"; +import { generateDrizzleSchema } from "auth/api"; import { getMigrations } from "better-auth/db/migration"; import { MongoClient } from "mongodb"; import { createPool } from "mysql2/promise"; import pg from "pg"; -import type { TelegramPluginOptions } from "../types"; -import { type AuthOptions, baseOptions, createClient } from "./harness"; +import { prismaLane } from "./adapter-prisma"; +import { + type AdapterAuth, + type AdapterLane, + generatedDirectory, + mysqlDatabase, + postgresDatabase, + uniqueName, + wrap, +} from "./adapter-resources"; +import { baseOptions } from "./auth"; + +export type { AdapterAuth, AdapterLane } from "./adapter-resources"; export const ADAPTER_ENV = { postgres: "BAT_TEST_POSTGRES_URL", @@ -30,82 +29,11 @@ export const ADAPTER_ENV = { mongodb: "BAT_TEST_MONGODB_URL", } as const; -const GENERATED_DIR = join( - process.cwd(), - "node_modules", - ".cache", - "better-auth-telegram-adapters" -); - -type Row = Record; - -export interface AdapterAuth { - auth: ReturnType; - client: ReturnType; - close: () => Promise; - options: AuthOptions; - /** Rows of a Better Auth model, read through the adapter (logical names). */ - rows: (model: "user" | "account" | "session") => Promise; -} - -export interface AdapterLane { - /** - * Two servers can't create the same Telegram user twice: the schema has - * unique indexes (MongoDB's has none) and the adapter writes the user and - * account in one transaction (Drizzle and Prisma only with - * `transaction: true`; this lane keeps their default, false). - */ - concurrentServers: boolean; - create: ( - pluginOptions?: Partial, - authOptions?: Partial - ) => Promise; - /** - * `advanced.database.generateId` "serial" / "uuid" can run here (not on - * MongoDB; the Prisma client is generated once, for the default ids). - */ - generatedIds: boolean; - name: string; - /** Skipped when the database URL is not set. */ - url: string | undefined; -} - -let databaseCounter = 0; -const uniqueName = () => { - databaseCounter += 1; - return `bat_${process.pid}_${Date.now().toString(36)}_${databaseCounter}`; -}; - -async function wrap( - options: AuthOptions, - close: () => Promise -): Promise { - const auth = betterAuth(options); - const context = await auth.$context; - return { - auth, - client: createClient(auth), - rows: (model) => context.adapter.findMany({ model }), - close, - options, - }; -} - -/** A second Better Auth instance ("server") on the same database. */ +/** A second Better Auth instance sharing the first instance's owned database. */ export function attach(harness: AdapterAuth): Promise { return wrap(harness.options, async () => undefined); } -async function postgresDatabase(url: string) { - const name = uniqueName(); - const admin = new pg.Pool({ connectionString: url, max: 1 }); - await admin.query(`create database "${name}"`); - await admin.end(); - const databaseURL = new URL(url); - databaseURL.pathname = `/${name}`; - return databaseURL.toString(); -} - function postgresLane(url: string | undefined): AdapterLane { return { name: "PostgreSQL (Kysely)", @@ -113,16 +41,26 @@ function postgresLane(url: string | undefined): AdapterLane { concurrentServers: true, generatedIds: true, async create(pluginOptions = {}, authOptions = {}) { - const pool = new pg.Pool({ - connectionString: await postgresDatabase(url!), - max: 10, - }); - const options = { - ...baseOptions(pluginOptions, authOptions), - database: pool, + const database = await postgresDatabase(url!); + const pool = new pg.Pool({ connectionString: database.url, max: 10 }); + const close = async () => { + try { + await pool.end(); + } finally { + await database.drop(); + } }; - await (await getMigrations(options)).runMigrations(); - return wrap(options, () => pool.end()); + try { + const options = { + ...baseOptions(pluginOptions, authOptions), + database: pool, + }; + await (await getMigrations(options)).runMigrations(); + return await wrap(options, close); + } catch (error) { + await close(); + throw error; + } }, }; } @@ -134,26 +72,31 @@ function mysqlLane(url: string | undefined): AdapterLane { concurrentServers: true, generatedIds: true, async create(pluginOptions = {}, authOptions = {}) { - const name = uniqueName(); - const admin = createPool({ uri: url!, connectionLimit: 1 }); - await admin.query( - `create database \`${name}\` character set utf8mb4 collate utf8mb4_0900_ai_ci` - ); - await admin.end(); - const databaseURL = new URL(url!); - databaseURL.pathname = `/${name}`; - // Better Auth's MySQL docs: timezone "Z". + const database = await mysqlDatabase(url!); + // Match Better Auth's documented UTC timezone setting. const pool = createPool({ - uri: databaseURL.toString(), + uri: database.url, timezone: "Z", connectionLimit: 10, }); - const options = { - ...baseOptions(pluginOptions, authOptions), - database: pool, + const close = async () => { + try { + await pool.end(); + } finally { + await database.drop(); + } }; - await (await getMigrations(options)).runMigrations(); - return wrap(options, () => pool.end()); + try { + const options = { + ...baseOptions(pluginOptions, authOptions), + database: pool, + }; + await (await getMigrations(options)).runMigrations(); + return await wrap(options, close); + } catch (error) { + await close(); + throw error; + } }, }; } @@ -166,17 +109,30 @@ function mongoLane(url: string | undefined): AdapterLane { generatedIds: false, async create(pluginOptions = {}, authOptions = {}) { const client = new MongoClient(url!); - await client.connect(); + try { + await client.connect(); + } catch (error) { + await client.close(); + throw error; + } const db = client.db(uniqueName()); - // `client` enables transactions (the container runs a replica set). - const options = { - ...baseOptions(pluginOptions, authOptions), - database: mongodbAdapter(db, { client }), + const close = async () => { + try { + await db.dropDatabase(); + } finally { + await client.close(); + } }; - return wrap(options, async () => { - await db.dropDatabase(); - await client.close(); - }); + try { + const options = { + ...baseOptions(pluginOptions, authOptions), + database: mongodbAdapter(db, { client }), + }; + return await wrap(options, close); + } catch (error) { + await close(); + throw error; + } }, }; } @@ -190,100 +146,39 @@ function drizzleLane(url: string | undefined): AdapterLane { async create(pluginOptions = {}, authOptions = {}) { const { drizzle } = await import("drizzle-orm/node-postgres"); const { pushSchema } = await import("drizzle-kit/api"); - const pool = new pg.Pool({ - connectionString: await postgresDatabase(url!), - max: 10, - }); - const plain = baseOptions(pluginOptions, authOptions); - // `npx auth generate` for Drizzle, written where drizzle-orm resolves. - const generated = await generateDrizzleSchema({ - adapter: drizzleAdapter({}, { provider: "pg" })(plain), - options: plain, - file: "schema.ts", - }); - mkdirSync(GENERATED_DIR, { recursive: true }); - const file = join(GENERATED_DIR, `${uniqueName()}.drizzle.ts`); - writeFileSync(file, generated.code!); - const schema = await import(pathToFileURL(file).href); - const db = drizzle(pool, { schema }); - const { apply } = await pushSchema(schema, db as any); - await apply(); - const options = { - ...plain, - database: drizzleAdapter(db, { provider: "pg", schema }), - }; - return wrap(options, () => pool.end()); - }, - }; -} - -/** - * Prisma generates one client per schema, so this lane runs the default - * options only and empties the tables between tests. - */ -function prismaLane(url: string | undefined): AdapterLane { - let ready: Promise<{ PrismaClient: any; databaseURL: string }> | undefined; - const prepare = async () => { - const databaseURL = await postgresDatabase(url!); - const plain = baseOptions({ miniApp: { enabled: true } }, {}); - mkdirSync(GENERATED_DIR, { recursive: true }); - const schemaFile = join(GENERATED_DIR, "schema.prisma"); - const clientDir = join(GENERATED_DIR, "prisma-client"); - // The generator edits an existing file. Start from what `prisma init` - // writes for a new Prisma 7 app: the `prisma-client` generator needs an - // output directory, and the URL lives outside the schema. - rmSync(clientDir, { recursive: true, force: true }); - writeFileSync( - schemaFile, - `generator client {\n provider = "prisma-client"\n output = "./prisma-client"\n}\n\ndatasource db {\n provider = "postgresql"\n}\n` - ); - const generated = await generatePrismaSchema({ - adapter: prismaAdapter({}, { provider: "postgresql" })(plain), - options: plain, - file: schemaFile, - }); - writeFileSync(schemaFile, generated.code!); - const prisma = (...args: string[]) => - execFileSync("npx", ["prisma", ...args, `--schema=${schemaFile}`], { - stdio: "pipe", - }); - // A database created for this run: nothing to lose, so no - // --accept-data-loss. - prisma("db", "push", `--url=${databaseURL}`); - prisma("generate"); - // This schema's client only exists after generate; a clean checkout's - // type-check must not depend on a previously generated database client. - const { PrismaClient } = await import( - pathToFileURL(join(clientDir, "client.ts")).href - ); - return { PrismaClient, databaseURL }; - }; - return { - name: "Prisma (PostgreSQL)", - url, - concurrentServers: false, - generatedIds: false, - async create(pluginOptions = {}, authOptions = {}) { - ready ??= prepare(); - const { PrismaClient, databaseURL } = await ready; - const prisma = new PrismaClient({ - adapter: new PrismaPg({ connectionString: databaseURL }), - }); - // Children first: session and account reference user. - await prisma.$transaction([ - prisma.session.deleteMany(), - prisma.account.deleteMany(), - prisma.verification.deleteMany(), - prisma.user.deleteMany(), - ]); - const options = { - ...baseOptions( - { miniApp: { enabled: true }, ...pluginOptions }, - authOptions - ), - database: prismaAdapter(prisma, { provider: "postgresql" }), + const database = await postgresDatabase(url!); + const pool = new pg.Pool({ connectionString: database.url, max: 10 }); + const close = async () => { + try { + await pool.end(); + } finally { + await database.drop(); + } }; - return wrap(options, () => prisma.$disconnect()); + try { + const plain = baseOptions(pluginOptions, authOptions); + const generated = await generateDrizzleSchema({ + adapter: drizzleAdapter({}, { provider: "pg" })(plain), + options: plain, + file: "schema.ts", + }); + const file = join(generatedDirectory(), `${uniqueName()}.drizzle.ts`); + writeFileSync(file, generated.code!); + const schema = await import(pathToFileURL(file).href); + const db = drizzle(pool, { schema }); + const { apply } = await pushSchema(schema, db as any); + await apply(); + return await wrap( + { + ...plain, + database: drizzleAdapter(db, { provider: "pg", schema }), + }, + close + ); + } catch (error) { + await close(); + throw error; + } }, }; } diff --git a/src/testing/auth.ts b/src/testing/auth.ts index ce1cb73..393373d 100644 --- a/src/testing/auth.ts +++ b/src/testing/auth.ts @@ -2,6 +2,7 @@ import { DatabaseSync } from "node:sqlite"; import { betterAuth } from "better-auth"; import { memoryAdapter } from "better-auth/adapters/memory"; import { getMigrations } from "better-auth/db/migration"; +import { onTestFinished } from "vitest"; import { telegram } from "../index"; import type { TelegramPluginOptions } from "../types"; import { BASE_URL, BOT_TOKEN } from "./constants"; @@ -66,12 +67,24 @@ export async function createSqliteAuth( authOptions: Partial = {} ) { const sqlite = new DatabaseSync(":memory:"); + const close = () => { + if (sqlite.isOpen) { + sqlite.close(); + } + }; + // Register before setup: a failed migration or assertion must release the handle. + onTestFinished(close); const options = { ...baseOptions(pluginOptions, authOptions), database: sqlite, }; - const { runMigrations } = await getMigrations(options); - await runMigrations(); + try { + const { runMigrations } = await getMigrations(options); + await runMigrations(); + } catch (error) { + close(); + throw error; + } const auth = betterAuth(options); const rows = (table: string) => sqlite.prepare(`select * from "${table}"`).all() as Record[]; diff --git a/src/testing/oidc-server.ts b/src/testing/oidc-server.ts index 27cf2cb..5cdefd5 100644 --- a/src/testing/oidc-server.ts +++ b/src/testing/oidc-server.ts @@ -39,7 +39,7 @@ export interface AuthorizeOptions { /** * Fake oauth.telegram.org. Intercepts `fetch` for the token and JWKS - * endpoints; everything else falls through to the real `fetch`. + * endpoints. Unexpected requests fail instead of reaching a real network. */ export async function mockTelegramOIDC( options: { @@ -68,25 +68,24 @@ export async function mockTelegramOIDC( let jwksRequests = 0; let codeCounter = 0; - const realFetch = globalThis.fetch; const fetchSpy = vi .spyOn(globalThis, "fetch") .mockImplementation(async (input, init) => { const { url } = new Request(input as RequestInfo); - if (url.startsWith(TELEGRAM_JWKS_URI)) { + if (url === TELEGRAM_JWKS_URI) { jwksRequests += 1; return jwksStatus === 200 ? Response.json({ keys: [signingKey.jwk] }) : new Response("Service Unavailable", { status: jwksStatus }); } - if (url.startsWith(TELEGRAM_TOKEN_ENDPOINT)) { + if (url === TELEGRAM_TOKEN_ENDPOINT) { const request = new Request(input as RequestInfo, init); const body = new URLSearchParams(await request.text()); const authorization = request.headers.get("authorization"); tokenRequests.push({ authorization, body }); return Response.json(await tokenResponse(authorization, body)); } - return realFetch(input as RequestInfo, init); + throw new Error(`Unexpected network request in Telegram fixture: ${url}`); }); /** Signs an ID token; `iss` / `aud` in `claims` override Telegram's. */ @@ -99,8 +98,8 @@ export async function mockTelegramOIDC( .setProtectedHeader({ alg, kid: signingKey.kid, typ: "JWT" }) .setIssuer(claims.iss ?? TELEGRAM_ISSUER) .setAudience(claims.aud ?? clientId) - .setIssuedAt(now) - .setExpirationTime(now + 30) + .setIssuedAt(claims.iat ?? now) + .setExpirationTime(claims.exp ?? now + 30) .sign(key); } diff --git a/src/types.ts b/src/types.ts index 6427e21..adc4611 100644 --- a/src/types.ts +++ b/src/types.ts @@ -69,6 +69,7 @@ export interface TelegramMiniAppData { * EdDSA or ES256K. */ export interface TelegramOIDCClaims { + /** Verified audience, normalized to the configured client ID. */ aud: string; exp: number; family_name?: string; diff --git a/src/verify.test.ts b/src/verify.test.ts index f8b75e3..1283199 100644 --- a/src/verify.test.ts +++ b/src/verify.test.ts @@ -12,12 +12,7 @@ */ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { signInitParams } from "./testing/harness"; -import { - parseMiniAppInitData, - validateMiniAppData, - verifyMiniAppInitData, - verifyTelegramAuth, -} from "./verify"; +import { verifyMiniAppInitData, verifyTelegramAuth } from "./verify"; const BOT_TOKEN = "123456789:AAtesttokentesttokentesttokentest"; /** Same bot id, different secret: the key must come from the whole token. */ @@ -128,22 +123,3 @@ describe("Mini App initData hash (literal vector)", () => { expect(await verifyMiniAppInitData(undated, BOT_TOKEN)).toBe(false); }); }); - -describe("parseMiniAppInitData", () => { - it("drops a malformed user JSON instead of throwing (the endpoint answers 400, not 500)", () => { - const parsed = parseMiniAppInitData( - "user={invalid json}&auth_date=1761730000&hash=abc123" - ); - - expect(parsed.user).toBeUndefined(); - expect(parsed.auth_date).toBe(1_761_730_000); - }); -}); - -describe("validateMiniAppData", () => { - it("rejects a null user without throwing", () => { - expect(validateMiniAppData({ user: null, auth_date: 1, hash: "x" })).toBe( - false - ); - }); -}); diff --git a/src/verify.ts b/src/verify.ts index db1f683..11c8c5f 100644 --- a/src/verify.ts +++ b/src/verify.ts @@ -121,6 +121,11 @@ export async function verifyTelegramAuth( return verifyHmacHex(secretKey, dataCheckString, hash); } +/** Reject identities that JSON numbers cannot represent without changing them. */ +function isTelegramUserId(id: unknown): id is number { + return typeof id === "number" && Number.isSafeInteger(id) && id > 0; +} + /** * Validates that required fields are present in Telegram auth data */ @@ -128,7 +133,7 @@ export function validateTelegramAuthData(data: any): data is TelegramAuthData { return ( typeof data === "object" && data !== null && - typeof data.id === "number" && + isTelegramUserId(data.id) && typeof data.first_name === "string" && typeof data.auth_date === "number" && typeof data.hash === "string" @@ -175,6 +180,11 @@ export async function verifyMiniAppInitData( maxAge = DEFAULT_MAX_AUTH_AGE ): Promise { const params = new URLSearchParams(initData); + // Verification reads first values; parsing keeps last values. Telegram's + // fields are unique, so reject ambiguity before trusting either view. + if (new Set(params.keys()).size !== params.size) { + return false; + } const hash = params.get("hash"); if (!hash) { @@ -215,7 +225,7 @@ export function validateMiniAppData(data: any): data is TelegramMiniAppData { (data.user === undefined || (typeof data.user === "object" && data.user !== null && - typeof data.user.id === "number" && + isTelegramUserId(data.user.id) && typeof data.user.first_name === "string")) ); } diff --git a/src/widget-mappers.integration.test.ts b/src/widget-mappers.integration.test.ts index baaa0ce..6a3365c 100644 --- a/src/widget-mappers.integration.test.ts +++ b/src/widget-mappers.integration.test.ts @@ -60,7 +60,7 @@ describe("what user mappers can set", () => { // A placeholder variant is still reserved for that Telegram user. it("refuses an email sign-up with another user's placeholder variant", async () => { - const { client } = await createSqliteAuth( + const { client, rows } = await createSqliteAuth( {}, { emailAndPassword: { enabled: true } } ); @@ -71,7 +71,12 @@ describe("what user mappers can set", () => { name: "Squatter", }); - expect(response.status).not.toBe(200); + expect(response.status).toBe(400); + expect(response.json.code).toBe("FAILED_TO_CREATE_USER"); + expect(rows("user")).toHaveLength(0); + expect(rows("account")).toHaveLength(0); + expect(rows("session")).toHaveLength(0); + expect(client.hasSession()).toBe(false); }); // Better Auth's /sign-up/email answers 422 USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL. diff --git a/src/widget.integration.test.ts b/src/widget.integration.test.ts index 524477a..06727e0 100644 --- a/src/widget.integration.test.ts +++ b/src/widget.integration.test.ts @@ -1,4 +1,5 @@ // @vitest-environment node +import { APIError } from "better-auth/api"; import { afterEach, describe, expect, it, vi } from "vitest"; import { createClient, @@ -33,22 +34,10 @@ describe("Login Widget sign-in", () => { }); }); - it("keeps an email returned by mapTelegramDataToUser", async () => { - const { client, db } = createMemoryAuth({ - mapTelegramDataToUser: (data) => ({ - name: data.first_name, - email: `ann-${data.id}@example.com`, - }), - }); - - await client.post("/telegram/signin", await widgetUser()); - - expect(db.user[0]!.email).toBe("ann-42@example.com"); - }); - it("returns the same user on the next sign-in and refreshes the username", async () => { const { client, db } = createMemoryAuth(); - await client.post("/telegram/signin", await widgetUser()); + const first = await client.post("/telegram/signin", await widgetUser()); + expect(first.status).toBe(200); client.clearCookies(); const response = await client.post( @@ -57,30 +46,12 @@ describe("Login Widget sign-in", () => { ); expect(response.status).toBe(200); + expect(response.json.user.id).toBe(first.json.user.id); expect(db.user).toHaveLength(1); expect(db.user[0]!.telegramUsername).toBe("ann_new"); expect(db.account[0]!.telegramUsername).toBe("ann_new"); }); - it("runs Better Auth database hooks for the new user and account", async () => { - const userBefore = vi.fn(); - const accountAfter = vi.fn(); - const { client } = createMemoryAuth( - {}, - { - databaseHooks: { - user: { create: { before: userBefore } }, - account: { create: { after: accountAfter } }, - }, - } - ); - - await client.post("/telegram/signin", await widgetUser()); - - expect(userBefore).toHaveBeenCalledOnce(); - expect(accountAfter).toHaveBeenCalledOnce(); - }); - it("honors user.validateUserInfo", async () => { const validateUserInfo = vi.fn(async () => ({ error: "not_invited" })); const { client, db } = createMemoryAuth({}, { user: { validateUserInfo } }); @@ -110,7 +81,10 @@ describe("Login Widget sign-in", () => { ); expect(response.status).toBe(401); + expect(response.json.code).toBe("INVALID_AUTHENTICATION"); expect(db.user).toHaveLength(0); + expect(db.account).toHaveLength(0); + expect(db.session).toHaveLength(0); }); it("answers 404 when auto-create is disabled", async () => { @@ -119,7 +93,10 @@ describe("Login Widget sign-in", () => { const response = await client.post("/telegram/signin", await widgetUser()); expect(response.status).toBe(404); + expect(response.json.code).toBe("USER_CREATION_DISABLED"); expect(db.user).toHaveLength(0); + expect(db.account).toHaveLength(0); + expect(db.session).toHaveLength(0); }); }); @@ -237,6 +214,7 @@ describe("Login Widget request validation", () => { const response = await client.post("/telegram/signin", { id: 42 }); expect(response.status).toBe(400); + expect(response.json.code).toBe("INVALID_AUTH_DATA"); }); it("answers 500 when the bot token is not configured", async () => { @@ -257,12 +235,15 @@ describe("Login Widget request validation", () => { }); it("answers 403 when linking is disabled", async () => { - const { client } = createMemoryAuth({ allowUserToLink: false }); + const { client, db } = createMemoryAuth({ allowUserToLink: false }); await client.post("/telegram/signin", await widgetUser()); const response = await client.post("/telegram/link", await widgetUser(43)); expect(response.status).toBe(403); + expect(response.json.code).toBe("LINKING_DISABLED"); + expect(db.account.map((account) => account.accountId)).toEqual(["42"]); + expect(db.user[0]!.telegramId).toBe("42"); }); it("answers 409 when the Telegram account is already linked to this user", async () => { @@ -293,43 +274,47 @@ describe("Login Widget request validation", () => { }); describe("Telegram account bookkeeping", () => { - it("does not write when nothing changed since the last sign-in", async () => { - const userUpdate = vi.fn(); - const { client } = createMemoryAuth( - {}, - { databaseHooks: { user: { update: { before: userUpdate } } } } - ); - await client.post("/telegram/signin", await widgetUser()); - client.clearCookies(); - - await client.post("/telegram/signin", await widgetUser()); - - expect(userUpdate).not.toHaveBeenCalled(); - }); - - it("does not write on every sign-in for users without a Telegram username", async () => { - const userUpdate = vi.fn(); - const accountUpdate = vi.fn(); - // SQL returns null for the missing username; the memory adapter keeps - // undefined, which would hide the bug. - const { client } = await createSqliteAuth( - {}, - { - databaseHooks: { - user: { update: { before: userUpdate } }, - account: { update: { before: accountUpdate } }, - }, + it.each([undefined, "ann"])( + "signs in without rewriting unchanged user/account metadata (username %s)", + async (username) => { + const userUpdate = vi.fn(); + const accountUpdate = vi.fn(); + // SQL stores a missing username as null, unlike the memory adapter. + const { client, rows, sqlite } = await createSqliteAuth( + {}, + { + databaseHooks: { + user: { update: { before: userUpdate } }, + account: { update: { before: accountUpdate } }, + }, + } + ); + try { + const payload = await signWidgetData({ + id: 42, + first_name: "Ann", + ...(username === undefined ? {} : { username }), + }); + const first = await client.post("/telegram/signin", payload); + expect(first.status).toBe(200); + const [storedUser] = rows("user"); + const [storedAccount] = rows("account"); + client.clearCookies(); + + const again = await client.post("/telegram/signin", payload); + const session = await client.get("/get-session"); + + expect(again.status).toBe(200); + expect(session.json.user.id).toBe(first.json.user.id); + expect(rows("user")).toEqual([storedUser]); + expect(rows("account")).toEqual([storedAccount]); + expect(userUpdate).not.toHaveBeenCalled(); + expect(accountUpdate).not.toHaveBeenCalled(); + } finally { + sqlite.close(); } - ); - const noUsername = () => signWidgetData({ id: 42, first_name: "Ann" }); - await client.post("/telegram/signin", await noUsername()); - client.clearCookies(); - - await client.post("/telegram/signin", await noUsername()); - - expect(userUpdate).not.toHaveBeenCalled(); - expect(accountUpdate).not.toHaveBeenCalled(); - }); + } + ); it("restores a missing telegramId on users that already have the account", async () => { const { client, db } = createMemoryAuth(); @@ -451,6 +436,29 @@ describe("another server creating the same Telegram user first", () => { expect(response.json.user.id).toBe(db.user[0]!.id); }); + it("does not turn an application refusal into sign-in after another server created the user", async () => { + const { serverA, db } = racingServers( + () => + new APIError("FORBIDDEN", { + code: "INVITE_REVOKED", + message: "Invite revoked", + }) + ); + + const response = await serverA.client.post( + "/telegram/signin", + await widgetUser() + ); + + expect(response.status).toBe(403); + expect(response.json.code).toBe("INVITE_REVOKED"); + expect(serverA.client.hasSession()).toBe(false); + expect(db.user).toHaveLength(1); + expect(db.account).toHaveLength(1); + // Only server B's permitted sign-in may have created a session. + expect(db.session).toHaveLength(1); + }); + it("still reports a database error when no Telegram user was created", async () => { const { client, db } = createMemoryAuth( {}, @@ -542,7 +550,3 @@ describe("maxAuthAge reaches the sign-in endpoints", () => { } ); }); - -// Better Auth's OAuth sign-up drops `id`, `email`, `emailVerified` and -// `input: false` fields from provider profiles (link-account.mjs, -// db/schema.mjs parseAdditionalUserInputFromProviderProfile). diff --git a/test-d/commonjs.cts b/test-d/commonjs.cts new file mode 100644 index 0000000..f9a5fec --- /dev/null +++ b/test-d/commonjs.cts @@ -0,0 +1,29 @@ +// A .cts consumer selects the require declarations; .ts in this ESM fixture +// only checks the import declarations, even under moduleResolution Node16. + +import server = require("better-auth-telegram"); +import browser = require("better-auth-telegram/client"); + +type IsAny = 0 extends 1 & T ? true : false; +function typed(_value: T, ..._check: IsAny extends true ? [never] : []) { + return _value; +} + +export async function commonJSConsumer() { + const { betterAuth } = await import("better-auth"); + const { createAuthClient } = await import("better-auth/client"); + const auth = betterAuth({ + plugins: [server.telegram({ botToken: "1:x", botUsername: "bot" })], + }); + const client = createAuthClient({ plugins: [browser.telegramClient()] }); + + const session = await auth.api.getSession({ headers: new Headers() }); + typed(session?.user.telegramId) satisfies string | null | undefined; + const result = await client.signInWithMiniApp("raw-signed-init-data"); + if (!result.error) { + typed(result.data.user.telegramId) satisfies string | null | undefined; + typed(result.data.session.token) satisfies string; + } + // @ts-expect-error CommonJS must preserve the same raw initData input contract + await client.signInWithMiniApp({ user: { id: 42 } }); +} diff --git a/test-d/consumer.ts b/test-d/consumer.ts index ebad225..3571113 100644 --- a/test-d/consumer.ts +++ b/test-d/consumer.ts @@ -35,7 +35,7 @@ const client = createAuthClient({ plugins: [telegramClient()] }); typed(client.signInWithTelegram); typed(client.signInWithTelegramOIDC); -// Telegram sends the user id as a string (a number would lose precision). +// The verified mapper profile normalizes Telegram numeric IDs to strings. export const id: TelegramOIDCClaims["id"] = "8306595751"; // @ts-expect-error the id claim is a string, never a number export const numericId: TelegramOIDCClaims["id"] = 8306595751; @@ -76,3 +76,30 @@ export async function widgets(element: HTMLElement) { const redirect = await client.initTelegramWidgetRedirect(element, "/cb"); redirect.destroy(); } + +// These calls compile against the published declarations, not source types. +// A function typed with `any` arguments still passes typed(function), so also +// check the input and result contracts consumers rely on. +export async function signInContract() { + const result = await client.signInWithTelegram({ + id: 42, + first_name: "Ann", + auth_date: 1_761_730_000, + hash: "signed-payload", + }); + if (result.error) { + typed(result.error.code) satisfies string | undefined; + } else { + typed(result.data.user.telegramId) satisfies string | null | undefined; + typed(result.data.session.token) satisfies string; + } + await client.signInWithTelegram({ + // @ts-expect-error raw Widget IDs are numbers, unlike normalized OIDC IDs + id: "42", + first_name: "Ann", + auth_date: 1, + hash: "x", + }); + // @ts-expect-error Mini App sign-in accepts the raw signed string, not parsed data + await client.signInWithMiniApp({ user: { id: 42 } }); +} diff --git a/test-d/snippets.ts b/test-d/snippets.ts index 49f90c5..a318da7 100644 --- a/test-d/snippets.ts +++ b/test-d/snippets.ts @@ -276,13 +276,12 @@ export const membersOnly = telegram({ enabled: true, clientId: process.env.TELEGRAM_OIDC_CLIENT_ID, clientSecret: process.env.TELEGRAM_OIDC_CLIENT_SECRET, - // memberId is declared in betterAuth({ user: { additionalFields } }) mapOIDCProfileToUser: async (claims) => { const member = await findMemberByTelegramId(claims.id); if (!member) { throw new APIError("FORBIDDEN", { message: "NOT_A_MEMBER" }); } - return { memberId: member.id, name: member.name }; + return { name: member.name }; }, }, }); diff --git a/test-d/tsconfig.node16.json b/test-d/tsconfig.node16.json index 1cb28f6..239ad9f 100644 --- a/test-d/tsconfig.node16.json +++ b/test-d/tsconfig.node16.json @@ -3,5 +3,6 @@ "compilerOptions": { "module": "Node16", "moduleResolution": "Node16" - } + }, + "files": ["consumer.ts", "snippets.ts", "commonjs.cts"] } From af0ca545bf814cf5d3331e0043452446890e4aea Mon Sep 17 00:00:00 2001 From: vcode-sh Date: Wed, 4 Nov 2026 11:16:46 +0100 Subject: [PATCH 2/6] chore: enhance testing documentation and structure Updated the .gitignore to expose only the repository skill while ignoring local Claude state. Revised AGENTS.md and CLAUDE.md to reference the new testing-patterns skill for improved test authoring and verification. Added comprehensive documentation for the testing-patterns skill and repository testing reference to guide contributors on effective testing practices. This update aims to streamline testing processes and ensure meaningful test coverage. --- .agents/skills/testing-patterns/SKILL.md | 97 +++++++++++ .../testing-patterns/references/repository.md | 138 +++++++++++++++ .claude/skills/testing-patterns | 1 + .gitignore | 6 + AGENTS.md | 8 +- CLAUDE.md | 2 +- docs/testing.md | 163 ++---------------- 7 files changed, 263 insertions(+), 152 deletions(-) create mode 100644 .agents/skills/testing-patterns/SKILL.md create mode 100644 .agents/skills/testing-patterns/references/repository.md create mode 120000 .claude/skills/testing-patterns diff --git a/.agents/skills/testing-patterns/SKILL.md b/.agents/skills/testing-patterns/SKILL.md new file mode 100644 index 0000000..31ce637 --- /dev/null +++ b/.agents/skills/testing-patterns/SKILL.md @@ -0,0 +1,97 @@ +--- +name: testing-patterns +description: "Write, review, or prune better-auth-telegram tests; choose justified expectations, fixtures, behavior boundaries, and verification effort. Use when deciding whether a test adds protection. Does not authorize a general code audit, suite cleanup, or runtime changes." +--- + +# Tests that earn their place + +Protect a justified contract or deliberate compatibility baseline, distinguish a +meaningful failure, and weigh the additional protection against maintenance cost. +Stay within the task. A small edit does not require a full audit or testing plan. +Read [repository guidance](references/repository.md) when choosing a local runner, +fixture, dependency boundary, or required gate. + +## Establish the claim + +Read the relevant implementation, callers and existing protection. Identify the +contract and its provenance, a plausible failure class, the behavior owner, and +what the proposed test adds. Usually the test name or a short explanation is enough. +If existing tests and static checks adequately protect the task, add no new test. + +Requirements, protocol examples, checked calculations, domain properties and +reviewed references can justify expected results. Current implementation is useful +but fallible evidence; do not use the calculation under test as its own oracle. +Shared setup and unrelated parsing helpers can be legitimate. A recorded legacy +output can protect compatibility during a refactor: label and review that baseline +without claiming it proves business correctness. If the contract is unknown, keep +the uncertainty visible rather than inventing an expectation. + +## Make the case discriminate + +Choose reachable inputs, relevant boundaries, roles, states or combinations that +separate the contract from the named mistake. Run the actual behavior owner. +Assert promised outputs and relevant effects: identities, durable state, external +requests, user-visible results, errors and prohibited actions. A denial must reach +the intended decision; invalid setup or an unawaited operation can make it vacuous. +Be precise about important fields without freezing unrelated output. + +Use the narrowest boundary that preserves the failure mechanism. Real database +engines are needed for claims about their constraints, transactions or locking; +a substitute does not establish those semantics. A real dependency is not required +for every test that happens to call it. Client-store behavior needs the real store; +DOM emulation does not establish browser layout or Telegram's live behavior. +Complementary unit, integration, contract and acceptance tests may overlap usefully. + +Mocks and fakes can control external responses, time, rare errors or expensive +collaborators. Interaction assertions can protect request contracts, forbidden +calls, duplication limits or ordering. Reviewed snapshots/goldens can protect +formats or visual baselines; source/architecture checks can enforce an explicit +structural policy. Type, presence and smoke checks can protect limited interface +or startup contracts. Judge their purpose, not their syntax; do not ban these +techniques or present them as stronger evidence than they supply. + +## Check sensitivity proportionately + +For a confirmed bug, prefer a focused failing regression before the fix when RED +is stable and economical. Inspect why it fails. For a doubtful assertion or an +important invariant, consider a targeted fault or mutation when it adds useful +confidence. Do not impose mutation on every test, a universal coverage target, +mandatory separate-model review, or a new testing dependency. + +A killed mutant does not validate the oracle. A survivor may be equivalent, +irrelevant, unreachable or evidence of weak protection. A broken build/import or +unselected case is not behavioral detection; an intentional consumer-type failure +can be the correct signal for a declaration contract. Restore only your own probes +and verify the resulting tree. Use an isolated copy when work is shared. + +Generated inputs need a useful domain and property, reviewed preconditions/filters, +and reproducible failures. Round trips can hide mutually cancelling faults; +differential agreement depends on a fallible reference. Retain independent examples +where they protect another dimension. No technique is mandatory for every function. + +## Decide and finish + +For an authorized test review, use: + +- **KEEP:** useful contract, reviewed baseline or distinct boundary at acceptable cost. +- **REWRITE:** meaningful risk, but inadequate oracle, fixture, boundary or reliability. +- **DELETE:** obsolete/no useful role, or equivalent relevant protection remains; + inspect callers, incident coverage, fixtures, registrations and required gates first. +- **UNRESOLVED:** insufficient contract or evidence; retain the test pending investigation. + +Equal coverage or mutation scores do not prove equivalent future protection. Do not +prune to a count target. "Confirmation testing" can legitimately mean verifying a +bug fix; describe weak cases as implementation-mirroring or weak-oracle tests. + +Await work and eventual assertions. Coordinate races at the relevant boundary +where practical; do not rely only on simultaneous promise creation. Prefer bounded +observable waits to guessed sleeps, and investigate intermittent product failures +instead of hiding them with retries. Any quarantine needs a reason, owner and path +back to coverage. Restore clocks, listeners, mocks and owned state; release owned +files, connections, processes and containers on failure, cancellation and timeout. + +Preserve the project's required gates, including surface acceptance when applicable. +Use the smallest relevant checks and reuse valid evidence until its assumptions +change. Coverage is a diagnostic, not a correctness certificate: do not lower gates, +exclude code or weaken assertions for a score. Report decisions, checks actually run, +unproved boundaries and cleanup; distinguish observation from prediction. diff --git a/.agents/skills/testing-patterns/references/repository.md b/.agents/skills/testing-patterns/references/repository.md new file mode 100644 index 0000000..d822075 --- /dev/null +++ b/.agents/skills/testing-patterns/references/repository.md @@ -0,0 +1,138 @@ +# Repository testing reference + +Paths below are relative to this reference. Run commands from the repository root. +Verify the current scripts/configuration when they change; this reference does not +override task scope or authorize installing dependencies or starting services. + +## Owners and fixtures + +| Claim | Owner and existing evidence | +| --- | --- | +| Signed Widget/Mini App data, freshness and canonical fields | [verify.ts](../../../../src/verify.ts), [literal vectors](../../../../src/verify.test.ts), [boundary tests](../../../../src/verify-hardening.test.ts) | +| OIDC token identity and mapping | [oidc-token.ts](../../../../src/oidc-token.ts), [oidc.ts](../../../../src/oidc.ts), co-located OIDC suites | +| Account ownership, hooks, revocation and session cookies | [account orchestration](../../../../src/telegram-account.ts), [identity hooks](../../../../src/telegram-identity.ts), [real-adapter suite](../../../../src/adapters.adapter.test.ts) | +| Client session refresh | [client.ts](../../../../src/client.ts), [real client/server tests](../../../../src/client.integration.test.ts) | +| Widget callback/host lifecycle | [client-widget.ts](../../../../src/client-widget.ts), [DOM tests](../../../../src/client.test.ts) | +| Installed exports and consumer types | [package verifier](../../../../scripts/check-package.mjs), [test-d](../../../../test-d/consumer.ts), [CommonJS consumer](../../../../test-d/commonjs.cts) | + +[testing/harness.ts](../../../../src/testing/harness.ts) exposes real Better Auth on +memory or SQLite, a cookie-aware HTTP client, signed inputs and a fake Telegram +issuer. Substitute the external provider, not Better Auth's authentication decisions. +The signing helpers are input factories; literal OpenSSL vectors independently +check the cryptographic format. The fake issuer rejects unexpected network calls. +SQLite fixtures register `onTestFinished` cleanup, including setup failure. + +The client integration tests use the real Better Auth store and server. Control +scheduled refresh work before asserting absence of a request; an immediate assertion +may run too early. Browser layout, iframe cookies and live Telegram login require +the corresponding acceptance environment. [test/](../../../../test/README.md) is a +manual playground, not an automated test lane. + +## Selection and gates + +The source of truth is [package.json](../../../../package.json), +[Vitest config](../../../../vitest.config.ts), +[adapter config](../../../../vitest.adapters.config.ts) and +[CI](../../../../.github/workflows/ci.yml). Node 24+ is required. Existing installs +are sufficient for the commands below; do not install or upgrade tools gratuitously. + +```sh +# Focused default-suite cases; inspect the selected/passed/skipped counts. +npm test -- src/verify-hardening.test.ts -t 'auth_date freshness' +npm test -- src/client.integration.test.ts -t 'disableSignal' + +# Scope lint while editing; type-check the package for affected TypeScript. +./node_modules/.bin/ultracite check src/verify-hardening.test.ts +npm run type-check + +# Default suite and its coverage gate. +npm test +npm run test:coverage + +# Bun compatibility uses Vitest under Bun, not the unrelated `bun test` runner. +bun --bun run test + +# Built public declarations and an isolated installed-package consumer. +npm run build +npm run test:types +npm run test:package +``` + +Default tests use happy-dom unless their file selects Node. `*.adapter.test.ts` is +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 +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 +when relevant, and `git diff --check`; do not run the runtime matrix just for prose. +A type-contract failure is assessed through declaration consumers, not only runtime +coverage. Tests at different levels can protect different failures of one feature. + +## Real adapters and resource ownership + +[testing/adapters.ts](../../../../src/testing/adapters.ts), +[adapter-resources.ts](../../../../src/testing/adapter-resources.ts) and +[adapter-prisma.ts](../../../../src/testing/adapter-prisma.ts) own fixture lifecycle. +The lane requires explicit URLs to disposable, test-owned services: + +- `BAT_TEST_POSTGRES_URL`: PostgreSQL, also used by Drizzle and Prisma. +- `BAT_TEST_MYSQL_URL`: MySQL; the fixture needs permission to create databases. +- `BAT_TEST_MONGODB_URL`: MongoDB replica set with direct connection support. + +Missing URLs skip the corresponding lanes. An all-skipped collection is not a pass. +The checked-in CI service setup uses PostgreSQL 18, MySQL 8.4 and MongoDB 8.2 with a +replica set. There is no repository-local general container launcher; use the +workflow as the setup reference for an authorized disposable run, not guessed host +ports, shared databases or another project's commands. + +Once those owned URLs are exported: + +```sh +npm run test:adapters +npm run test:adapters -- src/adapters.adapter.test.ts -t 'rejects account hooks' +``` + +The fixtures create named `bat_*` databases, close pools and drop owned databases. +Prisma has a suite-owned database; generated clients/schemas have per-run directories +under `node_modules/.cache/better-auth-telegram-adapters` and are removed after tests. +Caller-owned harnesses still need `close()` in teardown, including failed assertions. +For a process killed before hooks finish, the coordinator must remove its identified +containers/volumes and run-specific files. Verify cleanup without deleting shared +services, all `bat_*` databases on an unverified host, or another run's cache. + +Inside Better Auth transactions, use the current transaction adapter for reads. +Memory/SQLite rollback does not establish Drizzle/Prisma's default nontransactional +behavior. Generated serial/UUID IDs and independent servers need their actual +adapter lane. Existing cross-server identity uniqueness limits remain limits, not +promises supplied by containers or a process-local lock. + +## Useful local decisions + +- **Freshness:** the documented age window includes its endpoint. Use explicit + boundary expectations, with literal vectors elsewhere protecting signing. A + helper that computes the same age rule cannot be the oracle for that rule. +- **Binding refusal:** a 409 response alone misses a bad account insert that remains + after rejection. Use valid conflicting owners and durable readback on the relevant + nontransactional adapter. The faster memory case can remain complementary. +- **Session refresh:** keep the real store and await its scheduler; a mock notification + call alone cannot establish that the mounted session changed. +- **Compatibility:** preserve a reviewed serialized baseline during an internal + refactor, even if the format is quirky. A type-only public declaration change may + need a consumer check; a documentation correction with adequate existing coverage + may need no new test. Neither implies a blanket snapshot or structural-check ban. + +## Provenance + +Adapted from the supplied research reviewed 2026-11-04: +`guidelines.md` and `audit.md` in `/home/vcode/docs/research/test-quality-2026/`. +SHA-256 digests respectively: + +- `0b19c15a4d1fbccbbea6f61564788fa4d9e2a1c2a1992710465faea19da8d764` +- `7bd25662e3f4964c087a30d9dd07ce49078bec0fae445945838d9aa99e9321ce` + +Those external paths identify the source material; the skill does not require them +at runtime. The qualifications are incorporated in the shared core. The research +bibliography is not copied into default-loaded instructions. Historical repository +audit reports record their own scope and are not additional testing policies. diff --git a/.claude/skills/testing-patterns b/.claude/skills/testing-patterns new file mode 120000 index 0000000..4075fa1 --- /dev/null +++ b/.claude/skills/testing-patterns @@ -0,0 +1 @@ +../../.agents/skills/testing-patterns \ No newline at end of file diff --git a/.gitignore b/.gitignore index 358e668..e3b09c4 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,12 @@ dist info .mcp.json .claude +# Expose only the repository skill; keep local Claude state ignored. +!/.claude/ +/.claude/* +!/.claude/skills/ +/.claude/skills/* +!/.claude/skills/testing-patterns .npmrc .messages/ diff --git a/AGENTS.md b/AGENTS.md index a7a2f8c..5bda8ae 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,12 +2,8 @@ Read [CLAUDE.md](CLAUDE.md) for architecture and commands. -For every test change, apply [Testing standards](docs/testing.md). Tests must -challenge a named, plausible defect using independently established expected -behavior. Keep the behavior owner real, delete redundant or confirmation-only -cases, and validate authentication assertions with focused fault experiments. -Coverage and test counts are evidence, not goals. Do not change runtime behavior -during a test-only audit without separating the discovered bug from test cleanup. +For test authoring, review, pruning or verification decisions, use the shared +[testing-patterns skill](.agents/skills/testing-patterns/SKILL.md). Keep code, documentation and comments in English. Keep implementation modules focused (aim for at most 200 code lines) and test files under 600 code lines; diff --git a/CLAUDE.md b/CLAUDE.md index 813cb65..0f8be07 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -46,7 +46,7 @@ Schema conditionally extends `user` table with `telegramId`, `telegramUsername`, ## Testing -Apply [Testing standards](docs/testing.md) to every added, edited or deleted test. Name the contract and the plausible defect; use independent expected results and remove cases with no unique protection. +For test authoring, review, pruning or verification decisions, use `/testing-patterns` ([shared instructions](.claude/skills/testing-patterns/SKILL.md)). - **Vitest** with `happy-dom` environment; `*.integration.test.ts` run in `node` against a real Better Auth instance (see `src/testing/harness.ts`). Prefer those over mocking Better Auth: mock-only tests passed while OIDC was broken on 1.7. - Tests co-located in `src/` (`*.test.ts`). OIDC integration suites separate sign-in, protocol, identity, profile, claims and linking; Widget, Mini App and mapper suites cover their corresponding flows. diff --git a/docs/testing.md b/docs/testing.md index 82f8416..d29785a 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -1,147 +1,20 @@ # Testing standards -A test earns its place by detecting a plausible violation of a requirement. -Executing code, preserving a test count, and increasing coverage are not goals. -These rules apply to new tests and to reviews of existing tests. - -## Decide what the test proves - -Before changing a test, identify the observable contract, where its expected -result comes from, and a plausible wrong implementation it must reject. A short -test name or comment is enough; do not add a repeated checklist to every case. - -Expected results come from a documented API, a consumer requirement, an incident, -or an independently checked example. They do not come from running today's code. -Do not calculate expectations with the production helper or copy its algorithm. -Cryptographic fixtures need literal independently derived vectors as well as -signed integration fixtures: an encoder and verifier can share the same defect. - -Choose inputs where the correct and incorrect behaviors differ. Examples here: - -- An identity match must return the intended existing user, including when a - different user is also present. A row count of one is insufficient. -- A rejected sign-in must return the expected error and create no session. Check - durable rows when the contract forbids writes; lack of a cookie alone does not - establish that no session was created. -- A returning sign-in must succeed with the right session and profile. Unchanged - database rows alone also pass if the second request did nothing. -- A stale widget's cleanup must not remove its replacement's callback. Invoke the - replacement and observe the result instead of inspecting a callback name alone. -- Time limits need inputs on both sides of the documented boundary. Freeze time - deliberately; do not freeze the property a concurrency or uniqueness test claims - to measure. - -## Keep the behavior owner real - -| Risk | Smallest credible boundary | -| --- | --- | -| HMAC format, ordering, freshness | Direct verifier with independent vectors and boundary inputs | -| User/account ownership, authorization, hooks, cookies | Real Better Auth request and response, with database/session readback | -| SQL constraints, rollback, driver behavior, concurrent servers | Disposable real database through the affected adapter | -| Client session refresh | Real Better Auth client store and controlled HTTP boundary | -| Widget lifecycle | Real DOM operations with controlled external script events | -| Package entrypoints and declarations | Built tarball installed outside the checkout, runtime calls and consumer type checks | - -Mocks are appropriate at the external provider or network boundary. Request -assertions are useful when they enforce Telegram's protocol, not when they merely -repeat an internal call. A fake database cannot prove a transaction; a mocked -session store cannot prove refresh behavior. DOM emulation cannot prove browser -layout, iframe cookie policy or Telegram's live UI. Report those limits. - -## Remove tests that do not discriminate - -Delete a case when its unique contract cannot be established or another test -already protects the same failure. A deletion does not require a replacement. -Keep incident regressions unless their exact protection demonstrably survives -elsewhere. - -Common deletion or rewrite candidates: - -- Calling a function and asserting only `toBeDefined`, truthiness, no throw, or an - unqualified mock call. These assertions can support a stronger test, but rarely - establish the behavior by themselves. -- Returning a value from a mock and expecting the same value without checking any - transformation or external contract. -- Source-text, file-presence, internal object-shape or export-existence assertions - presented as runtime correctness. Genuine packaging and type contracts belong in - the installed-consumer checks. -- Log-count assertions when the actual requirement is recovery or refusal. - Documented startup diagnostics are observable output and can have direct tests. -- Cases that differ only cosmetically, impossible typed states at a trusted - boundary, or fixtures where both branches yield the same expected value. - -Untrusted HTTP and provider data can violate TypeScript types. Malformed inputs -are meaningful at those boundaries. Do not use the type checker as a reason to -remove their validation tests. - -## Challenge the assertions - -For new or rewritten authentication, identity, privacy, or concurrency cases, -check a concrete fault: remove the relevant guard, select the wrong owner, omit -an awaited mapper, or suppress the promised state transition. Run only the test -that claims to catch it, and inspect the failure reason. - -Use a disposable source copy for fault injection when other sessions share the -checkout. Restore every fault before another experiment. A failed import, syntax -error, unselected test or unrelated failure is not evidence that the assertion -caught the defect. A surviving fault requires investigation: the test may be weak, -the change may be behaviorally equivalent, or the expectation may lack a contract. -Do not replace a surviving fault with an easier one just to obtain a green report. - -Targeted fault experiments are evidence, not a mutation-score target or a proof -of all possible correctness. They cannot discover a requirement absent from both -implementation and tests. For a wide input space, use a small boundary table or -properties with reproducible counterexamples when justified; do not install a new -framework merely to generate more cases. - -For an actual bug, first reproduce the contract violation with a focused failing -test. Do not change an expectation to bless incorrect output. During a test-only -audit, report a discovered production bug and its reproducer separately rather -than silently changing runtime behavior or deleting the failing requirement. - -## Isolation and completion - -Await explicit events, promises, or bounded observable outcomes. Do not use sleep -to guess when a callback or concurrent operation has finished. Unexpected network -requests must fail the test instead of reaching the real provider. Restore clocks, -globals, mocks and listeners; close SQLite handles, servers and database pools. -Release test-owned databases and generated fixtures after success or failure. -Never use shared development or production databases for these tests. - -Run the affected files while iterating. On the final tree, run each applicable -[project gate](../CONTRIBUTING.md#ci-and-releases) once. Preserve useful evidence -until the code, fixtures, environment or toolchain it depends on changes. Report -actual passes, intentional skips, the faults detected and boundaries not exercised. - -Coverage is a map for finding unexamined risks. Inspect uncovered lines and -branches, but do not add unreachable scenarios, duplicate tests or exclusions to -improve the number. Keep the existing coverage floors; if removing weak tests -exposes a real gap, address that behavior. A coverage comment is not itself a test -requirement. - -## Sources checked on 2026-11-04 - -- [Vitest: Writing Tests with AI](https://vitest.dev/guide/learn/writing-tests-with-ai) - and [Testing in Practice](https://vitest.dev/guide/learn/testing-in-practice): - review generated assertions and test observable contracts rather than internals. -- [Vitest: Mocking Requests](https://vitest.dev/guide/mocking/requests): fail on - unhandled external requests and reset handlers between tests. -- [Google: Code Coverage Best Practices](https://testing.googleblog.com/2020/08/code-coverage-best-practices.html): - coverage measures execution, and chasing 100% can produce low-value tests. - This is established guidance, not a new 2026 rule. -- [Stryker: Mutant states](https://stryker-mutator.io/docs/mutation-testing-elements/mutant-states-and-metrics/) - and [Equivalent mutants](https://stryker-mutator.io/docs/mutation-testing-elements/equivalent-mutants/): - distinguish detected defects, survivors, invalid mutations and equivalent changes. -- [fast-check: Why property-based testing](https://fast-check.dev/docs/introduction/why-property-based/): - generated inputs are useful when paired with a meaningful property, shrinking - and reproducible failures, not as random-data volume. -- [Hamidi et al., September 2026 preprint](https://arxiv.org/abs/2609.09315): - in its LLM-generated-code benchmark, weak test oracles limited actual fault - detection even when faults were exercised. This is evidence from that study, - not a claim that every project or generated test has the same defect rate. - -The review method also follows the user's established `testing-patterns` -conventions: independent expectations, the real behavior owner, named defects, -and removal of tests without unique protection. - -The [2026-11-04 audit](testing-audit-2026-11-04.md) records the first complete application of these rules to this repository. +The authoritative instructions are the repository-local +[testing-patterns skill](../.agents/skills/testing-patterns/SKILL.md). +[Repository guidance](../.agents/skills/testing-patterns/references/repository.md) +contains verified commands, behavior owners, fixture isolation, cleanup and examples. + +Codex discovers `.agents/skills/testing-patterns/SKILL.md` and accepts +`$testing-patterns`. Claude Code discovers the relative directory symlink at +`.claude/skills/testing-patterns` and accepts `/testing-patterns`. Both use one body; +no plugin, global installation or host-specific frontmatter is required. + +The skill is adapted from the supplied 2026 research, preserving its qualifications: +meaningful contracts and deliberate baselines, proportional failure evidence, +legitimate doubles/structural checks, complementary test levels, and no universal +test or mutation quota. Source identifiers and hashes are in the reference. + +Historical evidence remains in the [test-quality audit](testing-audit-2026-11-04.md) +and [deeper verification report](deeper-verification-2026-11-04.md). These describe +completed work and its limits; they do not require repeating that work for each edit. From dab5cd61e6916aec85edddf695d0904f6fd3edf8 Mon Sep 17 00:00:00 2001 From: vcode-sh Date: Wed, 4 Nov 2026 11:28:52 +0100 Subject: [PATCH 3/6] docs: update testing documentation and add validation references Revised the CONTRIBUTING.md to clarify testing standards and practices, emphasizing the importance of distinguishing requirements from plausible defects. Introduced a new validation.md file to document client discovery and behavioral checks for the testing-patterns skill, enhancing guidance for contributors on effective testing methodologies. This update aims to improve the overall testing framework and ensure comprehensive coverage. --- .../testing-patterns/references/validation.md | 95 +++++++++++++++++++ CONTRIBUTING.md | 2 +- docs/testing.md | 3 + 3 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 .agents/skills/testing-patterns/references/validation.md diff --git a/.agents/skills/testing-patterns/references/validation.md b/.agents/skills/testing-patterns/references/validation.md new file mode 100644 index 0000000..2b16430 --- /dev/null +++ b/.agents/skills/testing-patterns/references/validation.md @@ -0,0 +1,95 @@ +# Skill validation, 2026-11-04 + +This is a record of bounded checks, not an additional testing policy or a claim +about the correctness of the repository's authentication implementation. + +## Discovery and portability + +Installed clients were `codex-cli 0.166.0` and Claude Code `2.1.318` on Linux. +The official [Codex skills documentation](https://learn.chatgpt.com/docs/build-skills) +and [Claude Code skills documentation](https://code.claude.com/docs/en/skills) +describe their respective discovery directories and support directory symlinks. +The shared core has only portable `name` and `description` frontmatter. + +- The installed Codex `app-server` answered `skills/list` with `forceReload: true` + for the repository root and `src/`. Each returned exactly one enabled, + repository-scoped `testing-patterns` at `.agents/skills/testing-patterns/SKILL.md`, + with no discovery errors. The server process was then terminated. +- A Claude Code provider evaluation selected the skill through its native `Skill` + tool: input `{"skill":"testing-patterns"}`, successful command `testing-patterns`. + This exercised actual invocation through `.claude/skills/testing-patterns`. +- The relative directory link is `../../.agents/skills/testing-patterns`. + Both paths resolve to the same instruction body. A disposable Git index and + `git checkout-index` roundtrip preserved mode `120000` and a working relative + link. `AGENTS.md` and `CLAUDE.md` are distinct regular files. + +Codex invocation is `$testing-patterns`; Claude Code invocation is +`/testing-patterns`. No plugin wrapper, MCP server, hooks or global installation +was added. The interactive slash-command menu was not separately exercised. +Checkout portability was checked on Linux, not Windows or macOS. + +## Behavioral checks + +Each client received the same four tasks in its own disposable fixture directory. +The prompts supplied the contract and allowed edits, but not the evaluator's +expected decisions or mutation checks. Agents were directed to use applicable +repository instructions; the four fixture tasks themselves did not name a skill. + +The Codex native subagent read the shared skill and repository reference. The +Claude Code provider used the native skill tool; it did not load the optional +reference because the fixtures explicitly selected Node's built-in test runner. +These are behavioral smoke checks, not a benchmark or exhaustive trigger test. + +| Task | Observable outcome in both clients | +| --- | --- | +| Inclusive freshness threshold, with a mirrored interior-only test | Replaced the computed oracle with literal contract examples, added the exact endpoint and an expired case, observed an assertion failure on the endpoint, then fixed the fixture. | +| Final-seat reservation with a fake SQL transaction | Identified that two mocked writes do not establish one successful reservation; required coordinated independent PostgreSQL transactions and durable readback. Did not provision a database or edit the scenario. | +| Reviewed double-space label golden before an internal refactor | Kept the baseline and test unchanged; distinguished compatibility from ideal formatting. | +| README spelling correction | Corrected the word and added no test. | + +Both clients observed RED with two passing cases and one failed assertion, then +GREEN with three passing cases. The lead independently ran each resulting test, +reintroduced the original `<` instead of `<=` defect, and observed exit 1 with an +`AssertionError`. Restoring the fix and running the freshness and compatibility +tests together gave exit 0. Node was `v26.13.0`. + +Fixture commands actually executed included: + +```sh +node --test regression/freshness.test.mjs +node --test regression/freshness.test.mjs compat/format.test.mjs +``` + +Hash comparisons found only the four allowed fixture outputs changed: freshness +implementation, freshness test, README and result report. The boundary scenario, +golden and compatibility test stayed unchanged. Evaluators made no changes to the +real tracked repository files or the shared skill/reference. + +## Structural checks and local command verification + +- The installed skill-creator `scripts/quick_validate.py` accepted the canonical + directory. Relative Markdown links, code fences, skill name and symlink target + were checked. `git diff --check` passed. +- Commands in [repository guidance](repository.md) were checked against local + package scripts, Vitest configuration, fixtures and CI. This source verification + does not mean the full commands or runtime matrix were executed for this task. +- `vitest list src/verify-hardening.test.ts -t 'auth_date freshness' --json=...` + found two static test templates; parameterized cases were not expanded. +- `vitest list src/client.integration.test.ts -t 'disableSignal' --json=...` + found one static test. +- The adapter selector `rejects account hooks` exists in the source. Both static + and `--staticParse=false` collection with `vitest.adapters.config.ts` returned + zero cases while all three `BAT_TEST_*_URL` variables were explicitly unset. + That is not a passing adapter run or proof of the selected runtime case. + +No repository runtime suite, real adapter, browser acceptance or release matrix was +run for this instruction-only change. Existing CI gates, production code, tests, +dependencies and package scripts were preserved. + +## Cleanup + +Evaluation-owned fixtures, logs and nested checkout/index probes under +`node_modules/.cache/testing-skill-eval-mmuar67i` were removed after recording these +results. No database, container or persistent server was created. Unrelated caches, +services and work were left intact. The evidence above is retained as a summary; +temporary model traces and fixtures are not part of the skill distribution. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 552ac14..85c31f2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -95,7 +95,7 @@ Not guidelines. Not suggestions. Rules. ## Testing -Follow [Testing standards](docs/testing.md). Each test must distinguish a requirement from a plausible defect. Delete cases with no unique protection; do not retain them for a coverage target or test count. +Use [Testing standards](docs/testing.md) to find the shared `testing-patterns` skill and repository guidance for writing, reviewing and pruning tests. - **Verification**: crypto tests in `verify.test.ts` and `verify-hardening.test.ts` -- HMAC paths, replay attacks, future `auth_date`, hash format, edge cases - **Server plugin**: `widget.integration.test.ts`, `miniapp.integration.test.ts` and `widget-mappers.integration.test.ts` cover Widget/Mini App sign-in, account changes and mapping. OIDC suites are grouped by behavior: `oidc.integration.test.ts`, `oidc-protocol.integration.test.ts`, `oidc-identity.integration.test.ts`, `oidc-profile.integration.test.ts`, `oidc-claims.integration.test.ts` and `oidc-linking.integration.test.ts`. `identity.integration.test.ts` and `hooks.integration.test.ts` cover revocation, placeholders and application hooks. These use real `betterAuth()` instances (memory or SQLite) and a fake Telegram modeled on the live one. Prefer them over mocking Better Auth: mock-only tests passed while OIDC was broken on 1.7 diff --git a/docs/testing.md b/docs/testing.md index d29785a..bd59c64 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -10,6 +10,9 @@ Codex discovers `.agents/skills/testing-patterns/SKILL.md` and accepts `.claude/skills/testing-patterns` and accepts `/testing-patterns`. Both use one body; no plugin, global installation or host-specific frontmatter is required. +[Validation evidence](../.agents/skills/testing-patterns/references/validation.md) +records client discovery, representative decisions and the limits of those checks. + The skill is adapted from the supplied 2026 research, preserving its qualifications: meaningful contracts and deliberate baselines, proportional failure evidence, legitimate doubles/structural checks, complementary test levels, and no universal From 0369a444954bd536605a7c52a87e6baeb899344d Mon Sep 17 00:00:00 2001 From: vcode-sh Date: Wed, 4 Nov 2026 11:32:41 +0100 Subject: [PATCH 4/6] chore: prepare 3.2.1 release --- CHANGELOG.md | 20 +++++++++++--------- package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 35d3478..6705b81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,21 +5,23 @@ All notable changes to the better-auth-telegram plugin will be documented in thi The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [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. ### Fixed -- Overlapping widget initializations on the same host now keep the newest requested configuration. A late older response cannot replace the current bot or login callback, and its cleanup handle is harmless. -- OIDC placeholder emails now support valid opaque and long subjects. Existing account keys and ordinary numeric placeholders remain unchanged, and collision variants stay within the email local-part limit. -- OIDC tokens with an empty or non-string subject are rejected before profile mapping or cross-flow linking. An accepted single-client audience array is normalized to the public string type before the mapper runs. -- Mini App data with duplicate parameter names is rejected, so signature verification and parsed output cannot select different copies of a field. Widget and Mini App user IDs must be positive safe integers. -- Widget and Mini App sign-in reject account keys owned by different users instead of selecting the first record. Same-owner legacy duplicates remain supported, including when a conflicting owner appears after the first two rows. -- Returning Telegram sign-ins recheck account ownership after application validation and profile-update hooks. Revocation or reassignment during those steps cannot authorize a new session from stale account data. +- **The latest widget keeps its button and callback.** When two initializations target the same element, an older request finishing late can no longer replace the current bot or handle its login. Disposing that older initialization leaves the current widget alone. +- **OIDC sign-in accepts long or unusual account identifiers.** Subjects that cannot fit in an email address now get a bounded placeholder instead of causing a server error. The original subject remains the account key, existing numeric placeholders stay the same, and signing in after unlinking cannot reconnect through the old placeholder email. +- **OIDC mappers receive the declared claim types.** An accepted audience array containing only this client is normalized to a string before mapping. Empty or non-string subjects are rejected before mapping or account linking. +- **Malformed Telegram input is rejected consistently.** Mini App data with repeated parameter names is refused so verification and parsing cannot use different copies of a field. Widget and Mini App user IDs must be positive integers that JavaScript can represent exactly; valid 52-bit Telegram IDs remain supported. +- **Conflicting account records no longer choose a user arbitrarily.** Widget and Mini App sign-in refuse a Telegram account key stored against different users. Legacy duplicate records belonging to the same user still work. +- **Account changes made by application hooks take effect during login.** Returning Widget and Mini App users cannot get a new session from an account link that validation or profile-update hooks removed or reassigned. Existing sessions are unaffected. ### Tests and maintenance -- Replaced redundant or weak checks with independently derived response, session and durable-state assertions; added real nontransactional adapter checks and installed CommonJS/type-consumer acceptance. -- Documented the testing standards and audit evidence. Test-owned SQLite handles, databases and generated fixtures are released after success or failure. +- Strengthened regression tests around returned identities, session cookies and persisted changes, including adapters where a rejected request does not automatically roll back writes. Installed-package checks now exercise sign-in through both ESM and CommonJS exports. +- Added shared test-quality guidance for Claude Code and Codex, with repository commands and documented verification limits. Test fixtures now release owned SQLite handles, databases and generated files after success or failure. ## [3.2.0] - 2026-11-04 diff --git a/package-lock.json b/package-lock.json index 1ea16ba..69e7420 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "better-auth-telegram", - "version": "3.2.0", + "version": "3.2.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "better-auth-telegram", - "version": "3.2.0", + "version": "3.2.1", "license": "MIT", "dependencies": { "jose": "^6.2.14" diff --git a/package.json b/package.json index 480f13c..fc910f9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "better-auth-telegram", - "version": "3.2.0", + "version": "3.2.1", "description": "Telegram authentication plugin for Better Auth", "keywords": [ "better-auth", From af1161466b52f07d1058f8fd828ea285e6d2a298 Mon Sep 17 00:00:00 2001 From: vcode-sh Date: Wed, 4 Nov 2026 11:39:44 +0100 Subject: [PATCH 5/6] test: cover revocation during account-only profile updates --- docs/deeper-verification-2026-11-04.md | 16 +++++ src/identity-transitions.integration.test.ts | 73 ++++++++++++-------- 2 files changed, 59 insertions(+), 30 deletions(-) diff --git a/docs/deeper-verification-2026-11-04.md b/docs/deeper-verification-2026-11-04.md index 641a311..d2663ba 100644 --- a/docs/deeper-verification-2026-11-04.md +++ b/docs/deeper-verification-2026-11-04.md @@ -78,5 +78,21 @@ these measurements do not justify the extra state or complexity. - Disposable database readback finds no remaining generated databases. Containers and temporary dependency installs are removed after verification. - Largest implementation module: 187 non-comment code lines. Largest test file: 466. +## 3.2.1 release follow-up + +Codecov identified an untested authority check when the user profile is already +current but the Telegram account metadata still needs updating. The profile-hook +regression now covers that state as well as the original stale-profile case, +checking the refusal code, removed account, unchanged stored sessions and absence +of an authenticated cookie. Removing only this authority check in an isolated +copy makes the new case fail with HTTP 200 instead of 401; restoring it passes. +No production change was needed. The temporary copy was removed. + +The updated default suite passes all 337 tests on Node 26.13.0. Coverage is 98.68% +lines, 98.70% statements, 95.78% branches and 100% functions; the affected account +module has 100% line coverage. Scoped lint, package type checks and diff checks +also pass. These results supplement the earlier runtime/adapter matrix; release +CI checks the new test on every required runtime without weakening existing gates. + No test claims that this finite review proves the absence of every possible defect. No release or production deployment is part of this working-tree verification. diff --git a/src/identity-transitions.integration.test.ts b/src/identity-transitions.integration.test.ts index 4e71c82..9f799dd 100644 --- a/src/identity-transitions.integration.test.ts +++ b/src/identity-transitions.integration.test.ts @@ -160,40 +160,53 @@ describe("Telegram identity authority transitions", () => { expect(client.hasSession()).toBe(false); }); - it("does not issue a session after a profile hook revokes the proving account", async () => { - let accountId = ""; - const { client, db } = createMemoryAuth( - {}, - { - databaseHooks: { - account: { - update: { - before: async (_account, ctx) => { - await ctx!.context.internalAdapter.deleteAccount(accountId); + it.each([ + { profile: "outdated", profileAlreadyCurrent: false }, + { profile: "already current", profileAlreadyCurrent: true }, + ])( + "does not issue a session after an account hook revokes its proof while the user profile is $profile", + async ({ profileAlreadyCurrent }) => { + let accountId = ""; + const { auth, client, db } = createMemoryAuth( + {}, + { + databaseHooks: { + account: { + update: { + before: async (_account, ctx) => { + await ctx!.context.internalAdapter.deleteAccount(accountId); + }, }, }, }, - }, + } + ); + const first = await client.post( + "/telegram/signin", + await signWidgetData({ id: 42, username: "before" }) + ); + expect(first.status).toBe(200); + accountId = db.account[0]!.id; + if (profileAlreadyCurrent) { + // Other sign-in methods can refresh the user before this account catches up. + const context = await auth.$context; + await context.internalAdapter.updateUser(first.json.user.id, { + telegramUsername: "after", + }); } - ); - const first = await client.post( - "/telegram/signin", - await signWidgetData({ id: 42, username: "before" }) - ); - expect(first.status).toBe(200); - accountId = db.account[0]!.id; - client.clearCookies(); - const sessionCount = db.session.length; + client.clearCookies(); + const sessions = structuredClone(db.session); - const response = await client.post( - "/telegram/signin", - await signWidgetData({ id: 42, username: "after" }) - ); + const response = await client.post( + "/telegram/signin", + await signWidgetData({ id: 42, username: "after" }) + ); - expect(response.status).toBe(401); - expect(response.json.code).toBe("ACCOUNT_NOT_LINKED"); - expect(db.account).toHaveLength(0); - expect(db.session).toHaveLength(sessionCount); - expect(client.hasSession()).toBe(false); - }); + expect(response.status).toBe(401); + expect(response.json.code).toBe("ACCOUNT_NOT_LINKED"); + expect(db.account).toHaveLength(0); + expect(db.session).toEqual(sessions); + expect(client.hasSession()).toBe(false); + } + ); }); From 2c8f39ef87afd1b7e7fcfcdc7cc9035ca49f4f4f Mon Sep 17 00:00:00 2001 From: vcode-sh Date: Wed, 4 Nov 2026 11:45:29 +0100 Subject: [PATCH 6/6] test: preserve sign-in after a username update veto --- docs/deeper-verification-2026-11-04.md | 12 +++++- src/identity-transitions.integration.test.ts | 44 ++++++++++++++++++++ 2 files changed, 54 insertions(+), 2 deletions(-) diff --git a/docs/deeper-verification-2026-11-04.md b/docs/deeper-verification-2026-11-04.md index d2663ba..630cda5 100644 --- a/docs/deeper-verification-2026-11-04.md +++ b/docs/deeper-verification-2026-11-04.md @@ -88,8 +88,16 @@ of an authenticated cookie. Removing only this authority check in an isolated copy makes the new case fail with HTTP 200 instead of 401; restoring it passes. No production change was needed. The temporary copy was removed. -The updated default suite passes all 337 tests on Node 26.13.0. Coverage is 98.68% -lines, 98.70% statements, 95.78% branches and 100% functions; the affected account +Codecov's processed report also exposed the null-result fallback after a user +update veto, which the local LCOV report did not label as a missed line. A +compatibility case now checks that refusing a username update preserves the saved +profile, returns it in the sign-in response and authenticates through the issued +cookie while the linked account remains valid. Removing the fallback in an +isolated copy causes HTTP 500 instead of 200; restoring it passes. This protects +existing behavior and needs no production change. The probe copy was removed. + +The updated default suite passes all 338 tests on Node 26.13.0. Coverage is 98.68% +lines, 98.70% statements, 95.94% branches and 100% functions; the affected account module has 100% line coverage. Scoped lint, package type checks and diff checks also pass. These results supplement the earlier runtime/adapter matrix; release CI checks the new test on every required runtime without weakening existing gates. diff --git a/src/identity-transitions.integration.test.ts b/src/identity-transitions.integration.test.ts index 9f799dd..fbafe95 100644 --- a/src/identity-transitions.integration.test.ts +++ b/src/identity-transitions.integration.test.ts @@ -7,6 +7,50 @@ import { } from "./testing/harness"; describe("Telegram identity authority transitions", () => { + it("keeps the stored profile and an authenticated session when a username update is vetoed", async () => { + const { client, db } = createMemoryAuth( + {}, + { + session: { cookieCache: { enabled: true } }, + databaseHooks: { user: { update: { before: async () => false } } }, + } + ); + const first = await client.post( + "/telegram/signin", + await signWidgetData({ id: 42, username: "before" }) + ); + expect(first.status).toBe(200); + const storedUser = structuredClone(db.user[0]); + client.clearCookies(); + + const response = await client.post( + "/telegram/signin", + await signWidgetData({ id: 42, username: "after" }) + ); + const session = await client.get("/get-session"); + + // Preserve the existing contract: a metadata veto keeps the stored profile; + // the independently proven account can still authorize this sign-in. + expect(response.status).toBe(200); + expect(response.json.user).toMatchObject({ + id: first.json.user.id, + telegramId: "42", + telegramUsername: "before", + }); + expect(db.user).toEqual([storedUser]); + expect(db.account[0]).toMatchObject({ + userId: first.json.user.id, + telegramUsername: "after", + }); + expect(session.status).toBe(200); + expect(session.json.user).toMatchObject({ + id: first.json.user.id, + telegramId: "42", + telegramUsername: "before", + }); + expect(db.session).toHaveLength(2); + }); + it.each(["Widget", "Mini App"])( "%s refuses a Telegram account key held by different users", async (method) => {