27 Commits

Author SHA1 Message Date
Prophet731
27cbe40c52 chore(release): 1.5.0
Some checks failed
Publish Release / release (push) Failing after 16s
Major client-area overhaul, WHMCS 9 + VirtFusion v7 compatibility, and a
hardening pass on every destructive client.php endpoint.

Tested against WHMCS 9.0.3 + VirtFusion v7.0.0 Build 9.

Features
- "On This Page" jump-link group injected into the WHMCS Actions sidebar
  via ClientAreaPrimarySidebar; auto-hides links for hidden panels.
- Monthly traffic chart (last 12 months) with rx/tx bars and centered
  legend; replaces the dead canvas that read non-existent JSON paths.
- Live Stats panel: CPU, memory, disk I/O from remoteState; 30s refresh
  while the panel is visible AND the page has focus.
- Filesystem usage rows in the Resources panel from qemu-guest-agent
  fsinfo; pseudo-FS filtered out.
- Server Overview meta chips: data-center location with country flag,
  OS template/agent name with kernel on hover, "Created N days ago".
- Hypervisor maintenance banner at the top of the page.
- Mask Sensitive screenshot mode: IPv4 keeps first two octets, IPv6
  keeps first two hextets, hostnames keep first char per dot-label.
  Inputs masked via text-security: disc; covers Server Name + Hostname
  + IP cells + rDNS panel rows.
- Per-IP copy buttons folded into the Server Overview cells (replaces
  the deleted standalone Network panel).
- VNC viewer popup served from a same-origin authenticated route
  (client.php?action=vncViewer) — POST + requireSameOrigin, rotates
  the wss token on every open, X-Frame-Options DENY, strict CSP.

Bug Fixes
- UsageUpdate cron silently no-op'd: read server.usage.traffic.used
  which doesn't exist. Bandwidth now from /servers/{id}/traffic;
  disk usage from remoteState.agent.fsinfo.
- WHMCS 9 multi-service order short-circuit: AfterModuleCreate's
  AcceptOrder fired after the first service and terminated the batch
  loop, orphaning siblings. Defer until every VF service in the order
  has a server_id.
- Orphaned services produced six generic 500s; new
  requireProvisionedService() helper emits one clean 409 with an
  actionable message. Wired into all 17 client.php cases.
- Server Overview Traffic showed "- / Unlimited"; now renders real
  bytes and "Unmetered" (limit=0 is per-period uncapped, not feature-off).
- Rename endpoint moved to PUT /servers/{id}/modify/name in VF v7
  (was 404'ing); response is HTTP 201 not 200/204.
- Rename was force-lowercasing the input; relaxed validation to
  preserve case + freeze the input row mid-flight to prevent
  double-submits.
- "Other" OS category icon override removed; uses VirtFusion's icon
  instead of a hardcoded SVG.
- Save button squish on the rename row fixed via flex-wrap layout.

Security
- CSRF protection (requirePost + requireSameOrigin) added to every
  destructive POST: rebuild, resetPassword, resetServerPassword,
  powerAction, rename, selfServiceAddCredit, toggleVnc, vncViewer.
  Previously only rdnsUpdate had it.
- Open-redirect defence in Module::fetchLoginTokens — refuses to
  return a redirect URL whose host doesn't match the configured VF
  panel hostname.
- Per-action rate limiting via new Module::requireRateLimit helper
  (Cache-backed): rebuild 60s, resetPassword/resetServerPassword 30s,
  powerAction 10s, vncViewer/toggleVnc/selfServiceAddCredit 5s.
- vncViewer route delivers strict Content-Security-Policy
  (default-src none, script-src self + VF panel, connect-src wss VF
  panel, frame-ancestors none).
- IPv6 examples in placeholder/comments switched to the IANA
  documentation prefix 2001:db8::/32 (RFC 3849).

Removed
- Network panel (duplicated Server Overview IP rows).
- VNC enable/disable toggle (VF firewall flag is non-functional;
  toggle was misleading).
- Network Speed row in Resources panel (always 0 from VF API).

Internal
- Module::fetchServerData now passes ?remoteState=true.
- ServerResource::process exposes osName/osPretty/osKernel/osDistro/
  osIcon/location/locationIcon/hypervisorMaintenance/createdAt/
  builtAt/live.* fields.
- Module::toggleVnc corrected to send {vnc:bool} (the actual API
  param) instead of {enabled:bool} (silent no-op).
- Module::getVncConsole + toggleVnc return baseUrl alongside the
  envelope so the viewer route can build the wss URL.
- Panel margins tightened mb-3 → mb-2 across all 11 panels.
2026-04-28 22:07:27 -04:00
Prophet731
7825f6be80 chore(release): 1.4.4
Some checks failed
Publish Release / release (push) Failing after 17s
2026-04-26 02:47:50 -04:00
Prophet731
1e0a1308bf fix(install): clear "TMP: unbound variable" + non-zero exit on cleanup
The cleanup `trap 'rm -rf "$TMP"' EXIT` referenced a `local TMP` from
inside cmd_sync(). EXIT traps fire when the shell exits, not when the
function returns — by then the function-local was out of scope, and
set -u exploded the trap body with "TMP: unbound variable", which
masked the script's true exit status with 1.

The install/upgrade work itself completed before the trap ran (so it
looked cosmetic), but the non-zero exit broke automated wrappers and
cron jobs that check $?.

Two changes, both small:

  1. Drop `local` so TMP persists at script scope through the EXIT
     trap.
  2. Use `${TMP:-}` in the trap body so any future regression that
     tightens TMP's scope (or adds a code path where TMP is never
     assigned) doesn't re-introduce the same explosion.

Verified with `bash -c 'set -euo pipefail; foo() { local TMP;
TMP=$(mktemp -d); trap "rm -rf \$TMP" EXIT; }; foo'` → reproduces
the original error; the patched form is silent and exits 0.
2026-04-26 02:47:50 -04:00
Prophet731
8caf8c0c01 chore(release): 1.4.3
Some checks failed
Publish Release / release (push) Failing after 17s
2026-04-26 02:42:32 -04:00
Prophet731
589442e59c docs: rewrite install/upgrade sections around install.sh script
Features the install script as the primary path for both install and
upgrade — with both curl and wget examples for the piped form. Adds
a `check` invocation in the upgrade section showing how to query
installed-vs-latest without making changes.

The manual rsync recipes are preserved in collapsible <details> blocks
for users who'd rather not pipe a script to bash. Both manual recipes
also gain the same ownership-preservation treatment via `stat -c
'%U:%G'` + rsync `--chown="$OWNER"`, so even the manual path no
longer leaves files owned by root:root.
2026-04-26 02:42:29 -04:00
Prophet731
c90cbd7399 fix(ci): force-publish releases as non-draft + latest
softprops/action-gh-release@v2 has a long-standing intermittent bug
where it creates the release as a draft and silently fails to flip the
draft→published step, even though it logs "🎉 Release ready" and the
job exits successfully. v1.4.0, v1.4.1, and v1.4.2 all shipped as
drafts because of this — meaning the GitHub `releases/latest` API
returned v1.3.0, the documented install snippets and the new install.sh
would both download v1.3.0, and admins running the upgrade flow would
never actually get the storage-type-code fix.

Two changes:

  1. Pass `make_latest: 'true'` to the action so a successful create
     also explicitly marks the release as latest (when the action is
     working correctly).
  2. Add an unconditional follow-up step `gh release edit --draft=false
     --latest` that runs whenever the create step ran. If the action
     already published correctly, this is a no-op. If it failed to
     flip, we recover.

Token + variables go through `env:` blocks (not interpolated inline
into `run:`) to match the workflow injection guidance the rest of the
file already follows.

v1.4.0/1/2 were manually re-published with `gh release edit` as a
one-off cleanup; this fix prevents the same situation from recurring.
2026-04-26 02:42:21 -04:00
Prophet731
bb12cae954 feat: add install.sh helper for ownership-preserving install/upgrade
Single-file POSIX bash script with three subcommands:

  install   First-time install. Refuses to overwrite an existing one.
  upgrade   Refresh existing install. Refuses if nothing's installed yet.
  check     Report installed version vs latest. No changes. Exit 0/1/2
            for current/outdated/not-installed (handy for cron-driven
            update monitoring).

Solves the long-standing "module installed but invisible in WHMCS" trap:
when admins ran the documented `git clone | rsync` recipe as root, the
new files landed as root:root and the WHMCS web user couldn't read
them. The script reads the parent dir's owner via `stat -c '%U:%G'` and
applies it via rsync `--chown`, so a `sudo bash` install ends up with
correct ownership automatically.

Other niceties:

  - --version v1.4.1   pin a specific tag (default: latest published)
  - --with-addon       also sync modules/addons/VirtFusionDns
  - Backs up + restores config/ConfigOptionMapping.php across the
    rsync --delete (the old docs warned about this; the script just
    handles it).
  - Writes .installed-version marker so `check` can report current state.
  - Pipeable via curl OR wget — both forms documented in the script
    header for ad-hoc piped invocations.
2026-04-26 02:42:08 -04:00
Prophet731
5249d6bc19 chore(release): 1.4.2
All checks were successful
Publish Release / release (push) Successful in 16s
2026-04-26 02:27:51 -04:00
Prophet731
3ea21dfb60 docs: switch install/upgrade instructions to release tarballs
Replaces the `git clone` of main with a GitHub release-tarball fetch.
Defaults to the latest published release (resolved live via the GitHub
API) and accepts a `VERSION=vX.Y.Z` override for pinning to a specific
release or rolling back. Only depends on curl/sed/tar/rsync — no jq,
gh CLI, or git client required.

Cloning main was a footgun: anyone who ran the install snippet between
v1.4.0 and the v1.4.1 fix would have shipped the qty-zeroing storage
matcher even though the documented "stable" version was v1.4.0. Pulling
release tarballs aligns what the docs say with what the user actually
gets.
2026-04-26 02:27:48 -04:00
Prophet731
fecbf701b7 chore(release): 1.4.1
All checks were successful
Publish Release / release (push) Successful in 17s
2026-04-26 02:21:48 -04:00
Prophet731
02e059274b docs: clarify storage type-code matching in stock control
The stock-control safety bullets and algorithm description called
`primaryStorageProfile` a "profile id" matched against `otherStorage[].id`.
That mirrored the buggy implementation rather than the actual VirtFusion
contract: it's a storage *type code* (mirrors `server_packages.storage_type`)
that filters against `otherStorage[].storageType`. Updated CLAUDE.md and
README.md so future readers don't repeat the bug. Also documents the new
behavior of walking all matching pools and picking the largest fit, with
disabled peers skipped rather than treated as fatal.

The `storageProfile` mapping table row is intentionally left untouched —
that documents an admin-facing configurable-option alias, and renaming it
could quietly invalidate existing operator setups.
2026-04-26 02:21:45 -04:00
Andrew
e9772ed29f Merge pull request #7 from EZSCALE/fix/storagetype-not-id
fix(StockControl): match storageType code instead of pool id
2026-04-25 23:48:14 -04:00
Prophet731
a3c4154fb2 fix(StockControl): match storageType code instead of pool id
The package field exposed by VirtFusion as `primaryStorageProfile` is a
storage *type code* (mirrors `server_packages.storage_type` in the VF
database), not a profile id. It's meant to filter to any pool whose
`storageType` matches — multiple pools across the fleet can carry the
same code, which is exactly how multi-hypervisor placement works for
mountpoint/datastore storage.

`capForStorage()` was checking `pool.id` against this code. Pool ids are
unique per hypervisor (e.g. for the same logical mountpoint on three
hypervisors, ids 23/28/30) and almost never match the type-code domain
(0=local default, 4=mountpoint, etc.). The mismatch silently returned 0
for every hypervisor, zeroing qty fleet-wide whenever the package's
type code didn't accidentally collide with some pool id.

Symptoms in the wild: every stock-controlled VPS product showed qty=0
in WHMCS even with abundant memory/CPU/IPv4 capacity. Disabling
`stockcontrol` on the product or removing `primaryStorageProfile` from
the package were the only known workarounds; both lose the actual stock
gating this module is meant to provide.

Fix:
- Match `pool.storageType` instead of `pool.id`.
- Walk all pools that match (a hypervisor may have multiple pools of
  the same type) and use the one that fits the most VMs, instead of
  short-circuiting on the first match. A disabled pool no longer kills
  the whole hypervisor's capacity for that type — we just skip it and
  keep looking for an enabled peer.
- Rename the parameter from `$profileId` to `$storageTypeId` so future
  readers don't fall into the same naming trap. Updated the docblock
  with a NOTE explaining the VirtFusion-side naming inconsistency.

Verified on a 3-hypervisor cluster with `storageType=4` (mountpoint)
packages: qty went from 0/0/0/0/0/0/0/0 to 66/32/15/7/3/1/32/15 across
the VPS-1 through VPS-32 + storage products without any other config
change.
2026-04-26 03:38:33 +00:00
Prophet731
cece1f5ae0 docs(readme): document stock control + order auto-accept features 2026-04-24 12:21:54 -04:00
Prophet731
f4d6b06203 chore(release): 1.4.0
All checks were successful
Publish Release / release (push) Successful in 17s
2026-04-24 12:14:26 -04:00
Prophet731
1f09671fee feat(stock): dynamic VPS inventory driven by live hypervisor capacity
Opt-in per product via WHMCS's native tblproducts.stockcontrol toggle.
When enabled, the module overwrites tblproducts.qty with the number of
VPSes the panel can still actually provision, derived from two
authoritative sources:

  - GET /packages/{id} for the per-VPS resource footprint (memory,
    cpuCores, primaryStorage, primaryStorageProfile, enabled)
  - GET /compute/hypervisors/groups/{id}/resources for live
    free/allocated data per hypervisor in the group

Algorithm sums min(memory, cpu, storage) across eligible hypervisors
(enabled AND commissioned AND !prohibit) for every group the product
can be placed in (default configoption1 plus every numeric value of a
Location configurable option), capped by the group-level IPv4 pool
taken as max() within a group to avoid double-counting. Storage
matching is strict against package.primaryStorageProfile; hypervisors
without the named pool contribute 0.

FAIL-SAFE INVARIANT: transient API failures return null from
Module::fetchPackage / Module::fetchGroupResources, and the orchestrator
leaves tblproducts.qty UNCHANGED in that case. Confirmed-missing
conditions (HTTP 404, package.enabled=false) return qty=0. Without this
tri-state contract the module would either zero out inventory during
API blips, or show inventory for packages that have been deleted.

Triggers:
  - AfterModuleCreate: refresh + auto-accept pending order
  - AfterModuleTerminate: refresh (capacity came back)
  - AfterCronJob: every-2-hour safety net for out-of-band panel changes
  - ClientAreaPageCart: opportunistic per-product refresh in order flow
  - admin.php?action=stockRecalculate: on-demand full recalc

Shared 30s rate-limit (stockrefresh:event) coalesces provision bursts;
60s per-product limit (stockrefresh:{pid}) caps cart-page refreshes;
grpres:{id} 120s TTL caps upstream API reads per group regardless of
how often hooks fire.

Auto-accept: AfterModuleCreate calls WHMCS AcceptOrder with
autosetup=false when the parent order is still Pending. Idempotent;
already-accepted orders are skipped via strcasecmp status check.

New per-product config option stockSafetyBufferPct (configoption7,
default 10) reserves X% of each resource's max before computing fits.
Blank falls back to 10% so existing products get headroom without any
config change. Ignored for unlimited resources (max=0) and for IPv4
(no per-hypervisor max in the response).

TestConnection now probes /compute/hypervisors/groups to surface
missing compute:read scope at config time instead of as unexplained
nightly silence.
2026-04-24 12:14:26 -04:00
Andrew
6ae3ab55a9 Merge pull request #6 from EZSCALE/Prophet731-patch-1
Add Contributor Covenant Code of Conduct
2026-04-17 22:18:51 -05:00
Andrew
0c913110cc Add Contributor Covenant Code of Conduct 2026-04-17 23:17:44 -04:00
Prophet731
3239b511bd chore(release): 1.3.0
All checks were successful
Publish Release / release (push) Successful in 7s
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 22:05:05 -04:00
Prophet731
c1c579dd14 feat(addon): Diagnose-an-IP tool + actionable auth-error messages
Two complementary improvements for operators debugging a misconfigured
addon — both motivated by a live production incident where "every IP
shows no zone" took several hypotheses (wrong serverId, wrong key,
stale cache) before landing on the real cause.

1. Diagnose-an-IP panel on the addon admin page (VirtFusionDns.php
   _output()). Takes an IP in a text input and runs the full pipeline
   inline: prints the current config snapshot, forces a fresh zone
   list from PowerDNS (bypassing cache), shows the computed PTR name,
   shows what IpUtil::findZoneAndPtrName selects, and fetches the
   current PTR content. Every common failure mode — wrong key, wrong
   serverId, forgotten zone, mis-aligned RFC 2317 label, stale cache
   — produces a distinctive shape in that output.

2. More actionable error messages in PowerDns\Client::ping():

   - On 401/403: now spells out the three real causes (API key
     mismatch, api-allow-from excluding the WHMCS IP, whitespace in
     the stored key) as a checklist, so the operator doesn't have to
     guess which they're hitting.

   - On 404: explicitly names serverId as the field to check and
     reminds that "localhost" is the PowerDNS API server identifier,
     NOT the nameserver's hostname (a surprisingly common misreading
     of the field label).

The addon helper virtfusiondns_load_server_libs() now also pulls in
Resolver + PtrManager lazily since the diagnostic pane needs IpUtil's
pipeline-level output. They're optional — missing files don't break
the basic status page.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 22:04:42 -04:00
Prophet731
7e7f3c1c14 feat(ipv6): surface /64 subnet allocations with custom-host PTR flow
VirtFusion's IPv6 allocation model routes a whole /64 to the VPS rather
than exposing discrete host addresses via the API. The previous module
silently filtered these entries — the client saw v4 IPs in the rDNS
panel but no v6 at all, with no indication why, and no way to set a
PTR for a specific address they were using inside the /64.

This commit surfaces subnets as first-class entries throughout:

- IpUtil::extractIps() now returns {addresses, subnets, skipped}. The
  subnets bucket carries {subnet, cidr} pairs for any v6 allocation
  with cidr != 128; /128 entries continue to be treated as discrete
  addresses, and genuinely malformed entries still go to skipped.

- IpUtil::ipv6InSubnet($ip, $prefix, $cidrBits) — new helper that does
  binary-prefix subnet containment via inet_pton + bit masking. Used
  for v6 ownership verification (see below).

- PtrManager::listPtrs() emits subnet-only rows ahead of per-IP rows,
  so the client UI can render the /64 as an informational anchor with
  an entry point for the custom-host flow.

- client.php::rdnsUpdate adds a second ownership-check stage: if the
  submitted IP is v6 AND doesn't match any discrete address, check
  whether it falls inside one of the server's allocated subnets. This
  preserves "only your own IPs" while unlocking the feature.

- Client-side (module.js / module.css) renders subnet rows with a
  collapsible "Add host PTR" form (IP + hostname inputs) that posts
  to the same rdnsUpdate endpoint. Subnet rows get a distinct cyan
  accent so they visually differ from per-host rows.

The usual guards still apply to v6 custom-host writes: forward-DNS
(FCrDNS) verification, PTR regex, per-IP rate limit, same-origin /
POST-method gates. Nothing about the security envelope changes — only
what input is accepted as "you own this IP".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 22:04:23 -04:00
Prophet731
daaddc7c24 fix(powerdns): prevent decrypt() garbage from corrupting plaintext API keys
WHMCS's addon-module password-type fields are stored plaintext in
tbladdonmodules.value — unlike tblservers.password which IS encrypted
at rest. Config::get() was blindly calling decrypt() on the raw value
and then preferring its output over raw when the two differed.

Unfortunately, when decrypt() is fed a plaintext string, it doesn't
return empty or unchanged — it returns a short binary-garbage string
(observed: 4 bytes of \xEF\xBF\xBD unicode-replacement noise for a
32-char plaintext). That garbage then went into the X-API-Key header,
PowerDNS responded 401, and every rDNS read returned an empty zone list,
surfacing as "no zone" for every IP in the client UI.

Fix: only accept decrypt()'s output when it's printable ASCII. Real
API keys are always printable; decrypted ciphertext that looks like
binary is a mangled-plaintext signal, so we fall back to raw. Also
trim() the chosen value to defeat a second foot-gun — admin UIs can
silently append a newline on paste, which would land in the header
verbatim and produce the same 401.

Diagnosed via direct WHMCS tbladdonmodules inspection on a user's
affected install; confirmed the fix end-to-end with a live ping()
returning HTTP 200 post-deploy.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 22:04:04 -04:00
Prophet731
65f3f36569 ci: generate proper release notes from CHANGELOG with commit-log fallback
Previous workflow dumped every commit subject since the last tag as raw
bullets — no grouping, no structure, and it overwrote hand-edited release
bodies on every re-push.

New strategy, in order of preference:

  1. Extract the "## [X.Y.Z]" section from CHANGELOG.md and use it as the
     release body. Maintainers already write structured notes there
     (Features / Bug Fixes / Documentation per Keep-a-Changelog); this
     flows them to GitHub with zero re-typing.

  2. If CHANGELOG.md has no matching section, fall back to grouping the
     commit range by conventional-commit prefix:
       feat:     → Features
       fix:      → Bug Fixes
       refactor: → Changes
       docs:     → Documentation
       other    → Other
     Automated "chore(release):" bumps are filtered out (they're noise in
     a release the reader is already viewing).

  3. Append a "Full Changelog" compare link at the bottom when a previous
     tag exists.

Retag safety: the workflow now checks the current release body before
regenerating. If a body is already present (manual edit), it's preserved
instead of being clobbered by a force-pushed tag. To intentionally
regenerate: `gh release edit vX.Y.Z --notes ""` then re-push the tag.

Security: all ${{ ... }} interpolation flows through `env:` blocks rather
than inline into `run:` commands. Shell scripts reference those env vars
with $VAR, which is immune to the command-injection pattern documented at
https://github.blog/security/vulnerability-research/how-to-catch-github-actions-workflow-injections-before-attackers-do/

Also switched to fetch-depth: 0 on checkout so `git describe --tags` can
find the previous tag (default fetch-depth: 1 has no tag history).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 21:36:46 -04:00
Prophet731
a1406f8193 docs(readme): factor install path into $WHMCS variable
All checks were successful
Publish Release / release (push) Successful in 7s
Both the Installation and Upgrading snippets previously hardcoded
/path/to/whmcs in multiple places, so a user copying the command had to
find-and-replace the placeholder twice (install) or three times (upgrade
with the addon). Set WHMCS=/path/to/whmcs once at the top of each snippet
and reference "$WHMCS/..." in every rsync destination instead — single
substitution point, less room for typos.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 21:27:49 -04:00
Prophet731
a2ffb7d53a chore(release): 1.2.0
All checks were successful
Publish Release / release (push) Successful in 7s
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 21:09:10 -04:00
Prophet731
8a88862364 docs: add design-rationale commentary to core support classes
Enriches class-level docblocks and inline comments across the shared
utility classes with the "why" behind design decisions that aren't
obvious from reading the code alone:

- Cache       two-tier rationale, atomic-write semantics, failure modes
- Curl        single-use-per-instance rationale, default option choices
- Log         wrapper rationale, redaction expectations for callers
- Database    auto-migration philosophy, schema-versioning approach
- ServerResource  flat-array rationale, interfaces[0]-only limit called
              out for future maintainers, unit-conversion map
- ConfigureService  why a sibling of ModuleFunctions, catalogue caching
              policy, cp-in-constructor reasoning

Pure documentation — no code changes, all files remain lint-clean and
Pint-formatted.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 21:08:37 -04:00
Prophet731
ad85439dfb feat: add PowerDNS reverse DNS (PTR) integration
Introduces an opt-in reverse DNS management subsystem backed by a PowerDNS
Authoritative HTTP API. Runs via a companion WHMCS addon module
(modules/addons/VirtFusionDns) that holds settings and a Test Connection
page; the server module reads those settings from tbladdonmodules and
short-circuits when the addon is absent or disabled, so provisioning is
unaffected for operators who don't use the feature.

Lifecycle hooks:
- createAccount creates PTRs for every assigned IP (forward DNS must
  already resolve to the IP — FCrDNS enforcement)
- renameServer updates only PTRs whose content matched the old hostname,
  preserving client-custom records
- terminateAccount deletes all PTRs before the local state is purged
- TestConnection merges PowerDNS health check with the existing VirtFusion
  check
- A DailyCronJob hook reconciles missing PTRs additive-only (never
  overwrites)

Client UI: new "Reverse DNS" panel on the service overview with one
editable PTR input per assigned IP, per-row status badges, and
forward-DNS rejection on save. Admin services tab gets a parallel
widget with Reconcile (additive) and Reconcile (force reset) buttons.

New subsystem at lib/PowerDns/:
- Client.php    PowerDNS API wrapper (X-API-Key, listZones/getZone/
                patchRRset/notifyZone), auto-NOTIFY on successful PATCH
- Config.php    Loads + decrypts addon settings from tbladdonmodules
- IpUtil.php    PTR-name generation (IPv4 + IPv6), zone matching,
                RFC 2317 classless parsing
- Resolver.php  FCrDNS verification via dns_get_record with CNAME-chain
                following and per-(hostname,ip) caching
- PtrManager.php Orchestrator: syncServer, deleteForServer, listPtrs,
                setPtr, reconcile, reconcileAll

Security hardening helpers added to Module and applied to the rDNS
endpoints:
- requirePost()           HTTP method gate (405 on non-POST mutations)
- requireSameOrigin()     Origin/Referer check against WHMCS host (CSRF
                          defence against cross-site form POST)
- requireServiceStatus()  tblhosting.domainstatus filter (Active for
                          writes, Active+Suspended for reads)

RFC 2317 classless delegations (e.g. 64/64.113.0.203.in-addr.arpa.)
supported with alignment validation: rejects misaligned start addresses
that don't correspond to any real delegation boundary.

PowerDNS zone IDs containing '/' are URL-encoded as '=2F' per the
PowerDNS API convention. PATCH success triggers PUT /zones/{id}/notify
so slaves pick up the SOA-bumped serial immediately.

Includes IPv4 + IPv6 support, per-IP write rate limit (10s), fresh
IP-ownership re-verification on every client write (defends against
stale-ownership after IP reassignment), and audit logging of every
successful edit to the WHMCS module log.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 21:08:22 -04:00
29 changed files with 7491 additions and 393 deletions

View File

@@ -1,43 +1,189 @@
name: Publish Release name: Publish Release
# -----------------------------------------------------------------------------
# Release-notes strategy (in order of preference):
#
# 1. If CHANGELOG.md has a "## [X.Y.Z] - YYYY-MM-DD" section matching the
# tag version, use that section verbatim. This is the normal path —
# maintainers write release notes once in CHANGELOG and they flow to
# GitHub automatically with no re-typing.
#
# 2. Otherwise, fall back to grouping the commits in the tag range by
# conventional-commit prefix (feat / fix / refactor / docs / other).
# Keeps releases useful even if the maintainer forgot the CHANGELOG.
#
# 3. Append a compare link (PREV_TAG...TAG) at the bottom so readers can
# dive into the full diff in one click.
#
# Retag safety:
# When a tag is force-pushed (e.g. to fix a last-minute doc error), the
# workflow normally would overwrite any hand-edited release body. We guard
# against that by checking the current release body BEFORE running the
# generator — if a body is already present, we leave it alone. To
# intentionally regenerate, clear the body first via:
# gh release edit vX.Y.Z --notes ""
#
# Security note:
# All ${{ ... }} interpolation in this file flows through `env:` blocks
# rather than inline in `run:` commands. Shell scripts reference those
# env vars with $VAR, which is immune to the command-injection pattern
# that hits workflows interpolating untrusted event data directly.
# -----------------------------------------------------------------------------
on: on:
push: push:
tags: tags:
- 'v*' - 'v*'
permissions:
contents: write
jobs: jobs:
release: release:
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
contents: write
steps: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@v4
with:
# Need full history for `git describe` to find the previous tag and
# for `git log PREV..HEAD` to enumerate commits in the release range.
fetch-depth: 0
- name: Extract tag name - name: Derive versions
id: tag id: version
run: echo "version=${GITHUB_REF#refs/tags/}" >> "$GITHUB_OUTPUT" env:
REF: ${{ github.ref }}
run: |
TAG="${REF#refs/tags/}"
VERSION="${TAG#v}"
# Previous tag for compare link + commit range. Empty on first release.
PREV_TAG=$(git describe --tags --abbrev=0 "$TAG^" 2>/dev/null || echo "")
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
echo "prev_tag=$PREV_TAG" >> "$GITHUB_OUTPUT"
echo "Tag: $TAG Version: $VERSION Previous: ${PREV_TAG:-<none>}"
- name: Check for existing release body
id: existing
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.version.outputs.tag }}
REPO: ${{ github.repository }}
run: |
# If the release already has a non-empty body, skip generation so
# hand-edits survive tag re-pushes. Fresh releases (no body) proceed.
BODY=$(gh release view "$TAG" --repo "$REPO" --json body -q .body 2>/dev/null || echo "")
if [ -n "$(printf '%s' "$BODY" | tr -d '[:space:]')" ]; then
echo "Existing release body detected — preserving manual edits."
echo "skip=true" >> "$GITHUB_OUTPUT"
else
echo "No existing body (or empty) — will generate."
echo "skip=false" >> "$GITHUB_OUTPUT"
fi
- name: Generate release notes - name: Generate release notes
id: notes if: steps.existing.outputs.skip != 'true'
env:
VERSION: ${{ steps.version.outputs.version }}
TAG: ${{ steps.version.outputs.tag }}
PREV_TAG: ${{ steps.version.outputs.prev_tag }}
REPO: ${{ github.repository }}
run: | run: |
# Get previous tag set -eo pipefail
PREV_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
if [ -n "$PREV_TAG" ]; then # --- 1. Try extracting the section from CHANGELOG.md --------------
NOTES=$(git log --pretty=format:"- %s" "$PREV_TAG"..HEAD) # Matches "## [1.2.0] ..." exactly and prints every line up to the
else # next "## [" heading or EOF.
NOTES=$(git log --pretty=format:"- %s") CHANGELOG_SECTION=""
if [ -f CHANGELOG.md ]; then
CHANGELOG_SECTION=$(awk -v ver="$VERSION" '
$0 ~ "^## \\[" ver "\\]" { found=1; next }
found && /^## \[/ { exit }
found { print }
' CHANGELOG.md)
fi fi
# Write to file for the release body
echo "$NOTES" > /tmp/release-notes.txt # --- 2. Commit-based fallback ------------------------------------
# Used only when CHANGELOG has no section for this version. Groups
# conventional-commit prefixes into readable categories; skips
# automated "chore(release): …" bump commits from display since
# they're noise in a release the reader is already looking at.
if [ -z "$(printf '%s' "$CHANGELOG_SECTION" | tr -d '[:space:]')" ]; then
echo "::warning::CHANGELOG.md has no section for [$VERSION]; falling back to commit-log grouping."
if [ -n "$PREV_TAG" ]; then RANGE="$PREV_TAG..HEAD"; else RANGE=""; fi
LOG=$(git log $RANGE --no-merges --pretty=format:'%s' \
| grep -vE '^chore\(release\)' || true)
# extract <regex> — prints matching commits as "- <rest>" with the
# conventional-commit "type(scope)?:" prefix stripped for readability.
extract() {
printf '%s\n' "$LOG" \
| grep -E "^($1)(\([^)]+\))?:" \
| sed -E "s/^($1)(\([^)]+\))?:[[:space:]]*/- /" \
|| true
}
FEATURES=$(extract 'feat')
FIXES=$(extract 'fix')
REFACTORS=$(extract 'refactor')
DOCS=$(extract 'docs')
OTHER=$(printf '%s\n' "$LOG" \
| grep -vE '^(feat|fix|refactor|docs|chore)(\([^)]+\))?:' \
| sed -E 's/^/- /' \
|| true)
{
[ -n "$FEATURES" ] && printf '### Features\n\n%s\n\n' "$FEATURES"
[ -n "$FIXES" ] && printf '### Bug Fixes\n\n%s\n\n' "$FIXES"
[ -n "$REFACTORS" ] && printf '### Changes\n\n%s\n\n' "$REFACTORS"
[ -n "$DOCS" ] && printf '### Documentation\n\n%s\n\n' "$DOCS"
[ -n "$OTHER" ] && printf '### Other\n\n%s\n\n' "$OTHER"
} > /tmp/generated.md
CHANGELOG_SECTION=$(cat /tmp/generated.md)
fi
# --- 3. Compose final body (content + compare footer) ------------
{
printf '%s\n' "$CHANGELOG_SECTION"
if [ -n "$PREV_TAG" ]; then
printf '\n---\n\n**Full Changelog:** [%s...%s](https://github.com/%s/compare/%s...%s)\n' \
"$PREV_TAG" "$TAG" "$REPO" "$PREV_TAG" "$TAG"
fi
} > /tmp/release-notes.md
echo "--- release notes ($(wc -c < /tmp/release-notes.md) bytes) ---"
head -20 /tmp/release-notes.md
echo "---"
- name: Create release - name: Create release
if: steps.existing.outputs.skip != 'true'
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@v2
with: with:
tag_name: ${{ steps.tag.outputs.version }} tag_name: ${{ steps.version.outputs.tag }}
name: ${{ steps.tag.outputs.version }} name: ${{ steps.version.outputs.tag }}
body_path: /tmp/release-notes.txt body_path: /tmp/release-notes.md
draft: false draft: false
prerelease: false prerelease: false
make_latest: 'true'
# Belt-and-suspenders: action-gh-release@v2 has a long-standing
# intermittent bug where it creates the release as a draft and silently
# fails to flip the draft→published step, even though it reports success.
# When that happens the install script + README snippets resolve "latest"
# to whatever was last properly published, so users would get an old
# version. We explicitly flip to published + latest here as a safety net;
# if the action already did it correctly, this is a no-op.
#
# Security note: TAG and REPO are sourced from earlier `env:` blocks (not
# interpolated inline into the run command), matching the same pattern
# used elsewhere in this workflow.
- name: Force-publish release
if: steps.existing.outputs.skip != 'true'
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.version.outputs.tag }}
REPO: ${{ github.repository }}
run: |
gh release edit "$TAG" --repo "$REPO" --draft=false --latest

View File

@@ -2,6 +2,173 @@
All notable changes to the VirtFusion Direct Provisioning Module for WHMCS. All notable changes to the VirtFusion Direct Provisioning Module for WHMCS.
## [1.5.0] - 2026-04-28
> **Tested against:** WHMCS 9.0.3 and VirtFusion v7.0.0 Build 9.
### Features
- **In-page section navigation in the WHMCS Actions sidebar.** Customers viewing a VirtFusion service get an "On This Page" group in the sidebar with jump-links to every visible panel (Overview, Traffic, Live Stats, Power, Manage, Rebuild, Reverse DNS, Resources, Billing & Usage, Billing Overview). Rendered server-side via a `ClientAreaPrimarySidebar` hook that's gated to productdetails pages for VF services only — no impact on other modules. Each link smooth-scrolls to its target via a delegated click handler. Conditionally-shown panels (Live Stats when remoteState is unavailable, Reverse DNS when PowerDNS isn't configured, Resources/Self-Service before their data loads) auto-hide their corresponding sidebar links so customers don't see dead jumps. VNC is intentionally excluded — its panel is the first thing on the page already. Theme-agnostic — WHMCS handles sidebar rendering for Six, Twenty-One, Lagom, etc.
- **Traffic chart panel showing the last 12 months of monthly aggregates.** New panel between Server Overview and Power Management, sourced from `/servers/{id}/traffic`'s `monthly[]` array. Renders side-by-side rx (blue) and tx (green) bars per month with month-or-month/year labels at the bottom and a centered legend with breathing room. Current period's used/limit/remaining tile sits below the chart. Replaces the previously broken in-resources chart that read non-existent `data.entries` / `data.used` paths and silently never rendered for any service since it was first added.
- **Live Stats panel — CPU, memory, disk I/O with 30s auto-refresh.** Surfaces `remoteState.cpu`, `remoteState.memory.{actual,unused}`, and `remoteState.disk.vda.{rd.bytes,wr.bytes}` from VirtFusion's libvirt introspection. CPU and memory render as colored progress bars with `bg-warning` at 75% and `bg-danger` at 90%. Disk I/O shows cumulative bytes since boot. Refresh polls `serverData` every 30s while the panel is visible AND the page has focus — pauses on `visibilitychange` to avoid hammering libvirt when the customer alt-tabs away. Hidden entirely when the upstream call returns no remoteState block.
- **Filesystem usage in the Resources panel.** Per-mount usage rows sourced from qemu-guest-agent's fsinfo block (requires `qemu-guest-agent` installed on the VM). Pseudo-FS (proc/sysfs/devtmpfs/tmpfs/cgroup/etc.) plus `/boot*` and `/run*` are filtered out — only customer-meaningful mounts show. Each row has a progress bar with the same 75%/90% warning thresholds. Hidden when the agent isn't running, with a one-line hint that customers can install qemu-guest-agent to populate the section.
- **Server Overview meta bar — Location, OS, lifetime.** Top of the panel now shows three chips: data-center location with country flag emoji (from `hypervisor.group.{name,icon}`, country codes mapped via Regional Indicator Symbols), the OS template name preferring the qemu-agent's pretty name when available (with kernel version on hover), and a relative "Created N days ago" chip with the absolute timestamp on hover.
- **Hypervisor maintenance banner.** Yellow alert at the very top of the page when `hypervisor.maintenance=true`. Prepares the customer to expect "operation may be unavailable" errors so they don't open support tickets for what's actually known maintenance.
- **"Mask Sensitive" toggle for screenshot-safe viewing.** Button on the Server Overview meta bar. When active, masks IPv4 (keeps first two octets — `205.186.•••.•••`), IPv6 (keeps first two hextets — `2602:2f3:••••::•`), hostnames (keeps first char of each dot-separated label — `m•••.e••••••.c••`). Covers the Server Name input, Hostname row, IPv4/IPv6 cells in Server Overview, AND in the Reverse DNS panel rows. Input fields mask via CSS `text-security: disc` (preserves the underlying value for editing — focus reveals); text cells via attribute swap with the original cached on `data-vf-ip-original`. State persists in `sessionStorage` so screenshots taken across page refreshes stay masked.
- **Per-IP copy buttons in Server Overview cells.** Each IPv4 / IPv6 address renders as a row with a copy button (replaces the standalone Network panel that duplicated this information).
### Bug Fixes
- **Critical: UsageUpdate cron silently never recorded any usage.** `VirtFusionDirect_UsageUpdate()` was reading `server.usage.traffic.used` and `server.usage.storage.used` — neither path exists in any VirtFusion API response, so `tblhosting.bwused` and `diskused` stayed at 0 forever for every service. Bandwidth now sourced from `/servers/{id}/traffic`'s `monthly[0].total` (canonical billing-period bytes); disk usage from `/servers/{id}?remoteState=true`'s `agent.fsinfo[]` summed (best-effort — only updates when qemu-guest-agent is running). Limits (`settings.resources.{storage,traffic}`) were already correct and untouched. Verified on live data: usage columns now populate correctly, unblocking suspend-on-overage rules and customer-facing usage bars.
- **Critical: WHMCS 9 multi-service order short-circuit.** WHMCS 9 added a batch order-acceptance loop that terminates as soon as the order leaves Pending status — calling `localAPI('AcceptOrder')` mid-batch (which our `AfterModuleCreate` hook did to advance the order) caused subsequent VF services in the same order to be skipped, leaving them Active in `tblhosting` but with no `mod_virtfusion_direct` row and no actual VPS in VirtFusion. Fix: defer the auto-accept until every VF service in the order has been provisioned. The hook fires once per service, so the last one to complete sees no unprovisioned siblings and triggers the actual accept. WHMCS 8 was unaffected (its loop ignored order status mid-batch); deferring there is harmless.
- **Service detail page returned generic 500s for orphaned services.** When a service exists in `tblhosting` but has no row (or NULL `server_id`) in `mod_virtfusion_direct` — e.g., the multi-service order bug above, or a failed CreateAccount — every client.php endpoint silently bailed via `resolveServiceContext()` and the customer saw a string of generic 500s with no actionable message. Added `Module::requireProvisionedService()` helper that emits a single clean 409 ("Server has not been provisioned yet. Please contact support if this is unexpected.") on the first endpoint call. Wired into all 17 client.php cases after `validateUserOwnsService()` so customers see one clear message instead of six broken sections.
- **Traffic display in Server Overview showed `- / Unlimited` even for servers with measured usage.** Same root cause as the UsageUpdate bug: `ServerResource::process()` read the non-existent `usage.traffic.used` path. Fixed by having `Module::fetchServerData()` make a secondary call to `/servers/{id}/traffic` and merge the current period's total bytes onto the server object as `trafficUsedBytes`; ServerResource reads from that stable field. Also renamed "Unlimited" → "Unmetered" everywhere — limit=0 means no cap, but traffic is still tracked per period, so Unmetered is more accurate.
- **VNC viewer popup didn't render — wrong URL pattern.** The `/vnc/?token=...` URL VirtFusion returns is the raw WebSocket endpoint and rejects HTTP GET with 405. The actual noVNC viewer is a tiny HTML shell that loads `<vfBaseUrl>/vnc/vnc.js`. Fixed by serving the shell ourselves from a same-origin authenticated PHP route (`client.php?action=vncViewer`) — see the Security section below for the full shape.
- **VNC toggle was lying and was removed.** The PHP `Module::toggleVnc()` was POSTing `{enabled: bool}` to VirtFusion when the API parameter is actually `vnc: bool` — silent no-op. Even after fixing the param, the API's `vnc.enabled` response field stayed `false` regardless of toggle state, and the wss endpoint accepts connections regardless of the panel toggle (per VirtFusion's current implementation, the toggle only manages a firewall flag that's currently broken at their panel level). Toggle removed entirely; VNC is treated as always-available, gated by WHMCS session + service ownership at our layer.
- **OS gallery's "Other" category icon was hardcoded to a generic SVG.** Forced override in `Module::groupOsTemplates()` and matching branches in `module.js` and `hooks.php` were nulling out the icon VirtFusion provides for the category. Reverted to use the upstream icon — applies in both the client-area Rebuild gallery and the checkout-side OS picker. Singleton-collected templates (those merged into a synthetic "Other" bucket) inherit the icon from VF's "Other" category if one was present in the source data.
- **Save button squished on the Server Name rename row.** Single flex row with 6px gap and a 200px max-width input was packing the randomise + save buttons into too-narrow columns on mid-width viewports. Wrapped the inputs in a flex-wrap container with explicit min-widths so all three controls stay readable down to mobile.
- **Server rename was force-lowercasing the input.** Customer typed "VPS-01", got "vps-01" back. Both client and server validation enforced an RFC-1123-style hostname regex, but VirtFusion's `name` field is a display label that accepts any printable string up to 63 chars. Validation relaxed to non-empty + length cap + reject control characters. Mid-flight, the input field, Save, and Randomise buttons all freeze together so customers can't double-submit or edit while the rename is in flight.
- **Server rename hit the wrong VirtFusion endpoint** (and silently treated success as failure). The PHP module was using `PATCH /servers/{id}/name`, which VirtFusion v7 returns 404 for — the path moved to `PUT /servers/{id}/modify/name` (consistent with `/modify/memory`, `/modify/cpu`, etc.). Even after fixing the URL, success was treated as failure because v7 returns HTTP 201 (Created) on rename and our success whitelist only accepted 200/204. Fixed both: switched to PUT + new path, added 201 to the whitelist.
### Security
- **CSRF protection added to every destructive client.php action.** `rebuild`, `resetPassword`, `resetServerPassword`, `powerAction`, `rename`, `selfServiceAddCredit`, `toggleVnc`, and `vncViewer` now require `requirePost()` + `requireSameOrigin()`. Closes a class of attacks where a malicious page (or compromised ad slot) could embed a hidden form targeting `client.php?serviceID=X&action=rebuild` and destroy the customer's data on the next page load they made while logged in. Previously only `rdnsUpdate` carried these gates.
- **Open-redirect defence on SSO.** `Module::fetchLoginTokens()` now validates that the URL constructed from VirtFusion's `endpoint_complete` resolves to the same hostname as the configured VirtFusion panel before returning it for redirect. Defends against a hostname-mismatched response (compromised VF panel, tampered `tblservers` row, etc.) being used to phish customers.
- **VNC viewer popup served from a same-origin authenticated POST route.** Click → hidden form-submit (POST) to `client.php?action=vncViewer``requirePost()` + `requireSameOrigin()` + `isAuthenticated()` + `validateUserOwnsService()` + `requireProvisionedService()` → POST `/vnc {vnc:true}` to rotate the wss token → return `text/html` with the noVNC shell embedded. The wss URL never appears in any URL bar, browser history, or shareable link — it lives only in the HTTP response body delivered to a logged-in session. Each open rotates the token, so any prior credential exposure is short-lived. Response carries `X-Frame-Options: DENY`, `Cache-Control: no-store, private`, and a strict `Content-Security-Policy` (`default-src 'none'`, `script-src 'self' <vf-panel>`, `connect-src wss://<vf-panel> <vf-panel>`, `frame-ancestors 'none'`) so the viewer cannot be re-hosted, embedded, or opened in a way that loads scripts from anywhere outside our WHMCS host or the configured VirtFusion panel.
- **Per-action rate limiting** on destructive endpoints via the new `Module::requireRateLimit()` helper (Cache-backed, Redis-or-filesystem). Limits: `rebuild` 60 s, `resetPassword` / `resetServerPassword` 30 s, `powerAction` 10 s, `vncViewer` / `toggleVnc` / `selfServiceAddCredit` 5 s — all per-(action, serviceID). Defence against runaway browser scripts and accidental double-submits hammering the VirtFusion API. Returns 429 with a clear "Too many requests" message instead of letting the request through.
- **IP and hostname masking covers screenshot-sensitive cells.** See the Mask Sensitive feature above — reduces leakage when customers screen-share or attach screenshots for support.
- **IPv6 examples in the Reverse DNS placeholder + comment switched to the IANA documentation prefix `2001:db8::/32`** (RFC 3849), eliminating an inadvertent reference to a deployer-specific IPv6 block that previously appeared in customer-facing UI.
### Removed
- **Network panel** (full removal) — duplicated Server Overview's IP rows. Per-IP copy buttons moved into the Overview cells via `vfRenderIpCells()`.
- **Network Speed row** from the Resources panel — VirtFusion's `inAverage`/`inPeak`/`inBurst` and matching out-fields all return 0 in our setup (network speed isn't capped at the package level), so the row was always empty.
- **VNC enable/disable toggle** — see Bug Fixes above.
### Internal
- **`Module::fetchServerData()` now passes `?remoteState=true`** on the upstream call so the response includes live CPU/memory, disk I/O counters, and qemu-agent fsinfo. Adds one libvirt round-trip per page load on the hypervisor side; revisit caching if hypervisor load becomes a concern.
- **`ServerResource::process()`** exposes new fields: `osName`, `osPretty`, `osKernel`, `osDistro`, `osIcon`, `location`, `locationIcon`, `hypervisorMaintenance`, `createdAt`, `builtAt`, plus a nested `live.{state, cpu, memoryActualKB, memoryUnusedKB, memoryAvailableKB, memoryRssKB, diskRdBytes, diskWrBytes, filesystems[]}` block.
- **`Module::toggleVnc()`** corrected to post `{vnc: bool}` (the actual API parameter) instead of `{enabled: bool}` (silent no-op). Also returns `baseUrl` alongside the API envelope so the new vncViewer route can build the wss URL without re-deriving it.
- **`Module::getVncConsole()`** also returns `baseUrl` for the same reason.
- **Panel margins tightened** from `mb-3` (16px) to `mb-2` (8px) across all 11 client-area panels for a tighter visual rhythm post-additions.
## [1.4.4] - 2026-04-25
### Bug Fixes
- **`install.sh`: "TMP: unbound variable" error at script exit, plus exit code 1 even on successful installs.** The cleanup `trap 'rm -rf "$TMP"' EXIT` referenced a `local TMP` from inside `cmd_sync()`. The EXIT trap doesn't fire until the *shell* exits — by which time the function-scoped local is out of scope — and `set -u` then exploded the trap body, masking the real exit code with `1`. Fix: drop `local` so `TMP` persists at script scope until cleanup runs, and switch the trap body to `${TMP:-}` so any future regression that tightens TMP's scope still survives the trap. Cosmetic in practice (the install/upgrade work itself completed before the trap ran), but the non-zero exit broke automated wrappers and cron-driven invocations that check `$?`.
## [1.4.3] - 2026-04-25
### Features
- **`install.sh` helper script with `install` / `upgrade` / `check` subcommands.** Single-file POSIX bash script that handles both first-time installation and upgrades, auto-detects the WHMCS web user from the parent directory's ownership and applies it to new files via rsync `--chown`, optionally syncs the PowerDNS reverse-DNS addon (`--with-addon`), accepts a pinned version (`--version v1.4.1`, default: latest published release), preserves any custom `config/ConfigOptionMapping.php` across the rsync `--delete`, and writes a `.installed-version` marker so the `check` subcommand can report installed-vs-latest without making changes. Pipeable via curl or wget. Exit codes for `check` (0=current, 1=outdated, 2=not installed) make it usable as a cron-driven update monitor. Closes the long-standing pitfall where rsyncing as root left files owned by `root:root` and the web server couldn't read them — the classic "module installed but invisible in WHMCS" symptom.
### Bug Fixes
- **Release workflow now force-publishes new releases to non-draft and marks them `--latest`.** `softprops/action-gh-release@v2` has a long-standing intermittent bug where it creates a release as a draft and silently fails to flip it to published, despite reporting success. v1.4.0, v1.4.1, and v1.4.2 all shipped as drafts because of this — meaning the GitHub `releases/latest` API returned v1.3.0, the install snippets and the new `install.sh` would all download v1.3.0, and users would never get the storage-type-code fix even after running the documented upgrade. Added a `make_latest: 'true'` input to the action and a follow-up `gh release edit --draft=false --latest` step that runs unconditionally as a safety net. v1.4.0/1/2 were manually re-published as a one-off cleanup.
### Documentation
- README install/upgrade sections rewritten to feature the `install.sh` script as the primary path (with both `curl` and `wget` examples), with the manual rsync recipe preserved in collapsible `<details>` blocks for users who prefer not to pipe scripts to bash. The manual recipe also gained a `stat -c '%U:%G'` ownership probe and `--chown="$OWNER"` flag, fixing the same root-owned-file pitfall the script handles automatically.
## [1.4.2] - 2026-04-25
### Documentation
- **Install/upgrade snippets now pull tagged releases instead of cloning `main`.** The previous `git clone` flow always pulled HEAD, which could include in-flight commits between releases — the same trap the v1.4.1 storage-type-code bug fell into for anyone who installed during the v1.4.0 release window. The new snippets default to the latest published release (queried live from the GitHub API at install time) and accept a `VERSION=vX.Y.Z` override for pinned installs and rollbacks. Pure POSIX — only requires `curl`, `sed`, `tar`, and `rsync`, all standard on any WHMCS host. The `archive/refs/tags/<TAG>.tar.gz` endpoint is public and cacheable, so only the version lookup hits the GitHub API (well under the 60/hr unauthenticated rate limit).
## [1.4.1] - 2026-04-25
### Bug Fixes
- **Critical: stock control returned qty=0 fleet-wide for packages with a `primaryStorageProfile`.** `StockControl::capForStorage()` was comparing the package's `primaryStorageProfile` against `otherStorage[].id`, but the VirtFusion API exposes that field as a **storage type code** (mirrors `server_packages.storage_type`) — a filter that should match `otherStorage[].storageType`. Pool ids are unique per hypervisor (e.g. 23/28/30 for the same logical mountpoint on three nodes) and almost never collide with the type-code domain (0=local, 4=mountpoint, etc.), so the check returned 0 for every hypervisor and silently zeroed inventory for any product that opted into stock control with a non-default storage profile. Symptoms: every stock-controlled VPS product showed qty=0 in WHMCS despite abundant memory/CPU/IPv4 capacity; only workarounds were disabling stock control or removing `primaryStorageProfile` from the package, both of which defeat the gating. Fix: match `pool.storageType` instead of `pool.id`; walk all pools that match (a hypervisor may carry multiple pools of the same type) and pick the one that fits the most VMs; treat a disabled pool as skip-and-continue rather than a hard zero, so an enabled peer of the same type still contributes. Also renamed the internal `$profileId` parameter to `$storageTypeId` so future readers don't fall into the same naming trap. Verified on a 3-hypervisor cluster: qty went from 0/0/0/0/0/0/0/0 to 66/32/15/7/3/1/32/15 across the VPS-1 through VPS-32 products with no other config change.
## [1.4.0] - 2026-04-24
### Features
- **Dynamic VPS stock control driven by live hypervisor capacity.** Opt-in per product via WHMCS's native `tblproducts.stockcontrol` toggle; when enabled, the module overwrites `tblproducts.qty` with the real number of VPSes the panel can still provision and WHMCS handles the "Out of Stock" badge, Add-to-Cart gating, and checkout refusal natively — no template work required. qty is derived by combining two authoritative sources:
- `GET /packages/{packageId}` for the per-VPS resource footprint (`memory`, `cpuCores`, `primaryStorage`, `primaryStorageProfile`, `enabled`)
- `GET /compute/hypervisors/groups/{id}/resources` for live per-hypervisor free/allocated data
Algorithm sums `min(memory, cpu, storage)` across eligible hypervisors (enabled AND commissioned AND !prohibit) for every group the product can be placed in (default `configoption1` plus every numeric value of a `Location` configurable option), capped by the group-level IPv4 pool taken as `max()` within a group to avoid double-counting. Storage matching is strict against `package.primaryStorageProfile`; hypervisors without the named pool contribute 0. Confirmed-missing conditions (HTTP 404 on `/packages/{id}`, `package.enabled=false`) force qty=0; transient failures leave `qty` UNTOUCHED to avoid false out-of-stock during API blips.
- **Event-driven stock recalculation hooks:**
- `AfterModuleCreate` — refreshes qty after every VirtFusion provision (capacity just decreased). Bursts of parallel provisions coalesce via a 30 s shared rate-limit.
- `AfterModuleTerminate` — refreshes qty after every VirtFusion termination (capacity just increased). Shares the 30 s rate-limit with create.
- `AfterCronJob` — every-2-hour safety net that catches capacity changes made directly in the VirtFusion panel without going through WHMCS. Interval tunable via `STOCK_CRON_INTERVAL_SECONDS` in `hooks.php`.
- `ClientAreaPageCart` — opportunistic per-product refresh during the order flow, rate-limited to once per product per 60 s.
- **Order auto-accept after successful provision.** `AfterModuleCreate` calls WHMCS `AcceptOrder` (with `autosetup=false` so there's no double-provision) when the parent order is still in Pending status. Closes the gap for installs that rely on pending-order workflows for non-VF products but want VirtFusion provisions to auto-advance. Idempotent — already-accepted orders are skipped.
- **Admin-triggered full recalculation.** New `admin.php?action=stockRecalculate` action (POST + same-origin required) runs `StockControl::recalculateAll()` on demand and returns a JSON `{productId: qty}` map; the module log gets a compact summary (`{total, updated, zeroed, skipped}`) so it stays readable on stores with hundreds of products.
- **Per-product safety buffer.** New `stockSafetyBufferPct` config option (configoption7, default 10) reserves X% of each resource's `max` during stock calculation. Applied only to capped resources (unlimited resources with `max=0` skip the buffer). Admins can override per product in the module settings; blank falls back to 10% so existing products get sensible headroom without any config change.
- **Test Connection now probes `/compute/hypervisors/groups`.** A VirtFusion API token scoped only to `/servers` would pass the existing `/connect` check but silently break nightly stock updates. The admin's Test Connection button now surfaces missing `/compute` read scope at config time with a specific error rather than as unexplained nightly silence.
### Caching
- New cache keys: `pkg:{packageId}` (10 min TTL, package definitions rarely change) and `grpres:{groupId}` (120 s TTL, resources change minute-to-minute under load). Confirmed 404 responses are cached for 60 s so an admin re-creating a deleted package/group takes effect quickly.
### Safety Properties
- `Module::fetchPackage()` and `Module::fetchGroupResources()` return a tri-state `array | false | null`: `false` means "VirtFusion confirmed this doesn't exist → OOS is correct", `null` means "we can't tell right now → don't touch existing qty". Without this distinction the module would either zero out inventory during transient API blips, or show inventory for deleted packages.
- `\Throwable` catches on every stock-path entry point (not just `\Exception`) so a `TypeError` from a malformed API response can't escape the tri-state contract.
- Stock-control is gated by `tblproducts.stockcontrol=1` — products that opt out are never touched, even by the safety-net cron.
## [1.3.0] - 2026-04-17
### Bug Fixes
- **Critical: decrypt() corruption of plaintext addon API keys.** `Config::get()` was calling WHMCS's `decrypt()` on the raw `tbladdonmodules.value` for the PowerDNS API key and accepting whatever non-empty result came back. WHMCS addon password-type fields are actually stored **plaintext** (unlike `tblservers.password` which is encrypted), and `decrypt()` on plaintext input returns ~4 bytes of binary garbage instead of empty. That garbage was ending up in the `X-API-Key:` header, producing a baffling 401 from PowerDNS and an empty zone list — which then surfaced as **"no zone"** for every IP in the client-area rDNS panel. Fix: only use `decrypt()`'s output when it's printable ASCII; fall back to raw otherwise. Also `trim()` the chosen value so a stray paste-newline can't corrupt the header.
### Features
- **IPv6 subnet visibility + custom-host PTR flow.** VirtFusion allocates v6 as whole subnets (e.g. a /64 routed to the VPS) rather than discrete host addresses. The module previously filtered these silently; now subnets appear as first-class rows in the client rDNS panel with a collapsible "Add host PTR" form. Ownership verification uses **subnet containment** (`IpUtil::ipv6InSubnet()` via `inet_pton` + bit masking) so any address inside one of the VPS's allocated subnets is writeable, while addresses outside them are rejected. FCrDNS / rate-limit / CSRF guards all still apply.
- **Diagnose-an-IP tool** on the VirtFusion DNS addon admin page. Takes an IP input and runs the full PtrManager pipeline inline: config snapshot, fresh zone list (cache-bypassed), computed PTR name, matched zone, current PTR content. Every common failure mode (wrong key, wrong serverId, forgotten zone, mis-aligned RFC 2317 label, stale cache) produces a distinctive shape in that output, turning "support ticket" into "screenshot the diagnosis".
- **Actionable auth-error messages.** `Client::ping()` now returns structured guidance on 401/403 (check API key, `api-allow-from`, whitespace) and 404 (check `serverId`, it should be the literal `localhost`), replacing the previous "authentication failed (check API key)" / "unexpected HTTP 404" which gave no clue which of several causes was actually biting.
## [1.2.0] - 2026-04-17
### Features
- **PowerDNS reverse DNS (PTR) integration** — opt-in via companion `VirtFusionDns` addon module:
- Automatic PTR sync on server create, rename, and terminate
- Client-area "Reverse DNS" panel with one editable PTR per assigned IP and per-row status badges
- Admin services-tab widget with Reconcile (additive) and Reconcile (force reset) buttons
- Daily cron additive reconciliation (never overwrites existing PTRs)
- Forward-confirmed reverse DNS (FCrDNS) enforcement — PTR writes rejected if forward A/AAAA doesn't resolve to the target IP
- IPv4 + IPv6 support with full nibble-reversal for `ip6.arpa`
- RFC 2317 classless delegation support (both CIDR-prefix `0/26` and block-size `64/64` conventions)
- Automatic NOTIFY after every successful PATCH so slaves pick up SOA bumps immediately
- PowerDNS zone ID `=2F` URL-encoding for zones containing `/`
- **Security hardening helpers** on the Module base class:
- `requirePost()` — 405 on non-POST mutations
- `requireSameOrigin()` — CSRF Origin/Referer check against WHMCS host
- `requireServiceStatus()` — filter endpoints by `tblhosting.domainstatus`
- Applied to all rDNS endpoints with successful-write audit logging
- Merged Test Connection — when the DNS addon is active the admin button verifies both VirtFusion AND PowerDNS in a single check
### Bug Fixes
- `IpUtil::parseClasslessZone` now rejects misaligned start addresses (e.g., `3/26.x.y.z` — /26 ranges must begin at a multiple of 64). Prevents silent write-into-wrong-zone on misconfigured zone names.
### Documentation
- Detailed design-rationale commentary added across the module for future-developer onboarding (Cache, Curl, Log, Database, ServerResource, ConfigureService) and throughout the new PowerDNS subsystem
- README updated with an extensive "Reverse DNS Addon (PowerDNS)" section covering activation, configuration, behaviour, and security posture
- CLAUDE.md updated with architecture notes and PowerDNS API compatibility details
## [1.0.0] - 2026-03-19 ## [1.0.0] - 2026-03-19
### Features ### Features

137
CLAUDE.md
View File

@@ -45,10 +45,11 @@ The `publish-release.yml` workflow creates a GitHub/Gitea release with auto-gene
| File | Purpose | | File | Purpose |
|------|---------| |------|---------|
| `VirtFusionDirect.php` | WHMCS module interface — non-namespaced functions (`VirtFusionDirect_CreateAccount()`, etc.) that delegate to library classes | | `modules/servers/VirtFusionDirect/VirtFusionDirect.php` | WHMCS module interface — non-namespaced functions (`VirtFusionDirect_CreateAccount()`, etc.) that delegate to library classes |
| `client.php` | Client-facing AJAX API — authenticated by WHMCS session + service ownership validation. POST for mutations, GET for reads. | | `modules/servers/VirtFusionDirect/client.php` | Client-facing AJAX API — authenticated by WHMCS session + service ownership validation. POST for mutations, GET for reads. |
| `admin.php` | Admin-facing AJAX API — requires WHMCS admin authentication | | `modules/servers/VirtFusionDirect/admin.php` | Admin-facing AJAX API — requires WHMCS admin authentication |
| `hooks.php` | WHMCS hooks — checkout validation (OS selection), OS gallery + SSH key UI injection, slider UI for configurable options | | `modules/servers/VirtFusionDirect/hooks.php` | WHMCS hooks — checkout validation (OS selection), OS gallery + SSH key UI injection, slider UI for configurable options, daily PowerDNS reconciliation |
| `modules/addons/VirtFusionDns/VirtFusionDns.php` | Optional companion addon — holds PowerDNS settings and provides a Test Connection admin page. See "Reverse DNS (PowerDNS)" below. |
### Core Classes (in `lib/`) ### Core Classes (in `lib/`)
@@ -60,9 +61,15 @@ The `publish-release.yml` workflow creates a GitHub/Gitea release with auto-gene
| `Database` | Static methods for `mod_virtfusion_direct` table operations and WHMCS DB queries. Auto-creates/migrates schema on first use. | | `Database` | Static methods for `mod_virtfusion_direct` table operations and WHMCS DB queries. Auto-creates/migrates schema on first use. |
| `Curl` | HTTP client wrapper with Bearer token auth, SSL verification, 30s timeout. Methods: `get`, `post`, `put`, `patch`, `delete`. Single-use — each instance makes one request. | | `Curl` | HTTP client wrapper with Bearer token auth, SSL verification, 30s timeout. Methods: `get`, `post`, `put`, `patch`, `delete`. Single-use — each instance makes one request. |
| `Cache` | Two-tier caching: Redis (if `ext-redis` available) with atomic filesystem fallback. TTLs: OS templates 10min, traffic/backups 2min, packages 10min. | | `Cache` | Two-tier caching: Redis (if `ext-redis` available) with atomic filesystem fallback. TTLs: OS templates 10min, traffic/backups 2min, packages 10min. |
| `ServerResource` | Transforms VirtFusion API response into flat key-value format for Smarty templates. | | `ServerResource` | Transforms VirtFusion API response into flat key-value format for Smarty templates. Only reads `interfaces[0]`; for rDNS use `PowerDns\IpUtil::extractIps()` which walks all interfaces. |
| `AdminHTML` | Static methods generating admin services tab HTML (server ID editor, JSON viewer, action buttons). | | `AdminHTML` | Static methods generating admin services tab HTML (server ID editor, JSON viewer, action buttons, `rdnsSection()` widget). |
| `Log` | Thin wrapper around WHMCS module logging. | | `Log` | Thin wrapper around WHMCS module logging. |
| `PowerDns\Client` | PowerDNS HTTP API wrapper (`X-API-Key` auth): `ping`, `listZones`, `getZone`, `patchRRset`, `notifyZone`. PATCH success triggers an automatic NOTIFY so slaves pick up the SOA bump immediately. |
| `PowerDns\Config` | Loads settings from `tbladdonmodules` (module="virtfusiondns") and decrypts `apiKey` via WHMCS `decrypt()`. `isEnabled()` gates every PowerDNS call site. |
| `PowerDns\IpUtil` | Pure helpers: `ptrNameForIp` (v4/v6 nibble reversal), `expandIpv6`, `extractIps` (all interfaces), `findZoneAndPtrName` (standard + RFC 2317 classless), `parseClasslessZone`. |
| `PowerDns\Resolver` | Forward-DNS verification via `dns_get_record()` with up-to-5-hop CNAME following. Cached per (hostname, ip) pair. |
| `PowerDns\PtrManager` | Orchestrator: `syncServer`, `deleteForServer`, `listPtrs`, `setPtr`, `reconcile`, `reconcileAll`. Per-request zone cache. 10s per-IP write rate limit. Enforces FCrDNS before writes. |
| `StockControl` | Orchestrator for dynamic inventory. `recalculateForProduct()` and `recalculateAll()` compute per-product qty from live `/packages/{id}` + `/compute/hypervisors/groups/{id}/resources` data and write to `tblproducts.qty`. Fail-safe: null return = qty untouched. |
### Class Hierarchy ### Class Hierarchy
@@ -70,16 +77,31 @@ The `publish-release.yml` workflow creates a GitHub/Gitea release with auto-gene
### Client-Side ### Client-Side
- **`templates/overview.tpl`** — Smarty template for client area (server info, power, network, rebuild with OS gallery, resources with traffic chart, VNC toggle, self-service billing, billing overview, backups timeline, server rename, password reset) - **`templates/overview.tpl`** — Smarty template for client area. Panel order top-down: Hypervisor maintenance banner → VNC Console (button only) → Server Overview (with location/OS/lifetime meta chips, Mask Sensitive toggle, IP rows with copy buttons, Login to Control Panel footer) → Traffic chart (12-month aggregates) → Live Stats (CPU/memory/disk I/O, 30s refresh) → Power Management → Manage (password reset + backups) → Rebuild (OS gallery) → Reverse DNS (when PowerDNS enabled) → Resources (with filesystem usage when qemu-agent reports it) → Self-Service Billing (when configoption4>0) → Billing Overview.
- **`templates/js/module.js`** — Vanilla JS + jQuery handling AJAX calls, DOM updates, status badges, power actions, all management UIs. Key helpers: `vfUrl()` (URL builder), `vfShowAlert()` (alert display), `vfRenderOsGallery()` (accordion gallery), `vfDrawTrafficChart()` (canvas chart) - **`templates/js/module.js`** — Vanilla JS + jQuery handling AJAX calls, DOM updates, status badges, power actions, all management UIs. Key helpers: `vfUrl()` (URL builder), `vfShowAlert()` (alert display), `vfRenderOsGallery()` (accordion gallery), `vfDrawTrafficChart()` (canvas chart, monthly bars + centered legend), `vfRenderIpCells()` (IP-row + copy button), `vfRenderLiveStats()` / `vfRenderFilesystems()` (remoteState surfaces), `vfMaskString()` / `vfApplyIpMask()` / `vfToggleIpMask()` (Mask Sensitive — IPv4 keeps first 2 octets, IPv6 keeps first 2 hextets, hostnames keep first char per dot-label; inputs masked via `text-security: disc`), `vfBuildSectionNav()` (toggles sidebar Jump-To items based on visible-panel state).
- **`templates/js/keygen.js`** — Client-side SSH Ed25519 key generator using Web Crypto API (loaded on checkout page) - **`templates/js/keygen.js`** — Client-side SSH Ed25519 key generator using Web Crypto API (loaded on checkout page)
- **`templates/css/module.css`** — Cross-theme styles with Bootstrap 3/4/5 dual class support (`panel card`, `panel-body card-body`) - **`templates/css/module.css`** — Cross-theme styles with Bootstrap 3/4/5 dual class support (`panel card`, `panel-body card-body`). Panel margins are `mb-2` (8px) for tight stacking; `.vf-panel-grid` provides side-by-side panel layouts when used.
### Sidebar Integration
- **WHMCS Actions sidebar** receives an "On This Page" group via `ClientAreaPrimarySidebar` hook (in `hooks.php`), gated to productdetails for VF services only. Each entry carries `data-vf-target=<panel-id>` so the document-level smooth-scroll click handler in `module.js` picks it up regardless of theme markup. Visibility per entry is toggled by `vfBuildSectionNav()` after page load — works whether the theme renders sidebar items in `<li>` wrappers (Six) or as bare `<a>` elements (Twenty-One).
- **`ServiceSingleSignOnLabel` metadata** is set to "Login to VirtFusion Panel" but the auto-render of this in the WHMCS 9 sidebar is unreliable. The reliable surface is the inline "Login to Control Panel" button in the Server Overview footer, which calls `vfLoginAsServerOwner()` to fetch a one-shot SSO URL via `Module::fetchLoginTokens()` and opens it in a new tab.
### VNC viewer security model
- Customer clicks "Open Console" → `window.open('client.php?action=vncViewer&serviceID=X')`.
- The route checks `isAuthenticated()` + `validateUserOwnsService()` + `requireProvisionedService()`, then POSTs to `/servers/{id}/vnc {vnc:true}` to rotate the wss token, returning `text/html` with the noVNC shell embedded (hidden `#con` / `#pass` / `#server-name` inputs + `<script src="{vfBaseUrl}/vnc/vnc.js">`). Headers: `X-Frame-Options: DENY`, `Cache-Control: no-store, private`.
- The wss URL never appears in any URL the customer can copy or share. Each open rotates the token, so any prior credential exposure is short-lived. Other customers landing on the popup URL get a 403 from the ownership check.
- The popup HTML is delivered with a strict CSP (`default-src 'none'`, `script-src` restricted to the WHMCS host + the VirtFusion panel origin, `connect-src` restricted to the VF wss endpoint + panel) and `X-Frame-Options: DENY` so the viewer cannot be re-hosted or embedded.
### Removed Features ### Removed Features
- **Firewall** — Removed (non-functional; rulesets must be created in VirtFusion admin panel) - **Firewall** — Removed (non-functional; rulesets must be created in VirtFusion admin panel)
- **IP add/remove buttons** — Removed; IPs are managed by VirtFusion during provisioning - **IP add/remove buttons** — Removed; IPs are managed by VirtFusion during provisioning
- **Upgrade/Downgrade link** — Removed from resources panel - **Upgrade/Downgrade link** — Removed from resources panel
- **VNC enable/disable toggle** — Removed in 1.5.0. VirtFusion's POST `/vnc {vnc:false}` only manipulates a firewall flag that's currently broken at the panel level; the wss endpoint accepts WebSocket upgrades regardless. Toggle was misleading. VNC is treated as always-available, gated by WHMCS session + service ownership at our layer.
- **Standalone Network panel** — Removed in 1.5.0. Duplicated Server Overview's IP rows. Per-IP copy buttons moved into the Overview cells via `vfRenderIpCells()`.
- **Network Speed row** in the Resources panel — Removed in 1.5.0. VirtFusion's `inAverage` / `outAverage` etc. all return 0 in our setup; the row was always empty.
### Data Flow: Server Creation ### Data Flow: Server Creation
@@ -89,14 +111,77 @@ The `publish-release.yml` workflow creates a GitHub/Gitea release with auto-gene
4. Dry-run validation → actual API POST to `/servers` 4. Dry-run validation → actual API POST to `/servers`
5. Stores server ID in `mod_virtfusion_direct` table 5. Stores server ID in `mod_virtfusion_direct` table
6. Updates WHMCS hosting record (IP, username, password, domain) 6. Updates WHMCS hosting record (IP, username, password, domain)
7. Calls `ConfigureService::initServerBuild()` with selected OS + SSH key 7. If the PowerDNS addon is enabled, calls `PowerDns\PtrManager::syncServer()` to write PTRs (non-blocking; failures log but never fail provisioning)
8. Calls `ConfigureService::initServerBuild()` with selected OS + SSH key
Custom fields (`Initial Operating System`, `Initial SSH Key`) are auto-created by `Database::ensureCustomFields()` on module load for all products using this module. No manual SQL setup required. Custom fields (`Initial Operating System`, `Initial SSH Key`) are auto-created by `Database::ensureCustomFields()` on module load for all products using this module. No manual SQL setup required.
### Reverse DNS (PowerDNS)
Opt-in integration via the companion `VirtFusionDns` addon module. Loose-coupled: the server module never requires addon code at runtime; it queries the addon's `tbladdonmodules` row and short-circuits when `enabled=0` or the addon isn't activated. Activate via WHMCS Admin → Addon Modules → VirtFusion DNS.
**Settings** (`tbladdonmodules`, module="virtfusiondns"): `enabled` (yesno), `endpoint` (e.g. `https://ns1.example.com:8081`), `apiKey` (encrypted by WHMCS), `serverId` (usually `localhost`), `defaultTtl` (3600), `cacheTtl` (60).
**Lifecycle hooks:**
- `createAccount` → sync PTRs to server hostname (forward DNS must match before each write)
- `renameServer` → update only PTRs whose current content equals the old hostname (preserves client-custom PTRs)
- `terminateAccount` → delete every PTR before `Database::deleteSystemService()`
- `VirtFusionDirect_TestConnection` → merged VirtFusion + PowerDNS health check
- `DailyCronJob``PtrManager::reconcileAll()` — additive-only (never overwrites)
**Client-facing actions** (`client.php`): `rdnsList`, `rdnsUpdate`. Admin (`admin.php`): `rdnsStatus`, `rdnsReconcile` (accepts `force=1` for explicit reset).
**Client UI:** Reverse DNS panel in `templates/overview.tpl` (rendered by `vfLoadRdns()` / `vfRenderRdnsPanel()` / `vfUpdateRdns()` in `module.js`). Admin services tab gets a status widget via `AdminHTML::rdnsSection()`.
**FCrDNS rule:** Every PTR write (auto or client-initiated) requires the hostname's forward DNS (A/AAAA) to already resolve to the target IP. On mismatch, auto-sync logs and skips; client edits return a 400 with guidance.
**Zone handling:** Zones are operator-managed — the module never creates zones. Zone discovery uses `GET /zones` (cached for `cacheTtl`) + longest-suffix match. RFC 2317 classless delegations (`X/Y.octet.octet.octet.in-addr.arpa.`) are supported: both CIDR-prefix (`0/26`) and block-size (`64/64`) conventions are parsed, and PTRs are written with the classless sub-zone label in the record name.
**SOA / NOTIFY:** PowerDNS auto-bumps SOA serials when `soa_edit_api=INCREASE` is set on the zone. After every successful PATCH the module issues an explicit `PUT /zones/{id}/notify` so slaves refresh immediately rather than waiting for the next scheduled poll.
**Safety properties:**
- PowerDNS failures never block VirtFusion operations (try/catch at every call site)
- Cron is additive-only — never auto-overwrites a PTR
- Admin Reconcile button supports `force=1` for explicit reset to hostname
- Client edits are IP-ownership-checked against a *fresh* VirtFusion fetch (not cached `server_object`), defending against reassigned-IP stale-ownership
- Per-IP write rate limit (10s, via `Cache`) prevents save-button abuse
### Configurable Option Mapping ### Configurable Option Mapping
Custom option names can be mapped in `config/ConfigOptionMapping.php` (copy from `-example.php`). Default mapping keys: `packageId`, `hypervisorId`, `ipv4`, `storage`, `memory`, `traffic`, `cpuCores`, `networkSpeedInbound`, `networkSpeedOutbound`, `networkProfile`, `storageProfile`. Custom option names can be mapped in `config/ConfigOptionMapping.php` (copy from `-example.php`). Default mapping keys: `packageId`, `hypervisorId`, `ipv4`, `storage`, `memory`, `traffic`, `cpuCores`, `networkSpeedInbound`, `networkSpeedOutbound`, `networkProfile`, `storageProfile`.
### Inventory / Stock Control
Opt-in per product via WHMCS's native stock-control toggle (`tblproducts.stockcontrol=1`). When enabled, the module overwrites `tblproducts.qty` with the real number of VPSes that can still be provisioned — WHMCS then handles the "Out of Stock" badge, Add-to-Cart gating, and checkout refusal natively. No templates or JS required.
**Data sources (authoritative):**
- `GET /packages/{id}` — per-VPS resource footprint (`memory`, `cpuCores`, `primaryStorage`, `primaryStorageProfile`, `enabled`)
- `GET /compute/hypervisors/groups/{id}/resources` — live free/allocated per hypervisor with per-metric quotas, storage pools (filtered by `pool.storageType` against the package's `primaryStorageProfile` *type code* — see Safety properties), and a group-level IPv4 pool
**Algorithm:** for every group the product can be placed in (default `configoption1` plus every numeric value of the `Location` configurable option), sum `min(memory, cpu, storage)` across eligible hypervisors (enabled AND commissioned AND !prohibit) and cap by the group-level IPv4 pool (`max` across hypervisors, not summed — IPv4 is a single group-wide pool). Sum across groups → qty.
**Triggers:**
- `AfterModuleCreate` — post-provision refresh; bursts rate-limited to one recalc per 30 s via `stockrefresh:event` cache key.
- `AfterModuleTerminate` — post-termination refresh; shares the same 30 s rate-limit key.
- `AfterCronJob` — every-2-hour safety net (captures out-of-band VirtFusion panel changes). Tunable via `STOCK_CRON_INTERVAL_SECONDS` constant in `hooks.php`.
- `ClientAreaPageCart` — opportunistic per-product refresh on cart/order pages with a 60 s rate-limit key (`stockrefresh:{pid}`). The `grpres:{id}` cache (120 s TTL) naturally coalesces bursts.
- `admin.php?action=stockRecalculate` — admin-triggered full recalc (POST + same-origin required); returns JSON `{productId: qty}` map.
**Order auto-accept:** `AfterModuleCreate` additionally calls WHMCS `AcceptOrder` with `autosetup=false` when the service's parent order is still Pending. Closes the loop for installs that rely on pending-order workflows for non-VF products but want VF provisions to auto-advance.
**Caching:** `pkg:{id}` 600 s (package definitions rarely change), `grpres:{id}` 120 s (resources change under load). Confirmed 404s cached 60 s so re-creating a deleted package/group takes effect quickly.
**Safety properties:**
- Transient API failures (null from `fetchPackage` / `fetchGroupResources`) leave `qty` UNTOUCHED — never silently takes the catalogue offline.
- Confirmed-missing conditions (HTTP 404 on package, `package.enabled=false`) return qty=0 — the product genuinely cannot be provisioned.
- IPv4 cap is max-within-group (not summed across hypervisors) to avoid double-counting the shared pool.
- Storage matching uses the package's `primaryStorageProfile` as a **storage type code** (it mirrors VirtFusion's `server_packages.storage_type` column — a *filter*, not a pool id). The hypervisor must expose at least one `otherStorage[]` pool whose `storageType` equals that code; if multiple match (e.g. several mountpoint pools on the same hypervisor) the one that fits the most VMs wins. A disabled pool is skipped, not fatal — an enabled peer of the same type still contributes. Hypervisors with no pool of the matching type contribute 0. Falls back to `localStorage` only when the package has no profile set (`primaryStorageProfile <= 0`).
- Stock control is gated by `tblproducts.stockcontrol=1` per product — the module never touches qty on products that opt out.
**Per-product setting:** `stockSafetyBufferPct` (configoption7, default 10). Reserves X% of each resource's `max` before computing fits; ignored for unlimited resources (`max=0`) and for IPv4 (no per-hypervisor `max` in the response). Admins can override per product in the module settings; blank falls back to 10%.
**API scope required:** the VirtFusion API token must have read access to both `/packages` and `/compute/hypervisors/groups`. The Test Connection button probes the compute endpoint and shows a clear error if scope is missing.
## Security Patterns ## Security Patterns
- All PHP files start with `if (!defined("WHMCS")) die()` to prevent direct access (except entry points using `init.php`) - All PHP files start with `if (!defined("WHMCS")) die()` to prevent direct access (except entry points using `init.php`)
@@ -110,12 +195,26 @@ Custom option names can be mapped in `config/ConfigOptionMapping.php` (copy from
## VirtFusion API Compatibility ## VirtFusion API Compatibility
- **API reference (OpenAPI spec):** https://docs.virtfusion.com/api/openapi.yaml - **API reference (OpenAPI spec):** https://docs.virtfusion.com/api/openapi.yaml
- **Tested against:** VirtFusion v7.0.0 Build 9 (current production target as of 2026-04-28)
- **Base features:** VirtFusion v1.7.3+ - **Base features:** VirtFusion v1.7.3+
- **VNC console:** v6.1.0+ - **VNC console:** v6.1.0+ — POST `/servers/{id}/vnc` with `{vnc: bool}` (NOT `{enabled: bool}` — the latter is a silent no-op). Response includes `data.vnc.{ip, port, password, wss.{token, url}, enabled}`. The `enabled` field is unreliable in v7.0.0 — it tracks "active session" rather than panel-toggle state, and the wss endpoint accepts WebSocket upgrades regardless of the toggle. Treat VNC as always-available and gate it at the WHMCS-session layer.
- **noVNC viewer:** the wss URL (`{baseUrl}/vnc/?token=<uuid>`) is the raw WebSocket endpoint; loading it as HTTP returns 405. The HTML viewer is assembled by the panel: an HTML shell with hidden `#con` (wss URL), `#pass` (VNC password), `#server-name` inputs, plus `<script src="{baseUrl}/vnc/vnc.js">`. The module reproduces this shell server-side via `client.php?action=vncViewer` (see Security model below).
- **Resource modification:** v6.2.0+ - **Resource modification:** v6.2.0+
- **Live state introspection:** `?remoteState=true` query param returns `remoteState.{state, cpu, memory.{actual,unused,available,rss}, disk.vda.{rd.bytes,wr.bytes}, agent.fsinfo[]}`. fsinfo only populated when qemu-guest-agent is running on the guest. Heavier than the bare `/servers/{id}` call (libvirt round-trip on the hypervisor).
- **Traffic history:** `/servers/{id}/traffic` returns `data.monthly[]` aggregates only — VirtFusion does NOT expose daily granularity. The `monthly[i].{rx, tx, total}` are bytes; `limit` is GB (0 = unmetered). The server fetch's `traffic.public.currentPeriod` only exposes the period window (start/end/limit), NOT the byte counter.
- **Self-service billing:** Requires self-service feature enabled in VirtFusion - **Self-service billing:** Requires self-service feature enabled in VirtFusion
- **OS icon path:** `{baseUrl}/img/logo/{icon_filename}` (public, no auth required) - **OS icon path:** `{baseUrl}/img/logo/{icon_filename}` (public, no auth required)
## PowerDNS API Compatibility
- **API reference:** https://doc.powerdns.com/authoritative/http-api/
- **Tested against:** PowerDNS Authoritative 4.8+
- **Auth:** `X-API-Key` header (not Bearer)
- **Required endpoints:** `GET /servers/{id}`, `GET /servers/{id}/zones`, `GET /servers/{id}/zones/{zone}`, `PATCH /servers/{id}/zones/{zone}`, `PUT /servers/{id}/zones/{zone}/notify`
- **Zone ID URL encoding:** `/` in zone names (RFC 2317) must be encoded as `=2F` not `%2F` — handled by `Client::zoneIdEncode()`
- **`api-allow-from`:** must include the WHMCS host's IP (PowerDNS's own ACL)
- **Recommended zone config:** `soa_edit_api: INCREASE` for automatic serial bumping on API-driven changes
## Product Config Options ## Product Config Options
| Option | Name | Description | Default | | Option | Name | Description | Default |
@@ -126,10 +225,22 @@ Custom option names can be mapped in `config/ConfigOptionMapping.php` (copy from
| configoption4 | Self-Service Mode | 0=Disabled, 1=Hourly, 2=Resource Packs, 3=Both | 0 | | configoption4 | Self-Service Mode | 0=Disabled, 1=Hourly, 2=Resource Packs, 3=Both | 0 |
| configoption5 | Auto Top-Off Threshold | Credit balance below which auto top-off triggers | 0 | | configoption5 | Auto Top-Off Threshold | Credit balance below which auto top-off triggers | 0 |
| configoption6 | Auto Top-Off Amount | Credit amount to add on auto top-off | 100 | | configoption6 | Auto Top-Off Amount | Credit amount to add on auto top-off | 100 |
| configoption7 | Stock Safety Buffer (%) | Headroom reserved per resource during stock calculation (0-100). Only effective with WHMCS stock control enabled. Blank falls back to the default. | 10 |
## WHMCS Compatibility ## WHMCS Compatibility
- WHMCS 8.x+ (tested 8.08.10) - WHMCS 8.x and 9.x supported
- PHP 8.0+ with cURL extension - **Tested against:** WHMCS 9.0.3 (current production target as of 2026-04-28); broadly compatible with 8.10 and earlier 8.x releases
- PHP 8.2+ required for WHMCS 9.x; PHP 8.0+ for WHMCS 8.x (matches the WHMCS minimums for each major)
- cURL extension required
### WHMCS 9 caveats
- Batch order acceptance terminates as soon as the order leaves Pending status. The module's `AfterModuleCreate` hook defers `localAPI('AcceptOrder')` until every VirtFusionDirect service in the order has a `mod_virtfusion_direct.server_id` row, so multi-VPS orders provision cleanly. WHMCS 8 was not affected (its loop ignored order status mid-batch).
- Email template rendering requires a properly-configured Storage backend (System Settings → Storage Settings). If the storage config has no `region` set (common with S3-compatible providers like Storj), template-based emails silently fail before SMTP is even contacted, while custom-message admin emails (e.g. cron activity reports) keep working. Setting any non-empty region value (e.g. `us-east-1`, `auto`, `US1` for Storj) restores templates.
### Module debug logging
`Log::insert()` wraps `logModuleCall()`, which only writes to `tblmodulelog` when **Module Debug Logging** is enabled (WHMCS Admin → Utilities → Logs → Module Log → Activate Module Debug Logging). When off, calls succeed silently and nothing lands in the table. Enable it before relying on the log table for diagnostics — or invoke module methods directly via `php -r` from the CLI for one-off testing.
- Redis extension optional (improves caching performance, falls back to filesystem) - Redis extension optional (improves caching performance, falls back to filesystem)
- All WHMCS themes supported (Six, Twenty-One, Lagom, custom) via Bootstrap 3/4/5 dual classes - All WHMCS themes supported (Six, Twenty-One, Lagom, custom) via Bootstrap 3/4/5 dual classes

128
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
support@ezscale.cloud.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

308
README.md
View File

@@ -20,6 +20,8 @@ A comprehensive WHMCS provisioning module for [VirtFusion](https://virtfusion.co
- [Module Configuration Options](#module-configuration-options) - [Module Configuration Options](#module-configuration-options)
- [Configurable Options (Dynamic Pricing)](#configurable-options-dynamic-pricing) - [Configurable Options (Dynamic Pricing)](#configurable-options-dynamic-pricing)
- [Custom Option Name Mapping](#custom-option-name-mapping) - [Custom Option Name Mapping](#custom-option-name-mapping)
- [Stock Control (Dynamic Inventory)](#stock-control-dynamic-inventory)
- [Reverse DNS Addon (PowerDNS)](#reverse-dns-addon-powerdns)
- [Client Area Features](#client-area-features) - [Client Area Features](#client-area-features)
- [Admin Area Features](#admin-area-features) - [Admin Area Features](#admin-area-features)
- [Theme Compatibility](#theme-compatibility) - [Theme Compatibility](#theme-compatibility)
@@ -35,10 +37,10 @@ A comprehensive WHMCS provisioning module for [VirtFusion](https://virtfusion.co
| Requirement | Minimum Version | Notes | | Requirement | Minimum Version | Notes |
|---|---|---| |---|---|---|
| **VirtFusion** | v1.7.3+ | v6.1.0+ required for VNC console | | **VirtFusion** | v1.7.3+ | Tested against **v7.0.0 Build 9** (current production target). v6.1.0+ required for VNC console; v6.2.0+ for resource modification. |
| **WHMCS** | 8.x+ | Tested with 8.0 through 8.10 | | **WHMCS** | 8.x or 9.x | Tested against **WHMCS 9.0.3** (current production target); broadly compatible with 8.10 and earlier 8.x releases. |
| **PHP** | 8.0+ | With cURL extension enabled | | **PHP** | 8.2+ for WHMCS 9.x; 8.0+ for WHMCS 8.x | With cURL extension enabled. |
| **SSL** | Valid certificate | Required on VirtFusion panel | | **SSL** | Valid certificate | Required on the VirtFusion panel. |
You also need a VirtFusion API token with the following permissions: You also need a VirtFusion API token with the following permissions:
- Server management (create, read, update, delete, power, build) - Server management (create, read, update, delete, power, build)
@@ -57,17 +59,23 @@ You also need a VirtFusion API token with the following permissions:
- Automatic memory unit conversion (GB to MB for values < 1024) - Automatic memory unit conversion (GB to MB for values < 1024)
### Client Area - Server Management ### Client Area - Server Management
- **Server Overview** - Real-time server info (hostname, IPs, resources) with status badge - **Server Overview** - Real-time server info (hostname, IPs, resources) with status badge, plus location flag, OS template name, and "Created N days ago" lifetime chips
- **VNC Console** - Browser-based console access via a popup window. Loads VirtFusion's noVNC viewer through a same-origin authenticated route (`client.php?action=vncViewer`), session-gated and ownership-validated; wss token rotates on every open and never appears in any URL
- **Hypervisor Maintenance Banner** - Yellow alert at the very top of the page when the hypervisor is in maintenance, so customers know to expect transient errors
- **Traffic Chart** - Last 12 months of bandwidth usage (rx + tx) as side-by-side monthly bars, plus current period used/limit/remaining tile
- **Live Stats** - CPU, memory, and disk I/O sourced from VirtFusion's libvirt introspection, auto-refreshing every 30 s while the panel is visible
- **Filesystem Usage** - Per-mount usage rows from qemu-guest-agent (when installed on the VM), with progress bars and warning thresholds
- **Power Management** - Start, restart, graceful shutdown, and force power off - **Power Management** - Start, restart, graceful shutdown, and force power off
- **Control Panel SSO** - One-click login to VirtFusion panel - **Control Panel SSO** - One-click login to VirtFusion panel from the Server Overview footer
- **Server Rebuild** - Reinstall with any available OS template - **Server Rebuild** - Reinstall with any available OS template
- **Password Reset** - Reset VirtFusion panel login credentials - **Password Reset** - Reset VirtFusion panel login credentials
- **Network Management** - View IPv4 addresses and IPv6 subnets with copy-to-clipboard - **IP Management** - IPv4 + IPv6 listed inline in the Server Overview cells, each with a per-address copy button
- **Resources Panel** - Current memory, CPU, storage, traffic allocation with usage bars - **Resources Panel** - Current memory, CPU, storage, traffic allocation with usage bars
- **VNC Console** - Browser-based console access (panel auto-hides when VNC is disabled on the server) - **Mask Sensitive (Screenshot Mode)** - Toggle in the Server Overview meta bar that masks IPs (keeps subnet visible: `205.186.•••.•••`), IPv6 (keeps prefix), hostnames, and the Server Name + Reverse DNS hostname inputs. Useful for support screenshots and screen-shares; state persists across page refreshes via `sessionStorage`
- **Self-Service Billing** - Credit balance display, usage breakdown, and credit top-up (when enabled) - **Self-Service Billing** - Credit balance display, usage breakdown, and credit top-up (when enabled)
- **Bandwidth Usage** - Traffic usage display with allocation limits - **Bandwidth Usage** - Traffic usage display with allocation limits
- **Billing Overview** - Product, billing cycle, dates, and payment information - **Billing Overview** - Product, billing cycle, dates, and payment information
- **In-Page Section Navigation** - "On This Page" group injected into the WHMCS Actions sidebar with smooth-scroll jump-links to every visible panel; auto-hides links for hidden panels (e.g. Live Stats when remoteState is unavailable, Reverse DNS when PowerDNS isn't configured)
### Admin Area ### Admin Area
- **Test Connection** - Verify API connectivity from WHMCS - **Test Connection** - Verify API connectivity from WHMCS
@@ -85,6 +93,15 @@ You also need a VirtFusion API token with the following permissions:
- Checkout validation ensuring OS selection before order placement - Checkout validation ensuring OS selection before order placement
- **Resource sliders** - Configurable option dropdowns are replaced with interactive range sliders - **Resource sliders** - Configurable option dropdowns are replaced with interactive range sliders
- Compatible with all WHMCS order form templates - Compatible with all WHMCS order form templates
- **Order auto-accept after provision** — when a paid order's VirtFusion service provisions successfully, the module calls WHMCS `AcceptOrder` (with `autosetup=false` so there's no double-provision) to flip the order from Pending → Active automatically. Idempotent; already-accepted orders are untouched.
### Stock Control (Dynamic Inventory)
- **Out-of-stock badges driven by real hypervisor capacity** — opt-in per product via WHMCS's native Stock Control toggle. When enabled, the module keeps `tblproducts.qty` synced to the number of VPSes the panel can still actually provision, and WHMCS renders the "Out of Stock" badge, disables Add-to-Cart, and refuses checkout natively. No templates or JavaScript required.
- **Live-capacity math** — combines `/packages/{id}` (per-VPS resource footprint) with `/compute/hypervisors/groups/{id}/resources` (live per-hypervisor free/allocated) to compute qty across every group the product can be placed in. Storage matching is by **type code** (`pool.storageType`), so a package targeting e.g. mountpoint storage qualifies on every hypervisor that exposes a mountpoint pool — and picks the largest-fit pool when several share the same type. Group-level IPv4 pool accounted for without double-counting.
- **Event-driven refresh** — qty recalculates after every successful provision (`AfterModuleCreate`), termination (`AfterModuleTerminate`), and on cart/order page views for individual products. A 2-hour safety-net cron catches capacity changes made directly in the VirtFusion panel.
- **Per-product safety buffer** — `stockSafetyBufferPct` config option (default 10%) reserves headroom so the storefront stops selling before a hypervisor is literally at 100%.
- **Fail-safe under API outages** — transient VirtFusion API failures leave `qty` UNCHANGED instead of zeroing it, so a brief network blip doesn't take the catalogue offline.
- **Admin recalc on demand** — POST `admin.php?action=stockRecalculate` forces a full re-sweep.
### Usage Tracking ### Usage Tracking
- **Automated bandwidth sync** - WHMCS daily cron pulls traffic usage from VirtFusion - **Automated bandwidth sync** - WHMCS daily cron pulls traffic usage from VirtFusion
@@ -106,31 +123,103 @@ You also need a VirtFusion API token with the following permissions:
- Auto top-off via WHMCS cron when credit falls below threshold - Auto top-off via WHMCS cron when credit falls below threshold
- Self-service mode configurable per product (Hourly, Resource Packs, or Both) - Self-service mode configurable per product (Hourly, Resource Packs, or Both)
### Reverse DNS (Optional PowerDNS Addon)
- **Automatic PTR sync** on server create, rename, and terminate
- **Client-editable rDNS** panel in the service overview — one input per assigned IP
- **Forward-confirmed reverse DNS (FCrDNS)** — every PTR write requires the hostname's A/AAAA to already resolve to the IP; mismatches are rejected with a clear error
- **IPv4 + IPv6** support out of the box (IPv6 nibble-reversal, `.ip6.arpa` zones)
- **RFC 2317 classless delegation** — supports both CIDR-prefix (`0/26`) and block-size (`64/64`) zone naming conventions
- **Admin reconciliation** — a "Reconcile" button on the services tab and an additive-only daily cron that creates any missing PTRs
- **Client-custom PTRs preserved across renames** — only PTRs whose content matches the previous hostname get rewritten
- **Auto NOTIFY + SOA bump** so slaves pick up changes immediately (when `soa_edit_api=INCREASE` is set on the zone)
- **Opt-in** via a companion WHMCS addon module — no impact on existing provisioning if not activated
## Installation ## Installation
The fastest path is the install script. It auto-detects the WHMCS web user from your `modules/servers` directory ownership and applies it to the new files — without that, rsyncing as root would leave files owned by `root:root` and the web server couldn't read them ("module installed but invisible in WHMCS").
```bash ```bash
git clone https://github.com/EZSCALE/virtfusion-whmcs-module.git /tmp/vf && rsync -ahP --delete /tmp/vf/modules/servers/VirtFusionDirect/ /path/to/whmcs/modules/servers/VirtFusionDirect/ && rm -rf /tmp/vf curl -fsSL https://raw.githubusercontent.com/EZSCALE/virtfusion-whmcs-module/main/install.sh \
| sudo bash -s -- install /path/to/whmcs
``` ```
Replace `/path/to/whmcs` with your actual WHMCS installation root. The database table, schema migrations, and custom fields are all created automatically on first load. Same thing with `wget`:
```bash
wget -qO- https://raw.githubusercontent.com/EZSCALE/virtfusion-whmcs-module/main/install.sh \
| sudo bash -s -- install /path/to/whmcs
```
Flags:
- `--with-addon` — also install the PowerDNS reverse-DNS addon (`modules/addons/VirtFusionDns/`).
- `--version v1.4.1` — pin a specific release tag (default: latest published release; any tag from [Releases](https://github.com/EZSCALE/virtfusion-whmcs-module/releases)).
The database table, schema migrations, and custom fields are all created automatically on first load.
<details>
<summary><b>Manual install</b> (if you'd rather not pipe a script to bash)</summary>
```bash
WHMCS=/path/to/whmcs
VERSION=${VERSION:-$(curl -fsSL https://api.github.com/repos/EZSCALE/virtfusion-whmcs-module/releases/latest \
| sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p')}
OWNER=$(stat -c '%U:%G' "$WHMCS/modules/servers")
curl -fsSL "https://github.com/EZSCALE/virtfusion-whmcs-module/archive/refs/tags/${VERSION}.tar.gz" -o /tmp/vf.tar.gz \
&& mkdir -p /tmp/vf && tar -xzf /tmp/vf.tar.gz -C /tmp/vf --strip-components=1 \
&& rsync -ahP --delete --chown="$OWNER" /tmp/vf/modules/servers/VirtFusionDirect/ "$WHMCS/modules/servers/VirtFusionDirect/" \
&& rm -rf /tmp/vf /tmp/vf.tar.gz
```
`--chown="$OWNER"` ensures the new files match your WHMCS web user (`www-data`, `apache`, etc.) instead of `root:root`. Requires rsync 3.1+ and root (or already running as the matching user). To pin a version, prepend `VERSION=v1.4.1` before the command.
</details>
Then configure in WHMCS Admin: Then configure in WHMCS Admin:
1. **Add Server** — Configuration > System Settings > Servers > Add New Server. Set hostname to your VirtFusion panel (e.g. `cp.example.com`), type to "VirtFusion Direct Provisioning", and paste your API token in the Password field. Click **Test Connection** to verify. 1. **Add Server** — Configuration > System Settings > Servers > Add New Server. Set hostname to your VirtFusion panel (e.g. `cp.example.com`), type to "VirtFusion Direct Provisioning", and paste your API token in the Password field. Click **Test Connection** to verify.
2. **Create Product** — Configuration > System Settings > Products/Services. On the Module Settings tab, select "VirtFusion Direct Provisioning", choose your server, and set the Hypervisor Group ID, Package ID, and Default IPv4 count. 2. **Create Product** — Configuration > System Settings > Products/Services. On the Module Settings tab, select "VirtFusion Direct Provisioning", choose your server, and set the Hypervisor Group ID, Package ID, and Default IPv4 count.
3. *(Optional)* **Install the Reverse DNS Addon** — also sync the `modules/addons/VirtFusionDns/` directory if you want PowerDNS-backed rDNS management. See [Reverse DNS Addon (PowerDNS)](#reverse-dns-addon-powerdns) below for activation and configuration.
That's it. Hooks activate automatically and custom fields are created on module load. That's it. Hooks activate automatically and custom fields are created on module load.
## Upgrading ## Upgrading
```bash ```bash
git clone https://github.com/EZSCALE/virtfusion-whmcs-module.git /tmp/vf && rsync -ahP --delete /tmp/vf/modules/servers/VirtFusionDirect/ /path/to/whmcs/modules/servers/VirtFusionDirect/ && rm -rf /tmp/vf curl -fsSL https://raw.githubusercontent.com/EZSCALE/virtfusion-whmcs-module/main/install.sh \
| sudo bash -s -- upgrade /path/to/whmcs
``` ```
> **Note:** If you have a custom `config/ConfigOptionMapping.php`, back it up first — `--delete` will remove it. Restore it after upgrading. Add `--with-addon` if you also use the PowerDNS addon. Pin a version with `--version v1.4.1` for controlled rollouts or rollbacks. Addon settings live in `tbladdonmodules` and survive file updates. The script automatically backs up and restores any custom `config/ConfigOptionMapping.php` across the rsync `--delete`.
To check whether you're current without making any changes:
```bash
curl -fsSL https://raw.githubusercontent.com/EZSCALE/virtfusion-whmcs-module/main/install.sh \
| bash -s -- check /path/to/whmcs
```
Exit codes: `0` = up-to-date, `1` = outdated (or version unknown), `2` = not installed. Useful in cron-driven monitoring.
If you use theme-overridden templates, review them for any new template variables. Clear the WHMCS template cache after upgrading: **Configuration > System Settings > General Settings > clear template cache**. If you use theme-overridden templates, review them for any new template variables. Clear the WHMCS template cache after upgrading: **Configuration > System Settings > General Settings > clear template cache**.
<details>
<summary><b>Manual upgrade</b> (if you'd rather not pipe a script to bash)</summary>
```bash
WHMCS=/path/to/whmcs
VERSION=${VERSION:-$(curl -fsSL https://api.github.com/repos/EZSCALE/virtfusion-whmcs-module/releases/latest \
| sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p')}
OWNER=$(stat -c '%U:%G' "$WHMCS/modules/servers")
curl -fsSL "https://github.com/EZSCALE/virtfusion-whmcs-module/archive/refs/tags/${VERSION}.tar.gz" -o /tmp/vf.tar.gz \
&& mkdir -p /tmp/vf && tar -xzf /tmp/vf.tar.gz -C /tmp/vf --strip-components=1 \
&& rsync -ahP --delete --chown="$OWNER" /tmp/vf/modules/servers/VirtFusionDirect/ "$WHMCS/modules/servers/VirtFusionDirect/" \
&& rsync -ahP --delete --chown="$OWNER" /tmp/vf/modules/addons/VirtFusionDns/ "$WHMCS/modules/addons/VirtFusionDns/" \
&& rm -rf /tmp/vf /tmp/vf.tar.gz
```
The second `rsync` line is only needed if you use the Reverse DNS addon; skip it otherwise.
> **Note:** If you have a custom `config/ConfigOptionMapping.php`, back it up first — `--delete` will remove it. Restore it after. The helper script does this automatically.
</details>
## Configuration ## Configuration
### Server Setup ### Server Setup
@@ -161,7 +250,7 @@ The fields are hidden text boxes that are dynamically replaced by dropdown selec
### Module Configuration Options ### Module Configuration Options
Each product has three module-specific settings: Each product has these module-specific settings:
| Option | Name | Description | Default | | Option | Name | Description | Default |
|---|---|---|---| |---|---|---|---|
@@ -171,6 +260,7 @@ Each product has three module-specific settings:
| Config Option 4 | Self-Service Mode | Enable VirtFusion self-service billing (0=Disabled, 1=Hourly, 2=Resource Packs, 3=Both) | 0 | | Config Option 4 | Self-Service Mode | Enable VirtFusion self-service billing (0=Disabled, 1=Hourly, 2=Resource Packs, 3=Both) | 0 |
| Config Option 5 | Auto Top-Off Threshold | Credit balance below which auto top-off triggers during cron (0=disabled) | 0 | | Config Option 5 | Auto Top-Off Threshold | Credit balance below which auto top-off triggers during cron (0=disabled) | 0 |
| Config Option 6 | Auto Top-Off Amount | Credit amount to add when auto top-off triggers | 100 | | Config Option 6 | Auto Top-Off Amount | Credit amount to add when auto top-off triggers | 100 |
| Config Option 7 | Stock Safety Buffer (%) | Headroom reserved per resource during stock calculation (0-100). Only effective with WHMCS Stock Control enabled on the product; blank falls back to the default. | 10 |
You can find your Hypervisor Group IDs and Package IDs in the VirtFusion admin panel. You can find your Hypervisor Group IDs and Package IDs in the VirtFusion admin panel.
@@ -208,15 +298,123 @@ return [
]; ];
``` ```
### Stock Control (Dynamic Inventory)
Optional but recommended once the catalogue is backed by real hypervisor capacity. When enabled on a product, the module keeps `tblproducts.qty` synced with the number of VPSes the panel can still actually provision — then WHMCS renders "Out of Stock" badges, disables Add-to-Cart, and refuses checkout entirely on its own.
**Prerequisites:**
- The VirtFusion API token on the WHMCS server must have read access to both `/packages` and `/compute/hypervisors/groups`. The **Test Connection** button (Admin → System Settings → Servers) now probes the compute endpoint explicitly — if the token is missing that scope you'll see a clear error at config time instead of nightly silence.
- No addon to activate. Stock control is enabled per product via WHMCS's native toggle.
**Enabling it on a product:**
1. WHMCS Admin → **System Settings → Products/Services → Products/Services** → edit the product.
2. Under the **Details** tab, tick **Stock Control** and save. (Leave *Quantity* at 0 — the module will populate it on the next recalc.)
3. Optionally tune **Config Option 7 — Stock Safety Buffer (%)** in the **Module Settings** tab. Default 10% means the module reserves 10% of each resource's max before counting fits, so you stop selling before a hypervisor is at 100%. Set to 0 for no buffer, higher for more headroom.
4. Either wait for the next recalc event (within 2 hours) or force one immediately: POST to `modules/servers/VirtFusionDirect/admin.php?action=stockRecalculate` from an authenticated admin session.
**How qty is computed:**
For every stock-controlled VirtFusion product:
1. Resolve the set of hypervisor groups the product can be placed in — the default group (Config Option 1) plus every numeric value of the `Location` configurable option if one is attached.
2. Fetch the product's package via `GET /packages/{id}` for the per-VPS resource footprint (`memory`, `cpuCores`, `primaryStorage`, `primaryStorageProfile`).
3. For each eligible group, fetch live resources via `GET /compute/hypervisors/groups/{id}/resources`.
4. For each hypervisor in the group that passes eligibility (`enabled` AND `commissioned` AND `!prohibit`), compute `min(memory, cpu, storage)` fits — with the per-product buffer applied — against the matched storage pool. `package.primaryStorageProfile` is a **storage type code** (mirrors VirtFusion's `server_packages.storage_type` column — a *filter*, not a pool id), matched against each `otherStorage[].storageType`. If multiple pools on the same hypervisor share that type (e.g. several mountpoint pools), the one with the largest fit wins; disabled peers are skipped, not fatal. Falls back to `localStorage` only when the package has no profile set.
5. Sum across hypervisors in each group, cap by the group-level IPv4 pool (`max()` within a group to avoid double-counting the shared pool), then sum across groups → `qty`.
**Refresh triggers:**
| Event | Trigger | Rate limit |
|---|---|---|
| New provision | `AfterModuleCreate` hook | 30 s shared with termination |
| VPS termination | `AfterModuleTerminate` hook | 30 s shared with create |
| Cart / order page view | `ClientAreaPageCart` hook | 60 s per product |
| Out-of-band panel change safety net | `AfterCronJob` hook | 2 hours (tunable via `STOCK_CRON_INTERVAL_SECONDS` in `hooks.php`) |
| Admin manual recalc | `admin.php?action=stockRecalculate` (POST + same-origin) | On demand |
**Safety properties:**
- **Transient API failures leave `qty` UNCHANGED.** `Module::fetchPackage()` and `Module::fetchGroupResources()` return a tri-state `array | false | null`: `false` means "VirtFusion confirmed this doesn't exist → OOS is correct", `null` means "we can't tell right now → don't touch existing qty". Without this distinction the module would either zero out inventory during API blips or show inventory for deleted packages.
- **Confirmed-missing → qty=0.** HTTP 404 on the package or `package.enabled=false` forces qty=0, because the product genuinely cannot be provisioned.
- **Storage type mismatch → 0 for that hypervisor.** If the package targets storage type code `4` (mountpoint) but the hypervisor only exposes pools of type `0` (local default), that hypervisor contributes zero capacity — not a guess at "maybe placement will work out." This is a filter on `pool.storageType`, not on `pool.id`; identical type codes across different hypervisors all qualify, which is what makes multi-hypervisor mountpoint/datastore placement work.
- **Stock Control gate is absolute.** Products without `tblproducts.stockcontrol=1` are never touched, even by the cron safety net.
- **`\Throwable` catches** on every stock-path entry point (not just `\Exception`) so a `TypeError` from a malformed API response can't escape the tri-state contract.
**Caching:**
- `pkg:{packageId}` — 10 min TTL (package definitions rarely change)
- `grpres:{groupId}` — 120 s TTL (resources change minute-to-minute under load; shared across products that target the same group)
- Confirmed 404 responses cached 60 s so re-creating a deleted package/group takes effect quickly.
**Order auto-accept:** the `AfterModuleCreate` hook additionally calls WHMCS `AcceptOrder` with `autosetup=false` when the service's parent order is still in Pending status. This closes the loop for installs that rely on a pending-order workflow for non-VF products but want VirtFusion provisions to advance to Active automatically. Idempotent — already-accepted orders are skipped.
### Reverse DNS Addon (PowerDNS)
Optional. Activate the `VirtFusionDns` addon module to let the provisioning module manage PTR records in a PowerDNS instance automatically (and expose an rDNS editor to clients).
**Prerequisites:**
- PowerDNS Authoritative 4.x with the HTTP API enabled (`webserver=yes`, `api=yes`, and an `api-key=...` set)
- `api-allow-from=` must include the IP of your WHMCS host
- **All reverse zones you intend to use must already exist in PowerDNS.** The addon never creates zones; it only PATCHes PTR RRsets into zones that are already delegated to your nameservers.
- Zones should have `soa_edit_api=INCREASE` (or similar) so PowerDNS auto-bumps the SOA serial on API writes. The addon additionally calls `PUT /zones/{id}/notify` after every PATCH to push changes to slaves immediately.
**Activation:**
1. Copy the addon into your WHMCS install (see the Installation section for the `rsync` command).
2. In WHMCS Admin → **System Settings → Addon Modules**, find **VirtFusion DNS** and click **Activate**. Grant admin role access as needed.
3. Click **Configure** and fill in:
| Field | Meaning |
|---|---|
| **Enable rDNS Sync** | Master switch. When off, every PowerDNS call short-circuits — the provisioning module behaves exactly as before the addon. |
| **PowerDNS API Endpoint** | Scheme + host + port, no path (e.g. `https://ns1.example.com:8081` or `http://10.0.0.5:8081`). The module appends `/api/v1/…` itself. |
| **PowerDNS API Key** | Password-type field. Encrypted at rest by WHMCS; decrypted server-side only when PowerDNS is called. |
| **PowerDNS Server ID** | Almost always `localhost` — the PowerDNS API server identifier, not a hostname. |
| **Default PTR TTL** | Applied to every PTR record the module creates. Default 3600. |
| **Cache TTL** | How long zone listings and DNS-resolution lookups are cached. Default 60, minimum 10. |
4. Click **Save Changes**.
5. Open the addon's admin page (same menu, usually **Addons → VirtFusion DNS**) and click **Run Test**. You should see "OK — PowerDNS reachable and authenticated" followed by a list of visible zones. If you don't see your expected reverse zones here, the module won't find them either — fix PowerDNS first.
**How it behaves:**
| Event | Behavior |
|---|---|
| Server provisioning | Creates a PTR for every assigned IP pointing to the VirtFusion hostname — but only if that hostname's A/AAAA already resolves to the IP. Forward-missing IPs are logged and skipped (provisioning still succeeds). |
| Server rename (via client or admin) | Rewrites only PTRs whose current content equals the previous hostname. Client-customised PTRs are preserved. |
| Server termination | Deletes every PTR belonging to the server before the local record is purged. |
| Client edits PTR in the Reverse DNS panel | Validates IP ownership (cross-checked against a fresh VirtFusion fetch), PTR regex, per-IP 10-second rate limit, and forward-DNS match. Empty value deletes. |
| Daily cron | Creates PTRs for IPs that don't have one yet (and whose forward DNS resolves correctly). **Additive-only — never overwrites.** |
| Admin "Reconcile (force reset)" button | The only code path that overwrites a non-matching PTR — explicit admin action. |
**RFC 2317 classless delegations** are supported: the module parses zones like `64/64.38.186.66.in-addr.arpa.` (both CIDR-prefix and block-size conventions), matches IPs by range rather than suffix, and writes PTRs with the correct classless RRset name. The PowerDNS URL-safe zone ID encoding (`/``=2F`) is handled transparently.
**Security posture:**
- PowerDNS integration is **opt-in** — if the addon is deactivated or `Enable rDNS Sync` is off, the provisioning module behaves exactly as before.
- Every client-facing rDNS endpoint validates service ownership and re-verifies the IP is currently assigned to the requesting user's server (defends against stale-ownership after IP reassignment).
- The API key is stored encrypted in `tbladdonmodules` by WHMCS; it is never logged.
- DNS write failures never block VirtFusion operations — provisioning, rename, and termination all succeed regardless of PowerDNS state, and errors are recorded in the WHMCS Module Log for review.
## Client Area Features ## Client Area Features
### Server Overview ### Server Overview
Displays real-time server information fetched from VirtFusion: Displays real-time server information fetched from VirtFusion:
- Server name and hostname - Server name (editable inline) and hostname
- **Meta chips:** data-center location with country flag, OS template name (with kernel version on hover when qemu-guest-agent is installed), and "Created N days ago" lifetime tag
- **Mask Sensitive toggle** — masks IPs (last two octets for v4, post-prefix for v6), hostnames, and Server Name input via CSS `text-security: disc`. State persists across refreshes via `sessionStorage` for screen-share / screenshot workflows
- Memory, CPU cores, storage allocation - Memory, CPU cores, storage allocation
- IPv4 and IPv6 addresses - IPv4 and IPv6 addresses, each rendered with its own copy button
- Traffic usage vs. allocation - Traffic usage vs. allocation (e.g. "0.04 GB / Unmetered" or "234 GB / 6 TB")
- Server status badge (Active, Suspended, etc.) - Server status badge (Active, Suspended, etc.)
- **"Login to Control Panel"** footer button — opens VirtFusion in a new tab via one-shot SSO
### Hypervisor Maintenance Banner
Yellow alert injected at the very top of the page when `hypervisor.maintenance=true` in the VirtFusion API response. Sets the customer's expectation that operations may be temporarily unavailable, reducing support tickets for known maintenance windows.
### Traffic Chart
A canvas chart between Server Overview and Power Management showing the last 12 months of bandwidth usage as side-by-side rx/tx bars. Sourced from VirtFusion's `/servers/{id}/traffic` endpoint (monthly aggregates only — VirtFusion does not expose daily granularity). Tile below the chart shows the current period's used / limit / remaining.
### Live Stats
CPU, memory, and disk I/O sourced from VirtFusion's libvirt introspection (`?remoteState=true`). CPU and memory render as colored progress bars with warning thresholds (75% / 90%). Disk I/O shows cumulative bytes since boot. Auto-refreshes every 30 s while the panel is visible AND the page has focus — pauses on `visibilitychange` so it doesn't hammer libvirt when the customer alt-tabs away.
### Power Management ### Power Management
Four power control buttons: Four power control buttons:
@@ -225,14 +423,19 @@ Four power control buttons:
- **Shutdown** - Graceful ACPI shutdown - **Shutdown** - Graceful ACPI shutdown
- **Force Off** - Immediate power cut (use with caution) - **Force Off** - Immediate power cut (use with caution)
### Network Management
- View all IPv4 addresses and IPv6 subnets assigned to the server
- Copy IP addresses to clipboard with one click
### VNC Console ### VNC Console
- Opens a browser-based VNC console to the server - Single "Open Console" button at the very top of the page (no toggle — see Known Issues for why)
- Opens a 1024×768 popup window with VirtFusion's noVNC viewer
- The popup is served by `client.php?action=vncViewer` — same-origin, session-required, ownership-validated
- The wss token rotates on every open; previously-leaked tokens become invalid
- Requires VirtFusion v6.1.0+ and the server must be running - Requires VirtFusion v6.1.0+ and the server must be running
- Opens in a new browser window/tab
### Resources Panel
- Memory, CPU, storage, traffic limits with usage bars where applicable
- **Filesystem Usage** section (when qemu-guest-agent is installed in the VM) — per-mount progress bars with warning thresholds; pseudo-FS (`proc`, `sysfs`, `/boot`, `/run`, etc.) filtered out
### In-Page Section Navigation
"On This Page" group injected into the WHMCS Actions sidebar via the `ClientAreaPrimarySidebar` hook. Smooth-scrolls to each section on click. Auto-hides links for panels that aren't rendered on this particular service (e.g. Live Stats when no remoteState data, Reverse DNS when PowerDNS isn't configured). Theme-agnostic — works in Six, Twenty-One, Lagom, etc.
### Server Rebuild ### Server Rebuild
- Select from available OS templates (filtered by server package) - Select from available OS templates (filtered by server package)
@@ -250,6 +453,14 @@ Four power control buttons:
- Registration and next due dates - Registration and next due dates
- Payment method - Payment method
### Reverse DNS *(requires the VirtFusion DNS addon)*
A panel listing every IP assigned to the server with an inline editor for the PTR record:
- One input per IP — populate to set a custom PTR, leave blank to delete
- Per-row status badge (OK / unverified / no PTR / no zone / error)
- Saves are rate-limited to one write per IP per 10 seconds
- Forward DNS must already resolve to the IP; mismatches show an inline error guiding the client to fix their A/AAAA first
- Hidden entirely when the addon is not activated
## Admin Area Features ## Admin Area Features
### Admin Services Tab ### Admin Services Tab
@@ -258,6 +469,7 @@ When viewing a service in WHMCS admin, the module adds:
- **Server Info** - Button to load live data from VirtFusion API - **Server Info** - Button to load live data from VirtFusion API
- **Server Object** - Full JSON response viewer - **Server Object** - Full JSON response viewer
- **Options** - Admin impersonation link - **Options** - Admin impersonation link
- **Reverse DNS** *(when the VirtFusion DNS addon is activated)* - Live per-IP PTR status plus **Reconcile (additive)** and **Reconcile (force reset)** buttons
### Module Commands (Admin Buttons) ### Module Commands (Admin Buttons)
- **Create** - Provision a new server - **Create** - Provision a new server
@@ -344,7 +556,7 @@ WHMCS automatically loads theme-specific templates when they exist. Copy the ori
| `POST` | `/selfService/credit/byUserExtRelationId/{id}` | Add credit by WHMCS client ID | | `POST` | `/selfService/credit/byUserExtRelationId/{id}` | Add credit by WHMCS client ID |
| `GET` | `/servers/{id}/traffic` | Traffic statistics | | `GET` | `/servers/{id}/traffic` | Traffic statistics |
| `GET` | `/backups/server/{id}` | Backup listing | | `GET` | `/backups/server/{id}` | Backup listing |
| `POST` | `/servers/{id}/vnc` | Toggle VNC on/off | | `POST` | `/servers/{id}/vnc` | Rotate VNC credentials (`{vnc:true}`) — called by the secure viewer route on every popup open |
| `POST` | `/servers/{id}/resetPassword` | Reset server root password | | `POST` | `/servers/{id}/resetPassword` | Reset server root password |
### Advanced ### Advanced
@@ -357,6 +569,18 @@ WHMCS automatically loads theme-specific templates when they exist. Copy the ori
| `PUT` | `/servers/{id}/modify/traffic` | Modify traffic (v6.0.0+) | | `PUT` | `/servers/{id}/modify/traffic` | Modify traffic (v6.0.0+) |
| `POST/DELETE` | `/servers/{id}/backup/plan` | Backup plan management (v4.3.0+) | | `POST/DELETE` | `/servers/{id}/backup/plan` | Backup plan management (v4.3.0+) |
### PowerDNS (Reverse DNS addon, PowerDNS Authoritative 4.x+)
| Method | Endpoint | Purpose |
|---|---|---|
| `GET` | `/api/v1/servers/{id}` | Health check (Test Connection button) |
| `GET` | `/api/v1/servers/{id}/zones` | Zone discovery (cached per `cacheTtl`) |
| `GET` | `/api/v1/servers/{id}/zones/{zone}` | Fetch current RRsets for status + reads |
| `PATCH` | `/api/v1/servers/{id}/zones/{zone}` | Create / replace / delete PTR RRsets |
| `PUT` | `/api/v1/servers/{id}/zones/{zone}/notify` | NOTIFY slaves after every successful PATCH |
Authentication is via the `X-API-Key` header (configured in the addon). Zone IDs containing `/` (RFC 2317 classless) are URL-encoded as `=2F` per PowerDNS convention.
## Usage Update (Cron) ## Usage Update (Cron)
The module implements the `UsageUpdate` function that is called by the WHMCS daily cron. It automatically syncs: The module implements the `UsageUpdate` function that is called by the WHMCS daily cron. It automatically syncs:
@@ -426,8 +650,9 @@ This data appears in the WHMCS client area and admin product details.
1. Requires VirtFusion v6.1.0 or higher 1. Requires VirtFusion v6.1.0 or higher
2. The server must be powered on and running 2. The server must be powered on and running
3. Check that VNC is enabled for the hypervisor in VirtFusion 3. Popup blockers may prevent the console window from opening — allow popups for the WHMCS host
4. Popup blockers may prevent the console window from opening 4. Module routes the popup through `client.php?action=vncViewer` (same-origin, session-required). If the popup redirects to the WHMCS login page, your client session has expired — log in again and retry
5. The VirtFusion panel toggle for VNC enable/disable is currently broken (only changes a firewall flag that doesn't propagate); the module does not surface this toggle. VNC is treated as always-available and gated by WHMCS session + service ownership
### UsageUpdate Not Syncing ### UsageUpdate Not Syncing
@@ -438,19 +663,27 @@ This data appears in the WHMCS client area and admin product details.
## Known Issues ## Known Issues
1. **VNC Console** - Requires VirtFusion v6.1.0+. Earlier versions do not expose a VNC API endpoint. The module gracefully handles this by showing an error message. 1. **VNC Console** - Requires VirtFusion v6.1.0+. Earlier versions do not expose a VNC API endpoint.
2. **Resource Modification** - Memory and CPU modification requires VirtFusion v6.2.0+. Traffic modification requires v6.0.0+. Backup management requires v4.3.0+. 2. **VirtFusion VNC enable/disable toggle is non-functional** - The VirtFusion panel's VNC toggle currently only manipulates a firewall flag that doesn't actually gate the wss endpoint, and the API's `vnc.enabled` response field tracks "active session" rather than feature state. The module therefore does not expose a toggle; VNC is treated as always-available and access is gated by WHMCS session + service ownership at our layer.
3. **IPv6 Display** - IPv6 subnet display depends on the VirtFusion installation having IPv6 pools configured. If no IPv6 is assigned, the network panel shows "No IPv6 subnets". 3. **Resource Modification** - Memory and CPU modification requires VirtFusion v6.2.0+. Traffic modification requires v6.0.0+. Backup management requires v4.3.0+.
4. **Order Form Custom Fields** - The custom fields ("Initial Operating System" and "Initial SSH Key") must be named exactly as specified. The module matches by field name with spaces removed and converted to lowercase. 4. **IPv6 Display** - IPv6 subnet display depends on the VirtFusion installation having IPv6 pools configured. If no IPv6 is assigned, the IPv6 cell shows "-".
5. **Hooks File Detection** - WHMCS detects the `hooks.php` file when the module is first activated. If you add the module files to an already-active installation, you may need to deactivate and reactivate the module, or re-save the product settings. 5. **Filesystem Usage requires qemu-guest-agent** - The Filesystem Usage section in the Resources panel reads from `remoteState.agent.fsinfo`, which is populated only when `qemu-guest-agent` is installed and running inside the VM. Builds without the agent simply hide the section.
6. **Bootstrap 3 Themes** - While the module supports BS3 themes, some visual differences may exist (e.g., `d-flex` not available in BS3). The module uses `display: flex` in CSS as a fallback. 6. **Order Form Custom Fields** - The custom fields ("Initial Operating System" and "Initial SSH Key") must be named exactly as specified. The module matches by field name with spaces removed and converted to lowercase.
7. **Concurrent API Calls** - The module makes individual API calls for each feature panel on the client area page. If the VirtFusion API is slow, the page may take longer to fully load. All panels load asynchronously to minimize perceived delay. 7. **Hooks File Detection** - WHMCS detects the `hooks.php` file when the module is first activated. If you add the module files to an already-active installation, you may need to deactivate and reactivate the module, or re-save the product settings.
8. **Bootstrap 3 Themes** - While the module supports BS3 themes, some visual differences may exist (e.g., `d-flex` not available in BS3). The module uses `display: flex` in CSS as a fallback.
9. **Concurrent API Calls** - The module makes individual API calls for each feature panel on the client area page. The Server Overview fetch now passes `?remoteState=true` so it includes a libvirt round-trip on the hypervisor side. At low volume this is fine; at high concurrency, watch hypervisor CPU.
10. **Module Debug Logging is off by default** - `tblmodulelog` (visible in **Utilities → Logs → Module Log**) only receives entries when **Module Debug Logging** is enabled at WHMCS Admin → Utilities → Logs → Module Log → Activate Module Debug Logging. Without that toggle, the module's `Log::insert()` calls succeed silently and nothing is recorded. Turn it on before opening a support ticket about a module call so we have logs to inspect.
11. **Email template attachment storage configuration (WHMCS 9)** - WHMCS 9 added an email-template-attachments asset type that requires a properly-configured Storage backend (System Settings → Storage Settings) — including a non-empty `region` field even for S3-compatible providers like Storj that don't use regions. Misconfiguration causes ALL template-based emails (Order Confirmation, Welcome, etc.) to silently fail before SMTP is contacted, while custom-message admin emails (cron activity reports) keep working. Setting any non-empty region (`us-east-1`, `auto`, `US1`) restores templates. Independent of this module.
8. **Self-Signed SSL Certificates** - SSL verification is enforced by default. VirtFusion panels using self-signed certificates will cause connection failures. Use a valid SSL certificate (e.g., Let's Encrypt) on your VirtFusion panel. 8. **Self-Signed SSL Certificates** - SSL verification is enforced by default. VirtFusion panels using self-signed certificates will cause connection failures. Use a valid SSL certificate (e.g., Let's Encrypt) on your VirtFusion panel.
@@ -480,7 +713,7 @@ modules/servers/VirtFusionDirect/
VirtFusionDirect.php # WHMCS module entry point (MetaData, ConfigOptions, all module functions) VirtFusionDirect.php # WHMCS module entry point (MetaData, ConfigOptions, all module functions)
client.php # Client-facing AJAX API (authenticated, ownership-validated) client.php # Client-facing AJAX API (authenticated, ownership-validated)
admin.php # Admin-facing AJAX API (admin authentication required) admin.php # Admin-facing AJAX API (admin authentication required)
hooks.php # WHMCS hooks (order form OS/SSH dropdowns, checkout validation) hooks.php # WHMCS hooks (order form OS/SSH dropdowns, checkout validation, daily rDNS cron)
lib/ lib/
Module.php # Base class: API communication, power, network, VNC, rebuild Module.php # Base class: API communication, power, network, VNC, rebuild
ModuleFunctions.php # Provisioning: create, suspend, unsuspend, terminate, change package ModuleFunctions.php # Provisioning: create, suspend, unsuspend, terminate, change package
@@ -491,6 +724,12 @@ modules/servers/VirtFusionDirect/
ServerResource.php # Data transformer: VirtFusion API response -> display format ServerResource.php # Data transformer: VirtFusion API response -> display format
AdminHTML.php # Admin interface: HTML generation for admin services tab AdminHTML.php # Admin interface: HTML generation for admin services tab
Log.php # Logging: WHMCS module log integration Log.php # Logging: WHMCS module log integration
PowerDns/
Client.php # PowerDNS HTTP API wrapper (X-API-Key, ping, listZones, getZone, patchRRset, notifyZone)
Config.php # Loads + decrypts addon settings from tbladdonmodules
IpUtil.php # PTR-name generation, IP extraction, RFC 2317 parsing, zone matching
Resolver.php # Forward-DNS verification (dns_get_record + CNAME chain, cached)
PtrManager.php # Orchestrator: syncServer, deleteForServer, listPtrs, setPtr, reconcile, reconcileAll
templates/ templates/
overview.tpl # Client area Smarty template (all management panels) overview.tpl # Client area Smarty template (all management panels)
error.tpl # Error display template error.tpl # Error display template
@@ -499,6 +738,9 @@ modules/servers/VirtFusionDirect/
js/keygen.js # SSH Ed25519 key generator (Web Crypto API) js/keygen.js # SSH Ed25519 key generator (Web Crypto API)
config/ config/
ConfigOptionMapping-example.php # Example custom option name mapping ConfigOptionMapping-example.php # Example custom option name mapping
modules/addons/VirtFusionDns/ # Optional — only needed for reverse DNS support
VirtFusionDns.php # Addon entry point: _config(), _activate(), _deactivate(), _output() (Test Connection page)
``` ```
## Contributing ## Contributing

196
install.sh Executable file
View File

@@ -0,0 +1,196 @@
#!/usr/bin/env bash
#
# install.sh — Manage the VirtFusion Direct WHMCS module.
#
# Subcommands:
# install First-time install. Refuses if already present (use upgrade).
# upgrade Refresh an existing install. Refuses if nothing is installed.
# check Report installed version vs latest available. No changes.
#
# Flags (install/upgrade only):
# --with-addon, -a Also sync the PowerDNS rDNS addon.
# --version, -v vX.Y.Z Pin a specific release tag (default: latest).
#
# Exit codes for `check`:
# 0 installed and up-to-date
# 1 installed but outdated (or installed-version unknown)
# 2 not installed
#
# Pipeable:
# curl -fsSL https://raw.githubusercontent.com/EZSCALE/virtfusion-whmcs-module/main/install.sh \
# | sudo bash -s -- install /path/to/whmcs
#
# wget -qO- https://raw.githubusercontent.com/EZSCALE/virtfusion-whmcs-module/main/install.sh \
# | sudo bash -s -- upgrade --with-addon /path/to/whmcs
#
# curl -fsSL https://raw.githubusercontent.com/EZSCALE/virtfusion-whmcs-module/main/install.sh \
# | bash -s -- check /path/to/whmcs
#
# Why a script? rsync into a directory owned by the WHMCS web user (e.g.
# www-data, apache) lands files as root:root by default, which the web server
# can't read — the classic "module installed but invisible in WHMCS" symptom.
# This script reads the parent directory's owner and applies it via --chown, so
# a `sudo bash` install ends up with correct ownership. It also preserves any
# custom config/ConfigOptionMapping.php across --delete.
set -euo pipefail
REPO="EZSCALE/virtfusion-whmcs-module"
MARKER=".installed-version"
err() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; }
warn() { printf '\033[1;33mwarn:\033[0m %s\n' "$*" >&2; }
info() { printf '\033[1;32m==>\033[0m %s\n' "$*"; }
usage() {
cat <<USAGE
Usage:
install.sh install [--with-addon] [--version vX.Y.Z] /path/to/whmcs
install.sh upgrade [--with-addon] [--version vX.Y.Z] /path/to/whmcs
install.sh check /path/to/whmcs
Examples:
curl -fsSL https://raw.githubusercontent.com/$REPO/main/install.sh \\
| sudo bash -s -- install /path/to/whmcs
wget -qO- https://raw.githubusercontent.com/$REPO/main/install.sh \\
| sudo bash -s -- upgrade --with-addon /path/to/whmcs
curl -fsSL https://raw.githubusercontent.com/$REPO/main/install.sh \\
| bash -s -- check /path/to/whmcs
USAGE
exit 2
}
resolve_latest() {
curl -fsSL "https://api.github.com/repos/$REPO/releases/latest" \
| sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p'
}
read_installed_version() {
local marker="$1/modules/servers/VirtFusionDirect/$MARKER"
if [ -f "$marker" ]; then
tr -d '[:space:]' < "$marker"
else
echo "unknown"
fi
}
cmd_check() {
local WHMCS="$1"
if [ ! -d "$WHMCS/modules/servers/VirtFusionDirect" ]; then
warn "Not installed at $WHMCS"
exit 2
fi
local current latest
current=$(read_installed_version "$WHMCS")
latest=$(resolve_latest)
[ -n "$latest" ] || { err "Could not resolve latest version from GitHub API"; exit 1; }
printf ' installed: %s\n latest: %s\n' "$current" "$latest"
if [ "$current" = "$latest" ]; then
info "Up to date"
exit 0
fi
warn "Update available: $current$latest"
exit 1
}
cmd_sync() {
local mode="$1"; shift
local WITH_ADDON=0 VERSION="${VERSION:-}" WHMCS=""
while [ $# -gt 0 ]; do
case "$1" in
--with-addon|-a) WITH_ADDON=1; shift ;;
--version|-v) VERSION="${2:-}"; shift 2 ;;
-h|--help) usage ;;
-*) err "Unknown flag: $1"; usage ;;
*) WHMCS="$1"; shift ;;
esac
done
[ -n "$WHMCS" ] || { err "Missing WHMCS path"; usage; }
[ -d "$WHMCS/modules/servers" ] || {
err "Not a WHMCS install: $WHMCS/modules/servers not found"; exit 1;
}
local target="$WHMCS/modules/servers/VirtFusionDirect"
if [ "$mode" = "install" ] && [ -d "$target" ]; then
err "Already installed at $target — use 'upgrade' to refresh."
exit 1
fi
if [ "$mode" = "upgrade" ] && [ ! -d "$target" ]; then
err "Not currently installed at $target — use 'install' instead."
exit 1
fi
if [ -z "$VERSION" ]; then
VERSION=$(resolve_latest)
[ -n "$VERSION" ] || { err "Could not resolve latest version from GitHub API"; exit 1; }
fi
info "Target version: $VERSION"
local OWNER
OWNER=$(stat -c '%U:%G' "$WHMCS/modules/servers" 2>/dev/null || true)
[ -n "$OWNER" ] || { err "Could not detect parent directory owner via stat"; exit 1; }
info "Owner (from $WHMCS/modules/servers): $OWNER"
# NOTE: TMP is intentionally NOT declared `local`. The EXIT trap fires when
# the shell exits, not when this function returns — by then a function-local
# would be out of scope and `set -u` would explode the trap body with
# "TMP: unbound variable", masking the script's real exit code with 1.
# The `${TMP:-}` expansion in the trap is belt-and-suspenders: harmless
# if TMP somehow ends up unset, and prevents future regressions if anyone
# moves the assignment back into a tighter scope.
TMP=$(mktemp -d)
trap 'rm -rf "${TMP:-}"' EXIT
info "Downloading $VERSION..."
curl -fsSL "https://github.com/$REPO/archive/refs/tags/$VERSION.tar.gz" -o "$TMP/src.tar.gz"
mkdir -p "$TMP/src"
tar -xzf "$TMP/src.tar.gz" -C "$TMP/src" --strip-components=1
local SRC="$TMP/src/modules/servers/VirtFusionDirect"
[ -d "$SRC" ] || { err "Tarball did not contain modules/servers/VirtFusionDirect"; exit 1; }
# Preserve user's custom configurable-option mapping across --delete.
local MAP_FILE="$target/config/ConfigOptionMapping.php"
local MAP_BACKUP=""
if [ -f "$MAP_FILE" ]; then
MAP_BACKUP="$TMP/ConfigOptionMapping.php.bak"
cp -p "$MAP_FILE" "$MAP_BACKUP"
info "Backed up custom ConfigOptionMapping.php"
fi
info "Syncing server module → $target/"
rsync -ahP --delete --chown="$OWNER" "$SRC/" "$target/"
if [ -n "$MAP_BACKUP" ]; then
cp -p "$MAP_BACKUP" "$MAP_FILE"
chown "$OWNER" "$MAP_FILE"
info "Restored custom ConfigOptionMapping.php"
fi
printf '%s\n' "$VERSION" > "$target/$MARKER"
chown "$OWNER" "$target/$MARKER"
if [ "$WITH_ADDON" = 1 ]; then
local addon_src="$TMP/src/modules/addons/VirtFusionDns"
local addon_target="$WHMCS/modules/addons/VirtFusionDns"
[ -d "$addon_src" ] || { err "Tarball did not contain modules/addons/VirtFusionDns"; exit 1; }
info "Syncing PowerDNS addon → $addon_target/"
rsync -ahP --delete --chown="$OWNER" "$addon_src/" "$addon_target/"
printf '%s\n' "$VERSION" > "$addon_target/$MARKER"
chown "$OWNER" "$addon_target/$MARKER"
fi
info "$mode complete: $VERSION (owner $OWNER)"
}
case "${1:-}" in
install) shift; cmd_sync install "$@" ;;
upgrade) shift; cmd_sync upgrade "$@" ;;
check) shift; [ $# -eq 1 ] || usage; cmd_check "$1" ;;
-h|--help|"") usage ;;
*) err "Unknown command: $1"; usage ;;
esac

View File

@@ -0,0 +1,367 @@
<?php
use WHMCS\Module\Server\VirtFusionDirect\PowerDns\Client;
use WHMCS\Module\Server\VirtFusionDirect\PowerDns\Config;
/**
* VirtFusion DNS — companion WHMCS addon module that holds PowerDNS settings for
* the VirtFusionDirect server module. Keeps the server module decoupled from the
* addon: the server module reads settings from tbladdonmodules and never loads
* addon code at runtime.
*
* Activation: WHMCS Admin -> System Settings -> Addon Modules -> Activate -> Configure.
*
* API key handling: WHMCS encrypts password-type addon fields in tbladdonmodules;
* the server module calls decrypt() on read (see lib/PowerDns/Config.php).
*/
if (! defined('WHMCS')) {
exit('This file cannot be accessed directly');
}
/**
* Load the server module's PowerDNS classes on demand. Done inside functions rather
* than at file scope so the WHMCS addon list still works if the server module is
* absent (e.g., uninstalled while the addon is still activated). Returns true when
* the classes are available.
*/
function virtfusiondns_load_server_libs(): bool
{
$base = __DIR__ . '/../../servers/VirtFusionDirect/lib/';
$files = [
'Curl.php',
'Log.php',
'Cache.php',
'PowerDns/Config.php',
'PowerDns/IpUtil.php',
'PowerDns/Client.php',
];
foreach ($files as $f) {
if (! is_file($base . $f)) {
return false;
}
require_once $base . $f;
}
// PtrManager + IpUtil are only needed for the diagnostic tool below; load them
// if present but don't require them for the basic status page to work.
foreach (['PowerDns/Resolver.php', 'PowerDns/PtrManager.php'] as $optional) {
if (is_file($base . $optional)) {
require_once $base . $optional;
}
}
return true;
}
/**
* WHMCS addon metadata.
*/
function VirtFusionDns_config()
{
return [
'name' => 'VirtFusion DNS',
'description' => 'Adds reverse DNS (PTR) management to the VirtFusionDirect server module using a PowerDNS HTTP API. Zones must already exist in PowerDNS; the addon never creates zones. Requires the VirtFusionDirect server module.',
'version' => '1.0',
'author' => 'VirtFusionDirect',
'language' => 'english',
'fields' => [
'enabled' => [
'FriendlyName' => 'Enable rDNS Sync',
'Type' => 'yesno',
'Description' => 'Master switch. When off, the server module skips every PowerDNS call.',
],
'endpoint' => [
'FriendlyName' => 'PowerDNS API Endpoint',
'Type' => 'text',
'Size' => '60',
'Default' => 'http://ns1.example.com:8081',
'Description' => 'Scheme + host + port (no path). The /api/v1/... path is appended automatically.',
],
'apiKey' => [
'FriendlyName' => 'PowerDNS API Key',
'Type' => 'password',
'Size' => '60',
'Description' => 'X-API-Key. Stored encrypted by WHMCS; decrypted only server-side when PowerDNS is called.',
],
'serverId' => [
'FriendlyName' => 'PowerDNS Server ID',
'Type' => 'text',
'Size' => '20',
'Default' => 'localhost',
'Description' => 'Almost always "localhost" (the PowerDNS API server identifier, not a hostname).',
],
'defaultTtl' => [
'FriendlyName' => 'Default PTR TTL (seconds)',
'Type' => 'text',
'Size' => '10',
'Default' => '3600',
'Description' => 'TTL applied to PTR records created by the module.',
],
'cacheTtl' => [
'FriendlyName' => 'Cache TTL (seconds)',
'Type' => 'text',
'Size' => '10',
'Default' => '60',
'Description' => 'How long zone lists and DNS-resolution results are cached. Minimum 10s.',
],
],
];
}
/**
* Called when the addon is activated. No schema to create — settings live in tbladdonmodules.
*/
function VirtFusionDns_activate()
{
return [
'status' => 'success',
'description' => 'VirtFusion DNS activated. Fill in the endpoint + API key in the addon configuration, then use the Test Connection button on the addon page.',
];
}
/**
* Called when the addon is deactivated. Settings preserved (re-activating restores them).
*/
function VirtFusionDns_deactivate()
{
return [
'status' => 'success',
'description' => 'VirtFusion DNS deactivated. Server lifecycle PowerDNS calls will now be skipped. Settings are preserved.',
];
}
/**
* Admin status page — rendered by WHMCS when the addon is clicked from the Addons menu.
*
* Shows a settings summary, a Test Connection button (calls PowerDNS ping), the current
* zone count, and a recent log extract filtered to PowerDNS-related entries.
*/
function VirtFusionDns_output($vars)
{
if (! virtfusiondns_load_server_libs()) {
echo '<div style="max-width:900px;padding:16px;border-radius:4px;background:#f8d7da;color:#721c24">';
echo '<strong>VirtFusionDirect server module not found.</strong> ';
echo 'This addon requires the VirtFusionDirect server module at <code>modules/servers/VirtFusionDirect/</code>. ';
echo 'Install or restore that module and reload this page.';
echo '</div>';
return;
}
Config::reset();
$config = Config::get();
$pingResult = null;
$zoneCount = null;
$zoneSample = [];
if (! empty($_GET['vfdns_test'])) {
if (Config::isEnabled()) {
$client = new Client;
$pingResult = $client->ping();
if ($pingResult['ok']) {
$client->forgetZoneCache();
$zones = $client->listZones();
$zoneCount = count($zones);
$zoneSample = array_slice($zones, 0, 8);
}
} else {
$pingResult = ['ok' => false, 'http' => 0, 'error' => 'Not enabled or missing endpoint/apiKey.'];
}
}
$modulelink = htmlspecialchars($vars['modulelink'] ?? '', ENT_QUOTES, 'UTF-8');
$endpoint = htmlspecialchars($config['endpoint'], ENT_QUOTES, 'UTF-8');
$serverId = htmlspecialchars($config['serverId'], ENT_QUOTES, 'UTF-8');
$ttl = (int) $config['defaultTtl'];
$cacheTtl = (int) $config['cacheTtl'];
$enabledBadge = $config['enabled']
? '<span style="color:#28a745;font-weight:bold">enabled</span>'
: '<span style="color:#dc3545;font-weight:bold">disabled</span>';
$keyBadge = $config['apiKey'] !== '' ? '<span style="color:#28a745">set</span>' : '<span style="color:#dc3545">missing</span>';
echo '<div style="max-width:900px">';
echo '<h2 style="margin-top:0">VirtFusion DNS</h2>';
echo '<p>Reverse DNS management for the VirtFusionDirect server module. All PTR writes happen through the VirtFusion server lifecycle (create, rename, terminate) and through the client-area Reverse DNS panel. Forward DNS (A/AAAA) is verified before every PTR write; mismatches are skipped and logged.</p>';
echo '<h3>Current settings</h3>';
echo '<table class="table table-sm" style="max-width:700px"><tbody>';
echo '<tr><th style="text-align:left;width:180px">Status</th><td>' . $enabledBadge . '</td></tr>';
echo '<tr><th style="text-align:left">Endpoint</th><td><code>' . ($endpoint ?: '<em>not set</em>') . '</code></td></tr>';
echo '<tr><th style="text-align:left">API Key</th><td>' . $keyBadge . '</td></tr>';
echo '<tr><th style="text-align:left">Server ID</th><td><code>' . $serverId . '</code></td></tr>';
echo '<tr><th style="text-align:left">Default PTR TTL</th><td>' . $ttl . 's</td></tr>';
echo '<tr><th style="text-align:left">Cache TTL</th><td>' . $cacheTtl . 's</td></tr>';
echo '</tbody></table>';
echo '<h3>Test Connection</h3>';
echo '<p>Calls <code>GET /api/v1/servers/' . $serverId . '</code> and, on success, lists available zones.</p>';
echo '<a href="' . $modulelink . '&vfdns_test=1" class="btn btn-primary btn-sm">Run Test</a>';
if ($pingResult !== null) {
echo '<div style="margin-top:12px;padding:10px;border-radius:4px;background:' . ($pingResult['ok'] ? '#d4edda' : '#f8d7da') . ';color:' . ($pingResult['ok'] ? '#155724' : '#721c24') . '">';
if ($pingResult['ok']) {
echo '<strong>OK.</strong> PowerDNS reachable and authenticated. ';
if ($zoneCount !== null) {
echo $zoneCount . ' zone(s) visible.';
if (! empty($zoneSample)) {
echo '<div style="margin-top:8px;font-family:monospace;font-size:12px">';
foreach ($zoneSample as $z) {
echo htmlspecialchars($z, ENT_QUOTES, 'UTF-8') . '<br>';
}
if ($zoneCount > count($zoneSample)) {
echo '<em>... and ' . ($zoneCount - count($zoneSample)) . ' more</em>';
}
echo '</div>';
}
}
} else {
echo '<strong>Failed.</strong> HTTP ' . (int) $pingResult['http'] . ': ' . htmlspecialchars((string) ($pingResult['error'] ?? 'unknown error'), ENT_QUOTES, 'UTF-8');
}
echo '</div>';
}
echo '<h3 style="margin-top:24px">Operation</h3>';
echo '<ul>';
echo '<li><strong>On server creation:</strong> a PTR is created for each assigned IP, set to the server hostname, <em>only if the forward DNS already resolves to that IP</em>.</li>';
echo '<li><strong>On server rename:</strong> PTRs whose current content matches the <em>previous</em> hostname are updated to the new hostname; custom PTRs set by the client are preserved.</li>';
echo '<li><strong>On server termination:</strong> every PTR for the server\'s IPs is deleted from PowerDNS.</li>';
echo '<li><strong>Clients:</strong> may set a custom PTR per IP via the Reverse DNS panel on the service overview page. Forward DNS must resolve to the IP; mismatch rejects the write.</li>';
echo '<li><strong>Reconcile cron:</strong> runs daily, additive-only — creates PTRs where none exist, never overwrites.</li>';
echo '<li><strong>Reconcile (admin):</strong> a button on the admin services tab triggers an explicit reconcile with optional <em>force</em> to reset client-custom PTRs back to the server hostname.</li>';
echo '</ul>';
echo '<h3>Requirements</h3>';
echo '<ul>';
echo '<li>PowerDNS Authoritative with HTTP API enabled (<code>webserver=yes</code>, <code>api=yes</code>).</li>';
echo '<li>Reverse zones (<code>*.in-addr.arpa</code> / <code>*.ip6.arpa</code>) for your IP ranges must exist in PowerDNS already — the addon never creates zones.</li>';
echo '<li><code>api-allow-from</code> must include the WHMCS host\'s IP.</li>';
echo '</ul>';
// -----------------------------------------------------------------------
// Diagnostic: "What does the module see for IP X?"
//
// Runs the full pipeline an admin would otherwise have to trace through
// multiple log lines to reproduce:
// 1. Current config (what values is Config::get() actually returning?)
// 2. Zone list (what does Client::listZones() return right now, post-cache?)
// 3. Zone match for an input IP (is findZoneAndPtrName selecting the right zone?)
// 4. Current PTR content at the located (zone, ptrName) pair
//
// Catches every common failure mode: wrong API key (empty zones, auth error),
// wrong server ID (404), forgotten zone (no match), stale cache (mismatched
// zones), and typos in the RFC 2317 zone name (parseClasslessZone rejection).
// -----------------------------------------------------------------------
echo '<h3 style="margin-top:24px">Diagnose an IP</h3>';
echo '<p>Runs the exact same pipeline the client-area rDNS panel uses. Useful when a specific IP shows "no zone" in the UI and you need to see <em>why</em>.</p>';
$diagIp = isset($_GET['diag_ip']) ? trim((string) $_GET['diag_ip']) : '';
echo '<form method="get" action="" style="display:flex;gap:8px;align-items:center;margin-bottom:12px">';
// WHMCS passes the module slug via ?module=... — preserve any existing query params
// by re-emitting the current GET state as hidden fields (except diag_ip itself).
foreach ($_GET as $k => $v) {
if ($k === 'diag_ip') {
continue;
}
echo '<input type="hidden" name="' . htmlspecialchars((string) $k, ENT_QUOTES, 'UTF-8') . '" value="' . htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8') . '">';
}
echo '<input type="text" name="diag_ip" placeholder="IP address (e.g. 198.51.100.42 or 2001:db8::1)" value="' . htmlspecialchars($diagIp, ENT_QUOTES, 'UTF-8') . '" class="form-control form-control-sm" style="max-width:320px;font-family:monospace">';
echo '<button type="submit" class="btn btn-primary btn-sm">Diagnose</button>';
echo '</form>';
if ($diagIp !== '') {
echo '<div style="background:#f8f9fa;border:1px solid #dee2e6;border-radius:4px;padding:12px;font-family:monospace;font-size:13px;white-space:pre-wrap;word-break:break-all">';
if (filter_var($diagIp, FILTER_VALIDATE_IP) === false) {
echo '<span style="color:#dc3545">Invalid IP address.</span>';
} elseif (! Config::isEnabled()) {
echo '<span style="color:#dc3545">Addon disabled or missing endpoint/API key. Diagnosis skipped.</span>';
} else {
$client = new Client;
echo '<strong>Config snapshot:</strong>' . "\n";
echo ' endpoint = ' . htmlspecialchars($config['endpoint'], ENT_QUOTES, 'UTF-8') . "\n";
echo ' serverId = ' . htmlspecialchars($config['serverId'], ENT_QUOTES, 'UTF-8') . "\n";
echo ' cacheTtl = ' . $cacheTtl . 's' . "\n";
echo ' apiKey = ' . ($config['apiKey'] !== '' ? '(set, ' . strlen($config['apiKey']) . ' chars)' : '(MISSING)') . "\n\n";
// Always forget cache before diagnose so we see the LIVE state, not a
// potentially-stale cached list from an earlier misconfigured call.
$client->forgetZoneCache();
$zones = $client->listZones();
echo '<strong>Live zone list (cache purged, ' . count($zones) . ' zones):</strong>' . "\n";
if (empty($zones)) {
echo ' <span style="color:#dc3545">NO ZONES RETURNED.</span>' . "\n";
echo ' Likely causes: wrong API key (PowerDNS returned 401/403), wrong Server ID' . "\n";
echo ' (PowerDNS returned 404), or api-allow-from blocking the WHMCS host IP.' . "\n";
echo ' Run the Test Connection button above to see the exact HTTP error.' . "\n\n";
} else {
foreach (array_slice($zones, 0, 15) as $z) {
echo ' ' . htmlspecialchars($z, ENT_QUOTES, 'UTF-8') . "\n";
}
if (count($zones) > 15) {
echo ' ... and ' . (count($zones) - 15) . ' more' . "\n";
}
echo "\n";
}
$ptrName = IpUtil::ptrNameForIp($diagIp);
echo '<strong>Computed PTR name for ' . htmlspecialchars($diagIp, ENT_QUOTES, 'UTF-8') . ':</strong>' . "\n";
echo ' ' . htmlspecialchars((string) $ptrName, ENT_QUOTES, 'UTF-8') . "\n\n";
$loc = IpUtil::findZoneAndPtrName($diagIp, $zones);
echo '<strong>Zone match (IpUtil::findZoneAndPtrName):</strong>' . "\n";
if ($loc === null) {
echo ' <span style="color:#dc3545">NO MATCH.</span>' . "\n";
echo ' The IP does not fall within any zone returned above.' . "\n";
if (IpUtil::isIpv4($diagIp)) {
$oct = (int) explode('.', $diagIp)[3];
echo " For IPv4: confirm a standard reverse zone exists (one of the listed\n";
echo " zones should end with the first-three-octets-reversed of $diagIp), OR\n";
echo " that an RFC 2317 classless zone exists whose range covers octet $oct.\n";
}
if (IpUtil::isIpv6($diagIp)) {
echo " For IPv6: confirm a reverse zone exists ending in .ip6.arpa. whose\n";
echo " nibble prefix matches the high-order bits of $diagIp.\n";
}
echo "\n";
} else {
echo ' zone = ' . htmlspecialchars($loc['zone'], ENT_QUOTES, 'UTF-8') . "\n";
echo ' ptrName = ' . htmlspecialchars($loc['ptrName'], ENT_QUOTES, 'UTF-8') . "\n\n";
// Actual current PTR content, if any.
echo '<strong>Current PTR record in PowerDNS:</strong>' . "\n";
$zoneData = $client->getZone($loc['zone']);
if ($zoneData === null) {
echo ' <span style="color:#dc3545">Unable to fetch zone contents (HTTP error or not found).</span>' . "\n";
} else {
$found = null;
foreach ($zoneData['rrsets'] ?? [] as $rr) {
if (($rr['type'] ?? '') === 'PTR' && rtrim($rr['name'], '.') === rtrim($loc['ptrName'], '.')) {
foreach ($rr['records'] ?? [] as $rec) {
if (empty($rec['disabled']) && ! empty($rec['content'])) {
$found = [
'content' => $rec['content'],
'ttl' => (int) ($rr['ttl'] ?? 0),
];
break 2;
}
}
}
}
if ($found === null) {
echo ' (no PTR record present at ' . htmlspecialchars($loc['ptrName'], ENT_QUOTES, 'UTF-8') . ')' . "\n";
} else {
echo ' content = ' . htmlspecialchars($found['content'], ENT_QUOTES, 'UTF-8') . "\n";
echo ' ttl = ' . $found['ttl'] . 's' . "\n";
}
}
}
}
echo '</div>';
}
echo '</div>';
}

View File

@@ -1,5 +1,41 @@
<?php <?php
/**
* VirtFusion Direct Provisioning Module — WHMCS server module entry point.
*
* This file contains the non-namespaced functions WHMCS calls via its reflection-
* based module dispatcher. They follow the naming convention:
*
* {ModuleDirectoryName}_{FunctionName}(...)
*
* WHMCS looks for these on every relevant event (provisioning, UI rendering,
* daily cron, test connection, etc.). Every function here is a thin shim that
* instantiates ModuleFunctions (or Module) and delegates to a method — keeping
* the dispatch surface small and the business logic in unit-exercisable classes.
*
* DO NOT add significant logic directly in these shims. If you need a new
* lifecycle behaviour, add it as a method on ModuleFunctions and point the
* shim at it. This makes the module predictable: one public function, one method.
*
* RESERVED NAMES — DO NOT CHANGE
* ------------------------------
* WHMCS looks up these specific function names by convention; renaming them
* disables the corresponding feature in WHMCS silently:
* VirtFusionDirect_MetaData → Displayed name + API version
* VirtFusionDirect_ConfigOptions → Product-level settings fields
* VirtFusionDirect_TestConnection → Admin "Test Connection" button
* VirtFusionDirect_CreateAccount → Provisioning on order-activation
* VirtFusionDirect_SuspendAccount → Suspension
* VirtFusionDirect_UnsuspendAccount → Unsuspension
* VirtFusionDirect_TerminateAccount → Termination
* VirtFusionDirect_ChangePackage → Package change on upgrade/downgrade
* VirtFusionDirect_AdminServicesTabFields → Admin services tab renderer
* VirtFusionDirect_AdminServicesTabFieldsSave → Admin services tab save handler
* VirtFusionDirect_ClientArea → Client-area template + vars
* VirtFusionDirect_ServiceSingleSignOn → SSO button handler
* VirtFusionDirect_AdminCustomButtonArray → Custom admin action buttons
* VirtFusionDirect_UsageUpdate → Daily cron bandwidth/disk usage sync
*/
if (! defined('WHMCS')) { if (! defined('WHMCS')) {
exit('This file cannot be accessed directly'); exit('This file cannot be accessed directly');
} }
@@ -9,6 +45,8 @@ use WHMCS\Module\Server\VirtFusionDirect\Database;
use WHMCS\Module\Server\VirtFusionDirect\Log; use WHMCS\Module\Server\VirtFusionDirect\Log;
use WHMCS\Module\Server\VirtFusionDirect\Module; use WHMCS\Module\Server\VirtFusionDirect\Module;
use WHMCS\Module\Server\VirtFusionDirect\ModuleFunctions; use WHMCS\Module\Server\VirtFusionDirect\ModuleFunctions;
use WHMCS\Module\Server\VirtFusionDirect\PowerDns\Client as PowerDnsClient;
use WHMCS\Module\Server\VirtFusionDirect\PowerDns\Config as PowerDnsConfig;
/** /**
* Returns module metadata consumed by WHMCS. * Returns module metadata consumed by WHMCS.
@@ -76,6 +114,13 @@ function VirtFusionDirect_ConfigOptions()
'Description' => 'Credit amount to add when auto top-off triggers.', 'Description' => 'Credit amount to add when auto top-off triggers.',
'Default' => '100', 'Default' => '100',
], ],
'stockSafetyBufferPct' => [
'FriendlyName' => 'Stock Safety Buffer (%)',
'Type' => 'text',
'Size' => '5',
'Description' => 'Reserved headroom applied per resource when calculating stock. Only effective when the WHMCS Stock Control toggle is enabled on this product. 0-100; ignored for resources with no quota set in VirtFusion. Default is 10% if left blank.',
'Default' => '10',
],
]; ];
} }
@@ -97,6 +142,42 @@ function VirtFusionDirect_TestConnection(array $params)
$httpCode = $request->getRequestInfo('http_code'); $httpCode = $request->getRequestInfo('http_code');
if ($httpCode == 200) { if ($httpCode == 200) {
// Probe the compute scope: stock control depends on read access to
// /compute/hypervisors/groups. A token scoped only to /servers will pass the
// /connect check above but silently break nightly stock recalculation, so we
// surface the missing scope at config time rather than a week later.
$groupsProbe = $module->initCurl($password);
$groupsProbe->get($url . '/compute/hypervisors/groups?results=1');
$groupsHttp = (int) $groupsProbe->getRequestInfo('http_code');
if ($groupsHttp === 401 || $groupsHttp === 403) {
return [
'success' => false,
'error' => 'VirtFusion OK but API token lacks read access to /compute/hypervisors/groups (HTTP ' . $groupsHttp . '). Stock Control will not work — re-issue the token with compute:read scope.',
];
}
if ($groupsHttp !== 200) {
return [
'success' => false,
'error' => 'VirtFusion OK but /compute/hypervisors/groups returned HTTP ' . $groupsHttp . '. Stock Control may not work correctly.',
];
}
// Also verify PowerDNS health when the DNS addon is activated, so the
// admin's Test Connection button reflects the full provisioning path.
if (PowerDnsConfig::isEnabled()) {
$pdns = (new PowerDnsClient)->ping();
if (! $pdns['ok']) {
return [
'success' => false,
'error' => 'VirtFusion OK; PowerDNS unreachable — '
. ($pdns['error'] ?? 'unknown')
. ' (HTTP ' . (int) $pdns['http'] . '). Fix the VirtFusion DNS addon settings.',
];
}
}
return ['success' => true, 'error' => '']; return ['success' => true, 'error' => ''];
} }
@@ -277,12 +358,20 @@ function VirtFusionDirect_UsageUpdate(array $params)
foreach ($services as $service) { foreach ($services as $service) {
try { try {
$systemService = Database::getSystemService($service->id); $systemService = Database::getSystemService($service->id);
if (! $systemService) { if (! $systemService || empty($systemService->server_id)) {
// No VirtFusion server linked to this WHMCS service yet —
// either provisioning hasn't happened or it failed mid-create.
// Skipping is correct: there is nothing to read usage from.
continue; continue;
} }
// Fetch server settings (limits + storage profile) with remoteState=true
// so the qemu-agent fsinfo block is included for disk usage. The agent
// is best-effort — guests without qemu-agent installed will have no
// fsinfo, in which case we simply skip the diskused write rather than
// zeroing it.
$request = $module->initCurl($cp['token']); $request = $module->initCurl($cp['token']);
$data = $request->get($cp['url'] . '/servers/' . (int) $systemService->server_id); $data = $request->get($cp['url'] . '/servers/' . (int) $systemService->server_id . '?remoteState=true');
if ($request->getRequestInfo('http_code') != 200) { if ($request->getRequestInfo('http_code') != 200) {
continue; continue;
@@ -296,19 +385,43 @@ function VirtFusionDirect_UsageUpdate(array $params)
$server = $serverData['data']; $server = $serverData['data'];
$update = []; $update = [];
// Disk usage (WHMCS expects MB) // Disk usage (WHMCS expects MB) — derived from qemu-agent fsinfo when
if (isset($server['usage']['storage']['used'])) { // available. Sum across all reported filesystems (root + any extra
$update['diskused'] = round($server['usage']['storage']['used'] / 1048576); // mounts) and convert bytes -> MB. If the agent isn't running we get
// no fsinfo entries and leave diskused untouched.
$fsinfo = $server['remoteState']['agent']['fsinfo'] ?? null;
if (is_array($fsinfo) && $fsinfo !== []) {
$diskUsedBytes = 0;
foreach ($fsinfo as $fs) {
if (isset($fs['used-bytes']) && is_numeric($fs['used-bytes'])) {
$diskUsedBytes += (int) $fs['used-bytes'];
}
}
if ($diskUsedBytes > 0) {
$update['diskused'] = (int) round($diskUsedBytes / 1048576);
}
} }
if (isset($server['settings']['resources']['storage'])) { if (isset($server['settings']['resources']['storage'])) {
// settings.resources.storage is in GB; WHMCS disklimit is MB.
$update['disklimit'] = (int) $server['settings']['resources']['storage'] * 1024; $update['disklimit'] = (int) $server['settings']['resources']['storage'] * 1024;
} }
// Bandwidth usage (WHMCS expects MB) // Bandwidth usage (WHMCS expects MB) — fetched from the dedicated
if (isset($server['usage']['traffic']['used'])) { // /servers/{id}/traffic endpoint, which is the canonical source for
$update['bwused'] = round($server['usage']['traffic']['used'] / 1048576); // billing-period totals. The /servers/{id} response only exposes the
// current period's window (start/end/limit), not the byte counter.
$trafficRequest = $module->initCurl($cp['token']);
$trafficData = $trafficRequest->get($cp['url'] . '/servers/' . (int) $systemService->server_id . '/traffic');
if ($trafficRequest->getRequestInfo('http_code') == 200) {
$trafficJson = json_decode($trafficData, true);
$currentPeriod = $trafficJson['data']['monthly'][0] ?? null;
if (is_array($currentPeriod) && isset($currentPeriod['total']) && is_numeric($currentPeriod['total'])) {
$update['bwused'] = (int) round($currentPeriod['total'] / 1048576);
}
} }
if (isset($server['settings']['resources']['traffic'])) { if (isset($server['settings']['resources']['traffic'])) {
// settings.resources.traffic is in GB; 0 means unlimited, which
// WHMCS represents the same way (0 bwlimit = no cap).
$trafficGB = (int) $server['settings']['resources']['traffic']; $trafficGB = (int) $server['settings']['resources']['traffic'];
$update['bwlimit'] = $trafficGB > 0 ? $trafficGB * 1024 : 0; $update['bwlimit'] = $trafficGB > 0 ? $trafficGB * 1024 : 0;
} }

View File

@@ -5,14 +5,41 @@ require dirname(__DIR__, 3) . '/init.php';
/** /**
* Admin-facing AJAX API endpoint. * Admin-facing AJAX API endpoint.
* *
* Requires WHMCS admin authentication. Provides server data lookup * MIRRORS client.php STRUCTURE
* and user impersonation for the admin services tab. * ----------------------------
* Same switch-on-$action dispatch pattern, same JSON response shape, same
* "output + break" convention. The only substantive difference is the auth
* gate at the top: $vf->adminOnly() instead of $vf->isAuthenticated().
*
* WHY SEPARATE FROM client.php
* ----------------------------
* A single file with a per-action admin/client switch would risk one bug
* (e.g. forgetting to call adminOnly on a new admin-only action) giving a
* client authenticated but without admin privileges access to admin data.
* Having two physical entry points means the admin auth gate is enforced
* at file scope — any action routed here already went through adminOnly().
*
* ADMIN-LEVEL AUTH ONLY — NO SERVICE OWNERSHIP CHECK
* --------------------------------------------------
* An admin is allowed to view/operate on any service, so we don't call
* validateUserOwnsService() here. If you add an action that needs finer-
* grained auth (e.g. restrict to the admin role that owns the product
* group), compose the additional check inside the case branch.
*
* SAME-ORIGIN / POST GATES STILL APPLY TO MUTATIONS
* -------------------------------------------------
* Admins are still subject to requirePost + requireSameOrigin on writes —
* admin sessions are just as CSRF-vulnerable as client sessions. See the
* rdnsReconcile case for the pattern.
*/ */
use WHMCS\Module\Server\VirtFusionDirect\Database; use WHMCS\Module\Server\VirtFusionDirect\Database;
use WHMCS\Module\Server\VirtFusionDirect\Log; use WHMCS\Module\Server\VirtFusionDirect\Log;
use WHMCS\Module\Server\VirtFusionDirect\Module; use WHMCS\Module\Server\VirtFusionDirect\Module;
use WHMCS\Module\Server\VirtFusionDirect\PowerDns\Config as PowerDnsConfig;
use WHMCS\Module\Server\VirtFusionDirect\PowerDns\PtrManager;
use WHMCS\Module\Server\VirtFusionDirect\ServerResource; use WHMCS\Module\Server\VirtFusionDirect\ServerResource;
use WHMCS\Module\Server\VirtFusionDirect\StockControl;
$vf = new Module; $vf = new Module;
@@ -88,6 +115,101 @@ try {
$vf->output(['success' => false, 'errors' => 'Unable to fetch user data'], true, true, 502); $vf->output(['success' => false, 'errors' => 'Unable to fetch user data'], true, true, 502);
break; break;
// =================================================================
// Reverse DNS (PowerDNS)
// =================================================================
/**
* Admin-side PTR status for a service. Same shape as client-side rdnsList but
* accessible without being the service owner (admin-only guard at top).
*/
case 'rdnsStatus':
$serviceID = $vf->validateServiceID(true);
if (! PowerDnsConfig::isEnabled()) {
$vf->output(['success' => true, 'data' => ['enabled' => false, 'ips' => []]], true, true, 200);
break;
}
$serverData = $vf->fetchServerData($serviceID);
if (! $serverData) {
$vf->output(['success' => false, 'errors' => 'Unable to retrieve server data'], true, true, 502);
break;
}
$ptrs = (new PtrManager)->listPtrs($serverData);
$vf->output(['success' => true, 'data' => ['enabled' => true, 'ips' => $ptrs]], true, true, 200);
break;
/**
* Trigger PTR reconciliation for a single service. Additive-only by default
* (missing PTRs are created with the current hostname); pass force=1 to also
* reset PTRs that differ from the server hostname.
*/
case 'rdnsReconcile':
// Mutating action — enforce POST + same-origin even though the session is admin-authenticated.
$vf->requirePost();
$vf->requireSameOrigin();
$serviceID = $vf->validateServiceID(true);
if (! PowerDnsConfig::isEnabled()) {
$vf->output(['success' => false, 'errors' => 'Reverse DNS is not enabled'], true, true, 400);
break;
}
$force = ! empty($_POST['force']);
$summary = (new PtrManager)->reconcile($serviceID, $force);
Log::insert(
'rdnsReconcile:ok',
['serviceID' => $serviceID, 'force' => $force],
$summary,
);
$vf->output(['success' => true, 'data' => $summary], true, true, 200);
break;
// =================================================================
// Stock Control
// =================================================================
/**
* Force a full stock-quantity recalculation across every VirtFusionDirect
* product that has WHMCS stock control enabled. Same logic as the 2-hour
* AfterCronJob safety-net hook and the post-provision / post-termination
* event hooks in hooks.php, but on-demand. Cache TTLs still govern freshness
* of the underlying VirtFusion API reads — run a separate cache bust first
* if the admin needs to bypass the 120 s grpres:{id} TTL.
*
* Usable by admins via POST; returns a JSON map of productId => qty (or null
* where the product was skipped / left untouched by the orchestrator).
*/
case 'stockRecalculate':
$vf->requirePost();
$vf->requireSameOrigin();
$results = (new StockControl)->recalculateAll();
// Log a compact summary instead of the full map — the admin client still
// gets the detailed per-product map in the JSON response, but the module
// log stays readable even on stores with hundreds of VirtFusion products.
$summary = ['total' => count($results), 'updated' => 0, 'zeroed' => 0, 'skipped' => 0];
foreach ($results as $qty) {
if ($qty === null) {
$summary['skipped']++;
} elseif ((int) $qty === 0) {
$summary['zeroed']++;
} else {
$summary['updated']++;
}
}
Log::insert('stockRecalculate:ok', [], $summary);
$vf->output(['success' => true, 'data' => $results], true, true, 200);
break;
default: default:
$vf->output(['success' => false, 'errors' => 'invalid action'], true, true, 400); $vf->output(['success' => false, 'errors' => 'invalid action'], true, true, 400);
} }

View File

@@ -5,12 +5,59 @@ require dirname(__DIR__, 3) . '/init.php';
/** /**
* Client-facing AJAX API endpoint. * Client-facing AJAX API endpoint.
* *
* Authenticated by WHMCS session + service ownership validation. * ROUTING MODEL
* POST for mutations (power, rebuild, rename, credit), GET for reads (serverData, templates, backups). * -------------
* Every request carries ?action=X&serviceID=Y. We dispatch on $action via the
* switch below. Because PHP's switch() is O(N) over case labels that's still
* fine at ~20 actions; if this grows large enough that dispatch cost matters
* we'd want a lookup table, but we're nowhere near that.
*
* WHMCS requires every action URL to re-authenticate on each request (no
* cross-request sticky state beyond the session cookie). That's why the
* isAuthenticated() call is the first thing inside the try block — nothing
* downstream may assume a session exists.
*
* AUTH LAYERS (ORDER MATTERS)
* ---------------------------
* Each case composes the defenses it needs:
*
* 1. $vf->isAuthenticated() — client session (401 otherwise)
* 2. $vf->validateServiceID(true) — numeric coercion + presence
* 3. $vf->validateUserOwnsService($id) — the session owns this service (403)
* 4. Optional: requireServiceStatus — filter by tblhosting.domainstatus
* 5. Optional (mutations): requirePost — HTTP method gate (405)
* 6. Optional (mutations): requireSameOrigin — CSRF origin gate (403)
*
* The helpers are "fail loudly" — they exit on failure rather than returning.
* So everything AFTER a guard in a case branch knows the guard passed.
*
* EVERY $vf->output() FOLLOWED BY break
* -------------------------------------
* output() emits a JSON response and exits by default, so in theory `break`
* is redundant. In practice we always break explicitly for two reasons:
* 1. If someone later passes exit=false to output() the switch would fall
* through to the default case and emit a second response body.
* 2. Code readers shouldn't have to remember that one function exits.
*
* RESPONSE SHAPE
* --------------
* Success: { success: true, data: { ... } }
* Error: { success: false, errors: "human-readable message" }
* Status codes match HTTP semantics (200/400/401/403/404/405/429/500/502).
*
* CATCH-ALL
* ---------
* The outer try/catch guarantees we never expose a raw PHP stack trace to the
* client, even on bugs in our own code. All uncaught exceptions are logged and
* the user sees a generic 500.
*/ */
use WHMCS\Database\Capsule;
use WHMCS\Module\Server\VirtFusionDirect\Log; use WHMCS\Module\Server\VirtFusionDirect\Log;
use WHMCS\Module\Server\VirtFusionDirect\Module; use WHMCS\Module\Server\VirtFusionDirect\Module;
use WHMCS\Module\Server\VirtFusionDirect\PowerDns\Config as PowerDnsConfig;
use WHMCS\Module\Server\VirtFusionDirect\PowerDns\IpUtil;
use WHMCS\Module\Server\VirtFusionDirect\PowerDns\PtrManager;
use WHMCS\Module\Server\VirtFusionDirect\ServerResource; use WHMCS\Module\Server\VirtFusionDirect\ServerResource;
$vf = new Module; $vf = new Module;
@@ -28,6 +75,13 @@ try {
*/ */
case 'resetPassword': case 'resetPassword':
// Destructive: rotates the customer's VirtFusion login password.
// Gated by POST + same-origin (anti-CSRF) and a 30 s rate limit
// so a runaway / malicious script can't lock out the customer
// by spamming password resets.
$vf->requirePost();
$vf->requireSameOrigin();
$serviceID = $vf->validateServiceID(true); $serviceID = $vf->validateServiceID(true);
$client = $vf->validateUserOwnsService($serviceID); $client = $vf->validateUserOwnsService($serviceID);
@@ -36,6 +90,9 @@ try {
break; break;
} }
$vf->requireProvisionedService($serviceID);
$vf->requireRateLimit('resetPassword:' . $serviceID, 30);
$data = $vf->resetUserPassword($serviceID, $client); $data = $vf->resetUserPassword($serviceID, $client);
if ($data) { if ($data) {
@@ -58,6 +115,8 @@ try {
break; break;
} }
$vf->requireProvisionedService($serviceID);
$data = $vf->fetchServerData($serviceID); $data = $vf->fetchServerData($serviceID);
if ($data) { if ($data) {
@@ -81,6 +140,8 @@ try {
break; break;
} }
$vf->requireProvisionedService($serviceID);
$token = $vf->fetchLoginTokens($serviceID); $token = $vf->fetchLoginTokens($serviceID);
if ($token) { if ($token) {
@@ -96,6 +157,12 @@ try {
*/ */
case 'powerAction': case 'powerAction':
// Destructive: poweroff/restart can interrupt running workloads.
// Anti-CSRF + 10 s rate limit (short — power actions can legitimately
// cycle quickly when an admin is testing).
$vf->requirePost();
$vf->requireSameOrigin();
$serviceID = $vf->validateServiceID(true); $serviceID = $vf->validateServiceID(true);
if (! $vf->validateUserOwnsService($serviceID)) { if (! $vf->validateUserOwnsService($serviceID)) {
@@ -103,6 +170,9 @@ try {
break; break;
} }
$vf->requireProvisionedService($serviceID);
$vf->requireRateLimit('power:' . $serviceID, 10);
$powerAction = isset($_POST['powerAction']) ? preg_replace('/[^a-zA-Z]/', '', $_POST['powerAction']) : ''; $powerAction = isset($_POST['powerAction']) ? preg_replace('/[^a-zA-Z]/', '', $_POST['powerAction']) : '';
$allowedActions = ['boot', 'shutdown', 'restart', 'poweroff']; $allowedActions = ['boot', 'shutdown', 'restart', 'poweroff'];
@@ -126,6 +196,13 @@ try {
*/ */
case 'rebuild': case 'rebuild':
// Most-destructive client action — wipes the server. Strict
// anti-CSRF (a malicious page tricking the customer into
// rebuilding their own server destroys data) + 60 s rate limit
// (no legitimate flow needs more than one rebuild per minute).
$vf->requirePost();
$vf->requireSameOrigin();
$serviceID = $vf->validateServiceID(true); $serviceID = $vf->validateServiceID(true);
if (! $vf->validateUserOwnsService($serviceID)) { if (! $vf->validateUserOwnsService($serviceID)) {
@@ -133,6 +210,9 @@ try {
break; break;
} }
$vf->requireProvisionedService($serviceID);
$vf->requireRateLimit('rebuild:' . $serviceID, 60);
$osId = isset($_POST['osId']) ? (int) $_POST['osId'] : 0; $osId = isset($_POST['osId']) ? (int) $_POST['osId'] : 0;
$hostname = isset($_POST['hostname']) ? preg_replace('/[^a-zA-Z0-9.\-]/', '', $_POST['hostname']) : null; $hostname = isset($_POST['hostname']) ? preg_replace('/[^a-zA-Z0-9.\-]/', '', $_POST['hostname']) : null;
@@ -156,6 +236,10 @@ try {
*/ */
case 'rename': case 'rename':
// Mutation: anti-CSRF. No rate limit — name changes are cheap.
$vf->requirePost();
$vf->requireSameOrigin();
$serviceID = $vf->validateServiceID(true); $serviceID = $vf->validateServiceID(true);
if (! $vf->validateUserOwnsService($serviceID)) { if (! $vf->validateUserOwnsService($serviceID)) {
@@ -163,9 +247,14 @@ try {
break; break;
} }
$vf->requireProvisionedService($serviceID);
$newName = isset($_POST['name']) ? trim($_POST['name']) : ''; $newName = isset($_POST['name']) ? trim($_POST['name']) : '';
if (empty($newName) || strlen($newName) > 63 || ! preg_match('/^[a-z0-9]([a-z0-9\-]{0,61}[a-z0-9])?$/', $newName)) { // VF "name" is a display label, not a DNS hostname — preserve
// case + accept any printable string up to 63 chars. The only
// hard rejects are empty, oversized, and control characters.
if ($newName === '' || strlen($newName) > 63 || preg_match('/[\x00-\x1F\x7F]/', $newName)) {
$vf->output(['success' => false, 'errors' => 'Invalid server name'], true, true, 400); $vf->output(['success' => false, 'errors' => 'Invalid server name'], true, true, 400);
break; break;
} }
@@ -192,6 +281,8 @@ try {
break; break;
} }
$vf->requireProvisionedService($serviceID);
$templates = $vf->fetchOsTemplates($serviceID); $templates = $vf->fetchOsTemplates($serviceID);
if ($templates !== false) { if ($templates !== false) {
@@ -211,6 +302,11 @@ try {
*/ */
case 'resetServerPassword': case 'resetServerPassword':
// Destructive: rotates the VPS root password. Anti-CSRF + 30 s
// rate limit so a hostile script can't lock out the customer.
$vf->requirePost();
$vf->requireSameOrigin();
$serviceID = $vf->validateServiceID(true); $serviceID = $vf->validateServiceID(true);
if (! $vf->validateUserOwnsService($serviceID)) { if (! $vf->validateUserOwnsService($serviceID)) {
@@ -218,6 +314,9 @@ try {
break; break;
} }
$vf->requireProvisionedService($serviceID);
$vf->requireRateLimit('resetServerPassword:' . $serviceID, 30);
$result = $vf->resetServerPassword($serviceID); $result = $vf->resetServerPassword($serviceID);
if ($result !== false) { if ($result !== false) {
@@ -244,6 +343,8 @@ try {
break; break;
} }
$vf->requireProvisionedService($serviceID);
$result = $vf->getServerBackups($serviceID); $result = $vf->getServerBackups($serviceID);
if ($result !== false) { if ($result !== false) {
@@ -270,6 +371,8 @@ try {
break; break;
} }
$vf->requireProvisionedService($serviceID);
$result = $vf->getTrafficStats($serviceID); $result = $vf->getTrafficStats($serviceID);
if ($result !== false) { if ($result !== false) {
@@ -296,6 +399,8 @@ try {
break; break;
} }
$vf->requireProvisionedService($serviceID);
$result = $vf->getVncConsole($serviceID); $result = $vf->getVncConsole($serviceID);
if ($result !== false) { if ($result !== false) {
@@ -307,9 +412,36 @@ try {
break; break;
/** /**
* Toggle VNC on/off. * Render the noVNC viewer HTML page.
*
* SECURITY MODEL
* --------------
* This is the popup target instead of a blob URL — it keeps the
* wss token out of any URL the customer can copy/share. The page
* is gated by the same client.php protections every other action
* uses:
* - WHMCS session required (isAuthenticated)
* - validateUserOwnsService prevents cross-customer access
* (any other customer hitting this URL with their session
* gets a 403)
* - requireProvisionedService blocks orphan services
*
* Each request rotates the wss token by POSTing to VirtFusion's
* /vnc endpoint with vnc:true — older tokens VirtFusion was
* tracking are superseded, so a leaked token from a previous
* popup open is no longer usable after the next click.
*
* Method is POST (not GET) so we can require same-origin and
* avoid the GET-with-side-effects anti-pattern. JS opens the
* popup via a hidden form-submit (see vfOpenVnc in module.js).
*
* Output is text/html (NOT the JSON the other actions use),
* directly delivered to the popup window.
*/ */
case 'toggleVnc': case 'vncViewer':
$vf->requirePost();
$vf->requireSameOrigin();
$serviceID = $vf->validateServiceID(true); $serviceID = $vf->validateServiceID(true);
@@ -318,6 +450,110 @@ try {
break; break;
} }
$vf->requireProvisionedService($serviceID);
// 5 s rate limit — protects against runaway-script token rotation
// bursts. A legitimate user clicking Open Console twice in a row
// (e.g. popup got closed) waits at most 5 s.
$vf->requireRateLimit('vncViewer:' . $serviceID, 5);
// Rotate credentials by toggling vnc=true (idempotent — VF returns
// a fresh token + password on each call). Falls back to a plain
// GET if the rotate call fails so the customer still gets a
// viewer with the existing creds.
$vncData = $vf->toggleVnc($serviceID, true);
if ($vncData === false) {
$vncData = $vf->getVncConsole($serviceID);
}
if ($vncData === false) {
http_response_code(500);
header('Content-Type: text/html; charset=utf-8');
echo '<!DOCTYPE html><html><head><title>VNC Console</title></head><body style="font-family:sans-serif;padding:40px;text-align:center;color:#aaa;background:#111;">Unable to obtain VNC credentials. The server may be powered off.</body></html>';
exit;
}
// Drill the response shape the same way module.js used to —
// wrapper.data.vnc holds the credentials; wrapper.baseUrl is
// added by Module::toggleVnc / Module::getVncConsole.
$apiRoot = isset($vncData['data']) ? $vncData['data'] : $vncData;
$vnc = $apiRoot['vnc'] ?? [];
$baseUrl = $vncData['baseUrl'] ?? '';
$wssPath = $vnc['wss']['url'] ?? '';
$password = $vnc['password'] ?? '';
if ($baseUrl === '' || $wssPath === '') {
http_response_code(500);
header('Content-Type: text/html; charset=utf-8');
echo '<!DOCTYPE html><html><head><title>VNC Console</title></head><body style="font-family:sans-serif;padding:40px;text-align:center;color:#aaa;background:#111;">VNC credentials missing from the API response.</body></html>';
exit;
}
// Look up the server name for the popup title (best-effort —
// doesn't gate rendering).
$serverName = '';
try {
$hosting = Capsule::table('tblhosting')->where('id', $serviceID)->first(['domain']);
$serverName = $hosting && $hosting->domain ? (string) $hosting->domain : '';
} catch (Throwable $e) { /* non-fatal */
}
$vfHost = preg_replace('~^https?://~', '', rtrim($baseUrl, '/'));
$vncJsSrc = $baseUrl . '/vnc/vnc.js';
$esc = fn ($s) => htmlspecialchars((string) $s, ENT_QUOTES, 'UTF-8');
header('Content-Type: text/html; charset=utf-8');
// Don't let the page be embedded by other origins or cached
// intermediaries — the rotated token must not stick around.
header('X-Frame-Options: DENY');
header('Cache-Control: no-store, no-cache, must-revalidate, private');
header('Pragma: no-cache');
// CSP — only the VirtFusion panel can serve scripts (vnc.js bundle)
// and only the wss endpoint on that host accepts our WebSocket.
// Self is needed for the inline script that runs the noVNC bundle.
header("Content-Security-Policy: default-src 'none'; script-src 'self' " . $baseUrl . '; connect-src wss://' . $vfHost . ' ' . $baseUrl . "; img-src 'self' data: " . $baseUrl . "; style-src 'self' 'unsafe-inline'; frame-ancestors 'none';");
?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>VNC — <?= $esc($serverName) ?></title>
<style>html,body{margin:0;padding:0;background:#000;height:100%;font-family:sans-serif;color:#aaa;}</style>
</head>
<body>
<input type="hidden" id="con" value="wss://<?= $esc($vfHost . $wssPath) ?>">
<input type="hidden" id="pass" value="<?= $esc($password) ?>">
<input type="hidden" id="server-name" value="<?= $esc($serverName) ?>">
<div id="noVNC_container" style="position:fixed;inset:0;"></div>
<script src="<?= $esc($vncJsSrc) ?>"></script>
</body>
</html><?php
exit;
break;
/**
* Toggle VNC on/off.
*
* Dead path as of 1.5.0 (UI no longer exposes a toggle — see
* VNC notes in CLAUDE.md). Kept for backwards-compat in case any
* out-of-tree caller invokes it; gated as if it were live so
* leaving it here doesn't widen the attack surface.
*/
case 'toggleVnc':
$vf->requirePost();
$vf->requireSameOrigin();
$serviceID = $vf->validateServiceID(true);
if (! $vf->validateUserOwnsService($serviceID)) {
$vf->output(['success' => false, 'errors' => 'service <> owner mismatch'], true, true, 403);
break;
}
$vf->requireProvisionedService($serviceID);
$vf->requireRateLimit('toggleVnc:' . $serviceID, 5);
$enabled = isset($_POST['enabled']) && $_POST['enabled'] === '1'; $enabled = isset($_POST['enabled']) && $_POST['enabled'] === '1';
$result = $vf->toggleVnc($serviceID, $enabled); $result = $vf->toggleVnc($serviceID, $enabled);
@@ -345,6 +581,8 @@ try {
break; break;
} }
$vf->requireProvisionedService($serviceID);
$result = $vf->getSelfServiceUsage($serviceID); $result = $vf->getSelfServiceUsage($serviceID);
if ($result !== false) { if ($result !== false) {
@@ -367,6 +605,8 @@ try {
break; break;
} }
$vf->requireProvisionedService($serviceID);
$result = $vf->getSelfServiceReport($serviceID); $result = $vf->getSelfServiceReport($serviceID);
if ($result !== false) { if ($result !== false) {
@@ -382,6 +622,13 @@ try {
*/ */
case 'selfServiceAddCredit': case 'selfServiceAddCredit':
// Money-affecting mutation: anti-CSRF + 5 s rate limit so a
// hostile script can't accidentally trigger duplicate charges
// by spamming credit-adds. The actual amount is also validated
// and money-bound on the WHMCS side, but defence-in-depth.
$vf->requirePost();
$vf->requireSameOrigin();
$serviceID = $vf->validateServiceID(true); $serviceID = $vf->validateServiceID(true);
if (! $vf->validateUserOwnsService($serviceID)) { if (! $vf->validateUserOwnsService($serviceID)) {
@@ -389,6 +636,9 @@ try {
break; break;
} }
$vf->requireProvisionedService($serviceID);
$vf->requireRateLimit('selfServiceAddCredit:' . $serviceID, 5);
$tokens = isset($_POST['tokens']) ? (float) $_POST['tokens'] : 0; $tokens = isset($_POST['tokens']) ? (float) $_POST['tokens'] : 0;
if ($tokens <= 0) { if ($tokens <= 0) {
$vf->output(['success' => false, 'errors' => 'Invalid credit amount. Must be a positive number.'], true, true, 400); $vf->output(['success' => false, 'errors' => 'Invalid credit amount. Must be a positive number.'], true, true, 400);
@@ -405,6 +655,171 @@ try {
$vf->output(['success' => false, 'errors' => 'Failed to add credit'], true, true, 500); $vf->output(['success' => false, 'errors' => 'Failed to add credit'], true, true, 500);
break; break;
// =================================================================
// Reverse DNS (PowerDNS)
// =================================================================
/**
* List PTR state for every IP assigned to the service's server.
*
* Always fetches fresh server data from VirtFusion (not cached server_object)
* so the displayed IPs match current reality — if an IP was reassigned out
* of this server since last sync, it won't appear here.
*/
case 'rdnsList':
$serviceID = $vf->validateServiceID(true);
if (! $vf->validateUserOwnsService($serviceID)) {
$vf->output(['success' => false, 'errors' => 'service <> owner mismatch'], true, true, 403);
break;
}
$vf->requireProvisionedService($serviceID);
// Reads are permitted for Active + Suspended (a suspended user can still see their rDNS);
// Terminated/Pending/Cancelled/Fraud return a clear 400 upfront.
$vf->requireServiceStatus($serviceID, ['Active', 'Suspended']);
if (! PowerDnsConfig::isEnabled()) {
$vf->output(['success' => true, 'data' => ['enabled' => false, 'ips' => []]], true, true, 200);
break;
}
$serverData = $vf->fetchServerData($serviceID);
if (! $serverData) {
$vf->output(['success' => false, 'errors' => 'Unable to retrieve server data'], true, true, 502);
break;
}
$ptrs = (new PtrManager)->listPtrs($serverData);
$vf->output(['success' => true, 'data' => ['enabled' => true, 'ips' => $ptrs]], true, true, 200);
break;
/**
* Update (or delete) the PTR for a single IP assigned to the user's server.
*
* Validation order: ownership -> IP format -> PTR regex -> IP belongs to this server
* -> rate-limit/forward-DNS checks inside PtrManager. Sending an empty `ptr` deletes.
*/
case 'rdnsUpdate':
// Mutation: enforce POST, same-origin, active service status in that order.
// requirePost/requireSameOrigin exit on failure (405/403 respectively), so nothing below runs.
$vf->requirePost();
$vf->requireSameOrigin();
$serviceID = $vf->validateServiceID(true);
$clientId = $vf->validateUserOwnsService($serviceID);
if (! $clientId) {
$vf->output(['success' => false, 'errors' => 'service <> owner mismatch'], true, true, 403);
break;
}
$vf->requireProvisionedService($serviceID);
// Writes require an Active service — Suspended/Terminated/etc. cannot mutate rDNS.
$vf->requireServiceStatus($serviceID, ['Active']);
if (! PowerDnsConfig::isEnabled()) {
$vf->output(['success' => false, 'errors' => 'Reverse DNS is not enabled on this installation'], true, true, 400);
break;
}
$ip = isset($_POST['ip']) ? trim((string) $_POST['ip']) : '';
$ptr = isset($_POST['ptr']) ? trim((string) $_POST['ptr']) : '';
if (filter_var($ip, FILTER_VALIDATE_IP) === false) {
$vf->output(['success' => false, 'errors' => 'Invalid IP address'], true, true, 400);
break;
}
if ($ptr !== '' && ! preg_match('/^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}\.?$/', $ptr)) {
$vf->output(['success' => false, 'errors' => 'Invalid hostname for PTR record'], true, true, 400);
break;
}
if (strlen($ptr) > 253) {
$vf->output(['success' => false, 'errors' => 'Hostname too long'], true, true, 400);
break;
}
// Cross-check: the submitted IP must be currently assigned to this user's server.
// Fetch fresh from VirtFusion (not the stored object) to prevent stale-ownership writes
// after an IP reassignment.
$serverData = $vf->fetchServerData($serviceID);
if (! $serverData) {
$vf->output(['success' => false, 'errors' => 'Unable to verify IP ownership'], true, true, 502);
break;
}
$extracted = IpUtil::extractIps($serverData);
$targetBin = @inet_pton($ip);
$owns = false;
// Stage 1: exact-IP match. Covers every v4 case and any v6 host address
// VirtFusion exposes directly (per-host records or /128 subnet entries).
foreach ($extracted['addresses'] as $a) {
if (@inet_pton($a) === $targetBin) {
$owns = true;
break;
}
}
// Stage 2: v6 subnet containment. If the exact match failed and this is
// a v6 address, check whether it falls inside any of the server's
// allocated v6 subnets. This is the path for "my VirtFusion VPS has a
// /64 routed to it and I want a PTR for mail.example.com on one of the
// host addresses inside that /64" — we don't know which host addresses
// are actually in use, but we can prove this one lies within a range
// the customer is authorised for.
if (! $owns && IpUtil::isIpv6($ip)) {
foreach ($extracted['subnets'] as $s) {
if (IpUtil::ipv6InSubnet($ip, $s['subnet'], (int) $s['cidr'])) {
$owns = true;
break;
}
}
}
if (! $owns) {
Log::insert('rdnsUpdate:ownership', ['serviceID' => $serviceID, 'ip' => $ip], 'IP not assigned to this service');
$vf->output(['success' => false, 'errors' => 'This IP is not assigned to your server'], true, true, 403);
break;
}
$result = (new PtrManager)->setPtr($ip, $ptr);
if ($result['ok']) {
// Audit trail for successful edits — surfaces in Utilities → Logs → Module Log,
// searchable by clientId / serviceId / ip for "who changed this PTR".
Log::insert(
'rdnsUpdate:ok',
['clientId' => $clientId, 'serviceID' => $serviceID, 'ip' => $ip, 'reason' => $result['reason']],
['ptr' => $ptr === '' ? '(deleted)' : $ptr],
);
$vf->output(['success' => true, 'data' => ['reason' => $result['reason']]], true, true, 200);
break;
}
// Map internal reasons to client-facing messages/status codes.
switch ($result['reason']) {
case 'forward-missing':
$vf->output(['success' => false, 'errors' => 'Forward DNS for "' . $ptr . '" does not resolve to ' . $ip . '. Configure the A/AAAA record with your DNS provider first, then try again.'], true, true, 400);
break;
case 'rate-limited':
$vf->output(['success' => false, 'errors' => 'Too many updates for this IP. Try again in a few seconds.'], true, true, 429);
break;
case 'no-zone':
$vf->output(['success' => false, 'errors' => 'This IP has no reverse DNS zone configured on the nameserver.'], true, true, 400);
break;
case 'disabled':
$vf->output(['success' => false, 'errors' => 'Reverse DNS is not enabled'], true, true, 400);
break;
default:
$vf->output(['success' => false, 'errors' => 'Reverse DNS update failed (' . $result['reason'] . ')'], true, true, 500);
}
break;
default: default:
$vf->output(['success' => false, 'errors' => 'invalid action'], true, true, 400); $vf->output(['success' => false, 'errors' => 'invalid action'], true, true, 400);
} }

View File

@@ -1,14 +1,289 @@
<?php <?php
/**
* WHMCS hooks for the VirtFusion module.
*
* HOW HOOKS WORK IN WHMCS
* -----------------------
* add_hook('EventName', $priority, $callback) registers $callback to fire on
* the named event. WHMCS discovers hook files by walking modules/servers/*
* /hooks.php and modules/addons/* /hooks.php on every page load, then invokes
* every registered hook for the current event.
*
* Hooks run IN-REQUEST — there's no queue or background worker. Anything
* expensive in a hook (like an external API call) blocks the user's page
* load. For that reason we only do:
* - Fast in-process work (building DOM snippets, validating session state)
* - Scheduled work on DailyCronJob where "in-request" means the cron worker,
* not a user session
*
* HOOKS REGISTERED HERE
* ---------------------
* DailyCronJob — PowerDNS reconciliation across all services
* AfterCronJob — Every-2-hour stock recalculation safety net
* AfterModuleCreate — Stock refresh + order auto-accept after a VPS provisions
* AfterModuleTerminate — Stock refresh after a VPS is destroyed
* ClientAreaPageCart — Lazy per-product stock refresh during the order flow
* ShoppingCartValidateCheckout — blocks checkout until OS is selected
* ClientAreaFooterOutput — injects the OS/SSH-key gallery on order form
*
* FAILURE SEMANTICS
* -----------------
* Every hook wraps its body in try/catch and silently absorbs any exception.
* A hook that throws would potentially break the entire WHMCS request for
* all users, not just this module — so we log and swallow, preferring
* degraded functionality over site-wide breakage.
*/
use WHMCS\Database\Capsule; use WHMCS\Database\Capsule;
use WHMCS\Module\Server\VirtFusionDirect\Cache;
use WHMCS\Module\Server\VirtFusionDirect\ConfigureService; use WHMCS\Module\Server\VirtFusionDirect\ConfigureService;
use WHMCS\Module\Server\VirtFusionDirect\Database; use WHMCS\Module\Server\VirtFusionDirect\Database;
use WHMCS\Module\Server\VirtFusionDirect\Log;
use WHMCS\Module\Server\VirtFusionDirect\Module; use WHMCS\Module\Server\VirtFusionDirect\Module;
use WHMCS\Module\Server\VirtFusionDirect\PowerDns\Config as PowerDnsConfig;
use WHMCS\Module\Server\VirtFusionDirect\PowerDns\PtrManager;
use WHMCS\Module\Server\VirtFusionDirect\StockControl;
if (! defined('WHMCS')) { if (! defined('WHMCS')) {
exit('This file cannot be accessed directly'); exit('This file cannot be accessed directly');
} }
/**
* Daily PowerDNS reconciliation.
*
* Walks every managed service and creates any missing PTRs (never overwrites existing
* values — cron is additive-only). Requires the VirtFusion DNS addon to be activated
* and enabled; otherwise short-circuits immediately.
*
* All error handling lives inside reconcileAll(); this wrapper just logs any escape
* without disturbing the rest of the daily cron run.
*/
add_hook('DailyCronJob', 1, function ($vars) {
try {
if (PowerDnsConfig::isEnabled()) {
(new PtrManager)->reconcileAll();
}
} catch (Throwable $e) {
Log::insert('PowerDns:DailyCronJob', [], $e->getMessage());
}
});
/**
* Every-~2-hour stock recalculation safety net.
*
* Events (AfterModuleCreate/Terminate) cover every capacity change driven
* through WHMCS. But an operator can also create/destroy VMs directly in the
* VirtFusion panel — no WHMCS hook fires for that, so stock qty would drift
* until the next cart-page visit or the next event-driven refresh. This hook
* closes that blind spot.
*
* AfterCronJob fires on every main WHMCS cron invocation (typically every
* 5 minutes). Cache::get on the rate-limit key means the hook is effectively
* free on the 99% of invocations where no recalc is due — one cache read,
* return. The actual recalc only runs when the key has expired.
*
* Interval: 2 hours. Tunable via the STOCK_CRON_INTERVAL_SECONDS constant
* below. Short enough that out-of-band VirtFusion panel changes surface the
* same business day; long enough that the storefront isn't writing
* tblproducts.qty every five minutes.
*
* FAIL-SAFE: StockControl::recalculateAll() returns a map of productId =>
* qty|null, where null means the orchestrator left qty UNTOUCHED (transient
* API failure, missing CP, etc.). Our catch here only fires on truly unexpected
* errors that escape the orchestrator itself.
*/
const STOCK_CRON_INTERVAL_SECONDS = 2 * 3600; // 2 hours
add_hook('AfterCronJob', 5, function ($vars) {
try {
$rateKey = 'stockrefresh:cron';
if (Cache::get($rateKey) !== null) {
return;
}
Cache::set($rateKey, 1, STOCK_CRON_INTERVAL_SECONDS);
(new StockControl)->recalculateAll();
} catch (Throwable $e) {
Log::insert('StockControl:AfterCronJob', [], $e->getMessage());
}
});
/**
* Post-provision: auto-accept the originating order and refresh stock.
*
* Fires after every successful VirtFusion CreateAccount. Two responsibilities,
* independent try/catch blocks so a failure in one doesn't short-circuit the other:
*
* 1. AUTO-ACCEPT — if the service's parent order is still 'Pending' (admin
* hasn't manually accepted yet), call WHMCS's AcceptOrder API with
* autosetup=false (we already provisioned, don't re-trigger CreateAccount).
* This closes the loop for installs that rely on pending-order workflows
* for non-VF products but want VF provisions to auto-advance.
*
* 2. STOCK REFRESH — a new VM just consumed memory/cpu/disk/IPv4 on the
* target hypervisor group. Bust the grpres:{id} cache and recalculate
* every stock-controlled product. A shared 30 s rate-limit key prevents
* a burst of 10 parallel provisions from triggering 10 full recalcs.
*
* Filtering by moduletype='VirtFusionDirect' keeps this hook harmless for
* unrelated products that happen to share the WHMCS install.
*/
add_hook('AfterModuleCreate', 1, function ($vars) {
if (($vars['params']['moduletype'] ?? '') !== 'VirtFusionDirect') {
return;
}
// Part 1: auto-accept the originating order if still Pending.
try {
$serviceId = (int) ($vars['params']['serviceid'] ?? 0);
if ($serviceId > 0) {
$hosting = Capsule::table('tblhosting')->where('id', $serviceId)->first();
$orderId = $hosting ? (int) ($hosting->orderid ?? 0) : 0;
if ($orderId > 0) {
$order = Capsule::table('tblorders')->where('id', $orderId)->first();
if ($order && strcasecmp((string) $order->status, 'Pending') === 0) {
// WHMCS 9 regression guard: WHMCS 9's batch order-acceptance
// loop terminates once the order leaves Pending status.
// Calling AcceptOrder after the first sibling completes
// therefore short-circuits provisioning of the rest of the
// order's services — they end up Active in tblhosting with
// no mod_virtfusion_direct row and no server in VirtFusion.
// Defer the AcceptOrder until every VF service in this
// order has provisioned; the hook fires once per service,
// so the last one to complete will see no unprovisioned
// siblings and trigger the accept. WHMCS 8 wasn't affected
// (its loop ignored order status mid-batch), but deferring
// there is harmless — same end state, just later timing.
$unprovisionedSiblings = Capsule::table('tblhosting AS h')
->join('tblproducts AS p', 'h.packageid', '=', 'p.id')
->leftJoin('mod_virtfusion_direct AS m', 'h.id', '=', 'm.service_id')
->where('h.orderid', $orderId)
->where('h.id', '!=', $serviceId)
->where('p.servertype', 'VirtFusionDirect')
->where('h.domainstatus', 'Pending')
->whereNull('m.server_id')
->count();
if ($unprovisionedSiblings > 0) {
Log::insert(
'AutoAcceptOrder:deferred',
['orderid' => $orderId, 'serviceid' => $serviceId, 'unprovisioned_siblings' => $unprovisionedSiblings],
'Order has more VirtFusionDirect services awaiting provisioning; AcceptOrder will fire after the last one',
);
} else {
$resp = localAPI('AcceptOrder', [
'orderid' => $orderId,
'autosetup' => false, // already provisioned; don't re-run CreateAccount
'sendemail' => true,
]);
Log::insert(
'AutoAcceptOrder',
['orderid' => $orderId, 'serviceid' => $serviceId],
$resp,
);
}
}
}
}
} catch (Throwable $e) {
Log::insert('AutoAcceptOrder:fail', ['serviceID' => $vars['params']['serviceid'] ?? null], $e->getMessage());
}
// Part 2: refresh stock (capacity just decreased).
try {
if (Cache::get('stockrefresh:event') === null) {
Cache::set('stockrefresh:event', 1, 30);
$groupId = (int) ($vars['params']['configoption1'] ?? 0);
if ($groupId > 0) {
Cache::forget('grpres:' . $groupId);
}
(new StockControl)->recalculateAll();
}
} catch (Throwable $e) {
Log::insert('StockControl:AfterModuleCreate', ['serviceID' => $vars['params']['serviceid'] ?? null], $e->getMessage());
}
});
/**
* Post-termination stock refresh.
*
* A destroyed VM just freed memory/cpu/disk/IPv4 on the target hypervisor group.
* Refresh so the storefront reflects the restored capacity immediately. Shares
* the 30 s rate-limit key with AfterModuleCreate — a provision-then-terminate in
* quick succession only triggers one full recalc.
*/
add_hook('AfterModuleTerminate', 1, function ($vars) {
if (($vars['params']['moduletype'] ?? '') !== 'VirtFusionDirect') {
return;
}
try {
if (Cache::get('stockrefresh:event') !== null) {
return;
}
Cache::set('stockrefresh:event', 1, 30);
$groupId = (int) ($vars['params']['configoption1'] ?? 0);
if ($groupId > 0) {
Cache::forget('grpres:' . $groupId);
}
(new StockControl)->recalculateAll();
} catch (Throwable $e) {
Log::insert('StockControl:AfterModuleTerminate', ['serviceID' => $vars['params']['serviceid'] ?? null], $e->getMessage());
}
});
/**
* Lazy stock refresh on order-flow cart pages.
*
* Keeps "hot" products fresh between daily cron runs without a polling loop: when a
* customer lands on a cart page for a specific product, we opportunistically recalculate
* that product's qty. If the upstream grpres:{id} cache is warm (populated in the last
* 120 s by an earlier view or the daily cron), recalculateForProduct does no HTTP calls
* and just re-writes the same qty — effectively free.
*
* WHY ClientAreaPageCart (not ClientAreaPageProductDetails)
* ---------------------------------------------------------
* ClientAreaPageProductDetails fires on the My Services → product-details view for an
* EXISTING service, which is the wrong place — the stock number only matters during
* pre-order. ClientAreaPageCart fires on every cart/order page (product browse, config,
* checkout) and WHMCS consults tblproducts.qty on each of those, so this is where a
* fresh number pays off.
*
* RATE LIMIT
* ----------
* 60 s per product (stockrefresh:{pid}). Short enough that a busy product refreshes
* near-continuously across viewers; long enough that two customers arriving within the
* same second don't trigger two identical DB UPDATEs. The pid check below filters this
* hook to only fire when a specific product is known — generic cart pages (templatefile=
* "cart.tpl") pass no pid and are no-ops.
*/
add_hook('ClientAreaPageCart', 1, function ($vars) {
try {
$productId = (int) ($vars['pid'] ?? $vars['productid'] ?? ($vars['productinfo']['pid'] ?? 0));
if ($productId <= 0) {
return null;
}
$rateKey = 'stockrefresh:' . $productId;
if (Cache::get($rateKey) !== null) {
return null;
}
Cache::set($rateKey, 1, 60);
(new StockControl)->recalculateForProduct($productId);
} catch (Throwable $e) {
Log::insert('StockControl:ClientAreaPageCart', ['pid' => $vars['pid'] ?? null], $e->getMessage());
}
return null;
});
/** /**
* Shopping Cart Validation Hook * Shopping Cart Validation Hook
* *
@@ -200,10 +475,10 @@ add_hook('ClientAreaFooterOutput', 1, function ($vars) {
catImg.alt = ''; catImg.alt = '';
catImg.onerror = function() { this.parentNode.style.background = catColor; this.parentNode.textContent = (cat.name || '?')[0].toUpperCase(); }; catImg.onerror = function() { this.parentNode.style.background = catColor; this.parentNode.textContent = (cat.name || '?')[0].toUpperCase(); };
catIcon.appendChild(catImg); catIcon.appendChild(catImg);
} else if (cat.name === 'Other') {
catIcon.style.background = '#6c757d';
catIcon.innerHTML = '<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"#fff\"><path d=\"M3 2a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V3a1 1 0 0 0-1-1H3zm1 2h8v2H4V4zm0 3h8v1H4V7zm0 2h5v1H4V9z\"/></svg>';
} else { } else {
// No icon (synthetic singletons bucket, etc.) — fall back
// to brand-color circle with the first letter, matching
// the client-area renderer.
catIcon.style.background = catColor; catIcon.style.background = catColor;
catIcon.textContent = (cat.name || '?')[0].toUpperCase(); catIcon.textContent = (cat.name || '?')[0].toUpperCase();
} }
@@ -576,3 +851,78 @@ add_hook('ClientAreaFooterOutput', 1, function ($vars) {
return null; return null;
} }
}); });
/**
* Inject a "On This Page" jump-link group into the client area sidebar
* when the customer is viewing a VirtFusionDirect product details page.
*
* Replaces the previous inline horizontal nav strip — sidebar placement
* keeps the links visible while scrolling the long product details page.
*
* Static rendering: every known section anchor is added regardless of
* whether its panel is visible. JS (vfBuildSectionNav in module.js) walks
* the rendered links post-load and hides the parent <li> for any target
* panel that isn't visible (Resources/VNC/Self-Service when their data
* hasn't loaded; rDNS when PowerDNS isn't enabled at the template level).
*
* Filtered to productdetails for VF services so we don't pollute the
* sidebar on unrelated pages or non-VF service detail pages.
*/
add_hook('ClientAreaPrimarySidebar', 1, function ($primarySidebar) {
try {
$action = $_REQUEST['action'] ?? '';
$serviceId = (int) ($_REQUEST['id'] ?? 0);
if ($action !== 'productdetails' || $serviceId <= 0) {
return;
}
// Verify this is a VirtFusionDirect service before adding our links.
$isVf = Capsule::table('tblhosting AS h')
->join('tblproducts AS p', 'h.packageid', '=', 'p.id')
->where('h.id', $serviceId)
->where('p.servertype', 'VirtFusionDirect')
->exists();
if (! $isVf) {
return;
}
// High order pushes us below the standard "Manage Product" entries.
$jump = $primarySidebar->addChild('VfJumpTo', [
'label' => 'On This Page',
'order' => 80,
]);
// VNC deliberately excluded — its panel sits at the very top of
// the page, so a sidebar jump-link would just scroll the customer
// past everything else they care about. The other entries are
// ordered to match the page's vertical flow.
$items = [
['Overview', 'vf-sec-overview'],
['Traffic', 'vf-sec-traffic'],
['Live Stats', 'vf-sec-livestats'],
['Power', 'vf-sec-power'],
['Manage', 'vf-sec-manage'],
['Rebuild', 'vf-sec-rebuild'],
['Reverse DNS', 'vf-sec-rdns'],
['Resources', 'vf-resources-panel'],
['Billing & Usage', 'vf-selfservice-panel'],
['Billing Overview', 'vf-sec-billing'],
];
foreach ($items as $i => $item) {
$child = $jump->addChild('vfsec-' . $item[1], [
'label' => $item[0],
'uri' => '#' . $item[1],
'order' => ($i + 1) * 10,
]);
// data-vf-target lets the smooth-scroll handler in module.js find
// these links generically (same selector covers both inline and
// sidebar nav). Class is duplicated for legacy CSS that may key
// on .vf-nav-link.
$child->setAttribute('data-vf-target', $item[1]);
$child->setClass('vf-nav-link');
}
} catch (Throwable $e) {
// Silent failure — sidebar customisation must never break the page.
}
});

View File

@@ -4,6 +4,27 @@ namespace WHMCS\Module\Server\VirtFusionDirect;
/** /**
* Static methods that generate HTML fragments for the WHMCS admin services tab. * Static methods that generate HTML fragments for the WHMCS admin services tab.
*
* WHY RAW HTML STRINGS INSTEAD OF TEMPLATES
* -----------------------------------------
* WHMCS's AdminServicesTabFields hook expects an associative array of
* label => HTML-string pairs. It renders each entry as a table row with the
* label on the left and the raw HTML inserted verbatim on the right. There's
* no way to return a Smarty template reference from that hook — WHMCS doesn't
* know how to render one in that context.
*
* So we concatenate HTML here. All variable interpolation uses htmlspecialchars()
* at the PHP boundary — never trust that a value passed in is safe for HTML.
*
* ASSET INJECTION
* ---------------
* Some renderers (serverInfo, rdnsSection) embed <link> and <script> tags so
* the admin services tab picks up our CSS and JS without a separate loader
* hook. This is safe because WHMCS's admin CSP allows same-origin resources
* and the admin page is already inside an authenticated admin session.
*
* Cache-busting uses time() as a query string — fine for an admin-only surface
* where we'd rather pay for the extra fetch than let stale JS cause bugs.
*/ */
class AdminHTML class AdminHTML
{ {
@@ -147,6 +168,38 @@ EOT;
</div> </div>
</div> </div>
<script>vfServerDataAdmin("${serviceId}","${systemUrl}");</script> <script>vfServerDataAdmin("${serviceId}","${systemUrl}");</script>
EOT;
}
/**
* Render the admin Reverse DNS section for the services tab.
*
* Ships an empty container + a Reconcile button. Data is loaded client-side via
* the admin rdnsStatus AJAX endpoint once the page opens. The JS function
* vfAdminLoadRdns (defined in templates/js/module.js) populates #vf-rdns-list
* and wires up the Reconcile button's onclick to admin.php?action=rdnsReconcile.
*
* @param string $systemUrl WHMCS system URL
* @param int $serviceId WHMCS service ID
* @return string HTML fragment for the admin services tab
*/
public static function rdnsSection($systemUrl, $serviceId)
{
$systemUrl = htmlspecialchars($systemUrl, ENT_QUOTES, 'UTF-8');
$serviceId = (int) $serviceId;
return <<<EOT
<div id="vf-rdns-admin-wrap">
<div id="vf-rdns-list" class="vf-rdns-list">
<em class="text-muted">Loading reverse DNS…</em>
</div>
<div class="vf-rdns-actions" style="margin-top:10px">
<button type="button" class="btn btn-default btn-sm" onclick="vfAdminReconcileRdns(${serviceId}, '${systemUrl}', false)">Reconcile (additive)</button>
<button type="button" class="btn btn-warning btn-sm" onclick="vfAdminReconcileRdns(${serviceId}, '${systemUrl}', true)">Reconcile (force reset)</button>
<span id="vf-rdns-report" style="margin-left:10px"></span>
</div>
</div>
<script>if(typeof vfAdminLoadRdns==='function'){vfAdminLoadRdns(${serviceId},"${systemUrl}");}</script>
EOT; EOT;
} }
} }

View File

@@ -3,11 +3,47 @@
namespace WHMCS\Module\Server\VirtFusionDirect; namespace WHMCS\Module\Server\VirtFusionDirect;
/** /**
* Two-tier cache: uses Redis when the ext-redis extension is available, with an atomic * Two-tier cache: Redis when ext-redis is available, atomic filesystem fallback otherwise.
* filesystem fallback stored in the system temp directory. *
* WHY TWO TIERS
* -------------
* The module is deployed to every kind of WHMCS install — shared hosting, dedicated
* VPS, bare-metal. Requiring Redis would exclude the long tail of smaller operators
* who never installed the extension. But operators who DO have Redis get a huge
* performance win for cross-request caching (PowerDNS zone lists, OS template
* listings, traffic stats), so we opportunistically use it when present.
*
* The fallback is filesystem-based, using the OS temp directory. Writes are atomic
* via the classic tmp-file + rename pattern so a process crash mid-write can never
* corrupt an existing cache entry for another concurrent reader.
*
* EXPIRY SEMANTICS
* ----------------
* Redis: native SETEX — the key auto-expires on the server side.
* Filesystem: we store a JSON envelope {expires, data} and check expiry on read,
* deleting stale entries lazily. This means a cache with lots of expired entries
* will slowly accumulate files until accessed — acceptable for the module's scale
* (tens-to-hundreds of keys per install) but worth noting if someone ports this
* to a higher-volume context.
*
* NAMESPACE
* ---------
* Every key is prefixed with "vfd:" to avoid collisions with anything else that
* shares the Redis instance. Nested keys add their own sub-prefix (e.g.
* "pdns:zones:<hash>" for PowerDNS zone lists) for semantic clarity in the logs.
*
* FAILURE MODES
* -------------
* Redis unreachable: we set $redisAvailable = false on first failure, which
* permanently disables Redis for the rest of this PHP process (subsequent calls
* skip straight to the file cache). Prevents paying reconnect overhead on every
* miss when Redis is down.
* File cache write fails: silently skipped. Cache is best-effort; a failed SET
* just means the next GET will re-fetch from the authoritative source.
*/ */
class Cache class Cache
{ {
/** Module-global key prefix — keeps us out of Redis key collisions on shared installs. */
const PREFIX = 'vfd:'; const PREFIX = 'vfd:';
/** @var \Redis|null */ /** @var \Redis|null */
@@ -150,12 +186,18 @@ class Cache
} }
} }
// File cache fallback with atomic write (race condition safe) // File cache fallback with atomic write.
// Writing to a temp file + rename ensures that readers either see the
// complete previous entry or the complete new entry — never a truncated
// or partially-written file. getmypid() suffix lets concurrent PHP
// processes write to the same key without stomping each other's temp files.
$path = self::filePath($key); $path = self::filePath($key);
$tmp = $path . '.' . getmypid() . '.tmp'; $tmp = $path . '.' . getmypid() . '.tmp';
$entry = json_encode(['expires' => time() + $ttl, 'data' => $value]); $entry = json_encode(['expires' => time() + $ttl, 'data' => $value]);
if (@file_put_contents($tmp, $entry, LOCK_EX) !== false) { if (@file_put_contents($tmp, $entry, LOCK_EX) !== false) {
// rename() is atomic on POSIX when source and target are on the same
// filesystem (which they always are here — both in sys_get_temp_dir).
@rename($tmp, $path); @rename($tmp, $path);
} }
} }

View File

@@ -8,9 +8,37 @@ use WHMCS\User\User;
/** /**
* Handles order-time and provisioning-time operations for VirtFusion servers. * Handles order-time and provisioning-time operations for VirtFusion servers.
* *
* Extends Module to provide package discovery, OS template fetching, server build * WHY A SIBLING OF ModuleFunctions RATHER THAN METHODS ON IT
* initialization, and SSH key retrieval/creation. Used during WHMCS checkout and * ----------------------------------------------------------
* account creation flows rather than ongoing service management. * ModuleFunctions handles the WHMCS LIFECYCLE (create, suspend, terminate, etc.)
* — operations driven by WHMCS service-state transitions.
*
* ConfigureService handles ORDER-TIME logic — package lookups, template fetching,
* SSH key creation, initial build triggering. These run during checkout (via the
* ClientAreaFooterOutput hook that populates dropdowns on the order form) and
* immediately after account creation (initServerBuild is called from
* ModuleFunctions::createAccount once the VirtFusion server exists).
*
* Splitting the concerns keeps ModuleFunctions focused on lifecycle state machines
* and ConfigureService focused on catalogue/discovery calls. They share the base
* Module's API plumbing via inheritance.
*
* CACHING
* -------
* Package/template lookups use the module's Cache class with 10-minute TTLs.
* These values change rarely (a package list is typically edited once per
* month at most) but the endpoints are on the checkout hot path, so aggressive
* caching matters for page-load performance.
*
* CP RESOLVED IN CONSTRUCTOR
* --------------------------
* Unlike ModuleFunctions which resolves the control panel per-request via the
* service ID, ConfigureService resolves it ONCE in the constructor via
* getCP(false, true) — "any available VirtFusion server". Order-time operations
* happen BEFORE a WHMCS service exists, so we can't dereference a specific
* server through mod_virtfusion_direct. "Any enabled server" is the pragmatic
* default for catalogue operations that typically return the same data
* regardless of which panel you hit.
*/ */
class ConfigureService extends Module class ConfigureService extends Module
{ {

View File

@@ -17,7 +17,20 @@ class Curl
/** @var array User-supplied cURL options that override defaults */ /** @var array User-supplied cURL options that override defaults */
private $customOptions = []; private $customOptions = [];
/** @var array Default cURL options applied to every request */ /**
* @var array Default cURL options applied to every request.
*
* Rationale:
* VERIFYPEER/VERIFYHOST: Full TLS chain + hostname validation. Disabling
* either is a common source of MITM bugs, so we never do it silently.
* RETURNTRANSFER: We always want the response body back as a string.
* HEADER off: Callers almost never need headers. Saves a parse cycle.
* NOBODY off: Default to GET-style body-returning requests.
* TIMEOUT 30s: Covers slow API endpoints without letting a hung connection
* block a whole WHMCS request indefinitely.
* CONNECTTIMEOUT 10s: Separate from the total timeout so a failed TCP
* handshake (firewall black-hole) fails fast rather than burning 30s.
*/
private $defaultOptions = [ private $defaultOptions = [
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_SSL_VERIFYHOST => 2,

View File

@@ -7,12 +7,45 @@ use WHMCS\Database\Capsule as DB;
/** /**
* Handles all database operations for the module's custom table (mod_virtfusion_direct) * Handles all database operations for the module's custom table (mod_virtfusion_direct)
* and queries against core WHMCS tables (tblhosting, tblclients, tblservers, etc.). * and queries against core WHMCS tables (tblhosting, tblclients, tblservers, etc.).
*
* SCHEMA AUTO-MIGRATION
* ---------------------
* schema() runs on every Module construction — the first call per request creates
* or migrates the module table and ensures all required custom fields exist on
* every VirtFusionDirect product. Subsequent calls within the same request hit
* the $fieldsChecked idempotency flag and short-circuit, so the overhead is
* one SHOW-columns query per request.
*
* This design means operators never need to run a separate install script —
* dropping the module files into place and hitting any admin page triggers the
* migration. The trade-off is small per-request overhead; we take it because
* WHMCS modules historically had fragile install/uninstall hooks.
*
* SCHEMA VERSIONING
* -----------------
* No explicit version table. Migrations are expressed as "create if missing"
* checks — hasTable(), hasColumn() — which makes forward migration additive
* and safe to re-run. Deletions would require a proper versioning scheme, but
* we have none so far; every column added has been non-breaking.
*
* WHMCS TABLE ACCESS
* ------------------
* Reads from tblhosting / tblclients / tblconfiguration are done via Capsule's
* fluent query builder, not raw SQL, to inherit WHMCS's database abstraction
* (connection pooling, character set, prepared statement handling).
*/ */
class Database class Database
{ {
/** Module's own per-service state table. Created on first Module instantiation. */
const SYSTEM_TABLE = 'mod_virtfusion_direct'; const SYSTEM_TABLE = 'mod_virtfusion_direct';
/** @var bool Tracks whether custom field existence has already been verified this request. */ /**
* @var bool Tracks whether custom field existence has already been verified this request.
*
* Custom-field creation is idempotent (updateOrInsert) but touching every
* product on every request is wasteful. This flag ensures it runs exactly
* once per PHP request.
*/
private static $fieldsChecked = false; private static $fieldsChecked = false;
/** /**

View File

@@ -3,18 +3,46 @@
namespace WHMCS\Module\Server\VirtFusionDirect; namespace WHMCS\Module\Server\VirtFusionDirect;
/** /**
* Thin wrapper around the WHMCS logModuleCall() function for module-level logging. * Thin wrapper around the WHMCS logModuleCall() function.
*
* WHY A WRAPPER
* -------------
* Consolidating log writes lets us:
* - Pin the module name in one place (the LOG_MODULE constant). All entries
* go under "VirtFusionDirect" regardless of which caller inserted them,
* which keeps WHMCS Admin → Utilities → Logs → Module Log filterable.
* - Get a stable import path for every file that logs (Log::insert).
* - Add cross-cutting policy later (e.g. redaction, sampling) without
* touching every call site.
*
* OUTPUT SURFACE
* --------------
* Entries appear in WHMCS Admin → Utilities → Logs → Module Log. The request
* and response parameters accept strings OR arrays — WHMCS serialises arrays
* to readable form automatically. Pass structured data (["zone" => $z, "ip" => $ip])
* rather than string-concatenated messages; the UI renders arrays as key/value
* pairs which makes filtering and debugging much easier.
*
* REDACTION EXPECTATION
* ---------------------
* Callers are responsible for not passing secrets into logs. In particular:
* - Never log Authorization/X-API-Key headers
* - Never log full request_header info from the Curl class
* - Never log the decrypted VirtFusion bearer token or PowerDNS API key
* The Curl class deliberately defaults CURLOPT_HEADER to off so header capture
* doesn't accidentally populate a field that callers might log.
*/ */
class Log class Log
{ {
/** Keep this in sync with the WHMCS server module name, so filters work. */
const LOG_MODULE = 'VirtFusionDirect'; const LOG_MODULE = 'VirtFusionDirect';
/** /**
* Write an entry to the WHMCS module log. * Write an entry to the WHMCS module log.
* *
* @param string $action Name of the action being logged (e.g. 'CreateAccount') * @param string $action Short tag identifying the operation (used as the "Function" column in the log UI)
* @param string|array $requestString Request data sent to the API * @param string|array $requestString Outbound payload or context data. Arrays preferred — rendered as key/value pairs.
* @param string|array $responseData Response data received from the API * @param string|array $responseData Inbound response or result. Same conventions as $requestString.
*/ */
public static function insert($action, $requestString, $responseData) public static function insert($action, $requestString, $responseData)
{ {

View File

@@ -10,11 +10,60 @@ use WHMCS\Database\Capsule;
* server feature methods (power, network, VNC, backup, resource modification, * server feature methods (power, network, VNC, backup, resource modification,
* self-service billing, traffic, rename, password reset). * self-service billing, traffic, rename, password reset).
* *
* Extended by ModuleFunctions (service lifecycle) and ConfigureService (order-time * INHERITANCE SHAPE
* operations). Most business logic lives here; subclasses delegate to these methods. * -----------------
* Extended by:
* - ModuleFunctions — service lifecycle (create, suspend, unsuspend, terminate, change package)
* - ConfigureService — order-time operations (package/template discovery, server build init)
*
* Most business logic lives HERE, not in the subclasses. Subclasses are intentionally
* thin — they orchestrate sequences of calls to methods defined on this base, which
* lets us unit-exercise any single feature (e.g. "what happens during rename when
* the VirtFusion API returns 423?") without standing up a full WHMCS lifecycle.
*
* THE resolveServiceContext() PATTERN
* -----------------------------------
* Almost every method follows the same preamble: look up the module table row,
* look up the WHMCS tblhosting row, resolve the control panel credentials, build
* a Curl client with the bearer token. That preamble is consolidated into
* resolveServiceContext() which returns everything as an array or false on any
* missing piece. Every feature method starts with "$ctx = $this->resolveServiceContext($id);
* if (! $ctx) return false;" and can then use $ctx['request'], $ctx['serverId'], etc.
*
* This pattern is the most important abstraction in the module — violating it
* (e.g. reading tblservers directly in a feature method) leads to drift where
* some features handle missing servers gracefully and others don't.
*
* ENDPOINT OUTPUT CONVENTION
* --------------------------
* client.php and admin.php call $this->output() to emit JSON responses. Every
* output() call in a switch case MUST be followed by a `break` — the module
* deliberately does NOT rely on exit() inside output() for flow control because
* that couples the HTTP response format to the control-flow mechanism and makes
* refactoring fragile.
*
* SECURITY HELPERS
* ----------------
* Five guards callers compose in front of sensitive actions:
* - isAuthenticated() — client session required
* - adminOnly() — admin session required
* - requirePost() — HTTP method gate (mutations only)
* - requireSameOrigin() — CSRF origin check
* - requireServiceStatus() — filter by tblhosting.domainstatus
*
* Each exits on failure with the appropriate HTTP status — callers treat them
* as "throw on failure" style assertions rather than having to check return values.
*/ */
class Module class Module
{ {
/**
* @var array|false|null Memoised catalogue-level CP connection used by fetchPackage/fetchGroupResources.
* Resolved via getCP(false, true) — "any available VirtFusion server" — on first use.
* Kept on the instance so a cron loop recalculating 20 products doesn't hit
* tblservers 20×N times when N stock helpers are called per product.
*/
private $catalogueCp = null;
/** /**
* Initialises the module and ensures the database schema is up to date. * Initialises the module and ensures the database schema is up to date.
*/ */
@@ -73,10 +122,23 @@ class Module
/** /**
* Resolve service context: system service, WHMCS service, control panel, and curl client. * Resolve service context: system service, WHMCS service, control panel, and curl client.
* Returns false if any lookup fails. *
* This is the most-called method in the module. Every feature action begins
* by calling it, so think of the return value as "everything you need to
* touch VirtFusion for this service":
*
* service — row from mod_virtfusion_direct (has server_id, server_object)
* whmcsService — row from tblhosting (has server, userid, domain, etc.)
* cp — ['url', 'base_url', 'token'] for the VirtFusion API
* request — a fresh Curl instance pre-configured with the bearer token
* serverId — (int) of service.server_id — used in every URL downstream
*
* Returning false on ANY missing piece lets callers write a single
* "if (! $ctx) return false;" check at the top of each feature method
* rather than threading nullability through three separate lookups.
* *
* @param int $serviceID * @param int $serviceID
* @return array{service: object, whmcsService: object, cp: array, request: Curl}|false * @return array{service: object, whmcsService: object, cp: array, request: Curl, serverId: int}|false
*/ */
protected function resolveServiceContext($serviceID) protected function resolveServiceContext($serviceID)
{ {
@@ -129,7 +191,21 @@ class Module
if ($ctx['request']->getRequestInfo('http_code') == '200') { if ($ctx['request']->getRequestInfo('http_code') == '200') {
$data = json_decode($data); $data = json_decode($data);
if (isset($data->data->authentication->endpoint_complete)) { if (isset($data->data->authentication->endpoint_complete)) {
return $ctx['cp']['base_url'] . $data->data->authentication->endpoint_complete; $ssoUrl = $ctx['cp']['base_url'] . $data->data->authentication->endpoint_complete;
// Open-redirect defence: assert the URL we're about to send
// the customer to is on the configured VirtFusion host. If
// the API response, the cp_base_url config, or someone
// tampering with tblservers managed to point us elsewhere,
// refuse rather than 302 to an arbitrary destination.
$expectedHost = parse_url($ctx['cp']['base_url'], PHP_URL_HOST);
$actualHost = parse_url($ssoUrl, PHP_URL_HOST);
if (! $expectedHost || strcasecmp((string) $expectedHost, (string) $actualHost) !== 0) {
Log::insert(__FUNCTION__ . ':host_mismatch', ['expected' => $expectedHost, 'actual' => $actualHost], 'SSO redirect rejected');
return false;
}
return $ssoUrl;
} }
} }
@@ -212,14 +288,46 @@ class Module
return false; return false;
} }
$data = $ctx['request']->get($ctx['cp']['url'] . '/servers/' . $ctx['serverId']); // ?remoteState=true asks VirtFusion to introspect libvirt + (when
// available) qemu-guest-agent on the guest, returning live CPU/memory
// gauges, disk I/O counters, and per-mount filesystem usage under
// remoteState.{cpu,memory,disk,agent.fsinfo}. This is heavier than
// the bare /servers/{id} call (libvirt round-trip on the hypervisor)
// — acceptable on the page-load path at our scale; revisit caching
// if hypervisor load becomes a concern.
$data = $ctx['request']->get($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '?remoteState=true');
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data); Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
if ($ctx['request']->getRequestInfo('http_code') == '200') { if ($ctx['request']->getRequestInfo('http_code') != '200') {
return json_decode($data); return false;
} }
return false; $serverObj = json_decode($data);
// Merge billing-period traffic onto the server object. The
// /servers/{id} response exposes only the period WINDOW
// (settings.resources.traffic = limit GB; traffic.public.currentPeriod
// = start/end/limit) — the actual byte counter for the period lives
// on the dedicated /servers/{id}/traffic endpoint at
// data.monthly[0].total. We surface it as ->data->trafficUsedBytes
// so ServerResource (and any future consumer) has one stable path
// to read from. Non-fatal: if the secondary call fails, the field
// stays absent and ServerResource falls back to its "-" sentinel.
try {
$trafficReq = $this->initCurl($ctx['cp']['token']);
$trafficResp = $trafficReq->get($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/traffic');
if ($trafficReq->getRequestInfo('http_code') == '200') {
$trafficJson = json_decode($trafficResp);
$current = $trafficJson->data->monthly[0] ?? null;
if ($current && isset($current->total) && is_numeric($current->total)) {
$serverObj->data->trafficUsedBytes = (int) $current->total;
}
}
} catch (\Exception $e) {
Log::insert(__FUNCTION__ . ':traffic', [], $e->getMessage());
}
return $serverObj;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::insert(__FUNCTION__, [], $e->getMessage()); Log::insert(__FUNCTION__, [], $e->getMessage());
@@ -328,13 +436,42 @@ class Module
return false; return false;
} }
// Capture old hostname + server object from stored state so we can sync rDNS
// after the rename. We read from the cached server_object rather than a fresh
// fetch; this is the hostname the PTR would be set to (if module-managed).
$oldHostname = null;
$serverObject = null;
if (! empty($ctx['service']->server_object)) {
$serverObject = json_decode($ctx['service']->server_object, true);
if (is_array($serverObject)) {
$oldHostname = PowerDns\PtrManager::extractHostname($serverObject);
}
}
// VirtFusion v7+ moved this endpoint from PATCH /servers/{id}/name
// to PUT /servers/{id}/modify/name (consistent with the rest of
// the /modify/* family). The old path returns 404 on v7 panels.
$ctx['request']->addOption(CURLOPT_POSTFIELDS, json_encode(['name' => $newName])); $ctx['request']->addOption(CURLOPT_POSTFIELDS, json_encode(['name' => $newName]));
$data = $ctx['request']->patch($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/name'); $data = $ctx['request']->put($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/modify/name');
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data); Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
$httpCode = $ctx['request']->getRequestInfo('http_code'); $httpCode = $ctx['request']->getRequestInfo('http_code');
// VF v7 returns 201 (Created) on rename — older versions returned
// 200/204. Accept all three so we cover the version range.
$success = $httpCode == 200 || $httpCode == 201 || $httpCode == 204;
return $httpCode == 200 || $httpCode == 204; if ($success && $serverObject !== null && PowerDns\Config::isEnabled()) {
// Sync PTRs: only records whose current content equals the old hostname
// will be rewritten; client-customized PTRs are preserved automatically.
// Non-blocking: rDNS failures log but never fail the rename.
try {
(new PowerDns\PtrManager)->syncServer($serverObject, $oldHostname, $newName);
} catch (\Throwable $e) {
Log::insert('PowerDns:renameServer', ['serviceID' => $serviceID], $e->getMessage());
}
}
return $success;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::insert(__FUNCTION__, [], $e->getMessage()); Log::insert(__FUNCTION__, [], $e->getMessage());
@@ -421,19 +558,29 @@ class Module
} }
if (count($catTemplates) <= 1) { if (count($catTemplates) <= 1) {
// Track the "Other"-category icon from VF so the singleton
// bucket below can reuse it instead of falling back to the
// generic letter placeholder.
if (($osCategory['name'] ?? '') === 'Other' && ! isset($otherIcon)) {
$otherIcon = $osCategory['icon'] ?? null;
}
$otherTemplates = array_merge($otherTemplates, $catTemplates); $otherTemplates = array_merge($otherTemplates, $catTemplates);
} else { } else {
$catName = $osCategory['name'] ?? 'Unknown'; $catName = $osCategory['name'] ?? 'Unknown';
// Use VF's category icon as-is for every category, including
// "Other" — the historic override that forced a generic icon
// was reverted; whatever the API returns (linux_logo.png in
// our setup) is the canonical source.
$categories[] = [ $categories[] = [
'name' => $esc($catName), 'name' => $esc($catName),
'icon' => ($catName === 'Other') ? null : ($osCategory['icon'] ?? null), 'icon' => $osCategory['icon'] ?? null,
'templates' => $catTemplates, 'templates' => $catTemplates,
]; ];
} }
} }
if (! empty($otherTemplates)) { if (! empty($otherTemplates)) {
$categories[] = ['name' => 'Other', 'icon' => null, 'templates' => $otherTemplates]; $categories[] = ['name' => 'Other', 'icon' => $otherIcon ?? null, 'templates' => $otherTemplates];
} }
return $categories; return $categories;
@@ -545,7 +692,19 @@ class Module
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data); Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
if ($ctx['request']->getRequestInfo('http_code') == 200) { if ($ctx['request']->getRequestInfo('http_code') == 200) {
return json_decode($data, true); $result = json_decode($data, true);
if (! is_array($result)) {
return false;
}
// The VirtFusion API returns the noVNC viewer path as
// data.vnc.wss.url (e.g. "/vnc/?token=...") — a relative
// path. The browser needs the full URL, so we expose the
// VF base URL alongside the API payload. Same pattern used
// by fetchOsTemplates so the OS gallery can build full
// logo URLs.
$result['baseUrl'] = rtrim(str_replace('/api/v1', '', $ctx['cp']['url']), '/');
return $result;
} }
return false; return false;
@@ -571,13 +730,25 @@ class Module
return false; return false;
} }
$ctx['request']->addOption(CURLOPT_POSTFIELDS, json_encode(['enabled' => (bool) $enabled])); // Body param is "vnc" — NOT "enabled". The API silently no-ops
// an unknown key, which is why earlier toggle clicks appeared to
// do nothing. Confirmed against the official endpoint signature.
$ctx['request']->addOption(CURLOPT_POSTFIELDS, json_encode(['vnc' => (bool) $enabled]));
$data = $ctx['request']->post($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/vnc'); $data = $ctx['request']->post($ctx['cp']['url'] . '/servers/' . $ctx['serverId'] . '/vnc');
Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data); Log::insert(__FUNCTION__, $ctx['request']->getRequestInfo(), $data);
$httpCode = $ctx['request']->getRequestInfo('http_code'); $httpCode = $ctx['request']->getRequestInfo('http_code');
if ($httpCode == 200 || $httpCode == 204) { if ($httpCode == 200 || $httpCode == 204) {
return json_decode($data, true) ?: ['success' => true]; $result = json_decode($data, true) ?: ['success' => true];
// Mirror getVncConsole() so the JS popup-opener can build the
// full wss:// URL from data.vnc.wss.url + baseUrl. Without
// this the response only carries the relative path and the
// popup goes nowhere.
if (is_array($result)) {
$result['baseUrl'] = rtrim(str_replace('/api/v1', '', $ctx['cp']['url']), '/');
}
return $result;
} }
return false; return false;
@@ -773,6 +944,26 @@ class Module
/** /**
* Resolve a WHMCS server record into an API base URL and decrypted Bearer token. * Resolve a WHMCS server record into an API base URL and decrypted Bearer token.
* *
* OUTPUT SHAPE
* ------------
* url — full API base like "https://vf.example.com/api/v1". Append
* path components to this for every VirtFusion call.
* base_url — scheme + host only, "https://vf.example.com". Used for SSO
* redirects where we need to hit the panel UI, not the API.
* token — decrypted bearer token. Pass to initCurl() to get an
* authenticated Curl handle.
*
* $any=true is an unusual behaviour: when a WHMCS product doesn't have a
* specific server pinned (allowed if the module is the only VF module on
* the install), we fall back to any enabled VirtFusion server. This mostly
* exists for the "Test Connection" button which doesn't know which server
* to use until after a successful connection. Normal provisioning always
* passes a real server ID.
*
* The token is stored encrypted in tblservers.password and decrypted here
* via WHMCS's global decrypt() — the same encryption key used for addon
* module password fields.
*
* @param int|object $server WHMCS server ID or server object * @param int|object $server WHMCS server ID or server object
* @param bool $any When true, fall back to any available server if the given one is not found * @param bool $any When true, fall back to any available server if the given one is not found
* @return array{url: string, base_url: string, token: string}|false * @return array{url: string, base_url: string, token: string}|false
@@ -825,6 +1016,236 @@ class Module
$this->output(['success' => false, 'errors' => 'unauthenticated'], true, true, 401); $this->output(['success' => false, 'errors' => 'unauthenticated'], true, true, 401);
} }
/**
* Enforce POST as the HTTP method. Emits a 405 JSON response and exits otherwise.
*
* WHY THIS EXISTS
* ---------------
* The REST principle says mutations should be POST, and PHP's $_POST / $_GET
* separation means a mutation that reads from $_POST would fail quietly when
* called via GET. But "fail quietly" isn't what we want — an attacker probing
* endpoints via crafted <img src="?action=...&ip=...&ptr=..."> tags shouldn't
* even reach our input-validation code. This gate kills that path with a 405
* before any per-endpoint logic runs.
*
* Combined with requireSameOrigin() below, this closes the most common
* cross-site request forgery vectors (form POST, image GET) without needing
* explicit CSRF tokens threaded through every AJAX call.
*
* @return bool|void
*/
public function requirePost()
{
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
return true;
}
$this->output(['success' => false, 'errors' => 'method not allowed'], true, true, 405);
}
/**
* Verify the request's Origin/Referer belongs to this WHMCS install.
*
* THREAT MODEL
* ------------
* A logged-in WHMCS user visits a malicious page. That page makes a POST
* to our rDNS endpoint; because the session cookie is tied to our domain,
* the browser attaches it automatically. Without this check, the attacker
* could silently rewrite the user's PTRs.
*
* The defence: browsers attach an Origin header on cross-origin fetch/XHR
* and a Referer on cross-origin form POST. Those headers carry the
* attacker's origin, not ours — so we compare them against our own
* hostname and reject mismatches with a 403.
*
* This is NOT a full CSRF token scheme. It defends against the common
* cross-site-POST and cross-site-form-submit vectors but a same-site XSS
* that can read the user's DOM could still circumvent it. For that you'd
* need per-request tokens bound to the session — out of scope for the
* current module, but the helper stays here ready to be composed with
* a token check if one's added later.
*
* IMPLEMENTATION
* --------------
* 1. Collect our "known good" host set from HTTP_HOST (what the browser
* connected to) plus the SystemURL host from tblconfiguration (what
* WHMCS thinks its canonical URL is). Behind a reverse proxy these
* can differ; accepting either closes the false-positive gap.
* 2. Parse HTTP_ORIGIN and HTTP_REFERER and pull out their host:port.
* 3. Require at least one of those headers to match.
*
* Fails closed: if we can't determine our own host OR if neither Origin
* nor Referer is present, we reject. A legitimate same-origin AJAX call
* from the module's own JS always sets Origin (fetch API) or Referer
* (form submit), so the "both absent" case only happens with scripted
* non-browser clients — which are exactly who we want to filter out.
*
* @return bool|void true on success; emits 403 JSON and exits otherwise
*/
public function requireSameOrigin()
{
$expected = [];
$host = (string) ($_SERVER['HTTP_HOST'] ?? '');
if ($host !== '') {
$expected[] = strtolower($host);
}
$systemUrl = Database::getSystemUrl();
if ($systemUrl) {
$parsed = parse_url($systemUrl);
if (! empty($parsed['host'])) {
$expected[] = strtolower($parsed['host'] . (isset($parsed['port']) ? ':' . $parsed['port'] : ''));
$expected[] = strtolower($parsed['host']);
}
}
$expected = array_unique(array_filter($expected));
if (empty($expected)) {
// Can't determine our own host; fail closed rather than silently allow.
$this->output(['success' => false, 'errors' => 'cross-origin check failed'], true, true, 403);
}
$origin = (string) ($_SERVER['HTTP_ORIGIN'] ?? '');
$referer = (string) ($_SERVER['HTTP_REFERER'] ?? '');
$candidates = [];
foreach ([$origin, $referer] as $raw) {
if ($raw === '') {
continue;
}
$parsed = parse_url($raw);
if (! empty($parsed['host'])) {
$candidates[] = strtolower($parsed['host'] . (isset($parsed['port']) ? ':' . $parsed['port'] : ''));
$candidates[] = strtolower($parsed['host']);
}
}
if (empty($candidates)) {
$this->output(['success' => false, 'errors' => 'cross-origin check failed (missing origin)'], true, true, 403);
}
foreach ($candidates as $c) {
if (in_array($c, $expected, true)) {
return true;
}
}
Log::insert('csrf:origin-mismatch', ['origin' => $origin, 'referer' => $referer, 'expected' => $expected], 'cross-origin request rejected');
$this->output(['success' => false, 'errors' => 'cross-origin check failed'], true, true, 403);
}
/**
* Per-(serviceID, action) rate limit. Emits 429 if hit; otherwise stamps
* a token in the cache that expires after $windowSec.
*
* Defence-in-depth against:
* - runaway client scripts hammering destructive actions on the
* customer's own service (rebuild, power-off, password reset)
* - cumulative VirtFusion API load from a misbehaving customer
*
* Uses the existing Cache class so it inherits Redis (when available)
* or atomic filesystem fallback. Keys are namespaced under "rl:" to
* avoid collisions with other Cache users.
*
* @param string $key Action/scope identifier (e.g. "power:1234")
* @param int $windowSec Minimum seconds between calls
* @return bool|void true if not rate-limited; emits 429 + exits otherwise
*/
public function requireRateLimit(string $key, int $windowSec)
{
$cacheKey = 'rl:' . $key;
if (Cache::get($cacheKey) !== null) {
$this->output(
['success' => false, 'errors' => 'Too many requests. Please wait a moment and try again.'],
true,
true,
429,
);
}
Cache::set($cacheKey, 1, $windowSec);
return true;
}
/**
* Ensure the WHMCS service is in a status where client-initiated writes make sense.
*
* tblhosting.domainstatus can be: Active, Suspended, Terminated, Pending,
* Cancelled, Fraud. Not every action makes sense in every status:
* - Reads (rdnsList, serverData) usually allow Active + Suspended so a
* suspended user can still see their current config.
* - Writes (rdnsUpdate, power, etc.) typically require Active only —
* mutating a cancelled service's rDNS has no sensible business meaning.
*
* Pass the allowed set explicitly per endpoint rather than trying to encode
* a global policy here. Some endpoints (admin reconcile) don't call this at
* all because the admin is allowed to touch any service.
*
* Fails with 404 if the service doesn't exist, 400 otherwise — keeping the
* two conditions distinct in the response code helps client-side error
* handling (a 404 usually means "link is stale", a 400 means "not right now").
*
* @param int $serviceID WHMCS service ID
* @param string[] $allowedStatuses Service statuses that permit the operation
* @return bool|void true on success; emits 400/404 JSON and exits otherwise
*/
public function requireServiceStatus(int $serviceID, array $allowedStatuses = ['Active'])
{
$row = Database::getWhmcsService($serviceID);
if (! $row) {
$this->output(['success' => false, 'errors' => 'service not found'], true, true, 404);
}
if (! in_array((string) $row->domainstatus, $allowedStatuses, true)) {
$this->output(
['success' => false, 'errors' => 'service status "' . (string) $row->domainstatus . '" does not permit this action'],
true,
true,
400,
);
}
return true;
}
/**
* Ensure the WHMCS service has a corresponding VirtFusion server linked.
*
* A service can exist in tblhosting (Active, paid for, etc.) without ever
* having been successfully provisioned in VirtFusion — typically when the
* order was accepted but the CreateAccount call failed or never ran. In
* that state, mod_virtfusion_direct has either no row for the service or
* a row with NULL server_id.
*
* Without this guard, every downstream feature method (getTrafficStats,
* getServerBackups, etc.) silently returns false because resolveServiceContext
* can't build a valid request, and client.php translates that into a generic
* "Unable to retrieve X" 500 — which gives the client a broken UI with no
* indication of the real problem. With the guard, the client gets a single
* clear 409 explaining the state, and our log shows the unprovisioned
* lookup attempt instead of N misleading "Unable to..." entries.
*
* Returns 409 Conflict because the request is well-formed but the server's
* current state (no provisioned VF server) prevents fulfilment — the same
* semantics WHMCS itself uses when a service is in the wrong status.
*
* @param int $serviceID WHMCS service ID
* @return bool|void true on success; emits 409 JSON and exits otherwise
*/
public function requireProvisionedService(int $serviceID)
{
$row = Database::getSystemService($serviceID);
if (! $row || empty($row->server_id)) {
$this->output(
['success' => false, 'errors' => 'Server has not been provisioned yet. Please contact support if this is unexpected.'],
true,
true,
409,
);
}
return true;
}
/** /**
* Create a pre-configured Curl instance with JSON Accept/Content-Type headers * Create a pre-configured Curl instance with JSON Accept/Content-Type headers
* and a Bearer token for authenticating against the VirtFusion API. * and a Bearer token for authenticating against the VirtFusion API.
@@ -984,4 +1405,175 @@ class Module
{ {
return json_decode($response, true, 512, JSON_THROW_ON_ERROR); return json_decode($response, true, 512, JSON_THROW_ON_ERROR);
} }
// =========================================================================
// Catalogue helpers — used by StockControl to size the WHMCS inventory from
// live VirtFusion data. Pre-order code path: CP is resolved via "any
// available server" since no service context exists yet.
// =========================================================================
/**
* Resolve the catalogue-level CP (any available VirtFusion server) and memoise.
*
* Stock calculations run from a cron loop or product-detail page view — there's
* no WHMCS service yet, so we can't dereference a specific panel via
* resolveServiceContext. "Any enabled server" is the correct fallback for read-only
* catalogue operations (package + hypervisor-group endpoints return the same data
* from every VirtFusion node on the same cluster).
*
* @return array{url: string, base_url: string, token: string}|false
*/
private function getCatalogueCp()
{
if ($this->catalogueCp === null) {
$this->catalogueCp = $this->getCP(false, true);
}
return $this->catalogueCp;
}
/**
* Fetch a VirtFusion package by ID — the authoritative source for "how much RAM,
* CPU, and disk does one VPS of this product cost?".
*
* Return values distinguish confirmed-missing from transient failure:
* array — package data (fields: memory, cpuCores, primaryStorage, primaryStorageProfile, enabled, …)
* false — HTTP 404: package has been deleted in VirtFusion. Callers treat as OOS.
* null — Transient failure (no CP, network error, 5xx, malformed body). Callers must
* NOT overwrite WHMCS qty on a null — that would zero out inventory during a blip.
*
* Success responses are cached 10 min (key "pkg:{id}") since package definitions
* rarely change; 404 responses get a short 60 s cache so an admin re-creating a
* deleted package doesn't have to wait ten minutes for stock to pick it up again.
*
* @param int $packageId VirtFusion package ID (from tblproducts.configoption2).
* @return array|false|null
*/
public function fetchPackage($packageId)
{
try {
$packageId = (int) $packageId;
if ($packageId <= 0) {
return null;
}
$cacheKey = 'pkg:' . $packageId;
$cached = Cache::get($cacheKey);
if ($cached !== null) {
// Sentinel marker for a previously-confirmed 404.
if (is_array($cached) && ! empty($cached['__notFound'])) {
return false;
}
return $cached;
}
$cp = $this->getCatalogueCp();
if (! $cp) {
return null;
}
$request = $this->initCurl($cp['token']);
$data = $request->get($cp['url'] . '/packages/' . $packageId);
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
$httpCode = (int) $request->getRequestInfo('http_code');
if ($httpCode === 200) {
$decoded = json_decode($data, true);
if (is_array($decoded)) {
$package = $decoded['data'] ?? $decoded;
if (is_array($package)) {
Cache::set($cacheKey, $package, 600);
return $package;
}
}
return null;
}
if ($httpCode === 404) {
Cache::set($cacheKey, ['__notFound' => true], 60);
return false;
}
return null;
} catch (\Throwable $e) {
Log::insert(__FUNCTION__, [], $e->getMessage());
return null;
}
}
/**
* Fetch free/allocated resources for every hypervisor in a group — the live picture
* of how much headroom remains to place more VPSes.
*
* Same tri-state return contract as fetchPackage():
* array — decoded response with a 'data' array of per-hypervisor resource breakdowns.
* false — HTTP 404: group has been deleted. Callers may treat as "zero capacity from this group".
* null — Transient failure. Callers must NOT overwrite WHMCS qty on a null.
*
* Cache TTL is 120 s — short enough that customers don't see stale OOS labels for
* long after capacity frees up, and long enough to amortise the upstream call across
* bursty product-page traffic. Matches the traffic-stats TTL in getTrafficStats().
*
* @param int $groupId VirtFusion hypervisor group ID.
* @return array|false|null
*/
public function fetchGroupResources($groupId)
{
try {
$groupId = (int) $groupId;
if ($groupId <= 0) {
return null;
}
$cacheKey = 'grpres:' . $groupId;
$cached = Cache::get($cacheKey);
if ($cached !== null) {
if (is_array($cached) && ! empty($cached['__notFound'])) {
return false;
}
return $cached;
}
$cp = $this->getCatalogueCp();
if (! $cp) {
return null;
}
$request = $this->initCurl($cp['token']);
$data = $request->get($cp['url'] . '/compute/hypervisors/groups/' . $groupId . '/resources');
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
$httpCode = (int) $request->getRequestInfo('http_code');
if ($httpCode === 200) {
$decoded = json_decode($data, true);
if (is_array($decoded) && isset($decoded['data']) && is_array($decoded['data'])) {
Cache::set($cacheKey, $decoded, 120);
return $decoded;
}
return null;
}
if ($httpCode === 404) {
Cache::set($cacheKey, ['__notFound' => true], 60);
return false;
}
return null;
} catch (\Throwable $e) {
Log::insert(__FUNCTION__, [], $e->getMessage());
return null;
}
}
} }

View File

@@ -5,8 +5,38 @@ namespace WHMCS\Module\Server\VirtFusionDirect;
/** /**
* Extends Module to handle the WHMCS service lifecycle for VirtFusion servers. * Extends Module to handle the WHMCS service lifecycle for VirtFusion servers.
* *
* Responsibilities include: provisioning (create, suspend, unsuspend, terminate), * WHY A SEPARATE CLASS FROM MODULE
* package changes, usage updates, client area rendering, and admin tab fields. * --------------------------------
* The WHMCS module interface (VirtFusionDirect.php) expects top-level functions
* like VirtFusionDirect_CreateAccount(). Those functions delegate into methods
* on this class so:
* 1. The top-level functions stay one-liners that are easy to audit.
* 2. All lifecycle logic lives in an object we can instantiate and unit-exercise
* without going through WHMCS's dispatch machinery.
* 3. The shared behaviour with Module (API calls, auth, validation) comes for
* free via inheritance — no copy-pasted curl setup or error handling.
*
* ERROR MESSAGE CONVENTION
* ------------------------
* Every public method either returns the literal string 'success' or an error
* string that WHMCS will render to the admin in the service activity log. Do NOT
* return arrays, objects, or booleans — WHMCS treats anything other than
* 'success' as an error and displays it verbatim.
*
* EXCEPTION HANDLING
* ------------------
* Every public method is wrapped in try/catch. Uncaught exceptions bubbling up
* to WHMCS appear as stack traces in the admin UI and leak implementation detail,
* so we catch and convert to a human error string. Log::insert() captures the
* original exception message for diagnostics in the module log.
*
* PowerDNS INTEGRATION
* --------------------
* createAccount(), terminateAccount(), and (via parent Module) renameServer()
* call into PowerDns\PtrManager to sync rDNS. Those calls are wrapped in their
* OWN try/catch so DNS failures never bubble up to WHMCS — provisioning must
* succeed even if PowerDNS is temporarily unreachable. See cleanupPowerDnsForService()
* for the termination-time cleanup helper.
*/ */
class ModuleFunctions extends Module class ModuleFunctions extends Module
{ {
@@ -163,6 +193,33 @@ class ModuleFunctions extends Module
Database::systemOnServerCreate($params['serviceid'], $data); Database::systemOnServerCreate($params['serviceid'], $data);
$this->updateWhmcsServiceParamsOnServerObject($params['serviceid'], $data); $this->updateWhmcsServiceParamsOnServerObject($params['serviceid'], $data);
// Initialize reverse DNS for the newly-assigned IPs.
//
// Ordering: after Database::systemOnServerCreate() AND
// updateWhmcsServiceParamsOnServerObject() so mod_virtfusion_direct
// has the stored server_object (admin reconcile later reads it) and
// tblhosting has the primary IP (for cross-check on client edits).
//
// But BEFORE ConfigureService::initServerBuild() so rDNS is in place
// when the VPS first boots — mail servers and other services that
// check FCrDNS during early-boot see correct PTRs.
//
// Non-blocking: rDNS failures are logged but never fail provisioning.
// A broken PowerDNS or missing zone must not prevent a customer
// from getting the VPS they paid for.
try {
if (PowerDns\Config::isEnabled()) {
// syncServer with $oldHostname=null means "create mode" — see
// PtrManager::syncServer() docblock for the semantics.
$hostname = PowerDns\PtrManager::extractHostname($data);
if ($hostname !== null) {
(new PowerDns\PtrManager)->syncServer($data, null, $hostname);
}
}
} catch (\Throwable $e) {
Log::insert('PowerDns:createAccount', ['serviceid' => $params['serviceid']], $e->getMessage());
}
// If the server is created successfully, we can initialize the server build. // If the server is created successfully, we can initialize the server build.
$cs = new ConfigureService; $cs = new ConfigureService;
$vfUserId = isset($data->data->owner->id) ? (int) $data->data->owner->id : null; $vfUserId = isset($data->data->owner->id) ? (int) $data->data->owner->id : null;
@@ -304,6 +361,7 @@ class ModuleFunctions extends Module
switch ($request->getRequestInfo('http_code')) { switch ($request->getRequestInfo('http_code')) {
case 204: case 204:
$this->cleanupPowerDnsForService($service);
Database::deleteSystemService($params['serviceid']); Database::deleteSystemService($params['serviceid']);
$this->updateWhmcsServiceParamsOnDestroy($params['serviceid']); $this->updateWhmcsServiceParamsOnDestroy($params['serviceid']);
@@ -312,6 +370,7 @@ class ModuleFunctions extends Module
case 404: case 404:
if (isset($data->msg)) { if (isset($data->msg)) {
if ($data->msg == 'server not found') { if ($data->msg == 'server not found') {
$this->cleanupPowerDnsForService($service);
Database::deleteSystemService($params['serviceid']); Database::deleteSystemService($params['serviceid']);
return 'success'; return 'success';
@@ -335,6 +394,33 @@ class ModuleFunctions extends Module
} }
} }
/**
* Delete any PTR records owned by this service before the local record is erased.
* The stored server_object is the last source of the IP list; once deleted from
* the module table we'd have no way to find them again. Non-fatal — DNS failures
* never block termination.
*
* @param object|null $service Row from mod_virtfusion_direct (has server_object JSON)
*/
protected function cleanupPowerDnsForService($service): void
{
try {
if (! PowerDns\Config::isEnabled()) {
return;
}
if (! $service || empty($service->server_object)) {
return;
}
$decoded = json_decode($service->server_object, true);
if (! is_array($decoded)) {
return;
}
(new PowerDns\PtrManager)->deleteForServer($decoded);
} catch (\Throwable $e) {
Log::insert('PowerDns:terminate', ['service' => $service->service_id ?? null], $e->getMessage());
}
}
/** /**
* Suspend a VirtFusion server, queuing the action if another operation is in progress. * Suspend a VirtFusion server, queuing the action if another operation is in progress.
* *
@@ -552,6 +638,9 @@ class ModuleFunctions extends Module
if ($params['status'] != 'Terminated') { if ($params['status'] != 'Terminated') {
$fields['Options'] = AdminHTML::options($systemUrl, $params['serviceid']); $fields['Options'] = AdminHTML::options($systemUrl, $params['serviceid']);
if (PowerDns\Config::isEnabled()) {
$fields['Reverse DNS'] = AdminHTML::rdnsSection($systemUrl, $params['serviceid']);
}
} }
return $fields; return $fields;
@@ -659,6 +748,7 @@ class ModuleFunctions extends Module
'serviceStatus' => $params['status'], 'serviceStatus' => $params['status'],
'serverHostname' => $serverHostname, 'serverHostname' => $serverHostname,
'selfServiceMode' => (int) ($params['configoption4'] ?? 0), 'selfServiceMode' => (int) ($params['configoption4'] ?? 0),
'rdnsEnabled' => PowerDns\Config::isEnabled(),
], ],
]; ];
} catch (\Throwable $e) { } catch (\Throwable $e) {

View File

@@ -0,0 +1,341 @@
<?php
namespace WHMCS\Module\Server\VirtFusionDirect\PowerDns;
use WHMCS\Module\Server\VirtFusionDirect\Cache;
use WHMCS\Module\Server\VirtFusionDirect\Curl;
use WHMCS\Module\Server\VirtFusionDirect\Log;
/**
* Thin HTTP wrapper around the PowerDNS Authoritative HTTP API.
*
* WHY A SEPARATE CLIENT INSTEAD OF REUSING MODULE::INITCURL()
* -----------------------------------------------------------
* Module::initCurl() is hardcoded to Bearer auth for VirtFusion. PowerDNS uses
* X-API-Key, and mixing the two authorization styles inside one factory method
* would either require a new flag (leaky abstraction) or accidental leakage of
* the VirtFusion token into a PowerDNS request. A dedicated wrapper keeps the
* two credential flows completely isolated — a bug in PowerDNS handling can
* never leak a VirtFusion token, and vice versa.
*
* LOGGING RULES
* -------------
* We NEVER pass the API key or any header containing it to Log::insert().
* PATCH/NOTIFY calls log the zone+operation+HTTP code, successes log minimally,
* errors include up to 500 bytes of response body (PowerDNS error responses are
* small JSON fragments, not customer data). The Curl class doesn't capture
* request headers by default (CURLOPT_HEADER is off), so even the internal
* request_header field doesn't contain the API key.
*
* CACHING
* -------
* listZones() caches the zone list via the module's Cache class (Redis/filesystem)
* for Config::cacheTtl() seconds. Zone lists rarely change — the TTL balances
* "pick up a newly-created zone soon" against "don't hammer PowerDNS for every
* listZones call across unrelated lifecycle events".
*
* getZone() and patchRRset() are NOT cached here; per-request memoisation of
* getZone results lives in PtrManager::getZoneCached so it can invalidate on
* write from within the same request.
*
* SINGLE-USE CURL INSTANCES
* -------------------------
* newCurl() returns a fresh Curl for every HTTP call. That's how the existing
* module's Curl class is designed — reusing a handle across requests produces
* undefined behaviour because options from the first call bleed into the second.
* It's cheap (curl_init is microseconds).
*/
class Client
{
/** @var string */
private $endpoint;
/** @var string */
private $apiKey;
/** @var string */
private $serverId;
/**
* @param array<string,mixed>|null $config Optional pre-resolved config; defaults to PowerDns\Config::get()
*/
public function __construct(?array $config = null)
{
$config = $config ?? Config::get();
$this->endpoint = rtrim((string) ($config['endpoint'] ?? ''), '/');
$this->apiKey = (string) ($config['apiKey'] ?? '');
$this->serverId = (string) ($config['serverId'] ?? 'localhost');
}
/** Base URL for the configured PowerDNS server (no trailing slash). */
private function base(): string
{
return $this->endpoint . '/api/v1/servers/' . rawurlencode($this->serverId);
}
/**
* Encode a zone name to its PowerDNS URL-safe id form.
*
* PowerDNS's API uses a custom URL encoding for zone names that have characters
* like "/" which would collide with path semantics. Instead of using %-encoding
* (which many HTTP frameworks would parse back out at routing time), PowerDNS
* uses "=HH" where HH is the hex code — so "/" becomes "=2F".
*
* This only matters for RFC 2317 classless-delegation zone names like
* "64/64.113.0.203.in-addr.arpa." whose zone id in the API is
* "64=2F64.113.0.203.in-addr.arpa.". Standard zones pass through unchanged
* because they contain no "/" characters.
*
* Using rawurlencode() here would produce "%2F" which PowerDNS does NOT accept.
* That's why this is a plain str_replace.
*/
private function zoneIdEncode(string $zoneName): string
{
return str_replace('/', '=2F', rtrim($zoneName, '.') . '.');
}
/** Fresh Curl instance with PowerDNS auth + JSON headers. */
private function newCurl(): Curl
{
$curl = new Curl;
$curl->addOption(CURLOPT_HTTPHEADER, [
'Accept: application/json',
'Content-Type: application/json; charset=utf-8',
'X-API-Key: ' . $this->apiKey,
]);
return $curl;
}
/**
* Healthcheck. Returns [ok: bool, http: int, error: ?string].
* Used by the addon's Test Connection button and by VirtFusionDirect_TestConnection().
*
* @return array{ok: bool, http: int, error: ?string}
*/
public function ping(): array
{
try {
$curl = $this->newCurl();
$body = $curl->get($this->base());
$http = (int) $curl->getRequestInfo('http_code');
if ($http === 200) {
return ['ok' => true, 'http' => 200, 'error' => null];
}
if ($http === 0) {
$err = (string) ($curl->getRequestInfo('curl_error') ?: 'connection failed');
return ['ok' => false, 'http' => 0, 'error' => $err];
}
if ($http === 401 || $http === 403) {
// Three distinct causes all produce 401/403 here:
// (a) Actual wrong API key — the #1 obvious cause.
// (b) `api-allow-from` in PowerDNS config excludes the WHMCS
// host's IP. PowerDNS rejects pre-auth in some configs,
// producing 401/403 even with a valid key.
// (c) Invisible whitespace in the stored key (fixed in Config
// via trim(), but a pre-upgrade install might still have
// a cached request dating from before the fix).
// Listing all three gives the operator a concrete checklist.
return [
'ok' => false,
'http' => $http,
'error' => 'HTTP ' . $http . ' — PowerDNS rejected authentication. Check: ' .
'(1) the X-API-Key matches the `api-key=` in PowerDNS config, ' .
'(2) `api-allow-from=` includes this WHMCS host\'s IP, and ' .
'(3) the key has no trailing whitespace/newlines (re-paste it if unsure).',
];
}
if ($http === 404) {
// The endpoint reached PowerDNS (no 0/connection-refused) but the
// server ID path segment isn't known. By far the most common cause
// is an addon misconfiguration where someone entered the nameserver
// FQDN instead of the literal string "localhost" into the Server ID
// field. Surface that hypothesis directly — it's the single highest-
// probability fix and turns a mystery into an actionable error.
return [
'ok' => false,
'http' => 404,
'error' => 'HTTP 404 — PowerDNS does not recognise server id "' . $this->serverId .
'". This field should almost always be the literal string "localhost" ' .
'(the PowerDNS API server identifier, NOT your nameserver hostname).',
];
}
return ['ok' => false, 'http' => $http, 'error' => 'unexpected HTTP ' . $http . ': ' . substr((string) $body, 0, 200)];
} catch (\Throwable $e) {
Log::insert('PowerDns:ping', [], $e->getMessage());
return ['ok' => false, 'http' => 0, 'error' => $e->getMessage()];
}
}
/**
* List every zone on the configured PowerDNS server.
*
* Result is cached for the configured cacheTtl. Used as the primary zone-discovery
* strategy: PtrManager finds the containing zone for a PTR name by longest-suffix
* matching against this list rather than probing individual zones.
*
* @return string[] Zone names with trailing dot
*/
public function listZones(): array
{
$ttl = Config::cacheTtl();
$cacheKey = 'pdns:zones:' . md5($this->endpoint . '|' . $this->serverId);
$cached = Cache::get($cacheKey);
if (is_array($cached)) {
return $cached;
}
$zones = [];
try {
$curl = $this->newCurl();
$body = $curl->get($this->base() . '/zones');
$http = (int) $curl->getRequestInfo('http_code');
if ($http === 200) {
$decoded = json_decode((string) $body, true);
if (is_array($decoded)) {
foreach ($decoded as $z) {
if (! empty($z['name'])) {
$zones[] = rtrim((string) $z['name'], '.') . '.';
}
}
}
} else {
Log::insert('PowerDns:listZones', ['http' => $http], substr((string) $body, 0, 500));
}
} catch (\Throwable $e) {
Log::insert('PowerDns:listZones', [], $e->getMessage());
}
Cache::set($cacheKey, $zones, $ttl);
return $zones;
}
/** Drop any cached zone list (call after PATCHes or settings changes). */
public function forgetZoneCache(): void
{
$cacheKey = 'pdns:zones:' . md5($this->endpoint . '|' . $this->serverId);
Cache::forget($cacheKey);
}
/**
* Fetch a single zone by name. Returns decoded JSON array, or null on 404/error.
*
* @return array<string,mixed>|null
*/
public function getZone(string $zoneName): ?array
{
try {
$zoneName = rtrim($zoneName, '.') . '.';
$curl = $this->newCurl();
$body = $curl->get($this->base() . '/zones/' . $this->zoneIdEncode($zoneName));
$http = (int) $curl->getRequestInfo('http_code');
if ($http === 200) {
$decoded = json_decode((string) $body, true);
return is_array($decoded) ? $decoded : null;
}
if ($http !== 404) {
Log::insert('PowerDns:getZone', ['zone' => $zoneName, 'http' => $http], substr((string) $body, 0, 500));
}
} catch (\Throwable $e) {
Log::insert('PowerDns:getZone', ['zone' => $zoneName], $e->getMessage());
}
return null;
}
/**
* Apply an RRset change to a zone via PATCH.
*
* $rrset keys (per PowerDNS API): name, type, ttl?, changetype (REPLACE|DELETE|EXTEND), records[].
* On success PowerDNS returns 204 No Content.
*
* @return array{ok: bool, http: int, body: string}
*/
public function patchRRset(string $zoneName, array $rrset): array
{
try {
$zoneName = rtrim($zoneName, '.') . '.';
if (isset($rrset['name'])) {
$rrset['name'] = rtrim((string) $rrset['name'], '.') . '.';
}
$payload = ['rrsets' => [$rrset]];
$curl = $this->newCurl();
$curl->addOption(CURLOPT_POSTFIELDS, json_encode($payload));
$body = $curl->patch($this->base() . '/zones/' . $this->zoneIdEncode($zoneName));
$http = (int) $curl->getRequestInfo('http_code');
Log::insert(
'PowerDns:patchRRset',
[
'zone' => $zoneName,
'name' => $rrset['name'] ?? null,
'type' => $rrset['type'] ?? null,
'changetype' => $rrset['changetype'] ?? null,
],
['http' => $http, 'body' => substr((string) $body, 0, 500)],
);
if ($http === 204) {
// Fire-and-forget NOTIFY so slaves pick up the bumped SOA serial immediately.
//
// Background: PowerDNS auto-increments SOA on every API write when the zone
// has soa_edit_api=INCREASE (recommended; see README). Slaves normally learn
// about the new serial via polling at the refresh interval (often 15+ min)
// OR via a NOTIFY push from the master. Without our NOTIFY, rDNS changes
// made via this module would take effect on the authoritative master
// immediately but wouldn't propagate until the next scheduled poll.
//
// Only meaningful for Master-kind zones. For Native zones (no slaves) or
// Slave zones (reverse direction), PowerDNS returns a 422 or similar —
// notifyZone() logs that and returns ok=false, but we don't care here:
// the PATCH itself succeeded, which is what we report upward.
$this->notifyZone($zoneName);
}
return ['ok' => $http === 204, 'http' => $http, 'body' => (string) $body];
} catch (\Throwable $e) {
Log::insert('PowerDns:patchRRset', ['zone' => $zoneName], $e->getMessage());
return ['ok' => false, 'http' => 0, 'body' => $e->getMessage()];
}
}
/**
* Send a DNS NOTIFY to all slaves for this zone. Only applicable to Master-kind zones;
* PowerDNS returns 400/422 for Native/Slave kinds and that's fine — we log and continue.
*
* SOA serial bumping itself is handled by PowerDNS (soa_edit_api=INCREASE or similar
* on the zone); this call just ensures slaves learn about the new serial right away
* rather than waiting for the next scheduled refresh.
*
* @return array{ok: bool, http: int}
*/
public function notifyZone(string $zoneName): array
{
try {
$zoneName = rtrim($zoneName, '.') . '.';
$curl = $this->newCurl();
$body = $curl->put($this->base() . '/zones/' . $this->zoneIdEncode($zoneName) . '/notify');
$http = (int) $curl->getRequestInfo('http_code');
if ($http !== 200) {
Log::insert('PowerDns:notifyZone', ['zone' => $zoneName, 'http' => $http], substr((string) $body, 0, 300));
}
return ['ok' => $http === 200, 'http' => $http];
} catch (\Throwable $e) {
Log::insert('PowerDns:notifyZone', ['zone' => $zoneName], $e->getMessage());
return ['ok' => false, 'http' => 0];
}
}
}

View File

@@ -0,0 +1,212 @@
<?php
namespace WHMCS\Module\Server\VirtFusionDirect\PowerDns;
use WHMCS\Database\Capsule as DB;
use WHMCS\Module\Server\VirtFusionDirect\Log;
/**
* Loads PowerDNS addon settings from tbladdonmodules (module="virtfusiondns") and
* decrypts the API key using WHMCS's native decrypt() helper.
*
* WHY "LOOSE COUPLING" VIA TBLADDONMODULES
* ----------------------------------------
* WHMCS lets an operator activate/deactivate addon modules independently of server
* modules. If the server module required addon PHP code at load time (e.g. via
* require_once on the addon's files), deactivating the addon would fatal-error every
* checkout and service page.
*
* Instead, the server module reads raw rows from tbladdonmodules. If the addon is
* missing OR deactivated OR "enabled" is set to No, isEnabled() returns false and
* every PtrManager call site short-circuits. The server module never dereferences
* addon code directly; it just asks the DB "what are the PowerDNS settings?" and
* does nothing with them if they're absent.
*
* REQUEST-SCOPED CACHE
* --------------------
* get() caches the resolved config in a static property for the remainder of the
* PHP request. Without that, every PtrManager call would re-query tbladdonmodules
* and re-decrypt the API key — wasteful on the provisioning path where we touch
* PowerDNS 1-5 times per server. reset() is exposed for scenarios where settings
* change mid-request (the addon's _output() page after a vfdns_test click).
*
* API KEY HANDLING
* ----------------
* WHMCS stores password-type addon config fields encrypted in tbladdonmodules.value.
* We call decrypt() — the same helper the server-module uses for the VirtFusion
* bearer token — to get plaintext. If decryption fails (e.g. the WHMCS encryption
* key changed or the value was inserted manually as plaintext), we fall back to
* using the raw value. This is defensive; logs note the failure so an operator
* can diagnose.
*
* The decrypted key exists only in memory inside this process's request lifetime.
* It's passed to PowerDns\Client via the get() array and used for the X-API-Key
* header; it's never written to disk, logged, or sent anywhere except to the
* configured PowerDNS endpoint.
*/
class Config
{
/**
* Name used for this addon in modules/addons/ AND stored in tbladdonmodules.module.
* These two MUST match — WHMCS auto-lowercases the module directory name when
* writing to the DB, so "VirtFusionDns" (directory) becomes "virtfusiondns" here.
*/
public const MODULE_NAME = 'virtfusiondns';
/** @var array<string,mixed>|null Null = not loaded yet; an array = resolved settings */
private static $cached = null;
/**
* Force a reload on next get().
*
* Primary use case: the addon's _output() page calls this before re-fetching
* config so a test-connection click after saving settings sees the saved values.
* Most other code should NOT call this — the request-scoped cache is there for
* good performance reasons.
*/
public static function reset(): void
{
self::$cached = null;
}
/**
* Return the fully-resolved configuration array with decrypted apiKey.
*
* Keys: enabled(bool), endpoint(string), apiKey(string), serverId(string),
* defaultTtl(int), cacheTtl(int).
*/
public static function get(): array
{
if (self::$cached !== null) {
return self::$cached;
}
$config = [
'enabled' => false,
'endpoint' => '',
'apiKey' => '',
'serverId' => 'localhost',
'defaultTtl' => 3600,
'cacheTtl' => 60,
];
try {
// pluck('value', 'setting') returns a Collection keyed by 'setting' with
// 'value' as the values — so $rows['enabled'] reads the row where
// setting='enabled'. Efficient: one query regardless of how many
// settings exist.
$rows = DB::table('tbladdonmodules')
->where('module', self::MODULE_NAME)
->pluck('value', 'setting')
->toArray();
// WHMCS yesno fields store either "on"/"" or "1"/"0" depending on version
// and form handling. Accept all common truthy representations rather than
// relying on a single literal.
$enabledRaw = $rows['enabled'] ?? '';
$config['enabled'] = in_array(strtolower((string) $enabledRaw), ['on', 'yes', '1', 'true'], true);
// Trim trailing slash from endpoint so Client::base() can safely concatenate
// "/api/v1/..." without producing doubled slashes.
$config['endpoint'] = rtrim((string) ($rows['endpoint'] ?? ''), '/');
$config['serverId'] = (string) ($rows['serverId'] ?? 'localhost');
// Floor at 60s for defaultTtl and 10s for cacheTtl. Prevents a foot-gun
// where an operator accidentally saves "0" and causes PowerDNS to treat
// PTRs as non-cacheable (which some resolvers refuse) or this module to
// hammer PowerDNS on every call.
$config['defaultTtl'] = max(60, (int) ($rows['defaultTtl'] ?? 3600));
$config['cacheTtl'] = max(10, (int) ($rows['cacheTtl'] ?? 60));
if (! empty($rows['apiKey'])) {
$raw = (string) $rows['apiKey'];
$decrypted = '';
try {
// decrypt() is WHMCS's global helper — matches how the VirtFusion
// bearer token is handled in Module::getCP().
$decrypted = (string) decrypt($raw);
} catch (\Throwable $e) {
// Even when decrypt throws, we try the raw value so a diagnostic
// path exists. Operator sees the decrypt error in the module log
// but isn't locked out of using the addon while they investigate.
Log::insert('PowerDns:Config', 'decrypt threw', $e->getMessage());
}
// WHMCS addon module password-type fields are stored PLAINTEXT in
// tbladdonmodules.value (unlike tblservers.password which IS encrypted).
// When fed a plaintext input, WHMCS's decrypt() doesn't return empty
// or unchanged — it returns a short binary garbage string. If we used
// that as the API key we'd produce a baffling 401 from PowerDNS.
//
// Heuristic: an API key is printable ASCII by definition. If
// decrypt() produced non-printable output, we know it mangled a
// plaintext value and we should stick with raw. If decrypt()
// produced a different-but-printable string, it's a genuine
// decryption of an actually-encrypted value (unusual for addons,
// but some third-party setups do encrypt at rest).
//
// trim() handles another common foot-gun: admin UIs silently
// appending a newline on paste, which would land in the
// X-API-Key: header verbatim and also produce a 401.
$candidate = $raw;
if ($decrypted !== '' && $decrypted !== $raw && ctype_print($decrypted)) {
$candidate = $decrypted;
} elseif ($decrypted !== '' && $decrypted !== $raw) {
// Decrypt output wasn't printable — it's garbage from mangling
// a plaintext input. Log once so the diagnostic trail is clear
// but don't expose key material.
Log::insert(
'PowerDns:Config',
'decrypt produced non-printable output; using raw',
['raw_len' => strlen($raw), 'dec_len' => strlen($decrypted)],
);
}
$config['apiKey'] = trim($candidate);
}
} catch (\Throwable $e) {
// Any DB-level failure (table doesn't exist, connection dropped, etc.)
// leaves $config at its safe defaults — isEnabled() returns false,
// nothing gets written to PowerDNS, and the server module continues
// to provision as if the addon weren't installed.
Log::insert('PowerDns:Config', 'load failed', $e->getMessage());
}
self::$cached = $config;
return $config;
}
/** True only when the addon is activated, configured, and has both endpoint and key. */
public static function isEnabled(): bool
{
$c = self::get();
return $c['enabled'] && $c['endpoint'] !== '' && $c['apiKey'] !== '';
}
public static function endpoint(): string
{
return self::get()['endpoint'];
}
public static function apiKey(): string
{
return self::get()['apiKey'];
}
public static function serverId(): string
{
return self::get()['serverId'];
}
public static function defaultTtl(): int
{
return self::get()['defaultTtl'];
}
public static function cacheTtl(): int
{
return self::get()['cacheTtl'];
}
}

View File

@@ -0,0 +1,499 @@
<?php
namespace WHMCS\Module\Server\VirtFusionDirect\PowerDns;
/**
* Pure static helpers for IP address manipulation and PTR-name construction.
*
* DESIGN NOTES
* ------------
* Everything here is pure — no I/O, no globals, no state. That matters for two reasons:
* 1. PtrManager can compose these helpers freely without worrying about test isolation.
* 2. They are safe to call inside tight loops (e.g. iterating every zone in PowerDNS
* and testing it against a PTR name) without triggering hidden network or DB hits.
*
* Naming conventions used here:
* - "PTR name" = the fully-qualified record name the PTR lives at,
* e.g. "5.113.0.203.in-addr.arpa." (trailing dot always).
* - "zone name" = the zone the record belongs to,
* e.g. "113.0.203.in-addr.arpa." (trailing dot always).
* - "nibble" = a single hex digit representing 4 bits, used in IPv6 reverse names.
* - "classless" = an RFC 2317 sub-zone like "64/64.113.0.203.in-addr.arpa." —
* a delegation of a sub-range of a /24, covered in parseClasslessZone().
*
* All zone/PTR strings are normalised with a trailing dot because PowerDNS's canonical
* form always carries one, and mixing dotted/undotted forms makes string comparison
* unreliable (".example.com." ≠ ".example.com").
*/
class IpUtil
{
/** Strict IPv4 validation (rejects "1", "::1", and other ambiguous forms). */
public static function isIpv4(string $ip): bool
{
return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
}
/** Strict IPv6 validation (rejects IPv4-mapped, etc. — only pure v6 addresses). */
public static function isIpv6(string $ip): bool
{
return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
}
/**
* Fully-expand an IPv6 address to 32 lowercase hex characters (no colons).
* e.g. 2001:db8::1 -> "20010db8000000000000000000000001"
*
* Why: PTR names under ip6.arpa use *all* 32 nibbles (no compression, no :: shorthand),
* so we need the fully-expanded form before we can reverse the nibbles.
*
* Implementation: inet_pton normalises any valid IPv6 notation to 16 raw bytes,
* and bin2hex turns that into 32 lowercase hex chars. No manual padding/splitting
* logic means we can't get ":" vs "::" compression wrong.
*
* @return string|null 32-char hex string, or null if input isn't valid IPv6
*/
public static function expandIpv6(string $ip): ?string
{
$bin = @inet_pton($ip);
// inet_pton returns 16 bytes for v6, 4 bytes for v4. Guard on both conditions
// so a valid IPv4 like "192.0.2.1" doesn't silently pass through this v6 helper.
if ($bin === false || strlen($bin) !== 16) {
return null;
}
return bin2hex($bin);
}
/**
* Build the fully-qualified PTR name (trailing dot) for an IPv4 or IPv6 address.
*
* IPv4 example: 203.0.113.5 -> "5.113.0.203.in-addr.arpa."
* IPv6 example: 2001:db8::1 -> "1.0.0.0.[...].8.b.d.0.1.0.0.2.ip6.arpa."
*
* @return string|null PTR name with trailing dot, or null if input isn't a valid IP
*/
public static function ptrNameForIp(string $ip): ?string
{
// IPv4: reverse the four octets and suffix with in-addr.arpa.
// 203.0.113.5 -> 5.113.0.203.in-addr.arpa.
if (self::isIpv4($ip)) {
$octets = array_reverse(explode('.', $ip));
return implode('.', $octets) . '.in-addr.arpa.';
}
// IPv6: expand to 32 nibbles, reverse each nibble, suffix with ip6.arpa.
// 2001:db8::1 -> 1.0.0.0.[...].8.b.d.0.1.0.0.2.ip6.arpa.
// The nibble-level reversal (not byte-level) is important: each hex digit
// becomes its own DNS label. inet_pton/bin2hex give us the 32-char form;
// str_split with no length arg defaults to 1 so each char becomes one label.
if (self::isIpv6($ip)) {
$hex = self::expandIpv6($ip);
if ($hex === null) {
return null;
}
$nibbles = array_reverse(str_split($hex));
return implode('.', $nibbles) . '.ip6.arpa.';
}
return null;
}
/**
* Extract every IP address and IPv6 subnet from a VirtFusion server object.
*
* Walks every interface, not just interfaces[0] (ServerResource only reads the primary).
* Returns three buckets:
*
* addresses — discrete host IPs (v4 always, v6 when the API exposes per-host records
* or a /128 subnet entry). Each entry is a plain IP string.
*
* subnets — IPv6 subnet allocations (e.g. 2001:db8:0:5d::/64) where the module
* cannot auto-discover individual host addresses. These are surfaced
* so the client UI can show "here's your /64" and offer an "Add host PTR"
* path where the customer types a specific address inside the subnet.
* Each entry: ['subnet' => '2001:db8:0:5d::', 'cidr' => 64].
*
* skipped — malformed / unusable entries (non-IP, missing cidr, etc.) kept for
* logging so we can diagnose schema drift in the VirtFusion API.
*
* @param object|array $serverObject Raw VirtFusion server payload (may be wrapped in `data`)
* @return array{addresses: string[], subnets: array<int, array{subnet: string, cidr: int}>, skipped: array}
*/
public static function extractIps($serverObject): array
{
$addresses = [];
$subnets = [];
$skipped = [];
// Normalise object-or-array input. json_decode(json_encode($x), true) is the
// cheapest defensive way to turn a stdClass tree (VirtFusion's response) or
// an already-decoded array (stored server_object blob) into a uniform array.
if (is_object($serverObject)) {
$serverObject = json_decode(json_encode($serverObject), true);
}
if (! is_array($serverObject)) {
return ['addresses' => [], 'subnets' => [], 'skipped' => []];
}
// VirtFusion wraps the payload in a "data" key on GET responses but the stored
// server_object blob is sometimes already unwrapped. Accept both shapes.
$data = $serverObject['data'] ?? $serverObject;
$interfaces = $data['network']['interfaces'] ?? [];
if (! is_array($interfaces)) {
return ['addresses' => [], 'subnets' => [], 'skipped' => []];
}
// Walk every interface (not just interfaces[0]). ServerResource only reads [0]
// because it's building display data for the "primary" IP; rDNS needs PTRs
// for every IP no matter which interface it lives on.
foreach ($interfaces as $iface) {
foreach (($iface['ipv4'] ?? []) as $v4) {
// Accept both "address" and "ip" field names — VirtFusion's schema
// has evolved and we want the module to survive minor shape changes.
$candidate = $v4['address'] ?? ($v4['ip'] ?? null);
if ($candidate && self::isIpv4($candidate)) {
// Use the IP as an array key for free de-duplication. If the same
// IP appears on two interfaces (unusual but possible), we write
// one PTR not two.
$addresses[$candidate] = true;
}
}
foreach (($iface['ipv6'] ?? []) as $v6) {
// Preferred shape: a discrete host address (the normal v6 pattern).
$candidate = $v6['address'] ?? ($v6['ip'] ?? null);
if ($candidate && self::isIpv6($candidate)) {
$addresses[$candidate] = true;
continue;
}
// Subnet-with-cidr shape. VirtFusion's common v6 allocation model is
// to route a whole /64 to the VPS and let the OS auto-assign specific
// host addresses. The module can't know which host the customer
// actually uses, so we surface the subnet as a first-class entry and
// let the client UI offer an "Add host PTR" path with containment
// ownership verification.
$subnet = $v6['subnet'] ?? null;
$cidr = isset($v6['cidr']) ? (int) $v6['cidr'] : null;
if ($subnet && self::isIpv6($subnet) && $cidr !== null) {
if ($cidr === 128) {
// Single-host "subnet" — treat as a discrete address.
$addresses[$subnet] = true;
} elseif ($cidr > 0 && $cidr < 128) {
// Genuine subnet allocation. Dedupe by (subnet, cidr) pair.
$key = $subnet . '/' . $cidr;
if (! isset($subnets[$key])) {
$subnets[$key] = ['subnet' => $subnet, 'cidr' => $cidr];
}
} else {
$skipped[] = ['subnet' => $subnet, 'cidr' => $cidr, 'reason' => 'invalid-cidr'];
}
}
}
}
return [
'addresses' => array_keys($addresses),
'subnets' => array_values($subnets),
'skipped' => $skipped,
];
}
/**
* True if $ip falls inside the subnet $prefix/$cidrBits.
*
* Used for subnet-containment ownership checks when the customer wants to set
* a PTR for a specific host address inside an IPv6 subnet allocated to their
* VPS — we can't enumerate their assigned hosts, but we CAN prove the address
* they're claiming lies within one of their subnets.
*
* Works on the binary (inet_pton) representation so v6 notation differences
* (compression, case) don't affect the comparison.
*
* ALGORITHM
* ---------
* 1. Convert both IPs to 16 raw bytes via inet_pton (or 4 for v4).
* 2. Compare the first floor(cidr/8) bytes byte-wise (full-byte prefix).
* 3. If cidr isn't a multiple of 8, mask the next byte and compare bits.
*
* Example: 2001:db8::5 vs 2001:db8::/32
* fullBytes = 32/8 = 4; first 4 bytes of both are 20:01:0d:b8 → match
* remBits = 0 → no partial byte to compare
* → true
*/
public static function ipv6InSubnet(string $ip, string $subnetPrefix, int $cidrBits): bool
{
if (! self::isIpv6($ip) || ! self::isIpv6($subnetPrefix)) {
return false;
}
if ($cidrBits < 0 || $cidrBits > 128) {
return false;
}
$ipBin = @inet_pton($ip);
$subBin = @inet_pton($subnetPrefix);
if ($ipBin === false || $subBin === false) {
return false;
}
$fullBytes = intdiv($cidrBits, 8);
$remBits = $cidrBits % 8;
// Compare whole-byte prefix with a single substr compare.
if ($fullBytes > 0 && substr($ipBin, 0, $fullBytes) !== substr($subBin, 0, $fullBytes)) {
return false;
}
// Compare the partial byte at the cidr boundary, if any.
if ($remBits > 0) {
$mask = (0xFF << (8 - $remBits)) & 0xFF;
if ((ord($ipBin[$fullBytes]) & $mask) !== (ord($subBin[$fullBytes]) & $mask)) {
return false;
}
}
return true;
}
/**
* Find the longest-suffix zone from a list of zone names that contains a given PTR name.
* Both inputs are normalised to a trailing dot before matching.
*
* @param string $ptrName Fully-qualified PTR name (with or without trailing dot)
* @param string[] $zones List of zone names from PowerDNS (with or without trailing dots)
* @return string|null Matching zone name with trailing dot, or null if no zone covers the PTR
*/
public static function findContainingZone(string $ptrName, array $zones): ?string
{
$ptrName = rtrim($ptrName, '.') . '.';
$best = null;
$bestLen = 0;
foreach ($zones as $zone) {
if (! is_string($zone) || $zone === '') {
continue;
}
if (strpos($zone, '/') !== false) {
// RFC 2317 classless zones can't be identified by plain suffix match:
// a PTR like "5.113.0.203.in-addr.arpa." does NOT end with
// ".64/64.113.0.203.in-addr.arpa." even when 5 is in range. Range
// matching lives in findZoneAndPtrName; this helper is kept for any
// caller that only deals with standard zones.
continue;
}
$z = rtrim($zone, '.') . '.';
// Prefix with "." so a zone "example.com." doesn't accidentally match
// "foo.anotherexample.com." via naive substring compare.
$suffix = '.' . $z;
if ($ptrName === $z || substr($ptrName, -strlen($suffix)) === $suffix) {
// Longest match wins. For nested delegations (e.g. both
// "0.203.in-addr.arpa." and "113.0.203.in-addr.arpa." exist),
// the more specific one is the correct authoritative zone.
$len = strlen($z);
if ($len > $bestLen) {
$best = $z;
$bestLen = $len;
}
}
}
return $best;
}
/**
* Parse an RFC 2317 classless-delegation IPv4 reverse zone name.
*
* RFC 2317 lets a /24 owner delegate sub-ranges of that /24 to separate
* authoritative servers by creating CNAMEs in the parent zone that point
* into a named sub-zone. The sub-zone's label conventionally uses "X/Y"
* where the slash carries structural meaning, not path semantics.
*
* Two "Y" conventions exist in the wild. We accept both:
*
* (a) Y is a CIDR prefix length, Y ∈ [24, 32]. Standard per the RFC.
* "64/26.113.0.203.in-addr.arpa." — /26 → 64 addresses → covers 64..127
* "0/25.1.168.192.in-addr.arpa." — /25 → 128 addresses → covers 0..127
*
* (b) Y is a block size (count of addresses), Y > 32. Non-standard but
* used by some operators because the label reads naturally:
* "64/64.113.0.203.in-addr.arpa." — size 64 → covers 64..127
*
* We disambiguate by Y's magnitude: ≤32 is a prefix length, >32 is a count.
* (Y=32 would be "a single-host delegation", valid under convention (a).)
*
* ALIGNMENT CHECK
* ---------------
* We also verify X is a multiple of the block size. Misaligned entries
* like "3/26.x.y.z" don't correspond to any real DNS delegation — a /26
* must start at a multiple of 64 (0, 64, 128, or 192). Rejecting these
* prevents silent write-into-wrong-zone if an operator mis-names a zone.
*
* @return array{parent: string, start: int, end: int}|null
* parent: parent /24 reverse zone name with trailing dot (e.g. "113.0.203.in-addr.arpa.")
* start/end: inclusive last-octet range covered by this classless zone
*/
public static function parseClasslessZone(string $zone): ?array
{
$zone = rtrim($zone, '.') . '.';
// Structural gate 1: must end in .in-addr.arpa. — classless only applies to IPv4.
if (substr($zone, -strlen('.in-addr.arpa.')) !== '.in-addr.arpa.') {
return null;
}
// Structural gate 2: must have at least 5 labels to contain both the
// classless label and a full /24 parent: "X/Y . o . o . o . in-addr . arpa . ''"
// The trailing empty label from the terminal dot bumps this to ≥ 7 in practice,
// but 5 is the minimum we need to safely slice below.
$labels = explode('.', $zone);
if (count($labels) < 5) {
return null;
}
// Structural gate 3: the first label must contain a "/". If not, this is a
// standard zone (e.g. "113.0.203.in-addr.arpa.") — let the caller handle it.
$first = $labels[0];
if (strpos($first, '/') === false) {
return null;
}
// Parse "X/Y" — reject if either side isn't a non-negative integer.
$parts = explode('/', $first, 2);
if (count($parts) !== 2 || ! ctype_digit($parts[0]) || ! ctype_digit($parts[1])) {
return null;
}
$x = (int) $parts[0];
$y = (int) $parts[1];
// X must fit in an octet; Y must be positive (0 and negative make no sense).
if ($x < 0 || $x > 255 || $y <= 0) {
return null;
}
// Map Y → block size using the dual-convention rule described in the doc-block.
if ($y <= 32) {
// CIDR prefix convention. Values <24 would cross /24 boundaries (outside
// the scope of a single-/24 delegation), >32 is impossible for IPv4.
if ($y < 24 || $y > 32) {
return null;
}
// 1 << (32 - Y) gives the block size. Y=24→256 (whole /24), Y=32→1 (host).
$size = 1 << (32 - $y);
} else {
// Block-size convention. Accept any positive Y that fits the /24 range check below.
$size = $y;
}
// Alignment: X must sit on a block boundary. For size=64, legal starts are
// 0, 64, 128, 192. Mis-alignments indicate a misconfigured zone label.
if ($x % $size !== 0) {
return null;
}
$end = $x + $size - 1;
// The range must stay within the parent /24 (last octet 0..255).
if ($end > 255) {
return null;
}
// The parent zone is everything after the first label, i.e. the /24 reverse zone.
// array_slice(labels, 1) drops "X/Y" and the implode reconstructs the trailing-dot form.
$parent = implode('.', array_slice($labels, 1));
return ['parent' => $parent, 'start' => $x, 'end' => $end];
}
/**
* Resolve an IP to its (zone, ptrName) pair in one shot, handling both standard
* reverse zones and RFC 2317 classless delegations.
*
* For a classless match, the returned ptrName includes the classless zone
* label (e.g. "100.64/64.113.0.203.in-addr.arpa.") — this is the actual DNS
* name the PTR record lives at in PowerDNS. Classless zones take precedence
* over any matching parent zone, because in a properly-delegated setup the
* parent only holds CNAMEs pointing into the classless sub-zone.
*
* @param string[] $zones Zone names from PowerDNS (trailing dots optional)
* @return array{zone: string, ptrName: string}|null
*/
public static function findZoneAndPtrName(string $ip, array $zones): ?array
{
$ptrName = self::ptrNameForIp($ip);
if ($ptrName === null) {
return null;
}
$ipv4 = self::isIpv4($ip);
// Extract the last octet up front for classless range comparison.
// Only meaningful for IPv4 since RFC 2317 is IPv4-only (IPv6 delegations
// naturally align on nibble boundaries and don't need classless tricks).
$lastOctet = null;
if ($ipv4) {
$octets = explode('.', $ip);
$lastOctet = (int) $octets[3];
}
$bestDirect = null;
$bestDirectLen = 0;
$classlessMatch = null;
// Single pass over the zone list, bucketing each candidate into the
// classless path or the direct-suffix-match path.
foreach ($zones as $zone) {
if (! is_string($zone) || $zone === '') {
continue;
}
$z = rtrim($zone, '.') . '.';
if (strpos($z, '/') !== false) {
// Classless path. Skip for IPv6 entirely.
if (! $ipv4) {
continue;
}
$parsed = self::parseClasslessZone($z);
if ($parsed === null) {
// Malformed classless zone name (misaligned, wrong TLD, etc.) — skip.
continue;
}
// The PTR still needs to suffix-match the PARENT zone; otherwise the
// classless zone lives under a different /24 and isn't relevant.
$parentSuffix = '.' . $parsed['parent'];
if (substr($ptrName, -strlen($parentSuffix)) !== $parentSuffix) {
continue;
}
// Range gate: the host octet must fall inside this classless zone's window.
if ($lastOctet < $parsed['start'] || $lastOctet > $parsed['end']) {
continue;
}
// The record name inside a classless zone prepends the full host octet
// to the classless label, e.g. PTR "100" lives at:
// "100.64/64.113.0.203.in-addr.arpa."
// (NOT "100.113.0.203.in-addr.arpa." — the classless sub-zone holds the RRset).
$classlessMatch = [
'zone' => $z,
'ptrName' => $lastOctet . '.' . $z,
];
continue;
}
// Direct suffix-match path (standard reverse zones).
$suffix = '.' . $z;
if ($ptrName === $z || substr($ptrName, -strlen($suffix)) === $suffix) {
// Longest-match wins (see findContainingZone() for rationale).
if (strlen($z) > $bestDirectLen) {
$bestDirect = ['zone' => $z, 'ptrName' => $ptrName];
$bestDirectLen = strlen($z);
}
}
}
// PRECEDENCE: classless beats direct. In a correctly-delegated RFC 2317 setup
// the parent /24 zone only contains CNAMEs pointing into the classless sub-zone —
// it does NOT hold the PTR RRset directly. Writing to the parent would create a
// record that's shadowed by the CNAME and never consulted during resolution.
return $classlessMatch ?? $bestDirect;
}
}

View File

@@ -0,0 +1,732 @@
<?php
namespace WHMCS\Module\Server\VirtFusionDirect\PowerDns;
use WHMCS\Database\Capsule as DB;
use WHMCS\Module\Server\VirtFusionDirect\Cache;
use WHMCS\Module\Server\VirtFusionDirect\Database;
use WHMCS\Module\Server\VirtFusionDirect\Log;
/**
* Orchestrates PTR lifecycle against PowerDNS for VirtFusion servers.
*
* RESPONSIBILITIES
* ----------------
* - Compute zone membership for a given IP by matching against PowerDNS's zone list
* - Verify forward DNS (A/AAAA) before writing any PTR; never write a PTR whose
* hostname doesn't already resolve to the target IP
* - Preserve client-customised PTRs during server renames (only overwrite PTRs
* whose current content equals the previous hostname)
* - Provide read-through views for client-area and admin panels with status flags
* - Support an explicit admin reconcile (optionally forceful) and an additive-only
* cron reconciliation that never overwrites existing values
*
* CACHING MODEL
* -------------
* Two tiers, both serving different purposes:
*
* $zoneListCache — the list of every zone PowerDNS knows about. Populated once
* per PtrManager instance via locate(). The underlying Client
* caches the HTTP response for Config::cacheTtl() seconds across
* requests; this instance field just memoises the lookup within
* one request so multiple IPs on the same server don't each
* call Client::listZones().
*
* $zoneCache — decoded RRset contents of individual zones, keyed by zone
* name. Populated lazily as findPtrRRset() looks up each IP's
* zone. IMPORTANT: request-scoped only — we must invalidate on
* writes (see invalidateZone) so a read-after-write within the
* same request sees fresh data. This is why deletePtr/writePtr
* call invalidateZone before returning.
*
* Neither cache is shared between PtrManager instances (new PtrManager per WHMCS
* request is cheap). The Client's HTTP-response cache IS shared across requests via
* the module's Cache class (Redis or filesystem), which is where cross-request
* amortisation happens.
*
* SHORT-CIRCUIT BEHAVIOUR
* -----------------------
* Every public method checks Config::isEnabled() and returns an empty/no-op summary
* when the addon is inactive. This means unrelated calling code (createAccount,
* terminateAccount, renameServer, the client panel endpoint, cron) can always
* invoke PtrManager without a feature flag — the gate lives here.
*
* The summary arrays deliberately include 'enabled' => bool so test harnesses and
* admin UIs can tell "we did nothing because disabled" apart from "we did nothing
* because there were no IPs".
*/
class PtrManager
{
/** @var Client */
private $client;
/** @var array<string, array<string,mixed>|null> Request-scoped zone contents cache, keyed by zone name */
private $zoneCache = [];
/** @var string[]|null Request-scoped zone-list memo (Client handles cross-request caching) */
private $zoneListCache = null;
public function __construct(?Client $client = null)
{
// Dependency-inject the Client so tests can pass a mock; default to the
// Config-driven instance so production code never has to wire this up.
$this->client = $client ?? new Client;
}
// -----------------------------------------------------------------------
// Public API
// -----------------------------------------------------------------------
/**
* Sync PTRs for every IP on the given server object.
*
* TWO MODES OF OPERATION
* ----------------------
* CREATE ($oldHostname = null) — provisioning path.
* Write $newHostname to every IP that doesn't
* already have a PTR. Pre-existing PTRs are
* preserved (shouldn't exist on a new server,
* but if they do they're likely left over from
* a previous owner of the IP and must not be
* silently overwritten).
*
* RENAME ($oldHostname given) — rename path.
* Only overwrite PTRs whose current content
* equals $oldHostname. Anything else was set
* by the client (custom rDNS like mail servers
* need to match HELO) and must be preserved.
*
* The forward-DNS check runs before every write. A PTR without a matching
* A/AAAA is FCrDNS-broken and actively harms deliverability, so we'd rather
* leave the PTR absent than set a broken one.
*
* ERROR SEMANTICS
* ---------------
* This method never throws. Every per-IP failure is caught, logged, and
* recorded in $summary['errors']. Lifecycle callers (createAccount,
* renameServer) wrap the call in their own try/catch as belt-and-braces,
* but the expectation is that DNS issues never bubble up to WHMCS as
* provisioning failures.
*
* @param object|array $serverObject VirtFusion server payload
* @return array Summary counts: written, preserved, forward_missing, no_zone, skipped_ipv6, errors, details[]
*/
public function syncServer($serverObject, ?string $oldHostname, string $newHostname): array
{
$summary = [
'enabled' => false,
'written' => 0,
'preserved' => 0,
'forward_missing' => 0,
'no_zone' => 0,
'skipped_ipv6' => 0,
'errors' => 0,
'details' => [],
];
if (! Config::isEnabled()) {
return $summary;
}
$summary['enabled'] = true;
$extracted = IpUtil::extractIps($serverObject);
// Report (not write) v6 subnet-only allocations. UI can surface "IPv6 PTR
// not configured — /64 without explicit host" as guidance.
$summary['skipped_ipv6'] = count($extracted['skipped']);
foreach ($extracted['addresses'] as $ip) {
try {
$loc = $this->locate($ip);
if ($loc === null) {
// IP isn't covered by any zone we host. Not an error — the
// operator may manage reverse DNS for this range elsewhere.
$summary['no_zone']++;
$summary['details'][] = ['ip' => $ip, 'status' => 'no-zone'];
continue;
}
$current = $this->readPtr($loc);
// Rename-mode preservation check. The "current PTR equals old
// hostname" comparison is the whole safety mechanism for protecting
// client-custom rDNS across server renames — see class docblock.
// On CREATE mode ($oldHostname === null) we skip this branch,
// which means pre-existing PTRs on a new IP get overwritten; this
// is acceptable because a fresh IP shouldn't have PTRs yet.
if ($oldHostname !== null && $current !== null) {
if (self::normalizeHost($current) !== self::normalizeHost($oldHostname)) {
$summary['preserved']++;
$summary['details'][] = ['ip' => $ip, 'status' => 'preserved', 'current' => $current];
continue;
}
}
if (! Resolver::resolvesTo($newHostname, $ip, Config::cacheTtl())) {
$summary['forward_missing']++;
$summary['details'][] = ['ip' => $ip, 'status' => 'forward-missing', 'desired' => $newHostname];
Log::insert('PowerDns:syncServer', ['ip' => $ip, 'hostname' => $newHostname], 'forward DNS mismatch; PTR skipped');
continue;
}
$result = $this->writePtr($loc, $newHostname);
if ($result['ok']) {
$summary['written']++;
$summary['details'][] = ['ip' => $ip, 'status' => 'written', 'content' => $newHostname];
} else {
$summary['errors']++;
$summary['details'][] = ['ip' => $ip, 'status' => 'error', 'http' => $result['http']];
}
} catch (\Throwable $e) {
$summary['errors']++;
Log::insert('PowerDns:syncServer', ['ip' => $ip], $e->getMessage());
}
}
return $summary;
}
/**
* Delete every PTR belonging to the given server.
*
* @return array Summary counts: deleted, no_zone, errors
*/
public function deleteForServer($serverObject): array
{
$summary = ['enabled' => false, 'deleted' => 0, 'no_zone' => 0, 'errors' => 0];
if (! Config::isEnabled()) {
return $summary;
}
$summary['enabled'] = true;
$extracted = IpUtil::extractIps($serverObject);
foreach ($extracted['addresses'] as $ip) {
try {
$loc = $this->locate($ip);
if ($loc === null) {
$summary['no_zone']++;
continue;
}
$result = $this->deletePtr($loc);
if ($result['ok']) {
$summary['deleted']++;
} else {
$summary['errors']++;
}
} catch (\Throwable $e) {
$summary['errors']++;
Log::insert('PowerDns:deleteForServer', ['ip' => $ip], $e->getMessage());
}
}
return $summary;
}
/**
* Produce a per-IP status list suitable for client-area and admin display.
*
* Each entry: [ip, ptr, ttl, zone, status]
* Status values: ok, unverified, missing, no-zone, error, disabled.
*
* @return array<int, array<string,mixed>>
*/
public function listPtrs($serverObject, ?string $expectedHostname = null): array
{
$out = [];
$extracted = IpUtil::extractIps($serverObject);
if (! Config::isEnabled()) {
foreach ($extracted['addresses'] as $ip) {
$out[] = ['ip' => $ip, 'ptr' => null, 'ttl' => null, 'zone' => null, 'status' => 'disabled'];
}
return $out;
}
// Subnet-only rows come first so the client UI can render "you have a /64,
// here's how to add a host PTR inside it" above the discrete-IP list.
// These carry no PTR content themselves — they're informational anchors
// plus the "Add custom host" entry point.
foreach ($extracted['subnets'] as $s) {
$out[] = [
'ip' => null,
'subnet' => $s['subnet'],
'cidr' => $s['cidr'],
'ptr' => null,
'ttl' => null,
'zone' => null,
'status' => 'subnet-only',
];
}
foreach ($extracted['addresses'] as $ip) {
try {
$loc = $this->locate($ip);
if ($loc === null) {
$out[] = ['ip' => $ip, 'ptr' => null, 'ttl' => null, 'zone' => null, 'status' => 'no-zone'];
continue;
}
$rrset = $this->findPtrRRset($loc);
if ($rrset === null) {
$out[] = ['ip' => $ip, 'ptr' => null, 'ttl' => null, 'zone' => $loc['zone'], 'status' => 'missing'];
continue;
}
$ptr = $rrset['content'];
$status = Resolver::resolvesTo($ptr, $ip, Config::cacheTtl()) ? 'ok' : 'unverified';
$out[] = [
'ip' => $ip,
'ptr' => $ptr,
'ttl' => $rrset['ttl'],
'zone' => $loc['zone'],
'status' => $status,
];
} catch (\Throwable $e) {
Log::insert('PowerDns:listPtrs', ['ip' => $ip], $e->getMessage());
$out[] = ['ip' => $ip, 'ptr' => null, 'ttl' => null, 'zone' => null, 'status' => 'error'];
}
}
return $out;
}
/**
* Client-initiated PTR set/delete.
*
* Differences from syncServer():
* - Only ever writes one PTR, not a whole server's worth
* - Rate-limited per IP (10s window) to stop save-button abuse
* - Forward-DNS failure is a HARD REJECT that surfaces to the user — not a
* silent skip like the automatic paths. The client wants immediate feedback
* when their A record is missing.
* - Empty content path is an explicit delete (DELETE changetype, not REPLACE-empty)
*
* IP-OWNERSHIP NOTE
* -----------------
* This method TRUSTS that the caller has already verified the client owns $ip —
* that check lives in the calling endpoint (client.php rdnsUpdate) where it has
* access to the WHMCS session. If you call setPtr() from a new code path, you
* MUST add the ownership guard upstream of it.
*
* @return array{ok: bool, reason: string, http?: int}
* reason values: disabled, invalid-ip, rate-limited, no-zone,
* forward-missing, deleted, delete-failed, written, write-failed
*/
public function setPtr(string $ip, string $content): array
{
if (! Config::isEnabled()) {
return ['ok' => false, 'reason' => 'disabled'];
}
if (! (IpUtil::isIpv4($ip) || IpUtil::isIpv6($ip))) {
return ['ok' => false, 'reason' => 'invalid-ip'];
}
// Rate limit: one successful check per IP per 10s. Uses the module's
// two-tier Cache (Redis or filesystem), so the limit spans PHP processes.
// md5 of IP as the key keeps filesystem filenames short and safe.
$rateKey = 'pdns:write-lock:' . md5($ip);
if (Cache::get($rateKey) !== null) {
return ['ok' => false, 'reason' => 'rate-limited'];
}
// Set the lock BEFORE any downstream work so a parallel request racing
// through the same IP sees the lock and gets rate-limited cleanly.
Cache::set($rateKey, 1, 10);
$loc = $this->locate($ip);
if ($loc === null) {
return ['ok' => false, 'reason' => 'no-zone'];
}
$content = trim($content);
if ($content === '') {
$result = $this->deletePtr($loc);
return ['ok' => $result['ok'], 'reason' => $result['ok'] ? 'deleted' : 'delete-failed', 'http' => $result['http']];
}
if (! Resolver::resolvesTo($content, $ip, Config::cacheTtl())) {
return ['ok' => false, 'reason' => 'forward-missing'];
}
$result = $this->writePtr($loc, $content);
return ['ok' => $result['ok'], 'reason' => $result['ok'] ? 'written' : 'write-failed', 'http' => $result['http']];
}
/**
* Admin reconciliation for a single service.
*
* The user-facing purpose: "make the PTRs match what they should be, but don't
* step on client customisations unless I explicitly ask".
*
* Uses the STORED server_object (from mod_virtfusion_direct) rather than fetching
* fresh from VirtFusion. Reasons:
* 1. Admin reconcile runs from the services tab — no live-data dependency
* 2. Cron calls this once per service; fetching fresh would mean N VirtFusion
* calls per reconcile run
* 3. The stored object is the ground truth for "what IPs/hostname did this
* service have at last sync" — if VirtFusion temporarily returns a different
* shape, we'd rather work from known-good data than retry.
*
* If the stored state is materially out of date (e.g. IPs were added in VirtFusion
* after last sync), an admin should hit "Update Server Object" first.
*
* FORCE MODE
* ----------
* $force = true is the only code path in the entire module that overwrites a
* non-matching PTR. It's reachable exclusively via the admin "Reconcile (force
* reset)" button — never from cron, never from client writes, never from
* automatic lifecycle. This asymmetry is deliberate: forceful overrides are
* the admin's explicit choice, not a silent automation.
*
* @return array Summary counts: added, reset, preserved, forward_missing, no_zone, errors
*/
public function reconcile(int $serviceId, bool $force = false): array
{
$summary = [
'enabled' => false,
'added' => 0,
'reset' => 0,
'preserved' => 0,
'forward_missing' => 0,
'no_zone' => 0,
'errors' => 0,
];
if (! Config::isEnabled()) {
return $summary;
}
$summary['enabled'] = true;
$row = Database::getSystemService($serviceId);
if (! $row || empty($row->server_object)) {
$summary['errors']++;
return $summary;
}
$serverObject = json_decode($row->server_object, true);
if (! is_array($serverObject)) {
$summary['errors']++;
return $summary;
}
$hostname = self::extractHostname($serverObject);
if ($hostname === null) {
$summary['errors']++;
return $summary;
}
$extracted = IpUtil::extractIps($serverObject);
foreach ($extracted['addresses'] as $ip) {
try {
$loc = $this->locate($ip);
if ($loc === null) {
$summary['no_zone']++;
continue;
}
$current = $this->readPtr($loc);
$verified = Resolver::resolvesTo($hostname, $ip, Config::cacheTtl());
if ($current === null) {
if (! $verified) {
$summary['forward_missing']++;
continue;
}
$result = $this->writePtr($loc, $hostname);
if ($result['ok']) {
$summary['added']++;
} else {
$summary['errors']++;
}
continue;
}
if ($force && self::normalizeHost($current) !== self::normalizeHost($hostname)) {
if (! $verified) {
$summary['forward_missing']++;
continue;
}
$result = $this->writePtr($loc, $hostname);
if ($result['ok']) {
$summary['reset']++;
} else {
$summary['errors']++;
}
continue;
}
$summary['preserved']++;
} catch (\Throwable $e) {
$summary['errors']++;
Log::insert('PowerDns:reconcile', ['ip' => $ip, 'service' => $serviceId], $e->getMessage());
}
}
return $summary;
}
/**
* Cron reconciliation across every managed service.
*
* Called from the DailyCronJob hook. Iterates every row in mod_virtfusion_direct
* and runs reconcile() on each with $force = false. That means:
*
* - IPs missing a PTR get one (if forward DNS resolves)
* - Existing PTRs are NEVER touched, even if they differ from the hostname
*
* This asymmetry is the safety property. A brief forward-DNS blip during the
* cron window shouldn't trigger mass-rewrites that corrupt client-custom
* records. Admins who need forceful re-alignment must run the per-service
* "Reconcile (force reset)" button explicitly.
*
* Failures on individual services are logged and counted but never abort the
* job — a misconfigured single zone or one VirtFusion-unreachable service
* should not block reconciliation for the rest of the fleet.
*
* @return array Aggregate summary across all services
*/
public function reconcileAll(): array
{
$summary = [
'enabled' => false,
'services' => 0,
'added' => 0,
'preserved' => 0,
'forward_missing' => 0,
'no_zone' => 0,
'errors' => 0,
];
if (! Config::isEnabled()) {
return $summary;
}
$summary['enabled'] = true;
try {
$rows = DB::table(Database::SYSTEM_TABLE)->pluck('service_id');
} catch (\Throwable $e) {
Log::insert('PowerDns:reconcileAll', [], $e->getMessage());
return $summary;
}
foreach ($rows as $serviceId) {
$summary['services']++;
try {
$r = $this->reconcile((int) $serviceId, false);
$summary['added'] += $r['added'];
$summary['preserved'] += $r['preserved'];
$summary['forward_missing'] += $r['forward_missing'];
$summary['no_zone'] += $r['no_zone'];
$summary['errors'] += $r['errors'];
} catch (\Throwable $e) {
$summary['errors']++;
Log::insert('PowerDns:reconcileAll:service', ['service' => $serviceId], $e->getMessage());
}
}
Log::insert('PowerDns:reconcileAll', [], $summary);
return $summary;
}
// -----------------------------------------------------------------------
// Internal
// -----------------------------------------------------------------------
/**
* Resolve an IP to the (zone, ptrName) pair using the cached zone list.
* Handles both standard and RFC 2317 classless zones (delegates to IpUtil).
*
* Memoised within this instance: the zone list is fetched once (via the Client,
* which itself caches across requests per Config::cacheTtl()) and reused for
* every IP of the current server. A server with 3 IPs in the same /24 therefore
* triggers ONE listZones call, not three.
*
* @return array{zone: string, ptrName: string}|null null means "no zone covers this IP"
*/
private function locate(string $ip): ?array
{
if ($this->zoneListCache === null) {
$this->zoneListCache = $this->client->listZones();
}
return IpUtil::findZoneAndPtrName($ip, $this->zoneListCache);
}
/** @return array<string,mixed>|null */
private function getZoneCached(string $zoneName): ?array
{
if (array_key_exists($zoneName, $this->zoneCache)) {
return $this->zoneCache[$zoneName];
}
$this->zoneCache[$zoneName] = $this->client->getZone($zoneName);
return $this->zoneCache[$zoneName];
}
/**
* Current PTR content for a located address, or null if absent.
*
* @param array{zone: string, ptrName: string} $loc
*/
private function readPtr(array $loc): ?string
{
$rrset = $this->findPtrRRset($loc);
return $rrset === null ? null : $rrset['content'];
}
/**
* Find a PTR RRset at the located name.
*
* @param array{zone: string, ptrName: string} $loc
* @return array{content: string, ttl: int}|null
*/
private function findPtrRRset(array $loc): ?array
{
$zone = $this->getZoneCached($loc['zone']);
if ($zone === null || empty($zone['rrsets']) || ! is_array($zone['rrsets'])) {
return null;
}
foreach ($zone['rrsets'] as $rrset) {
if (($rrset['type'] ?? '') !== 'PTR') {
continue;
}
if (self::normalizeHost($rrset['name'] ?? '') !== self::normalizeHost($loc['ptrName'])) {
continue;
}
$records = $rrset['records'] ?? [];
foreach ($records as $record) {
if (! empty($record['disabled'])) {
continue;
}
if (! empty($record['content'])) {
return [
'content' => rtrim((string) $record['content'], '.'),
'ttl' => (int) ($rrset['ttl'] ?? Config::defaultTtl()),
];
}
}
}
return null;
}
/**
* Write/replace a PTR record.
*
* Always uses REPLACE changetype rather than a create-then-update pattern —
* REPLACE is idempotent and atomic from PowerDNS's view, whereas separate
* create + update would briefly leave the record absent.
*
* Content is canonicalised to end with a trailing dot before sending (PowerDNS
* treats unqualified names as relative to the zone, which is not what we want
* for PTR content — "host.example.com" without a trailing dot would be stored
* as "host.example.com.113.0.203.in-addr.arpa.").
*
* @param array{zone: string, ptrName: string} $loc
* @return array{ok: bool, http: int}
*/
private function writePtr(array $loc, string $content): array
{
$content = rtrim(trim($content), '.') . '.';
$ttl = Config::defaultTtl();
$result = $this->client->patchRRset($loc['zone'], [
'name' => $loc['ptrName'],
'type' => 'PTR',
'ttl' => $ttl,
'changetype' => 'REPLACE',
'records' => [['content' => $content, 'disabled' => false]],
]);
$this->invalidateZone($loc['zone']);
return ['ok' => $result['ok'], 'http' => $result['http']];
}
/**
* Delete a PTR record.
*
* @param array{zone: string, ptrName: string} $loc
* @return array{ok: bool, http: int}
*/
private function deletePtr(array $loc): array
{
$result = $this->client->patchRRset($loc['zone'], [
'name' => $loc['ptrName'],
'type' => 'PTR',
'changetype' => 'DELETE',
]);
$this->invalidateZone($loc['zone']);
return ['ok' => $result['ok'], 'http' => $result['http']];
}
/**
* Drop the cached zone contents so the next read re-fetches from PowerDNS.
* Called after every successful write so read-after-write in the same request
* (e.g. listPtrs right after setPtr in a test harness) observes fresh data.
*/
private function invalidateZone(string $zoneName): void
{
unset($this->zoneCache[$zoneName]);
}
/**
* Normalise a hostname for comparison: lowercase, no trailing dot.
*
* DNS hostnames are case-insensitive and the trailing dot is syntactic, not
* semantic. PowerDNS returns content with a trailing dot ("host.example.com.");
* user input typically doesn't have one. Both forms of "FooBar.example.com."
* vs "foobar.example.com" should compare equal, which is what this produces.
*/
private static function normalizeHost(string $h): string
{
return strtolower(rtrim(trim($h), '.'));
}
/**
* Extract the server hostname from a VirtFusion server payload.
*
* Accepts either object or array shape, wrapped or unwrapped by a `data` property.
* Falls back to `name` when `hostname` is absent or "-", matching the semantics
* of the existing ServerResource::process() behavior.
*
* Public so lifecycle call sites (createAccount, renameServer) can pull the
* hostname from a response or stored JSON blob without duplicating the logic.
*
* @param object|array $serverObject
*/
public static function extractHostname($serverObject): ?string
{
if (is_object($serverObject)) {
$serverObject = json_decode(json_encode($serverObject), true);
}
if (! is_array($serverObject)) {
return null;
}
$data = $serverObject['data'] ?? $serverObject;
if (! empty($data['hostname']) && $data['hostname'] !== '-') {
return (string) $data['hostname'];
}
if (! empty($data['name']) && $data['name'] !== '-') {
return (string) $data['name'];
}
return null;
}
}

View File

@@ -0,0 +1,140 @@
<?php
namespace WHMCS\Module\Server\VirtFusionDirect\PowerDns;
use WHMCS\Module\Server\VirtFusionDirect\Cache;
use WHMCS\Module\Server\VirtFusionDirect\Log;
/**
* Public-DNS verification helper used for forward-confirmed reverse DNS (FCrDNS) checks.
*
* WHAT FCrDNS IS AND WHY IT MATTERS HERE
* --------------------------------------
* A PTR record by itself is easy to lie about — anyone who controls a reverse zone
* can say "this IP is mail.example.com". Receivers defend against that by looking
* UP the hostname the PTR claims and checking that its A/AAAA records point back
* at the IP. That "two-way agreement" is FCrDNS.
*
* For mail deliverability in particular, a PTR without matching forward DNS is
* worse than no PTR at all — some filters treat it as evidence of a compromised
* host. The module enforces FCrDNS before every PTR write: if the user asks us
* to set "mail.example.com" as the PTR for 1.2.3.4 but mail.example.com resolves
* to something other than 1.2.3.4, we refuse.
*
* USES PUBLIC DNS, NOT POWERDNS
* -----------------------------
* This calls dns_get_record(), which hits the system's configured recursive
* resolver. That's deliberate: the hostname in a PTR may live in a zone hosted
* anywhere (client's own domain, another DNS provider, etc.) — not necessarily
* in the PowerDNS instance we're managing. Using the recursive public view means
* our verification matches what mail servers and other FCrDNS checkers actually
* see downstream.
*
* CNAME FOLLOWING
* ---------------
* If the hostname is itself a CNAME, dns_get_record returns the CNAME record
* (with DNS_CNAME flag) rather than auto-resolving to the ultimate A/AAAA. We
* follow up to MAX_CNAME_DEPTH hops before giving up. The depth cap prevents
* accidental infinite loops from misconfigured zones and bounds work per check.
*
* CACHING
* -------
* Keyed by md5(hostname|ip). A bad-A-record result lives in the cache just like
* a good one, which means a client who fixes their forward DNS must wait up to
* cacheTtl seconds before a retry succeeds. Documented in the admin settings
* tooltip as the tradeoff for not hammering authoritative resolvers when a
* user mashes the Save button while debugging.
*/
class Resolver
{
private const CACHE_PREFIX = 'pdns:resolve:';
/**
* Maximum hops through a CNAME chain before we give up.
* Real-world chains are usually 0-2 hops; 5 is generous headroom without
* letting a loop run unbounded.
*/
private const MAX_CNAME_DEPTH = 5;
/**
* Does the public DNS A/AAAA of $hostname resolve to $ip?
* Follows up to 5 CNAME hops. Cached for $ttl seconds on the initial call.
*/
public static function resolvesTo(string $hostname, string $ip, int $ttl = 60): bool
{
$hostname = rtrim(trim($hostname), '.');
if ($hostname === '' || ! (IpUtil::isIpv4($ip) || IpUtil::isIpv6($ip))) {
return false;
}
$cacheKey = self::CACHE_PREFIX . md5($hostname . '|' . $ip);
$cached = Cache::get($cacheKey);
if ($cached !== null) {
return (bool) $cached;
}
$match = self::resolveInternal($hostname, $ip, 0);
Cache::set($cacheKey, $match ? 1 : 0, $ttl);
return $match;
}
private static function resolveInternal(string $hostname, string $ip, int $depth): bool
{
if ($depth > self::MAX_CNAME_DEPTH) {
return false;
}
// Request both the matching forward type AND CNAME in one query so we see
// the whole picture at each hop. If the hostname is a direct A/AAAA, we
// see that and match immediately; if it's a CNAME, we see the target and
// recurse.
$type = IpUtil::isIpv6($ip) ? DNS_AAAA | DNS_CNAME : DNS_A | DNS_CNAME;
$records = [];
try {
// @-suppress: dns_get_record emits a PHP warning on NXDOMAIN, which we'd
// rather just treat as "no match". The return value (empty array or false)
// tells us the same thing without polluting the error log.
$records = @dns_get_record($hostname, $type);
} catch (\Throwable $e) {
// Some PHP configurations throw on resolver failure instead of returning false.
// We treat those as "no match" and log once per (hostname, ip) since callers
// cache the result — we won't spam the log even for a permanently-broken name.
Log::insert('PowerDns:Resolver', ['hostname' => $hostname, 'ip' => $ip], $e->getMessage());
return false;
}
if (! is_array($records)) {
// dns_get_record returns false on resolver failure. Same semantics as above.
return false;
}
// Convert target to binary once, outside the loop. inet_pton normalises
// "2001:db8::1" and "2001:0db8:0000:0000:0000:0000:0000:0001" to the same
// bytes, so we can compare regardless of how the resolver formatted its reply.
$targetBin = @inet_pton($ip);
foreach ($records as $r) {
$t = $r['type'] ?? null;
if ($t === 'CNAME') {
// CNAME hop: recurse on the target. We don't use a visited-set to
// detect cycles — MAX_CNAME_DEPTH is a simpler, sufficient guard.
$next = $r['target'] ?? null;
if ($next && self::resolveInternal(rtrim($next, '.'), $ip, $depth + 1)) {
return true;
}
continue;
}
// A records expose the address under 'ip', AAAA records under 'ipv6'.
// Only one of these will be set per record; the other is null.
$candidate = $r['ip'] ?? ($r['ipv6'] ?? null);
if ($candidate && $targetBin !== false && @inet_pton($candidate) === $targetBin) {
return true;
}
}
return false;
}
}

View File

@@ -4,6 +4,47 @@ namespace WHMCS\Module\Server\VirtFusionDirect;
/** /**
* Transforms a VirtFusion API server response into a flat key-value array for Smarty templates and admin display. * Transforms a VirtFusion API server response into a flat key-value array for Smarty templates and admin display.
*
* WHY A FLAT ARRAY
* ----------------
* Smarty templates can traverse nested structures (`{$data.network.interfaces[0].ipv4[0].address}`)
* but that leaks the API shape into the template layer. A flat array ("hostname",
* "primaryNetwork.ipv4[]", "memoryRaw", etc.) decouples the template from the upstream
* schema: if VirtFusion renames `network.interfaces` tomorrow, only this file needs
* to change.
*
* PRIMARY-INTERFACE-ONLY DESIGN
* -----------------------------
* process() only reads interfaces[0]. That's the primary network — the one the
* client-area "Overview" card displays. Servers with multiple interfaces (common
* for dedicated IPMI networks, storage networks, etc.) still work for display
* because the primary interface holds the customer-facing IP.
*
* The reverse-DNS subsystem (PowerDns\IpUtil::extractIps) walks ALL interfaces
* explicitly because PTRs matter for every IP no matter which NIC it's on.
* If you add a feature that needs secondary-interface data for display, do NOT
* generalise this class — add a new one or a helper that doesn't disturb the
* well-tested primary-interface behaviour.
*
* UNIT CONVERSIONS
* ----------------
* VirtFusion stores:
* - traffic as bytes (usage) or GB (limits)
* - storage as GB (limits) or bytes (usage)
* - memory as MB
* WHMCS expects MB for storage/traffic in tblhosting. This class produces two
* pairs of values per resource: a human-readable string with unit suffix
* (e.g. "200 GB") AND a raw integer without the unit (for slider UIs and
* arithmetic). Keep both — removing one breaks a UI consumer somewhere.
*
* "-" SENTINELS
* -------------
* Fields that are missing or empty are rendered as "-" rather than empty strings.
* That makes the client-area card always have content (a dash is a valid visual
* placeholder) and distinguishes "missing data" from "empty string returned by
* the API". Consumers who need boolean presence checks should test against "-",
* not "" / null — and upstream (e.g. updateWhmcsServiceParamsOnServerObject)
* already does.
*/ */
class ServerResource class ServerResource
{ {
@@ -23,15 +64,23 @@ class ServerResource
if ($server['settings']['resources']['traffic'] > 0) { if ($server['settings']['resources']['traffic'] > 0) {
$traffic = $server['settings']['resources']['traffic'] . ' GB'; $traffic = $server['settings']['resources']['traffic'] . ' GB';
} else { } else {
$traffic = 'Unlimited'; // limit=0 in VirtFusion means "no cap on this period". We
// surface that as "Unmetered" rather than "Unlimited" — limits
// exist (the period still rolls over monthly, traffic is still
// counted), the customer just isn't billed for overage.
$traffic = 'Unmetered';
} }
} }
// trafficUsedBytes is merged onto the response by Module::fetchServerData()
// from the dedicated /servers/{id}/traffic endpoint. Reading it directly
// (rather than the non-existent server.usage.traffic.used path that we
// historically referenced) is what unblocks the "X GB / Unmetered" display
// for unmetered plans — there IS usage to show even when there's no cap.
$trafficUsed = '-'; $trafficUsed = '-';
if (isset($server['usage']['traffic']['used'])) { if (isset($server['trafficUsedBytes']) && is_numeric($server['trafficUsedBytes'])) {
$trafficUsed = round($server['usage']['traffic']['used'] / 1073741824, 2) . ' GB'; $bytes = (int) $server['trafficUsedBytes'];
} elseif (isset($server['settings']['resources']['traffic']) && $server['settings']['resources']['traffic'] > 0) { $trafficUsed = ($bytes > 0 ? round($bytes / 1073741824, 2) : 0) . ' GB';
$trafficUsed = '0 GB';
} }
$data = [ $data = [
@@ -53,18 +102,55 @@ class ServerResource
'ipv6Unformatted' => [], 'ipv6Unformatted' => [],
'mac' => '-', 'mac' => '-',
], ],
'networkSpeed' => [
'inbound' => isset($server['settings']['resources']['networkSpeedInbound']) ? $server['settings']['resources']['networkSpeedInbound'] . ' Mbps' : '-',
'outbound' => isset($server['settings']['resources']['networkSpeedOutbound']) ? $server['settings']['resources']['networkSpeedOutbound'] . ' Mbps' : '-',
],
'vncEnabled' => isset($server['vnc']['enabled']) ? (bool) $server['vnc']['enabled'] : false, 'vncEnabled' => isset($server['vnc']['enabled']) ? (bool) $server['vnc']['enabled'] : false,
'memoryRaw' => isset($server['settings']['resources']['memory']) ? (int) $server['settings']['resources']['memory'] : 0, 'memoryRaw' => isset($server['settings']['resources']['memory']) ? (int) $server['settings']['resources']['memory'] : 0,
'cpuRaw' => isset($server['settings']['resources']['cpuCores']) ? (int) $server['settings']['resources']['cpuCores'] : 0, 'cpuRaw' => isset($server['settings']['resources']['cpuCores']) ? (int) $server['settings']['resources']['cpuCores'] : 0,
'storageRaw' => isset($server['settings']['resources']['storage']) ? (int) $server['settings']['resources']['storage'] : 0, 'storageRaw' => isset($server['settings']['resources']['storage']) ? (int) $server['settings']['resources']['storage'] : 0,
'trafficRaw' => isset($server['settings']['resources']['traffic']) ? (int) $server['settings']['resources']['traffic'] : 0, 'trafficRaw' => isset($server['settings']['resources']['traffic']) ? (int) $server['settings']['resources']['traffic'] : 0,
'trafficUsedRaw' => isset($server['usage']['traffic']['used']) ? round($server['usage']['traffic']['used'] / 1073741824, 2) : 0, 'trafficUsedRaw' => isset($server['trafficUsedBytes']) ? round((int) $server['trafficUsedBytes'] / 1073741824, 2) : 0,
'networkSpeedInboundRaw' => isset($server['settings']['resources']['networkSpeedInbound']) ? (int) $server['settings']['resources']['networkSpeedInbound'] : 0,
'networkSpeedOutboundRaw' => isset($server['settings']['resources']['networkSpeedOutbound']) ? (int) $server['settings']['resources']['networkSpeedOutbound'] : 0, // -- Identity / catalog ---------------------------------------
// os.templateName is always present; qemuAgent.os.* only when
// qemu-guest-agent is installed and running on the guest. Both
// are surfaced; the template chooses which to emphasise.
'osName' => $server['os']['templateName'] ?? '-',
'osPretty' => $server['qemuAgent']['os']['pretty-name'] ?? null,
'osKernel' => $server['qemuAgent']['os']['kernel-release'] ?? null,
'osDistro' => $server['qemuAgent']['os']['id'] ?? null,
'osIcon' => $server['qemuAgent']['os']['img'] ?? null,
// -- Data center / hypervisor ---------------------------------
'location' => $server['hypervisor']['group']['name'] ?? '-',
'locationIcon' => $server['hypervisor']['group']['icon'] ?? null,
'hypervisorMaintenance' => (bool) ($server['hypervisor']['maintenance'] ?? false),
// -- Server lifetime ------------------------------------------
'createdAt' => $server['created'] ?? null,
'builtAt' => $server['built'] ?? null,
// -- Live state (requires ?remoteState=true on the upstream call) -
// Fields default to null when the live block is absent — happens
// when remoteState wasn't requested or the hypervisor couldn't
// reach libvirt at fetch time. Templates must isset()-guard each.
'live' => [
'state' => $server['remoteState']['state'] ?? null,
'cpu' => isset($server['remoteState']['cpu']) ? (float) $server['remoteState']['cpu'] : null,
// memory.* values are kilobytes (libvirt convention).
'memoryActualKB' => isset($server['remoteState']['memory']['actual']) ? (int) $server['remoteState']['memory']['actual'] : null,
'memoryUnusedKB' => isset($server['remoteState']['memory']['unused']) ? (int) $server['remoteState']['memory']['unused'] : null,
'memoryAvailableKB' => isset($server['remoteState']['memory']['available']) ? (int) $server['remoteState']['memory']['available'] : null,
'memoryRssKB' => isset($server['remoteState']['memory']['rss']) ? (int) $server['remoteState']['memory']['rss'] : null,
// disk.{drive}.{rd,wr,fl}.{reqs,bytes,times} — surfacing the
// primary drive (vda) cumulative byte counters. JS can derive
// throughput rates from successive samples.
'diskRdBytes' => isset($server['remoteState']['disk']['vda']['rd.bytes']) ? (int) $server['remoteState']['disk']['vda']['rd.bytes'] : null,
'diskWrBytes' => isset($server['remoteState']['disk']['vda']['wr.bytes']) ? (int) $server['remoteState']['disk']['vda']['wr.bytes'] : null,
// Filesystems: only present when qemu-guest-agent is running
// inside the VM. Each entry is normalised to {name, mountpoint,
// type, usedBytes, totalBytes}; pseudo-FS (devtmpfs, proc, sys)
// are filtered out — only real mounts the customer cares about.
'filesystems' => self::extractFilesystems($server['remoteState']['agent']['fsinfo'] ?? null),
],
]; ];
if (array_key_exists('network', $server)) { if (array_key_exists('network', $server)) {
@@ -99,4 +185,67 @@ class ServerResource
return $data; return $data;
} }
/**
* Normalise the qemu-guest-agent fsinfo array into customer-facing rows.
*
* Only "real" filesystems are returned — pseudo-FS like proc/sysfs/devtmpfs
* have no meaning in a usage context. Returned entries are sorted with the
* root mount first so the most relevant row leads in the UI.
*
* @param array|null $fsinfo remoteState.agent.fsinfo from the API
* @return array List of {name, mountpoint, type, usedBytes, totalBytes}
*/
private static function extractFilesystems($fsinfo): array
{
if (! is_array($fsinfo) || $fsinfo === []) {
return [];
}
// Filesystems we never want to show — they're kernel/runtime, not user storage.
$skipTypes = ['proc', 'sysfs', 'devtmpfs', 'devpts', 'tmpfs', 'cgroup', 'cgroup2',
'pstore', 'bpf', 'mqueue', 'debugfs', 'tracefs', 'securityfs',
'configfs', 'fusectl', 'autofs', 'hugetlbfs', 'rpc_pipefs',
'binfmt_misc', 'overlay', 'squashfs', 'ramfs', 'fuse.gvfsd-fuse',
'efivarfs', 'selinuxfs'];
$rows = [];
foreach ($fsinfo as $fs) {
if (! is_array($fs)) {
continue;
}
$type = $fs['type'] ?? '';
if (in_array($type, $skipTypes, true)) {
continue;
}
$mount = $fs['mountpoint'] ?? '';
// Skip /boot* and /run* — useful in monitoring tools but noisy on
// a customer-facing dashboard. Customers care about the root and
// any data mounts.
if ($mount === '/boot' || str_starts_with($mount, '/boot/')) {
continue;
}
if ($mount === '/run' || str_starts_with($mount, '/run/')) {
continue;
}
$rows[] = [
'name' => (string) ($fs['name'] ?? '-'),
'mountpoint' => (string) $mount,
'type' => (string) $type,
'usedBytes' => isset($fs['used-bytes']) ? (int) $fs['used-bytes'] : 0,
'totalBytes' => isset($fs['total-bytes']) ? (int) $fs['total-bytes'] : 0,
];
}
// Root mount first; everything else by mountpoint alphabetical.
usort($rows, function ($a, $b) {
if ($a['mountpoint'] === '/') {
return -1;
}
if ($b['mountpoint'] === '/') {
return 1;
}
return strcmp($a['mountpoint'], $b['mountpoint']);
});
return $rows;
}
} }

View File

@@ -0,0 +1,557 @@
<?php
namespace WHMCS\Module\Server\VirtFusionDirect;
use WHMCS\Database\Capsule as DB;
/**
* Computes accurate stock quantities for VirtFusionDirect products and writes them
* to tblproducts.qty, leveraging WHMCS's native stock-control feature (badges,
* disabled Add-to-Cart, checkout block) instead of building parallel UI.
*
* HOW THE NUMBER IS DERIVED
* -------------------------
* For every product with tblproducts.stockcontrol=1:
*
* qty = Σ groupCapacity(g, package, ipv4Req, bufferPct) for every eligible group g
*
* where groupCapacity is computed from live /compute/hypervisors/groups/{id}/resources
* data and package is the VirtFusion /packages/{id} response — the authoritative
* per-VPS resource footprint. Each hypervisor's per-metric capacity is
* min(memory, cpu, storage), summed across hypervisors in the group; IPv4 is a
* group-level pool so its cap is taken as the per-hypervisor max within the group
* (not summed) to avoid double-counting.
*
* ELIGIBLE GROUPS
* ---------------
* The default group (tblproducts.configoption1) plus every value of the Location
* configurable option, if the product exposes one. Location is detected by matching
* the configurable option name against the "hypervisorId" label from
* config/ConfigOptionMapping.php (falls back to "Location") — same convention
* ModuleFunctions::createAccount() uses to map configoptions to VirtFusion fields.
* This lets a single product span multiple regions and still get a meaningful qty.
*
* ELIGIBLE HYPERVISORS
* --------------------
* enabled=true AND commissioned=true AND prohibit=false. Everything else is skipped
* with zero contribution to the group total.
*
* FAIL-SAFE INVARIANT
* -------------------
* CRITICAL: if the computation cannot complete (missing CP, transient API failure,
* malformed response, no groups resolved), recalculateForProduct() returns null and
* the caller MUST NOT touch tblproducts.qty. The reason: a false zero during a
* transient failure would pull every product out of the storefront, causing
* lost-order incidents that take human intervention to recover. Better to keep a
* slightly-stale qty than to silently take the catalogue offline.
*
* Confirmed-missing cases (package 404 or package.enabled=false) DO return 0 —
* that's the right answer, the product genuinely cannot be provisioned.
*
* CACHING
* -------
* Packages cached 10 min (rarely change), group resources cached 120 s (change
* meaningfully minute-to-minute under load). Both handled inside Module's
* fetchPackage / fetchGroupResources helpers, keyed 'pkg:{id}' / 'grpres:{id}' so
* multiple products in a cron sweep share cached data for the same upstream call.
*/
class StockControl
{
/** Default mapping from internal VF key → WHMCS configurable-option label.
* Kept in sync with $configOptionDefaultNaming in ModuleFunctions::createAccount(). */
private const DEFAULT_OPTION_LABELS = [
'ipv4' => 'IPv4',
'packageId' => 'Package',
'hypervisorId' => 'Location',
'storage' => 'Storage',
'memory' => 'Memory',
'traffic' => 'Bandwidth',
'networkSpeedInbound' => 'Inbound Network Speed',
'networkSpeedOutbound' => 'Outbound Network Speed',
'cpuCores' => 'CPU Cores',
'networkProfile' => 'Network Type',
'storageProfile' => 'Storage Type',
];
/** @var Module Shared for its CP memoisation + initCurl/fetchPackage/fetchGroupResources helpers. */
private $module;
/** @var array<string,string>|null Resolved per-request once. */
private $optionLabelMap = null;
public function __construct(?Module $module = null)
{
// Dependency-inject for testability; default wires up a real Module so production
// callers (hooks.php, admin.php) don't have to know about the dependency.
$this->module = $module ?? new Module;
}
// -----------------------------------------------------------------------
// Public API
// -----------------------------------------------------------------------
/**
* Recalculate qty for every VirtFusionDirect product that has WHMCS stock control enabled.
*
* Called from the every-2-hour AfterCronJob safety-net hook, from the post-provision
* and post-termination event hooks in hooks.php, and from the admin stockRecalculate
* AJAX endpoint in admin.php. Returns a map of productId => resulting qty (or null
* where the product was skipped / left untouched), useful for the admin endpoint's
* JSON response and for per-event logging.
*
* @return array<int,int|null>
*/
public function recalculateAll(): array
{
$results = [];
try {
$products = DB::table('tblproducts')
->where('servertype', 'VirtFusionDirect')
->where('stockcontrol', 1)
->get();
foreach ($products as $product) {
$results[(int) $product->id] = $this->recalculateForProduct((int) $product->id);
}
} catch (\Throwable $e) {
Log::insert('StockControl:recalculateAll', [], $e->getMessage());
}
return $results;
}
/**
* Recalculate qty for a single product.
*
* Returns the new qty on success, or null on any unrecoverable failure — in which case
* tblproducts.qty is left unchanged (fail-safe invariant).
*/
public function recalculateForProduct(int $productId): ?int
{
try {
$product = DB::table('tblproducts')->where('id', $productId)->first();
if (! $product) {
return null;
}
if ($product->servertype !== 'VirtFusionDirect') {
return null;
}
if ((int) $product->stockcontrol !== 1) {
// Stock control disabled on this product — don't manage qty.
return null;
}
$qty = $this->computeQtyForProduct($product);
if ($qty === null) {
// Transient / unrecoverable — preserve existing qty.
return null;
}
DB::table('tblproducts')
->where('id', $productId)
->update(['qty' => (int) $qty]);
Log::insert(
'StockControl:recalculate',
[
'productId' => $productId,
'packageId' => (int) $product->configoption2,
'defaultGroupId' => (int) $product->configoption1,
],
['qty' => $qty],
);
return $qty;
} catch (\Throwable $e) {
Log::insert('StockControl:recalculateForProduct', ['productId' => $productId], $e->getMessage());
return null;
}
}
// -----------------------------------------------------------------------
// Computation
// -----------------------------------------------------------------------
/**
* Compute the qty integer without touching the DB.
*
* @param object $product tblproducts row.
* @return int|null Non-negative qty, or null when the computation cannot complete.
*/
private function computeQtyForProduct($product): ?int
{
$productId = (int) $product->id;
$packageId = (int) $product->configoption2;
if ($packageId <= 0) {
Log::insert(
'StockControl:compute',
['productId' => $productId],
'no packageId in configoption2 — skipped',
);
return null;
}
$package = $this->module->fetchPackage($packageId);
if ($package === null) {
// Transient — preserve qty.
return null;
}
if ($package === false) {
// Confirmed 404: package deleted in VirtFusion. Product is unfulfillable.
Log::insert(
'StockControl:compute',
['productId' => $productId, 'packageId' => $packageId],
'package 404 — qty forced to 0',
);
return 0;
}
if (empty($package['enabled'])) {
Log::insert(
'StockControl:compute',
['productId' => $productId, 'packageId' => $packageId],
'package disabled in VirtFusion — qty forced to 0',
);
return 0;
}
$groupIds = $this->resolveHypervisorGroupIds($product);
if (empty($groupIds)) {
Log::insert(
'StockControl:compute',
['productId' => $productId],
'no hypervisor groups resolved — qty untouched',
);
return null;
}
$ipv4Required = max(1, (int) ($product->configoption3 ?? 1));
$bufferPct = $this->bufferPctForProduct($product);
$total = 0;
foreach ($groupIds as $groupId) {
$resources = $this->module->fetchGroupResources($groupId);
if ($resources === null) {
// Transient failure on any group aborts the whole computation — we can't
// safely reduce qty to a partial total and risk under-reporting stock.
return null;
}
if ($resources === false) {
// Group 404 — deleted; contributes 0. Keep going so other eligible groups still count.
Log::insert(
'StockControl:compute',
['productId' => $productId, 'groupId' => $groupId],
'group 404 — contributing 0 capacity',
);
continue;
}
$total += $this->groupCapacity($resources, $package, $ipv4Required, $bufferPct);
}
return max(0, $total);
}
/**
* Sum of per-hypervisor minimums (mem/cpu/storage), capped by the group-level IPv4 pool.
*
* IPv4 CAP IS MAX-WITHIN-GROUP, NOT SUMMED
* ----------------------------------------
* network.total.ipv4.free in the API is a group-level pool visible from every hypervisor
* in the group — the same number is reported on each. Summing per-hypervisor IPv4 caps
* would overcount the pool by the hypervisor count. Taking max() within a group, then
* summing across groups, reflects the real constraint.
*/
private function groupCapacity(array $resources, array $package, int $ipv4Required, float $bufferPct): int
{
$hypervisors = $resources['data'] ?? [];
if (! is_array($hypervisors) || empty($hypervisors)) {
return 0;
}
$hypMinSum = 0;
$ipv4CapForGroup = 0;
foreach ($hypervisors as $h) {
$hyp = $h['hypervisor'] ?? [];
if (empty($hyp['enabled']) || empty($hyp['commissioned']) || ! empty($hyp['prohibit'])) {
continue;
}
$res = $h['resources'] ?? [];
if (! is_array($res)) {
continue;
}
$memCap = self::capFor($res['memory'] ?? null, (int) ($package['memory'] ?? 0), $bufferPct);
$cpuCap = self::capFor($res['cpuCores'] ?? null, (int) ($package['cpuCores'] ?? 0), $bufferPct);
$storeCap = self::capForStorage(
$res,
(int) ($package['primaryStorageProfile'] ?? 0),
(int) ($package['primaryStorage'] ?? 0),
$bufferPct,
);
$hypMinSum += min($memCap, $cpuCap, $storeCap);
$ipv4Free = (int) ($res['network']['total']['ipv4']['free'] ?? 0);
if ($ipv4Free > 0) {
$ipv4Cap = intdiv($ipv4Free, max(1, $ipv4Required));
if ($ipv4Cap > $ipv4CapForGroup) {
$ipv4CapForGroup = $ipv4Cap;
}
}
}
// If no hypervisor reported any ipv4 data (unusual but defensible), don't let
// the cap kill an otherwise-valid count — treat as "no IPv4 constraint known".
if ($ipv4CapForGroup === 0) {
foreach ($hypervisors as $h) {
if (isset($h['resources']['network']['total']['ipv4']['free'])) {
// There WAS an ipv4 value (possibly 0); the cap is genuinely 0.
return 0;
}
}
// No ipv4 data anywhere in the response → don't apply the cap.
return max(0, $hypMinSum);
}
return min($hypMinSum, $ipv4CapForGroup);
}
/**
* How many VPSes fit into a single (free, max, buffer) cell for one resource.
*
* Handles three edge cases consistent with live API behaviour:
* - need <= 0 → unlimited fit (nothing consumed for this dimension)
* - resource.max = 0 → unlimited quota; free can be negative but we don't care
* - negative/zero available after buffer → 0 (clamp; never negative qty)
*/
private static function capFor($resource, int $need, float $bufferPct): int
{
if ($need <= 0) {
return PHP_INT_MAX;
}
if (! is_array($resource)) {
return 0;
}
$max = (int) ($resource['max'] ?? 0);
$free = (int) ($resource['free'] ?? 0);
if ($max === 0) {
// Unlimited quota — buffer doesn't apply (X% of 0 is 0).
return PHP_INT_MAX;
}
$reserve = (int) ceil(((float) $max) * ($bufferPct / 100.0));
$available = $free - $reserve;
if ($available <= 0) {
return 0;
}
return intdiv($available, $need);
}
/**
* Storage variant of capFor() that respects the package's primaryStorageProfile.
*
* NOTE on naming: VirtFusion exposes two confusingly-named fields with the
* same numeric domain. `package.primaryStorageProfile` (mirrors the DB column
* `server_packages.storage_type`) is a **storage type code** — a filter,
* not an ID — and matches `otherStorage[].storageType` on each hypervisor.
* The pool's own `id` is unique per hypervisor and is never what the package
* targets. Treating $storageTypeId as `pool.id` (as this method previously
* did) returned 0 for every package whose type code didn't happen to also
* exist as a pool id, silently zeroing qty fleet-wide.
*
* Rules:
* - storageTypeId > 0 → match any enabled otherStorage[] whose storageType
* equals this code. If multiple match (e.g. several
* mountpoint pools on one hypervisor), pick the one
* that fits the most VMs.
* - storageTypeId <= 0 → fall back to localStorage. If local is disabled, 0.
*/
private static function capForStorage(array $res, int $storageTypeId, int $needGb, float $bufferPct): int
{
if ($needGb <= 0) {
return PHP_INT_MAX;
}
if ($storageTypeId > 0) {
$best = 0;
$matched = false;
foreach ($res['otherStorage'] ?? [] as $pool) {
if ((int) ($pool['storageType'] ?? 0) !== $storageTypeId) {
continue;
}
$matched = true;
if (empty($pool['enabled'])) {
continue;
}
$cap = self::capFor(
['max' => (int) ($pool['max'] ?? 0), 'free' => (int) ($pool['free'] ?? 0)],
$needGb,
$bufferPct,
);
if ($cap > $best) {
$best = $cap;
}
}
if (! $matched) {
// No pool of this storage type on this hypervisor — cannot place the VM.
return 0;
}
return $best;
}
$local = $res['localStorage'] ?? null;
if (is_array($local) && ! empty($local['enabled'])) {
return self::capFor(
['max' => (int) ($local['max'] ?? 0), 'free' => (int) ($local['free'] ?? 0)],
$needGb,
$bufferPct,
);
}
return 0;
}
/**
* The admin-tunable safety buffer (configoption7), clamped to [0, 100].
*
* Default is 10% when the field is blank or non-numeric — reserves 10% of each
* resource's max so we stop selling a product before the hypervisor is literally
* at 100%, which is where placement timing issues and fragmentation start biting.
* Admins can override per product (including down to 0) in the module settings.
*/
private function bufferPctForProduct($product): float
{
$raw = $product->configoption7 ?? '';
if ($raw === null || $raw === '') {
return 10.0;
}
$val = is_numeric($raw) ? (float) $raw : 10.0;
return max(0.0, min(100.0, $val));
}
// -----------------------------------------------------------------------
// Hypervisor-group resolution
// -----------------------------------------------------------------------
/**
* Collect every hypervisor group ID this product could be provisioned into:
* the default (configoption1) plus every numeric value of the "Location"
* configurable option (if one is attached).
*
* @return int[] Deduplicated list of group IDs, strictly positive.
*/
private function resolveHypervisorGroupIds($product): array
{
$groups = [];
$defaultGroup = (int) ($product->configoption1 ?? 0);
if ($defaultGroup > 0) {
$groups[] = $defaultGroup;
}
$locationLabel = $this->optionLabelFor('hypervisorId');
if ($locationLabel !== null && $locationLabel !== '') {
foreach ($this->fetchConfigurableOptionValues((int) $product->id, $locationLabel) as $value) {
$asInt = (int) $value;
if ($asInt > 0) {
$groups[] = $asInt;
}
}
}
return array_values(array_unique($groups));
}
/**
* Look up every sub-option value for a given configurable option name on a product.
*
* WHMCS stores option names as either "Location" or "Location|Display Override" —
* this method normalises both by comparing just the part before the pipe.
*
* @return array<int,string> Raw sub-option names (callers decide numeric parsing).
*/
private function fetchConfigurableOptionValues(int $productId, string $label): array
{
try {
$options = DB::table('tblproductconfiglinks as l')
->join('tblproductconfigoptions as o', 'o.gid', '=', 'l.gid')
->where('l.pid', $productId)
->select('o.id', 'o.optionname')
->get();
$matchedIds = [];
foreach ($options as $opt) {
$name = (string) $opt->optionname;
$pipe = strpos($name, '|');
if ($pipe !== false) {
$name = substr($name, 0, $pipe);
}
if ($name === $label) {
$matchedIds[] = (int) $opt->id;
}
}
if (empty($matchedIds)) {
return [];
}
return DB::table('tblproductconfigoptionssub')
->whereIn('configid', $matchedIds)
->pluck('optionname')
->toArray();
} catch (\Throwable $e) {
Log::insert('StockControl:fetchConfigurableOptionValues', ['productId' => $productId, 'label' => $label], $e->getMessage());
return [];
}
}
/**
* Resolve the WHMCS configurable-option label for an internal key, respecting
* config/ConfigOptionMapping.php overrides — same contract as ModuleFunctions::createAccount().
*/
private function optionLabelFor(string $key): ?string
{
if ($this->optionLabelMap === null) {
$this->optionLabelMap = self::DEFAULT_OPTION_LABELS;
try {
// Resolve the mapping file directly relative to this class — avoids
// depending on WHMCS's ROOTDIR, which isn't defined when the module
// is loaded outside a full WHMCS request (cron tooling, tests).
// __DIR__ is .../modules/servers/VirtFusionDirect/lib, so the config
// directory is one level up.
$overridePath = dirname(__DIR__) . '/config/ConfigOptionMapping.php';
if (is_file($overridePath)) {
$override = require $overridePath;
if (is_array($override)) {
$this->optionLabelMap = array_merge($this->optionLabelMap, $override);
}
}
} catch (\Throwable $e) {
// Swallow — mapping override is best-effort; defaults still work.
}
}
return $this->optionLabelMap[$key] ?? null;
}
}

View File

@@ -471,3 +471,308 @@
flex-wrap: wrap; flex-wrap: wrap;
} }
} }
/* =========================================================================
Reverse DNS panel
========================================================================= */
.vf-rdns-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
padding: 8px 0;
border-bottom: 1px solid rgba(0,0,0,.06);
}
.vf-rdns-row:last-child { border-bottom: none; }
.vf-rdns-ip {
font-family: monospace;
font-size: 13px;
min-width: 180px;
font-weight: 600;
}
.vf-rdns-edit {
display: flex;
flex: 1 1 auto;
gap: 6px;
align-items: center;
min-width: 240px;
}
.vf-rdns-input {
flex: 1 1 auto;
min-width: 180px;
max-width: 420px;
font-family: monospace;
font-size: 13px;
}
.vf-rdns-badge {
display: inline-block;
padding: 2px 8px;
border-radius: 10px;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: .02em;
line-height: 1.4;
white-space: nowrap;
}
.vf-rdns-msg {
flex-basis: 100%;
font-size: 12px;
display: none;
padding-left: 180px;
}
.vf-rdns-admin-row {
display: flex;
align-items: center;
gap: 12px;
padding: 4px 0;
font-size: 13px;
}
.vf-rdns-ip-admin {
font-family: monospace;
font-weight: 600;
min-width: 180px;
}
.vf-rdns-ptr-admin {
font-family: monospace;
color: #333;
flex: 1 1 auto;
overflow: hidden;
text-overflow: ellipsis;
}
@media (max-width: 768px) {
.vf-rdns-row { flex-direction: column; align-items: stretch; }
.vf-rdns-edit { flex-direction: column; align-items: stretch; }
.vf-rdns-msg { padding-left: 0; }
}
/* Subnet-only rows (IPv6 /64 allocations). Distinct visual treatment so
customers see "this is a subnet, not a host" without reading the badge. */
.vf-rdns-subnet-row {
background: rgba(23, 162, 184, 0.04);
border-left: 3px solid #17a2b8;
padding-left: 8px;
}
.vf-rdns-subnet-form {
flex-basis: 100%;
padding: 10px 0 0 180px;
display: flex;
flex-direction: column;
gap: 6px;
}
.vf-rdns-subnet-inputs {
display: flex;
gap: 6px;
flex-wrap: wrap;
}
.vf-rdns-subnet-actions {
display: flex;
gap: 6px;
align-items: center;
}
@media (max-width: 768px) {
.vf-rdns-subnet-form { padding-left: 0; }
.vf-rdns-subnet-inputs { flex-direction: column; }
}
/* ---------------- In-page Section Nav ---------------- */
.vf-section-nav-body {
display: flex;
flex-wrap: wrap;
gap: 6px;
align-items: center;
}
.vf-section-nav-body::before {
content: "Jump to:";
font-weight: 600;
color: #555;
margin-right: 4px;
font-size: 13px;
}
.vf-nav-link {
display: inline-block;
padding: 4px 10px;
border: 1px solid #d6d8db;
border-radius: 4px;
background: #f8f9fa;
color: #333;
text-decoration: none;
font-size: 13px;
line-height: 1.4;
transition: background-color 0.12s ease, border-color 0.12s ease, color 0.12s ease;
}
.vf-nav-link:hover,
.vf-nav-link:focus {
background: #e9ecef;
border-color: #adb5bd;
color: #000;
text-decoration: none;
outline: none;
}
@media (max-width: 576px) {
.vf-section-nav-body::before { display: block; width: 100%; margin-bottom: 4px; }
}
/* ---------------- Server Overview meta bar ---------------- */
.vf-overview-meta {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
padding: 8px 12px;
background: #f8f9fa;
border: 1px solid #e6e8eb;
border-radius: 4px;
}
.vf-meta-chip {
display: inline-block;
padding: 3px 10px;
background: #fff;
border: 1px solid #d6d8db;
border-radius: 12px;
font-size: 12px;
color: #333;
line-height: 1.5;
}
.vf-meta-chip-muted {
color: #6c757d;
font-style: italic;
background: transparent;
border: none;
padding: 3px 4px;
}
.vf-mask-ips-btn {
margin-left: auto;
font-size: 12px;
padding: 3px 10px;
}
@media (max-width: 576px) {
.vf-mask-ips-btn { margin-left: 0; width: 100%; }
}
/* ---------------- Live Stats panel ---------------- */
.vf-live-bar {
width: 100%;
height: 14px;
background: #e9ecef;
border-radius: 7px;
overflow: hidden;
position: relative;
}
.vf-live-bar-fill {
height: 100%;
background: linear-gradient(90deg, #28a745, #20c997);
transition: width 0.5s ease, background 0.3s ease;
}
.vf-live-bar-fill.bg-warning {
background: linear-gradient(90deg, #ffc107, #fd7e14);
}
.vf-live-bar-fill.bg-danger {
background: linear-gradient(90deg, #dc3545, #c82333);
}
.vf-livestats-updated {
color: #6c757d;
}
/* ---------------- Filesystem rows ---------------- */
.vf-fs-row .progress {
background-color: #e9ecef;
}
.vf-fs-row .progress-bar {
background-color: #337ab7;
transition: width 0.5s ease;
}
.vf-fs-row .progress-bar.bg-warning { background-color: #ffc107 !important; }
.vf-fs-row .progress-bar.bg-danger { background-color: #dc3545 !important; }
/* ---------------- Layout: side-by-side panel grid ---------------- */
/*
* Used to lay out compact panels (Traffic + Live Stats) side-by-side on
* wide screens. CSS Grid with auto-fit handles the case where one panel is
* display:none (e.g. Live Stats hidden when remoteState is unavailable) —
* the visible panel fills the row.
*/
.vf-panel-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 360px), 1fr));
gap: 1rem;
}
.vf-panel-grid > .panel,
.vf-panel-grid > .card {
margin-bottom: 0 !important;
height: 100%;
}
/* ---------------- Server Overview rename row ---------------- */
/*
* Was previously a single flex row that squished the Save button on
* narrower viewports. Wrap-on-overflow + min-widths keep buttons readable
* regardless of cell width.
*/
.vf-rename-row {
display: flex;
flex-wrap: wrap;
gap: 6px;
align-items: center;
}
.vf-rename-input-field {
flex: 1 1 160px;
min-width: 140px;
max-width: 240px;
}
.vf-rename-btn-randomise,
.vf-rename-btn-save {
flex: 0 0 auto;
white-space: nowrap;
min-width: 38px;
}
.vf-rename-btn-save {
min-width: 56px;
}
/* ---------------- IP cell rows (Server Overview) ---------------- */
/*
* Each IPv4/IPv6 address renders as a compact row: address span + copy
* button. Replaces the standalone Network panel; the per-address copy
* affordance moved here.
*/
.vf-ip-cell-row {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 2px;
line-height: 1.5;
}
.vf-ip-cell-row .vf-ip-address {
word-break: break-all;
}
.vf-ip-cell-row:last-child {
margin-bottom: 0;
}
/* ---------------- Sensitive-input masking ---------------- */
/*
* Companion to the JS-based IP text masking. When body.vf-mask-active is
* set, render the value of any input.vf-sensitive as discs so the actual
* characters don't leak into a screenshot. Hover/focus restores the real
* value for editing — the customer can still see what they're typing.
*
* `text-security` is widely supported under the -webkit- prefix (Chrome,
* Edge, Safari) and as the unprefixed property in modern Firefox. Falls
* through to `-webkit-text-security: disc` everywhere else; if a browser
* truly doesn't honour it the screenshot mask just isn't applied to the
* input field — the IP cells still mask, so the customer's worst case is
* an unmasked rDNS hostname (failsafe-soft, not security-critical).
*/
body.vf-mask-active input.vf-sensitive {
-webkit-text-security: disc;
text-security: disc;
font-family: text-security-disc, sans-serif;
transition: filter 0.15s ease;
}
body.vf-mask-active input.vf-sensitive:focus,
body.vf-mask-active input.vf-sensitive:hover {
-webkit-text-security: none;
text-security: none;
font-family: inherit;
}

File diff suppressed because it is too large Load Diff

View File

@@ -3,8 +3,39 @@
{if $serviceStatus eq 'Active'} {if $serviceStatus eq 'Active'}
{* Hypervisor maintenance banner — populated by vfServerData. Hidden by
default; surfaces only when hypervisor.maintenance=true so the customer
knows operations may be unavailable. *}
<div id="vf-maintenance-banner" class="alert alert-warning mb-3" style="display:none;">
<strong>Hypervisor maintenance.</strong>
Your server's hypervisor is currently in maintenance. Some operations may be temporarily unavailable.
</div>
{* VNC Console — placed at the very top so it's the first action the
customer reaches. No toggle (VirtFusion's VNC enable/disable was a
broken firewall flag), no IP/port/password panel — just the button.
Click → noVNC popup. *}
<div id="vf-vnc-panel" class="panel card panel-default mb-2">
<div class="panel-heading card-header">
<h3 class="panel-title card-title m-0">VNC Console</h3>
</div>
<div class="panel-body card-body p-4">
<div id="vf-vnc-alert" class="alert" style="display: none;"></div>
<p class="mb-3">Access your server's console directly in your browser. The server must be running for VNC access.</p>
<button id="vf-vnc-button" onclick="vfOpenVnc('{$serviceid}','{$systemURL}')" type="button" class="btn btn-primary d-flex align-items-center">
<span id="vf-vnc-spinner" class="spinner-border spinner-border-sm vf-spinner-margin" style="display:none;"></span>
Open Console
</button>
</div>
</div>
{* Section navigation moved to the WHMCS Actions sidebar via the
ClientAreaPrimarySidebar hook in hooks.php. The sidebar version stays
visible while scrolling, which the inline strip never could. JS still
walks the rendered links and hides ones whose target panels are hidden. *}
{* Server Overview Panel *} {* Server Overview Panel *}
<div class="panel card panel-default mb-3"> <div id="vf-sec-overview" class="panel card panel-default mb-2" data-vf-nav-label="Overview">
<div class="panel-heading card-header"> <div class="panel-heading card-header">
<h3 class="panel-title card-title m-0"> <h3 class="panel-title card-title m-0">
Server Overview Server Overview
@@ -39,6 +70,20 @@
<div id="vf-server-info-error"> <div id="vf-server-info-error">
<div class="alert alert-warning mb-0">Information unavailable. Try again later.</div> <div class="alert alert-warning mb-0">Information unavailable. Try again later.</div>
</div> </div>
{* Top meta bar — populated by JS once server data loads. Holds the
data-center chip (flag + city), OS chip, lifetime chip, and the
Mask IPs toggle. The toggle stays visible on every overview load
regardless of which other chips have data. *}
<div id="vf-overview-meta" class="vf-overview-meta mb-3" style="display:none;">
<span id="vf-data-location" class="vf-meta-chip" style="display:none;"></span>
<span id="vf-data-os" class="vf-meta-chip" style="display:none;"></span>
<span id="vf-data-created" class="vf-meta-chip vf-meta-chip-muted" style="display:none;"></span>
<button id="vf-mask-ips-btn" type="button" class="btn btn-sm btn-outline-secondary vf-mask-ips-btn" onclick="vfToggleIpMask()" title="Hide IPs and rDNS hostnames for screenshots">
<span id="vf-mask-ips-label">Mask Sensitive</span>
</button>
</div>
<div id="vf-server-info" class="row mb-2"> <div id="vf-server-info" class="row mb-2">
<div class="col-12"> <div class="col-12">
<div class="row"> <div class="row">
@@ -46,10 +91,10 @@
<div class="row p-1"> <div class="row p-1">
<div class="col-xs-4 col-4 text-right vf-bold">Name:</div> <div class="col-xs-4 col-4 text-right vf-bold">Name:</div>
<div class="col-xs-8 col-8"> <div class="col-xs-8 col-8">
<div class="d-flex" style="display:flex; gap:6px; align-items:center;"> <div class="vf-rename-row">
<input type="text" id="vf-rename-input" class="form-control form-control-sm" maxlength="63" style="max-width:200px;" placeholder="Server name"> <input type="text" id="vf-rename-input" class="form-control form-control-sm vf-rename-input-field vf-sensitive" maxlength="63" placeholder="Server name">
<button id="vf-randomise-btn" onclick="vfShowNameDropdown('{$serviceid}','{$systemURL}')" type="button" class="btn btn-sm btn-outline-secondary" title="Randomise">&#x21bb;</button> <button id="vf-randomise-btn" onclick="vfShowNameDropdown('{$serviceid}','{$systemURL}')" type="button" class="btn btn-sm btn-outline-secondary vf-rename-btn-randomise" title="Randomise">&#x21bb;</button>
<button id="vf-rename-save" onclick="vfRenameServer('{$serviceid}','{$systemURL}')" type="button" class="btn btn-sm btn-primary">Save</button> <button id="vf-rename-save" onclick="vfRenameServer('{$serviceid}','{$systemURL}')" type="button" class="btn btn-sm btn-primary vf-rename-btn-save">Save</button>
</div> </div>
<div id="vf-name-dropdown" style="display:none;"></div> <div id="vf-name-dropdown" style="display:none;"></div>
<div id="vf-rename-alert" class="mt-1" style="display:none;"></div> <div id="vf-rename-alert" class="mt-1" style="display:none;"></div>
@@ -57,7 +102,7 @@
</div> </div>
<div class="row p-1"> <div class="row p-1">
<div class="col-xs-4 col-4 text-right vf-bold">Hostname:</div> <div class="col-xs-4 col-4 text-right vf-bold">Hostname:</div>
<div class="col-xs-8 col-8" id="vf-data-server-hostname"></div> <div class="col-xs-8 col-8 vf-sensitive" id="vf-data-server-hostname"></div>
</div> </div>
<div class="row p-1"> <div class="row p-1">
<div class="col-xs-4 col-4 text-right vf-bold">Memory:</div> <div class="col-xs-4 col-4 text-right vf-bold">Memory:</div>
@@ -93,11 +138,99 @@
</div> </div>
</div> </div>
</div> </div>
{* Server Overview footer — Login to Control Panel SSO. Was briefly
moved to the WHMCS Actions sidebar via _CustomActions, but the
sidebar dispatch path didn't carry the SSO redirect through cleanly
in this WHMCS 9 install. Inline button is reliable: vfLoginAsServerOwner
opens a new tab and navigates it to the upstream SSO URL fetched
via fetchLoginTokens. *}
<div id="vf-overview-footer" class="vf-overview-footer mt-3 pt-3" style="border-top:1px solid #e6e8eb;">
<div id="vf-login-error" class="alert alert-danger" style="display:none;"></div>
<button id="vf-login-button" onclick="vfLoginAsServerOwner('{$serviceid}','{$systemURL}',true)" type="button" class="btn btn-primary d-flex align-items-center">
<span id="vf-login-button-spinner" class="spinner-border spinner-border-sm text-light vf-spinner-margin" style="display:none;"></span>
Login to Control Panel
</button>
<p class="mb-0 mt-2 vf-small text-muted">Opens VirtFusion in a new tab. Trouble? <a href="#" onclick="vfLoginAsServerOwner('{$serviceid}','{$systemURL}',false); return false;">Open in this tab instead</a>.</p>
</div>
</div>
</div>
{* Traffic Panel — last N months of monthly aggregates from VF. Renders
full-width (own row) — side-by-side with Live Stats was tested and felt
too cramped. *}
<div id="vf-sec-traffic" class="panel card panel-default mb-2" style="display:none;" data-vf-nav-label="Traffic">
<div class="panel-heading card-header">
<h3 class="panel-title card-title m-0">Traffic</h3>
</div>
<div class="panel-body card-body p-4">
<div id="vf-traffic-chart-section">
<canvas id="vf-traffic-chart" style="width:100%; height:240px;"></canvas>
<div class="row mt-3 text-center">
<div class="col-4"><small class="text-muted">This Period Used</small><div id="vf-traffic-used" class="vf-bold">-</div></div>
<div class="col-4"><small class="text-muted">Period Limit</small><div id="vf-traffic-limit" class="vf-bold">-</div></div>
<div class="col-4"><small class="text-muted">Remaining</small><div id="vf-traffic-remaining" class="vf-bold">-</div></div>
</div>
</div>
<script>
if (typeof vfLoadTrafficStats === 'function') {
vfLoadTrafficStats('{$serviceid}', '{$systemURL}');
}
</script>
</div>
</div>
{* Live Stats Panel — CPU, memory, disk I/O sourced from VirtFusion's
?remoteState=true introspection (libvirt + qemu-agent). Hidden by default;
surfaces only when the upstream call returns a remoteState block. Auto-
refreshes every 30s; refresh stops when the panel scrolls out of view to
keep hypervisor load proportional to actual customer attention. *}
<div id="vf-sec-livestats" class="panel card panel-default mb-2" style="display:none;" data-vf-nav-label="Live Stats">
<div class="panel-heading card-header">
<h3 class="panel-title card-title m-0">
Live Stats
<small class="text-muted vf-livestats-updated" id="vf-live-updated" style="float:right; font-size:11px; font-weight:normal;"></small>
</h3>
</div>
<div class="panel-body card-body p-4">
<div class="row">
<div class="col-md-4 mb-3">
<div class="vf-bold mb-2">CPU</div>
<div class="vf-live-gauge">
<div class="vf-live-bar"><div id="vf-live-cpu-bar" class="vf-live-bar-fill" style="width:0%;"></div></div>
<div class="d-flex justify-content-between vf-small mt-1">
<span id="vf-live-cpu-pct">-</span>
<span class="text-muted">load</span>
</div>
</div>
</div>
<div class="col-md-4 mb-3">
<div class="vf-bold mb-2">Memory</div>
<div class="vf-live-gauge">
<div class="vf-live-bar"><div id="vf-live-mem-bar" class="vf-live-bar-fill" style="width:0%;"></div></div>
<div class="d-flex justify-content-between vf-small mt-1">
<span id="vf-live-mem-text">-</span>
<span id="vf-live-mem-pct" class="text-muted">-</span>
</div>
</div>
</div>
<div class="col-md-4 mb-3">
<div class="vf-bold mb-2">Disk I/O <small class="text-muted">(since boot)</small></div>
<div class="d-flex justify-content-between vf-small">
<span class="text-muted">Read</span>
<span id="vf-live-disk-rd">-</span>
</div>
<div class="d-flex justify-content-between vf-small mt-1">
<span class="text-muted">Write</span>
<span id="vf-live-disk-wr">-</span>
</div>
</div>
</div>
</div> </div>
</div> </div>
{* Power Management Panel *} {* Power Management Panel *}
<div class="panel card panel-default mb-3"> <div id="vf-sec-power" class="panel card panel-default mb-2" data-vf-nav-label="Power">
<div class="panel-heading card-header"> <div class="panel-heading card-header">
<h3 class="panel-title card-title m-0">Power Management</h3> <h3 class="panel-title card-title m-0">Power Management</h3>
</div> </div>
@@ -129,23 +262,16 @@
</div> </div>
{* Manage Panel *} {* Manage Panel *}
<div class="panel card panel-default mb-3"> <div id="vf-sec-manage" class="panel card panel-default mb-2" data-vf-nav-label="Manage">
<div class="panel-heading card-header"> <div class="panel-heading card-header">
<h3 class="panel-title card-title m-0">Manage</h3> <h3 class="panel-title card-title m-0">Manage</h3>
</div> </div>
<div class="panel-body card-body p-4"> <div class="panel-body card-body p-4">
<div class="row"> <div class="row">
<div class="col-12"> {* Inline "Open Control Panel" button removed — WHMCS already
<div id="vf-login-error" class="alert alert-danger"></div> surfaces this in the Actions sidebar via the module's
<p>Manage your server via our dedicated control panel. You will be automatically authenticated and the control panel will open in a new window.</p> ServiceSingleSignOnLabel ("Login to VirtFusion Panel").
<button id="vf-login-button" onclick="vfLoginAsServerOwner('{$serviceid}','{$systemURL}',true)" type="button" class="btn btn-primary text-uppercase d-flex align-items-center"> Keeping both was a duplicate. *}
<div id="vf-login-button-spinner" class="spinner-border spinner-border-sm text-light vf-spinner-margin"></div>
Open Control Panel
</button>
</div>
<div class="col-12">
<p class="mb-0 pt-3 vf-small">Having trouble opening the control panel in a new window? <a href="#" onclick="vfLoginAsServerOwner('{$serviceid}','{$systemURL}',false); return false;">Click here</a> to open in this window.</p>
</div>
{if $serverHostname} {if $serverHostname}
<div class="col-12"> <div class="col-12">
<hr> <hr>
@@ -188,7 +314,7 @@
</div> </div>
{* Rebuild Panel *} {* Rebuild Panel *}
<div class="panel card panel-default mb-3"> <div id="vf-sec-rebuild" class="panel card panel-default mb-2" data-vf-nav-label="Rebuild">
<div class="panel-heading card-header"> <div class="panel-heading card-header">
<h3 class="panel-title card-title m-0">Rebuild Server</h3> <h3 class="panel-title card-title m-0">Rebuild Server</h3>
</div> </div>
@@ -215,30 +341,34 @@
</div> </div>
</div> </div>
{* Network Management Panel *} {* The standalone Network panel was removed — its IP list duplicated the
<div class="panel card panel-default mb-3"> Server Overview's IPv4/IPv6 rows. The unique value (per-IP copy buttons)
was folded into the Overview cells via vfRenderIpCells in module.js. *}
{if $rdnsEnabled}
{* Reverse DNS Panel *}
<div id="vf-sec-rdns" class="panel card panel-default mb-2" data-vf-nav-label="Reverse DNS">
<div class="panel-heading card-header"> <div class="panel-heading card-header">
<h3 class="panel-title card-title m-0">Network</h3> <h3 class="panel-title card-title m-0">Reverse DNS</h3>
</div> </div>
<div class="panel-body card-body p-4"> <div class="panel-body card-body p-4">
<div id="vf-network-alert" class="alert" style="display: none;"></div> <p class="vf-small text-muted mb-3">Set a custom PTR record for each assigned IP. Forward DNS (A/AAAA) for the hostname must already resolve to the IP before the PTR can be saved.</p>
<div id="vf-network-content" style="display: none;"> <div id="vf-rdns-alert" class="alert" style="display:none;"></div>
<div class="row mb-3"> <div id="vf-rdns-list">
<div class="col-md-6"> <div class="vf-skeleton vf-skeleton-line vf-skeleton-line-medium"></div>
<h5 class="vf-bold">IPv4 Addresses</h5> <div class="vf-skeleton vf-skeleton-line vf-skeleton-line-medium"></div>
<div id="vf-ipv4-list" class="mb-2"></div>
</div>
<div class="col-md-6">
<h5 class="vf-bold">IPv6 Subnets</h5>
<div id="vf-ipv6-list" class="mb-2"></div>
</div>
</div>
</div> </div>
<script>
if (typeof vfLoadRdns === 'function') {
vfLoadRdns('{$serviceid}', '{$systemURL}');
}
</script>
</div> </div>
</div> </div>
{/if}
{* Resources Panel — populated by JS after server data loads *} {* Resources Panel — populated by JS after server data loads *}
<div id="vf-resources-panel" class="panel card panel-default mb-3" style="display: none;"> <div id="vf-resources-panel" class="panel card panel-default mb-2" style="display: none;" data-vf-nav-label="Resources">
<div class="panel-heading card-header"> <div class="panel-heading card-header">
<h3 class="panel-title card-title m-0">Resources</h3> <h3 class="panel-title card-title m-0">Resources</h3>
</div> </div>
@@ -274,77 +404,34 @@
<div id="vf-res-traffic-bar" class="progress-bar" role="progressbar" style="width: 0%"></div> <div id="vf-res-traffic-bar" class="progress-bar" role="progressbar" style="width: 0%"></div>
</div> </div>
</div> </div>
<div class="vf-resource-item mb-3">
<div class="d-flex justify-content-between mb-1">
<span class="vf-bold">Network Speed</span>
<span id="vf-res-network-speed"></span>
</div> </div>
</div> </div>
</div> {* Note: dedicated Traffic panel near the top of the page (vf-sec-traffic)
</div> handles the chart + period tile. Resources panel here just lists the
<div id="vf-traffic-chart-section" style="display:none;"> configured limits — no chart duplication. Network speed row was
removed: VirtFusion's API returns 0 for inAverage/inPeak/inBurst
when speed isn't capped at the package level, which is the
common case for our setup — there's nothing useful to show. *}
{* Filesystem usage — only renders when qemu-guest-agent is running on
the guest. vfRenderFilesystems() shows or hides the section based
on whether remoteState.agent.fsinfo came back populated. *}
<div id="vf-fs-section" class="mt-4" style="display:none;">
<hr> <hr>
<h5 class="vf-bold mb-2">Traffic Usage</h5> <h5 class="vf-bold mb-3">Filesystem Usage</h5>
<canvas id="vf-traffic-chart" style="width:100%; height:200px;"></canvas> <div id="vf-fs-container"></div>
<div class="row mt-2 text-center"> <p class="vf-small text-muted mt-2 mb-0">Reported by qemu-guest-agent inside the VM. Install <code>qemu-guest-agent</code> if no filesystems show.</p>
<div class="col-4"><small class="text-muted">Used</small><div id="vf-traffic-used" class="vf-bold">-</div></div>
<div class="col-4"><small class="text-muted">Limit</small><div id="vf-traffic-limit" class="vf-bold">-</div></div>
<div class="col-4"><small class="text-muted">Remaining</small><div id="vf-traffic-remaining" class="vf-bold">-</div></div>
</div> </div>
</div> </div>
<script>
if (typeof vfLoadTrafficStats === 'function') {
vfLoadTrafficStats('{$serviceid}', '{$systemURL}');
}
</script>
</div>
</div> </div>
{* VNC Console Panel — hidden by default, shown by JS if VNC is enabled *} {* VNC panel relocated to the very top of the page (above Server Overview).
<div id="vf-vnc-panel" class="panel card panel-default mb-3" style="display: none;"> See its definition there. This block is intentionally left as a comment
<div class="panel-heading card-header"> marker so future readers know where the panel used to live. *}
<h3 class="panel-title card-title m-0">VNC Console</h3>
</div>
<div class="panel-body card-body p-4">
<div id="vf-vnc-alert" class="alert" style="display: none;"></div>
<p>Access your server's console directly in your browser. The server must be running for VNC access.</p>
<div class="d-flex align-items-center mb-3" style="display:flex; gap:12px; align-items:center;">
<button id="vf-vnc-button" onclick="vfOpenVnc('{$serviceid}','{$systemURL}')" type="button" class="btn btn-primary text-uppercase d-flex align-items-center">
<span id="vf-vnc-spinner" class="spinner-border spinner-border-sm vf-spinner-margin" style="display:none;"></span>
Open Console
</button>
<label class="vf-toggle-label mb-0" style="display:flex; align-items:center; gap:6px; cursor:pointer;">
<input type="checkbox" id="vf-vnc-toggle" class="vf-toggle-input" onchange="vfToggleVnc('{$serviceid}','{$systemURL}', this.checked)">
<span class="vf-toggle-switch"></span>
<span class="vf-small">VNC Enabled</span>
</label>
</div>
<div id="vf-vnc-details" style="display:none;">
<div class="row">
<div class="col-md-6">
<div class="row p-1">
<div class="col-4 text-right vf-bold vf-small">IP:</div>
<div class="col-8 vf-small" id="vf-vnc-ip">-</div>
</div>
<div class="row p-1">
<div class="col-4 text-right vf-bold vf-small">Port:</div>
<div class="col-8 vf-small" id="vf-vnc-port">-</div>
</div>
</div>
<div class="col-md-6">
<button type="button" class="btn btn-sm btn-outline-secondary" onclick="vfCopyVncPassword('{$serviceid}','{$systemURL}')">
Copy VNC Password
</button>
<span id="vf-vnc-copy-confirm" class="text-success vf-small" style="display:none;">Copied!</span>
</div>
</div>
</div>
</div>
</div>
{* Self Service — Billing & Usage Panel *} {* Self Service — Billing & Usage Panel *}
{if $selfServiceMode > 0} {if $selfServiceMode > 0}
<div id="vf-selfservice-panel" class="panel card panel-default mb-3" style="display: none;"> <div id="vf-selfservice-panel" class="panel card panel-default mb-2" style="display: none;" data-vf-nav-label="Billing & Usage">
<div class="panel-heading card-header"> <div class="panel-heading card-header">
<h3 class="panel-title card-title m-0">Billing & Usage</h3> <h3 class="panel-title card-title m-0">Billing & Usage</h3>
</div> </div>
@@ -394,7 +481,7 @@
{elseif $serviceStatus eq 'Suspended'} {elseif $serviceStatus eq 'Suspended'}
<div class="panel card panel-default mb-3"> <div class="panel card panel-default mb-2">
<div class="panel-heading card-header"> <div class="panel-heading card-header">
<h3 class="panel-title card-title m-0">Service Suspended</h3> <h3 class="panel-title card-title m-0">Service Suspended</h3>
</div> </div>
@@ -408,7 +495,7 @@
{/if} {/if}
{* Billing Overview - Always visible *} {* Billing Overview - Always visible *}
<div class="panel card panel-default mb-3"> <div id="vf-sec-billing" class="panel card panel-default mb-2" data-vf-nav-label="Billing Overview">
<div class="panel-heading card-header"> <div class="panel-heading card-header">
<h3 class="panel-title card-title m-0">Billing Overview</h3> <h3 class="panel-title card-title m-0">Billing Overview</h3>
</div> </div>