@coolsiarh/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.
@@ -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 './possport-options.interface';
2
+ export * from './possport-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("./possport-options.interface"), exports);
18
+ __exportStar(require("./possport-async-options.interface"), exports);
19
+ __exportStar(require("./token.interface"), exports);
@@ -0,0 +1,6 @@
1
+ import { FactoryProvider, ModuleMetadata } from '@nestjs/common';
2
+ import type { PossportOptions } from './possport-options.interface';
3
+ export interface PossportAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
4
+ useFactory: (...args: any[]) => Promise<PossportOptions> | PossportOptions;
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 PossportOptions {
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,7 @@
1
+ import { PossportOptions } from './interfaces/possport-options.interface';
2
+ import { DynamicModule } from '@nestjs/common';
3
+ import { PossportAsyncOptions } from './interfaces';
4
+ export declare class PassportModule {
5
+ static register(options: PossportOptions): DynamicModule;
6
+ static registerAsync(options: PossportAsyncOptions): DynamicModule;
7
+ }
@@ -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 constants_1 = require("./utils/constants");
12
+ const common_1 = require("@nestjs/common");
13
+ const passport_service_1 = require("./passport.service");
14
+ const possport_providers_1 = require("./possport.providers");
15
+ let PassportModule = PassportModule_1 = class PassportModule {
16
+ static register(options) {
17
+ const optionsProvider = (0, possport_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 asyncOptionsProvider = (0, possport_providers_1.createPassportAsyncOptionsProvider)(options);
26
+ return {
27
+ module: PassportModule_1,
28
+ imports: options.imports || [],
29
+ providers: [asyncOptionsProvider, 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,21 @@
1
+ import { PossportOptions } 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: PossportOptions);
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,104 @@
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 node_crypto_1 = require("node:crypto");
18
+ const constants_1 = require("./utils/constants");
19
+ const common_1 = require("@nestjs/common");
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 = this.options.secretKey;
30
+ }
31
+ generate(userId, ttl) {
32
+ const issuedAt = this.now();
33
+ const expiresAt = issuedAt + ttl;
34
+ //dXNlcjEyMwkJCQ
35
+ const userPart = (0, utils_1.base64UrlEncode)(userId);
36
+ console.log('userPart:', userPart);
37
+ //MTc2ODcyMjY3Mg
38
+ const iatPart = (0, utils_1.base64UrlEncode)(String(issuedAt));
39
+ console.log('iatPart:', iatPart);
40
+ //MTc2ODc1ODg2OQ
41
+ const expPart = (0, utils_1.base64UrlEncode)(String(expiresAt));
42
+ console.log('expPart:', expPart);
43
+ //dXNlcjEyMwkJCQ|MTc2ODcyMjY3Mg|MTc2ODc1ODg2OQ
44
+ const serialized = this.serialize(userPart, iatPart, expPart);
45
+ console.log('serialized:', serialized);
46
+ //1e9f20ab540607c8f3c747a795f488ba4db9416a681807481d71abc32e66dcf6
47
+ const mac = this.computeHmac(this.SECRET_KEY, serialized);
48
+ console.log('mac:', mac);
49
+ //dXNlcjEyMwkJCQ.MTc2ODcyMjY3Mg.MTc2ODc1ODg2OQ.1e9f20ab540607c8f3c747a795f488ba4db9416a681807481d71abc32e66dcf6
50
+ const token = `${userPart}.${iatPart}.${expPart}.${mac}`;
51
+ return token;
52
+ }
53
+ verify(token) {
54
+ const parts = token.split('.');
55
+ if (parts.length !== 4) {
56
+ return { valid: false, reason: 'Invalid token format' };
57
+ }
58
+ const [userPart, iatPart, expPart, mac] = parts;
59
+ const serialized = this.serialize(userPart, iatPart, expPart);
60
+ const computedMac = this.computeHmac(this.SECRET_KEY, serialized);
61
+ if (!(0, utils_1.constantTimeCompare)(computedMac, mac)) {
62
+ return { valid: false, reason: 'Invalid token signature' };
63
+ }
64
+ const expNumber = Number((0, utils_1.base64UrlDecode)(expPart));
65
+ if (this.now() > expNumber) {
66
+ return { valid: false, reason: 'Token has expired' };
67
+ }
68
+ return {
69
+ valid: true,
70
+ userId: (0, utils_1.base64UrlDecode)(userPart)
71
+ };
72
+ }
73
+ now() {
74
+ return Math.floor(Date.now() / 1000);
75
+ }
76
+ serialize(user, iat, exp) {
77
+ return [PassportService_1.HMAC_DOMAIN, user, iat, exp].join(PassportService_1.INTERNAL_SEP);
78
+ }
79
+ // signature of token:f49cf057cd4de7c1a4cb0b051570372892674487333ac5ab3ea603f29aec9ffe
80
+ computeHmac(secretKey, data) {
81
+ return (0, node_crypto_1.createHmac)('sha256', secretKey).update(data).digest('hex');
82
+ }
83
+ };
84
+ exports.PassportService = PassportService;
85
+ exports.PassportService = PassportService = PassportService_1 = __decorate([
86
+ (0, common_1.Injectable)(),
87
+ __param(0, (0, common_1.Inject)(constants_1.PASSPORT_OPTIONS)),
88
+ __metadata("design:paramtypes", [Object])
89
+ ], PassportService);
90
+ /* // Example usage:
91
+ const SECRET_KEY = 'mysecret'
92
+ const PassportServiceInstance = new PassportService()
93
+ const { generate, verify } = PassportServiceInstance
94
+ console.log('GENERATED_TOKEN:', generate('sk', 1000000))
95
+
96
+ console.log('---------------------')
97
+
98
+ console.log(
99
+ 'USER_FROM_TOKEN:',
100
+ verify(
101
+ 'c2s.MTc2ODcyNjQ0NQ.MTc2OTcyNjQ0NQ.a67e30d676ed4757cc3f1665f71c226d76c5f98553bc2c73132cb42ade73c655'
102
+ )
103
+ )
104
+ */
@@ -0,0 +1,4 @@
1
+ import { Provider } from '@nestjs/common';
2
+ import { PossportAsyncOptions, PossportOptions } from './interfaces';
3
+ export declare function createPassportOptionsProvider(options: PossportOptions): Provider;
4
+ export declare function createPassportAsyncOptionsProvider(options: PossportAsyncOptions): 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("./utils/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,2 @@
1
+ export declare function base64UrlEncode(buf: Buffer | string): string;
2
+ export declare function base64UrlDecode(str: string): string;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.base64UrlEncode = base64UrlEncode;
4
+ exports.base64UrlDecode = base64UrlDecode;
5
+ function base64UrlEncode(buf) {
6
+ const buffer = typeof buf === 'string' ? Buffer.from(buf) : buf;
7
+ return buffer
8
+ .toString('base64')
9
+ .replace(/\+/g, '-')
10
+ .replace(/\//g, '_')
11
+ .replace(/=+/g, '');
12
+ }
13
+ function base64UrlDecode(str) {
14
+ if (!str || typeof str !== 'string') {
15
+ throw new Error('Invalid base64url string');
16
+ }
17
+ let decoded = str.replace(/-/g, '+').replace(/_/g, '/');
18
+ while (decoded.length % 4) {
19
+ decoded += '=';
20
+ }
21
+ return Buffer.from(decoded, 'base64').toString();
22
+ }
@@ -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,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PASSPORT_OPTIONS = void 0;
4
+ //DI key
5
+ exports.PASSPORT_OPTIONS = Symbol('PASSPORT_OPTIONS');
@@ -0,0 +1 @@
1
+ export declare function constantTimeCompare(a: Buffer | string, b: Buffer | string): boolean;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.constantTimeCompare = constantTimeCompare;
4
+ const crypto_1 = require("crypto");
5
+ function constantTimeCompare(a, b) {
6
+ const bufferA = Buffer.isBuffer(a) ? a : Buffer.from(a);
7
+ const bufferB = Buffer.isBuffer(b) ? b : Buffer.from(b);
8
+ if (bufferA.length !== bufferB.length) {
9
+ return false;
10
+ }
11
+ return (0, crypto_1.timingSafeEqual)(bufferA, bufferB);
12
+ }
@@ -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,34 @@
1
+ {
2
+ "name": "@coolsiarh/passport",
3
+ "version": "1.0.0",
4
+ "description": "Lightweight authentication module for NestJS applications.",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "scripts": {
11
+ "build": "tsc -p tsconfig.build.json",
12
+ "format": "prettier --write \"./lib/**/*.ts\""
13
+ },
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "keywords": [],
18
+ "author": "",
19
+ "license": "ISC",
20
+ "type": "commonjs",
21
+ "devDependencies": {
22
+ "@coolsiarh/core": "^1.0.5",
23
+ "@types/node": "^25.0.9",
24
+ "prettier": "^3.8.0",
25
+ "ts-node": "^10.9.2",
26
+ "typescript": "^5.9.3"
27
+ },
28
+ "dependencies": {
29
+ "@nestjs/common": "^11.1.12",
30
+ "@nestjs/core": "^11.1.12",
31
+ "reflect-metadata": "^0.2.2",
32
+ "rxjs": "^7.8.2"
33
+ }
34
+ }