Twenty sdk cli oauth (#18638)
<img width="1418" height="804" alt="image" src="https://github.com/user-attachments/assets/de6c8222-6496-4a71-bc21-7e5e1269d5cb" /> --------- Co-authored-by: Félix Malfait <felix.malfait@gmail.com> Co-authored-by: Félix Malfait <felix@twenty.com>
This commit is contained in:
@@ -0,0 +1,177 @@
|
||||
import { ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import axios, { type AxiosInstance } from 'axios';
|
||||
import chalk from 'chalk';
|
||||
|
||||
export class ApiClient {
|
||||
readonly client: AxiosInstance;
|
||||
readonly configService: ConfigService;
|
||||
private readonly tokenOverride?: string;
|
||||
readonly serverUrlOverride?: string;
|
||||
|
||||
constructor(options?: {
|
||||
disableInterceptors?: boolean;
|
||||
serverUrl?: string;
|
||||
token?: string;
|
||||
}) {
|
||||
const { disableInterceptors = false, serverUrl, token } = options || {};
|
||||
this.configService = new ConfigService();
|
||||
this.tokenOverride = token;
|
||||
this.serverUrlOverride = serverUrl;
|
||||
this.client = axios.create();
|
||||
|
||||
this.client.interceptors.request.use(async (config) => {
|
||||
const twentyConfig = await this.configService.getConfig();
|
||||
|
||||
config.baseURL = this.serverUrlOverride ?? twentyConfig.apiUrl;
|
||||
|
||||
if (!config.headers.Authorization) {
|
||||
const authToken = await this.resolveAuthToken();
|
||||
|
||||
if (authToken) {
|
||||
config.headers.Authorization = `Bearer ${authToken}`;
|
||||
}
|
||||
}
|
||||
|
||||
return config;
|
||||
});
|
||||
|
||||
if (disableInterceptors) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.client.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
if (error.response?.status === 401) {
|
||||
console.error(
|
||||
chalk.red(
|
||||
'Authentication failed. Run `twenty remote add` to authenticate.',
|
||||
),
|
||||
);
|
||||
} else if (error.response?.status === 403) {
|
||||
console.error(
|
||||
chalk.red(
|
||||
'Access denied. Check your API key and workspace permissions.',
|
||||
),
|
||||
);
|
||||
} else if (error.code === 'ECONNREFUSED') {
|
||||
console.error(
|
||||
chalk.red('Cannot connect to Twenty server. Is it running?'),
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async validateAuth(): Promise<{ authValid: boolean; serverUp: boolean }> {
|
||||
try {
|
||||
const query = `
|
||||
query CurrentWorkspace {
|
||||
currentWorkspace {
|
||||
id
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
authValid: response.status === 200 && !response.data.errors,
|
||||
serverUp: response.status === 200,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
authValid: false,
|
||||
serverUp: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
authValid: false,
|
||||
serverUp: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async refreshToken(): Promise<string | null> {
|
||||
const config = await this.configService.getConfig();
|
||||
|
||||
if (!config.refreshToken || !config.oauthClientId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const tokenResponse = await axios.post(`${config.apiUrl}/oauth/token`, {
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: config.refreshToken,
|
||||
client_id: config.oauthClientId,
|
||||
});
|
||||
|
||||
const { access_token: newAccessToken, refresh_token: newRefreshToken } =
|
||||
tokenResponse.data;
|
||||
|
||||
await this.configService.setConfig({
|
||||
accessToken: newAccessToken,
|
||||
...(newRefreshToken ? { refreshToken: newRefreshToken } : {}),
|
||||
});
|
||||
|
||||
return newAccessToken;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async resolveAuthToken(): Promise<string | undefined> {
|
||||
if (this.tokenOverride) {
|
||||
return this.tokenOverride;
|
||||
}
|
||||
|
||||
const envToken = process.env.TWENTY_TOKEN;
|
||||
|
||||
if (envToken) {
|
||||
return envToken;
|
||||
}
|
||||
|
||||
const config = await this.configService.getConfig();
|
||||
const accessToken = config.accessToken;
|
||||
|
||||
if (accessToken && this.isTokenExpired(accessToken)) {
|
||||
const refreshed = await this.refreshToken();
|
||||
|
||||
if (refreshed) {
|
||||
return refreshed;
|
||||
}
|
||||
}
|
||||
|
||||
return accessToken ?? config.apiKey;
|
||||
}
|
||||
|
||||
private isTokenExpired(token: string): boolean {
|
||||
try {
|
||||
const payload = JSON.parse(
|
||||
Buffer.from(token.split('.')[1], 'base64').toString(),
|
||||
);
|
||||
|
||||
const EXPIRATION_MARGIN_IN_SECONDS = 30;
|
||||
|
||||
return (
|
||||
payload.exp * 1_000 < Date.now() + EXPIRATION_MARGIN_IN_SECONDS * 1_000
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,286 @@
|
||||
import { type ApiResponse } from '@/cli/utilities/api/api-response-type';
|
||||
import axios, { type AxiosInstance, type AxiosResponse } from 'axios';
|
||||
import { type Manifest } from 'twenty-shared/application';
|
||||
|
||||
export class ApplicationApi {
|
||||
constructor(private readonly client: AxiosInstance) {}
|
||||
|
||||
async findApplicationRegistrationByUniversalIdentifier(
|
||||
universalIdentifier: string,
|
||||
): Promise<
|
||||
ApiResponse<{
|
||||
id: string;
|
||||
universalIdentifier: string;
|
||||
name: string;
|
||||
oAuthClientId: string;
|
||||
} | null>
|
||||
> {
|
||||
try {
|
||||
const query = `
|
||||
query FindApplicationRegistrationByUniversalIdentifier($universalIdentifier: String!) {
|
||||
findApplicationRegistrationByUniversalIdentifier(universalIdentifier: $universalIdentifier) {
|
||||
id
|
||||
universalIdentifier
|
||||
name
|
||||
oAuthClientId
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query,
|
||||
variables: { universalIdentifier },
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data
|
||||
.findApplicationRegistrationByUniversalIdentifier,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async createApplicationRegistration(input: {
|
||||
name: string;
|
||||
description?: string;
|
||||
universalIdentifier: string;
|
||||
}): Promise<
|
||||
ApiResponse<{
|
||||
applicationRegistration: {
|
||||
id: string;
|
||||
universalIdentifier: string;
|
||||
oAuthClientId: string;
|
||||
};
|
||||
clientSecret: string;
|
||||
}>
|
||||
> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation CreateApplicationRegistration($input: CreateApplicationRegistrationInput!) {
|
||||
createApplicationRegistration(input: $input) {
|
||||
applicationRegistration {
|
||||
id
|
||||
universalIdentifier
|
||||
oAuthClientId
|
||||
}
|
||||
clientSecret
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables: { input },
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.createApplicationRegistration,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async createDevelopmentApplication(input: {
|
||||
universalIdentifier: string;
|
||||
name: string;
|
||||
}): Promise<ApiResponse<{ id: string; universalIdentifier: string }>> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation CreateDevelopmentApplication($universalIdentifier: String!, $name: String!) {
|
||||
createDevelopmentApplication(universalIdentifier: $universalIdentifier, name: $name) {
|
||||
id
|
||||
universalIdentifier
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables: input,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.createDevelopmentApplication,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async syncApplication(manifest: Manifest): Promise<ApiResponse> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation SyncApplication($manifest: JSON!) {
|
||||
syncApplication(manifest: $manifest) {
|
||||
applicationUniversalIdentifier
|
||||
actions
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const variables = { manifest };
|
||||
|
||||
const response: AxiosResponse = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.syncApplication,
|
||||
message: `Successfully synced application: ${manifest.application.displayName}`,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
const graphqlErrors = error.response.data?.errors;
|
||||
|
||||
if (Array.isArray(graphqlErrors) && graphqlErrors.length > 0) {
|
||||
return {
|
||||
success: false,
|
||||
error: graphqlErrors[0]?.message || error.message,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
error.response.data?.message ||
|
||||
`HTTP ${error.response.status}: ${error.message}`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async uninstallApplication(
|
||||
universalIdentifier: string,
|
||||
): Promise<ApiResponse> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation UninstallApplication($universalIdentifier: String!) {
|
||||
uninstallApplication(universalIdentifier: $universalIdentifier)
|
||||
}
|
||||
`;
|
||||
|
||||
const variables = { universalIdentifier };
|
||||
|
||||
const response: AxiosResponse = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
response.data.errors[0]?.message || 'Failed to delete application',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.uninstallApplication,
|
||||
message: 'Successfully uninstalled application',
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.response.data?.errors?.[0]?.message || error.message,
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import { type ApiResponse } from '@/cli/utilities/api/api-response-type';
|
||||
import axios, { type AxiosInstance, type AxiosResponse } from 'axios';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { type FileFolder } from 'twenty-shared/types';
|
||||
import { pascalCase } from 'twenty-shared/utils';
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.png': 'image/png',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.bmp': 'image/bmp',
|
||||
'.ico': 'image/x-icon',
|
||||
'.pdf': 'application/pdf',
|
||||
'.doc': 'application/msword',
|
||||
'.docx':
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'.xls': 'application/vnd.ms-excel',
|
||||
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'.ppt': 'application/vnd.ms-powerpoint',
|
||||
'.pptx':
|
||||
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
'.txt': 'text/plain',
|
||||
'.csv': 'text/csv',
|
||||
'.json': 'application/json',
|
||||
'.xml': 'application/xml',
|
||||
'.zip': 'application/zip',
|
||||
'.tar': 'application/x-tar',
|
||||
'.gz': 'application/gzip',
|
||||
'.mp3': 'audio/mpeg',
|
||||
'.mp4': 'video/mp4',
|
||||
'.avi': 'video/x-msvideo',
|
||||
'.mov': 'video/quicktime',
|
||||
'.js': 'application/javascript',
|
||||
'.ts': 'application/typescript',
|
||||
'.jsx': 'application/javascript',
|
||||
'.tsx': 'application/typescript',
|
||||
'.html': 'text/html',
|
||||
'.css': 'text/css',
|
||||
};
|
||||
|
||||
const getMimeType = (filename: string): string => {
|
||||
const ext = path.extname(filename).toLowerCase();
|
||||
|
||||
return MIME_TYPES[ext] || 'application/octet-stream';
|
||||
};
|
||||
|
||||
export class FileApi {
|
||||
constructor(private readonly client: AxiosInstance) {}
|
||||
|
||||
// TODO: Migrate to MetadataClient once available
|
||||
// (see https://github.com/twentyhq/core-team-issues/issues/2289)
|
||||
async uploadAppTarball({
|
||||
tarballBuffer,
|
||||
universalIdentifier,
|
||||
}: {
|
||||
tarballBuffer: Buffer;
|
||||
universalIdentifier?: string;
|
||||
}): Promise<
|
||||
ApiResponse<{
|
||||
id: string;
|
||||
universalIdentifier: string;
|
||||
name: string;
|
||||
}>
|
||||
> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation UploadAppTarball($file: Upload!, $universalIdentifier: String) {
|
||||
uploadAppTarball(file: $file, universalIdentifier: $universalIdentifier) {
|
||||
id
|
||||
universalIdentifier
|
||||
name
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const operations = JSON.stringify({
|
||||
query: mutation,
|
||||
variables: {
|
||||
file: null,
|
||||
universalIdentifier: universalIdentifier ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
const map = JSON.stringify({
|
||||
'0': ['variables.file'],
|
||||
});
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
formData.append('operations', operations);
|
||||
formData.append('map', map);
|
||||
formData.append(
|
||||
'0',
|
||||
new Blob([new Uint8Array(tarballBuffer)], {
|
||||
type: 'application/gzip',
|
||||
}),
|
||||
'app.tar.gz',
|
||||
);
|
||||
|
||||
const response: AxiosResponse = await this.client.post(
|
||||
'/metadata',
|
||||
formData,
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0]?.message || 'Failed to upload tarball',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.uploadAppTarball,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.response.data?.errors?.[0]?.message || error.message,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async installTarballApp({
|
||||
universalIdentifier,
|
||||
}: {
|
||||
universalIdentifier: string;
|
||||
}): Promise<ApiResponse<boolean>> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation InstallMarketplaceApp($universalIdentifier: String!) {
|
||||
installMarketplaceApp(universalIdentifier: $universalIdentifier)
|
||||
}
|
||||
`;
|
||||
|
||||
const response: AxiosResponse = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables: { universalIdentifier },
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
response.data.errors[0]?.message || 'Failed to install application',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.installMarketplaceApp,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.response.data?.errors?.[0]?.message || error.message,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async uploadFile({
|
||||
filePath,
|
||||
builtHandlerPath,
|
||||
fileFolder,
|
||||
applicationUniversalIdentifier,
|
||||
}: {
|
||||
filePath: string;
|
||||
builtHandlerPath: string;
|
||||
fileFolder: FileFolder;
|
||||
applicationUniversalIdentifier: string;
|
||||
}): Promise<ApiResponse<boolean>> {
|
||||
try {
|
||||
const absolutePath = path.resolve(filePath);
|
||||
|
||||
if (!fs.existsSync(absolutePath)) {
|
||||
return {
|
||||
success: false,
|
||||
error: `File not found: ${absolutePath}`,
|
||||
};
|
||||
}
|
||||
|
||||
const filename = path.basename(absolutePath);
|
||||
const buffer = fs.readFileSync(absolutePath);
|
||||
const mimeType = getMimeType(filename);
|
||||
|
||||
const mutation = `
|
||||
mutation UploadApplicationFile($file: Upload!, $applicationUniversalIdentifier: String!, $fileFolder: FileFolder!, $filePath: String!) {
|
||||
uploadApplicationFile(file: $file, applicationUniversalIdentifier: $applicationUniversalIdentifier, fileFolder: $fileFolder, filePath: $filePath)
|
||||
{ path }
|
||||
}
|
||||
`;
|
||||
|
||||
const graphqlEnumFileFolder = pascalCase(fileFolder);
|
||||
|
||||
const operations = JSON.stringify({
|
||||
query: mutation,
|
||||
variables: {
|
||||
file: null,
|
||||
applicationUniversalIdentifier,
|
||||
filePath: builtHandlerPath,
|
||||
fileFolder: graphqlEnumFileFolder,
|
||||
},
|
||||
});
|
||||
|
||||
const map = JSON.stringify({
|
||||
'0': ['variables.file'],
|
||||
});
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
formData.append('operations', operations);
|
||||
formData.append('map', map);
|
||||
formData.append(
|
||||
'0',
|
||||
new Blob([new Uint8Array(buffer)], { type: mimeType }),
|
||||
filename,
|
||||
);
|
||||
|
||||
const response: AxiosResponse = await this.client.post(
|
||||
'/metadata',
|
||||
formData,
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0]?.message || 'Failed to upload file',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.uploadApplicationFile,
|
||||
message: `Successfully uploaded ${filename}`,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.response.data?.errors?.[0]?.message || error.message,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import { type ApiClient } from '@/cli/utilities/api/api-client';
|
||||
import { type ApiResponse } from '@/cli/utilities/api/api-response-type';
|
||||
import { createClient } from 'graphql-sse';
|
||||
|
||||
export class LogicFunctionApi {
|
||||
constructor(private readonly apiClient: ApiClient) {}
|
||||
|
||||
async findLogicFunctions(): Promise<
|
||||
ApiResponse<
|
||||
Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
universalIdentifier: string;
|
||||
applicationId: string | null;
|
||||
}>
|
||||
>
|
||||
> {
|
||||
try {
|
||||
const query = `
|
||||
query FindManyLogicFunctions {
|
||||
findManyLogicFunctions {
|
||||
id
|
||||
name
|
||||
universalIdentifier
|
||||
applicationId
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await this.apiClient.client.post(
|
||||
'/metadata',
|
||||
{ query },
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
response.data.errors[0]?.message || 'Failed to fetch functions',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.findManyLogicFunctions,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async executeLogicFunction({
|
||||
functionId,
|
||||
payload,
|
||||
}: {
|
||||
functionId: string;
|
||||
payload: Record<string, unknown>;
|
||||
}): Promise<
|
||||
ApiResponse<{
|
||||
data: unknown;
|
||||
logs: string;
|
||||
duration: number;
|
||||
status: string;
|
||||
error?: {
|
||||
errorType: string;
|
||||
errorMessage: string;
|
||||
stackTrace: string;
|
||||
};
|
||||
}>
|
||||
> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation ExecuteOneLogicFunction($input: ExecuteOneLogicFunctionInput!) {
|
||||
executeOneLogicFunction(input: $input) {
|
||||
data
|
||||
logs
|
||||
duration
|
||||
status
|
||||
error
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const variables = {
|
||||
input: {
|
||||
id: functionId,
|
||||
payload,
|
||||
},
|
||||
};
|
||||
|
||||
const response = await this.apiClient.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
response.data.errors[0]?.message ||
|
||||
'Failed to execute logic function',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.executeOneLogicFunction,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async subscribeToLogs({
|
||||
applicationUniversalIdentifier,
|
||||
functionUniversalIdentifier,
|
||||
functionName,
|
||||
}: {
|
||||
applicationUniversalIdentifier: string;
|
||||
functionUniversalIdentifier?: string;
|
||||
functionName?: string;
|
||||
}) {
|
||||
const twentyConfig = await this.apiClient.configService.getConfig();
|
||||
const baseUrl = this.apiClient.serverUrlOverride ?? twentyConfig.apiUrl;
|
||||
|
||||
const wsClient = createClient({
|
||||
url: baseUrl + '/metadata',
|
||||
headers: async () => {
|
||||
const authToken = await this.apiClient.resolveAuthToken();
|
||||
|
||||
return {
|
||||
Authorization: authToken ? `Bearer ${authToken}` : '',
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'text/event-stream',
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const query = `
|
||||
subscription SubscribeToLogs($input: LogicFunctionLogsInput!) {
|
||||
logicFunctionLogs(input: $input) {
|
||||
logs
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const variables = {
|
||||
input: {
|
||||
applicationUniversalIdentifier,
|
||||
universalIdentifier: functionUniversalIdentifier,
|
||||
name: functionName,
|
||||
},
|
||||
};
|
||||
|
||||
wsClient.subscribe<{ logicFunctionLogs: { logs: string } }>(
|
||||
{
|
||||
query,
|
||||
variables,
|
||||
},
|
||||
{
|
||||
next: ({ data }) => console.log(data?.logicFunctionLogs.logs),
|
||||
error: (err: unknown) => console.error(err),
|
||||
complete: () => console.log('Completed'),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { type ApiResponse } from '@/cli/utilities/api/api-response-type';
|
||||
import axios, { type AxiosInstance } from 'axios';
|
||||
import { buildClientSchema, getIntrospectionQuery, printSchema } from 'graphql';
|
||||
|
||||
export class SchemaApi {
|
||||
constructor(private readonly client: AxiosInstance) {}
|
||||
|
||||
async getSchema(options?: {
|
||||
authToken?: string;
|
||||
}): Promise<ApiResponse<string>> {
|
||||
return this.introspectEndpoint('/graphql', options);
|
||||
}
|
||||
|
||||
async getMetadataSchema(options?: {
|
||||
authToken?: string;
|
||||
}): Promise<ApiResponse<string>> {
|
||||
return this.introspectEndpoint('/metadata', options);
|
||||
}
|
||||
|
||||
private async introspectEndpoint(
|
||||
endpoint: string,
|
||||
options?: { authToken?: string },
|
||||
): Promise<ApiResponse<string>> {
|
||||
try {
|
||||
const introspectionQuery = getIntrospectionQuery();
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
};
|
||||
|
||||
if (options?.authToken) {
|
||||
headers.Authorization = `Bearer ${options.authToken}`;
|
||||
}
|
||||
|
||||
const response = await this.client.post(
|
||||
endpoint,
|
||||
{
|
||||
query: introspectionQuery,
|
||||
},
|
||||
{ headers },
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: `GraphQL introspection errors: ${JSON.stringify(response.data.errors)}`,
|
||||
};
|
||||
}
|
||||
|
||||
const schema = buildClientSchema(response.data.data);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: printSchema(schema),
|
||||
message: `Successfully loaded schema from ${endpoint}`,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
error.response.data?.errors?.[0]?.message ||
|
||||
`Failed to load schema from ${endpoint}`,
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import http from 'node:http';
|
||||
|
||||
import { startCallbackServer } from '../callback-server';
|
||||
|
||||
const httpGet = (url: string): Promise<{ status: number; body: string }> =>
|
||||
new Promise((resolve, reject) => {
|
||||
http
|
||||
.get(url, (res) => {
|
||||
let body = '';
|
||||
|
||||
res.on('data', (chunk: string) => (body += chunk));
|
||||
res.on('end', () => resolve({ status: res.statusCode ?? 0, body }));
|
||||
})
|
||||
.on('error', reject);
|
||||
});
|
||||
|
||||
describe('startCallbackServer', () => {
|
||||
it('should start on a random port and provide a callback URL', async () => {
|
||||
const server = await startCallbackServer();
|
||||
|
||||
try {
|
||||
expect(server.port).toBeGreaterThan(0);
|
||||
expect(server.callbackUrl).toBe(
|
||||
`http://127.0.0.1:${server.port}/callback`,
|
||||
);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('should resolve with the authorization code on successful callback', async () => {
|
||||
const server = await startCallbackServer();
|
||||
|
||||
try {
|
||||
const waitPromise = server.waitForCallback();
|
||||
|
||||
await httpGet(`${server.callbackUrl}?code=test-auth-code`);
|
||||
|
||||
const result = await waitPromise;
|
||||
|
||||
expect(result).toEqual({ success: true, code: 'test-auth-code' });
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('should resolve with error when callback contains an error', async () => {
|
||||
const server = await startCallbackServer();
|
||||
|
||||
try {
|
||||
const waitPromise = server.waitForCallback();
|
||||
|
||||
await httpGet(`${server.callbackUrl}?error=access_denied`);
|
||||
|
||||
const result = await waitPromise;
|
||||
|
||||
expect(result).toEqual({ success: false, error: 'access_denied' });
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('should return 404 for non-callback paths', async () => {
|
||||
const server = await startCallbackServer();
|
||||
|
||||
try {
|
||||
const response = await httpGet(
|
||||
`http://127.0.0.1:${server.port}/other-path`,
|
||||
);
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('should time out if no callback is received', async () => {
|
||||
const server = await startCallbackServer({ timeoutMs: 500 });
|
||||
|
||||
try {
|
||||
const result = await server.waitForCallback();
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
|
||||
if (!result.success) {
|
||||
expect(result.error).toContain('Timed out');
|
||||
}
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
import { generatePkceChallenge } from '../pkce';
|
||||
|
||||
describe('generatePkceChallenge', () => {
|
||||
it('should return a code verifier and code challenge', () => {
|
||||
const { codeVerifier, codeChallenge } = generatePkceChallenge();
|
||||
|
||||
expect(codeVerifier).toBeDefined();
|
||||
expect(codeChallenge).toBeDefined();
|
||||
expect(codeVerifier.length).toBeGreaterThan(0);
|
||||
expect(codeChallenge.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should produce a challenge that is the SHA256 hash of the verifier', () => {
|
||||
const { codeVerifier, codeChallenge } = generatePkceChallenge();
|
||||
|
||||
const expectedChallenge = crypto
|
||||
.createHash('sha256')
|
||||
.update(codeVerifier)
|
||||
.digest('base64url');
|
||||
|
||||
expect(codeChallenge).toBe(expectedChallenge);
|
||||
});
|
||||
|
||||
it('should generate unique values on each call', () => {
|
||||
const first = generatePkceChallenge();
|
||||
const second = generatePkceChallenge();
|
||||
|
||||
expect(first.codeVerifier).not.toBe(second.codeVerifier);
|
||||
expect(first.codeChallenge).not.toBe(second.codeChallenge);
|
||||
});
|
||||
|
||||
it('should use base64url encoding with no padding', () => {
|
||||
const { codeVerifier, codeChallenge } = generatePkceChallenge();
|
||||
|
||||
// base64url uses - and _ instead of + and /, and no = padding
|
||||
expect(codeVerifier).not.toMatch(/[+/=]/);
|
||||
expect(codeChallenge).not.toMatch(/[+/=]/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import http from 'node:http';
|
||||
|
||||
type CallbackResult =
|
||||
| { success: true; code: string }
|
||||
| { success: false; error: string };
|
||||
|
||||
type CallbackServer = {
|
||||
port: number;
|
||||
callbackUrl: string;
|
||||
waitForCallback: () => Promise<CallbackResult>;
|
||||
close: () => void;
|
||||
};
|
||||
|
||||
const TWENTY_LOGO_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 96 96">
|
||||
<rect width="96" height="96" rx="11.3" fill="#000"/>
|
||||
<path fill="#fff" d="M19.25 35.75c0-5.25 4.26-9.5 9.5-9.5h18.29c.27 0 .51.16.63.4.11.25.06.54-.12.75l-4.01 4.35c-.7.76-1.68 1.2-2.71 1.2H28.8c-1.57 0-2.85 1.27-2.85 2.85v7.18c0 .93-.75 1.67-1.68 1.67h-3.34c-.93 0-1.67-.75-1.67-1.67v-7.23z"/>
|
||||
<path fill="#fff" d="M76.15 60.25c0 5.25-4.26 9.5-9.5 9.5h-7.77c-5.25 0-9.5-4.25-9.5-9.5V46.65c0-.93.35-1.82.98-2.5l4.53-4.92c.19-.2.49-.27.75-.17.26.11.44.36.44.64v20.52c0 1.57 1.28 2.85 2.85 2.85h7.68c1.57 0 2.85-1.28 2.85-2.85V35.8c0-1.57-1.28-2.85-2.85-2.85h-8.93c-1.02 0-2 .43-2.7 1.18L28.35 63.06h16c.92 0 1.67.75 1.67 1.68v3.34c0 .93-.75 1.67-1.67 1.67H22.79c-1.95 0-3.55-1.59-3.55-3.54v-1.77c0-.89.33-1.75.94-2.4l29.86-32.43c1.98-2.15 4.75-3.36 7.67-3.36h8.93c5.25 0 9.5 4.25 9.5 9.5v24.5z"/>
|
||||
</svg>`;
|
||||
|
||||
const pageHtml = ({
|
||||
title,
|
||||
message,
|
||||
isSuccess,
|
||||
}: {
|
||||
title: string;
|
||||
message: string;
|
||||
isSuccess: boolean;
|
||||
}) => `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>${title} — Twenty</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
|
||||
background: #fafafa;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100dvh;
|
||||
color: #333;
|
||||
}
|
||||
.card {
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
box-shadow: 2px 4px 16px rgba(0,0,0,0.08), 0 2px 4px rgba(0,0,0,0.04);
|
||||
padding: 32px;
|
||||
width: 400px;
|
||||
max-width: calc(100vw - 32px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
.logo { margin-bottom: 4px; }
|
||||
.icon {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.icon-success { background: #f0faf0; }
|
||||
.icon-error { background: #fef0f0; }
|
||||
.icon svg { width: 24px; height: 24px; }
|
||||
h2 {
|
||||
font-size: 1.23rem;
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
}
|
||||
p {
|
||||
font-size: 0.92rem;
|
||||
color: #666;
|
||||
text-align: center;
|
||||
line-height: 1.5;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<div class="logo">${TWENTY_LOGO_SVG}</div>
|
||||
<div class="icon ${isSuccess ? 'icon-success' : 'icon-error'}">
|
||||
${
|
||||
isSuccess
|
||||
? '<svg viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>'
|
||||
: '<svg viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>'
|
||||
}
|
||||
</div>
|
||||
<h2>${title}</h2>
|
||||
<p>${message}</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
const SUCCESS_HTML = pageHtml({
|
||||
title: 'Authentication successful',
|
||||
message: 'You can close this window and return to the terminal.',
|
||||
isSuccess: true,
|
||||
});
|
||||
|
||||
const escapeHtml = (text: string): string =>
|
||||
text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
|
||||
const errorHtml = (error: string) =>
|
||||
pageHtml({
|
||||
title: 'Authentication failed',
|
||||
message: `${escapeHtml(error)}<br>Please return to the terminal and try again.`,
|
||||
isSuccess: false,
|
||||
});
|
||||
|
||||
export const startCallbackServer = (options?: {
|
||||
timeoutMs?: number;
|
||||
}): Promise<CallbackServer> => {
|
||||
const timeoutMs = options?.timeoutMs ?? 120_000;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let callbackResolve: (result: CallbackResult) => void;
|
||||
let timeoutHandle: ReturnType<typeof setTimeout>;
|
||||
|
||||
const callbackPromise = new Promise<CallbackResult>((res) => {
|
||||
callbackResolve = res;
|
||||
});
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
const url = new URL(req.url ?? '/', `http://127.0.0.1`);
|
||||
|
||||
if (url.pathname !== '/callback') {
|
||||
res.writeHead(404);
|
||||
res.end('Not found');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const code = url.searchParams.get('code');
|
||||
const error = url.searchParams.get('error');
|
||||
|
||||
const headers = {
|
||||
'Content-Type': 'text/html',
|
||||
Connection: 'close',
|
||||
};
|
||||
|
||||
if (code) {
|
||||
res.writeHead(200, headers);
|
||||
res.end(SUCCESS_HTML);
|
||||
callbackResolve({ success: true, code });
|
||||
} else {
|
||||
const errorMessage =
|
||||
error ?? url.searchParams.get('error_description') ?? 'Unknown error';
|
||||
|
||||
res.writeHead(200, headers);
|
||||
res.end(errorHtml(errorMessage));
|
||||
callbackResolve({ success: false, error: errorMessage });
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
const address = server.address();
|
||||
|
||||
if (!address || typeof address === 'string') {
|
||||
reject(new Error('Failed to start callback server'));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const port = address.port;
|
||||
|
||||
resolve({
|
||||
port,
|
||||
callbackUrl: `http://127.0.0.1:${port}/callback`,
|
||||
waitForCallback: () => {
|
||||
timeoutHandle = setTimeout(() => {
|
||||
callbackResolve({
|
||||
success: false,
|
||||
error: `Timed out waiting for authorization (${timeoutMs / 1000}s)`,
|
||||
});
|
||||
}, timeoutMs);
|
||||
|
||||
return callbackPromise.finally(() => {
|
||||
clearTimeout(timeoutHandle);
|
||||
});
|
||||
},
|
||||
close: () => {
|
||||
clearTimeout(timeoutHandle);
|
||||
server.closeAllConnections();
|
||||
server.close();
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
server.on('error', reject);
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
import { execFile } from 'node:child_process';
|
||||
|
||||
export const openBrowser = (url: string): Promise<boolean> => {
|
||||
try {
|
||||
new URL(url);
|
||||
} catch {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
const [command, args]: [string, string[]] =
|
||||
process.platform === 'darwin'
|
||||
? ['open', [url]]
|
||||
: process.platform === 'win32'
|
||||
? ['cmd', ['/c', 'start', '', url]]
|
||||
: ['xdg-open', [url]];
|
||||
|
||||
return new Promise((resolve) => {
|
||||
execFile(command, args, (error) => {
|
||||
resolve(!error);
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
export type PkceChallenge = {
|
||||
codeVerifier: string;
|
||||
codeChallenge: string;
|
||||
};
|
||||
|
||||
export const generatePkceChallenge = (): PkceChallenge => {
|
||||
const codeVerifier = crypto.randomBytes(32).toString('base64url');
|
||||
const codeChallenge = crypto
|
||||
.createHash('sha256')
|
||||
.update(codeVerifier)
|
||||
.digest('base64url');
|
||||
|
||||
return { codeVerifier, codeChallenge };
|
||||
};
|
||||
@@ -1,7 +1,4 @@
|
||||
import {
|
||||
APP_ERROR_CODES,
|
||||
type CommandResult,
|
||||
} from '@/cli/public-operations/types';
|
||||
import { APP_ERROR_CODES, type CommandResult } from '@/cli/types';
|
||||
import { ApiService } from '@/cli/utilities/api/api-service';
|
||||
import { type BuiltFileInfo } from '@/cli/utilities/build/common/build-application';
|
||||
import { manifestUpdateChecksums } from '@/cli/utilities/build/manifest/manifest-update-checksums';
|
||||
@@ -12,7 +9,7 @@ import { type Manifest } from 'twenty-shared/application';
|
||||
|
||||
export type AppSyncOptions = {
|
||||
appPath: string;
|
||||
workspace?: string;
|
||||
remote?: string;
|
||||
};
|
||||
|
||||
const ensureApplicationRegistrationExists = async (
|
||||
|
||||
@@ -368,21 +368,27 @@ export const buildManifest = async (
|
||||
};
|
||||
}
|
||||
|
||||
const byId = <T extends { universalIdentifier: string }>(a: T, b: T) =>
|
||||
a.universalIdentifier.localeCompare(b.universalIdentifier);
|
||||
|
||||
const byPath = <T extends { filePath: string }>(a: T, b: T) =>
|
||||
a.filePath.localeCompare(b.filePath);
|
||||
|
||||
const manifest = !application
|
||||
? null
|
||||
: {
|
||||
application,
|
||||
objects,
|
||||
fields,
|
||||
roles,
|
||||
skills,
|
||||
agents,
|
||||
logicFunctions,
|
||||
frontComponents,
|
||||
publicAssets,
|
||||
views,
|
||||
navigationMenuItems,
|
||||
pageLayouts,
|
||||
objects: objects.sort(byId),
|
||||
fields: fields.sort(byId),
|
||||
roles: roles.sort(byId),
|
||||
skills: skills.sort(byId),
|
||||
agents: agents.sort(byId),
|
||||
logicFunctions: logicFunctions.sort(byId),
|
||||
frontComponents: frontComponents.sort(byId),
|
||||
publicAssets: publicAssets.sort(byPath),
|
||||
views: views.sort(byId),
|
||||
navigationMenuItems: navigationMenuItems.sort(byId),
|
||||
pageLayouts: pageLayouts.sort(byId),
|
||||
};
|
||||
|
||||
const entityFilePaths: EntityFilePaths = {
|
||||
|
||||
@@ -5,158 +5,233 @@ import { ensureDir, ensureFile } from '@/cli/utilities/file/fs-utils';
|
||||
|
||||
import { getConfigPath } from '@/cli/utilities/config/get-config-path';
|
||||
|
||||
export type TwentyConfig = {
|
||||
export type RemoteConfig = {
|
||||
apiUrl: string;
|
||||
apiKey?: string;
|
||||
applicationAccessToken?: string;
|
||||
applicationRefreshToken?: string;
|
||||
accessToken?: string;
|
||||
refreshToken?: string;
|
||||
oauthClientId?: string;
|
||||
oauthClientSecret?: string;
|
||||
};
|
||||
|
||||
type PersistedConfig = TwentyConfig & {
|
||||
profiles?: Record<string, TwentyConfig>;
|
||||
defaultWorkspace?: string;
|
||||
type PersistedConfig = {
|
||||
version?: number;
|
||||
defaultRemote?: string;
|
||||
remotes?: Record<string, RemoteConfig>;
|
||||
};
|
||||
|
||||
const DEFAULT_WORKSPACE_NAME = 'default';
|
||||
const CONFIG_VERSION = 1;
|
||||
|
||||
const DEFAULT_REMOTE_NAME = 'local';
|
||||
|
||||
export class ConfigService {
|
||||
private readonly configPath: string;
|
||||
private static activeWorkspace = DEFAULT_WORKSPACE_NAME;
|
||||
private static activeRemote = DEFAULT_REMOTE_NAME;
|
||||
|
||||
constructor() {
|
||||
this.configPath = getConfigPath();
|
||||
}
|
||||
|
||||
static setActiveWorkspace(name?: string) {
|
||||
this.activeWorkspace = name ?? DEFAULT_WORKSPACE_NAME;
|
||||
static setActiveRemote(name?: string) {
|
||||
this.activeRemote = name ?? DEFAULT_REMOTE_NAME;
|
||||
}
|
||||
|
||||
static getActiveWorkspace(): string {
|
||||
return this.activeWorkspace;
|
||||
static getActiveRemote(): string {
|
||||
return this.activeRemote;
|
||||
}
|
||||
|
||||
private getActiveWorkspaceName(): string {
|
||||
return ConfigService.getActiveWorkspace();
|
||||
private getActiveRemoteName(): string {
|
||||
return ConfigService.getActiveRemote();
|
||||
}
|
||||
|
||||
private async readRawConfig(): Promise<PersistedConfig> {
|
||||
await ensureFile(this.configPath);
|
||||
const content = await readFile(this.configPath, 'utf8');
|
||||
return JSON.parse(content || '{}');
|
||||
const raw = JSON.parse(content || '{}');
|
||||
|
||||
return this.migrateConfigIfNeeded(raw);
|
||||
}
|
||||
|
||||
async getConfig(): Promise<TwentyConfig> {
|
||||
return this.getConfigForWorkspace(this.getActiveWorkspaceName());
|
||||
// TODO: Remove after 2026-04-30 — migrates legacy config format
|
||||
// (profiles, top-level keys, applicationAccessToken/applicationRefreshToken)
|
||||
// to the current format (remotes, accessToken/refreshToken)
|
||||
private async migrateConfigIfNeeded(
|
||||
raw: Record<string, unknown>,
|
||||
): Promise<PersistedConfig> {
|
||||
if ((raw as PersistedConfig).version === CONFIG_VERSION) {
|
||||
return raw as PersistedConfig;
|
||||
}
|
||||
|
||||
const hasLegacyProfiles = 'profiles' in raw;
|
||||
const hasTopLevelApiUrl = 'apiUrl' in raw && !('remotes' in raw);
|
||||
|
||||
if (!hasLegacyProfiles && !hasTopLevelApiUrl) {
|
||||
return raw as PersistedConfig;
|
||||
}
|
||||
|
||||
const migrated: PersistedConfig = { version: CONFIG_VERSION };
|
||||
|
||||
const str = (value: unknown): string | undefined =>
|
||||
typeof value === 'string' ? value : undefined;
|
||||
|
||||
const migrateRemoteFields = (
|
||||
source: Record<string, unknown>,
|
||||
): RemoteConfig => ({
|
||||
apiUrl: str(source.apiUrl) ?? '',
|
||||
apiKey: str(source.apiKey),
|
||||
accessToken:
|
||||
str(source.accessToken) ?? str(source.applicationAccessToken),
|
||||
refreshToken:
|
||||
str(source.refreshToken) ?? str(source.applicationRefreshToken),
|
||||
oauthClientId: str(source.oauthClientId),
|
||||
});
|
||||
|
||||
const profiles =
|
||||
(raw.profiles as Record<string, Record<string, unknown>> | undefined) ??
|
||||
{};
|
||||
|
||||
migrated.remotes = {};
|
||||
|
||||
for (const [name, profile] of Object.entries(profiles)) {
|
||||
const remoteName = name === 'default' ? DEFAULT_REMOTE_NAME : name;
|
||||
|
||||
migrated.remotes[remoteName] = migrateRemoteFields(profile);
|
||||
}
|
||||
|
||||
// Current-format remotes override legacy profiles — they're newer.
|
||||
const existingRemotes =
|
||||
(raw.remotes as Record<string, RemoteConfig> | undefined) ?? {};
|
||||
|
||||
for (const [name, remote] of Object.entries(existingRemotes)) {
|
||||
const remoteName = name === 'default' ? DEFAULT_REMOTE_NAME : name;
|
||||
|
||||
migrated.remotes[remoteName] = remote;
|
||||
}
|
||||
|
||||
if (hasTopLevelApiUrl && !migrated.remotes[DEFAULT_REMOTE_NAME]) {
|
||||
migrated.remotes[DEFAULT_REMOTE_NAME] = migrateRemoteFields(
|
||||
raw as Record<string, unknown>,
|
||||
);
|
||||
}
|
||||
|
||||
const legacyDefault = raw.defaultWorkspace as string | undefined;
|
||||
|
||||
if (legacyDefault) {
|
||||
migrated.defaultRemote =
|
||||
legacyDefault === 'default' ? DEFAULT_REMOTE_NAME : legacyDefault;
|
||||
}
|
||||
|
||||
await ensureDir(path.dirname(this.configPath));
|
||||
await writeFile(this.configPath, JSON.stringify(migrated, null, 2));
|
||||
|
||||
return migrated;
|
||||
}
|
||||
|
||||
async getConfigForWorkspace(workspaceName: string): Promise<TwentyConfig> {
|
||||
async getConfig(): Promise<RemoteConfig> {
|
||||
if (process.env.TWENTY_TOKEN && process.env.TWENTY_API_URL) {
|
||||
return {
|
||||
apiUrl: process.env.TWENTY_API_URL,
|
||||
accessToken: process.env.TWENTY_TOKEN,
|
||||
};
|
||||
}
|
||||
|
||||
return this.getConfigForRemote(this.getActiveRemoteName());
|
||||
}
|
||||
|
||||
async getConfigForRemote(remoteName: string): Promise<RemoteConfig> {
|
||||
const defaultConfig = this.getDefaultConfig();
|
||||
|
||||
try {
|
||||
const raw = await this.readRawConfig();
|
||||
const remoteConfig = raw.remotes?.[remoteName];
|
||||
|
||||
const profileConfig =
|
||||
workspaceName === DEFAULT_WORKSPACE_NAME &&
|
||||
!raw.profiles?.[DEFAULT_WORKSPACE_NAME]
|
||||
? raw
|
||||
: raw.profiles?.[workspaceName];
|
||||
|
||||
// Fallback to legacy top-level values if profile value is missing
|
||||
const apiUrl = profileConfig?.apiUrl ?? defaultConfig.apiUrl;
|
||||
const apiKey = profileConfig?.apiKey;
|
||||
const applicationAccessToken = profileConfig?.applicationAccessToken;
|
||||
const applicationRefreshToken = profileConfig?.applicationRefreshToken;
|
||||
if (!remoteConfig) {
|
||||
return defaultConfig;
|
||||
}
|
||||
|
||||
return {
|
||||
apiUrl,
|
||||
apiKey,
|
||||
applicationAccessToken,
|
||||
applicationRefreshToken,
|
||||
apiUrl: remoteConfig.apiUrl ?? defaultConfig.apiUrl,
|
||||
apiKey: remoteConfig.apiKey,
|
||||
accessToken: remoteConfig.accessToken,
|
||||
refreshToken: remoteConfig.refreshToken,
|
||||
oauthClientId: remoteConfig.oauthClientId,
|
||||
};
|
||||
} catch {
|
||||
return defaultConfig;
|
||||
}
|
||||
}
|
||||
|
||||
async setConfig(config: Partial<TwentyConfig>): Promise<void> {
|
||||
async setConfig(config: Partial<RemoteConfig>): Promise<void> {
|
||||
const raw = await this.readRawConfig();
|
||||
const profile = this.getActiveWorkspaceName();
|
||||
const remote = this.getActiveRemoteName();
|
||||
|
||||
// Ensure profiles map exists
|
||||
if (!raw.profiles) {
|
||||
raw.profiles = {};
|
||||
raw.version = CONFIG_VERSION;
|
||||
|
||||
if (!raw.remotes) {
|
||||
raw.remotes = {};
|
||||
}
|
||||
|
||||
const currentProfile = raw.profiles[profile] || { apiUrl: '' };
|
||||
const currentRemote = raw.remotes[remote] || { apiUrl: '' };
|
||||
|
||||
raw.profiles[profile] = { ...currentProfile, ...config };
|
||||
raw.remotes[remote] = { ...currentRemote, ...config };
|
||||
|
||||
await ensureDir(path.dirname(this.configPath));
|
||||
await writeFile(this.configPath, JSON.stringify(raw, null, 2));
|
||||
}
|
||||
|
||||
async clearConfig(): Promise<void> {
|
||||
// Clear only the active profile credentials (non-breaking for other profiles)
|
||||
const raw = await this.readRawConfig();
|
||||
const profile = this.getActiveWorkspaceName();
|
||||
const remote = this.getActiveRemoteName();
|
||||
|
||||
if (!raw.profiles) {
|
||||
raw.profiles = {};
|
||||
if (!raw.remotes) {
|
||||
raw.remotes = {};
|
||||
}
|
||||
|
||||
if (raw.profiles[profile]) {
|
||||
delete raw.profiles[profile];
|
||||
}
|
||||
|
||||
// Also clear legacy top-level apiKey for compatibility when active profile is default
|
||||
if (profile === DEFAULT_WORKSPACE_NAME) {
|
||||
const defaultConfig = this.getDefaultConfig();
|
||||
delete raw.apiKey;
|
||||
raw.apiUrl = defaultConfig.apiUrl;
|
||||
if (raw.remotes[remote]) {
|
||||
delete raw.remotes[remote];
|
||||
}
|
||||
|
||||
await ensureDir(path.dirname(this.configPath));
|
||||
await writeFile(this.configPath, JSON.stringify(raw, null, 2));
|
||||
}
|
||||
|
||||
private getDefaultConfig(): TwentyConfig {
|
||||
private getDefaultConfig(): RemoteConfig {
|
||||
return {
|
||||
apiUrl: 'http://localhost:3000',
|
||||
};
|
||||
}
|
||||
|
||||
async getAvailableWorkspaces(): Promise<string[]> {
|
||||
async getRemotes(): Promise<string[]> {
|
||||
try {
|
||||
const raw = await this.readRawConfig();
|
||||
const workspaces = new Set<string>();
|
||||
const remotes = new Set<string>();
|
||||
|
||||
// Always include the default workspace
|
||||
workspaces.add(DEFAULT_WORKSPACE_NAME);
|
||||
remotes.add(DEFAULT_REMOTE_NAME);
|
||||
|
||||
// Add all profiles
|
||||
if (raw.profiles) {
|
||||
Object.keys(raw.profiles).forEach((name) => workspaces.add(name));
|
||||
if (raw.remotes) {
|
||||
Object.keys(raw.remotes).forEach((name) => remotes.add(name));
|
||||
}
|
||||
|
||||
return Array.from(workspaces).sort();
|
||||
return Array.from(remotes).sort();
|
||||
} catch {
|
||||
return [DEFAULT_WORKSPACE_NAME];
|
||||
return [DEFAULT_REMOTE_NAME];
|
||||
}
|
||||
}
|
||||
|
||||
async getDefaultWorkspace(): Promise<string> {
|
||||
async getDefaultRemote(): Promise<string> {
|
||||
try {
|
||||
const raw = await this.readRawConfig();
|
||||
return raw.defaultWorkspace ?? DEFAULT_WORKSPACE_NAME;
|
||||
|
||||
return raw.defaultRemote ?? DEFAULT_REMOTE_NAME;
|
||||
} catch {
|
||||
return DEFAULT_WORKSPACE_NAME;
|
||||
return DEFAULT_REMOTE_NAME;
|
||||
}
|
||||
}
|
||||
|
||||
async setDefaultWorkspace(name: string): Promise<void> {
|
||||
async setDefaultRemote(name: string): Promise<void> {
|
||||
const raw = await this.readRawConfig();
|
||||
raw.defaultWorkspace = name;
|
||||
|
||||
raw.defaultRemote = name;
|
||||
|
||||
await ensureDir(path.dirname(this.configPath));
|
||||
await writeFile(this.configPath, JSON.stringify(raw, null, 2));
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import { ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import { type OrchestratorState } from '@/cli/utilities/dev/orchestrator/dev-mode-orchestrator-state';
|
||||
import { BuildManifestOrchestratorStep } from '@/cli/utilities/dev/orchestrator/steps/build-manifest-orchestrator-step';
|
||||
import { CheckServerOrchestratorStep } from '@/cli/utilities/dev/orchestrator/steps/check-server-orchestrator-step';
|
||||
import { EnsureValidTokensOrchestratorStep } from '@/cli/utilities/dev/orchestrator/steps/ensure-valid-tokens-orchestrator-step';
|
||||
import { GenerateApiClientOrchestratorStep } from '@/cli/utilities/dev/orchestrator/steps/generate-api-client-orchestrator-step';
|
||||
import { RegisterAppOrchestratorStep } from '@/cli/utilities/dev/orchestrator/steps/register-app-orchestrator-step';
|
||||
import {
|
||||
@@ -33,7 +32,6 @@ export class DevModeOrchestrator {
|
||||
private clientService: ClientService;
|
||||
private skipTypecheck = true;
|
||||
private checkServerStep: CheckServerOrchestratorStep;
|
||||
private ensureValidTokensStep: EnsureValidTokensOrchestratorStep;
|
||||
private buildManifestStep: BuildManifestOrchestratorStep;
|
||||
private registerAppStep: RegisterAppOrchestratorStep;
|
||||
private uploadFilesStep: UploadFilesOrchestratorStep;
|
||||
@@ -55,11 +53,6 @@ export class DevModeOrchestrator {
|
||||
...stepDeps,
|
||||
apiService,
|
||||
});
|
||||
this.ensureValidTokensStep = new EnsureValidTokensOrchestratorStep({
|
||||
...stepDeps,
|
||||
apiService,
|
||||
configService,
|
||||
});
|
||||
this.buildManifestStep = new BuildManifestOrchestratorStep(stepDeps);
|
||||
this.registerAppStep = new RegisterAppOrchestratorStep({
|
||||
...stepDeps,
|
||||
@@ -167,10 +160,6 @@ export class DevModeOrchestrator {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.ensureValidTokensStep.execute({
|
||||
applicationId: this.state.steps.resolveApplication.output.applicationId,
|
||||
});
|
||||
|
||||
const buildResult = await this.buildManifestStep.execute({
|
||||
appPath: this.state.appPath,
|
||||
});
|
||||
@@ -244,10 +233,6 @@ export class DevModeOrchestrator {
|
||||
{ message: 'Application created', status: 'success' },
|
||||
]);
|
||||
|
||||
await this.ensureValidTokensStep.exchangeTokens({
|
||||
applicationId: createResult.data.id,
|
||||
});
|
||||
|
||||
this.uploadFilesStep.initialize({
|
||||
appPath: this.state.appPath,
|
||||
universalIdentifier: manifest.application.universalIdentifier,
|
||||
|
||||
+16
-2
@@ -34,7 +34,17 @@ export class CheckServerOrchestratorStep {
|
||||
step.output = { isReady: false, errorLogged: true };
|
||||
step.status = 'error';
|
||||
this.state.applyStepEvents([
|
||||
{ message: 'Cannot reach server', status: 'error' },
|
||||
{
|
||||
message:
|
||||
'Cannot reach Twenty at localhost:3000.\n\n' +
|
||||
' Start a local server with Docker:\n' +
|
||||
' curl -sL https://raw.githubusercontent.com/twentyhq/twenty/main/packages/twenty-docker/docker-compose.yml -o docker-compose.yml\n' +
|
||||
' docker compose up -d\n\n' +
|
||||
' Or from the monorepo:\n' +
|
||||
' yarn start\n\n' +
|
||||
' Waiting for server...',
|
||||
status: 'error',
|
||||
},
|
||||
]);
|
||||
this.state.updatePipeline({ status: 'error' });
|
||||
}
|
||||
@@ -47,7 +57,11 @@ export class CheckServerOrchestratorStep {
|
||||
step.output = { isReady: false, errorLogged: true };
|
||||
step.status = 'error';
|
||||
this.state.applyStepEvents([
|
||||
{ message: 'Authentication failed', status: 'error' },
|
||||
{
|
||||
message:
|
||||
'Authentication failed. Run `twenty remote add --local` to authenticate.',
|
||||
status: 'error',
|
||||
},
|
||||
]);
|
||||
this.state.updatePipeline({ status: 'error' });
|
||||
}
|
||||
|
||||
-134
@@ -1,134 +0,0 @@
|
||||
import { type ApiService } from '@/cli/utilities/api/api-service';
|
||||
import { type ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import { type OrchestratorState } from '@/cli/utilities/dev/orchestrator/dev-mode-orchestrator-state';
|
||||
|
||||
export class EnsureValidTokensOrchestratorStep {
|
||||
private apiService: ApiService;
|
||||
private configService: ConfigService;
|
||||
private state: OrchestratorState;
|
||||
private notify: () => void;
|
||||
|
||||
constructor({
|
||||
apiService,
|
||||
configService,
|
||||
state,
|
||||
notify,
|
||||
}: {
|
||||
apiService: ApiService;
|
||||
configService: ConfigService;
|
||||
state: OrchestratorState;
|
||||
notify: () => void;
|
||||
}) {
|
||||
this.apiService = apiService;
|
||||
this.configService = configService;
|
||||
this.state = state;
|
||||
this.notify = notify;
|
||||
}
|
||||
|
||||
async execute(input: { applicationId: string | null }): Promise<void> {
|
||||
if (!input.applicationId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const step = this.state.steps.ensureValidTokens;
|
||||
|
||||
step.status = 'in_progress';
|
||||
this.notify();
|
||||
|
||||
const config = await this.configService.getConfig();
|
||||
|
||||
if (
|
||||
config.applicationAccessToken &&
|
||||
!this.isTokenExpired(config.applicationAccessToken)
|
||||
) {
|
||||
step.status = 'done';
|
||||
this.notify();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
config.applicationRefreshToken &&
|
||||
!this.isTokenExpired(config.applicationRefreshToken)
|
||||
) {
|
||||
const renewResult = await this.apiService.renewApplicationToken(
|
||||
config.applicationRefreshToken,
|
||||
);
|
||||
|
||||
if (renewResult.success) {
|
||||
await this.configService.setConfig({
|
||||
applicationAccessToken: renewResult.data.applicationAccessToken.token,
|
||||
applicationRefreshToken:
|
||||
renewResult.data.applicationRefreshToken.token,
|
||||
});
|
||||
|
||||
this.state.applyStepEvents([
|
||||
{ message: 'Renewing application tokens', status: 'info' },
|
||||
{ message: 'Application tokens renewed', status: 'success' },
|
||||
]);
|
||||
step.status = 'done';
|
||||
this.notify();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.state.applyStepEvents([
|
||||
{ message: 'Renewing application tokens', status: 'info' },
|
||||
{
|
||||
message: `Failed to renew application tokens: ${JSON.stringify(renewResult.error, null, 2)}`,
|
||||
status: 'error',
|
||||
},
|
||||
]);
|
||||
|
||||
await this.exchangeTokens({ applicationId: input.applicationId });
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
await this.exchangeTokens({ applicationId: input.applicationId });
|
||||
}
|
||||
|
||||
async exchangeTokens(input: { applicationId: string }): Promise<void> {
|
||||
const tokenResult = await this.apiService.generateApplicationToken(
|
||||
input.applicationId,
|
||||
);
|
||||
|
||||
if (!tokenResult.success) {
|
||||
this.state.applyStepEvents([
|
||||
{ message: 'Generating application tokens', status: 'info' },
|
||||
{
|
||||
message: `Failed to generate application tokens: ${JSON.stringify(tokenResult.error, null, 2)}`,
|
||||
status: 'error',
|
||||
},
|
||||
]);
|
||||
this.state.steps.ensureValidTokens.status = 'error';
|
||||
this.notify();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
await this.configService.setConfig({
|
||||
applicationAccessToken: tokenResult.data.applicationAccessToken.token,
|
||||
applicationRefreshToken: tokenResult.data.applicationRefreshToken.token,
|
||||
});
|
||||
|
||||
this.state.applyStepEvents([
|
||||
{ message: 'Generating application tokens', status: 'info' },
|
||||
{ message: 'Application tokens stored in config', status: 'success' },
|
||||
]);
|
||||
this.state.steps.ensureValidTokens.status = 'done';
|
||||
this.notify();
|
||||
}
|
||||
|
||||
private isTokenExpired(token: string): boolean {
|
||||
try {
|
||||
const payload = JSON.parse(
|
||||
Buffer.from(token.split('.')[1], 'base64').toString(),
|
||||
);
|
||||
|
||||
return Date.now() >= payload.exp * 1000 - 60_000;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -36,7 +36,7 @@ export class GenerateApiClientOrchestratorStep {
|
||||
|
||||
await this.clientService.generateCoreClient({
|
||||
appPath: input.appPath,
|
||||
authToken: config.applicationAccessToken,
|
||||
authToken: config.accessToken,
|
||||
});
|
||||
|
||||
step.status = 'done';
|
||||
|
||||
-1
@@ -88,7 +88,6 @@ export class RegisterAppOrchestratorStep {
|
||||
|
||||
await this.configService.setConfig({
|
||||
oauthClientId: createResult.data.applicationRegistration.oAuthClientId,
|
||||
oauthClientSecret: createResult.data.clientSecret,
|
||||
});
|
||||
|
||||
this.state.applyStepEvents([
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type CommandResult } from '@/cli/public-operations/types';
|
||||
import { type CommandResult } from '@/cli/types';
|
||||
|
||||
export const runSafe = async <T>(
|
||||
operation: () => Promise<CommandResult<T>>,
|
||||
|
||||
Reference in New Issue
Block a user