@nexusts/auth 0.7.0 → 0.7.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.
- package/README.md +4 -2
- package/dist/auth.controller.d.ts +106 -0
- package/dist/auth.d.ts +46 -0
- package/dist/auth.module.d.ts +33 -0
- package/dist/auth.service.d.ts +122 -0
- package/dist/decorators/current-user.d.ts +57 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.js +6 -6
- package/dist/index.js.map +5 -5
- package/dist/middleware.d.ts +49 -0
- package/dist/types.d.ts +134 -0
- package/package.json +6 -19
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ This module is part of the NexusTS monorepo. Each module is published as its own
|
|
|
15
15
|
Most apps start with just the core:
|
|
16
16
|
|
|
17
17
|
```bash
|
|
18
|
-
bun add @nexusts/core
|
|
18
|
+
bun add @nexusts/core
|
|
19
19
|
```
|
|
20
20
|
|
|
21
21
|
Then add this module only if you need it:
|
|
@@ -30,7 +30,9 @@ bun add @nexusts/auth
|
|
|
30
30
|
bun add better-auth
|
|
31
31
|
```
|
|
32
32
|
|
|
33
|
-
|
|
33
|
+
- **`better-auth`** ^1.6.0 — Authentication provider required by this module.
|
|
34
|
+
|
|
35
|
+
Without them the module loads but its public methods throw a clear error pointing to this install command on first call.
|
|
34
36
|
|
|
35
37
|
## Usage
|
|
36
38
|
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `AuthController` — built-in controller exposing common auth endpoints.
|
|
3
|
+
*
|
|
4
|
+
* Mount it in any `@Module` to get a working auth API:
|
|
5
|
+
*
|
|
6
|
+
* @Module({
|
|
7
|
+
* controllers: [AuthController],
|
|
8
|
+
* providers: [AuthService],
|
|
9
|
+
* })
|
|
10
|
+
* export class AuthModule {}
|
|
11
|
+
*
|
|
12
|
+
* Endpoints (all prefixed with `config.basePath`, default `/api/auth`):
|
|
13
|
+
* - GET /session → current session
|
|
14
|
+
* - POST /sign-up/email → email/password registration
|
|
15
|
+
* - POST /sign-in/email → email/password login
|
|
16
|
+
* - POST /sign-out → invalidate session
|
|
17
|
+
* - GET /sign-in/:provider → start OAuth flow
|
|
18
|
+
* - GET /callback/:provider → OAuth callback
|
|
19
|
+
* - POST /jwt → issue JWT (JWT plugin only)
|
|
20
|
+
* - POST /passkey/register → start passkey registration
|
|
21
|
+
* - POST /passkey/authenticate → complete passkey auth
|
|
22
|
+
*
|
|
23
|
+
* Most of the actual logic is delegated to `auth.handler` from
|
|
24
|
+
* better-auth. The controller exists to make the routes visible to
|
|
25
|
+
* `nx route:list` and to add NexusTS-style DI.
|
|
26
|
+
*/
|
|
27
|
+
import type { Context } from "hono";
|
|
28
|
+
import { AuthService } from "./auth.service.js";
|
|
29
|
+
export declare class AuthController {
|
|
30
|
+
private readonly auth;
|
|
31
|
+
constructor(auth: AuthService);
|
|
32
|
+
/**
|
|
33
|
+
* GET /api/auth/session
|
|
34
|
+
* Returns the current session (or null if unauthenticated).
|
|
35
|
+
*/
|
|
36
|
+
session(c: Context): Promise<Response & import("hono").TypedResponse<{
|
|
37
|
+
user: {
|
|
38
|
+
[x: string]: import("hono/utils/types").JSONValue;
|
|
39
|
+
id: string;
|
|
40
|
+
email: string;
|
|
41
|
+
emailVerified: boolean;
|
|
42
|
+
name: string;
|
|
43
|
+
image?: string | null;
|
|
44
|
+
createdAt: string;
|
|
45
|
+
updatedAt: string;
|
|
46
|
+
};
|
|
47
|
+
session: {
|
|
48
|
+
[x: string]: import("hono/utils/types").JSONValue;
|
|
49
|
+
id: string;
|
|
50
|
+
userId: string;
|
|
51
|
+
token: string;
|
|
52
|
+
expiresAt: string;
|
|
53
|
+
ipAddress?: string | null;
|
|
54
|
+
userAgent?: string | null;
|
|
55
|
+
createdAt: string;
|
|
56
|
+
updatedAt: string;
|
|
57
|
+
};
|
|
58
|
+
}, import("hono/utils/http-status").ContentfulStatusCode, "json">>;
|
|
59
|
+
/**
|
|
60
|
+
* POST /api/auth/sign-up/email
|
|
61
|
+
* Body: { email, password, name, callbackURL? }
|
|
62
|
+
*/
|
|
63
|
+
signUpEmail(c: Context, body: any): Promise<Response & import("hono").TypedResponse<any, 201, "json">>;
|
|
64
|
+
/**
|
|
65
|
+
* POST /api/auth/sign-in/email
|
|
66
|
+
* Body: { email, password, callbackURL? }
|
|
67
|
+
*/
|
|
68
|
+
signInEmail(c: Context, body: any): Promise<Response & import("hono").TypedResponse<any, import("hono/utils/http-status").ContentfulStatusCode, "json">>;
|
|
69
|
+
/**
|
|
70
|
+
* POST /api/auth/sign-out
|
|
71
|
+
*/
|
|
72
|
+
signOut(c: Context, _res: Response): Promise<Response & import("hono").TypedResponse<{
|
|
73
|
+
ok: true;
|
|
74
|
+
}, import("hono/utils/http-status").ContentfulStatusCode, "json">>;
|
|
75
|
+
/**
|
|
76
|
+
* GET /api/auth/sign-in/:provider
|
|
77
|
+
* Returns a redirect to the social provider's auth page.
|
|
78
|
+
*/
|
|
79
|
+
socialSignIn(c: Context, _body: never): Promise<Response & import("hono").TypedResponse<any, import("hono/utils/http-status").ContentfulStatusCode, "json">>;
|
|
80
|
+
/**
|
|
81
|
+
* GET /api/auth/callback/:provider
|
|
82
|
+
* Social provider redirect target. The better-auth handler does the
|
|
83
|
+
* real work; this is a passthrough for `route:list` visibility.
|
|
84
|
+
*/
|
|
85
|
+
oauthCallback(c: Context): Promise<Response & import("hono").TypedResponse<any, import("hono/utils/http-status").ContentfulStatusCode, "json">>;
|
|
86
|
+
/**
|
|
87
|
+
* POST /api/auth/jwt
|
|
88
|
+
* Issues a JWT for the current user. Requires the JWT plugin.
|
|
89
|
+
*/
|
|
90
|
+
issueJwt(c: Context): Promise<(Response & import("hono").TypedResponse<{
|
|
91
|
+
error: string;
|
|
92
|
+
}, 401, "json">) | (Response & import("hono").TypedResponse<{
|
|
93
|
+
token: string;
|
|
94
|
+
expiresAt: string;
|
|
95
|
+
}, import("hono/utils/http-status").ContentfulStatusCode, "json">)>;
|
|
96
|
+
/**
|
|
97
|
+
* POST /api/auth/passkey/register
|
|
98
|
+
* Start passkey registration. Requires the passkey plugin.
|
|
99
|
+
*/
|
|
100
|
+
passkeyRegister(c: Context): Promise<Response & import("hono").TypedResponse<import("hono/utils/types").JSONValue, import("hono/utils/http-status").ContentfulStatusCode, "json">>;
|
|
101
|
+
/**
|
|
102
|
+
* POST /api/auth/passkey/authenticate
|
|
103
|
+
* Body: passkey assertion
|
|
104
|
+
*/
|
|
105
|
+
passkeyAuthenticate(c: Context, body: any): Promise<Response & import("hono").TypedResponse<import("hono/utils/types").JSONValue, import("hono/utils/http-status").ContentfulStatusCode, "json">>;
|
|
106
|
+
}
|
package/dist/auth.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `createAuth()` — wrap better-auth's `betterAuth()` factory with
|
|
3
|
+
* NexusTS-friendly defaults.
|
|
4
|
+
*
|
|
5
|
+
* This is the **only** place that talks to better-auth directly. Every
|
|
6
|
+
* other NexusTS auth module consumes the resulting `Auth` instance via
|
|
7
|
+
* DI or the registered token.
|
|
8
|
+
*
|
|
9
|
+
* Why an adapter layer instead of calling `betterAuth()` directly?
|
|
10
|
+
* 1. NexusTS users write `auth.config.ts`, not raw better-auth options.
|
|
11
|
+
* The adapter translates between the two.
|
|
12
|
+
* 2. Plugin selection (jwt, passkey) is toggled by boolean flags,
|
|
13
|
+
* not by importing plugin objects.
|
|
14
|
+
* 3. Cookie / CORS / cross-subdomain defaults match Hono's `cors()`
|
|
15
|
+
* middleware so the two never conflict.
|
|
16
|
+
*
|
|
17
|
+
* Usage:
|
|
18
|
+
* // src/auth/auth.ts
|
|
19
|
+
* import { createAuth } from 'nexusjs/auth';
|
|
20
|
+
* export const auth = createAuth({
|
|
21
|
+
* basePath: '/api/auth',
|
|
22
|
+
* emailAndPassword: { enabled: true },
|
|
23
|
+
* socialProviders: {
|
|
24
|
+
* github: {
|
|
25
|
+
* clientId: process.env.GITHUB_CLIENT_ID!,
|
|
26
|
+
* clientSecret: process.env.GITHUB_CLIENT_SECRET!,
|
|
27
|
+
* },
|
|
28
|
+
* },
|
|
29
|
+
* });
|
|
30
|
+
*/
|
|
31
|
+
import { betterAuth } from "better-auth";
|
|
32
|
+
import type { AuthConfig } from "./types.js";
|
|
33
|
+
type BetterAuthInstance = ReturnType<typeof betterAuth>;
|
|
34
|
+
/**
|
|
35
|
+
* Create a better-auth instance with NexusTS-friendly defaults.
|
|
36
|
+
*
|
|
37
|
+
* @param config NexusTS-shaped config (see types.ts).
|
|
38
|
+
* @returns A `better-auth` Auth instance.
|
|
39
|
+
*/
|
|
40
|
+
export declare function createAuth(config?: AuthConfig): BetterAuthInstance;
|
|
41
|
+
/**
|
|
42
|
+
* Type alias for the returned auth instance — convenient for DI token
|
|
43
|
+
* typings.
|
|
44
|
+
*/
|
|
45
|
+
export type NexusAuth = ReturnType<typeof createAuth>;
|
|
46
|
+
export {};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `AuthModule` — drop-in module for adding auth to any NexusTS app.
|
|
3
|
+
*
|
|
4
|
+
* Usage:
|
|
5
|
+
* // src/app/app.module.ts
|
|
6
|
+
* @Module({
|
|
7
|
+
* imports: [AuthModule.forRoot({ ... })],
|
|
8
|
+
* })
|
|
9
|
+
* export class AppModule {}
|
|
10
|
+
*
|
|
11
|
+
* The `forRoot` static factory builds a one-off `AuthModule` subclass
|
|
12
|
+
* pre-configured with the user's `auth` config. The provider token
|
|
13
|
+
* `'AUTH_CONFIG'` carries the config to the `AuthService` constructor.
|
|
14
|
+
*
|
|
15
|
+
* AuthService is registered under **both** its class token and
|
|
16
|
+
* `AuthService.TOKEN` (a Symbol). The class token is what the
|
|
17
|
+
* container scans; the Symbol is what `@Inject(AuthService.TOKEN)`
|
|
18
|
+
* looks up. Both resolve to the same instance via `useExisting`.
|
|
19
|
+
*/
|
|
20
|
+
import "reflect-metadata";
|
|
21
|
+
import type { AuthConfig } from "./types.js";
|
|
22
|
+
export declare class AuthModule {
|
|
23
|
+
/**
|
|
24
|
+
* Build a configured `AuthModule` class with the given config.
|
|
25
|
+
*
|
|
26
|
+
* The returned class can be `imports`-ed by any other module and
|
|
27
|
+
* will provide the `AuthService` (and a `AUTH_CONFIG` value
|
|
28
|
+
* provider) to its container.
|
|
29
|
+
*/
|
|
30
|
+
static forRoot(config: AuthConfig): {
|
|
31
|
+
new (): {};
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `AuthService` — DI-friendly wrapper around a better-auth instance.
|
|
3
|
+
*
|
|
4
|
+
* Why a service wrapper?
|
|
5
|
+
* - Hides the raw better-auth object behind a stable NexusTS API.
|
|
6
|
+
* - Exposes the high-level operations controllers need:
|
|
7
|
+
* signUp, signIn, signOut, getSession, oauthUrl, jwt, passkey.
|
|
8
|
+
* - Allows tests to swap the implementation via DI.
|
|
9
|
+
*
|
|
10
|
+
* Usage:
|
|
11
|
+
* constructor(@Inject(AuthService.TOKEN) private auth: AuthService) {}
|
|
12
|
+
*
|
|
13
|
+
* await this.auth.signUp.email({ email, password, name });
|
|
14
|
+
* const session = await this.auth.getSession({ headers: c.req.raw.headers });
|
|
15
|
+
* return this.auth.redirect('/dashboard'); // 302
|
|
16
|
+
*/
|
|
17
|
+
import type { AuthUser, AuthSessionRecord, AuthSession, AuthConfig } from "./types.js";
|
|
18
|
+
import { type NexusAuth } from "./auth.js";
|
|
19
|
+
import type { SessionService } from "@nexusts/session";
|
|
20
|
+
export declare class AuthService {
|
|
21
|
+
#private;
|
|
22
|
+
private readonly config;
|
|
23
|
+
/** DI token — use with `@Inject(AuthService.TOKEN)`. */
|
|
24
|
+
static readonly TOKEN: unique symbol;
|
|
25
|
+
/** The underlying better-auth instance. */
|
|
26
|
+
readonly instance: NexusAuth;
|
|
27
|
+
constructor(config: AuthConfig);
|
|
28
|
+
/**
|
|
29
|
+
* Bind a SessionService. When bound, `getSession()` consults the
|
|
30
|
+
* SessionService first and falls back to better-auth. Returns `this`
|
|
31
|
+
* for chaining.
|
|
32
|
+
*/
|
|
33
|
+
bindSession(sessionService: SessionService): this;
|
|
34
|
+
/**
|
|
35
|
+
* Returns true when a SessionService has been bound.
|
|
36
|
+
*/
|
|
37
|
+
hasSessionBinding(): boolean;
|
|
38
|
+
/**
|
|
39
|
+
* Get the current session from a request. Returns `null` if not
|
|
40
|
+
* authenticated.
|
|
41
|
+
*
|
|
42
|
+
* When a SessionService is bound, we try it first (cookie-based,
|
|
43
|
+
* stateless, edge-friendly); better-auth remains the source of
|
|
44
|
+
* truth for `user` / `session` records. The cookie value carries
|
|
45
|
+
* `userId` which lets you cross-reference both systems.
|
|
46
|
+
*/
|
|
47
|
+
getSession(input: {
|
|
48
|
+
headers: Headers;
|
|
49
|
+
}): Promise<AuthSession>;
|
|
50
|
+
/**
|
|
51
|
+
* Read the raw SessionService record from a request (no better-auth
|
|
52
|
+
* lookup). Returns null when no SessionService is bound or no
|
|
53
|
+
* session is found.
|
|
54
|
+
*/
|
|
55
|
+
getRawSession(input: {
|
|
56
|
+
headers: Headers;
|
|
57
|
+
}): Promise<any>;
|
|
58
|
+
/**
|
|
59
|
+
* Email + password sign-up. Throws if email/password is disabled
|
|
60
|
+
* in the auth config.
|
|
61
|
+
*/
|
|
62
|
+
signUp(input: {
|
|
63
|
+
email: string;
|
|
64
|
+
password: string;
|
|
65
|
+
name: string;
|
|
66
|
+
image?: string;
|
|
67
|
+
callbackURL?: string;
|
|
68
|
+
}): Promise<any>;
|
|
69
|
+
/** Email + password sign-in. */
|
|
70
|
+
signIn(input: {
|
|
71
|
+
email: string;
|
|
72
|
+
password: string;
|
|
73
|
+
callbackURL?: string;
|
|
74
|
+
}): Promise<any>;
|
|
75
|
+
/** Sign out — invalidates the current session. */
|
|
76
|
+
signOut(input: {
|
|
77
|
+
headers: Headers;
|
|
78
|
+
}): Promise<any>;
|
|
79
|
+
/**
|
|
80
|
+
* Get the URL the client should redirect to for a social sign-in.
|
|
81
|
+
*/
|
|
82
|
+
getOAuthUrl(input: {
|
|
83
|
+
provider: string;
|
|
84
|
+
callbackURL?: string;
|
|
85
|
+
}): Promise<any>;
|
|
86
|
+
/**
|
|
87
|
+
* Sign in / link a social account and return the user.
|
|
88
|
+
*/
|
|
89
|
+
handleOAuthCallback(input: {
|
|
90
|
+
headers: Headers;
|
|
91
|
+
query: Record<string, string>;
|
|
92
|
+
}): Promise<any>;
|
|
93
|
+
/**
|
|
94
|
+
* Issue a JWT for the currently-authenticated user. Returns
|
|
95
|
+
* `{ token, expiresAt }`. Requires the JWT plugin (`config.jwt.enabled`).
|
|
96
|
+
*/
|
|
97
|
+
issueJwt(input: {
|
|
98
|
+
userId: string;
|
|
99
|
+
}): Promise<{
|
|
100
|
+
token: string;
|
|
101
|
+
expiresAt: Date;
|
|
102
|
+
}>;
|
|
103
|
+
registerPasskey(input: {
|
|
104
|
+
headers: Headers;
|
|
105
|
+
}): Promise<unknown>;
|
|
106
|
+
authenticatePasskey(input: {
|
|
107
|
+
headers: Headers;
|
|
108
|
+
body: unknown;
|
|
109
|
+
}): Promise<unknown>;
|
|
110
|
+
/**
|
|
111
|
+
* Build a redirect Response. Used by controllers that need to send
|
|
112
|
+
* the user to a different page after sign-in / sign-up.
|
|
113
|
+
*/
|
|
114
|
+
redirect(to: string, status?: 302 | 303 | 307 | 308): Response;
|
|
115
|
+
/**
|
|
116
|
+
* Convert a session into the `AuthVariables` shape Hono expects.
|
|
117
|
+
*/
|
|
118
|
+
toContextVariables(session: AuthSession): {
|
|
119
|
+
user: AuthUser | null;
|
|
120
|
+
session: AuthSessionRecord | null;
|
|
121
|
+
};
|
|
122
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@CurrentUser()` — controller parameter decorator that injects the
|
|
3
|
+
* authenticated user (and optionally the session) into a handler.
|
|
4
|
+
*
|
|
5
|
+
* Usage:
|
|
6
|
+
* @Get('/me')
|
|
7
|
+
* me(@CurrentUser() user: AuthUser) {
|
|
8
|
+
* return user;
|
|
9
|
+
* }
|
|
10
|
+
*
|
|
11
|
+
* @Get('/profile')
|
|
12
|
+
* profile(@CurrentUser({ session: true }) ctx: { user: AuthUser; session: AuthSessionRecord }) {
|
|
13
|
+
* return ctx;
|
|
14
|
+
* }
|
|
15
|
+
*
|
|
16
|
+
* @Get('/dashboard')
|
|
17
|
+
* dashboard(@CurrentUser({ required: true }) user: AuthUser) {
|
|
18
|
+
* // 401 is thrown before the handler if no user is present.
|
|
19
|
+
* return this.dashboardService.forUser(user.id);
|
|
20
|
+
* }
|
|
21
|
+
*/
|
|
22
|
+
import "reflect-metadata";
|
|
23
|
+
import type { AuthUser, AuthSessionRecord } from "../types.js";
|
|
24
|
+
export interface CurrentUserOptions {
|
|
25
|
+
/**
|
|
26
|
+
* Include the session in the injected value. Default: `false`.
|
|
27
|
+
* When true, the value is `{ user, session }` instead of just the user.
|
|
28
|
+
*/
|
|
29
|
+
session?: boolean;
|
|
30
|
+
/**
|
|
31
|
+
* Throw 401 if no user is present. Default: `false`.
|
|
32
|
+
* When true, the framework returns a 401 response without invoking
|
|
33
|
+
* the handler.
|
|
34
|
+
*/
|
|
35
|
+
required?: boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Throw 403 if the user does not satisfy the predicate.
|
|
38
|
+
*/
|
|
39
|
+
assert?: (user: AuthUser) => boolean | Promise<boolean>;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Inject the authenticated user (or `{ user, session }` if `session: true`).
|
|
43
|
+
*/
|
|
44
|
+
export declare function CurrentUser(options?: CurrentUserOptions): ParameterDecorator;
|
|
45
|
+
/**
|
|
46
|
+
* Convenience: throw 401 with a JSON body when no user is present.
|
|
47
|
+
* Exposed for users who want to enforce auth inside the handler.
|
|
48
|
+
*/
|
|
49
|
+
export declare class UnauthenticatedError extends Error {
|
|
50
|
+
readonly status = 401;
|
|
51
|
+
constructor(message?: string);
|
|
52
|
+
}
|
|
53
|
+
export declare class ForbiddenError extends Error {
|
|
54
|
+
readonly status = 403;
|
|
55
|
+
constructor(message?: string);
|
|
56
|
+
}
|
|
57
|
+
export type { AuthSessionRecord as AuthSession };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public API for the NexusTS auth module.
|
|
3
|
+
*
|
|
4
|
+
* This is a thin layer over `better-auth` — it does not re-implement
|
|
5
|
+
* any auth primitives. It adapts better-auth's surface to NexusTS's
|
|
6
|
+
* DI / decorator model.
|
|
7
|
+
*
|
|
8
|
+
* Quick start:
|
|
9
|
+
*
|
|
10
|
+
* // src/auth/auth.ts
|
|
11
|
+
* import { createAuth } from 'nexusjs/auth';
|
|
12
|
+
* export const auth = createAuth({
|
|
13
|
+
* emailAndPassword: { enabled: true },
|
|
14
|
+
* socialProviders: { github: { clientId: '...', clientSecret: '...' } },
|
|
15
|
+
* });
|
|
16
|
+
*
|
|
17
|
+
* // src/app/app.module.ts
|
|
18
|
+
* import { Module } from 'nexusjs';
|
|
19
|
+
* import { AuthModule } from 'nexusjs/auth';
|
|
20
|
+
*
|
|
21
|
+
* @Module({ imports: [AuthModule.forRoot({ ... })] })
|
|
22
|
+
* export class AppModule {}
|
|
23
|
+
*
|
|
24
|
+
* // any controller
|
|
25
|
+
* import { CurrentUser } from 'nexusjs/auth';
|
|
26
|
+
*
|
|
27
|
+
* @Controller('/profile')
|
|
28
|
+
* class ProfileController {
|
|
29
|
+
* @Get('/')
|
|
30
|
+
* me(@CurrentUser({ required: true }) user) {
|
|
31
|
+
* return user;
|
|
32
|
+
* }
|
|
33
|
+
* }
|
|
34
|
+
*/
|
|
35
|
+
export * from "./types.js";
|
|
36
|
+
export { createAuth } from "./auth.js";
|
|
37
|
+
export type { NexusAuth } from "./auth.js";
|
|
38
|
+
export { AuthService } from "./auth.service.js";
|
|
39
|
+
export { AuthController } from "./auth.controller.js";
|
|
40
|
+
export { AuthModule } from "./auth.module.js";
|
|
41
|
+
export { authMiddleware, authHandler, type AuthMiddlewareMode, type AuthMiddlewareOptions, } from "./middleware.js";
|
|
42
|
+
export { CurrentUser, UnauthenticatedError, ForbiddenError, type CurrentUserOptions, } from "./decorators/current-user.js";
|
package/dist/index.js
CHANGED
|
@@ -79,7 +79,7 @@ function createAuth(config = {}) {
|
|
|
79
79
|
});
|
|
80
80
|
}
|
|
81
81
|
// packages/auth/src/auth.service.ts
|
|
82
|
-
import { Inject, Injectable } from "@nexusts/core
|
|
82
|
+
import { Inject, Injectable } from "@nexusts/core";
|
|
83
83
|
class AuthService {
|
|
84
84
|
config;
|
|
85
85
|
static TOKEN = Symbol.for("nexus:AuthService");
|
|
@@ -220,7 +220,7 @@ import {
|
|
|
220
220
|
Post,
|
|
221
221
|
Req,
|
|
222
222
|
Res
|
|
223
|
-
} from "@nexusts/core
|
|
223
|
+
} from "@nexusts/core";
|
|
224
224
|
class AuthController {
|
|
225
225
|
auth;
|
|
226
226
|
constructor(auth) {
|
|
@@ -380,7 +380,7 @@ AuthController = __legacyDecorateClassTS([
|
|
|
380
380
|
], AuthController);
|
|
381
381
|
// packages/auth/src/auth.module.ts
|
|
382
382
|
import"reflect-metadata";
|
|
383
|
-
import { Module } from "@nexusts/core
|
|
383
|
+
import { Module } from "@nexusts/core";
|
|
384
384
|
class AuthModule {
|
|
385
385
|
static forRoot(config) {
|
|
386
386
|
class ConfiguredAuthModule {
|
|
@@ -465,8 +465,8 @@ function authHandler(auth) {
|
|
|
465
465
|
}
|
|
466
466
|
// packages/auth/src/decorators/current-user.ts
|
|
467
467
|
import"reflect-metadata";
|
|
468
|
-
import { createParamDecorator } from "@nexusts/core
|
|
469
|
-
import { PARAM_TYPES } from "@nexusts/core
|
|
468
|
+
import { createParamDecorator } from "@nexusts/core";
|
|
469
|
+
import { PARAM_TYPES } from "@nexusts/core";
|
|
470
470
|
function CurrentUser(options = {}) {
|
|
471
471
|
return createParamDecorator(PARAM_TYPES.USER, options);
|
|
472
472
|
}
|
|
@@ -498,5 +498,5 @@ export {
|
|
|
498
498
|
AuthController
|
|
499
499
|
};
|
|
500
500
|
|
|
501
|
-
//# debugId=
|
|
501
|
+
//# debugId=D67F72E911A0099D64756E2164756E21
|
|
502
502
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -3,13 +3,13 @@
|
|
|
3
3
|
"sources": ["../src/auth.ts", "../src/auth.service.ts", "../src/auth.controller.ts", "../src/auth.module.ts", "../src/middleware.ts", "../src/decorators/current-user.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"/**\n * `createAuth()` — wrap better-auth's `betterAuth()` factory with\n * NexusTS-friendly defaults.\n *\n * This is the **only** place that talks to better-auth directly. Every\n * other NexusTS auth module consumes the resulting `Auth` instance via\n * DI or the registered token.\n *\n * Why an adapter layer instead of calling `betterAuth()` directly?\n * 1. NexusTS users write `auth.config.ts`, not raw better-auth options.\n * The adapter translates between the two.\n * 2. Plugin selection (jwt, passkey) is toggled by boolean flags,\n * not by importing plugin objects.\n * 3. Cookie / CORS / cross-subdomain defaults match Hono's `cors()`\n * middleware so the two never conflict.\n *\n * Usage:\n * // src/auth/auth.ts\n * import { createAuth } from 'nexusjs/auth';\n * export const auth = createAuth({\n * basePath: '/api/auth',\n * emailAndPassword: { enabled: true },\n * socialProviders: {\n * github: {\n * clientId: process.env.GITHUB_CLIENT_ID!,\n * clientSecret: process.env.GITHUB_CLIENT_SECRET!,\n * },\n * },\n * });\n */\n\nimport { betterAuth } from \"better-auth\";\nimport type { AuthConfig } from \"./types.js\";\n\ntype BetterAuthInstance = ReturnType<typeof betterAuth>;\n\n/**\n * Create a better-auth instance with NexusTS-friendly defaults.\n *\n * @param config NexusTS-shaped config (see types.ts).\n * @returns A `better-auth` Auth instance.\n */\nexport function createAuth(config: AuthConfig = {}): BetterAuthInstance {\n\tconst secret = config.secret ?? process.env[\"BETTER_AUTH_SECRET\"];\n\tconst baseURL = config.baseUrl ?? process.env[\"BETTER_AUTH_URL\"];\n\n\tif (!secret) {\n\t\tthrow new Error(\n\t\t\t\"[nexus/auth] BETTER_AUTH_SECRET is required. \" +\n\t\t\t\t\"Generate one with `openssl rand -base64 32` and add it to .env.\",\n\t\t);\n\t}\n\tif (!baseURL) {\n\t\tthrow new Error(\n\t\t\t\"[nexus/auth] BETTER_AUTH_URL is required (e.g. http://localhost:3000).\",\n\t\t);\n\t}\n\n\tconst plugins: Array<unknown> = [];\n\n\t// JWT plugin — opt-in.\n\tif (config.jwt?.enabled) {\n\t\t// Lazy import so the plugin's transitive dependencies don't load\n\t\t// when the user hasn't asked for JWT.\n\t\t// eslint-disable-next-line @typescript-eslint/no-require-imports\n\t\tconst { jwt } = require(\"better-auth/plugins\");\n\t\tplugins.push(\n\t\t\tjwt({\n\t\t\t\tjwks: {\n\t\t\t\t\tpath: config.jwt.jwksPath ?? \"/api/auth/jwks\",\n\t\t\t\t},\n\t\t\t\tissuer: config.jwt.issuer ?? baseURL,\n\t\t\t\taudience: config.jwt.audience ?? baseURL,\n\t\t\t\texpiresIn: config.jwt.expiresIn ?? 60 * 15,\n\t\t\t}),\n\t\t);\n\t}\n\n\t// Passkey plugin — opt-in.\n\tif (config.passkey?.enabled) {\n\t\t// eslint-disable-next-line @typescript-eslint/no-require-imports\n\t\tconst { passkey } = require(\"better-auth/plugins\");\n\t\tplugins.push(\n\t\t\tpasskey({\n\t\t\t\trpName: config.passkey.rpName,\n\t\t\t\trpID: config.passkey.rpId,\n\t\t\t\torigin: config.passkey.origin,\n\t\t\t}),\n\t\t);\n\t}\n\n\treturn betterAuth({\n\t\tsecret,\n\t\tbaseURL,\n\t\tbasePath: config.basePath ?? \"/api/auth\",\n\t\temailAndPassword: {\n\t\t\tenabled: config.emailAndPassword?.enabled ?? true,\n\t\t\trequireEmailVerification:\n\t\t\t\tconfig.emailAndPassword?.requireEmailVerification ?? false,\n\t\t\tminPasswordLength: config.emailAndPassword?.minPasswordLength ?? 8,\n\t\t\tmaxPasswordLength: config.emailAndPassword?.maxPasswordLength ?? 128,\n\t\t},\n\t\tsession: {\n\t\t\texpiresIn: config.sessionExpiresInSeconds ?? 60 * 60 * 24 * 7, // 7 days\n\t\t},\n\t\tsocialProviders: config.socialProviders as never,\n\t\tadvanced: {\n\t\t\tcookies: {\n\t\t\t\tsessionToken: {\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\tsameSite: (config.cookieSameSite ?? \"lax\") as\n\t\t\t\t\t\t\t| \"lax\"\n\t\t\t\t\t\t\t| \"strict\"\n\t\t\t\t\t\t\t| \"none\",\n\t\t\t\t\t\tsecure:\n\t\t\t\t\t\t\tconfig.cookieSecure ?? process.env[\"NODE_ENV\"] === \"production\",\n\t\t\t\t\t\t...(config.cookieDomain ? { domain: config.cookieDomain } : {}),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tcrossSubDomainCookies: config.crossSubDomainCookies?.enabled\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdomain: config.crossSubDomainCookies.domain,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t},\n\t\tplugins,\n\t} as never) as unknown as BetterAuthInstance;\n}\n\n/**\n * Type alias for the returned auth instance — convenient for DI token\n * typings.\n */\nexport type NexusAuth = ReturnType<typeof createAuth>;\n",
|
|
6
|
-
"/**\n * `AuthService` — DI-friendly wrapper around a better-auth instance.\n *\n * Why a service wrapper?\n * - Hides the raw better-auth object behind a stable NexusTS API.\n * - Exposes the high-level operations controllers need:\n * signUp, signIn, signOut, getSession, oauthUrl, jwt, passkey.\n * - Allows tests to swap the implementation via DI.\n *\n * Usage:\n * constructor(@Inject(AuthService.TOKEN) private auth: AuthService) {}\n *\n * await this.auth.signUp.email({ email, password, name });\n * const session = await this.auth.getSession({ headers: c.req.raw.headers });\n * return this.auth.redirect('/dashboard'); // 302\n */\n\nimport { Inject, Injectable } from \"@nexusts/core
|
|
7
|
-
"/**\n * `AuthController` — built-in controller exposing common auth endpoints.\n *\n * Mount it in any `@Module` to get a working auth API:\n *\n * @Module({\n * controllers: [AuthController],\n * providers: [AuthService],\n * })\n * export class AuthModule {}\n *\n * Endpoints (all prefixed with `config.basePath`, default `/api/auth`):\n * - GET /session → current session\n * - POST /sign-up/email → email/password registration\n * - POST /sign-in/email → email/password login\n * - POST /sign-out → invalidate session\n * - GET /sign-in/:provider → start OAuth flow\n * - GET /callback/:provider → OAuth callback\n * - POST /jwt → issue JWT (JWT plugin only)\n * - POST /passkey/register → start passkey registration\n * - POST /passkey/authenticate → complete passkey auth\n *\n * Most of the actual logic is delegated to `auth.handler` from\n * better-auth. The controller exists to make the routes visible to\n * `nx route:list` and to add NexusTS-style DI.\n */\n\nimport {\n\tBody,\n\tController,\n\tGet,\n\tInject,\n\tPost,\n\tReq,\n\tRes,\n} from \"@nexusts/core
|
|
8
|
-
"/**\n * `AuthModule` — drop-in module for adding auth to any NexusTS app.\n *\n * Usage:\n * // src/app/app.module.ts\n * @Module({\n * imports: [AuthModule.forRoot({ ... })],\n * })\n * export class AppModule {}\n *\n * The `forRoot` static factory builds a one-off `AuthModule` subclass\n * pre-configured with the user's `auth` config. The provider token\n * `'AUTH_CONFIG'` carries the config to the `AuthService` constructor.\n *\n * AuthService is registered under **both** its class token and\n * `AuthService.TOKEN` (a Symbol). The class token is what the\n * container scans; the Symbol is what `@Inject(AuthService.TOKEN)`\n * looks up. Both resolve to the same instance via `useExisting`.\n */\n\nimport \"reflect-metadata\";\nimport { Module } from \"@nexusts/core
|
|
6
|
+
"/**\n * `AuthService` — DI-friendly wrapper around a better-auth instance.\n *\n * Why a service wrapper?\n * - Hides the raw better-auth object behind a stable NexusTS API.\n * - Exposes the high-level operations controllers need:\n * signUp, signIn, signOut, getSession, oauthUrl, jwt, passkey.\n * - Allows tests to swap the implementation via DI.\n *\n * Usage:\n * constructor(@Inject(AuthService.TOKEN) private auth: AuthService) {}\n *\n * await this.auth.signUp.email({ email, password, name });\n * const session = await this.auth.getSession({ headers: c.req.raw.headers });\n * return this.auth.redirect('/dashboard'); // 302\n */\n\nimport { Inject, Injectable } from \"@nexusts/core\";\nimport type {\n\tAuthUser,\n\tAuthSessionRecord,\n\tAuthSession,\n\tAuthConfig,\n} from \"./types.js\";\nimport { createAuth, type NexusAuth } from \"./auth.js\";\nimport type { SessionService } from \"@nexusts/session\";\n\n@Injectable()\nexport class AuthService {\n\t/** DI token — use with `@Inject(AuthService.TOKEN)`. */\n\tstatic readonly TOKEN = Symbol.for(\"nexus:AuthService\");\n\n\t/** The underlying better-auth instance. */\n\treadonly instance: NexusAuth;\n\n\t/**\n\t * Optional SessionService binding. When set, `getSession()` will\n\t * first check the SessionService's cookie before falling back to\n\t * better-auth. This enables shared session state between the two\n\t * modules (e.g. flash messages, guest cart).\n\t *\n\t * Set via `bindSession()` from a feature module's `onInit`, or via\n\t * DI when both modules are present.\n\t */\n\t#sessionService: SessionService | null = null;\n\n\tconstructor(\n\t\t@Inject(\"AUTH_CONFIG\") private readonly config: AuthConfig,\n\t) {\n\t\t// Lazy: defer construction to the first call so module-load\n\t\t// order doesn't matter.\n\t\tthis.instance = createAuth(this.config);\n\t}\n\n\t// ===========================================================================\n\t// Session integration\n\t// ===========================================================================\n\n\t/**\n\t * Bind a SessionService. When bound, `getSession()` consults the\n\t * SessionService first and falls back to better-auth. Returns `this`\n\t * for chaining.\n\t */\n\tbindSession(sessionService: SessionService): this {\n\t\tthis.#sessionService = sessionService;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Returns true when a SessionService has been bound.\n\t */\n\thasSessionBinding(): boolean {\n\t\treturn this.#sessionService !== null;\n\t}\n\n\t// ===========================================================================\n\t// Session\n\t// ===========================================================================\n\n\t/**\n\t * Get the current session from a request. Returns `null` if not\n\t * authenticated.\n\t *\n\t * When a SessionService is bound, we try it first (cookie-based,\n\t * stateless, edge-friendly); better-auth remains the source of\n\t * truth for `user` / `session` records. The cookie value carries\n\t * `userId` which lets you cross-reference both systems.\n\t */\n\tasync getSession(input: { headers: Headers }): Promise<AuthSession> {\n\t\t// 1) Try SessionService (cookie-based) first.\n\t\tif (this.#sessionService) {\n\t\t\tconst cookieName = this.#sessionService.cookieName;\n\t\t\tif (cookieName) {\n\t\t\t\tconst cookieHeader = input.headers.get(\"cookie\") ?? \"\";\n\t\t\t\tconst value = parseCookie(cookieHeader, cookieName);\n\t\t\t\tif (value) {\n\t\t\t\t\tconst decoded = this.#sessionService.decodeCookie(value);\n\t\t\t\t\tif (decoded?.userId) {\n\t\t\t\t\t\t// Hydrate the user from better-auth (so the returned\n\t\t\t\t\t\t// shape matches what controllers expect).\n\t\t\t\t\t\tconst fromBetterAuth = (await this.instance.api.getSession({\n\t\t\t\t\t\t\theaders: input.headers,\n\t\t\t\t\t\t})) as AuthSession | null;\n\t\t\t\t\t\tif (fromBetterAuth?.user) {\n\t\t\t\t\t\t\treturn fromBetterAuth;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// 2) Fallback to better-auth.\n\t\tconst result = await this.instance.api.getSession({\n\t\t\theaders: input.headers,\n\t\t});\n\t\treturn result as AuthSession;\n\t}\n\n\t/**\n\t * Read the raw SessionService record from a request (no better-auth\n\t * lookup). Returns null when no SessionService is bound or no\n\t * session is found.\n\t */\n\tasync getRawSession(input: { headers: Headers }) {\n\t\tif (!this.#sessionService) return null;\n\t\tconst cookieName = this.#sessionService.cookieName;\n\t\tif (!cookieName) return null;\n\t\tconst cookieHeader = input.headers.get(\"cookie\") ?? \"\";\n\t\tconst value = parseCookie(cookieHeader, cookieName);\n\t\tif (!value) return null;\n\t\treturn this.#sessionService.decodeCookie(value);\n\t}\n\n\t// ===========================================================================\n\t// Sign up / Sign in / Sign out\n\t// ===========================================================================\n\n\t/**\n\t * Email + password sign-up. Throws if email/password is disabled\n\t * in the auth config.\n\t */\n\tasync signUp(input: {\n\t\temail: string;\n\t\tpassword: string;\n\t\tname: string;\n\t\timage?: string;\n\t\tcallbackURL?: string;\n\t}) {\n\t\treturn this.instance.api.signUpEmail({\n\t\t\tbody: input as never,\n\t\t});\n\t}\n\n\t/** Email + password sign-in. */\n\tasync signIn(input: { email: string; password: string; callbackURL?: string }) {\n\t\treturn this.instance.api.signInEmail({\n\t\t\tbody: input as never,\n\t\t});\n\t}\n\n\t/** Sign out — invalidates the current session. */\n\tasync signOut(input: { headers: Headers }) {\n\t\treturn this.instance.api.signOut({\n\t\t\theaders: input.headers,\n\t\t});\n\t}\n\n\t// ===========================================================================\n\t// Social / OAuth\n\t// ===========================================================================\n\n\t/**\n\t * Get the URL the client should redirect to for a social sign-in.\n\t */\n\tasync getOAuthUrl(input: {\n\t\tprovider: string;\n\t\tcallbackURL?: string;\n\t}) {\n\t\treturn this.instance.api.signInSocial({\n\t\t\tbody: input as never,\n\t\t});\n\t}\n\n\t/**\n\t * Sign in / link a social account and return the user.\n\t */\n\tasync handleOAuthCallback(input: { headers: Headers; query: Record<string, string> }) {\n\t\treturn this.instance.api.signInSocial({\n\t\t\theaders: input.headers,\n\t\t\tquery: input.query,\n\t\t\tbody: {} as never,\n\t\t});\n\t}\n\n\t// ===========================================================================\n\t// JWT\n\t// ===========================================================================\n\n\t/**\n\t * Issue a JWT for the currently-authenticated user. Returns\n\t * `{ token, expiresAt }`. Requires the JWT plugin (`config.jwt.enabled`).\n\t */\n\tasync issueJwt(input: { userId: string }) {\n\t\tconst api = this.instance.api as unknown as {\n\t\t\tsignJWT?: (input: { body: { userId: string } }) => Promise<{\n\t\t\t\ttoken: string;\n\t\t\t\texpiresAt: Date;\n\t\t\t}>;\n\t\t};\n\t\tif (!api.signJWT) {\n\t\t\tthrow new Error(\n\t\t\t\t\"[nexus/auth] JWT plugin not enabled. Set `auth.jwt.enabled: true` in nx.config.ts.\",\n\t\t\t);\n\t\t}\n\t\treturn api.signJWT({ body: { userId: input.userId } });\n\t}\n\n\t// ===========================================================================\n\t// Passkey\n\t// ===========================================================================\n\n\tasync registerPasskey(input: { headers: Headers }) {\n\t\tconst api = this.instance.api as unknown as {\n\t\t\tpasskey?: {\n\t\t\t\tregister: (input: { headers: Headers }) => Promise<unknown>;\n\t\t\t};\n\t\t};\n\t\tif (!api.passkey) {\n\t\t\tthrow new Error(\n\t\t\t\t\"[nexus/auth] Passkey plugin not enabled. Set `auth.passkey.enabled: true` in nx.config.ts.\",\n\t\t\t);\n\t\t}\n\t\treturn api.passkey.register({ headers: input.headers });\n\t}\n\n\tasync authenticatePasskey(input: { headers: Headers; body: unknown }) {\n\t\tconst api = this.instance.api as unknown as {\n\t\t\tpasskey?: {\n\t\t\t\tauthenticate: (input: { headers: Headers; body: unknown }) => Promise<unknown>;\n\t\t\t};\n\t\t};\n\t\tif (!api.passkey) {\n\t\t\tthrow new Error(\"[nexus/auth] Passkey plugin not enabled.\");\n\t\t}\n\t\treturn api.passkey.authenticate({ headers: input.headers, body: input.body });\n\t}\n\n\t// ===========================================================================\n\t// Helpers\n\t// ===========================================================================\n\n\t/**\n\t * Build a redirect Response. Used by controllers that need to send\n\t * the user to a different page after sign-in / sign-up.\n\t */\n\tredirect(to: string, status: 302 | 303 | 307 | 308 = 302): Response {\n\t\treturn new Response(null, { status, headers: { Location: to } });\n\t}\n\n\t/**\n\t * Convert a session into the `AuthVariables` shape Hono expects.\n\t */\n\ttoContextVariables(session: AuthSession): {\n\t\tuser: AuthUser | null;\n\t\tsession: AuthSessionRecord | null;\n\t} {\n\t\tif (!session) return { user: null, session: null };\n\t\treturn { user: session.user, session: session.session };\n\t}\n}\n\n/**\n * Extract a single cookie value from a `Cookie` header string.\n * Tiny helper to avoid pulling in a cookie-parsing dependency.\n */\nfunction parseCookie(cookieHeader: string, name: string): string | null {\n\tif (!cookieHeader) return null;\n\tconst parts = cookieHeader.split(\";\");\n\tfor (const part of parts) {\n\t\tconst eq = part.indexOf(\"=\");\n\t\tif (eq < 0) continue;\n\t\tconst k = part.slice(0, eq).trim();\n\t\tif (k === name) {\n\t\t\treturn decodeURIComponent(part.slice(eq + 1).trim());\n\t\t}\n\t}\n\treturn null;\n}",
|
|
7
|
+
"/**\n * `AuthController` — built-in controller exposing common auth endpoints.\n *\n * Mount it in any `@Module` to get a working auth API:\n *\n * @Module({\n * controllers: [AuthController],\n * providers: [AuthService],\n * })\n * export class AuthModule {}\n *\n * Endpoints (all prefixed with `config.basePath`, default `/api/auth`):\n * - GET /session → current session\n * - POST /sign-up/email → email/password registration\n * - POST /sign-in/email → email/password login\n * - POST /sign-out → invalidate session\n * - GET /sign-in/:provider → start OAuth flow\n * - GET /callback/:provider → OAuth callback\n * - POST /jwt → issue JWT (JWT plugin only)\n * - POST /passkey/register → start passkey registration\n * - POST /passkey/authenticate → complete passkey auth\n *\n * Most of the actual logic is delegated to `auth.handler` from\n * better-auth. The controller exists to make the routes visible to\n * `nx route:list` and to add NexusTS-style DI.\n */\n\nimport {\n\tBody,\n\tController,\n\tGet,\n\tInject,\n\tPost,\n\tReq,\n\tRes,\n} from \"@nexusts/core\";\nimport type { Context } from \"hono\";\nimport { AuthService } from \"./auth.service.js\";\nimport type { AuthSession } from \"./types.js\";\n\n@Controller(\"/api/auth\")\nexport class AuthController {\n\tconstructor(@Inject(AuthService.TOKEN) private readonly auth: AuthService) {}\n\n\t/**\n\t * GET /api/auth/session\n\t * Returns the current session (or null if unauthenticated).\n\t */\n\t@Get(\"/session\")\n\tasync session(@Req() c: Context) {\n\t\tconst session: AuthSession = await this.auth.getSession({\n\t\t\theaders: c.req.raw.headers,\n\t\t});\n\t\treturn c.json(session ?? { user: null, session: null });\n\t}\n\n\t/**\n\t * POST /api/auth/sign-up/email\n\t * Body: { email, password, name, callbackURL? }\n\t */\n\t@Post(\"/sign-up/email\")\n\tasync signUpEmail(@Req() c: Context, @Body() body: any) {\n\t\tconst result = await this.auth.signUp(body);\n\t\treturn c.json(result, 201);\n\t}\n\n\t/**\n\t * POST /api/auth/sign-in/email\n\t * Body: { email, password, callbackURL? }\n\t */\n\t@Post(\"/sign-in/email\")\n\tasync signInEmail(@Req() c: Context, @Body() body: any) {\n\t\tconst result = await this.auth.signIn(body);\n\t\treturn c.json(result);\n\t}\n\n\t/**\n\t * POST /api/auth/sign-out\n\t */\n\t@Post(\"/sign-out\")\n\tasync signOut(@Req() c: Context, @Res() _res: Response) {\n\t\tawait this.auth.signOut({ headers: c.req.raw.headers });\n\t\treturn c.json({ ok: true });\n\t}\n\n\t/**\n\t * GET /api/auth/sign-in/:provider\n\t * Returns a redirect to the social provider's auth page.\n\t */\n\t@Get(\"/sign-in/:provider\")\n\tasync socialSignIn(\n\t\t@Req() c: Context,\n\t\t@Body() _body: never,\n\t) {\n\t\tconst provider = c.req.param(\"provider\") ?? \"\";\n\t\tconst callbackURL = c.req.query(\"callbackURL\") ?? \"/\";\n\t\tconst result = await this.auth.getOAuthUrl({ provider, callbackURL });\n\t\treturn c.json(result);\n\t}\n\n\t/**\n\t * GET /api/auth/callback/:provider\n\t * Social provider redirect target. The better-auth handler does the\n\t * real work; this is a passthrough for `route:list` visibility.\n\t */\n\t@Get(\"/callback/:provider\")\n\tasync oauthCallback(@Req() c: Context) {\n\t\tconst result = await this.auth.handleOAuthCallback({\n\t\t\theaders: c.req.raw.headers,\n\t\t\tquery: c.req.query() as Record<string, string>,\n\t\t});\n\t\treturn c.json(result);\n\t}\n\n\t/**\n\t * POST /api/auth/jwt\n\t * Issues a JWT for the current user. Requires the JWT plugin.\n\t */\n\t@Post(\"/jwt\")\n\tasync issueJwt(@Req() c: Context) {\n\t\tconst session = await this.auth.getSession({\n\t\t\theaders: c.req.raw.headers,\n\t\t});\n\t\tif (!session) return c.json({ error: \"Unauthorized\" }, 401);\n\t\tconst token = await this.auth.issueJwt({ userId: session.user.id });\n\t\treturn c.json(token);\n\t}\n\n\t/**\n\t * POST /api/auth/passkey/register\n\t * Start passkey registration. Requires the passkey plugin.\n\t */\n\t@Post(\"/passkey/register\")\n\tasync passkeyRegister(@Req() c: Context) {\n\t\tconst result = await this.auth.registerPasskey({\n\t\t\theaders: c.req.raw.headers,\n\t\t});\n\t\treturn c.json(result);\n\t}\n\n\t/**\n\t * POST /api/auth/passkey/authenticate\n\t * Body: passkey assertion\n\t */\n\t@Post(\"/passkey/authenticate\")\n\tasync passkeyAuthenticate(@Req() c: Context, @Body() body: any) {\n\t\tconst result = await this.auth.authenticatePasskey({\n\t\t\theaders: c.req.raw.headers,\n\t\t\tbody,\n\t\t});\n\t\treturn c.json(result);\n\t}\n}",
|
|
8
|
+
"/**\n * `AuthModule` — drop-in module for adding auth to any NexusTS app.\n *\n * Usage:\n * // src/app/app.module.ts\n * @Module({\n * imports: [AuthModule.forRoot({ ... })],\n * })\n * export class AppModule {}\n *\n * The `forRoot` static factory builds a one-off `AuthModule` subclass\n * pre-configured with the user's `auth` config. The provider token\n * `'AUTH_CONFIG'` carries the config to the `AuthService` constructor.\n *\n * AuthService is registered under **both** its class token and\n * `AuthService.TOKEN` (a Symbol). The class token is what the\n * container scans; the Symbol is what `@Inject(AuthService.TOKEN)`\n * looks up. Both resolve to the same instance via `useExisting`.\n */\n\nimport \"reflect-metadata\";\nimport { Module } from \"@nexusts/core\";\nimport { AuthController } from \"./auth.controller.js\";\nimport { AuthService } from \"./auth.service.js\";\nimport type { AuthConfig } from \"./types.js\";\n\n@Module({\n\tcontrollers: [AuthController],\n\tproviders: [\n\t\tAuthService,\n\t\t{ provide: AuthService.TOKEN, useExisting: AuthService },\n\t],\n\texports: [AuthService, AuthService.TOKEN],\n})\nexport class AuthModule {\n\t/**\n\t * Build a configured `AuthModule` class with the given config.\n\t *\n\t * The returned class can be `imports`-ed by any other module and\n\t * will provide the `AuthService` (and a `AUTH_CONFIG` value\n\t * provider) to its container.\n\t */\n\tstatic forRoot(config: AuthConfig) {\n\t\t@Module({\n\t\t\tcontrollers: [AuthController],\n\t\t\tproviders: [\n\t\t\t\tAuthService,\n\t\t\t\t{ provide: AuthService.TOKEN, useExisting: AuthService },\n\t\t\t\t{ provide: \"AUTH_CONFIG\", useValue: config },\n\t\t\t],\n\t\t\texports: [AuthService, AuthService.TOKEN],\n\t\t})\n\t\tclass ConfiguredAuthModule {}\n\n\t\t// Tag the dynamic class so the user can see where it came from.\n\t\tObject.defineProperty(ConfiguredAuthModule, \"name\", {\n\t\t\tvalue: \"ConfiguredAuthModule\",\n\t\t});\n\n\t\treturn ConfiguredAuthModule;\n\t}\n}\n",
|
|
9
9
|
"/**\n * `authMiddleware` — populate `c.var.user` and `c.var.session` on\n * every request, optionally enforcing a \"must be logged in\" policy.\n *\n * This is a Hono middleware that wraps better-auth's `getSession`.\n * It runs after the better-auth handler has set its own cookies, so\n * subsequent reads are cheap (a single DB lookup).\n *\n * Three modes:\n * - optional → always allow; populate user/session if present\n * - required → 401 if no user\n * - scoped → require user only for paths matching a regex\n *\n * Usage:\n * import { authMiddleware } from 'nexusjs/auth';\n * app.use('*', authMiddleware(auth, { mode: 'optional' }));\n * app.use('/api/*', authMiddleware(auth, { mode: 'required' }));\n */\n\nimport type { Context, MiddlewareHandler, Next } from \"hono\";\nimport type { Auth } from \"better-auth\";\nimport type { AuthVariables } from \"./types.js\";\n\nexport type AuthMiddlewareMode = \"optional\" | \"required\" | \"scoped\";\n\nexport interface AuthMiddlewareOptions {\n\t/** Auth mode. Default: `'optional'`. */\n\tmode?: AuthMiddlewareMode;\n\t/** Path matcher (only used in `'scoped'` mode). */\n\tscope?: RegExp;\n\t/** Path matcher for `'scoped'` mode's protected set. */\n\tprotectedPaths?: RegExp | RegExp[];\n\t/** Path matcher for paths that should be skipped entirely. */\n\tignoredPaths?: RegExp | RegExp[];\n\t/** Customize the 401 response. */\n\tonUnauthenticated?: (c: Context) => Response | Promise<Response>;\n\t/** Customize the 403 response when a scope check fails. */\n\tonForbidden?: (c: Context) => Response | Promise<Response>;\n}\n\nexport function authMiddleware(\n\tauth: Auth,\n\toptions: AuthMiddlewareOptions = {},\n): MiddlewareHandler<{ Variables: AuthVariables }> {\n\tconst {\n\t\tmode = \"optional\",\n\t\tscope,\n\t\tprotectedPaths,\n\t\tignoredPaths,\n\t\tonUnauthenticated = defaultUnauthenticated,\n\t\tonForbidden = defaultForbidden,\n\t} = options;\n\n\tconst ignored = toMatcher(ignoredPaths);\n\tconst protected_ =\n\t\tmode === \"scoped\"\n\t\t\t? toMatcher(scope ?? protectedPaths ?? /^\\/.+/) // everything\n\t\t\t: null;\n\n\treturn async (c, next) => {\n\t\tconst path = c.req.path;\n\n\t\t// Skip ignored paths entirely (e.g. health checks).\n\t\tif (ignored?.test(path)) {\n\t\t\treturn next();\n\t\t}\n\n\t\t// Populate the session.\n\t\tconst session = await auth.api.getSession({\n\t\t\theaders: c.req.raw.headers,\n\t\t});\n\n\t\tif (session) {\n\t\t\tc.set(\"user\", session.user as never);\n\t\t\tc.set(\"session\", session.session as never);\n\t\t} else {\n\t\t\tc.set(\"user\", null);\n\t\t\tc.set(\"session\", null);\n\t\t}\n\n\t\t// Apply mode.\n\t\tif (mode === \"required\" || (protected_?.test(path) && session === null)) {\n\t\t\tif (session === null) return onUnauthenticated(c);\n\t\t}\n\n\t\t// Scope-based forbidden check (e.g. \"user must have a specific role\").\n\t\t// Skipped here — the route handler can call `requireRole(...)` itself.\n\n\t\treturn next();\n\t};\n}\n\nfunction toMatcher(input?: RegExp | RegExp[]): RegExp | null {\n\tif (!input) return null;\n\tif (Array.isArray(input)) {\n\t\treturn new RegExp(input.map((r) => `(?:${r.source})`).join(\"|\"));\n\t}\n\treturn input;\n}\n\nfunction defaultUnauthenticated(c: Context): Response {\n\treturn c.json(\n\t\t{ error: \"Unauthorized\", message: \"Authentication required.\" },\n\t\t401,\n\t);\n}\n\nfunction defaultForbidden(c: Context): Response {\n\treturn c.json(\n\t\t{ error: \"Forbidden\", message: \"Insufficient permissions.\" },\n\t\t403,\n\t);\n}\n\n/**\n * `authHandler` — mount better-auth's catch-all handler at a path.\n *\n * Use this instead of writing the `app.on(['POST', 'GET'], path, ...)`\n * boilerplate yourself.\n *\n * app.use('/api/auth/*', cors({ ... }));\n * app.all('/api/auth/*', authHandler(auth));\n */\nexport function authHandler(auth: Auth): MiddlewareHandler {\n\treturn async (c) => auth.handler(c.req.raw);\n}\n",
|
|
10
|
-
"/**\n * `@CurrentUser()` — controller parameter decorator that injects the\n * authenticated user (and optionally the session) into a handler.\n *\n * Usage:\n * @Get('/me')\n * me(@CurrentUser() user: AuthUser) {\n * return user;\n * }\n *\n * @Get('/profile')\n * profile(@CurrentUser({ session: true }) ctx: { user: AuthUser; session: AuthSessionRecord }) {\n * return ctx;\n * }\n *\n * @Get('/dashboard')\n * dashboard(@CurrentUser({ required: true }) user: AuthUser) {\n * // 401 is thrown before the handler if no user is present.\n * return this.dashboardService.forUser(user.id);\n * }\n */\n\nimport \"reflect-metadata\";\nimport { createParamDecorator } from \"@nexusts/core
|
|
10
|
+
"/**\n * `@CurrentUser()` — controller parameter decorator that injects the\n * authenticated user (and optionally the session) into a handler.\n *\n * Usage:\n * @Get('/me')\n * me(@CurrentUser() user: AuthUser) {\n * return user;\n * }\n *\n * @Get('/profile')\n * profile(@CurrentUser({ session: true }) ctx: { user: AuthUser; session: AuthSessionRecord }) {\n * return ctx;\n * }\n *\n * @Get('/dashboard')\n * dashboard(@CurrentUser({ required: true }) user: AuthUser) {\n * // 401 is thrown before the handler if no user is present.\n * return this.dashboardService.forUser(user.id);\n * }\n */\n\nimport \"reflect-metadata\";\nimport { createParamDecorator } from \"@nexusts/core\";\nimport { PARAM_TYPES } from \"@nexusts/core\";\nimport type { AuthUser, AuthSessionRecord } from \"../types.js\";\n\nexport interface CurrentUserOptions {\n\t/**\n\t * Include the session in the injected value. Default: `false`.\n\t * When true, the value is `{ user, session }` instead of just the user.\n\t */\n\tsession?: boolean;\n\t/**\n\t * Throw 401 if no user is present. Default: `false`.\n\t * When true, the framework returns a 401 response without invoking\n\t * the handler.\n\t */\n\trequired?: boolean;\n\t/**\n\t * Throw 403 if the user does not satisfy the predicate.\n\t */\n\tassert?: (user: AuthUser) => boolean | Promise<boolean>;\n}\n\n/**\n * Inject the authenticated user (or `{ user, session }` if `session: true`).\n */\nexport function CurrentUser(\n\toptions: CurrentUserOptions = {},\n): ParameterDecorator {\n\treturn createParamDecorator(PARAM_TYPES.USER, options as never);\n}\n\n/**\n * Convenience: throw 401 with a JSON body when no user is present.\n * Exposed for users who want to enforce auth inside the handler.\n */\nexport class UnauthenticatedError extends Error {\n\treadonly status = 401;\n\tconstructor(message = \"Authentication required.\") {\n\t\tsuper(message);\n\t\tthis.name = \"UnauthenticatedError\";\n\t}\n}\n\nexport class ForbiddenError extends Error {\n\treadonly status = 403;\n\tconstructor(message = \"Insufficient permissions.\") {\n\t\tsuper(message);\n\t\tthis.name = \"ForbiddenError\";\n\t}\n}\n\n// Re-export session record type for convenience.\nexport type { AuthSessionRecord as AuthSession };\n"
|
|
11
11
|
],
|
|
12
12
|
"mappings": ";;;;;;;;;;;;;;;;;;AA+BA;AAWO,SAAS,UAAU,CAAC,SAAqB,CAAC,GAAuB;AAAA,EACvE,MAAM,SAAS,OAAO,UAAU,QAAQ,IAAI;AAAA,EAC5C,MAAM,UAAU,OAAO,WAAW,QAAQ,IAAI;AAAA,EAE9C,IAAI,CAAC,QAAQ;AAAA,IACZ,MAAM,IAAI,MACT,kDACC,iEACF;AAAA,EACD;AAAA,EACA,IAAI,CAAC,SAAS;AAAA,IACb,MAAM,IAAI,MACT,wEACD;AAAA,EACD;AAAA,EAEA,MAAM,UAA0B,CAAC;AAAA,EAGjC,IAAI,OAAO,KAAK,SAAS;AAAA,IAIxB,QAAQ;AAAA,IACR,QAAQ,KACP,IAAI;AAAA,MACH,MAAM;AAAA,QACL,MAAM,OAAO,IAAI,YAAY;AAAA,MAC9B;AAAA,MACA,QAAQ,OAAO,IAAI,UAAU;AAAA,MAC7B,UAAU,OAAO,IAAI,YAAY;AAAA,MACjC,WAAW,OAAO,IAAI,aAAa,KAAK;AAAA,IACzC,CAAC,CACF;AAAA,EACD;AAAA,EAGA,IAAI,OAAO,SAAS,SAAS;AAAA,IAE5B,QAAQ;AAAA,IACR,QAAQ,KACP,QAAQ;AAAA,MACP,QAA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AACA;AAwBO,SAAS,WAAW,CAC1B,UAA8B,CAAC,GACV;AAAA,EACrB,OAAO,qBAAqB,YAAY,MAAM,OAAgB;AAAA;AAAA;AAOxD,MAAM,6BAA6B,MAAM;AAAA,EACtC,SAAS;AAAA,EAClB,WAAW,CAAC,UAAU,4BAA4B;AAAA,IACjD,MAAM,OAAO;AAAA,IACb,KAAK,OAAO;AAAA;AAEd;AAAA;AAEO,MAAM,uBAAuB,MAAM;AAAA,EAChC,SAAS;AAAA,EAClB,WAAW,CAAC,UAAU,6BAA6B;AAAA,IAClD,MAAM,OAAO;AAAA,IACb,KAAK,OAAO;AAAA;AAEd;",
|
|
13
|
-
"debugId": "
|
|
13
|
+
"debugId": "D67F72E911A0099D64756E2164756E21",
|
|
14
14
|
"names": []
|
|
15
15
|
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `authMiddleware` — populate `c.var.user` and `c.var.session` on
|
|
3
|
+
* every request, optionally enforcing a "must be logged in" policy.
|
|
4
|
+
*
|
|
5
|
+
* This is a Hono middleware that wraps better-auth's `getSession`.
|
|
6
|
+
* It runs after the better-auth handler has set its own cookies, so
|
|
7
|
+
* subsequent reads are cheap (a single DB lookup).
|
|
8
|
+
*
|
|
9
|
+
* Three modes:
|
|
10
|
+
* - optional → always allow; populate user/session if present
|
|
11
|
+
* - required → 401 if no user
|
|
12
|
+
* - scoped → require user only for paths matching a regex
|
|
13
|
+
*
|
|
14
|
+
* Usage:
|
|
15
|
+
* import { authMiddleware } from 'nexusjs/auth';
|
|
16
|
+
* app.use('*', authMiddleware(auth, { mode: 'optional' }));
|
|
17
|
+
* app.use('/api/*', authMiddleware(auth, { mode: 'required' }));
|
|
18
|
+
*/
|
|
19
|
+
import type { Context, MiddlewareHandler } from "hono";
|
|
20
|
+
import type { Auth } from "better-auth";
|
|
21
|
+
import type { AuthVariables } from "./types.js";
|
|
22
|
+
export type AuthMiddlewareMode = "optional" | "required" | "scoped";
|
|
23
|
+
export interface AuthMiddlewareOptions {
|
|
24
|
+
/** Auth mode. Default: `'optional'`. */
|
|
25
|
+
mode?: AuthMiddlewareMode;
|
|
26
|
+
/** Path matcher (only used in `'scoped'` mode). */
|
|
27
|
+
scope?: RegExp;
|
|
28
|
+
/** Path matcher for `'scoped'` mode's protected set. */
|
|
29
|
+
protectedPaths?: RegExp | RegExp[];
|
|
30
|
+
/** Path matcher for paths that should be skipped entirely. */
|
|
31
|
+
ignoredPaths?: RegExp | RegExp[];
|
|
32
|
+
/** Customize the 401 response. */
|
|
33
|
+
onUnauthenticated?: (c: Context) => Response | Promise<Response>;
|
|
34
|
+
/** Customize the 403 response when a scope check fails. */
|
|
35
|
+
onForbidden?: (c: Context) => Response | Promise<Response>;
|
|
36
|
+
}
|
|
37
|
+
export declare function authMiddleware(auth: Auth, options?: AuthMiddlewareOptions): MiddlewareHandler<{
|
|
38
|
+
Variables: AuthVariables;
|
|
39
|
+
}>;
|
|
40
|
+
/**
|
|
41
|
+
* `authHandler` — mount better-auth's catch-all handler at a path.
|
|
42
|
+
*
|
|
43
|
+
* Use this instead of writing the `app.on(['POST', 'GET'], path, ...)`
|
|
44
|
+
* boilerplate yourself.
|
|
45
|
+
*
|
|
46
|
+
* app.use('/api/auth/*', cors({ ... }));
|
|
47
|
+
* app.all('/api/auth/*', authHandler(auth));
|
|
48
|
+
*/
|
|
49
|
+
export declare function authHandler(auth: Auth): MiddlewareHandler;
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auth types — the contract between NexusTS and better-auth.
|
|
3
|
+
*
|
|
4
|
+
* Better-auth provides a comprehensive set of authentication primitives
|
|
5
|
+
* (email/password, OAuth, magic links, passkeys, JWT). We don't try to
|
|
6
|
+
* re-implement any of that — we adapt better-auth's surface to fit
|
|
7
|
+
* NexusTS's DI / decorator model.
|
|
8
|
+
*
|
|
9
|
+
* Most types are re-exported from `better-auth` so consumers can use
|
|
10
|
+
* them directly. The few we define here are NexusTS-specific helpers.
|
|
11
|
+
*/
|
|
12
|
+
import type { Auth } from "better-auth";
|
|
13
|
+
export type { Auth } from "better-auth";
|
|
14
|
+
/** Per-request session payload (user + session). */
|
|
15
|
+
export type AuthSession = {
|
|
16
|
+
user: AuthUser;
|
|
17
|
+
session: AuthSessionRecord;
|
|
18
|
+
} | null;
|
|
19
|
+
export type AuthUser = {
|
|
20
|
+
id: string;
|
|
21
|
+
email: string;
|
|
22
|
+
emailVerified: boolean;
|
|
23
|
+
name: string;
|
|
24
|
+
image?: string | null;
|
|
25
|
+
createdAt: Date;
|
|
26
|
+
updatedAt: Date;
|
|
27
|
+
[key: string]: unknown;
|
|
28
|
+
};
|
|
29
|
+
export type AuthSessionRecord = {
|
|
30
|
+
id: string;
|
|
31
|
+
userId: string;
|
|
32
|
+
token: string;
|
|
33
|
+
expiresAt: Date;
|
|
34
|
+
ipAddress?: string | null;
|
|
35
|
+
userAgent?: string | null;
|
|
36
|
+
createdAt: Date;
|
|
37
|
+
updatedAt: Date;
|
|
38
|
+
[key: string]: unknown;
|
|
39
|
+
};
|
|
40
|
+
/** Configuration knobs for the auth subsystem. */
|
|
41
|
+
export interface AuthConfig {
|
|
42
|
+
/**
|
|
43
|
+
* Better-auth handler mount path.
|
|
44
|
+
* Default: `'/api/auth/*'`.
|
|
45
|
+
*/
|
|
46
|
+
basePath?: string;
|
|
47
|
+
/** Enable email + password authentication. Default: true. */
|
|
48
|
+
emailAndPassword?: {
|
|
49
|
+
enabled?: boolean;
|
|
50
|
+
requireEmailVerification?: boolean;
|
|
51
|
+
minPasswordLength?: number;
|
|
52
|
+
maxPasswordLength?: number;
|
|
53
|
+
};
|
|
54
|
+
/** Social providers keyed by provider name (github, google, etc.). */
|
|
55
|
+
socialProviders?: Record<string, SocialProviderConfig>;
|
|
56
|
+
/** JWT plugin settings (token + JWKS endpoint). */
|
|
57
|
+
jwt?: JwtConfig;
|
|
58
|
+
/** Passkey (WebAuthn) plugin settings. */
|
|
59
|
+
passkey?: PasskeyConfig;
|
|
60
|
+
/** Session expiry in seconds. Default: 7 days. */
|
|
61
|
+
sessionExpiresInSeconds?: number;
|
|
62
|
+
/** Cookie domain. Useful for subdomains. */
|
|
63
|
+
cookieDomain?: string;
|
|
64
|
+
/** Cross-subdomain cookies (turn on for `*.example.com`). */
|
|
65
|
+
crossSubDomainCookies?: {
|
|
66
|
+
enabled: boolean;
|
|
67
|
+
domain?: string;
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* Cookie attribute strategy for cross-origin requests.
|
|
71
|
+
* - 'lax' → same-site only (default, safest)
|
|
72
|
+
* - 'none' → cross-site; requires `secure: true`
|
|
73
|
+
* - 'strict' → same-origin only
|
|
74
|
+
*/
|
|
75
|
+
cookieSameSite?: "lax" | "strict" | "none";
|
|
76
|
+
/** `Secure` flag on cookies. Default: true in production. */
|
|
77
|
+
cookieSecure?: boolean;
|
|
78
|
+
/** A custom `BETTER_AUTH_SECRET` (otherwise read from env). */
|
|
79
|
+
secret?: string;
|
|
80
|
+
/** Custom `BETTER_AUTH_URL` (otherwise read from env). */
|
|
81
|
+
baseUrl?: string;
|
|
82
|
+
}
|
|
83
|
+
export interface SocialProviderConfig {
|
|
84
|
+
clientId: string;
|
|
85
|
+
clientSecret: string;
|
|
86
|
+
scope?: string[];
|
|
87
|
+
redirectURI?: string;
|
|
88
|
+
}
|
|
89
|
+
export interface JwtConfig {
|
|
90
|
+
enabled: boolean;
|
|
91
|
+
/** Path for JWKS endpoint. Default: `/api/auth/jwks`. */
|
|
92
|
+
jwksPath?: string;
|
|
93
|
+
/** Issuer claim. Default: baseUrl. */
|
|
94
|
+
issuer?: string;
|
|
95
|
+
/** Audience claim. Default: baseUrl. */
|
|
96
|
+
audience?: string;
|
|
97
|
+
/** Token TTL in seconds. Default: 15 min. */
|
|
98
|
+
expiresIn?: number;
|
|
99
|
+
}
|
|
100
|
+
export interface PasskeyConfig {
|
|
101
|
+
enabled: boolean;
|
|
102
|
+
/** Relying Party name (displayed by the browser). */
|
|
103
|
+
rpName: string;
|
|
104
|
+
/** Relying Party ID (typically the domain). */
|
|
105
|
+
rpId: string;
|
|
106
|
+
/** Allowed origins (e.g. `https://example.com`). */
|
|
107
|
+
origin: string | string[];
|
|
108
|
+
}
|
|
109
|
+
/** Per-request authentication context attached to the Hono context. */
|
|
110
|
+
export interface AuthContext {
|
|
111
|
+
user: AuthUser | null;
|
|
112
|
+
session: AuthSessionRecord | null;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Type augmentation so the Hono context has `user` and `session` keys.
|
|
116
|
+
*
|
|
117
|
+
* Usage in user code:
|
|
118
|
+
* import type { AuthVariables } from 'nexusjs/auth';
|
|
119
|
+
* const app = new Hono<{ Variables: AuthVariables }>();
|
|
120
|
+
*/
|
|
121
|
+
export type AuthVariables = {
|
|
122
|
+
user: AuthUser | null;
|
|
123
|
+
session: AuthSessionRecord | null;
|
|
124
|
+
};
|
|
125
|
+
/**
|
|
126
|
+
* A loose type that matches what `betterAuth.handler` returns for
|
|
127
|
+
* `getSession()`. Re-exported so users don't need to import from
|
|
128
|
+
* `better-auth` directly when extending the auth instance.
|
|
129
|
+
*/
|
|
130
|
+
export type SecondaryStorage = NonNullable<Auth extends {
|
|
131
|
+
options: {
|
|
132
|
+
secondaryStorage?: infer S;
|
|
133
|
+
};
|
|
134
|
+
} ? S : never>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nexusts/auth",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"description": "Authentication via better-auth integration",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -12,28 +12,15 @@
|
|
|
12
12
|
"import": "./dist/index.js"
|
|
13
13
|
}
|
|
14
14
|
},
|
|
15
|
-
"files": [
|
|
16
|
-
"dist",
|
|
17
|
-
"README.md"
|
|
18
|
-
],
|
|
15
|
+
"files": ["dist", "README.md"],
|
|
19
16
|
"scripts": {
|
|
20
17
|
"build": "bun run ../../build.ts"
|
|
21
18
|
},
|
|
22
|
-
"keywords": [
|
|
23
|
-
"nexusts",
|
|
24
|
-
"framework",
|
|
25
|
-
"bun"
|
|
26
|
-
],
|
|
19
|
+
"keywords": ["nexusts", "framework", "bun"],
|
|
27
20
|
"license": "MIT",
|
|
28
|
-
"peerDependencies": {
|
|
29
|
-
|
|
30
|
-
},
|
|
31
|
-
"peerDependenciesMeta": {
|
|
32
|
-
"better-auth": {
|
|
33
|
-
"optional": true
|
|
34
|
-
}
|
|
35
|
-
},
|
|
21
|
+
"peerDependencies": { "better-auth": "^1.6.0" },
|
|
22
|
+
"peerDependenciesMeta": { "better-auth": { "optional": true } },
|
|
36
23
|
"dependencies": {
|
|
37
|
-
"@nexusts/core": "
|
|
24
|
+
"@nexusts/core": "file:../core"
|
|
38
25
|
}
|
|
39
26
|
}
|