@riao/iam 3.3.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1 +1 @@
1
- # riao-iam - Changelog
1
+ # riao-iam - Changelog
package/LICENSE.md CHANGED
@@ -1,20 +1,20 @@
1
- Copyright (c) 2022 riao-iam and others
2
-
3
- Permission is hereby granted, free of charge, to any person obtaining
4
- a copy of this software and associated documentation files (the
5
- "Software"), to deal in the Software without restriction, including
6
- without limitation the rights to use, copy, modify, merge, publish,
7
- distribute, sublicense, and/or sell copies of the Software, and to
8
- permit persons to whom the Software is furnished to do so, subject to
9
- the following conditions:
10
-
11
- The above copyright notice and this permission notice shall be
12
- included in all copies or substantial portions of the Software.
13
-
14
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1
+ Copyright (c) 2022 riao-iam and others
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,71 +1,224 @@
1
- # @riao/iam - Readme
2
-
3
- ## Installation
4
-
5
- `npm i @riao/iam`
6
-
7
- ## Encryption & Key Pairs
8
-
9
- To use encryption and signing features, you need to generate a key pair. The `KeyPairGenerator` class supports generating RSA and Elliptic Curve key pairs.
10
-
11
- ### Quick Start with Encryptor/Decryptor (Recommended)
12
-
13
- The `Encryptor` and `Decryptor` classes provide a simple, object-oriented interface for managing encryption and decryption:
14
-
15
- ```typescript
16
- import { Encryptor, Decryptor, KeyPairGenerator } from '@riao/iam';
17
-
18
- // Generate a key pair
19
- const generator = new KeyPairGenerator({ algorithm: 'RS256' });
20
- const keypair = generator.generate();
21
-
22
- // Create Encryptor and Decryptor instances
23
- const encryptor = new Encryptor(keypair.publicKey);
24
- const decryptor = new Decryptor(keypair.privateKey);
25
-
26
- // Encrypt and decrypt
27
- const encrypted = encryptor.encrypt('Secret message');
28
- const decrypted = decryptor.decrypt(encrypted);
29
- console.log(decrypted.toString()); // 'Secret message'
30
- ```
31
-
32
- ## JSON Web Tokens (JWT)
33
-
34
- The `Jwt` class provides a secure way to generate and verify JSON Web Tokens for authentication and authorization. It supports both symmetric signing (using a shared secret) and asymmetric signing (using public/private key pairs).
35
-
36
- ### Quick Start
37
-
38
- ```typescript
39
- import { Jwt } from '@riao/iam';
40
-
41
- // Create a JWT manager with a shared secret
42
- const jwtManager = new Jwt({
43
- secret: 'your-secret-key',
44
- algorithm: 'HS512',
45
- expiresIn: '1h',
46
- });
47
-
48
- // Generate a token
49
- const { token } = await jwtManager.generateToken({
50
- userId: 'user-123',
51
- role: 'admin',
52
- });
53
-
54
- // Verify and decode a token
55
- const payload = await jwtManager.decodeToken(token);
56
- console.log(payload.userId); // 'user-123'
57
- ```
58
-
59
- For detailed usage, algorithms, security best practices, and advanced patterns, see the [JWT Guide](docs/jwt-guide.md).
60
-
61
- ### Documentation
62
-
63
- - [Encryptor & Decryptor Guide](docs/encryptor-decryptor-guide.md) - **Recommended** - Object-oriented encryption/decryption interface
64
- - [KeyPair Usage Guide](docs/keypair-guide.md) - Learn how to use the KeyPairGenerator for cryptographic operations
65
- - [Encryption & Decryption Guide](docs/crypto-guide.md) - Lower-level `encrypt` and `decrypt` functions (for advanced use cases)
66
- - [Hash Guide](docs/hash-guide.md) - Password hashing and verification with bcrypt
67
- - [JWT Guide](docs/jwt-guide.md) - Generate and verify JSON Web Tokens for authentication and authorization
68
-
69
- ## Contributing & Development
70
-
71
- See [contributing.md](docs/contributing/contributing.md) for information on how to develop or contribute to this project!
1
+ # @riao/iam - Readme
2
+
3
+ ## Installation
4
+
5
+ `npm i @riao/iam`
6
+
7
+ ## Usage
8
+
9
+ ### Quick Start
10
+
11
+ @riao/iam is an Identity and Access Management (IAM) library that provides a flexible framework for:
12
+ - **Authentication**: Validating user credentials and managing principals
13
+ - **Authorization**: Controlling access to resources based on permissions
14
+
15
+ ### Core Concepts
16
+
17
+ #### Principal
18
+ A principal represents any entity (user, service, bot, or system) that can authenticate and be authorized.
19
+
20
+ #### Auth Class
21
+ Base class that manages principals and provides access to the principals repository.
22
+
23
+ #### Authentication
24
+ Abstract class extending `Auth` that handles credential validation. Implement this to create custom authentication drivers (password-based, OAuth, JWT, etc.).
25
+
26
+ #### Authorization
27
+ Abstract class extending `Auth` that manages permissions and access control. Implement this to define your authorization model.
28
+
29
+ ### Setup & Configuration
30
+
31
+ #### 1. Initialize with a Database
32
+
33
+ ```typescript
34
+ import { Database } from '@riao/dbal';
35
+ import { Authentication, Authorization } from '@riao/iam';
36
+
37
+ const db = new Database({
38
+ // Your database configuration
39
+ });
40
+ ```
41
+
42
+ #### 2. Create a Custom Authentication Driver
43
+
44
+ Extend the `Authentication` class to implement your authentication logic:
45
+
46
+ ```typescript
47
+ import { Authentication, Principal } from '@riao/iam';
48
+
49
+ class PasswordAuthentication extends Authentication<Principal> {
50
+ async authenticate(credentials: {
51
+ login: string;
52
+ password: string
53
+ }): Promise<Principal | null> {
54
+ // Find the principal by login
55
+ const principal = await this.findActivePrincipal({
56
+ where: { login: credentials.login }
57
+ });
58
+
59
+ if (!principal) {
60
+ return null;
61
+ }
62
+
63
+ // Verify password (you'd use your hash verification logic)
64
+ const isValid = await verifyPassword(
65
+ credentials.password,
66
+ principal.passwordHash
67
+ );
68
+
69
+ return isValid ? principal : null;
70
+ }
71
+
72
+ // Implement the isActiveQuery if needed for custom active status logic
73
+ protected isActiveQuery() {
74
+ return { deactivate_timestamp: null };
75
+ }
76
+ }
77
+
78
+ // Initialize your authentication driver
79
+ const auth = new PasswordAuthentication({ db });
80
+ ```
81
+
82
+ #### 3. Create a Custom Authorization Driver
83
+
84
+ Extend the `Authorization` class to implement your permission model:
85
+
86
+ ```typescript
87
+ import { Authorization, AuthorizationContext, AuthorizationResult } from '@riao/iam';
88
+
89
+ class RoleBasedAuthorization extends Authorization<Principal> {
90
+ async evaluate(context: AuthorizationContext<Principal>): Promise<AuthorizationResult> {
91
+ const { principal, action, resource } = context;
92
+
93
+ // Implement your authorization logic
94
+ const hasPermission = await this.checkPermission(context);
95
+ return hasPermission;
96
+ }
97
+
98
+ async grantPermission(options: GrantPermissionOptions): Promise<void> {
99
+ // Implement grant logic
100
+ }
101
+
102
+ async revokePermission(options: RevokePermissionOptions): Promise<void> {
103
+ // Implement revoke logic
104
+ }
105
+ }
106
+
107
+ const authz = new RoleBasedAuthorization({ db });
108
+ ```
109
+
110
+ ### Common Tasks
111
+
112
+ #### Authenticate a User
113
+
114
+ ```typescript
115
+ const credentials = { login: 'john.doe', password: 'secret123' };
116
+ const principal = await auth.authenticate(credentials);
117
+
118
+ if (principal) {
119
+ console.log(`Authenticated as: ${principal.name}`);
120
+ } else {
121
+ console.log('Authentication failed');
122
+ }
123
+ ```
124
+
125
+ #### Create a New Principal
126
+
127
+ ```typescript
128
+ const principalId = await auth.createPrincipal({
129
+ login: 'jane.doe',
130
+ name: 'Jane Doe',
131
+ type: 'user',
132
+ deactivate_timestamp: null
133
+ });
134
+
135
+ console.log(`Created principal with ID: ${principalId}`);
136
+ ```
137
+
138
+ #### Check Authorization
139
+
140
+ ```typescript
141
+ const context = {
142
+ principal: authenticatedPrincipal,
143
+ resource: 'document-123',
144
+ action: 'read'
145
+ };
146
+
147
+ const isAuthorized = await authz.isAuthorized(context);
148
+ if (isAuthorized) {
149
+ console.log('Access granted');
150
+ } else {
151
+ console.log('Access denied');
152
+ }
153
+ ```
154
+
155
+ #### Grant Permissions
156
+
157
+ ```typescript
158
+ await authz.grantPermission({
159
+ principalId: principal.id,
160
+ action: 'delete',
161
+ resource: 'document-123',
162
+ metadata: { grantedBy: 'admin', grantedAt: new Date() }
163
+ });
164
+ ```
165
+
166
+ #### Revoke Permissions
167
+
168
+ ```typescript
169
+ await authz.revokePermission({
170
+ principalId: principal.id,
171
+ action: 'delete',
172
+ resource: 'document-123'
173
+ });
174
+ ```
175
+
176
+ ### Authentication Protection and Lockout
177
+
178
+ Authentication drivers can optionally plug into a shared protection contract to prevent brute-force attempts and enforce temporary lockout windows.
179
+
180
+ ```typescript
181
+ import {
182
+ AuthenticationAttempt,
183
+ AuthenticationProtection,
184
+ AuthenticationProtectionResult,
185
+ } from '@riao/iam/authentication';
186
+
187
+ const protection: AuthenticationProtection = {
188
+ beforeAttempt: async (
189
+ attempt: AuthenticationAttempt
190
+ ): Promise<AuthenticationProtectionResult> => {
191
+ return { allowed: true };
192
+ },
193
+ onFailure: async (attempt: AuthenticationAttempt) => {
194
+ // Record failed auth attempt metadata or update a rate limit store.
195
+ },
196
+ onSuccess: async (attempt: AuthenticationAttempt) => {
197
+ // Reset counters or clear temporary blocks.
198
+ },
199
+ };
200
+ ```
201
+
202
+ When `beforeAttempt()` returns `allowed: false`, the driver should skip credential verification and return `null`. See the [authentication driver guide](docs/authentication-driver-guide.md#authentication-protection-hooks) for hook behavior and recommendations for surfacing `retryAfterSeconds`.
203
+
204
+ ### Advanced
205
+
206
+ For detailed information on:
207
+ - Building custom authentication drivers, see [authentication-driver-guide.md](docs/authentication-driver-guide.md)
208
+ - Building custom authorization drivers, see [authorization-driver-guide.md](docs/authorization-driver-guide.md)
209
+ - Database migrations and schema setup, see [Database Setup](#database-setup)
210
+
211
+ ### Database Setup
212
+
213
+ @riao/iam requires database tables to store principals and permissions. Use the `AuthMigrations` class to set up the required schema:
214
+
215
+ ```typescript
216
+ import { AuthMigrations } from '@riao/iam';
217
+
218
+ const migrations = new AuthMigrations();
219
+ await db.runMigrations(migrations);
220
+ ```
221
+
222
+ ## Contributing & Development
223
+
224
+ See [contributing.md](docs/contributing/contributing.md) for information on how to develop or contribute to this project!
@@ -1 +1 @@
1
- {"version":3,"file":"001-create-principals-table.js","sourceRoot":"","sources":["../../../../src/auth/migrations/001-create-principals-table.ts"],"names":[],"mappings":";;;AAAA,wDAKgC;AAChC,qCAAmD;AAEnD,MAAa,8BAA+B,SAAQ,gBAAS;IACnD,KAAK,CAAC,EAAE;QAChB,MAAM,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC;YAC1B,IAAI,EAAE,gBAAgB;YACtB,OAAO,EAAE;gBACR,2BAAa;gBACb;oBACC,IAAI,EAAE,MAAM;oBACZ,IAAI,EAAE,iBAAU,CAAC,OAAO;oBACxB,MAAM,EAAE,GAAG;oBACX,QAAQ,EAAE,IAAI;iBACd;gBACD;oBACC,IAAI,EAAE,iBAAU,CAAC,OAAO;oBACxB,MAAM,EAAE,GAAG;oBACX,IAAI,EAAE,OAAO;oBACb,QAAQ,EAAE,IAAI;iBACd;gBACD,EAAE,GAAG,wBAAU,EAAE,QAAQ,EAAE,IAAI,EAAE;gBACjC,mCAAqB;gBACrB;oBACC,IAAI,EAAE,sBAAsB;oBAC5B,IAAI,EAAE,iBAAU,CAAC,SAAS;iBAC1B;aACD;SACD,CAAC,CAAC;IACJ,CAAC;IAEQ,KAAK,CAAC,IAAI;QAClB,MAAM,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC;YACxB,MAAM,EAAE,CAAC,gBAAgB,CAAC;SAC1B,CAAC,CAAC;IACJ,CAAC;CACD;AAjCD,wEAiCC"}
1
+ {"version":3,"file":"001-create-principals-table.js","sourceRoot":"","sources":["../../../../src/auth/migrations/001-create-principals-table.ts"],"names":[],"mappings":";;;AAAA,wDAIgC;AAChC,qCAAmD;AAEnD,MAAa,8BAA+B,SAAQ,gBAAS;IACnD,KAAK,CAAC,EAAE;QAChB,MAAM,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC;YAC1B,IAAI,EAAE,gBAAgB;YACtB,OAAO,EAAE;gBACR,2BAAa;gBACb;oBACC,IAAI,EAAE,MAAM;oBACZ,IAAI,EAAE,iBAAU,CAAC,OAAO;oBACxB,MAAM,EAAE,GAAG;oBACX,QAAQ,EAAE,IAAI;iBACd;gBACD;oBACC,IAAI,EAAE,iBAAU,CAAC,OAAO;oBACxB,MAAM,EAAE,GAAG;oBACX,IAAI,EAAE,OAAO;oBACb,QAAQ,EAAE,IAAI;iBACd;gBACD,EAAE,GAAG,wBAAU,EAAE,QAAQ,EAAE,IAAI,EAAE;gBACjC,mCAAqB;gBACrB;oBACC,IAAI,EAAE,sBAAsB;oBAC5B,IAAI,EAAE,iBAAU,CAAC,SAAS;iBAC1B;aACD;SACD,CAAC,CAAC;IACJ,CAAC;IAEQ,KAAK,CAAC,IAAI;QAClB,MAAM,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC;YACxB,MAAM,EAAE,CAAC,gBAAgB,CAAC;SAC1B,CAAC,CAAC;IACJ,CAAC;CACD;AAjCD,wEAiCC"}
@@ -1,7 +1,19 @@
1
1
  import { DatabaseRecordId, Expression, SelectQuery } from '@riao/dbal';
2
- import { Auth, Principal } from '../auth';
2
+ import { Auth, AuthOptions, Principal } from '../auth';
3
+ import { AuthenticationAttempt, AuthenticationProtection, AuthenticationProtectionResult } from './protection';
4
+ export interface AuthenticationOptions extends AuthOptions {
5
+ authenticationProtection?: AuthenticationProtection;
6
+ }
3
7
  export declare abstract class Authentication<TPrincipal extends Principal> extends Auth<TPrincipal> {
8
+ protected readonly authenticationProtection: AuthenticationProtection;
9
+ constructor(options: AuthenticationOptions);
10
+ protected beforeAuthenticationAttempt(attempt: AuthenticationAttempt): Promise<AuthenticationProtectionResult>;
11
+ protected recordAuthenticationFailure(attempt: AuthenticationAttempt): Promise<void>;
12
+ protected recordAuthenticationSuccess(attempt: AuthenticationAttempt): Promise<void>;
4
13
  createPrincipal(principal: Omit<TPrincipal, 'id' | 'create_timestamp'>): Promise<DatabaseRecordId>;
14
+ /**
15
+ * Return an active principal or null for ordinary credential rejection.
16
+ */
5
17
  abstract authenticate(credentials: any): Promise<TPrincipal | null>;
6
18
  findActivePrincipal(query: SelectQuery<TPrincipal>): Promise<TPrincipal | null>;
7
19
  deactivatePrincipal(principalId: DatabaseRecordId): Promise<void>;
@@ -3,7 +3,24 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Authentication = void 0;
4
4
  const dbal_1 = require("@riao/dbal");
5
5
  const auth_1 = require("../auth");
6
+ const protection_1 = require("./protection");
6
7
  class Authentication extends auth_1.Auth {
8
+ authenticationProtection;
9
+ constructor(options) {
10
+ super(options);
11
+ this.authenticationProtection =
12
+ options.authenticationProtection ??
13
+ new protection_1.NoopAuthenticationProtection();
14
+ }
15
+ async beforeAuthenticationAttempt(attempt) {
16
+ return this.authenticationProtection.beforeAttempt(attempt);
17
+ }
18
+ async recordAuthenticationFailure(attempt) {
19
+ await this.authenticationProtection.onFailure(attempt);
20
+ }
21
+ async recordAuthenticationSuccess(attempt) {
22
+ await this.authenticationProtection.onSuccess(attempt);
23
+ }
7
24
  async createPrincipal(principal) {
8
25
  const inserted = await this.principalRepo.insertOne({
9
26
  record: principal,
@@ -1 +1 @@
1
- {"version":3,"file":"authentication.js","sourceRoot":"","sources":["../../../src/authentication/authentication.ts"],"names":[],"mappings":";;;AAAA,qCAA4E;AAC5E,kCAA0C;AAG1C,MAAsB,cAEpB,SAAQ,WAAgB;IAClB,KAAK,CAAC,eAAe,CAC3B,SAAsD;QAEtD,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,SAAS,CAAC;YACnD,MAAM,EAAE,SAAuB;SAC/B,CAAC,CAAC;QAEH,OAAO,QAAQ,CAAC,EAAsB,CAAC;IACxC,CAAC;IAKM,KAAK,CAAC,mBAAmB,CAC/B,KAA8B;QAE9B,MAAM,aAAa,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC;QAE3C,IAAI,KAAK,CAAC,KAAK,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YAChD,KAAK,CAAC,KAAK,GAAG,CAAC,aAAa,EAAE,UAAG,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;QACjD,CAAC;aACI,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YACtC,KAAK,CAAC,KAAK,GAAG,aAAa,CAAC;QAC7B,CAAC;QAED,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC;YAClD,GAAG,KAAK;SACR,CAAC,CAAC;QAEH,OAAO,SAAS,CAAC;IAClB,CAAC;IAEM,KAAK,CAAC,mBAAmB,CAC/B,WAA6B;QAE7B,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;YAChC,GAAG,EAAE;gBACJ,oBAAoB,EAAE,IAAI,IAAI,EAAE;aACT;YACxB,KAAK,EAAE,EAAE,EAAE,EAAE,WAAW,EAAkC;SAC1D,CAAC,CAAC;IACJ,CAAC;IAES,aAAa;QACtB,OAAO;YACN,oBAAoB,EAAE,IAAI;SACM,CAAC;IACnC,CAAC;CACD;AAnDD,wCAmDC"}
1
+ {"version":3,"file":"authentication.js","sourceRoot":"","sources":["../../../src/authentication/authentication.ts"],"names":[],"mappings":";;;AAAA,qCAA4E;AAC5E,kCAAuD;AAGvD,6CAKsB;AAMtB,MAAsB,cAEpB,SAAQ,WAAgB;IACN,wBAAwB,CAA2B;IAEtE,YAAmB,OAA8B;QAChD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,wBAAwB;YAC5B,OAAO,CAAC,wBAAwB;gBAChC,IAAI,yCAA4B,EAAE,CAAC;IACrC,CAAC;IAES,KAAK,CAAC,2BAA2B,CAC1C,OAA8B;QAE9B,OAAO,IAAI,CAAC,wBAAwB,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;IAC7D,CAAC;IAES,KAAK,CAAC,2BAA2B,CAC1C,OAA8B;QAE9B,MAAM,IAAI,CAAC,wBAAwB,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IACxD,CAAC;IAES,KAAK,CAAC,2BAA2B,CAC1C,OAA8B;QAE9B,MAAM,IAAI,CAAC,wBAAwB,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IACxD,CAAC;IAEM,KAAK,CAAC,eAAe,CAC3B,SAAsD;QAEtD,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,SAAS,CAAC;YACnD,MAAM,EAAE,SAAuB;SAC/B,CAAC,CAAC;QAEH,OAAO,QAAQ,CAAC,EAAsB,CAAC;IACxC,CAAC;IAQM,KAAK,CAAC,mBAAmB,CAC/B,KAA8B;QAE9B,MAAM,aAAa,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC;QAE3C,IAAI,KAAK,CAAC,KAAK,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YAChD,KAAK,CAAC,KAAK,GAAG,CAAC,aAAa,EAAE,UAAG,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;QACjD,CAAC;aACI,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YACtC,KAAK,CAAC,KAAK,GAAG,aAAa,CAAC;QAC7B,CAAC;QAED,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC;YAClD,GAAG,KAAK;SACR,CAAC,CAAC;QAEH,OAAO,SAAS,CAAC;IAClB,CAAC;IAEM,KAAK,CAAC,mBAAmB,CAC/B,WAA6B;QAE7B,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC;YAChC,GAAG,EAAE;gBACJ,oBAAoB,EAAE,IAAI,IAAI,EAAE;aACT;YACxB,KAAK,EAAE,EAAE,EAAE,EAAE,WAAW,EAAkC;SAC1D,CAAC,CAAC;IACJ,CAAC;IAES,aAAa;QACtB,OAAO;YACN,oBAAoB,EAAE,IAAI;SACM,CAAC;IACnC,CAAC;CACD;AAjFD,wCAiFC"}
@@ -0,0 +1,7 @@
1
+ export declare class AuthenticationRejectedError extends Error {
2
+ constructor(message?: string);
3
+ }
4
+ export declare class AuthenticationBlockedError extends AuthenticationRejectedError {
5
+ readonly retryAfterSeconds?: number | undefined;
6
+ constructor(retryAfterSeconds?: number | undefined);
7
+ }
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuthenticationBlockedError = exports.AuthenticationRejectedError = void 0;
4
+ class AuthenticationRejectedError extends Error {
5
+ constructor(message = 'Authentication rejected') {
6
+ super(message);
7
+ this.name = 'AuthenticationRejectedError';
8
+ }
9
+ }
10
+ exports.AuthenticationRejectedError = AuthenticationRejectedError;
11
+ class AuthenticationBlockedError extends AuthenticationRejectedError {
12
+ retryAfterSeconds;
13
+ constructor(retryAfterSeconds) {
14
+ super('Authentication temporarily unavailable');
15
+ this.retryAfterSeconds = retryAfterSeconds;
16
+ this.name = 'AuthenticationBlockedError';
17
+ }
18
+ }
19
+ exports.AuthenticationBlockedError = AuthenticationBlockedError;
20
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/authentication/errors.ts"],"names":[],"mappings":";;;AAAA,MAAa,2BAA4B,SAAQ,KAAK;IACrD,YAAmB,OAAO,GAAG,yBAAyB;QACrD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,6BAA6B,CAAC;IAC3C,CAAC;CACD;AALD,kEAKC;AAED,MAAa,0BAA2B,SAAQ,2BAA2B;IACvC;IAAnC,YAAmC,iBAA0B;QAC5D,KAAK,CAAC,wCAAwC,CAAC,CAAC;QADd,sBAAiB,GAAjB,iBAAiB,CAAS;QAE5D,IAAI,CAAC,IAAI,GAAG,4BAA4B,CAAC;IAC1C,CAAC;CACD;AALD,gEAKC"}
@@ -1 +1,4 @@
1
1
  export { Authentication } from './authentication';
2
+ export { AuthenticationOptions } from './authentication';
3
+ export { AuthenticationRejectedError, AuthenticationBlockedError, } from './errors';
4
+ export { AuthenticationAttempt, AuthenticationProtection, AuthenticationProtectionResult, NoopAuthenticationProtection, } from './protection';
@@ -1,6 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Authentication = void 0;
3
+ exports.NoopAuthenticationProtection = exports.AuthenticationBlockedError = exports.AuthenticationRejectedError = exports.Authentication = void 0;
4
4
  var authentication_1 = require("./authentication");
5
5
  Object.defineProperty(exports, "Authentication", { enumerable: true, get: function () { return authentication_1.Authentication; } });
6
+ var errors_1 = require("./errors");
7
+ Object.defineProperty(exports, "AuthenticationRejectedError", { enumerable: true, get: function () { return errors_1.AuthenticationRejectedError; } });
8
+ Object.defineProperty(exports, "AuthenticationBlockedError", { enumerable: true, get: function () { return errors_1.AuthenticationBlockedError; } });
9
+ var protection_1 = require("./protection");
10
+ Object.defineProperty(exports, "NoopAuthenticationProtection", { enumerable: true, get: function () { return protection_1.NoopAuthenticationProtection; } });
6
11
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/authentication/index.ts"],"names":[],"mappings":";;;AAAA,mDAAkD;AAAzC,gHAAA,cAAc,OAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/authentication/index.ts"],"names":[],"mappings":";;;AAAA,mDAAkD;AAAzC,gHAAA,cAAc,OAAA;AAEvB,mCAGkB;AAFjB,qHAAA,2BAA2B,OAAA;AAC3B,oHAAA,0BAA0B,OAAA;AAE3B,2CAKsB;AADrB,0HAAA,4BAA4B,OAAA"}
@@ -0,0 +1,19 @@
1
+ export interface AuthenticationAttempt {
2
+ scheme: string;
3
+ subject: string;
4
+ metadata?: Record<string, unknown>;
5
+ }
6
+ export interface AuthenticationProtectionResult {
7
+ allowed: boolean;
8
+ retryAfterSeconds?: number;
9
+ }
10
+ export interface AuthenticationProtection {
11
+ beforeAttempt(attempt: AuthenticationAttempt): Promise<AuthenticationProtectionResult>;
12
+ onFailure(attempt: AuthenticationAttempt): Promise<void>;
13
+ onSuccess(attempt: AuthenticationAttempt): Promise<void>;
14
+ }
15
+ export declare class NoopAuthenticationProtection implements AuthenticationProtection {
16
+ beforeAttempt(): Promise<AuthenticationProtectionResult>;
17
+ onFailure(): Promise<void>;
18
+ onSuccess(): Promise<void>;
19
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NoopAuthenticationProtection = void 0;
4
+ class NoopAuthenticationProtection {
5
+ async beforeAttempt() {
6
+ return { allowed: true };
7
+ }
8
+ async onFailure() { }
9
+ async onSuccess() { }
10
+ }
11
+ exports.NoopAuthenticationProtection = NoopAuthenticationProtection;
12
+ //# sourceMappingURL=protection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protection.js","sourceRoot":"","sources":["../../../src/authentication/protection.ts"],"names":[],"mappings":";;;AAmBA,MAAa,4BAA4B;IACjC,KAAK,CAAC,aAAa;QACzB,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC1B,CAAC;IAEM,KAAK,CAAC,SAAS,KAAmB,CAAC;IAEnC,KAAK,CAAC,SAAS,KAAmB,CAAC;CAC1C;AARD,oEAQC"}
@@ -1,16 +1,24 @@
1
1
  import { DatabaseRecordId } from '@riao/dbal';
2
2
  import { Auth, AuthOptions, Principal } from '../auth';
3
3
  export type AuthorizationOptions = AuthOptions;
4
- export interface AuthorizationContext<TPrincipal extends Principal = Principal> {
5
- principal: TPrincipal;
4
+ export interface AuthorizationSubject {
5
+ id: string;
6
+ }
7
+ export interface AuthorizationRequirement {
6
8
  resource?: string | Record<string, unknown>;
7
9
  action: string;
8
10
  metadata?: Record<string, unknown>;
9
11
  }
12
+ export interface AuthorizationContext<TSubject extends AuthorizationSubject = Principal> extends AuthorizationRequirement {
13
+ principal: TSubject;
14
+ }
10
15
  export interface AuthorizationResult {
11
16
  allowed: boolean;
12
17
  reason?: string;
13
18
  }
19
+ export interface AuthorizationService<TSubject extends AuthorizationSubject = AuthorizationSubject> {
20
+ evaluate(context: AuthorizationContext<TSubject>): Promise<AuthorizationResult>;
21
+ }
14
22
  export interface GrantPermissionOptions {
15
23
  principalId: DatabaseRecordId;
16
24
  action: string;
@@ -23,27 +31,27 @@ export interface RevokePermissionOptions {
23
31
  resource?: string;
24
32
  metadata?: Record<string, unknown>;
25
33
  }
26
- export declare abstract class Authorization<TPrincipal extends Principal> extends Auth<TPrincipal> {
34
+ export declare abstract class Authorization<TPrincipal extends Principal, TSubject extends AuthorizationSubject = TPrincipal> extends Auth<TPrincipal> implements AuthorizationService<TSubject> {
27
35
  /**
28
36
  * Evaluate authorization for a given context
29
37
  * @param context The authorization context containing principal,
30
38
  * resource, action, and optional metadata
31
39
  * @returns Authorization result with allowed status and optional reason
32
40
  */
33
- abstract evaluate(context: AuthorizationContext<TPrincipal>): Promise<AuthorizationResult>;
41
+ abstract evaluate(context: AuthorizationContext<TSubject>): Promise<AuthorizationResult>;
34
42
  /**
35
43
  * Check if a principal is authorized for a specific action on a resource
36
44
  * @param context The authorization context
37
45
  * @returns True if authorized, false otherwise
38
46
  */
39
- isAuthorized(context: AuthorizationContext<TPrincipal>): Promise<boolean>;
47
+ isAuthorized(context: AuthorizationContext<TSubject>): Promise<boolean>;
40
48
  /**
41
49
  * Check if a principal has permission for an action
42
50
  * Subclasses should override this for specific authorization models
43
51
  * @param context The authorization context
44
52
  * @returns Authorization result
45
53
  */
46
- protected checkPermission(context: AuthorizationContext<TPrincipal>): Promise<AuthorizationResult>;
54
+ protected checkPermission(context: AuthorizationContext<TSubject>): Promise<AuthorizationResult>;
47
55
  /**
48
56
  * Grant a permission to a principal
49
57
  * Subclasses should implement this based on their model
@@ -1 +1 @@
1
- {"version":3,"file":"authorization.js","sourceRoot":"","sources":["../../../src/authorization/authorization.ts"],"names":[],"mappings":";;;AACA,kCAAuD;AAgCvD,MAAsB,aAEpB,SAAQ,WAAgB;IAWzB;;;;OAIG;IACI,KAAK,CAAC,YAAY,CACxB,OAAyC;QAEzC,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QAC5C,OAAO,MAAM,CAAC,OAAO,CAAC;IACvB,CAAC;IAED;;;;;OAKG;IACO,KAAK,CAAC,eAAe;IAC9B,6DAA6D;IAC7D,OAAyC;QAEzC,uCAAuC;QACvC,OAAO;YACN,OAAO,EAAE,KAAK;YACd,MAAM,EAAE,mCAAmC;SAC3C,CAAC;IACH,CAAC;CAmBD;AA3DD,sCA2DC"}
1
+ {"version":3,"file":"authorization.js","sourceRoot":"","sources":["../../../src/authorization/authorization.ts"],"names":[],"mappings":";;;AACA,kCAAuD;AA+CvD,MAAsB,aAGpB,SAAQ,WAAgB;IAWzB;;;;OAIG;IACI,KAAK,CAAC,YAAY,CACxB,OAAuC;QAEvC,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QAC5C,OAAO,MAAM,CAAC,OAAO,CAAC;IACvB,CAAC;IAED;;;;;OAKG;IACO,KAAK,CAAC,eAAe;IAC9B,6DAA6D;IAC7D,OAAuC;QAEvC,uCAAuC;QACvC,OAAO;YACN,OAAO,EAAE,KAAK;YACd,MAAM,EAAE,mCAAmC;SAC3C,CAAC;IACH,CAAC;CAmBD;AA5DD,sCA4DC"}
@@ -1 +1 @@
1
- export { Authorization, AuthorizationContext, AuthorizationOptions, AuthorizationResult, GrantPermissionOptions, RevokePermissionOptions, } from './authorization';
1
+ export { Authorization, AuthorizationSubject, AuthorizationRequirement, AuthorizationService, AuthorizationContext, AuthorizationOptions, AuthorizationResult, GrantPermissionOptions, RevokePermissionOptions, } from './authorization';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/authorization/index.ts"],"names":[],"mappings":";;;AAAA,iDAOyB;AANxB,8GAAA,aAAa,OAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/authorization/index.ts"],"names":[],"mappings":";;;AAAA,iDAUyB;AATxB,8GAAA,aAAa,OAAA"}
package/index.d.ts CHANGED
@@ -1,5 +1,3 @@
1
- export { encrypt, decrypt, Encryptor, Decryptor } from './crypto';
2
- export { KeyPairGenerator } from './keypair';
3
1
  export * from './auth';
4
2
  export * from './authentication';
5
3
  export * from './authorization';
package/index.js CHANGED
@@ -1,14 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.KeyPairGenerator = exports.Decryptor = exports.Encryptor = exports.decrypt = exports.encrypt = void 0;
4
3
  const tslib_1 = require("tslib");
5
- var crypto_1 = require("./crypto");
6
- Object.defineProperty(exports, "encrypt", { enumerable: true, get: function () { return crypto_1.encrypt; } });
7
- Object.defineProperty(exports, "decrypt", { enumerable: true, get: function () { return crypto_1.decrypt; } });
8
- Object.defineProperty(exports, "Encryptor", { enumerable: true, get: function () { return crypto_1.Encryptor; } });
9
- Object.defineProperty(exports, "Decryptor", { enumerable: true, get: function () { return crypto_1.Decryptor; } });
10
- var keypair_1 = require("./keypair");
11
- Object.defineProperty(exports, "KeyPairGenerator", { enumerable: true, get: function () { return keypair_1.KeyPairGenerator; } });
12
4
  tslib_1.__exportStar(require("./auth"), exports);
13
5
  tslib_1.__exportStar(require("./authentication"), exports);
14
6
  tslib_1.__exportStar(require("./authorization"), exports);
package/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAAA,mCAAkE;AAAzD,iGAAA,OAAO,OAAA;AAAE,iGAAA,OAAO,OAAA;AAAE,mGAAA,SAAS,OAAA;AAAE,mGAAA,SAAS,OAAA;AAC/C,qCAA6C;AAApC,2GAAA,gBAAgB,OAAA;AAEzB,iDAAuB;AACvB,2DAAiC;AACjC,0DAAgC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,iDAAuB;AACvB,2DAAiC;AACjC,0DAAgC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@riao/iam",
3
- "version": "3.3.0",
3
+ "version": "5.0.0",
4
4
  "description": "Identity Access Management for Riao",
5
5
  "typescript-template": {
6
6
  "base": "1.0.1",
@@ -9,10 +9,7 @@
9
9
  },
10
10
  "scripts": {},
11
11
  "dependencies": {
12
- "@riao/dbal": "^3.8.0",
13
- "bcrypt": "^6.0.0",
14
- "jsonwebtoken": "^9.0.3",
15
- "ms": "^2.1.3"
12
+ "@riao/dbal": "^3.12.0"
16
13
  },
17
14
  "repository": {
18
15
  "type": "git",
package/crypto.d.ts DELETED
@@ -1,16 +0,0 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- /// <reference types="node" />
4
- import * as crypto from 'crypto';
5
- export declare function encrypt(publicKey: crypto.KeyObject, data: string | Buffer): Buffer;
6
- export declare function decrypt(privateKey: crypto.KeyObject, encryptedData: Buffer): Buffer;
7
- export declare class Encryptor {
8
- private publicKey;
9
- constructor(publicKey: crypto.KeyObject);
10
- encrypt(data: string | Buffer): Buffer;
11
- }
12
- export declare class Decryptor {
13
- private privateKey;
14
- constructor(privateKey: crypto.KeyObject);
15
- decrypt(encryptedData: Buffer): Buffer;
16
- }
package/crypto.js DELETED
@@ -1,35 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Decryptor = exports.Encryptor = exports.decrypt = exports.encrypt = void 0;
4
- const tslib_1 = require("tslib");
5
- const crypto = tslib_1.__importStar(require("crypto"));
6
- function encrypt(publicKey, data) {
7
- data = Buffer.isBuffer(data) ? data : Buffer.from(data);
8
- return crypto.publicEncrypt(publicKey, data);
9
- }
10
- exports.encrypt = encrypt;
11
- function decrypt(privateKey, encryptedData) {
12
- return crypto.privateDecrypt(privateKey, encryptedData);
13
- }
14
- exports.decrypt = decrypt;
15
- class Encryptor {
16
- publicKey;
17
- constructor(publicKey) {
18
- this.publicKey = publicKey;
19
- }
20
- encrypt(data) {
21
- return encrypt(this.publicKey, data);
22
- }
23
- }
24
- exports.Encryptor = Encryptor;
25
- class Decryptor {
26
- privateKey;
27
- constructor(privateKey) {
28
- this.privateKey = privateKey;
29
- }
30
- decrypt(encryptedData) {
31
- return decrypt(this.privateKey, encryptedData);
32
- }
33
- }
34
- exports.Decryptor = Decryptor;
35
- //# sourceMappingURL=crypto.js.map
package/crypto.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../src/crypto.ts"],"names":[],"mappings":";;;;AAAA,uDAAiC;AAEjC,SAAgB,OAAO,CACtB,SAA2B,EAC3B,IAAqB;IAErB,IAAI,GAAG,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxD,OAAO,MAAM,CAAC,aAAa,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAC9C,CAAC;AAND,0BAMC;AAED,SAAgB,OAAO,CACtB,UAA4B,EAC5B,aAAqB;IAErB,OAAO,MAAM,CAAC,cAAc,CAAC,UAAU,EAAE,aAAa,CAAC,CAAC;AACzD,CAAC;AALD,0BAKC;AAED,MAAa,SAAS;IACb,SAAS,CAAmB;IAEpC,YAAY,SAA2B;QACtC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC5B,CAAC;IAED,OAAO,CAAC,IAAqB;QAC5B,OAAO,OAAO,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IACtC,CAAC;CACD;AAVD,8BAUC;AAED,MAAa,SAAS;IACb,UAAU,CAAmB;IAErC,YAAY,UAA4B;QACvC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC9B,CAAC;IAED,OAAO,CAAC,aAAqB;QAC5B,OAAO,OAAO,CAAC,IAAI,CAAC,UAAU,EAAE,aAAa,CAAC,CAAC;IAChD,CAAC;CACD;AAVD,8BAUC"}
package/hash.d.ts DELETED
@@ -1,5 +0,0 @@
1
- export declare class Hash {
2
- rounds: number;
3
- make(input: string, rounds?: number): Promise<string>;
4
- check(input: string, hashed: string): Promise<boolean>;
5
- }
package/hash.js DELETED
@@ -1,15 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Hash = void 0;
4
- const bcrypt_1 = require("bcrypt");
5
- class Hash {
6
- rounds = 12;
7
- async make(input, rounds) {
8
- return await (0, bcrypt_1.hash)(input, rounds || this.rounds);
9
- }
10
- async check(input, hashed) {
11
- return await (0, bcrypt_1.compare)(input, hashed);
12
- }
13
- }
14
- exports.Hash = Hash;
15
- //# sourceMappingURL=hash.js.map
package/hash.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"hash.js","sourceRoot":"","sources":["../../src/hash.ts"],"names":[],"mappings":";;;AAAA,mCAAuC;AAEvC,MAAa,IAAI;IACT,MAAM,GAAW,EAAE,CAAC;IAEpB,KAAK,CAAC,IAAI,CAAC,KAAa,EAAE,MAAe;QAC/C,OAAO,MAAM,IAAA,aAAI,EAAC,KAAK,EAAE,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC;IACjD,CAAC;IAEM,KAAK,CAAC,KAAK,CAAC,KAAa,EAAE,MAAc;QAC/C,OAAO,MAAM,IAAA,gBAAO,EAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACrC,CAAC;CACD;AAVD,oBAUC"}
package/jwt.d.ts DELETED
@@ -1,26 +0,0 @@
1
- /// <reference types="node" />
2
- import * as jwt from 'jsonwebtoken';
3
- import ms from 'ms';
4
- import { Secret, SecretAlgorithm } from './secret';
5
- import { KeyPair, KeyPairAlgorithm } from './keypair';
6
- import { KeyObject } from 'crypto';
7
- export type JwtPayload = Record<string, unknown>;
8
- export type JwtSigningOptions = Secret | KeyPair;
9
- export type JwtOptions = JwtSigningOptions & {
10
- expiresIn?: ms.StringValue;
11
- notBefore?: ms.StringValue;
12
- };
13
- export interface Token {
14
- token: string;
15
- }
16
- export declare class Jwt<TPayload extends JwtPayload = JwtPayload> {
17
- protected publicKey: KeyObject;
18
- protected privateKey: KeyObject;
19
- protected expiresIn?: ms.StringValue;
20
- protected notBefore?: ms.StringValue;
21
- protected algorithm?: SecretAlgorithm | KeyPairAlgorithm;
22
- constructor(options: JwtOptions);
23
- protected tokenOptions(): jwt.SignOptions;
24
- generateToken(data: TPayload, options?: jwt.SignOptions): Promise<Token>;
25
- decodeToken(token: string): Promise<TPayload>;
26
- }
package/jwt.js DELETED
@@ -1,49 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Jwt = void 0;
4
- const tslib_1 = require("tslib");
5
- const jwt = tslib_1.__importStar(require("jsonwebtoken"));
6
- const crypto_1 = require("crypto");
7
- class Jwt {
8
- publicKey;
9
- privateKey;
10
- expiresIn;
11
- notBefore;
12
- algorithm;
13
- constructor(options) {
14
- this.expiresIn = options.expiresIn ?? this.expiresIn;
15
- this.notBefore = options.notBefore ?? this.notBefore;
16
- this.algorithm = options.algorithm;
17
- if ('secret' in options && options.secret) {
18
- this.privateKey = this.publicKey = (0, crypto_1.createSecretKey)(Buffer.from(options.secret));
19
- }
20
- else if ('privateKey' in options && options.privateKey) {
21
- this.publicKey = options.publicKey;
22
- this.privateKey = options.privateKey;
23
- }
24
- }
25
- tokenOptions() {
26
- return {
27
- expiresIn: this.expiresIn ?? '15m',
28
- notBefore: this.notBefore ?? 1,
29
- algorithm: this.algorithm,
30
- };
31
- }
32
- async generateToken(data, options = {}) {
33
- options = {
34
- ...this.tokenOptions(),
35
- ...options,
36
- };
37
- const token = await jwt.sign(data, this.privateKey, options);
38
- return { token };
39
- }
40
- async decodeToken(token) {
41
- const result = await jwt.verify(token, this.publicKey);
42
- delete result['iat'];
43
- delete result['nbf'];
44
- delete result['exp'];
45
- return result;
46
- }
47
- }
48
- exports.Jwt = Jwt;
49
- //# sourceMappingURL=jwt.js.map
package/jwt.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"jwt.js","sourceRoot":"","sources":["../../src/jwt.ts"],"names":[],"mappings":";;;;AAAA,0DAAoC;AAKpC,mCAAoD;AAepD,MAAa,GAAG;IACL,SAAS,CAAY;IACrB,UAAU,CAAY;IAEtB,SAAS,CAAkB;IAC3B,SAAS,CAAkB;IAC3B,SAAS,CAAsC;IAEzD,YAAmB,OAAmB;QACrC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,IAAI,CAAC,SAAS,CAAC;QACrD,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,IAAI,CAAC,SAAS,CAAC;QACrD,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QAEnC,IAAI,QAAQ,IAAI,OAAO,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;YAC3C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,SAAS,GAAG,IAAA,wBAAe,EACjD,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAC3B,CAAC;QACH,CAAC;aACI,IAAI,YAAY,IAAI,OAAO,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;YACxD,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;YACnC,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;QACtC,CAAC;IACF,CAAC;IAES,YAAY;QACrB,OAAO;YACN,SAAS,EAAE,IAAI,CAAC,SAAS,IAAI,KAAK;YAClC,SAAS,EAAE,IAAI,CAAC,SAAS,IAAI,CAAC;YAC9B,SAAS,EAAE,IAAI,CAAC,SAAS;SACzB,CAAC;IACH,CAAC;IAEM,KAAK,CAAC,aAAa,CACzB,IAAc,EACd,UAA2B,EAAE;QAE7B,OAAO,GAAG;YACT,GAAG,IAAI,CAAC,YAAY,EAAE;YACtB,GAAG,OAAO;SACV,CAAC;QAEF,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAE7D,OAAO,EAAE,KAAK,EAAE,CAAC;IAClB,CAAC;IAEM,KAAK,CAAC,WAAW,CAAC,KAAa;QACrC,MAAM,MAAM,GAAa,MAAM,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;QAEjE,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;QACrB,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;QACrB,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;QAErB,OAAO,MAAM,CAAC;IACf,CAAC;CACD;AAvDD,kBAuDC"}
package/keypair.d.ts DELETED
@@ -1,24 +0,0 @@
1
- /// <reference types="node" />
2
- import * as crypto from 'crypto';
3
- export type KeyPairAlgorithm = 'RS256' | 'RS384' | 'RS512' | 'HS256' | 'ES256' | 'ES384' | 'ES512';
4
- export interface KeyPair {
5
- publicKey: crypto.KeyObject;
6
- privateKey: crypto.KeyObject;
7
- algorithm: KeyPairAlgorithm;
8
- }
9
- export declare class KeyPairGenerator {
10
- algorithm: KeyPairAlgorithm;
11
- constructor(options: {
12
- algorithm: KeyPairAlgorithm;
13
- });
14
- generate(): KeyPair;
15
- load(options: {
16
- publicKeyPath: string;
17
- privateKeyPath: string;
18
- }): Promise<KeyPair>;
19
- save(options: {
20
- keys: KeyPair;
21
- publicKeyPath: string;
22
- privateKeyPath: string;
23
- }): Promise<void>;
24
- }
package/keypair.js DELETED
@@ -1,71 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.KeyPairGenerator = void 0;
4
- const tslib_1 = require("tslib");
5
- const crypto = tslib_1.__importStar(require("crypto"));
6
- const promises_1 = require("fs/promises");
7
- class KeyPairGenerator {
8
- algorithm;
9
- constructor(options) {
10
- this.algorithm = options.algorithm;
11
- }
12
- generate() {
13
- let type = null;
14
- let modulusLength, namedCurve;
15
- if (this.algorithm === 'RS256') {
16
- type = 'rsa';
17
- modulusLength = 2048;
18
- }
19
- else if (this.algorithm === 'RS384') {
20
- type = 'rsa';
21
- modulusLength = 3072;
22
- }
23
- else if (this.algorithm === 'RS512') {
24
- type = 'rsa';
25
- modulusLength = 4096;
26
- }
27
- else if (this.algorithm === 'ES256') {
28
- type = 'ec';
29
- namedCurve = 'prime256v1';
30
- }
31
- else if (this.algorithm === 'ES384') {
32
- type = 'ec';
33
- namedCurve = 'secp384r1';
34
- }
35
- else if (this.algorithm === 'ES512') {
36
- type = 'ec';
37
- namedCurve = 'secp521r1';
38
- }
39
- if (type === null) {
40
- throw new Error('Keypair type could not be inferred');
41
- }
42
- const { publicKey, privateKey } = crypto.generateKeyPairSync(
43
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
44
- type, {
45
- modulusLength,
46
- namedCurve,
47
- });
48
- return {
49
- algorithm: this.algorithm,
50
- publicKey,
51
- privateKey,
52
- };
53
- }
54
- async load(options) {
55
- const publicKey = (await (0, promises_1.readFile)(options.publicKeyPath)).toString();
56
- const privateKey = (await (0, promises_1.readFile)(options.privateKeyPath)).toString();
57
- return {
58
- algorithm: this.algorithm,
59
- publicKey: crypto.createPublicKey(publicKey),
60
- privateKey: crypto.createPrivateKey(privateKey),
61
- };
62
- }
63
- async save(options) {
64
- const publicKey = options.keys.publicKey;
65
- const privateKey = options.keys.privateKey;
66
- await (0, promises_1.writeFile)(options.publicKeyPath, publicKey.export({ format: 'pem', type: 'spki' }));
67
- await (0, promises_1.writeFile)(options.privateKeyPath, privateKey.export({ format: 'pem', type: 'pkcs8' }));
68
- }
69
- }
70
- exports.KeyPairGenerator = KeyPairGenerator;
71
- //# sourceMappingURL=keypair.js.map
package/keypair.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"keypair.js","sourceRoot":"","sources":["../../src/keypair.ts"],"names":[],"mappings":";;;;AAAA,uDAAiC;AACjC,0CAAkD;AAiBlD,MAAa,gBAAgB;IACrB,SAAS,CAAmB;IAEnC,YAAmB,OAAwC;QAC1D,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;IACpC,CAAC;IAEM,QAAQ;QACd,IAAI,IAAI,GAAwB,IAAI,CAAC;QACrC,IAAI,aAAa,EAAE,UAAU,CAAC;QAE9B,IAAI,IAAI,CAAC,SAAS,KAAK,OAAO,EAAE,CAAC;YAChC,IAAI,GAAG,KAAK,CAAC;YACb,aAAa,GAAG,IAAI,CAAC;QACtB,CAAC;aACI,IAAI,IAAI,CAAC,SAAS,KAAK,OAAO,EAAE,CAAC;YACrC,IAAI,GAAG,KAAK,CAAC;YACb,aAAa,GAAG,IAAI,CAAC;QACtB,CAAC;aACI,IAAI,IAAI,CAAC,SAAS,KAAK,OAAO,EAAE,CAAC;YACrC,IAAI,GAAG,KAAK,CAAC;YACb,aAAa,GAAG,IAAI,CAAC;QACtB,CAAC;aACI,IAAI,IAAI,CAAC,SAAS,KAAK,OAAO,EAAE,CAAC;YACrC,IAAI,GAAG,IAAI,CAAC;YACZ,UAAU,GAAG,YAAY,CAAC;QAC3B,CAAC;aACI,IAAI,IAAI,CAAC,SAAS,KAAK,OAAO,EAAE,CAAC;YACrC,IAAI,GAAG,IAAI,CAAC;YACZ,UAAU,GAAG,WAAW,CAAC;QAC1B,CAAC;aACI,IAAI,IAAI,CAAC,SAAS,KAAK,OAAO,EAAE,CAAC;YACrC,IAAI,GAAG,IAAI,CAAC;YACZ,UAAU,GAAG,WAAW,CAAC;QAC1B,CAAC;QAED,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;QACvD,CAAC;QAED,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,MAAM,CAAC,mBAAmB;QAC3D,8DAA8D;QAC9D,IAAW,EACX;YACC,aAAa;YACb,UAAU;SACV,CACD,CAAC;QAEF,OAAO;YACN,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,SAAS;YACT,UAAU;SACV,CAAC;IACH,CAAC;IAEM,KAAK,CAAC,IAAI,CAAC,OAGjB;QACA,MAAM,SAAS,GAAG,CAAC,MAAM,IAAA,mBAAQ,EAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;QACrE,MAAM,UAAU,GAAG,CAAC,MAAM,IAAA,mBAAQ,EAAC,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;QAEvE,OAAO;YACN,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,SAAS,EAAE,MAAM,CAAC,eAAe,CAAC,SAAS,CAAC;YAC5C,UAAU,EAAE,MAAM,CAAC,gBAAgB,CAAC,UAAU,CAAC;SAC/C,CAAC;IACH,CAAC;IAEM,KAAK,CAAC,IAAI,CAAC,OAIjB;QACA,MAAM,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC;QACzC,MAAM,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC;QAE3C,MAAM,IAAA,oBAAS,EACd,OAAO,CAAC,aAAa,EACrB,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CACjD,CAAC;QACF,MAAM,IAAA,oBAAS,EACd,OAAO,CAAC,cAAc,EACtB,UAAU,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CACnD,CAAC;IACH,CAAC;CACD;AAvFD,4CAuFC"}
package/secret.d.ts DELETED
@@ -1,5 +0,0 @@
1
- export type SecretAlgorithm = 'HS256' | 'HS384' | 'HS512';
2
- export interface Secret {
3
- secret: string;
4
- algorithm: SecretAlgorithm;
5
- }
package/secret.js DELETED
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=secret.js.map
package/secret.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"secret.js","sourceRoot":"","sources":["../../src/secret.ts"],"names":[],"mappings":""}