@dimgit9/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,30 @@
1
+ name: Publish
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ jobs:
9
+ publish:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - name: Checkout repository
13
+ uses: actions/checkout@v4
14
+
15
+ - name: Setup Node.js
16
+ uses: actions/setup-node@v4
17
+ with:
18
+ node-version: 20
19
+ registry-url: "https://registry.npmjs.org"
20
+
21
+ - name: Install deps
22
+ run: npm install --frozen-lockfile
23
+
24
+ - name: Build
25
+ run: npm run build
26
+
27
+ - name: Publish Package
28
+ run: npm publish
29
+ env:
30
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
@@ -0,0 +1 @@
1
+ export const PASSPORT_OPTIONS_KEY = Symbol("PassportOptions")
package/lib/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./interfaces"
2
+
3
+ export * from "./passport.module"
4
+ export * from "./passport.service"
@@ -0,0 +1,3 @@
1
+ export * from "./passport-async-options.interface"
2
+ export * from "./passport-options.interface"
3
+ export * from "./token.interface"
@@ -0,0 +1,7 @@
1
+ import { FactoryProvider, ModuleMetadata } from "@nestjs/common"
2
+ import { PassportOptions } from "./passport-options.interface"
3
+
4
+ export interface PassportAsyncOptions extends Pick<ModuleMetadata, "imports"> {
5
+ useFactory: (...args: any[]) => Promise<PassportOptions> | PassportOptions
6
+ inject?: FactoryProvider["inject"]
7
+ }
@@ -0,0 +1,4 @@
1
+ export interface PassportOptions {
2
+ secretKey: string
3
+ }
4
+
@@ -0,0 +1,9 @@
1
+ export interface TokenPayload {
2
+ sub: string | number
3
+ }
4
+
5
+ export interface VerifyResult {
6
+ valid: boolean
7
+ reason?: string
8
+ userId?: string
9
+ }
@@ -0,0 +1,33 @@
1
+ import { DynamicModule, Global, Module } from "@nestjs/common"
2
+ import { PassportAsyncOptions, PassportOptions } from "./interfaces"
3
+ import {
4
+ createPassportAsyncOptionsProvider,
5
+ createPassportOptionsProvider,
6
+ } from "./passport.providers"
7
+ import { PassportService } from "./passport.service"
8
+ import { PASSPORT_OPTIONS_KEY } from "./constants/passport.contants"
9
+
10
+ @Global()
11
+ @Module({})
12
+ export class PassportModule {
13
+ static register(options: PassportOptions): DynamicModule {
14
+ const optionsProvider = createPassportOptionsProvider(options)
15
+
16
+ return {
17
+ module: PassportModule,
18
+ providers: [optionsProvider, PassportService],
19
+ exports: [PassportService, PASSPORT_OPTIONS_KEY],
20
+ }
21
+ }
22
+
23
+ static registerAsync(options: PassportAsyncOptions): DynamicModule {
24
+ const optionsProvider = createPassportAsyncOptionsProvider(options)
25
+
26
+ return {
27
+ module: PassportModule,
28
+ imports: options.imports ?? [],
29
+ providers: [optionsProvider, PassportService],
30
+ exports: [PassportService, PASSPORT_OPTIONS_KEY],
31
+ }
32
+ }
33
+ }
@@ -0,0 +1,32 @@
1
+ import { type Provider } from "@nestjs/common"
2
+ import { PassportAsyncOptions, type PassportOptions } from "./interfaces"
3
+ import { PASSPORT_OPTIONS_KEY } from "./constants/passport.contants"
4
+
5
+ export function createPassportOptionsProvider(
6
+ options: PassportOptions,
7
+ ): Provider {
8
+ return {
9
+ provide: PASSPORT_OPTIONS_KEY,
10
+ useValue: Object.freeze({ ...options }),
11
+ }
12
+ }
13
+
14
+ export function createPassportAsyncOptionsProvider(
15
+ options: PassportAsyncOptions,
16
+ ): Provider {
17
+ return {
18
+ provide: PASSPORT_OPTIONS_KEY,
19
+ useFactory: async (...args: any[]) => {
20
+ const resolved = await options.useFactory!(...args)
21
+
22
+ if (!resolved || typeof resolved.secretKey != "string") {
23
+ throw new Error(
24
+ '[PassportModule]: "secretKey" is required and must be a string',
25
+ )
26
+ }
27
+
28
+ return Object.freeze({ ...options })
29
+ },
30
+ inject: options.inject ?? [],
31
+ }
32
+ }
@@ -0,0 +1,94 @@
1
+ import { createHmac } from "node:crypto"
2
+ import { base64UrlDecode, base64UrlEncode, constantTimeEqual } from "./utils"
3
+ import { Inject, Injectable } from "@nestjs/common"
4
+ import { PASSPORT_OPTIONS_KEY } from "./constants/passport.contants"
5
+ import { PassportOptions } from "./interfaces"
6
+
7
+ // console.log("GENERATED TOKEN: ", generateToken("123", "user-123", 1))
8
+
9
+ // console.log(
10
+ // "VERIFY TOKEN: ",
11
+ // verifyToken(
12
+ // "123",
13
+ // "dXNlci0xMjM.MTc3MTQ3MjI4OQ.MTc3MTQ3MjI5MA.3077b9755ab7f77d997120ba148bb129dcecc1a1fa3ee9def5cc93bc3128b590",
14
+ // ),
15
+ // )
16
+
17
+ @Injectable()
18
+ export class PassportService {
19
+ private readonly SECRET_KEY: string
20
+
21
+ private static readonly HMAC_DOMAIN = "PassportTokenAuth/v1"
22
+ private static readonly INTERNAL_SEP = "|"
23
+
24
+ constructor(
25
+ @Inject(PASSPORT_OPTIONS_KEY) private readonly options: PassportOptions,
26
+ ) {
27
+ this.SECRET_KEY = options.secretKey
28
+ }
29
+
30
+ private now() {
31
+ return Math.floor(Date.now() / 1000)
32
+ }
33
+
34
+ private serialize(user: string, iat: string, exp: string) {
35
+ return [PassportService.HMAC_DOMAIN, user, iat, exp].join(
36
+ PassportService.INTERNAL_SEP,
37
+ )
38
+ }
39
+
40
+ private computeHmac(data: string) {
41
+ return createHmac("sha256", this.SECRET_KEY).update(data).digest("hex")
42
+ }
43
+
44
+ generate(userId: string, ttl: number) {
45
+ const issuedAt = this.now()
46
+ const expiresAt = issuedAt + ttl
47
+
48
+ const userPart = base64UrlEncode(userId)
49
+ const iatPart = base64UrlEncode(String(issuedAt))
50
+ const expPart = base64UrlEncode(String(expiresAt))
51
+
52
+ const serialized = this.serialize(userPart, iatPart, expPart)
53
+ const mac = this.computeHmac(serialized)
54
+
55
+ return `${userPart}.${iatPart}.${expPart}.${mac}`
56
+ }
57
+
58
+ verify(token: string) {
59
+ const parts = token.split(".")
60
+
61
+ if (parts.length != 4)
62
+ return {
63
+ valid: false,
64
+ reason: "Invalid format",
65
+ }
66
+
67
+ const [userPart, iatPart, expPart, mac] = parts
68
+
69
+ const serialized = this.serialize(userPart, iatPart, expPart)
70
+
71
+ const expectedMac = this.computeHmac(serialized)
72
+
73
+ if (!constantTimeEqual(expectedMac, mac))
74
+ return {
75
+ valid: false,
76
+ reason: "Invalid signature",
77
+ }
78
+
79
+ const expNum = Number(base64UrlDecode(expPart))
80
+
81
+ if (!Number.isFinite(expNum))
82
+ return {
83
+ valid: false,
84
+ reason: "Error",
85
+ }
86
+
87
+ if (this.now() > expNum) return { valid: false, reason: "Expired" }
88
+
89
+ return {
90
+ valid: true,
91
+ userId: base64UrlDecode(userPart),
92
+ }
93
+ }
94
+ }
@@ -0,0 +1,17 @@
1
+ export function base64UrlEncode(buf: Buffer | string) {
2
+ const b = typeof buf === "string" ? Buffer.from(buf) : buf
3
+
4
+ return b
5
+ .toString("base64")
6
+ .replace(/\+/g, "-")
7
+ .replace(/\//g, "_")
8
+ .replace(/=+$/, "")
9
+ }
10
+
11
+ export function base64UrlDecode(base: string) {
12
+ base = base.replace(/-/g, "+").replace(/_/g, "/")
13
+
14
+ while (base.length % 4) base += "="
15
+
16
+ return Buffer.from(base, "base64").toString()
17
+ }
@@ -0,0 +1,11 @@
1
+ import { timingSafeEqual } from "node:crypto"
2
+
3
+ export function constantTimeEqual(a: string, b: string) {
4
+ const bufA = Buffer.from(a)
5
+
6
+ const bufB = Buffer.from(b)
7
+
8
+ if (bufA.length !== bufB.length) return false
9
+
10
+ return timingSafeEqual(bufA, bufB)
11
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./base64"
2
+ export * from "./crypto"
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "@dimgit9/passport",
3
+ "version": "1.0.0",
4
+ "description": "Lightweight authentication library",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "scripts": {
8
+ "build": "tsc -p tsconfig.build.json"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "keywords": [],
14
+ "author": "",
15
+ "license": "ISC",
16
+ "type": "commonjs",
17
+ "devDependencies": {
18
+ "@types/node": "^25.2.2",
19
+ "typescript": "^5.9.3"
20
+ },
21
+ "dependencies": {
22
+ "@nestjs/common": "^11.1.14",
23
+ "@nestjs/core": "^11.1.14",
24
+ "reflect-metadata": "^0.2.2",
25
+ "rx-js": "^0.0.0"
26
+ }
27
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "declaration": true,
5
+ "outDir": "./dist"
6
+ },
7
+ "include": ["lib/**/*"],
8
+ "exclude": ["node_modules", "dist", "test"]
9
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "commonjs",
4
+ "target": "es2024",
5
+ "strict": true,
6
+ "esModuleInterop": true,
7
+ "skipLibCheck": true,
8
+ "experimentalDecorators": true,
9
+ "emitDecoratorMetadata": true,
10
+ "forceConsistentCasingInFileNames": true,
11
+ "strictNullChecks": false
12
+ }
13
+ }