agentleFS
yultyyevyultyyev/better-auth-firestore/AGENTS.md

better-auth-firestore

AGENTS.md10 starsChanged 3 months agoMITView on GitHub

This document provides additional context for AI assistants working on this project. Please read README.md first for project overview and features. All phases are complete. The adapter is production-ready and actively maintained. Phase 1: Core Adapter ✅ Complete Phase 2: Collection naming strategies ✅ Complete Phase 3: Composite index tooling ✅ Complete (generateIndexSetupUrl) Phase 4: Emulator support ✅ Complete Phase 5: Tests (Vitest + Firestore Emulator) ✅ Complete Phase 6: CI/CD and Example Project ✅ Complete Phase 7: Migration from…

  • Installs packages
  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.

    Of the AGENTS.md files we read, the 35,266 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repository3 other files it gives its agents.

The file

We split this AGENTS.md into the rules it gives an agent

3 rules. About 0 are common, 3 are distinctive, and 0 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    All phases are complete. The adapter is production-ready and actively maintained.

    line 14
  2. Distinctive:

    No classes — follow Better Auth's functional plugin conventions

    line 110
  3. Distinctive:

    Keep functions small and focused

    line 111

≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

AI Assistant Guidelines

This document provides additional context for AI assistants working on this project. Please read README.md first for project overview and features.

Quick Reference

  • Package name: better-auth-firestore
  • Main Documentation: See README.md
  • Contributing Guidelines: See CONTRIBUTING.md
  • Adapter Guide: See Better Auth Adapter Guide

Current Project State

All phases are complete. The adapter is production-ready and actively maintained.

Phase 1: Core Adapter ✅ Complete
Phase 2: Collection naming strategies ✅ Complete
Phase 3: Composite index tooling ✅ Complete (generateIndexSetupUrl)
Phase 4: Emulator support ✅ Complete
Phase 5: Tests (Vitest + Firestore Emulator) ✅ Complete
Phase 6: CI/CD and Example Project ✅ Complete
Phase 7: Migration from scoped package ✅ Complete

Project Structure

src/
  firebase-adapter.ts    # Core Firestore adapter implementation
  firestore.ts           # initFirestore helper and Firestore utilities
  setup.ts               # generateIndexSetupUrl helper
  types.ts               # TypeScript types for adapter options
  index.ts               # Public exports
tests/
  *.test.ts              # Vitest integration tests (run against Firestore Emulator)
examples/
  minimal/               # Minimal Next.js App Router example
scripts/                 # Build/release scripts

Key Exports

import {
  firestoreAdapter,         // Main adapter factory
  initFirestore,            // Helper to initialize Firebase Admin + Firestore
  generateIndexSetupUrl,    // Generate Firebase Console URL for index creation
  backfillAccountIssuers,   // One-off data migration for Better Auth 1.7 (account.issuer)
} from "better-auth-firestore";

Adapter Options

firestoreAdapter({
  firestore?: Firestore;          // Firebase Admin Firestore instance (default: getFirestore())
  namingStrategy?: "default" | "snake_case";  // Collection naming convention
  collections?: {
    users?: string;
    sessions?: string;
    accounts?: string;
    verificationTokens?: string;
  };
  debugLogs?: boolean | DBAdapterDebugLogOption;
  migrationChecks?: boolean;      // default true: warn once at startup if account docs lack `issuer` (Better Auth 1.7)
});

CLI

npx better-auth-firestore backfill-account-issuers [--apply] (src/cli.ts, bin/better-auth-firestore.js) is the one-command form of the Better Auth 1.7 account-issuer migration: dry run by default, --apply to write, --collection / --naming-strategy / --issuer provider=url / --service-account / --json; exit 1 on collisions or unresolved documents, 2 on usage errors. Credentials resolve like initFirestore() (service account file, FIREBASE_* env trio, ADC, emulator). It is the answer to "existing users can't sign in after upgrading to 1.7.0–1.7.2" — the startup check logs the exact command.

Firestore Index (Optional)

No composite index is required. Every method, plain and transactional, reads through readMatches in src/firebase-adapter.ts: per OR group, Firestore gets only the equality filters (or, when there are none, the range filters on a single field) — exactly what its automatic single-field indexes serve — and every other condition is checked in memory. findMany with both a filter and a sortBy sorts in memory. So the verification-token lookup (identifier == ordered by createdAt desc), the 1.7.22 consume cleanup (identifier ==, id !=, createdAt <=), session lists (userId ==, expiresAt >) and the rate limiter's incrementOne guards all work without a composite index; tests/null-and-id-conditions.test.ts records the filters each one sends.

Older versions required composite indexes — on the verification collection (identifier ASC, createdAt DESC, __name__ DESC; < v1.1) and on rateLimit (< v1.3). If a user reports 9 FAILED_PRECONDITION: The query requires an index (often surfaced by Better Auth as Failed to parse state), the fix is to upgrade — not to create the index.

Better Auth 1.7 Compatibility

  • 1.7 made incrementOne and consumeOne required on custom adapters and removed the transaction(findMany + updateMany) fallback. Both are implemented natively in src/firebase-adapter.ts — on the plain adapter and on the transaction adapter (runWithTransaction hands whatever our transaction() passes to its callback to plugins as the current adapter). Adding them is additive: 1.6 prefers a native implementation when present, so one codebase supports 1.6 and 1.7. CI runs the suite against both.
  • 1.7.0–1.7.2 identify accounts by (issuer, accountId); account.issuer is required there. 1.7.3 went back to (providerId, accountId), so it needs no backfill; the startup check and the issuer tests read getAuthTables({}).account.fields.issuer rather than the version, so they switch off on their own. Firestore has no auth migrate, so backfillAccountIssuers (src/backfill-account-issuers.ts, exposed as the CLI above) stamps existing documents. Rules mirror @better-auth/core: credential → local:credential (with accountId = userId), siwe → local:siwe, google/apple/facebook/line → the fixed real issuer their provider factory declares, and every provider that declares none → local:oauth:<encodeURIComponent(providerId)>. Providers whose real issuer depends on configuration or on the token (cognito, paybin, microsoft, and the fixed-id generic-OAuth helpers okta, auth0, keycloak, microsoft-entra-id) are left unresolved rather than guessed — supply them via issuers / resolveIssuer / --issuer. Do not "simplify" this back to a blanket local:oauth:<providerId>: that was the v1.3.0 bug, and it silently locked out every Google user until sign-in failed in production. Documents that v1.3.0 already mis-stamped are detected and repaired (legacyIssuersRepaired) even without overwrite, since 1.7 itself never writes that pairing. warnIfAccountsLackIssuer in src/firebase-adapter.ts runs once per process when the adapter is bound to a betterAuth() instance whose schema has issuer (two count() aggregations; orderBy(issuer) excludes documents missing the field) and warns with the exact command.
  • create is an INSERT, never an upsert: both the plain and the transaction adapter write new documents with create() (a create staged over a delete of the same ref in one transaction is the one set()), so a second create with the same id fails the way it does in SQL and MongoDB. better-auth's first-writer-wins reservations (reserveVerificationValue — SAML assertion and DPoP proof replay protection, the SIWE email claim, the 1.7 unverified-account cleanup lock) depend on that failure. Firestore has no unique constraints; the one better-auth relies on, rateLimit.key, is restored by keying that model's documents by a SHA-256 of the key (uniqueKeyDocId), so a burst of concurrent first requests cannot create one row — and one budget — per request. tests/create-uniqueness.test.ts pins both.
  • Where clauses mean the same thing in every method (readMatches → planGroup per OR group → matchesCondition for the in-memory part), inside and outside transactions; the first clause's connector is ignored. Two Firestore facts drive the design:

    • Document IDs are metadata, not fields: where("id", …) matches nothing. An id eq/in reads those documents by ref; every other id condition (ne, not_in, ranges) is compared with the document id in memory. better-auth pairs id with other clauses (consumeOne on a device code, findTeamById with organizationId, findMany with id in […] plus a range), and 1.7.22's consumeVerificationValue deletes [identifier ==, id != latest.id, createdAt <= latest.createdAt] inside its transaction.
    • The adapter never writes undefined, so an optional field nobody set is missing, and Firestore's == null only matches a stored null. Null therefore follows SQL and is evaluated in memory: eq null (IS NULL) matches a missing or null field, ne null (IS NOT NULL) only a value, and every other comparison with a missing or null field is false. 1.7.22 depends on it: oauth-provider's findConsent (referenceId == null), refresh-token rotation (incrementOne guarded by revoked == null), device-code approval (userId == null), invalidateRefreshFamily (refreshId != null).

    tests/where-id-clauses.test.ts and tests/null-and-id-conditions.test.ts pin this.

  • SecondaryStorage.getAndDelete / increment are required in 1.7; the test helper tests/helpers/firestore-secondary-storage.ts implements both (and encodes keys — better-auth keys contain /, which Firestore reads as a path separator).
  • The transaction adapter is factory-wrapped, like the official MongoDB adapter: transaction() builds a per-transaction CustomAdapter (createTransactionAdapter) and passes it through createAdapterFactory({ ...config, transaction: false })(options) before handing it to the callback, so it receives the same mapped modelName/fieldNames, cleaned where clauses and transformed data (generated ids, createdAt/updatedAt, emailVerified defaults) as the plain adapter. better-auth calls the current adapter with schema model keys and raw data, so an unwrapped adapter silently targets the wrong collection as soon as a modelName is customized — tests/transaction-model-name.test.ts pins this. A custom modelName names the Firestore collection directly and takes precedence over the collections option, inside and outside transactions.

Helper (optional, for advanced/direct-query setups only): generateIndexSetupUrl(projectId, databaseId?, collectionName?) and getIndexConfig(collectionName?). Both default collectionName to verificationTokens (use verification_tokens for snake_case).

Important Constraints

  • Edge Runtime not supported — Firebase Admin SDK requires Node.js. If a route sets export const runtime = 'edge', the Admin SDK will not load. Standard Vercel deployments (Node.js serverless runtime) work fine.
  • FIREBASE_PRIVATE_KEY newlines — Environment variables often store the key with literal \n strings. Users must call .replace(/\\n/g, "\n").
  • Emulator support — Set FIRESTORE_EMULATOR_HOST=localhost:8080; the Admin SDK automatically routes requests there. No credentials needed. The emulator does not enforce composite indexes, so index requirements only surface against real Firestore.

Sister Package

better-auth-firebase-auth (GitHub) is the companion Firebase Authentication plugin. It handles Phone OTP, Google Sign-In, and Email/Password via Firebase. The two packages are designed to be used together:

  • better-auth-firestore — database storage layer
  • better-auth-firebase-auth — authentication/identity layer

Code Style

  • BiomeJS for formatting (tab indentation)
  • TypeScript strict mode
  • No classes — follow Better Auth's functional plugin conventions
  • Keep functions small and focused

Build Commands

pnpm install       # Install dependencies
pnpm build         # Build the project (outputs to dist/)
pnpm typecheck     # Typecheck src + tests without emitting
pnpm test          # Run tests (requires FIRESTORE_EMULATOR_HOST)
pnpm verify:pack   # Pack the tarball and import/type-check it from a scratch consumer (after pnpm build)
pnpm lint          # Check for linting issues
pnpm lint:fix      # Fix auto-fixable linting issues

The build emits ESM only; main and both exports["."] conditions (import, require) point at ./dist/index.js, and require() works through Node's require(esm) (>= 22.12). Never point main or require at a .cjs file — the build does not produce one, and that exact mistake shipped in every release up to 1.2.9. pnpm verify:pack is what catches it.

Test Setup

Tests use Vitest and run against the Firestore Emulator:

docker run -d --rm -p 8080:8080 google/cloud-sdk:emulators \
  gcloud beta emulators firestore start --host-port=0.0.0.0:8080

FIRESTORE_EMULATOR_HOST=localhost:8080 pnpm vitest run

CI runs three things on every PR: the lint/build/test job as a matrix against the lockfile's Better Auth (1.7) and the latest 1.6 (pnpm add -D better-auth@1.6), each ending with pnpm verify:pack; and a types job that typechecks and builds under TypeScript 5, 6 and 7. Keep all of them green — the adapter promises to work with every combination.

tests/conformance.test.ts runs Better Auth's own adapter conformance suite (@better-auth/test-utils/adapter) in a separate emulator project. Keep @better-auth/test-utils on the same version as the better-auth devDependency; the file skips itself on the 1.6 job. Only findMany - should select fields is disabled, because findMany ignores select.

Commit Messages

Follow Conventional Commits:

  • feat(adapter): description — New features
  • fix(adapter): description — Bug fixes
  • docs: description — Documentation changes
  • chore: description — Build/tooling changes
  • test: description — Test changes

References

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.