@moriajs/auth 0.1.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/.turbo/turbo-build.log +4 -0
- package/.turbo/turbo-typecheck.log +4 -0
- package/LICENSE +21 -0
- package/dist/index.d.ts +84 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +78 -0
- package/dist/index.js.map +1 -0
- package/package.json +47 -0
- package/src/index.ts +138 -0
- package/tsconfig.json +10 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Guntur D
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @moriajs/auth
|
|
3
|
+
*
|
|
4
|
+
* Pluggable authentication system for MoriaJS.
|
|
5
|
+
* Default: JWT + httpOnly cookies.
|
|
6
|
+
* Architecture: Provider-based for future OAuth, sessions, etc.
|
|
7
|
+
*/
|
|
8
|
+
import type { FastifyRequest, FastifyReply } from 'fastify';
|
|
9
|
+
/**
|
|
10
|
+
* User payload stored in JWT token.
|
|
11
|
+
* Extend this via TypeScript module augmentation in your app.
|
|
12
|
+
*/
|
|
13
|
+
export interface AuthUser {
|
|
14
|
+
id: string | number;
|
|
15
|
+
email?: string;
|
|
16
|
+
role?: string;
|
|
17
|
+
[key: string]: unknown;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Configuration for the auth plugin.
|
|
21
|
+
*/
|
|
22
|
+
export interface AuthConfig {
|
|
23
|
+
/** JWT secret key (required) */
|
|
24
|
+
secret: string;
|
|
25
|
+
/** Token expiration (default: '7d') */
|
|
26
|
+
expiresIn?: string;
|
|
27
|
+
/** Cookie name for JWT storage (default: 'moria_token') */
|
|
28
|
+
cookieName?: string;
|
|
29
|
+
/** Use secure cookies (default: true in production) */
|
|
30
|
+
secureCookies?: boolean;
|
|
31
|
+
/** Cookie path (default: '/') */
|
|
32
|
+
cookiePath?: string;
|
|
33
|
+
/** SameSite cookie attribute (default: 'lax') */
|
|
34
|
+
sameSite?: 'strict' | 'lax' | 'none';
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Auth provider interface for pluggable authentication strategies.
|
|
38
|
+
*/
|
|
39
|
+
export interface AuthProvider {
|
|
40
|
+
/** Provider name (e.g., 'jwt', 'session', 'oauth-google') */
|
|
41
|
+
name: string;
|
|
42
|
+
/** Verify a request and return the authenticated user, or null */
|
|
43
|
+
verify: (request: FastifyRequest) => Promise<AuthUser | null>;
|
|
44
|
+
/** Create a token/session for a user */
|
|
45
|
+
sign: (user: AuthUser, reply: FastifyReply) => Promise<string>;
|
|
46
|
+
/** Invalidate a token/session */
|
|
47
|
+
revoke?: (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Create the JWT auth plugin for MoriaJS.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* ```ts
|
|
54
|
+
* import { createApp } from '@moriajs/core';
|
|
55
|
+
* import { createAuthPlugin } from '@moriajs/auth';
|
|
56
|
+
*
|
|
57
|
+
* const app = await createApp();
|
|
58
|
+
* await app.use(createAuthPlugin({
|
|
59
|
+
* secret: process.env.JWT_SECRET!,
|
|
60
|
+
* expiresIn: '24h',
|
|
61
|
+
* }));
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
export declare function createAuthPlugin(config: AuthConfig): {
|
|
65
|
+
name: string;
|
|
66
|
+
register({ server }: {
|
|
67
|
+
server: any;
|
|
68
|
+
}): Promise<void>;
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* Route-level authentication guard.
|
|
72
|
+
* Use as a Fastify preHandler hook.
|
|
73
|
+
*
|
|
74
|
+
* @example
|
|
75
|
+
* ```ts
|
|
76
|
+
* server.get('/protected', { preHandler: [requireAuth()] }, async (req) => {
|
|
77
|
+
* return { user: req.user };
|
|
78
|
+
* });
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
81
|
+
export declare function requireAuth(options?: {
|
|
82
|
+
role?: string;
|
|
83
|
+
}): (request: FastifyRequest, reply: FastifyReply) => Promise<undefined>;
|
|
84
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAmB,cAAc,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE7E;;;GAGG;AACH,MAAM,WAAW,QAAQ;IACrB,EAAE,EAA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|
package/dist/index.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @moriajs/auth
|
|
3
|
+
*
|
|
4
|
+
* Pluggable authentication system for MoriaJS.
|
|
5
|
+
* Default: JWT + httpOnly cookies.
|
|
6
|
+
* Architecture: Provider-based for future OAuth, sessions, etc.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Create the JWT auth plugin for MoriaJS.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* import { createApp } from '@moriajs/core';
|
|
14
|
+
* import { createAuthPlugin } from '@moriajs/auth';
|
|
15
|
+
*
|
|
16
|
+
* const app = await createApp();
|
|
17
|
+
* await app.use(createAuthPlugin({
|
|
18
|
+
* secret: process.env.JWT_SECRET!,
|
|
19
|
+
* expiresIn: '24h',
|
|
20
|
+
* }));
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
export function createAuthPlugin(config) {
|
|
24
|
+
return {
|
|
25
|
+
name: '@moriajs/auth',
|
|
26
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
27
|
+
async register({ server }) {
|
|
28
|
+
const jwt = await import('@fastify/jwt');
|
|
29
|
+
await server.register(jwt.default, {
|
|
30
|
+
secret: config.secret,
|
|
31
|
+
cookie: {
|
|
32
|
+
cookieName: config.cookieName ?? 'moria_token',
|
|
33
|
+
signed: false,
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
// Auth utility: sign JWT and set cookie
|
|
37
|
+
server.decorate('signIn', async (user, reply) => {
|
|
38
|
+
const token = server.jwt.sign({ ...user }, { expiresIn: config.expiresIn ?? '7d' });
|
|
39
|
+
reply.header('Set-Cookie', `${config.cookieName ?? 'moria_token'}=${token}; HttpOnly; Path=${config.cookiePath ?? '/'}; SameSite=${config.sameSite ?? 'Lax'}${(config.secureCookies ?? process.env.NODE_ENV === 'production') ? '; Secure' : ''}`);
|
|
40
|
+
return token;
|
|
41
|
+
});
|
|
42
|
+
// Auth utility: sign out (clear cookie)
|
|
43
|
+
server.decorate('signOut', async (_request, reply) => {
|
|
44
|
+
reply.header('Set-Cookie', `${config.cookieName ?? 'moria_token'}=; HttpOnly; Path=${config.cookiePath ?? '/'}; Max-Age=0`);
|
|
45
|
+
});
|
|
46
|
+
server.log.info('@moriajs/auth: JWT auth plugin registered');
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Route-level authentication guard.
|
|
52
|
+
* Use as a Fastify preHandler hook.
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* ```ts
|
|
56
|
+
* server.get('/protected', { preHandler: [requireAuth()] }, async (req) => {
|
|
57
|
+
* return { user: req.user };
|
|
58
|
+
* });
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
export function requireAuth(options) {
|
|
62
|
+
return async (request, reply) => {
|
|
63
|
+
try {
|
|
64
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
65
|
+
await request.jwtVerify();
|
|
66
|
+
if (options?.role) {
|
|
67
|
+
const user = request.user;
|
|
68
|
+
if (user.role !== options.role) {
|
|
69
|
+
return reply.status(403).send({ error: 'Forbidden' });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return reply.status(401).send({ error: 'Unauthorized' });
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AA+CH;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,gBAAgB,CAAC,MAAkB;IAC/C,OAAO;QACH,IAAI,EAAE,eAAe;QACrB,8DAA8D;QAC9D,KAAK,CAAC,QAAQ,CAAC,EAAE,MAAM,EA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,CAAC;QACtF,CAAC;KACJ,CAAC;AACN,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,WAAW,CAAC,OAA2B;IACnD,OAAO,KAAK,EAAE,OAAuB,EAAE,KAAmB,EAAE,EAAE;QAC1D,IAAI,CAAC;YACD,8DAA8D;YAC9D,MAAO,OAAe,CAAC,SAAS,EAAE,CAAC;YAEnC,IAAI,OAAO,EAAE,IAAI,EAAE,CAAC;gBAChB,MAAM,IAAI,GAAG,OAAO,CAAC,IAAgB,CAAC;gBACtC,IAAI,IAAI,CAAC,IAAI,KAAK,OAAO,CAAC,IAAI,EAAE,CAAC;oBAC7B,OAAO,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC,CAAC;gBAC1D,CAAC;YACL,CAAC;QACL,CAAC;QAAC,MAAM,CAAC;YACL,OAAO,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,cAAc,EAAE,CAAC,CAAC;QAC7D,CAAC;IACL,CAAC,CAAC;AACN,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@moriajs/auth",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "MoriaJS auth — JWT + httpOnly cookies, pluggable auth system",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@fastify/jwt": "^10.0.0",
|
|
16
|
+
"@fastify/cookie": "^11.0.0"
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"typescript": "^5.7.0",
|
|
20
|
+
"rimraf": "^6.0.0",
|
|
21
|
+
"@types/node": "^22.0.0",
|
|
22
|
+
"fastify": "^5.2.0"
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"@moriajs/core": "0.1.1"
|
|
26
|
+
},
|
|
27
|
+
"license": "MIT",
|
|
28
|
+
"author": "Guntur-D <guntur.d.npm@gmail.com>",
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/guntur-d/moriajs.git",
|
|
32
|
+
"directory": "packages/auth"
|
|
33
|
+
},
|
|
34
|
+
"homepage": "https://github.com/guntur-d/moriajs/tree/main/packages/auth#readme",
|
|
35
|
+
"bugs": {
|
|
36
|
+
"url": "https://github.com/guntur-d/moriajs/issues"
|
|
37
|
+
},
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"build": "tsc",
|
|
43
|
+
"dev": "tsc --watch",
|
|
44
|
+
"typecheck": "tsc --noEmit",
|
|
45
|
+
"clean": "rimraf dist .turbo"
|
|
46
|
+
}
|
|
47
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @moriajs/auth
|
|
3
|
+
*
|
|
4
|
+
* Pluggable authentication system for MoriaJS.
|
|
5
|
+
* Default: JWT + httpOnly cookies.
|
|
6
|
+
* Architecture: Provider-based for future OAuth, sessions, etc.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* User payload stored in JWT token.
|
|
13
|
+
* Extend this via TypeScript module augmentation in your app.
|
|
14
|
+
*/
|
|
15
|
+
export interface AuthUser {
|
|
16
|
+
id: string | number;
|
|
17
|
+
email?: string;
|
|
18
|
+
role?: string;
|
|
19
|
+
[key: string]: unknown;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Configuration for the auth plugin.
|
|
24
|
+
*/
|
|
25
|
+
export interface AuthConfig {
|
|
26
|
+
/** JWT secret key (required) */
|
|
27
|
+
secret: string;
|
|
28
|
+
/** Token expiration (default: '7d') */
|
|
29
|
+
expiresIn?: string;
|
|
30
|
+
/** Cookie name for JWT storage (default: 'moria_token') */
|
|
31
|
+
cookieName?: string;
|
|
32
|
+
/** Use secure cookies (default: true in production) */
|
|
33
|
+
secureCookies?: boolean;
|
|
34
|
+
/** Cookie path (default: '/') */
|
|
35
|
+
cookiePath?: string;
|
|
36
|
+
/** SameSite cookie attribute (default: 'lax') */
|
|
37
|
+
sameSite?: 'strict' | 'lax' | 'none';
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Auth provider interface for pluggable authentication strategies.
|
|
42
|
+
*/
|
|
43
|
+
export interface AuthProvider {
|
|
44
|
+
/** Provider name (e.g., 'jwt', 'session', 'oauth-google') */
|
|
45
|
+
name: string;
|
|
46
|
+
/** Verify a request and return the authenticated user, or null */
|
|
47
|
+
verify: (request: FastifyRequest) => Promise<AuthUser | null>;
|
|
48
|
+
/** Create a token/session for a user */
|
|
49
|
+
sign: (user: AuthUser, reply: FastifyReply) => Promise<string>;
|
|
50
|
+
/** Invalidate a token/session */
|
|
51
|
+
revoke?: (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Create the JWT auth plugin for MoriaJS.
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* ```ts
|
|
59
|
+
* import { createApp } from '@moriajs/core';
|
|
60
|
+
* import { createAuthPlugin } from '@moriajs/auth';
|
|
61
|
+
*
|
|
62
|
+
* const app = await createApp();
|
|
63
|
+
* await app.use(createAuthPlugin({
|
|
64
|
+
* secret: process.env.JWT_SECRET!,
|
|
65
|
+
* expiresIn: '24h',
|
|
66
|
+
* }));
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
export function createAuthPlugin(config: AuthConfig) {
|
|
70
|
+
return {
|
|
71
|
+
name: '@moriajs/auth',
|
|
72
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
73
|
+
async register({ server }: { server: any }) {
|
|
74
|
+
const jwt = await import('@fastify/jwt');
|
|
75
|
+
|
|
76
|
+
await (server as FastifyInstance).register(jwt.default, {
|
|
77
|
+
secret: config.secret,
|
|
78
|
+
cookie: {
|
|
79
|
+
cookieName: config.cookieName ?? 'moria_token',
|
|
80
|
+
signed: false,
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
// Auth utility: sign JWT and set cookie
|
|
85
|
+
server.decorate('signIn', async (user: AuthUser, reply: FastifyReply) => {
|
|
86
|
+
const token = server.jwt.sign(
|
|
87
|
+
{ ...user },
|
|
88
|
+
{ expiresIn: config.expiresIn ?? '7d' }
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
reply.header('Set-Cookie',
|
|
92
|
+
`${config.cookieName ?? 'moria_token'}=${token}; HttpOnly; Path=${config.cookiePath ?? '/'}; SameSite=${config.sameSite ?? 'Lax'}${(config.secureCookies ?? process.env.NODE_ENV === 'production') ? '; Secure' : ''
|
|
93
|
+
}`
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
return token;
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// Auth utility: sign out (clear cookie)
|
|
100
|
+
server.decorate('signOut', async (_request: FastifyRequest, reply: FastifyReply) => {
|
|
101
|
+
reply.header('Set-Cookie',
|
|
102
|
+
`${config.cookieName ?? 'moria_token'}=; HttpOnly; Path=${config.cookiePath ?? '/'}; Max-Age=0`
|
|
103
|
+
);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
(server as FastifyInstance).log.info('@moriajs/auth: JWT auth plugin registered');
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Route-level authentication guard.
|
|
113
|
+
* Use as a Fastify preHandler hook.
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* ```ts
|
|
117
|
+
* server.get('/protected', { preHandler: [requireAuth()] }, async (req) => {
|
|
118
|
+
* return { user: req.user };
|
|
119
|
+
* });
|
|
120
|
+
* ```
|
|
121
|
+
*/
|
|
122
|
+
export function requireAuth(options?: { role?: string }) {
|
|
123
|
+
return async (request: FastifyRequest, reply: FastifyReply) => {
|
|
124
|
+
try {
|
|
125
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
126
|
+
await (request as any).jwtVerify();
|
|
127
|
+
|
|
128
|
+
if (options?.role) {
|
|
129
|
+
const user = request.user as AuthUser;
|
|
130
|
+
if (user.role !== options.role) {
|
|
131
|
+
return reply.status(403).send({ error: 'Forbidden' });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
} catch {
|
|
135
|
+
return reply.status(401).send({ error: 'Unauthorized' });
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
}
|