@sermas/sermas-toolkit-node-sdk 1.0.0-alpha.3 → 1.0.0-alpha.4

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,9 @@
1
+ export declare const defaults: {
2
+ readonly auth: {
3
+ readonly PUBLIC_AUTH_URL: "http://172.17.0.1:8080/keycloak";
4
+ readonly PUBLIC_AUTH_REALM: "sermas-local";
5
+ readonly PRIVATE_AUTH_CLIENT_ID: "platform";
6
+ readonly PRIVATE_AUTH_CLIENT_SECRET: "platform";
7
+ readonly PRIVATE_API_BASE_URL: "http://api:3000/api";
8
+ };
9
+ };
@@ -0,0 +1,9 @@
1
+ export const defaults = {
2
+ auth: {
3
+ PUBLIC_AUTH_URL: "http://172.17.0.1:8080/keycloak",
4
+ PUBLIC_AUTH_REALM: "sermas-local",
5
+ PRIVATE_AUTH_CLIENT_ID: "platform",
6
+ PRIVATE_AUTH_CLIENT_SECRET: "platform",
7
+ PRIVATE_API_BASE_URL: "http://api:3000/api",
8
+ },
9
+ };
@@ -0,0 +1 @@
1
+ export { getAvatarToken, getAvatarTokenWithClientSecret, } from "./modules/auth.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { getAvatarToken, getAvatarTokenWithClientSecret, } from "./modules/auth.js";
@@ -0,0 +1,30 @@
1
+ export type AuthConfig = {
2
+ PUBLIC_AUTH_URL?: string;
3
+ PUBLIC_AUTH_REALM?: string;
4
+ PRIVATE_AUTH_CLIENT_ID?: string;
5
+ PRIVATE_AUTH_CLIENT_SECRET?: string;
6
+ PRIVATE_API_BASE_URL?: string;
7
+ };
8
+ /**
9
+ * Returns access and refresh tokens for the given appId
10
+ * @param {string} appId null by default
11
+ * @param {AuthConfig} authConfig
12
+ */
13
+ export declare const getAvatarToken: (appId?: string | null, authConfig?: AuthConfig) => Promise<{
14
+ appId: string | null;
15
+ accessToken?: string | undefined;
16
+ refreshToken?: string | undefined;
17
+ expiresIn?: Date | undefined;
18
+ }>;
19
+ /**
20
+ * Returns access and refresh tokens for the given appId
21
+ * @param {string} appId null by default
22
+ * @param {AuthConfig} authConfig only PRIVATE_API_BASE_URL and PRIVATE_AUTH_CLIENT_ID are used
23
+ * @param {string} clientSecret needed for server2server authentication
24
+ */
25
+ export declare const getAvatarTokenWithClientSecret: (appId?: string | null, authConfig?: AuthConfig, clientSecret?: string) => Promise<{
26
+ appId: string | null;
27
+ accessToken?: string | undefined;
28
+ refreshToken?: string | undefined;
29
+ expiresIn?: Date | undefined;
30
+ }>;
@@ -0,0 +1,209 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import axios, { isAxiosError } from "axios";
11
+ import * as https from "https";
12
+ import { defaults } from "../config/defaults.js";
13
+ const httpsAgent = new https.Agent({
14
+ rejectUnauthorized: process.env.NODE_ENV !== "development",
15
+ });
16
+ /**
17
+ * Returns access and refresh tokens for the given appId
18
+ * @param {string} appId null by default
19
+ * @param {AuthConfig} authConfig
20
+ */
21
+ export const getAvatarToken = (...args_1) => __awaiter(void 0, [...args_1], void 0, function* (appId = null, authConfig = defaults.auth) {
22
+ const logger = console;
23
+ const tokens = {};
24
+ let kioskToken = null;
25
+ const PUBLIC_AUTH_URL = authConfig.PUBLIC_AUTH_URL || defaults.auth.PUBLIC_AUTH_URL;
26
+ const PUBLIC_AUTH_REALM = authConfig.PUBLIC_AUTH_REALM || defaults.auth.PUBLIC_AUTH_REALM;
27
+ const PRIVATE_AUTH_CLIENT_ID = authConfig.PRIVATE_AUTH_CLIENT_ID || defaults.auth.PRIVATE_AUTH_CLIENT_ID;
28
+ const PRIVATE_AUTH_CLIENT_SECRET = authConfig.PRIVATE_AUTH_CLIENT_SECRET ||
29
+ defaults.auth.PRIVATE_AUTH_CLIENT_SECRET;
30
+ const PRIVATE_API_BASE_URL = authConfig.PRIVATE_API_BASE_URL || defaults.auth.PRIVATE_API_BASE_URL;
31
+ const getAvatarToken = (...args_2) => __awaiter(void 0, [...args_2], void 0, function* (appId = null) {
32
+ yield getSystemAccessToken();
33
+ let appToken = null;
34
+ if (appId) {
35
+ appToken = yield getAppAccessToken(appId);
36
+ }
37
+ return Object.assign(Object.assign({}, (appToken || {})), { appId });
38
+ });
39
+ const getAppAccessToken = (appId_1, ...args_3) => __awaiter(void 0, [appId_1, ...args_3], void 0, function* (appId, clientId = "avatar") {
40
+ var _a, _b;
41
+ logger.log(`Fetch app token for appId=${appId} clientId=${clientId}`);
42
+ const cacheKey = `${appId}-${clientId}`;
43
+ tokens[cacheKey] = tokens[cacheKey] || null;
44
+ if (tokens[cacheKey]) {
45
+ const expiresIn = (_a = tokens[cacheKey]) === null || _a === void 0 ? void 0 : _a.expiresIn;
46
+ if (!expiresIn || new Date(expiresIn).getTime() - 30000 < Date.now()) {
47
+ tokens[cacheKey] = null;
48
+ }
49
+ }
50
+ if (tokens[cacheKey]) {
51
+ logger.log(`Using cached token for ${cacheKey}`);
52
+ return tokens[cacheKey];
53
+ }
54
+ try {
55
+ const url = `${PRIVATE_API_BASE_URL}/platform/token`;
56
+ const data = {
57
+ appId,
58
+ clientId,
59
+ };
60
+ logger.debug(`Requesting to ${url}`);
61
+ const res = yield axios.post(url, data, {
62
+ httpsAgent,
63
+ headers: {
64
+ Authorization: `Bearer ${kioskToken === null || kioskToken === void 0 ? void 0 : kioskToken.accessToken}`,
65
+ },
66
+ });
67
+ // expires 1min before
68
+ const expiresIn = res.data.expires_in * 1000;
69
+ logger.log(`Token for ${appId} expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`);
70
+ const { access_token, refresh_token } = res.data;
71
+ const token = {
72
+ accessToken: access_token,
73
+ refreshToken: refresh_token,
74
+ expiresIn: new Date(Date.now() + expiresIn),
75
+ };
76
+ tokens[cacheKey] = token;
77
+ return token;
78
+ }
79
+ catch (e) {
80
+ if (e instanceof Error)
81
+ logger.error(`Request failed ${e === null || e === void 0 ? void 0 : e.message}`);
82
+ if (isAxiosError(e)) {
83
+ logger.error((_b = e.response) === null || _b === void 0 ? void 0 : _b.data);
84
+ delete tokens[cacheKey];
85
+ }
86
+ }
87
+ return null;
88
+ });
89
+ const getSystemAccessToken = () => __awaiter(void 0, void 0, void 0, function* () {
90
+ var _c, _d;
91
+ const cacheKey = "___kiosk___";
92
+ if (tokens[cacheKey]) {
93
+ const expiresIn = (_c = tokens[cacheKey]) === null || _c === void 0 ? void 0 : _c.expiresIn;
94
+ if (!expiresIn || new Date(expiresIn).getTime() - 30000 < Date.now()) {
95
+ tokens[cacheKey] = null;
96
+ }
97
+ }
98
+ if (tokens[cacheKey])
99
+ return tokens[cacheKey];
100
+ logger.debug(`Load kiosk access token`);
101
+ const url = `${PUBLIC_AUTH_URL}/realms/${PUBLIC_AUTH_REALM}/protocol/openid-connect/token`;
102
+ const data = {
103
+ client_id: PRIVATE_AUTH_CLIENT_ID,
104
+ client_secret: PRIVATE_AUTH_CLIENT_SECRET,
105
+ grant_type: "client_credentials",
106
+ };
107
+ try {
108
+ logger.debug(`Requesting to ${url}`);
109
+ const res = yield axios.post(url, data, {
110
+ headers: {
111
+ "Content-Type": "application/x-www-form-urlencoded",
112
+ Authorization: `Bearer ${btoa(PRIVATE_AUTH_CLIENT_ID + ":" + PRIVATE_AUTH_CLIENT_SECRET)}`,
113
+ },
114
+ });
115
+ // expires 1min before
116
+ const expiresIn = res.data.expires_in * 1000;
117
+ logger.debug(`kioskToken expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`);
118
+ // const access_token = await getAuthorizationToken(res.data.access_token)
119
+ const { access_token, refresh_token } = res.data;
120
+ kioskToken = {
121
+ accessToken: access_token,
122
+ refreshToken: refresh_token,
123
+ expiresIn: new Date(Date.now() + expiresIn),
124
+ };
125
+ tokens["__kiosk"] = kioskToken;
126
+ return kioskToken;
127
+ }
128
+ catch (e) {
129
+ kioskToken = null;
130
+ if (e instanceof Error)
131
+ logger.error(`Request failed ${e.message}`);
132
+ if (isAxiosError(e)) {
133
+ logger.error((_d = e.response) === null || _d === void 0 ? void 0 : _d.data);
134
+ }
135
+ }
136
+ return null;
137
+ });
138
+ return yield getAvatarToken(appId);
139
+ });
140
+ /**
141
+ * Returns access and refresh tokens for the given appId
142
+ * @param {string} appId null by default
143
+ * @param {AuthConfig} authConfig only PRIVATE_API_BASE_URL and PRIVATE_AUTH_CLIENT_ID are used
144
+ * @param {string} clientSecret needed for server2server authentication
145
+ */
146
+ export const getAvatarTokenWithClientSecret = (...args_4) => __awaiter(void 0, [...args_4], void 0, function* (appId = null, authConfig = defaults.auth, clientSecret = "") {
147
+ const logger = console;
148
+ const tokens = {};
149
+ const PRIVATE_API_BASE_URL = authConfig.PRIVATE_API_BASE_URL || defaults.auth.PRIVATE_API_BASE_URL;
150
+ const PRIVATE_AUTH_CLIENT_ID = authConfig.PRIVATE_AUTH_CLIENT_ID || defaults.auth.PRIVATE_AUTH_CLIENT_ID;
151
+ const getAppAccessTokenWithClientSecret = (appId_2, ...args_5) => __awaiter(void 0, [appId_2, ...args_5], void 0, function* (appId, clientId = "avatar", clientSecret = "") {
152
+ var _e, _f;
153
+ logger.log(`Fetch app token for appId=${appId} clientId=${clientId} clientSecret=${clientSecret}`);
154
+ const cacheKey = `${appId}-${clientId}`;
155
+ tokens[cacheKey] = tokens[cacheKey] || null;
156
+ if (tokens[cacheKey]) {
157
+ const expiresIn = (_e = tokens[cacheKey]) === null || _e === void 0 ? void 0 : _e.expiresIn;
158
+ if (!expiresIn ||
159
+ new Date(expiresIn).getTime() - 60 * 1000 < Date.now()) {
160
+ tokens[cacheKey] = null;
161
+ }
162
+ }
163
+ if (tokens[cacheKey]) {
164
+ logger.log(`Using cached token for ${cacheKey}`);
165
+ return tokens[cacheKey];
166
+ }
167
+ try {
168
+ const url = `${PRIVATE_API_BASE_URL}/platform/token/access_token`;
169
+ logger.debug(`Requesting to ${url}`);
170
+ const data = {
171
+ appId,
172
+ clientId,
173
+ clientSecret,
174
+ };
175
+ logger.debug(`get token from ${url}`);
176
+ const res = yield axios.post(url, data, {
177
+ httpsAgent,
178
+ });
179
+ // expires 1min before
180
+ const expiresIn = res.data.expires_in * 1000;
181
+ logger.log(`Token for ${appId} expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`);
182
+ const { access_token, refresh_token } = res.data;
183
+ const token = {
184
+ accessToken: access_token,
185
+ refreshToken: refresh_token,
186
+ expiresIn: new Date(Date.now() + expiresIn),
187
+ };
188
+ tokens[cacheKey] = token;
189
+ return token;
190
+ }
191
+ catch (e) {
192
+ if (e instanceof Error)
193
+ logger.error(`Request failed ${e.message}`);
194
+ if (isAxiosError(e)) {
195
+ logger.error((_f = e.response) === null || _f === void 0 ? void 0 : _f.data);
196
+ delete tokens[cacheKey];
197
+ }
198
+ }
199
+ return null;
200
+ });
201
+ const getAvatarTokenWithClientSecret = (...args_6) => __awaiter(void 0, [...args_6], void 0, function* (appId = null, clientId = "", clientSecret = "") {
202
+ let appToken = null;
203
+ if (appId) {
204
+ appToken = yield getAppAccessTokenWithClientSecret(appId, clientId, clientSecret);
205
+ }
206
+ return Object.assign(Object.assign({}, (appToken || {})), { appId });
207
+ });
208
+ return yield getAvatarTokenWithClientSecret(appId, PRIVATE_AUTH_CLIENT_ID, clientSecret);
209
+ });
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "@sermas/sermas-toolkit-node-sdk",
3
- "version": "1.0.0-alpha.3",
3
+ "version": "1.0.0-alpha.4",
4
4
  "description": "Sermas toolkit node SDK",
5
5
  "type": "module",
6
+ "files": ["dist"],
6
7
  "exports": "./dist/index.js",
7
8
  "main": "./dist/index.js",
8
9
  "types": "./dist/index.d.ts",
package/.eslintrc.cjs DELETED
@@ -1,30 +0,0 @@
1
- module.exports = {
2
- env: {
3
- es2021: true,
4
- node: true,
5
- },
6
- extends: [
7
- "eslint:recommended",
8
- "plugin:@typescript-eslint/recommended",
9
- "plugin:prettier/recommended",
10
- ],
11
- ignorePatterns: ["dist"],
12
- overrides: [
13
- {
14
- env: {
15
- node: true,
16
- },
17
- files: [".eslintrc.{js,cjs}"],
18
- parserOptions: {
19
- sourceType: "script",
20
- },
21
- },
22
- ],
23
- parser: "@typescript-eslint/parser",
24
- parserOptions: {
25
- ecmaVersion: "latest",
26
- sourceType: "module",
27
- },
28
- plugins: ["@typescript-eslint"],
29
- rules: {},
30
- };
@@ -1,22 +0,0 @@
1
- name: Release npm latest package
2
-
3
- on:
4
- push:
5
- tags:
6
- - 'v*.*.*'
7
-
8
- jobs:
9
- npm-release:
10
- runs-on: ubuntu-latest
11
- steps:
12
- - uses: actions/checkout@v4
13
- # Setup .npmrc file to publish to npm
14
- - uses: actions/setup-node@v3
15
- with:
16
- node-version: '20.x'
17
- registry-url: 'https://registry.npmjs.org'
18
- - run: npm install
19
- - run: npm run build
20
- - run: npm publish --access public --tag latest
21
- env:
22
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
package/.prettierrc DELETED
File without changes
@@ -1,9 +0,0 @@
1
- export const defaults = {
2
- auth: {
3
- PUBLIC_AUTH_URL: "http://172.17.0.1:8080/keycloak",
4
- PUBLIC_AUTH_REALM: "sermas-local",
5
- PRIVATE_AUTH_CLIENT_ID: "platform",
6
- PRIVATE_AUTH_CLIENT_SECRET: "platform",
7
- PRIVATE_API_BASE_URL: "http://api:3000/api",
8
- },
9
- } as const;
package/src/index.ts DELETED
@@ -1,4 +0,0 @@
1
- export {
2
- getAvatarToken,
3
- getAvatarTokenWithClientSecret,
4
- } from "./modules/auth.js";
@@ -1,299 +0,0 @@
1
- import axios, { isAxiosError } from "axios";
2
- import * as https from "https";
3
- import { defaults } from "../config/defaults.js";
4
-
5
- export type AuthConfig = {
6
- PUBLIC_AUTH_URL?: string;
7
- PUBLIC_AUTH_REALM?: string;
8
- PRIVATE_AUTH_CLIENT_ID?: string;
9
- PRIVATE_AUTH_CLIENT_SECRET?: string;
10
- PRIVATE_API_BASE_URL?: string;
11
- };
12
-
13
- type TokenResponse = {
14
- accessToken: string;
15
- refreshToken: string;
16
- expiresIn: Date;
17
- };
18
-
19
- const httpsAgent = new https.Agent({
20
- rejectUnauthorized: process.env.NODE_ENV !== "development",
21
- });
22
-
23
- /**
24
- * Returns access and refresh tokens for the given appId
25
- * @param {string} appId null by default
26
- * @param {AuthConfig} authConfig
27
- */
28
- export const getAvatarToken = async (
29
- appId: string | null = null,
30
- authConfig: AuthConfig = defaults.auth,
31
- ) => {
32
- const logger = console;
33
- const tokens: Record<string, TokenResponse | null> = {};
34
- let kioskToken: TokenResponse | null = null;
35
-
36
- const PUBLIC_AUTH_URL =
37
- authConfig.PUBLIC_AUTH_URL || defaults.auth.PUBLIC_AUTH_URL;
38
- const PUBLIC_AUTH_REALM =
39
- authConfig.PUBLIC_AUTH_REALM || defaults.auth.PUBLIC_AUTH_REALM;
40
- const PRIVATE_AUTH_CLIENT_ID =
41
- authConfig.PRIVATE_AUTH_CLIENT_ID || defaults.auth.PRIVATE_AUTH_CLIENT_ID;
42
- const PRIVATE_AUTH_CLIENT_SECRET =
43
- authConfig.PRIVATE_AUTH_CLIENT_SECRET ||
44
- defaults.auth.PRIVATE_AUTH_CLIENT_SECRET;
45
- const PRIVATE_API_BASE_URL =
46
- authConfig.PRIVATE_API_BASE_URL || defaults.auth.PRIVATE_API_BASE_URL;
47
-
48
- const getAvatarToken = async (appId: string | null = null) => {
49
- await getSystemAccessToken();
50
-
51
- let appToken: TokenResponse | null = null;
52
- if (appId) {
53
- appToken = await getAppAccessToken(appId);
54
- }
55
-
56
- return {
57
- ...(appToken || {}),
58
- appId,
59
- };
60
- };
61
-
62
- const getAppAccessToken = async (
63
- appId: string,
64
- clientId = "avatar",
65
- ): Promise<TokenResponse | null> => {
66
- logger.log(`Fetch app token for appId=${appId} clientId=${clientId}`);
67
-
68
- const cacheKey = `${appId}-${clientId}`;
69
-
70
- tokens[cacheKey] = tokens[cacheKey] || null;
71
-
72
- if (tokens[cacheKey]) {
73
- const expiresIn = tokens[cacheKey]?.expiresIn;
74
- if (!expiresIn || new Date(expiresIn).getTime() - 30000 < Date.now()) {
75
- tokens[cacheKey] = null;
76
- }
77
- }
78
-
79
- if (tokens[cacheKey]) {
80
- logger.log(`Using cached token for ${cacheKey}`);
81
- return tokens[cacheKey];
82
- }
83
-
84
- try {
85
- const url = `${PRIVATE_API_BASE_URL}/platform/token`;
86
- const data = {
87
- appId,
88
- clientId,
89
- };
90
-
91
- logger.debug(`Requesting to ${url}`);
92
- const res = await axios.post(url, data, {
93
- httpsAgent,
94
- headers: {
95
- Authorization: `Bearer ${kioskToken?.accessToken}`,
96
- },
97
- });
98
-
99
- // expires 1min before
100
- const expiresIn = res.data.expires_in * 1000;
101
- logger.log(
102
- `Token for ${appId} expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`,
103
- );
104
-
105
- const { access_token, refresh_token } = res.data;
106
-
107
- const token = {
108
- accessToken: access_token,
109
- refreshToken: refresh_token,
110
- expiresIn: new Date(Date.now() + expiresIn),
111
- };
112
-
113
- tokens[cacheKey] = token;
114
-
115
- return token;
116
- } catch (e) {
117
- if (e instanceof Error) logger.error(`Request failed ${e?.message}`);
118
- if (isAxiosError(e)) {
119
- logger.error(e.response?.data);
120
- delete tokens[cacheKey];
121
- }
122
- }
123
- return null;
124
- };
125
-
126
- const getSystemAccessToken = async (): Promise<TokenResponse | null> => {
127
- const cacheKey = "___kiosk___";
128
-
129
- if (tokens[cacheKey]) {
130
- const expiresIn = tokens[cacheKey]?.expiresIn;
131
- if (!expiresIn || new Date(expiresIn).getTime() - 30000 < Date.now()) {
132
- tokens[cacheKey] = null;
133
- }
134
- }
135
-
136
- if (tokens[cacheKey]) return tokens[cacheKey];
137
-
138
- logger.debug(`Load kiosk access token`);
139
-
140
- const url = `${PUBLIC_AUTH_URL}/realms/${PUBLIC_AUTH_REALM}/protocol/openid-connect/token`;
141
- const data = {
142
- client_id: PRIVATE_AUTH_CLIENT_ID,
143
- client_secret: PRIVATE_AUTH_CLIENT_SECRET,
144
- grant_type: "client_credentials",
145
- };
146
-
147
- try {
148
- logger.debug(`Requesting to ${url}`);
149
- const res = await axios.post(url, data, {
150
- headers: {
151
- "Content-Type": "application/x-www-form-urlencoded",
152
- Authorization: `Bearer ${btoa(PRIVATE_AUTH_CLIENT_ID + ":" + PRIVATE_AUTH_CLIENT_SECRET)}`,
153
- },
154
- });
155
-
156
- // expires 1min before
157
- const expiresIn = res.data.expires_in * 1000;
158
- logger.debug(
159
- `kioskToken expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`,
160
- );
161
-
162
- // const access_token = await getAuthorizationToken(res.data.access_token)
163
- const { access_token, refresh_token } = res.data;
164
-
165
- kioskToken = {
166
- accessToken: access_token,
167
- refreshToken: refresh_token,
168
- expiresIn: new Date(Date.now() + expiresIn),
169
- };
170
-
171
- tokens["__kiosk"] = kioskToken;
172
-
173
- return kioskToken;
174
- } catch (e) {
175
- kioskToken = null;
176
- if (e instanceof Error) logger.error(`Request failed ${e.message}`);
177
- if (isAxiosError(e)) {
178
- logger.error(e.response?.data);
179
- }
180
- }
181
- return null;
182
- };
183
-
184
- return await getAvatarToken(appId);
185
- };
186
-
187
- /**
188
- * Returns access and refresh tokens for the given appId
189
- * @param {string} appId null by default
190
- * @param {AuthConfig} authConfig only PRIVATE_API_BASE_URL and PRIVATE_AUTH_CLIENT_ID are used
191
- * @param {string} clientSecret needed for server2server authentication
192
- */
193
- export const getAvatarTokenWithClientSecret = async (
194
- appId: string | null = null,
195
- authConfig: AuthConfig = defaults.auth,
196
- clientSecret: string = "",
197
- ) => {
198
- const logger = console;
199
- const tokens: Record<string, TokenResponse | null> = {};
200
-
201
- const PRIVATE_API_BASE_URL =
202
- authConfig.PRIVATE_API_BASE_URL || defaults.auth.PRIVATE_API_BASE_URL;
203
- const PRIVATE_AUTH_CLIENT_ID =
204
- authConfig.PRIVATE_AUTH_CLIENT_ID || defaults.auth.PRIVATE_AUTH_CLIENT_ID;
205
-
206
- const getAppAccessTokenWithClientSecret = async (
207
- appId: string,
208
- clientId = "avatar",
209
- clientSecret = "",
210
- ): Promise<TokenResponse | null> => {
211
- logger.log(
212
- `Fetch app token for appId=${appId} clientId=${clientId} clientSecret=${clientSecret}`,
213
- );
214
-
215
- const cacheKey = `${appId}-${clientId}`;
216
-
217
- tokens[cacheKey] = tokens[cacheKey] || null;
218
-
219
- if (tokens[cacheKey]) {
220
- const expiresIn = tokens[cacheKey]?.expiresIn;
221
- if (
222
- !expiresIn ||
223
- new Date(expiresIn).getTime() - 60 * 1000 < Date.now()
224
- ) {
225
- tokens[cacheKey] = null;
226
- }
227
- }
228
-
229
- if (tokens[cacheKey]) {
230
- logger.log(`Using cached token for ${cacheKey}`);
231
- return tokens[cacheKey];
232
- }
233
-
234
- try {
235
- const url = `${PRIVATE_API_BASE_URL}/platform/token/access_token`;
236
- logger.debug(`Requesting to ${url}`);
237
- const data = {
238
- appId,
239
- clientId,
240
- clientSecret,
241
- };
242
- logger.debug(`get token from ${url}`);
243
- const res = await axios.post(url, data, {
244
- httpsAgent,
245
- });
246
-
247
- // expires 1min before
248
- const expiresIn = res.data.expires_in * 1000;
249
- logger.log(
250
- `Token for ${appId} expires in ${Math.round(expiresIn / 60 / 60 / 1000)}min`,
251
- );
252
-
253
- const { access_token, refresh_token } = res.data;
254
-
255
- const token = {
256
- accessToken: access_token,
257
- refreshToken: refresh_token,
258
- expiresIn: new Date(Date.now() + expiresIn),
259
- };
260
-
261
- tokens[cacheKey] = token;
262
-
263
- return token;
264
- } catch (e) {
265
- if (e instanceof Error) logger.error(`Request failed ${e.message}`);
266
- if (isAxiosError(e)) {
267
- logger.error(e.response?.data);
268
- delete tokens[cacheKey];
269
- }
270
- }
271
- return null;
272
- };
273
-
274
- const getAvatarTokenWithClientSecret = async (
275
- appId: string | null = null,
276
- clientId: string = "",
277
- clientSecret = "",
278
- ) => {
279
- let appToken: TokenResponse | null = null;
280
- if (appId) {
281
- appToken = await getAppAccessTokenWithClientSecret(
282
- appId,
283
- clientId,
284
- clientSecret,
285
- );
286
- }
287
-
288
- return {
289
- ...(appToken || {}),
290
- appId,
291
- };
292
- };
293
-
294
- return await getAvatarTokenWithClientSecret(
295
- appId,
296
- PRIVATE_AUTH_CLIENT_ID,
297
- clientSecret,
298
- );
299
- };
package/tsconfig.json DELETED
@@ -1,14 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2015",
4
- "moduleResolution": "NodeNext",
5
- "module": "NodeNext",
6
- "esModuleInterop": true,
7
- "forceConsistentCasingInFileNames": true,
8
- "declaration": true,
9
- "strict": true,
10
- "skipLibCheck": true,
11
- "outDir": "./dist"
12
- },
13
- "include": ["src"]
14
- }