Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 423860c21c | |||
| 47e1463163 | |||
| a0b3032c22 | |||
| 56403224c0 | |||
| 75d35405dc |
27
changelog.md
27
changelog.md
@@ -1,5 +1,32 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 2026-03-02 - 2.11.1 - fix(meta)
|
||||||
|
update repository metadata (non-functional change)
|
||||||
|
|
||||||
|
- Change was metadata-only (+1 -1) with no source code changes
|
||||||
|
- Current package.json version: 2.11.0 — recommend patch bump to 2.11.1
|
||||||
|
|
||||||
|
## 2026-03-02 - 2.11.0 - feat(sync)
|
||||||
|
add branch & tag listing support and improve sync mirroring and sync log routing
|
||||||
|
|
||||||
|
- Bump @apiclient.xyz/gitea to 1.3.0 and @apiclient.xyz/gitlab to 2.4.0
|
||||||
|
- Add IBranch and ITag interfaces and export them from ts_interfaces
|
||||||
|
- Add getBranches/getTags to BaseProvider and implement paginated branch/tag listing for Gitea and GitLab providers
|
||||||
|
- SyncManager now creates a temporary mirrors directory (RAM-backed), auto-cleans it on shutdown, and no longer requires a configured syncMirrorsPath (removed from paths and gitopsapp)
|
||||||
|
- Add refsMatch in SyncManager to accurately compare local branches/tags with target refs (uses for-each-ref and ls-remote) to avoid unnecessary pushes
|
||||||
|
- Introduce avatarUploadCache and other internal sync manager improvements
|
||||||
|
- Change log channel/tagging: sync log messages use 'sync' (was 'git') and TypedSocket broadcasts use a new 'syncLogClient' tag; web client now sets that tag when creating the socket
|
||||||
|
|
||||||
|
## 2026-02-28 - 2.10.0 - feat(managed-secrets)
|
||||||
|
add centrally managed secrets with GITOPS_ prefix pushed to multiple targets
|
||||||
|
|
||||||
|
- Add IManagedSecret, IManagedSecretTarget, IManagedSecretStored interfaces and TypedRequest contracts for CRUD + push operations
|
||||||
|
- Add ManagedSecretsManager with keychain-backed storage, upsert push logic, target diff on update, and best-effort delete
|
||||||
|
- Add ManagedSecretsHandler with 7 endpoints wired into OpsServer with auth guards and action logging
|
||||||
|
- Add frontend state part, 6 appstate actions, and Managed Secrets view with table, target picker, and push/edit/delete modals
|
||||||
|
- Add Managed Secrets tab to dashboard after Secrets
|
||||||
|
- Extend action log types with 'managed-secret' entity and 'push' action
|
||||||
|
|
||||||
## 2026-02-28 - 2.9.0 - feat(sync)
|
## 2026-02-28 - 2.9.0 - feat(sync)
|
||||||
remove target avatar when source has none to keep avatars fully in sync
|
remove target avatar when source has none to keep avatars fully in sync
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@serve.zone/gitops",
|
"name": "@serve.zone/gitops",
|
||||||
"version": "2.8.0",
|
"version": "2.11.1",
|
||||||
"exports": "./mod.ts",
|
"exports": "./mod.ts",
|
||||||
"nodeModulesDir": "auto",
|
"nodeModulesDir": "auto",
|
||||||
"tasks": {
|
"tasks": {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@serve.zone/gitops",
|
"name": "@serve.zone/gitops",
|
||||||
"version": "2.9.0",
|
"version": "2.11.1",
|
||||||
"description": "GitOps management app for Gitea and GitLab - manage secrets, browse projects, view CI pipelines, and stream build logs",
|
"description": "GitOps management app for Gitea and GitLab - manage secrets, browse projects, view CI pipelines, and stream build logs",
|
||||||
"main": "mod.ts",
|
"main": "mod.ts",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
@@ -16,8 +16,8 @@
|
|||||||
"@api.global/typedrequest-interfaces": "^3.0.19",
|
"@api.global/typedrequest-interfaces": "^3.0.19",
|
||||||
"@api.global/typedserver": "8.4.0",
|
"@api.global/typedserver": "8.4.0",
|
||||||
"@api.global/typedsocket": "^4.1.0",
|
"@api.global/typedsocket": "^4.1.0",
|
||||||
"@apiclient.xyz/gitea": "1.2.0",
|
"@apiclient.xyz/gitea": "1.3.0",
|
||||||
"@apiclient.xyz/gitlab": "2.3.0",
|
"@apiclient.xyz/gitlab": "2.4.0",
|
||||||
"@design.estate/dees-catalog": "^3.43.3",
|
"@design.estate/dees-catalog": "^3.43.3",
|
||||||
"@design.estate/dees-element": "^2.1.6"
|
"@design.estate/dees-element": "^2.1.6"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -3,6 +3,6 @@
|
|||||||
*/
|
*/
|
||||||
export const commitinfo = {
|
export const commitinfo = {
|
||||||
name: '@serve.zone/gitops',
|
name: '@serve.zone/gitops',
|
||||||
version: '2.8.0',
|
version: '2.11.1',
|
||||||
description: 'GitOps management app for Gitea and GitLab - manage secrets, browse projects, view CI pipelines, and stream build logs'
|
description: 'GitOps management app for Gitea and GitLab - manage secrets, browse projects, view CI pipelines, and stream build logs'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { logger } from '../logging.ts';
|
|||||||
import { ConnectionManager } from './connectionmanager.ts';
|
import { ConnectionManager } from './connectionmanager.ts';
|
||||||
import { ActionLog } from './actionlog.ts';
|
import { ActionLog } from './actionlog.ts';
|
||||||
import { SyncManager } from './syncmanager.ts';
|
import { SyncManager } from './syncmanager.ts';
|
||||||
|
import { ManagedSecretsManager } from './managedsecrets.manager.ts';
|
||||||
import { OpsServer } from '../opsserver/index.ts';
|
import { OpsServer } from '../opsserver/index.ts';
|
||||||
import { StorageManager } from '../storage/index.ts';
|
import { StorageManager } from '../storage/index.ts';
|
||||||
import { CacheDb, CacheCleaner, CachedProject, CachedSecret, SecretsScanService } from '../cache/index.ts';
|
import { CacheDb, CacheCleaner, CachedProject, CachedSecret, SecretsScanService } from '../cache/index.ts';
|
||||||
@@ -20,6 +21,7 @@ export class GitopsApp {
|
|||||||
public cacheDb: CacheDb;
|
public cacheDb: CacheDb;
|
||||||
public cacheCleaner: CacheCleaner;
|
public cacheCleaner: CacheCleaner;
|
||||||
public syncManager!: SyncManager;
|
public syncManager!: SyncManager;
|
||||||
|
public managedSecretsManager!: ManagedSecretsManager;
|
||||||
public secretsScanService!: SecretsScanService;
|
public secretsScanService!: SecretsScanService;
|
||||||
private scanIntervalId: number | null = null;
|
private scanIntervalId: number | null = null;
|
||||||
private paths: ReturnType<typeof resolvePaths>;
|
private paths: ReturnType<typeof resolvePaths>;
|
||||||
@@ -55,12 +57,19 @@ export class GitopsApp {
|
|||||||
// Initialize connection manager (loads saved connections)
|
// Initialize connection manager (loads saved connections)
|
||||||
await this.connectionManager.init();
|
await this.connectionManager.init();
|
||||||
|
|
||||||
|
// Initialize managed secrets manager
|
||||||
|
this.managedSecretsManager = new ManagedSecretsManager(
|
||||||
|
this.storageManager,
|
||||||
|
this.smartSecret,
|
||||||
|
this.connectionManager,
|
||||||
|
);
|
||||||
|
await this.managedSecretsManager.init();
|
||||||
|
|
||||||
// Initialize sync manager
|
// Initialize sync manager
|
||||||
this.syncManager = new SyncManager(
|
this.syncManager = new SyncManager(
|
||||||
this.storageManager,
|
this.storageManager,
|
||||||
this.connectionManager,
|
this.connectionManager,
|
||||||
this.actionLog,
|
this.actionLog,
|
||||||
this.paths.syncMirrorsPath,
|
|
||||||
);
|
);
|
||||||
await this.syncManager.init();
|
await this.syncManager.init();
|
||||||
|
|
||||||
|
|||||||
322
ts/classes/managedsecrets.manager.ts
Normal file
322
ts/classes/managedsecrets.manager.ts
Normal file
@@ -0,0 +1,322 @@
|
|||||||
|
import * as plugins from '../plugins.ts';
|
||||||
|
import { logger } from '../logging.ts';
|
||||||
|
import type * as interfaces from '../../ts_interfaces/index.ts';
|
||||||
|
import type { StorageManager } from '../storage/index.ts';
|
||||||
|
import type { ConnectionManager } from './connectionmanager.ts';
|
||||||
|
|
||||||
|
const MANAGED_SECRETS_PREFIX = '/managed-secrets/';
|
||||||
|
const KEYCHAIN_PREFIX = 'keychain:';
|
||||||
|
const KEYCHAIN_ID_PREFIX = 'gitops-msecret-';
|
||||||
|
const SECRET_KEY_PREFIX = 'GITOPS_';
|
||||||
|
|
||||||
|
export class ManagedSecretsManager {
|
||||||
|
private secrets: interfaces.data.IManagedSecretStored[] = [];
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private storageManager: StorageManager,
|
||||||
|
private smartSecret: plugins.smartsecret.SmartSecret,
|
||||||
|
private connectionManager: ConnectionManager,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async init(): Promise<void> {
|
||||||
|
await this.loadSecrets();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Storage helpers ----
|
||||||
|
|
||||||
|
private keychainId(secretId: string): string {
|
||||||
|
return `${KEYCHAIN_ID_PREFIX}${secretId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private prefixedKey(key: string): string {
|
||||||
|
return `${SECRET_KEY_PREFIX}${key}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadSecrets(): Promise<void> {
|
||||||
|
const keys = await this.storageManager.list(MANAGED_SECRETS_PREFIX);
|
||||||
|
this.secrets = [];
|
||||||
|
for (const key of keys) {
|
||||||
|
const stored = await this.storageManager.getJSON<interfaces.data.IManagedSecretStored>(key);
|
||||||
|
if (stored) {
|
||||||
|
this.secrets.push(stored);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (this.secrets.length > 0) {
|
||||||
|
logger.info(`Loaded ${this.secrets.length} managed secret(s)`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async persistSecret(stored: interfaces.data.IManagedSecretStored, realValue: string): Promise<void> {
|
||||||
|
// Store real value in keychain
|
||||||
|
await this.smartSecret.setSecret(this.keychainId(stored.id), realValue);
|
||||||
|
// Save JSON with sentinel
|
||||||
|
const jsonStored = { ...stored, value: `${KEYCHAIN_PREFIX}${this.keychainId(stored.id)}` };
|
||||||
|
await this.storageManager.setJSON(`${MANAGED_SECRETS_PREFIX}${stored.id}.json`, jsonStored);
|
||||||
|
// Update in-memory sentinel too
|
||||||
|
stored.value = jsonStored.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async removeFromStorage(id: string): Promise<void> {
|
||||||
|
await this.smartSecret.deleteSecret(this.keychainId(id));
|
||||||
|
await this.storageManager.delete(`${MANAGED_SECRETS_PREFIX}${id}.json`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getSecretValue(id: string): Promise<string | null> {
|
||||||
|
return await this.smartSecret.getSecret(this.keychainId(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
private toApiModel(stored: interfaces.data.IManagedSecretStored): interfaces.data.IManagedSecret {
|
||||||
|
return {
|
||||||
|
id: stored.id,
|
||||||
|
key: stored.key,
|
||||||
|
description: stored.description,
|
||||||
|
targets: stored.targets,
|
||||||
|
targetStatuses: stored.targetStatuses,
|
||||||
|
createdAt: stored.createdAt,
|
||||||
|
updatedAt: stored.updatedAt,
|
||||||
|
lastPushedAt: stored.lastPushedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Push logic ----
|
||||||
|
|
||||||
|
private async pushToTargets(
|
||||||
|
stored: interfaces.data.IManagedSecretStored,
|
||||||
|
mode: 'upsert' | 'delete',
|
||||||
|
targetsOverride?: interfaces.data.IManagedSecretTarget[],
|
||||||
|
): Promise<interfaces.data.IManagedSecretTargetStatus[]> {
|
||||||
|
const targets = targetsOverride || stored.targets;
|
||||||
|
const value = mode === 'upsert' ? await this.getSecretValue(stored.id) : null;
|
||||||
|
const prefixedKey = this.prefixedKey(stored.key);
|
||||||
|
const results: interfaces.data.IManagedSecretTargetStatus[] = [];
|
||||||
|
|
||||||
|
for (const target of targets) {
|
||||||
|
const status: interfaces.data.IManagedSecretTargetStatus = {
|
||||||
|
connectionId: target.connectionId,
|
||||||
|
scope: target.scope,
|
||||||
|
scopeId: target.scopeId,
|
||||||
|
scopeName: target.scopeName,
|
||||||
|
status: 'pending',
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const provider = this.connectionManager.getProvider(target.connectionId);
|
||||||
|
if (mode === 'upsert') {
|
||||||
|
// Try update first; if it fails, create
|
||||||
|
try {
|
||||||
|
if (target.scope === 'project') {
|
||||||
|
await provider.updateProjectSecret(target.scopeId, prefixedKey, value!);
|
||||||
|
} else {
|
||||||
|
await provider.updateGroupSecret(target.scopeId, prefixedKey, value!);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Secret doesn't exist yet — create it
|
||||||
|
if (target.scope === 'project') {
|
||||||
|
await provider.createProjectSecret(target.scopeId, prefixedKey, value!);
|
||||||
|
} else {
|
||||||
|
await provider.createGroupSecret(target.scopeId, prefixedKey, value!);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// mode === 'delete'
|
||||||
|
try {
|
||||||
|
if (target.scope === 'project') {
|
||||||
|
await provider.deleteProjectSecret(target.scopeId, prefixedKey);
|
||||||
|
} else {
|
||||||
|
await provider.deleteGroupSecret(target.scopeId, prefixedKey);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Secret may not exist on target — that's fine
|
||||||
|
}
|
||||||
|
}
|
||||||
|
status.status = 'success';
|
||||||
|
status.lastPushedAt = Date.now();
|
||||||
|
} catch (err) {
|
||||||
|
status.status = 'error';
|
||||||
|
status.error = err instanceof Error ? err.message : String(err);
|
||||||
|
}
|
||||||
|
results.push(status);
|
||||||
|
}
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Public API ----
|
||||||
|
|
||||||
|
async getAll(): Promise<interfaces.data.IManagedSecret[]> {
|
||||||
|
return this.secrets.map((s) => this.toApiModel(s));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getById(id: string): Promise<interfaces.data.IManagedSecret | null> {
|
||||||
|
const stored = this.secrets.find((s) => s.id === id);
|
||||||
|
return stored ? this.toApiModel(stored) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(
|
||||||
|
key: string,
|
||||||
|
value: string,
|
||||||
|
description: string | undefined,
|
||||||
|
targets: interfaces.data.IManagedSecretTarget[],
|
||||||
|
): Promise<{
|
||||||
|
managedSecret: interfaces.data.IManagedSecret;
|
||||||
|
pushResults: interfaces.data.IManagedSecretTargetStatus[];
|
||||||
|
}> {
|
||||||
|
// Validate key
|
||||||
|
if (key.toUpperCase().startsWith(SECRET_KEY_PREFIX)) {
|
||||||
|
throw new Error(`Key must not start with ${SECRET_KEY_PREFIX} — the prefix is added automatically`);
|
||||||
|
}
|
||||||
|
if (this.secrets.some((s) => s.key === key)) {
|
||||||
|
throw new Error(`A managed secret with key "${key}" already exists`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const stored: interfaces.data.IManagedSecretStored = {
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
key,
|
||||||
|
description,
|
||||||
|
value: '', // will be set by persistSecret
|
||||||
|
targets,
|
||||||
|
targetStatuses: [],
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.secrets.push(stored);
|
||||||
|
await this.persistSecret(stored, value);
|
||||||
|
|
||||||
|
// Push to all targets
|
||||||
|
const pushResults = await this.pushToTargets(stored, 'upsert');
|
||||||
|
stored.targetStatuses = pushResults;
|
||||||
|
stored.lastPushedAt = now;
|
||||||
|
stored.updatedAt = now;
|
||||||
|
await this.storageManager.setJSON(`${MANAGED_SECRETS_PREFIX}${stored.id}.json`, {
|
||||||
|
...stored,
|
||||||
|
value: `${KEYCHAIN_PREFIX}${this.keychainId(stored.id)}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`Created managed secret "${key}" with ${targets.length} target(s)`);
|
||||||
|
return { managedSecret: this.toApiModel(stored), pushResults };
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(
|
||||||
|
id: string,
|
||||||
|
updates: {
|
||||||
|
value?: string;
|
||||||
|
description?: string;
|
||||||
|
targets?: interfaces.data.IManagedSecretTarget[];
|
||||||
|
},
|
||||||
|
): Promise<{
|
||||||
|
managedSecret: interfaces.data.IManagedSecret;
|
||||||
|
pushResults: interfaces.data.IManagedSecretTargetStatus[];
|
||||||
|
}> {
|
||||||
|
const stored = this.secrets.find((s) => s.id === id);
|
||||||
|
if (!stored) throw new Error(`Managed secret not found: ${id}`);
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
// Update value in keychain if provided
|
||||||
|
if (updates.value !== undefined) {
|
||||||
|
await this.smartSecret.setSecret(this.keychainId(id), updates.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (updates.description !== undefined) {
|
||||||
|
stored.description = updates.description;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle target changes — delete from removed targets
|
||||||
|
let removedTargets: interfaces.data.IManagedSecretTarget[] = [];
|
||||||
|
if (updates.targets !== undefined) {
|
||||||
|
const oldTargets = stored.targets;
|
||||||
|
const newTargetKeys = new Set(
|
||||||
|
updates.targets.map((t) => `${t.connectionId}:${t.scope}:${t.scopeId}`),
|
||||||
|
);
|
||||||
|
removedTargets = oldTargets.filter(
|
||||||
|
(t) => !newTargetKeys.has(`${t.connectionId}:${t.scope}:${t.scopeId}`),
|
||||||
|
);
|
||||||
|
stored.targets = updates.targets;
|
||||||
|
}
|
||||||
|
|
||||||
|
stored.updatedAt = now;
|
||||||
|
|
||||||
|
// Delete from removed targets
|
||||||
|
if (removedTargets.length > 0) {
|
||||||
|
await this.pushToTargets(stored, 'delete', removedTargets);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Push to current targets
|
||||||
|
const pushResults = await this.pushToTargets(stored, 'upsert');
|
||||||
|
stored.targetStatuses = pushResults;
|
||||||
|
stored.lastPushedAt = now;
|
||||||
|
|
||||||
|
await this.storageManager.setJSON(`${MANAGED_SECRETS_PREFIX}${stored.id}.json`, {
|
||||||
|
...stored,
|
||||||
|
value: `${KEYCHAIN_PREFIX}${this.keychainId(stored.id)}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`Updated managed secret "${stored.key}"`);
|
||||||
|
return { managedSecret: this.toApiModel(stored), pushResults };
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete(id: string): Promise<{
|
||||||
|
ok: boolean;
|
||||||
|
deleteResults: interfaces.data.IManagedSecretTargetStatus[];
|
||||||
|
}> {
|
||||||
|
const stored = this.secrets.find((s) => s.id === id);
|
||||||
|
if (!stored) throw new Error(`Managed secret not found: ${id}`);
|
||||||
|
|
||||||
|
// Best-effort: remove from all targets
|
||||||
|
const deleteResults = await this.pushToTargets(stored, 'delete');
|
||||||
|
|
||||||
|
// Remove from local storage regardless
|
||||||
|
const idx = this.secrets.indexOf(stored);
|
||||||
|
this.secrets.splice(idx, 1);
|
||||||
|
await this.removeFromStorage(id);
|
||||||
|
|
||||||
|
logger.info(`Deleted managed secret "${stored.key}"`);
|
||||||
|
return { ok: true, deleteResults };
|
||||||
|
}
|
||||||
|
|
||||||
|
async pushOne(id: string): Promise<{
|
||||||
|
managedSecret: interfaces.data.IManagedSecret;
|
||||||
|
pushResults: interfaces.data.IManagedSecretTargetStatus[];
|
||||||
|
}> {
|
||||||
|
const stored = this.secrets.find((s) => s.id === id);
|
||||||
|
if (!stored) throw new Error(`Managed secret not found: ${id}`);
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const pushResults = await this.pushToTargets(stored, 'upsert');
|
||||||
|
stored.targetStatuses = pushResults;
|
||||||
|
stored.lastPushedAt = now;
|
||||||
|
stored.updatedAt = now;
|
||||||
|
|
||||||
|
await this.storageManager.setJSON(`${MANAGED_SECRETS_PREFIX}${stored.id}.json`, {
|
||||||
|
...stored,
|
||||||
|
value: `${KEYCHAIN_PREFIX}${this.keychainId(stored.id)}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
return { managedSecret: this.toApiModel(stored), pushResults };
|
||||||
|
}
|
||||||
|
|
||||||
|
async pushAll(): Promise<
|
||||||
|
Array<{
|
||||||
|
managedSecretId: string;
|
||||||
|
key: string;
|
||||||
|
pushResults: interfaces.data.IManagedSecretTargetStatus[];
|
||||||
|
}>
|
||||||
|
> {
|
||||||
|
const results: Array<{
|
||||||
|
managedSecretId: string;
|
||||||
|
key: string;
|
||||||
|
pushResults: interfaces.data.IManagedSecretTargetStatus[];
|
||||||
|
}> = [];
|
||||||
|
|
||||||
|
for (const stored of this.secrets) {
|
||||||
|
const { pushResults } = await this.pushOne(stored.id);
|
||||||
|
results.push({
|
||||||
|
managedSecretId: stored.id,
|
||||||
|
key: stored.key,
|
||||||
|
pushResults,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import type * as interfaces from '../../ts_interfaces/index.ts';
|
|||||||
import type { ConnectionManager } from './connectionmanager.ts';
|
import type { ConnectionManager } from './connectionmanager.ts';
|
||||||
import type { ActionLog } from './actionlog.ts';
|
import type { ActionLog } from './actionlog.ts';
|
||||||
import type { StorageManager } from '../storage/index.ts';
|
import type { StorageManager } from '../storage/index.ts';
|
||||||
|
import type { BaseProvider } from '../providers/classes.baseprovider.ts';
|
||||||
|
|
||||||
const SYNC_PREFIX = '/sync/';
|
const SYNC_PREFIX = '/sync/';
|
||||||
const SYNC_STATUS_PREFIX = '/sync-status/';
|
const SYNC_STATUS_PREFIX = '/sync-status/';
|
||||||
@@ -19,15 +20,19 @@ export class SyncManager {
|
|||||||
private runningSync: Set<string> = new Set();
|
private runningSync: Set<string> = new Set();
|
||||||
private syncedGroupMeta: Set<string> = new Set();
|
private syncedGroupMeta: Set<string> = new Set();
|
||||||
private currentSyncConfig: interfaces.data.ISyncConfig | null = null;
|
private currentSyncConfig: interfaces.data.ISyncConfig | null = null;
|
||||||
|
private avatarUploadCache: Map<string, string> = new Map();
|
||||||
|
|
||||||
|
private mirrorsPath = '';
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private storageManager: StorageManager,
|
private storageManager: StorageManager,
|
||||||
private connectionManager: ConnectionManager,
|
private connectionManager: ConnectionManager,
|
||||||
private actionLog: ActionLog,
|
private actionLog: ActionLog,
|
||||||
private mirrorsPath: string,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async init(): Promise<void> {
|
async init(): Promise<void> {
|
||||||
|
// Create temp directory for mirrors (RAM-backed on most Linux systems via tmpfs)
|
||||||
|
this.mirrorsPath = await Deno.makeTempDir({ prefix: 'gitops-mirrors-' });
|
||||||
await this.loadConfigs();
|
await this.loadConfigs();
|
||||||
for (const config of this.configs) {
|
for (const config of this.configs) {
|
||||||
if (config.status === 'active') {
|
if (config.status === 'active') {
|
||||||
@@ -44,6 +49,12 @@ export class SyncManager {
|
|||||||
clearInterval(timer);
|
clearInterval(timer);
|
||||||
}
|
}
|
||||||
this.timers.clear();
|
this.timers.clear();
|
||||||
|
// Clean up temp mirrors directory
|
||||||
|
if (this.mirrorsPath) {
|
||||||
|
try {
|
||||||
|
await Deno.remove(this.mirrorsPath, { recursive: true });
|
||||||
|
} catch { /* may already be gone */ }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -290,7 +301,7 @@ export class SyncManager {
|
|||||||
const batch = projects.slice(i, i + CONCURRENCY);
|
const batch = projects.slice(i, i + CONCURRENCY);
|
||||||
await Promise.all(batch.map(async (project) => {
|
await Promise.all(batch.map(async (project) => {
|
||||||
try {
|
try {
|
||||||
logger.syncLog('info', `Syncing ${project.fullPath}...`, 'git');
|
logger.syncLog('info', `Syncing ${project.fullPath}...`, 'sync');
|
||||||
await this.syncRepo(config, project, sourceConn, targetConn);
|
await this.syncRepo(config, project, sourceConn, targetConn);
|
||||||
synced++;
|
synced++;
|
||||||
await this.updateRepoStatus(config.id, project.fullPath, {
|
await this.updateRepoStatus(config.id, project.fullPath, {
|
||||||
@@ -298,7 +309,7 @@ export class SyncManager {
|
|||||||
lastSyncAt: Date.now(),
|
lastSyncAt: Date.now(),
|
||||||
lastSyncError: undefined,
|
lastSyncError: undefined,
|
||||||
});
|
});
|
||||||
logger.syncLog('success', `Synced ${project.fullPath}`, 'git');
|
logger.syncLog('success', `Synced ${project.fullPath}`, 'sync');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errMsg = err instanceof Error ? err.message : String(err);
|
const errMsg = err instanceof Error ? err.message : String(err);
|
||||||
await this.updateRepoStatus(config.id, project.fullPath, {
|
await this.updateRepoStatus(config.id, project.fullPath, {
|
||||||
@@ -306,7 +317,7 @@ export class SyncManager {
|
|||||||
lastSyncError: errMsg,
|
lastSyncError: errMsg,
|
||||||
lastSyncAt: Date.now(),
|
lastSyncAt: Date.now(),
|
||||||
});
|
});
|
||||||
logger.syncLog('error', `Sync failed for ${project.fullPath}: ${errMsg}`, 'git');
|
logger.syncLog('error', `Sync failed for ${project.fullPath}: ${errMsg}`, 'sync');
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
@@ -372,21 +383,38 @@ export class SyncManager {
|
|||||||
// Ensure target group/project hierarchy exists
|
// Ensure target group/project hierarchy exists
|
||||||
await this.ensureTargetExists(targetConn, targetFullPath, project, sourceConn, sourceConn.groupFilter, config.targetGroupOffset);
|
await this.ensureTargetExists(targetConn, targetFullPath, project, sourceConn, sourceConn.groupFilter, config.targetGroupOffset);
|
||||||
|
|
||||||
|
// API-based ref comparison (fast path — avoids git clone when refs already match)
|
||||||
|
const sourceProvider = this.connectionManager.getProvider(sourceConn.id);
|
||||||
|
const targetProvider = this.connectionManager.getProvider(targetConn.id);
|
||||||
|
const apiRefsMatch = await this.refsMatchViaApi(
|
||||||
|
sourceProvider, targetProvider, project.fullPath, targetFullPath,
|
||||||
|
);
|
||||||
|
if (apiRefsMatch === true) {
|
||||||
|
logger.syncLog('info', `Refs match via API for ${project.fullPath}, skipping git`, 'api');
|
||||||
|
await this.syncProjectMetadata(config, sourceConn, targetConn, project.fullPath, targetFullPath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Clone or fetch from source
|
// Clone or fetch from source
|
||||||
try {
|
try {
|
||||||
const exists = await this.dirExists(mirrorDir);
|
const exists = await this.dirExists(mirrorDir);
|
||||||
if (!exists) {
|
if (!exists) {
|
||||||
await Deno.mkdir(mirrorDir, { recursive: true });
|
await Deno.mkdir(mirrorDir, { recursive: true });
|
||||||
await this.runGit(['clone', '--bare', sourceUrl, '.'], mirrorDir);
|
await this.runGit(['clone', '--bare', sourceUrl, '.'], mirrorDir);
|
||||||
} else {
|
}
|
||||||
// Update source remote URL in case it changed
|
// Ensure fetch refspec is configured (bare clones don't set one by default,
|
||||||
|
// which prevents tracking branch renames like master -> main)
|
||||||
|
await this.runGit(
|
||||||
|
['config', 'remote.origin.fetch', '+refs/heads/*:refs/heads/*'], mirrorDir,
|
||||||
|
);
|
||||||
|
// Update source remote URL in case connection changed
|
||||||
try {
|
try {
|
||||||
await this.runGit(['remote', 'set-url', 'origin', sourceUrl], mirrorDir);
|
await this.runGit(['remote', 'set-url', 'origin', sourceUrl], mirrorDir);
|
||||||
} catch {
|
} catch {
|
||||||
// Ignore errors
|
// Ignore errors
|
||||||
}
|
}
|
||||||
|
// Fetch latest refs from source (--prune removes branches deleted on remote)
|
||||||
await this.runGit(['fetch', '--prune', 'origin'], mirrorDir);
|
await this.runGit(['fetch', '--prune', 'origin'], mirrorDir);
|
||||||
}
|
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
const msg = err instanceof Error ? err.message : String(err);
|
const msg = err instanceof Error ? err.message : String(err);
|
||||||
if (msg.includes("couldn't find remote ref HEAD")) {
|
if (msg.includes("couldn't find remote ref HEAD")) {
|
||||||
@@ -421,6 +449,12 @@ export class SyncManager {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Compare refs to determine if push is needed
|
||||||
|
const refsAlreadyMatch = !isUnrelated && await this.refsMatch(mirrorDir);
|
||||||
|
|
||||||
|
if (refsAlreadyMatch) {
|
||||||
|
logger.syncLog('info', `Refs already match for ${project.fullPath}, skipping push`, 'api');
|
||||||
|
} else {
|
||||||
// Phase 1: push all refs without pruning (ensures target has all source branches)
|
// Phase 1: push all refs without pruning (ensures target has all source branches)
|
||||||
await this.runGit([
|
await this.runGit([
|
||||||
'push', 'target',
|
'push', 'target',
|
||||||
@@ -441,6 +475,7 @@ export class SyncManager {
|
|||||||
'+refs/tags/*:refs/tags/*',
|
'+refs/tags/*:refs/tags/*',
|
||||||
'--prune',
|
'--prune',
|
||||||
], mirrorDir);
|
], mirrorDir);
|
||||||
|
}
|
||||||
|
|
||||||
// Sync project metadata (description, visibility, topics, default_branch, avatar)
|
// Sync project metadata (description, visibility, topics, default_branch, avatar)
|
||||||
await this.syncProjectMetadata(config, sourceConn, targetConn, project.fullPath, targetFullPath);
|
await this.syncProjectMetadata(config, sourceConn, targetConn, project.fullPath, targetFullPath);
|
||||||
@@ -1007,10 +1042,14 @@ export class SyncManager {
|
|||||||
if (data[0] === 0x89 && data[1] === 0x50) return 'image/png';
|
if (data[0] === 0x89 && data[1] === 0x50) return 'image/png';
|
||||||
if (data[0] === 0xFF && data[1] === 0xD8) return 'image/jpeg';
|
if (data[0] === 0xFF && data[1] === 0xD8) return 'image/jpeg';
|
||||||
if (data[0] === 0x47 && data[1] === 0x49) return 'image/gif';
|
if (data[0] === 0x47 && data[1] === 0x49) return 'image/gif';
|
||||||
|
// SVG: text-based XML, no magic bytes — check content
|
||||||
|
const textStart = new TextDecoder().decode(data.slice(0, 200));
|
||||||
|
if (textStart.includes('<svg') || textStart.includes('<?xml')) return 'image/svg+xml';
|
||||||
// Fallback: check URL extension
|
// Fallback: check URL extension
|
||||||
if (url.includes('.png')) return 'image/png';
|
if (url.includes('.png')) return 'image/png';
|
||||||
if (url.includes('.jpg') || url.includes('.jpeg')) return 'image/jpeg';
|
if (url.includes('.jpg') || url.includes('.jpeg')) return 'image/jpeg';
|
||||||
if (url.includes('.gif')) return 'image/gif';
|
if (url.includes('.gif')) return 'image/gif';
|
||||||
|
if (url.includes('.svg')) return 'image/svg+xml';
|
||||||
return 'image/png'; // default
|
return 'image/png'; // default
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1146,7 +1185,6 @@ export class SyncManager {
|
|||||||
if (sourceGroup) {
|
if (sourceGroup) {
|
||||||
const groupMeta = this.extractGroupMeta(sourceConn, sourceGroup);
|
const groupMeta = this.extractGroupMeta(sourceConn, sourceGroup);
|
||||||
if (groupMeta.avatarUrl) {
|
if (groupMeta.avatarUrl) {
|
||||||
logger.syncLog('info', `Applying group avatar to ${targetFullPath}`, 'api');
|
|
||||||
await this.syncProjectAvatar(sourceConn, targetConn, sourceFullPath, targetFullPath, groupMeta.avatarUrl, targetProject);
|
await this.syncProjectAvatar(sourceConn, targetConn, sourceFullPath, targetFullPath, groupMeta.avatarUrl, targetProject);
|
||||||
groupAvatarApplied = true;
|
groupAvatarApplied = true;
|
||||||
}
|
}
|
||||||
@@ -1293,24 +1331,41 @@ export class SyncManager {
|
|||||||
meta: { description: string; visibility: string; topics: string[]; defaultBranch: string },
|
meta: { description: string; visibility: string; topics: string[]; defaultBranch: string },
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
if (conn.providerType === 'gitlab') {
|
if (conn.providerType === 'gitlab') {
|
||||||
|
// Update description, visibility, topics (always safe)
|
||||||
await this.rawApiCall(conn, 'PUT', `/api/v4/projects/${rawProject.id}`, {
|
await this.rawApiCall(conn, 'PUT', `/api/v4/projects/${rawProject.id}`, {
|
||||||
description: meta.description,
|
description: meta.description,
|
||||||
visibility: this.normalizeVisibility(meta.visibility),
|
visibility: this.normalizeVisibility(meta.visibility),
|
||||||
topics: meta.topics,
|
topics: meta.topics,
|
||||||
|
});
|
||||||
|
// Update default_branch separately — may fail if the branch doesn't exist in git
|
||||||
|
try {
|
||||||
|
await this.rawApiCall(conn, 'PUT', `/api/v4/projects/${rawProject.id}`, {
|
||||||
default_branch: meta.defaultBranch,
|
default_branch: meta.defaultBranch,
|
||||||
});
|
});
|
||||||
|
} catch (err) {
|
||||||
|
const errMsg = err instanceof Error ? err.message : String(err);
|
||||||
|
logger.syncLog('warn', `Could not set default_branch to "${meta.defaultBranch}" for ${fullPath}: ${errMsg}`, 'api');
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
const segments = fullPath.split('/');
|
const segments = fullPath.split('/');
|
||||||
const repo = segments.pop()!;
|
const repo = segments.pop()!;
|
||||||
const owner = segments[0] || '';
|
const owner = segments[0] || '';
|
||||||
const encodedOwner = encodeURIComponent(owner);
|
const encodedOwner = encodeURIComponent(owner);
|
||||||
const encodedRepo = encodeURIComponent(repo);
|
const encodedRepo = encodeURIComponent(repo);
|
||||||
// Update description, visibility, default_branch
|
// Update description, visibility
|
||||||
await this.rawApiCall(conn, 'PATCH', `/api/v1/repos/${encodedOwner}/${encodedRepo}`, {
|
await this.rawApiCall(conn, 'PATCH', `/api/v1/repos/${encodedOwner}/${encodedRepo}`, {
|
||||||
description: meta.description,
|
description: meta.description,
|
||||||
private: this.normalizeVisibility(meta.visibility) === 'private',
|
private: this.normalizeVisibility(meta.visibility) === 'private',
|
||||||
|
});
|
||||||
|
// Update default_branch separately — may fail if the branch doesn't exist in git
|
||||||
|
try {
|
||||||
|
await this.rawApiCall(conn, 'PATCH', `/api/v1/repos/${encodedOwner}/${encodedRepo}`, {
|
||||||
default_branch: meta.defaultBranch,
|
default_branch: meta.defaultBranch,
|
||||||
});
|
});
|
||||||
|
} catch (err) {
|
||||||
|
const errMsg = err instanceof Error ? err.message : String(err);
|
||||||
|
logger.syncLog('warn', `Could not set default_branch to "${meta.defaultBranch}" for ${fullPath}: ${errMsg}`, 'api');
|
||||||
|
}
|
||||||
// Topics are a separate endpoint in Gitea
|
// Topics are a separate endpoint in Gitea
|
||||||
await this.rawApiCall(conn, 'PUT', `/api/v1/repos/${encodedOwner}/${encodedRepo}/topics`, {
|
await this.rawApiCall(conn, 'PUT', `/api/v1/repos/${encodedOwner}/${encodedRepo}/topics`, {
|
||||||
topics: meta.topics,
|
topics: meta.topics,
|
||||||
@@ -1355,25 +1410,55 @@ export class SyncManager {
|
|||||||
private async syncProjectAvatar(
|
private async syncProjectAvatar(
|
||||||
sourceConn: interfaces.data.IProviderConnection,
|
sourceConn: interfaces.data.IProviderConnection,
|
||||||
targetConn: interfaces.data.IProviderConnection,
|
targetConn: interfaces.data.IProviderConnection,
|
||||||
sourceFullPath: string,
|
_sourceFullPath: string,
|
||||||
targetFullPath: string,
|
targetFullPath: string,
|
||||||
sourceAvatarUrl: string,
|
sourceAvatarUrl: string,
|
||||||
targetRawProject: any,
|
targetRawProject: any,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
// Resolve relative avatar URLs
|
// Resolve relative avatar URLs
|
||||||
const resolvedUrl = sourceAvatarUrl.startsWith('http')
|
const resolvedSourceUrl = sourceAvatarUrl.startsWith('http')
|
||||||
? sourceAvatarUrl
|
? sourceAvatarUrl
|
||||||
: `${sourceConn.baseUrl.replace(/\/+$/, '')}${sourceAvatarUrl}`;
|
: `${sourceConn.baseUrl.replace(/\/+$/, '')}${sourceAvatarUrl}`;
|
||||||
|
|
||||||
const avatarData = await this.rawBinaryFetch(sourceConn, resolvedUrl);
|
const sourceAvatarData = await this.rawBinaryFetch(sourceConn, resolvedSourceUrl);
|
||||||
if (!avatarData || avatarData.length === 0) return;
|
if (!sourceAvatarData || sourceAvatarData.length === 0) return;
|
||||||
|
|
||||||
|
// Skip SVG avatars — not supported by GitLab project endpoints
|
||||||
|
const mimeType = this.guessAvatarMimeType(sourceAvatarData, resolvedSourceUrl);
|
||||||
|
if (mimeType === 'image/svg+xml') {
|
||||||
|
logger.syncLog('warn', `Skipping SVG avatar for ${targetFullPath} (not supported by target)`, 'api');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check in-memory cache: skip if source hasn't changed since last upload
|
||||||
|
const sourceHash = await this.hashBytes(sourceAvatarData);
|
||||||
|
const cacheKey = `project:${targetFullPath}`;
|
||||||
|
if (this.avatarUploadCache.get(cacheKey) === sourceHash) {
|
||||||
|
return; // Source avatar unchanged since last upload
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compare with target's current avatar to avoid unnecessary uploads
|
||||||
|
const targetMeta = this.extractProjectMeta(targetConn, targetRawProject);
|
||||||
|
if (targetMeta.avatarUrl) {
|
||||||
|
try {
|
||||||
|
const resolvedTargetUrl = targetMeta.avatarUrl.startsWith('http')
|
||||||
|
? targetMeta.avatarUrl
|
||||||
|
: `${targetConn.baseUrl.replace(/\/+$/, '')}${targetMeta.avatarUrl}`;
|
||||||
|
const targetAvatarData = await this.rawBinaryFetch(targetConn, resolvedTargetUrl);
|
||||||
|
if (targetAvatarData && this.binaryEqual(sourceAvatarData, targetAvatarData)) {
|
||||||
|
this.avatarUploadCache.set(cacheKey, sourceHash);
|
||||||
|
return; // Avatars are identical — skip upload
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Failed to fetch target avatar — proceed with upload as safe fallback
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
logger.syncLog('info', `Syncing avatar for ${targetFullPath}...`, 'api');
|
logger.syncLog('info', `Syncing avatar for ${targetFullPath}...`, 'api');
|
||||||
|
|
||||||
if (targetConn.providerType === 'gitlab') {
|
if (targetConn.providerType === 'gitlab') {
|
||||||
// GitLab: multipart upload
|
// GitLab: multipart upload
|
||||||
const mimeType = this.guessAvatarMimeType(avatarData, resolvedUrl);
|
const blob = new Blob([sourceAvatarData.buffer as ArrayBuffer], { type: mimeType });
|
||||||
const blob = new Blob([avatarData.buffer as ArrayBuffer], { type: mimeType });
|
|
||||||
const ext = mimeType.split('/')[1] || 'png';
|
const ext = mimeType.split('/')[1] || 'png';
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('avatar', blob, `avatar.${ext}`);
|
formData.append('avatar', blob, `avatar.${ext}`);
|
||||||
@@ -1387,13 +1472,15 @@ export class SyncManager {
|
|||||||
const segments = targetFullPath.split('/');
|
const segments = targetFullPath.split('/');
|
||||||
const repo = segments.pop()!;
|
const repo = segments.pop()!;
|
||||||
const owner = segments[0] || '';
|
const owner = segments[0] || '';
|
||||||
const base64Image = this.uint8ArrayToBase64(avatarData);
|
const base64Image = this.uint8ArrayToBase64(sourceAvatarData);
|
||||||
await this.rawApiCall(
|
await this.rawApiCall(
|
||||||
targetConn, 'POST',
|
targetConn, 'POST',
|
||||||
`/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/avatar`,
|
`/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/avatar`,
|
||||||
{ image: base64Image },
|
{ image: base64Image },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.avatarUploadCache.set(cacheKey, sourceHash);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async removeProjectAvatar(
|
private async removeProjectAvatar(
|
||||||
@@ -1423,18 +1510,48 @@ export class SyncManager {
|
|||||||
sourceAvatarUrl: string,
|
sourceAvatarUrl: string,
|
||||||
targetRawGroup: any,
|
targetRawGroup: any,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const resolvedUrl = sourceAvatarUrl.startsWith('http')
|
const resolvedSourceUrl = sourceAvatarUrl.startsWith('http')
|
||||||
? sourceAvatarUrl
|
? sourceAvatarUrl
|
||||||
: `${sourceConn.baseUrl.replace(/\/+$/, '')}${sourceAvatarUrl}`;
|
: `${sourceConn.baseUrl.replace(/\/+$/, '')}${sourceAvatarUrl}`;
|
||||||
|
|
||||||
const avatarData = await this.rawBinaryFetch(sourceConn, resolvedUrl);
|
const sourceAvatarData = await this.rawBinaryFetch(sourceConn, resolvedSourceUrl);
|
||||||
if (!avatarData || avatarData.length === 0) return;
|
if (!sourceAvatarData || sourceAvatarData.length === 0) return;
|
||||||
|
|
||||||
|
// Skip SVG avatars — not supported by GitLab project endpoints
|
||||||
|
const mimeType = this.guessAvatarMimeType(sourceAvatarData, resolvedSourceUrl);
|
||||||
|
if (mimeType === 'image/svg+xml') {
|
||||||
|
logger.syncLog('warn', `Skipping SVG avatar for group ${targetGroupPath} (not supported by target)`, 'api');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check in-memory cache: skip if source hasn't changed since last upload
|
||||||
|
const sourceHash = await this.hashBytes(sourceAvatarData);
|
||||||
|
const cacheKey = `group:${targetGroupPath}`;
|
||||||
|
if (this.avatarUploadCache.get(cacheKey) === sourceHash) {
|
||||||
|
return; // Source avatar unchanged since last upload
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compare with target's current avatar to avoid unnecessary uploads
|
||||||
|
const targetMeta = this.extractGroupMeta(targetConn, targetRawGroup);
|
||||||
|
if (targetMeta.avatarUrl) {
|
||||||
|
try {
|
||||||
|
const resolvedTargetUrl = targetMeta.avatarUrl.startsWith('http')
|
||||||
|
? targetMeta.avatarUrl
|
||||||
|
: `${targetConn.baseUrl.replace(/\/+$/, '')}${targetMeta.avatarUrl}`;
|
||||||
|
const targetAvatarData = await this.rawBinaryFetch(targetConn, resolvedTargetUrl);
|
||||||
|
if (targetAvatarData && this.binaryEqual(sourceAvatarData, targetAvatarData)) {
|
||||||
|
this.avatarUploadCache.set(cacheKey, sourceHash);
|
||||||
|
return; // Avatars are identical — skip upload
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Failed to fetch target avatar — proceed with upload as safe fallback
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
logger.syncLog('info', `Syncing avatar for group ${targetGroupPath}...`, 'api');
|
logger.syncLog('info', `Syncing avatar for group ${targetGroupPath}...`, 'api');
|
||||||
|
|
||||||
if (targetConn.providerType === 'gitlab') {
|
if (targetConn.providerType === 'gitlab') {
|
||||||
const mimeType = this.guessAvatarMimeType(avatarData, resolvedUrl);
|
const blob = new Blob([sourceAvatarData.buffer as ArrayBuffer], { type: mimeType });
|
||||||
const blob = new Blob([avatarData.buffer as ArrayBuffer], { type: mimeType });
|
|
||||||
const ext = mimeType.split('/')[1] || 'png';
|
const ext = mimeType.split('/')[1] || 'png';
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('avatar', blob, `avatar.${ext}`);
|
formData.append('avatar', blob, `avatar.${ext}`);
|
||||||
@@ -1445,13 +1562,15 @@ export class SyncManager {
|
|||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
const orgName = targetGroupPath.split('/')[0] || targetGroupPath;
|
const orgName = targetGroupPath.split('/')[0] || targetGroupPath;
|
||||||
const base64Image = this.uint8ArrayToBase64(avatarData);
|
const base64Image = this.uint8ArrayToBase64(sourceAvatarData);
|
||||||
await this.rawApiCall(
|
await this.rawApiCall(
|
||||||
targetConn, 'POST',
|
targetConn, 'POST',
|
||||||
`/api/v1/orgs/${encodeURIComponent(orgName)}/avatar`,
|
`/api/v1/orgs/${encodeURIComponent(orgName)}/avatar`,
|
||||||
{ image: base64Image },
|
{ image: base64Image },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.avatarUploadCache.set(cacheKey, sourceHash);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async removeGroupAvatar(
|
private async removeGroupAvatar(
|
||||||
@@ -1471,6 +1590,19 @@ export class SyncManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private binaryEqual(a: Uint8Array, b: Uint8Array): boolean {
|
||||||
|
if (a.length !== b.length) return false;
|
||||||
|
for (let i = 0; i < a.length; i++) {
|
||||||
|
if (a[i] !== b[i]) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async hashBytes(data: Uint8Array): Promise<string> {
|
||||||
|
const hashBuffer = await crypto.subtle.digest('SHA-256', data.buffer as ArrayBuffer);
|
||||||
|
return Array.from(new Uint8Array(hashBuffer)).map(b => b.toString(16).padStart(2, '0')).join('');
|
||||||
|
}
|
||||||
|
|
||||||
private uint8ArrayToBase64(bytes: Uint8Array): string {
|
private uint8ArrayToBase64(bytes: Uint8Array): string {
|
||||||
let binary = '';
|
let binary = '';
|
||||||
for (let i = 0; i < bytes.length; i++) {
|
for (let i = 0; i < bytes.length; i++) {
|
||||||
@@ -1690,6 +1822,133 @@ export class SyncManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch all branch and tag SHAs from a repo via provider API.
|
||||||
|
* Returns null on any error (safe fallback to git-based comparison).
|
||||||
|
*/
|
||||||
|
private async listRefsViaProvider(
|
||||||
|
provider: BaseProvider,
|
||||||
|
fullPath: string,
|
||||||
|
): Promise<{ branches: Map<string, string>; tags: Map<string, string> } | null> {
|
||||||
|
try {
|
||||||
|
const [branches, tags] = await Promise.all([
|
||||||
|
provider.getBranches(fullPath),
|
||||||
|
provider.getTags(fullPath),
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
branches: new Map(branches.map((b) => [b.name, b.commitSha])),
|
||||||
|
tags: new Map(tags.map((t) => [t.name, t.commitSha])),
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compare refs between source and target via provider API (no git clone needed).
|
||||||
|
* Returns true (match), false (differ), or null (can't determine — fall through to git).
|
||||||
|
*/
|
||||||
|
private async refsMatchViaApi(
|
||||||
|
sourceProvider: BaseProvider,
|
||||||
|
targetProvider: BaseProvider,
|
||||||
|
sourceFullPath: string,
|
||||||
|
targetFullPath: string,
|
||||||
|
): Promise<boolean | null> {
|
||||||
|
const [sourceRefs, targetRefs] = await Promise.all([
|
||||||
|
this.listRefsViaProvider(sourceProvider, sourceFullPath),
|
||||||
|
this.listRefsViaProvider(targetProvider, targetFullPath),
|
||||||
|
]);
|
||||||
|
if (!sourceRefs || !targetRefs) return null;
|
||||||
|
|
||||||
|
// Compare branches
|
||||||
|
if (sourceRefs.branches.size !== targetRefs.branches.size) return false;
|
||||||
|
for (const [name, sha] of sourceRefs.branches) {
|
||||||
|
if (targetRefs.branches.get(name) !== sha) return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compare tags
|
||||||
|
if (sourceRefs.tags.size !== targetRefs.tags.size) return false;
|
||||||
|
for (const [name, sha] of sourceRefs.tags) {
|
||||||
|
if (targetRefs.tags.get(name) !== sha) return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compare local refs (source) with target remote refs.
|
||||||
|
* Returns true when all branches and tags are identical — no push needed.
|
||||||
|
*/
|
||||||
|
private async refsMatch(mirrorDir: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
// Local branches (source)
|
||||||
|
const localHeadsRaw = await this.runGit(
|
||||||
|
['for-each-ref', '--format=%(refname:strip=2) %(objectname)', 'refs/heads/'], mirrorDir,
|
||||||
|
);
|
||||||
|
// Target branches (fetched by checkUnrelatedHistory)
|
||||||
|
const targetHeadsRaw = await this.runGit(
|
||||||
|
['for-each-ref', '--format=%(refname:strip=3) %(objectname)', 'refs/remotes/target/'], mirrorDir,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Local tags
|
||||||
|
const localTagsRaw = await this.runGit(
|
||||||
|
['for-each-ref', '--format=%(refname:strip=2) %(objectname)', 'refs/tags/'], mirrorDir,
|
||||||
|
);
|
||||||
|
// Target tags via ls-remote (avoids shared refs/tags/ namespace ambiguity in bare repos)
|
||||||
|
const targetTagsRaw = await this.runGit(['ls-remote', '--tags', 'target'], mirrorDir);
|
||||||
|
|
||||||
|
const parseRefLines = (raw: string): Map<string, string> => {
|
||||||
|
const map = new Map<string, string>();
|
||||||
|
for (const line of raw.trim().split('\n')) {
|
||||||
|
if (!line.trim()) continue;
|
||||||
|
const parts = line.trim().split(/\s+/);
|
||||||
|
if (parts.length >= 2) {
|
||||||
|
map.set(parts[0], parts[1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseLsRemoteTags = (raw: string): Map<string, string> => {
|
||||||
|
const map = new Map<string, string>();
|
||||||
|
for (const line of raw.trim().split('\n')) {
|
||||||
|
if (!line.trim()) continue;
|
||||||
|
// Skip ^{} dereference lines
|
||||||
|
if (line.includes('^{}')) continue;
|
||||||
|
const parts = line.trim().split(/\s+/);
|
||||||
|
if (parts.length >= 2) {
|
||||||
|
// parts[0] = sha, parts[1] = refs/tags/name
|
||||||
|
const tagName = parts[1].replace('refs/tags/', '');
|
||||||
|
map.set(tagName, parts[0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
};
|
||||||
|
|
||||||
|
const localHeads = parseRefLines(localHeadsRaw);
|
||||||
|
const targetHeads = parseRefLines(targetHeadsRaw);
|
||||||
|
const localTags = parseRefLines(localTagsRaw);
|
||||||
|
const targetTags = parseLsRemoteTags(targetTagsRaw);
|
||||||
|
|
||||||
|
// Compare branches
|
||||||
|
if (localHeads.size !== targetHeads.size) return false;
|
||||||
|
for (const [name, sha] of localHeads) {
|
||||||
|
if (targetHeads.get(name) !== sha) return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compare tags
|
||||||
|
if (localTags.size !== targetTags.size) return false;
|
||||||
|
for (const [name, sha] of localTags) {
|
||||||
|
if (targetTags.get(name) !== sha) return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
// On any error, fall back to pushing (safe default)
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async runGit(args: string[], cwd?: string): Promise<string> {
|
private async runGit(args: string[], cwd?: string): Promise<string> {
|
||||||
const cmd = new Deno.Command('git', {
|
const cmd = new Deno.Command('git', {
|
||||||
args,
|
args,
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ export class OpsServer {
|
|||||||
public actionsHandler!: handlers.ActionsHandler;
|
public actionsHandler!: handlers.ActionsHandler;
|
||||||
public actionLogHandler!: handlers.ActionLogHandler;
|
public actionLogHandler!: handlers.ActionLogHandler;
|
||||||
public syncHandler!: handlers.SyncHandler;
|
public syncHandler!: handlers.SyncHandler;
|
||||||
|
public managedSecretsHandler!: handlers.ManagedSecretsHandler;
|
||||||
|
|
||||||
constructor(gitopsAppRef: GitopsApp) {
|
constructor(gitopsAppRef: GitopsApp) {
|
||||||
this.gitopsAppRef = gitopsAppRef;
|
this.gitopsAppRef = gitopsAppRef;
|
||||||
@@ -65,6 +66,7 @@ export class OpsServer {
|
|||||||
this.actionsHandler = new handlers.ActionsHandler(this);
|
this.actionsHandler = new handlers.ActionsHandler(this);
|
||||||
this.actionLogHandler = new handlers.ActionLogHandler(this);
|
this.actionLogHandler = new handlers.ActionLogHandler(this);
|
||||||
this.syncHandler = new handlers.SyncHandler(this);
|
this.syncHandler = new handlers.SyncHandler(this);
|
||||||
|
this.managedSecretsHandler = new handlers.ManagedSecretsHandler(this);
|
||||||
|
|
||||||
logger.success('OpsServer TypedRequest handlers initialized');
|
logger.success('OpsServer TypedRequest handlers initialized');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,3 +9,4 @@ export { WebhookHandler } from './webhook.handler.ts';
|
|||||||
export { ActionsHandler } from './actions.handler.ts';
|
export { ActionsHandler } from './actions.handler.ts';
|
||||||
export { ActionLogHandler } from './actionlog.handler.ts';
|
export { ActionLogHandler } from './actionlog.handler.ts';
|
||||||
export { SyncHandler } from './sync.handler.ts';
|
export { SyncHandler } from './sync.handler.ts';
|
||||||
|
export { ManagedSecretsHandler } from './managedsecrets.handler.ts';
|
||||||
|
|||||||
158
ts/opsserver/handlers/managedsecrets.handler.ts
Normal file
158
ts/opsserver/handlers/managedsecrets.handler.ts
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
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 ManagedSecretsHandler {
|
||||||
|
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||||
|
|
||||||
|
constructor(private opsServerRef: OpsServer) {
|
||||||
|
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||||
|
this.registerHandlers();
|
||||||
|
}
|
||||||
|
|
||||||
|
private get actionLog() {
|
||||||
|
return this.opsServerRef.gitopsAppRef.actionLog;
|
||||||
|
}
|
||||||
|
|
||||||
|
private get manager() {
|
||||||
|
return this.opsServerRef.gitopsAppRef.managedSecretsManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
private registerHandlers(): void {
|
||||||
|
// List all managed secrets
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetManagedSecrets>(
|
||||||
|
'getManagedSecrets',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const managedSecrets = await this.manager.getAll();
|
||||||
|
return { managedSecrets };
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Get single managed secret
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetManagedSecret>(
|
||||||
|
'getManagedSecret',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const managedSecret = await this.manager.getById(dataArg.managedSecretId);
|
||||||
|
if (!managedSecret) throw new Error(`Managed secret not found: ${dataArg.managedSecretId}`);
|
||||||
|
return { managedSecret };
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Create managed secret
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateManagedSecret>(
|
||||||
|
'createManagedSecret',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const result = await this.manager.create(
|
||||||
|
dataArg.key,
|
||||||
|
dataArg.value,
|
||||||
|
dataArg.description,
|
||||||
|
dataArg.targets,
|
||||||
|
);
|
||||||
|
this.actionLog.append({
|
||||||
|
actionType: 'create',
|
||||||
|
entityType: 'managed-secret',
|
||||||
|
entityId: result.managedSecret.id,
|
||||||
|
entityName: `GITOPS_${dataArg.key}`,
|
||||||
|
details: `Created managed secret "${dataArg.key}" with ${dataArg.targets.length} target(s)`,
|
||||||
|
username: dataArg.identity.username,
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Update managed secret
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateManagedSecret>(
|
||||||
|
'updateManagedSecret',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const result = await this.manager.update(dataArg.managedSecretId, {
|
||||||
|
value: dataArg.value,
|
||||||
|
description: dataArg.description,
|
||||||
|
targets: dataArg.targets,
|
||||||
|
});
|
||||||
|
this.actionLog.append({
|
||||||
|
actionType: 'update',
|
||||||
|
entityType: 'managed-secret',
|
||||||
|
entityId: dataArg.managedSecretId,
|
||||||
|
entityName: `GITOPS_${result.managedSecret.key}`,
|
||||||
|
details: `Updated managed secret "${result.managedSecret.key}"`,
|
||||||
|
username: dataArg.identity.username,
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Delete managed secret
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteManagedSecret>(
|
||||||
|
'deleteManagedSecret',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const secret = await this.manager.getById(dataArg.managedSecretId);
|
||||||
|
const result = await this.manager.delete(dataArg.managedSecretId);
|
||||||
|
this.actionLog.append({
|
||||||
|
actionType: 'delete',
|
||||||
|
entityType: 'managed-secret',
|
||||||
|
entityId: dataArg.managedSecretId,
|
||||||
|
entityName: secret ? `GITOPS_${secret.key}` : dataArg.managedSecretId,
|
||||||
|
details: `Deleted managed secret${secret ? ` "${secret.key}"` : ''}`,
|
||||||
|
username: dataArg.identity.username,
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Push single managed secret
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushManagedSecret>(
|
||||||
|
'pushManagedSecret',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const result = await this.manager.pushOne(dataArg.managedSecretId);
|
||||||
|
this.actionLog.append({
|
||||||
|
actionType: 'push',
|
||||||
|
entityType: 'managed-secret',
|
||||||
|
entityId: dataArg.managedSecretId,
|
||||||
|
entityName: `GITOPS_${result.managedSecret.key}`,
|
||||||
|
details: `Pushed managed secret "${result.managedSecret.key}" to ${result.pushResults.length} target(s)`,
|
||||||
|
username: dataArg.identity.username,
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Push all managed secrets
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushAllManagedSecrets>(
|
||||||
|
'pushAllManagedSecrets',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireValidIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const results = await this.manager.pushAll();
|
||||||
|
this.actionLog.append({
|
||||||
|
actionType: 'push',
|
||||||
|
entityType: 'managed-secret',
|
||||||
|
entityId: 'all',
|
||||||
|
entityName: 'All managed secrets',
|
||||||
|
details: `Pushed ${results.length} managed secret(s) to their targets`,
|
||||||
|
username: dataArg.identity.username,
|
||||||
|
});
|
||||||
|
return { results };
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,7 +22,7 @@ export class SyncHandler {
|
|||||||
try {
|
try {
|
||||||
const typedsocket = this.opsServerRef.server?.typedserver?.typedsocket;
|
const typedsocket = this.opsServerRef.server?.typedserver?.typedsocket;
|
||||||
if (!typedsocket) return;
|
if (!typedsocket) return;
|
||||||
typedsocket.findAllTargetConnectionsByTag('allClients').then((connections) => {
|
typedsocket.findAllTargetConnectionsByTag('syncLogClient').then((connections) => {
|
||||||
for (const conn of connections) {
|
for (const conn of connections) {
|
||||||
typedsocket
|
typedsocket
|
||||||
.createTypedRequest<interfaces.requests.IReq_PushSyncLog>('pushSyncLog', conn)
|
.createTypedRequest<interfaces.requests.IReq_PushSyncLog>('pushSyncLog', conn)
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ export class WebhookHandler {
|
|||||||
try {
|
try {
|
||||||
const typedsocket = this.opsServerRef.server.typedserver.typedsocket;
|
const typedsocket = this.opsServerRef.server.typedserver.typedsocket;
|
||||||
if (typedsocket) {
|
if (typedsocket) {
|
||||||
const connections = await typedsocket.findAllTargetConnectionsByTag('allClients');
|
const connections = await typedsocket.findAllTargetConnectionsByTag('syncLogClient');
|
||||||
for (const conn of connections) {
|
for (const conn of connections) {
|
||||||
const req = typedsocket.createTypedRequest<interfaces.requests.IReq_WebhookNotification>(
|
const req = typedsocket.createTypedRequest<interfaces.requests.IReq_WebhookNotification>(
|
||||||
'webhookNotification',
|
'webhookNotification',
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ export interface IGitopsPaths {
|
|||||||
gitopsHomeDir: string;
|
gitopsHomeDir: string;
|
||||||
defaultStoragePath: string;
|
defaultStoragePath: string;
|
||||||
defaultTsmDbPath: string;
|
defaultTsmDbPath: string;
|
||||||
syncMirrorsPath: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -16,6 +15,5 @@ export function resolvePaths(baseDir?: string): IGitopsPaths {
|
|||||||
gitopsHomeDir: home,
|
gitopsHomeDir: home,
|
||||||
defaultStoragePath: path.join(home, 'storage'),
|
defaultStoragePath: path.join(home, 'storage'),
|
||||||
defaultTsmDbPath: path.join(home, 'tsmdb'),
|
defaultTsmDbPath: path.join(home, 'tsmdb'),
|
||||||
syncMirrorsPath: path.join(home, 'mirrors'),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -64,6 +64,10 @@ export abstract class BaseProvider {
|
|||||||
): Promise<interfaces.data.ISecret>;
|
): Promise<interfaces.data.ISecret>;
|
||||||
abstract deleteGroupSecret(groupId: string, key: string): Promise<void>;
|
abstract deleteGroupSecret(groupId: string, key: string): Promise<void>;
|
||||||
|
|
||||||
|
// Branches / Tags
|
||||||
|
abstract getBranches(projectFullPath: string, opts?: IListOptions): Promise<interfaces.data.IBranch[]>;
|
||||||
|
abstract getTags(projectFullPath: string, opts?: IListOptions): Promise<interfaces.data.ITag[]>;
|
||||||
|
|
||||||
// Pipelines / CI
|
// Pipelines / CI
|
||||||
abstract getPipelines(
|
abstract getPipelines(
|
||||||
projectId: string,
|
projectId: string,
|
||||||
|
|||||||
@@ -70,6 +70,42 @@ export class GiteaProvider extends BaseProvider {
|
|||||||
return allOrgs.map((o) => this.mapGroup(o));
|
return allOrgs.map((o) => this.mapGroup(o));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Branches / Tags ---
|
||||||
|
|
||||||
|
async getBranches(projectFullPath: string, opts?: IListOptions): Promise<interfaces.data.IBranch[]> {
|
||||||
|
if (opts?.page) {
|
||||||
|
const branches = await this.client.getRepoBranches(projectFullPath, opts);
|
||||||
|
return branches.map((b) => ({ name: b.name, commitSha: b.commit.id }));
|
||||||
|
}
|
||||||
|
const all: interfaces.data.IBranch[] = [];
|
||||||
|
const perPage = opts?.perPage || 50;
|
||||||
|
let page = 1;
|
||||||
|
while (true) {
|
||||||
|
const branches = await this.client.getRepoBranches(projectFullPath, { ...opts, page, perPage });
|
||||||
|
all.push(...branches.map((b) => ({ name: b.name, commitSha: b.commit.id })));
|
||||||
|
if (branches.length < perPage) break;
|
||||||
|
page++;
|
||||||
|
}
|
||||||
|
return all;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getTags(projectFullPath: string, opts?: IListOptions): Promise<interfaces.data.ITag[]> {
|
||||||
|
if (opts?.page) {
|
||||||
|
const tags = await this.client.getRepoTags(projectFullPath, opts);
|
||||||
|
return tags.map((t) => ({ name: t.name, commitSha: t.commit.sha }));
|
||||||
|
}
|
||||||
|
const all: interfaces.data.ITag[] = [];
|
||||||
|
const perPage = opts?.perPage || 50;
|
||||||
|
let page = 1;
|
||||||
|
while (true) {
|
||||||
|
const tags = await this.client.getRepoTags(projectFullPath, { ...opts, page, perPage });
|
||||||
|
all.push(...tags.map((t) => ({ name: t.name, commitSha: t.commit.sha })));
|
||||||
|
if (tags.length < perPage) break;
|
||||||
|
page++;
|
||||||
|
}
|
||||||
|
return all;
|
||||||
|
}
|
||||||
|
|
||||||
// --- Project Secrets ---
|
// --- Project Secrets ---
|
||||||
|
|
||||||
async getProjectSecrets(projectId: string): Promise<interfaces.data.ISecret[]> {
|
async getProjectSecrets(projectId: string): Promise<interfaces.data.ISecret[]> {
|
||||||
|
|||||||
@@ -85,6 +85,42 @@ export class GitLabProvider extends BaseProvider {
|
|||||||
return allGroups.map((g) => this.mapGroup(g));
|
return allGroups.map((g) => this.mapGroup(g));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Branches / Tags ---
|
||||||
|
|
||||||
|
async getBranches(projectFullPath: string, opts?: IListOptions): Promise<interfaces.data.IBranch[]> {
|
||||||
|
if (opts?.page) {
|
||||||
|
const branches = await this.client.getRepoBranches(projectFullPath, opts);
|
||||||
|
return branches.map((b) => ({ name: b.name, commitSha: b.commit.id }));
|
||||||
|
}
|
||||||
|
const all: interfaces.data.IBranch[] = [];
|
||||||
|
const perPage = opts?.perPage || 50;
|
||||||
|
let page = 1;
|
||||||
|
while (true) {
|
||||||
|
const branches = await this.client.getRepoBranches(projectFullPath, { ...opts, page, perPage });
|
||||||
|
all.push(...branches.map((b) => ({ name: b.name, commitSha: b.commit.id })));
|
||||||
|
if (branches.length < perPage) break;
|
||||||
|
page++;
|
||||||
|
}
|
||||||
|
return all;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getTags(projectFullPath: string, opts?: IListOptions): Promise<interfaces.data.ITag[]> {
|
||||||
|
if (opts?.page) {
|
||||||
|
const tags = await this.client.getRepoTags(projectFullPath, opts);
|
||||||
|
return tags.map((t) => ({ name: t.name, commitSha: t.commit.id }));
|
||||||
|
}
|
||||||
|
const all: interfaces.data.ITag[] = [];
|
||||||
|
const perPage = opts?.perPage || 50;
|
||||||
|
let page = 1;
|
||||||
|
while (true) {
|
||||||
|
const tags = await this.client.getRepoTags(projectFullPath, { ...opts, page, perPage });
|
||||||
|
all.push(...tags.map((t) => ({ name: t.name, commitSha: t.commit.id })));
|
||||||
|
if (tags.length < perPage) break;
|
||||||
|
page++;
|
||||||
|
}
|
||||||
|
return all;
|
||||||
|
}
|
||||||
|
|
||||||
// --- Project Secrets (CI/CD Variables) ---
|
// --- Project Secrets (CI/CD Variables) ---
|
||||||
|
|
||||||
async getProjectSecrets(projectId: string): Promise<interfaces.data.ISecret[]> {
|
async getProjectSecrets(projectId: string): Promise<interfaces.data.ISecret[]> {
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -1,5 +1,5 @@
|
|||||||
export type TActionType = 'create' | 'update' | 'delete' | 'pause' | 'resume' | 'test' | 'scan' | 'sync' | 'obsolete';
|
export type TActionType = 'create' | 'update' | 'delete' | 'pause' | 'resume' | 'test' | 'scan' | 'sync' | 'obsolete' | 'push';
|
||||||
export type TActionEntity = 'connection' | 'secret' | 'pipeline' | 'sync';
|
export type TActionEntity = 'connection' | 'secret' | 'pipeline' | 'sync' | 'managed-secret';
|
||||||
|
|
||||||
export interface IActionLogEntry {
|
export interface IActionLogEntry {
|
||||||
id: string;
|
id: string;
|
||||||
|
|||||||
9
ts_interfaces/data/branch.ts
Normal file
9
ts_interfaces/data/branch.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
export interface IBranch {
|
||||||
|
name: string;
|
||||||
|
commitSha: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ITag {
|
||||||
|
name: string;
|
||||||
|
commitSha: string;
|
||||||
|
}
|
||||||
@@ -2,7 +2,9 @@ export * from './identity.ts';
|
|||||||
export * from './connection.ts';
|
export * from './connection.ts';
|
||||||
export * from './project.ts';
|
export * from './project.ts';
|
||||||
export * from './group.ts';
|
export * from './group.ts';
|
||||||
|
export * from './branch.ts';
|
||||||
export * from './secret.ts';
|
export * from './secret.ts';
|
||||||
export * from './pipeline.ts';
|
export * from './pipeline.ts';
|
||||||
export * from './actionlog.ts';
|
export * from './actionlog.ts';
|
||||||
export * from './sync.ts';
|
export * from './sync.ts';
|
||||||
|
export * from './managedsecret.ts';
|
||||||
|
|||||||
41
ts_interfaces/data/managedsecret.ts
Normal file
41
ts_interfaces/data/managedsecret.ts
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
export interface IManagedSecretTarget {
|
||||||
|
connectionId: string;
|
||||||
|
scope: 'project' | 'group';
|
||||||
|
scopeId: string;
|
||||||
|
scopeName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TPushStatus = 'pending' | 'success' | 'error';
|
||||||
|
|
||||||
|
export interface IManagedSecretTargetStatus {
|
||||||
|
connectionId: string;
|
||||||
|
scope: 'project' | 'group';
|
||||||
|
scopeId: string;
|
||||||
|
scopeName: string;
|
||||||
|
status: TPushStatus;
|
||||||
|
error?: string;
|
||||||
|
lastPushedAt?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IManagedSecret {
|
||||||
|
id: string;
|
||||||
|
key: string;
|
||||||
|
description?: string;
|
||||||
|
targets: IManagedSecretTarget[];
|
||||||
|
targetStatuses: IManagedSecretTargetStatus[];
|
||||||
|
createdAt: number;
|
||||||
|
updatedAt: number;
|
||||||
|
lastPushedAt?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IManagedSecretStored {
|
||||||
|
id: string;
|
||||||
|
key: string;
|
||||||
|
description?: string;
|
||||||
|
value: string;
|
||||||
|
targets: IManagedSecretTarget[];
|
||||||
|
targetStatuses: IManagedSecretTargetStatus[];
|
||||||
|
createdAt: number;
|
||||||
|
updatedAt: number;
|
||||||
|
lastPushedAt?: number;
|
||||||
|
}
|
||||||
@@ -9,3 +9,4 @@ export * from './webhook.ts';
|
|||||||
export * from './actions.ts';
|
export * from './actions.ts';
|
||||||
export * from './actionlog.ts';
|
export * from './actionlog.ts';
|
||||||
export * from './sync.ts';
|
export * from './sync.ts';
|
||||||
|
export * from './managedsecrets.ts';
|
||||||
|
|||||||
112
ts_interfaces/requests/managedsecrets.ts
Normal file
112
ts_interfaces/requests/managedsecrets.ts
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
import * as plugins from '../plugins.ts';
|
||||||
|
import * as data from '../data/index.ts';
|
||||||
|
|
||||||
|
export interface IReq_GetManagedSecrets extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_GetManagedSecrets
|
||||||
|
> {
|
||||||
|
method: 'getManagedSecrets';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
managedSecrets: data.IManagedSecret[];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_GetManagedSecret extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_GetManagedSecret
|
||||||
|
> {
|
||||||
|
method: 'getManagedSecret';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
managedSecretId: string;
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
managedSecret: data.IManagedSecret;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_CreateManagedSecret extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_CreateManagedSecret
|
||||||
|
> {
|
||||||
|
method: 'createManagedSecret';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
key: string;
|
||||||
|
value: string;
|
||||||
|
description?: string;
|
||||||
|
targets: data.IManagedSecretTarget[];
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
managedSecret: data.IManagedSecret;
|
||||||
|
pushResults: data.IManagedSecretTargetStatus[];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_UpdateManagedSecret extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_UpdateManagedSecret
|
||||||
|
> {
|
||||||
|
method: 'updateManagedSecret';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
managedSecretId: string;
|
||||||
|
value?: string;
|
||||||
|
description?: string;
|
||||||
|
targets?: data.IManagedSecretTarget[];
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
managedSecret: data.IManagedSecret;
|
||||||
|
pushResults: data.IManagedSecretTargetStatus[];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_DeleteManagedSecret extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_DeleteManagedSecret
|
||||||
|
> {
|
||||||
|
method: 'deleteManagedSecret';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
managedSecretId: string;
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
ok: boolean;
|
||||||
|
deleteResults: data.IManagedSecretTargetStatus[];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_PushManagedSecret extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_PushManagedSecret
|
||||||
|
> {
|
||||||
|
method: 'pushManagedSecret';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
managedSecretId: string;
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
managedSecret: data.IManagedSecret;
|
||||||
|
pushResults: data.IManagedSecretTargetStatus[];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_PushAllManagedSecrets extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_PushAllManagedSecrets
|
||||||
|
> {
|
||||||
|
method: 'pushAllManagedSecrets';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
results: Array<{
|
||||||
|
managedSecretId: string;
|
||||||
|
key: string;
|
||||||
|
pushResults: data.IManagedSecretTargetStatus[];
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -3,6 +3,6 @@
|
|||||||
*/
|
*/
|
||||||
export const commitinfo = {
|
export const commitinfo = {
|
||||||
name: '@serve.zone/gitops',
|
name: '@serve.zone/gitops',
|
||||||
version: '2.8.0',
|
version: '2.11.1',
|
||||||
description: 'GitOps management app for Gitea and GitLab - manage secrets, browse projects, view CI pipelines, and stream build logs'
|
description: 'GitOps management app for Gitea and GitLab - manage secrets, browse projects, view CI pipelines, and stream build logs'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -704,6 +704,142 @@ export const setRefreshIntervalAction = uiStatePart.createAction<{ interval: num
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Managed Secrets State
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
export interface IManagedSecretsState {
|
||||||
|
managedSecrets: interfaces.data.IManagedSecret[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const managedSecretsStatePart = await appState.getStatePart<IManagedSecretsState>(
|
||||||
|
'managedSecrets',
|
||||||
|
{ managedSecrets: [] },
|
||||||
|
'soft',
|
||||||
|
);
|
||||||
|
|
||||||
|
export const fetchManagedSecretsAction = managedSecretsStatePart.createAction(
|
||||||
|
async (statePartArg) => {
|
||||||
|
const context = getActionContext();
|
||||||
|
try {
|
||||||
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_GetManagedSecrets
|
||||||
|
>('/typedrequest', 'getManagedSecrets');
|
||||||
|
const response = await typedRequest.fire({ identity: context.identity! });
|
||||||
|
return { managedSecrets: response.managedSecrets };
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to fetch managed secrets:', err);
|
||||||
|
return statePartArg.getState();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export const createManagedSecretAction = managedSecretsStatePart.createAction<{
|
||||||
|
key: string;
|
||||||
|
value: string;
|
||||||
|
description?: string;
|
||||||
|
targets: interfaces.data.IManagedSecretTarget[];
|
||||||
|
}>(async (statePartArg, dataArg) => {
|
||||||
|
const context = getActionContext();
|
||||||
|
try {
|
||||||
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_CreateManagedSecret
|
||||||
|
>('/typedrequest', 'createManagedSecret');
|
||||||
|
await typedRequest.fire({ identity: context.identity!, ...dataArg });
|
||||||
|
// Re-fetch
|
||||||
|
const listReq = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_GetManagedSecrets
|
||||||
|
>('/typedrequest', 'getManagedSecrets');
|
||||||
|
const listResp = await listReq.fire({ identity: context.identity! });
|
||||||
|
return { managedSecrets: listResp.managedSecrets };
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to create managed secret:', err);
|
||||||
|
return statePartArg.getState();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export const updateManagedSecretAction = managedSecretsStatePart.createAction<{
|
||||||
|
managedSecretId: string;
|
||||||
|
value?: string;
|
||||||
|
description?: string;
|
||||||
|
targets?: interfaces.data.IManagedSecretTarget[];
|
||||||
|
}>(async (statePartArg, dataArg) => {
|
||||||
|
const context = getActionContext();
|
||||||
|
try {
|
||||||
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_UpdateManagedSecret
|
||||||
|
>('/typedrequest', 'updateManagedSecret');
|
||||||
|
await typedRequest.fire({ identity: context.identity!, ...dataArg });
|
||||||
|
const listReq = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_GetManagedSecrets
|
||||||
|
>('/typedrequest', 'getManagedSecrets');
|
||||||
|
const listResp = await listReq.fire({ identity: context.identity! });
|
||||||
|
return { managedSecrets: listResp.managedSecrets };
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to update managed secret:', err);
|
||||||
|
return statePartArg.getState();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export const deleteManagedSecretAction = managedSecretsStatePart.createAction<{
|
||||||
|
managedSecretId: string;
|
||||||
|
}>(async (statePartArg, dataArg) => {
|
||||||
|
const context = getActionContext();
|
||||||
|
try {
|
||||||
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_DeleteManagedSecret
|
||||||
|
>('/typedrequest', 'deleteManagedSecret');
|
||||||
|
await typedRequest.fire({ identity: context.identity!, ...dataArg });
|
||||||
|
const state = statePartArg.getState();
|
||||||
|
return {
|
||||||
|
managedSecrets: state.managedSecrets.filter((s) => s.id !== dataArg.managedSecretId),
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to delete managed secret:', err);
|
||||||
|
return statePartArg.getState();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pushManagedSecretAction = managedSecretsStatePart.createAction<{
|
||||||
|
managedSecretId: string;
|
||||||
|
}>(async (statePartArg, dataArg) => {
|
||||||
|
const context = getActionContext();
|
||||||
|
try {
|
||||||
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_PushManagedSecret
|
||||||
|
>('/typedrequest', 'pushManagedSecret');
|
||||||
|
await typedRequest.fire({ identity: context.identity!, ...dataArg });
|
||||||
|
const listReq = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_GetManagedSecrets
|
||||||
|
>('/typedrequest', 'getManagedSecrets');
|
||||||
|
const listResp = await listReq.fire({ identity: context.identity! });
|
||||||
|
return { managedSecrets: listResp.managedSecrets };
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to push managed secret:', err);
|
||||||
|
return statePartArg.getState();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export const pushAllManagedSecretsAction = managedSecretsStatePart.createAction(
|
||||||
|
async (statePartArg) => {
|
||||||
|
const context = getActionContext();
|
||||||
|
try {
|
||||||
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_PushAllManagedSecrets
|
||||||
|
>('/typedrequest', 'pushAllManagedSecrets');
|
||||||
|
await typedRequest.fire({ identity: context.identity! });
|
||||||
|
const listReq = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_GetManagedSecrets
|
||||||
|
>('/typedrequest', 'getManagedSecrets');
|
||||||
|
const listResp = await listReq.fire({ identity: context.identity! });
|
||||||
|
return { managedSecrets: listResp.managedSecrets };
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to push all managed secrets:', err);
|
||||||
|
return statePartArg.getState();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// Sync State
|
// Sync State
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -899,11 +1035,12 @@ export async function initSyncLogSocket(): Promise<void> {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
await plugins.typedsocket.TypedSocket.createClient(
|
const typedsocketClient = await plugins.typedsocket.TypedSocket.createClient(
|
||||||
typedrouter,
|
typedrouter,
|
||||||
plugins.typedsocket.TypedSocket.useWindowLocationOriginUrl(),
|
plugins.typedsocket.TypedSocket.useWindowLocationOriginUrl(),
|
||||||
{ autoReconnect: true },
|
{ autoReconnect: true },
|
||||||
);
|
);
|
||||||
|
await typedsocketClient.setTag('syncLogClient', {});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to init sync log TypedSocket client:', err);
|
console.error('Failed to init sync log TypedSocket client:', err);
|
||||||
syncLogSocketInitialized = false;
|
syncLogSocketInitialized = false;
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ export class GitopsDashboard extends DeesElement {
|
|||||||
{ name: 'Projects', iconName: 'lucide:folderGit2', element: (async () => (await import('./views/projects/index.js')).GitopsViewProjects)() },
|
{ name: 'Projects', iconName: 'lucide:folderGit2', element: (async () => (await import('./views/projects/index.js')).GitopsViewProjects)() },
|
||||||
{ name: 'Groups', iconName: 'lucide:users', element: (async () => (await import('./views/groups/index.js')).GitopsViewGroups)() },
|
{ name: 'Groups', iconName: 'lucide:users', element: (async () => (await import('./views/groups/index.js')).GitopsViewGroups)() },
|
||||||
{ name: 'Secrets', iconName: 'lucide:key', element: (async () => (await import('./views/secrets/index.js')).GitopsViewSecrets)() },
|
{ name: 'Secrets', iconName: 'lucide:key', element: (async () => (await import('./views/secrets/index.js')).GitopsViewSecrets)() },
|
||||||
|
{ name: 'Managed Secrets', iconName: 'lucide:keyRound', element: (async () => (await import('./views/managedsecrets/index.js')).GitopsViewManagedSecrets)() },
|
||||||
{ name: 'Pipelines', iconName: 'lucide:play', element: (async () => (await import('./views/pipelines/index.js')).GitopsViewPipelines)() },
|
{ name: 'Pipelines', iconName: 'lucide:play', element: (async () => (await import('./views/pipelines/index.js')).GitopsViewPipelines)() },
|
||||||
{ name: 'Build Log', iconName: 'lucide:scrollText', element: (async () => (await import('./views/buildlog/index.js')).GitopsViewBuildlog)() },
|
{ name: 'Build Log', iconName: 'lucide:scrollText', element: (async () => (await import('./views/buildlog/index.js')).GitopsViewBuildlog)() },
|
||||||
{ name: 'Actions', iconName: 'lucide:zap', element: (async () => (await import('./views/actions/index.js')).GitopsViewActions)() },
|
{ name: 'Actions', iconName: 'lucide:zap', element: (async () => (await import('./views/actions/index.js')).GitopsViewActions)() },
|
||||||
|
|||||||
@@ -7,3 +7,4 @@ import './views/secrets/index.js';
|
|||||||
import './views/pipelines/index.js';
|
import './views/pipelines/index.js';
|
||||||
import './views/buildlog/index.js';
|
import './views/buildlog/index.js';
|
||||||
import './views/actions/index.js';
|
import './views/actions/index.js';
|
||||||
|
import './views/managedsecrets/index.js';
|
||||||
|
|||||||
502
ts_web/elements/views/managedsecrets/index.ts
Normal file
502
ts_web/elements/views/managedsecrets/index.ts
Normal file
@@ -0,0 +1,502 @@
|
|||||||
|
import * as plugins from '../../../plugins.js';
|
||||||
|
import * as appstate from '../../../appstate.js';
|
||||||
|
import { viewHostCss } from '../../shared/index.js';
|
||||||
|
import {
|
||||||
|
DeesElement,
|
||||||
|
customElement,
|
||||||
|
html,
|
||||||
|
state,
|
||||||
|
css,
|
||||||
|
cssManager,
|
||||||
|
type TemplateResult,
|
||||||
|
} from '@design.estate/dees-element';
|
||||||
|
|
||||||
|
@customElement('gitops-view-managedsecrets')
|
||||||
|
export class GitopsViewManagedSecrets extends DeesElement {
|
||||||
|
@state()
|
||||||
|
accessor managedSecretsState: appstate.IManagedSecretsState = { managedSecrets: [] };
|
||||||
|
|
||||||
|
@state()
|
||||||
|
accessor connectionsState: appstate.IConnectionsState = {
|
||||||
|
connections: [],
|
||||||
|
activeConnectionId: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
@state()
|
||||||
|
accessor dataState: appstate.IDataState = {
|
||||||
|
projects: [],
|
||||||
|
groups: [],
|
||||||
|
secrets: [],
|
||||||
|
pipelines: [],
|
||||||
|
pipelineJobs: [],
|
||||||
|
currentJobLog: '',
|
||||||
|
};
|
||||||
|
|
||||||
|
private _autoRefreshHandler: () => void;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super();
|
||||||
|
const msSub = appstate.managedSecretsStatePart
|
||||||
|
.select((s) => s)
|
||||||
|
.subscribe((s) => { this.managedSecretsState = s; });
|
||||||
|
this.rxSubscriptions.push(msSub);
|
||||||
|
|
||||||
|
const connSub = appstate.connectionsStatePart
|
||||||
|
.select((s) => s)
|
||||||
|
.subscribe((s) => { this.connectionsState = s; });
|
||||||
|
this.rxSubscriptions.push(connSub);
|
||||||
|
|
||||||
|
const dataSub = appstate.dataStatePart
|
||||||
|
.select((s) => s)
|
||||||
|
.subscribe((s) => { this.dataState = s; });
|
||||||
|
this.rxSubscriptions.push(dataSub);
|
||||||
|
|
||||||
|
this._autoRefreshHandler = () => this.refresh();
|
||||||
|
document.addEventListener('gitops-auto-refresh', this._autoRefreshHandler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override disconnectedCallback() {
|
||||||
|
super.disconnectedCallback();
|
||||||
|
document.removeEventListener('gitops-auto-refresh', this._autoRefreshHandler);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static styles = [
|
||||||
|
cssManager.defaultStyles,
|
||||||
|
viewHostCss,
|
||||||
|
css`
|
||||||
|
.target-list {
|
||||||
|
margin: 8px 0;
|
||||||
|
}
|
||||||
|
.target-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 6px 10px;
|
||||||
|
margin: 4px 0;
|
||||||
|
background: rgba(255, 255, 255, 0.05);
|
||||||
|
border-radius: 4px;
|
||||||
|
color: #ccc;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.target-item .remove-btn {
|
||||||
|
cursor: pointer;
|
||||||
|
color: #e74c3c;
|
||||||
|
font-size: 16px;
|
||||||
|
padding: 0 4px;
|
||||||
|
}
|
||||||
|
.status-ok { color: #2ecc71; }
|
||||||
|
.status-error { color: #e74c3c; }
|
||||||
|
.status-pending { color: #f39c12; }
|
||||||
|
`,
|
||||||
|
];
|
||||||
|
|
||||||
|
public render(): TemplateResult {
|
||||||
|
return html`
|
||||||
|
<div class="view-title">Managed Secrets</div>
|
||||||
|
<div class="view-description">Centrally managed secrets pushed as GITOPS_{key} to configured targets</div>
|
||||||
|
<div class="toolbar">
|
||||||
|
<dees-button @click=${() => this.addManagedSecret()}>Add Managed Secret</dees-button>
|
||||||
|
<dees-button @click=${() => this.pushAll()}>Push All</dees-button>
|
||||||
|
<dees-button @click=${() => this.refresh()}>Refresh</dees-button>
|
||||||
|
</div>
|
||||||
|
<dees-table
|
||||||
|
.heading1=${'Managed Secrets'}
|
||||||
|
.heading2=${'Define once, push to many targets'}
|
||||||
|
.data=${this.managedSecretsState.managedSecrets}
|
||||||
|
.displayFunction=${(item: any) => ({
|
||||||
|
Key: item.key,
|
||||||
|
'On Target': 'GITOPS_' + item.key,
|
||||||
|
Description: item.description || '-',
|
||||||
|
Targets: String(item.targets.length),
|
||||||
|
Status: this.summarizeStatus(item.targetStatuses),
|
||||||
|
'Last Pushed': item.lastPushedAt ? new Date(item.lastPushedAt).toLocaleString() : 'Never',
|
||||||
|
})}
|
||||||
|
.dataActions=${[
|
||||||
|
{
|
||||||
|
name: 'Edit',
|
||||||
|
iconName: 'lucide:edit',
|
||||||
|
type: ['inRow', 'contextmenu'],
|
||||||
|
actionFunc: async ({ item }: any) => { await this.editManagedSecret(item); },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Push',
|
||||||
|
iconName: 'lucide:upload',
|
||||||
|
type: ['inRow', 'contextmenu'],
|
||||||
|
actionFunc: async ({ item }: any) => { await this.pushOne(item); },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'View Targets',
|
||||||
|
iconName: 'lucide:list',
|
||||||
|
type: ['inRow', 'contextmenu'],
|
||||||
|
actionFunc: async ({ item }: any) => { await this.viewTargets(item); },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Delete',
|
||||||
|
iconName: 'lucide:trash2',
|
||||||
|
type: ['inRow', 'contextmenu'],
|
||||||
|
actionFunc: async ({ item }: any) => { await this.deleteManagedSecret(item); },
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
></dees-table>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async firstUpdated() {
|
||||||
|
await appstate.connectionsStatePart.dispatchAction(appstate.fetchConnectionsAction, null);
|
||||||
|
await appstate.managedSecretsStatePart.dispatchAction(appstate.fetchManagedSecretsAction, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private summarizeStatus(statuses: any[]): string {
|
||||||
|
if (!statuses || statuses.length === 0) return 'Not pushed';
|
||||||
|
const ok = statuses.filter((s: any) => s.status === 'success').length;
|
||||||
|
const err = statuses.filter((s: any) => s.status === 'error').length;
|
||||||
|
if (err === 0) return `All OK (${ok})`;
|
||||||
|
return `${ok} OK / ${err} Failed`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async refresh() {
|
||||||
|
await appstate.managedSecretsStatePart.dispatchAction(appstate.fetchManagedSecretsAction, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async pushAll() {
|
||||||
|
await appstate.managedSecretsStatePart.dispatchAction(appstate.pushAllManagedSecretsAction, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async pushOne(item: any) {
|
||||||
|
await appstate.managedSecretsStatePart.dispatchAction(appstate.pushManagedSecretAction, {
|
||||||
|
managedSecretId: item.id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async deleteManagedSecret(item: any) {
|
||||||
|
await plugins.deesCatalog.DeesModal.createAndShow({
|
||||||
|
heading: 'Delete Managed Secret',
|
||||||
|
content: html`<p style="color: #fff;">Are you sure you want to delete managed secret "${item.key}"?<br>This will also remove GITOPS_${item.key} from all ${item.targets.length} target(s).</p>`,
|
||||||
|
menuOptions: [
|
||||||
|
{ name: 'Cancel', action: async (modal: any) => { modal.destroy(); } },
|
||||||
|
{
|
||||||
|
name: 'Delete',
|
||||||
|
action: async (modal: any) => {
|
||||||
|
await appstate.managedSecretsStatePart.dispatchAction(appstate.deleteManagedSecretAction, {
|
||||||
|
managedSecretId: item.id,
|
||||||
|
});
|
||||||
|
modal.destroy();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async viewTargets(item: any) {
|
||||||
|
const targetRows = (item.targetStatuses && item.targetStatuses.length > 0)
|
||||||
|
? item.targetStatuses
|
||||||
|
: item.targets.map((t: any) => ({ ...t, status: 'pending' }));
|
||||||
|
|
||||||
|
const statusIcon = (status: string) => {
|
||||||
|
if (status === 'success') return html`<span class="status-ok">OK</span>`;
|
||||||
|
if (status === 'error') return html`<span class="status-error">Error</span>`;
|
||||||
|
return html`<span class="status-pending">Pending</span>`;
|
||||||
|
};
|
||||||
|
|
||||||
|
await plugins.deesCatalog.DeesModal.createAndShow({
|
||||||
|
heading: `Targets for ${item.key}`,
|
||||||
|
content: html`
|
||||||
|
<div style="color: #ccc; min-width: 400px;">
|
||||||
|
${targetRows.map((t: any) => html`
|
||||||
|
<div style="display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid rgba(255,255,255,0.1);">
|
||||||
|
<div>
|
||||||
|
<div style="font-weight: bold;">${t.scopeName || t.scopeId}</div>
|
||||||
|
<div style="font-size: 12px; opacity: 0.7;">${t.scope} on ${this.getConnectionName(t.connectionId)}</div>
|
||||||
|
${t.error ? html`<div style="font-size: 12px; color: #e74c3c; margin-top: 4px;">${t.error}</div>` : ''}
|
||||||
|
</div>
|
||||||
|
<div>${statusIcon(t.status)}</div>
|
||||||
|
</div>
|
||||||
|
`)}
|
||||||
|
${targetRows.length === 0 ? html`<p>No targets configured.</p>` : ''}
|
||||||
|
</div>
|
||||||
|
`,
|
||||||
|
menuOptions: [
|
||||||
|
{ name: 'Close', action: async (modal: any) => { modal.destroy(); } },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private getConnectionName(connectionId: string): string {
|
||||||
|
const conn = this.connectionsState.connections.find((c) => c.id === connectionId);
|
||||||
|
return conn ? conn.name : connectionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async addManagedSecret() {
|
||||||
|
// Load entities for all connections
|
||||||
|
const connections = this.connectionsState.connections;
|
||||||
|
let targets: any[] = [];
|
||||||
|
let selectedConnId = connections.length > 0 ? connections[0].id : '';
|
||||||
|
let selectedScope: 'project' | 'group' = 'project';
|
||||||
|
|
||||||
|
// Pre-load entities for first connection
|
||||||
|
if (selectedConnId) {
|
||||||
|
await appstate.dataStatePart.dispatchAction(appstate.fetchProjectsAction, {
|
||||||
|
connectionId: selectedConnId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const buildTargetListHtml = () => {
|
||||||
|
if (targets.length === 0) return html`<p style="color: #888; font-size: 13px;">No targets added yet.</p>`;
|
||||||
|
return html`${targets.map((t, i) => html`
|
||||||
|
<div class="target-item">
|
||||||
|
<span>${t.scopeName} (${t.scope}) on ${this.getConnectionName(t.connectionId)}</span>
|
||||||
|
<span class="remove-btn" @click=${() => { targets.splice(i, 1); this.requestUpdate(); }}>x</span>
|
||||||
|
</div>
|
||||||
|
`)}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
await plugins.deesCatalog.DeesModal.createAndShow({
|
||||||
|
heading: 'Add Managed Secret',
|
||||||
|
content: html`
|
||||||
|
<style>
|
||||||
|
.form-row { margin-bottom: 16px; }
|
||||||
|
.target-section { margin-top: 16px; padding-top: 16px; border-top: 1px solid rgba(255,255,255,0.1); }
|
||||||
|
.add-target-row { display: flex; gap: 8px; align-items: flex-end; flex-wrap: wrap; }
|
||||||
|
</style>
|
||||||
|
<div class="form-row">
|
||||||
|
<dees-input-text .label=${'Key'} .key=${'key'} .description=${'Will be stored as GITOPS_{key} on targets'}></dees-input-text>
|
||||||
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<dees-input-text .label=${'Value'} .key=${'value'} type="password"></dees-input-text>
|
||||||
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<dees-input-text .label=${'Description'} .key=${'description'}></dees-input-text>
|
||||||
|
</div>
|
||||||
|
<div class="target-section">
|
||||||
|
<div style="color: #fff; font-weight: bold; margin-bottom: 8px;">Targets</div>
|
||||||
|
<div class="add-target-row">
|
||||||
|
<dees-input-dropdown
|
||||||
|
.label=${'Connection'}
|
||||||
|
.key=${'targetConn'}
|
||||||
|
.options=${connections.map((c) => ({ option: c.name, key: c.id }))}
|
||||||
|
.selectedOption=${connections.length > 0 ? { option: connections[0].name, key: connections[0].id } : undefined}
|
||||||
|
@selectedOption=${async (e: CustomEvent) => {
|
||||||
|
selectedConnId = e.detail.key;
|
||||||
|
if (selectedScope === 'project') {
|
||||||
|
await appstate.dataStatePart.dispatchAction(appstate.fetchProjectsAction, { connectionId: selectedConnId });
|
||||||
|
} else {
|
||||||
|
await appstate.dataStatePart.dispatchAction(appstate.fetchGroupsAction, { connectionId: selectedConnId });
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
></dees-input-dropdown>
|
||||||
|
<dees-input-dropdown
|
||||||
|
.label=${'Scope'}
|
||||||
|
.key=${'targetScope'}
|
||||||
|
.options=${[{ option: 'Project', key: 'project' }, { option: 'Group', key: 'group' }]}
|
||||||
|
.selectedOption=${{ option: 'Project', key: 'project' }}
|
||||||
|
@selectedOption=${async (e: CustomEvent) => {
|
||||||
|
selectedScope = e.detail.key as 'project' | 'group';
|
||||||
|
if (selectedScope === 'project') {
|
||||||
|
await appstate.dataStatePart.dispatchAction(appstate.fetchProjectsAction, { connectionId: selectedConnId });
|
||||||
|
} else {
|
||||||
|
await appstate.dataStatePart.dispatchAction(appstate.fetchGroupsAction, { connectionId: selectedConnId });
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
></dees-input-dropdown>
|
||||||
|
<dees-input-dropdown
|
||||||
|
.label=${'Entity'}
|
||||||
|
.key=${'targetEntity'}
|
||||||
|
.options=${(() => {
|
||||||
|
const data = appstate.dataStatePart.getState();
|
||||||
|
const items = selectedScope === 'project' ? data.projects : data.groups;
|
||||||
|
return items.map((item: any) => ({ option: item.fullPath || item.name, key: item.id }));
|
||||||
|
})()}
|
||||||
|
></dees-input-dropdown>
|
||||||
|
<dees-button @click=${() => {
|
||||||
|
const data = appstate.dataStatePart.getState();
|
||||||
|
const items = selectedScope === 'project' ? data.projects : data.groups;
|
||||||
|
// Find entity dropdown value
|
||||||
|
const modal = document.querySelector('dees-modal');
|
||||||
|
if (!modal) return;
|
||||||
|
const entityDropdowns = modal.shadowRoot?.querySelectorAll('dees-input-dropdown');
|
||||||
|
let entityKey = '';
|
||||||
|
let entityName = '';
|
||||||
|
if (entityDropdowns) {
|
||||||
|
for (const dd of entityDropdowns) {
|
||||||
|
if ((dd as any).key === 'targetEntity') {
|
||||||
|
const sel = (dd as any).selectedOption;
|
||||||
|
if (sel) {
|
||||||
|
entityKey = sel.key;
|
||||||
|
entityName = sel.option;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!entityKey) return;
|
||||||
|
// Avoid duplicates
|
||||||
|
const exists = targets.some(
|
||||||
|
(t) => t.connectionId === selectedConnId && t.scope === selectedScope && t.scopeId === entityKey,
|
||||||
|
);
|
||||||
|
if (exists) return;
|
||||||
|
targets.push({
|
||||||
|
connectionId: selectedConnId,
|
||||||
|
scope: selectedScope,
|
||||||
|
scopeId: entityKey,
|
||||||
|
scopeName: entityName,
|
||||||
|
});
|
||||||
|
}}>Add Target</dees-button>
|
||||||
|
</div>
|
||||||
|
<div class="target-list" id="targetList">
|
||||||
|
${buildTargetListHtml()}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`,
|
||||||
|
menuOptions: [
|
||||||
|
{ name: 'Cancel', action: async (modal: any) => { modal.destroy(); } },
|
||||||
|
{
|
||||||
|
name: 'Create',
|
||||||
|
action: async (modal: any) => {
|
||||||
|
const inputs = modal.shadowRoot.querySelectorAll('dees-input-text');
|
||||||
|
const data: any = {};
|
||||||
|
for (const input of inputs) { data[input.key] = input.value || ''; }
|
||||||
|
if (!data.key) return;
|
||||||
|
await appstate.managedSecretsStatePart.dispatchAction(appstate.createManagedSecretAction, {
|
||||||
|
key: data.key,
|
||||||
|
value: data.value,
|
||||||
|
description: data.description || undefined,
|
||||||
|
targets,
|
||||||
|
});
|
||||||
|
modal.destroy();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async editManagedSecret(item: any) {
|
||||||
|
const connections = this.connectionsState.connections;
|
||||||
|
let targets = [...item.targets];
|
||||||
|
let selectedConnId = connections.length > 0 ? connections[0].id : '';
|
||||||
|
let selectedScope: 'project' | 'group' = 'project';
|
||||||
|
|
||||||
|
if (selectedConnId) {
|
||||||
|
await appstate.dataStatePart.dispatchAction(appstate.fetchProjectsAction, {
|
||||||
|
connectionId: selectedConnId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await plugins.deesCatalog.DeesModal.createAndShow({
|
||||||
|
heading: `Edit: ${item.key}`,
|
||||||
|
content: html`
|
||||||
|
<style>
|
||||||
|
.form-row { margin-bottom: 16px; }
|
||||||
|
.target-section { margin-top: 16px; padding-top: 16px; border-top: 1px solid rgba(255,255,255,0.1); }
|
||||||
|
.add-target-row { display: flex; gap: 8px; align-items: flex-end; flex-wrap: wrap; }
|
||||||
|
</style>
|
||||||
|
<div class="form-row">
|
||||||
|
<dees-input-text .label=${'Value (leave empty to keep current)'} .key=${'value'} type="password"></dees-input-text>
|
||||||
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<dees-input-text .label=${'Description'} .key=${'description'} .value=${item.description || ''}></dees-input-text>
|
||||||
|
</div>
|
||||||
|
<div class="target-section">
|
||||||
|
<div style="color: #fff; font-weight: bold; margin-bottom: 8px;">Targets</div>
|
||||||
|
<div class="add-target-row">
|
||||||
|
<dees-input-dropdown
|
||||||
|
.label=${'Connection'}
|
||||||
|
.key=${'targetConn'}
|
||||||
|
.options=${connections.map((c) => ({ option: c.name, key: c.id }))}
|
||||||
|
.selectedOption=${connections.length > 0 ? { option: connections[0].name, key: connections[0].id } : undefined}
|
||||||
|
@selectedOption=${async (e: CustomEvent) => {
|
||||||
|
selectedConnId = e.detail.key;
|
||||||
|
if (selectedScope === 'project') {
|
||||||
|
await appstate.dataStatePart.dispatchAction(appstate.fetchProjectsAction, { connectionId: selectedConnId });
|
||||||
|
} else {
|
||||||
|
await appstate.dataStatePart.dispatchAction(appstate.fetchGroupsAction, { connectionId: selectedConnId });
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
></dees-input-dropdown>
|
||||||
|
<dees-input-dropdown
|
||||||
|
.label=${'Scope'}
|
||||||
|
.key=${'targetScope'}
|
||||||
|
.options=${[{ option: 'Project', key: 'project' }, { option: 'Group', key: 'group' }]}
|
||||||
|
.selectedOption=${{ option: 'Project', key: 'project' }}
|
||||||
|
@selectedOption=${async (e: CustomEvent) => {
|
||||||
|
selectedScope = e.detail.key as 'project' | 'group';
|
||||||
|
if (selectedScope === 'project') {
|
||||||
|
await appstate.dataStatePart.dispatchAction(appstate.fetchProjectsAction, { connectionId: selectedConnId });
|
||||||
|
} else {
|
||||||
|
await appstate.dataStatePart.dispatchAction(appstate.fetchGroupsAction, { connectionId: selectedConnId });
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
></dees-input-dropdown>
|
||||||
|
<dees-input-dropdown
|
||||||
|
.label=${'Entity'}
|
||||||
|
.key=${'targetEntity'}
|
||||||
|
.options=${(() => {
|
||||||
|
const data = appstate.dataStatePart.getState();
|
||||||
|
const items = selectedScope === 'project' ? data.projects : data.groups;
|
||||||
|
return items.map((item: any) => ({ option: item.fullPath || item.name, key: item.id }));
|
||||||
|
})()}
|
||||||
|
></dees-input-dropdown>
|
||||||
|
<dees-button @click=${() => {
|
||||||
|
const modal = document.querySelector('dees-modal');
|
||||||
|
if (!modal) return;
|
||||||
|
const entityDropdowns = modal.shadowRoot?.querySelectorAll('dees-input-dropdown');
|
||||||
|
let entityKey = '';
|
||||||
|
let entityName = '';
|
||||||
|
if (entityDropdowns) {
|
||||||
|
for (const dd of entityDropdowns) {
|
||||||
|
if ((dd as any).key === 'targetEntity') {
|
||||||
|
const sel = (dd as any).selectedOption;
|
||||||
|
if (sel) {
|
||||||
|
entityKey = sel.key;
|
||||||
|
entityName = sel.option;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!entityKey) return;
|
||||||
|
const exists = targets.some(
|
||||||
|
(t: any) => t.connectionId === selectedConnId && t.scope === selectedScope && t.scopeId === entityKey,
|
||||||
|
);
|
||||||
|
if (exists) return;
|
||||||
|
targets.push({
|
||||||
|
connectionId: selectedConnId,
|
||||||
|
scope: selectedScope,
|
||||||
|
scopeId: entityKey,
|
||||||
|
scopeName: entityName,
|
||||||
|
});
|
||||||
|
}}>Add Target</dees-button>
|
||||||
|
</div>
|
||||||
|
<div class="target-list">
|
||||||
|
${targets.length === 0
|
||||||
|
? html`<p style="color: #888; font-size: 13px;">No targets.</p>`
|
||||||
|
: targets.map((t: any, i: number) => html`
|
||||||
|
<div class="target-item">
|
||||||
|
<span>${t.scopeName} (${t.scope}) on ${this.getConnectionName(t.connectionId)}</span>
|
||||||
|
<span class="remove-btn" @click=${() => { targets.splice(i, 1); }}>x</span>
|
||||||
|
</div>
|
||||||
|
`)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`,
|
||||||
|
menuOptions: [
|
||||||
|
{ name: 'Cancel', action: async (modal: any) => { modal.destroy(); } },
|
||||||
|
{
|
||||||
|
name: 'Update',
|
||||||
|
action: async (modal: any) => {
|
||||||
|
const inputs = modal.shadowRoot.querySelectorAll('dees-input-text');
|
||||||
|
const data: any = {};
|
||||||
|
for (const input of inputs) { data[input.key] = input.value || ''; }
|
||||||
|
const updatePayload: any = {
|
||||||
|
managedSecretId: item.id,
|
||||||
|
targets,
|
||||||
|
description: data.description || undefined,
|
||||||
|
};
|
||||||
|
if (data.value) {
|
||||||
|
updatePayload.value = data.value;
|
||||||
|
}
|
||||||
|
await appstate.managedSecretsStatePart.dispatchAction(appstate.updateManagedSecretAction, updatePayload);
|
||||||
|
modal.destroy();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user