@antelopejs/interface-auth 0.0.2

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/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright (c) 2025-present - AntelopeJS Team
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,41 @@
1
+ ![Auth](.github/social-card.png)
2
+
3
+ # Interface Auth
4
+
5
+ <div align="center">
6
+ <a href="./LICENSE"><img alt="License" src="https://img.shields.io/badge/License-Apache_2.0-blue.svg?style=for-the-badge&labelColor=000000"></a>
7
+ <a href="https://discord.gg/sjK28QHrA7"><img src="https://img.shields.io/badge/Discord-18181B?logo=discord&style=for-the-badge&color=000000" alt="Discord"></a>
8
+ <a href="./docs/1.introduction.md"><img src="https://img.shields.io/badge/Docs-18181B?style=for-the-badge&color=000000" alt="Documentation"></a>
9
+ </div>
10
+
11
+ A flexible, decorator-based framework for implementing authentication and authorization in TypeScript. Interface Auth simplifies securing API endpoints, validating user credentials, and managing user sessions with a clean, declarative syntax.
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ ajs module imports add auth@beta
17
+ ```
18
+
19
+ ## Documentation
20
+
21
+ Detailed documentation is available in the `docs` directory:
22
+
23
+ - [Introduction](./docs/1.introduction.md) - Overview and basic concepts
24
+ - [Authentication Basics](./docs/2.authentication.md) - Core authentication concepts and usage
25
+ - [Token Handling](./docs/3.token-handling.md) - Token generation and validation
26
+ - [Parameter Decoration](./docs/4.parameter-decoration.md) - Authentication decorators and parameter validation
27
+
28
+ ## Current Status
29
+
30
+ This is the development version (`beta`) of the Interface Auth. It is currently in pre-release stage and may undergo changes before the final release. The interface is not considered stable for production use without understanding that breaking changes may occur.
31
+
32
+ ## Versions
33
+
34
+ | Version | Link | Status |
35
+ | ------- | ---------------------------------------------------------------------------------------- | --------------------------------------------- |
36
+ | beta | [auth@beta](https://github.com/AntelopeJS/auth-jwt/tree/main/.antelope/output/auth/beta) | Waiting validation from community to go in v1 |
37
+ | 1 | _Not yet released_ | Planned stable release |
38
+
39
+ ## License
40
+
41
+ This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,2 @@
1
+ declare const _default: import("@antelopejs/interface-core/config").ConfigInput;
2
+ export default _default;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const config_1 = require("@antelopejs/interface-core/config");
4
+ const mongodb_memory_server_core_1 = require("mongodb-memory-server-core");
5
+ let mongod;
6
+ exports.default = (0, config_1.defineConfig)({
7
+ name: "interface-auth-test",
8
+ cacheFolder: ".antelope/cache",
9
+ modules: {
10
+ "auth-jwt": {
11
+ source: {
12
+ type: "local",
13
+ path: "../auth-jwt",
14
+ installCommand: ["pnpm install", "npx tsc"],
15
+ },
16
+ config: { secret: "test-secret-key-for-jwt" },
17
+ },
18
+ mongodb: {
19
+ source: {
20
+ type: "local",
21
+ path: "../mongodb",
22
+ installCommand: ["pnpm install", "npx tsc"],
23
+ },
24
+ },
25
+ database_decorators: {
26
+ source: {
27
+ type: "local",
28
+ path: "../database-decorators",
29
+ installCommand: ["pnpm install", "npx tsc"],
30
+ },
31
+ },
32
+ api: {
33
+ source: {
34
+ type: "local",
35
+ path: "../api",
36
+ installCommand: ["pnpm install", "npx tsc"],
37
+ },
38
+ config: {
39
+ servers: [{ protocol: "http", host: "127.0.0.1", port: 5010 }],
40
+ },
41
+ },
42
+ },
43
+ test: {
44
+ folder: "dist/tests",
45
+ async setup() {
46
+ mongod = await mongodb_memory_server_core_1.MongoMemoryServer.create();
47
+ return {
48
+ modules: {
49
+ mongodb: {
50
+ config: { url: mongod.getUri() },
51
+ },
52
+ },
53
+ };
54
+ },
55
+ async cleanup() {
56
+ await mongod.stop();
57
+ },
58
+ },
59
+ });
60
+ //# sourceMappingURL=antelope.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"antelope.test.js","sourceRoot":"","sources":["../src/antelope.test.ts"],"names":[],"mappings":";;AAAA,8DAAiE;AACjE,2EAA+D;AAE/D,IAAI,MAAyB,CAAC;AAE9B,kBAAe,IAAA,qBAAY,EAAC;IAC1B,IAAI,EAAE,qBAAqB;IAC3B,WAAW,EAAE,iBAAiB;IAC9B,OAAO,EAAE;QACP,UAAU,EAAE;YACV,MAAM,EAAE;gBACN,IAAI,EAAE,OAAO;gBACb,IAAI,EAAE,aAAa;gBACnB,cAAc,EAAE,CAAC,cAAc,EAAE,SAAS,CAAC;aAC5C;YACD,MAAM,EAAE,EAAE,MAAM,EAAE,yBAAyB,EAAE;SAC9C;QACD,OAAO,EAAE;YACP,MAAM,EAAE;gBACN,IAAI,EAAE,OAAO;gBACb,IAAI,EAAE,YAAY;gBAClB,cAAc,EAAE,CAAC,cAAc,EAAE,SAAS,CAAC;aAC5C;SACF;QACD,mBAAmB,EAAE;YACnB,MAAM,EAAE;gBACN,IAAI,EAAE,OAAO;gBACb,IAAI,EAAE,wBAAwB;gBAC9B,cAAc,EAAE,CAAC,cAAc,EAAE,SAAS,CAAC;aAC5C;SACF;QACD,GAAG,EAAE;YACH,MAAM,EAAE;gBACN,IAAI,EAAE,OAAO;gBACb,IAAI,EAAE,QAAQ;gBACd,cAAc,EAAE,CAAC,cAAc,EAAE,SAAS,CAAC;aAC5C;YACD,MAAM,EAAE;gBACN,OAAO,EAAE,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;aAC/D;SACF;KACF;IACD,IAAI,EAAE;QACJ,MAAM,EAAE,YAAY;QACpB,KAAK,CAAC,KAAK;YACT,MAAM,GAAG,MAAM,8CAAiB,CAAC,MAAM,EAAE,CAAC;YAC1C,OAAO;gBACL,OAAO,EAAE;oBACP,OAAO,EAAE;wBACP,MAAM,EAAE,EAAE,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,EAAE;qBACjC;iBACF;aACF,CAAC;QACJ,CAAC;QACD,KAAK,CAAC,OAAO;YACX,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;QACtB,CAAC;KACF;CACF,CAAC,CAAC"}
@@ -0,0 +1,275 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ /**
3
+ * Function type that extracts authentication data from HTTP request.
4
+ *
5
+ * @param req - The incoming HTTP request
6
+ * @param res - The server response object
7
+ * @returns The authentication token string or undefined if not found
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * const headerSource: AuthSource = (req) => req.headers['authorization']?.replace('Bearer ', '');
12
+ * ```
13
+ */
14
+ export type AuthSource = (req: IncomingMessage, res: ServerResponse) => string | undefined;
15
+ /**
16
+ * Function type that verifies authentication data and returns parsed content.
17
+ *
18
+ * @template T - The type of the verified data
19
+ * @param data - The authentication data to verify
20
+ * @param options - Optional verification parameters
21
+ * @returns The verified data or a Promise resolving to the verified data
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * const jwtVerifier: AuthVerifier<UserProfile> = (token) =>
26
+ * jwt.verify(token, SECRET_KEY) as UserProfile;
27
+ * ```
28
+ */
29
+ export type AuthVerifier<T = unknown> = (data?: string, options?: VerifyOptions) => Promise<T> | T;
30
+ /**
31
+ * Function type that performs additional validation on verified authentication data.
32
+ *
33
+ * @template T - The type of input data to validate
34
+ * @template R - The type of the validation result
35
+ * @param data - The verified data to validate
36
+ * @returns The validation result or a Promise resolving to the validation result
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * const roleValidator: AuthValidator<UserProfile, boolean> = (profile) =>
41
+ * profile.roles.includes('admin');
42
+ * ```
43
+ */
44
+ export type AuthValidator<T = unknown, R = unknown> = (data: T) => Promise<R> | R;
45
+ /**
46
+ * HTTP Cookie options for controlling how authentication cookies are set.
47
+ *
48
+ * @property maxAge - Number of milliseconds until the cookie expires
49
+ * @property signed - Whether the cookie should be signed
50
+ * @property expires - Specific date when the cookie expires
51
+ * @property httpOnly - Whether the cookie is only accessible via HTTP(S) and not client JavaScript
52
+ * @property path - URL path for which the cookie is valid
53
+ * @property domain - Domain for which the cookie is valid
54
+ * @property secure - Whether the cookie should only be sent over HTTPS
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * const secureOptions: CookieOptions = {
59
+ * httpOnly: true,
60
+ * secure: true,
61
+ * maxAge: 3600000, // 1 hour
62
+ * path: '/'
63
+ * };
64
+ * ```
65
+ */
66
+ export interface CookieOptions {
67
+ maxAge?: number;
68
+ signed?: boolean;
69
+ expires?: Date;
70
+ httpOnly?: boolean;
71
+ path?: string;
72
+ domain?: string;
73
+ secure?: boolean;
74
+ }
75
+ /**
76
+ * Options for signing authentication tokens.
77
+ *
78
+ * @property expiresIn - Duration until the token expires, as seconds or timespan string (e.g. '1h', '2d')
79
+ * @property notBefore - Duration before which the token is not valid, as seconds or timespan string
80
+ *
81
+ * @example
82
+ * ```typescript
83
+ * const tokenOptions: SignOptions = {
84
+ * expiresIn: '2h', // Token valid for 2 hours
85
+ * notBefore: '5s' // Token not valid until 5 seconds after issuance
86
+ * };
87
+ * ```
88
+ */
89
+ export interface SignOptions {
90
+ /**
91
+ * Expiration as a number of seconds or a timespan string.
92
+ */
93
+ expiresIn?: string | number;
94
+ /**
95
+ * Not-before field as a number of seconds or a timespan string.
96
+ */
97
+ notBefore?: string | number;
98
+ }
99
+ /**
100
+ * Options for verifying authentication tokens.
101
+ *
102
+ * @property ignoreExpiration - If true, expired tokens will still be considered valid
103
+ * @property ignoreNotBefore - If true, tokens that are not yet valid will still be considered valid
104
+ * @property maxAge - Maximum age of the token, as seconds or timespan string
105
+ *
106
+ * @example
107
+ * ```typescript
108
+ * const verifyOptions: VerifyOptions = {
109
+ * ignoreExpiration: false,
110
+ * maxAge: '30m' // Reject tokens older than 30 minutes
111
+ * };
112
+ * ```
113
+ */
114
+ export interface VerifyOptions {
115
+ /**
116
+ * Ignore signature expiration.
117
+ */
118
+ ignoreExpiration?: boolean;
119
+ /**
120
+ * Ignore signature not-before field.
121
+ */
122
+ ignoreNotBefore?: boolean;
123
+ /**
124
+ * Maximum signature age as a number of seconds or a timespan string.
125
+ */
126
+ maxAge?: string | number;
127
+ }
128
+ type AuthPayload = string | Buffer | object;
129
+ interface AuthDecoratorCallbacks<T, R> {
130
+ source?: AuthSource;
131
+ authenticator?: AuthVerifier<T>;
132
+ authenticatorOptions?: VerifyOptions;
133
+ validator?: AuthValidator<T, R>;
134
+ }
135
+ /**
136
+ * @internal
137
+ */
138
+ export declare namespace internal {
139
+ const Verify: (data?: string | undefined, options?: VerifyOptions | undefined) => Promise<unknown>;
140
+ const Sign: (data: AuthPayload, options?: SignOptions | undefined) => Promise<string>;
141
+ function defaultSource(req: IncomingMessage, _res: ServerResponse): string | undefined;
142
+ const defaultAuthenticator: AuthVerifier<unknown>;
143
+ /**
144
+ * Verifies the signature of signed data attached to the HTTP request and returns the data contained therein.
145
+ *
146
+ * @template T - The type of data after verification
147
+ * @template R - The type of data after validation
148
+ * @param req - HTTP Request
149
+ * @param res - HTTP Response
150
+ * @param source - Callback to retrieve the signed data from the request
151
+ * @param authenticator - Callback to verify the signature
152
+ * @param authenticatorOptions - Verifier options
153
+ * @param validator - Custom validator callback
154
+ * @returns The authenticated and validated data
155
+ */
156
+ function CheckAuthentication<T = unknown, R = unknown>(req: IncomingMessage, res: ServerResponse, source?: AuthSource, authenticator?: AuthVerifier<T>, authenticatorOptions?: VerifyOptions, validator?: AuthValidator<T, R>): Promise<T | R>;
157
+ }
158
+ /**
159
+ * Verifies the signature of some signed data and returns the data contained therein.
160
+ *
161
+ * @template T - The type of data expected after verification
162
+ * @param token - The signed data token to verify
163
+ * @param options - Options for verification
164
+ * @returns A promise resolving to the verified data
165
+ *
166
+ * @example
167
+ * ```typescript
168
+ * const userData = await ValidateRaw<UserProfile>(authToken, { maxAge: '1h' });
169
+ * console.log(userData.name);
170
+ * ```
171
+ */
172
+ export declare function ValidateRaw<T = unknown>(token?: string, options?: VerifyOptions): Promise<T>;
173
+ /**
174
+ * Signs some data to create an authentication token.
175
+ *
176
+ * @param data - The data to sign
177
+ * @param options - Options for signing
178
+ * @returns The signed data token
179
+ *
180
+ * @example
181
+ * ```typescript
182
+ * const token = SignRaw({ userId: 123, role: 'admin' }, { expiresIn: '24h' });
183
+ * ```
184
+ */
185
+ export declare function SignRaw(data: AuthPayload, options?: SignOptions): Promise<string>;
186
+ /**
187
+ * Signs some data and attaches it to an HTTP Response object as a cookie.
188
+ *
189
+ * @param res - HTTP Response object to set the cookie on
190
+ * @param data - Data to sign and attach
191
+ * @param signOptions - Options for signing the data
192
+ * @param cookieOptions - Options for the cookie
193
+ * @returns A promise that resolves when the cookie has been set
194
+ *
195
+ * @example
196
+ * ```typescript
197
+ * await SignServerResponse(
198
+ * res,
199
+ * { userId: 123, permissions: ['read', 'write'] },
200
+ * { expiresIn: '8h' },
201
+ * { httpOnly: true, secure: true }
202
+ * );
203
+ * ```
204
+ */
205
+ export declare function SignServerResponse(res: ServerResponse, data: AuthPayload, signOptions?: SignOptions, cookieOptions?: CookieOptions): Promise<ServerResponse>;
206
+ /**
207
+ * Creates a Parameter Provider using the specified source and signature verification callbacks.
208
+ *
209
+ * The callbacks are processed in the following order:
210
+ * `source(req, res)` => `authenticator(prev, authenticatorOptions)` => `validator(prev)` => Parameter
211
+ *
212
+ * @template R - The type of the final validator result
213
+ * @template T - The type of the authenticated data before validation
214
+ * @param callbacks - Configuration object containing callback functions
215
+ * @param callbacks.source - Extracts the signed data from the request
216
+ * @param callbacks.authenticator - Verifies the signature
217
+ * @param callbacks.authenticatorOptions - Options for verification
218
+ * @param callbacks.validator - Custom validation step (overrideable with decorator call)
219
+ * @returns A decorator for parameters, methods, properties, and classes
220
+ *
221
+ * @example
222
+ * ```typescript
223
+ * // Create a custom auth decorator
224
+ * const RequireAdmin = CreateAuthDecorator({
225
+ * validator: (user: any) => {
226
+ * if (!user || user.role !== 'admin') {
227
+ * throw new Error('Admin access required');
228
+ * }
229
+ * return user;
230
+ * }
231
+ * });
232
+ *
233
+ * // Use the decorator
234
+ * class AdminController {
235
+ * @Route('/admin/settings')
236
+ * getSettings(@RequireAdmin() user: UserProfile) {
237
+ * // Only admin users can access this
238
+ * return { settings: this.adminSettings };
239
+ * }
240
+ * }
241
+ * ```
242
+ */
243
+ export declare function CreateAuthDecorator<R = unknown, T = unknown>(callbacks: AuthDecoratorCallbacks<T, R>): (validator?: AuthValidator<T, R> | undefined) => import("@antelopejs/interface-core/decorators").ClassDecorator<import("@antelopejs/interface-core/decorators").Class<any, any[]>> & import("@antelopejs/interface-core/decorators").PropertyDecorator & import("@antelopejs/interface-core/decorators").ParameterDecorator;
244
+ /**
245
+ * Parameter Provider using the default source and signature verification callbacks.
246
+ * This decorator can be applied to parameters, methods, properties, or classes to
247
+ * require authentication.
248
+ *
249
+ * @param validator - Optional custom validation callback
250
+ * @returns The authenticated user data
251
+ *
252
+ * @example
253
+ * ```typescript
254
+ * class UserController {
255
+ * @Route('/profile')
256
+ * getProfile(@Authentication user: UserProfile) {
257
+ * // 'user' contains the authenticated user data
258
+ * return { name: user.name, email: user.email };
259
+ * }
260
+ *
261
+ * @Route('/admin')
262
+ * adminPage(@Authentication((user) => {
263
+ * if (user.role !== 'admin') throw new Error('Admin only');
264
+ * return user;
265
+ * }) user: UserProfile) {
266
+ * // Only admins will reach this code
267
+ * return { adminData: this.sensitiveData };
268
+ * }
269
+ * }
270
+ * ```
271
+ *
272
+ * @see {@link CreateAuthDecorator}
273
+ */
274
+ export declare const Authentication: (validator?: AuthValidator<unknown, unknown> | undefined) => import("@antelopejs/interface-core/decorators").ClassDecorator<import("@antelopejs/interface-core/decorators").Class<any, any[]>> & import("@antelopejs/interface-core/decorators").PropertyDecorator & import("@antelopejs/interface-core/decorators").ParameterDecorator;
275
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,239 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Authentication = exports.internal = void 0;
4
+ exports.ValidateRaw = ValidateRaw;
5
+ exports.SignRaw = SignRaw;
6
+ exports.SignServerResponse = SignServerResponse;
7
+ exports.CreateAuthDecorator = CreateAuthDecorator;
8
+ const interface_api_1 = require("@antelopejs/interface-api");
9
+ const interface_core_1 = require("@antelopejs/interface-core");
10
+ const decorators_1 = require("@antelopejs/interface-core/decorators");
11
+ const AuthHeaderName = "x-antelopejs-auth";
12
+ const AuthCookieName = "ANTELOPEJS_AUTH";
13
+ const EmptyString = "";
14
+ const CookieOptionSeparator = "; ";
15
+ const ClassParameterProviderSymbolDescription = "authentication-class-provider";
16
+ function readAuthHeader(req) {
17
+ const header = req.headers[AuthHeaderName];
18
+ if (typeof header === "string") {
19
+ return header;
20
+ }
21
+ if (!header || header.length === 0) {
22
+ return undefined;
23
+ }
24
+ return header[0];
25
+ }
26
+ function readCookieToken(req) {
27
+ const cookieHeader = req.headers.cookie;
28
+ if (!cookieHeader) {
29
+ return undefined;
30
+ }
31
+ const cookieMatch = ` ${cookieHeader}`.match(/ ANTELOPEJS_AUTH=([^;]*)/);
32
+ return cookieMatch?.[1];
33
+ }
34
+ function serializeCookieOptions(cookieOptions) {
35
+ if (!cookieOptions) {
36
+ return EmptyString;
37
+ }
38
+ const entries = Object.entries(cookieOptions).filter(([, value]) => value !== undefined && value !== false);
39
+ if (entries.length === 0) {
40
+ return EmptyString;
41
+ }
42
+ return entries
43
+ .map(([key, value]) => typeof value === "boolean" ? key : `${key}=${String(value)}`)
44
+ .join(CookieOptionSeparator);
45
+ }
46
+ function createSetCookieHeader(token, cookieOptions) {
47
+ const serializedCookieOptions = serializeCookieOptions(cookieOptions);
48
+ if (!serializedCookieOptions) {
49
+ return `${AuthCookieName}=${token}`;
50
+ }
51
+ return `${AuthCookieName}=${token}; ${serializedCookieOptions}`;
52
+ }
53
+ function resolveAuthDecoratorCallbacks(callbacks) {
54
+ return {
55
+ source: callbacks.source ?? internal.defaultSource,
56
+ authenticator: callbacks.authenticator ??
57
+ internal.defaultAuthenticator,
58
+ authenticatorOptions: callbacks.authenticatorOptions ?? {},
59
+ validator: callbacks.validator,
60
+ };
61
+ }
62
+ function createAuthParameterProvider(callbacks, validator) {
63
+ return (context) => internal.CheckAuthentication(context.rawRequest, context.rawResponse, callbacks.source, callbacks.authenticator, callbacks.authenticatorOptions, validator);
64
+ }
65
+ function registerClassParameterProvider(target, provider) {
66
+ (0, interface_api_1.SetParameterProvider)(target.prototype, Symbol(ClassParameterProviderSymbolDescription), undefined, provider);
67
+ }
68
+ /**
69
+ * @internal
70
+ */
71
+ var internal;
72
+ (function (internal) {
73
+ internal.Verify = (0, interface_core_1.InterfaceFunction)();
74
+ internal.Sign = (0, interface_core_1.InterfaceFunction)();
75
+ function defaultSource(req, _res) {
76
+ return readAuthHeader(req) ?? readCookieToken(req);
77
+ }
78
+ internal.defaultSource = defaultSource;
79
+ internal.defaultAuthenticator = ValidateRaw;
80
+ /**
81
+ * Verifies the signature of signed data attached to the HTTP request and returns the data contained therein.
82
+ *
83
+ * @template T - The type of data after verification
84
+ * @template R - The type of data after validation
85
+ * @param req - HTTP Request
86
+ * @param res - HTTP Response
87
+ * @param source - Callback to retrieve the signed data from the request
88
+ * @param authenticator - Callback to verify the signature
89
+ * @param authenticatorOptions - Verifier options
90
+ * @param validator - Custom validator callback
91
+ * @returns The authenticated and validated data
92
+ */
93
+ async function CheckAuthentication(req, res, source = defaultSource, authenticator = internal.defaultAuthenticator, authenticatorOptions = {}, validator) {
94
+ const verifiedData = await authenticator(source(req, res), authenticatorOptions);
95
+ if (!validator) {
96
+ return verifiedData;
97
+ }
98
+ return validator(verifiedData);
99
+ }
100
+ internal.CheckAuthentication = CheckAuthentication;
101
+ })(internal || (exports.internal = internal = {}));
102
+ /**
103
+ * Verifies the signature of some signed data and returns the data contained therein.
104
+ *
105
+ * @template T - The type of data expected after verification
106
+ * @param token - The signed data token to verify
107
+ * @param options - Options for verification
108
+ * @returns A promise resolving to the verified data
109
+ *
110
+ * @example
111
+ * ```typescript
112
+ * const userData = await ValidateRaw<UserProfile>(authToken, { maxAge: '1h' });
113
+ * console.log(userData.name);
114
+ * ```
115
+ */
116
+ function ValidateRaw(token, options) {
117
+ return internal.Verify(token, options);
118
+ }
119
+ /**
120
+ * Signs some data to create an authentication token.
121
+ *
122
+ * @param data - The data to sign
123
+ * @param options - Options for signing
124
+ * @returns The signed data token
125
+ *
126
+ * @example
127
+ * ```typescript
128
+ * const token = SignRaw({ userId: 123, role: 'admin' }, { expiresIn: '24h' });
129
+ * ```
130
+ */
131
+ function SignRaw(data, options) {
132
+ return internal.Sign(data, options);
133
+ }
134
+ /**
135
+ * Signs some data and attaches it to an HTTP Response object as a cookie.
136
+ *
137
+ * @param res - HTTP Response object to set the cookie on
138
+ * @param data - Data to sign and attach
139
+ * @param signOptions - Options for signing the data
140
+ * @param cookieOptions - Options for the cookie
141
+ * @returns A promise that resolves when the cookie has been set
142
+ *
143
+ * @example
144
+ * ```typescript
145
+ * await SignServerResponse(
146
+ * res,
147
+ * { userId: 123, permissions: ['read', 'write'] },
148
+ * { expiresIn: '8h' },
149
+ * { httpOnly: true, secure: true }
150
+ * );
151
+ * ```
152
+ */
153
+ function SignServerResponse(res, data, signOptions, cookieOptions) {
154
+ return SignRaw(data, signOptions).then((token) => {
155
+ res.setHeader("Set-Cookie", createSetCookieHeader(token, cookieOptions));
156
+ return res;
157
+ });
158
+ }
159
+ /**
160
+ * Creates a Parameter Provider using the specified source and signature verification callbacks.
161
+ *
162
+ * The callbacks are processed in the following order:
163
+ * `source(req, res)` => `authenticator(prev, authenticatorOptions)` => `validator(prev)` => Parameter
164
+ *
165
+ * @template R - The type of the final validator result
166
+ * @template T - The type of the authenticated data before validation
167
+ * @param callbacks - Configuration object containing callback functions
168
+ * @param callbacks.source - Extracts the signed data from the request
169
+ * @param callbacks.authenticator - Verifies the signature
170
+ * @param callbacks.authenticatorOptions - Options for verification
171
+ * @param callbacks.validator - Custom validation step (overrideable with decorator call)
172
+ * @returns A decorator for parameters, methods, properties, and classes
173
+ *
174
+ * @example
175
+ * ```typescript
176
+ * // Create a custom auth decorator
177
+ * const RequireAdmin = CreateAuthDecorator({
178
+ * validator: (user: any) => {
179
+ * if (!user || user.role !== 'admin') {
180
+ * throw new Error('Admin access required');
181
+ * }
182
+ * return user;
183
+ * }
184
+ * });
185
+ *
186
+ * // Use the decorator
187
+ * class AdminController {
188
+ * @Route('/admin/settings')
189
+ * getSettings(@RequireAdmin() user: UserProfile) {
190
+ * // Only admin users can access this
191
+ * return { settings: this.adminSettings };
192
+ * }
193
+ * }
194
+ * ```
195
+ */
196
+ function CreateAuthDecorator(callbacks) {
197
+ const resolvedCallbacks = resolveAuthDecoratorCallbacks(callbacks);
198
+ return (0, decorators_1.MakeParameterAndPropertyAndClassDecorator)((target, key, index, validator) => {
199
+ const authValidator = validator ?? resolvedCallbacks.validator;
200
+ const provider = createAuthParameterProvider(resolvedCallbacks, authValidator);
201
+ if (key === undefined) {
202
+ registerClassParameterProvider(target, provider);
203
+ return;
204
+ }
205
+ (0, interface_api_1.SetParameterProvider)(target, key, index, provider);
206
+ });
207
+ }
208
+ /**
209
+ * Parameter Provider using the default source and signature verification callbacks.
210
+ * This decorator can be applied to parameters, methods, properties, or classes to
211
+ * require authentication.
212
+ *
213
+ * @param validator - Optional custom validation callback
214
+ * @returns The authenticated user data
215
+ *
216
+ * @example
217
+ * ```typescript
218
+ * class UserController {
219
+ * @Route('/profile')
220
+ * getProfile(@Authentication user: UserProfile) {
221
+ * // 'user' contains the authenticated user data
222
+ * return { name: user.name, email: user.email };
223
+ * }
224
+ *
225
+ * @Route('/admin')
226
+ * adminPage(@Authentication((user) => {
227
+ * if (user.role !== 'admin') throw new Error('Admin only');
228
+ * return user;
229
+ * }) user: UserProfile) {
230
+ * // Only admins will reach this code
231
+ * return { adminData: this.sensitiveData };
232
+ * }
233
+ * }
234
+ * ```
235
+ *
236
+ * @see {@link CreateAuthDecorator}
237
+ */
238
+ exports.Authentication = CreateAuthDecorator({});
239
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AA6VA,kCAKC;AAcD,0BAKC;AAqBD,gDAUC;AAuCD,kDA6BC;AAvdD,6DAAiE;AACjE,+DAA+D;AAC/D,sEAAkG;AAElG,MAAM,cAAc,GAAG,mBAAmB,CAAC;AAC3C,MAAM,cAAc,GAAG,iBAAiB,CAAC;AACzC,MAAM,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,EAAE;QAC/C,GAAG,CAAC,SAAS,CAAC,YAAY,EAAE,qBAAqB,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC,CAAC;QACzE,OAAO,GAAG,CAAC;IACb,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,SAAgB,mBAAmB,CACjC,SAAuC;IAEvC,MAAM,iBAAiB,GAAG,6BAA6B,CAAC,SAAS,CAAC,CAAC;IAEnE,OAAO,IAAA,sDAAyC,EAC9C,CACE,MAAuB,EACvB,GAAiB,EACjB,KAAqB,EACrB,SAA+B,EAC/B,EAAE;QACF,MAAM,aAAa,GAAG,SAAS,IAAI,iBAAiB,CAAC,SAAS,CAAC;QAC/D,MAAM,QAAQ,GAAG,2BAA2B,CAC1C,iBAAiB,EACjB,aAAa,CACd,CAAC;QAEF,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;YACtB,8BAA8B,CAC5B,MAA8B,EAC9B,QAAQ,CACT,CAAC;YACF,OAAO;QACT,CAAC;QAED,IAAA,oCAAoB,EAAC,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;IACrD,CAAC,CACF,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACU,QAAA,cAAc,GAAG,mBAAmB,CAAC,EAAE,CAAC,CAAC"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const interface_api_1 = require("@antelopejs/interface-api");
4
+ const interface_auth_1 = require("@antelopejs/interface-auth");
5
+ const chai_1 = require("chai");
6
+ const testUsers = {
7
+ default: {
8
+ name: "Bob",
9
+ email: "bob@email.com",
10
+ password: "very-secure-qwerty123",
11
+ },
12
+ alternate: {
13
+ name: "Alice",
14
+ email: "alice@email.com",
15
+ password: "very-secure-qwerty123",
16
+ },
17
+ };
18
+ describe("JWT Authentication Tests", () => {
19
+ it("jwt token is valid", async () => await jwtTokenIsValid());
20
+ it("jwt token is invalid", async () => await jwtTokenIsInvalid());
21
+ it("jwt token is expired", async () => await jwtTokenIsExpired());
22
+ it("set-cookie uses standalone boolean directives", async () => await setCookieUsesStandaloneBooleanDirectives());
23
+ });
24
+ async function jwtTokenIsValid() {
25
+ const userData = testUsers.default;
26
+ const token = await (0, interface_auth_1.SignRaw)(userData, { expiresIn: "1h" });
27
+ const verifiedData = await (0, interface_auth_1.ValidateRaw)(token);
28
+ (0, chai_1.expect)(verifiedData).to.be.an("object");
29
+ (0, chai_1.expect)(verifiedData).to.have.property("name", userData.name);
30
+ (0, chai_1.expect)(verifiedData).to.have.property("email", userData.email);
31
+ (0, chai_1.expect)(verifiedData).to.have.property("password", userData.password);
32
+ }
33
+ async function jwtTokenIsInvalid() {
34
+ const invalidToken = "invalid.jwt.token";
35
+ try {
36
+ await (0, interface_auth_1.ValidateRaw)(invalidToken);
37
+ chai_1.expect.fail("Should have thrown an error for invalid token");
38
+ }
39
+ catch (error) {
40
+ (0, chai_1.expect)(error).to.be.instanceOf(interface_api_1.HTTPResult);
41
+ }
42
+ }
43
+ async function jwtTokenIsExpired() {
44
+ const userData = testUsers.default;
45
+ const token = await (0, interface_auth_1.SignRaw)(userData, { expiresIn: "1ms" });
46
+ await new Promise((resolve) => setTimeout(resolve, 10));
47
+ try {
48
+ await (0, interface_auth_1.ValidateRaw)(token);
49
+ chai_1.expect.fail("Should have thrown an error for expired token");
50
+ }
51
+ catch (error) {
52
+ (0, chai_1.expect)(error).to.be.instanceOf(interface_api_1.HTTPResult);
53
+ }
54
+ }
55
+ async function setCookieUsesStandaloneBooleanDirectives() {
56
+ const headers = {};
57
+ const responseLike = {
58
+ setHeader(name, value) {
59
+ headers[name.toLowerCase()] = normalizeHeaderValue(value);
60
+ return responseLike;
61
+ },
62
+ };
63
+ await (0, interface_auth_1.SignServerResponse)(responseLike, { userId: "user-7" }, { expiresIn: "1h" }, { httpOnly: true });
64
+ const setCookieHeader = headers["set-cookie"];
65
+ (0, chai_1.expect)(setCookieHeader).to.be.a("string");
66
+ (0, chai_1.expect)(setCookieHeader).to.match(/^ANTELOPEJS_AUTH=/);
67
+ (0, chai_1.expect)(setCookieHeader).to.match(/httpOnly/);
68
+ (0, chai_1.expect)(setCookieHeader).to.not.match(/httpOnly=true/);
69
+ }
70
+ function normalizeHeaderValue(value) {
71
+ if (Array.isArray(value)) {
72
+ return value.join(",");
73
+ }
74
+ return String(value);
75
+ }
76
+ //# sourceMappingURL=index.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.test.js","sourceRoot":"","sources":["../../src/tests/index.test.ts"],"names":[],"mappings":";;AACA,6DAAuD;AACvD,+DAIoC;AACpC,+BAA8B;AAc9B,MAAM,SAAS,GAAc;IAC3B,OAAO,EAAE;QACP,IAAI,EAAE,KAAK;QACX,KAAK,EAAE,eAAe;QACtB,QAAQ,EAAE,uBAAuB;KAClC;IACD,SAAS,EAAE;QACT,IAAI,EAAE,OAAO;QACb,KAAK,EAAE,iBAAiB;QACxB,QAAQ,EAAE,uBAAuB;KAClC;CACF,CAAC;AAEF,QAAQ,CAAC,0BAA0B,EAAE,GAAG,EAAE;IACxC,EAAE,CAAC,oBAAoB,EAAE,KAAK,IAAI,EAAE,CAAC,MAAM,eAAe,EAAE,CAAC,CAAC;IAC9D,EAAE,CAAC,sBAAsB,EAAE,KAAK,IAAI,EAAE,CAAC,MAAM,iBAAiB,EAAE,CAAC,CAAC;IAClE,EAAE,CAAC,sBAAsB,EAAE,KAAK,IAAI,EAAE,CAAC,MAAM,iBAAiB,EAAE,CAAC,CAAC;IAClE,EAAE,CAAC,+CAA+C,EAAE,KAAK,IAAI,EAAE,CAC7D,MAAM,wCAAwC,EAAE,CAAC,CAAC;AACtD,CAAC,CAAC,CAAC;AAEH,KAAK,UAAU,eAAe;IAC5B,MAAM,QAAQ,GAAG,SAAS,CAAC,OAAO,CAAC;IACnC,M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IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACzB,CAAC;IAED,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;AACvB,CAAC"}
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@antelopejs/interface-auth",
3
+ "version": "0.0.2",
4
+ "description": "AntelopeJS interface for JWT authentication and session management",
5
+ "keywords": [
6
+ "antelopejs",
7
+ "interface",
8
+ "auth",
9
+ "jwt"
10
+ ],
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/AntelopeJS/interface-auth.git"
14
+ },
15
+ "license": "Apache-2.0",
16
+ "packageManager": "pnpm@10.6.5",
17
+ "main": "dist/index.js",
18
+ "types": "dist/index.d.ts",
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ },
27
+ "./package.json": "./package.json"
28
+ },
29
+ "scripts": {
30
+ "build": "rimraf dist && tsc",
31
+ "format": "biome format --write .",
32
+ "lint:fix": "biome check --write .",
33
+ "lint": "biome check .",
34
+ "prepack": "pnpm run build",
35
+ "release": "pnpm run lint && pnpm run prepack && release-it",
36
+ "test": "pnpm run build && ajs module test ."
37
+ },
38
+ "dependencies": {
39
+ "@antelopejs/interface-api": "^0.0.2",
40
+ "@antelopejs/interface-core": "^0.0.2"
41
+ },
42
+ "devDependencies": {
43
+ "@types/chai": "^4.3.20",
44
+ "@types/mocha": "^10.0.10",
45
+ "@types/node": "^22.14.1",
46
+ "@biomejs/biome": "2.3.2",
47
+ "chai": "^4.5.0",
48
+ "release-it": "^19.0.2",
49
+ "release-it-changelogen": "^0.1.0",
50
+ "rimraf": "^6.0.1",
51
+ "typescript": "^5.8.3",
52
+ "mongodb-memory-server-core": "^10.1.4",
53
+ "@types/semver": "^7.7.0"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ },
58
+ "antelopeJs": {
59
+ "test": "src/antelope.test.ts"
60
+ }
61
+ }