@3d-outlet/passport 1.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/README.md ADDED
@@ -0,0 +1,171 @@
1
+ <div align="center">
2
+
3
+ # 🔑 @3d-outlet/passport
4
+
5
+ **Token-based Authentication Module for 3D OUTLET Microservices**
6
+
7
+ [![npm version](https://img.shields.io/npm/v/@3d-outlet/passport?style=for-the-badge)](https://www.npmjs.com/package/@3d-outlet/passport)
8
+ [![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg?style=for-the-badge)](https://opensource.org/licenses/ISC)
9
+
10
+ </div>
11
+
12
+ ---
13
+
14
+ ## ✨ Features
15
+
16
+ - 🛡️ **Secure Token Generation** - Creates HMAC-based tokens considering `userId`, `issuedAt`, and `expiresAt`.
17
+ - 🔑 **Reliable Token Verification** - Authenticates and validates token expiration using constant-time comparison.
18
+ - 🚀 **NestJS Integration** - Easy integration into NestJS applications using `PassportModule`.
19
+ - 🔄 **Flexible Configuration** - Supports synchronous and asynchronous module configuration.
20
+ - 🔐 **Encoding and Decoding** - Built-in utilities for Base64 URL encoding/decoding and cryptographic operations.
21
+
22
+ ---
23
+
24
+ ## 📦 Installation
25
+
26
+ ```bash
27
+ npm install @3d-outlet/passport
28
+ # or
29
+ pnpm add @3d-outlet/passport
30
+ # or
31
+ yarn add @3d-outlet/passport
32
+ # or
33
+ bun add @3d-outlet/passport
34
+ ```
35
+
36
+ ---
37
+
38
+ ## 🚀 Quick Start
39
+
40
+ ### Module Registration
41
+
42
+ #### Synchronous Registration
43
+
44
+ ```typescript
45
+ import { Module } from '@nestjs/common'
46
+ import { PassportModule } from '@3d-outlet/passport'
47
+
48
+ @Module({
49
+ imports: [
50
+ PassportModule.register({
51
+ secretKey: 'YOUR_VERY_SECRET_KEY', // Replace with your secret key
52
+ }),
53
+ ],
54
+ })
55
+ export class AppModule {}
56
+ ```
57
+
58
+ #### Asynchronous Registration
59
+
60
+ ```typescript
61
+ import { Module } from '@nestjs/common'
62
+ import { PassportModule } from '@3d-outlet/passport'
63
+ import { ConfigModule, ConfigService } from '@nestjs/config'
64
+
65
+ @Module({
66
+ imports: [
67
+ PassportModule.registerAsync({
68
+ imports: [ConfigModule],
69
+ useFactory: async (configService: ConfigService) => ({
70
+ secretKey: configService.get<string>('PASSPORT_SECRET_KEY'),
71
+ }),
72
+ inject: [ConfigService],
73
+ }),
74
+ ],
75
+ })
76
+ export class AppModule {}
77
+ ```
78
+
79
+ ### Using `PassportService`
80
+
81
+ ```typescript
82
+ import { Injectable } from '@nestjs/common'
83
+ import { PassportService } from '@3d-outlet/passport'
84
+
85
+ @Injectable()
86
+ export class AuthService {
87
+ constructor(private readonly passportService: PassportService) {}
88
+
89
+ async login(userId: string) {
90
+ const ttl = 3600 // Token expiration in seconds (1 hour)
91
+ const token = this.passportService.generate(userId, ttl)
92
+ return { token }
93
+ }
94
+
95
+ async verifyToken(token: string) {
96
+ const result = this.passportService.verify(token)
97
+ if (!result.valid) {
98
+ console.error('Invalid token:', result.reason)
99
+ return null
100
+ }
101
+ console.log('User:', result.userId)
102
+ return result.userId
103
+ }
104
+ }
105
+ ```
106
+
107
+ ---
108
+
109
+ ## 📁 Project Structure
110
+
111
+ ```
112
+ passport/
113
+ ├── lib/ # TypeScript source files
114
+ │ ├── constants/ # Passport module constants
115
+ │ ├── interfaces/ # Interfaces for module options and tokens
116
+ │ ├── utils/ # Utility functions (Base64, Crypto)
117
+ │ ├── passport.module.ts # Main NestJS Passport module
118
+ │ ├── passport.providers.ts # Module configuration providers
119
+ │ └── passport.service.ts # Service for token generation and verification
120
+ └── dist/ # Compiled JavaScript (after build)
121
+ ```
122
+
123
+ ---
124
+
125
+ ## 🛠️ Development
126
+
127
+ ### Prerequisites
128
+
129
+ - **Node.js**: >= 16.0.0
130
+ - **TypeScript**: ^5.9.3
131
+
132
+ ### Building the Package
133
+
134
+ ```bash
135
+ # Install dependencies
136
+ npm install
137
+ # или
138
+ pnpm install
139
+ # или
140
+ bun install
141
+
142
+ # Build TypeScript
143
+ npm run build
144
+ ```
145
+
146
+ ---
147
+
148
+ ## 📝 License
149
+
150
+ ISC © [TeaCoder](mailto:admin@teacoder.ru) & [Ilnaz Mingaleev](mailto:development@teamkaif.com)
151
+
152
+ ---
153
+
154
+ ## 👨‍💻 Authors
155
+
156
+ **TeaCoder (Vadim)**
157
+
158
+ - Email: [admin@teacoder.ru](mailto:admin@teacoder.ru)
159
+
160
+ **Ilnaz Mingaleev**
161
+
162
+ - Email: [development@teamkaif.com](mailto:development@teamkaif.com)
163
+
164
+ ---
165
+
166
+ <div align="center">
167
+
168
+ **Made with ❤️ for the 3D OUTLET project (private repo)**
169
+ Internal use only.
170
+
171
+ </div>
@@ -0,0 +1 @@
1
+ export * from './passport.constants';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./passport.constants"), exports);
@@ -0,0 +1 @@
1
+ export declare const PASSPORT_OPTIONS: unique symbol;
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PASSPORT_OPTIONS = void 0;
4
+ exports.PASSPORT_OPTIONS = Symbol('PassportOptions');
@@ -0,0 +1,3 @@
1
+ export * from './interfaces';
2
+ export * from './passport.module';
3
+ export * from './passport.service';
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./interfaces"), exports);
18
+ __exportStar(require("./passport.module"), exports);
19
+ __exportStar(require("./passport.service"), exports);
@@ -0,0 +1,3 @@
1
+ export * from './passport-options.interface';
2
+ export * from './passport-async-options.interface';
3
+ export * from './token.interface';
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./passport-options.interface"), exports);
18
+ __exportStar(require("./passport-async-options.interface"), exports);
19
+ __exportStar(require("./token.interface"), exports);
@@ -0,0 +1,6 @@
1
+ import type { FactoryProvider, ModuleMetadata } from '@nestjs/common';
2
+ import type { PassportOptions } from './passport-options.interface';
3
+ export interface PassportAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
4
+ useFactory: (...args: any[]) => Promise<PassportOptions> | PassportOptions;
5
+ inject?: FactoryProvider['inject'];
6
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,3 @@
1
+ export interface PassportOptions {
2
+ secretKey: string;
3
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,8 @@
1
+ export interface TokenPayload {
2
+ sub: string | number;
3
+ }
4
+ export interface VerifyResult {
5
+ valid: boolean;
6
+ reason?: string;
7
+ userId?: string;
8
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,6 @@
1
+ import { type DynamicModule } from '@nestjs/common';
2
+ import type { PassportAsyncOptions, PassportOptions } from './interfaces';
3
+ export declare class PassportModule {
4
+ static register(options: PassportOptions): DynamicModule;
5
+ static registerAsync(options: PassportAsyncOptions): DynamicModule;
6
+ }
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var PassportModule_1;
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.PassportModule = void 0;
11
+ const common_1 = require("@nestjs/common");
12
+ const constants_1 = require("./constants");
13
+ const passport_providers_1 = require("./passport.providers");
14
+ const passport_service_1 = require("./passport.service");
15
+ let PassportModule = PassportModule_1 = class PassportModule {
16
+ static register(options) {
17
+ const optionsProvider = (0, passport_providers_1.createPassportOptionsProvider)(options);
18
+ return {
19
+ module: PassportModule_1,
20
+ providers: [optionsProvider, passport_service_1.PassportService],
21
+ exports: [passport_service_1.PassportService, constants_1.PASSPORT_OPTIONS]
22
+ };
23
+ }
24
+ static registerAsync(options) {
25
+ const optionsProvider = (0, passport_providers_1.createPassportAsyncOptionsProvider)(options);
26
+ return {
27
+ module: PassportModule_1,
28
+ imports: options.imports ?? [],
29
+ providers: [optionsProvider, passport_service_1.PassportService],
30
+ exports: [passport_service_1.PassportService, constants_1.PASSPORT_OPTIONS]
31
+ };
32
+ }
33
+ };
34
+ exports.PassportModule = PassportModule;
35
+ exports.PassportModule = PassportModule = PassportModule_1 = __decorate([
36
+ (0, common_1.Global)(),
37
+ (0, common_1.Module)({})
38
+ ], PassportModule);
@@ -0,0 +1,4 @@
1
+ import type { Provider } from '@nestjs/common';
2
+ import type { PassportAsyncOptions, PassportOptions } from './interfaces';
3
+ export declare function createPassportOptionsProvider(options: PassportOptions): Provider;
4
+ export declare function createPassportAsyncOptionsProvider(options: PassportAsyncOptions): Provider;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPassportOptionsProvider = createPassportOptionsProvider;
4
+ exports.createPassportAsyncOptionsProvider = createPassportAsyncOptionsProvider;
5
+ const constants_1 = require("./constants");
6
+ function createPassportOptionsProvider(options) {
7
+ return {
8
+ provide: constants_1.PASSPORT_OPTIONS,
9
+ useValue: Object.freeze({ ...options })
10
+ };
11
+ }
12
+ function createPassportAsyncOptionsProvider(options) {
13
+ return {
14
+ provide: constants_1.PASSPORT_OPTIONS,
15
+ useFactory: async (...args) => {
16
+ const resolved = await options.useFactory(...args);
17
+ if (!resolved || typeof resolved.secretKey !== 'string') {
18
+ throw new Error('[PassportModule] "secretKey" is required and must be a string');
19
+ }
20
+ return Object.freeze({ ...resolved });
21
+ },
22
+ inject: options.inject ?? []
23
+ };
24
+ }
@@ -0,0 +1,21 @@
1
+ import { PassportOptions } from './interfaces';
2
+ export declare class PassportService {
3
+ private readonly options;
4
+ private readonly SECRET_KEY;
5
+ private static readonly HMAC_DOMAIN;
6
+ private static readonly INTERNAL_SEP;
7
+ constructor(options: PassportOptions);
8
+ generate(userId: string, ttl: number): string;
9
+ verify(token: string): {
10
+ valid: boolean;
11
+ reason: string;
12
+ userId?: undefined;
13
+ } | {
14
+ valid: boolean;
15
+ userId: string;
16
+ reason?: undefined;
17
+ };
18
+ private now;
19
+ private serialize;
20
+ private computeHmac;
21
+ }
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var PassportService_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.PassportService = void 0;
17
+ const common_1 = require("@nestjs/common");
18
+ const crypto_1 = require("crypto");
19
+ const constants_1 = require("./constants");
20
+ const utils_1 = require("./utils");
21
+ let PassportService = class PassportService {
22
+ static { PassportService_1 = this; }
23
+ options;
24
+ SECRET_KEY;
25
+ static HMAC_DOMAIN = 'PassportTokenAuth/v1';
26
+ static INTERNAL_SEP = '|';
27
+ constructor(options) {
28
+ this.options = options;
29
+ this.SECRET_KEY = options.secretKey;
30
+ }
31
+ generate(userId, ttl) {
32
+ const issuedAt = this.now();
33
+ const expiresAt = issuedAt + ttl;
34
+ const userPart = (0, utils_1.base64UrlEncode)(userId);
35
+ const iatPart = (0, utils_1.base64UrlEncode)(String(issuedAt));
36
+ const expPart = (0, utils_1.base64UrlEncode)(String(expiresAt));
37
+ const serialized = this.serialize(userPart, iatPart, expPart);
38
+ const mac = this.computeHmac(this.SECRET_KEY, serialized);
39
+ return `${userPart}.${iatPart}.${expPart}.${mac}`;
40
+ }
41
+ verify(token) {
42
+ const parts = token.split('.');
43
+ if (parts.length !== 4)
44
+ return { valid: false, reason: 'Invalid format' };
45
+ const [userPart, iatPart, expPart, mac] = parts;
46
+ const serialized = this.serialize(userPart, iatPart, expPart);
47
+ const expectedMac = this.computeHmac(this.SECRET_KEY, serialized);
48
+ if (!(0, utils_1.constantTimeEqual)(expectedMac, mac))
49
+ return { valid: false, reason: 'Invalid signature' };
50
+ const expNumber = Number((0, utils_1.base64UrlDecode)(expPart));
51
+ if (!Number.isFinite(expNumber))
52
+ return { valid: false, reason: 'Error' };
53
+ if (this.now() > expNumber)
54
+ return { valid: false, reason: 'Expired' };
55
+ return { valid: true, userId: (0, utils_1.base64UrlDecode)(userPart) };
56
+ }
57
+ now() {
58
+ return Math.floor(Date.now() / 1000);
59
+ }
60
+ serialize(user, iat, exp) {
61
+ return [PassportService_1.HMAC_DOMAIN, user, iat, exp].join(PassportService_1.INTERNAL_SEP);
62
+ }
63
+ computeHmac(secretKey, data) {
64
+ return (0, crypto_1.createHmac)('sha256', secretKey).update(data).digest('hex');
65
+ }
66
+ };
67
+ exports.PassportService = PassportService;
68
+ exports.PassportService = PassportService = PassportService_1 = __decorate([
69
+ (0, common_1.Injectable)(),
70
+ __param(0, (0, common_1.Inject)(constants_1.PASSPORT_OPTIONS)),
71
+ __metadata("design:paramtypes", [Object])
72
+ ], PassportService);
@@ -0,0 +1,2 @@
1
+ export declare function base64UrlEncode(buf: Buffer | string): string;
2
+ export declare function base64UrlDecode(str: string): string;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.base64UrlEncode = base64UrlEncode;
4
+ exports.base64UrlDecode = base64UrlDecode;
5
+ function base64UrlEncode(buf) {
6
+ const s = typeof buf === 'string' ? Buffer.from(buf) : buf;
7
+ return s
8
+ .toString('base64')
9
+ .replace(/\+/g, '-')
10
+ .replace(/\//g, '_')
11
+ .replace(/=+$/, '');
12
+ }
13
+ function base64UrlDecode(str) {
14
+ str = str.replace(/-/g, '+').replace(/_/g, '/');
15
+ while (str.length % 4)
16
+ str += '=';
17
+ return Buffer.from(str, 'base64').toString();
18
+ }
@@ -0,0 +1 @@
1
+ export declare function constantTimeEqual(a: string, b: string): boolean;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.constantTimeEqual = constantTimeEqual;
4
+ const crypto_1 = require("crypto");
5
+ function constantTimeEqual(a, b) {
6
+ const bufA = Buffer.from(a);
7
+ const bufB = Buffer.from(b);
8
+ if (bufA.length !== bufB.length)
9
+ return false;
10
+ return (0, crypto_1.timingSafeEqual)(bufA, bufB);
11
+ }
@@ -0,0 +1,2 @@
1
+ export * from './base64';
2
+ export * from './crypto';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./base64"), exports);
18
+ __exportStar(require("./crypto"), exports);
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@3d-outlet/passport",
3
+ "version": "1.0.0",
4
+ "description": "Lightweight Face3D authentication library",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "scripts": {
14
+ "build": "tsc -p tsconfig.build.json",
15
+ "format": "prettier --write \"lib/**/*.ts\""
16
+ },
17
+ "keywords": [],
18
+ "author": "",
19
+ "license": "ISC",
20
+ "type": "commonjs",
21
+ "devDependencies": {
22
+ "@3d-outlet/core": "^1.0.2",
23
+ "@types/node": "^24.10.1",
24
+ "prettier": "^3.7.3",
25
+ "typescript": "^5.9.3"
26
+ },
27
+ "dependencies": {
28
+ "@nestjs/common": "^11.1.9",
29
+ "@nestjs/core": "^11.1.9",
30
+ "reflect-metadata": "^0.2.2",
31
+ "txjs": "^0.1.1"
32
+ }
33
+ }