@velajs/better-auth 1.30.0 → 1.31.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 +84 -0
- package/README.md +30 -20
- package/dist/{better-auth.service-CvmboUID.d.ts → better-auth.service-98MF2Inz.d.ts} +25 -15
- package/dist/better-auth.service-SNg1YFTK.js.map +1 -1
- package/dist/index.d.ts +21 -47
- package/dist/index.js +78 -95
- package/dist/index.js.map +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,89 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.31.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
|
|
9
|
+
**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`.
|
|
10
|
+
|
|
11
|
+
**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.
|
|
12
|
+
|
|
13
|
+
**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.
|
|
14
|
+
|
|
15
|
+
**Behavior change:** `identityFromUser` no longer sets the removed `userId` alias; read `subject` (with `issuer`).
|
|
16
|
+
|
|
17
|
+
`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.
|
|
18
|
+
- 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.
|
|
19
|
+
|
|
20
|
+
**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.
|
|
21
|
+
- 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`.
|
|
22
|
+
|
|
23
|
+
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.
|
|
24
|
+
|
|
25
|
+
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.
|
|
26
|
+
|
|
27
|
+
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`.
|
|
28
|
+
|
|
29
|
+
`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.
|
|
30
|
+
|
|
31
|
+
**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.
|
|
32
|
+
|
|
33
|
+
**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.
|
|
34
|
+
|
|
35
|
+
**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:
|
|
36
|
+
|
|
37
|
+
- `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.
|
|
38
|
+
- `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).
|
|
39
|
+
- `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.
|
|
40
|
+
- `AuthzModule`: handlers without `@Roles()` or `@RequirePermission()` pass; those declarations on gateway handlers and RPC procedures are now enforced.
|
|
41
|
+
|
|
42
|
+
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).
|
|
43
|
+
|
|
44
|
+
**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.
|
|
45
|
+
|
|
46
|
+
**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.
|
|
47
|
+
- 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)`.
|
|
48
|
+
|
|
49
|
+
- 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.
|
|
50
|
+
- 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.
|
|
51
|
+
- 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.
|
|
52
|
+
- 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.
|
|
53
|
+
|
|
54
|
+
**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.
|
|
55
|
+
- f267c2f: The new `@Ctx()` parameter decorator injects the Hono context (`VelaContext`); `@Res()` still returns it as the response handle.
|
|
56
|
+
|
|
57
|
+
**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.
|
|
58
|
+
|
|
59
|
+
### Patch Changes
|
|
60
|
+
|
|
61
|
+
- Updated dependencies [0b8c649]
|
|
62
|
+
- Updated dependencies [1011653]
|
|
63
|
+
- Updated dependencies [088f4d4]
|
|
64
|
+
- Updated dependencies [f267c2f]
|
|
65
|
+
- Updated dependencies [dfe925c]
|
|
66
|
+
- Updated dependencies [fd11d20]
|
|
67
|
+
- Updated dependencies [748e4f8]
|
|
68
|
+
- Updated dependencies [b227d22]
|
|
69
|
+
- Updated dependencies [096e259]
|
|
70
|
+
- Updated dependencies [fd11d20]
|
|
71
|
+
- Updated dependencies [3418c55]
|
|
72
|
+
- Updated dependencies [fd11d20]
|
|
73
|
+
- Updated dependencies [d51dbb3]
|
|
74
|
+
- Updated dependencies [f267c2f]
|
|
75
|
+
- Updated dependencies [4a06057]
|
|
76
|
+
- Updated dependencies [f267c2f]
|
|
77
|
+
- Updated dependencies [1bfc1c1]
|
|
78
|
+
- Updated dependencies [f267c2f]
|
|
79
|
+
- Updated dependencies [f267c2f]
|
|
80
|
+
- Updated dependencies [1ef55ac]
|
|
81
|
+
- Updated dependencies [f267c2f]
|
|
82
|
+
- Updated dependencies [b227d22]
|
|
83
|
+
- Updated dependencies [2c92243]
|
|
84
|
+
- @velajs/vela@1.31.0
|
|
85
|
+
- @velajs/authz@1.31.0
|
|
86
|
+
|
|
3
87
|
## 1.30.0
|
|
4
88
|
|
|
5
89
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -18,7 +18,7 @@ import {
|
|
|
18
18
|
} from '@velajs/better-auth';
|
|
19
19
|
|
|
20
20
|
const auth = betterAuth({
|
|
21
|
-
database:
|
|
21
|
+
database: databaseAdapter, // a drizzle, prisma or kysely adapter
|
|
22
22
|
emailAndPassword: { enabled: true },
|
|
23
23
|
socialProviders: { github: { clientId, clientSecret } },
|
|
24
24
|
});
|
|
@@ -49,15 +49,20 @@ export default app; // edge-compatible (.fetch)
|
|
|
49
49
|
|
|
50
50
|
```ts
|
|
51
51
|
BetterAuthModule.forRoot({
|
|
52
|
-
auth, //
|
|
52
|
+
auth, // betterAuth({ ... }) instance, or () => betterAuth({ ... })
|
|
53
53
|
issuer: 'my-app:better-auth', // stable namespace paired with user ids
|
|
54
54
|
basePath: '/api/auth', // default — must match your better-auth config
|
|
55
|
-
|
|
55
|
+
guard: 'global', // default — AuthGuard runs globally in the authenticate phase
|
|
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. `
|
|
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. `guard: 'none'` is intended only for applications that install an equivalent global authentication guard themselves.
|
|
62
|
+
|
|
63
|
+
`basePath`, `mountHandler` and `guard` 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 integrations install globally never block sign-in, including a `TenantGuard` the application registers globally itself; throttling and the other global guards still apply.
|
|
61
66
|
|
|
62
67
|
## Three composition patterns
|
|
63
68
|
|
|
@@ -67,7 +72,6 @@ Authentication has no allow-by-default compatibility mode. Use `@Public(true)` f
|
|
|
67
72
|
imports: [
|
|
68
73
|
BetterAuthModule.forRoot({
|
|
69
74
|
auth: betterAuth({ database, plugins: [magicLink({ sendMagicLink }), apiKey()] }),
|
|
70
|
-
isGlobal: true,
|
|
71
75
|
}),
|
|
72
76
|
]
|
|
73
77
|
```
|
|
@@ -80,15 +84,18 @@ imports: [
|
|
|
80
84
|
imports: [
|
|
81
85
|
BetterAuthModule.forRootAsync({
|
|
82
86
|
inject: [ENV, EmailService],
|
|
83
|
-
useFactory: (env, email) =>
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
87
|
+
useFactory: (env, email) => ({
|
|
88
|
+
// Built on the first authentication, not while the application initializes.
|
|
89
|
+
auth: () =>
|
|
90
|
+
betterAuth({
|
|
91
|
+
database: drizzleAdapter(drizzle(env.DB), { provider: 'sqlite' }),
|
|
92
|
+
plugins: [
|
|
93
|
+
magicLink({ sendMagicLink: (data) => email.send(data) }), // DI'd EmailService
|
|
94
|
+
apiKey(),
|
|
95
|
+
twoFactor(),
|
|
96
|
+
],
|
|
97
|
+
}),
|
|
90
98
|
}),
|
|
91
|
-
isGlobal: true,
|
|
92
99
|
}),
|
|
93
100
|
]
|
|
94
101
|
```
|
|
@@ -130,8 +137,9 @@ export class MagicLinkAuthModule {}
|
|
|
130
137
|
BetterAuthModule.forRootAsync({
|
|
131
138
|
imports: [MagicLinkAuthModule, OAuthAuthModule],
|
|
132
139
|
inject: [MAGIC_LINK_PLUGIN, OAUTH_PLUGIN],
|
|
133
|
-
useFactory: (magicLink, oauth) =>
|
|
134
|
-
|
|
140
|
+
useFactory: (magicLink, oauth) => ({
|
|
141
|
+
auth: () => betterAuth({ database, plugins: [magicLink, oauth] }),
|
|
142
|
+
}),
|
|
135
143
|
}),
|
|
136
144
|
],
|
|
137
145
|
})
|
|
@@ -148,18 +156,20 @@ import { BetterAuthService } from '@velajs/better-auth';
|
|
|
148
156
|
|
|
149
157
|
@Injectable()
|
|
150
158
|
class AdminUserService {
|
|
151
|
-
constructor(
|
|
159
|
+
constructor(
|
|
160
|
+
@Inject(BetterAuthService) private readonly authService: BetterAuthService<typeof auth>,
|
|
161
|
+
) {}
|
|
152
162
|
|
|
153
163
|
listSessions(userId: string) {
|
|
154
|
-
return this.
|
|
164
|
+
return this.authService.api.listUserSessions({ userId });
|
|
155
165
|
}
|
|
156
166
|
revoke(token: string) {
|
|
157
|
-
return this.
|
|
167
|
+
return this.authService.api.revokeSession({ sessionToken: token });
|
|
158
168
|
}
|
|
159
169
|
}
|
|
160
170
|
```
|
|
161
171
|
|
|
162
|
-
|
|
172
|
+
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
173
|
|
|
164
174
|
## Decorators
|
|
165
175
|
|
|
@@ -263,7 +273,7 @@ import { BetterAuthService, Public } from '@velajs/better-auth';
|
|
|
263
273
|
@Controller('/auth')
|
|
264
274
|
class CustomCatchallController {
|
|
265
275
|
constructor(@Inject(BetterAuthService) private auth: BetterAuthService) {}
|
|
266
|
-
@All('/*') handle(@Req()
|
|
276
|
+
@All('/*') handle(@Req() request: Request) { return this.auth.handler(request); }
|
|
267
277
|
}
|
|
268
278
|
```
|
|
269
279
|
|
|
@@ -13,20 +13,32 @@ 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
|
-
|
|
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
30
|
/**
|
|
24
|
-
*
|
|
25
|
-
*
|
|
31
|
+
* `'global'` (default) installs AuthGuard as a global guard in the
|
|
32
|
+
* `authenticate` phase, so it runs before tenant, authorization and feature
|
|
33
|
+
* guards whatever the import order. Use `'none'` only when the application
|
|
34
|
+
* installs an equivalent authentication guard itself. Structural.
|
|
26
35
|
*/
|
|
27
|
-
|
|
36
|
+
guard?: 'global' | 'none';
|
|
37
|
+
/** Mount the catch-all better-auth handler (default `true`). Structural. */
|
|
28
38
|
mountHandler?: boolean;
|
|
29
39
|
}
|
|
40
|
+
/** The fields `forRootAsync` takes alongside its factory: they shape the module graph. */
|
|
41
|
+
type BetterAuthStructuralOption = 'basePath' | 'guard' | 'mountHandler';
|
|
30
42
|
type User$1 = User;
|
|
31
43
|
type Session$1 = Session;
|
|
32
44
|
//#endregion
|
|
@@ -35,15 +47,13 @@ type Session$1 = Session;
|
|
|
35
47
|
* The single injectable consumers reach for to interact with better-auth.
|
|
36
48
|
* Wraps the underlying `betterAuth({...})` instance with lazy construction:
|
|
37
49
|
*
|
|
38
|
-
* - `
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
* `service.api` / `service.handler`), the native environment is registered and the
|
|
46
|
-
* factory can read them safely.
|
|
50
|
+
* - `auth` is an instance — the builder returns it, so the first `.auth` /
|
|
51
|
+
* `.api` / `.handler` access is effectively a read-and-cache.
|
|
52
|
+
* - `auth` is a function (`auth: () => betterAuth({ ... })`, typically
|
|
53
|
+
* returned by a `forRootAsync` factory) — the first access calls it. On
|
|
54
|
+
* Workers, construction then happens on the first request (when AuthGuard
|
|
55
|
+
* or the catch-all calls `service.api` / `service.handler`), never at
|
|
56
|
+
* bootstrap.
|
|
47
57
|
*
|
|
48
58
|
* Used directly by AuthGuard and the catch-all controller. Consumers in
|
|
49
59
|
* application code inject the same way: `@Inject(BetterAuthService)`.
|
|
@@ -63,5 +73,5 @@ declare class BetterAuthService<TAuth extends BetterAuthInstance = BetterAuthIns
|
|
|
63
73
|
get handler(): TAuth['handler'];
|
|
64
74
|
}
|
|
65
75
|
//#endregion
|
|
66
|
-
export {
|
|
67
|
-
//# sourceMappingURL=better-auth.service-
|
|
76
|
+
export { BetterAuthStructuralOption as a, BetterAuthRuntimeOptions as i, BetterAuthInstance as n, Session$1 as o, BetterAuthModuleOptions as r, User$1 as s, BetterAuthService as t };
|
|
77
|
+
//# sourceMappingURL=better-auth.service-98MF2Inz.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 * - `
|
|
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,28 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
import { CanActivate,
|
|
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-98MF2Inz.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
|
-
*
|
|
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 `AuthGuard`, registered application-wide by default.
|
|
13
12
|
*
|
|
14
13
|
* ```ts
|
|
14
|
+
* BetterAuthModule.forRoot({ auth: betterAuth({ ... }) });
|
|
15
15
|
* BetterAuthModule.forRootAsync({
|
|
16
|
-
* inject: [ENV
|
|
17
|
-
* useFactory: (env
|
|
18
|
-
* betterAuth({ database: drizzleAdapter(drizzle(env.DB), ...) }),
|
|
16
|
+
* inject: [ENV],
|
|
17
|
+
* useFactory: (env) => ({ auth: () => betterAuth({ database: env.DB }), issuer: 'accounts' }),
|
|
19
18
|
* });
|
|
20
19
|
* ```
|
|
21
20
|
*
|
|
22
|
-
*
|
|
21
|
+
* `basePath`, `mountHandler` and `guard` are structural: `forRootAsync`
|
|
22
|
+
* takes them alongside the factory. The factory runs when the application
|
|
23
|
+
* initializes; an `auth` function it returns runs on first authentication.
|
|
23
24
|
*/
|
|
24
|
-
|
|
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
|
-
}
|
|
25
|
+
export declare class BetterAuthModule extends ConfigurableModuleClass {}
|
|
55
26
|
//#endregion
|
|
56
27
|
//#region src/better-auth.controller.d.ts
|
|
57
28
|
/**
|
|
@@ -59,6 +30,7 @@ export declare class BetterAuthModule {
|
|
|
59
30
|
* (default `/api/auth`). This is a factory because vela reads a controller's
|
|
60
31
|
* route off the class at decoration time, so a custom base path needs its own
|
|
61
32
|
* decorated class — the path can't be parametrized on a single shared class.
|
|
33
|
+
* Calls with the same base path return the same class.
|
|
62
34
|
*
|
|
63
35
|
* Two base paths to keep consistent:
|
|
64
36
|
* - this `basePath` is RELATIVE to vela's `globalPrefix` (always prepended);
|
|
@@ -77,6 +49,8 @@ export declare class AuthGuard implements CanActivate {
|
|
|
77
49
|
private readonly auth;
|
|
78
50
|
private readonly opts;
|
|
79
51
|
private readonly reflector;
|
|
52
|
+
/** Global guards run authentication first, then tenant, authorization and feature phases. */
|
|
53
|
+
static readonly phase: GuardPhase;
|
|
80
54
|
constructor(auth: BetterAuthService, opts: BetterAuthRuntimeOptions, reflector: Reflector);
|
|
81
55
|
canActivate(context: ExecutionContext): Promise<boolean>;
|
|
82
56
|
}
|
|
@@ -122,11 +96,11 @@ export declare const CurrentUser: (data?: unknown, ...pipes: import("@velajs/vel
|
|
|
122
96
|
export declare const CurrentSession: (data?: unknown, ...pipes: import("@velajs/vela/module-kit").PipeType[]) => ParameterDecorator;
|
|
123
97
|
//#endregion
|
|
124
98
|
//#region src/decorators/public.decorator.d.ts
|
|
125
|
-
export declare const Public: import("@velajs/vela").ReflectableDecorator<boolean>;
|
|
99
|
+
export declare const Public: import("@velajs/vela").ReflectableDecorator<boolean, boolean>;
|
|
126
100
|
export declare const PUBLIC_KEY: string;
|
|
127
101
|
//#endregion
|
|
128
102
|
//#region src/decorators/optional-auth.decorator.d.ts
|
|
129
|
-
export declare const OptionalAuth: import("@velajs/vela").ReflectableDecorator<boolean>;
|
|
103
|
+
export declare const OptionalAuth: import("@velajs/vela").ReflectableDecorator<boolean, boolean>;
|
|
130
104
|
export declare const OPTIONAL_AUTH_KEY: string;
|
|
131
105
|
//#endregion
|
|
132
106
|
//#region src/authz-bridge.d.ts
|
|
@@ -143,7 +117,7 @@ export declare const BETTER_AUTH_ISSUER = "better-auth";
|
|
|
143
117
|
/**
|
|
144
118
|
* Pure authorization projection; this does not authenticate or publish trusted state.
|
|
145
119
|
* Adapts an already verified better-auth user into a stable `@velajs/authz` {@link Identity}.
|
|
146
|
-
* The issuer scopes `user.id` as
|
|
120
|
+
* The issuer scopes `user.id` as the `subject`;
|
|
147
121
|
* the admin-plugin `role` field supplies local roles.
|
|
148
122
|
*
|
|
149
123
|
* Fail-closed: a missing user (`null`/`undefined`, i.e. an unauthenticated
|
|
@@ -184,5 +158,5 @@ export declare const permissionsFromAcRole: (role: BetterAuthAcRole) => string[]
|
|
|
184
158
|
*/
|
|
185
159
|
export declare const betterAuthAcResolver: (roles: Readonly<Record<string, BetterAuthAcRole>>) => PermissionResolver;
|
|
186
160
|
//#endregion
|
|
187
|
-
export { type AuthUser, type BetterAuthAcRole, type BetterAuthInstance, type BetterAuthModuleOptions, type BetterAuthRuntimeOptions, BetterAuthService, type BetterAuthUpgradeSession, type BetterAuthUpgradeTenantResolver, type Session, type User };
|
|
161
|
+
export { type AuthUser, type BetterAuthAcRole, type BetterAuthInstance, type BetterAuthModuleOptions, type BetterAuthRuntimeOptions, BetterAuthService, type BetterAuthStructuralOption, type BetterAuthUpgradeSession, type BetterAuthUpgradeTenantResolver, type Session, type User };
|
|
188
162
|
//# 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,
|
|
2
|
+
import { APP_GUARD, 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(
|
|
44
|
-
return this.auth.handler(
|
|
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,83 @@ AuthGuard = __decorate([
|
|
|
213
224
|
], AuthGuard);
|
|
214
225
|
//#endregion
|
|
215
226
|
//#region src/better-auth.module.ts
|
|
216
|
-
const
|
|
217
|
-
|
|
218
|
-
function
|
|
219
|
-
const
|
|
220
|
-
if (
|
|
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
|
-
|
|
238
|
+
guard: options.guard ?? "global",
|
|
244
239
|
mountHandler: options.mountHandler ?? true
|
|
245
240
|
};
|
|
246
241
|
}
|
|
247
|
-
/**
|
|
248
|
-
function
|
|
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
|
-
};
|
|
242
|
+
/** The instance itself, or the one its builder function returns. */
|
|
243
|
+
function buildAuth(auth) {
|
|
244
|
+
return typeof auth === "function" ? auth() : auth;
|
|
258
245
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
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);
|
|
246
|
+
const { ConfigurableModuleClass } = defineModule({
|
|
247
|
+
name: "BetterAuth",
|
|
248
|
+
optionsToken: MODULE_OPTIONS,
|
|
249
|
+
structural: [
|
|
250
|
+
"basePath",
|
|
251
|
+
"guard",
|
|
252
|
+
"mountHandler"
|
|
253
|
+
],
|
|
254
|
+
defaults: {
|
|
255
|
+
basePath: DEFAULT_BETTER_AUTH_BASE_PATH,
|
|
256
|
+
guard: "global",
|
|
257
|
+
mountHandler: true
|
|
258
|
+
},
|
|
259
|
+
setup: ({ OPTIONS, options }) => {
|
|
260
|
+
const basePath = normalizeBetterAuthBasePath(options.basePath);
|
|
261
|
+
const guard = options.guard;
|
|
262
|
+
if (guard !== "global" && guard !== "none") throw new Error("@velajs/better-auth: guard must be 'global' or 'none'");
|
|
263
|
+
const controllers = options.mountHandler === false ? [] : [createBetterAuthCatchallController(basePath)];
|
|
301
264
|
return {
|
|
302
|
-
module: BetterAuthModule,
|
|
303
|
-
key,
|
|
304
|
-
imports: options.imports ?? [],
|
|
305
265
|
providers: [
|
|
306
|
-
defineProvider(BETTER_AUTH_OPTIONS, {
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
266
|
+
defineProvider(BETTER_AUTH_OPTIONS, {
|
|
267
|
+
useFactory: (resolved) => runtimeOptions(resolved),
|
|
268
|
+
inject: [OPTIONS]
|
|
269
|
+
}),
|
|
270
|
+
defineProvider(BETTER_AUTH_BUILDER, {
|
|
271
|
+
useFactory: (resolved) => () => buildAuth(resolved.auth),
|
|
272
|
+
inject: [OPTIONS]
|
|
311
273
|
}),
|
|
312
|
-
|
|
313
|
-
|
|
274
|
+
BetterAuthService,
|
|
275
|
+
AuthGuard,
|
|
276
|
+
...guard === "global" ? [defineProvider(APP_GUARD, { useExisting: AuthGuard })] : []
|
|
314
277
|
],
|
|
315
|
-
controllers
|
|
316
|
-
exports:
|
|
278
|
+
controllers,
|
|
279
|
+
exports: [
|
|
280
|
+
BetterAuthService,
|
|
281
|
+
BETTER_AUTH_OPTIONS,
|
|
282
|
+
AuthGuard
|
|
283
|
+
]
|
|
317
284
|
};
|
|
318
285
|
}
|
|
319
|
-
};
|
|
286
|
+
});
|
|
287
|
+
/**
|
|
288
|
+
* better-auth for Vela: `BetterAuthService`, the catch-all handler under
|
|
289
|
+
* `basePath`, and `AuthGuard`, registered application-wide by default.
|
|
290
|
+
*
|
|
291
|
+
* ```ts
|
|
292
|
+
* BetterAuthModule.forRoot({ auth: betterAuth({ ... }) });
|
|
293
|
+
* BetterAuthModule.forRootAsync({
|
|
294
|
+
* inject: [ENV],
|
|
295
|
+
* useFactory: (env) => ({ auth: () => betterAuth({ database: env.DB }), issuer: 'accounts' }),
|
|
296
|
+
* });
|
|
297
|
+
* ```
|
|
298
|
+
*
|
|
299
|
+
* `basePath`, `mountHandler` and `guard` are structural: `forRootAsync`
|
|
300
|
+
* takes them alongside the factory. The factory runs when the application
|
|
301
|
+
* initializes; an `auth` function it returns runs on first authentication.
|
|
302
|
+
*/
|
|
303
|
+
var BetterAuthModule = class extends ConfigurableModuleClass {};
|
|
320
304
|
//#endregion
|
|
321
305
|
//#region src/upgrade-authenticator.ts
|
|
322
306
|
/**
|
|
@@ -387,7 +371,7 @@ const normalizeRoles = (role) => {
|
|
|
387
371
|
/**
|
|
388
372
|
* Pure authorization projection; this does not authenticate or publish trusted state.
|
|
389
373
|
* Adapts an already verified better-auth user into a stable `@velajs/authz` {@link Identity}.
|
|
390
|
-
* The issuer scopes `user.id` as
|
|
374
|
+
* The issuer scopes `user.id` as the `subject`;
|
|
391
375
|
* the admin-plugin `role` field supplies local roles.
|
|
392
376
|
*
|
|
393
377
|
* Fail-closed: a missing user (`null`/`undefined`, i.e. an unauthenticated
|
|
@@ -401,7 +385,6 @@ const identityFromUser = (user, issuer = BETTER_AUTH_ISSUER, principalType = "us
|
|
|
401
385
|
issuer,
|
|
402
386
|
subject: user.id,
|
|
403
387
|
principalType,
|
|
404
|
-
userId: user.id,
|
|
405
388
|
roles: normalizeRoles(user.role)
|
|
406
389
|
};
|
|
407
390
|
};
|
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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ACX,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 { APP_GUARD, 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 guard: options.guard ?? 'global',\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', 'guard', 'mountHandler'],\n // Spelling out a default configures what leaving it out does: one instance.\n defaults: { basePath: DEFAULT_BETTER_AUTH_BASE_PATH, guard: 'global', mountHandler: true },\n setup: ({ OPTIONS, options }) => {\n // Validates the mount path and guard when the module is declared, before bootstrap.\n const basePath = normalizeBetterAuthBasePath(options.basePath);\n const guard = options.guard;\n if (guard !== 'global' && guard !== 'none') {\n throw new Error(\"@velajs/better-auth: guard must be 'global' or 'none'\");\n }\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 // Fail closed: every route authenticates unless it opts out. AuthGuard\n // declares the `authenticate` phase, so it runs first whatever the\n // import order.\n ...(guard === 'global' ? [defineProvider(APP_GUARD, { useExisting: 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 `AuthGuard`, registered application-wide by default.\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`, `mountHandler` and `guard` 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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c,aAAa,IAAI,IAAI,KAAK,CAAC,GAAG,IAAI,IAAI,UAAU;EAE3E,OAAO;CACT,EACF;AACF"}
|
package/dist/testing/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as BetterAuthService } from "../better-auth.service-
|
|
1
|
+
import { t as BetterAuthService } from "../better-auth.service-98MF2Inz.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.
|
|
3
|
+
"version": "1.31.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.
|
|
50
|
+
"@velajs/authz": "1.31.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.
|
|
67
|
-
"@velajs/
|
|
68
|
-
"@velajs/
|
|
66
|
+
"@velajs/tenant": "1.31.0",
|
|
67
|
+
"@velajs/testing": "1.31.0",
|
|
68
|
+
"@velajs/vela": "1.31.0"
|
|
69
69
|
},
|
|
70
70
|
"peerDependencies": {
|
|
71
71
|
"better-auth": ">=1.2.0",
|
|
72
72
|
"hono": ">=4",
|
|
73
|
-
"@velajs/vela": "^1.
|
|
73
|
+
"@velajs/vela": "^1.31.0"
|
|
74
74
|
},
|
|
75
75
|
"engines": {
|
|
76
76
|
"node": ">=24"
|