@zcatalyst/auth-admin 0.0.3

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/LICENCE ADDED
@@ -0,0 +1,55 @@
1
+ Zoho Catalyst SDK
2
+
3
+ Copyright (c) 2025 Zoho Corporation Private Limited
4
+
5
+
6
+ Apache License Version 2.0
7
+ http://www.apache.org/licenses/
8
+
9
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
10
+
11
+ 1. Definitions.
12
+
13
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
14
+
15
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
18
+
19
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
20
+
21
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
22
+
23
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
24
+
25
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
26
+
27
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
28
+
29
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
30
+
31
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
32
+
33
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
34
+
35
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
36
+
37
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
38
+
39
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
40
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,251 @@
1
+ # @zcatalyst/auth-admin
2
+
3
+ > **Internal package.** Consumed transitively by service packages. Do not install directly.
4
+
5
+ JavaScript SDK for Catalyst Admin Authentication - Catalyst App Initialization
6
+
7
+ ## Overview
8
+
9
+ The `@zcatalyst/auth-admin` package provides Node.js APIs for initializing Catalyst app instances and accessing configured credentials. Its package metadata marks it as server-only for browser builds.
10
+
11
+ ### Prerequisites
12
+
13
+ - A [Catalyst project](https://docs.catalyst.zoho.com/en/getting-started/catalyst-projects) set up
14
+ - Project credentials
15
+ - Node.js environment (server-side only)
16
+
17
+ ## Installation
18
+
19
+ To install this package, simply type add or install @zcatalyst/auth-admin
20
+ using your favorite package manager:
21
+
22
+ - `npm install @zcatalyst/auth-admin`
23
+ - `yarn add @zcatalyst/auth-admin`
24
+ - `pnpm add @zcatalyst/auth-admin`
25
+
26
+ ## Getting Started
27
+
28
+ ### Import
29
+
30
+ The Catalyst SDK is modularized by Components.
31
+ To handle admin authentication, you only need to import the `ZCAuth`:
32
+
33
+ ```js
34
+ // CommonJS
35
+ const { ZCAuth } = require("@zcatalyst/auth-admin");
36
+ ```
37
+
38
+ ```ts
39
+ // ES6+
40
+ import { ZCAuth } from "@zcatalyst/auth-admin";
41
+ ```
42
+
43
+ ### Usage
44
+
45
+ #### Initialize Admin Authentication
46
+
47
+ ```js
48
+ const auth = new ZCAuth();
49
+
50
+ const app = auth.init({
51
+ credential: {
52
+ getToken: async () => 'access-token'
53
+ },
54
+ projectId: 'your_project_id',
55
+ projectKey: 'your_project_key',
56
+ environment: 'development'
57
+ }, { type: 'custom' });
58
+ ```
59
+
60
+ #### Environment Variables
61
+
62
+ You can also configure authentication using environment variables:
63
+
64
+ ```bash
65
+ export ZCATALYST_PROJECT_ID=your_project_id
66
+ export ZCATALYST_PROJECT_KEY=your_project_key
67
+ export ZCATALYST_ENVIRONMENT=development
68
+ export ZCATALYST_PROJECT_DOMAIN=catalyst.zoho.com
69
+ export ZCATALYST_PROJECT_SECRET_KEY=your_secret_key
70
+ ```
71
+
72
+ Then initialize without parameters:
73
+
74
+ ```js
75
+ const auth = new ZCAuth();
76
+ const app = auth.getDefaultCredentials();
77
+ ```
78
+
79
+ ### Async/await
80
+
81
+ We recommend using [await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)
82
+ operator to wait for the promise returned by authentication operations:
83
+
84
+ ```js
85
+ try {
86
+ const app = auth.init(credentials, { type: 'custom' });
87
+ } catch (error) {
88
+ // error handling
89
+ } finally {
90
+ // cleanup
91
+ }
92
+ ```
93
+
94
+ ### Error Handling
95
+
96
+
97
+ ```js
98
+ try {
99
+ const app = auth.init(credentials, { type: 'custom' });
100
+ } catch (error) {
101
+ const message = error.message;
102
+ const status = error.statusCode;
103
+ console.log({ message, status });
104
+ }
105
+ ```
106
+
107
+ ## Supported Credential Types
108
+
109
+ `@zcatalyst/auth-admin` exposes the following credential classes. Pass any of them as the `credential` field to `auth.init({ credential, ... }, { type })`.
110
+
111
+ | Class | When to use |
112
+ |---|---|
113
+ | `RefreshTokenCredential` | You have a long-lived OAuth refresh token + client id/secret. |
114
+ | `AccessTokenCredential` | You already hold a short-lived access token. |
115
+ | `TicketCredential` | You have a Catalyst-issued ticket. |
116
+ | `CookieCredential` | You forward a browser session cookie to the server. |
117
+ | `CatalystCredential` | Wraps the headers Catalyst attaches to incoming serverless requests. |
118
+ | `ApplicationDefaultCredential` | Loads credentials from `~/.config/<suffix>` or `CLIENT_ID`/`CLIENT_SECRET`/`REFRESH_TOKEN` env vars. |
119
+ | `ApplicationCustomCredential` | Loads from a credential object you build at runtime (e.g. from your own secret store). |
120
+
121
+ ### Per-credential examples
122
+
123
+ ```ts
124
+ import {
125
+ ZCAuth,
126
+ RefreshTokenCredential,
127
+ AccessTokenCredential,
128
+ TicketCredential,
129
+ CookieCredential,
130
+ CatalystCredential,
131
+ ApplicationDefaultCredential,
132
+ ApplicationCustomCredential
133
+ } from '@zcatalyst/auth-admin';
134
+
135
+ const auth = new ZCAuth();
136
+
137
+ // 1. RefreshTokenCredential
138
+ auth.init({
139
+ credential: new RefreshTokenCredential({
140
+ client_id: process.env.CLIENT_ID!,
141
+ client_secret: process.env.CLIENT_SECRET!,
142
+ refresh_token: process.env.REFRESH_TOKEN!
143
+ }),
144
+ projectId: 'your_project_id',
145
+ projectKey: 'your_project_key'
146
+ }, { type: 'custom' });
147
+
148
+ // 2. AccessTokenCredential
149
+ auth.init({
150
+ credential: new AccessTokenCredential({ access_token: 'eyJ...' }),
151
+ projectId: 'your_project_id',
152
+ projectKey: 'your_project_key'
153
+ }, { type: 'custom' });
154
+
155
+ // 3. TicketCredential
156
+ auth.init({
157
+ credential: new TicketCredential({ ticket: 'ticket-value' }),
158
+ projectId: 'your_project_id',
159
+ projectKey: 'your_project_key'
160
+ }, { type: 'custom' });
161
+
162
+ // 4. CookieCredential
163
+ auth.init({
164
+ credential: new CookieCredential({ cookie: req.headers.cookie }),
165
+ projectId: 'your_project_id',
166
+ projectKey: 'your_project_key'
167
+ }, { type: 'custom' });
168
+
169
+ // 5. CatalystCredential — typical inside a Catalyst function
170
+ auth.init({ credential: new CatalystCredential(req.headers as Record<string, string>) },
171
+ { type: 'advancedio' });
172
+
173
+ // 6. ApplicationDefaultCredential — picks up file/env automatically
174
+ auth.init({
175
+ credential: new ApplicationDefaultCredential(),
176
+ projectId: 'your_project_id',
177
+ projectKey: 'your_project_key'
178
+ }, { type: 'custom' });
179
+
180
+ // 7. ApplicationCustomCredential — build the credential object yourself
181
+ auth.init({
182
+ credential: new ApplicationCustomCredential({
183
+ client_id: 'xxx',
184
+ client_secret: 'xxx',
185
+ refresh_token: 'xxx'
186
+ }),
187
+ projectId: 'your_project_id',
188
+ projectKey: 'your_project_key'
189
+ }, { type: 'custom' });
190
+ ```
191
+
192
+ ## Method Details
193
+
194
+ <details>
195
+ <summary>
196
+ <strong>init(options)</strong> - Initialize Authentication
197
+ </summary>
198
+
199
+ ```js
200
+ const auth = new ZCAuth();
201
+ const app = auth.init({
202
+ credential: {
203
+ getToken: async () => 'access-token'
204
+ },
205
+ projectId: 'your_project_id',
206
+ projectKey: 'your_project_key',
207
+ environment: 'development'
208
+ }, {
209
+ type: 'custom',
210
+ appName: 'my-app',
211
+ scope: 'admin'
212
+ });
213
+ ```
214
+
215
+ </details>
216
+
217
+ <details>
218
+ <summary>
219
+ <strong>app(name)</strong> - Get App Instance
220
+ </summary>
221
+
222
+ ```js
223
+ const app = auth.app('your_app_name');
224
+ ```
225
+
226
+ </details>
227
+
228
+ <details>
229
+ <summary>
230
+ <strong>getDefaultCredentials()</strong> - Get Default Credentials
231
+ </summary>
232
+
233
+ ```js
234
+ const auth = new ZCAuth();
235
+ const app = auth.getDefaultCredentials();
236
+ ```
237
+
238
+ </details>
239
+
240
+ ## Resources
241
+
242
+ - [Catalyst Authentication Documentation](https://docs.catalyst.zoho.com/en/cloud-scale/help/authentication/introduction/)
243
+ - [Project Credentials](https://docs.catalyst.zoho.com/en/getting-started/catalyst-projects/)
244
+
245
+ ## Contributing
246
+
247
+ See [CONTRIBUTING](../../CONTRIBUTING.md) for more information on how to get started.
248
+
249
+ ## License
250
+
251
+ This SDK is distributed under the Apache License 2.0. See [LICENSE](../../LICENCE) file for more information.
@@ -0,0 +1,362 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ApplicationCustomCredential = exports.ApplicationDefaultCredential = exports.CatalystCredential = exports.CookieCredential = exports.TicketCredential = exports.AccessTokenCredential = exports.RefreshTokenCredential = exports.Credential = exports.globalValue = void 0;
7
+ const utils_1 = require("@zcatalyst/utils");
8
+ const fs_1 = require("fs");
9
+ const http_1 = __importDefault(require("http"));
10
+ const https_1 = __importDefault(require("https"));
11
+ const path_1 = require("path");
12
+ const querystring_1 = require("querystring");
13
+ const errors_1 = require("./errors");
14
+ const { CREDENTIAL_SUFFIX, REQ_METHOD, CREDENTIAL_HEADER, CREDENTIAL_TYPE, CREDENTIAL_USER, CSRF_TOKEN_NAME, ACCOUNTS_ORIGIN } = utils_1.CONSTANTS;
15
+ exports.globalValue = {};
16
+ const CREDENTIAL_PATH = process.env.HOME
17
+ ? (0, path_1.resolve)((0, path_1.resolve)(process.env.HOME, '.config'), CREDENTIAL_SUFFIX)
18
+ : (0, path_1.resolve)('.', CREDENTIAL_SUFFIX);
19
+ function getAttr(from, key, alt) {
20
+ const tmp = from[key] || (alt ? from[alt] : undefined);
21
+ if (typeof tmp === 'undefined') {
22
+ throw new errors_1.CatalystAuthError('INVALID_CREDENTIAL', `Unable to get ${alt} from credential Object provided`, from);
23
+ }
24
+ return tmp;
25
+ }
26
+ function fromPath(filePath) {
27
+ let jsonString;
28
+ try {
29
+ jsonString = (0, fs_1.readFileSync)(filePath, 'utf8');
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ try {
35
+ return JSON.parse(jsonString);
36
+ }
37
+ catch (err) {
38
+ throw new errors_1.CatalystAuthError('INVALID_CREDENTIAL', 'Failed to parse token file: ' + err, err);
39
+ }
40
+ }
41
+ function fromEnv() {
42
+ const clientId = process.env['CLIENT_ID'];
43
+ const clientSecret = process.env['CLIENT_SECRET'];
44
+ const refreshToken = process.env['REFRESH_TOKEN'];
45
+ if (clientId && clientSecret && refreshToken) {
46
+ return {
47
+ client_id: clientId,
48
+ client_secret: clientSecret,
49
+ refresh_token: refreshToken
50
+ };
51
+ }
52
+ else {
53
+ throw new errors_1.CatalystAuthError('INVALID_CREDENTIAL', `Failed to get the credential string from env variables`);
54
+ }
55
+ }
56
+ function _appendQueryData(url, data) {
57
+ if (data && Object.keys(data).length > 0) {
58
+ url += url.includes('?') ? '&' : '?';
59
+ url += (0, querystring_1.stringify)(data);
60
+ }
61
+ return url;
62
+ }
63
+ function isHttps(url) {
64
+ if (url === undefined) {
65
+ return false;
66
+ }
67
+ const parsedUrl = url instanceof URL ? url : new URL(url);
68
+ return parsedUrl.protocol !== 'http:';
69
+ }
70
+ async function _request(config) {
71
+ config.url = _appendQueryData(String(config.origin) + String(config.path), config.qs);
72
+ const parsedUrl = new URL(config.url);
73
+ if (parsedUrl.hostname === null) {
74
+ throw new errors_1.CatalystAuthError('unparsable_config', 'Hostname cannot be null', config.path);
75
+ }
76
+ const isHttpsProtocol = isHttps(parsedUrl);
77
+ parsedUrl.searchParams?.sort();
78
+ const options = {
79
+ hostname: parsedUrl.hostname,
80
+ port: parsedUrl.port,
81
+ path: parsedUrl.pathname + parsedUrl.search,
82
+ method: config.method,
83
+ headers: {
84
+ 'Content-Type': 'application/json',
85
+ ...(config.headers || {})
86
+ }
87
+ };
88
+ const transport = isHttpsProtocol ? https_1.default : http_1.default;
89
+ return new Promise((resolve, reject) => {
90
+ const req = transport.request(options, (res) => {
91
+ const chunks = [];
92
+ res.on('data', (chunk) => {
93
+ chunks.push(chunk);
94
+ });
95
+ res.on('end', () => {
96
+ const body = Buffer.concat(chunks).toString();
97
+ const response = {
98
+ headers: res.headers,
99
+ request: req,
100
+ stream: res,
101
+ statusCode: res.statusCode,
102
+ config,
103
+ body
104
+ };
105
+ resolve(response);
106
+ });
107
+ });
108
+ req.on('error', (err) => {
109
+ reject(err);
110
+ });
111
+ req.write(JSON.stringify({ your: 'data' }));
112
+ req.end();
113
+ });
114
+ }
115
+ async function requestAccessToken(request) {
116
+ const options = {
117
+ method: request.method,
118
+ origin: request.origin,
119
+ qs: request.qs,
120
+ path: request.path
121
+ };
122
+ const resp = await _request(options);
123
+ const json = JSON.parse(resp.body);
124
+ if (json.error) {
125
+ const errorMessage = 'Error fetching access token: ' + json.error;
126
+ return Promise.reject(errorMessage);
127
+ }
128
+ else if (!json.access_token || !json.expires_in) {
129
+ return Promise.reject(`Unexpected response while fetching access token: ${JSON.stringify(json)}`);
130
+ }
131
+ else {
132
+ return json;
133
+ }
134
+ }
135
+ class Credential {
136
+ getCurrentUser() {
137
+ return CREDENTIAL_USER.admin;
138
+ }
139
+ switchUser(_givenUser) {
140
+ return null;
141
+ }
142
+ getCurrentUserType() {
143
+ return CREDENTIAL_USER.admin;
144
+ }
145
+ }
146
+ exports.Credential = Credential;
147
+ class RefreshTokenCredential extends Credential {
148
+ constructor(refreshObj) {
149
+ super();
150
+ this.clientId = getAttr(refreshObj, 'clientId', 'client_id');
151
+ this.clientSecret = getAttr(refreshObj, 'clientSecret', 'client_secret');
152
+ this.refreshToken = getAttr(refreshObj, 'refreshToken', 'refresh_token');
153
+ this.cachedToken = null;
154
+ }
155
+ async getToken() {
156
+ if (this.cachedToken === null || this.cachedToken['expires_in'] <= Date.now()) {
157
+ const token = await requestAccessToken({
158
+ method: REQ_METHOD.post,
159
+ origin: ACCOUNTS_ORIGIN,
160
+ path: '/oauth/v2/token',
161
+ qs: {
162
+ client_id: this.clientId,
163
+ client_secret: this.clientSecret,
164
+ refresh_token: this.refreshToken,
165
+ grant_type: 'refresh_token'
166
+ }
167
+ });
168
+ this.cachedToken = token;
169
+ this.cachedToken.expires_in = Date.now() + token.expires_in * 1000;
170
+ }
171
+ return this.cachedToken;
172
+ }
173
+ }
174
+ exports.RefreshTokenCredential = RefreshTokenCredential;
175
+ class AccessTokenCredential extends Credential {
176
+ constructor(accessObj) {
177
+ super();
178
+ this.accessToken = getAttr(accessObj, 'accessToken', 'access_token');
179
+ }
180
+ async getToken() {
181
+ return Promise.resolve({
182
+ access_token: this.accessToken
183
+ });
184
+ }
185
+ }
186
+ exports.AccessTokenCredential = AccessTokenCredential;
187
+ class TicketCredential extends Credential {
188
+ constructor(ticketObj) {
189
+ super();
190
+ this.ticket = getAttr(ticketObj, 'ticket', 'ticket');
191
+ }
192
+ async getToken() {
193
+ return Promise.resolve({ ticket: this.ticket });
194
+ }
195
+ }
196
+ exports.TicketCredential = TicketCredential;
197
+ class CookieCredential extends Credential {
198
+ constructor(cookieObj) {
199
+ super();
200
+ this.cookie = getAttr(cookieObj, 'cookie', 'cookie');
201
+ this.cookieObj = {};
202
+ }
203
+ getAsObject() {
204
+ if (Object.keys(this.cookieObj).length > 0) {
205
+ return this.cookieObj;
206
+ }
207
+ this.cookie.split(';').forEach((cookie) => {
208
+ const parts = cookie.split('=');
209
+ this.cookieObj[parts.shift()?.trim()] = decodeURI(parts.join('='));
210
+ });
211
+ return this.cookieObj;
212
+ }
213
+ getZCSRFHeader() {
214
+ const cookieObj = this.getAsObject();
215
+ return 'zd_csrparam=' + cookieObj[CSRF_TOKEN_NAME];
216
+ }
217
+ async getToken() {
218
+ return Promise.resolve({ cookie: this.cookie, zcrf_header: this.getZCSRFHeader() });
219
+ }
220
+ }
221
+ exports.CookieCredential = CookieCredential;
222
+ class CatalystCredential extends Credential {
223
+ constructor(credObj, scope) {
224
+ super();
225
+ this.adminCredType = getAttr(credObj, 'adminType', CREDENTIAL_HEADER.admin_cred_type);
226
+ this.adminToken = getAttr(credObj, 'adminToken', CREDENTIAL_HEADER.admin_token);
227
+ this.userCredType = credObj[CREDENTIAL_HEADER.user_cred_type];
228
+ this.userToken = credObj[CREDENTIAL_HEADER.user_token];
229
+ this.cookieStr = credObj[CREDENTIAL_HEADER.cookie];
230
+ this.userType =
231
+ credObj[CREDENTIAL_HEADER.user] === CREDENTIAL_USER.admin
232
+ ? CREDENTIAL_USER.admin
233
+ : CREDENTIAL_USER.user;
234
+ this.scope = scope || this.userType;
235
+ if (this.scope === CREDENTIAL_USER.user) {
236
+ if (this.userType === CREDENTIAL_USER.admin) {
237
+ throw new errors_1.CatalystAuthError('AUTH_ERROR', 'User not authenticated. Please login to proceed with user scope', credObj);
238
+ }
239
+ if (this.userToken === undefined && this.cookieStr === undefined) {
240
+ throw new errors_1.CatalystAuthError('INVALID_CREDENTIAL', 'missing user credentials', credObj);
241
+ }
242
+ }
243
+ switch (this.adminCredType) {
244
+ case CREDENTIAL_TYPE.ticket:
245
+ this.adminCred = new TicketCredential({ ticket: this.adminToken });
246
+ break;
247
+ case CREDENTIAL_TYPE.token:
248
+ this.adminCred = new AccessTokenCredential({ access_token: this.adminToken });
249
+ break;
250
+ default:
251
+ throw new errors_1.CatalystAuthError('INVALID_CREDENTIAL', 'admin credential type is unknown', credObj);
252
+ }
253
+ switch (this.userCredType) {
254
+ case CREDENTIAL_TYPE.ticket:
255
+ this.userCred = new TicketCredential({ ticket: this.userToken });
256
+ break;
257
+ case CREDENTIAL_TYPE.token:
258
+ this.userCred = new AccessTokenCredential({
259
+ access_token: this.userToken
260
+ });
261
+ break;
262
+ default:
263
+ if (this.cookieStr !== undefined) {
264
+ this.userCred = new CookieCredential({
265
+ cookie: this.cookieStr
266
+ });
267
+ }
268
+ }
269
+ }
270
+ async getToken() {
271
+ switch (this.scope) {
272
+ case CREDENTIAL_USER.admin:
273
+ return this.adminCred.getToken();
274
+ case CREDENTIAL_USER.user:
275
+ if (this.userCred === undefined) {
276
+ throw new errors_1.CatalystAuthError('INVALID_CREDENTIAL', 'User Credential is not initialised', this.scope);
277
+ }
278
+ return this.userCred.getToken();
279
+ default:
280
+ throw new errors_1.CatalystAuthError('INVALID_CREDENTIAL', 'user provided is not recognized', this.scope);
281
+ }
282
+ }
283
+ getScope() {
284
+ return this.scope;
285
+ }
286
+ getCurrentUser() {
287
+ return this.scope;
288
+ }
289
+ getCurrentUserType() {
290
+ if (this.scope === CREDENTIAL_USER.user) {
291
+ return this.userType;
292
+ }
293
+ return this.scope;
294
+ }
295
+ switchUser(givenUser) {
296
+ if (givenUser === undefined) {
297
+ switch (this.scope) {
298
+ case CREDENTIAL_USER.admin:
299
+ givenUser = CREDENTIAL_USER.user;
300
+ break;
301
+ case CREDENTIAL_USER.user:
302
+ givenUser = CREDENTIAL_USER.admin;
303
+ break;
304
+ }
305
+ }
306
+ this.scope = givenUser;
307
+ return this.scope;
308
+ }
309
+ }
310
+ exports.CatalystCredential = CatalystCredential;
311
+ class ApplicationDefaultCredential extends Credential {
312
+ constructor() {
313
+ super();
314
+ let token = fromPath(CREDENTIAL_PATH);
315
+ if (token === undefined || token === null) {
316
+ token = fromEnv();
317
+ }
318
+ if (token === undefined || token === null) {
319
+ throw new errors_1.CatalystAuthError('INVALID_CREDENTIAL', 'Unable to get token object from path or env', token);
320
+ }
321
+ if ('refresh_token' in token) {
322
+ this.credential = new RefreshTokenCredential(token);
323
+ }
324
+ else if ('access_token' in token) {
325
+ this.credential = new AccessTokenCredential(token);
326
+ }
327
+ else if ('ticket' in token) {
328
+ this.credential = new TicketCredential(token);
329
+ }
330
+ else {
331
+ throw new errors_1.CatalystAuthError('INVALID_CREDENTIAL', 'The given token object does not contain proper credentials', token);
332
+ }
333
+ }
334
+ async getToken() {
335
+ return this.credential.getToken();
336
+ }
337
+ }
338
+ exports.ApplicationDefaultCredential = ApplicationDefaultCredential;
339
+ class ApplicationCustomCredential extends Credential {
340
+ constructor(credObj) {
341
+ super();
342
+ if (credObj === undefined || credObj === null) {
343
+ throw new errors_1.CatalystAuthError('INVALID_CREDENTIAL', 'Unable to get token object from path or env', credObj);
344
+ }
345
+ if ('refresh_token' in credObj) {
346
+ this.credential = new RefreshTokenCredential(credObj);
347
+ }
348
+ else if ('access_token' in credObj) {
349
+ this.credential = new AccessTokenCredential(credObj);
350
+ }
351
+ else if ('ticket' in credObj) {
352
+ this.credential = new TicketCredential(credObj);
353
+ }
354
+ else {
355
+ throw new errors_1.CatalystAuthError('INVALID_CREDENTIAL', 'The given token object does not contain proper credentials', credObj);
356
+ }
357
+ }
358
+ async getToken() {
359
+ return this.credential.getToken();
360
+ }
361
+ }
362
+ exports.ApplicationCustomCredential = ApplicationCustomCredential;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CatalystAuthError = void 0;
4
+ const utils_1 = require("@zcatalyst/utils");
5
+ class CatalystAuthError extends utils_1.PrefixedCatalystError {
6
+ constructor(code, message, value) {
7
+ super('app', code, message, value);
8
+ }
9
+ }
10
+ exports.CatalystAuthError = CatalystAuthError;