@velajs/better-auth 0.6.0 → 0.6.1

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.
Files changed (36) hide show
  1. package/CHANGELOG.md +6 -1
  2. package/dist/better-auth.service-BMkyFX-w.js +63 -0
  3. package/dist/better-auth.service-BMkyFX-w.js.map +1 -0
  4. package/dist/index.d.ts +270 -12
  5. package/dist/index.js +364 -15
  6. package/dist/index.js.map +1 -0
  7. package/dist/testing/index.d.ts +50 -2
  8. package/dist/testing/index.js +60 -3
  9. package/dist/testing/index.js.map +1 -0
  10. package/package.json +58 -41
  11. package/dist/better-auth.controller.d.ts +0 -21
  12. package/dist/better-auth.controller.js +0 -68
  13. package/dist/better-auth.module.d.ts +0 -52
  14. package/dist/better-auth.module.js +0 -138
  15. package/dist/better-auth.service.d.ts +0 -42
  16. package/dist/better-auth.service.js +0 -51
  17. package/dist/better-auth.tokens.d.ts +0 -5
  18. package/dist/better-auth.tokens.js +0 -4
  19. package/dist/better-auth.types.d.ts +0 -11
  20. package/dist/better-auth.types.js +0 -1
  21. package/dist/decorators/current-session.decorator.d.ts +0 -1
  22. package/dist/decorators/current-session.decorator.js +0 -7
  23. package/dist/decorators/current-user.decorator.d.ts +0 -1
  24. package/dist/decorators/current-user.decorator.js +0 -7
  25. package/dist/decorators/optional-auth.decorator.d.ts +0 -2
  26. package/dist/decorators/optional-auth.decorator.js +0 -5
  27. package/dist/decorators/public.decorator.d.ts +0 -2
  28. package/dist/decorators/public.decorator.js +0 -5
  29. package/dist/decorators/roles.decorator.d.ts +0 -2
  30. package/dist/decorators/roles.decorator.js +0 -5
  31. package/dist/guards/auth.guard.d.ts +0 -10
  32. package/dist/guards/auth.guard.js +0 -68
  33. package/dist/guards/roles.guard.d.ts +0 -5
  34. package/dist/guards/roles.guard.js +0 -36
  35. package/dist/testing/acting-as.d.ts +0 -46
  36. package/dist/testing/acting-as.js +0 -70
@@ -1,68 +0,0 @@
1
- function _ts_decorate(decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- 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;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
6
- }
7
- function _ts_metadata(k, v) {
8
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
- }
10
- function _ts_param(paramIndex, decorator) {
11
- return function(target, key) {
12
- decorator(target, key, paramIndex);
13
- };
14
- }
15
- import { Inject, Injectable, REQUEST_CONTEXT, Reflector, UnauthorizedException } from "@velajs/vela";
16
- import { AUTH_SESSION_KEY, AUTH_USER_KEY, BETTER_AUTH_OPTIONS } from "../better-auth.tokens.js";
17
- import { BetterAuthService } from "../better-auth.service.js";
18
- import { OptionalAuth } from "../decorators/optional-auth.decorator.js";
19
- import { Public } from "../decorators/public.decorator.js";
20
- export class AuthGuard {
21
- auth;
22
- opts;
23
- reflector = new Reflector();
24
- constructor(// Inject BetterAuthService rather than the raw better-auth instance.
25
- // The service's lazy `.auth` getter defers construction to first use, so
26
- // forRootAsync factories that depend on values only available at
27
- // request time (Cloudflare D1/KV bindings, etc.) build safely on the
28
- // first canActivate — not at module-load bootstrap.
29
- auth, opts){
30
- this.auth = auth;
31
- this.opts = opts;
32
- }
33
- async canActivate(context) {
34
- if (this.reflector.getAllAndOverride(Public, context)) return true;
35
- const request = context.getRequest();
36
- const path = new URL(request.url).pathname;
37
- const basePath = this.opts.basePath ?? '/api/auth';
38
- if (path === basePath || path.startsWith(`${basePath}/`)) return true;
39
- const data = await this.auth.api.getSession({
40
- headers: request.headers
41
- });
42
- if (data) {
43
- const reqCtx = resolveRequestContext(context);
44
- reqCtx.set(AUTH_USER_KEY, data.user);
45
- reqCtx.set(AUTH_SESSION_KEY, data.session);
46
- return true;
47
- }
48
- if (this.opts.defaultPolicy === 'allow' || this.reflector.getAllAndOverride(OptionalAuth, context)) {
49
- return true;
50
- }
51
- throw new UnauthorizedException('Authentication required');
52
- }
53
- }
54
- AuthGuard = _ts_decorate([
55
- Injectable(),
56
- _ts_param(0, Inject(BetterAuthService)),
57
- _ts_param(1, Inject(BETTER_AUTH_OPTIONS)),
58
- _ts_metadata("design:type", Function),
59
- _ts_metadata("design:paramtypes", [
60
- typeof BetterAuthService === "undefined" ? Object : BetterAuthService,
61
- typeof BetterAuthModuleOptions === "undefined" ? Object : BetterAuthModuleOptions
62
- ])
63
- ], AuthGuard);
64
- function resolveRequestContext(context) {
65
- const honoCtx = context.getContext();
66
- const container = honoCtx.get('container');
67
- return container.resolve(REQUEST_CONTEXT);
68
- }
@@ -1,5 +0,0 @@
1
- import { type CanActivate, type ExecutionContext } from '@velajs/vela';
2
- export declare class RolesGuard implements CanActivate {
3
- private readonly reflector;
4
- canActivate(context: ExecutionContext): boolean;
5
- }
@@ -1,36 +0,0 @@
1
- function _ts_decorate(decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- 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;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
6
- }
7
- import { ForbiddenException, Injectable, REQUEST_CONTEXT, Reflector } from "@velajs/vela";
8
- import { AUTH_USER_KEY } from "../better-auth.tokens.js";
9
- import { Roles } from "../decorators/roles.decorator.js";
10
- export class RolesGuard {
11
- reflector = new Reflector();
12
- canActivate(context) {
13
- const required = this.reflector.getAllAndOverride(Roles, context);
14
- if (!required || required.length === 0) return true;
15
- const honoCtx = context.getContext();
16
- const reqCtx = honoCtx.get('container').resolve(REQUEST_CONTEXT);
17
- const user = reqCtx.get(AUTH_USER_KEY);
18
- if (!user) {
19
- throw new ForbiddenException('Role check requires authentication');
20
- }
21
- const userRoles = normalizeRoles(user.role);
22
- const ok = required.some((r)=>userRoles.includes(r));
23
- if (!ok) {
24
- throw new ForbiddenException(`Insufficient role; one of [${required.join(', ')}] required`);
25
- }
26
- return true;
27
- }
28
- }
29
- RolesGuard = _ts_decorate([
30
- Injectable()
31
- ], RolesGuard);
32
- function normalizeRoles(role) {
33
- if (!role) return [];
34
- if (Array.isArray(role)) return role;
35
- return role.split(',').map((r)=>r.trim()).filter(Boolean);
36
- }
@@ -1,46 +0,0 @@
1
- /**
2
- * The slice of `@velajs/testing`'s `TestingModule` this resolver depends on.
3
- * Declared structurally so `@velajs/better-auth/testing` carries NO runtime
4
- * (or type) dependency on `@velajs/testing` — a real `TestingModule` satisfies
5
- * it, and the resolver stays assignable to `@velajs/testing`'s `ActingAsResolver`.
6
- */
7
- export interface TestModuleLike {
8
- get<T>(token: unknown): T;
9
- }
10
- /**
11
- * A test principal. Opaque `Record<string, unknown>` to stay compatible with
12
- * `@velajs/testing`'s `TestPrincipal`. Recognized fields:
13
- *
14
- * - `id` — reuse the user with this id if it already exists.
15
- * - `email` — reuse the user with this email, else create one.
16
- * - `name` — display name for a created user (defaults to the email).
17
- *
18
- * Any other fields are forwarded to `internalAdapter.createUser` (e.g. `role`)
19
- * when a new user is minted, so role-guarded routes can be exercised.
20
- */
21
- export type ActingAsPrincipal = Record<string, unknown>;
22
- /**
23
- * actingAs — a `@velajs/testing` auth resolver for better-auth.
24
- *
25
- * Resolves {@link BetterAuthService} from the module, mints a REAL better-auth
26
- * session for `principal` through `auth.$context.internalAdapter`, and returns
27
- * a `Headers` carrying a properly signed session cookie. Guarded routes
28
- * (`AuthGuard`) then accept requests carrying those headers because
29
- * `auth.api.getSession` validates the cookie against the same session store.
30
- *
31
- * The signature `(module, principal) => Promise<Headers>` is exactly
32
- * `@velajs/testing`'s `ActingAsResolver`, so it plugs straight in:
33
- *
34
- * @example
35
- * ```ts
36
- * import { actingAs } from '@velajs/better-auth/testing';
37
- *
38
- * // As the default resolver for the module:
39
- * module.setAuthResolver(actingAs);
40
- * await module.http.get('/me').actingAs({ email: 'ada@example.com' }).send();
41
- *
42
- * // Or passed per-request:
43
- * await module.http.get('/me').actingAs({ id: existingUserId }, actingAs).send();
44
- * ```
45
- */
46
- export declare function actingAs(module: TestModuleLike, principal: ActingAsPrincipal): Promise<Headers>;
@@ -1,70 +0,0 @@
1
- // Mechanics adapted from @stratal/testing (MIT, © Temitayo Fadojutimi):
2
- // mint a real better-auth session via `$context.internalAdapter` and hand back
3
- // a signed session-cookie header. Adapted to better-auth >=1.6: the session
4
- // cookie is signed with the package's own `makeSignature` (better-auth/crypto)
5
- // — the same primitive better-auth's built-in test cookie builder uses — so no
6
- // endpoint-context shim or `setSessionCookie` mock is needed.
7
- import { makeSignature } from "better-auth/crypto";
8
- import { BetterAuthService } from "../better-auth.service.js";
9
- /**
10
- * actingAs — a `@velajs/testing` auth resolver for better-auth.
11
- *
12
- * Resolves {@link BetterAuthService} from the module, mints a REAL better-auth
13
- * session for `principal` through `auth.$context.internalAdapter`, and returns
14
- * a `Headers` carrying a properly signed session cookie. Guarded routes
15
- * (`AuthGuard`) then accept requests carrying those headers because
16
- * `auth.api.getSession` validates the cookie against the same session store.
17
- *
18
- * The signature `(module, principal) => Promise<Headers>` is exactly
19
- * `@velajs/testing`'s `ActingAsResolver`, so it plugs straight in:
20
- *
21
- * @example
22
- * ```ts
23
- * import { actingAs } from '@velajs/better-auth/testing';
24
- *
25
- * // As the default resolver for the module:
26
- * module.setAuthResolver(actingAs);
27
- * await module.http.get('/me').actingAs({ email: 'ada@example.com' }).send();
28
- *
29
- * // Or passed per-request:
30
- * await module.http.get('/me').actingAs({ id: existingUserId }, actingAs).send();
31
- * ```
32
- */ export async function actingAs(module, principal) {
33
- const auth = module.get(BetterAuthService).auth;
34
- const ctx = await auth.$context;
35
- const internalAdapter = ctx.internalAdapter;
36
- const id = typeof principal.id === 'string' ? principal.id : undefined;
37
- const email = typeof principal.email === 'string' ? principal.email : undefined;
38
- const name = typeof principal.name === 'string' ? principal.name : undefined;
39
- // `findUserById`/`createUser` yield a bare user; `findUserByEmail` nests it
40
- // under `{ user, accounts }` — normalize to the id we need.
41
- let user = null;
42
- if (id) user = await internalAdapter.findUserById(id);
43
- if (!user && email) {
44
- const found = await internalAdapter.findUserByEmail(email);
45
- user = found?.user ?? null;
46
- }
47
- if (!user) {
48
- if (!email) {
49
- throw new Error('actingAs: principal must carry an `email` (to create a user) or an ' + '`id` matching an existing user.');
50
- }
51
- const { id: _id, email: _email, name: _name, ...extra } = principal;
52
- user = await internalAdapter.createUser({
53
- ...extra,
54
- email,
55
- name: name ?? email,
56
- ...id ? {
57
- id
58
- } : {}
59
- });
60
- }
61
- const session = await internalAdapter.createSession(user.id, false, {
62
- ipAddress: '127.0.0.1',
63
- userAgent: 'vela-test'
64
- });
65
- const cookieName = ctx.authCookies.sessionToken.name;
66
- const signedToken = `${session.token}.${await makeSignature(session.token, ctx.secret)}`;
67
- const headers = new Headers();
68
- headers.set('Cookie', `${cookieName}=${signedToken}`);
69
- return headers;
70
- }