initial
This commit is contained in:
114
ts/classes/connectionmanager.ts
Normal file
114
ts/classes/connectionmanager.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
import * as plugins from '../plugins.ts';
|
||||
import { logger } from '../logging.ts';
|
||||
import type * as interfaces from '../../ts_interfaces/index.ts';
|
||||
import { BaseProvider, GiteaProvider, GitLabProvider } from '../providers/index.ts';
|
||||
|
||||
const CONNECTIONS_FILE = './.nogit/connections.json';
|
||||
|
||||
/**
|
||||
* Manages provider connections - persists to .nogit/connections.json
|
||||
* and creates provider instances on demand.
|
||||
*/
|
||||
export class ConnectionManager {
|
||||
private connections: interfaces.data.IProviderConnection[] = [];
|
||||
|
||||
async init(): Promise<void> {
|
||||
await this.loadConnections();
|
||||
}
|
||||
|
||||
private async loadConnections(): Promise<void> {
|
||||
try {
|
||||
const text = await Deno.readTextFile(CONNECTIONS_FILE);
|
||||
this.connections = JSON.parse(text);
|
||||
logger.info(`Loaded ${this.connections.length} connection(s)`);
|
||||
} catch {
|
||||
this.connections = [];
|
||||
logger.debug('No existing connections file found, starting fresh');
|
||||
}
|
||||
}
|
||||
|
||||
private async saveConnections(): Promise<void> {
|
||||
// Ensure .nogit directory exists
|
||||
try {
|
||||
await Deno.mkdir('./.nogit', { recursive: true });
|
||||
} catch { /* already exists */ }
|
||||
await Deno.writeTextFile(CONNECTIONS_FILE, JSON.stringify(this.connections, null, 2));
|
||||
}
|
||||
|
||||
getConnections(): interfaces.data.IProviderConnection[] {
|
||||
// Return connections without exposing tokens
|
||||
return this.connections.map((c) => ({ ...c, token: '***' }));
|
||||
}
|
||||
|
||||
getConnection(id: string): interfaces.data.IProviderConnection | undefined {
|
||||
return this.connections.find((c) => c.id === id);
|
||||
}
|
||||
|
||||
async createConnection(
|
||||
name: string,
|
||||
providerType: interfaces.data.TProviderType,
|
||||
baseUrl: string,
|
||||
token: string,
|
||||
): Promise<interfaces.data.IProviderConnection> {
|
||||
const connection: interfaces.data.IProviderConnection = {
|
||||
id: crypto.randomUUID(),
|
||||
name,
|
||||
providerType,
|
||||
baseUrl: baseUrl.replace(/\/+$/, ''),
|
||||
token,
|
||||
createdAt: Date.now(),
|
||||
status: 'disconnected',
|
||||
};
|
||||
this.connections.push(connection);
|
||||
await this.saveConnections();
|
||||
logger.success(`Connection created: ${name} (${providerType})`);
|
||||
return { ...connection, token: '***' };
|
||||
}
|
||||
|
||||
async updateConnection(
|
||||
id: string,
|
||||
updates: { name?: string; baseUrl?: string; token?: string },
|
||||
): Promise<interfaces.data.IProviderConnection> {
|
||||
const conn = this.connections.find((c) => c.id === id);
|
||||
if (!conn) throw new Error(`Connection not found: ${id}`);
|
||||
if (updates.name) conn.name = updates.name;
|
||||
if (updates.baseUrl) conn.baseUrl = updates.baseUrl.replace(/\/+$/, '');
|
||||
if (updates.token) conn.token = updates.token;
|
||||
await this.saveConnections();
|
||||
return { ...conn, token: '***' };
|
||||
}
|
||||
|
||||
async deleteConnection(id: string): Promise<void> {
|
||||
const idx = this.connections.findIndex((c) => c.id === id);
|
||||
if (idx === -1) throw new Error(`Connection not found: ${id}`);
|
||||
this.connections.splice(idx, 1);
|
||||
await this.saveConnections();
|
||||
logger.info(`Connection deleted: ${id}`);
|
||||
}
|
||||
|
||||
async testConnection(id: string): Promise<{ ok: boolean; error?: string }> {
|
||||
const provider = this.getProvider(id);
|
||||
const result = await provider.testConnection();
|
||||
const conn = this.connections.find((c) => c.id === id)!;
|
||||
conn.status = result.ok ? 'connected' : 'error';
|
||||
await this.saveConnections();
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory: returns the correct provider instance for a connection ID
|
||||
*/
|
||||
getProvider(connectionId: string): BaseProvider {
|
||||
const conn = this.connections.find((c) => c.id === connectionId);
|
||||
if (!conn) throw new Error(`Connection not found: ${connectionId}`);
|
||||
|
||||
switch (conn.providerType) {
|
||||
case 'gitea':
|
||||
return new GiteaProvider(conn.id, conn.baseUrl, conn.token);
|
||||
case 'gitlab':
|
||||
return new GitLabProvider(conn.id, conn.baseUrl, conn.token);
|
||||
default:
|
||||
throw new Error(`Unknown provider type: ${conn.providerType}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
34
ts/classes/gitopsapp.ts
Normal file
34
ts/classes/gitopsapp.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { logger } from '../logging.ts';
|
||||
import { ConnectionManager } from './connectionmanager.ts';
|
||||
import { OpsServer } from '../opsserver/index.ts';
|
||||
|
||||
/**
|
||||
* Main GitOps application orchestrator
|
||||
*/
|
||||
export class GitopsApp {
|
||||
public connectionManager: ConnectionManager;
|
||||
public opsServer: OpsServer;
|
||||
|
||||
constructor() {
|
||||
this.connectionManager = new ConnectionManager();
|
||||
this.opsServer = new OpsServer(this);
|
||||
}
|
||||
|
||||
async start(port = 3000): Promise<void> {
|
||||
logger.info('Initializing GitOps...');
|
||||
|
||||
// Initialize connection manager (loads saved connections)
|
||||
await this.connectionManager.init();
|
||||
|
||||
// Start OpsServer
|
||||
await this.opsServer.start(port);
|
||||
|
||||
logger.success('GitOps initialized successfully');
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
logger.info('Shutting down GitOps...');
|
||||
await this.opsServer.stop();
|
||||
logger.success('GitOps shutdown complete');
|
||||
}
|
||||
}
|
||||
37
ts/index.ts
Normal file
37
ts/index.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Main exports and CLI entry point for GitOps
|
||||
*/
|
||||
|
||||
export { GitopsApp } from './classes/gitopsapp.ts';
|
||||
export { logger } from './logging.ts';
|
||||
|
||||
import { GitopsApp } from './classes/gitopsapp.ts';
|
||||
import { logger } from './logging.ts';
|
||||
|
||||
export async function runCli(): Promise<void> {
|
||||
const args = Deno.args;
|
||||
const command = args[0] || 'server';
|
||||
|
||||
switch (command) {
|
||||
case 'server': {
|
||||
const port = parseInt(Deno.env.get('GITOPS_PORT') || '3000', 10);
|
||||
const app = new GitopsApp();
|
||||
await app.start(port);
|
||||
|
||||
// Handle graceful shutdown
|
||||
const shutdown = async () => {
|
||||
logger.info('Shutting down...');
|
||||
await app.stop();
|
||||
Deno.exit(0);
|
||||
};
|
||||
|
||||
Deno.addSignalListener('SIGINT', shutdown);
|
||||
Deno.addSignalListener('SIGTERM', shutdown);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
logger.error(`Unknown command: ${command}`);
|
||||
logger.info('Usage: gitops [server]');
|
||||
Deno.exit(1);
|
||||
}
|
||||
}
|
||||
75
ts/logging.ts
Normal file
75
ts/logging.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* Logging utilities for GitOps
|
||||
*/
|
||||
|
||||
type LogLevel = 'info' | 'success' | 'warn' | 'error' | 'debug';
|
||||
|
||||
class Logger {
|
||||
private debugMode = false;
|
||||
|
||||
constructor() {
|
||||
this.debugMode = Deno.args.includes('--debug') || Deno.env.get('DEBUG') === 'true';
|
||||
}
|
||||
|
||||
log(level: LogLevel, message: string, ...args: unknown[]): void {
|
||||
const prefix = this.getPrefix(level);
|
||||
const formattedMessage = `${prefix} ${message}`;
|
||||
|
||||
switch (level) {
|
||||
case 'error':
|
||||
console.error(formattedMessage, ...args);
|
||||
break;
|
||||
case 'warn':
|
||||
console.warn(formattedMessage, ...args);
|
||||
break;
|
||||
case 'debug':
|
||||
if (this.debugMode) {
|
||||
console.log(formattedMessage, ...args);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
console.log(formattedMessage, ...args);
|
||||
}
|
||||
}
|
||||
|
||||
info(message: string, ...args: unknown[]): void {
|
||||
this.log('info', message, ...args);
|
||||
}
|
||||
|
||||
success(message: string, ...args: unknown[]): void {
|
||||
this.log('success', message, ...args);
|
||||
}
|
||||
|
||||
warn(message: string, ...args: unknown[]): void {
|
||||
this.log('warn', message, ...args);
|
||||
}
|
||||
|
||||
error(message: string, ...args: unknown[]): void {
|
||||
this.log('error', message, ...args);
|
||||
}
|
||||
|
||||
debug(message: string, ...args: unknown[]): void {
|
||||
this.log('debug', message, ...args);
|
||||
}
|
||||
|
||||
private getPrefix(level: LogLevel): string {
|
||||
const colors: Record<LogLevel, string> = {
|
||||
info: '\x1b[36m',
|
||||
success: '\x1b[32m',
|
||||
warn: '\x1b[33m',
|
||||
error: '\x1b[31m',
|
||||
debug: '\x1b[90m',
|
||||
};
|
||||
const reset = '\x1b[0m';
|
||||
const icons: Record<LogLevel, string> = {
|
||||
info: 'i',
|
||||
success: '+',
|
||||
warn: '!',
|
||||
error: 'x',
|
||||
debug: '*',
|
||||
};
|
||||
return `${colors[level]}[${icons[level]}]${reset}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const logger = new Logger();
|
||||
64
ts/opsserver/classes.opsserver.ts
Normal file
64
ts/opsserver/classes.opsserver.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import * as plugins from '../plugins.ts';
|
||||
import { logger } from '../logging.ts';
|
||||
import type { GitopsApp } from '../classes/gitopsapp.ts';
|
||||
import * as handlers from './handlers/index.ts';
|
||||
|
||||
export class OpsServer {
|
||||
public gitopsAppRef: GitopsApp;
|
||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||
public server!: plugins.typedserver.utilityservers.UtilityWebsiteServer;
|
||||
|
||||
// Handler instances
|
||||
public adminHandler!: handlers.AdminHandler;
|
||||
public connectionsHandler!: handlers.ConnectionsHandler;
|
||||
public projectsHandler!: handlers.ProjectsHandler;
|
||||
public groupsHandler!: handlers.GroupsHandler;
|
||||
public secretsHandler!: handlers.SecretsHandler;
|
||||
public pipelinesHandler!: handlers.PipelinesHandler;
|
||||
public logsHandler!: handlers.LogsHandler;
|
||||
|
||||
constructor(gitopsAppRef: GitopsApp) {
|
||||
this.gitopsAppRef = gitopsAppRef;
|
||||
}
|
||||
|
||||
public async start(port = 3000) {
|
||||
const absoluteServeDir = plugins.path.resolve('./dist_serve');
|
||||
this.server = new plugins.typedserver.utilityservers.UtilityWebsiteServer({
|
||||
domain: 'localhost',
|
||||
feedMetadata: undefined,
|
||||
serveDir: absoluteServeDir,
|
||||
});
|
||||
|
||||
// Chain typedrouters
|
||||
this.server.typedrouter.addTypedRouter(this.typedrouter);
|
||||
|
||||
// Set up all handlers
|
||||
await this.setupHandlers();
|
||||
|
||||
await this.server.start(port);
|
||||
logger.success(`OpsServer started on http://localhost:${port}`);
|
||||
}
|
||||
|
||||
private async setupHandlers(): Promise<void> {
|
||||
// AdminHandler requires async initialization for JWT key generation
|
||||
this.adminHandler = new handlers.AdminHandler(this);
|
||||
await this.adminHandler.initialize();
|
||||
|
||||
// All other handlers self-register in their constructors
|
||||
this.connectionsHandler = new handlers.ConnectionsHandler(this);
|
||||
this.projectsHandler = new handlers.ProjectsHandler(this);
|
||||
this.groupsHandler = new handlers.GroupsHandler(this);
|
||||
this.secretsHandler = new handlers.SecretsHandler(this);
|
||||
this.pipelinesHandler = new handlers.PipelinesHandler(this);
|
||||
this.logsHandler = new handlers.LogsHandler(this);
|
||||
|
||||
logger.success('OpsServer TypedRequest handlers initialized');
|
||||
}
|
||||
|
||||
public async stop() {
|
||||
if (this.server) {
|
||||
await this.server.stop();
|
||||
logger.success('OpsServer stopped');
|
||||
}
|
||||
}
|
||||
}
|
||||
122
ts/opsserver/handlers/admin.handler.ts
Normal file
122
ts/opsserver/handlers/admin.handler.ts
Normal file
@@ -0,0 +1,122 @@
|
||||
import * as plugins from '../../plugins.ts';
|
||||
import { logger } from '../../logging.ts';
|
||||
import type { OpsServer } from '../classes.opsserver.ts';
|
||||
import * as interfaces from '../../../ts_interfaces/index.ts';
|
||||
|
||||
export interface IJwtData {
|
||||
userId: string;
|
||||
status: 'loggedIn' | 'loggedOut';
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export class AdminHandler {
|
||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||
public smartjwtInstance!: plugins.smartjwt.SmartJwt<IJwtData>;
|
||||
|
||||
constructor(private opsServerRef: OpsServer) {
|
||||
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||
}
|
||||
|
||||
public async initialize(): Promise<void> {
|
||||
this.smartjwtInstance = new plugins.smartjwt.SmartJwt();
|
||||
await this.smartjwtInstance.init();
|
||||
await this.smartjwtInstance.createNewKeyPair();
|
||||
this.registerHandlers();
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
// Login
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_AdminLogin>(
|
||||
'adminLogin',
|
||||
async (dataArg) => {
|
||||
const expectedUsername = Deno.env.get('GITOPS_ADMIN_USERNAME') || 'admin';
|
||||
const expectedPassword = Deno.env.get('GITOPS_ADMIN_PASSWORD') || 'admin';
|
||||
|
||||
if (dataArg.username !== expectedUsername || dataArg.password !== expectedPassword) {
|
||||
throw new plugins.typedrequest.TypedResponseError('Invalid credentials');
|
||||
}
|
||||
|
||||
const expiresAt = Date.now() + 24 * 3600 * 1000;
|
||||
const userId = 'admin';
|
||||
const jwt = await this.smartjwtInstance.createJWT({
|
||||
userId,
|
||||
status: 'loggedIn',
|
||||
expiresAt,
|
||||
});
|
||||
|
||||
logger.info(`User logged in: ${dataArg.username}`);
|
||||
|
||||
return {
|
||||
identity: {
|
||||
jwt,
|
||||
userId,
|
||||
username: dataArg.username,
|
||||
expiresAt,
|
||||
role: 'admin' as const,
|
||||
},
|
||||
};
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Logout
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_AdminLogout>(
|
||||
'adminLogout',
|
||||
async (_dataArg) => {
|
||||
return { ok: true };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Verify Identity
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_VerifyIdentity>(
|
||||
'verifyIdentity',
|
||||
async (dataArg) => {
|
||||
if (!dataArg.identity?.jwt) {
|
||||
return { valid: false };
|
||||
}
|
||||
try {
|
||||
const jwtData = await this.smartjwtInstance.verifyJWTAndGetData(dataArg.identity.jwt);
|
||||
if (jwtData.expiresAt < Date.now()) return { valid: false };
|
||||
if (jwtData.status !== 'loggedIn') return { valid: false };
|
||||
return {
|
||||
valid: true,
|
||||
identity: {
|
||||
jwt: dataArg.identity.jwt,
|
||||
userId: jwtData.userId,
|
||||
username: dataArg.identity.username,
|
||||
expiresAt: jwtData.expiresAt,
|
||||
role: dataArg.identity.role,
|
||||
},
|
||||
};
|
||||
} catch {
|
||||
return { valid: false };
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Guard for valid identity
|
||||
public validIdentityGuard = new plugins.smartguard.Guard<{
|
||||
identity: interfaces.data.IIdentity;
|
||||
}>(
|
||||
async (dataArg) => {
|
||||
if (!dataArg.identity?.jwt) return false;
|
||||
try {
|
||||
const jwtData = await this.smartjwtInstance.verifyJWTAndGetData(dataArg.identity.jwt);
|
||||
if (jwtData.expiresAt < Date.now()) return false;
|
||||
if (jwtData.status !== 'loggedIn') return false;
|
||||
if (dataArg.identity.expiresAt !== jwtData.expiresAt) return false;
|
||||
if (dataArg.identity.userId !== jwtData.userId) return false;
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
{ failedHint: 'identity is not valid', name: 'validIdentityGuard' },
|
||||
);
|
||||
}
|
||||
91
ts/opsserver/handlers/connections.handler.ts
Normal file
91
ts/opsserver/handlers/connections.handler.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import * as plugins from '../../plugins.ts';
|
||||
import type { OpsServer } from '../classes.opsserver.ts';
|
||||
import * as interfaces from '../../../ts_interfaces/index.ts';
|
||||
import { requireValidIdentity } from '../helpers/guards.ts';
|
||||
|
||||
export class ConnectionsHandler {
|
||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||
|
||||
constructor(private opsServerRef: OpsServer) {
|
||||
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||
this.registerHandlers();
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
// Get all connections
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetConnections>(
|
||||
'getConnections',
|
||||
async (dataArg) => {
|
||||
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const connections = this.opsServerRef.gitopsAppRef.connectionManager.getConnections();
|
||||
return { connections };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Create connection
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateConnection>(
|
||||
'createConnection',
|
||||
async (dataArg) => {
|
||||
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const connection = await this.opsServerRef.gitopsAppRef.connectionManager.createConnection(
|
||||
dataArg.name,
|
||||
dataArg.providerType,
|
||||
dataArg.baseUrl,
|
||||
dataArg.token,
|
||||
);
|
||||
return { connection };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Update connection
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateConnection>(
|
||||
'updateConnection',
|
||||
async (dataArg) => {
|
||||
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const connection = await this.opsServerRef.gitopsAppRef.connectionManager.updateConnection(
|
||||
dataArg.connectionId,
|
||||
{
|
||||
name: dataArg.name,
|
||||
baseUrl: dataArg.baseUrl,
|
||||
token: dataArg.token,
|
||||
},
|
||||
);
|
||||
return { connection };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Test connection
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_TestConnection>(
|
||||
'testConnection',
|
||||
async (dataArg) => {
|
||||
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const result = await this.opsServerRef.gitopsAppRef.connectionManager.testConnection(
|
||||
dataArg.connectionId,
|
||||
);
|
||||
return result;
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Delete connection
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteConnection>(
|
||||
'deleteConnection',
|
||||
async (dataArg) => {
|
||||
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
await this.opsServerRef.gitopsAppRef.connectionManager.deleteConnection(
|
||||
dataArg.connectionId,
|
||||
);
|
||||
return { ok: true };
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
32
ts/opsserver/handlers/groups.handler.ts
Normal file
32
ts/opsserver/handlers/groups.handler.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import * as plugins from '../../plugins.ts';
|
||||
import type { OpsServer } from '../classes.opsserver.ts';
|
||||
import * as interfaces from '../../../ts_interfaces/index.ts';
|
||||
import { requireValidIdentity } from '../helpers/guards.ts';
|
||||
|
||||
export class GroupsHandler {
|
||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||
|
||||
constructor(private opsServerRef: OpsServer) {
|
||||
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||
this.registerHandlers();
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetGroups>(
|
||||
'getGroups',
|
||||
async (dataArg) => {
|
||||
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const provider = this.opsServerRef.gitopsAppRef.connectionManager.getProvider(
|
||||
dataArg.connectionId,
|
||||
);
|
||||
const groups = await provider.getGroups({
|
||||
search: dataArg.search,
|
||||
page: dataArg.page,
|
||||
});
|
||||
return { groups };
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
7
ts/opsserver/handlers/index.ts
Normal file
7
ts/opsserver/handlers/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export { AdminHandler } from './admin.handler.ts';
|
||||
export { ConnectionsHandler } from './connections.handler.ts';
|
||||
export { ProjectsHandler } from './projects.handler.ts';
|
||||
export { GroupsHandler } from './groups.handler.ts';
|
||||
export { SecretsHandler } from './secrets.handler.ts';
|
||||
export { PipelinesHandler } from './pipelines.handler.ts';
|
||||
export { LogsHandler } from './logs.handler.ts';
|
||||
29
ts/opsserver/handlers/logs.handler.ts
Normal file
29
ts/opsserver/handlers/logs.handler.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import * as plugins from '../../plugins.ts';
|
||||
import type { OpsServer } from '../classes.opsserver.ts';
|
||||
import * as interfaces from '../../../ts_interfaces/index.ts';
|
||||
import { requireValidIdentity } from '../helpers/guards.ts';
|
||||
|
||||
export class LogsHandler {
|
||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||
|
||||
constructor(private opsServerRef: OpsServer) {
|
||||
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||
this.registerHandlers();
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetJobLog>(
|
||||
'getJobLog',
|
||||
async (dataArg) => {
|
||||
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const provider = this.opsServerRef.gitopsAppRef.connectionManager.getProvider(
|
||||
dataArg.connectionId,
|
||||
);
|
||||
const log = await provider.getJobLog(dataArg.projectId, dataArg.jobId);
|
||||
return { log };
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
77
ts/opsserver/handlers/pipelines.handler.ts
Normal file
77
ts/opsserver/handlers/pipelines.handler.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import * as plugins from '../../plugins.ts';
|
||||
import type { OpsServer } from '../classes.opsserver.ts';
|
||||
import * as interfaces from '../../../ts_interfaces/index.ts';
|
||||
import { requireValidIdentity } from '../helpers/guards.ts';
|
||||
|
||||
export class PipelinesHandler {
|
||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||
|
||||
constructor(private opsServerRef: OpsServer) {
|
||||
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||
this.registerHandlers();
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
// Get pipelines
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetPipelines>(
|
||||
'getPipelines',
|
||||
async (dataArg) => {
|
||||
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const provider = this.opsServerRef.gitopsAppRef.connectionManager.getProvider(
|
||||
dataArg.connectionId,
|
||||
);
|
||||
const pipelines = await provider.getPipelines(dataArg.projectId, {
|
||||
page: dataArg.page,
|
||||
});
|
||||
return { pipelines };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Get pipeline jobs
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetPipelineJobs>(
|
||||
'getPipelineJobs',
|
||||
async (dataArg) => {
|
||||
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const provider = this.opsServerRef.gitopsAppRef.connectionManager.getProvider(
|
||||
dataArg.connectionId,
|
||||
);
|
||||
const jobs = await provider.getPipelineJobs(dataArg.projectId, dataArg.pipelineId);
|
||||
return { jobs };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Retry pipeline
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_RetryPipeline>(
|
||||
'retryPipeline',
|
||||
async (dataArg) => {
|
||||
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const provider = this.opsServerRef.gitopsAppRef.connectionManager.getProvider(
|
||||
dataArg.connectionId,
|
||||
);
|
||||
await provider.retryPipeline(dataArg.projectId, dataArg.pipelineId);
|
||||
return { ok: true };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Cancel pipeline
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CancelPipeline>(
|
||||
'cancelPipeline',
|
||||
async (dataArg) => {
|
||||
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const provider = this.opsServerRef.gitopsAppRef.connectionManager.getProvider(
|
||||
dataArg.connectionId,
|
||||
);
|
||||
await provider.cancelPipeline(dataArg.projectId, dataArg.pipelineId);
|
||||
return { ok: true };
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
32
ts/opsserver/handlers/projects.handler.ts
Normal file
32
ts/opsserver/handlers/projects.handler.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import * as plugins from '../../plugins.ts';
|
||||
import type { OpsServer } from '../classes.opsserver.ts';
|
||||
import * as interfaces from '../../../ts_interfaces/index.ts';
|
||||
import { requireValidIdentity } from '../helpers/guards.ts';
|
||||
|
||||
export class ProjectsHandler {
|
||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||
|
||||
constructor(private opsServerRef: OpsServer) {
|
||||
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||
this.registerHandlers();
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetProjects>(
|
||||
'getProjects',
|
||||
async (dataArg) => {
|
||||
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const provider = this.opsServerRef.gitopsAppRef.connectionManager.getProvider(
|
||||
dataArg.connectionId,
|
||||
);
|
||||
const projects = await provider.getProjects({
|
||||
search: dataArg.search,
|
||||
page: dataArg.page,
|
||||
});
|
||||
return { projects };
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
85
ts/opsserver/handlers/secrets.handler.ts
Normal file
85
ts/opsserver/handlers/secrets.handler.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
import * as plugins from '../../plugins.ts';
|
||||
import type { OpsServer } from '../classes.opsserver.ts';
|
||||
import * as interfaces from '../../../ts_interfaces/index.ts';
|
||||
import { requireValidIdentity } from '../helpers/guards.ts';
|
||||
|
||||
export class SecretsHandler {
|
||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||
|
||||
constructor(private opsServerRef: OpsServer) {
|
||||
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||
this.registerHandlers();
|
||||
}
|
||||
|
||||
private registerHandlers(): void {
|
||||
// Get secrets
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetSecrets>(
|
||||
'getSecrets',
|
||||
async (dataArg) => {
|
||||
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const provider = this.opsServerRef.gitopsAppRef.connectionManager.getProvider(
|
||||
dataArg.connectionId,
|
||||
);
|
||||
const secrets = dataArg.scope === 'project'
|
||||
? await provider.getProjectSecrets(dataArg.scopeId)
|
||||
: await provider.getGroupSecrets(dataArg.scopeId);
|
||||
return { secrets };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Create secret
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateSecret>(
|
||||
'createSecret',
|
||||
async (dataArg) => {
|
||||
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const provider = this.opsServerRef.gitopsAppRef.connectionManager.getProvider(
|
||||
dataArg.connectionId,
|
||||
);
|
||||
const secret = dataArg.scope === 'project'
|
||||
? await provider.createProjectSecret(dataArg.scopeId, dataArg.key, dataArg.value)
|
||||
: await provider.createGroupSecret(dataArg.scopeId, dataArg.key, dataArg.value);
|
||||
return { secret };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Update secret
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateSecret>(
|
||||
'updateSecret',
|
||||
async (dataArg) => {
|
||||
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const provider = this.opsServerRef.gitopsAppRef.connectionManager.getProvider(
|
||||
dataArg.connectionId,
|
||||
);
|
||||
const secret = dataArg.scope === 'project'
|
||||
? await provider.updateProjectSecret(dataArg.scopeId, dataArg.key, dataArg.value)
|
||||
: await provider.updateGroupSecret(dataArg.scopeId, dataArg.key, dataArg.value);
|
||||
return { secret };
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Delete secret
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteSecret>(
|
||||
'deleteSecret',
|
||||
async (dataArg) => {
|
||||
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||
const provider = this.opsServerRef.gitopsAppRef.connectionManager.getProvider(
|
||||
dataArg.connectionId,
|
||||
);
|
||||
if (dataArg.scope === 'project') {
|
||||
await provider.deleteProjectSecret(dataArg.scopeId, dataArg.key);
|
||||
} else {
|
||||
await provider.deleteGroupSecret(dataArg.scopeId, dataArg.key);
|
||||
}
|
||||
return { ok: true };
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
16
ts/opsserver/helpers/guards.ts
Normal file
16
ts/opsserver/helpers/guards.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import * as plugins from '../../plugins.ts';
|
||||
import type { AdminHandler } from '../handlers/admin.handler.ts';
|
||||
import * as interfaces from '../../../ts_interfaces/index.ts';
|
||||
|
||||
export async function requireValidIdentity<T extends { identity?: interfaces.data.IIdentity }>(
|
||||
adminHandler: AdminHandler,
|
||||
dataArg: T,
|
||||
): Promise<void> {
|
||||
if (!dataArg.identity) {
|
||||
throw new plugins.typedrequest.TypedResponseError('No identity provided');
|
||||
}
|
||||
const passed = await adminHandler.validIdentityGuard.exec({ identity: dataArg.identity });
|
||||
if (!passed) {
|
||||
throw new plugins.typedrequest.TypedResponseError('Valid identity required');
|
||||
}
|
||||
}
|
||||
1
ts/opsserver/index.ts
Normal file
1
ts/opsserver/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { OpsServer } from './classes.opsserver.ts';
|
||||
20
ts/plugins.ts
Normal file
20
ts/plugins.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Centralized dependency imports for GitOps
|
||||
*/
|
||||
|
||||
// Deno Standard Library
|
||||
import * as path from '@std/path';
|
||||
import * as fs from '@std/fs';
|
||||
import * as encoding from '@std/encoding';
|
||||
|
||||
export { path, fs, encoding };
|
||||
|
||||
// TypedRequest/TypedServer infrastructure
|
||||
import * as typedrequest from '@api.global/typedrequest';
|
||||
import * as typedserver from '@api.global/typedserver';
|
||||
export { typedrequest, typedserver };
|
||||
|
||||
// Auth & Guards
|
||||
import * as smartguard from '@push.rocks/smartguard';
|
||||
import * as smartjwt from '@push.rocks/smartjwt';
|
||||
export { smartguard, smartjwt };
|
||||
89
ts/providers/classes.baseprovider.ts
Normal file
89
ts/providers/classes.baseprovider.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import type * as interfaces from '../../ts_interfaces/index.ts';
|
||||
|
||||
export interface ITestConnectionResult {
|
||||
ok: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface IListOptions {
|
||||
search?: string;
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Abstract base class for Git provider implementations.
|
||||
* Subclasses implement Gitea API v1 or GitLab API v4.
|
||||
*/
|
||||
export abstract class BaseProvider {
|
||||
constructor(
|
||||
public readonly connectionId: string,
|
||||
public readonly baseUrl: string,
|
||||
protected readonly token: string,
|
||||
) {}
|
||||
|
||||
// Connection
|
||||
abstract testConnection(): Promise<ITestConnectionResult>;
|
||||
|
||||
// Projects
|
||||
abstract getProjects(opts?: IListOptions): Promise<interfaces.data.IProject[]>;
|
||||
|
||||
// Groups / Orgs
|
||||
abstract getGroups(opts?: IListOptions): Promise<interfaces.data.IGroup[]>;
|
||||
|
||||
// Secrets — project scope
|
||||
abstract getProjectSecrets(projectId: string): Promise<interfaces.data.ISecret[]>;
|
||||
abstract createProjectSecret(
|
||||
projectId: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<interfaces.data.ISecret>;
|
||||
abstract updateProjectSecret(
|
||||
projectId: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<interfaces.data.ISecret>;
|
||||
abstract deleteProjectSecret(projectId: string, key: string): Promise<void>;
|
||||
|
||||
// Secrets — group scope
|
||||
abstract getGroupSecrets(groupId: string): Promise<interfaces.data.ISecret[]>;
|
||||
abstract createGroupSecret(
|
||||
groupId: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<interfaces.data.ISecret>;
|
||||
abstract updateGroupSecret(
|
||||
groupId: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<interfaces.data.ISecret>;
|
||||
abstract deleteGroupSecret(groupId: string, key: string): Promise<void>;
|
||||
|
||||
// Pipelines / CI
|
||||
abstract getPipelines(
|
||||
projectId: string,
|
||||
opts?: IListOptions,
|
||||
): Promise<interfaces.data.IPipeline[]>;
|
||||
abstract getPipelineJobs(
|
||||
projectId: string,
|
||||
pipelineId: string,
|
||||
): Promise<interfaces.data.IPipelineJob[]>;
|
||||
abstract getJobLog(projectId: string, jobId: string): Promise<string>;
|
||||
abstract retryPipeline(projectId: string, pipelineId: string): Promise<void>;
|
||||
abstract cancelPipeline(projectId: string, pipelineId: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* Helper for making authenticated fetch requests
|
||||
*/
|
||||
protected async apiFetch(
|
||||
path: string,
|
||||
options: RequestInit = {},
|
||||
): Promise<Response> {
|
||||
const url = `${this.baseUrl.replace(/\/+$/, '')}${path}`;
|
||||
const headers = new Headers(options.headers);
|
||||
this.setAuthHeader(headers);
|
||||
return fetch(url, { ...options, headers });
|
||||
}
|
||||
|
||||
protected abstract setAuthHeader(headers: Headers): void;
|
||||
}
|
||||
263
ts/providers/classes.giteaprovider.ts
Normal file
263
ts/providers/classes.giteaprovider.ts
Normal file
@@ -0,0 +1,263 @@
|
||||
import type * as interfaces from '../../ts_interfaces/index.ts';
|
||||
import { BaseProvider, type ITestConnectionResult, type IListOptions } from './classes.baseprovider.ts';
|
||||
|
||||
/**
|
||||
* Gitea API v1 provider implementation
|
||||
*/
|
||||
export class GiteaProvider extends BaseProvider {
|
||||
protected setAuthHeader(headers: Headers): void {
|
||||
headers.set('Authorization', `token ${this.token}`);
|
||||
if (!headers.has('Content-Type')) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
}
|
||||
|
||||
async testConnection(): Promise<ITestConnectionResult> {
|
||||
try {
|
||||
const resp = await this.apiFetch('/api/v1/user');
|
||||
if (!resp.ok) {
|
||||
return { ok: false, error: `HTTP ${resp.status}: ${resp.statusText}` };
|
||||
}
|
||||
return { ok: true };
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
async getProjects(opts?: IListOptions): Promise<interfaces.data.IProject[]> {
|
||||
const page = opts?.page || 1;
|
||||
const limit = opts?.perPage || 50;
|
||||
let url = `/api/v1/repos/search?page=${page}&limit=${limit}&sort=updated`;
|
||||
if (opts?.search) {
|
||||
url += `&q=${encodeURIComponent(opts.search)}`;
|
||||
}
|
||||
const resp = await this.apiFetch(url);
|
||||
if (!resp.ok) throw new Error(`Gitea getProjects failed: ${resp.status}`);
|
||||
const body = await resp.json();
|
||||
const repos = body.data || body;
|
||||
return (repos as any[]).map((r) => this.mapProject(r));
|
||||
}
|
||||
|
||||
async getGroups(opts?: IListOptions): Promise<interfaces.data.IGroup[]> {
|
||||
const page = opts?.page || 1;
|
||||
const limit = opts?.perPage || 50;
|
||||
const resp = await this.apiFetch(`/api/v1/orgs?page=${page}&limit=${limit}`);
|
||||
if (!resp.ok) throw new Error(`Gitea getGroups failed: ${resp.status}`);
|
||||
const orgs = await resp.json() as any[];
|
||||
return orgs.map((o) => this.mapGroup(o));
|
||||
}
|
||||
|
||||
// --- Project Secrets ---
|
||||
|
||||
async getProjectSecrets(projectId: string): Promise<interfaces.data.ISecret[]> {
|
||||
const resp = await this.apiFetch(`/api/v1/repos/${projectId}/actions/secrets`);
|
||||
if (!resp.ok) throw new Error(`Gitea getProjectSecrets failed: ${resp.status}`);
|
||||
const secrets = await resp.json() as any[];
|
||||
return secrets.map((s) => this.mapSecret(s, 'project', projectId));
|
||||
}
|
||||
|
||||
async createProjectSecret(
|
||||
projectId: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<interfaces.data.ISecret> {
|
||||
const resp = await this.apiFetch(`/api/v1/repos/${projectId}/actions/secrets/${key}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ data: value }),
|
||||
});
|
||||
if (!resp.ok) throw new Error(`Gitea createProjectSecret failed: ${resp.status}`);
|
||||
return { key, value: '***', protected: false, masked: true, scope: 'project', scopeId: projectId, connectionId: this.connectionId, environment: '*' };
|
||||
}
|
||||
|
||||
async updateProjectSecret(
|
||||
projectId: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<interfaces.data.ISecret> {
|
||||
return this.createProjectSecret(projectId, key, value);
|
||||
}
|
||||
|
||||
async deleteProjectSecret(projectId: string, key: string): Promise<void> {
|
||||
const resp = await this.apiFetch(`/api/v1/repos/${projectId}/actions/secrets/${key}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
if (!resp.ok) throw new Error(`Gitea deleteProjectSecret failed: ${resp.status}`);
|
||||
}
|
||||
|
||||
// --- Group Secrets ---
|
||||
|
||||
async getGroupSecrets(groupId: string): Promise<interfaces.data.ISecret[]> {
|
||||
const resp = await this.apiFetch(`/api/v1/orgs/${groupId}/actions/secrets`);
|
||||
if (!resp.ok) throw new Error(`Gitea getGroupSecrets failed: ${resp.status}`);
|
||||
const secrets = await resp.json() as any[];
|
||||
return secrets.map((s) => this.mapSecret(s, 'group', groupId));
|
||||
}
|
||||
|
||||
async createGroupSecret(
|
||||
groupId: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<interfaces.data.ISecret> {
|
||||
const resp = await this.apiFetch(`/api/v1/orgs/${groupId}/actions/secrets/${key}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ data: value }),
|
||||
});
|
||||
if (!resp.ok) throw new Error(`Gitea createGroupSecret failed: ${resp.status}`);
|
||||
return { key, value: '***', protected: false, masked: true, scope: 'group', scopeId: groupId, connectionId: this.connectionId, environment: '*' };
|
||||
}
|
||||
|
||||
async updateGroupSecret(
|
||||
groupId: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<interfaces.data.ISecret> {
|
||||
return this.createGroupSecret(groupId, key, value);
|
||||
}
|
||||
|
||||
async deleteGroupSecret(groupId: string, key: string): Promise<void> {
|
||||
const resp = await this.apiFetch(`/api/v1/orgs/${groupId}/actions/secrets/${key}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
if (!resp.ok) throw new Error(`Gitea deleteGroupSecret failed: ${resp.status}`);
|
||||
}
|
||||
|
||||
// --- Pipelines (Action Runs) ---
|
||||
|
||||
async getPipelines(
|
||||
projectId: string,
|
||||
opts?: IListOptions,
|
||||
): Promise<interfaces.data.IPipeline[]> {
|
||||
const page = opts?.page || 1;
|
||||
const limit = opts?.perPage || 30;
|
||||
const resp = await this.apiFetch(
|
||||
`/api/v1/repos/${projectId}/actions/runs?page=${page}&limit=${limit}`,
|
||||
);
|
||||
if (!resp.ok) throw new Error(`Gitea getPipelines failed: ${resp.status}`);
|
||||
const body = await resp.json();
|
||||
const runs = body.workflow_runs || body;
|
||||
return (runs as any[]).map((r) => this.mapPipeline(r, projectId));
|
||||
}
|
||||
|
||||
async getPipelineJobs(
|
||||
projectId: string,
|
||||
pipelineId: string,
|
||||
): Promise<interfaces.data.IPipelineJob[]> {
|
||||
const resp = await this.apiFetch(
|
||||
`/api/v1/repos/${projectId}/actions/runs/${pipelineId}/jobs`,
|
||||
);
|
||||
if (!resp.ok) throw new Error(`Gitea getPipelineJobs failed: ${resp.status}`);
|
||||
const body = await resp.json();
|
||||
const jobs = body.jobs || body;
|
||||
return (jobs as any[]).map((j) => this.mapJob(j, pipelineId));
|
||||
}
|
||||
|
||||
async getJobLog(projectId: string, jobId: string): Promise<string> {
|
||||
const resp = await this.apiFetch(
|
||||
`/api/v1/repos/${projectId}/actions/jobs/${jobId}/logs`,
|
||||
);
|
||||
if (!resp.ok) throw new Error(`Gitea getJobLog failed: ${resp.status}`);
|
||||
return resp.text();
|
||||
}
|
||||
|
||||
async retryPipeline(projectId: string, pipelineId: string): Promise<void> {
|
||||
// Gitea doesn't have a native retry — we re-run the workflow
|
||||
const resp = await this.apiFetch(
|
||||
`/api/v1/repos/${projectId}/actions/runs/${pipelineId}/rerun`,
|
||||
{ method: 'POST' },
|
||||
);
|
||||
if (!resp.ok) throw new Error(`Gitea retryPipeline failed: ${resp.status}`);
|
||||
}
|
||||
|
||||
async cancelPipeline(projectId: string, pipelineId: string): Promise<void> {
|
||||
const resp = await this.apiFetch(
|
||||
`/api/v1/repos/${projectId}/actions/runs/${pipelineId}/cancel`,
|
||||
{ method: 'POST' },
|
||||
);
|
||||
if (!resp.ok) throw new Error(`Gitea cancelPipeline failed: ${resp.status}`);
|
||||
}
|
||||
|
||||
// --- Mappers ---
|
||||
|
||||
private mapProject(r: any): interfaces.data.IProject {
|
||||
return {
|
||||
id: String(r.id),
|
||||
name: r.name || '',
|
||||
fullPath: r.full_name || '',
|
||||
description: r.description || '',
|
||||
defaultBranch: r.default_branch || 'main',
|
||||
webUrl: r.html_url || '',
|
||||
connectionId: this.connectionId,
|
||||
visibility: r.private ? 'private' : (r.internal ? 'internal' : 'public'),
|
||||
topics: r.topics || [],
|
||||
lastActivity: r.updated_at || '',
|
||||
};
|
||||
}
|
||||
|
||||
private mapGroup(o: any): interfaces.data.IGroup {
|
||||
return {
|
||||
id: String(o.id || o.name),
|
||||
name: o.name || o.username || '',
|
||||
fullPath: o.name || o.username || '',
|
||||
description: o.description || '',
|
||||
webUrl: `${this.baseUrl}/${o.name || o.username}`,
|
||||
connectionId: this.connectionId,
|
||||
visibility: o.visibility || 'public',
|
||||
projectCount: o.repo_count || 0,
|
||||
};
|
||||
}
|
||||
|
||||
private mapSecret(s: any, scope: 'project' | 'group', scopeId: string): interfaces.data.ISecret {
|
||||
return {
|
||||
key: s.name || s.key || '',
|
||||
value: '***',
|
||||
protected: false,
|
||||
masked: true,
|
||||
scope,
|
||||
scopeId,
|
||||
connectionId: this.connectionId,
|
||||
environment: '*',
|
||||
};
|
||||
}
|
||||
|
||||
private mapPipeline(r: any, projectId: string): interfaces.data.IPipeline {
|
||||
return {
|
||||
id: String(r.id),
|
||||
projectId,
|
||||
projectName: projectId,
|
||||
connectionId: this.connectionId,
|
||||
status: this.mapStatus(r.status || r.conclusion),
|
||||
ref: r.head_branch || '',
|
||||
sha: r.head_sha || '',
|
||||
webUrl: r.html_url || '',
|
||||
duration: r.run_duration || 0,
|
||||
createdAt: r.created_at || '',
|
||||
source: r.event || 'push',
|
||||
};
|
||||
}
|
||||
|
||||
private mapJob(j: any, pipelineId: string): interfaces.data.IPipelineJob {
|
||||
return {
|
||||
id: String(j.id),
|
||||
pipelineId,
|
||||
name: j.name || '',
|
||||
stage: j.name || 'default',
|
||||
status: this.mapStatus(j.status || j.conclusion),
|
||||
duration: j.run_duration || 0,
|
||||
};
|
||||
}
|
||||
|
||||
private mapStatus(status: string): interfaces.data.TPipelineStatus {
|
||||
const map: Record<string, interfaces.data.TPipelineStatus> = {
|
||||
success: 'success',
|
||||
completed: 'success',
|
||||
failure: 'failed',
|
||||
cancelled: 'canceled',
|
||||
waiting: 'waiting',
|
||||
running: 'running',
|
||||
queued: 'pending',
|
||||
in_progress: 'running',
|
||||
skipped: 'skipped',
|
||||
};
|
||||
return map[status?.toLowerCase()] || 'pending';
|
||||
}
|
||||
}
|
||||
275
ts/providers/classes.gitlabprovider.ts
Normal file
275
ts/providers/classes.gitlabprovider.ts
Normal file
@@ -0,0 +1,275 @@
|
||||
import type * as interfaces from '../../ts_interfaces/index.ts';
|
||||
import { BaseProvider, type ITestConnectionResult, type IListOptions } from './classes.baseprovider.ts';
|
||||
|
||||
/**
|
||||
* GitLab API v4 provider implementation
|
||||
*/
|
||||
export class GitLabProvider extends BaseProvider {
|
||||
protected setAuthHeader(headers: Headers): void {
|
||||
headers.set('PRIVATE-TOKEN', this.token);
|
||||
if (!headers.has('Content-Type')) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
}
|
||||
|
||||
async testConnection(): Promise<ITestConnectionResult> {
|
||||
try {
|
||||
const resp = await this.apiFetch('/api/v4/user');
|
||||
if (!resp.ok) {
|
||||
return { ok: false, error: `HTTP ${resp.status}: ${resp.statusText}` };
|
||||
}
|
||||
return { ok: true };
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
async getProjects(opts?: IListOptions): Promise<interfaces.data.IProject[]> {
|
||||
const page = opts?.page || 1;
|
||||
const perPage = opts?.perPage || 50;
|
||||
let url = `/api/v4/projects?page=${page}&per_page=${perPage}&order_by=updated_at&sort=desc&membership=true`;
|
||||
if (opts?.search) {
|
||||
url += `&search=${encodeURIComponent(opts.search)}`;
|
||||
}
|
||||
const resp = await this.apiFetch(url);
|
||||
if (!resp.ok) throw new Error(`GitLab getProjects failed: ${resp.status}`);
|
||||
const projects = await resp.json() as any[];
|
||||
return projects.map((p) => this.mapProject(p));
|
||||
}
|
||||
|
||||
async getGroups(opts?: IListOptions): Promise<interfaces.data.IGroup[]> {
|
||||
const page = opts?.page || 1;
|
||||
const perPage = opts?.perPage || 50;
|
||||
let url = `/api/v4/groups?page=${page}&per_page=${perPage}&order_by=name&sort=asc`;
|
||||
if (opts?.search) {
|
||||
url += `&search=${encodeURIComponent(opts.search)}`;
|
||||
}
|
||||
const resp = await this.apiFetch(url);
|
||||
if (!resp.ok) throw new Error(`GitLab getGroups failed: ${resp.status}`);
|
||||
const groups = await resp.json() as any[];
|
||||
return groups.map((g) => this.mapGroup(g));
|
||||
}
|
||||
|
||||
// --- Project Secrets (CI/CD Variables) ---
|
||||
|
||||
async getProjectSecrets(projectId: string): Promise<interfaces.data.ISecret[]> {
|
||||
const resp = await this.apiFetch(`/api/v4/projects/${encodeURIComponent(projectId)}/variables`);
|
||||
if (!resp.ok) throw new Error(`GitLab getProjectSecrets failed: ${resp.status}`);
|
||||
const vars = await resp.json() as any[];
|
||||
return vars.map((v) => this.mapVariable(v, 'project', projectId));
|
||||
}
|
||||
|
||||
async createProjectSecret(
|
||||
projectId: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<interfaces.data.ISecret> {
|
||||
const resp = await this.apiFetch(`/api/v4/projects/${encodeURIComponent(projectId)}/variables`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ key, value, protected: false, masked: false }),
|
||||
});
|
||||
if (!resp.ok) throw new Error(`GitLab createProjectSecret failed: ${resp.status}`);
|
||||
const v = await resp.json();
|
||||
return this.mapVariable(v, 'project', projectId);
|
||||
}
|
||||
|
||||
async updateProjectSecret(
|
||||
projectId: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<interfaces.data.ISecret> {
|
||||
const resp = await this.apiFetch(
|
||||
`/api/v4/projects/${encodeURIComponent(projectId)}/variables/${encodeURIComponent(key)}`,
|
||||
{
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ value }),
|
||||
},
|
||||
);
|
||||
if (!resp.ok) throw new Error(`GitLab updateProjectSecret failed: ${resp.status}`);
|
||||
const v = await resp.json();
|
||||
return this.mapVariable(v, 'project', projectId);
|
||||
}
|
||||
|
||||
async deleteProjectSecret(projectId: string, key: string): Promise<void> {
|
||||
const resp = await this.apiFetch(
|
||||
`/api/v4/projects/${encodeURIComponent(projectId)}/variables/${encodeURIComponent(key)}`,
|
||||
{ method: 'DELETE' },
|
||||
);
|
||||
if (!resp.ok) throw new Error(`GitLab deleteProjectSecret failed: ${resp.status}`);
|
||||
}
|
||||
|
||||
// --- Group Secrets (CI/CD Variables) ---
|
||||
|
||||
async getGroupSecrets(groupId: string): Promise<interfaces.data.ISecret[]> {
|
||||
const resp = await this.apiFetch(`/api/v4/groups/${encodeURIComponent(groupId)}/variables`);
|
||||
if (!resp.ok) throw new Error(`GitLab getGroupSecrets failed: ${resp.status}`);
|
||||
const vars = await resp.json() as any[];
|
||||
return vars.map((v) => this.mapVariable(v, 'group', groupId));
|
||||
}
|
||||
|
||||
async createGroupSecret(
|
||||
groupId: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<interfaces.data.ISecret> {
|
||||
const resp = await this.apiFetch(`/api/v4/groups/${encodeURIComponent(groupId)}/variables`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ key, value, protected: false, masked: false }),
|
||||
});
|
||||
if (!resp.ok) throw new Error(`GitLab createGroupSecret failed: ${resp.status}`);
|
||||
const v = await resp.json();
|
||||
return this.mapVariable(v, 'group', groupId);
|
||||
}
|
||||
|
||||
async updateGroupSecret(
|
||||
groupId: string,
|
||||
key: string,
|
||||
value: string,
|
||||
): Promise<interfaces.data.ISecret> {
|
||||
const resp = await this.apiFetch(
|
||||
`/api/v4/groups/${encodeURIComponent(groupId)}/variables/${encodeURIComponent(key)}`,
|
||||
{
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ value }),
|
||||
},
|
||||
);
|
||||
if (!resp.ok) throw new Error(`GitLab updateGroupSecret failed: ${resp.status}`);
|
||||
const v = await resp.json();
|
||||
return this.mapVariable(v, 'group', groupId);
|
||||
}
|
||||
|
||||
async deleteGroupSecret(groupId: string, key: string): Promise<void> {
|
||||
const resp = await this.apiFetch(
|
||||
`/api/v4/groups/${encodeURIComponent(groupId)}/variables/${encodeURIComponent(key)}`,
|
||||
{ method: 'DELETE' },
|
||||
);
|
||||
if (!resp.ok) throw new Error(`GitLab deleteGroupSecret failed: ${resp.status}`);
|
||||
}
|
||||
|
||||
// --- Pipelines ---
|
||||
|
||||
async getPipelines(
|
||||
projectId: string,
|
||||
opts?: IListOptions,
|
||||
): Promise<interfaces.data.IPipeline[]> {
|
||||
const page = opts?.page || 1;
|
||||
const perPage = opts?.perPage || 30;
|
||||
const resp = await this.apiFetch(
|
||||
`/api/v4/projects/${encodeURIComponent(projectId)}/pipelines?page=${page}&per_page=${perPage}&order_by=updated_at&sort=desc`,
|
||||
);
|
||||
if (!resp.ok) throw new Error(`GitLab getPipelines failed: ${resp.status}`);
|
||||
const pipelines = await resp.json() as any[];
|
||||
return pipelines.map((p) => this.mapPipeline(p, projectId));
|
||||
}
|
||||
|
||||
async getPipelineJobs(
|
||||
projectId: string,
|
||||
pipelineId: string,
|
||||
): Promise<interfaces.data.IPipelineJob[]> {
|
||||
const resp = await this.apiFetch(
|
||||
`/api/v4/projects/${encodeURIComponent(projectId)}/pipelines/${pipelineId}/jobs`,
|
||||
);
|
||||
if (!resp.ok) throw new Error(`GitLab getPipelineJobs failed: ${resp.status}`);
|
||||
const jobs = await resp.json() as any[];
|
||||
return jobs.map((j) => this.mapJob(j, pipelineId));
|
||||
}
|
||||
|
||||
async getJobLog(projectId: string, jobId: string): Promise<string> {
|
||||
const resp = await this.apiFetch(
|
||||
`/api/v4/projects/${encodeURIComponent(projectId)}/jobs/${jobId}/trace`,
|
||||
{ headers: { Accept: 'text/plain' } },
|
||||
);
|
||||
if (!resp.ok) throw new Error(`GitLab getJobLog failed: ${resp.status}`);
|
||||
return resp.text();
|
||||
}
|
||||
|
||||
async retryPipeline(projectId: string, pipelineId: string): Promise<void> {
|
||||
const resp = await this.apiFetch(
|
||||
`/api/v4/projects/${encodeURIComponent(projectId)}/pipelines/${pipelineId}/retry`,
|
||||
{ method: 'POST' },
|
||||
);
|
||||
if (!resp.ok) throw new Error(`GitLab retryPipeline failed: ${resp.status}`);
|
||||
}
|
||||
|
||||
async cancelPipeline(projectId: string, pipelineId: string): Promise<void> {
|
||||
const resp = await this.apiFetch(
|
||||
`/api/v4/projects/${encodeURIComponent(projectId)}/pipelines/${pipelineId}/cancel`,
|
||||
{ method: 'POST' },
|
||||
);
|
||||
if (!resp.ok) throw new Error(`GitLab cancelPipeline failed: ${resp.status}`);
|
||||
}
|
||||
|
||||
// --- Mappers ---
|
||||
|
||||
private mapProject(p: any): interfaces.data.IProject {
|
||||
return {
|
||||
id: String(p.id),
|
||||
name: p.name || '',
|
||||
fullPath: p.path_with_namespace || '',
|
||||
description: p.description || '',
|
||||
defaultBranch: p.default_branch || 'main',
|
||||
webUrl: p.web_url || '',
|
||||
connectionId: this.connectionId,
|
||||
visibility: p.visibility || 'private',
|
||||
topics: p.topics || p.tag_list || [],
|
||||
lastActivity: p.last_activity_at || '',
|
||||
};
|
||||
}
|
||||
|
||||
private mapGroup(g: any): interfaces.data.IGroup {
|
||||
return {
|
||||
id: String(g.id),
|
||||
name: g.name || '',
|
||||
fullPath: g.full_path || '',
|
||||
description: g.description || '',
|
||||
webUrl: g.web_url || '',
|
||||
connectionId: this.connectionId,
|
||||
visibility: g.visibility || 'private',
|
||||
projectCount: g.projects?.length || 0,
|
||||
};
|
||||
}
|
||||
|
||||
private mapVariable(
|
||||
v: any,
|
||||
scope: 'project' | 'group',
|
||||
scopeId: string,
|
||||
): interfaces.data.ISecret {
|
||||
return {
|
||||
key: v.key || '',
|
||||
value: v.value || '***',
|
||||
protected: v.protected || false,
|
||||
masked: v.masked || false,
|
||||
scope,
|
||||
scopeId,
|
||||
connectionId: this.connectionId,
|
||||
environment: v.environment_scope || '*',
|
||||
};
|
||||
}
|
||||
|
||||
private mapPipeline(p: any, projectId: string): interfaces.data.IPipeline {
|
||||
return {
|
||||
id: String(p.id),
|
||||
projectId,
|
||||
projectName: projectId,
|
||||
connectionId: this.connectionId,
|
||||
status: (p.status || 'pending') as interfaces.data.TPipelineStatus,
|
||||
ref: p.ref || '',
|
||||
sha: p.sha || '',
|
||||
webUrl: p.web_url || '',
|
||||
duration: p.duration || 0,
|
||||
createdAt: p.created_at || '',
|
||||
source: p.source || 'push',
|
||||
};
|
||||
}
|
||||
|
||||
private mapJob(j: any, pipelineId: string): interfaces.data.IPipelineJob {
|
||||
return {
|
||||
id: String(j.id),
|
||||
pipelineId: String(pipelineId),
|
||||
name: j.name || '',
|
||||
stage: j.stage || '',
|
||||
status: (j.status || 'pending') as interfaces.data.TPipelineStatus,
|
||||
duration: j.duration || 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
3
ts/providers/index.ts
Normal file
3
ts/providers/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export { BaseProvider } from './classes.baseprovider.ts';
|
||||
export { GiteaProvider } from './classes.giteaprovider.ts';
|
||||
export { GitLabProvider } from './classes.gitlabprovider.ts';
|
||||
Reference in New Issue
Block a user