Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 2s
123 lines
3.8 KiB
TypeScript
123 lines
3.8 KiB
TypeScript
import type { IWorkspaceCredentials } from '@rocket.chat/core-typings';
|
|
import { License } from '@rocket.chat/license';
|
|
import { WorkspaceCredentials } from '@rocket.chat/models';
|
|
|
|
import { getWorkspaceAccessTokenWithScope } from './getWorkspaceAccessTokenWithScope';
|
|
import { workspaceScopes } from './oauthScopes';
|
|
import { retrieveRegistrationStatus } from './retrieveRegistrationStatus';
|
|
import { SystemLogger } from '../logger/system';
|
|
|
|
const hasWorkspaceAccessTokenExpired = (credentials: IWorkspaceCredentials): boolean => new Date() >= credentials.expirationDate;
|
|
|
|
/**
|
|
* Returns the access token for the workspace, if it is expired or forceNew is true, it will get a new one
|
|
* and save it to the database, therefore if this function does not throw an error, it will always return a valid token.
|
|
*
|
|
* @param {boolean} forceNew - If true, it will get a new token even if the current one is not expired
|
|
* @param {string} scope - The scope of the token to get
|
|
* @param {boolean} save - If true, it will save the new token to the database
|
|
* @throws {CloudWorkspaceAccessTokenError} If the workspace is not registered (no credentials in the database)
|
|
*
|
|
* @returns string - A valid access token for the workspace
|
|
*/
|
|
export async function getWorkspaceAccessToken(forceNew = false, scope = '', save = true, throwOnError = false): Promise<string> {
|
|
const { workspaceRegistered } = await retrieveRegistrationStatus();
|
|
|
|
if (!workspaceRegistered) {
|
|
return '';
|
|
}
|
|
|
|
if (License.hasOfflineLicense()) {
|
|
return '';
|
|
}
|
|
|
|
// Note: If no scope is given, it means we should assume the default scope, we store the default scopes
|
|
// in the global variable workspaceScopes.
|
|
if (scope === '') {
|
|
scope = workspaceScopes.join(' ');
|
|
}
|
|
|
|
const workspaceCredentials = await WorkspaceCredentials.getCredentialByScope(scope);
|
|
if (workspaceCredentials && !hasWorkspaceAccessTokenExpired(workspaceCredentials) && !forceNew) {
|
|
SystemLogger.debug({
|
|
msg: 'Workspace credentials cache hit. Avoiding generating a new access token from cloud services.',
|
|
scope,
|
|
});
|
|
return workspaceCredentials.accessToken;
|
|
}
|
|
|
|
SystemLogger.debug({
|
|
msg: 'Workspace credentials cache miss, fetching new access token from cloud services.',
|
|
scope,
|
|
});
|
|
|
|
const accessToken = await getWorkspaceAccessTokenWithScope({ scope, throwOnError });
|
|
|
|
if (save) {
|
|
await WorkspaceCredentials.updateCredentialByScope({
|
|
scope: accessToken.scope,
|
|
accessToken: accessToken.token,
|
|
expirationDate: accessToken.expiresAt,
|
|
});
|
|
}
|
|
|
|
return accessToken.token;
|
|
}
|
|
|
|
export class CloudWorkspaceAccessTokenError extends Error {
|
|
constructor() {
|
|
super('Could not get workspace access token');
|
|
}
|
|
}
|
|
|
|
export const isAbortError = (error: unknown): error is { type: 'AbortError' } => {
|
|
if (typeof error !== 'object' || error === null) {
|
|
return false;
|
|
}
|
|
|
|
return 'type' in error && error.type === 'AbortError';
|
|
};
|
|
|
|
export class CloudWorkspaceAccessTokenEmptyError extends Error {
|
|
constructor() {
|
|
super('Workspace access token is empty');
|
|
}
|
|
}
|
|
|
|
export async function getWorkspaceAccessTokenOrThrow(forceNew = false, scope = '', save = true): Promise<string> {
|
|
const token = await getWorkspaceAccessToken(forceNew, scope, save, true);
|
|
|
|
if (!token) {
|
|
throw new CloudWorkspaceAccessTokenEmptyError();
|
|
}
|
|
|
|
return token;
|
|
}
|
|
|
|
export const generateWorkspaceBearerHttpHeaderOrThrow = async (
|
|
forceNew = false,
|
|
scope = '',
|
|
save = true,
|
|
): Promise<{ Authorization: string }> => {
|
|
const token = await getWorkspaceAccessTokenOrThrow(forceNew, scope, save);
|
|
return {
|
|
Authorization: `Bearer ${token}`,
|
|
};
|
|
};
|
|
|
|
export const generateWorkspaceBearerHttpHeader = async (
|
|
forceNew = false,
|
|
scope = '',
|
|
save = true,
|
|
): Promise<{ Authorization: string } | undefined> => {
|
|
const token = await getWorkspaceAccessToken(forceNew, scope, save);
|
|
|
|
if (!token) {
|
|
return undefined;
|
|
}
|
|
|
|
return {
|
|
Authorization: `Bearer ${token}`,
|
|
};
|
|
};
|