Skip to content

Refactor: Separate authentication configuration from identity data models#55

Merged
hotlong merged 6 commits intomainfrom
copilot/refactor-authentication-architecture
Jan 21, 2026
Merged

Refactor: Separate authentication configuration from identity data models#55
hotlong merged 6 commits intomainfrom
copilot/refactor-authentication-architecture

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Jan 21, 2026

Resolves architectural confusion between authentication providers/strategies (configuration) and user identity models (runtime data).

Changes

Migrated enterprise auth to auth.zod.ts

  • Moved OIDCConfigSchema, SAMLConfigSchema, LDAPConfigSchema from identity.zod.ts
  • Added enterprise field to AuthConfigSchema:
    enterprise: {
      oidc?: { issuer, clientId, clientSecret, ... },
      saml?: { entryPoint, cert, issuer, ... },
      ldap?: { url, bindDn, searchBase, ... }
    }

Redefined identity.zod.ts as data models

Removed authentication configuration schemas. Replaced with runtime data models:

  • UserSchema: Core identity (id, email, emailVerified, name, image, timestamps) - minimal and identity-focused
  • AccountSchema: Links external OAuth/OIDC/SAML providers to users
  • SessionSchema: Session state with device fingerprinting
  • VerificationTokenSchema: Email verification and password reset tokens

Created auth-protocol.ts

Wire protocol constants and interfaces:

  • AUTH_CONSTANTS: Standard headers, prefixes, cookies (Authorization, Bearer , os_*)
  • AuthHeaders, AuthResponse, AuthError, TokenPayload interfaces
  • AUTH_ERROR_CODES: Standard error codes

Added database field mapping for driver compatibility

  • Created DatabaseMappingSchema to map ObjectStack standard field names (Auth.js conventions) to driver-specific field names
  • Added mapping field to AuthConfigSchema with pre-configured better-auth defaults
  • Exported BETTER_AUTH_FIELD_MAPPINGS constant for maintainability
  • Default mappings bridge the gap between ObjectStack and better-auth:
    • sessionTokentoken
    • expiresexpiresAt
    • providerAccountIdaccountId
    • providerproviderId
  • Fully customizable for any authentication driver (Auth.js, Passport, custom implementations)

Updated exports and documentation

  • Added enterprise SSO examples to AUTHENTICATION_STANDARD.md
  • Added database field mapping configuration section with examples
  • Updated index exports to reflect new 3-file structure

Architecture

Before: identity.zod.ts (mixed concerns)
├── AuthProviderSchema (config + data)
├── OIDC/SAML/LDAP configs
└── [no user data models]

After: Clean separation
├── auth.zod.ts → Configuration (how to login + field mappings)
├── identity.zod.ts → Data models (who is logged in)  
└── auth-protocol.ts → Wire protocol (how to communicate)

Driver Agnostic Design

The spec now supports any authentication driver through field mapping:

  • Default mappings for better-auth compatibility (via BETTER_AUTH_FIELD_MAPPINGS)
  • Customizable mappings for other drivers
  • Clean separation between spec fields (Auth.js conventions) and driver-specific fields

Breaking Changes

AuthProvider schema removed. Consumers should use:

  • AuthConfig with optional enterprise and mapping fields for configuration
  • User, Account, Session schemas for runtime data
  • AUTH_CONSTANTS for protocol constants
Original prompt

This section details on the original issue you should resolve

<issue_title>Please perform a final refactoring on PR #46 to consolidate the Authentication Architecture and resolve conflicts with the existing identity.zod.ts.</issue_title>
<issue_description>The goal is to strictly separate "Authentication" (Providers/Strategies) from "Identity" (User Models).

Task 1: Migrate Authentication Providers (Resolve Conflicts)

Migrate the legacy Enterprise Auth definitions from packages/spec/src/system/identity.zod.ts into the new packages/spec/src/system/auth.zod.ts.

  • Move OIDCConfigSchema to auth.zod.ts.
  • Move SAMLConfigSchema to auth.zod.ts.
  • Move LDAPConfigSchema to auth.zod.ts.
  • Add a new optional field enterprise to the main AuthConfig schema in auth.zod.ts to hold these configurations (e.g., enterprise: z.object({ saml: ..., ldap: ... }).optional()).

Task 2: Redefine Identity as User Model

Refactor packages/spec/src/system/identity.zod.ts to become the dedicated User Model Specification.

  • Remove AuthProviderSchema and all auth-related configs from this file (since they are now in auth.zod.ts).
  • Create and export UserSchema:
    • Fields: id (string), email (email), emailVerified (boolean), name (optional string), image (optional url), createdAt (date), updatedAt (date).
  • Create and export AccountSchema (for linking OAuth accounts).
  • Create and export SessionSchema.

Task 3: Define Wire Protocol & Constants

Create packages/spec/src/system/auth-protocol.ts (new file) to define the API contract:

  • Export AUTH_CONSTANTS:
    • HEADER_KEY: 'Authorization'
    • TOKEN_PREFIX: 'Bearer '
    • COOKIE_PREFIX: 'os_'
    • CSRF_HEADER: 'x-os-csrf-token'
  • Export AuthHeaders interface.

Task 4: Cleanup & Consistency

  • Ensure packages/spec/src/index.ts exports the new schemas from both auth.zod.ts (Configuration) and identity.zod.ts (Data Models).
  • Update docs/AUTHENTICATION_STANDARD.md to reflect that Enterprise Authentication (SAML/LDAP) is now part of this unified standard.

This refactoring will result in:

  1. auth.zod.ts: How to login (Config for OAuth, Email, SAML, better-auth driver settings).
  2. identity.zod.ts: Who is logged in (Standard User/Session data models).
  3. auth-protocol.ts: How to communicate (API constants).</issue_description>

Comments on the Issue (you are @copilot in this section)


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

@vercel
Copy link
Copy Markdown

vercel bot commented Jan 21, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
spec Error Error Jan 21, 2026 10:58am

Request Review

…ity models

Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
…ion)

Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
@github-actions
Copy link
Copy Markdown
Contributor

This PR is very large. Consider breaking it into smaller PRs for easier review.

Copilot AI changed the title [WIP] Refactor authentication architecture and resolve identity conflicts Refactor: Separate authentication configuration from identity data models Jan 21, 2026
Copilot AI requested a review from hotlong January 21, 2026 09:26
@hotlong
Copy link
Copy Markdown
Contributor

hotlong commented Jan 21, 2026

@copilot 这是一段可以直接发给 AI (Copilot) 的提示词。这段提示词明确指出了模型字段与 better-auth 的差异,并要求通过添加“字段映射配置”来解决这个问题,使架构更加健壮。

您可以直接复制以下内容回复在 PR 的评论中,或者发给您的 AI 助手:


Please update packages/spec/src/system/auth.zod.ts to explicitly handle the schema differences between our ObjectStack standard (which follows Auth.js conventions) and the default better-auth models.

While the separation of concerns is great, our AccountSchema and SessionSchema use different field names than better-auth (e.g., sessionToken vs token, providerAccountId vs accountId).

Action Items:

  1. Update AuthConfigSchema in auth.zod.ts:
    Add a databaseMapping section (distinct from the existing database adapter config) that allows defining column names. This will serve as the instruction set for the Driver to map our Spec fields to the underlying engine's fields.

    Suggested structure to add inside AuthConfigSchema:

    /**
     * Database field mapping configuration.
     * Useful when the underlying driver (e.g., better-auth) uses different column names
     * than the ObjectStack standard schemas.
     */
    mapping: z.object({
      user: z.record(z.string()).optional(),
      session: z.record(z.string()).default({
        sessionToken: 'token',
        expires: 'expiresAt'
      }),
      account: z.record(z.string()).default({
        providerAccountId: 'accountId',
        provider: 'providerId',
      }),
    }).optional(),
  2. Verify UserSchema Compatibility:
    Ensure the UserSchema in identity.zod.ts remains minimal and strictly for "Identity" (profile data), while keeping sensitive auth data (like password hashes) handled internally by the driver or linked via the Account model, to avoid leaking implementation details into the general user model.

This ensures our Spec remains "Driver Agnostic" while providing built-in compatibility for our default driver (better-auth).

…ort)

Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
Copy link
Copy Markdown
Contributor Author

Copilot AI commented Jan 21, 2026

@copilot 这是一段可以直接发给 AI (Copilot) 的提示词。这段提示词明确指出了模型字段与 better-auth 的差异,并要求通过添加“字段映射配置”来解决这个...

I've implemented the database field mapping configuration to handle schema differences between ObjectStack (Auth.js conventions) and better-auth.

Changes made in commit fb0b264:

  1. Added DatabaseMappingSchema to auth.zod.ts:

    • User field mapping (optional)
    • Session field mapping with defaults: sessionTokentoken, expiresexpiresAt
    • Account field mapping with defaults: providerAccountIdaccountId, providerproviderId
    • Verification token field mapping (optional)
  2. Added mapping field to AuthConfigSchema:

    • Optional configuration distinct from database adapter config
    • Pre-configured with better-auth compatible defaults
    • Fully customizable for other drivers
  3. Verified UserSchema compatibility:

    • Confirmed it's minimal and identity-focused
    • No password hashes or sensitive auth data
    • Only profile fields: id, email, emailVerified, name, image, timestamps
  4. Added comprehensive tests (7 new tests):

    • Default mapping behavior
    • Custom mapping overrides
    • better-auth compatibility validation
  5. Updated documentation:

    • Added "Database Field Mapping" section to AUTHENTICATION_STANDARD.md
    • Included examples and default mappings table
    • Explained when to use custom mappings

The spec is now truly driver-agnostic while providing built-in compatibility for better-auth.

…nability

Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
@hotlong hotlong marked this pull request as ready for review January 21, 2026 11:26
Copilot AI review requested due to automatic review settings January 21, 2026 11:26
@github-actions
Copy link
Copy Markdown
Contributor

This PR is very large. Consider breaking it into smaller PRs for easier review.

@hotlong hotlong merged commit 69b5785 into main Jan 21, 2026
13 of 14 checks passed
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This pull request successfully refactors the authentication architecture by separating authentication configuration from identity data models, resolving architectural confusion and establishing clear boundaries.

Changes:

  • Migrated enterprise authentication configurations (OIDC, SAML, LDAP) from identity.zod.ts to auth.zod.ts under a new enterprise field
  • Redefined identity.zod.ts as pure data models (User, Account, Session, VerificationToken) representing "who is logged in"
  • Created auth-protocol.ts with wire protocol constants and interfaces (AUTH_CONSTANTS, AuthHeaders, AuthResponse, etc.)
  • Added database field mapping configuration to support driver compatibility (particularly better-auth)
  • Comprehensive test coverage for all new schemas
  • Extensive documentation updates with practical examples

Reviewed changes

Copilot reviewed 30 out of 30 changed files in this pull request and generated no comments.

Show a summary per file
File Description
packages/spec/src/system/identity.zod.ts Complete refactoring to define User, Account, Session, and VerificationToken data models; removed authentication configuration schemas
packages/spec/src/system/identity.test.ts New comprehensive test suite covering all identity data models with validation and type inference tests
packages/spec/src/system/auth.zod.ts Added enterprise auth configurations (OIDC, SAML, LDAP), database field mapping schema with better-auth defaults, and integrated into AuthConfig
packages/spec/src/system/auth.test.ts Added thorough tests for enterprise auth schemas and database mapping functionality
packages/spec/src/system/auth-protocol.ts New file defining wire protocol constants, interfaces for headers/responses/errors, and standard error codes
packages/spec/src/index.ts Updated exports with clear comments distinguishing configuration, data models, and wire protocol
packages/spec/json-schema/*.json Generated/updated JSON schemas for all new and modified types; removed deprecated AuthProvider and AuthProtocol schemas
docs/AUTHENTICATION_STANDARD.md Added enterprise SSO examples, database field mapping documentation, and updated architecture overview
content/docs/references/system/*.mdx Updated/created MDX documentation for all new schemas with property tables

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation protocol:system size/xl tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Please perform a final refactoring on PR #46 to consolidate the Authentication Architecture and resolve conflicts with the existing identity.zod.ts.

3 participants