Plesk-Connector (XML-API): Abgleich, Kundenübernahme, Bereitstellung, Panel-Login
- Neues Paket @kc/connector-plesk: ein Plesk-Abonnement = ein Hosting-Konto, Kontaktdaten vom Plesk-Kunden; Service-Pläne als Produktvorlagen - Abgleich mit Besitzer, Plan, Limits, Nutzung und Ablauf; Kundenübernahme - Bereitstellung: Kunde (Login kc+Vertragsnummer, Vermerk) und Abonnement kc<Nr>.<Domain> auf dem Plan, sichere Wiederholung ohne Doppelanlage; Passwörter werden nie gespeichert - Sperren/Entsperren, Planwechsel, Löschen (nie automatisch wiederholt), Passwort des Besitzers, Panel-Login als Einmal-Sitzung - Unterobjekte (Domains, Postfächer, Datenbanken, FTP) nur lesend - Eigener kleiner XML-Baustein: Werte maskiert, DOCTYPE/ENTITY abgelehnt - 17 Tests gegen einen Plesk-Nachbau (test/fake.ts); NICHT gegen eine echte Instanz geprüft – Annahmen in docs/connector-plesk.md - Verbindungen: Einrichtungshinweis für Plesk; Domain-Übernahme-Text neutral Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
672aa5ad89
commit
2aa793ed05
13 changed files with 758 additions and 3 deletions
|
|
@ -31,6 +31,7 @@ export default function Connectors() {
|
|||
{msg && <Alert kind={msg.k}>{msg.t}</Alert>}
|
||||
{open && type && <form className="card" onSubmit={create}><h2>Neue Verbindung</h2>
|
||||
{sel === 'keyhelp' && <Alert kind="info"><strong>KeyHelp einrichten:</strong> Im KeyHelp-Adminbereich unter <em>Konfiguration → API</em> die API aktivieren und einen Schlüssel anlegen. Den Schlüssel <strong>auf die IP-Adresse dieses Servers beschränken</strong> (er hat Administratorrechte) und hier eintragen. Die KeyHelp-Version wird automatisch erkannt. Bei einem selbstsignierten Zertifikat den SHA-256-Fingerabdruck angeben (sicherer als die Prüfung abzuschalten). Der Abgleich arbeitet zunächst nur lesend.</Alert>}
|
||||
{sel === 'plesk' && <Alert kind="info"><strong>Plesk einrichten:</strong> Auf dem Plesk-Server als root einen Secret Key erzeugen: <code>plesk bin secret_key -c -ip-address <IP dieses Servers> -description Kundencenter</code>. Der Schlüssel ist <strong>an diese IP gebunden</strong> und hat Administratorrechte. Adresse mit Port angeben (meist <code>:8443</code>); bei selbstsigniertem Zertifikat den Fingerabdruck eintragen. Für die Bereitstellung neuer Konten zusätzlich die gemeinsame IP-Adresse und eine Domain für neue Abonnements angeben. Abgleich, Kundenübernahme und Panel-Login funktionieren ohne diese beiden Angaben.</Alert>}
|
||||
<div className="cols"><Field id="type" label="Typ"><select id="type" value={sel} onChange={(e) => setSel(e.target.value)}>{types.map((t) => <option key={t.key} value={t.key}>{t.name}</option>)}</select></Field>
|
||||
<Field id="name" label="Name"><input id="name" name="name" required /></Field></div>
|
||||
<ConfigFields fields={type.fields} prefix="f-" />
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ export function DomainRecords({ orgId }: { orgId?: string }) {
|
|||
{err && <Alert kind="err">{err}</Alert>}{ok && <Alert kind="ok">{ok}</Alert>}
|
||||
{w && <div className="card"><div className="cols">
|
||||
<form onSubmit={add}><Field id={`nd${orgId ?? ''}`} label="Domain manuell erfassen"><input id={`nd${orgId ?? ''}`} name="domain" placeholder="beispiel.de" required autoComplete="off" /></Field><button className="btn primary" type="submit">Erfassen</button></form>
|
||||
<form onSubmit={fromRes}><Field id={`nr${orgId ?? ''}`} label="Domains eines Hosting-Kontos übernehmen" hint="Liest die Domains aus KeyHelp (ohne Subdomains)."><select id={`nr${orgId ?? ''}`} name="res" defaultValue=""><option value="">Konto wählen …</option>{res.map((r) => <option key={r.id} value={r.id}>{r.name}</option>)}</select></Field><button className="btn" type="submit">Übernehmen</button></form></div></div>}
|
||||
<form onSubmit={fromRes}><Field id={`nr${orgId ?? ''}`} label="Domains eines Hosting-Kontos übernehmen" hint="Liest die Domains aus dem Hosting-Panel (ohne Subdomains)."><select id={`nr${orgId ?? ''}`} name="res" defaultValue=""><option value="">Konto wählen …</option>{res.map((r) => <option key={r.id} value={r.id}>{r.name}</option>)}</select></Field><button className="btn" type="submit">Übernehmen</button></form></div></div>}
|
||||
<div className="card">
|
||||
<div className="cols"><Field id={`q${orgId ?? ''}`} label="Suche"><input id={`q${orgId ?? ''}`} type="search" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Domain" /></Field>
|
||||
<Field id={`st${orgId ?? ''}`} label="Status"><select id={`st${orgId ?? ''}`} value={status} onChange={(e) => setStatus(e.target.value)}><option value="">Alle</option>{Object.entries(PROC).map(([k, v]) => <option key={k} value={k}>{v}</option>)}</select></Field></div>
|
||||
|
|
|
|||
45
docs/connector-plesk.md
Normal file
45
docs/connector-plesk.md
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
# Plesk-Connector
|
||||
|
||||
## Umsetzungsstand (05.10.2026)
|
||||
Paket `packages/connector-plesk`, gebaut nach der Plesk-Dokumentation (XML-API, Plesk Obsidian 18) und getestet gegen einen Nachbau (`test/fake.ts`), **nicht gegen eine echte Instanz** (kein Testzugang). Zugang: Plesk-Adresse mit Port (meist `https://host:8443`) + **Secret Key**.
|
||||
|
||||
### Einrichtung
|
||||
1. Auf dem Plesk-Server als root: `plesk bin secret_key -c -ip-address <IP des Kundencenter-Servers> -description Kundencenter` → Schlüssel kopieren. Er ist an diese IP gebunden und hat **Administratorrechte** (verschlüsselt gespeichert, nur Superadmins).
|
||||
2. Kundencenter → Einstellungen → Verbindungen → „Plesk (Webhosting)“: Adresse, Secret Key; bei selbstsigniertem Zertifikat (Port 8443 üblich) den SHA-256-Fingerabdruck.
|
||||
3. Nur für die Bereitstellung neuer Konten: **IP-Adresse für neue Abonnements** (gemeinsame IPv4) und **Domain für neue Abonnements** (z. B. `kunden.example.de`).
|
||||
|
||||
### Abbildung
|
||||
| Kundencenter | Plesk | Bemerkung |
|
||||
|---|---|---|
|
||||
| Hosting-Konto (Ressource) | **Abonnement** (`webspace`) | `externalRef` = Abonnement-ID. Name „domain · login des Besitzers“. |
|
||||
| Kontaktdaten bei der Übernahme | Plesk-**Kunde** (Besitzer des Abonnements) | Je Abonnement ein Eintrag. Hat ein Kunde mehrere Abonnements, das zweite bei der Übernahme **mit dem bereits angelegten Kunden verknüpfen**. Abonnements des Administrators haben keinen Kunden. |
|
||||
| Produktvorlage | **Service-Plan** | `plan:<id>`, fest vorgegeben; Bereitstellungsparameter `planId` (+ `planName` zur Anzeige). |
|
||||
| Zustand | `gen_info/status` | 0 aktiv, 4 Sicherung läuft (aktiv), 16/32/64 gesperrt, 256 abgelaufen. |
|
||||
| Limits / Nutzung | `limits` (Plan), `stat`, `real_size` | Gleiche Schlüssel wie beim KeyHelp-Connector (`disk_space`, `traffic`, `domains`, `subdomains`, `email_accounts`, `databases`, `ftp_users`); -1 = unbegrenzt; `expiration` → „gültig bis“. |
|
||||
|
||||
### Funktionen
|
||||
- **Lesen/Abgleich**: Health mit Plesk-Version, Abonnements mit Besitzer, Plan, Limits, Nutzung (3 Abfragen, unabhängig von der Anzahl).
|
||||
- **Kunden übernehmen**, **Service-Pläne übernehmen** (Produkte → Aus Verbindung übernehmen).
|
||||
- **Bereitstellung** (Bestellung): Kunde mit Login `kc` + Ziffern der Vertragsnummer und Vermerk „Kundencenter K-… V-…“, dann Abonnement `kc<Nr>.<Domain für neue Abonnements>` auf dem Plan. Wiederholung findet Kunde (am Vermerk) und Abonnement (am Besitzer) wieder statt doppelt anzulegen. Passwörter (Kunde, FTP) werden zufällig erzeugt und **nie gespeichert**; Zugang über den Panel-Login.
|
||||
- **Aktionen**: Sperren/Entsperren (Status 16/0), Planwechsel (`switch-subscription`), Löschen des Abonnements (Kunde bleibt; nie automatisch wiederholt), Passwort des Besitzers neu setzen.
|
||||
- **Panel-Login**: Einmal-Sitzung für den Besitzer (`server/create_session` → `rsession_init.php`), nie gespeichert.
|
||||
- **Unterobjekte nur lesend**: Domains (Hauptdomain + weitere Sites), Postfächer, Datenbanken, FTP-Benutzer – jeweils auf das Abonnement gefiltert.
|
||||
|
||||
### Sicherheit
|
||||
- Alle Werte werden in XML maskiert (keine Element-Injektion); Antworten mit DOCTYPE/ENTITY werden abgelehnt (kein XXE).
|
||||
- Der Secret Key steht nur im Header `KEY`, nie im Paket. Lesende Pakete werden bei 5xx/Netzfehler wiederholt, schreibende nie automatisch.
|
||||
|
||||
### Annahmen, die an einer echten Instanz zu prüfen sind
|
||||
1. Secret Key wird von der XML-API im Header `KEY` akzeptiert (alternativ wären `HTTP_AUTH_LOGIN`/`HTTP_AUTH_PASSWD` möglich).
|
||||
2. Leerer `<filter/>` liefert alle Objekte; „nicht gefunden“ kommt als Fehler 1013 je Ergebnis.
|
||||
3. Elementreihenfolge bei `customer/add` (`cname, pname, login, passwd, status, email, description`) und `webspace/add` (`gen_setup, hosting, plan-name`) entspricht dem Schema.
|
||||
4. `webspace/get` mit `<subscriptions/>` liefert die `plan-guid`; `limits` enthält die effektiven Limits inkl. `expiration` (Unix-Zeit, -1 = nie).
|
||||
5. `real_size` und Traffic in **Byte**; `cr_date` als `YYYY-MM-DD`.
|
||||
6. `server/create_session` mit `user_ip` (Base64) und leerem `source_server` liefert eine Sitzung, die vom Browser des Kunden (andere IP) genutzt werden kann; Gültigkeit ~5 Min. angenommen.
|
||||
7. `site/get` mit `parent-id` liefert weitere Domains/Subdomains des Abonnements; `mail/get_info` mit `site-id` die Postfächer.
|
||||
|
||||
### Noch nicht umgesetzt
|
||||
Neue Service-Pläne aus dem Kundencenter anlegen, Ändern von Domains/Postfächern/Datenbanken/FTP, SSL-Zertifikate, DNS, Reseller, mehrere Abonnements je Bestellung.
|
||||
|
||||
### Testen ohne eigenen Server
|
||||
Plesk bietet ein offizielles Docker-Image (`plesk/plesk`) und eine kostenlose Testlizenz (14 Tage). Damit lassen sich die Annahmen oben in kurzer Zeit gegen eine echte Instanz prüfen.
|
||||
|
|
@ -28,7 +28,8 @@ Status: geplant → wird ausgeführt → erfolgreich | wird wiederholt → manue
|
|||
- `lifecycle`: Sperren/Entsperren/Verlängern über die Endpunkte `/licenses/{id}/suspend|unsuspend|extend` (Zielzustand, protokolliert); sonst Rückfall auf `PUT`.
|
||||
- Zustand berücksichtigt `is_active`, `blocked`, `status`, `suspended_at`, `revoked_at` und Ablauf. Bei `utc_timestamps` werden Zeiten als UTC gelesen, sonst als Ortszeit.
|
||||
- Anlage (`lifecycle.create`) mit `product_id` (Plan/Edition des Lizenzsystems); Produkt und Präfix dürfen nie stillschweigend verloren gehen (Antwort wird geprüft).
|
||||
- KeyHelp, Plesk: **offen** (keine Testzugänge; siehe Plane).
|
||||
- `keyhelp` – KeyHelp-Panel, siehe `docs/connector-keyhelp.md`.
|
||||
- `plesk` – Plesk-Panel über die XML-API (Abonnement = Hosting-Konto), siehe `docs/connector-plesk.md`. Ungetestet gegen eine echte Instanz.
|
||||
|
||||
## Zugangsdaten
|
||||
Secrets werden pro Verbindung mit AES-256-GCM verschlüsselt (`connector_instances.secrets_enc`), nur Superadmins dürfen Verbindungen anlegen/ändern, die UI zeigt sie nie wieder an, das Audit-Protokoll maskiert sie.
|
||||
|
|
|
|||
22
packages/connector-plesk/package.json
Normal file
22
packages/connector-plesk/package.json
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"name": "@kc/connector-plesk",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@kc/connector-sdk": "workspace:*",
|
||||
"undici": "^8.11.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^26.6.3",
|
||||
"typescript": "^7.0.2",
|
||||
"vitest": "^5.0.2"
|
||||
}
|
||||
}
|
||||
344
packages/connector-plesk/src/index.ts
Normal file
344
packages/connector-plesk/src/index.ts
Normal file
|
|
@ -0,0 +1,344 @@
|
|||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { Agent, fetch as undiciFetch } from 'undici';
|
||||
import {
|
||||
ConnectorError, CONTRACT_VERSION,
|
||||
type Capability, type CatalogItem, type ChildAccess, type ChildKind, type Connector, type ConnectorContext, type HttpOptions, type ImportableCustomer, type NormalizedChild, type NormalizedResource, type ProvisionContext,
|
||||
} from '@kc/connector-sdk';
|
||||
import { kid, kids, parseXml, path, txt, x, xs, type XNode } from './xml.js';
|
||||
|
||||
/**
|
||||
* Plesk-Connector (Plesk Obsidian 18.x) über die XML-API (`/enterprise/control/agent.php`, Anmeldung mit Secret Key im Header `KEY`).
|
||||
* Abbildung: ein Plesk-**Abonnement** (webspace) = ein Hosting-Konto im Kundencenter; Kontaktdaten kommen vom Plesk-Kunden (Besitzer).
|
||||
* Gebaut nach der Dokumentation und getestet gegen einen Nachbau (test/fake.ts), NICHT gegen eine echte Instanz – Annahmen siehe docs/connector-plesk.md.
|
||||
*/
|
||||
export interface PleskDeps extends HttpOptions { randomPassword?: () => string }
|
||||
|
||||
type ErrCode = ConstructorParameters<typeof ConnectorError>[0];
|
||||
/** Fehlercodes der XML-API → normalisierte Fehler. */
|
||||
const ERRCODE: Record<string, ErrCode> = { '1001': 'AUTH_FAILED', '1003': 'AUTH_FAILED', '1006': 'AUTH_FAILED', '1013': 'NOT_FOUND', '1015': 'NOT_FOUND', '1007': 'CONFLICT', '1014': 'INVALID_INPUT', '1019': 'INVALID_INPUT', '1018': 'INVALID_INPUT', '1023': 'UPSTREAM_ERROR', '1002': 'UNSUPPORTED', '1005': 'UPSTREAM_ERROR' };
|
||||
/** Abonnement-Status: 0 aktiv, 4 Sicherung/Wiederherstellung läuft, 16 vom Admin gesperrt, 32 vom Reseller, 64 vom Kunden, 256 abgelaufen. */
|
||||
const STATUS_LABEL: Record<string, string> = { '0': 'aktiv', '4': 'Sicherung/Wiederherstellung', '16': 'vom Administrator gesperrt', '32': 'vom Reseller gesperrt', '64': 'vom Kunden deaktiviert', '256': 'abgelaufen' };
|
||||
const stateOf = (s: string | null): NormalizedResource['state'] => (s === null ? 'unknown' : s === '0' || s === '4' ? 'active' : s === '256' ? 'expired' : 'suspended');
|
||||
/** Limits/Nutzung: Plesk-Namen → einheitliche Schlüssel (wie beim KeyHelp-Connector), Größen in Byte, -1 = unbegrenzt. */
|
||||
const LIMIT_KEYS: Record<string, string> = { disk_space: 'disk_space', max_traffic: 'traffic', max_site: 'domains', max_subdom: 'subdomains', max_box: 'email_accounts', max_db: 'databases', max_subftp_users: 'ftp_users', max_dom_aliases: 'domain_aliases' };
|
||||
const STAT_KEYS: Record<string, string> = { traffic: 'traffic', subdom: 'subdomains', box: 'email_accounts', db: 'databases', sites: 'domains' };
|
||||
const RES_LABEL: Record<string, string> = { disk_space: 'Speicher', traffic: 'Traffic', domains: 'Domains', subdomains: 'Subdomains', email_accounts: 'Postfächer', databases: 'Datenbanken', ftp_users: 'FTP-Benutzer', domain_aliases: 'Domain-Aliase' };
|
||||
const fmtRes = (k: string, v: number) => (v < 0 ? 'unbegrenzt' : k === 'disk_space' || k === 'traffic' ? `${Math.round((v / 1024 ** 3) * 10) / 10} GB` : String(v));
|
||||
|
||||
const bad = (m: string) => new ConnectorError('INVALID_INPUT', m);
|
||||
const LOGIN_RE = /^[a-z0-9][a-z0-9._-]{0,59}$/;
|
||||
const DOMAIN_RE = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9-]{2,63}$/i;
|
||||
const IPV4_RE = /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;
|
||||
const digits = (s: string | undefined) => (s ?? '').replace(/\D/g, '');
|
||||
/** Stabiler Plesk-Login je Vertrag: "kc" + Ziffern der Vertragsnummer (Wiederholung findet das eigene Konto wieder). */
|
||||
export const loginFor = (c: ProvisionContext | undefined, key: string): string =>
|
||||
c?.contractNumber && digits(c.contractNumber) ? `kc${digits(c.contractNumber)}` : `kc${createHash('sha256').update(key).digest('hex').slice(0, 8)}`;
|
||||
const noteFor = (c: ProvisionContext) => `Kundencenter ${c.customerNumber} ${c.contractNumber}`;
|
||||
/** Starkes Zufallspasswort (wird nie gespeichert; Zugang für Kunden über den Panel-Login aus dem Kundencenter). */
|
||||
const strongPassword = () => `Kc${randomBytes(18).toString('base64url')}!9`;
|
||||
const unixIso = (s: string | null): string | null => { const n = Number(s); return s && Number.isFinite(n) && n > 0 ? new Date(n * 1000).toISOString() : null; };
|
||||
/** Plesk liefert cr_date als "YYYY-MM-DD" (Serverzeit): als Datum (UTC-Mitternacht) gelesen. */
|
||||
const dateIso = (s: string | null): string | null => { if (!s || !/^\d{4}-\d{2}-\d{2}/.test(s)) return null; const d = new Date(`${s.slice(0, 10)}T00:00:00Z`); return Number.isNaN(d.getTime()) ? null : d.toISOString(); };
|
||||
|
||||
interface Webspace { id: string; name: string; status: string | null; ownerId: string | null; createdAt: string | null; realSize: number | null; limits: Record<string, number>; stat: Record<string, number>; planGuid: string | null; expiration: string | null }
|
||||
interface Customer { id: string; login: string; company: string | null; person: string | null; email: string | null; phone: string | null; street: string | null; zip: string | null; city: string | null; state: string | null; country: string | null; status: string | null; description: string | null; createdAt: string | null; externalId: string | null }
|
||||
interface Plan { id: string; guid: string; name: string; limits: Record<string, number>; permissions: string[] }
|
||||
|
||||
export function createPleskConnector(deps: PleskDeps = {}): Connector {
|
||||
const genPassword = deps.randomPassword ?? strongPassword;
|
||||
const agents = new Map<string, Agent>();
|
||||
|
||||
const base = (ctx: ConnectorContext) => {
|
||||
const u = String(ctx.config.baseUrl ?? '').trim().replace(/\/+$/, '').replace(/\/enterprise\/control\/agent\.php$/, '');
|
||||
if (!/^https:\/\/[^/\s]+$/.test(u)) throw new ConnectorError('BAD_CONFIG', 'baseUrl muss https://host[:port] sein (z. B. https://plesk.example.de:8443)');
|
||||
return u;
|
||||
};
|
||||
const secretKey = (ctx: ConnectorContext) => { const k = ctx.secrets.apiKey; if (!k) throw new ConnectorError('BAD_CONFIG', 'Secret Key fehlt');
|
||||
const b = [...k].find((c) => c.charCodeAt(0) < 33 || c.charCodeAt(0) > 126);
|
||||
if (b !== undefined) throw new ConnectorError('BAD_CONFIG', `Secret Key enthält ein ungültiges Zeichen „${b}“ (Leerzeichen oder Zeilenumbruch beim Kopieren?)`);
|
||||
return k; };
|
||||
|
||||
/** TLS wie beim KeyHelp-Connector: volle Prüfung, Fingerabdruck (bevorzugt bei selbstsigniertem Plesk-Zertifikat) oder abgeschaltet. */
|
||||
function fetchFor(ctx: ConnectorContext): typeof fetch {
|
||||
if (deps.fetchImpl) return deps.fetchImpl;
|
||||
const fp = String(ctx.config.tlsFingerprint ?? '').replace(/[:\s]/g, '').toLowerCase();
|
||||
const verify = String(ctx.config.verifyTls ?? 'true').toLowerCase() !== 'false';
|
||||
if (verify && !fp) return fetch;
|
||||
if (fp && !/^[0-9a-f]{64}$/.test(fp)) throw new ConnectorError('BAD_CONFIG', 'tlsFingerprint muss ein SHA-256-Fingerabdruck sein (64 Hex-Zeichen)');
|
||||
const key = `${base(ctx)}|${fp}|${verify}`; let a = agents.get(key);
|
||||
if (!a) {
|
||||
a = new Agent({ connect: { rejectUnauthorized: false, ...(fp ? { checkServerIdentity: (_h: string, cert: { fingerprint256?: string }) => ((cert.fingerprint256 ?? '').replace(/:/g, '').toLowerCase() === fp ? undefined : new Error('TLS-Fingerabdruck stimmt nicht überein')) } : {}) } });
|
||||
agents.set(key, a);
|
||||
}
|
||||
const agent = a; return ((url: string, init: RequestInit) => undiciFetch(url, { ...(init as object), dispatcher: agent } as never)) as unknown as typeof fetch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein XML-Paket senden. Lesende Pakete (`write=false`) werden bei Netz-/5xx-Fehlern wiederholt; schreibende nie automatisch.
|
||||
* Liefert den Operator-Knoten (z. B. <webspace>) der Antwort; System- und HTTP-Fehler werden normalisiert.
|
||||
*/
|
||||
async function packet(ctx: ConnectorContext, body: string, write: boolean): Promise<XNode> {
|
||||
const f = fetchFor(ctx); const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
|
||||
const attempts = write ? 1 : (deps.retries ?? 2) + 1; let last: ConnectorError | undefined;
|
||||
for (let i = 0; i < attempts; i++) {
|
||||
const ctl = new AbortController(); const timer = setTimeout(() => ctl.abort(), deps.timeoutMs ?? 20_000);
|
||||
try {
|
||||
const res = await f(`${base(ctx)}/enterprise/control/agent.php`, { method: 'POST', signal: ctl.signal, headers: { 'content-type': 'text/xml; charset=utf-8', accept: 'text/xml', KEY: secretKey(ctx), HTTP_PRETTY_PRINT: 'TRUE' }, body: `<?xml version="1.0" encoding="UTF-8"?><packet>${body}</packet>` });
|
||||
if (res.status === 401 || res.status === 403) throw new ConnectorError('AUTH_FAILED', `HTTP ${res.status}`);
|
||||
if (res.status === 404) throw new ConnectorError('NOT_FOUND', 'XML-API nicht gefunden');
|
||||
if (res.status === 429) { const ra = Number(res.headers.get('retry-after')); throw new ConnectorError('RATE_LIMITED', undefined, Number.isFinite(ra) && ra > 0 ? ra * 1000 : undefined); }
|
||||
if (!res.ok) throw new ConnectorError('UPSTREAM_ERROR', `HTTP ${res.status}`);
|
||||
let doc: XNode; try { doc = parseXml(await res.text()); } catch (e) { throw new ConnectorError('INVALID_RESPONSE', `ungültige Antwort: ${(e as Error).message}`); }
|
||||
const pk = kid(doc, 'packet'); if (!pk) throw new ConnectorError('INVALID_RESPONSE', 'kein <packet>');
|
||||
const sys = kid(pk, 'system');
|
||||
if (sys && txt(sys, 'status') === 'error') { const code = txt(sys, 'errcode') ?? ''; throw new ConnectorError(ERRCODE[code] ?? 'UPSTREAM_ERROR', `Plesk ${code}: ${(txt(sys, 'errtext') ?? '').slice(0, 200)}`); }
|
||||
const op = pk.children[0]; if (!op) throw new ConnectorError('INVALID_RESPONSE', 'leeres <packet>');
|
||||
return op;
|
||||
} catch (e) {
|
||||
last = e instanceof ConnectorError ? e : (e as { name?: string }).name === 'AbortError' ? new ConnectorError('TIMEOUT') : new ConnectorError('UNREACHABLE', (e as { cause?: { code?: string } }).cause?.code ?? (e as Error).message);
|
||||
if (!last.retryable || i === attempts - 1) throw last;
|
||||
await sleep(last.retryAfterMs ?? Math.min(10_000, (deps.baseDelayMs ?? 1000) * 2 ** i));
|
||||
} finally { clearTimeout(timer); }
|
||||
}
|
||||
throw last!;
|
||||
}
|
||||
/** Ergebnisse einer Operation; Fehler je Ergebnis werden zu ConnectorError (bei `allowMissing` wird "nicht gefunden" zu leerer Liste). */
|
||||
function results(op: XNode, operation: string, allowMissing = false): XNode[] {
|
||||
const o = kid(op, operation); if (!o) throw new ConnectorError('INVALID_RESPONSE', `keine Antwort auf ${operation}`);
|
||||
const out: XNode[] = [];
|
||||
for (const r of kids(o, 'result')) {
|
||||
if (txt(r, 'status') === 'ok') { out.push(r); continue; }
|
||||
const code = txt(r, 'errcode') ?? ''; const ec = ERRCODE[code] ?? 'UPSTREAM_ERROR';
|
||||
if (allowMissing && ec === 'NOT_FOUND') continue;
|
||||
throw new ConnectorError(ec, `Plesk ${code}: ${(txt(r, 'errtext') ?? '').slice(0, 200)}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const one = (rs: XNode[]): XNode => { const r = rs[0]; if (!r) throw new ConnectorError('INVALID_RESPONSE', 'leeres Ergebnis'); return r; };
|
||||
const num = (s: string | null): number | null => (s === null || !/^-?\d+(\.\d+)?$/.test(s) ? null : Number(s));
|
||||
const limitMap = (n: XNode | undefined): Record<string, number> => Object.fromEntries(kids(n, 'limit').map((l) => [txt(l, 'name') ?? '', num(txt(l, 'value'))]).filter(([k, v]) => k && v !== null) as [string, number][]);
|
||||
|
||||
// ---- Lesen -----------------------------------------------------------------------------
|
||||
function mapWebspace(r: XNode): Webspace {
|
||||
const gi = path(r, 'data', 'gen_info'); const st = path(r, 'data', 'stat'); const limits = limitMap(path(r, 'data', 'limits'));
|
||||
const stat: Record<string, number> = {}; for (const c of st?.children ?? []) { const v = num(c.text.trim()); if (v !== null) stat[c.name] = v; }
|
||||
return { id: txt(r, 'id') ?? '', name: txt(gi, 'name') ?? '', status: txt(gi, 'status'), ownerId: txt(gi, 'owner-id'), createdAt: dateIso(txt(gi, 'cr_date')), realSize: num(txt(gi, 'real_size')),
|
||||
limits, stat, planGuid: txt(path(r, 'data', 'subscriptions', 'subscription', 'plan'), 'plan-guid'), expiration: limits.expiration !== undefined ? String(limits.expiration) : null };
|
||||
}
|
||||
async function webspaces(ctx: ConnectorContext, filter: string = x('filter')): Promise<Webspace[]> {
|
||||
const op = await packet(ctx, xs('webspace', xs('get', filter, xs('dataset', x('gen_info'), x('limits'), x('stat'), x('subscriptions')))), false);
|
||||
return results(op, 'get', true).map(mapWebspace).filter((w) => w.id);
|
||||
}
|
||||
async function webspace(ctx: ConnectorContext, id: string): Promise<Webspace> {
|
||||
if (!/^\d{1,12}$/.test(id)) throw new ConnectorError('NOT_FOUND');
|
||||
const w = (await webspaces(ctx, x('filter', { id })))[0]; if (!w) throw new ConnectorError('NOT_FOUND'); return w;
|
||||
}
|
||||
function mapCustomer(r: XNode): Customer {
|
||||
const gi = path(r, 'data', 'gen_info');
|
||||
return { id: txt(r, 'id') ?? '', login: txt(gi, 'login') ?? '', company: txt(gi, 'cname'), person: txt(gi, 'pname'), email: txt(gi, 'email'), phone: txt(gi, 'phone'), street: txt(gi, 'address'), zip: txt(gi, 'pcode'), city: txt(gi, 'city'), state: txt(gi, 'state'), country: txt(gi, 'country'),
|
||||
status: txt(gi, 'status'), description: txt(gi, 'description'), createdAt: dateIso(txt(gi, 'cr_date')), externalId: txt(gi, 'external-id') };
|
||||
}
|
||||
async function customers(ctx: ConnectorContext, filter: string = x('filter')): Promise<Customer[]> {
|
||||
const op = await packet(ctx, xs('customer', xs('get', filter, xs('dataset', x('gen_info')))), false);
|
||||
return results(op, 'get', true).map(mapCustomer).filter((c) => c.id);
|
||||
}
|
||||
async function plans(ctx: ConnectorContext): Promise<Plan[]> {
|
||||
const op = await packet(ctx, xs('service-plan', xs('get', x('filter'))), false);
|
||||
return results(op, 'get', true).map((r) => ({ id: txt(r, 'id') ?? '', guid: txt(r, 'guid') ?? '', name: txt(r, 'name') ?? '', limits: limitMap(kid(r, 'limits')),
|
||||
permissions: kids(kid(r, 'permissions'), 'permission').filter((p) => txt(p, 'value') === 'true').map((p) => txt(p, 'name') ?? '').filter(Boolean) })).filter((p) => p.id && p.name);
|
||||
}
|
||||
const plansSafe = (ctx: ConnectorContext) => plans(ctx).catch(() => [] as Plan[]);
|
||||
|
||||
function normalize(w: Webspace, owner: Customer | undefined, planList: Plan[]): NormalizedResource {
|
||||
const limits: Record<string, number | null> = {}; const usage: Record<string, number | null> = {};
|
||||
for (const [k, v] of Object.entries(w.limits)) { const key = LIMIT_KEYS[k]; if (key) limits[key] = v < 0 ? null : v; }
|
||||
for (const [k, v] of Object.entries(w.stat)) { const key = STAT_KEYS[k]; if (key) usage[key] = v; }
|
||||
if (w.realSize !== null) usage.disk_space = w.realSize;
|
||||
const plan = planList.find((p) => p.guid && p.guid === w.planGuid);
|
||||
return {
|
||||
externalRef: w.id, type: 'hosting_account', name: `${w.name} · ${owner?.login ?? 'admin'}`, state: stateOf(w.status),
|
||||
validFrom: w.createdAt, validUntil: unixIso(w.expiration), limits, usage,
|
||||
details: { domain: w.name, username: owner?.login ?? null, owner: owner ? (owner.company ?? owner.person) : null, plan: plan?.name ?? null, planId: plan?.id ?? null,
|
||||
providerStatus: w.status !== null ? (STATUS_LABEL[w.status] ?? `Status ${w.status}`) : null, units: 'Speicher/Traffic in Byte' },
|
||||
};
|
||||
}
|
||||
async function normalized(ctx: ConnectorContext, w: Webspace): Promise<NormalizedResource> {
|
||||
const [owner, planList] = await Promise.all([w.ownerId ? customers(ctx, x('filter', { id: w.ownerId })).then((l) => l[0]) : Promise.resolve(undefined), plansSafe(ctx)]);
|
||||
return normalize(w, owner, planList);
|
||||
}
|
||||
async function ownerOf(ctx: ConnectorContext, ref: string): Promise<{ w: Webspace; owner: Customer }> {
|
||||
const w = await webspace(ctx, ref); if (!w.ownerId) throw new ConnectorError('UNSUPPORTED', 'Das Abonnement gehört dem Plesk-Administrator, nicht einem Kunden');
|
||||
const owner = (await customers(ctx, x('filter', { id: w.ownerId })))[0]; if (!owner) throw new ConnectorError('NOT_FOUND', 'Besitzer des Abonnements nicht gefunden');
|
||||
return { w, owner };
|
||||
}
|
||||
|
||||
function planItem(p: Plan): CatalogItem {
|
||||
return {
|
||||
externalRef: `plan:${p.id}`, name: p.name, description: null, category: 'hosting', fixed: true, providerActive: true, program: 'Plesk',
|
||||
features: [...Object.entries(p.limits).filter(([k]) => LIMIT_KEYS[k]).map(([k, v]) => `${RES_LABEL[LIMIT_KEYS[k]!]}: ${fmtRes(LIMIT_KEYS[k]!, v)}`)],
|
||||
meta: Object.fromEntries(Object.entries(p.limits).filter(([k]) => LIMIT_KEYS[k]).map(([k, v]) => [LIMIT_KEYS[k]!, v])),
|
||||
provisioning: { planId: Number(p.id), planName: p.name },
|
||||
};
|
||||
}
|
||||
async function planById(ctx: ConnectorContext, id: unknown): Promise<Plan> {
|
||||
const pid = String(id ?? ''); if (!/^\d{1,12}$/.test(pid)) throw new ConnectorError('BAD_CONFIG', 'planId fehlt oder ist ungültig');
|
||||
const p = (await plans(ctx)).find((x0) => x0.id === pid); if (!p) throw new ConnectorError('BAD_CONFIG', `Service-Plan ${pid} gibt es in Plesk nicht (mehr)`); return p;
|
||||
}
|
||||
|
||||
// ---- Unterobjekte (nur lesen; Änderungen folgen nach dem Test an einer echten Instanz) ----
|
||||
const children: ChildAccess = {
|
||||
async kinds() { return [{ kind: 'domain', canWrite: false }, { kind: 'email', canWrite: false }, { kind: 'database', canWrite: false }, { kind: 'ftp', canWrite: false }]; },
|
||||
async list(ctx, parentRef, kind): Promise<NormalizedChild[]> {
|
||||
const w = await webspace(ctx, parentRef); // prüft, dass es das Abonnement gibt; alle Abfragen sind auf dieses Abonnement gefiltert
|
||||
const sites = async () => {
|
||||
const op = await packet(ctx, xs('site', xs('get', x('filter', { 'parent-id': w.id }), xs('dataset', x('gen_info')))), false);
|
||||
return results(op, 'get', true).map((r) => { const gi = path(r, 'data', 'gen_info'); return { id: txt(r, 'id') ?? '', name: txt(gi, 'name') ?? '', status: txt(gi, 'status'), parent: txt(gi, 'webspace-id') }; })
|
||||
.filter((s) => s.id && (s.parent === null || s.parent === w.id));
|
||||
};
|
||||
if (kind === 'domain') {
|
||||
const list = await sites(); const all = [{ id: w.id, name: w.name, status: w.status }, ...list.filter((s) => s.id !== w.id)];
|
||||
const names = all.map((s) => s.name.toLowerCase());
|
||||
return all.map((s): NormalizedChild => ({ id: s.id, kind, name: s.name, state: s.status === null || s.status === '0' ? 'active' : 'disabled',
|
||||
details: { subdomain: names.some((n) => s.name.toLowerCase() !== n && s.name.toLowerCase().endsWith(`.${n}`)), system: false, main: s.id === w.id } }));
|
||||
}
|
||||
if (kind === 'email') {
|
||||
const siteList = [{ id: w.id, name: w.name }, ...(await sites()).filter((s) => s.id !== w.id)]; const out: NormalizedChild[] = [];
|
||||
for (const s of siteList) {
|
||||
const op = await packet(ctx, xs('mail', xs('get_info', x('filter', { 'site-id': s.id }), x('mailbox'))), false);
|
||||
for (const r of results(op, 'get_info', true)) for (const m of kids(r, 'mailname')) {
|
||||
const enabled = txt(path(m, 'mailbox'), 'enabled'); const quota = num(txt(path(m, 'mailbox'), 'quota'));
|
||||
out.push({ id: `${s.id}:${txt(m, 'id') ?? txt(m, 'name')}`, kind, name: `${txt(m, 'name')}@${s.name}`, state: enabled === 'false' ? 'disabled' : 'active', details: { maxSizeBytes: quota !== null && quota >= 0 ? quota : null, mailbox: enabled !== null } });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (kind === 'database') {
|
||||
const op = await packet(ctx, xs('database', xs('get-db', x('filter', { 'webspace-id': w.id }))), false);
|
||||
return results(op, 'get-db', true).filter((r) => (txt(r, 'webspace-id') ?? w.id) === w.id).map((r) => ({ id: txt(r, 'id') ?? '', kind, name: txt(r, 'name') ?? '', state: 'active', details: { type: txt(r, 'type') } }));
|
||||
}
|
||||
if (kind === 'ftp') {
|
||||
const op = await packet(ctx, xs('ftp-user', xs('get', x('filter', { 'webspace-id': w.id }))), false);
|
||||
return results(op, 'get', true).filter((r) => (txt(r, 'webspace-id') ?? w.id) === w.id).map((r) => ({ id: txt(r, 'id') ?? '', kind, name: txt(r, 'name') ?? '', state: 'active', details: { home: txt(r, 'home') } }));
|
||||
}
|
||||
throw new ConnectorError('UNSUPPORTED', `${kind as ChildKind} wird bei Plesk noch nicht gelesen`);
|
||||
},
|
||||
async act() { throw new ConnectorError('UNSUPPORTED', 'Änderungen an Domains/Postfächern/Datenbanken sind für Plesk noch nicht freigeschaltet'); },
|
||||
};
|
||||
|
||||
const capabilities: Capability[] = ['customers.list', 'catalog.list', 'resources.list', 'resources.get', 'status.read', 'usage.read', 'lifecycle.create', 'lifecycle.suspend', 'lifecycle.unsuspend', 'lifecycle.terminate', 'plan.change', 'sso.login', 'children.read', 'panel.password_reset'];
|
||||
|
||||
return {
|
||||
contractVersion: CONTRACT_VERSION, key: 'plesk', displayName: 'Plesk (Webhosting)',
|
||||
configFields: [
|
||||
{ name: 'baseUrl', label: 'Plesk-Adresse', required: true, placeholder: 'https://plesk.example.de:8443', help: 'Die Adresse des Plesk-Panels mit https:// und Port (meist 8443).' },
|
||||
{ name: 'apiKey', label: 'Secret Key', secret: true, required: true, help: 'Auf dem Plesk-Server erzeugen: plesk bin secret_key -c -ip-address <IP dieses Servers> -description Kundencenter. Der Schlüssel hat Administratorrechte.' },
|
||||
{ name: 'ipAddress', label: 'IP-Adresse für neue Abonnements', placeholder: '203.0.113.10', help: 'Gemeinsame IPv4-Adresse des Plesk-Servers, auf der neue Abonnements angelegt werden. Nur für die Bereitstellung nötig.' },
|
||||
{ name: 'subscriptionDomain', label: 'Domain für neue Abonnements', placeholder: 'kunden.example.de', help: 'Neue Abonnements heißen kc<Vertragsnummer>.<diese Domain>; die eigentlichen Domains fügt der Kunde danach in Plesk hinzu. Nur für die Bereitstellung nötig.' },
|
||||
{ name: 'verifyTls', label: 'Zertifikat von Plesk prüfen', advanced: true, options: [{ value: 'true', label: 'Ja, prüfen (empfohlen)' }, { value: 'false', label: 'Nein, nicht prüfen (unsicher)' }], help: 'Plesk nutzt auf Port 8443 oft ein selbstsigniertes Zertifikat. Dann besser den Fingerabdruck unten eintragen statt die Prüfung abzuschalten.' },
|
||||
{ name: 'tlsFingerprint', label: 'Zertifikat-Fingerabdruck (SHA-256)', advanced: true, placeholder: 'AB:CD:EF:…', help: 'Nur bei selbstsigniertem Zertifikat: Das Kundencenter vertraut dann genau diesem Zertifikat.' },
|
||||
],
|
||||
capabilities: () => capabilities,
|
||||
async healthCheck(ctx) {
|
||||
const t0 = Date.now();
|
||||
try {
|
||||
const op = await packet(ctx, xs('server', xs('get', x('stat'), x('gen_info'))), false); const r = one(results(op, 'get'));
|
||||
const v = txt(path(r, 'stat', 'version'), 'plesk_version'); const host = txt(kid(r, 'gen_info'), 'server_name');
|
||||
return { ok: true, latencyMs: Date.now() - t0, version: v ? `Plesk ${v}${host ? ` (${host})` : ''}` : undefined };
|
||||
} catch (e) { return { ok: false, latencyMs: Date.now() - t0, message: e instanceof ConnectorError ? e.message : 'Unbekannter Fehler' }; }
|
||||
},
|
||||
/** Alle Abonnements mit Limits, Nutzung, Tarif und Besitzer (drei Abfragen, unabhängig von der Anzahl). */
|
||||
async listResources(ctx) {
|
||||
const [ws, cs, pl] = await Promise.all([webspaces(ctx), customers(ctx), plansSafe(ctx)]);
|
||||
const byId = new Map(cs.map((c) => [c.id, c]));
|
||||
return ws.map((w) => normalize(w, w.ownerId ? byId.get(w.ownerId) : undefined, pl));
|
||||
},
|
||||
/** Service-Pläne als Produktvorlagen (fest vorgegeben, Bereitstellung über den Plan). */
|
||||
async listCatalog(ctx) { return (await plans(ctx)).map(planItem); },
|
||||
/** Je Abonnement ein Eintrag mit den Kontaktdaten des Plesk-Kunden (mehrere Abonnements eines Kunden → mit demselben Kunden verknüpfen). */
|
||||
async listCustomers(ctx) {
|
||||
const [ws, cs, pl] = await Promise.all([webspaces(ctx), customers(ctx), plansSafe(ctx)]);
|
||||
const byId = new Map(cs.map((c) => [c.id, c]));
|
||||
return ws.map((w): ImportableCustomer => {
|
||||
const c = w.ownerId ? byId.get(w.ownerId) : undefined; const [first, ...rest] = (c?.person ?? '').split(/\s+/).filter(Boolean); const plan = pl.find((p) => p.guid && p.guid === w.planGuid);
|
||||
return { externalRef: w.id, displayName: `${c?.company ?? c?.person ?? c?.login ?? 'Administrator'} · ${w.name}`, company: c?.company ?? null, firstName: first ?? null, lastName: rest.join(' ') || null, email: c?.email ?? null, phone: c?.phone ?? null,
|
||||
address: { street: c?.street ?? null, zip: c?.zip ?? null, city: c?.city ?? null, state: c?.state ?? null, country: c?.country ?? null }, legacyNumber: c?.externalId ?? c?.login ?? null,
|
||||
planRef: plan ? `plan:${plan.id}` : null, planName: plan?.name ?? null, state: stateOf(w.status) === 'active' ? 'active' : 'suspended', createdAt: w.createdAt };
|
||||
});
|
||||
},
|
||||
validateProvisioning(p) {
|
||||
if (p.planId === undefined || p.planId === null || !Number.isInteger(p.planId) || (p.planId as number) < 1) return 'planId (Service-Plan) muss eine ganze Zahl ≥ 1 sein';
|
||||
if (p.planName !== undefined && (typeof p.planName !== 'string' || p.planName.length > 200)) return 'planName ist ungültig';
|
||||
return null;
|
||||
},
|
||||
/**
|
||||
* Legt Kunde (Login "kc"+Vertragsnummer) und Abonnement an. Beides ist über stabile Namen wiederauffindbar: Existiert der Kunde mit unserem
|
||||
* Vermerk bzw. das Abonnement mit diesem Besitzer schon, wird es übernommen (sichere Wiederholung). Passwörter werden nie gespeichert.
|
||||
*/
|
||||
async provision(ctx, req) {
|
||||
const err = this.validateProvisioning!(req.params); if (err) throw new ConnectorError('BAD_CONFIG', err);
|
||||
const c = req.context; if (!c?.customerEmail) throw new ConnectorError('BAD_CONFIG', 'Für das Plesk-Konto wird die E-Mail-Adresse des Kunden benötigt');
|
||||
const ip = String(ctx.config.ipAddress ?? '').trim(); if (!IPV4_RE.test(ip)) throw new ConnectorError('BAD_CONFIG', 'IP-Adresse für neue Abonnements fehlt (Verbindungseinstellungen)');
|
||||
const sub = String(ctx.config.subscriptionDomain ?? '').trim().toLowerCase(); if (!DOMAIN_RE.test(sub)) throw new ConnectorError('BAD_CONFIG', 'Domain für neue Abonnements fehlt (Verbindungseinstellungen)');
|
||||
const plan = await planById(ctx, req.params.planId);
|
||||
const login = loginFor(c, req.idempotencyKey); if (!LOGIN_RE.test(login)) throw new ConnectorError('BAD_CONFIG', `Login ${login} ist ungültig`);
|
||||
const name = `${login}.${sub}`;
|
||||
// 1) Kunde
|
||||
let cust = (await customers(ctx, x('filter', { login })))[0];
|
||||
if (cust && !String(cust.description ?? '').includes(noteFor(c))) throw new ConnectorError('CONFLICT', `Der Plesk-Login ${login} ist bereits an einen anderen Kunden vergeben`);
|
||||
if (!cust) {
|
||||
const op = await packet(ctx, xs('customer', xs('add', x('gen_info', { cname: c.customerName.slice(0, 60), pname: (c.contactName ?? c.customerName).slice(0, 60), login, passwd: genPassword(), status: 0, email: c.customerEmail, description: noteFor(c) }))), true);
|
||||
const id = txt(one(results(op, 'add')), 'id'); if (!id) throw new ConnectorError('INVALID_RESPONSE', 'keine Kunden-ID');
|
||||
cust = (await customers(ctx, x('filter', { id })))[0]; if (!cust || cust.login !== login) throw new ConnectorError('INVALID_RESPONSE', `Kunde ${id} mit unerwartetem Login angelegt`);
|
||||
}
|
||||
// 2) Abonnement
|
||||
const existing = (await webspaces(ctx, x('filter', { name })))[0];
|
||||
if (existing) {
|
||||
if (existing.ownerId !== cust.id) throw new ConnectorError('CONFLICT', `Das Abonnement ${name} gehört einem anderen Kunden`);
|
||||
return { resource: await normalized(ctx, existing) };
|
||||
}
|
||||
const add = xs('webspace', xs('add',
|
||||
x('gen_setup', { name, 'owner-id': cust.id, htype: 'vrt_hst', ip_address: ip, status: 0 }),
|
||||
xs('hosting', xs('vrt_hst', x('property', { name: 'ftp_login', value: `${login}ftp` }), x('property', { name: 'ftp_password', value: genPassword() }), x('ip_address', ip))),
|
||||
x('plan-name', plan.name)));
|
||||
const id = txt(one(results(await packet(ctx, add, true), 'add')), 'id'); if (!id) throw new ConnectorError('INVALID_RESPONSE', 'keine Abonnement-ID');
|
||||
const w = await webspace(ctx, id); if (w.name !== name || w.ownerId !== cust.id) throw new ConnectorError('INVALID_RESPONSE', `Abonnement ${id} weicht von der Anfrage ab`);
|
||||
return { resource: await normalized(ctx, w) };
|
||||
},
|
||||
/** Sperren/Entsperren setzen den Zielstatus, Planwechsel den Plan, Löschen entfernt das Abonnement (nie automatisch wiederholt). */
|
||||
async execute(ctx, req) {
|
||||
const ref = req.externalRef;
|
||||
if (req.action === 'suspend' || req.action === 'unsuspend') {
|
||||
await webspace(ctx, ref);
|
||||
results(await packet(ctx, xs('webspace', xs('set', x('filter', { id: ref }), xs('values', x('gen_setup', { status: req.action === 'suspend' ? 16 : 0 })))), true), 'set');
|
||||
return { resource: await normalized(ctx, await webspace(ctx, ref)) };
|
||||
}
|
||||
if (req.action === 'change_plan') {
|
||||
const p = await planById(ctx, req.params?.planId); if (!p.guid) throw new ConnectorError('INVALID_RESPONSE', 'Service-Plan ohne GUID');
|
||||
await webspace(ctx, ref);
|
||||
results(await packet(ctx, xs('webspace', xs('switch-subscription', x('filter', { id: ref }), x('plan-guid', p.guid))), true), 'switch-subscription');
|
||||
return { resource: await normalized(ctx, await webspace(ctx, ref)) };
|
||||
}
|
||||
if (req.action === 'terminate') {
|
||||
if (!/^\d{1,12}$/.test(ref)) throw new ConnectorError('NOT_FOUND');
|
||||
results(await packet(ctx, xs('webspace', xs('del', x('filter', { id: ref }))), true), 'del', true); // schon gelöscht = Ziel erreicht
|
||||
return {};
|
||||
}
|
||||
if (req.action === 'reset_password') {
|
||||
const p = req.secrets?.password; if (!p || p.length < 8 || p.length > 128 || /[\0\r\n]/.test(p)) throw bad('Passwort fehlt oder ist ungültig (mindestens 8 Zeichen)');
|
||||
const { owner } = await ownerOf(ctx, ref);
|
||||
results(await packet(ctx, xs('customer', xs('set', x('filter', { id: owner.id }), xs('values', x('gen_info', { passwd: p })))), true), 'set');
|
||||
return { resource: await normalized(ctx, await webspace(ctx, ref)) };
|
||||
}
|
||||
throw new ConnectorError('UNSUPPORTED', 'Diese Aktion gibt es bei Plesk nicht');
|
||||
},
|
||||
/** Einmal-Sitzung für den Besitzer des Abonnements (server/create_session); der Link wird nie gespeichert. */
|
||||
async loginUrl(ctx, ref) {
|
||||
const { owner } = await ownerOf(ctx, ref);
|
||||
const op = await packet(ctx, xs('server', xs('create_session', x('login', owner.login), x('data', { user_ip: Buffer.from('127.0.0.1').toString('base64'), source_server: '' }))), true);
|
||||
const sid = txt(one(results(op, 'create_session')), 'id'); if (!sid || !/^[\w-]{8,200}$/.test(sid)) throw new ConnectorError('INVALID_RESPONSE', 'keine Sitzungs-ID');
|
||||
return { url: `${base(ctx)}/enterprise/rsession_init.php?PLESKSESSID=${encodeURIComponent(sid)}`, validForSec: 300 };
|
||||
},
|
||||
children,
|
||||
};
|
||||
}
|
||||
export const pleskConnector = createPleskConnector();
|
||||
57
packages/connector-plesk/src/xml.ts
Normal file
57
packages/connector-plesk/src/xml.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
/**
|
||||
* Kleiner XML-Baustein für die Plesk-XML-API: Anfragen bauen (alle Werte werden maskiert) und Antworten lesen.
|
||||
* Die Antworten der API sind einfache Elementbäume (fast ohne Attribute); DOCTYPE/Entitäten-Deklarationen werden
|
||||
* nicht unterstützt und führen zum Abbruch (kein XXE, keine Entitäten-Expansion).
|
||||
*/
|
||||
export interface XNode { name: string; children: XNode[]; text: string }
|
||||
|
||||
const ENT: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
|
||||
const decode = (s: string): string => s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e: string) => {
|
||||
if (e[0] === '#') { const n = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10); return Number.isFinite(n) && n > 0 && n <= 0x10ffff ? String.fromCodePoint(n) : m; }
|
||||
return ENT[e.toLowerCase()] ?? m;
|
||||
});
|
||||
export const esc = (s: string): string => s.replace(/[&<>"']/g, (c) => `&${({ '&': 'amp', '<': 'lt', '>': 'gt', '"': 'quot', "'": 'apos' } as Record<string, string>)[c]};`);
|
||||
|
||||
export function parseXml(src: string): XNode {
|
||||
if (/<!DOCTYPE|<!ENTITY/i.test(src)) throw new Error('DOCTYPE/ENTITY nicht erlaubt');
|
||||
const root: XNode = { name: '#root', children: [], text: '' }; const stack: XNode[] = [root]; let i = 0;
|
||||
while (i < src.length) {
|
||||
const lt = src.indexOf('<', i);
|
||||
if (lt < 0) { stack[stack.length - 1]!.text += decode(src.slice(i)); break; }
|
||||
if (lt > i) stack[stack.length - 1]!.text += decode(src.slice(i, lt));
|
||||
if (src.startsWith('<?', lt)) { const e = src.indexOf('?>', lt); if (e < 0) throw new Error('XML unvollständig'); i = e + 2; continue; }
|
||||
if (src.startsWith('<!--', lt)) { const e = src.indexOf('-->', lt); if (e < 0) throw new Error('XML unvollständig'); i = e + 3; continue; }
|
||||
if (src.startsWith('<![CDATA[', lt)) { const e = src.indexOf(']]>', lt); if (e < 0) throw new Error('XML unvollständig'); stack[stack.length - 1]!.text += src.slice(lt + 9, e); i = e + 3; continue; }
|
||||
const gt = src.indexOf('>', lt); if (gt < 0) throw new Error('XML unvollständig');
|
||||
const raw = src.slice(lt + 1, gt).trim(); i = gt + 1;
|
||||
if (raw.startsWith('/')) {
|
||||
const name = raw.slice(1).trim(); const top = stack.pop();
|
||||
if (!top || top.name !== name || stack.length === 0) throw new Error(`XML: unerwartetes </${name}>`);
|
||||
continue;
|
||||
}
|
||||
const selfClose = raw.endsWith('/'); const name = (selfClose ? raw.slice(0, -1) : raw).trim().split(/\s+/)[0]!;
|
||||
if (!/^[A-Za-z_][\w.:-]*$/.test(name)) throw new Error('XML: ungültiger Elementname');
|
||||
const node: XNode = { name, children: [], text: '' }; stack[stack.length - 1]!.children.push(node);
|
||||
if (!selfClose) stack.push(node);
|
||||
}
|
||||
if (stack.length !== 1) throw new Error('XML unvollständig');
|
||||
return root;
|
||||
}
|
||||
|
||||
/** Hilfen zum Lesen: erstes/alle Kindelemente, Text (getrimmt) eines Kindes. */
|
||||
export const kid = (n: XNode | undefined, name: string): XNode | undefined => n?.children.find((c) => c.name === name);
|
||||
export const kids = (n: XNode | undefined, name: string): XNode[] => (n ? n.children.filter((c) => c.name === name) : []);
|
||||
export const txt = (n: XNode | undefined, name?: string): string | null => { const t = name ? kid(n, name) : n; if (!t) return null; const v = t.text.trim(); return v === '' ? null : v; };
|
||||
/** Pfad lesen: path(n, 'data', 'gen_info', 'name'). */
|
||||
export const path = (n: XNode | undefined, ...names: string[]): XNode | undefined => names.reduce<XNode | undefined>((a, k) => kid(a, k), n);
|
||||
|
||||
/** Element bauen. Kinder als Array, Text wird maskiert. `null`/`undefined` werden ausgelassen. */
|
||||
export type XIn = string | number | boolean | null | undefined | XIn[] | { [k: string]: XIn };
|
||||
export function x(name: string, content?: XIn): string {
|
||||
if (content === undefined || content === null) return `<${name}/>`;
|
||||
if (Array.isArray(content)) return `<${name}>${content.map((c) => (typeof c === 'string' && c.startsWith('<') ? c : '')).join('')}</${name}>`;
|
||||
if (typeof content === 'object') return `<${name}>${Object.entries(content).filter(([, v]) => v !== undefined && v !== null).map(([k, v]) => x(k, v)).join('')}</${name}>`;
|
||||
return `<${name}>${esc(String(content))}</${name}>`;
|
||||
}
|
||||
/** Bereits gebaute Elemente zusammensetzen (vertrauenswürdige Bausteine aus x()). */
|
||||
export const xs = (name: string, ...parts: string[]): string => `<${name}>${parts.join('')}</${name}>`;
|
||||
125
packages/connector-plesk/test/fake.ts
Normal file
125
packages/connector-plesk/test/fake.ts
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
/**
|
||||
* Nachbau eines Plesk-Servers (Teilmenge der XML-API, Plesk Obsidian 18) für Tests ohne echte Instanz.
|
||||
* Antworten folgen dem dokumentierten Format (<packet><operator><operation><result>…); Verhalten, das die Doku offenlässt, ist bewusst einfach.
|
||||
*/
|
||||
import { esc, kid, kids, parseXml, path, txt, type XNode } from '../src/xml.js';
|
||||
|
||||
type Row = Record<string, any>;
|
||||
export interface Fake {
|
||||
fetch: typeof fetch;
|
||||
state: { customers: Row[]; webspaces: Row[]; plans: Row[]; sites: Row[]; mail: Row[]; dbs: Row[]; ftp: Row[]; sessions: string[] };
|
||||
calls: { op: string; body: string; key?: string }[];
|
||||
opts: { fail503: number };
|
||||
}
|
||||
|
||||
const ok = (inner: string) => `<result><status>ok</status>${inner}</result>`;
|
||||
const errR = (code: string, text: string) => `<result><status>error</status><errcode>${code}</errcode><errtext>${esc(text)}</errtext></result>`;
|
||||
const v = (name: string, val: unknown) => (val === undefined || val === null ? '' : `<${name}>${esc(String(val))}</${name}>`);
|
||||
|
||||
export function createFake(secret = 'test-secret'): Fake {
|
||||
let seq = 100;
|
||||
const state: Fake['state'] = {
|
||||
plans: [
|
||||
{ id: 1, guid: 'g-plan-1', name: 'Starter', limits: { disk_space: 10737418240, max_traffic: 107374182400, max_site: 2, max_subdom: 10, max_box: 5, max_db: 2, max_subftp_users: 1 }, perms: { manage_dns: true, manage_php_settings: false } },
|
||||
{ id: 2, guid: 'g-plan-2', name: 'Business', limits: { disk_space: -1, max_traffic: -1, max_site: 50, max_subdom: -1, max_box: -1, max_db: 20, max_subftp_users: 10 }, perms: { manage_dns: true } },
|
||||
],
|
||||
customers: [
|
||||
{ id: 11, login: 'alpha', cname: 'Alpha GmbH', pname: 'Anna Alpha', email: 'anna@alpha.test', phone: '040 123', address: 'Hafenstr. 1', pcode: '20095', city: 'Hamburg', country: 'DE', status: 0, description: 'Bestand', cr_date: '2025-03-01', passwd: 'GEHEIM-ALPHA' },
|
||||
{ id: 12, login: 'beta', cname: '', pname: 'Bernd Beta', email: 'bernd@beta.test', status: 0, cr_date: '2026-01-15', passwd: 'GEHEIM-BETA' },
|
||||
],
|
||||
webspaces: [
|
||||
{ id: 21, name: 'alpha.test', status: 0, owner: 11, cr_date: '2025-03-01', real_size: 524288000, plan: 'g-plan-1', expiration: -1, stat: { traffic: 1048576, subdom: 2, box: 3, db: 1 } },
|
||||
{ id: 22, name: 'alpha-shop.test', status: 16, owner: 11, cr_date: '2025-06-01', real_size: 1000, plan: 'g-plan-2', expiration: 1798761600, stat: { traffic: 0, subdom: 0, box: 0, db: 0 } },
|
||||
{ id: 23, name: 'beta.test', status: 0, owner: 12, cr_date: '2026-01-15', real_size: 2000, plan: 'g-plan-1', expiration: -1, stat: { traffic: 10, subdom: 0, box: 1, db: 0 } },
|
||||
{ id: 24, name: 'admin-intern.test', status: 0, owner: null, cr_date: '2024-01-01', real_size: 1, plan: null, expiration: -1, stat: {} },
|
||||
],
|
||||
sites: [{ id: 31, name: 'blog.alpha.test', parent: 21, status: 0 }, { id: 32, name: 'alpha-zwei.test', parent: 21, status: 0 }, { id: 33, name: 'beta-zwei.test', parent: 23, status: 0 }],
|
||||
mail: [{ id: 41, site: 21, name: 'info', enabled: true, quota: 1073741824, passwd: 'GEHEIM-MAIL' }, { id: 42, site: 32, name: 'post', enabled: false, quota: -1 }, { id: 43, site: 23, name: 'bernd', enabled: true, quota: -1 }],
|
||||
dbs: [{ id: 51, ws: 21, name: 'alpha_wp', type: 'mysql' }, { id: 52, ws: 23, name: 'beta_db', type: 'mysql' }],
|
||||
ftp: [{ id: 61, ws: 21, name: 'alpha_dev', home: '/httpdocs' }, { id: 62, ws: 23, name: 'beta_ftp', home: '/' }],
|
||||
sessions: [],
|
||||
};
|
||||
const calls: Fake['calls'] = []; const opts: Fake['opts'] = { fail503: 0 };
|
||||
|
||||
const wsXml = (w: Row, ds: Set<string>) => {
|
||||
const owner = w.owner ? state.customers.find((c) => c.id === w.owner) : null;
|
||||
const gi = ds.has('gen_info') ? `<gen_info>${v('cr_date', w.cr_date)}${v('name', w.name)}${v('ascii-name', w.name)}${v('status', w.status)}${v('real_size', w.real_size)}${owner ? v('owner-id', owner.id) + v('owner-login', owner.login) : ''}${v('htype', 'vrt_hst')}<guid>ws-${w.id}</guid></gen_info>` : '';
|
||||
const lim = ds.has('limits') ? `<limits><overuse>normal</overuse>${Object.entries(w.plan ? state.plans.find((p) => p.guid === w.plan)?.limits ?? {} : {}).map(([k, val]) => `<limit><name>${k}</name><value>${val}</value></limit>`).join('')}<limit><name>expiration</name><value>${w.expiration}</value></limit></limits>` : '';
|
||||
const st = ds.has('stat') ? `<stat>${Object.entries(w.stat).map(([k, val]) => v(k, val)).join('')}</stat>` : '';
|
||||
const subs = ds.has('subscriptions') ? `<subscriptions>${w.plan ? `<subscription><locked>false</locked><synchronized>true</synchronized><plan><plan-guid>${w.plan}</plan-guid></plan></subscription>` : ''}</subscriptions>` : '';
|
||||
return ok(`${v('id', w.id)}<data>${gi}${lim}${st}${subs}</data>`);
|
||||
};
|
||||
const custXml = (c: Row) => ok(`${v('id', c.id)}<data><gen_info>${v('cr_date', c.cr_date)}${v('cname', c.cname)}${v('pname', c.pname)}${v('login', c.login)}${v('status', c.status)}${v('phone', c.phone)}${v('email', c.email)}${v('address', c.address)}${v('city', c.city)}${v('pcode', c.pcode)}${v('country', c.country)}${v('description', c.description)}<guid>c-${c.id}</guid></gen_info></data>`);
|
||||
const filt = (op: XNode | undefined) => { const f = kid(op, 'filter'); return { id: txt(f, 'id'), name: txt(f, 'name'), login: txt(f, 'login'), parent: txt(f, 'parent-id'), site: txt(f, 'site-id'), ws: txt(f, 'webspace-id'), empty: !f || f.children.length === 0 }; };
|
||||
const dataset = (op: XNode | undefined) => new Set((kid(op, 'dataset')?.children ?? []).map((c) => c.name));
|
||||
|
||||
function handle(pk: XNode): string {
|
||||
const opNode = pk.children[0]!; const operation = opNode.children[0]!; const o = opNode.name; const n = operation.name;
|
||||
const wrap = (inner: string) => `<${o}><${n}>${inner}</${n}></${o}>`;
|
||||
if (o === 'server' && n === 'get') return wrap(ok(`<gen_info><server_name>plesk.fake.test</server_name></gen_info><stat><version><plesk_version>18.0.62</plesk_version><plesk_os>Debian</plesk_os></version></stat>`));
|
||||
if (o === 'server' && n === 'create_session') {
|
||||
const login = txt(operation, 'login'); if (!state.customers.some((c) => c.login === login)) return wrap(errR('1013', 'Client does not exist'));
|
||||
const sid = `sess${++seq}abcdef`; state.sessions.push(`${login}:${sid}`); return wrap(ok(v('id', sid)));
|
||||
}
|
||||
if (o === 'service-plan' && n === 'get') return wrap(state.plans.map((p) => ok(`${v('id', p.id)}${v('name', p.name)}${v('guid', p.guid)}<limits><overuse>block</overuse>${Object.entries(p.limits).map(([k, val]) => `<limit><name>${k}</name><value>${val}</value></limit>`).join('')}</limits><permissions>${Object.entries(p.perms).map(([k, val]) => `<permission><name>${k}</name><value>${val}</value></permission>`).join('')}</permissions>`)).join(''));
|
||||
if (o === 'customer' && n === 'get') {
|
||||
const f = filt(operation); const list = state.customers.filter((c) => f.empty || (f.id && String(c.id) === f.id) || (f.login && c.login === f.login));
|
||||
return wrap(list.length ? list.map(custXml).join('') : errR('1013', 'Client does not exist'));
|
||||
}
|
||||
if (o === 'customer' && n === 'add') {
|
||||
const gi = kid(operation, 'gen_info'); const login = txt(gi, 'login')!;
|
||||
if (!txt(gi, 'passwd') || !txt(gi, 'pname')) return wrap(errR('1019', 'pname/passwd required'));
|
||||
if (state.customers.some((c) => c.login === login)) return wrap(errR('1007', 'Client already exists'));
|
||||
const c = { id: ++seq, login, cname: txt(gi, 'cname'), pname: txt(gi, 'pname'), email: txt(gi, 'email'), status: Number(txt(gi, 'status') ?? 0), description: txt(gi, 'description'), cr_date: '2026-10-05', passwd: txt(gi, 'passwd') };
|
||||
state.customers.push(c); return wrap(ok(`${v('id', c.id)}<guid>c-${c.id}</guid>`));
|
||||
}
|
||||
if (o === 'customer' && n === 'set') {
|
||||
const f = filt(operation); const c = state.customers.find((x0) => String(x0.id) === f.id); if (!c) return wrap(errR('1013', 'Client does not exist'));
|
||||
const pw = txt(path(operation, 'values', 'gen_info'), 'passwd'); if (pw) c.passwd = pw; return wrap(ok(v('id', c.id)));
|
||||
}
|
||||
if (o === 'webspace' && n === 'get') {
|
||||
const f = filt(operation); const ds = dataset(operation); const list = state.webspaces.filter((w) => f.empty || (f.id && String(w.id) === f.id) || (f.name && w.name === f.name));
|
||||
return wrap(list.length ? list.map((w) => wsXml(w, ds)).join('') : errR('1013', 'Domain does not exist'));
|
||||
}
|
||||
if (o === 'webspace' && n === 'add') {
|
||||
const gs = kid(operation, 'gen_setup'); const name = txt(gs, 'name')!; const owner = Number(txt(gs, 'owner-id')); const planName = txt(operation, 'plan-name');
|
||||
if (!txt(gs, 'ip_address')) return wrap(errR('1019', 'IP address required'));
|
||||
if (state.webspaces.some((w) => w.name === name)) return wrap(errR('1007', 'Domain already exists'));
|
||||
const plan = state.plans.find((p) => p.name === planName); if (!plan) return wrap(errR('1013', 'Service plan does not exist'));
|
||||
const w = { id: ++seq, name, status: Number(txt(gs, 'status') ?? 0), owner, cr_date: '2026-10-05', real_size: 0, plan: plan.guid, expiration: -1, stat: { traffic: 0, subdom: 0, box: 0, db: 0 } };
|
||||
state.webspaces.push(w); return wrap(ok(`${v('id', w.id)}<guid>ws-${w.id}</guid>`));
|
||||
}
|
||||
if (o === 'webspace' && (n === 'set' || n === 'switch-subscription' || n === 'del')) {
|
||||
const f = filt(operation); const w = state.webspaces.find((x0) => String(x0.id) === f.id); if (!w) return wrap(errR('1013', 'Domain does not exist'));
|
||||
if (n === 'set') { const st = txt(path(operation, 'values', 'gen_setup'), 'status'); if (st !== null) w.status = Number(st); }
|
||||
if (n === 'switch-subscription') { const g = txt(operation, 'plan-guid'); if (!state.plans.some((p) => p.guid === g)) return wrap(errR('1013', 'Plan does not exist')); w.plan = g; }
|
||||
if (n === 'del') state.webspaces.splice(state.webspaces.indexOf(w), 1);
|
||||
return wrap(ok(v('id', w.id)));
|
||||
}
|
||||
if (o === 'site' && n === 'get') {
|
||||
const f = filt(operation); const list = state.sites.filter((s) => String(s.parent) === f.parent);
|
||||
return wrap(list.length ? list.map((s) => ok(`${v('id', s.id)}<data><gen_info>${v('name', s.name)}${v('status', s.status)}${v('webspace-id', s.parent)}</gen_info></data>`)).join('') : errR('1013', 'Site does not exist'));
|
||||
}
|
||||
if (o === 'mail' && n === 'get_info') {
|
||||
const f = filt(operation); const list = state.mail.filter((m) => String(m.site) === f.site);
|
||||
return wrap(ok(`${v('filter-id', f.site)}${list.map((m) => `<mailname>${v('id', m.id)}${v('name', m.name)}<mailbox>${v('enabled', m.enabled)}${v('quota', m.quota)}</mailbox></mailname>`).join('')}`));
|
||||
}
|
||||
if (o === 'database' && n === 'get-db') { const f = filt(operation); return wrap(state.dbs.filter((d) => String(d.ws) === f.ws).map((d) => ok(`${v('id', d.id)}${v('name', d.name)}${v('type', d.type)}${v('webspace-id', d.ws)}`)).join('')); }
|
||||
if (o === 'ftp-user' && n === 'get') { const f = filt(operation); return wrap(state.ftp.filter((u) => String(u.ws) === f.ws).map((u) => ok(`${v('id', u.id)}${v('name', u.name)}${v('home', u.home)}${v('webspace-id', u.ws)}`)).join('')); }
|
||||
return wrap(errR('1014', `unbekannte Operation ${o}/${n}`));
|
||||
}
|
||||
|
||||
const f = (async (url: string, init: RequestInit = {}) => {
|
||||
const u = new URL(url); if (u.pathname !== '/enterprise/control/agent.php') return new Response('not found', { status: 404 });
|
||||
const h = (init.headers ?? {}) as Record<string, string>; const body = String(init.body ?? '');
|
||||
const doc = parseXml(body); const pk = kid(doc, 'packet')!; const opName = `${pk.children[0]?.name}/${pk.children[0]?.children[0]?.name}`;
|
||||
calls.push({ op: opName, body, key: h.KEY });
|
||||
const isRead = /\/(get|get_info|get-db)$/.test(opName);
|
||||
if (isRead && opts.fail503 > 0) { opts.fail503--; return new Response('busy', { status: 503 }); }
|
||||
const xmlRes = (inner: string) => new Response(`<?xml version="1.0" encoding="UTF-8"?>\n<packet version="1.6.9.1">${inner}</packet>`, { status: 200, headers: { 'content-type': 'text/xml' } });
|
||||
if (h.KEY !== secret) return xmlRes('<system><status>error</status><errcode>1001</errcode><errtext>Authentication failed - wrong secret key or usage of not allowed IP address.</errtext></system>');
|
||||
return xmlRes(handle(pk));
|
||||
}) as unknown as typeof fetch;
|
||||
void kids;
|
||||
return { fetch: f, state, calls, opts };
|
||||
}
|
||||
135
packages/connector-plesk/test/plesk.test.ts
Normal file
135
packages/connector-plesk/test/plesk.test.ts
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { ConnectorError, type ConnectorContext, type ProvisionContext } from '@kc/connector-sdk';
|
||||
import { runContract } from '@kc/connector-sdk/dist/contract.js';
|
||||
import { createPleskConnector, loginFor } from '../src/index.js';
|
||||
import { parseXml, x, xs } from '../src/xml.js';
|
||||
import { createFake, type Fake } from './fake.js';
|
||||
|
||||
const ctx = (extra: Record<string, unknown> = {}, secret = 'test-secret'): ConnectorContext => ({ config: { baseUrl: 'https://plesk.test:8443', ipAddress: '203.0.113.10', subscriptionDomain: 'kunden.example.test', ...extra }, secrets: { apiKey: secret }, correlationId: 'c' });
|
||||
const mk = (fake: Fake, extra: Record<string, unknown> = {}) => createPleskConnector({ fetchImpl: fake.fetch, sleep: async () => {}, randomPassword: () => 'Zufall-Pw-123!', ...extra });
|
||||
const PC: ProvisionContext = { source: 'kundencenter', customerNumber: 'K-10001', customerName: 'Muster GmbH', contactName: 'Max Muster', customerEmail: 'max@example.test', orderNumber: 'B-20001', contractNumber: 'V-30001' };
|
||||
const code = async (p: Promise<unknown>) => { try { await p; return 'OK'; } catch (e) { return e instanceof ConnectorError ? e.code : String(e); } };
|
||||
|
||||
describe('XML-Baustein', () => {
|
||||
it('maskiert Werte (keine Injektion von Elementen)', () => {
|
||||
expect(x('name', '</name><passwd>x</passwd>')).toBe('<name></name><passwd>x</passwd></name>');
|
||||
expect(x('filter', { id: 5, name: undefined })).toBe('<filter><id>5</id></filter>');
|
||||
expect(xs('a', x('b'), x('c', 'ä & ö'))).toBe('<a><b/><c>ä & ö</c></a>');
|
||||
});
|
||||
it('liest Entitäten/CDATA und lehnt DOCTYPE ab (kein XXE)', () => {
|
||||
const d = parseXml('<?xml version="1.0"?><p><a>x & y ä</a><b><![CDATA[<roh>]]></b><c/></p>');
|
||||
expect(d.children[0]!.children.map((c) => [c.name, c.text])).toEqual([['a', 'x & y ä'], ['b', '<roh>'], ['c', '']]);
|
||||
expect(() => parseXml('<!DOCTYPE x [<!ENTITY e SYSTEM "file:///etc/passwd">]><p>&e;</p>')).toThrow();
|
||||
expect(() => parseXml('<p><a></p>')).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Plesk-Connector: Lesen', () => {
|
||||
it('erfüllt den Connector-Vertrag', async () => { await runContract(expect as never, mk(createFake()), ctx()); });
|
||||
it('Health mit Version', async () => {
|
||||
expect(await mk(createFake()).healthCheck(ctx())).toMatchObject({ ok: true, version: 'Plesk 18.0.62 (plesk.fake.test)' });
|
||||
const h = await mk(createFake()).healthCheck(ctx({}, 'falsch')); expect(h.ok).toBe(false); expect(h.message).toMatch(/Anmeldung/);
|
||||
});
|
||||
it('normalisiert Abonnements mit Besitzer, Tarif, Zustand, Limits und Nutzung – ohne Geheimnisse', async () => {
|
||||
const list = await mk(createFake()).listResources(ctx());
|
||||
expect(list.map((r) => [r.externalRef, r.state, r.name])).toEqual([['21', 'active', 'alpha.test · alpha'], ['22', 'suspended', 'alpha-shop.test · alpha'], ['23', 'active', 'beta.test · beta'], ['24', 'active', 'admin-intern.test · admin']]);
|
||||
const a = list[0]!;
|
||||
expect(a.details).toMatchObject({ domain: 'alpha.test', username: 'alpha', owner: 'Alpha GmbH', plan: 'Starter', planId: '1', providerStatus: 'aktiv' });
|
||||
expect(a.limits).toMatchObject({ disk_space: 10737418240, traffic: 107374182400, domains: 2, email_accounts: 5, databases: 2 });
|
||||
expect(a.usage).toMatchObject({ disk_space: 524288000, traffic: 1048576, subdomains: 2, email_accounts: 3, databases: 1 });
|
||||
expect(a.validFrom).toBe('2025-03-01T00:00:00.000Z'); expect(a.validUntil).toBeNull();
|
||||
expect(list[1]!.limits!.disk_space).toBeNull(); expect(list[1]!.validUntil).toBe('2027-01-01T00:00:00.000Z'); expect(list[1]!.details!.providerStatus).toBe('vom Administrator gesperrt');
|
||||
expect(JSON.stringify(list)).not.toMatch(/GEHEIM|passwd/i);
|
||||
});
|
||||
it('wiederholt Lesezugriffe bei 503, nie Schreibzugriffe', async () => {
|
||||
const f = createFake(); f.opts.fail503 = 2; expect(await mk(f).listResources(ctx())).toHaveLength(4);
|
||||
});
|
||||
it('Service-Pläne als feste Produktvorlagen', async () => {
|
||||
const items = await mk(createFake()).listCatalog!(ctx());
|
||||
expect(items.map((i) => [i.externalRef, i.name, i.fixed, i.provisioning])).toEqual([['plan:1', 'Starter', true, { planId: 1, planName: 'Starter' }], ['plan:2', 'Business', true, { planId: 2, planName: 'Business' }]]);
|
||||
expect(items[1]!.features).toContain('Speicher: unbegrenzt'); expect(items[0]!.features).toContain('Speicher: 10 GB');
|
||||
});
|
||||
it('Kunden zur Übernahme: je Abonnement mit Kontaktdaten des Besitzers und Tarif', async () => {
|
||||
const list = await mk(createFake()).listCustomers!(ctx());
|
||||
expect(list.map((c) => [c.externalRef, c.displayName, c.planRef, c.state])).toEqual([['21', 'Alpha GmbH · alpha.test', 'plan:1', 'active'], ['22', 'Alpha GmbH · alpha-shop.test', 'plan:2', 'suspended'], ['23', 'Bernd Beta · beta.test', 'plan:1', 'active'], ['24', 'Administrator · admin-intern.test', null, 'active']]);
|
||||
expect(list[0]).toMatchObject({ company: 'Alpha GmbH', firstName: 'Anna', lastName: 'Alpha', email: 'anna@alpha.test', phone: '040 123', address: { street: 'Hafenstr. 1', zip: '20095', city: 'Hamburg', country: 'DE' }, legacyNumber: 'alpha' });
|
||||
expect(list[2]).toMatchObject({ company: null, firstName: 'Bernd', lastName: 'Beta' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('Plesk-Connector: Bereitstellung und Aktionen', () => {
|
||||
it('legt Kunde und Abonnement an (Login kc+Vertragsnummer, Vermerk, Plan), Passwort wird nicht zurückgegeben', async () => {
|
||||
const f = createFake(); const c = mk(f);
|
||||
const { resource } = await c.provision!(ctx(), { params: { planId: 2 }, label: 'x', idempotencyKey: 'job-1', context: PC });
|
||||
expect(loginFor(PC, 'job-1')).toBe('kc30001');
|
||||
expect(resource).toMatchObject({ type: 'hosting_account', state: 'active', name: 'kc30001.kunden.example.test · kc30001', details: { plan: 'Business', username: 'kc30001' } });
|
||||
const cust = f.state.customers.find((x0) => x0.login === 'kc30001')!; expect(cust).toMatchObject({ cname: 'Muster GmbH', pname: 'Max Muster', email: 'max@example.test', description: 'Kundencenter K-10001 V-30001' });
|
||||
expect(JSON.stringify(resource)).not.toMatch(/Zufall-Pw/);
|
||||
const add = f.calls.find((k) => k.op === 'webspace/add')!.body; expect(add).toMatch(/<ip_address>203\.0\.113\.10<\/ip_address>/); expect(add).toMatch(/<plan-name>Business<\/plan-name>/);
|
||||
});
|
||||
it('Wiederholung übernimmt das eigene Konto statt doppelt anzulegen; fremder Login → Konflikt', async () => {
|
||||
const f = createFake(); const c = mk(f);
|
||||
const r1 = await c.provision!(ctx(), { params: { planId: 1 }, label: 'x', idempotencyKey: 'job-1', context: PC });
|
||||
const r2 = await c.provision!(ctx(), { params: { planId: 1 }, label: 'x', idempotencyKey: 'job-1', context: PC });
|
||||
expect(r2.resource.externalRef).toBe(r1.resource.externalRef); expect(f.calls.filter((k) => k.op === 'webspace/add')).toHaveLength(1); expect(f.calls.filter((k) => k.op === 'customer/add')).toHaveLength(1);
|
||||
f.state.customers.push({ id: 999, login: 'kc40001', pname: 'Fremd', description: 'nicht von uns', status: 0 });
|
||||
expect(await code(c.provision!(ctx(), { params: { planId: 1 }, label: 'x', idempotencyKey: 'k', context: { ...PC, contractNumber: 'V-40001' } }))).toBe('CONFLICT');
|
||||
});
|
||||
it('fehlende Bereitstellungs-Einstellungen und unbekannte Pläne werden klar abgelehnt', async () => {
|
||||
const c = mk(createFake());
|
||||
expect(await code(c.provision!(ctx({ ipAddress: '' }), { params: { planId: 1 }, label: 'x', idempotencyKey: 'k', context: PC }))).toBe('BAD_CONFIG');
|
||||
expect(await code(c.provision!(ctx({ subscriptionDomain: 'kein domain' }), { params: { planId: 1 }, label: 'x', idempotencyKey: 'k', context: PC }))).toBe('BAD_CONFIG');
|
||||
expect(await code(c.provision!(ctx(), { params: { planId: 77 }, label: 'x', idempotencyKey: 'k', context: PC }))).toBe('BAD_CONFIG');
|
||||
expect(c.validateProvisioning!({ planId: 'x' })).toMatch(/planId/); expect(c.validateProvisioning!({ planId: 1 })).toBeNull();
|
||||
});
|
||||
it('sperrt/entsperrt (Zielzustand), wechselt den Plan, löscht idempotent', async () => {
|
||||
const f = createFake(); const c = mk(f);
|
||||
expect((await c.execute!(ctx(), { action: 'suspend', externalRef: '21', idempotencyKey: 'a' })).resource!.state).toBe('suspended');
|
||||
expect((await c.execute!(ctx(), { action: 'suspend', externalRef: '21', idempotencyKey: 'a' })).resource!.state).toBe('suspended');
|
||||
expect((await c.execute!(ctx(), { action: 'unsuspend', externalRef: '21', idempotencyKey: 'b' })).resource!.state).toBe('active');
|
||||
expect((await c.execute!(ctx(), { action: 'change_plan', externalRef: '21', params: { planId: 2 }, idempotencyKey: 'c' })).resource!.details!.plan).toBe('Business');
|
||||
await c.execute!(ctx(), { action: 'terminate', externalRef: '23', idempotencyKey: 'd' }); expect(f.state.webspaces.some((w) => w.id === 23)).toBe(false);
|
||||
expect(await code(c.execute!(ctx(), { action: 'terminate', externalRef: '23', idempotencyKey: 'd' }))).toBe('OK');
|
||||
expect(await code(c.execute!(ctx(), { action: 'suspend', externalRef: '999', idempotencyKey: 'e' }))).toBe('NOT_FOUND');
|
||||
expect(await code(c.execute!(ctx(), { action: 'extend', externalRef: '21', idempotencyKey: 'f' }))).toBe('UNSUPPORTED');
|
||||
});
|
||||
it('Passwort des Besitzers neu setzen; Abonnements des Admins sind ausgenommen', async () => {
|
||||
const f = createFake(); const c = mk(f);
|
||||
await c.execute!(ctx(), { action: 'reset_password', externalRef: '23', secrets: { password: 'NeuesPasswort1' }, idempotencyKey: 'p' });
|
||||
expect(f.state.customers.find((x0) => x0.id === 12)!.passwd).toBe('NeuesPasswort1');
|
||||
expect(JSON.stringify(f.calls.map((k) => k.op))).not.toMatch(/NeuesPasswort/);
|
||||
expect(await code(c.execute!(ctx(), { action: 'reset_password', externalRef: '24', secrets: { password: 'NeuesPasswort1' }, idempotencyKey: 'p' }))).toBe('UNSUPPORTED');
|
||||
expect(await code(c.execute!(ctx(), { action: 'reset_password', externalRef: '23', secrets: { password: 'kurz' }, idempotencyKey: 'p' }))).toBe('INVALID_INPUT');
|
||||
});
|
||||
it('Panel-Login als Einmal-Sitzung des Besitzers', async () => {
|
||||
const f = createFake(); const r = await mk(f).loginUrl!(ctx(), '22');
|
||||
expect(r.url).toMatch(/^https:\/\/plesk\.test:8443\/enterprise\/rsession_init\.php\?PLESKSESSID=sess\d+abcdef$/); expect(f.state.sessions[0]).toMatch(/^alpha:/);
|
||||
expect(await code(mk(f).loginUrl!(ctx(), '24'))).toBe('UNSUPPORTED');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Plesk-Connector: Unterobjekte (nur lesen, nur eigenes Abonnement)', () => {
|
||||
it('Domains, Postfächer, Datenbanken und FTP des Abonnements', async () => {
|
||||
const c = mk(createFake());
|
||||
expect((await c.children!.list(ctx(), '21', 'domain')).map((d) => [d.name, d.details.subdomain, d.details.main])).toEqual([['alpha.test', false, true], ['blog.alpha.test', true, false], ['alpha-zwei.test', false, false]]);
|
||||
expect((await c.children!.list(ctx(), '21', 'email')).map((m) => [m.name, m.state, m.details.maxSizeBytes])).toEqual([['info@alpha.test', 'active', 1073741824], ['post@alpha-zwei.test', 'disabled', null]]);
|
||||
expect((await c.children!.list(ctx(), '21', 'database')).map((d) => d.name)).toEqual(['alpha_wp']);
|
||||
expect((await c.children!.list(ctx(), '21', 'ftp')).map((d) => d.name)).toEqual(['alpha_dev']);
|
||||
const all = JSON.stringify(await c.children!.list(ctx(), '23', 'email')); expect(all).toMatch(/bernd@beta\.test/); expect(all).not.toMatch(/alpha|GEHEIM/);
|
||||
expect(await code(c.children!.act(ctx(), { parentRef: '21', kind: 'email', op: 'create', data: {}, idempotencyKey: 'x' }))).toBe('UNSUPPORTED');
|
||||
expect(await code(c.children!.list(ctx(), '../21', 'domain'))).toBe('NOT_FOUND');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Plesk-Connector: Konfiguration und Fehler', () => {
|
||||
it('prüft Adresse und Schlüssel', async () => {
|
||||
expect(await code(mk(createFake()).listResources(ctx({ baseUrl: 'http://plesk.test:8443' })))).toBe('BAD_CONFIG');
|
||||
expect(await code(mk(createFake()).listResources({ ...ctx(), secrets: { apiKey: 'mit leerzeichen' } }))).toBe('BAD_CONFIG');
|
||||
expect(await code(mk(createFake()).listResources(ctx({}, 'falsch')))).toBe('AUTH_FAILED');
|
||||
expect(await code(mk(createFake()).listResources(ctx({ baseUrl: 'https://plesk.test:8443/enterprise/control/agent.php' })))).toBe('OK');
|
||||
});
|
||||
it('sendet den Secret Key nur im Header KEY', async () => {
|
||||
const f = createFake(); await mk(f).listResources(ctx());
|
||||
expect(f.calls.every((k) => k.key === 'test-secret' && !k.body.includes('test-secret'))).toBe(true);
|
||||
});
|
||||
});
|
||||
1
packages/connector-plesk/tsconfig.json
Normal file
1
packages/connector-plesk/tsconfig.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{ "extends": "../../tsconfig.base.json", "compilerOptions": { "rootDir": "src", "outDir": "dist", "declaration": true }, "include": ["src"] }
|
||||
|
|
@ -14,6 +14,7 @@
|
|||
"@kc/connector-keyhelp": "workspace:*",
|
||||
"@kc/connector-licensing": "workspace:*",
|
||||
"@kc/connector-mock": "workspace:*",
|
||||
"@kc/connector-plesk": "workspace:*",
|
||||
"@kc/connector-sdk": "workspace:*",
|
||||
"@kc/platform": "workspace:*"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { ACTION_CAPABILITY, ConnectorError, DESTRUCTIVE_ACTIONS, type ActionName
|
|||
import { licensingConnector } from '@kc/connector-licensing';
|
||||
import { mockConnector } from '@kc/connector-mock';
|
||||
import { keyhelpConnector } from '@kc/connector-keyhelp';
|
||||
import { pleskConnector } from '@kc/connector-plesk';
|
||||
import { audit } from '@kc/platform/audit';
|
||||
import { decrypt, encrypt } from '@kc/platform/crypto';
|
||||
import { one, query, run } from '@kc/platform/db';
|
||||
|
|
@ -11,7 +12,7 @@ import { addMonths } from '@kc/platform/contractterms';
|
|||
import { CONTRACT_MACHINE, ORDER_MACHINE, transition } from '@kc/platform/statemachine';
|
||||
|
||||
/** Registry: neue Connectoren (KeyHelp, Plesk, …) werden hier eingetragen, sonst nirgends. */
|
||||
const registry = new Map<string, Connector>([licensingConnector, keyhelpConnector, mockConnector].map((c) => [c.key, c]));
|
||||
const registry = new Map<string, Connector>([licensingConnector, keyhelpConnector, pleskConnector, mockConnector].map((c) => [c.key, c]));
|
||||
export const listConnectors = (): Connector[] => [...registry.values()];
|
||||
export const getConnector = (key: string): Connector => {
|
||||
const c = registry.get(key);
|
||||
|
|
|
|||
22
pnpm-lock.yaml
generated
22
pnpm-lock.yaml
generated
|
|
@ -194,6 +194,25 @@ importers:
|
|||
specifier: ^5.0.2
|
||||
version: 5.0.2(@types/node@26.6.3)(vite@8.3.1(@types/node@26.6.3)(esbuild@0.28.2)(tsx@4.23.15))
|
||||
|
||||
packages/connector-plesk:
|
||||
dependencies:
|
||||
'@kc/connector-sdk':
|
||||
specifier: workspace:*
|
||||
version: link:../connector-sdk
|
||||
undici:
|
||||
specifier: ^8.11.2
|
||||
version: 8.11.2
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^26.6.3
|
||||
version: 26.6.3
|
||||
typescript:
|
||||
specifier: ^7.0.2
|
||||
version: 7.0.2
|
||||
vitest:
|
||||
specifier: ^5.0.2
|
||||
version: 5.0.2(@types/node@26.6.3)(vite@8.3.1(@types/node@26.6.3)(esbuild@0.28.2)(tsx@4.23.15))
|
||||
|
||||
packages/connector-sdk:
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
|
|
@ -217,6 +236,9 @@ importers:
|
|||
'@kc/connector-mock':
|
||||
specifier: workspace:*
|
||||
version: link:../connector-mock
|
||||
'@kc/connector-plesk':
|
||||
specifier: workspace:*
|
||||
version: link:../connector-plesk
|
||||
'@kc/connector-sdk':
|
||||
specifier: workspace:*
|
||||
version: link:../connector-sdk
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue