@velajs/better-auth 1.30.0 → 1.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,107 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.32.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 9a00506: Align module APIs with instance ownership: shared facilities use forRoot, local and named services use register, and Queue, I18n and Seeder contribute declarations through forFeature. Remove replaced APIs. Local registrations receive independent identities; reused definitions share within an application, and explicit keys retain conflict checks.
8
+
9
+ Require applications to attach exported guards and interceptors explicitly. Remove automatic installation and guard options while preserving policy ownership, request scope, phase ordering, testing overrides and integration-route exemptions. Keep translation contributions and mutable runtime configuration isolated per application, and return runtime-only settings from async factories. Storage separates structural httpController mounting from runtime http options.
10
+
11
+ Add schema-first GraphQL resolver and parameter decorators with exact provider ownership, endpoint selection and duplicate binding validation. Add the optional Cloudflare workflow-definitions entrypoint to host portable workflows and compiled agents with validated input, per-run dependency resolution, explicit dispatch authority and native replay/error semantics.
12
+
13
+ Update CLI output, runnable examples, packed consumers and migration documentation together. Keep root Cloudflare declarations usable without installing the optional Feature Flags peer. See docs/module-api-migration.md for the new signatures and required application changes. This is a coordinated breaking change on the 1.x line; no compatibility aliases are retained.
14
+
15
+ ### Patch Changes
16
+
17
+ - Updated dependencies [9a00506]
18
+ - @velajs/vela@1.34.0
19
+ - @velajs/authz@1.32.0
20
+
21
+ ## 1.31.0
22
+
23
+ ### Minor Changes
24
+
25
+ - b227d22: Build `BetterAuthModule` on `defineModule`. `basePath`, `mountHandler` and `guard` are structural (`BetterAuthStructuralOption`), and `auth` may be a function, `auth: () => betterAuth({ ... })`, which runs on the first authentication and is cached.
26
+
27
+ **Behavior change:** the option that registers `AuthGuard` application-wide is `guard: 'global' | 'none'` instead of `isGlobal`, and still defaults to registering it (`'global'`). `isGlobal` is now the standard extra: it makes `BetterAuthService` and its exports visible to every module, and defaults to `false`.
28
+
29
+ **Behavior change:** a `forRootAsync` factory returns the module options instead of the auth instance, and it runs while the application initializes: `useFactory: (env) => ({ issuer: 'accounts', auth: () => betterAuth({ ... }) })`. `issuer` comes from the factory; `basePath`, `mountHandler` and `guard` go next to it. Options without an `auth` instance or function fail bootstrap.
30
+
31
+ **Behavior change:** registrations are keyed by their structural options (`basePath`, `guard` and `mountHandler`) instead of the auth instance or factory reference, so a second auth configuration with the same structural options fails bootstrap instead of becoming another instance, and two configurations that mount the handler at one base path fail bootstrap as a duplicate controller. The process-wide reference table is removed. `createBetterAuthCatchallController` returns one class per base path, so a registration imported twice mounts the handler once.
32
+
33
+ **Behavior change:** `identityFromUser` no longer sets the removed `userId` alias; read `subject` (with `issuer`).
34
+
35
+ `basePath` (`'/api/auth'`), `guard` (`'global'`) and `mountHandler` (`true`) have structural defaults, so `forRoot({ auth })` and `forRoot({ auth, guard: 'global' })` are one instance with one catch-all controller instead of two.
36
+ - 3fc6f2b: The mounted Better Auth handler carries `SkipGuardPhases(['tenant', 'authorize'])` from `@velajs/vela/module-kit`, so the global tenant and authorization guards whose class declares `static readonly skippable = true` (`TenantGuard`, `PermissionGuard`, `RolesGuard` and `CedarGuard`) never block sign-in. Throttling and the other global guards still run there.
37
+
38
+ **Behavior change:** those guards no longer run on the Better Auth handler, including one the application registers itself, such as `{ provide: APP_GUARD, useClass: TenantGuard }`, and an application guard that extends one without declaring `static override readonly skippable = false`. @velajs/better-auth 1.30.0 ran every global guard on the handler.
39
+ - f267c2f: Global guards run in deterministic phases, whatever order modules register them in: `authenticate` → `tenant` → `authorize` → `feature`. A guard declares its phase with `static readonly phase: GuardPhase` (an instance may carry its own `phase`); a guard without one runs in `feature`, and guards keep registration order within a phase. HTTP, WebSocket and RPC dispatch order the constructed guards, so a guard provided by a factory (`APP_GUARD` with `useFactory`) runs in the phase its instance declares; other transports call `orderGuardsByPhase` from `@velajs/vela/module-kit`. Global guards still run before controller and method guards. `ThrottlerGuard` and `FeatureFlagGuard` are feature guards, so throttling partitions by the identity an `authenticate`-phase guard verifies, and such a guard no longer has to be imported before `ThrottlerModule`.
40
+
41
+ Each integration installs its guard globally (through the `defineModule` `global:` slot or an `APP_GUARD` provider under the guard's own token, so `overrideGuard(TenantGuard)` and `overrideGuard(CedarGuard)` in `@velajs/testing` reach the installed instance) and takes `guard: 'global' | 'none'`, defaulting to `'global'`: `BetterAuthModule` and `CloudflareAccessModule` authenticate, `TenantModule` admits the tenant, and `AuthzModule` (`PermissionGuard`, `RolesGuard`) and `CedarModule` authorize. `guard` is a structural option with that default, so `forRoot({ ... })` and `forRoot({ ..., guard: 'global' })` are one instance; with `forRootAsync`, pass it beside the factory. The per-phase markers stay: `@Public`/`@OptionalAuth`, `@TenantIgnored`/`@TenantOptional`, `@CedarPublic`. The installed `TenantGuard` and `CedarGuard` cover every application route, including routes in modules that do not import `TenantModule` or `CedarModule` (they admit or authorize through the installing module), whether or not the module is registered with `isGlobal`, and they also run on WebSocket, live-query and RPC entrypoints (see the behavior changes below); a route-level `TenantGuard` or `CedarGuard` in a module that cannot see its module answers 403.
42
+
43
+ An integration package marks its own controller, which applications cannot annotate, with `SkipGuardPhases(['tenant', 'authorize'])` from `@velajs/vela/module-kit`: the global guards integrations install in those phases do not run for its routes. Only a guard that declares `static readonly skippable = true` is skipped, as `TenantGuard`, `PermissionGuard`, `RolesGuard` and `CedarGuard` do; other global guards run in every phase on these routes, as do authentication, feature and route guards. `skippable` belongs to the guard class, whoever registers it: an application guard that extends an integration guard inherits it, and declares `static override readonly skippable = false` to run on these routes too. The Better Auth handler and the `@velajs/storage` controller skip both phases; the GraphQL endpoint skips `authorize`, because resolvers authorize each field.
44
+
45
+ To declare route metadata such as Cedar policy on generated CRUD controllers, which applications do not write, use the new `decorators` and `endpointDecorators` resource options of `@velajs/crud`.
46
+
47
+ `RpcModule` and `rpcAdapter` run the `authorize` policy in the global `authorize` phase, before the other global authorize guards: after global authentication and tenant admission, so a policy can read the trusted identity those guards publish.
48
+
49
+ **Behavior change:** `CloudflareAccessModule`, `TenantModule` and `AuthzModule` now install their guards globally. Remove `@UseGuards(CloudflareAccessGuard)`, `@UseGuards(TenantGuard)` and `@UseGuards(PermissionGuard, RolesGuard)` where the module now covers the route, or pass `guard: 'none'` and keep a fully route-level pipeline (a global guard runs before every route guard). Mark tenant-free routes with `@TenantIgnored()` or `@TenantOptional()`. `AUTHZ_OPTIONS` is typed as the new `AuthzModuleOptions`. Registrations of `CloudflareAccessModule`, `TenantModule`, `AuthzModule` and `CedarModule` are keyed by `guard` (and Cedar's `undeclared`) instead of by all their options, so a second registration with the same `guard` and other options, such as a feature module's own `AuthzModule` engine with other roles, fails bootstrap: give each additional registration its own `key`, and keep `guard: 'global'` on only one `AuthzModule`, `TenantModule` or `CedarModule` registration.
50
+
51
+ **Behavior change:** `CedarModule`'s `globalGuard: false` is replaced by `guard: 'none'`, and `CedarGuard` denies (403) application routes without `@RequireResource()` or `@CedarPublic()`, in every module. Set `undeclared: 'allow'` to let them through as before. `undeclared` is structural, like `guard` (default `'deny'`): with `forRootAsync`, pass it beside the factory, which cannot return it.
52
+
53
+ **Behavior change:** the guards `CloudflareAccessModule`, `TenantModule`, `AuthzModule` and `CedarModule` install run wherever the application's global guards run, not only on controller routes: on WebSocket gateway messages, on the check before each push to a socket (a gateway or live-query push, run with the gateway class), on the reserved `$live` frames that subscribe to and unsubscribe from live queries and send presence heartbeats (run with the framework's `LiveEngine` class, which applications cannot annotate) and on RPC procedures. `SkipGuardPhases` applies only to controller routes. With default options:
54
+
55
+ - `CedarModule` (`undeclared: 'deny'`): a gateway message without `@RequireResource()` or `@CedarPublic()` answers an `exception` frame (`code: 'internal'`), pushes are not delivered, `$live` frames get no reply, and an undeclared RPC procedure answers a 403 failure frame. The guard @velajs/authz-cedar 1.30.0 installed let undeclared handlers through.
56
+ - `TenantModule`: gateway messages, pushes and `$live` frames fail the same way, because a socket context has no request to select the tenant from. RPC procedures require a tenant and an authenticated identity, as routes do (400 without them).
57
+ - `CloudflareAccessModule`: every gateway message, push and `$live` frame fails, in `mode: 'optional'` too, because the guard verifies HTTP requests only. RPC procedures require an Access identity, as routes do.
58
+ - `AuthzModule`: handlers without `@Roles()` or `@RequirePermission()` pass; those declarations on gateway handlers and RPC procedures are now enforced.
59
+
60
+ A guard failure on a `$live` frame or a push reaches only the error reporter, which does not log 4xx errors by default; a rejected presence heartbeat leaves the socket out of its room's presence roster. Mark gateway classes and RPC providers or procedures with `@CedarPublic()` or `@RequireResource()`, and with `@TenantIgnored()` or `@TenantOptional()`; a marker on the gateway class, not on a handler, also admits its pushes. Markers cannot reach `$live` frames: for live queries and presence, give `TenantModule` a `resolve` option that returns the tenant of a socket context (from the connection's verified identity, `normalizeWebSocketUpgradeIdentity(client.data)` from `@velajs/vela/websocket`), set Cedar's `undeclared: 'allow'`, or pass `guard: 'none'`. `CloudflareAccessModule` has no socket option: an application with gateways or live queries passes `guard: 'none'`, authenticates HTTP routes with `@UseGuards(CloudflareAccessGuard)` and sockets at upgrade with `CloudflareAccessUpgradeAuthenticator`; global guards run before route guards, so it applies the tenant and authorization guards on those routes too (`guard: 'none'` on their modules).
61
+
62
+ **Behavior change:** The RPC `authorize` policy runs after global authentication and tenant guards instead of before every global guard. A policy that denied callers because the identity was not yet published now sees the identity an `authenticate`-phase guard publishes.
63
+
64
+ **Behavior change:** an application's own global guard without a `phase` runs in `feature`, where @velajs/vela 1.30.0 ran every global guard in registration order. A custom global authentication guard, such as an `APP_GUARD` JWT guard, that does not declare `static readonly phase = 'authenticate'` now runs after the tenant and authorize guards the integrations install (`TenantGuard`, `PermissionGuard`, `RolesGuard` and `CedarGuard`) and after the RPC `authorize` policy, so they run without the identity it publishes, and it runs in import order relative to `ThrottlerGuard`. Declare `static readonly phase = 'authenticate'` on such a guard, and `'tenant'` or `'authorize'` on a custom global tenant or authorization guard.
65
+ - 096e259: Declarations on an ancestor class apply to the classes that extend it, as reflect-metadata resolves them in Nest. In @velajs/vela 1.30.0 every reader looked only at the concrete class. Route decorators (`@Get()`, `@Post()`, …) are still read from the controller class itself, unlike Nest: a method an ancestor routes is not mounted on the subclass. Route an inherited method on the subclass, for example `Get('list')(Sub.prototype, 'list', descriptor)`.
66
+
67
+ - Class metadata applies to a subclass through every `Reflector` form (`get`, `getClass`, `getAll`, `getAllAndOverride` and `getAllAndMerge`, with an execution context, `context.getClass()` or the `[context.getHandler(), context.getClass()]` list): the controller's own, else the nearest ancestor's, so `@Roles(['admin'])` on an abstract base controller guards every controller that extends it.
68
+ - Method metadata an ancestor declares on a method the controller inherits without overriding, such as one it routes with `Get()(Sub.prototype, 'list', descriptor)`, applies through every `Reflector` form too: the nearest declaration wins, the controller's own, else the nearest ancestor's. A method the controller overrides reads only its own declarations, and metadata one controller declares on a shared method never applies to a sibling.
69
+ - Class-level `@UseGuards`, `@UseInterceptors`, `@UsePipes`, `@UseFilters` and `@UseMiddleware` on an ancestor run for the subclass on every transport, the root class's first and the subclass's own last. On an inherited method, the method-level enhancers each ancestor declares run before the controller's own, and `@Serialize` and `SkipGuardPhases` read the nearest declaration. The module loader registers the enhancer classes a class inherits, as it does its own.
70
+ - Guards that read route metadata, such as `AuthGuard`, `RolesGuard`, `PermissionGuard`, `TenantGuard`, `CedarGuard`, `FeatureFlagGuard` and `ThrottlerGuard`, enforce inherited requirements, and `authorizationAudit()` and `auditCedarRoutes()` read declarations as the guards do. `CacheModule` checks `@CacheResponse` at bootstrap as `CacheInterceptor` reads it, and `ThrottlerModule` checks `@Throttle()` as `ThrottlerGuard` reads it, inherited declarations included, so an invalid inherited declaration, such as tags without an invalidation store or a throttler the module does not declare, fails bootstrap instead of every request.
71
+
72
+ **Behavior change:** class metadata and class-level enhancers an ancestor declares, and the metadata, method-level enhancers, `@Serialize` and `SkipGuardPhases` an ancestor declares on a method a controller inherits unchanged, now apply to the classes that extend it. Requirements such as `@Roles()`, `@RequirePermission()` or `@RequireResource()` there are enforced, where the routes previously ran without them. Opening markers apply the same way: an inherited `@Public()`, `@OptionalAuth()`, `@TenantIgnored()`, `@CedarPublic()`, `@SkipThrottle()` or `SkipGuardPhases` now opens or relaxes routes that previously required authentication, tenant admission, Cedar authorization or throttling. Remove a declaration from the ancestor, or override the method in the controller, where a subclass must not inherit it.
73
+ - f267c2f: The new `@Ctx()` parameter decorator injects the Hono context (`VelaContext`); `@Res()` still returns it as the response handle.
74
+
75
+ **Behavior change:** `@Req()` injects the platform `Request`, as Nest's `@Req()` injects the request object, instead of the Hono context. Replace `@Req() c: Context` with `@Ctx() c: Context`, or with `@Req() request: Request` when the handler only read `c.req.raw`. The Better Auth catch-all handler and generated CRUD handlers are migrated.
76
+
77
+ ### Patch Changes
78
+
79
+ - Updated dependencies [0b8c649]
80
+ - Updated dependencies [1011653]
81
+ - Updated dependencies [088f4d4]
82
+ - Updated dependencies [f267c2f]
83
+ - Updated dependencies [dfe925c]
84
+ - Updated dependencies [fd11d20]
85
+ - Updated dependencies [748e4f8]
86
+ - Updated dependencies [b227d22]
87
+ - Updated dependencies [096e259]
88
+ - Updated dependencies [fd11d20]
89
+ - Updated dependencies [3418c55]
90
+ - Updated dependencies [fd11d20]
91
+ - Updated dependencies [d51dbb3]
92
+ - Updated dependencies [f267c2f]
93
+ - Updated dependencies [4a06057]
94
+ - Updated dependencies [f267c2f]
95
+ - Updated dependencies [1bfc1c1]
96
+ - Updated dependencies [f267c2f]
97
+ - Updated dependencies [f267c2f]
98
+ - Updated dependencies [1ef55ac]
99
+ - Updated dependencies [f267c2f]
100
+ - Updated dependencies [b227d22]
101
+ - Updated dependencies [2c92243]
102
+ - @velajs/vela@1.31.0
103
+ - @velajs/authz@1.31.0
104
+
3
105
  ## 1.30.0
4
106
 
5
107
  ### Minor Changes
package/README.md CHANGED
@@ -8,17 +8,17 @@ pnpm add @velajs/better-auth better-auth
8
8
 
9
9
  ## Quick start
10
10
 
11
- Construct your better-auth instance once and hand it to `BetterAuthModule.forRoot`. The module installs `AuthGuard` application-wide by default; use `@CurrentUser()` on authenticated routes and mark the small anonymous surface explicitly.
11
+ Construct your better-auth instance once and hand it to `BetterAuthModule.forRoot`. Attach its exported `AuthGuard` in the application; use `@CurrentUser()` on authenticated routes and mark the small anonymous surface explicitly.
12
12
 
13
13
  ```ts
14
14
  import { betterAuth } from 'better-auth';
15
- import { Module, Controller, Get, VelaFactory } from '@velajs/vela';
15
+ import { APP_GUARD, Module, Controller, Get, VelaFactory } from '@velajs/vela';
16
16
  import {
17
- BetterAuthModule, CurrentUser, Public,
17
+ AuthGuard, BetterAuthModule, CurrentUser, Public,
18
18
  } from '@velajs/better-auth';
19
19
 
20
20
  const auth = betterAuth({
21
- database: /* drizzle / prisma / kysely adapter */,
21
+ database: databaseAdapter, // a drizzle, prisma or kysely adapter
22
22
  emailAndPassword: { enabled: true },
23
23
  socialProviders: { github: { clientId, clientSecret } },
24
24
  });
@@ -36,6 +36,7 @@ class MeController {
36
36
  @Module({
37
37
  imports: [BetterAuthModule.forRoot({ auth })],
38
38
  controllers: [MeController],
39
+ providers: [{ provide: APP_GUARD, useExisting: AuthGuard }],
39
40
  })
40
41
  class AppModule {}
41
42
 
@@ -49,15 +50,22 @@ export default app; // edge-compatible (.fetch)
49
50
 
50
51
  ```ts
51
52
  BetterAuthModule.forRoot({
52
- auth, // pre-constructed betterAuth({ ... }) instance
53
+ auth, // betterAuth({ ... }) instance, or () => betterAuth({ ... })
53
54
  issuer: 'my-app:better-auth', // stable namespace paired with user ids
54
55
  basePath: '/api/auth', // default — must match your better-auth config
55
- isGlobal: true, // default — register AuthGuard as APP_GUARD
56
56
  mountHandler: true, // mount /api/auth/* catch-all controller
57
+ isGlobal: false, // default — true makes BetterAuthService visible to every module
57
58
  });
58
59
  ```
59
60
 
60
- Authentication has no allow-by-default compatibility mode. Use `@Public(true)` for routes that intentionally skip authentication, or `@OptionalAuth(true)` when the route accepts an anonymous identity. `isGlobal: false` is intended only for applications that install an equivalent global authentication guard themselves.
61
+ Authentication has no allow-by-default compatibility mode. Use `@Public(true)` for routes that intentionally skip authentication, or `@OptionalAuth(true)` when the route accepts an anonymous identity. Importing the module alone does not install authentication; attach an application alias or `@UseGuards(AuthGuard)`.
62
+
63
+ `basePath` and `mountHandler` are structural: `forRootAsync` takes them next to its factory, which returns the other options. An `auth` function runs on the first authentication, not while the application initializes.
64
+
65
+ Global guards run in deterministic phases whatever the import order: `authenticate` (AuthGuard), `tenant` (TenantGuard), `authorize` (PermissionGuard, RolesGuard, CedarGuard), then `feature` (ThrottlerGuard and any guard without a declared phase). Throttling therefore always partitions by the verified identity. The mounted auth handler is `@Public(true)` and marked `SkipGuardPhases(['tenant', 'authorize'])`, so the tenant admission and authorization guards applications install globally never block sign-in, including a `TenantGuard` the application registers globally itself; throttling and the other global guards still apply.
66
+
67
+ The following imports configure authentication; retain the `APP_GUARD` alias from
68
+ the quick start in the application root.
61
69
 
62
70
  ## Three composition patterns
63
71
 
@@ -67,7 +75,6 @@ Authentication has no allow-by-default compatibility mode. Use `@Public(true)` f
67
75
  imports: [
68
76
  BetterAuthModule.forRoot({
69
77
  auth: betterAuth({ database, plugins: [magicLink({ sendMagicLink }), apiKey()] }),
70
- isGlobal: true,
71
78
  }),
72
79
  ]
73
80
  ```
@@ -80,15 +87,18 @@ imports: [
80
87
  imports: [
81
88
  BetterAuthModule.forRootAsync({
82
89
  inject: [ENV, EmailService],
83
- useFactory: (env, email) => betterAuth({
84
- database: drizzleAdapter(drizzle(env.DB), { provider: 'sqlite' }),
85
- plugins: [
86
- magicLink({ sendMagicLink: (data) => email.send(data) }), // DI'd EmailService
87
- apiKey(),
88
- twoFactor(),
89
- ],
90
+ useFactory: (env, email) => ({
91
+ // Built on the first authentication, not while the application initializes.
92
+ auth: () =>
93
+ betterAuth({
94
+ database: drizzleAdapter(drizzle(env.DB), { provider: 'sqlite' }),
95
+ plugins: [
96
+ magicLink({ sendMagicLink: (data) => email.send(data) }), // DI'd EmailService
97
+ apiKey(),
98
+ twoFactor(),
99
+ ],
100
+ }),
90
101
  }),
91
- isGlobal: true,
92
102
  }),
93
103
  ]
94
104
  ```
@@ -130,8 +140,9 @@ export class MagicLinkAuthModule {}
130
140
  BetterAuthModule.forRootAsync({
131
141
  imports: [MagicLinkAuthModule, OAuthAuthModule],
132
142
  inject: [MAGIC_LINK_PLUGIN, OAUTH_PLUGIN],
133
- useFactory: (magicLink, oauth) => betterAuth({ database, plugins: [magicLink, oauth] }),
134
- isGlobal: true,
143
+ useFactory: (magicLink, oauth) => ({
144
+ auth: () => betterAuth({ database, plugins: [magicLink, oauth] }),
145
+ }),
135
146
  }),
136
147
  ],
137
148
  })
@@ -148,18 +159,20 @@ import { BetterAuthService } from '@velajs/better-auth';
148
159
 
149
160
  @Injectable()
150
161
  class AdminUserService {
151
- constructor(@Inject(BetterAuthService) private readonly auth: BetterAuthService<typeof auth>) {}
162
+ constructor(
163
+ @Inject(BetterAuthService) private readonly authService: BetterAuthService<typeof auth>,
164
+ ) {}
152
165
 
153
166
  listSessions(userId: string) {
154
- return this.auth.api.listUserSessions({ userId });
167
+ return this.authService.api.listUserSessions({ userId });
155
168
  }
156
169
  revoke(token: string) {
157
- return this.auth.api.revokeSession({ sessionToken: token });
170
+ return this.authService.api.revokeSession({ sessionToken: token });
158
171
  }
159
172
  }
160
173
  ```
161
174
 
162
- Under `forRootAsync`, the underlying `betterAuth({...})` instance is constructed lazily on first `.auth` / `.api` / `.handler` access. The Workers adapter supplies the typed environment before DI and owns a separate application for each environment, so a cached auth instance never crosses environments.
175
+ When `auth` is a function (`auth: () => betterAuth({...})`), the instance is constructed on first `.auth` / `.api` / `.handler` access and cached. The Workers adapter supplies the typed environment before DI and owns a separate application for each environment, so a cached auth instance never crosses environments.
163
176
 
164
177
  ## Decorators
165
178
 
@@ -183,9 +196,9 @@ handle(@CurrentUser() user: User | undefined) {
183
196
  - **`AuthGuard`** — singleton. Reads `Authorization` header / cookies via `auth.api.getSession`, validates the full base user/session models, and publishes Vela's trusted principal, tenant, roles, and session expiry for downstream security components. The Better Auth organization plugin's verified `activeOrganizationId` becomes the tenant partition when present. The guard honors only explicit `@Public()` / `@OptionalAuth()` metadata. The generated Better Auth catch-all controller is explicitly public; sharing its URL prefix never makes an application controller public.
184
197
  Permission and role guards live in `@velajs/authz/vela`: import `PermissionGuard`, `RequirePermission`, `RolesGuard`, and `Roles` there. They read the same trusted identity for Better Auth and Cloudflare Access. Run authentication before authorization.
185
198
 
186
- Global registration is the default: installing the module binds `AuthGuard` to `APP_GUARD`. Routes are deny-by-default; mark public ones with `@Public(true)`. The generated Better Auth controller is already marked public.
199
+ Install globally with `{ provide: APP_GUARD, useExisting: AuthGuard }`, or select routes with `@UseGuards(AuthGuard)`. Routes are deny-by-default; mark public ones with `@Public(true)`. The generated Better Auth controller is already marked public.
187
200
 
188
- When using `ThrottlerModule`, import Better Auth first. Vela then rate-limits by
201
+ When using `ThrottlerModule`, also attach its exported `ThrottlerGuard`. Guard phases ensure Vela rate-limits by
189
202
  the verified issuer, subject, principal type, and active organization before it
190
203
  falls back to a platform-attested client address.
191
204
 
@@ -263,7 +276,7 @@ import { BetterAuthService, Public } from '@velajs/better-auth';
263
276
  @Controller('/auth')
264
277
  class CustomCatchallController {
265
278
  constructor(@Inject(BetterAuthService) private auth: BetterAuthService) {}
266
- @All('/*') handle(@Req() c: Context) { return this.auth.handler(c.req.raw); }
279
+ @All('/*') handle(@Req() request: Request) { return this.auth.handler(request); }
267
280
  }
268
281
  ```
269
282
 
@@ -13,20 +13,25 @@ interface BetterAuthInstance {
13
13
  readonly $context?: Promise<Pick<Awaited<Auth['$context']>, 'internalAdapter' | 'authCookies' | 'secret'>>;
14
14
  }
15
15
  interface BetterAuthModuleOptions<TAuth extends BetterAuthInstance = BetterAuthInstance> extends BetterAuthRuntimeOptions {
16
- auth: TAuth;
16
+ /**
17
+ * The better-auth instance, or a function that builds it. A function runs on
18
+ * the first authentication (`BetterAuthService.auth`), so a `forRootAsync`
19
+ * factory can return `{ auth: () => betterAuth({ ... }) }` from injected
20
+ * bindings without constructing better-auth at bootstrap.
21
+ */
22
+ auth: TAuth | (() => TAuth);
17
23
  }
18
24
  /** Provider configuration, separate from the lazily constructed auth instance. */
19
25
  interface BetterAuthRuntimeOptions {
20
26
  /** Stable namespace paired with user ids in authorization identities. */
21
27
  issuer?: string;
28
+ /** Mount path of the catch-all handler (default `/api/auth`). Structural. */
22
29
  basePath?: string;
23
- /**
24
- * Register AuthGuard application-wide. Defaults to `true`; opt out only when
25
- * the application installs an equivalent global authentication guard itself.
26
- */
27
- isGlobal?: boolean;
30
+ /** Mount the catch-all better-auth handler (default `true`). Structural. */
28
31
  mountHandler?: boolean;
29
32
  }
33
+ /** The fields `forRootAsync` takes alongside its factory: they shape the module graph. */
34
+ type BetterAuthStructuralOption = 'basePath' | 'mountHandler';
30
35
  type User$1 = User;
31
36
  type Session$1 = Session;
32
37
  //#endregion
@@ -35,15 +40,13 @@ type Session$1 = Session;
35
40
  * The single injectable consumers reach for to interact with better-auth.
36
41
  * Wraps the underlying `betterAuth({...})` instance with lazy construction:
37
42
  *
38
- * - `forRoot({ auth })` — the builder returns the eagerly-provided instance,
39
- * so the first `.auth` / `.api` / `.handler` access is effectively a
40
- * read-and-cache.
41
- * - `forRootAsync({ inject, useFactory })` — the builder wraps the user's
42
- * factory + inject deps. First access triggers `useFactory(...deps)`. This
43
- * is what makes Cloudflare D1/KV bindings work: at module load the factory
44
- * doesn't run; on first request (when AuthGuard or the catch-all calls
45
- * `service.api` / `service.handler`), the native environment is registered and the
46
- * factory can read them safely.
43
+ * - `auth` is an instance — the builder returns it, so the first `.auth` /
44
+ * `.api` / `.handler` access is effectively a read-and-cache.
45
+ * - `auth` is a function (`auth: () => betterAuth({ ... })`, typically
46
+ * returned by a `forRootAsync` factory) — the first access calls it. On
47
+ * Workers, construction then happens on the first request (when AuthGuard
48
+ * or the catch-all calls `service.api` / `service.handler`), never at
49
+ * bootstrap.
47
50
  *
48
51
  * Used directly by AuthGuard and the catch-all controller. Consumers in
49
52
  * application code inject the same way: `@Inject(BetterAuthService)`.
@@ -63,5 +66,5 @@ declare class BetterAuthService<TAuth extends BetterAuthInstance = BetterAuthIns
63
66
  get handler(): TAuth['handler'];
64
67
  }
65
68
  //#endregion
66
- export { Session$1 as a, BetterAuthRuntimeOptions as i, BetterAuthInstance as n, User$1 as o, BetterAuthModuleOptions as r, BetterAuthService as t };
67
- //# sourceMappingURL=better-auth.service-CvmboUID.d.ts.map
69
+ export { BetterAuthStructuralOption as a, BetterAuthRuntimeOptions as i, BetterAuthInstance as n, Session$1 as o, BetterAuthModuleOptions as r, User$1 as s, BetterAuthService as t };
70
+ //# sourceMappingURL=better-auth.service-D_G-PP8p.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"better-auth.service-SNg1YFTK.js","names":[],"sources":["../src/better-auth.service.ts"],"sourcesContent":["import { Inject, Injectable, InjectionToken } from '@velajs/vela';\nimport type { BetterAuthInstance } from './better-auth.types';\n\n/**\n * Internal token holding the auth-construction closure with its inject deps\n * closed over. Resolves cheaply at module load (just captures references);\n * the inner call happens lazily on first auth use (see `BetterAuthService`).\n *\n * Not exported from the public surface — only the service consumes it.\n */\nexport const BETTER_AUTH_BUILDER = new InjectionToken<() => BetterAuthInstance>(\n 'vela.better-auth.Builder',\n);\n\n/**\n * The single injectable consumers reach for to interact with better-auth.\n * Wraps the underlying `betterAuth({...})` instance with lazy construction:\n *\n * - `forRoot({ auth })` — the builder returns the eagerly-provided instance,\n * so the first `.auth` / `.api` / `.handler` access is effectively a\n * read-and-cache.\n * - `forRootAsync({ inject, useFactory })` — the builder wraps the user's\n * factory + inject deps. First access triggers `useFactory(...deps)`. This\n * is what makes Cloudflare D1/KV bindings work: at module load the factory\n * doesn't run; on first request (when AuthGuard or the catch-all calls\n * `service.api` / `service.handler`), the native environment is registered and the\n * factory can read them safely.\n *\n * Used directly by AuthGuard and the catch-all controller. Consumers in\n * application code inject the same way: `@Inject(BetterAuthService)`.\n */\n@Injectable()\nexport class BetterAuthService<TAuth extends BetterAuthInstance = BetterAuthInstance> {\n #cached: TAuth | undefined;\n\n readonly #build: () => TAuth;\n\n constructor(@Inject(BETTER_AUTH_BUILDER) build: () => TAuth) {\n this.#build = build;\n }\n\n /**\n * The underlying better-auth instance. Constructed once on first access.\n * Safe to call from any request-time code path (guards, controllers,\n * services invoked from handlers).\n */\n get auth(): TAuth {\n if (!this.#cached) this.#cached = this.#build();\n return this.#cached;\n }\n\n /** Convenience accessor — equivalent to `service.auth.api`. */\n get api(): TAuth['api'] {\n return this.auth.api;\n }\n\n /** Convenience accessor — equivalent to `service.auth.handler`. */\n get handler(): TAuth['handler'] {\n return this.auth.handler;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,MAAa,sBAAsB,IAAI,eACrC,0BACF;AAoBO,IAAM,oBAAN,MAAM,kBAAyE;CACpF;CAEA;CAEA,YAAY,OAAiD;EAC3D,KAAK,SAAS;CAChB;;;;;;CAOA,IAAI,OAAc;EAChB,IAAI,CAAC,KAAK,SAAS,KAAK,UAAU,KAAK,OAAO;EAC9C,OAAO,KAAK;CACd;;CAGA,IAAI,MAAoB;EACtB,OAAO,KAAK,KAAK;CACnB;;CAGA,IAAI,UAA4B;EAC9B,OAAO,KAAK,KAAK;CACnB;AACF;;CA7BC,WAAW;CAMG,gBAAA,GAAA,OAAO,mBAAmB,CAAA"}
1
+ {"version":3,"file":"better-auth.service-SNg1YFTK.js","names":[],"sources":["../src/better-auth.service.ts"],"sourcesContent":["import { Inject, Injectable, InjectionToken } from '@velajs/vela';\nimport type { BetterAuthInstance } from './better-auth.types';\n\n/**\n * Internal token holding the auth-construction closure with its inject deps\n * closed over. Resolves cheaply at module load (just captures references);\n * the inner call happens lazily on first auth use (see `BetterAuthService`).\n *\n * Not exported from the public surface — only the service consumes it.\n */\nexport const BETTER_AUTH_BUILDER = new InjectionToken<() => BetterAuthInstance>(\n 'vela.better-auth.Builder',\n);\n\n/**\n * The single injectable consumers reach for to interact with better-auth.\n * Wraps the underlying `betterAuth({...})` instance with lazy construction:\n *\n * - `auth` is an instance — the builder returns it, so the first `.auth` /\n * `.api` / `.handler` access is effectively a read-and-cache.\n * - `auth` is a function (`auth: () => betterAuth({ ... })`, typically\n * returned by a `forRootAsync` factory) — the first access calls it. On\n * Workers, construction then happens on the first request (when AuthGuard\n * or the catch-all calls `service.api` / `service.handler`), never at\n * bootstrap.\n *\n * Used directly by AuthGuard and the catch-all controller. Consumers in\n * application code inject the same way: `@Inject(BetterAuthService)`.\n */\n@Injectable()\nexport class BetterAuthService<TAuth extends BetterAuthInstance = BetterAuthInstance> {\n #cached: TAuth | undefined;\n\n readonly #build: () => TAuth;\n\n constructor(@Inject(BETTER_AUTH_BUILDER) build: () => TAuth) {\n this.#build = build;\n }\n\n /**\n * The underlying better-auth instance. Constructed once on first access.\n * Safe to call from any request-time code path (guards, controllers,\n * services invoked from handlers).\n */\n get auth(): TAuth {\n if (!this.#cached) this.#cached = this.#build();\n return this.#cached;\n }\n\n /** Convenience accessor — equivalent to `service.auth.api`. */\n get api(): TAuth['api'] {\n return this.auth.api;\n }\n\n /** Convenience accessor — equivalent to `service.auth.handler`. */\n get handler(): TAuth['handler'] {\n return this.auth.handler;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,MAAa,sBAAsB,IAAI,eACrC,0BACF;AAkBO,IAAM,oBAAN,MAAM,kBAAyE;CACpF;CAEA;CAEA,YAAY,OAAiD;EAC3D,KAAK,SAAS;CAChB;;;;;;CAOA,IAAI,OAAc;EAChB,IAAI,CAAC,KAAK,SAAS,KAAK,UAAU,KAAK,OAAO;EAC9C,OAAO,KAAK;CACd;;CAGA,IAAI,MAAoB;EACtB,OAAO,KAAK,KAAK;CACnB;;CAGA,IAAI,UAA4B;EAC9B,OAAO,KAAK,KAAK;CACnB;AACF;;CA7BC,WAAW;CAMG,gBAAA,GAAA,OAAO,mBAAmB,CAAA"}
package/dist/index.d.ts CHANGED
@@ -1,57 +1,29 @@
1
- import { a as Session, i as BetterAuthRuntimeOptions, n as BetterAuthInstance, o as User, r as BetterAuthModuleOptions, t as BetterAuthService } from "./better-auth.service-CvmboUID.js";
2
- import { CanActivate, DynamicModule, ExecutionContext, InjectionToken, Reflector, Token, Type } from "@velajs/vela";
3
- import { FactoryInject, InferTokens } from "@velajs/vela/module-kit";
1
+ import { a as BetterAuthStructuralOption, i as BetterAuthRuntimeOptions, n as BetterAuthInstance, o as Session, r as BetterAuthModuleOptions, s as User, t as BetterAuthService } from "./better-auth.service-D_G-PP8p.js";
2
+ import { CanActivate, ExecutionContext, GuardPhase, InjectionToken, Reflector, Type } from "@velajs/vela";
4
3
  import { UpgradeAuthenticator, WebSocketUpgradeAuthenticationContext, WebSocketUpgradeIdentity } from "@velajs/vela/websocket";
5
4
  import { Identity, PermissionResolver } from "@velajs/authz";
6
5
  //#region src/better-auth.module.d.ts
6
+ declare const ConfigurableModuleClass: import("@velajs/vela").ConfigurableModuleClassType<BetterAuthModuleOptions<BetterAuthInstance>, "forRoot", "create", {
7
+ isGlobal?: boolean;
8
+ }, BetterAuthStructuralOption>;
7
9
  /**
8
- * Options for {@link BetterAuthModule.forRootAsync}.
9
- *
10
- * The `Inject` type parameter captures the literal `inject` tuple at the call
11
- * site (via `const` inference) so `useFactory` parameters are typed from the
12
- * inject array, position-by-position — no `as const`, no `(...deps: any[])`:
10
+ * better-auth for Vela: `BetterAuthService`, the catch-all handler under
11
+ * `basePath`, and an injectable `AuthGuard`. Applications install it through `APP_GUARD`
12
+ * with `useExisting: AuthGuard`, or attach it with `@UseGuards`.
13
13
  *
14
14
  * ```ts
15
+ * BetterAuthModule.forRoot({ auth: betterAuth({ ... }) });
15
16
  * BetterAuthModule.forRootAsync({
16
- * inject: [ENV, ConfigService], // captured as readonly tuple
17
- * useFactory: (env, config) => // inferred from the tokens
18
- * betterAuth({ database: drizzleAdapter(drizzle(env.DB), ...) }),
17
+ * inject: [ENV],
18
+ * useFactory: (env) => ({ auth: () => betterAuth({ database: env.DB }), issuer: 'accounts' }),
19
19
  * });
20
20
  * ```
21
21
  *
22
- * A factory without parameters may omit `inject`.
22
+ * `basePath` and `mountHandler` are structural: `forRootAsync`
23
+ * takes them alongside the factory. The factory runs when the application
24
+ * initializes; an `auth` function it returns runs on first authentication.
23
25
  */
24
- type ForRootAsyncOptions<Inject extends readonly Token[] = readonly Token[]> = {
25
- imports?: DynamicModule['imports'];
26
- useFactory: (...deps: InferTokens<Inject>) => BetterAuthInstance;
27
- isGlobal?: boolean;
28
- mountHandler?: boolean;
29
- basePath?: string;
30
- issuer?: string;
31
- key?: string;
32
- } & FactoryInject<Inject>;
33
- export declare class BetterAuthModule {
34
- /**
35
- * Synchronous registration. The auth instance is constructed by the consumer
36
- * at module-load time and passed in directly. Use this when the inputs to
37
- * `betterAuth({...})` are available at startup (Node apps with a static DB
38
- * connection, in-memory adapters, etc.).
39
- */
40
- static forRoot(options: BetterAuthModuleOptions & {
41
- isGlobal?: boolean;
42
- key?: string;
43
- }): DynamicModule;
44
- /**
45
- * Deferred / DI-driven registration. The user factory runs **lazily**, on the
46
- * first time anything reads `BetterAuthService.auth` (or `.api` / `.handler`).
47
- * In normal request handling that's `AuthGuard.canActivate` or the catch-all
48
- * controller's `.handle`. At module load the factory does NOT run — it's only
49
- * captured in the checked builder provider. The Workers adapter supplies its
50
- * native environment before DI; the lazily constructed auth instance belongs
51
- * to that environment's application and never captures another app's bindings.
52
- */
53
- static forRootAsync<const Inject extends readonly Token[] = readonly Token[]>(options: ForRootAsyncOptions<Inject>): DynamicModule;
54
- }
26
+ export declare class BetterAuthModule extends ConfigurableModuleClass {}
55
27
  //#endregion
56
28
  //#region src/better-auth.controller.d.ts
57
29
  /**
@@ -59,6 +31,7 @@ export declare class BetterAuthModule {
59
31
  * (default `/api/auth`). This is a factory because vela reads a controller's
60
32
  * route off the class at decoration time, so a custom base path needs its own
61
33
  * decorated class — the path can't be parametrized on a single shared class.
34
+ * Calls with the same base path return the same class.
62
35
  *
63
36
  * Two base paths to keep consistent:
64
37
  * - this `basePath` is RELATIVE to vela's `globalPrefix` (always prepended);
@@ -77,6 +50,8 @@ export declare class AuthGuard implements CanActivate {
77
50
  private readonly auth;
78
51
  private readonly opts;
79
52
  private readonly reflector;
53
+ /** Global guards run authentication first, then tenant, authorization and feature phases. */
54
+ static readonly phase: GuardPhase;
80
55
  constructor(auth: BetterAuthService, opts: BetterAuthRuntimeOptions, reflector: Reflector);
81
56
  canActivate(context: ExecutionContext): Promise<boolean>;
82
57
  }
@@ -122,11 +97,11 @@ export declare const CurrentUser: (data?: unknown, ...pipes: import("@velajs/vel
122
97
  export declare const CurrentSession: (data?: unknown, ...pipes: import("@velajs/vela/module-kit").PipeType[]) => ParameterDecorator;
123
98
  //#endregion
124
99
  //#region src/decorators/public.decorator.d.ts
125
- export declare const Public: import("@velajs/vela").ReflectableDecorator<boolean>;
100
+ export declare const Public: import("@velajs/vela").ReflectableDecorator<boolean, boolean>;
126
101
  export declare const PUBLIC_KEY: string;
127
102
  //#endregion
128
103
  //#region src/decorators/optional-auth.decorator.d.ts
129
- export declare const OptionalAuth: import("@velajs/vela").ReflectableDecorator<boolean>;
104
+ export declare const OptionalAuth: import("@velajs/vela").ReflectableDecorator<boolean, boolean>;
130
105
  export declare const OPTIONAL_AUTH_KEY: string;
131
106
  //#endregion
132
107
  //#region src/authz-bridge.d.ts
@@ -143,7 +118,7 @@ export declare const BETTER_AUTH_ISSUER = "better-auth";
143
118
  /**
144
119
  * Pure authorization projection; this does not authenticate or publish trusted state.
145
120
  * Adapts an already verified better-auth user into a stable `@velajs/authz` {@link Identity}.
146
- * The issuer scopes `user.id` as both `subject` and the compatibility `userId`;
121
+ * The issuer scopes `user.id` as the `subject`;
147
122
  * the admin-plugin `role` field supplies local roles.
148
123
  *
149
124
  * Fail-closed: a missing user (`null`/`undefined`, i.e. an unauthenticated
@@ -184,5 +159,5 @@ export declare const permissionsFromAcRole: (role: BetterAuthAcRole) => string[]
184
159
  */
185
160
  export declare const betterAuthAcResolver: (roles: Readonly<Record<string, BetterAuthAcRole>>) => PermissionResolver;
186
161
  //#endregion
187
- export { type AuthUser, type BetterAuthAcRole, type BetterAuthInstance, type BetterAuthModuleOptions, type BetterAuthRuntimeOptions, BetterAuthService, type BetterAuthUpgradeSession, type BetterAuthUpgradeTenantResolver, type Session, type User };
162
+ export { type AuthUser, type BetterAuthAcRole, type BetterAuthInstance, type BetterAuthModuleOptions, type BetterAuthRuntimeOptions, BetterAuthService, type BetterAuthStructuralOption, type BetterAuthUpgradeSession, type BetterAuthUpgradeTenantResolver, type Session, type User };
188
163
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,10 +1,13 @@
1
1
  import { a as __decorateMetadata, i as __decorateParam, n as BetterAuthService, r as __decorate, t as BETTER_AUTH_BUILDER } from "./better-auth.service-SNg1YFTK.js";
2
- import { All, Controller, Inject, Injectable, InjectionToken, Optional, Reflector, Req, UnauthorizedException, createParamDecorator, defineProvider } from "@velajs/vela";
3
- import { clearTrustedRequestIdentity, createTrustedRequestIdentityStore, getTrustedContextRequest, lazyProvider, provideGlobal, setTrustedRequestIdentity, stableHash } from "@velajs/vela/module-kit";
2
+ import { All, Controller, Inject, Injectable, InjectionToken, Optional, Reflector, Req, UnauthorizedException, createParamDecorator, defineModule, defineProvider } from "@velajs/vela";
3
+ import { SkipGuardPhases, clearTrustedRequestIdentity, createTrustedRequestIdentityStore, getTrustedContextRequest, setTrustedRequestIdentity } from "@velajs/vela/module-kit";
4
4
  import { getContextIdentity } from "@velajs/authz/vela";
5
5
  //#region src/decorators/public.decorator.ts
6
6
  const Public = Reflector.createDecorator({ key: "vela.auth.public" });
7
7
  const PUBLIC_KEY = Public.KEY;
8
+ //#endregion
9
+ //#region src/base-path.ts
10
+ const DEFAULT_BETTER_AUTH_BASE_PATH = "/api/auth";
8
11
  /** Validate and canonicalize the route prefix used by the public auth controller. */
9
12
  function normalizeBetterAuthBasePath(value) {
10
13
  const basePath = value ?? "/api/auth";
@@ -20,11 +23,13 @@ function normalizeBetterAuthBasePath(value) {
20
23
  }
21
24
  //#endregion
22
25
  //#region src/better-auth.controller.ts
26
+ const controllers = /* @__PURE__ */ new Map();
23
27
  /**
24
28
  * Build a catch-all controller that mounts better-auth's handler at `basePath`
25
29
  * (default `/api/auth`). This is a factory because vela reads a controller's
26
30
  * route off the class at decoration time, so a custom base path needs its own
27
31
  * decorated class — the path can't be parametrized on a single shared class.
32
+ * Calls with the same base path return the same class.
28
33
  *
29
34
  * Two base paths to keep consistent:
30
35
  * - this `basePath` is RELATIVE to vela's `globalPrefix` (always prepended);
@@ -35,28 +40,32 @@ function normalizeBetterAuthBasePath(value) {
35
40
  */
36
41
  function createBetterAuthCatchallController(basePath = "/api/auth") {
37
42
  const normalizedBasePath = normalizeBetterAuthBasePath(basePath);
43
+ const existing = controllers.get(normalizedBasePath);
44
+ if (existing) return existing;
38
45
  let BetterAuthCatchallController = class BetterAuthCatchallController {
39
46
  auth;
40
47
  constructor(auth) {
41
48
  this.auth = auth;
42
49
  }
43
- async handle(c) {
44
- return this.auth.handler(c.req.raw);
50
+ async handle(request) {
51
+ return this.auth.handler(request);
45
52
  }
46
53
  };
47
54
  __decorate([
48
55
  All("/*"),
49
56
  __decorateParam(0, Req()),
50
57
  __decorateMetadata("design:type", Function),
51
- __decorateMetadata("design:paramtypes", [Object]),
58
+ __decorateMetadata("design:paramtypes", [typeof Request === "undefined" ? Object : Request]),
52
59
  __decorateMetadata("design:returntype", Promise)
53
60
  ], BetterAuthCatchallController.prototype, "handle", null);
54
61
  BetterAuthCatchallController = __decorate([
55
62
  Public(true),
63
+ SkipGuardPhases(["tenant", "authorize"]),
56
64
  Controller(normalizedBasePath),
57
65
  __decorateParam(0, Inject(BetterAuthService)),
58
66
  __decorateMetadata("design:paramtypes", [typeof BetterAuthService === "undefined" ? Object : BetterAuthService])
59
67
  ], BetterAuthCatchallController);
68
+ controllers.set(normalizedBasePath, BetterAuthCatchallController);
60
69
  return BetterAuthCatchallController;
61
70
  }
62
71
  //#endregion
@@ -175,6 +184,8 @@ let AuthGuard = class AuthGuard {
175
184
  auth;
176
185
  opts;
177
186
  reflector;
187
+ /** Global guards run authentication first, then tenant, authorization and feature phases. */
188
+ static phase = "authenticate";
178
189
  constructor(auth, opts, reflector) {
179
190
  this.auth = auth;
180
191
  this.opts = opts;
@@ -213,110 +224,75 @@ AuthGuard = __decorate([
213
224
  ], AuthGuard);
214
225
  //#endregion
215
226
  //#region src/better-auth.module.ts
216
- const referenceIds = /* @__PURE__ */ new WeakMap();
217
- let nextReferenceId = 1;
218
- function referenceId(reference) {
219
- const existing = referenceIds.get(reference);
220
- if (existing !== void 0) return existing;
221
- const id = nextReferenceId++;
222
- referenceIds.set(reference, id);
223
- return id;
224
- }
225
- /**
226
- * An explicit key names a registration without widening its identity: the
227
- * options shape and auth reference stay in the module key, so the same
228
- * registration deduplicates within an application while a different one
229
- * (including a root rebuilt per environment) becomes its own instance. No
230
- * process-wide state is kept, so repeated bootstraps in one isolate succeed.
231
- */
232
- function explicitKey(key, shape, reference) {
233
- if (key.length === 0 || key !== key.trim()) throw new Error("@velajs/better-auth: an explicit module key must be a non-empty string");
234
- return `explicit:${key}:${shape}:ref:${referenceId(reference)}`;
235
- }
236
- function normalize(options) {
227
+ const MODULE_OPTIONS = new InjectionToken("vela.better-auth.ModuleOptions");
228
+ /** Runtime options with defaults applied: what AuthGuard and the upgrade authenticator read. */
229
+ function runtimeOptions(options) {
230
+ const auth = options.auth;
231
+ if (typeof auth !== "function" && (typeof auth !== "object" || auth === null)) throw new TypeError("@velajs/better-auth: options need `auth`, a better-auth instance or a function that builds one");
237
232
  const basePath = normalizeBetterAuthBasePath(options.basePath);
238
233
  const issuer = options.issuer ?? `better-auth:${basePath}`;
239
234
  if (issuer.length === 0 || issuer !== issuer.trim()) throw new Error("@velajs/better-auth: issuer must be a non-empty stable namespace");
240
235
  return {
241
236
  basePath,
242
237
  issuer,
243
- isGlobal: options.isGlobal ?? true,
244
238
  mountHandler: options.mountHandler ?? true
245
239
  };
246
240
  }
247
- /** Providers, controllers, and exports shared by both entry points. */
248
- function commonContributions(n) {
249
- return {
250
- providers: [BetterAuthService, AuthGuard],
251
- controllers: n.mountHandler ? [createBetterAuthCatchallController(n.basePath)] : [],
252
- exports: [
253
- BetterAuthService,
254
- BETTER_AUTH_OPTIONS,
255
- AuthGuard
256
- ]
257
- };
241
+ /** The instance itself, or the one its builder function returns. */
242
+ function buildAuth(auth) {
243
+ return typeof auth === "function" ? auth() : auth;
258
244
  }
259
- var BetterAuthModule = class BetterAuthModule {
260
- /**
261
- * Synchronous registration. The auth instance is constructed by the consumer
262
- * at module-load time and passed in directly. Use this when the inputs to
263
- * `betterAuth({...})` are available at startup (Node apps with a static DB
264
- * connection, in-memory adapters, etc.).
265
- */
266
- static forRoot(options) {
267
- const normalized = normalize(options);
268
- const shape = stableHash(normalized);
269
- const key = options.key === void 0 ? `${shape}:auth:${referenceId(options.auth)}` : explicitKey(options.key, shape, options.auth);
270
- const common = commonContributions(normalized);
271
- return {
272
- module: BetterAuthModule,
273
- key,
274
- providers: [
275
- defineProvider(BETTER_AUTH_OPTIONS, { useValue: normalized }),
276
- defineProvider(BETTER_AUTH_BUILDER, { useValue: () => options.auth }),
277
- ...common.providers,
278
- ...normalized.isGlobal ? provideGlobal("guard", AuthGuard) : []
279
- ],
280
- controllers: common.controllers,
281
- exports: common.exports
282
- };
283
- }
284
- /**
285
- * Deferred / DI-driven registration. The user factory runs **lazily**, on the
286
- * first time anything reads `BetterAuthService.auth` (or `.api` / `.handler`).
287
- * In normal request handling that's `AuthGuard.canActivate` or the catch-all
288
- * controller's `.handle`. At module load the factory does NOT run — it's only
289
- * captured in the checked builder provider. The Workers adapter supplies its
290
- * native environment before DI; the lazily constructed auth instance belongs
291
- * to that environment's application and never captures another app's bindings.
292
- */
293
- static forRootAsync(options) {
294
- const n = normalize(options);
295
- const common = commonContributions(n);
296
- const shape = stableHash({
297
- ...n,
298
- inject: options.inject
299
- });
300
- const key = options.key === void 0 ? `${shape}:factory:${referenceId(options.useFactory)}` : explicitKey(options.key, shape, options.useFactory);
245
+ const { ConfigurableModuleClass } = defineModule({
246
+ name: "BetterAuth",
247
+ optionsToken: MODULE_OPTIONS,
248
+ structural: ["basePath", "mountHandler"],
249
+ defaults: {
250
+ basePath: DEFAULT_BETTER_AUTH_BASE_PATH,
251
+ mountHandler: true
252
+ },
253
+ setup: ({ OPTIONS, options }) => {
254
+ const basePath = normalizeBetterAuthBasePath(options.basePath);
255
+ const controllers = options.mountHandler === false ? [] : [createBetterAuthCatchallController(basePath)];
301
256
  return {
302
- module: BetterAuthModule,
303
- key,
304
- imports: options.imports ?? [],
305
257
  providers: [
306
- defineProvider(BETTER_AUTH_OPTIONS, { useValue: n }),
307
- lazyProvider({
308
- ...options,
309
- provide: BETTER_AUTH_BUILDER,
310
- memoize: false
258
+ defineProvider(BETTER_AUTH_OPTIONS, {
259
+ useFactory: (resolved) => runtimeOptions(resolved),
260
+ inject: [OPTIONS]
261
+ }),
262
+ defineProvider(BETTER_AUTH_BUILDER, {
263
+ useFactory: (resolved) => () => buildAuth(resolved.auth),
264
+ inject: [OPTIONS]
311
265
  }),
312
- ...common.providers,
313
- ...n.isGlobal ? provideGlobal("guard", AuthGuard) : []
266
+ BetterAuthService,
267
+ AuthGuard
314
268
  ],
315
- controllers: common.controllers,
316
- exports: common.exports
269
+ controllers,
270
+ exports: [
271
+ BetterAuthService,
272
+ BETTER_AUTH_OPTIONS,
273
+ AuthGuard
274
+ ]
317
275
  };
318
276
  }
319
- };
277
+ });
278
+ /**
279
+ * better-auth for Vela: `BetterAuthService`, the catch-all handler under
280
+ * `basePath`, and an injectable `AuthGuard`. Applications install it through `APP_GUARD`
281
+ * with `useExisting: AuthGuard`, or attach it with `@UseGuards`.
282
+ *
283
+ * ```ts
284
+ * BetterAuthModule.forRoot({ auth: betterAuth({ ... }) });
285
+ * BetterAuthModule.forRootAsync({
286
+ * inject: [ENV],
287
+ * useFactory: (env) => ({ auth: () => betterAuth({ database: env.DB }), issuer: 'accounts' }),
288
+ * });
289
+ * ```
290
+ *
291
+ * `basePath` and `mountHandler` are structural: `forRootAsync`
292
+ * takes them alongside the factory. The factory runs when the application
293
+ * initializes; an `auth` function it returns runs on first authentication.
294
+ */
295
+ var BetterAuthModule = class extends ConfigurableModuleClass {};
320
296
  //#endregion
321
297
  //#region src/upgrade-authenticator.ts
322
298
  /**
@@ -387,7 +363,7 @@ const normalizeRoles = (role) => {
387
363
  /**
388
364
  * Pure authorization projection; this does not authenticate or publish trusted state.
389
365
  * Adapts an already verified better-auth user into a stable `@velajs/authz` {@link Identity}.
390
- * The issuer scopes `user.id` as both `subject` and the compatibility `userId`;
366
+ * The issuer scopes `user.id` as the `subject`;
391
367
  * the admin-plugin `role` field supplies local roles.
392
368
  *
393
369
  * Fail-closed: a missing user (`null`/`undefined`, i.e. an unauthenticated
@@ -401,7 +377,6 @@ const identityFromUser = (user, issuer = BETTER_AUTH_ISSUER, principalType = "us
401
377
  issuer,
402
378
  subject: user.id,
403
379
  principalType,
404
- userId: user.id,
405
380
  roles: normalizeRoles(user.role)
406
381
  };
407
382
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/decorators/public.decorator.ts","../src/base-path.ts","../src/better-auth.controller.ts","../src/better-auth.tokens.ts","../src/auth-request-state.ts","../src/session-data.ts","../src/decorators/optional-auth.decorator.ts","../src/guards/auth.guard.ts","../src/better-auth.module.ts","../src/upgrade-authenticator.ts","../src/decorators/current-user.decorator.ts","../src/decorators/current-session.decorator.ts","../src/authz-bridge.ts"],"sourcesContent":["import { Reflector } from '@velajs/vela';\n\nexport const Public = Reflector.createDecorator<boolean>({ key: 'vela.auth.public' });\nexport const PUBLIC_KEY = Public.KEY;\n","export const DEFAULT_BETTER_AUTH_BASE_PATH = '/api/auth';\n\n/** Validate and canonicalize the route prefix used by the public auth controller. */\nexport function normalizeBetterAuthBasePath(value?: string): string {\n const basePath = value ?? DEFAULT_BETTER_AUTH_BASE_PATH;\n if (\n basePath.length === 0 ||\n basePath !== basePath.trim() ||\n !basePath.startsWith('/') ||\n basePath.startsWith('//') ||\n basePath === '/' ||\n basePath.endsWith('/') ||\n /[\\\\?#*]/u.test(basePath) ||\n /%(?:2e|2f|5c)/iu.test(basePath)\n ) {\n throw new Error(\n '@velajs/better-auth: basePath must be a canonical absolute path such as \"/api/auth\"',\n );\n }\n\n let decoded: string;\n try {\n decoded = decodeURIComponent(basePath);\n } catch {\n throw new Error('@velajs/better-auth: basePath contains invalid percent encoding');\n }\n if (decoded.split('/').some((segment) => segment === '.' || segment === '..')) {\n throw new Error('@velajs/better-auth: basePath must not contain dot segments');\n }\n return basePath;\n}\n","import { All, Controller, Inject, Req, type Type } from '@velajs/vela';\nimport type { Context } from 'hono';\nimport { BetterAuthService } from './better-auth.service';\nimport { Public } from './decorators/public.decorator';\nimport { normalizeBetterAuthBasePath } from './base-path';\n\n/**\n * Build a catch-all controller that mounts better-auth's handler at `basePath`\n * (default `/api/auth`). This is a factory because vela reads a controller's\n * route off the class at decoration time, so a custom base path needs its own\n * decorated class — the path can't be parametrized on a single shared class.\n *\n * Two base paths to keep consistent:\n * - this `basePath` is RELATIVE to vela's `globalPrefix` (always prepended);\n * - better-auth routes against its OWN absolute `basePath` (the one you pass to\n * `betterAuth({ basePath })`), which must equal `globalPrefix + basePath`.\n *\n * Both default to `/api/auth`, so the no-prefix / no-config case just works.\n */\nexport function createBetterAuthCatchallController(basePath: string = '/api/auth'): Type {\n const normalizedBasePath = normalizeBetterAuthBasePath(basePath);\n @Public(true)\n @Controller(normalizedBasePath)\n class BetterAuthCatchallController {\n // Inject the service — its `.handler` getter triggers lazy construction\n // of the underlying betterAuth() instance on first access, AFTER any\n // runtime adapter middleware (Cloudflare env capture) has run.\n constructor(@Inject(BetterAuthService) private readonly auth: BetterAuthService) {}\n\n @All('/*')\n async handle(@Req() c: Context): Promise<Response> {\n return this.auth.handler(c.req.raw);\n }\n }\n return BetterAuthCatchallController;\n}\n","import { InjectionToken } from '@velajs/vela';\nimport type { BetterAuthRuntimeOptions } from './better-auth.types';\n\nexport const BETTER_AUTH_OPTIONS = new InjectionToken<BetterAuthRuntimeOptions>(\n 'vela.BetterAuthOptions',\n);\n","import type { ExecutionContext } from '@velajs/vela';\nimport {\n clearTrustedRequestIdentity,\n createTrustedRequestIdentityStore,\n getTrustedContextRequest,\n setTrustedRequestIdentity,\n} from '@velajs/vela/module-kit';\nimport type { SessionData } from './session-data';\n\n// This map stores provider payload, never a second authentication authority.\n// A clear, expiry, or identity replacement makes the payload unreachable.\nconst sessions = createTrustedRequestIdentityStore<SessionData>();\n\nexport function beginAuthRequest(context: ExecutionContext): void {\n clearTrustedRequestIdentity(context.getRequest());\n}\n\nexport function authenticateRequest(\n context: ExecutionContext,\n data: SessionData,\n issuer: string,\n): void {\n const request = context.getRequest();\n setTrustedRequestIdentity(request, {\n principal: { issuer, subject: data.user.id, principalType: 'user' },\n expiresAtMs: data.session.expiresAt.getTime(),\n roles: data.roles,\n ...(data.tenantId === undefined ? {} : { tenantId: data.tenantId }),\n });\n sessions.set(request, data);\n}\n\nexport function getAuthRequestState(context: ExecutionContext): SessionData | undefined {\n const request = getTrustedContextRequest(context);\n return request ? sessions.get(request) : undefined;\n}\n","import type { Session, User } from './better-auth.types';\n\nexport interface SessionData {\n readonly user: User;\n readonly session: Session;\n readonly roles: readonly string[];\n readonly tenantId?: string;\n}\n\nfunction own(value: unknown, key: string): unknown {\n if (typeof value !== 'object' || value === null) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n return descriptor && 'value' in descriptor ? descriptor.value : undefined;\n}\n\nfunction requiredString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n\nfunction date(value: unknown): Date | undefined {\n return value instanceof Date && Number.isFinite(value.getTime()) ? new Date(value) : undefined;\n}\n\nfunction optionalString(value: unknown): value is string | null | undefined {\n return value === undefined || value === null || typeof value === 'string';\n}\n\n/** Keep plugin data opaque; base model fields below are validated individually. */\nfunction dataProperties(value: object): Record<string, unknown> {\n return Object.fromEntries(Object.keys(value).map((key) => [key, own(value, key)]));\n}\n\n/** Validate the full Better Auth base models, not merely ids masquerading as them. */\nexport function validateSessionData(value: unknown): SessionData | undefined {\n try {\n const user = own(value, 'user');\n const session = own(value, 'session');\n if (\n typeof user !== 'object' ||\n user === null ||\n typeof session !== 'object' ||\n session === null\n ) {\n return undefined;\n }\n const id = own(user, 'id');\n const email = own(user, 'email');\n const name = own(user, 'name');\n const emailVerified = own(user, 'emailVerified');\n const image = own(user, 'image');\n const createdAt = date(own(user, 'createdAt'));\n const updatedAt = date(own(user, 'updatedAt'));\n const sessionId = own(session, 'id');\n const userId = own(session, 'userId');\n const token = own(session, 'token');\n const sessionCreatedAt = date(own(session, 'createdAt'));\n const sessionUpdatedAt = date(own(session, 'updatedAt'));\n const expiresAt = date(own(session, 'expiresAt'));\n const ipAddress = own(session, 'ipAddress');\n const userAgent = own(session, 'userAgent');\n const organization = own(session, 'activeOrganizationId');\n const role = own(user, 'role');\n let roles: string[] = [];\n if (role !== undefined && role !== null) {\n if (typeof role === 'string')\n roles = role\n .split(',')\n .map((part) => part.trim())\n .filter(Boolean);\n else if (\n Array.isArray(role) &&\n role.every((entry: unknown): entry is string => typeof entry === 'string')\n ) {\n roles = role.map((entry: string) => entry.trim()).filter(Boolean);\n } else return undefined;\n }\n if (\n !requiredString(id) ||\n !requiredString(email) ||\n typeof name !== 'string' ||\n typeof emailVerified !== 'boolean' ||\n !optionalString(image) ||\n !createdAt ||\n !updatedAt ||\n !requiredString(sessionId) ||\n userId !== id ||\n !requiredString(token) ||\n !sessionCreatedAt ||\n !sessionUpdatedAt ||\n !expiresAt ||\n expiresAt.getTime() <= Date.now() ||\n !optionalString(ipAddress) ||\n !optionalString(userAgent) ||\n (organization !== undefined && organization !== null && !requiredString(organization))\n )\n return undefined;\n return {\n user: Object.freeze({\n ...dataProperties(user),\n id,\n email,\n name,\n emailVerified,\n createdAt,\n updatedAt,\n image,\n }),\n session: Object.freeze({\n ...dataProperties(session),\n id: sessionId,\n userId: id,\n token,\n createdAt: sessionCreatedAt,\n updatedAt: sessionUpdatedAt,\n expiresAt,\n ipAddress,\n userAgent,\n }),\n roles: Object.freeze(roles),\n ...(typeof organization === 'string' ? { tenantId: organization } : {}),\n };\n } catch {\n return undefined;\n }\n}\n","import { Reflector } from '@velajs/vela';\n\nexport const OptionalAuth = Reflector.createDecorator<boolean>({ key: 'vela.auth.optional' });\nexport const OPTIONAL_AUTH_KEY = OptionalAuth.KEY;\n","import {\n Inject,\n Injectable,\n Reflector,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n} from '@velajs/vela';\nimport { getTrustedContextRequest } from '@velajs/vela/module-kit';\nimport { getContextIdentity } from '@velajs/authz/vela';\nimport { BETTER_AUTH_OPTIONS } from '../better-auth.tokens';\nimport { BetterAuthService } from '../better-auth.service';\nimport type { BetterAuthRuntimeOptions } from '../better-auth.types';\nimport { authenticateRequest, beginAuthRequest, getAuthRequestState } from '../auth-request-state';\nimport { validateSessionData } from '../session-data';\nimport { OptionalAuth } from '../decorators/optional-auth.decorator';\nimport { Public } from '../decorators/public.decorator';\n\n@Injectable()\nexport class AuthGuard implements CanActivate {\n constructor(\n @Inject(BetterAuthService) private readonly auth: BetterAuthService,\n @Inject(BETTER_AUTH_OPTIONS) private readonly opts: BetterAuthRuntimeOptions,\n @Inject(Reflector) private readonly reflector: Reflector,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n // Frames trust only the authenticated connection attachment; HTTP cookies\n // and request payload never become ambient WebSocket authentication.\n if (context.getType() === 'ws') {\n if (getContextIdentity(context)) return true;\n throw new UnauthorizedException('Authentication required');\n }\n // Custom HTTP-backed dispatchers authenticate once at the outer boundary.\n // Never re-read credentials or clear shared authority across sibling fields.\n if (context.getType() !== 'http') {\n if (\n getTrustedContextRequest(context) &&\n (getAuthRequestState(context) ||\n this.reflector.getAllAndOverride(Public, context) ||\n this.reflector.getAllAndOverride(OptionalAuth, context))\n )\n return true;\n throw new UnauthorizedException('Authentication required');\n }\n beginAuthRequest(context);\n if (this.reflector.getAllAndOverride(Public, context)) return true;\n\n const raw = await this.auth.api.getSession({ headers: context.getRequest().headers });\n const data = validateSessionData(raw);\n if (data) {\n authenticateRequest(context, data, this.opts.issuer ?? 'better-auth');\n return true;\n }\n if (this.reflector.getAllAndOverride(OptionalAuth, context)) return true;\n throw new UnauthorizedException('Authentication required');\n }\n}\n","import { defineProvider, type DynamicModule, type Token, type Type } from '@velajs/vela';\nimport {\n lazyProvider,\n provideGlobal,\n stableHash,\n type FactoryInject,\n type InferTokens,\n} from '@velajs/vela/module-kit';\nimport { createBetterAuthCatchallController } from './better-auth.controller';\nimport { BetterAuthService, BETTER_AUTH_BUILDER } from './better-auth.service';\nimport { BETTER_AUTH_OPTIONS } from './better-auth.tokens';\nimport type {\n BetterAuthInstance,\n BetterAuthModuleOptions,\n BetterAuthRuntimeOptions,\n} from './better-auth.types';\nimport { AuthGuard } from './guards/auth.guard';\nimport { normalizeBetterAuthBasePath } from './base-path';\n\nconst referenceIds = new WeakMap<object, number>();\nlet nextReferenceId = 1;\n\nfunction referenceId(reference: object): number {\n const existing = referenceIds.get(reference);\n if (existing !== undefined) return existing;\n const id = nextReferenceId++;\n referenceIds.set(reference, id);\n return id;\n}\n\n/**\n * An explicit key names a registration without widening its identity: the\n * options shape and auth reference stay in the module key, so the same\n * registration deduplicates within an application while a different one\n * (including a root rebuilt per environment) becomes its own instance. No\n * process-wide state is kept, so repeated bootstraps in one isolate succeed.\n */\nfunction explicitKey(key: string, shape: string, reference: object): string {\n if (key.length === 0 || key !== key.trim()) {\n throw new Error('@velajs/better-auth: an explicit module key must be a non-empty string');\n }\n return `explicit:${key}:${shape}:ref:${referenceId(reference)}`;\n}\n\n/** Structural options with defaults applied (everything but the auth instance). */\ninterface NormalizedOptions {\n basePath: string;\n issuer: string;\n isGlobal: boolean;\n mountHandler: boolean;\n}\n\nfunction normalize(options: BetterAuthRuntimeOptions): NormalizedOptions {\n const basePath = normalizeBetterAuthBasePath(options.basePath);\n const issuer = options.issuer ?? `better-auth:${basePath}`;\n if (issuer.length === 0 || issuer !== issuer.trim()) {\n throw new Error('@velajs/better-auth: issuer must be a non-empty stable namespace');\n }\n return {\n basePath,\n issuer,\n isGlobal: options.isGlobal ?? true,\n mountHandler: options.mountHandler ?? true,\n };\n}\n\n/** Providers, controllers, and exports shared by both entry points. */\nfunction commonContributions(n: NormalizedOptions): {\n providers: NonNullable<DynamicModule['providers']>;\n controllers: Type[];\n exports: DynamicModule['exports'];\n} {\n return {\n providers: [BetterAuthService, AuthGuard],\n controllers: n.mountHandler ? [createBetterAuthCatchallController(n.basePath)] : [],\n exports: [BetterAuthService, BETTER_AUTH_OPTIONS, AuthGuard],\n };\n}\n\n/**\n * Options for {@link BetterAuthModule.forRootAsync}.\n *\n * The `Inject` type parameter captures the literal `inject` tuple at the call\n * site (via `const` inference) so `useFactory` parameters are typed from the\n * inject array, position-by-position — no `as const`, no `(...deps: any[])`:\n *\n * ```ts\n * BetterAuthModule.forRootAsync({\n * inject: [ENV, ConfigService], // captured as readonly tuple\n * useFactory: (env, config) => // inferred from the tokens\n * betterAuth({ database: drizzleAdapter(drizzle(env.DB), ...) }),\n * });\n * ```\n *\n * A factory without parameters may omit `inject`.\n */\ntype ForRootAsyncOptions<Inject extends readonly Token[] = readonly Token[]> = {\n imports?: DynamicModule['imports'];\n useFactory: (...deps: InferTokens<Inject>) => BetterAuthInstance;\n isGlobal?: boolean;\n mountHandler?: boolean;\n basePath?: string;\n issuer?: string;\n key?: string;\n} & FactoryInject<Inject>;\n\nexport class BetterAuthModule {\n /**\n * Synchronous registration. The auth instance is constructed by the consumer\n * at module-load time and passed in directly. Use this when the inputs to\n * `betterAuth({...})` are available at startup (Node apps with a static DB\n * connection, in-memory adapters, etc.).\n */\n static forRoot(\n options: BetterAuthModuleOptions & { isGlobal?: boolean; key?: string },\n ): DynamicModule {\n const normalized = normalize(options);\n const shape = stableHash(normalized);\n const key =\n options.key === undefined\n ? `${shape}:auth:${referenceId(options.auth)}`\n : explicitKey(options.key, shape, options.auth);\n const common = commonContributions(normalized);\n return {\n module: BetterAuthModule,\n key,\n providers: [\n defineProvider(BETTER_AUTH_OPTIONS, { useValue: normalized }),\n defineProvider(BETTER_AUTH_BUILDER, { useValue: () => options.auth }),\n ...common.providers,\n ...(normalized.isGlobal ? provideGlobal('guard', AuthGuard) : []),\n ],\n controllers: common.controllers,\n exports: common.exports,\n };\n }\n\n /**\n * Deferred / DI-driven registration. The user factory runs **lazily**, on the\n * first time anything reads `BetterAuthService.auth` (or `.api` / `.handler`).\n * In normal request handling that's `AuthGuard.canActivate` or the catch-all\n * controller's `.handle`. At module load the factory does NOT run — it's only\n * captured in the checked builder provider. The Workers adapter supplies its\n * native environment before DI; the lazily constructed auth instance belongs\n * to that environment's application and never captures another app's bindings.\n */\n static forRootAsync<const Inject extends readonly Token[] = readonly Token[]>(\n options: ForRootAsyncOptions<Inject>,\n ): DynamicModule {\n const n = normalize(options);\n const common = commonContributions(n);\n const shape = stableHash({ ...n, inject: options.inject });\n const key =\n options.key === undefined\n ? `${shape}:factory:${referenceId(options.useFactory)}`\n : explicitKey(options.key, shape, options.useFactory);\n return {\n module: BetterAuthModule,\n key,\n imports: options.imports ?? [],\n providers: [\n defineProvider(BETTER_AUTH_OPTIONS, { useValue: n }),\n // Unmemoized: BetterAuthService caches the instance it builds.\n lazyProvider<BetterAuthInstance, Inject>({\n ...options,\n provide: BETTER_AUTH_BUILDER,\n memoize: false,\n }),\n ...common.providers,\n ...(n.isGlobal ? provideGlobal('guard', AuthGuard) : []),\n ],\n controllers: common.controllers,\n exports: common.exports,\n };\n }\n}\n","import { Inject, Injectable, InjectionToken, Optional } from '@velajs/vela';\nimport type {\n UpgradeAuthenticator,\n WebSocketUpgradeAuthenticationContext,\n WebSocketUpgradeIdentity,\n} from '@velajs/vela/websocket';\nimport { BetterAuthService } from './better-auth.service';\nimport { BETTER_AUTH_OPTIONS } from './better-auth.tokens';\nimport type { BetterAuthRuntimeOptions, Session, User } from './better-auth.types';\nimport { validateSessionData } from './session-data';\n\n/** The validated Better Auth session behind a WebSocket upgrade. */\nexport interface BetterAuthUpgradeSession {\n readonly user: User;\n readonly session: Session;\n}\n\n/**\n * Chooses the tenant a WebSocket connection joins. Returning no tenant (or\n * throwing) refuses the upgrade.\n */\nexport type BetterAuthUpgradeTenantResolver = (\n session: BetterAuthUpgradeSession,\n context: WebSocketUpgradeAuthenticationContext,\n request: Request,\n) => string | undefined | Promise<string | undefined>;\n\n/**\n * Optional tenant resolver for {@link BetterAuthUpgradeAuthenticator}. Provide it\n * in the module that declares the gateway; without one, the session's active\n * organization is the tenant.\n */\nexport const BETTER_AUTH_UPGRADE_TENANT = new InjectionToken<BetterAuthUpgradeTenantResolver>(\n 'vela.better-auth.UpgradeTenant',\n);\n\n/**\n * WebSocket upgrade authenticator backed by the Better Auth session cookie:\n * `@WebSocketGateway({ authenticator: BetterAuthUpgradeAuthenticator })`.\n *\n * The principal uses the `BetterAuthModule` issuer, as `AuthGuard` does for\n * HTTP. The identity expires with the session. Every WebSocket identity carries\n * a tenant, so a session without an active organization is refused unless a\n * {@link BETTER_AUTH_UPGRADE_TENANT} resolver supplies one.\n */\n@Injectable()\nexport class BetterAuthUpgradeAuthenticator implements UpgradeAuthenticator {\n constructor(\n @Inject(BetterAuthService) private readonly auth: BetterAuthService,\n @Inject(BETTER_AUTH_OPTIONS) private readonly options: BetterAuthRuntimeOptions,\n @Optional()\n @Inject(BETTER_AUTH_UPGRADE_TENANT)\n private readonly resolveTenant?: BetterAuthUpgradeTenantResolver,\n ) {}\n\n async authenticate(\n request: Request,\n context: WebSocketUpgradeAuthenticationContext,\n ): Promise<WebSocketUpgradeIdentity | false> {\n const data = validateSessionData(await this.auth.api.getSession({ headers: request.headers }));\n if (!data) return false;\n const tenantId = this.resolveTenant\n ? await this.resolveTenant({ user: data.user, session: data.session }, context, request)\n : data.tenantId;\n if (typeof tenantId !== 'string' || tenantId.length === 0) return false;\n return {\n principal: {\n issuer: this.options.issuer ?? 'better-auth',\n subject: data.user.id,\n principalType: 'user',\n },\n tenantId,\n expiresAtMs: data.session.expiresAt.getTime(),\n };\n }\n}\n","import { createParamDecorator, type ExecutionContext } from '@velajs/vela';\nimport { getAuthRequestState } from '../auth-request-state';\nimport type { User } from '../better-auth.types';\n\nexport const CurrentUser = createParamDecorator(\n (_data: unknown, ctx: ExecutionContext): User | undefined => {\n const state = getAuthRequestState(ctx);\n return state?.user;\n },\n);\n","import { createParamDecorator, type ExecutionContext } from '@velajs/vela';\nimport { getAuthRequestState } from '../auth-request-state';\nimport type { Session } from '../better-auth.types';\n\nexport const CurrentSession = createParamDecorator(\n (_data: unknown, ctx: ExecutionContext): Session | undefined => {\n const state = getAuthRequestState(ctx);\n return state?.session;\n },\n);\n","import type { Identity, PermissionResolver } from '@velajs/authz';\nimport type { User } from './better-auth.types';\n\n/**\n * A better-auth user carrying the optional `role` field contributed by the\n * admin plugin. `role` may be a single role, a comma-separated list, or an\n * array — {@link identityFromUser} normalizes all three.\n */\nexport type AuthUser = Pick<User, 'id'> & { role?: string | string[] | null };\n\n/** Stable issuer namespace used for better-auth session principals. */\nexport const BETTER_AUTH_ISSUER = 'better-auth';\n\nconst normalizeRoles = (role: string | string[] | null | undefined): string[] => {\n if (!role) return [];\n // Strip empty entries and return a fresh array (never alias the caller's\n // input), matching the comma-string path below.\n if (Array.isArray(role)) return role.filter(Boolean);\n return role\n .split(',')\n .map((r) => r.trim())\n .filter(Boolean);\n};\n\n/**\n * Pure authorization projection; this does not authenticate or publish trusted state.\n * Adapts an already verified better-auth user into a stable `@velajs/authz` {@link Identity}.\n * The issuer scopes `user.id` as both `subject` and the compatibility `userId`;\n * the admin-plugin `role` field supplies local roles.\n *\n * Fail-closed: a missing user (`null`/`undefined`, i.e. an unauthenticated\n * request) maps to the zero-privilege identity `{ roles: [] }`, so downstream\n * `can()` checks grant nothing.\n */\nexport const identityFromUser = (\n user: AuthUser | null | undefined,\n issuer: string = BETTER_AUTH_ISSUER,\n principalType: 'user' | 'service' = 'user',\n): Identity => {\n if (!user || typeof user.id !== 'string' || user.id.length === 0) return { roles: [] };\n if (issuer.length === 0)\n throw new Error('@velajs/better-auth: identity issuer must be non-empty');\n return {\n issuer,\n subject: user.id,\n principalType,\n userId: user.id,\n roles: normalizeRoles(user.role),\n };\n};\n\n/**\n * The minimal slice of a better-auth access-control role consumed here. Both\n * `createAccessControl(...).newRole(...)` and the standalone `role(...)` return\n * `{ authorize, statements }`; `statements` is the `{ resource: actions[] }`\n * grant map for that role — the only accessor {@link betterAuthAcResolver}\n * reads.\n */\nexport interface BetterAuthAcRole {\n readonly statements: Readonly<Record<string, readonly string[]>>;\n}\n\n/**\n * Flattens a better-auth AC role's `statements` into `resource:action`\n * permission strings — the granted-side format `@velajs/authz` matches\n * (wildcards included).\n */\nexport const permissionsFromAcRole = (role: BetterAuthAcRole): string[] => {\n const permissions: string[] = [];\n for (const [resource, actions] of Object.entries(role.statements ?? {})) {\n for (const action of actions ?? []) permissions.push(`${resource}:${action}`);\n }\n return permissions;\n};\n\n/**\n * Builds a fail-closed `@velajs/authz` {@link PermissionResolver} from a\n * better-auth access-control role table (`{ roleName: acRole }` — the same map\n * shape passed to better-auth's admin/organization plugins). An identity's\n * `roles` are unioned into their granted permission strings; unknown roles\n * contribute nothing.\n *\n * ```ts\n * const ac = createAccessControl({ posts: ['read', 'write'] });\n * const authz = createAuthz({\n * resolver: betterAuthAcResolver({ editor: ac.newRole({ posts: ['write'] }) }),\n * });\n * await authz.can(identityFromUser(user), 'posts:write');\n * ```\n */\nexport const betterAuthAcResolver = (\n roles: Readonly<Record<string, BetterAuthAcRole>>,\n): PermissionResolver => {\n const grantsByRole = new Map<string, string[]>();\n for (const [name, role] of Object.entries(roles)) {\n grantsByRole.set(name, permissionsFromAcRole(role));\n }\n return {\n grants(identity: Identity): Set<string> {\n const out = new Set<string>();\n for (const name of identity.roles ?? []) {\n for (const permission of grantsByRole.get(name) ?? []) out.add(permission);\n }\n return out;\n },\n };\n};\n"],"mappings":";;;;;AAEA,MAAa,SAAS,UAAU,gBAAyB,EAAE,KAAK,mBAAmB,CAAC;AACpF,MAAa,aAAa,OAAO;;ACAjC,SAAgB,4BAA4B,OAAwB;CAClE,MAAM,WAAW,SAAA;CACjB,IACE,SAAS,WAAW,KACpB,aAAa,SAAS,KAAK,KAC3B,CAAC,SAAS,WAAW,GAAG,KACxB,SAAS,WAAW,IAAI,KACxB,aAAa,OACb,SAAS,SAAS,GAAG,KACrB,WAAW,KAAK,QAAQ,KACxB,kBAAkB,KAAK,QAAQ,GAE/B,MAAM,IAAI,MACR,uFACF;CAGF,IAAI;CACJ,IAAI;EACF,UAAU,mBAAmB,QAAQ;CACvC,QAAQ;EACN,MAAM,IAAI,MAAM,iEAAiE;CACnF;CACA,IAAI,QAAQ,MAAM,GAAG,CAAC,CAAC,MAAM,YAAY,YAAY,OAAO,YAAY,IAAI,GAC1E,MAAM,IAAI,MAAM,6DAA6D;CAE/E,OAAO;AACT;;;;;;;;;;;;;;;;ACXA,SAAgB,mCAAmC,WAAmB,aAAmB;CACvF,MAAM,qBAAqB,4BAA4B,QAAQ;CAC/D,IAEM,+BAFN,MAEM,6BAA6B;EAIuB;EAAxD,YAAY,MAAqE;GAAzB,KAAA,OAAA;EAA0B;EAElF,MACM,OAAO,GAAsC;GACjD,OAAO,KAAK,KAAK,QAAQ,EAAE,IAAI,GAAG;EACpC;CACF;;EAJG,IAAI,IAAI;EACK,gBAAA,GAAA,IAAI,CAAA;;;;;;EATnB,OAAO,IAAI;EACX,WAAW,kBAAkB;EAKf,gBAAA,GAAA,OAAO,iBAAiB,CAAA;;;CAOvC,OAAO;AACT;;;AChCA,MAAa,sBAAsB,IAAI,eACrC,wBACF;;;ACMA,MAAM,WAAW,kCAA+C;AAEhE,SAAgB,iBAAiB,SAAiC;CAChE,4BAA4B,QAAQ,WAAW,CAAC;AAClD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AO,KACJ,MAAM,GAAG,CAAC,CACV,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,CACpB,OAAO,OAAO;AACnB;;;;;;;;;;;AAYA,MAAa,oBACX,MACA,SAAiB,oBACjB,gBAAoC,WACvB;CACb,IAAI,CAAC,QAAQ,OAAO,KAAK,OAAO,YAAY,KAAK,GAAG,WAAW,GAAG,OAAO,EAAE,OAAO,CAAC,EAAE;CACrF,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,MAAM,wDAAwD;CAC1E,OAAO;EACL;EACA,SAAS,KAAK;EACd;EACA,QAAQ,KAAK;EACb,OAAO,eAAe,KAAK,IAAI;CACjC;AACF;;;;;;AAkBA,MAAa,yBAAyB,SAAqC;CACzE,MAAM,cAAwB,CAAC;CAC/B,KAAK,MAAM,CAAC,UAAU,YAAY,OAAO,QAAQ,KAAK,cAAc,CAAC,CAAC,GACpE,KAAK,MAAM,UAAU,WAAW,CAAC,GAAG,YAAY,KAAK,GAAG,SAAS,GAAG,QAAQ;CAE9E,OAAO;AACT;;;;;;;;;;;;;;;;AAiBA,MAAa,wBACX,UACuB;CACvB,MAAM,+BAAe,IAAI,IAAsB;CAC/C,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,KAAK,GAC7C,aAAa,IAAI,MAAM,sBAAsB,IAAI,CAAC;CAEpD,OAAO,EACL,OAAO,UAAiC;EACtC,MAAM,sBAAM,IAAI,IAAY;EAC5B,KAAK,MAAM,QAAQ,SAAS,SAAS,CAAC,GACpC,KAAK,MAAM,cAAc,aAAa,IAAI,IAAI,KAAK,CAAC,GAAG,IAAI,IAAI,UAAU;EAE3E,OAAO;CACT,EACF;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/decorators/public.decorator.ts","../src/base-path.ts","../src/better-auth.controller.ts","../src/better-auth.tokens.ts","../src/auth-request-state.ts","../src/session-data.ts","../src/decorators/optional-auth.decorator.ts","../src/guards/auth.guard.ts","../src/better-auth.module.ts","../src/upgrade-authenticator.ts","../src/decorators/current-user.decorator.ts","../src/decorators/current-session.decorator.ts","../src/authz-bridge.ts"],"sourcesContent":["import { Reflector } from '@velajs/vela';\n\nexport const Public = Reflector.createDecorator<boolean>({ key: 'vela.auth.public' });\nexport const PUBLIC_KEY = Public.KEY;\n","export const DEFAULT_BETTER_AUTH_BASE_PATH = '/api/auth';\n\n/** Validate and canonicalize the route prefix used by the public auth controller. */\nexport function normalizeBetterAuthBasePath(value?: string): string {\n const basePath = value ?? DEFAULT_BETTER_AUTH_BASE_PATH;\n if (\n basePath.length === 0 ||\n basePath !== basePath.trim() ||\n !basePath.startsWith('/') ||\n basePath.startsWith('//') ||\n basePath === '/' ||\n basePath.endsWith('/') ||\n /[\\\\?#*]/u.test(basePath) ||\n /%(?:2e|2f|5c)/iu.test(basePath)\n ) {\n throw new Error(\n '@velajs/better-auth: basePath must be a canonical absolute path such as \"/api/auth\"',\n );\n }\n\n let decoded: string;\n try {\n decoded = decodeURIComponent(basePath);\n } catch {\n throw new Error('@velajs/better-auth: basePath contains invalid percent encoding');\n }\n if (decoded.split('/').some((segment) => segment === '.' || segment === '..')) {\n throw new Error('@velajs/better-auth: basePath must not contain dot segments');\n }\n return basePath;\n}\n","import { All, Controller, Inject, Req, type Type } from '@velajs/vela';\nimport { SkipGuardPhases } from '@velajs/vela/module-kit';\nimport { BetterAuthService } from './better-auth.service';\nimport { Public } from './decorators/public.decorator';\nimport { normalizeBetterAuthBasePath } from './base-path';\n\n// One decorated class per base path: every registration of a path, and every\n// call, shares it (the class reads nothing else).\nconst controllers = new Map<string, Type>();\n\n/**\n * Build a catch-all controller that mounts better-auth's handler at `basePath`\n * (default `/api/auth`). This is a factory because vela reads a controller's\n * route off the class at decoration time, so a custom base path needs its own\n * decorated class — the path can't be parametrized on a single shared class.\n * Calls with the same base path return the same class.\n *\n * Two base paths to keep consistent:\n * - this `basePath` is RELATIVE to vela's `globalPrefix` (always prepended);\n * - better-auth routes against its OWN absolute `basePath` (the one you pass to\n * `betterAuth({ basePath })`), which must equal `globalPrefix + basePath`.\n *\n * Both default to `/api/auth`, so the no-prefix / no-config case just works.\n */\nexport function createBetterAuthCatchallController(basePath: string = '/api/auth'): Type {\n const normalizedBasePath = normalizeBetterAuthBasePath(basePath);\n const existing = controllers.get(normalizedBasePath);\n if (existing) return existing;\n // Better Auth authenticates its own endpoints; application-wide tenant\n // admission and authorization do not apply to signing in.\n @Public(true)\n @SkipGuardPhases(['tenant', 'authorize'])\n @Controller(normalizedBasePath)\n class BetterAuthCatchallController {\n // Inject the service — its `.handler` getter triggers lazy construction\n // of the underlying betterAuth() instance on first access, AFTER any\n // runtime adapter middleware (Cloudflare env capture) has run.\n constructor(@Inject(BetterAuthService) private readonly auth: BetterAuthService) {}\n\n @All('/*')\n async handle(@Req() request: Request): Promise<Response> {\n return this.auth.handler(request);\n }\n }\n controllers.set(normalizedBasePath, BetterAuthCatchallController);\n return BetterAuthCatchallController;\n}\n","import { InjectionToken } from '@velajs/vela';\nimport type { BetterAuthRuntimeOptions } from './better-auth.types';\n\nexport const BETTER_AUTH_OPTIONS = new InjectionToken<BetterAuthRuntimeOptions>(\n 'vela.BetterAuthOptions',\n);\n","import type { ExecutionContext } from '@velajs/vela';\nimport {\n clearTrustedRequestIdentity,\n createTrustedRequestIdentityStore,\n getTrustedContextRequest,\n setTrustedRequestIdentity,\n} from '@velajs/vela/module-kit';\nimport type { SessionData } from './session-data';\n\n// This map stores provider payload, never a second authentication authority.\n// A clear, expiry, or identity replacement makes the payload unreachable.\nconst sessions = createTrustedRequestIdentityStore<SessionData>();\n\nexport function beginAuthRequest(context: ExecutionContext): void {\n clearTrustedRequestIdentity(context.getRequest());\n}\n\nexport function authenticateRequest(\n context: ExecutionContext,\n data: SessionData,\n issuer: string,\n): void {\n const request = context.getRequest();\n setTrustedRequestIdentity(request, {\n principal: { issuer, subject: data.user.id, principalType: 'user' },\n expiresAtMs: data.session.expiresAt.getTime(),\n roles: data.roles,\n ...(data.tenantId === undefined ? {} : { tenantId: data.tenantId }),\n });\n sessions.set(request, data);\n}\n\nexport function getAuthRequestState(context: ExecutionContext): SessionData | undefined {\n const request = getTrustedContextRequest(context);\n return request ? sessions.get(request) : undefined;\n}\n","import type { Session, User } from './better-auth.types';\n\nexport interface SessionData {\n readonly user: User;\n readonly session: Session;\n readonly roles: readonly string[];\n readonly tenantId?: string;\n}\n\nfunction own(value: unknown, key: string): unknown {\n if (typeof value !== 'object' || value === null) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n return descriptor && 'value' in descriptor ? descriptor.value : undefined;\n}\n\nfunction requiredString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n\nfunction date(value: unknown): Date | undefined {\n return value instanceof Date && Number.isFinite(value.getTime()) ? new Date(value) : undefined;\n}\n\nfunction optionalString(value: unknown): value is string | null | undefined {\n return value === undefined || value === null || typeof value === 'string';\n}\n\n/** Keep plugin data opaque; base model fields below are validated individually. */\nfunction dataProperties(value: object): Record<string, unknown> {\n return Object.fromEntries(Object.keys(value).map((key) => [key, own(value, key)]));\n}\n\n/** Validate the full Better Auth base models, not merely ids masquerading as them. */\nexport function validateSessionData(value: unknown): SessionData | undefined {\n try {\n const user = own(value, 'user');\n const session = own(value, 'session');\n if (\n typeof user !== 'object' ||\n user === null ||\n typeof session !== 'object' ||\n session === null\n ) {\n return undefined;\n }\n const id = own(user, 'id');\n const email = own(user, 'email');\n const name = own(user, 'name');\n const emailVerified = own(user, 'emailVerified');\n const image = own(user, 'image');\n const createdAt = date(own(user, 'createdAt'));\n const updatedAt = date(own(user, 'updatedAt'));\n const sessionId = own(session, 'id');\n const userId = own(session, 'userId');\n const token = own(session, 'token');\n const sessionCreatedAt = date(own(session, 'createdAt'));\n const sessionUpdatedAt = date(own(session, 'updatedAt'));\n const expiresAt = date(own(session, 'expiresAt'));\n const ipAddress = own(session, 'ipAddress');\n const userAgent = own(session, 'userAgent');\n const organization = own(session, 'activeOrganizationId');\n const role = own(user, 'role');\n let roles: string[] = [];\n if (role !== undefined && role !== null) {\n if (typeof role === 'string')\n roles = role\n .split(',')\n .map((part) => part.trim())\n .filter(Boolean);\n else if (\n Array.isArray(role) &&\n role.every((entry: unknown): entry is string => typeof entry === 'string')\n ) {\n roles = role.map((entry: string) => entry.trim()).filter(Boolean);\n } else return undefined;\n }\n if (\n !requiredString(id) ||\n !requiredString(email) ||\n typeof name !== 'string' ||\n typeof emailVerified !== 'boolean' ||\n !optionalString(image) ||\n !createdAt ||\n !updatedAt ||\n !requiredString(sessionId) ||\n userId !== id ||\n !requiredString(token) ||\n !sessionCreatedAt ||\n !sessionUpdatedAt ||\n !expiresAt ||\n expiresAt.getTime() <= Date.now() ||\n !optionalString(ipAddress) ||\n !optionalString(userAgent) ||\n (organization !== undefined && organization !== null && !requiredString(organization))\n )\n return undefined;\n return {\n user: Object.freeze({\n ...dataProperties(user),\n id,\n email,\n name,\n emailVerified,\n createdAt,\n updatedAt,\n image,\n }),\n session: Object.freeze({\n ...dataProperties(session),\n id: sessionId,\n userId: id,\n token,\n createdAt: sessionCreatedAt,\n updatedAt: sessionUpdatedAt,\n expiresAt,\n ipAddress,\n userAgent,\n }),\n roles: Object.freeze(roles),\n ...(typeof organization === 'string' ? { tenantId: organization } : {}),\n };\n } catch {\n return undefined;\n }\n}\n","import { Reflector } from '@velajs/vela';\n\nexport const OptionalAuth = Reflector.createDecorator<boolean>({ key: 'vela.auth.optional' });\nexport const OPTIONAL_AUTH_KEY = OptionalAuth.KEY;\n","import {\n Inject,\n Injectable,\n Reflector,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n type GuardPhase,\n} from '@velajs/vela';\nimport { getTrustedContextRequest } from '@velajs/vela/module-kit';\nimport { getContextIdentity } from '@velajs/authz/vela';\nimport { BETTER_AUTH_OPTIONS } from '../better-auth.tokens';\nimport { BetterAuthService } from '../better-auth.service';\nimport type { BetterAuthRuntimeOptions } from '../better-auth.types';\nimport { authenticateRequest, beginAuthRequest, getAuthRequestState } from '../auth-request-state';\nimport { validateSessionData } from '../session-data';\nimport { OptionalAuth } from '../decorators/optional-auth.decorator';\nimport { Public } from '../decorators/public.decorator';\n\n@Injectable()\nexport class AuthGuard implements CanActivate {\n /** Global guards run authentication first, then tenant, authorization and feature phases. */\n static readonly phase: GuardPhase = 'authenticate';\n\n constructor(\n @Inject(BetterAuthService) private readonly auth: BetterAuthService,\n @Inject(BETTER_AUTH_OPTIONS) private readonly opts: BetterAuthRuntimeOptions,\n @Inject(Reflector) private readonly reflector: Reflector,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n // Frames trust only the authenticated connection attachment; HTTP cookies\n // and request payload never become ambient WebSocket authentication.\n if (context.getType() === 'ws') {\n if (getContextIdentity(context)) return true;\n throw new UnauthorizedException('Authentication required');\n }\n // Custom HTTP-backed dispatchers authenticate once at the outer boundary.\n // Never re-read credentials or clear shared authority across sibling fields.\n if (context.getType() !== 'http') {\n if (\n getTrustedContextRequest(context) &&\n (getAuthRequestState(context) ||\n this.reflector.getAllAndOverride(Public, context) ||\n this.reflector.getAllAndOverride(OptionalAuth, context))\n )\n return true;\n throw new UnauthorizedException('Authentication required');\n }\n beginAuthRequest(context);\n if (this.reflector.getAllAndOverride(Public, context)) return true;\n\n const raw = await this.auth.api.getSession({ headers: context.getRequest().headers });\n const data = validateSessionData(raw);\n if (data) {\n authenticateRequest(context, data, this.opts.issuer ?? 'better-auth');\n return true;\n }\n if (this.reflector.getAllAndOverride(OptionalAuth, context)) return true;\n throw new UnauthorizedException('Authentication required');\n }\n}\n","import { defineModule, defineProvider, InjectionToken, type Type } from '@velajs/vela';\nimport { createBetterAuthCatchallController } from './better-auth.controller';\nimport { BetterAuthService, BETTER_AUTH_BUILDER } from './better-auth.service';\nimport { BETTER_AUTH_OPTIONS } from './better-auth.tokens';\nimport type {\n BetterAuthInstance,\n BetterAuthModuleOptions,\n BetterAuthRuntimeOptions,\n BetterAuthStructuralOption,\n} from './better-auth.types';\nimport { AuthGuard } from './guards/auth.guard';\nimport { DEFAULT_BETTER_AUTH_BASE_PATH, normalizeBetterAuthBasePath } from './base-path';\n\nconst MODULE_OPTIONS = new InjectionToken<BetterAuthModuleOptions>(\n 'vela.better-auth.ModuleOptions',\n);\n\n/** Runtime options with defaults applied: what AuthGuard and the upgrade authenticator read. */\nfunction runtimeOptions(options: BetterAuthModuleOptions): Required<BetterAuthRuntimeOptions> {\n const auth: unknown = options.auth;\n if (typeof auth !== 'function' && (typeof auth !== 'object' || auth === null)) {\n throw new TypeError(\n '@velajs/better-auth: options need `auth`, a better-auth instance or a function that builds one',\n );\n }\n const basePath = normalizeBetterAuthBasePath(options.basePath);\n const issuer = options.issuer ?? `better-auth:${basePath}`;\n if (issuer.length === 0 || issuer !== issuer.trim()) {\n throw new Error('@velajs/better-auth: issuer must be a non-empty stable namespace');\n }\n return {\n basePath,\n issuer,\n mountHandler: options.mountHandler ?? true,\n };\n}\n\n/** The instance itself, or the one its builder function returns. */\nfunction buildAuth(auth: BetterAuthModuleOptions['auth']): BetterAuthInstance {\n return typeof auth === 'function' ? auth() : auth;\n}\n\nconst { ConfigurableModuleClass } = defineModule<\n BetterAuthModuleOptions,\n BetterAuthStructuralOption\n>({\n name: 'BetterAuth',\n optionsToken: MODULE_OPTIONS,\n structural: ['basePath', 'mountHandler'],\n // Spelling out a default configures what leaving it out does: one instance.\n defaults: { basePath: DEFAULT_BETTER_AUTH_BASE_PATH, mountHandler: true },\n setup: ({ OPTIONS, options }) => {\n // Validates the mount path when the module is declared, before bootstrap.\n const basePath = normalizeBetterAuthBasePath(options.basePath);\n const controllers: Type[] =\n options.mountHandler === false ? [] : [createBetterAuthCatchallController(basePath)];\n return {\n providers: [\n defineProvider(BETTER_AUTH_OPTIONS, {\n useFactory: (resolved) => runtimeOptions(resolved),\n inject: [OPTIONS],\n }),\n // BetterAuthService calls the builder on first use and caches the\n // instance, so a builder function never runs at bootstrap.\n defineProvider(BETTER_AUTH_BUILDER, {\n useFactory: (resolved) => () => buildAuth(resolved.auth),\n inject: [OPTIONS],\n }),\n BetterAuthService,\n AuthGuard,\n ],\n controllers,\n exports: [BetterAuthService, BETTER_AUTH_OPTIONS, AuthGuard],\n };\n },\n});\n\n/**\n * better-auth for Vela: `BetterAuthService`, the catch-all handler under\n * `basePath`, and an injectable `AuthGuard`. Applications install it through `APP_GUARD`\n * with `useExisting: AuthGuard`, or attach it with `@UseGuards`.\n *\n * ```ts\n * BetterAuthModule.forRoot({ auth: betterAuth({ ... }) });\n * BetterAuthModule.forRootAsync({\n * inject: [ENV],\n * useFactory: (env) => ({ auth: () => betterAuth({ database: env.DB }), issuer: 'accounts' }),\n * });\n * ```\n *\n * `basePath` and `mountHandler` are structural: `forRootAsync`\n * takes them alongside the factory. The factory runs when the application\n * initializes; an `auth` function it returns runs on first authentication.\n */\nexport class BetterAuthModule extends ConfigurableModuleClass {}\n","import { Inject, Injectable, InjectionToken, Optional } from '@velajs/vela';\nimport type {\n UpgradeAuthenticator,\n WebSocketUpgradeAuthenticationContext,\n WebSocketUpgradeIdentity,\n} from '@velajs/vela/websocket';\nimport { BetterAuthService } from './better-auth.service';\nimport { BETTER_AUTH_OPTIONS } from './better-auth.tokens';\nimport type { BetterAuthRuntimeOptions, Session, User } from './better-auth.types';\nimport { validateSessionData } from './session-data';\n\n/** The validated Better Auth session behind a WebSocket upgrade. */\nexport interface BetterAuthUpgradeSession {\n readonly user: User;\n readonly session: Session;\n}\n\n/**\n * Chooses the tenant a WebSocket connection joins. Returning no tenant (or\n * throwing) refuses the upgrade.\n */\nexport type BetterAuthUpgradeTenantResolver = (\n session: BetterAuthUpgradeSession,\n context: WebSocketUpgradeAuthenticationContext,\n request: Request,\n) => string | undefined | Promise<string | undefined>;\n\n/**\n * Optional tenant resolver for {@link BetterAuthUpgradeAuthenticator}. Provide it\n * in the module that declares the gateway; without one, the session's active\n * organization is the tenant.\n */\nexport const BETTER_AUTH_UPGRADE_TENANT = new InjectionToken<BetterAuthUpgradeTenantResolver>(\n 'vela.better-auth.UpgradeTenant',\n);\n\n/**\n * WebSocket upgrade authenticator backed by the Better Auth session cookie:\n * `@WebSocketGateway({ authenticator: BetterAuthUpgradeAuthenticator })`.\n *\n * The principal uses the `BetterAuthModule` issuer, as `AuthGuard` does for\n * HTTP. The identity expires with the session. Every WebSocket identity carries\n * a tenant, so a session without an active organization is refused unless a\n * {@link BETTER_AUTH_UPGRADE_TENANT} resolver supplies one.\n */\n@Injectable()\nexport class BetterAuthUpgradeAuthenticator implements UpgradeAuthenticator {\n constructor(\n @Inject(BetterAuthService) private readonly auth: BetterAuthService,\n @Inject(BETTER_AUTH_OPTIONS) private readonly options: BetterAuthRuntimeOptions,\n @Optional()\n @Inject(BETTER_AUTH_UPGRADE_TENANT)\n private readonly resolveTenant?: BetterAuthUpgradeTenantResolver,\n ) {}\n\n async authenticate(\n request: Request,\n context: WebSocketUpgradeAuthenticationContext,\n ): Promise<WebSocketUpgradeIdentity | false> {\n const data = validateSessionData(await this.auth.api.getSession({ headers: request.headers }));\n if (!data) return false;\n const tenantId = this.resolveTenant\n ? await this.resolveTenant({ user: data.user, session: data.session }, context, request)\n : data.tenantId;\n if (typeof tenantId !== 'string' || tenantId.length === 0) return false;\n return {\n principal: {\n issuer: this.options.issuer ?? 'better-auth',\n subject: data.user.id,\n principalType: 'user',\n },\n tenantId,\n expiresAtMs: data.session.expiresAt.getTime(),\n };\n }\n}\n","import { createParamDecorator, type ExecutionContext } from '@velajs/vela';\nimport { getAuthRequestState } from '../auth-request-state';\nimport type { User } from '../better-auth.types';\n\nexport const CurrentUser = createParamDecorator(\n (_data: unknown, ctx: ExecutionContext): User | undefined => {\n const state = getAuthRequestState(ctx);\n return state?.user;\n },\n);\n","import { createParamDecorator, type ExecutionContext } from '@velajs/vela';\nimport { getAuthRequestState } from '../auth-request-state';\nimport type { Session } from '../better-auth.types';\n\nexport const CurrentSession = createParamDecorator(\n (_data: unknown, ctx: ExecutionContext): Session | undefined => {\n const state = getAuthRequestState(ctx);\n return state?.session;\n },\n);\n","import type { Identity, PermissionResolver } from '@velajs/authz';\nimport type { User } from './better-auth.types';\n\n/**\n * A better-auth user carrying the optional `role` field contributed by the\n * admin plugin. `role` may be a single role, a comma-separated list, or an\n * array — {@link identityFromUser} normalizes all three.\n */\nexport type AuthUser = Pick<User, 'id'> & { role?: string | string[] | null };\n\n/** Stable issuer namespace used for better-auth session principals. */\nexport const BETTER_AUTH_ISSUER = 'better-auth';\n\nconst normalizeRoles = (role: string | string[] | null | undefined): string[] => {\n if (!role) return [];\n // Strip empty entries and return a fresh array (never alias the caller's\n // input), matching the comma-string path below.\n if (Array.isArray(role)) return role.filter(Boolean);\n return role\n .split(',')\n .map((r) => r.trim())\n .filter(Boolean);\n};\n\n/**\n * Pure authorization projection; this does not authenticate or publish trusted state.\n * Adapts an already verified better-auth user into a stable `@velajs/authz` {@link Identity}.\n * The issuer scopes `user.id` as the `subject`;\n * the admin-plugin `role` field supplies local roles.\n *\n * Fail-closed: a missing user (`null`/`undefined`, i.e. an unauthenticated\n * request) maps to the zero-privilege identity `{ roles: [] }`, so downstream\n * `can()` checks grant nothing.\n */\nexport const identityFromUser = (\n user: AuthUser | null | undefined,\n issuer: string = BETTER_AUTH_ISSUER,\n principalType: 'user' | 'service' = 'user',\n): Identity => {\n if (!user || typeof user.id !== 'string' || user.id.length === 0) return { roles: [] };\n if (issuer.length === 0)\n throw new Error('@velajs/better-auth: identity issuer must be non-empty');\n return {\n issuer,\n subject: user.id,\n principalType,\n roles: normalizeRoles(user.role),\n };\n};\n\n/**\n * The minimal slice of a better-auth access-control role consumed here. Both\n * `createAccessControl(...).newRole(...)` and the standalone `role(...)` return\n * `{ authorize, statements }`; `statements` is the `{ resource: actions[] }`\n * grant map for that role — the only accessor {@link betterAuthAcResolver}\n * reads.\n */\nexport interface BetterAuthAcRole {\n readonly statements: Readonly<Record<string, readonly string[]>>;\n}\n\n/**\n * Flattens a better-auth AC role's `statements` into `resource:action`\n * permission strings — the granted-side format `@velajs/authz` matches\n * (wildcards included).\n */\nexport const permissionsFromAcRole = (role: BetterAuthAcRole): string[] => {\n const permissions: string[] = [];\n for (const [resource, actions] of Object.entries(role.statements ?? {})) {\n for (const action of actions ?? []) permissions.push(`${resource}:${action}`);\n }\n return permissions;\n};\n\n/**\n * Builds a fail-closed `@velajs/authz` {@link PermissionResolver} from a\n * better-auth access-control role table (`{ roleName: acRole }` — the same map\n * shape passed to better-auth's admin/organization plugins). An identity's\n * `roles` are unioned into their granted permission strings; unknown roles\n * contribute nothing.\n *\n * ```ts\n * const ac = createAccessControl({ posts: ['read', 'write'] });\n * const authz = createAuthz({\n * resolver: betterAuthAcResolver({ editor: ac.newRole({ posts: ['write'] }) }),\n * });\n * await authz.can(identityFromUser(user), 'posts:write');\n * ```\n */\nexport const betterAuthAcResolver = (\n roles: Readonly<Record<string, BetterAuthAcRole>>,\n): PermissionResolver => {\n const grantsByRole = new Map<string, string[]>();\n for (const [name, role] of Object.entries(roles)) {\n grantsByRole.set(name, permissionsFromAcRole(role));\n }\n return {\n grants(identity: Identity): Set<string> {\n const out = new Set<string>();\n for (const name of identity.roles ?? []) {\n for (const permission of grantsByRole.get(name) ?? []) out.add(permission);\n }\n return out;\n },\n };\n};\n"],"mappings":";;;;;AAEA,MAAa,SAAS,UAAU,gBAAyB,EAAE,KAAK,mBAAmB,CAAC;AACpF,MAAa,aAAa,OAAO;;;ACHjC,MAAa,gCAAgC;;AAG7C,SAAgB,4BAA4B,OAAwB;CAClE,MAAM,WAAW,SAAA;CACjB,IACE,SAAS,WAAW,KACpB,aAAa,SAAS,KAAK,KAC3B,CAAC,SAAS,WAAW,GAAG,KACxB,SAAS,WAAW,IAAI,KACxB,aAAa,OACb,SAAS,SAAS,GAAG,KACrB,WAAW,KAAK,QAAQ,KACxB,kBAAkB,KAAK,QAAQ,GAE/B,MAAM,IAAI,MACR,uFACF;CAGF,IAAI;CACJ,IAAI;EACF,UAAU,mBAAmB,QAAQ;CACvC,QAAQ;EACN,MAAM,IAAI,MAAM,iE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,CAAC,CACV,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,CACpB,OAAO,OAAO;AACnB;;;;;;;;;;;AAYA,MAAa,oBACX,MACA,SAAiB,oBACjB,gBAAoC,WACvB;CACb,IAAI,CAAC,QAAQ,OAAO,KAAK,OAAO,YAAY,KAAK,GAAG,WAAW,GAAG,OAAO,EAAE,OAAO,CAAC,EAAE;CACrF,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,MAAM,wDAAwD;CAC1E,OAAO;EACL;EACA,SAAS,KAAK;EACd;EACA,OAAO,eAAe,KAAK,IAAI;CACjC;AACF;;;;;;AAkBA,MAAa,yBAAyB,SAAqC;CACzE,MAAM,cAAwB,CAAC;CAC/B,KAAK,MAAM,CAAC,UAAU,YAAY,OAAO,QAAQ,KAAK,cAAc,CAAC,CAAC,GACpE,KAAK,MAAM,UAAU,WAAW,CAAC,GAAG,YAAY,KAAK,GAAG,SAAS,GAAG,QAAQ;CAE9E,OAAO;AACT;;;;;;;;;;;;;;;;AAiBA,MAAa,wBACX,UACuB;CACvB,MAAM,+BAAe,IAAI,IAAsB;CAC/C,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,KAAK,GAC7C,aAAa,IAAI,MAAM,sBAAsB,IAAI,CAAC;CAEpD,OAAO,EACL,OAAO,UAAiC;EACtC,MAAM,sBAAM,IAAI,IAAY;EAC5B,KAAK,MAAM,QAAQ,SAAS,SAAS,CAAC,GACpC,KAAK,MAAM,cAAc,aAAa,IAAI,IAAI,KAAK,CAAC,GAAG,IAAI,IAAI,UAAU;EAE3E,OAAO;CACT,EACF;AACF"}
@@ -1,4 +1,4 @@
1
- import { t as BetterAuthService } from "../better-auth.service-CvmboUID.js";
1
+ import { t as BetterAuthService } from "../better-auth.service-D_G-PP8p.js";
2
2
  //#region src/testing/acting-as.d.ts
3
3
  /**
4
4
  * The slice of `@velajs/testing`'s `TestingModule` this resolver depends on.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@velajs/better-auth",
3
- "version": "1.30.0",
3
+ "version": "1.32.0",
4
4
  "description": "better-auth integration for the Vela framework",
5
5
  "keywords": [
6
6
  "auth",
@@ -47,7 +47,7 @@
47
47
  "access": "public"
48
48
  },
49
49
  "dependencies": {
50
- "@velajs/authz": "1.30.0"
50
+ "@velajs/authz": "1.32.0"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@arethetypeswrong/cli": "0.18.5",
@@ -63,14 +63,14 @@
63
63
  "unplugin-swc": "1.5.9",
64
64
  "vite": "^8.0.16",
65
65
  "vitest": "4.1.11",
66
- "@velajs/tenant": "1.30.0",
67
- "@velajs/vela": "1.30.0",
68
- "@velajs/testing": "1.30.0"
66
+ "@velajs/tenant": "1.32.0",
67
+ "@velajs/testing": "1.34.0",
68
+ "@velajs/vela": "1.34.0"
69
69
  },
70
70
  "peerDependencies": {
71
71
  "better-auth": ">=1.2.0",
72
72
  "hono": ">=4",
73
- "@velajs/vela": "^1.30.0"
73
+ "@velajs/vela": "^1.34.0"
74
74
  },
75
75
  "engines": {
76
76
  "node": ">=24"