@velajs/better-auth 1.33.0 → 1.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.34.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 7ba8f90: Require Better Auth `^1.7.29`, the release the integration is now tested against, including the organization plugin on its own database adapter. The previous `>=1.2.0` peer range covered releases no test exercised.
8
+ - 1e90154: Select a tenant from a route parameter and admit it with the principal's roles in that tenant.
9
+
10
+ `pathTenant(name, { resolve })` selects the tenant from a path segment such as `:workspace` and can map it to the canonical id, for example by slug; an unresolved value is denied like a tenant the principal may not enter. Selectors may now be asynchronous and receive the matched route.
11
+
12
+ `TenantModule` takes `deniedStatus: 404` to answer unknown tenants, non-members and conflicting selections with the same `Not Found` response, and `identityTenantConflict: 'selector'` to let the selected tenant win over the tenant the identity is bound to (such as Better Auth's active organization). Admission still checks membership of the selected tenant and rebinds the request identity to it. The defaults, `403` and rejecting the conflict, are unchanged.
13
+
14
+ `authorize` may return `{ roles }` instead of `true`. The roles appear on the tenant snapshot and replace the request identity's roles, so role and permission guards decide by the role in the admitted tenant. Core's `setTrustedContextTenant` and `setTrustedRequestTenant` accept `{ rebind, roles }` for this; without them an admission cannot replace a bound tenant or change roles, as before.
15
+
16
+ `betterAuthOrganizations({ auth, issuer, roles })` supplies `lookup`, `authorize` and `organizationIdBySlug` from the Better Auth organization plugin through Better Auth's own database adapter, admitting members with their organization roles.
17
+
18
+ ### Patch Changes
19
+
20
+ - Updated dependencies [0202d0f]
21
+ - Updated dependencies [0f9490f]
22
+ - Updated dependencies [1e90154]
23
+ - @velajs/vela@1.37.0
24
+ - @velajs/authz@1.33.0
25
+
3
26
  ## 1.33.0
4
27
 
5
28
  ### Minor Changes
package/README.md CHANGED
@@ -249,6 +249,54 @@ The integration accepts the minimal `BetterAuthInstance` contract instead of `Au
249
249
 
250
250
  Use validated parameter decorators or core's trusted identity reader for authentication state. Import shared permission guards and decorators from `@velajs/authz/vela`.
251
251
 
252
+ ## Organizations as tenants
253
+
254
+ With the organization plugin, `betterAuthOrganizations()` gives `TenantModule`
255
+ (`@velajs/tenant/vela`) its `lookup` and `authorize`: an organization is a
256
+ tenant, and a member is admitted with the roles stored on their membership in
257
+ that organization. Those roles replace `user.role` on the request identity, so
258
+ `@Roles(...)`, `@RequirePermission(...)` with `betterAuthAcResolver(roles)` and
259
+ CRUD guards decide by the role in the tenant being used.
260
+
261
+ ```ts
262
+ import { BetterAuthService, betterAuthOrganizations } from '@velajs/better-auth';
263
+ import { pathTenant } from '@velajs/tenant';
264
+ import { TenantModule } from '@velajs/tenant/vela';
265
+
266
+ const auth = BetterAuthModule.forRootAsync({ /* ... */ });
267
+
268
+ TenantModule.forRootAsync({
269
+ imports: [auth],
270
+ inject: [BetterAuthService],
271
+ useFactory: (service: BetterAuthService) => {
272
+ const organizations = betterAuthOrganizations({
273
+ auth: service,
274
+ issuer: 'accounts', // the BetterAuthModule issuer
275
+ roles: ['owner', 'admin', 'editor', 'viewer'],
276
+ });
277
+ return {
278
+ lookup: organizations.lookup,
279
+ authorize: organizations.authorize,
280
+ // /workspaces/:workspace/... names the organization by its slug.
281
+ selector: pathTenant('workspace', { resolve: organizations.organizationIdBySlug }),
282
+ // The URL wins over the session's active organization; membership is still checked.
283
+ identityTenantConflict: 'selector',
284
+ // Unknown workspaces and non-members both answer 404.
285
+ deniedStatus: 404,
286
+ };
287
+ },
288
+ });
289
+ ```
290
+
291
+ `issuer` must equal the module's `issuer` (default `better-auth:<basePath>`);
292
+ principals of any other issuer are never members. With `roles`, stored roles
293
+ outside the list are dropped and a member left with none is denied (Better Auth
294
+ keeps its built-in `member` role alongside custom ones). Each admission reads the
295
+ organization and the membership through Better Auth's own database adapter, so
296
+ it works with whichever adapter the instance uses, including Drizzle on D1.
297
+ Without `identityTenantConflict: 'selector'`, a request for another organization
298
+ than the session's active one is refused.
299
+
252
300
  ## Edge-safe DB adapters
253
301
 
254
302
  `@velajs/better-auth` itself is `node:`-clean. Edge-safety of your runtime depends on your better-auth DB adapter:
@@ -1,25 +1,22 @@
1
1
  import { Inject, Injectable, InjectionToken } from "@velajs/vela";
2
- //#region \0@oxc-project+runtime@0.150.0/helpers/esm/decorateMetadata.js
2
+ // \0@oxc-project+runtime@0.160.0/helpers/esm/decorateMetadata.js
3
3
  function __decorateMetadata(k, v) {
4
4
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
5
5
  }
6
- //#endregion
7
- //#region \0@oxc-project+runtime@0.150.0/helpers/esm/decorateParam.js
6
+ // \0@oxc-project+runtime@0.160.0/helpers/esm/decorateParam.js
8
7
  function __decorateParam(paramIndex, decorator) {
9
8
  return function(target, key) {
10
9
  decorator(target, key, paramIndex);
11
10
  };
12
11
  }
13
- //#endregion
14
- //#region \0@oxc-project+runtime@0.150.0/helpers/esm/decorate.js
12
+ // \0@oxc-project+runtime@0.160.0/helpers/esm/decorate.js
15
13
  function __decorate(decorators, target, key, desc) {
16
14
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17
15
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
18
16
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
19
17
  return c > 3 && r && Object.defineProperty(target, key, r), r;
20
18
  }
21
- //#endregion
22
- //#region src/better-auth.service.ts
19
+ // src/better-auth.service.ts
23
20
  /**
24
21
  * Internal token holding the auth-construction closure with its inject deps
25
22
  * closed over. Resolves cheaply at module load (just captures references);
@@ -57,7 +54,6 @@ BetterAuthService = __decorate([
57
54
  __decorateParam(0, Inject(BETTER_AUTH_BUILDER)),
58
55
  __decorateMetadata("design:paramtypes", [Function])
59
56
  ], BetterAuthService);
60
- //#endregion
61
57
  export { __decorateMetadata as a, __decorateParam as i, BetterAuthService as n, __decorate as r, BETTER_AUTH_BUILDER as t };
62
58
 
63
- //# sourceMappingURL=better-auth.service-SNg1YFTK.js.map
59
+ //# sourceMappingURL=better-auth.service-BleR_Iv4.js.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 * - `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"}
1
+ {"version":3,"file":"better-auth.service-BleR_Iv4.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;CAES;CAET,YAAyC,OAAoB;EAC3D,KAAK,SAAS;CAChB;;;;;;CAOA,IAAI,OAAc;EAChB,IAAI,CAAC,KAAK,SAAS,KAAK,UAAU,KAAK,OAAO;EAC9C,OAAO,KAAK;CACd;;CAGA,IAAI,MAAoB;EACtB,OAAO,KAAK,KAAK;CACnB;;CAGA,IAAI,UAA4B;EAC9B,OAAO,KAAK,KAAK;CACnB;AACF;;CA7BC,WAAW;CAMG,gBAAA,GAAA,OAAO,mBAAmB,CAAA"}
@@ -1,6 +1,5 @@
1
- import { InjectionToken } from "@velajs/vela";
2
- import { Auth, Session, User } from "better-auth";
3
- //#region src/better-auth.types.d.ts
1
+ import "@velajs/vela";
2
+ import { Auth, Session as Session$1, User as User$1 } from "better-auth";
4
3
  /** The runtime surface required by the integration; concrete instances retain their generics. */
5
4
  interface BetterAuthInstance {
6
5
  readonly api: {
@@ -32,10 +31,8 @@ interface BetterAuthRuntimeOptions {
32
31
  }
33
32
  /** The fields `forRootAsync` takes alongside its factory: they shape the module graph. */
34
33
  type BetterAuthStructuralOption = 'basePath' | 'mountHandler';
35
- type User$1 = User;
36
- type Session$1 = Session;
37
- //#endregion
38
- //#region src/better-auth.service.d.ts
34
+ type User = User$1;
35
+ type Session = Session$1;
39
36
  /**
40
37
  * The single injectable consumers reach for to interact with better-auth.
41
38
  * Wraps the underlying `betterAuth({...})` instance with lazy construction:
@@ -65,6 +62,4 @@ declare class BetterAuthService<TAuth extends BetterAuthInstance = BetterAuthIns
65
62
  /** Convenience accessor — equivalent to `service.auth.handler`. */
66
63
  get handler(): TAuth['handler'];
67
64
  }
68
- //#endregion
69
- export { BetterAuthStructuralOption as a, BetterAuthRuntimeOptions as i, BetterAuthInstance as n, Session$1 as o, BetterAuthModuleOptions as r, User$1 as s, BetterAuthService as t };
70
- //# sourceMappingURL=better-auth.service-D_G-PP8p.d.ts.map
65
+ export { BetterAuthStructuralOption as a, BetterAuthRuntimeOptions as i, BetterAuthInstance as n, Session as o, BetterAuthModuleOptions as r, User as s, BetterAuthService as t };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,7 @@
1
- import { a as BetterAuthStructuralOption, i as BetterAuthRuntimeOptions, n as BetterAuthInstance, o as Session, r as BetterAuthModuleOptions, s as User, t as BetterAuthService } from "./better-auth.service-D_G-PP8p.js";
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-Db61kU5e.js";
2
2
  import { CanActivate, ExecutionContext, GuardPhase, InjectionToken, Reflector, Type } from "@velajs/vela";
3
3
  import { UpgradeAuthenticator, WebSocketUpgradeAuthenticationContext, WebSocketUpgradeIdentity } from "@velajs/vela/websocket";
4
4
  import { Identity, PermissionResolver } from "@velajs/authz";
5
- //#region src/better-auth.module.d.ts
6
5
  declare const ConfigurableModuleClass: import("@velajs/vela").ConfigurableModuleClassType<BetterAuthModuleOptions<BetterAuthInstance>, "forRoot", "create", {
7
6
  isGlobal?: boolean;
8
7
  }, BetterAuthStructuralOption>;
@@ -24,8 +23,6 @@ declare const ConfigurableModuleClass: import("@velajs/vela").ConfigurableModule
24
23
  * initializes; an `auth` function it returns runs on first authentication.
25
24
  */
26
25
  export declare class BetterAuthModule extends ConfigurableModuleClass {}
27
- //#endregion
28
- //#region src/better-auth.controller.d.ts
29
26
  /**
30
27
  * Build a catch-all controller that mounts better-auth's handler at `basePath`
31
28
  * (default `/api/auth`). This is a factory because vela reads a controller's
@@ -41,11 +38,7 @@ export declare class BetterAuthModule extends ConfigurableModuleClass {}
41
38
  * Both default to `/api/auth`, so the no-prefix / no-config case just works.
42
39
  */
43
40
  export declare function createBetterAuthCatchallController(basePath?: string): Type;
44
- //#endregion
45
- //#region src/better-auth.tokens.d.ts
46
41
  export declare const BETTER_AUTH_OPTIONS: InjectionToken<BetterAuthRuntimeOptions>;
47
- //#endregion
48
- //#region src/guards/auth.guard.d.ts
49
42
  export declare class AuthGuard implements CanActivate {
50
43
  private readonly auth;
51
44
  private readonly opts;
@@ -55,8 +48,6 @@ export declare class AuthGuard implements CanActivate {
55
48
  constructor(auth: BetterAuthService, opts: BetterAuthRuntimeOptions, reflector: Reflector);
56
49
  canActivate(context: ExecutionContext): Promise<boolean>;
57
50
  }
58
- //#endregion
59
- //#region src/upgrade-authenticator.d.ts
60
51
  /** The validated Better Auth session behind a WebSocket upgrade. */
61
52
  interface BetterAuthUpgradeSession {
62
53
  readonly user: User;
@@ -89,22 +80,12 @@ export declare class BetterAuthUpgradeAuthenticator implements UpgradeAuthentica
89
80
  constructor(auth: BetterAuthService, options: BetterAuthRuntimeOptions, resolveTenant?: BetterAuthUpgradeTenantResolver | undefined);
90
81
  authenticate(request: Request, context: WebSocketUpgradeAuthenticationContext): Promise<WebSocketUpgradeIdentity | false>;
91
82
  }
92
- //#endregion
93
- //#region src/decorators/current-user.decorator.d.ts
94
83
  export declare const CurrentUser: (data?: unknown, ...pipes: import("@velajs/vela/module-kit").PipeType[]) => ParameterDecorator;
95
- //#endregion
96
- //#region src/decorators/current-session.decorator.d.ts
97
84
  export declare const CurrentSession: (data?: unknown, ...pipes: import("@velajs/vela/module-kit").PipeType[]) => ParameterDecorator;
98
- //#endregion
99
- //#region src/decorators/public.decorator.d.ts
100
85
  export declare const Public: import("@velajs/vela").ReflectableDecorator<boolean, boolean>;
101
86
  export declare const PUBLIC_KEY: string;
102
- //#endregion
103
- //#region src/decorators/optional-auth.decorator.d.ts
104
87
  export declare const OptionalAuth: import("@velajs/vela").ReflectableDecorator<boolean, boolean>;
105
88
  export declare const OPTIONAL_AUTH_KEY: string;
106
- //#endregion
107
- //#region src/authz-bridge.d.ts
108
89
  /**
109
90
  * A better-auth user carrying the optional `role` field contributed by the
110
91
  * admin plugin. `role` may be a single role, a comma-separated list, or an
@@ -158,6 +139,81 @@ export declare const permissionsFromAcRole: (role: BetterAuthAcRole) => string[]
158
139
  * ```
159
140
  */
160
141
  export declare const betterAuthAcResolver: (roles: Readonly<Record<string, BetterAuthAcRole>>) => PermissionResolver;
161
- //#endregion
162
- export { type AuthUser, type BetterAuthAcRole, type BetterAuthInstance, type BetterAuthModuleOptions, type BetterAuthRuntimeOptions, BetterAuthService, type BetterAuthStructuralOption, type BetterAuthUpgradeSession, type BetterAuthUpgradeTenantResolver, type Session, type User };
163
- //# sourceMappingURL=index.d.ts.map
142
+ /** A Better Auth organization as a tenant record (`@velajs/tenant` `TenantRecord`). */
143
+ interface OrganizationTenantRecord {
144
+ readonly id: string;
145
+ readonly name: string;
146
+ readonly status: 'active';
147
+ readonly revision: number;
148
+ readonly settings: Readonly<Record<string, never>>;
149
+ }
150
+ interface BetterAuthOrganizationsOptions {
151
+ /**
152
+ * The Better Auth instance, the `BetterAuthService` that wraps it, or a
153
+ * function returning either. Read on first use, never at bootstrap.
154
+ */
155
+ readonly auth: BetterAuthService | Pick<BetterAuthInstance, '$context'> | (() => Pick<BetterAuthInstance, '$context'>);
156
+ /**
157
+ * The issuer `BetterAuthModule` publishes principals under (its `issuer`
158
+ * option, `better-auth:<basePath>` by default). Principals from any other
159
+ * issuer are never members.
160
+ */
161
+ readonly issuer: string;
162
+ /**
163
+ * The organization roles the application knows. A member's stored roles
164
+ * outside this list are dropped; a member left with none is denied.
165
+ * Without it, every stored role is kept.
166
+ */
167
+ readonly roles?: readonly string[];
168
+ }
169
+ /** Lookup, membership and slug resolution for `TenantModule` from Better Auth organizations. */
170
+ interface BetterAuthOrganizations {
171
+ /** `TenantModule` `lookup`: an organization by id, as an active tenant. */
172
+ readonly lookup: {
173
+ get(id: string): Promise<OrganizationTenantRecord | null>;
174
+ };
175
+ /**
176
+ * `TenantModule` `authorize`: the principal's membership of the organization.
177
+ * Admits with the member's organization roles, which then replace the
178
+ * request identity's roles (`user.role`) for the rest of the pipeline.
179
+ */
180
+ authorize(input: {
181
+ readonly tenant: {
182
+ readonly id: string;
183
+ };
184
+ readonly principal: {
185
+ readonly issuer: string;
186
+ readonly subject: string;
187
+ readonly principalType: string;
188
+ };
189
+ }): Promise<false | {
190
+ readonly roles: readonly string[];
191
+ }>;
192
+ /** An organization id by slug, for `pathTenant(name, { resolve })`. */
193
+ organizationIdBySlug(slug: string): Promise<string | undefined>;
194
+ }
195
+ /**
196
+ * Tenants from the Better Auth organization plugin: an organization is a
197
+ * tenant, its members are admitted with their organization roles.
198
+ *
199
+ * ```ts
200
+ * TenantModule.forRootAsync({
201
+ * imports: [AuthModule],
202
+ * inject: [BetterAuthService],
203
+ * useFactory: (auth) => {
204
+ * const organizations = betterAuthOrganizations({ auth, issuer: 'accounts', roles });
205
+ * return {
206
+ * ...organizations,
207
+ * selector: pathTenant('workspace', { resolve: organizations.organizationIdBySlug }),
208
+ * identityTenantConflict: 'selector',
209
+ * deniedStatus: 404,
210
+ * };
211
+ * },
212
+ * });
213
+ * ```
214
+ *
215
+ * Every admission reads the organization and the membership from Better
216
+ * Auth's own database adapter; nothing is cached.
217
+ */
218
+ export declare function betterAuthOrganizations(options: BetterAuthOrganizationsOptions): BetterAuthOrganizations;
219
+ export { type AuthUser, type BetterAuthAcRole, type BetterAuthInstance, type BetterAuthModuleOptions, type BetterAuthOrganizations, type BetterAuthOrganizationsOptions, type BetterAuthRuntimeOptions, BetterAuthService, type BetterAuthStructuralOption, type BetterAuthUpgradeSession, type BetterAuthUpgradeTenantResolver, type OrganizationTenantRecord, type Session, type User };
package/dist/index.js CHANGED
@@ -1,12 +1,11 @@
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
1
  import { All, Controller, Inject, Injectable, InjectionToken, Optional, Reflector, Req, UnauthorizedException, createParamDecorator, defineModule, defineProvider } from "@velajs/vela";
3
2
  import { SkipGuardPhases, clearTrustedRequestIdentity, createTrustedRequestIdentityStore, getTrustedContextRequest, setTrustedRequestIdentity } from "@velajs/vela/module-kit";
3
+ import { a as __decorateMetadata, i as __decorateParam, n as BetterAuthService, r as __decorate, t as BETTER_AUTH_BUILDER } from "./better-auth.service-BleR_Iv4.js";
4
4
  import { getContextIdentity } from "@velajs/authz/vela";
5
- //#region src/decorators/public.decorator.ts
5
+ // 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
8
+ // src/base-path.ts
10
9
  const DEFAULT_BETTER_AUTH_BASE_PATH = "/api/auth";
11
10
  /** Validate and canonicalize the route prefix used by the public auth controller. */
12
11
  function normalizeBetterAuthBasePath(value) {
@@ -21,8 +20,7 @@ function normalizeBetterAuthBasePath(value) {
21
20
  if (decoded.split("/").some((segment) => segment === "." || segment === "..")) throw new Error("@velajs/better-auth: basePath must not contain dot segments");
22
21
  return basePath;
23
22
  }
24
- //#endregion
25
- //#region src/better-auth.controller.ts
23
+ // src/better-auth.controller.ts
26
24
  const controllers = /* @__PURE__ */ new Map();
27
25
  /**
28
26
  * Build a catch-all controller that mounts better-auth's handler at `basePath`
@@ -68,11 +66,9 @@ function createBetterAuthCatchallController(basePath = "/api/auth") {
68
66
  controllers.set(normalizedBasePath, BetterAuthCatchallController);
69
67
  return BetterAuthCatchallController;
70
68
  }
71
- //#endregion
72
- //#region src/better-auth.tokens.ts
69
+ // src/better-auth.tokens.ts
73
70
  const BETTER_AUTH_OPTIONS = new InjectionToken("vela.BetterAuthOptions");
74
- //#endregion
75
- //#region src/auth-request-state.ts
71
+ // src/auth-request-state.ts
76
72
  const sessions = createTrustedRequestIdentityStore();
77
73
  function beginAuthRequest(context) {
78
74
  clearTrustedRequestIdentity(context.getRequest());
@@ -95,9 +91,8 @@ function getAuthRequestState(context) {
95
91
  const request = getTrustedContextRequest(context);
96
92
  return request ? sessions.get(request) : void 0;
97
93
  }
98
- //#endregion
99
- //#region src/session-data.ts
100
- function own(value, key) {
94
+ // src/session-data.ts
95
+ function own$1(value, key) {
101
96
  if (typeof value !== "object" || value === null) return void 0;
102
97
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
103
98
  return descriptor && "value" in descriptor ? descriptor.value : void 0;
@@ -113,31 +108,31 @@ function optionalString(value) {
113
108
  }
114
109
  /** Keep plugin data opaque; base model fields below are validated individually. */
115
110
  function dataProperties(value) {
116
- return Object.fromEntries(Object.keys(value).map((key) => [key, own(value, key)]));
111
+ return Object.fromEntries(Object.keys(value).map((key) => [key, own$1(value, key)]));
117
112
  }
118
113
  /** Validate the full Better Auth base models, not merely ids masquerading as them. */
119
114
  function validateSessionData(value) {
120
115
  try {
121
- const user = own(value, "user");
122
- const session = own(value, "session");
116
+ const user = own$1(value, "user");
117
+ const session = own$1(value, "session");
123
118
  if (typeof user !== "object" || user === null || typeof session !== "object" || session === null) return;
124
- const id = own(user, "id");
125
- const email = own(user, "email");
126
- const name = own(user, "name");
127
- const emailVerified = own(user, "emailVerified");
128
- const image = own(user, "image");
129
- const createdAt = date(own(user, "createdAt"));
130
- const updatedAt = date(own(user, "updatedAt"));
131
- const sessionId = own(session, "id");
132
- const userId = own(session, "userId");
133
- const token = own(session, "token");
134
- const sessionCreatedAt = date(own(session, "createdAt"));
135
- const sessionUpdatedAt = date(own(session, "updatedAt"));
136
- const expiresAt = date(own(session, "expiresAt"));
137
- const ipAddress = own(session, "ipAddress");
138
- const userAgent = own(session, "userAgent");
139
- const organization = own(session, "activeOrganizationId");
140
- const role = own(user, "role");
119
+ const id = own$1(user, "id");
120
+ const email = own$1(user, "email");
121
+ const name = own$1(user, "name");
122
+ const emailVerified = own$1(user, "emailVerified");
123
+ const image = own$1(user, "image");
124
+ const createdAt = date(own$1(user, "createdAt"));
125
+ const updatedAt = date(own$1(user, "updatedAt"));
126
+ const sessionId = own$1(session, "id");
127
+ const userId = own$1(session, "userId");
128
+ const token = own$1(session, "token");
129
+ const sessionCreatedAt = date(own$1(session, "createdAt"));
130
+ const sessionUpdatedAt = date(own$1(session, "updatedAt"));
131
+ const expiresAt = date(own$1(session, "expiresAt"));
132
+ const ipAddress = own$1(session, "ipAddress");
133
+ const userAgent = own$1(session, "userAgent");
134
+ const organization = own$1(session, "activeOrganizationId");
135
+ const role = own$1(user, "role");
141
136
  let roles = [];
142
137
  if (role !== void 0 && role !== null) {
143
138
  if (typeof role === "string") roles = role.split(",").map((part) => part.trim()).filter(Boolean);
@@ -174,12 +169,10 @@ function validateSessionData(value) {
174
169
  return;
175
170
  }
176
171
  }
177
- //#endregion
178
- //#region src/decorators/optional-auth.decorator.ts
172
+ // src/decorators/optional-auth.decorator.ts
179
173
  const OptionalAuth = Reflector.createDecorator({ key: "vela.auth.optional" });
180
174
  const OPTIONAL_AUTH_KEY = OptionalAuth.KEY;
181
- //#endregion
182
- //#region src/guards/auth.guard.ts
175
+ // src/guards/auth.guard.ts
183
176
  let AuthGuard = class AuthGuard {
184
177
  auth;
185
178
  opts;
@@ -222,8 +215,7 @@ AuthGuard = __decorate([
222
215
  typeof Reflector === "undefined" ? Object : Reflector
223
216
  ])
224
217
  ], AuthGuard);
225
- //#endregion
226
- //#region src/better-auth.module.ts
218
+ // src/better-auth.module.ts
227
219
  const MODULE_OPTIONS = new InjectionToken("vela.better-auth.ModuleOptions");
228
220
  /** Runtime options with defaults applied: what AuthGuard and the upgrade authenticator read. */
229
221
  function runtimeOptions(options) {
@@ -293,8 +285,7 @@ const { ConfigurableModuleClass } = defineModule({
293
285
  * initializes; an `auth` function it returns runs on first authentication.
294
286
  */
295
287
  var BetterAuthModule = class extends ConfigurableModuleClass {};
296
- //#endregion
297
- //#region src/upgrade-authenticator.ts
288
+ // src/upgrade-authenticator.ts
298
289
  /**
299
290
  * Optional tenant resolver for {@link BetterAuthUpgradeAuthenticator}. Provide it
300
291
  * in the module that declares the gateway; without one, the session's active
@@ -341,18 +332,15 @@ BetterAuthUpgradeAuthenticator = __decorate([
341
332
  Object
342
333
  ])
343
334
  ], BetterAuthUpgradeAuthenticator);
344
- //#endregion
345
- //#region src/decorators/current-user.decorator.ts
335
+ // src/decorators/current-user.decorator.ts
346
336
  const CurrentUser = createParamDecorator((_data, ctx) => {
347
337
  return getAuthRequestState(ctx)?.user;
348
338
  });
349
- //#endregion
350
- //#region src/decorators/current-session.decorator.ts
339
+ // src/decorators/current-session.decorator.ts
351
340
  const CurrentSession = createParamDecorator((_data, ctx) => {
352
341
  return getAuthRequestState(ctx)?.session;
353
342
  });
354
- //#endregion
355
- //#region src/authz-bridge.ts
343
+ // src/authz-bridge.ts
356
344
  /** Stable issuer namespace used for better-auth session principals. */
357
345
  const BETTER_AUTH_ISSUER = "better-auth";
358
346
  const normalizeRoles = (role) => {
@@ -414,7 +402,108 @@ const betterAuthAcResolver = (roles) => {
414
402
  return out;
415
403
  } };
416
404
  };
417
- //#endregion
418
- export { AuthGuard, BETTER_AUTH_ISSUER, BETTER_AUTH_OPTIONS, BETTER_AUTH_UPGRADE_TENANT, BetterAuthModule, BetterAuthService, BetterAuthUpgradeAuthenticator, CurrentSession, CurrentUser, OPTIONAL_AUTH_KEY, OptionalAuth, PUBLIC_KEY, Public, betterAuthAcResolver, createBetterAuthCatchallController, identityFromUser, permissionsFromAcRole };
405
+ // src/organization-tenancy.ts
406
+ function own(value, key) {
407
+ if (typeof value !== "object" || value === null) return void 0;
408
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
409
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
410
+ }
411
+ function isOrganizationAdapter(value) {
412
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "findOne") === "function";
413
+ }
414
+ function text(value) {
415
+ return typeof value === "string" && value.length > 0;
416
+ }
417
+ /** Better Auth stores a member's roles as one comma-separated string. */
418
+ function storedRoles(value) {
419
+ if (typeof value !== "string") return [];
420
+ return [...new Set(value.split(",").map((role) => role.trim()).filter(Boolean))];
421
+ }
422
+ /**
423
+ * Tenants from the Better Auth organization plugin: an organization is a
424
+ * tenant, its members are admitted with their organization roles.
425
+ *
426
+ * ```ts
427
+ * TenantModule.forRootAsync({
428
+ * imports: [AuthModule],
429
+ * inject: [BetterAuthService],
430
+ * useFactory: (auth) => {
431
+ * const organizations = betterAuthOrganizations({ auth, issuer: 'accounts', roles });
432
+ * return {
433
+ * ...organizations,
434
+ * selector: pathTenant('workspace', { resolve: organizations.organizationIdBySlug }),
435
+ * identityTenantConflict: 'selector',
436
+ * deniedStatus: 404,
437
+ * };
438
+ * },
439
+ * });
440
+ * ```
441
+ *
442
+ * Every admission reads the organization and the membership from Better
443
+ * Auth's own database adapter; nothing is cached.
444
+ */
445
+ function betterAuthOrganizations(options) {
446
+ if (!text(options.issuer) || options.issuer !== options.issuer.trim()) throw new TypeError("@velajs/better-auth: organizations need the module issuer");
447
+ const known = options.roles === void 0 ? void 0 : new Set(options.roles);
448
+ if (known && [...known].some((role) => !text(role) || role !== role.trim())) throw new TypeError("@velajs/better-auth: organization roles must be non-empty names");
449
+ const instance = () => {
450
+ const source = options.auth;
451
+ if (typeof source === "function") return source();
452
+ return source instanceof BetterAuthService ? source.auth : source;
453
+ };
454
+ const adapter = async () => {
455
+ const found = own(await instance().$context, "adapter");
456
+ if (!isOrganizationAdapter(found)) throw new TypeError("@velajs/better-auth: the auth instance has no database adapter");
457
+ return found;
458
+ };
459
+ const organization = async (field, value) => {
460
+ if (!text(value)) return null;
461
+ const row = await (await adapter()).findOne({
462
+ model: "organization",
463
+ where: [{
464
+ field,
465
+ value
466
+ }]
467
+ });
468
+ const id = own(row, "id");
469
+ const name = own(row, "name");
470
+ return text(id) && typeof name === "string" && own(row, field) === value ? {
471
+ id,
472
+ name
473
+ } : null;
474
+ };
475
+ return Object.freeze({
476
+ lookup: Object.freeze({ async get(id) {
477
+ const found = await organization("id", id);
478
+ return found ? Object.freeze({
479
+ id: found.id,
480
+ name: found.name,
481
+ status: "active",
482
+ revision: 1,
483
+ settings: {}
484
+ }) : null;
485
+ } }),
486
+ async authorize({ tenant, principal }) {
487
+ if (principal.issuer !== options.issuer || principal.principalType !== "user" || !text(principal.subject) || !text(tenant.id)) return false;
488
+ const member = await (await adapter()).findOne({
489
+ model: "member",
490
+ where: [{
491
+ field: "organizationId",
492
+ value: tenant.id
493
+ }, {
494
+ field: "userId",
495
+ value: principal.subject
496
+ }]
497
+ });
498
+ if (own(member, "organizationId") !== tenant.id || own(member, "userId") !== principal.subject) return false;
499
+ const roles = storedRoles(own(member, "role")).filter((role) => !known || known.has(role));
500
+ return roles.length > 0 ? Object.freeze({ roles: Object.freeze(roles) }) : false;
501
+ },
502
+ async organizationIdBySlug(slug) {
503
+ return (await organization("slug", slug))?.id;
504
+ }
505
+ });
506
+ }
507
+ export { AuthGuard, BETTER_AUTH_ISSUER, BETTER_AUTH_OPTIONS, BETTER_AUTH_UPGRADE_TENANT, BetterAuthModule, BetterAuthService, BetterAuthUpgradeAuthenticator, CurrentSession, CurrentUser, OPTIONAL_AUTH_KEY, OptionalAuth, PUBLIC_KEY, Public, betterAuthAcResolver, betterAuthOrganizations, createBetterAuthCatchallController, identityFromUser, permissionsFromAcRole };
419
508
 
420
509
  //# sourceMappingURL=index.js.map
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 { SkipGuardPhases } from '@velajs/vela/module-kit';\nimport { BetterAuthService } from './better-auth.service';\nimport { Public } from './decorators/public.decorator';\nimport { normalizeBetterAuthBasePath } from './base-path';\n\n// One decorated class per base path: every registration of a path, and every\n// call, shares it (the class reads nothing else).\nconst controllers = new Map<string, Type>();\n\n/**\n * Build a catch-all controller that mounts better-auth's handler at `basePath`\n * (default `/api/auth`). This is a factory because vela reads a controller's\n * route off the class at decoration time, so a custom base path needs its own\n * decorated class — the path can't be parametrized on a single shared class.\n * Calls with the same base path return the same class.\n *\n * Two base paths to keep consistent:\n * - this `basePath` is RELATIVE to vela's `globalPrefix` (always prepended);\n * - better-auth routes against its OWN absolute `basePath` (the one you pass to\n * `betterAuth({ basePath })`), which must equal `globalPrefix + basePath`.\n *\n * Both default to `/api/auth`, so the no-prefix / no-config case just works.\n */\nexport function createBetterAuthCatchallController(basePath: string = '/api/auth'): Type {\n const normalizedBasePath = normalizeBetterAuthBasePath(basePath);\n const existing = controllers.get(normalizedBasePath);\n if (existing) return existing;\n // Better Auth authenticates its own endpoints; application-wide tenant\n // admission and authorization do not apply to signing in.\n @Public(true)\n @SkipGuardPhases(['tenant', 'authorize'])\n @Controller(normalizedBasePath)\n class BetterAuthCatchallController {\n // Inject the service — its `.handler` getter triggers lazy construction\n // of the underlying betterAuth() instance on first access, AFTER any\n // runtime adapter middleware (Cloudflare env capture) has run.\n constructor(@Inject(BetterAuthService) private readonly auth: BetterAuthService) {}\n\n @All('/*')\n async handle(@Req() request: Request): Promise<Response> {\n return this.auth.handler(request);\n }\n }\n controllers.set(normalizedBasePath, BetterAuthCatchallController);\n return BetterAuthCatchallController;\n}\n","import { InjectionToken } from '@velajs/vela';\nimport type { BetterAuthRuntimeOptions } from './better-auth.types';\n\nexport const BETTER_AUTH_OPTIONS = new InjectionToken<BetterAuthRuntimeOptions>(\n 'vela.BetterAuthOptions',\n);\n","import type { ExecutionContext } from '@velajs/vela';\nimport {\n clearTrustedRequestIdentity,\n createTrustedRequestIdentityStore,\n getTrustedContextRequest,\n setTrustedRequestIdentity,\n} from '@velajs/vela/module-kit';\nimport type { SessionData } from './session-data';\n\n// This map stores provider payload, never a second authentication authority.\n// A clear, expiry, or identity replacement makes the payload unreachable.\nconst sessions = createTrustedRequestIdentityStore<SessionData>();\n\nexport function beginAuthRequest(context: ExecutionContext): void {\n clearTrustedRequestIdentity(context.getRequest());\n}\n\nexport function authenticateRequest(\n context: ExecutionContext,\n data: SessionData,\n issuer: string,\n): void {\n const request = context.getRequest();\n setTrustedRequestIdentity(request, {\n principal: { issuer, subject: data.user.id, principalType: 'user' },\n expiresAtMs: data.session.expiresAt.getTime(),\n roles: data.roles,\n ...(data.tenantId === undefined ? {} : { tenantId: data.tenantId }),\n });\n sessions.set(request, data);\n}\n\nexport function getAuthRequestState(context: ExecutionContext): SessionData | undefined {\n const request = getTrustedContextRequest(context);\n return request ? sessions.get(request) : undefined;\n}\n","import type { Session, User } from './better-auth.types';\n\nexport interface SessionData {\n readonly user: User;\n readonly session: Session;\n readonly roles: readonly string[];\n readonly tenantId?: string;\n}\n\nfunction own(value: unknown, key: string): unknown {\n if (typeof value !== 'object' || value === null) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n return descriptor && 'value' in descriptor ? descriptor.value : undefined;\n}\n\nfunction requiredString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n\nfunction date(value: unknown): Date | undefined {\n return value instanceof Date && Number.isFinite(value.getTime()) ? new Date(value) : undefined;\n}\n\nfunction optionalString(value: unknown): value is string | null | undefined {\n return value === undefined || value === null || typeof value === 'string';\n}\n\n/** Keep plugin data opaque; base model fields below are validated individually. */\nfunction dataProperties(value: object): Record<string, unknown> {\n return Object.fromEntries(Object.keys(value).map((key) => [key, own(value, key)]));\n}\n\n/** Validate the full Better Auth base models, not merely ids masquerading as them. */\nexport function validateSessionData(value: unknown): SessionData | undefined {\n try {\n const user = own(value, 'user');\n const session = own(value, 'session');\n if (\n typeof user !== 'object' ||\n user === null ||\n typeof session !== 'object' ||\n session === null\n ) {\n return undefined;\n }\n const id = own(user, 'id');\n const email = own(user, 'email');\n const name = own(user, 'name');\n const emailVerified = own(user, 'emailVerified');\n const image = own(user, 'image');\n const createdAt = date(own(user, 'createdAt'));\n const updatedAt = date(own(user, 'updatedAt'));\n const sessionId = own(session, 'id');\n const userId = own(session, 'userId');\n const token = own(session, 'token');\n const sessionCreatedAt = date(own(session, 'createdAt'));\n const sessionUpdatedAt = date(own(session, 'updatedAt'));\n const expiresAt = date(own(session, 'expiresAt'));\n const ipAddress = own(session, 'ipAddress');\n const userAgent = own(session, 'userAgent');\n const organization = own(session, 'activeOrganizationId');\n const role = own(user, 'role');\n let roles: string[] = [];\n if (role !== undefined && role !== null) {\n if (typeof role === 'string')\n roles = role\n .split(',')\n .map((part) => part.trim())\n .filter(Boolean);\n else if (\n Array.isArray(role) &&\n role.every((entry: unknown): entry is string => typeof entry === 'string')\n ) {\n roles = role.map((entry: string) => entry.trim()).filter(Boolean);\n } else return undefined;\n }\n if (\n !requiredString(id) ||\n !requiredString(email) ||\n typeof name !== 'string' ||\n typeof emailVerified !== 'boolean' ||\n !optionalString(image) ||\n !createdAt ||\n !updatedAt ||\n !requiredString(sessionId) ||\n userId !== id ||\n !requiredString(token) ||\n !sessionCreatedAt ||\n !sessionUpdatedAt ||\n !expiresAt ||\n expiresAt.getTime() <= Date.now() ||\n !optionalString(ipAddress) ||\n !optionalString(userAgent) ||\n (organization !== undefined && organization !== null && !requiredString(organization))\n )\n return undefined;\n return {\n user: Object.freeze({\n ...dataProperties(user),\n id,\n email,\n name,\n emailVerified,\n createdAt,\n updatedAt,\n image,\n }),\n session: Object.freeze({\n ...dataProperties(session),\n id: sessionId,\n userId: id,\n token,\n createdAt: sessionCreatedAt,\n updatedAt: sessionUpdatedAt,\n expiresAt,\n ipAddress,\n userAgent,\n }),\n roles: Object.freeze(roles),\n ...(typeof organization === 'string' ? { tenantId: organization } : {}),\n };\n } catch {\n return undefined;\n }\n}\n","import { Reflector } from '@velajs/vela';\n\nexport const OptionalAuth = Reflector.createDecorator<boolean>({ key: 'vela.auth.optional' });\nexport const OPTIONAL_AUTH_KEY = OptionalAuth.KEY;\n","import {\n Inject,\n Injectable,\n Reflector,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n type GuardPhase,\n} from '@velajs/vela';\nimport { getTrustedContextRequest } from '@velajs/vela/module-kit';\nimport { getContextIdentity } from '@velajs/authz/vela';\nimport { BETTER_AUTH_OPTIONS } from '../better-auth.tokens';\nimport { BetterAuthService } from '../better-auth.service';\nimport type { BetterAuthRuntimeOptions } from '../better-auth.types';\nimport { authenticateRequest, beginAuthRequest, getAuthRequestState } from '../auth-request-state';\nimport { validateSessionData } from '../session-data';\nimport { OptionalAuth } from '../decorators/optional-auth.decorator';\nimport { Public } from '../decorators/public.decorator';\n\n@Injectable()\nexport class AuthGuard implements CanActivate {\n /** Global guards run authentication first, then tenant, authorization and feature phases. */\n static readonly phase: GuardPhase = 'authenticate';\n\n constructor(\n @Inject(BetterAuthService) private readonly auth: BetterAuthService,\n @Inject(BETTER_AUTH_OPTIONS) private readonly opts: BetterAuthRuntimeOptions,\n @Inject(Reflector) private readonly reflector: Reflector,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n // Frames trust only the authenticated connection attachment; HTTP cookies\n // and request payload never become ambient WebSocket authentication.\n if (context.getType() === 'ws') {\n if (getContextIdentity(context)) return true;\n throw new UnauthorizedException('Authentication required');\n }\n // Custom HTTP-backed dispatchers authenticate once at the outer boundary.\n // Never re-read credentials or clear shared authority across sibling fields.\n if (context.getType() !== 'http') {\n if (\n getTrustedContextRequest(context) &&\n (getAuthRequestState(context) ||\n this.reflector.getAllAndOverride(Public, context) ||\n this.reflector.getAllAndOverride(OptionalAuth, context))\n )\n return true;\n throw new UnauthorizedException('Authentication required');\n }\n beginAuthRequest(context);\n if (this.reflector.getAllAndOverride(Public, context)) return true;\n\n const raw = await this.auth.api.getSession({ headers: context.getRequest().headers });\n const data = validateSessionData(raw);\n if (data) {\n authenticateRequest(context, data, this.opts.issuer ?? 'better-auth');\n return true;\n }\n if (this.reflector.getAllAndOverride(OptionalAuth, context)) return true;\n throw new UnauthorizedException('Authentication required');\n }\n}\n","import { defineModule, defineProvider, InjectionToken, type Type } from '@velajs/vela';\nimport { createBetterAuthCatchallController } from './better-auth.controller';\nimport { BetterAuthService, BETTER_AUTH_BUILDER } from './better-auth.service';\nimport { BETTER_AUTH_OPTIONS } from './better-auth.tokens';\nimport type {\n BetterAuthInstance,\n BetterAuthModuleOptions,\n BetterAuthRuntimeOptions,\n BetterAuthStructuralOption,\n} from './better-auth.types';\nimport { AuthGuard } from './guards/auth.guard';\nimport { DEFAULT_BETTER_AUTH_BASE_PATH, normalizeBetterAuthBasePath } from './base-path';\n\nconst MODULE_OPTIONS = new InjectionToken<BetterAuthModuleOptions>(\n 'vela.better-auth.ModuleOptions',\n);\n\n/** Runtime options with defaults applied: what AuthGuard and the upgrade authenticator read. */\nfunction runtimeOptions(options: BetterAuthModuleOptions): Required<BetterAuthRuntimeOptions> {\n const auth: unknown = options.auth;\n if (typeof auth !== 'function' && (typeof auth !== 'object' || auth === null)) {\n throw new TypeError(\n '@velajs/better-auth: options need `auth`, a better-auth instance or a function that builds one',\n );\n }\n const basePath = normalizeBetterAuthBasePath(options.basePath);\n const issuer = options.issuer ?? `better-auth:${basePath}`;\n if (issuer.length === 0 || issuer !== issuer.trim()) {\n throw new Error('@velajs/better-auth: issuer must be a non-empty stable namespace');\n }\n return {\n basePath,\n issuer,\n mountHandler: options.mountHandler ?? true,\n };\n}\n\n/** The instance itself, or the one its builder function returns. */\nfunction buildAuth(auth: BetterAuthModuleOptions['auth']): BetterAuthInstance {\n return typeof auth === 'function' ? auth() : auth;\n}\n\nconst { ConfigurableModuleClass } = defineModule<\n BetterAuthModuleOptions,\n BetterAuthStructuralOption\n>({\n name: 'BetterAuth',\n optionsToken: MODULE_OPTIONS,\n structural: ['basePath', 'mountHandler'],\n // Spelling out a default configures what leaving it out does: one instance.\n defaults: { basePath: DEFAULT_BETTER_AUTH_BASE_PATH, mountHandler: true },\n setup: ({ OPTIONS, options }) => {\n // Validates the mount path when the module is declared, before bootstrap.\n const basePath = normalizeBetterAuthBasePath(options.basePath);\n const controllers: Type[] =\n options.mountHandler === false ? [] : [createBetterAuthCatchallController(basePath)];\n return {\n providers: [\n defineProvider(BETTER_AUTH_OPTIONS, {\n useFactory: (resolved) => runtimeOptions(resolved),\n inject: [OPTIONS],\n }),\n // BetterAuthService calls the builder on first use and caches the\n // instance, so a builder function never runs at bootstrap.\n defineProvider(BETTER_AUTH_BUILDER, {\n useFactory: (resolved) => () => buildAuth(resolved.auth),\n inject: [OPTIONS],\n }),\n BetterAuthService,\n AuthGuard,\n ],\n controllers,\n exports: [BetterAuthService, BETTER_AUTH_OPTIONS, AuthGuard],\n };\n },\n});\n\n/**\n * better-auth for Vela: `BetterAuthService`, the catch-all handler under\n * `basePath`, and an injectable `AuthGuard`. Applications install it through `APP_GUARD`\n * with `useExisting: AuthGuard`, or attach it with `@UseGuards`.\n *\n * ```ts\n * BetterAuthModule.forRoot({ auth: betterAuth({ ... }) });\n * BetterAuthModule.forRootAsync({\n * inject: [ENV],\n * useFactory: (env) => ({ auth: () => betterAuth({ database: env.DB }), issuer: 'accounts' }),\n * });\n * ```\n *\n * `basePath` and `mountHandler` are structural: `forRootAsync`\n * takes them alongside the factory. The factory runs when the application\n * initializes; an `auth` function it returns runs on first authentication.\n */\nexport class BetterAuthModule extends ConfigurableModuleClass {}\n","import { Inject, Injectable, InjectionToken, Optional } from '@velajs/vela';\nimport type {\n UpgradeAuthenticator,\n WebSocketUpgradeAuthenticationContext,\n WebSocketUpgradeIdentity,\n} from '@velajs/vela/websocket';\nimport { BetterAuthService } from './better-auth.service';\nimport { BETTER_AUTH_OPTIONS } from './better-auth.tokens';\nimport type { BetterAuthRuntimeOptions, Session, User } from './better-auth.types';\nimport { validateSessionData } from './session-data';\n\n/** The validated Better Auth session behind a WebSocket upgrade. */\nexport interface BetterAuthUpgradeSession {\n readonly user: User;\n readonly session: Session;\n}\n\n/**\n * Chooses the tenant a WebSocket connection joins. Returning no tenant (or\n * throwing) refuses the upgrade.\n */\nexport type BetterAuthUpgradeTenantResolver = (\n session: BetterAuthUpgradeSession,\n context: WebSocketUpgradeAuthenticationContext,\n request: Request,\n) => string | undefined | Promise<string | undefined>;\n\n/**\n * Optional tenant resolver for {@link BetterAuthUpgradeAuthenticator}. Provide it\n * in the module that declares the gateway; without one, the session's active\n * organization is the tenant.\n */\nexport const BETTER_AUTH_UPGRADE_TENANT = new InjectionToken<BetterAuthUpgradeTenantResolver>(\n 'vela.better-auth.UpgradeTenant',\n);\n\n/**\n * WebSocket upgrade authenticator backed by the Better Auth session cookie:\n * `@WebSocketGateway({ authenticator: BetterAuthUpgradeAuthenticator })`.\n *\n * The principal uses the `BetterAuthModule` issuer, as `AuthGuard` does for\n * HTTP. The identity expires with the session. Every WebSocket identity carries\n * a tenant, so a session without an active organization is refused unless a\n * {@link BETTER_AUTH_UPGRADE_TENANT} resolver supplies one.\n */\n@Injectable()\nexport class BetterAuthUpgradeAuthenticator implements UpgradeAuthenticator {\n constructor(\n @Inject(BetterAuthService) private readonly auth: BetterAuthService,\n @Inject(BETTER_AUTH_OPTIONS) private readonly options: BetterAuthRuntimeOptions,\n @Optional()\n @Inject(BETTER_AUTH_UPGRADE_TENANT)\n private readonly resolveTenant?: BetterAuthUpgradeTenantResolver,\n ) {}\n\n async authenticate(\n request: Request,\n context: WebSocketUpgradeAuthenticationContext,\n ): Promise<WebSocketUpgradeIdentity | false> {\n const data = validateSessionData(await this.auth.api.getSession({ headers: request.headers }));\n if (!data) return false;\n const tenantId = this.resolveTenant\n ? await this.resolveTenant({ user: data.user, session: data.session }, context, request)\n : data.tenantId;\n if (typeof tenantId !== 'string' || tenantId.length === 0) return false;\n return {\n principal: {\n issuer: this.options.issuer ?? 'better-auth',\n subject: data.user.id,\n principalType: 'user',\n },\n tenantId,\n expiresAtMs: data.session.expiresAt.getTime(),\n };\n }\n}\n","import { createParamDecorator, type ExecutionContext } from '@velajs/vela';\nimport { getAuthRequestState } from '../auth-request-state';\nimport type { User } from '../better-auth.types';\n\nexport const CurrentUser = createParamDecorator(\n (_data: unknown, ctx: ExecutionContext): User | undefined => {\n const state = getAuthRequestState(ctx);\n return state?.user;\n },\n);\n","import { createParamDecorator, type ExecutionContext } from '@velajs/vela';\nimport { getAuthRequestState } from '../auth-request-state';\nimport type { Session } from '../better-auth.types';\n\nexport const CurrentSession = createParamDecorator(\n (_data: unknown, ctx: ExecutionContext): Session | undefined => {\n const state = getAuthRequestState(ctx);\n return state?.session;\n },\n);\n","import type { Identity, PermissionResolver } from '@velajs/authz';\nimport type { User } from './better-auth.types';\n\n/**\n * A better-auth user carrying the optional `role` field contributed by the\n * admin plugin. `role` may be a single role, a comma-separated list, or an\n * array — {@link identityFromUser} normalizes all three.\n */\nexport type AuthUser = Pick<User, 'id'> & { role?: string | string[] | null };\n\n/** Stable issuer namespace used for better-auth session principals. */\nexport const BETTER_AUTH_ISSUER = 'better-auth';\n\nconst normalizeRoles = (role: string | string[] | null | undefined): string[] => {\n if (!role) return [];\n // Strip empty entries and return a fresh array (never alias the caller's\n // input), matching the comma-string path below.\n if (Array.isArray(role)) return role.filter(Boolean);\n return role\n .split(',')\n .map((r) => r.trim())\n .filter(Boolean);\n};\n\n/**\n * Pure authorization projection; this does not authenticate or publish trusted state.\n * Adapts an already verified better-auth user into a stable `@velajs/authz` {@link Identity}.\n * The issuer scopes `user.id` as the `subject`;\n * the admin-plugin `role` field supplies local roles.\n *\n * Fail-closed: a missing user (`null`/`undefined`, i.e. an unauthenticated\n * request) maps to the zero-privilege identity `{ roles: [] }`, so downstream\n * `can()` checks grant nothing.\n */\nexport const identityFromUser = (\n user: AuthUser | null | undefined,\n issuer: string = BETTER_AUTH_ISSUER,\n principalType: 'user' | 'service' = 'user',\n): Identity => {\n if (!user || typeof user.id !== 'string' || user.id.length === 0) return { roles: [] };\n if (issuer.length === 0)\n throw new Error('@velajs/better-auth: identity issuer must be non-empty');\n return {\n issuer,\n subject: user.id,\n principalType,\n roles: normalizeRoles(user.role),\n };\n};\n\n/**\n * The minimal slice of a better-auth access-control role consumed here. Both\n * `createAccessControl(...).newRole(...)` and the standalone `role(...)` return\n * `{ authorize, statements }`; `statements` is the `{ resource: actions[] }`\n * grant map for that role — the only accessor {@link betterAuthAcResolver}\n * reads.\n */\nexport interface BetterAuthAcRole {\n readonly statements: Readonly<Record<string, readonly string[]>>;\n}\n\n/**\n * Flattens a better-auth AC role's `statements` into `resource:action`\n * permission strings — the granted-side format `@velajs/authz` matches\n * (wildcards included).\n */\nexport const permissionsFromAcRole = (role: BetterAuthAcRole): string[] => {\n const permissions: string[] = [];\n for (const [resource, actions] of Object.entries(role.statements ?? {})) {\n for (const action of actions ?? []) permissions.push(`${resource}:${action}`);\n }\n return permissions;\n};\n\n/**\n * Builds a fail-closed `@velajs/authz` {@link PermissionResolver} from a\n * better-auth access-control role table (`{ roleName: acRole }` — the same map\n * shape passed to better-auth's admin/organization plugins). An identity's\n * `roles` are unioned into their granted permission strings; unknown roles\n * contribute nothing.\n *\n * ```ts\n * const ac = createAccessControl({ posts: ['read', 'write'] });\n * const authz = createAuthz({\n * resolver: betterAuthAcResolver({ editor: ac.newRole({ posts: ['write'] }) }),\n * });\n * await authz.can(identityFromUser(user), 'posts:write');\n * ```\n */\nexport const betterAuthAcResolver = (\n roles: Readonly<Record<string, BetterAuthAcRole>>,\n): PermissionResolver => {\n const grantsByRole = new Map<string, string[]>();\n for (const [name, role] of Object.entries(roles)) {\n grantsByRole.set(name, permissionsFromAcRole(role));\n }\n return {\n grants(identity: Identity): Set<string> {\n const out = new Set<string>();\n for (const name of identity.roles ?? []) {\n for (const permission of grantsByRole.get(name) ?? []) out.add(permission);\n }\n return out;\n },\n };\n};\n"],"mappings":";;;;;AAEA,MAAa,SAAS,UAAU,gBAAyB,EAAE,KAAK,mBAAmB,CAAC;AACpF,MAAa,aAAa,OAAO;;;ACHjC,MAAa,gCAAgC;;AAG7C,SAAgB,4BAA4B,OAAwB;CAClE,MAAM,WAAW,SAAA;CACjB,IACE,SAAS,WAAW,KACpB,aAAa,SAAS,KAAK,KAC3B,CAAC,SAAS,WAAW,GAAG,KACxB,SAAS,WAAW,IAAI,KACxB,aAAa,OACb,SAAS,SAA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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","../src/organization-tenancy.ts"],"sourcesContent":["import { Reflector } from '@velajs/vela';\n\nexport const Public = Reflector.createDecorator<boolean>({ key: 'vela.auth.public' });\nexport const PUBLIC_KEY = Public.KEY;\n","export const DEFAULT_BETTER_AUTH_BASE_PATH = '/api/auth';\n\n/** Validate and canonicalize the route prefix used by the public auth controller. */\nexport function normalizeBetterAuthBasePath(value?: string): string {\n const basePath = value ?? DEFAULT_BETTER_AUTH_BASE_PATH;\n if (\n basePath.length === 0 ||\n basePath !== basePath.trim() ||\n !basePath.startsWith('/') ||\n basePath.startsWith('//') ||\n basePath === '/' ||\n basePath.endsWith('/') ||\n /[\\\\?#*]/u.test(basePath) ||\n /%(?:2e|2f|5c)/iu.test(basePath)\n ) {\n throw new Error(\n '@velajs/better-auth: basePath must be a canonical absolute path such as \"/api/auth\"',\n );\n }\n\n let decoded: string;\n try {\n decoded = decodeURIComponent(basePath);\n } catch {\n throw new Error('@velajs/better-auth: basePath contains invalid percent encoding');\n }\n if (decoded.split('/').some((segment) => segment === '.' || segment === '..')) {\n throw new Error('@velajs/better-auth: basePath must not contain dot segments');\n }\n return basePath;\n}\n","import { All, Controller, Inject, Req, type Type } from '@velajs/vela';\nimport { SkipGuardPhases } from '@velajs/vela/module-kit';\nimport { BetterAuthService } from './better-auth.service';\nimport { Public } from './decorators/public.decorator';\nimport { normalizeBetterAuthBasePath } from './base-path';\n\n// One decorated class per base path: every registration of a path, and every\n// call, shares it (the class reads nothing else).\nconst controllers = new Map<string, Type>();\n\n/**\n * Build a catch-all controller that mounts better-auth's handler at `basePath`\n * (default `/api/auth`). This is a factory because vela reads a controller's\n * route off the class at decoration time, so a custom base path needs its own\n * decorated class — the path can't be parametrized on a single shared class.\n * Calls with the same base path return the same class.\n *\n * Two base paths to keep consistent:\n * - this `basePath` is RELATIVE to vela's `globalPrefix` (always prepended);\n * - better-auth routes against its OWN absolute `basePath` (the one you pass to\n * `betterAuth({ basePath })`), which must equal `globalPrefix + basePath`.\n *\n * Both default to `/api/auth`, so the no-prefix / no-config case just works.\n */\nexport function createBetterAuthCatchallController(basePath: string = '/api/auth'): Type {\n const normalizedBasePath = normalizeBetterAuthBasePath(basePath);\n const existing = controllers.get(normalizedBasePath);\n if (existing) return existing;\n // Better Auth authenticates its own endpoints; application-wide tenant\n // admission and authorization do not apply to signing in.\n @Public(true)\n @SkipGuardPhases(['tenant', 'authorize'])\n @Controller(normalizedBasePath)\n class BetterAuthCatchallController {\n // Inject the service — its `.handler` getter triggers lazy construction\n // of the underlying betterAuth() instance on first access, AFTER any\n // runtime adapter middleware (Cloudflare env capture) has run.\n constructor(@Inject(BetterAuthService) private readonly auth: BetterAuthService) {}\n\n @All('/*')\n async handle(@Req() request: Request): Promise<Response> {\n return this.auth.handler(request);\n }\n }\n controllers.set(normalizedBasePath, BetterAuthCatchallController);\n return BetterAuthCatchallController;\n}\n","import { InjectionToken } from '@velajs/vela';\nimport type { BetterAuthRuntimeOptions } from './better-auth.types';\n\nexport const BETTER_AUTH_OPTIONS = new InjectionToken<BetterAuthRuntimeOptions>(\n 'vela.BetterAuthOptions',\n);\n","import type { ExecutionContext } from '@velajs/vela';\nimport {\n clearTrustedRequestIdentity,\n createTrustedRequestIdentityStore,\n getTrustedContextRequest,\n setTrustedRequestIdentity,\n} from '@velajs/vela/module-kit';\nimport type { SessionData } from './session-data';\n\n// This map stores provider payload, never a second authentication authority.\n// A clear, expiry, or identity replacement makes the payload unreachable.\nconst sessions = createTrustedRequestIdentityStore<SessionData>();\n\nexport function beginAuthRequest(context: ExecutionContext): void {\n clearTrustedRequestIdentity(context.getRequest());\n}\n\nexport function authenticateRequest(\n context: ExecutionContext,\n data: SessionData,\n issuer: string,\n): void {\n const request = context.getRequest();\n setTrustedRequestIdentity(request, {\n principal: { issuer, subject: data.user.id, principalType: 'user' },\n expiresAtMs: data.session.expiresAt.getTime(),\n roles: data.roles,\n ...(data.tenantId === undefined ? {} : { tenantId: data.tenantId }),\n });\n sessions.set(request, data);\n}\n\nexport function getAuthRequestState(context: ExecutionContext): SessionData | undefined {\n const request = getTrustedContextRequest(context);\n return request ? sessions.get(request) : undefined;\n}\n","import type { Session, User } from './better-auth.types';\n\nexport interface SessionData {\n readonly user: User;\n readonly session: Session;\n readonly roles: readonly string[];\n readonly tenantId?: string;\n}\n\nfunction own(value: unknown, key: string): unknown {\n if (typeof value !== 'object' || value === null) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n return descriptor && 'value' in descriptor ? descriptor.value : undefined;\n}\n\nfunction requiredString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n\nfunction date(value: unknown): Date | undefined {\n return value instanceof Date && Number.isFinite(value.getTime()) ? new Date(value) : undefined;\n}\n\nfunction optionalString(value: unknown): value is string | null | undefined {\n return value === undefined || value === null || typeof value === 'string';\n}\n\n/** Keep plugin data opaque; base model fields below are validated individually. */\nfunction dataProperties(value: object): Record<string, unknown> {\n return Object.fromEntries(Object.keys(value).map((key) => [key, own(value, key)]));\n}\n\n/** Validate the full Better Auth base models, not merely ids masquerading as them. */\nexport function validateSessionData(value: unknown): SessionData | undefined {\n try {\n const user = own(value, 'user');\n const session = own(value, 'session');\n if (\n typeof user !== 'object' ||\n user === null ||\n typeof session !== 'object' ||\n session === null\n ) {\n return undefined;\n }\n const id = own(user, 'id');\n const email = own(user, 'email');\n const name = own(user, 'name');\n const emailVerified = own(user, 'emailVerified');\n const image = own(user, 'image');\n const createdAt = date(own(user, 'createdAt'));\n const updatedAt = date(own(user, 'updatedAt'));\n const sessionId = own(session, 'id');\n const userId = own(session, 'userId');\n const token = own(session, 'token');\n const sessionCreatedAt = date(own(session, 'createdAt'));\n const sessionUpdatedAt = date(own(session, 'updatedAt'));\n const expiresAt = date(own(session, 'expiresAt'));\n const ipAddress = own(session, 'ipAddress');\n const userAgent = own(session, 'userAgent');\n const organization = own(session, 'activeOrganizationId');\n const role = own(user, 'role');\n let roles: string[] = [];\n if (role !== undefined && role !== null) {\n if (typeof role === 'string')\n roles = role\n .split(',')\n .map((part) => part.trim())\n .filter(Boolean);\n else if (\n Array.isArray(role) &&\n role.every((entry: unknown): entry is string => typeof entry === 'string')\n ) {\n roles = role.map((entry: string) => entry.trim()).filter(Boolean);\n } else return undefined;\n }\n if (\n !requiredString(id) ||\n !requiredString(email) ||\n typeof name !== 'string' ||\n typeof emailVerified !== 'boolean' ||\n !optionalString(image) ||\n !createdAt ||\n !updatedAt ||\n !requiredString(sessionId) ||\n userId !== id ||\n !requiredString(token) ||\n !sessionCreatedAt ||\n !sessionUpdatedAt ||\n !expiresAt ||\n expiresAt.getTime() <= Date.now() ||\n !optionalString(ipAddress) ||\n !optionalString(userAgent) ||\n (organization !== undefined && organization !== null && !requiredString(organization))\n )\n return undefined;\n return {\n user: Object.freeze({\n ...dataProperties(user),\n id,\n email,\n name,\n emailVerified,\n createdAt,\n updatedAt,\n image,\n }),\n session: Object.freeze({\n ...dataProperties(session),\n id: sessionId,\n userId: id,\n token,\n createdAt: sessionCreatedAt,\n updatedAt: sessionUpdatedAt,\n expiresAt,\n ipAddress,\n userAgent,\n }),\n roles: Object.freeze(roles),\n ...(typeof organization === 'string' ? { tenantId: organization } : {}),\n };\n } catch {\n return undefined;\n }\n}\n","import { Reflector } from '@velajs/vela';\n\nexport const OptionalAuth = Reflector.createDecorator<boolean>({ key: 'vela.auth.optional' });\nexport const OPTIONAL_AUTH_KEY = OptionalAuth.KEY;\n","import {\n Inject,\n Injectable,\n Reflector,\n UnauthorizedException,\n type CanActivate,\n type ExecutionContext,\n type GuardPhase,\n} from '@velajs/vela';\nimport { getTrustedContextRequest } from '@velajs/vela/module-kit';\nimport { getContextIdentity } from '@velajs/authz/vela';\nimport { BETTER_AUTH_OPTIONS } from '../better-auth.tokens';\nimport { BetterAuthService } from '../better-auth.service';\nimport type { BetterAuthRuntimeOptions } from '../better-auth.types';\nimport { authenticateRequest, beginAuthRequest, getAuthRequestState } from '../auth-request-state';\nimport { validateSessionData } from '../session-data';\nimport { OptionalAuth } from '../decorators/optional-auth.decorator';\nimport { Public } from '../decorators/public.decorator';\n\n@Injectable()\nexport class AuthGuard implements CanActivate {\n /** Global guards run authentication first, then tenant, authorization and feature phases. */\n static readonly phase: GuardPhase = 'authenticate';\n\n constructor(\n @Inject(BetterAuthService) private readonly auth: BetterAuthService,\n @Inject(BETTER_AUTH_OPTIONS) private readonly opts: BetterAuthRuntimeOptions,\n @Inject(Reflector) private readonly reflector: Reflector,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n // Frames trust only the authenticated connection attachment; HTTP cookies\n // and request payload never become ambient WebSocket authentication.\n if (context.getType() === 'ws') {\n if (getContextIdentity(context)) return true;\n throw new UnauthorizedException('Authentication required');\n }\n // Custom HTTP-backed dispatchers authenticate once at the outer boundary.\n // Never re-read credentials or clear shared authority across sibling fields.\n if (context.getType() !== 'http') {\n if (\n getTrustedContextRequest(context) &&\n (getAuthRequestState(context) ||\n this.reflector.getAllAndOverride(Public, context) ||\n this.reflector.getAllAndOverride(OptionalAuth, context))\n )\n return true;\n throw new UnauthorizedException('Authentication required');\n }\n beginAuthRequest(context);\n if (this.reflector.getAllAndOverride(Public, context)) return true;\n\n const raw = await this.auth.api.getSession({ headers: context.getRequest().headers });\n const data = validateSessionData(raw);\n if (data) {\n authenticateRequest(context, data, this.opts.issuer ?? 'better-auth');\n return true;\n }\n if (this.reflector.getAllAndOverride(OptionalAuth, context)) return true;\n throw new UnauthorizedException('Authentication required');\n }\n}\n","import { defineModule, defineProvider, InjectionToken, type Type } from '@velajs/vela';\nimport { createBetterAuthCatchallController } from './better-auth.controller';\nimport { BetterAuthService, BETTER_AUTH_BUILDER } from './better-auth.service';\nimport { BETTER_AUTH_OPTIONS } from './better-auth.tokens';\nimport type {\n BetterAuthInstance,\n BetterAuthModuleOptions,\n BetterAuthRuntimeOptions,\n BetterAuthStructuralOption,\n} from './better-auth.types';\nimport { AuthGuard } from './guards/auth.guard';\nimport { DEFAULT_BETTER_AUTH_BASE_PATH, normalizeBetterAuthBasePath } from './base-path';\n\nconst MODULE_OPTIONS = new InjectionToken<BetterAuthModuleOptions>(\n 'vela.better-auth.ModuleOptions',\n);\n\n/** Runtime options with defaults applied: what AuthGuard and the upgrade authenticator read. */\nfunction runtimeOptions(options: BetterAuthModuleOptions): Required<BetterAuthRuntimeOptions> {\n const auth: unknown = options.auth;\n if (typeof auth !== 'function' && (typeof auth !== 'object' || auth === null)) {\n throw new TypeError(\n '@velajs/better-auth: options need `auth`, a better-auth instance or a function that builds one',\n );\n }\n const basePath = normalizeBetterAuthBasePath(options.basePath);\n const issuer = options.issuer ?? `better-auth:${basePath}`;\n if (issuer.length === 0 || issuer !== issuer.trim()) {\n throw new Error('@velajs/better-auth: issuer must be a non-empty stable namespace');\n }\n return {\n basePath,\n issuer,\n mountHandler: options.mountHandler ?? true,\n };\n}\n\n/** The instance itself, or the one its builder function returns. */\nfunction buildAuth(auth: BetterAuthModuleOptions['auth']): BetterAuthInstance {\n return typeof auth === 'function' ? auth() : auth;\n}\n\nconst { ConfigurableModuleClass } = defineModule<\n BetterAuthModuleOptions,\n BetterAuthStructuralOption\n>({\n name: 'BetterAuth',\n optionsToken: MODULE_OPTIONS,\n structural: ['basePath', 'mountHandler'],\n // Spelling out a default configures what leaving it out does: one instance.\n defaults: { basePath: DEFAULT_BETTER_AUTH_BASE_PATH, mountHandler: true },\n setup: ({ OPTIONS, options }) => {\n // Validates the mount path when the module is declared, before bootstrap.\n const basePath = normalizeBetterAuthBasePath(options.basePath);\n const controllers: Type[] =\n options.mountHandler === false ? [] : [createBetterAuthCatchallController(basePath)];\n return {\n providers: [\n defineProvider(BETTER_AUTH_OPTIONS, {\n useFactory: (resolved) => runtimeOptions(resolved),\n inject: [OPTIONS],\n }),\n // BetterAuthService calls the builder on first use and caches the\n // instance, so a builder function never runs at bootstrap.\n defineProvider(BETTER_AUTH_BUILDER, {\n useFactory: (resolved) => () => buildAuth(resolved.auth),\n inject: [OPTIONS],\n }),\n BetterAuthService,\n AuthGuard,\n ],\n controllers,\n exports: [BetterAuthService, BETTER_AUTH_OPTIONS, AuthGuard],\n };\n },\n});\n\n/**\n * better-auth for Vela: `BetterAuthService`, the catch-all handler under\n * `basePath`, and an injectable `AuthGuard`. Applications install it through `APP_GUARD`\n * with `useExisting: AuthGuard`, or attach it with `@UseGuards`.\n *\n * ```ts\n * BetterAuthModule.forRoot({ auth: betterAuth({ ... }) });\n * BetterAuthModule.forRootAsync({\n * inject: [ENV],\n * useFactory: (env) => ({ auth: () => betterAuth({ database: env.DB }), issuer: 'accounts' }),\n * });\n * ```\n *\n * `basePath` and `mountHandler` are structural: `forRootAsync`\n * takes them alongside the factory. The factory runs when the application\n * initializes; an `auth` function it returns runs on first authentication.\n */\nexport class BetterAuthModule extends ConfigurableModuleClass {}\n","import { Inject, Injectable, InjectionToken, Optional } from '@velajs/vela';\nimport type {\n UpgradeAuthenticator,\n WebSocketUpgradeAuthenticationContext,\n WebSocketUpgradeIdentity,\n} from '@velajs/vela/websocket';\nimport { BetterAuthService } from './better-auth.service';\nimport { BETTER_AUTH_OPTIONS } from './better-auth.tokens';\nimport type { BetterAuthRuntimeOptions, Session, User } from './better-auth.types';\nimport { validateSessionData } from './session-data';\n\n/** The validated Better Auth session behind a WebSocket upgrade. */\nexport interface BetterAuthUpgradeSession {\n readonly user: User;\n readonly session: Session;\n}\n\n/**\n * Chooses the tenant a WebSocket connection joins. Returning no tenant (or\n * throwing) refuses the upgrade.\n */\nexport type BetterAuthUpgradeTenantResolver = (\n session: BetterAuthUpgradeSession,\n context: WebSocketUpgradeAuthenticationContext,\n request: Request,\n) => string | undefined | Promise<string | undefined>;\n\n/**\n * Optional tenant resolver for {@link BetterAuthUpgradeAuthenticator}. Provide it\n * in the module that declares the gateway; without one, the session's active\n * organization is the tenant.\n */\nexport const BETTER_AUTH_UPGRADE_TENANT = new InjectionToken<BetterAuthUpgradeTenantResolver>(\n 'vela.better-auth.UpgradeTenant',\n);\n\n/**\n * WebSocket upgrade authenticator backed by the Better Auth session cookie:\n * `@WebSocketGateway({ authenticator: BetterAuthUpgradeAuthenticator })`.\n *\n * The principal uses the `BetterAuthModule` issuer, as `AuthGuard` does for\n * HTTP. The identity expires with the session. Every WebSocket identity carries\n * a tenant, so a session without an active organization is refused unless a\n * {@link BETTER_AUTH_UPGRADE_TENANT} resolver supplies one.\n */\n@Injectable()\nexport class BetterAuthUpgradeAuthenticator implements UpgradeAuthenticator {\n constructor(\n @Inject(BetterAuthService) private readonly auth: BetterAuthService,\n @Inject(BETTER_AUTH_OPTIONS) private readonly options: BetterAuthRuntimeOptions,\n @Optional()\n @Inject(BETTER_AUTH_UPGRADE_TENANT)\n private readonly resolveTenant?: BetterAuthUpgradeTenantResolver,\n ) {}\n\n async authenticate(\n request: Request,\n context: WebSocketUpgradeAuthenticationContext,\n ): Promise<WebSocketUpgradeIdentity | false> {\n const data = validateSessionData(await this.auth.api.getSession({ headers: request.headers }));\n if (!data) return false;\n const tenantId = this.resolveTenant\n ? await this.resolveTenant({ user: data.user, session: data.session }, context, request)\n : data.tenantId;\n if (typeof tenantId !== 'string' || tenantId.length === 0) return false;\n return {\n principal: {\n issuer: this.options.issuer ?? 'better-auth',\n subject: data.user.id,\n principalType: 'user',\n },\n tenantId,\n expiresAtMs: data.session.expiresAt.getTime(),\n };\n }\n}\n","import { createParamDecorator, type ExecutionContext } from '@velajs/vela';\nimport { getAuthRequestState } from '../auth-request-state';\nimport type { User } from '../better-auth.types';\n\nexport const CurrentUser = createParamDecorator(\n (_data: unknown, ctx: ExecutionContext): User | undefined => {\n const state = getAuthRequestState(ctx);\n return state?.user;\n },\n);\n","import { createParamDecorator, type ExecutionContext } from '@velajs/vela';\nimport { getAuthRequestState } from '../auth-request-state';\nimport type { Session } from '../better-auth.types';\n\nexport const CurrentSession = createParamDecorator(\n (_data: unknown, ctx: ExecutionContext): Session | undefined => {\n const state = getAuthRequestState(ctx);\n return state?.session;\n },\n);\n","import type { Identity, PermissionResolver } from '@velajs/authz';\nimport type { User } from './better-auth.types';\n\n/**\n * A better-auth user carrying the optional `role` field contributed by the\n * admin plugin. `role` may be a single role, a comma-separated list, or an\n * array — {@link identityFromUser} normalizes all three.\n */\nexport type AuthUser = Pick<User, 'id'> & { role?: string | string[] | null };\n\n/** Stable issuer namespace used for better-auth session principals. */\nexport const BETTER_AUTH_ISSUER = 'better-auth';\n\nconst normalizeRoles = (role: string | string[] | null | undefined): string[] => {\n if (!role) return [];\n // Strip empty entries and return a fresh array (never alias the caller's\n // input), matching the comma-string path below.\n if (Array.isArray(role)) return role.filter(Boolean);\n return role\n .split(',')\n .map((r) => r.trim())\n .filter(Boolean);\n};\n\n/**\n * Pure authorization projection; this does not authenticate or publish trusted state.\n * Adapts an already verified better-auth user into a stable `@velajs/authz` {@link Identity}.\n * The issuer scopes `user.id` as the `subject`;\n * the admin-plugin `role` field supplies local roles.\n *\n * Fail-closed: a missing user (`null`/`undefined`, i.e. an unauthenticated\n * request) maps to the zero-privilege identity `{ roles: [] }`, so downstream\n * `can()` checks grant nothing.\n */\nexport const identityFromUser = (\n user: AuthUser | null | undefined,\n issuer: string = BETTER_AUTH_ISSUER,\n principalType: 'user' | 'service' = 'user',\n): Identity => {\n if (!user || typeof user.id !== 'string' || user.id.length === 0) return { roles: [] };\n if (issuer.length === 0)\n throw new Error('@velajs/better-auth: identity issuer must be non-empty');\n return {\n issuer,\n subject: user.id,\n principalType,\n roles: normalizeRoles(user.role),\n };\n};\n\n/**\n * The minimal slice of a better-auth access-control role consumed here. Both\n * `createAccessControl(...).newRole(...)` and the standalone `role(...)` return\n * `{ authorize, statements }`; `statements` is the `{ resource: actions[] }`\n * grant map for that role — the only accessor {@link betterAuthAcResolver}\n * reads.\n */\nexport interface BetterAuthAcRole {\n readonly statements: Readonly<Record<string, readonly string[]>>;\n}\n\n/**\n * Flattens a better-auth AC role's `statements` into `resource:action`\n * permission strings — the granted-side format `@velajs/authz` matches\n * (wildcards included).\n */\nexport const permissionsFromAcRole = (role: BetterAuthAcRole): string[] => {\n const permissions: string[] = [];\n for (const [resource, actions] of Object.entries(role.statements ?? {})) {\n for (const action of actions ?? []) permissions.push(`${resource}:${action}`);\n }\n return permissions;\n};\n\n/**\n * Builds a fail-closed `@velajs/authz` {@link PermissionResolver} from a\n * better-auth access-control role table (`{ roleName: acRole }` — the same map\n * shape passed to better-auth's admin/organization plugins). An identity's\n * `roles` are unioned into their granted permission strings; unknown roles\n * contribute nothing.\n *\n * ```ts\n * const ac = createAccessControl({ posts: ['read', 'write'] });\n * const authz = createAuthz({\n * resolver: betterAuthAcResolver({ editor: ac.newRole({ posts: ['write'] }) }),\n * });\n * await authz.can(identityFromUser(user), 'posts:write');\n * ```\n */\nexport const betterAuthAcResolver = (\n roles: Readonly<Record<string, BetterAuthAcRole>>,\n): PermissionResolver => {\n const grantsByRole = new Map<string, string[]>();\n for (const [name, role] of Object.entries(roles)) {\n grantsByRole.set(name, permissionsFromAcRole(role));\n }\n return {\n grants(identity: Identity): Set<string> {\n const out = new Set<string>();\n for (const name of identity.roles ?? []) {\n for (const permission of grantsByRole.get(name) ?? []) out.add(permission);\n }\n return out;\n },\n };\n};\n","import { BetterAuthService } from './better-auth.service';\nimport type { BetterAuthInstance } from './better-auth.types';\n\n/** The part of Better Auth's database adapter read here. */\ninterface OrganizationAdapter {\n findOne<T>(query: {\n model: string;\n where: Array<{ field: string; value: string }>;\n }): Promise<T | null>;\n}\n\n/** A Better Auth organization as a tenant record (`@velajs/tenant` `TenantRecord`). */\nexport interface OrganizationTenantRecord {\n readonly id: string;\n readonly name: string;\n readonly status: 'active';\n readonly revision: number;\n readonly settings: Readonly<Record<string, never>>;\n}\n\nexport interface BetterAuthOrganizationsOptions {\n /**\n * The Better Auth instance, the `BetterAuthService` that wraps it, or a\n * function returning either. Read on first use, never at bootstrap.\n */\n readonly auth:\n | BetterAuthService\n | Pick<BetterAuthInstance, '$context'>\n | (() => Pick<BetterAuthInstance, '$context'>);\n /**\n * The issuer `BetterAuthModule` publishes principals under (its `issuer`\n * option, `better-auth:<basePath>` by default). Principals from any other\n * issuer are never members.\n */\n readonly issuer: string;\n /**\n * The organization roles the application knows. A member's stored roles\n * outside this list are dropped; a member left with none is denied.\n * Without it, every stored role is kept.\n */\n readonly roles?: readonly string[];\n}\n\n/** Lookup, membership and slug resolution for `TenantModule` from Better Auth organizations. */\nexport interface BetterAuthOrganizations {\n /** `TenantModule` `lookup`: an organization by id, as an active tenant. */\n readonly lookup: {\n get(id: string): Promise<OrganizationTenantRecord | null>;\n };\n /**\n * `TenantModule` `authorize`: the principal's membership of the organization.\n * Admits with the member's organization roles, which then replace the\n * request identity's roles (`user.role`) for the rest of the pipeline.\n */\n authorize(input: {\n readonly tenant: { readonly id: string };\n readonly principal: {\n readonly issuer: string;\n readonly subject: string;\n readonly principalType: string;\n };\n }): Promise<false | { readonly roles: readonly string[] }>;\n /** An organization id by slug, for `pathTenant(name, { resolve })`. */\n organizationIdBySlug(slug: string): Promise<string | undefined>;\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 isOrganizationAdapter(value: unknown): value is OrganizationAdapter {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof Reflect.get(value, 'findOne') === 'function'\n );\n}\n\nfunction text(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n\n/** Better Auth stores a member's roles as one comma-separated string. */\nfunction storedRoles(value: unknown): string[] {\n if (typeof value !== 'string') return [];\n return [\n ...new Set(\n value\n .split(',')\n .map((role) => role.trim())\n .filter(Boolean),\n ),\n ];\n}\n\n/**\n * Tenants from the Better Auth organization plugin: an organization is a\n * tenant, its members are admitted with their organization roles.\n *\n * ```ts\n * TenantModule.forRootAsync({\n * imports: [AuthModule],\n * inject: [BetterAuthService],\n * useFactory: (auth) => {\n * const organizations = betterAuthOrganizations({ auth, issuer: 'accounts', roles });\n * return {\n * ...organizations,\n * selector: pathTenant('workspace', { resolve: organizations.organizationIdBySlug }),\n * identityTenantConflict: 'selector',\n * deniedStatus: 404,\n * };\n * },\n * });\n * ```\n *\n * Every admission reads the organization and the membership from Better\n * Auth's own database adapter; nothing is cached.\n */\nexport function betterAuthOrganizations(\n options: BetterAuthOrganizationsOptions,\n): BetterAuthOrganizations {\n if (!text(options.issuer) || options.issuer !== options.issuer.trim())\n throw new TypeError('@velajs/better-auth: organizations need the module issuer');\n const known = options.roles === undefined ? undefined : new Set(options.roles);\n if (known && [...known].some((role) => !text(role) || role !== role.trim()))\n throw new TypeError('@velajs/better-auth: organization roles must be non-empty names');\n\n const instance = (): Pick<BetterAuthInstance, '$context'> => {\n const source = options.auth;\n if (typeof source === 'function') return source();\n return source instanceof BetterAuthService ? source.auth : source;\n };\n const adapter = async (): Promise<OrganizationAdapter> => {\n const context: unknown = await instance().$context;\n const found = own(context, 'adapter');\n if (!isOrganizationAdapter(found))\n throw new TypeError('@velajs/better-auth: the auth instance has no database adapter');\n return found;\n };\n const organization = async (field: 'id' | 'slug', value: string) => {\n if (!text(value)) return null;\n const row = await (\n await adapter()\n ).findOne<unknown>({\n model: 'organization',\n where: [{ field, value }],\n });\n const id = own(row, 'id');\n const name = own(row, 'name');\n return text(id) && typeof name === 'string' && own(row, field) === value ? { id, name } : null;\n };\n\n return Object.freeze({\n lookup: Object.freeze({\n async get(id: string): Promise<OrganizationTenantRecord | null> {\n const found = await organization('id', id);\n // Organizations carry no revision or status; each admission re-reads them.\n return found\n ? Object.freeze({\n id: found.id,\n name: found.name,\n status: 'active',\n revision: 1,\n settings: {},\n })\n : null;\n },\n }),\n async authorize({ tenant, principal }: Parameters<BetterAuthOrganizations['authorize']>[0]) {\n if (\n principal.issuer !== options.issuer ||\n principal.principalType !== 'user' ||\n !text(principal.subject) ||\n !text(tenant.id)\n )\n return false;\n const member = await (\n await adapter()\n ).findOne<unknown>({\n model: 'member',\n where: [\n { field: 'organizationId', value: tenant.id },\n { field: 'userId', value: principal.subject },\n ],\n });\n if (\n own(member, 'organizationId') !== tenant.id ||\n own(member, 'userId') !== principal.subject\n )\n return false;\n const roles = storedRoles(own(member, 'role')).filter((role) => !known || known.has(role));\n return roles.length > 0 ? Object.freeze({ roles: Object.freeze(roles) }) : false;\n },\n async organizationIdBySlug(slug: string): Promise<string | undefined> {\n return (await organization('slug', slug))?.id;\n },\n });\n}\n"],"mappings":";;;;;AAEA,MAAa,SAAS,UAAU,gBAAyB,EAAE,KAAK,mBAAmB,CAAC;AACpF,MAAa,aAAa,OAAO;;ACHjC,MAAa,gCAAgC;;AAG7C,SAAgB,4BAA4B,OAAwB;CAClE,MAAM,WAAW,SAAA;CACjB,IACE,SAAS,WAAW,KACpB,aAAa,SAAS,KAAK,KAC3B,CAAC,SAAS,WAAW,GAAG,KACxB,SAAS,WAAW,IAAI,KACxB,aAAa,OACb,SAAS,SAAS,GAAG,KACrB,WAAW,KAAK,QAAQ,KACxB,kBAAkB,KAAK,QAAQ,GAE/B,MAAM,IAAI,MACR,uFACF;CAGF,IAAI;CACJ,IAAI;EACF,UAAU,mBAAmB,QAAQ;CACvC,QAAQ;EACN,MAAM,IAAI,MAAM,iEAAiE;CACnF;CACA,IAAI,QAAQ,MAAM,GAAG,CAAC,CAAC,MAAM,YAAY,YAAY,OAAO,YAAY,IAAI,GAC1E,MAAM,IAAI,MAAM,6DAA6D;CAE/E,OAAO;AACT;;ACtBA,MAAM,8BAAc,IAAI,IAAkB;;;;;;;;;;;;;;;AAgB1C,SAAgB,mCAAmC,WAAmB,aAAmB;CACvF,MAAM,qBAAqB,4BAA4B,QAAQ;CAC/D,MAAM,WAAW,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M,QAAQ,MAAM,aAAa,MAAM,EAAE;GAEzC,OAAO,QACH,OAAO,OAAO;IACZ,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,QAAQ;IACR,UAAU;IACV,UAAU,CAAC;GACb,CAAC,IACD;EACN,EACF,CAAC;EACD,MAAM,UAAU,EAAE,QAAQ,aAAkE;GAC1F,IACE,UAAU,WAAW,QAAQ,UAC7B,UAAU,kBAAkB,UAC5B,CAAC,KAAK,UAAU,OAAO,KACvB,CAAC,KAAK,OAAO,EAAE,GAEf,OAAO;GACT,MAAM,SAAS,OACb,MAAM,QAAQ,EAAA,CACd,QAAiB;IACjB,OAAO;IACP,OAAO,CACL;KAAE,OAAO;KAAkB,OAAO,OAAO;IAAG,GAC5C;KAAE,OAAO;KAAU,OAAO,UAAU;IAAQ,CAC9C;GACF,CAAC;GACD,IACE,IAAI,QAAQ,gBAAgB,MAAM,OAAO,MACzC,IAAI,QAAQ,QAAQ,MAAM,UAAU,SAEpC,OAAO;GACT,MAAM,QAAQ,YAAY,IAAI,QAAQ,MAAM,CAAC,CAAC,CAAC,QAAQ,SAAS,CAAC,SAAS,MAAM,IAAI,IAAI,CAAC;GACzF,OAAO,MAAM,SAAS,IAAI,OAAO,OAAO,EAAE,OAAO,OAAO,OAAO,KAAK,EAAE,CAAC,IAAI;EAC7E;EACA,MAAM,qBAAqB,MAA2C;GACpE,QAAQ,MAAM,aAAa,QAAQ,IAAI,EAAA,EAAI;EAC7C;CACF,CAAC;AACH"}
@@ -1,5 +1,4 @@
1
- import { t as BetterAuthService } from "../better-auth.service-D_G-PP8p.js";
2
- //#region src/testing/acting-as.d.ts
1
+ import { t as BetterAuthService } from "../better-auth.service-Db61kU5e.js";
3
2
  /**
4
3
  * The slice of `@velajs/testing`'s `TestingModule` this resolver depends on.
5
4
  * Declared structurally so `@velajs/better-auth/testing` carries NO runtime
@@ -46,6 +45,4 @@ type ActingAsPrincipal = Record<string, unknown>;
46
45
  * ```
47
46
  */
48
47
  export declare function actingAs(module: TestModuleLike, principal: ActingAsPrincipal): Promise<Headers>;
49
- //#endregion
50
- export type { ActingAsPrincipal, TestModuleLike };
51
- //# sourceMappingURL=index.d.ts.map
48
+ export type { ActingAsPrincipal, TestModuleLike };
@@ -1,6 +1,6 @@
1
- import { n as BetterAuthService } from "../better-auth.service-SNg1YFTK.js";
2
1
  import { makeSignature } from "better-auth/crypto";
3
- //#region src/testing/acting-as.ts
2
+ import { n as BetterAuthService } from "../better-auth.service-BleR_Iv4.js";
3
+ // src/testing/acting-as.ts
4
4
  /**
5
5
  * actingAs — a `@velajs/testing` auth resolver for better-auth.
6
6
  *
@@ -55,7 +55,6 @@ async function actingAs(module, principal) {
55
55
  headers.set("Cookie", `${cookieName}=${signedToken}`);
56
56
  return headers;
57
57
  }
58
- //#endregion
59
58
  export { actingAs };
60
59
 
61
60
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@velajs/better-auth",
3
- "version": "1.33.0",
3
+ "version": "1.34.0",
4
4
  "description": "better-auth integration for the Vela framework",
5
5
  "keywords": [
6
6
  "auth",
@@ -51,26 +51,26 @@
51
51
  },
52
52
  "devDependencies": {
53
53
  "@arethetypeswrong/cli": "0.18.5",
54
- "@changesets/cli": "3.0.1",
55
- "@swc/core": "1.15.43",
56
- "better-auth": "^1.6.20",
57
- "hono": "4.13.8",
58
- "oxfmt": "0.58.0",
59
- "oxlint": "1.73.0",
60
- "publint": "0.3.21",
61
- "tsdown": "0.23.0",
54
+ "@changesets/cli": "3.1.0",
55
+ "@swc/core": "1.16.30",
56
+ "better-auth": "^1.7.29",
57
+ "hono": "4.13.23",
58
+ "oxfmt": "0.81.0",
59
+ "oxlint": "1.96.0",
60
+ "publint": "0.3.25",
61
+ "tsdown": "0.23.8",
62
62
  "typescript": "7.0.2",
63
- "unplugin-swc": "1.5.9",
64
- "vite": "^8.0.16",
65
- "vitest": "4.1.11",
63
+ "unplugin-swc": "2.0.0",
64
+ "vite": "^8.4.1",
65
+ "vitest": "5.1.2",
66
66
  "@velajs/testing": "1.34.0",
67
- "@velajs/vela": "1.35.0",
68
- "@velajs/tenant": "1.33.0"
67
+ "@velajs/vela": "1.37.0",
68
+ "@velajs/tenant": "1.34.0"
69
69
  },
70
70
  "peerDependencies": {
71
- "better-auth": ">=1.2.0",
71
+ "better-auth": "^1.7.29",
72
72
  "hono": ">=4",
73
- "@velajs/vela": "^1.35.0"
73
+ "@velajs/vela": "^1.37.0"
74
74
  },
75
75
  "engines": {
76
76
  "node": ">=24"