Skip to content
ContractSpec
Start here

Package manual · integrations

·Identity, access and subject context

integration.authos-better-auth

Better Auth bridge that maps AuthOS contracts to provider configuration, plugins, and redacted events.

integrationsintegrationv2.1.4experimentalbrowserreact-nativeservernode
@lssm-tech/integration.authos-better-auth
bun add @lssm-tech/integration.authos-better-auth
Package source ↗Manifest ↗

Manifest declarations describe the current workspace; they do not verify registry publication or runtime execution.

Package guide

Better Auth bridge for AuthOS Broad V0.

The web bridge preserves legacy signIn.oauth2({ providerId }) and oauth2.link({ providerId }) callers through Better Auth 1.7's supported signIn.social/linkSocial endpoints. It no longer imports the removed genericOAuthClient. Provider callback registration/schema migration remains a separate host rollout requirement.

This package turns AuthOS contracts into Better Auth configuration and maps Better Auth-like user/session/events back to AuthOS contracts. Canonical models stay in @lssm-tech/lib.authos-spec; pure projections and security gates stay in @lssm-tech/lib.authos-runtime.

advanced.cookiePrefix passes the host-selected namespace to Better Auth. Preview hosts can combine a distinct prefix with secure cookies and disabled cross-subdomain cookies. This separates cookie names and host scope; data/secret isolation must still be provisioned and verified independently.

Maturity

  • Core email/password, magic link, email OTP, organization/team, admin, OAuth/OIDC client, MFA, and WebAuthn passkeys are runtime-backed through Better Auth (passkeys live-verified on Managed CompanyOS 2026-08-14).
  • The bridge can also wire the phoneNumber and oneTap plugins, but no LSSM deployment enables them or has live-verified them: Managed CompanyOS does not list them in companyOsEnabledPlugins, and the generic authOsV0Fixture marks phone OTP/verification and one-tap fixture-backed. Phone OTP also needs a host sendPhoneOtp delivery callback.
  • Connect with LSSM / LSSM-as-IdP (@better-auth/oauth-provider) stays contract-only for Managed CompanyOS until enableLssmIdp and a security review reference are configured.
  • Built-in social login is typed for Apple, Discord, Facebook, GitHub, Railway, Google, Linear, LinkedIn, Microsoft, Notion, PayPal, Reddit, Slack, TikTok, Twitter/X (twitter), and Vercel. Hosts may retain genericOAuth for additional providers.
  • Generic OIDC hosts can opt into profileNameFallback: "email" for legacy identities without a display name. The bridge reuses the provider email verbatim and never infers a human name.
  • Invite-only hosts set disableSignUp; verified-email providers may resolve an existing verified identity, while TikTok and missing-email LinkedIn/Facebook identities require an explicit authenticated account link.
  • Passkeys use the matching @better-auth/passkey server and browser plugins. Hosts must apply the provider's passkey table migration before enabling enrollment.
  • SSO and SCIM remain declared external plugin capabilities until their production package wiring is separately reviewed.
  • LSSM-as-IdP uses the supported @better-auth/oauth-provider OAuth 2.1/OIDC runtime, with dynamic registration disabled, PKCE/S256 provider defaults, pairwise subject derivation, asymmetric JWT/JWKS support, explicit login/consent routes, and resource audiences. It remains contract-only unless securityReviewRef and a server-only pairwise secret are present and production enablement is explicitly gated.
  • IdP hosts may supply a product-access policy. Without one, post-login always redirects to the configured access boundary. Reviewed hosts can publish explicit product scopes, bind consent to an entitlement reference, and emit only coarse application/tier/entitlement claims after the host confirms active access.
  • Product membership handoffs expose a bounded, bearer-authenticated internal handler. It accepts only an RP-specific pairwise subject and idempotent provisioning scope; canonical identity IDs, local role authority, and secret material are excluded from its contracts and replay evidence.
  • ./relying-party-reconciliation prepares the exact catalog-owned Better Auth OAuth client record for an operator-controlled host reconciliation. It hashes the confidential client secret with the provider's SHA-256/base64url format, keeps dynamic registration disabled, and exposes only a secret-free configuration digest and evidence reference.

Optional central identity plugins

The pinned runtime is Better Auth 1.7.14, with matching OAuth-provider, passkey, SSO, API-key and i18n packages; Agent Auth is pinned independently to 0.6.2. Add i18n, api-key, agent-auth, or multi-session to enabledPlugins to request a plugin. The default plugin list and CompanyOS deployment list do not activate these new capabilities automatically.

  • i18n defaults to EN/FR/ES with NEXT_LOCALE cookie then Accept-Language. Authentication delivery callbacks receive the negotiated locale separately from secret challenge material. Hosts own localized emails and branding.
  • apiKey accepts the official options and requires authorizePluginRequest. Existing CompanyOS cos_pk_ credentials retain their separate verifier.
  • agentAuth requires capability validation, execution and host authorization callbacks. Hosts must qualify durable replay protection and Connect checks before enabling it across server instances. Package installation alone does not qualify delegated or autonomous execution.
  • multiSession requires host authorization so switching a stored session cannot bypass assurance or carry the previous identity's authority.
  • authorizePluginRequest runs before protected official plugin endpoints, including server API calls. disabledPluginPaths closes HTTP paths while retaining guarded server APIs. Hosts must distinguish global operators, organization permissions and user-owned grants.

Apple providers can supply resolveClientSecret for short-lived signed client assertions. Central hosts use allowMissingEmail: false and accountLinking.disableImplicitLinking: true; a missing email must be completed through verified registration rather than a fabricated address. Existing product fallbacks remain available for compatibility.

enforcePasswordlessMfa: true extends enrolled TOTP enforcement to email OTP, magic links, passkey authentication and multi-session activation/removal. Supply twoFactorChallengePage on the same host as the post-login continuation. These options require actual host routes, database models and consumer qualification.

Referral and affiliate handoff

attribution configuration composes with an existing Better Auth databaseHooks.user.create.after hook. When a host resolves a valid signed acquisition token, the bridge calls onIdentityCreated after email/password or OAuth identity creation. The callback receives the opaque token and classified flow; the bridge does not persist, decode, or emit the token.

Native bearer sessions

./native-session-client exposes a storage-port-driven Better Auth client for Expo, Tauri, and other trusted native shells. Email/password and TOTP flows capture set-auth-token and the bounded set-mfa-authority projection, while the host-supplied vault keeps both values device-only. Credentials are sent only in JSON request bodies to the configured AuthOS origin and never enter URLs, logs, events, or replay evidence.

Entry points: server and client

  • ./server is the server-only surface: createBetterAuthInstance, buildBetterAuthOptions, database hooks, OAuth provider discovery, resource-token policy and the development registration helpers. Its source file uses the .server.ts suffix, so the package boundary check fails any client ('use client' / .client.ts) graph that reaches it.
  • ./client (createAuthClient, createBetterAuthBridgeClient) and ./native-session-client are the browser and native clients; ./bridge-plan and ./edge-cookie are pure and safe in any runtime.
  • The root entry stays a compatibility barrel that re-exports ./server plus both clients. Server hosts may keep importing it; client code must use the explicit client entries.

Verification

bash
bun run lint:check
bun run typecheck
bun run test
bun run build

Schema check rehearsal

./server exports two read-only helpers for operator rehearsals. runBetterAuthSchemaCheck(await auth.$context) returns clean, unregistered (an adapter wrapper dropped the check) or mismatch with Better Auth's findings. With the Drizzle adapter that check compares only the Drizzle schema object, never the database, so findBetterAuthStoreSchemaProblems(options, tables) runs Better Auth's own diff against tables introspected from the live store (in the adapter's logical names). The CompanyOS API uses both in scripts/better-auth-schema-rehearsal.ts.

Pure bridge-plan inspection

Use @lssm-tech/integration.authos-better-auth/bridge-plan for browser/native inspection of provider plugin plans. It retains buildBetterAuthBridgePlan behavior without importing Better Auth server initialization, database adapters or Next.js cookie integration. The existing root/config exports remain compatible for server consumers. Native preview imports must use this pure entry point; a build-boundary test guards against server code re-entering the graph.

Better Auth 1.7 client compatibility

The shared bridge no longer imports the removed genericOAuthClient plugin. Existing signIn.oauth2({ providerId, ...options }) and oauth2.link({ providerId, ...options }) bridge calls are retained as adapters to Better Auth's supported signIn.social and linkSocial methods. They translate providerId to provider, preserve request options and return provider errors. Other dynamic client methods retain their original behavior.

This client repair does not migrate provider registrations, callback forwarding routes, native clients built directly on Better Auth, or account identity data. Review those separately using the Better Auth 1.7 upgrade guide before qualifying live OAuth. No production identity records were changed.

Server-side bearer session reads

createBetterAuthBearerSessionReader resolves a bearer through the configured AuthOS /api/auth/get-session?disableCookieCache=true endpoint and maps it to the canonical AuthOsSession. It requires HTTPS except loopback development, forbids redirects, bounds time/body size, and rejects expired, banned or mismatched user sessions. Tokens, email and role strings are not returned. This is authentication only: callers must separately resolve current tenant-scoped permissions and must not infer fleet-management access from the identity or provider role.

Verified social registration and assurance

centralIdentityAuthOsSpec, centralIdentityAuthOsCapabilities and centralIdentityEnabledPlugins describe the central LSSM ID implementation independently of CompanyOS. createCentralIdentityAuthOsSpec projects the actual host signup-admission flag. All sixteen native providers support proven-subject resolution and verified registration; deployment credentials, approvals and real OAuth canaries determine which providers can be advertised. runtime-backed describes local implementation, never production qualification. The declaration contains no users, sessions, product access or production approval. Central SMS and product SSO provisioning remain disabled; CompanyOS declarations are unchanged.

Native PayPal references accept environment: 'live' | 'sandbox' and default to live, with openid profile email login scopes unless the host supplies its reviewed scope list. Sandbox must be selected explicitly. These scopes provide identity, name and email attributes according to PayPal's scope reference. The pinned SDK ignores its PayPal scope option, so the bridge uses the supported authorization-endpoint override with that same host-owned scope query. The native SDK still constructs state, PKCE and the callback and performs the token exchange. Live Log in with PayPal still requires PayPal app review; the native configuration and a successful authorization start do not prove approval.

Central hosts can supply missingEmailRegistration to capture a native provider's proven subject after Better Auth consumes browser-bound OAuth state and verifies the code, PKCE and profile. The host persists a token-free pending registration and verifies the person's local email. Existing linked subjects resolve only through the exact provider/account owner; this never merges users by email or creates placeholder addresses. Explicit links with missing, unverified or different provider email use the same host proof boundary.

requireSocialEmailVerification: true separately requires a verified email for native social sign-in. Better Auth sends the host's verification email when a provider returns an unverified address and withholds the session until it is verified. Credential requireEmailVerification does not enable this OAuth policy. Existing hosts retain their previous behavior when the social option is omitted; central hosts also set allowMissingEmail: false and disable implicit account linking.

Native OAuth client and resource management is denied by default, including client creation, metadata updates, deletion, credential rotation and resource links. The host's reviewed application registry owns these operations. Disabling dynamic registration alone does not close the SDK's other management routes. An admitted resource-token policy retains its explicit client/resource privilege callbacks and native management behavior.

Hosts can supply Better Auth's logger option to route authentication diagnostics through their structured logger. The host must redact provider errors and database parameters before logging; these can contain personal data or credential hashes. The optional onAPIError setting also passes through, allowing a host to rethrow unexpected SDK failures into its redacting HTTP boundary.

advanced.backgroundTasks.handler passes through to the SDK so a host can track background writes in a request-scoped authority fence and drain them before its lock is released. Omitting the handler retains the SDK's background-task behavior.

twoFactor passes the official plugin options through. Central hosts can opt into allowPasswordless: true for OTP, magic-link and social identities. They must guard initial enrollment with fresh verified primary-session proof and protect disable and reenrollment with fresh completed MFA; the option itself grants no host authority. Accounts with a credential password still prove their real password.

guardCredentialManagement: true routes native MFA, passkey registration/removal, social account linking/unlinking and password management through authorizePluginRequest as credential-management before SDK effects. It also guards the pathless server-only setPassword and viewBackupCodes operations. Challenge verification, authentication and email reset flows keep their ordinary proof handling. This opt-in requires a host callback; product defaults are unchanged. The same classification covers /get-access-token and /refresh-token. Central hosts deny these exports even for the account owner, so login-provider tokens cannot substitute for separately consented platform connections. SDK-internal login refresh and the connection broker retain their own lifecycle paths.

Generic OIDC references with an expected issuer are bound to that exact issuer after discovery and every retry. requireIssuerValidation requires the callback issuer; requireIdTokenVerification also requires the signed ID token and its state-bound nonce before userinfo is trusted. Strict confidential web consumers complete the state/PKCE flow and cannot substitute browser-submitted ID tokens or fall back to access-token-only userinfo. Cryptographic checks remain SDK-owned. For these strict references, userinfo's raw sub must match the cryptographically verified token subject exactly. Strict account keys use that subject even when discovery omits the native SDK's OIDC-detection hint. Verified subjects are invocation-local, and host claim-policy callbacks remain effective without being allowed to replace the captured signed subject.

Native Apple is verified before pending registration: the SDK-generated nonce is sent to Apple and checked with the official signature/issuer/audience verifier. When a host supplies resolveClientSecret, every token exchange and refresh gets a newly resolved assertion; the SDK's startup options cache cannot strand a warm process with an expired short-lived Apple assertion.

Native Linear uses the SDK's authorization and token helpers with its original state-bound verifier in both directions. This repairs the pinned native provider's missing PKCE parameters while keeping its profile, immutable subject and refresh behavior. The compatibility wrapper runs before verified pending registration.

Central hosts set enforceSocialAuthorizationCodeFlow: true to reject requested scope additions and direct ID-token inputs at native login/link endpoints, including server API calls. Empty or omitted scopes keep the ordinary SDK code flow and host-reviewed provider defaults. Other hosts keep their existing policy when this opt-in is omitted; delegated platform scopes belong to the connection broker. With minimalSocialLoginScopes: true, native Google login also sends no include_granted_scopes, so earlier incremental grants for that client are never folded into the login token. Google requests openid email profile with S256 PKCE; LinkedIn (Sign In with LinkedIn using OpenID Connect) requests openid profile email, reads https://api.linkedin.com/v2/userinfo and relies on the confidential client secret plus browser-bound state, as the pinned SDK sends no PKCE challenge to LinkedIn.

POST /api/auth/authos/registration/complete consumes the host's verified proof and invokes the official OAuth provisioning helper inside one adapter transaction. The host's complete callback must use getCurrentAdapter for its pending-row compare-and-set and return selectedIdentityId only after fresh browser/session proof. Production refuses adapters without real transaction support. Cookies are written after commit, and enrolled MFA still challenges before sign-in.

autoSignInAfterVerification is opt-in and its verification session also passes the passwordless MFA gate. onSessionAssuranceVerified receives only final successful TOTP, recovery-code or passkey sessions. Hosts can persist this proof for account switching. Authenticated TOTP and recovery step-up refresh proof for the exact current session, after matching the official verifier's returned token and user. Failed factors never refresh it. agentAssertionStorage supplies the Agent Auth plugin's replay cache without moving browser sessions into secondary storage. Host plugin authority runs after official assertion verification and before execution.

Proposed reviewed development resource authority

Both development registration recipes require the same canonical reviewed-profile verifier as the optional resource-token factory. Missing/non-function verification or any result other than literal true rejects before store, provider, resource-link or secret-manager calls. Actual canonical registry, admin/lifecycle serialization and resumable cleanup adapters remain required and unqualified.

PROPOSED_NOT_ADMITTED private development resource authority: optional canonical AuthOS resource JWT/workload profiles; exact <=300-second TTL and registered resource/claim validation; durable scoped OSINT receipts preserve SAME active decisionRef and terminal expiry/revocation. Existing defaults and production RP catalog remain unchanged. Real adoption, security review, TLS/registration, canonical lifecycle/obligation/evidence adapters, migration admission and runtime qualification are required before enablement. Product entitlement is not an OSINT effect grant. No issuer, key, token, grant or database has been created or verified by this source preparation.

The proposed development composition adds a current canonical reviewed-profile registry verifier and serialized workload registration journal recipe. The recipe resumes persisted safe phases, verifies actual native client/resource configuration and quarantines orphan clients. It requires a genuine privileged provider/store adapter, secret manager, serialized durable journal and atomic canonical registration completion. These source helpers do not approve a security review, create trust or enable the issuer. Adoption and runtime admission remain required.

Pure binding checks for host adapters ship through ./server (and the root barrel), still PROPOSED_NOT_ADMITTED and side-effect free: assertNativeAccessTokenClaimsBindingV1/nativeIssuanceNotBeforeV1 (single lane resource, scope subset, unchanged identity, exact workload metadata, one safe DB clock row); the dev-registration-binding checks behind SerializedDevRegistrationAdminV1 (client_credentials-only creation, resource and lookup binding, the 4096-client inventory bound, exact native client and current reviewed resource/link); and admitApprovedDevSecurityReviewV1 with the database-system and installer-window assertions (canonical JSON that rejects rather than omits non-JSON content, approved SHA-256 and profile digest binding). Hosts keep the SQL, locks, roles and DB clock reads.

The app custody adapter can complete a fresh registration after checking immutable GCP-version bytes against the genuine one-time native client secret. Persisted resume currently quarantines: a nonempty version alone cannot prove the native credential still matches. A genuine provider verification context is required before enabling recovery. Native policy/key callbacks commit their read transactions before issuance completes, so actual issuance/revocation concurrency remains an explicit qualification requirement.

Proposed local disposable custody

Local disposable custody successor: an additive V2 whole-review arm admits only the genuine Windows DPAPI CurrentUser provider, exact owner SID/owner-only ACL, local namespace/root and immutable pairwise/issuer ciphertext digests. V1 review syntax and generic SecretProvider interface remain unchanged. Only explicit local-disposable host composition admits the factory-branded provider; native signing, reserved claims, canonical SQL locks/policies and revocation remain. This source proposal is unapproved and unqualified. Source/runtime/security admission, actual DB/TLS/native key installation and mandatory real issuance, revocation/custody/cleanup acceptance remain required. No cloud backend is impersonated, production admission introduced, keys generated or review installed.

Exact issuer login witness (opt in)

After applying the native RP store's private session-column migration, strict OIDC hosts may set requireIssuerSessionWitness: true on their existing verified provider reference. The SDK's signature, exact issuer, client audience, expiry and state-bound nonce verification must yield a nonempty signed sid. The existing callback then writes token-free metadata on the native RP session before issuing its cookie. Missing SID refuses that sign-in. Existing sessions have no witness and must sign in again; account tokens are never backfilled. The native issuer client prepared by prepareBetterAuthRelyingPartyClient enables end-session support, which makes the pinned OAuth provider emit sid.

readBetterAuthIssuerSessionWitness from ./server accepts native adapter session/account rows and the expected provider/issuer/client/RP session/identity. Read those rows within the host's current authority fence. The witness retains the original login's issuer SID across later logins of the same account. It is private (input: false, returned: false) and is absent from public session responses and cache cookies: both plugin schema and native session.additionalFields apply the private output filter. Deleting the native session removes its witness. Unlinked or replaced accounts refuse. The reader grants no access: separately recheck the exact live issuer session, reciprocal pairwise link and current product entitlement before releasing a private response. Never use a later account access token as the original session's issuer witness.

Native RP session store migration (owner: this package)

This package owns the native RP session/account custody that createAuthOsResourceRelyingParty creates, so it also owns the private column's forward SQL: migrations/0002_authos_rp_session_issuer_witness.sql in the authos-better-auth migration series (allocated by the integrator; the series is registered in scripts/delivery/migration-registry). The file targets each product host's existing native Better Auth RP database (never the central identity database), resolves session in the connection's current schema like the native adapter, adds a nullable text column without default or backfill, and refuses an existing column of another type, nullability or default. A store generated fresh from the RP's own options by Better Auth's native migration already includes the column; the SQL is idempotent there. Applying it is owner-operated: no host auto-migrates, and this package ships no loader. Sessions created before it keep a NULL witness and refuse until a fresh sign-in. Roll back the host first; dropping the column afterwards refuses every RP session.

For read-only HOME resolution, set native session.deferSessionRefresh: true and read with disableCookieCache: true and disableRefresh: true. The former also prevents GET from deleting an expired stored session; the two query flags alone do not. The host keeps Set-Cookie output out of the HOME response and must not call get-access-token/refresh-token, provision entitlement, or persist consent. These source capabilities do not authorize a native store, host rollout or production activation.

createAuthOsRpRequestAuthority from ./server composes the request-local server ports a career host hands to the existing P-01n processor binding: principal.readCurrentPrincipal() and admissions.resolveCurrentAdmission() / verify(). Both re-read readAuthOsRpRequestIdentity for the original cookie on every call, use only that witness's raw pairwise subject and user credential, and return an admission only if the same RP session, issuer SID, account and raw subject are still current afterwards. They carry identity and admission evidence only; consent and candidate scope stay with P-01n.

Native resource relying-party schema

migrations/0001_resource_relying_party_native_schema.sql (series authos-better-auth, number 0001 allocated by the integrator) is the operator-applied native schema behind createAuthOsResourceRelyingParty: Better Auth's core user, session, account and verification tables with their default field names, plus the private nullable session.authos_issuer_session_witness column. It is brand-neutral, targets one dedicated host-local RP database (first consumer: tafio-web), carries a paired .down.sql usable only before sign-ins are served, and is never applied by a host at runtime. The .down.sql refuses to drop anything when public.oauth_client exists (the central identity database) or when public.session holds a row. A store that Better Auth's own native migration already created records 0001 as its baseline and applies only 0002. The api-application-monolith PGlite test proves Better Auth reports no pending table, column or index once it is applied.

Relationships

THIS PACKAGEintegration.authos-better-auth29 import paths

Arrows point from a package to its direct dependency. Counts are derived from captured workspace manifests.

10 declarations

  • @better-auth/core

    1.7.14

  • @better-auth/agent-auth

    0.6.2

  • @better-auth/api-key

    1.7.14

  • @better-auth/i18n

    1.7.14

  • @better-auth/oauth-provider

    1.7.14

  • @better-auth/passkey

    1.7.14

Declared capabilities

Integration Authos Better Auth

Better Auth bridge that maps AuthOS contracts to provider configuration, plugins, and redacted events.

Scripts

  • publish:pkgbun publish --tolerate-republish --ignore-scripts --verbose
  • publish:pkg:canarybun publish:pkg --tag canary
  • buildcontractspec-bun-build build
  • build:bundlecontractspec-bun-build transpile
  • build:typescontractspec-bun-build types
  • devcontractspec-bun-build dev
  • cleanrimraf dist .turbo
  • lintbun lint:fix
  • lint:fixnode ../../../scripts/biome.cjs check --write .
  • lint:checknode ../../../scripts/biome.cjs check .
  • testbun test
  • prebuildcontractspec-bun-build prebuild
  • typechecktsgo --noEmit