Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Feb 10, 2026

Integrates better-auth v1.4.18 as the authentication engine for @objectstack/plugin-auth, replacing stub implementations with a production-ready foundation.

Changes

Core Integration

  • AuthManager wrapper class with lazy initialization pattern - defers better-auth instantiation until first use to avoid database initialization failures in test environments
  • Type-safe HTTP handlers using IHttpRequest/IHttpResponse from @objectstack/core
  • Method structures for login, register, logout, session management, email verification, and password reset (API wiring pending)

Security & Configuration

  • Environment-based secret management with runtime warnings when AUTH_SECRET is missing
  • Removed hardcoded database adapter dependency - configuration now warns when databaseUrl is provided without drizzle-orm
  • Dynamic secret generation for development: dev-secret-${timestamp}

Architecture

export class AuthManager {
  private auth: Auth<any> | null = null;  // Lazy init
  
  private getOrCreateAuth(): Auth<any> {
    if (!this.auth) {
      this.auth = betterAuth({
        secret: this.config.secret || this.generateSecret(),
        baseURL: this.config.baseUrl || 'http://localhost:3000',
        database: this.createDatabaseConfig(),
        emailAndPassword: { enabled: true },
        session: {
          expiresIn: this.config.session?.expiresIn || 604800,
          updateAge: this.config.session?.updateAge || 86400,
        },
      });
    }
    return this.auth;
  }
}

Next Steps

  • Wire better-auth API methods to route handlers
  • Implement drizzle-orm database adapter
  • Add OAuth provider configurations (Google, GitHub)
  • Enable advanced features (2FA, passkeys, magic links)

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • www.better-auth.com
    • Triggering command: /home/REDACTED/work/_temp/ghcca-node/node/bin/node /home/REDACTED/work/_temp/ghcca-node/node/bin/node --enable-source-maps /home/REDACTED/work/_temp/copilot-developer-action-main/dist/index.js (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

Original prompt

Start implementation

The user has attached the following file paths as relevant context:

  • .github/copilot-instructions.md
1. **Chronological Review**: The conversation began with the user outlining a plan for the full integration of the Better-Auth library, including various authentication features such as OAuth, 2FA, and session management. The user then requested to start the implementation, followed by a command to commit changes and delegate tasks to a cloud agent.
  1. Intent Mapping:

    • User requested to "Integrate actual better-auth library" and implement various authentication features.
    • User initiated the implementation process with "Start implementation."
    • User commanded to "Commit Changes and Delegate: 'Delegate to cloud agent.'"
  2. Technical Inventory:

    • Technologies mentioned include the Better-Auth library for authentication.
    • Features planned for integration include OAuth, 2FA, passkeys, magic links, and session management.
  3. Code Archaeology:

    • The user is working within the file /Users/steedos/Documents/GitHub/spec/packages/plugins/plugin-auth/IMPLEMENTATION_SUMMARY.md, which likely contains documentation or implementation notes related to the Better-Auth integration.
  4. Progress Assessment:

    • The user has outlined a comprehensive plan for the Better-Auth integration but has just initiated the implementation phase. No specific code changes have been documented yet.
  5. Context Validation:

    • All necessary context for continuing the integration of the Better-Auth library is captured, including the planned features and the current state of the implementation.
  6. Recent Commands Analysis:

    • Last Agent Commands:
      • "Start implementation" - initiated the integration process.
      • "Commit Changes and Delegate: 'Delegate to cloud agent'" - instructed to commit changes and delegate tasks.
    • Tool Results Summary: No specific tool results were returned as the commands were more procedural in nature.
    • Pre-Summary State: The agent was actively preparing to commit changes and delegate tasks related to the Better-Auth integration when the token budget was exceeded.
    • Operation Context: These commands were executed to move forward with the integration of the Better-Auth library, aligning with the user's goals of enhancing authentication features.
1. Conversation Overview: - Primary Objectives: User aims to integrate the Better-Auth library with features like OAuth, 2FA, passkeys, magic links, and session management. - Session Context: The conversation transitioned from planning the integration to initiating the implementation and committing changes. - User Intent Evolution: The user moved from outlining a comprehensive plan to actively starting the implementation and delegating tasks.
  1. Technical Foundation:
  • Better-Auth Library: A library intended for enhancing authentication processes with various features.
  1. Codebase Status:
  • File Name: IMPLEMENTATION_SUMMARY.md
  • Purpose: Document the integration process and features of the Better-Auth library.
  • Current State: The user has just initiated the implementation phase.
  • Key Code Segments: Not applicable yet as no specific code changes have been made.
  • Dependencies: Relates to the overall authentication framework being developed.
  1. Problem Resolution:
  • Issues Encountered: None reported yet as the implementation phase has just begun.
  • Solutions Implemented: Not applicable at this stage.
  • Debugging Context: No ongoing troubleshooting efforts reported.
  • Lessons Learned: Not applicable yet.
  1. Progress Tracking:
  • Completed Tasks: User has outlined the integration plan.
  • Partially Complete Work: Implementation has just started; no specific tasks have been completed yet.
  • Validated Outcomes: None yet as the implementation phase is in its infancy.
  1. Active Work State:
  • Current Focus: The user is focused on integrating the Better-Auth library.
  • Recent Context: The user has requested to start the implementation and commit changes.
  • Working Code: No specific code snippets have been discussed recently.
  • Immediate Context: The user was preparing to commit changes and delegate tasks related to the integration.
  1. Recent Operations:
  • Last Agent Commands: "Start implementation" and "Commit Changes and Delegate: 'Delegate to cloud agent.'"
  • Tool Results Summary: No specific results were returned; the commands were procedural.
  • Pre-Summary State: The agent was preparing to commit changes and delegate tasks.
  • Operation Context: These commands were executed to advance the integration of the Better-Auth library.
  1. Continuation Plan:
  • Pending Task: Implement the actual Better-Auth library and its features as outlined.
  • Priority Information: The integration of authentication features is the most urgent task.
  • Next Action: Proceed with the implementation of the Better-Auth library and related features as planned.

Created from VS Code.


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

@vercel
Copy link

vercel bot commented Feb 10, 2026

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

Project Deployment Actions Updated (UTC)
objectstack-studio Ready Ready Preview, Comment Feb 10, 2026 6:35am
spec Ready Ready Preview, Comment Feb 10, 2026 6:35am

Request Review

Copilot AI and others added 3 commits February 10, 2026 04:21
Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
…tatus

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

Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
Copilot AI changed the title [WIP] Start implementation of Better-Auth library features feat: Integrate better-auth library into authentication plugin Feb 10, 2026
Copilot AI requested a review from hotlong February 10, 2026 04:28
Copilot AI and others added 5 commits February 10, 2026 05:33
Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
Copilot AI and others added 4 commits February 10, 2026 05:51
Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
Copilot AI and others added 2 commits February 10, 2026 06:28
- Changed table names: auth_user → user, auth_session → session, etc.
- Changed field names: email_verified → emailVerified, created_at → createdAt, etc.
- Removed name conversion logic from adapter (no longer needed)
- Updated documentation to reflect better-auth native schema usage
- All tests passing (11/11)

This ensures existing better-auth databases can migrate without schema changes.

Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
@hotlong hotlong marked this pull request as ready for review February 10, 2026 07:22
Copilot AI review requested due to automatic review settings February 10, 2026 07:22
@hotlong hotlong merged commit 07ae78a into main Feb 10, 2026
14 checks passed
Copy link
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

Integrates better-auth v1.4.18 into @objectstack/plugin-auth, replacing the prior stubbed auth logic with a real AuthManager, ObjectQL persistence adapter, and wildcard request-forwarding route wiring.

Changes:

  • Added AuthManager wrapper with lazy initialization and request forwarding to better-auth’s universal handler.
  • Implemented an ObjectQL-backed better-auth adapter and added ObjectQL auth object definitions (user, session, account, verification).
  • Updated plugin exports, tests, examples, and documentation to reflect the new architecture and dependency setup.

Reviewed changes

Copilot reviewed 15 out of 16 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
pnpm-lock.yaml Updates lockfile for better-auth v1.4.18 and its optional deps.
packages/plugins/plugin-auth/package.json Moves better-auth to a runtime dependency.
packages/plugins/plugin-auth/src/index.ts Re-exports new AuthManager/adapter/objects entrypoints.
packages/plugins/plugin-auth/src/auth-plugin.ts Switches to wildcard forwarding via Hono raw app and wires in AuthManager.
packages/plugins/plugin-auth/src/auth-plugin.test.ts Updates tests to assert wildcard route registration via getRawApp().all().
packages/plugins/plugin-auth/src/auth-manager.ts Adds lazy-init better-auth integration and handler forwarding API.
packages/plugins/plugin-auth/src/objectql-adapter.ts Adds adapter bridging better-auth DB interface to IDataEngine.
packages/plugins/plugin-auth/src/objects/index.ts Adds barrel export for auth ObjectQL objects.
packages/plugins/plugin-auth/src/objects/auth-*.object.ts Defines ObjectQL object schemas for better-auth persistence models.
packages/plugins/plugin-auth/examples/basic-usage.ts Updates usage output to list better-auth endpoints under the wildcard base path.
packages/plugins/plugin-auth/README.md Updates docs to describe wildcard forwarding + ObjectQL persistence architecture.
packages/plugins/plugin-auth/IMPLEMENTATION_SUMMARY.md Updates implementation summary (but currently has some stale sections).
packages/plugins/plugin-auth/ARCHITECTURE.md Adds ADR describing the direct forwarding approach.
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported
Comments suppressed due to low confidence (2)

packages/plugins/plugin-auth/IMPLEMENTATION_SUMMARY.md:95

  • This section is now out of date with the implementation: the plugin no longer registers discrete /login, /register, /logout, /session routes, but instead forwards all requests under the base path via a wildcard route. Update the listed “API Routes Registered” to match the current behavior (or explicitly label them as removed).
## API Routes Registered

- `POST /api/v1/auth/login` - User login (stub)
- `POST /api/v1/auth/register` - User registration (stub)
- `POST /api/v1/auth/logout` - User logout (stub)
- `GET /api/v1/auth/session` - Get current session (stub)

packages/plugins/plugin-auth/src/auth-plugin.test.ts:127

  • These tests initialize the plugin with a mocked getService that returns undefined by default, but in the real kernel ctx.getService() throws when a service is missing. To keep the tests representative (and to exercise the new data-engine wiring), consider making the default mock throw and explicitly stubbing the required services (data, http.server/http-server) per test case.
      mockContext.getService = vi.fn((name: string) => {
        if (name === 'http-server') return mockHttpServer;
        throw new Error(`Service not found: ${name}`);
      });

Comment on lines 65 to 68
// Validate required configuration
if (!this.options.secret) {
throw new Error('AuthPlugin: secret is required');
}
Copy link

Copilot AI Feb 10, 2026

Choose a reason for hiding this comment

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

AuthManager already supports resolving the secret from process.env.AUTH_SECRET and generating a dev fallback, but the plugin currently hard-throws when options.secret is not provided. This makes the env-based secret management code path unreachable when using AuthPlugin; consider allowing secret to be omitted (and delegating validation/warnings to AuthManager), or remove the unused fallback behavior to keep the API consistent.

Copilot uses AI. Check for mistakes.
} else if (condition.operator === 'lte') {
filter[fieldName] = { $lte: condition.value };
} else if (condition.operator === 'contains') {
filter[fieldName] = { $regex: condition.value };
Copy link

Copilot AI Feb 10, 2026

Choose a reason for hiding this comment

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

ObjectQL’s filter DSL uses string operators like $contains/$startsWith/$endsWith (see packages/spec/src/data/filter.zod.ts), but the adapter maps better-auth contains to $regex. This likely won’t be understood by ObjectQL drivers; map contains to $contains instead.

Suggested change
filter[fieldName] = { $regex: condition.value };
filter[fieldName] = { $contains: condition.value };

Copilot uses AI. Check for mistakes.
Comment on lines +117 to +121
const result = await dataEngine.update(objectName, {
...update,
id: record.id,
});

Copy link

Copilot AI Feb 10, 2026

Choose a reason for hiding this comment

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

IDataEngine.update() / delete() accept IDs via either id or _id (ObjectQL internally checks both), but the adapter only uses record.id when applying updates/deletes. To avoid breaking when the engine/driver returns _id, use record.id ?? record._id (and likewise when building the delete filter).

Copilot uses AI. Check for mistakes.
Comment on lines +133 to +141
// Get raw Hono app to use native wildcard routing
// Type assertion is safe here because we explicitly require Hono server as a dependency
if (!('getRawApp' in httpServer) || typeof (httpServer as any).getRawApp !== 'function') {
ctx.logger.error('HTTP server does not support getRawApp() - wildcard routing requires Hono server');
throw new Error(
'AuthPlugin requires HonoServerPlugin for wildcard routing support. ' +
'Please ensure HonoServerPlugin is loaded before AuthPlugin.'
);
}
Copy link

Copilot AI Feb 10, 2026

Choose a reason for hiding this comment

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

The new getRawApp() guard path in registerAuthRoutes() throws a specific error when the HTTP server doesn’t support wildcard routing, but there’s no unit test covering this behavior. Adding a test that asserts the thrown error message when getRawApp is missing would keep coverage aligned with the new failure mode.

Copilot uses AI. Check for mistakes.
Comment on lines +101 to 105
- `better-auth` ^1.4.18 - Authentication library

### Peer Dependencies (Optional)
- `better-auth` ^1.0.0 - For future authentication implementation
- `drizzle-orm` >=0.41.0 - For database persistence (optional)

Copy link

Copilot AI Feb 10, 2026

Choose a reason for hiding this comment

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

The summary lists drizzle-orm as an optional peer dependency, but packages/plugins/plugin-auth/package.json no longer declares it as a peer dependency (and the implementation/documentation elsewhere says no ORM is required). Align this dependency section with the actual package manifest and intended support story.

Copilot uses AI. Check for mistakes.
Comment on lines +70 to +74
// Get data engine service for database operations
const dataEngine = ctx.getService<any>('data');
if (!dataEngine) {
ctx.logger.warn('No data engine service found - auth will use in-memory storage');
}
Copy link

Copilot AI Feb 10, 2026

Choose a reason for hiding this comment

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

ctx.getService('data') throws when the service is missing (it doesn’t return undefined), so the if (!dataEngine) { ... } warning branch is effectively unreachable and init will hard-fail if data isn't registered. If data is optional here, wrap the lookup in try/catch (or use getServices()), and type it as IDataEngine instead of any.

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dependencies Pull requests that update a dependency file documentation Improvements or additions to documentation size/l size/xl tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants