supaapps-auth 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 to NPM
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "v*"
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - name: Checkout code
13
+ uses: actions/checkout@v2
14
+
15
+ - name: Use Node.js
16
+ uses: actions/setup-node@v3
17
+ with:
18
+ node-version: lts/*
19
+ registry-url: 'https://registry.npmjs.org'
20
+
21
+ - name: Install dependencies
22
+ run: npm install
23
+
24
+ - name: Build
25
+ run: npm run build
26
+
27
+ - name: Publish to npm
28
+ run: npm publish
29
+ env:
30
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
package/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ MIT License
2
+
3
+ Notice: While this software is open-source under the MIT License, the "Supaapps" name, branding, and logo are proprietary and copyrighted by Supaapps GmbH. Any use, reproduction, or distribution of the "Supaapps" brand assets without explicit permission is strictly prohibited.
4
+
5
+ Copyright (c) 2023 Supaapps GmbH
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
@@ -0,0 +1,14 @@
1
+ export declare class AuthManager {
2
+ private static instance;
3
+ private readonly authServer;
4
+ private readonly realmName;
5
+ private readonly redirectUri;
6
+ private constructor();
7
+ static getInstance<T>(): AuthManager;
8
+ private toBase64Url;
9
+ private generatePKCEPair;
10
+ getLoginWithGoogleUri(): string;
11
+ isLoggedIn(): Promise<boolean>;
12
+ getAccessToken(): Promise<string>;
13
+ loginUsingPkce(code: any): Promise<void>;
14
+ }
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.AuthManager = void 0;
13
+ const crypto_1 = require("crypto");
14
+ class AuthManager {
15
+ constructor(authServer, realmName, redirectUri) {
16
+ this.authServer = null;
17
+ this.realmName = null;
18
+ this.redirectUri = null;
19
+ this.toBase64Url = (base64String) => {
20
+ return base64String
21
+ .replace(/\+/g, '-')
22
+ .replace(/\//g, '_')
23
+ .replace(/=+$/, '');
24
+ };
25
+ this.generatePKCEPair = () => {
26
+ const NUM_OF_BYTES = 32; // This will generate a verifier of sufficient length
27
+ const HASH_ALG = 'sha256';
28
+ // Generate code verifier
29
+ const codeVerifier = this.toBase64Url((0, crypto_1.randomBytes)(NUM_OF_BYTES).toString('base64'));
30
+ // Generate code challenge
31
+ const hash = (0, crypto_1.createHash)(HASH_ALG)
32
+ .update(codeVerifier)
33
+ .digest('base64');
34
+ const codeChallenge = this.toBase64Url(hash);
35
+ return { codeVerifier, codeChallenge };
36
+ };
37
+ this.authServer = authServer;
38
+ this.realmName = realmName;
39
+ this.redirectUri = redirectUri;
40
+ }
41
+ static getInstance() {
42
+ if (!AuthManager.instance) {
43
+ throw new Error('AuthManager not initialized');
44
+ }
45
+ return AuthManager.instance;
46
+ }
47
+ getLoginWithGoogleUri() {
48
+ const { codeVerifier, codeChallenge } = this.generatePKCEPair();
49
+ localStorage.setItem('codeVerifier', codeVerifier);
50
+ localStorage.setItem('codeChallenge', codeChallenge);
51
+ if (this.authServer && this.realmName && this.redirectUri) {
52
+ return `${this.authServer}auth/login_with_google?realm_name=${this.realmName}` +
53
+ `&redirect_uri=${encodeURIComponent(this.realmName)}&code_challenge=${codeChallenge}&code_challenge_method=S256`;
54
+ }
55
+ }
56
+ isLoggedIn() {
57
+ return __awaiter(this, void 0, void 0, function* () {
58
+ // todo here: check if refresh token is expired and if so, try to refresh, then update token
59
+ return new Promise((resolve, reject) => {
60
+ try {
61
+ const accessToken = localStorage.getItem('access_token');
62
+ if (!accessToken) {
63
+ return resolve(false);
64
+ }
65
+ // decode access token and check if it's expired
66
+ const decodedToken = accessToken ? JSON.parse(atob(accessToken.split('.')[1])) : null;
67
+ if (decodedToken) {
68
+ const currentTime = Date.now() / 1000;
69
+ if (decodedToken.exp < currentTime) {
70
+ // add refresh check here instead and
71
+ localStorage.removeItem('access_token');
72
+ return resolve(false);
73
+ }
74
+ }
75
+ return resolve(true);
76
+ }
77
+ catch (error) {
78
+ reject(error);
79
+ }
80
+ });
81
+ });
82
+ }
83
+ getAccessToken() {
84
+ return __awaiter(this, void 0, void 0, function* () {
85
+ // todo here: check if refresh token is expired and if so, try to refresh, then update token
86
+ // otherwise throw error
87
+ return new Promise((resolve, reject) => {
88
+ try {
89
+ const accessToken = localStorage.getItem('access_token');
90
+ if (!accessToken) {
91
+ throw new Error('No access token found');
92
+ }
93
+ // decode access token and check if it's expired
94
+ const decodedToken = accessToken ? JSON.parse(atob(accessToken.split('.')[1])) : null;
95
+ if (decodedToken) {
96
+ const currentTime = Date.now() / 1000;
97
+ if (decodedToken.exp < currentTime) {
98
+ // add refresh check here instead and
99
+ localStorage.removeItem('access_token');
100
+ throw new Error('Access token expired');
101
+ }
102
+ }
103
+ return resolve(accessToken);
104
+ }
105
+ catch (error) {
106
+ reject(error);
107
+ }
108
+ });
109
+ });
110
+ }
111
+ loginUsingPkce(code) {
112
+ return __awaiter(this, void 0, void 0, function* () {
113
+ return new Promise((resolve, reject) => {
114
+ try {
115
+ const codeVerifier = localStorage.getItem('codeVerifier');
116
+ if (codeVerifier) {
117
+ fetch(`${this.authServer}auth/pkce_exchange`, {
118
+ method: 'POST',
119
+ headers: {
120
+ 'Content-Type': 'application/json',
121
+ },
122
+ body: JSON.stringify({
123
+ realm_name: this.realmName,
124
+ code: code,
125
+ redirect_uri: this.redirectUri,
126
+ code_verifier: codeVerifier,
127
+ }),
128
+ })
129
+ .then((response) => {
130
+ if (response.status !== 200) {
131
+ throw new Error('Failed to exchange code for token');
132
+ }
133
+ return response.json();
134
+ })
135
+ .then((exchangeJson) => {
136
+ localStorage.setItem('access_token', exchangeJson.access_token);
137
+ localStorage.setItem('refresh_token', exchangeJson.refresh_token);
138
+ resolve();
139
+ })
140
+ .catch((error) => {
141
+ reject(error);
142
+ });
143
+ }
144
+ }
145
+ catch (error) {
146
+ reject(error);
147
+ }
148
+ });
149
+ });
150
+ }
151
+ }
152
+ exports.AuthManager = AuthManager;
153
+ AuthManager.instance = null;
@@ -0,0 +1 @@
1
+ export { AuthManager } from './AuthManager';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuthManager = void 0;
4
+ var AuthManager_1 = require("./AuthManager");
5
+ Object.defineProperty(exports, "AuthManager", { enumerable: true, get: function () { return AuthManager_1.AuthManager; } });
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "supaapps-auth",
3
+ "version": "1.0.0",
4
+ "description": "",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "test": "echo \"Error: no test specified\" && exit 1",
9
+ "build": "tsc"
10
+ },
11
+ "author": "",
12
+ "license": "MIT",
13
+ "dependencies": {
14
+ "axios": "^1.6.7",
15
+ "crypto": "^1.0.1"
16
+ },
17
+ "devDependencies": {
18
+ "@types/node": "^20.11.10",
19
+ "typescript": "^5.3.3"
20
+ }
21
+ }
@@ -0,0 +1,149 @@
1
+ import axios from 'axios';
2
+ import { createHash, randomBytes } from 'crypto';
3
+
4
+
5
+ export class AuthManager {
6
+ private static instance: AuthManager | null = null;
7
+ private readonly authServer: string | null = null;
8
+
9
+ private readonly realmName: string | null = null;
10
+
11
+ private readonly redirectUri: string | null = null;
12
+ private constructor(authServer: string, realmName: string, redirectUri: string) {
13
+ this.authServer = authServer;
14
+ this.realmName = realmName;
15
+ this.redirectUri = redirectUri;
16
+ }
17
+
18
+ public static getInstance<T>(): AuthManager{
19
+ if (!AuthManager.instance) {
20
+ throw new Error('AuthManager not initialized');
21
+ }
22
+ return AuthManager.instance;
23
+ }
24
+
25
+ private toBase64Url = (base64String: string) => {
26
+ return base64String
27
+ .replace(/\+/g, '-')
28
+ .replace(/\//g, '_')
29
+ .replace(/=+$/, '');
30
+ };
31
+ private generatePKCEPair = () => {
32
+ const NUM_OF_BYTES = 32; // This will generate a verifier of sufficient length
33
+ const HASH_ALG = 'sha256';
34
+
35
+ // Generate code verifier
36
+ const codeVerifier = this.toBase64Url(
37
+ randomBytes(NUM_OF_BYTES).toString('base64'),
38
+ );
39
+
40
+ // Generate code challenge
41
+ const hash = createHash(HASH_ALG)
42
+ .update(codeVerifier)
43
+ .digest('base64');
44
+ const codeChallenge = this.toBase64Url(hash);
45
+
46
+ return { codeVerifier, codeChallenge };
47
+ };
48
+ public getLoginWithGoogleUri(): string {
49
+ const { codeVerifier, codeChallenge } = this.generatePKCEPair();
50
+ localStorage.setItem('codeVerifier', codeVerifier);
51
+ localStorage.setItem('codeChallenge', codeChallenge);
52
+
53
+ if (this.authServer && this.realmName && this.redirectUri) {
54
+ return `${this.authServer}auth/login_with_google?realm_name=${this.realmName}` +
55
+ `&redirect_uri=${encodeURIComponent(this.realmName )}&code_challenge=${codeChallenge}&code_challenge_method=S256`
56
+ }
57
+ }
58
+ public async isLoggedIn(): Promise<boolean> {
59
+ // todo here: check if refresh token is expired and if so, try to refresh, then update token
60
+ return new Promise((resolve, reject) => {
61
+ try {
62
+ const accessToken: string | null = localStorage.getItem('access_token');
63
+ if (!accessToken) {
64
+ return resolve(false);
65
+ }
66
+ // decode access token and check if it's expired
67
+ const decodedToken = accessToken ? JSON.parse(atob(accessToken.split('.')[1])) : null;
68
+ if (decodedToken) {
69
+ const currentTime = Date.now() / 1000;
70
+ if (decodedToken.exp < currentTime) {
71
+ // add refresh check here instead and
72
+ localStorage.removeItem('access_token');
73
+ return resolve(false);
74
+ }
75
+ }
76
+
77
+ return resolve(true);
78
+ } catch (error) {
79
+ reject(error);
80
+ }
81
+ });
82
+ }
83
+
84
+ public async getAccessToken(): Promise<string> {
85
+ // todo here: check if refresh token is expired and if so, try to refresh, then update token
86
+ // otherwise throw error
87
+ return new Promise((resolve, reject) => {
88
+ try {
89
+ const accessToken: string | null = localStorage.getItem('access_token');
90
+ if (!accessToken) {
91
+ throw new Error('No access token found');
92
+ }
93
+ // decode access token and check if it's expired
94
+ const decodedToken = accessToken ? JSON.parse(atob(accessToken.split('.')[1])) : null;
95
+ if (decodedToken) {
96
+ const currentTime = Date.now() / 1000;
97
+ if (decodedToken.exp < currentTime) {
98
+ // add refresh check here instead and
99
+ localStorage.removeItem('access_token');
100
+ throw new Error('Access token expired');
101
+ }
102
+ }
103
+
104
+ return resolve(accessToken);
105
+ } catch (error) {
106
+ reject(error);
107
+ }
108
+ });
109
+ }
110
+
111
+ public async loginUsingPkce(code): Promise<void> {
112
+ return new Promise((resolve, reject) => {
113
+ try {
114
+ const codeVerifier = localStorage.getItem('codeVerifier');
115
+ if (codeVerifier) {
116
+ fetch(`${this.authServer}auth/pkce_exchange`, {
117
+ method: 'POST',
118
+ headers: {
119
+ 'Content-Type': 'application/json',
120
+ },
121
+ body: JSON.stringify({
122
+ realm_name: this.realmName,
123
+ code: code,
124
+ redirect_uri: this.redirectUri,
125
+ code_verifier: codeVerifier,
126
+ }),
127
+ })
128
+ .then((response) => {
129
+ if (response.status !== 200) {
130
+ throw new Error('Failed to exchange code for token');
131
+ }
132
+ return response.json();
133
+ })
134
+ .then((exchangeJson) => {
135
+ localStorage.setItem('access_token', exchangeJson.access_token);
136
+ localStorage.setItem('refresh_token', exchangeJson.refresh_token);
137
+ resolve();
138
+ })
139
+ .catch((error) => {
140
+ reject(error);
141
+ });
142
+ }
143
+ } catch (error) {
144
+ reject(error);
145
+ }
146
+ });
147
+ }
148
+
149
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { AuthManager } from './AuthManager';
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "compilerOptions": {
3
+ "outDir": "./dist",
4
+ "declaration": true,
5
+ "module": "commonjs",
6
+ "target": "ES6"
7
+ },
8
+ "include": ["src/**/*.ts"]
9
+ }