Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

feat(power-pages): add security skills (#151)

Ramachandran Re55e1d338774
diff --git a/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md b/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md
index f158998d3..dddaccad7 100644
--- a/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md
+++ b/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md
@@ -220,7 +220,7 @@ LLMs are probabilistic. When an LLM constructs inline bash commands for Datavers
| `dataverse-request.js` | Generic authenticated Dataverse API request helper |
| `verify-dataverse-access.js` | Verifies Dataverse connectivity and permissions |
| `check-activation-status.js` | Queries Power Platform API for site activation status |
-| `clear-site-cache.js` | Clears site cache via Power Platform admin API |
+| `clear-site-cache.js` | Clears site cache via Power Platform API |
### Usage Pattern
diff --git a/plugins/power-pages/references/skill-tracking-reference.md b/plugins/power-pages/references/skill-tracking-reference.md
index 0020350b6..38750967e 100644
--- a/plugins/power-pages/references/skill-tracking-reference.md
+++ b/plugins/power-pages/references/skill-tracking-reference.md
@@ -41,6 +41,10 @@ If the tracking script creates or updates site setting YAML files, include those
| add-server-logic | AddServerLogic | Site/AI/Skills/AddServerLogic |
| add-cloud-flow | AddCloudFlow | Site/AI/Skills/AddCloudFlow |
| integrate-backend | IntegrateBackend | Site/AI/Skills/IntegrateBackend |
+| scan-site | ScanSite | Site/AI/Skills/ScanSite |
+| manage-headers | ManageHeaders | Site/AI/Skills/ManageHeaders |
+| manage-firewall | ManageFirewall | Site/AI/Skills/ManageFirewall |
+| security-review | SecurityReview | Site/AI/Skills/SecurityReview |
| setup-solution | SetupSolution | Site/AI/Skills/SetupSolution |
| export-solution | ExportSolution | Site/AI/Skills/ExportSolution |
| import-solution | ImportSolution | Site/AI/Skills/ImportSolution |
diff --git a/plugins/power-pages/scripts/build-review-data.js b/plugins/power-pages/scripts/build-review-data.js
new file mode 100644
index 000000000..07b907cb4
--- /dev/null
+++ b/plugins/power-pages/scripts/build-review-data.js
@@ -0,0 +1,192 @@
+#!/usr/bin/env node
+
+const fs = require('fs');
+const path = require('path');
+
+const REQUIRED_FLAGS = [
+ 'reportName',
+ 'inputDir',
+ 'siteName',
+ 'goalLabel',
+ 'scopeLabel',
+ 'output',
+];
+
+const SECTION_MAP = {
+ 'scan-site.json': { id: 'site-scan', label: 'Live Site Scan', icon: '◐' },
+ 'manage-headers.json': { id: 'headers', label: 'Browser Headers', icon: '◑' },
+ 'manage-firewall.json': {
+ id: 'firewall',
+ label: 'Web Application Firewall',
+ icon: '◆',
+ },
+ 'audit-permissions.json': { id: 'permissions', label: 'Roles & Permissions', icon: '◇' },
+ 'setup-auth.json': { id: 'auth', label: 'Access & Identity', icon: '◈' },
+};
+
+// Every severity a finding may carry. `pass` is shown as a stat but excluded
+// from the issue count by the report template.
+const SEVERITIES = ['critical', 'high', 'warning', 'medium', 'info', 'low', 'pass'];
+
+const HELP = `build-review-data.js — Consolidate per-skill JSON into a single review data file.
+
+Usage:
+ node build-review-data.js --reportName <name> --inputDir <dir> --siteName <name> --goalLabel <label> --scopeLabel <label> --output <path> [--summary <text>] [--nextStepsFile <path>]
+
+Flags:
+ --reportName Top-bar report title (e.g., "Security Review", "Site Scan") (required)
+ --inputDir Directory containing per-skill review JSON files (required)
+ --siteName Site display name (required)
+ --goalLabel Plain-language goal label (required)
+ --scopeLabel Plain-language scope label (required)
+ --output Output data-file path (required)
+ --summary Overall plain-language summary, 2-4 sentences (optional)
+ --nextStepsFile Path to a JSON file containing an array of next-step strings (optional)
+ --help Show this help message
+
+Exit codes:
+ 0 Success (data file written; status JSON on stdout)
+ 1 Invocation error (missing flag or unreadable input dir)
+`;
+
+function getArg(name, fallback = null) {
+ const idx = process.argv.indexOf('--' + name);
+ return idx !== -1 && idx + 1 < process.argv.length ? process.argv[idx + 1] : fallback;
+}
+
+function readNextSteps(filePath) {
+ try {
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ return Array.isArray(parsed) ? parsed.filter((x) => typeof x === 'string') : [];
+ } catch (err) {
+ process.stderr.write(`Could not read next-steps file: ${err.message}\n`);
+ return [];
+ }
+}
+
+function formatGeneratedAt(now) {
+ const pad = (n) => String(n).padStart(2, '0');
+ // Intl returns "GMT+5:30" on some platforms; keep only the short abbreviation when present.
+ const tzName =
+ new Intl.DateTimeFormat(undefined, { timeZoneName: 'short' })
+ .formatToParts(now)
+ .find((p) => p.type === 'timeZoneName')?.value || '';
+ const stamp =
+ `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ` +
+ `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
+ return tzName ? `${stamp} ${tzName}` : stamp;
+}
+
+function skippedSection(meta, reason) {
+ return {
+ id: meta.id,
+ icon: meta.icon,
+ label: meta.label,
+ description: '',
+ findings: [
+ {
+ id: `${meta.id}-skipped`,
+ title: `${meta.label} check was skipped`,
+ details: reason || 'No additional detail.',
+ },
+ ],
+ details: {},
+ };
+}
+
+function buildSections(inputDir, outputBasename) {
+ const sections = [];
+ const totals = Object.fromEntries(SEVERITIES.map((s) => [s, 0]));
+
+ for (const fileName of fs.readdirSync(inputDir).sort()) {
+ if (!fileName.endsWith('.json')) continue;
+ if (fileName === outputBasename) continue;
+ const meta = SECTION_MAP[fileName];
+ if (!meta) continue;
+
+ const filePath = path.join(inputDir, fileName);
+ let raw;
+ try {
+ raw = JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ } catch (err) {
+ process.stderr.write(`Skipping ${fileName}: ${err.message}\n`);
+ continue;
+ }
+
+ if (raw?.status === 'skipped') {
+ sections.push(skippedSection(meta, raw.reason));
+ continue;
+ }
+
+ const findings = Array.isArray(raw?.findings) ? raw.findings : [];
+ sections.push({
+ id: meta.id,
+ icon: meta.icon,
+ label: meta.label,
+ description: '',
+ findings,
+ details: raw?.details || {},
+ });
+
+ for (const f of findings) {
+ if (f.severity && totals[f.severity] !== undefined) totals[f.severity] += 1;
+ }
+ }
+
+ return { sections, totals };
+}
+
+function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const values = Object.fromEntries(REQUIRED_FLAGS.map((flag) => [flag, getArg(flag)]));
+ for (const flag of REQUIRED_FLAGS) {
+ if (!values[flag]) {
+ process.stderr.write(`Missing required flag: --${flag}\n`);
+ process.exit(1);
+ }
+ }
+
+ const inputDir = values.inputDir;
+ const outputPath = values.output;
+ if (!fs.existsSync(inputDir)) {
+ process.stderr.write(`Input dir not found: ${inputDir}\n`);
+ process.exit(1);
+ }
+
+ const summary = getArg('summary', '');
+ const nextStepsFile = getArg('nextStepsFile');
+ const nextSteps = nextStepsFile ? readNextSteps(nextStepsFile) : [];
+
+ const { sections, totals } = buildSections(inputDir, path.basename(outputPath));
+
+ const payload = {
+ REPORT_NAME: values.reportName,
+ SITE_NAME: values.siteName,
+ GOAL_LABEL: values.goalLabel,
+ SCOPE_LABEL: values.scopeLabel,
+ GENERATED_AT: formatGeneratedAt(new Date()),
+ REVIEW_DATA: { summary: summary || '', totals, sections, nextSteps },
+ };
+
+ fs.mkdirSync(path.dirname(outputPath), { recursive: true });
+ fs.writeFileSync(outputPath, JSON.stringify(payload, null, 2));
+
+ process.stdout.write(
+ JSON.stringify({
+ status: 'ok',
+ outputPath,
+ totals,
+ sectionsCount: sections.length,
+ }) + '\n'
+ );
+}
+
+if (require.main === module) {
+ main();
+}
+
+module.exports = { buildSections, formatGeneratedAt, SECTION_MAP, SEVERITIES };
diff --git a/plugins/power-pages/scripts/clear-site-cache.js b/plugins/power-pages/scripts/clear-site-cache.js
index 521c52e76..6d2aa361a 100644
--- a/plugins/power-pages/scripts/clear-site-cache.js
+++ b/plugins/power-pages/scripts/clear-site-cache.js
@@ -1,7 +1,7 @@
#!/usr/bin/env node
// Clears the runtime cache of an activated Power Pages site by restarting it
-// via the Power Platform admin API.
+// via the Power Platform API.
//
// Usage:
// node clear-site-cache.js --projectRoot "<path>"
diff --git a/plugins/power-pages/scripts/lib/power-platform-api.js b/plugins/power-pages/scripts/lib/power-platform-api.js
new file mode 100644
index 000000000..1b4858108
--- /dev/null
+++ b/plugins/power-pages/scripts/lib/power-platform-api.js
@@ -0,0 +1,269 @@
+#!/usr/bin/env node
+
+// Shared client for Power Pages operations against the Power Platform API.
+// Resolves auth/tenant/environment context from local PAC + Azure CLI state
+// and issues HTTP requests with consistent error handling and async polling.
+
+const { execSync } = require('child_process');
+const {
+ getAuthToken,
+ makeRequest,
+ getPacAuthInfo,
+ CLOUD_TO_API,
+} = require('./validation-helpers');
+
+const DEFAULT_POLL_TIMEOUT_MS = 10 * 60 * 1000;
+const DEFAULT_POLL_INTERVAL_MS = 5000;
+const AZ_TIMEOUT_MS = 15_000;
+const API_VERSION = '2022-03-01-preview';
+
+function getTenantId() {
+ // PAC CLI does not expose tenant id; pull it from Azure CLI which shares
+ // the same identity. stdio settings suppress az's stderr noise on logout.
+ try {
+ const out = execSync('az account show --query tenantId -o tsv', {
+ encoding: 'utf8',
+ timeout: AZ_TIMEOUT_MS,
+ stdio: ['ignore', 'pipe', 'ignore'],
+ }).trim();
+ return out || null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Resolves the full Power Platform API context from local CLI state. Callers build
+ * site-specific URL paths themselves using a portalId — the Power Platform API URL
+ * segment is portalId, never websiteRecordId. See `lib/website.js` for the
+ * resolution from a Dataverse websiteRecordId to a portalId.
+ *
+ * @returns {{ tenantId, environmentId, baseUrl, token, apiHost } | { error: string }}
+ */
+function resolveContext() {
+ const pac = getPacAuthInfo();
+ if (!pac) {
+ return { error: 'Power Platform CLI is not signed in. Run: pac auth create' };
+ }
+ const tenantId = getTenantId();
+ if (!tenantId) {
+ return { error: 'Azure CLI is not signed in. Run: az login' };
+ }
+ const apiHost = CLOUD_TO_API[pac.cloud] || CLOUD_TO_API.Public;
+ const token = getAuthToken(apiHost);
+ if (!token) {
+ return { error: `Failed to acquire access token for ${apiHost}.` };
+ }
+ const baseUrl = `${apiHost}/powerpages/environments/${pac.environmentId}`;
+ return { tenantId, environmentId: pac.environmentId, baseUrl, token, apiHost };
+}
+
+function buildQuery(params) {
+ if (!params) return '';
+ const entries = Object.entries(params).filter(([, v]) => v !== undefined && v !== null);
+ if (entries.length === 0) return '';
+ return '?' + entries
+ .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
+ .join('&');
+}
+
+/**
+ * Issues a request against the Power Platform API. Returns a normalized envelope.
+ *
+ * @param {object} options
+ * @param {object} options.context - Result of resolveContext()
+ * @param {string} options.method - HTTP method
+ * @param {string} options.path - Path relative to context.baseUrl (must start with '/')
+ * @param {object} [options.query] - Query parameters (encoded)
+ * @param {object|string} [options.body] - JSON body (object) or raw string
+ * @param {object} [options.extraHeaders]
+ * @param {number} [options.timeout] - Request timeout in ms (default: 15000)
+ * @returns {Promise<{ ok: boolean, statusCode: number, body: any, headers: object, error?: { code, message } }>}
+ */
+async function request({ context, method, path, query, body, extraHeaders, timeout }) {
+ if (!context || !context.baseUrl) throw new Error('context is required');
+ if (!path.startsWith('/')) throw new Error('path must start with /');
+
+ const mergedQuery = { 'api-version': API_VERSION, ...query };
+ const url = `${context.baseUrl}${path}${buildQuery(mergedQuery)}`;
+ const headers = {
+ Authorization: `Bearer ${context.token}`,
+ Accept: 'application/json',
+ ...(extraHeaders || {}),
+ };
+ let payload = null;
+ if (body !== undefined && body !== null) {
+ if (typeof body === 'string') {
+ payload = body;
+ headers['Content-Type'] = headers['Content-Type'] || 'application/json';
+ } else {
+ payload = JSON.stringify(body);
+ headers['Content-Type'] = 'application/json';
+ }
+ }
+
+ const res = await makeRequest({
+ url,
+ method,
+ headers,
+ body: payload,
+ includeHeaders: true,
+ ...(timeout != null && { timeout }),
+ });
+ if (res.error) {
+ return {
+ ok: false,
+ statusCode: 0,
+ body: null,
+ headers: {},
+ error: { code: 'NetworkError', message: res.error },
+ };
+ }
+
+ const parsedBody = parseBody(res.body, res.headers || {});
+ const ok = res.statusCode >= 200 && res.statusCode < 300;
+ const out = { ok, statusCode: res.statusCode, body: parsedBody, headers: res.headers || {} };
+ if (!ok) out.error = extractError(parsedBody, res.statusCode);
+ return out;
+}
+
+function parseBody(raw, headers) {
+ if (!raw) return null;
+ const ct = (headers['content-type'] || headers['Content-Type'] || '').toLowerCase();
+ const first = typeof raw === 'string' ? raw.trimStart()[0] : '';
+ if (ct.includes('application/json') || first === '{' || first === '[') {
+ try {
+ return JSON.parse(raw);
+ } catch {
+ // Fall through and return the raw string.
+ }
+ }
+ return raw;
+}
+
+function extractError(body, statusCode) {
+ if (body && typeof body === 'object' && body.error) {
+ return { code: body.error.code || `HTTP_${statusCode}`, message: body.error.message || '' };
+ }
+ if (typeof body === 'string') {
+ return { code: `HTTP_${statusCode}`, message: body };
+ }
+ return { code: `HTTP_${statusCode}`, message: '' };
+}
+
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/**
+ * Polls a status endpoint until a predicate returns truthy or timeout elapses.
+ *
+ * @param {object} options
+ * @param {function} options.fetchStatus - async () => { ok, body }
+ * @param {function} options.isDone - (body) => boolean
+ * @param {number} [options.timeoutMs]
+ * @param {number} [options.intervalMs]
+ * @returns {Promise<{ ok: boolean, body?: any, error?: string, attempts: number }>}
+ */
+async function pollUntil({
+ fetchStatus,
+ isDone,
+ timeoutMs = DEFAULT_POLL_TIMEOUT_MS,
+ intervalMs = DEFAULT_POLL_INTERVAL_MS,
+}) {
+ const deadline = Date.now() + timeoutMs;
+ let attempts = 0;
+ while (Date.now() < deadline) {
+ attempts += 1;
+ const status = await fetchStatus();
+ if (!status.ok) {
+ return { ok: false, error: status.error || 'status fetch failed', attempts };
+ }
+ if (isDone(status.body)) {
+ return { ok: true, body: status.body, attempts };
+ }
+ await sleep(intervalMs);
+ }
+ return { ok: false, error: 'timeout', attempts };
+}
+
+function parseCliArgs(argv) {
+ const out = {};
+ for (let i = 2; i < argv.length; i++) {
+ const a = argv[i];
+ if (!a.startsWith('--')) continue;
+ const key = a.slice(2);
+ const next = argv[i + 1];
+ if (next === undefined || next.startsWith('--')) {
+ out[key] = true;
+ } else {
+ out[key] = next;
+ i++;
+ }
+ }
+ return out;
+}
+
+function emitJson(value) {
+ process.stdout.write(JSON.stringify(value, null, 2) + '\n');
+}
+
+function fail(message, code = 1) {
+ process.stderr.write(message.endsWith('\n') ? message : message + '\n');
+ process.exit(code);
+}
+
+/**
+ * Returns true when the response carries one of the given error codes. Power
+ * Platform error codes are unique per scenario (B022/B023 = 400, B003 = 409,
+ * etc.), so the helper does not constrain status.
+ */
+function hasErrorCode(res, ...codes) {
+ return codes.includes(res.error?.code);
+}
+
+/**
+ * Returns true when the response indicates the feature is not supported for
+ * this site (region restriction, trial site, etc.). Recognizes the documented
+ * error codes plus a "not supported" fallback in the message.
+ */
+function isFeatureUnsupported(res, ...codes) {
+ if (hasErrorCode(res, ...codes)) return true;
+ return res.statusCode === 400 && /not supported/i.test(res.error?.message || '');
+}
+
+/**
+ * Parses --timeoutMinutes (or any positive-integer-minute flag) into milliseconds.
+ * Calls `fail()` on non-finite or non-positive values.
+ */
+function parseTimeoutMs(value, defaultMinutes) {
+ const minutes = value === undefined ? defaultMinutes : Number(value);
+ if (!Number.isFinite(minutes) || minutes <= 0) {
+ fail(`Invalid --timeoutMinutes value "${value}". Must be a positive number.`, 1);
+ }
+ return minutes * 60 * 1000;
+}
+
+/**
+ * Wraps an async `main` for CLI scripts. Caller passes its own `module` so the
+ * gate fires only when the script is executed directly, not when required.
+ */
+function runCli(callerModule, mainFn) {
+ if (require.main !== callerModule) return;
+ Promise.resolve()
+ .then(mainFn)
+ .catch((err) => fail(err?.message || String(err), 1));
+}
+
+module.exports = {
+ resolveContext,
+ request,
+ pollUntil,
+ parseCliArgs,
+ parseTimeoutMs,
+ emitJson,
+ fail,
+ hasErrorCode,
+ isFeatureUnsupported,
+ runCli,
+ DEFAULT_POLL_TIMEOUT_MS,
+ DEFAULT_POLL_INTERVAL_MS,
+};
diff --git a/plugins/power-pages/scripts/lib/templates/security-review-report.html b/plugins/power-pages/scripts/lib/templates/security-review-report.html
new file mode 100644
index 000000000..cc1751ea1
--- /dev/null
+++ b/plugins/power-pages/scripts/lib/templates/security-review-report.html
@@ -0,0 +1,266 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8"/>
+<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
+<title>__REPORT_NAME__ — __SITE_NAME__</title>
+<style>
+:root {
+ --bg:#faf9f8; --surface:#ffffff; --surface2:#f3f2f1; --surface3:#edebe9;
+ --border:#e1dfdd; --border-light:#c8c6c4;
+ --text:#323130; --text-dim:#605e5c; --text-bright:#201f1e;
+ --accent:#0078d4; --accent-bg:#0078d40a; --accent-border:#0078d425;
+ --critical:#d13438; --critical-bg:#d134380a; --critical-border:#d1343825;
+ --warning:#ca5010; --warning-bg:#ca50100a; --warning-border:#ca501025;
+ --pass:#107c10; --pass-bg:#107c100a; --pass-border:#107c1025;
+ --info:#0078d4; --info-bg:#0078d40a; --info-border:#0078d425;
+ --purple:#8764b8; --purple-bg:#8764b80a; --purple-border:#8764b825;
+ --mono:'Cascadia Code','Consolas',monospace;
+ --sans:'Segoe UI','Segoe UI Web (West European)',-apple-system,system-ui,sans-serif;
+ --radius:8px; --radius-sm:4px;
+ --shadow-4:0 1.6px 3.6px 0 rgba(0,0,0,0.132),0 0.3px 0.9px 0 rgba(0,0,0,0.108);
+ --shadow-8:0 3.2px 7.2px 0 rgba(0,0,0,0.132),0 0.6px 1.8px 0 rgba(0,0,0,0.108);
+}
+*{margin:0;padding:0;box-sizing:border-box;}
+html{scroll-behavior:smooth;}
+body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14px;line-height:1.6;}
+
+.topbar{z-index:100;background:var(--surface);box-shadow:var(--shadow-4);padding:14px 28px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;}
+.topbar-left{display:flex;align-items:center;gap:14px;}
+.logo{width:36px;height:36px;object-fit:contain;display:block;flex-shrink:0;}
+.topbar-title{font-size:16px;font-weight:700;color:var(--text-bright);}
+.topbar-sub{font-size:11px;color:var(--text-dim);margin-top:1px;}
+.layout{display:flex;min-height:calc(100vh - 61px);}
+.sidebar{width:240px;background:var(--surface);border-right:1px solid var(--border);padding:20px 0;flex-shrink:0;}
+.nav-group-label{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--text-dim);font-weight:700;padding:14px 22px 6px;}
+.nav-btn{display:flex;align-items:center;gap:10px;width:100%;padding:10px 22px;background:none;border:none;border-left:2px solid transparent;color:var(--text-dim);font-size:13px;font-weight:500;cursor:pointer;font-family:var(--sans);text-align:left;transition:all 0.15s;position:relative;}
+.nav-btn:hover{color:var(--text);background:var(--surface2);}
+.nav-btn.active{color:var(--accent);font-weight:600;border-left-color:var(--accent);background:var(--accent-bg);}
+.nav-btn .nav-icon{font-size:14px;opacity:0.6;width:16px;text-align:center;}
+.nav-btn.active .nav-icon{opacity:0.95;}
+.nav-badge{position:absolute;right:14px;font-size:10px;font-family:var(--mono);padding:1px 6px;border-radius:8px;font-weight:700;}
+
+.content{flex:1;padding:32px 40px;max-width:1100px;}
+.section{display:none;}
+.section.active{display:block;animation:fadeIn 0.3s ease;}
+@keyframes fadeIn{from{opacity:0;transform:translateY(8px);}to{opacity:1;transform:translateY(0);}}
+
+h2{font-size:21px;font-weight:800;color:var(--text-bright);letter-spacing:-0.3px;margin-bottom:5px;}
+.section-desc{font-size:13px;color:var(--text-dim);margin-bottom:20px;}
+h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margin-bottom:12px;}
+
+.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 20px;margin-bottom:10px;transition:box-shadow 0.2s;}
+.card:hover{box-shadow:var(--shadow-4);}
+
+.stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px;margin-bottom:20px;}
+.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 16px;text-align:center;box-shadow:var(--shadow-4);}
+.stat-num{font-size:28px;font-weight:800;font-family:var(--mono);line-height:1;}
+.stat-label{font-size:10px;color:var(--text-dim);text-transform:uppercase;letter-spacing:1px;margin-top:6px;}
+
+.severity{font-size:9px;font-weight:700;padding:3px 8px;border-radius:3px;font-family:var(--mono);display:inline-block;text-transform:uppercase;letter-spacing:0.5px;}
+.severity-critical,.severity-high{color:var(--critical);background:var(--critical-bg);border:1px solid var(--critical-border);}
+.severity-warning,.severity-medium{color:var(--warning);background:var(--warning-bg);border:1px solid var(--warning-border);}
+.severity-info,.severity-low{color:var(--info);background:var(--info-bg);border:1px solid var(--info-border);}
+.severity-pass{color:var(--pass);background:var(--pass-bg);border:1px solid var(--pass-border);}
+
+.finding-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);margin-bottom:10px;overflow:hidden;transition:box-shadow 0.2s;}
+.finding-card:hover{box-shadow:var(--shadow-4);}
+.finding-header{display:flex;align-items:flex-start;gap:12px;padding:14px 18px;cursor:pointer;-webkit-user-select:none;user-select:none;}
+.finding-header:hover{background:var(--surface2);}
+.finding-title{font-size:14px;font-weight:600;color:var(--text-bright);flex:1;}
+.finding-tag{font-size:11px;color:var(--accent);background:var(--accent-bg);padding:1px 6px;border-radius:3px;border:1px solid var(--accent-border);font-family:var(--mono);}
+.finding-chevron{color:var(--text-dim);font-size:12px;transition:transform 0.2s;flex-shrink:0;margin-top:3px;}
+.finding-card.expanded .finding-chevron{transform:rotate(90deg);}
+.finding-body{display:none;padding:0 18px 14px;border-top:1px solid var(--border);}
+.finding-card.expanded .finding-body{display:block;animation:fadeIn 0.2s ease;}
+
+.field-label{font-size:11px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:0.5px;margin-bottom:4px;}
+.reasoning-block{background:var(--surface2);border-left:2px solid var(--accent);border-radius:var(--radius-sm);padding:10px 14px;margin-top:10px;font-size:12px;line-height:1.7;white-space:pre-wrap;}
+.fix-block{background:var(--pass-bg);border-left:2px solid var(--pass);border-radius:var(--radius-sm);padding:10px 14px;margin-top:8px;font-size:12px;line-height:1.7;}
+.fix-block strong{color:var(--pass);}
+
+.detail-table{width:100%;border-collapse:collapse;font-size:13px;margin:10px 0;}
+.detail-table th{text-align:left;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:0.8px;color:var(--text-dim);padding:10px 12px;border-bottom:2px solid var(--border);}
+.detail-table td{padding:10px 12px;border-bottom:1px solid var(--border);vertical-align:top;}
+.detail-table tr:last-child td{border-bottom:none;}
+.detail-table tr:hover td{background:var(--surface2);}
+
+.kv-list{display:grid;grid-template-columns:200px 1fr;gap:6px 14px;font-size:13px;}
+.kv-list dt{color:var(--text-dim);font-weight:600;}
+.kv-list dd{color:var(--text);}
+
+.glossary-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:14px 18px;margin-bottom:10px;}
+.glossary-term{font-size:14px;font-weight:700;color:var(--text-bright);}
+.glossary-aka{font-size:12px;font-family:var(--mono);color:var(--text-dim);margin-left:6px;}
+.glossary-def{font-size:13px;color:var(--text);margin-top:6px;line-height:1.7;}
+
+.next-steps li{margin:8px 0;}
+.next-steps strong{color:var(--text-bright);}
+
+@media(max-width:768px){
+ .sidebar{display:none;}
+ .content{padding:20px 16px;}
+ .stats-grid{grid-template-columns:repeat(auto-fit,minmax(120px,1fr));}
+}
+</style>
+</head>
+<body>
+
+<div class="topbar">
+ <div class="topbar-left">
+ <img class="logo" src="./power-pages-icon.png" alt="Power Pages" />
+ <div>
+ <div class="topbar-title">__REPORT_NAME__</div>
+ <div class="topbar-sub">__SITE_NAME__ · Generated __GENERATED_AT__</div>
+ </div>
+ </div>
+</div>
+
+<div class="layout">
+ <div class="sidebar" id="sidebar"></div>
+ <div class="content" id="contentRoot"></div>
+</div>
+
+<footer style="position:fixed;bottom:0;left:0;right:0;text-align:center;padding:10px;font-size:12px;color:#605e5c;border-top:1px solid #c8c6c4;background:#ffffff;z-index:100;">AI-generated content may be incorrect</footer>
+
+<script>
+const REPORT_NAME = "__REPORT_NAME__";
+const SITE_NAME = "__SITE_NAME__";
+const GOAL_LABEL = "__GOAL_LABEL__";
+const SCOPE_LABEL = "__SCOPE_LABEL__";
+const REVIEW_DATA = __REVIEW_DATA__;
+
+// REVIEW_DATA shape:
+// {
+// summary: "<plain-language summary>",
+// totals: { critical, warning, info, pass },
+// sections: [
+// { id, label, description, findings: [...], details: { kind, ... } }
+// ],
+// nextSteps: [ "string" ],
+// glossary: [ { term, aka?, definition } ]
+// }
+
+function esc(s) { if (!s) return ''; return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;'); }
+// Like esc(), but renders newlines as <br> for multi-line details/fix text.
+function escMultiline(s) { return esc(s).replace(/\n/g, '<br>'); }
+function escAttr(s) { return String(s || '').replace(/[^a-zA-Z0-9_.-]/g, ''); }
+const sevLabel = (s) => ({ critical:'CRITICAL', high:'HIGH', warning:'WARNING', medium:'MEDIUM', info:'INFO', low:'LOW', pass:'PASSED' }[s] || (s ? s.toUpperCase() : ''));
+
+function findingHtml(f, idx) {
+ const id = escAttr(f.id || ('f' + idx));
+ const sev = escAttr(f.severity);
+ return '<div class="finding-card" id="finding-' + id + '">' +
+ '<div class="finding-header">' +
+ (f.severity ? '<span class="severity severity-' + sev + '">' + sevLabel(f.severity) + '</span>' : '') +
+ '<span class="finding-title">' + esc(f.title) + '</span>' +
+ (f.tag ? '<span class="finding-tag">' + esc(f.tag) + '</span>' : '') +
+ '<span class="finding-chevron">&#9654;</span>' +
+ '</div>' +
+ '<div class="finding-body">' +
+ (f.location ? '<div style="margin-top:10px;font-size:12px;"><span class="field-label">Location:</span> <code style="background:var(--surface2);padding:1px 5px;border-radius:3px;">' + esc(f.location) + '</code></div>' : '') +
+ (f.details ? '<div style="margin-top:10px;font-size:12px;line-height:1.7;">' + escMultiline(f.details) + '</div>' : '') +
+ (f.reasoning ? '<div style="margin-top:10px;"><div class="field-label">Why this matters</div><div class="reasoning-block">' + escMultiline(f.reasoning) + '</div></div>' : '') +
+ (f.fix ? '<div style="margin-top:8px;"><div class="field-label">Suggested Fix</div><div class="fix-block">' + escMultiline(f.fix) + '</div></div>' : '') +
+ '</div>' +
+ '</div>';
+}
+
+function detailsHtml(d) {
+ if (!d) return '';
+ if (d.kind === 'table' && Array.isArray(d.columns) && Array.isArray(d.rows)) {
+ let h = '<table class="detail-table"><thead><tr>';
+ d.columns.forEach((c) => h += '<th>' + esc(c) + '</th>');
+ h += '</tr></thead><tbody>';
+ d.rows.forEach((r) => { h += '<tr>' + r.map((cell) => '<td>' + (cell == null ? '' : esc(cell)) + '</td>').join('') + '</tr>'; });
+ h += '</tbody></table>';
+ return '<h3>' + esc(d.label || 'Details') + '</h3>' + h;
+ }
+ if (d.kind === 'kv' && Array.isArray(d.entries)) {
+ let h = '<div class="card"><dl class="kv-list">';
+ d.entries.forEach((e) => h += '<dt>' + esc(e.key) + '</dt><dd>' + esc(e.value) + '</dd>');
+ h += '</dl></div>';
+ return '<h3>' + esc(d.label || 'Details') + '</h3>' + h;
+ }
+ return '';
+}
+
+function sectionHtml(s) {
+ // Sort only when at least one finding has severity; otherwise preserve insertion order (inventory sections).
+ const order = { critical:0, high:0, warning:1, medium:1, info:2, low:2, pass:3 };
+ const findings = (s.findings || []).some(f => f.severity)
+ ? (s.findings || []).slice().sort((a, b) => (order[a.severity] ?? 99) - (order[b.severity] ?? 99))
+ : (s.findings || []);
+
+ let html = '<div class="section" id="tab-' + escAttr(s.id) + '">' +
+ '<h2>' + esc(s.label) + '</h2>' +
+ (s.description ? '<p class="section-desc">' + esc(s.description) + '</p>' : '') +
+ (findings.length ? findings.map(findingHtml).join('') : '<div class="card" style="color:var(--text-dim)">Nothing to report for this section.</div>') +
+ detailsHtml(s.details) +
+ '</div>';
+ return html;
+}
+
+// Stat-card metadata for every severity that may appear on findings.
+// Same precedence ordering used everywhere (critical → high → warning → medium → info → low → pass).
+const STAT_CARDS = [
+ { key: 'critical', label: 'Critical', color: 'var(--critical)' },
+ { key: 'high', label: 'High', color: 'var(--critical)' },
+ { key: 'warning', label: 'Warning', color: 'var(--warning)' },
+ { key: 'medium', label: 'Medium', color: 'var(--warning)' },
+ { key: 'info', label: 'Info', color: 'var(--info)' },
+ { key: 'low', label: 'Low', color: 'var(--info)' },
+ { key: 'pass', label: 'Passed', color: 'var(--pass)' },
+];
+// Severities that count as "issues" for the sidebar badge.
+const ISSUE_KEYS = new Set(['critical', 'high', 'warning', 'medium']);
+
+// Overview section
+function overviewHtml() {
+ const t = REVIEW_DATA.totals || {};
+ const cards = STAT_CARDS
+ .filter(c => (t[c.key] || 0) > 0)
+ .map(c => '<div class="stat-card"><div class="stat-num" style="color:' + c.color + '">' + (t[c.key] || 0) + '</div><div class="stat-label">' + c.label + '</div></div>')
+ .join('');
+ return '<div class="section active" id="tab-overview">' +
+ '<h2>' + esc(REPORT_NAME) + '</h2>' +
+ '<p class="section-desc">' + esc(GOAL_LABEL || '') + ' — ' + esc(SCOPE_LABEL) + '</p>' +
+ (cards ? '<div class="stats-grid">' + cards + '</div>' : '') +
+ '<h3>Summary</h3><div class="card" style="line-height:1.75;">' + esc(REVIEW_DATA.summary) + '</div>' +
+ (REVIEW_DATA.nextSteps && REVIEW_DATA.nextSteps.length ? ('<h3>Recommended next steps</h3><div class="card"><ol class="next-steps">' + REVIEW_DATA.nextSteps.map((n) => '<li>' + esc(n) + '</li>').join('') + '</ol></div>') : '') +
+ '</div>';
+}
+
+// Compose content + sidebar
+const content = [overviewHtml()];
+const navHtml = ['<div class="nav-group-label">Overview</div>'];
+navHtml.push('<button class="nav-btn active" data-tab="overview"><span class="nav-icon">●</span> Overview</button>');
+navHtml.push('<div class="nav-group-label">Sections</div>');
+
+(REVIEW_DATA.sections || []).forEach((s) => {
+ const issues = (s.findings || []).reduce((acc, f) => acc + (ISSUE_KEYS.has(f.severity) ? 1 : 0), 0);
+ navHtml.push('<button class="nav-btn" data-tab="' + escAttr(s.id) + '"><span class="nav-icon">' + esc(s.icon || '▦') + '</span> ' + esc(s.label) + (issues > 0 ? '<span class="nav-badge" style="background:var(--critical-bg);color:var(--critical);">' + issues + '</span>' : '') + '</button>');
+ content.push(sectionHtml(s));
+});
+
+document.getElementById('sidebar').innerHTML = navHtml.join('');
+document.getElementById('contentRoot').innerHTML = content.join('');
+
+document.querySelectorAll('.nav-btn').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ document.querySelectorAll('.nav-btn').forEach((b) => b.classList.remove('active'));
+ btn.classList.add('active');
+ document.querySelectorAll('.section').forEach((s) => s.classList.remove('active'));
+ const target = document.getElementById('tab-' + escAttr(btn.dataset.tab));
+ if (target) target.classList.add('active');
+ window.scrollTo({ top: 0, behavior: 'smooth' });
+ });
+});
+
+document.addEventListener('click', (e) => {
+ const header = e.target.closest('.finding-header');
+ if (header) { header.closest('.finding-card').classList.toggle('expanded'); }
+});
+</script>
+</body>
+</html>
diff --git a/plugins/power-pages/scripts/render-review.js b/plugins/power-pages/scripts/render-review.js
new file mode 100644
index 000000000..1b00885f5
--- /dev/null
+++ b/plugins/power-pages/scripts/render-review.js
@@ -0,0 +1,46 @@
+#!/usr/bin/env node
+/**
+ * render-review.js — Renders a security-review HTML report (consolidated or single-section)
+ * from a JSON data file produced by build-review-data.js.
+ *
+ * Used by security-review (multi-section) and by scan-site for its standalone
+ * report (single-section). Same template, same UX.
+ *
+ * Usage:
+ * node render-review.js --output <path> --data <json-file>
+ *
+ * Required keys in the JSON data file:
+ * REPORT_NAME, SITE_NAME, GOAL_LABEL, SCOPE_LABEL, GENERATED_AT, REVIEW_DATA
+ */
+
+const path = require('path');
+const { renderTemplate, parseArgs } = require('./lib/render-template');
+
+const TEMPLATE_PATH = path.join(__dirname, 'lib', 'templates', 'security-review-report.html');
+const REQUIRED_KEYS = [
+ 'REPORT_NAME',
+ 'SITE_NAME',
+ 'GOAL_LABEL',
+ 'SCOPE_LABEL',
+ 'GENERATED_AT',
+ 'REVIEW_DATA',
+];
+
+function main() {
+ const args = parseArgs(process.argv);
+ if (!args.output || !args.data) {
+ process.stderr.write('Usage: node render-review.js --output <path> --data <json-file>\n');
+ process.exit(1);
+ }
+
+ renderTemplate({
+ templatePath: TEMPLATE_PATH,
+ outputPath: path.resolve(args.output),
+ dataPath: path.resolve(args.data),
+ requiredKeys: REQUIRED_KEYS,
+ });
+}
+
+if (require.main === module) {
+ main();
+}
diff --git a/plugins/power-pages/scripts/tests/build-review-data.test.js b/plugins/power-pages/scripts/tests/build-review-data.test.js
new file mode 100644
index 000000000..142b4c748
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/build-review-data.test.js
@@ -0,0 +1,299 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const { spawnSync } = require('child_process');
+
+const {
+ buildSections,
+ formatGeneratedAt,
+ SECTION_MAP,
+ SEVERITIES,
+} = require('../build-review-data');
+
+const SCRIPT = path.join(__dirname, '..', 'build-review-data.js');
+
+function withTempDir(t) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'brd-test-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ return dir;
+}
+
+function writeJson(dir, name, value) {
+ fs.writeFileSync(path.join(dir, name), JSON.stringify(value));
+}
+
+function runCli(args, env = {}) {
+ return spawnSync(process.execPath, [SCRIPT, ...args], {
+ encoding: 'utf8',
+ env: { ...process.env, ...env },
+ });
+}
+
+test('SECTION_MAP recognizes the five known per-skill files', () => {
+ const expected = [
+ 'scan-site.json',
+ 'manage-headers.json',
+ 'manage-firewall.json',
+ 'audit-permissions.json',
+ 'setup-auth.json',
+ ];
+ for (const file of expected) {
+ assert.ok(SECTION_MAP[file], `${file} missing from SECTION_MAP`);
+ assert.equal(typeof SECTION_MAP[file].id, 'string');
+ assert.equal(typeof SECTION_MAP[file].label, 'string');
+ }
+});
+
+test('SEVERITIES lists the seven supported severity buckets in precedence order', () => {
+ assert.deepEqual(SEVERITIES, [
+ 'critical',
+ 'high',
+ 'warning',
+ 'medium',
+ 'info',
+ 'low',
+ 'pass',
+ ]);
+});
+
+test('buildSections skips files not in SECTION_MAP', (t) => {
+ const dir = withTempDir(t);
+ writeJson(dir, 'unknown.json', { status: 'ok', findings: [] });
+ writeJson(dir, 'next-steps.json', ['step1']);
+
+ const result = buildSections(dir, 'data.json');
+ assert.deepEqual(result.sections, []);
+});
+
+test('buildSections ignores the configured output basename', (t) => {
+ const dir = withTempDir(t);
+ writeJson(dir, 'scan-site.json', { status: 'ok', findings: [], details: {} });
+ writeJson(dir, 'data.json', { REVIEW_DATA: {} });
+
+ const result = buildSections(dir, 'data.json');
+ assert.equal(result.sections.length, 1);
+ assert.equal(result.sections[0].id, 'site-scan');
+});
+
+test('buildSections aggregates findings into severity totals', (t) => {
+ const dir = withTempDir(t);
+ writeJson(dir, 'scan-site.json', {
+ status: 'ok',
+ findings: [
+ { id: 'a', severity: 'critical', title: 't' },
+ { id: 'b', severity: 'high', title: 't' },
+ { id: 'c', severity: 'warning', title: 't' },
+ { id: 'd', severity: 'warning', title: 't' },
+ { id: 'e', severity: 'medium', title: 't' },
+ { id: 'f', severity: 'info', title: 't' },
+ { id: 'g', severity: 'low', title: 't' },
+ { id: 'h', severity: 'pass', title: 't' },
+ ],
+ details: {},
+ });
+
+ const { sections, totals } = buildSections(dir, 'data.json');
+ assert.equal(sections.length, 1);
+ assert.equal(totals.critical, 1);
+ assert.equal(totals.high, 1);
+ assert.equal(totals.warning, 2);
+ assert.equal(totals.medium, 1);
+ assert.equal(totals.info, 1);
+ assert.equal(totals.low, 1);
+ assert.equal(totals.pass, 1);
+});
+
+test('buildSections renders skipped status without a severity field', (t) => {
+ const dir = withTempDir(t);
+ writeJson(dir, 'manage-firewall.json', {
+ status: 'skipped',
+ reason: 'sign-in required',
+ });
+
+ const { sections, totals } = buildSections(dir, 'data.json');
+ assert.equal(sections.length, 1);
+ assert.equal(sections[0].id, 'firewall');
+ assert.equal(sections[0].findings.length, 1);
+ assert.ok(!('severity' in sections[0].findings[0]));
+ assert.equal(sections[0].findings[0].details, 'sign-in required');
+ for (const sev of SEVERITIES) {
+ assert.equal(totals[sev], 0, `totals.${sev} should be 0 for skipped-only run`);
+ }
+});
+
+test('buildSections defaults skipped reason when missing', (t) => {
+ const dir = withTempDir(t);
+ writeJson(dir, 'scan-site.json', { status: 'skipped' });
+
+ const { sections } = buildSections(dir, 'data.json');
+ assert.equal(sections[0].findings[0].details, 'No additional detail.');
+});
+
+test('buildSections skips files that are not valid JSON', (t) => {
+ const dir = withTempDir(t);
+ fs.writeFileSync(path.join(dir, 'scan-site.json'), '{not json');
+
+ const { sections } = buildSections(dir, 'data.json');
+ assert.deepEqual(sections, []);
+});
+
+test('buildSections treats unknown severity values as non-counting', (t) => {
+ const dir = withTempDir(t);
+ writeJson(dir, 'scan-site.json', {
+ status: 'ok',
+ findings: [
+ { id: 'x', severity: 'unrecognized', title: 't' },
+ { id: 'y', severity: 'warning', title: 't' },
+ ],
+ details: {},
+ });
+
+ const { totals } = buildSections(dir, 'data.json');
+ assert.equal(totals.warning, 1);
+ assert.equal(totals.unrecognized, undefined);
+});
+
+test('buildSections defaults missing findings array to empty', (t) => {
+ const dir = withTempDir(t);
+ writeJson(dir, 'scan-site.json', { status: 'ok' });
+
+ const { sections } = buildSections(dir, 'data.json');
+ assert.deepEqual(sections[0].findings, []);
+});
+
+test('formatGeneratedAt produces YYYY-MM-DD HH:MM:SS plus a timezone abbreviation', () => {
+ const originalTz = process.env.TZ;
+ process.env.TZ = 'UTC';
+ try {
+ const stamp = formatGeneratedAt(new Date('2026-05-26T03:04:05Z'));
+ assert.match(stamp, /^2026-05-26 03:04:05 [A-Z][A-Z0-9+/:-]+$/);
+ } finally {
+ if (originalTz === undefined) delete process.env.TZ;
+ else process.env.TZ = originalTz;
+ }
+});
+
+test('buildSections returns no sections and zero totals for an empty directory', (t) => {
+ const dir = withTempDir(t);
+ const { sections, totals } = buildSections(dir, 'data.json');
+ assert.deepEqual(sections, []);
+ for (const sev of SEVERITIES) {
+ assert.equal(totals[sev], 0);
+ }
+});
+
+test('CLI exits 1 with a clear message when a required flag is missing', () => {
+ const result = runCli([
+ '--reportName',
+ 'X',
+ '--inputDir',
+ '.',
+ '--siteName',
+ 'Y',
+ '--goalLabel',
+ 'Z',
+ '--scopeLabel',
+ 'W',
+ ]);
+ assert.equal(result.status, 1, `stderr: ${result.stderr}`);
+ assert.match(result.stderr, /Missing required flag: --output/);
+});
+
+test('CLI exits 1 when --inputDir does not exist', (t) => {
+ const tmp = withTempDir(t);
+ const result = runCli([
+ '--reportName',
+ 'X',
+ '--inputDir',
+ path.join(tmp, 'no-such-dir'),
+ '--siteName',
+ 'Y',
+ '--goalLabel',
+ 'Z',
+ '--scopeLabel',
+ 'W',
+ '--output',
+ path.join(tmp, 'data.json'),
+ ]);
+ assert.equal(result.status, 1, `stderr: ${result.stderr}`);
+ assert.match(result.stderr, /Input dir not found/);
+});
+
+test('CLI --help writes usage to stdout and exits 0', () => {
+ const result = runCli(['--help']);
+ assert.equal(result.status, 0, `stderr: ${result.stderr}`);
+ assert.match(result.stdout, /build-review-data\.js/);
+ assert.match(result.stdout, /Usage:/);
+});
+
+test('CLI writes the data file and a status line to stdout', (t) => {
+ const inputDir = withTempDir(t);
+ writeJson(inputDir, 'scan-site.json', {
+ status: 'ok',
+ findings: [{ id: 'a', severity: 'warning', title: 't' }],
+ details: {},
+ });
+ const outPath = path.join(inputDir, 'data.json');
+
+ const result = runCli([
+ '--reportName',
+ 'Security Review',
+ '--inputDir',
+ inputDir,
+ '--siteName',
+ 'Demo',
+ '--goalLabel',
+ 'release',
+ '--scopeLabel',
+ 'site',
+ '--output',
+ outPath,
+ ]);
+ assert.equal(result.status, 0, `stderr: ${result.stderr}`);
+ const status = JSON.parse(result.stdout);
+ assert.equal(status.status, 'ok');
+ assert.equal(status.sectionsCount, 1);
+ assert.equal(status.totals.warning, 1);
+
+ const written = JSON.parse(fs.readFileSync(outPath, 'utf8'));
+ assert.equal(written.REPORT_NAME, 'Security Review');
+ assert.equal(written.SITE_NAME, 'Demo');
+ assert.equal(written.REVIEW_DATA.sections.length, 1);
+});
+
+test('CLI reads --nextStepsFile and folds entries into REVIEW_DATA.nextSteps', (t) => {
+ const inputDir = withTempDir(t);
+ writeJson(inputDir, 'scan-site.json', { status: 'ok', findings: [], details: {} });
+
+ const nextStepsPath = path.join(inputDir, 'next-steps.json');
+ fs.writeFileSync(
+ nextStepsPath,
+ JSON.stringify(['Fix CSP wildcard', 'Enable rate limiting', 42, null])
+ );
+ const outPath = path.join(inputDir, 'data.json');
+
+ const result = runCli([
+ '--reportName',
+ 'X',
+ '--inputDir',
+ inputDir,
+ '--siteName',
+ 'Y',
+ '--goalLabel',
+ 'Z',
+ '--scopeLabel',
+ 'W',
+ '--output',
+ outPath,
+ '--nextStepsFile',
+ nextStepsPath,
+ ]);
+ assert.equal(result.status, 0, `stderr: ${result.stderr}`);
+ const written = JSON.parse(fs.readFileSync(outPath, 'utf8'));
+ assert.deepEqual(written.REVIEW_DATA.nextSteps, [
+ 'Fix CSP wildcard',
+ 'Enable rate limiting',
+ ]);
+});
diff --git a/plugins/power-pages/scripts/tests/power-platform-api.test.js b/plugins/power-pages/scripts/tests/power-platform-api.test.js
new file mode 100644
index 000000000..302f48199
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/power-platform-api.test.js
@@ -0,0 +1,255 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const {
+ parseCliArgs,
+ parseTimeoutMs,
+ hasErrorCode,
+ isFeatureUnsupported,
+ pollUntil,
+ DEFAULT_POLL_TIMEOUT_MS,
+ DEFAULT_POLL_INTERVAL_MS,
+} = require('../lib/power-platform-api');
+
+test('parseCliArgs reads value flags', () => {
+ const out = parseCliArgs(['node', 'script', '--portalId', 'abc', '--name', 'foo']);
+ assert.equal(out.portalId, 'abc');
+ assert.equal(out.name, 'foo');
+});
+
+test('parseCliArgs treats a flag with no value as a boolean', () => {
+ const out = parseCliArgs(['node', 'script', '--once', '--portalId', 'abc']);
+ assert.equal(out.once, true);
+ assert.equal(out.portalId, 'abc');
+});
+
+test('parseCliArgs treats a flag followed by another flag as a boolean', () => {
+ const out = parseCliArgs(['node', 'script', '--reinstall', '--name', 'x']);
+ assert.equal(out.reinstall, true);
+ assert.equal(out.name, 'x');
+});
+
+test('parseCliArgs ignores positional arguments', () => {
+ const out = parseCliArgs(['node', 'script', 'positional', '--name', 'x', 'tail']);
+ assert.equal(out.name, 'x');
+ assert.equal(out.positional, undefined);
+});
+
+test('parseTimeoutMs uses default when value is undefined', () => {
+ assert.equal(parseTimeoutMs(undefined, 15), 15 * 60 * 1000);
+});
+
+test('parseTimeoutMs accepts a numeric string', () => {
+ assert.equal(parseTimeoutMs('30', 15), 30 * 60 * 1000);
+});
+
+test('parseTimeoutMs accepts a number', () => {
+ assert.equal(parseTimeoutMs(45, 15), 45 * 60 * 1000);
+});
+
+// parseTimeoutMs calls fail() → process.exit(1) on rejection. The helper
+// intercepts both so the test process does not actually terminate, restores
+// them in finally, and returns the captured exit code + stderr.
+function runRejectingValue(value) {
+ const originalExit = process.exit;
+ const originalStderrWrite = process.stderr.write;
+ let exitCode = null;
+ let stderr = '';
+ process.exit = (code) => {
+ exitCode = code;
+ throw new Error('__exit__');
+ };
+ process.stderr.write = (chunk) => {
+ stderr += chunk;
+ return true;
+ };
+ try {
+ assert.throws(() => parseTimeoutMs(value, 15), /__exit__/);
+ } finally {
+ process.exit = originalExit;
+ process.stderr.write = originalStderrWrite;
+ }
+ return { exitCode, stderr };
+}
+
+for (const value of ['abc', '0', '-1', '-0.5', 'NaN', '']) {
+ test(`parseTimeoutMs exits the process on invalid value ${JSON.stringify(value)}`, () => {
+ const { exitCode, stderr } = runRejectingValue(value);
+ assert.equal(exitCode, 1);
+ assert.match(stderr, /Invalid --timeoutMinutes/);
+ });
+}
+
+test('hasErrorCode matches any status when the error code matches', () => {
+ assert.equal(
+ hasErrorCode({ statusCode: 409, error: { code: 'B003' } }, 'B003'),
+ true
+ );
+ assert.equal(
+ hasErrorCode({ statusCode: 400, error: { code: 'B022' } }, 'B022', 'B023'),
+ true
+ );
+ assert.equal(
+ hasErrorCode({ statusCode: 500, error: { code: 'B022' } }, 'B022'),
+ true,
+ 'status is ignored; only the code is matched'
+ );
+});
+
+test('hasErrorCode returns false when no code matches', () => {
+ assert.equal(
+ hasErrorCode({ statusCode: 400, error: { code: 'OTHER' } }, 'B022', 'B023'),
+ false
+ );
+ assert.equal(hasErrorCode({ statusCode: 200, error: undefined }, 'B022'), false);
+});
+
+test('isFeatureUnsupported matches the documented error codes', () => {
+ assert.equal(
+ isFeatureUnsupported({ statusCode: 400, error: { code: 'B022' } }, 'B022', 'B023'),
+ true
+ );
+ assert.equal(
+ isFeatureUnsupported({ statusCode: 400, error: { code: 'B023' } }, 'B022', 'B023'),
+ true
+ );
+});
+
+test('isFeatureUnsupported falls back to the message regex on 400', () => {
+ assert.equal(
+ isFeatureUnsupported(
+ { statusCode: 400, error: { code: 'OTHER', message: 'feature not supported in region' } },
+ 'B022',
+ 'B023'
+ ),
+ true
+ );
+});
+
+test('isFeatureUnsupported does not match the message fallback on non-400 responses', () => {
+ assert.equal(
+ isFeatureUnsupported(
+ { statusCode: 500, error: { code: 'OTHER', message: 'feature not supported' } },
+ 'B022'
+ ),
+ false
+ );
+});
+
+test('exposes the documented polling defaults', () => {
+ // Pinned so a silent change to either constant is caught.
+ assert.equal(DEFAULT_POLL_TIMEOUT_MS, 10 * 60 * 1000);
+ assert.equal(DEFAULT_POLL_INTERVAL_MS, 5000);
+});
+
+// Stubs global.setTimeout so the sleep between attempts completes instantly
+// while still capturing the delay the caller requested. The original is
+// restored in finally so an assertion failure cannot leak the stub.
+function captureSleepDelays(fn) {
+ const originalSetTimeout = global.setTimeout;
+ const captured = [];
+ global.setTimeout = (cb, ms) => {
+ captured.push(ms);
+ return originalSetTimeout(cb, 0);
+ };
+ return Promise.resolve()
+ .then(() => fn(captured))
+ .finally(() => {
+ global.setTimeout = originalSetTimeout;
+ });
+}
+
+test('pollUntil applies DEFAULT_POLL_INTERVAL_MS when intervalMs is omitted', async () => {
+ let isDoneCalls = 0;
+ const captured = [];
+ await captureSleepDelays(async (delays) => {
+ const result = await pollUntil({
+ fetchStatus: async () => ({ ok: true, body: 'pending' }),
+ isDone: () => ++isDoneCalls >= 3,
+ timeoutMs: 60_000,
+ });
+ captured.push(...delays);
+ assert.equal(result.ok, true);
+ assert.equal(result.body, 'pending');
+ assert.equal(result.attempts, 3);
+ });
+
+ // Three attempts → exactly two sleep calls between them.
+ assert.equal(captured.length, 2);
+ for (const delay of captured) {
+ assert.equal(delay, DEFAULT_POLL_INTERVAL_MS);
+ }
+});
+
+test('pollUntil honors a caller-supplied intervalMs', async () => {
+ const customInterval = 1234;
+ let isDoneCalls = 0;
+ const captured = [];
+ await captureSleepDelays(async (delays) => {
+ await pollUntil({
+ fetchStatus: async () => ({ ok: true, body: 'pending' }),
+ isDone: () => ++isDoneCalls >= 2,
+ timeoutMs: 60_000,
+ intervalMs: customInterval,
+ });
+ captured.push(...delays);
+ });
+
+ assert.equal(captured.length, 1);
+ assert.equal(captured[0], customInterval);
+});
+
+test('pollUntil returns ok=true when isDone matches on first attempt', async () => {
+ const result = await pollUntil({
+ fetchStatus: async () => ({ ok: true, body: 'done' }),
+ isDone: (status) => status === 'done',
+ timeoutMs: 1000,
+ intervalMs: 10,
+ });
+ assert.equal(result.ok, true);
+ assert.equal(result.body, 'done');
+ assert.equal(result.attempts, 1);
+});
+
+test('pollUntil polls until isDone returns true', async () => {
+ const responses = ['pending', 'pending', 'done'];
+ let i = 0;
+ const result = await pollUntil({
+ fetchStatus: async () => ({ ok: true, body: responses[i++] }),
+ isDone: (status) => status === 'done',
+ timeoutMs: 1000,
+ intervalMs: 1,
+ });
+ assert.equal(result.ok, true);
+ assert.equal(result.attempts, 3);
+});
+
+test('pollUntil returns timeout when isDone never matches', async () => {
+ const result = await pollUntil({
+ fetchStatus: async () => ({ ok: true, body: 'pending' }),
+ isDone: () => false,
+ timeoutMs: 30,
+ intervalMs: 5,
+ });
+ assert.equal(result.ok, false);
+ assert.equal(result.error, 'timeout');
+ assert.ok(result.attempts >= 1);
+});
+
+test('pollUntil short-circuits on a fetchStatus error', async () => {
+ let isDoneCalls = 0;
+ const result = await pollUntil({
+ fetchStatus: async () => ({ ok: false, error: 'service unavailable' }),
+ isDone: () => {
+ isDoneCalls += 1;
+ return true;
+ },
+ timeoutMs: 1000,
+ intervalMs: 5,
+ });
+ assert.equal(result.ok, false);
+ assert.equal(result.error, 'service unavailable');
+ // Short-circuit MUST fire before isDone is evaluated, on the first fetch.
+ assert.equal(result.attempts, 1);
+ assert.equal(isDoneCalls, 0);
+});
diff --git a/plugins/power-pages/scripts/tests/render-review.test.js b/plugins/power-pages/scripts/tests/render-review.test.js
new file mode 100644
index 000000000..7c80bb84f
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/render-review.test.js
@@ -0,0 +1,139 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const { spawnSync } = require('child_process');
+
+const SCRIPT = path.join(__dirname, '..', 'render-review.js');
+
+const REQUIRED_KEYS = [
+ 'REPORT_NAME',
+ 'SITE_NAME',
+ 'GOAL_LABEL',
+ 'SCOPE_LABEL',
+ 'GENERATED_AT',
+ 'REVIEW_DATA',
+];
+
+function withTempDir(t) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rr-test-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ return dir;
+}
+
+function runRenderReview(args) {
+ return spawnSync(process.execPath, [SCRIPT, ...args], { encoding: 'utf8' });
+}
+
+function fullDataPayload() {
+ return {
+ REPORT_NAME: 'Security Review',
+ SITE_NAME: 'Test Site',
+ GOAL_LABEL: 'Release readiness',
+ SCOPE_LABEL: 'Full site',
+ GENERATED_AT: '2026-05-26 12:00:00',
+ REVIEW_DATA: {
+ summary: 'All clear.',
+ totals: { critical: 0, warning: 0, info: 0, pass: 1 },
+ sections: [
+ {
+ id: 'site-scan',
+ icon: '◐',
+ label: 'Live Site Scan',
+ findings: [],
+ details: {},
+ },
+ ],
+ nextSteps: [],
+ },
+ };
+}
+
+test('exits 1 when --output is missing', () => {
+ const result = runRenderReview(['--data', 'whatever.json']);
+ assert.equal(result.status, 1, `stderr: ${result.stderr}`);
+ assert.match(result.stderr, /Usage:/);
+});
+
+test('exits 1 when --data is missing', () => {
+ const result = runRenderReview(['--output', 'whatever.html']);
+ assert.equal(result.status, 1, `stderr: ${result.stderr}`);
+ assert.match(result.stderr, /Usage:/);
+});
+
+test('exits 1 when --data file does not exist', (t) => {
+ const dir = withTempDir(t);
+ const result = runRenderReview([
+ '--output',
+ path.join(dir, 'out.html'),
+ '--data',
+ path.join(dir, 'missing.json'),
+ ]);
+ assert.equal(result.status, 1, `stderr: ${result.stderr}`);
+ assert.match(result.stderr, /ENOENT|not found|missing/i);
+});
+
+test('exits 1 when --data file contains unparseable JSON', (t) => {
+ const dir = withTempDir(t);
+ const dataPath = path.join(dir, 'data.json');
+ fs.writeFileSync(dataPath, '{not valid json');
+
+ const result = runRenderReview([
+ '--output',
+ path.join(dir, 'out.html'),
+ '--data',
+ dataPath,
+ ]);
+ assert.equal(result.status, 1, `stderr: ${result.stderr}`);
+ assert.match(result.stderr, /JSON|parse|unexpected/i);
+});
+
+for (const key of REQUIRED_KEYS) {
+ test(`exits 1 when required key "${key}" is missing from the data file`, (t) => {
+ const dir = withTempDir(t);
+ const dataPath = path.join(dir, 'data.json');
+ const incomplete = fullDataPayload();
+ delete incomplete[key];
+ fs.writeFileSync(dataPath, JSON.stringify(incomplete));
+
+ const result = runRenderReview([
+ '--output',
+ path.join(dir, 'out.html'),
+ '--data',
+ dataPath,
+ ]);
+ assert.equal(result.status, 1, `stderr: ${result.stderr}`);
+ assert.ok(
+ result.stderr.includes(key),
+ `stderr should name the missing key "${key}", got: ${result.stderr}`
+ );
+ });
+}
+
+test('renders the shared security-review template when given a full data payload', (t) => {
+ const dir = withTempDir(t);
+ const dataPath = path.join(dir, 'data.json');
+ const outPath = path.join(dir, 'out.html');
+ fs.writeFileSync(dataPath, JSON.stringify(fullDataPayload()));
+
+ const result = runRenderReview(['--output', outPath, '--data', dataPath]);
+ assert.equal(result.status, 0, `stderr: ${result.stderr}`);
+
+ const html = fs.readFileSync(outPath, 'utf8');
+ const expectedSubstrings = [
+ ['REPORT_NAME', 'Security Review'],
+ ['SITE_NAME', 'Test Site'],
+ ['summary', 'All clear.'],
+ // REVIEW_DATA payload — section label must reach the rendered HTML so a
+ // regression that drops REVIEW_DATA substitution is caught even when the
+ // placeholder is also removed.
+ ['REVIEW_DATA section label', 'Live Site Scan'],
+ ];
+ for (const [label, value] of expectedSubstrings) {
+ assert.ok(html.includes(value), `rendered HTML must include ${label} value "${value}"`);
+ }
+ for (const placeholder of ['__REPORT_NAME__', '__SITE_NAME__', '__REVIEW_DATA__']) {
+ assert.ok(!html.includes(placeholder), `${placeholder} must be substituted`);
+ }
+});
diff --git a/plugins/power-pages/scripts/tests/website.test.js b/plugins/power-pages/scripts/tests/website.test.js
new file mode 100644
index 000000000..e27b56d9e
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/website.test.js
@@ -0,0 +1,186 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('path');
+
+const WEBSITE_PATH = path.resolve(__dirname, '..', 'website.js');
+const API_PATH = path.resolve(__dirname, '..', 'lib', 'power-platform-api.js');
+
+// Loads website.js with the `power-platform-api` module replaced by a stub.
+// Uses require.cache injection (not Module._resolveFilename patching) so the
+// override is contained, exception-safe, and uses only documented Node APIs.
+function loadWebsiteWithStubs({ pages, contextError }) {
+ const stub = {
+ resolveContext: () =>
+ contextError ? { error: contextError } : { baseUrl: 'http://stub', token: 't' },
+ request: async ({ query }) => {
+ const skip = query?.skip ? Number.parseInt(query.skip, 10) : 0;
+ const page = pages.find((p) => p.skip === skip) || pages[pages.length - 1];
+ if (page.networkError) {
+ return {
+ ok: false,
+ statusCode: 0,
+ body: null,
+ headers: {},
+ error: { code: 'NetworkError', message: page.networkError },
+ };
+ }
+ return { ok: true, statusCode: 200, body: page.body, headers: {} };
+ },
+ parseCliArgs: () => ({}),
+ fail: () => {
+ throw new Error('fail() should not run during unit tests');
+ },
+ runCli: () => {},
+ };
+
+ delete require.cache[WEBSITE_PATH];
+ require.cache[API_PATH] = {
+ id: API_PATH,
+ filename: API_PATH,
+ loaded: true,
+ exports: stub,
+ children: [],
+ paths: [],
+ };
+
+ try {
+ return require(WEBSITE_PATH);
+ } finally {
+ delete require.cache[WEBSITE_PATH];
+ delete require.cache[API_PATH];
+ }
+}
+
+test('nextSkipFrom returns the parsed offset from an @odata.nextLink', () => {
+ const { nextSkipFrom } = loadWebsiteWithStubs({ pages: [] });
+ assert.equal(nextSkipFrom('https://api.example.com/websites?select=Id&skip=20'), 20);
+ assert.equal(nextSkipFrom('https://api.example.com/websites?skip=100&top=10'), 100);
+});
+
+test('nextSkipFrom returns null when the link is missing or malformed', () => {
+ const { nextSkipFrom } = loadWebsiteWithStubs({ pages: [] });
+ assert.equal(nextSkipFrom(undefined), null);
+ assert.equal(nextSkipFrom(null), null);
+ assert.equal(nextSkipFrom(''), null);
+ assert.equal(nextSkipFrom('https://api.example.com/websites'), null);
+ assert.equal(nextSkipFrom('https://api.example.com/websites?skip=abc'), null);
+ // Non-positive offsets are treated as missing so the pagination loop
+ // terminates rather than re-fetching the same page.
+ assert.equal(nextSkipFrom('https://api.example.com/websites?skip=0'), null);
+});
+
+test('recordIdOf reads WebsiteRecordId or its camelCase variant', () => {
+ const { recordIdOf } = loadWebsiteWithStubs({ pages: [] });
+ assert.equal(recordIdOf({ WebsiteRecordId: 'abc' }), 'abc');
+ assert.equal(recordIdOf({ websiteRecordId: 'xyz' }), 'xyz');
+ assert.equal(recordIdOf({ Id: 'p1' }), null);
+ assert.equal(recordIdOf(null), null);
+ assert.equal(recordIdOf('string'), null);
+});
+
+test('findWebsite returns the matching site on the first page', async () => {
+ const id = 'AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE';
+ const { findWebsite } = loadWebsiteWithStubs({
+ pages: [
+ {
+ skip: 0,
+ body: {
+ value: [
+ { Id: 'p1', WebsiteRecordId: '11111111-2222-3333-4444-555555555555' },
+ { Id: 'p2', WebsiteRecordId: id },
+ ],
+ },
+ },
+ ],
+ });
+
+ const result = await findWebsite(id);
+ assert.equal(result.Id, 'p2');
+});
+
+test('findWebsite matches case-insensitively', async () => {
+ const upperId = 'AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE';
+ const lowerId = upperId.toLowerCase();
+ const { findWebsite } = loadWebsiteWithStubs({
+ pages: [{ skip: 0, body: { value: [{ Id: 'p1', WebsiteRecordId: lowerId }] } }],
+ });
+
+ const result = await findWebsite(upperId);
+ assert.equal(result.Id, 'p1');
+});
+
+test('findWebsite follows @odata.nextLink across pages', async () => {
+ const target = 'TARGET-ID';
+ const { findWebsite } = loadWebsiteWithStubs({
+ pages: [
+ {
+ skip: 0,
+ body: {
+ value: [{ Id: 'p1', WebsiteRecordId: 'other-1' }],
+ '@odata.nextLink': 'https://api/websites?skip=10',
+ },
+ },
+ {
+ skip: 10,
+ body: {
+ value: [{ Id: 'p2', WebsiteRecordId: 'other-2' }],
+ '@odata.nextLink': 'https://api/websites?skip=20',
+ },
+ },
+ {
+ skip: 20,
+ body: { value: [{ Id: 'p3', WebsiteRecordId: target }] },
+ },
+ ],
+ });
+
+ const result = await findWebsite(target);
+ assert.equal(result.Id, 'p3');
+});
+
+test('findWebsite returns null when no page contains the websiteId', async () => {
+ const { findWebsite } = loadWebsiteWithStubs({
+ pages: [{ skip: 0, body: { value: [{ Id: 'p1', WebsiteRecordId: 'other' }] } }],
+ });
+ assert.equal(await findWebsite('not-present'), null);
+});
+
+test('findWebsite stops pagination when the server fails to advance skip', async () => {
+ // Server returns the same nextLink twice — the loop must terminate rather
+ // than spin forever.
+ const { findWebsite } = loadWebsiteWithStubs({
+ pages: [
+ {
+ skip: 0,
+ body: {
+ value: [{ Id: 'p1', WebsiteRecordId: 'other' }],
+ '@odata.nextLink': 'https://api/websites?skip=0',
+ },
+ },
+ ],
+ });
+ const result = await findWebsite('not-present');
+ assert.equal(result, null);
+});
+
+test('findWebsite throws when the request fails', async () => {
+ const { findWebsite } = loadWebsiteWithStubs({
+ pages: [{ skip: 0, networkError: 'connection refused' }],
+ });
+ await assert.rejects(() => findWebsite('any-id'), /List websites failed/);
+});
+
+test('findWebsite throws when context resolution fails', async () => {
+ const { findWebsite } = loadWebsiteWithStubs({
+ pages: [],
+ contextError: 'Power Platform CLI is not signed in',
+ });
+ await assert.rejects(() => findWebsite('any-id'), /CLI is not signed in/);
+});
+
+test('findWebsite rejects empty or non-string websiteId', async () => {
+ const { findWebsite } = loadWebsiteWithStubs({ pages: [] });
+ await assert.rejects(() => findWebsite(''), /must be a non-empty string/);
+ await assert.rejects(() => findWebsite(null), /must be a non-empty string/);
+ await assert.rejects(() => findWebsite(undefined), /must be a non-empty string/);
+});
diff --git a/plugins/power-pages/scripts/website.js b/plugins/power-pages/scripts/website.js
new file mode 100644
index 000000000..6e915ea20
--- /dev/null
+++ b/plugins/power-pages/scripts/website.js
@@ -0,0 +1,143 @@
+#!/usr/bin/env node
+/**
+ * website.js — Resolves a Power Pages website record against the Power Platform API.
+ *
+ * Two distinct identifiers float around in the codebase. They look the same
+ * (both are GUIDs) but they are not interchangeable:
+ *
+ * websiteId The Dataverse website record id. This is what
+ * `.powerpages-site/website.yml` stores as `id`, what
+ * `pac pages list` surfaces as "Website Record ID", and
+ * therefore what user-facing CLI flags accept. It maps to the
+ * `WebsiteRecordId` field on the Power Platform API response.
+ *
+ * portalId The Power Platform API URL segment. Every per-site admin call
+ * (`/websites/{id}/...`) takes this value. It maps to the
+ * `Id` field on the Power Platform API response.
+ *
+ * The skill calls this helper once during prerequisites to translate the
+ * Dataverse `websiteId` into the Power Platform API portalId for the rest of the run.
+ *
+ * Usage:
+ * node website.js --websiteId <guid>
+ *
+ * Stdout (JSON): the matching website record, or `null`.
+ *
+ * Exit codes:
+ * 0 = success (including a `null` match)
+ * 1 = invocation or service error
+ * 2 = sign-in required
+ */
+
+const {
+ resolveContext,
+ request,
+ parseCliArgs,
+ fail,
+ runCli,
+} = require('./lib/power-platform-api');
+
+// Hard cap on pagination — far above any realistic site count. Exists only
+// so a misbehaving server cannot keep the helper looping forever.
+const MAX_PAGES = 500;
+
+// Field projection sent to the Power Platform API. Covers everything the skill needs
+// from the response (portalId via `Id`, the websiteId echo via
+// `WebsiteRecordId`, plus the metadata used for trial-site warnings, summaries,
+// and the report header).
+const FIELDS = [
+ 'Id',
+ 'Name',
+ 'WebsiteRecordId',
+ 'WebsiteUrl',
+ 'Type',
+ 'status',
+ 'Subdomain',
+ 'SiteVisibility',
+ 'PortalWAFStatus',
+ 'PortalAFDStatus',
+ 'TrialExpiringInDays',
+].join(',');
+
+const SIGN_IN_HINT = /CLI is not signed in|Failed to acquire access token/;
+
+/**
+ * Returns the next `skip` value embedded in an `@odata.nextLink`, or `null`
+ * when the link is missing, malformed, or carries a non-positive offset.
+ */
+function nextSkipFrom(nextLink) {
+ if (typeof nextLink !== 'string') return null;
+ const match = nextLink.match(/[?&]skip=(\d+)/i);
+ if (!match) return null;
+ const value = Number.parseInt(match[1], 10);
+ return Number.isInteger(value) && value > 0 ? value : null;
+}
+
+/**
+ * Reads the Dataverse record id from a website record, tolerating PascalCase
+ * (the documented shape) and any normalized casing a future server might use.
+ */
+function recordIdOf(website) {
+ if (!website || typeof website !== 'object') return null;
+ return website.WebsiteRecordId || website.websiteRecordId || null;
+}
+
+/**
+ * Resolves a Dataverse `websiteId` to its full website record by paginating
+ * `/websites` and matching on `WebsiteRecordId` (case-insensitive — tolerates
+ * GUID casing differences between local YAML, `pac pages list`, and the
+ * Power Platform API response).
+ *
+ * @param {string} websiteId
+ * @returns {Promise<object|null>}
+ */
+async function findWebsite(websiteId) {
+ if (typeof websiteId !== 'string' || websiteId.length === 0) {
+ throw new Error('websiteId must be a non-empty string.');
+ }
+ const target = websiteId.toLowerCase();
+ const context = resolveContext();
+ if (context.error) throw new Error(context.error);
+
+ let skip;
+ for (let page = 0; page < MAX_PAGES; page += 1) {
+ const query = { select: FIELDS };
+ if (skip !== undefined) query.skip = String(skip);
+
+ const response = await request({ context, method: 'GET', path: '/websites', query });
+ if (!response.ok) {
+ throw new Error(`List websites failed (${response.statusCode}): ${response.error?.message || ''}`);
+ }
+
+ const body = response.body && typeof response.body === 'object' ? response.body : {};
+ for (const site of body.value || []) {
+ const id = recordIdOf(site);
+ if (typeof id === 'string' && id.toLowerCase() === target) return site;
+ }
+
+ const advance = nextSkipFrom(body['@odata.nextLink'] || body.nextLink);
+ // null = no more pages; non-advancing = malformed server response → stop either way.
+ if (advance == null || advance <= (skip ?? 0)) break;
+ skip = advance;
+ }
+
+ return null;
+}
+
+async function main() {
+ const args = parseCliArgs(process.argv);
+ if (typeof args.websiteId !== 'string') {
+ fail('Usage: node website.js --websiteId <guid>', 1);
+ }
+ try {
+ const website = await findWebsite(args.websiteId);
+ process.stdout.write(JSON.stringify(website, null, 2) + '\n');
+ } catch (err) {
+ const message = err.message || String(err);
+ fail(message, SIGN_IN_HINT.test(message) ? 2 : 1);
+ }
+}
+
+module.exports = { findWebsite, nextSkipFrom, recordIdOf };
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/audit-permissions/assets/audit-report.html b/plugins/power-pages/skills/audit-permissions/assets/audit-report.html
index 68645b8eb..cdb18951e 100644
--- a/plugins/power-pages/skills/audit-permissions/assets/audit-report.html
+++ b/plugins/power-pages/skills/audit-permissions/assets/audit-report.html
@@ -175,7 +175,7 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi
<p class="section-desc" id="findingsDesc"></p>
<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;">
<div class="filter-bar" id="filterBar" style="margin-bottom:0;"></div>
- <button class="filter-btn" id="expandAllBtn" onclick="toggleExpandAll()" style="white-space:nowrap;">Expand All</button>
+ <button class="filter-btn" id="expandAllBtn" style="white-space:nowrap;">Expand All</button>
</div>
<div id="findingsContainer" style="margin-top:16px;"></div>
</div>
@@ -251,6 +251,8 @@ document.querySelectorAll('.nav-btn').forEach(btn => {
});
// Severity config
+function esc(s) { if (!s) return ''; return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;'); }
+function escAttr(s) { return String(s || '').replace(/[^a-zA-Z0-9_.-]/g, ''); }
const sevConfig = {
critical: { color: 'var(--critical)', label: 'CRITICAL', icon: '\u2716' },
warning: { color: 'var(--warning)', label: 'WARNING', icon: '\u26A0' },
@@ -290,7 +292,7 @@ function renderFilterBar() {
let html = '';
Object.entries(labels).forEach(([key, label]) => {
if (counts[key] === 0 && key !== 'all') return;
- html += `<button class="filter-btn ${activeFilter === key ? 'active' : ''}" onclick="setFilter('${key}')">${label}<span class="filter-count">${counts[key]}</span></button>`;
+ html += '<button class="filter-btn ' + (activeFilter === key ? 'active' : '') + '" data-filter="' + escAttr(key) + '">' + esc(label) + '<span class="filter-count">' + counts[key] + '</span></button>';
});
c.innerHTML = html;
}
@@ -305,28 +307,29 @@ function renderFindings() {
const c = document.getElementById('findingsContainer');
const filtered = activeFilter === 'all' ? FINDINGS : FINDINGS.filter(f => f.severity === activeFilter);
- // Sort: critical first, then warning, info, pass
const order = { critical: 0, warning: 1, info: 2, pass: 3 };
const sorted = [...filtered].sort((a, b) => (order[a.severity] ?? 99) - (order[b.severity] ?? 99));
let html = '';
sorted.forEach(f => {
const sev = sevConfig[f.severity] || sevConfig.info;
- html += `<div class="finding-card" id="finding-${f.id}">
- <div class="finding-header" onclick="document.getElementById('finding-${f.id}').classList.toggle('expanded')">
- <span class="severity severity-${f.severity}">${sev.label}</span>
- <span class="finding-title">${f.title}</span>
- ${f.table ? `<span class="finding-table">${f.table}</span>` : ''}
- <span class="finding-chevron">&#9654;</span>
- </div>
- <div class="finding-body">
- ${f.permission ? `<div style="margin-top:10px;font-size:12px;"><span class="field-label">Permission:</span> <span style="font-weight:600;color:var(--text-bright)">${f.permission}</span></div>` : ''}
- ${f.scope ? `<div style="margin-top:6px;font-size:12px;"><span class="field-label">Scope:</span> <span class="scope-tag scope-${scopeName(f.scope)}" style="font-size:10px;padding:1px 6px;min-width:auto;">${scopeName(f.scope)}</span></div>` : ''}
- ${f.details ? `<div style="margin-top:10px;font-size:12px;color:var(--text);line-height:1.7;">${f.details}</div>` : ''}
- ${f.reasoning ? `<div style="margin-top:10px;"><div class="field-label">Reasoning</div><div class="reasoning-block">${f.reasoning}</div></div>` : ''}
- ${f.fix ? `<div style="margin-top:8px;"><div class="field-label">Suggested Fix</div><div class="fix-block"><strong>Fix:</strong> ${f.fix}</div></div>` : ''}
- </div>
- </div>`;
+ const fid = escAttr(f.id);
+ const fsev = escAttr(f.severity);
+ html += '<div class="finding-card" id="finding-' + fid + '">' +
+ '<div class="finding-header">' +
+ '<span class="severity severity-' + fsev + '">' + esc(sev.label) + '</span>' +
+ '<span class="finding-title">' + esc(f.title) + '</span>' +
+ (f.table ? '<span class="finding-table">' + esc(f.table) + '</span>' : '') +
+ '<span class="finding-chevron">&#9654;</span>' +
+ '</div>' +
+ '<div class="finding-body">' +
+ (f.permission ? '<div style="margin-top:10px;font-size:12px;"><span class="field-label">Permission:</span> <span style="font-weight:600;color:var(--text-bright)">' + esc(f.permission) + '</span></div>' : '') +
+ (f.scope ? '<div style="margin-top:6px;font-size:12px;"><span class="field-label">Scope:</span> <span class="scope-tag scope-' + escAttr(scopeName(f.scope)) + '" style="font-size:10px;padding:1px 6px;min-width:auto;">' + esc(scopeName(f.scope)) + '</span></div>' : '') +
+ (f.details ? '<div style="margin-top:10px;font-size:12px;color:var(--text);line-height:1.7;">' + esc(f.details) + '</div>' : '') +
+ (f.reasoning ? '<div style="margin-top:10px;"><div class="field-label">Reasoning</div><div class="reasoning-block">' + esc(f.reasoning) + '</div></div>' : '') +
+ (f.fix ? '<div style="margin-top:8px;"><div class="field-label">Suggested Fix</div><div class="fix-block"><strong>Fix:</strong> ' + esc(f.fix) + '</div></div>' : '') +
+ '</div>' +
+ '</div>';
});
if (sorted.length === 0) {
@@ -357,18 +360,28 @@ function renderInventory() {
let html = '<table class="inv-table"><thead><tr><th>Permission Name</th><th>Table</th><th>Scope</th><th>Roles</th><th>Privileges</th></tr></thead><tbody>';
INVENTORY.forEach(p => {
const flags = { Read: p.read, Create: p.create, Write: p.write, Delete: p.delete, Append: p.append, AppendTo: p.appendto };
- html += `<tr>
- <td style="font-weight:600;color:var(--text-bright)">${p.name}</td>
- <td><code style="font-size:11px;color:var(--accent);background:var(--accent-bg);padding:1px 5px;border-radius:3px;border:1px solid var(--accent-border);">${p.table}</code></td>
- <td><span class="scope-tag scope-${scopeName(p.scope)}" style="font-size:9px;padding:1px 6px;min-width:auto;">${scopeName(p.scope)}</span></td>
- <td style="font-size:12px;">${Array.isArray(p.roles) ? p.roles.join(', ') : p.roles}</td>
- <td style="display:flex;gap:3px;flex-wrap:wrap;">${privs.map(pr => `<span class="priv ${flags[pr] ? 'priv-on' : 'priv-off'}">${pr[0]}${pr === 'AppendTo' ? 'T' : ''}</span>`).join('')}</td>
- </tr>`;
+ html += '<tr>' +
+ '<td style="font-weight:600;color:var(--text-bright)">' + esc(p.name) + '</td>' +
+ '<td><code style="font-size:11px;color:var(--accent);background:var(--accent-bg);padding:1px 5px;border-radius:3px;border:1px solid var(--accent-border);">' + esc(p.table) + '</code></td>' +
+ '<td><span class="scope-tag scope-' + escAttr(scopeName(p.scope)) + '" style="font-size:9px;padding:1px 6px;min-width:auto;">' + esc(scopeName(p.scope)) + '</span></td>' +
+ '<td style="font-size:12px;">' + (Array.isArray(p.roles) ? esc(p.roles.join(', ')) : esc(p.roles)) + '</td>' +
+ '<td style="display:flex;gap:3px;flex-wrap:wrap;">' + privs.map(function(pr) { return '<span class="priv ' + (flags[pr] ? 'priv-on' : 'priv-off') + '">' + pr[0] + (pr === 'AppendTo' ? 'T' : '') + '</span>'; }).join('') + '</td>' +
+ '</tr>';
});
html += '</tbody></table>';
c.innerHTML = html;
}
+document.getElementById('expandAllBtn').addEventListener('click', toggleExpandAll);
+
+// Event delegation — no inline onclick handlers
+document.addEventListener('click', function(e) {
+ var btn = e.target.closest('.filter-btn[data-filter]');
+ if (btn) { setFilter(btn.dataset.filter); return; }
+ var hdr = e.target.closest('.finding-header');
+ if (hdr) { hdr.closest('.finding-card').classList.toggle('expanded'); }
+});
+
// Init
renderFilterBar();
renderFindings();
diff --git a/plugins/power-pages/skills/deploy-site/SKILL.md b/plugins/power-pages/skills/deploy-site/SKILL.md
index fdf0a954c..6d446d5e0 100644
--- a/plugins/power-pages/skills/deploy-site/SKILL.md
+++ b/plugins/power-pages/skills/deploy-site/SKILL.md
@@ -283,7 +283,7 @@ Use `AskUserQuestion` to confirm before proceeding:
node "${CLAUDE_PLUGIN_ROOT}/scripts/clear-site-cache.js" --projectRoot "<PROJECT_ROOT>"
```
-The script reads `siteName` from `powerpages.config.json`, looks up the website via the Power Platform admin API, and restarts it to flush the runtime cache.
+The script reads `siteName` from `powerpages.config.json`, looks up the website via the Power Platform API, and restarts it to flush the runtime cache.
Evaluate the result:
diff --git a/plugins/power-pages/skills/manage-firewall/SKILL.md b/plugins/power-pages/skills/manage-firewall/SKILL.md
new file mode 100644
index 000000000..a55abde9e
--- /dev/null
+++ b/plugins/power-pages/skills/manage-firewall/SKILL.md
@@ -0,0 +1,288 @@
+---
+name: manage-firewall
+description: >-
+ Inspects and configures the web application firewall (WAF) in front of a
+ Power Pages production site. Lists the current state, recommends enabling
+ protection when it is off, and walks the user through adding, updating,
+ or removing custom rules — IP blocks, country blocks, path blocks, and
+ rate limits. Use when the user wants to turn on WAF, block traffic by
+ IP or country, rate-limit login or signup pages, protect pages from
+ brute-force attempts, restrict access to specific paths, review the
+ current firewall configuration, or asks "is my site protected against
+ bots / common web attacks?" — even if they say "add rate limit" or
+ "protect login page" without mentioning "firewall" or "WAF".
+user-invocable: true
+argument-hint: "[optional: --review <out-dir>]"
+allowed-tools: Read, Write, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList
+model: opus
+---
+
+> **Plugin check**: Run `node "${CLAUDE_PLUGIN_ROOT}/scripts/check-version.js"` — if it outputs a message, show it to the user before proceeding.
+
+# Manage Web Application Firewall
+
+Configure the firewall for a Power Pages production site. The firewall is only available on production sites and in supported regions — the scripts detect and report eligibility issues. After rule changes, edge propagation takes up to one hour.
+
+**Initial request:** $ARGUMENTS
+
+## Gotchas
+
+- **Website record id vs portal id.** `.powerpages-site/website.yml` stores the website record id, not the portal id. Every script takes `--portalId`. Resolve once via `website.js --websiteId` during prerequisites.
+- **Never resolve by name.** Site names can duplicate; only the website record id is safe.
+- **Async operations.** `enable.js` and `disable.js` poll until the status reaches the target value (or timeout). `delete-rules.js` returns immediately (202) — verify via `get-rules.js`.
+- **Concurrent-operation guard.** `B003` means another enable/disable is in flight. Poll status until it settles, then retry.
+- **False-positive managed rule:** disable via a rule override (`EnabledState: "Disabled"` inside `RuleGroupOverrides` — managed rule fields use PascalCase).
+- **First-match-wins.** Rules evaluate in priority order. A geo-allow-then-default-deny pattern requires an explicit default-deny rule AFTER the allow.
+- **Custom rule priority range: 11–65000.** Values 1–10 are reserved for platform-managed rules.
+- **`set-rules.js` is additive / update-only.** Send only rules being created or modified. The service merges them; existing rules not in the payload are untouched.
+- **Use `delete-rules.js` to remove rules.** `set-rules.js` cannot remove. Always use `delete-rules.js --names`.
+- **WAF state semantics — `Created` is the only "enabled" state.** `get-status.js` returns `value: "Created"` when the firewall is enabled and actively filtering (counter-intuitive — the API does NOT use `"Enabled"`). Any other value (`Disabled`, `None`, `Enabling`, `Disabling`, `Failed`) means no active policy exists. **MUST** call `get-status.js` first and only invoke `get-rules.js` when `value` is `Created` — otherwise the rules endpoint returns a 500 and the whole firewall section gets skipped in the report.
+
+## Workflow
+
+1. **Prerequisites** — Locate project, confirm sign-in, identify site, check eligibility
+2. **Check firewall state** — Capture status and rules
+3. **Choose an action** — Context-aware recommendation or question
+4. **Apply the change** — Run the matching script, verify
+5. **Summarize and next steps** — Present result, record usage, offer follow-ups
+
+## Task Tracking
+
+Create tasks in three groups. Mark each `in_progress` when starting, `completed` when done.
+
+| Group | When to create | Tasks |
+|-------|----------------|-------|
+| 1 | At start | Check prerequisites |
+| 2 | After prerequisites pass | Check firewall state · Choose an action (skip in review mode) |
+| 3 | After user confirms an action | Apply the change (skip in review mode OR no change action was chosen) · Summarize and next steps (always) |
+
+---
+
+## 1. Prerequisites
+
+### 1.1 Locate the project, detect review mode
+
+Use `Glob` to find `**/powerpages.config.json`. If `$ARGUMENTS` contains `--review <out-dir>`, remember the output directory — Steps 3–4 are skipped and Step 5 writes JSON only.
+
+### 1.2 Resolve site identifiers
+
+Read `.powerpages-site/website.yml` → extract `id` field → that is `<WEBSITE_ID>`.
+
+If missing, the site has not been deployed. Tell the user and recommend `/deploy-site`. Stop. Do **not** resolve by name or URL.
+
+Resolve to portalId:
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/scripts/website.js" --websiteId "<WEBSITE_ID>"
+```
+
+Capture `Id` (portalId), `Type`, `Name`, `WebsiteUrl`. If exit code `2` → sign-in required (`pac auth create` or `az login`). If `null` → site not found in this environment. Stop in either case.
+
+### 1.3 Eligibility
+
+Check the `Type` field and the script responses for eligibility. The scripts return specific error codes for ineligible sites (non-production, unsupported region, restricted feature). Read `references/commands.md` § "Common error catalogue" and § "Regional availability" for the full list.
+
+If the site is ineligible, tell the user in plain language what the limitation is and stop.
+
+---
+
+## 2. Check firewall state
+
+### 2.1 Get status (always run first)
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/manage-firewall/scripts/get-status.js" --portalId "<PORTAL_ID>"
+```
+
+The response shape is `{ "status": "ok", "value": "<state>" }`.
+
+- `Created` — WAF is enabled and filtering. Proceed to **2.2** to fetch rules.
+- Any other value (`Disabled`, `None`, `Enabling`, `Disabling`, `Failed`, etc.) — **WAF is not enabled**. **MUST NOT** call `get-rules.js` — the rules endpoint will return a 500 because no active policy exists to read. Skip **2.2** and treat the rules payload as empty: `{ "status": "ok", "body": { "CustomRules": [], "ManagedRules": [] } }`.
+
+If the status response is `"status": "unsupported"`, tell the user the firewall is not available and stop.
+
+### 2.2 Get rules (only when WAF is enabled)
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/manage-firewall/scripts/get-rules.js" --portalId "<PORTAL_ID>"
+```
+
+Both scripts output the full response as JSON to stdout. If `get-rules.js` returns `"status": "unsupported"`, tell the user the firewall is not available and stop.
+
+---
+
+## 3. Choose an action
+
+Skip in **review mode**.
+
+MUST use plain language only with the user. Never use words like WAF, OWASP, ModSec, ruleset, geo-block, rate-limit, ASN, SocketAddr, or rule priority.
+
+Each `AskUserQuestion` call is a **separate** call. Wait for the user's answer before asking the next.
+
+### Default approach
+
+Analyze the site's current state (firewall status, existing custom rules, managed rules, region eligibility) and **recommend the single most relevant action**. Present the recommendation with a plain-language explanation of why. The user can accept, choose a different action, or ask to just view the current state.
+
+- Firewall off → recommend enabling it.
+- Firewall on, no custom rules → recommend adding a rule if there is a clear gap (e.g., no rate limiting). Otherwise, summarize the state and ask if the user wants to add a rule.
+- Firewall on, rules exist → summarize what is configured and ask what the user wants to do.
+
+If the site's state does not warrant a specific recommendation, do not force one — ask what the user wants to do.
+
+MUST NOT proactively offer actions that reduce security (disabling the firewall, removing managed rules, weakening existing rules). If the user needs those, they will ask.
+
+### Option rules
+
+When presenting options via `AskUserQuestion`:
+- Keep `label` to 1–5 words. Include `description` on every option.
+- Include `preview` **only** when the option represents a concrete change (create, update, or delete a rule) — use it to show the configuration that will be applied so the user can review before approving. Do not add `preview` to navigation or informational choices.
+- Only show options that are actionable given the current state. Omit options for features the site cannot use (check `references/commands.md` § "Regional availability").
+- Mark "(Recommended)" only when there is a genuine, context-based reason. If nothing stands out, do not mark any.
+- When offering to add a rule type that already exists on the site, acknowledge it in the `description` — include the count and summarize what is configured so the user can decide whether to add or update.
+- For path-based rules, reference actual page paths from the project structure when known. Fall back to generic language only when no project context is available.
+
+### Rule type follow-up
+
+When the user picks "Add a rule", ask a follow-up for the rule type. The same option rules apply. Translate the answer into `set-rules.js` parameters — keep the user out of priority-numbering and rule-naming details. Read `references/rule-reference.md` for rule shapes.
+
+### Remove a rule
+
+List current custom rules showing: what each rule does (plain language), what traffic it matches, whether it blocks or allows, and its priority relative to others. If removing a rule would break a deny/allow pattern, warn before proceeding.
+
+### Plan-validate-execute
+
+For all rule changes:
+
+1. **Plan** — build the JSON payload containing only the rules being added or updated.
+2. **Validate** — check the plan against the existing rule set and surface:
+ - Priority conflicts with existing rules
+ - Overlapping match conditions (same `matchVariable`/`operator`, overlapping `matchValue`) — explain which rule wins via first-match-wins
+ - Contradictions between Allow and Block rules — flag and explain priority implications
+ - Redundancy — suggest updating the existing rule instead of adding a duplicate
+3. **Execute** — apply only after user approval.
+
+For deletions, show the rule names and what each currently does before proceeding.
+
+In **review mode**, skip this step entirely.
+
+---
+
+## 4. Apply the change
+
+Skip in **review mode**.
+
+| Action | Script |
+|--------|--------|
+| Enable | `enable.js --portalId <id>` |
+| Disable | `disable.js --portalId <id>` |
+| Add / update rules | `set-rules.js --portalId <id> --data-inline '<json>'` |
+| Remove rules | `delete-rules.js --portalId <id> --names <comma-separated>` |
+
+Run enable/disable with `run_in_background: true` (async operations with built-in polling).
+
+Before applying, show only the disclosure relevant to the action being taken:
+- **Enabling:** managed rule set enforces immediately; some legitimate requests may be blocked until reviewed.
+- **Disabling:** site is unprotected until re-enabled.
+- **Adding / updating rules:** propagation takes up to an hour. If the rule uses Allow, explain it creates an exception even when block rules would apply.
+- **Deleting rules:** matched traffic is no longer blocked (or allowed). If the rule was an Allow exception in a deny pattern, warn that traffic will now be blocked.
+- **Disabling a managed rule:** that attack category is no longer inspected — name the category.
+
+After completion, re-run status and rules calls to verify the new state.
+
+---
+
+## 5. Summarize and next steps
+
+### 5.1 Review mode
+
+Apply the same status-then-rules gating as § 2 — `get-rules.js` MUST only be invoked when the status `value` is `Created`. For any other value the WAF policy does not exist and the rules endpoint will return 500; the orchestrator must write the empty-rules payload directly instead of calling the script.
+
+**Step A — always run status:**
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/manage-firewall/scripts/get-status.js" --portalId "<PORTAL_ID>" > "<REVIEW_DIR>/firewall-status.json"
+```
+
+**Step B — branch on the captured `value`:**
+
+- If `value` is `Created`, fetch rules:
+
+ ```bash
+ node "${CLAUDE_PLUGIN_ROOT}/skills/manage-firewall/scripts/get-rules.js" --portalId "<PORTAL_ID>" > "<REVIEW_DIR>/firewall-rules.json"
+ ```
+
+- Otherwise (`Disabled`, `None`, `Enabling`, `Disabling`, `Failed`, anything else), do NOT call `get-rules.js`. Write the empty-rules payload yourself:
+
+ ```json
+ { "status": "ok", "body": { "CustomRules": [], "ManagedRules": [] } }
+ ```
+
+After capturing the raw output, **read both files** and write `<REVIEW_DIR>/firewall-annotations.json` with plain-language descriptions of the state and each rule (the transform script no longer hardcodes these — they come from you):
+
+```json
+{
+ "state": {
+ "description": "Plain-language explanation of what \"<value>\" means — is the firewall actively filtering requests, or not?",
+ "fix": "Optional — include only if the state genuinely needs action."
+ },
+ "rules": {
+ "<RuleName>": { "description": "What this rule does, in plain language.", "fix": "Optional fix if the rule has a genuine issue." }
+ }
+}
+```
+
+Power Pages WAF state semantics (use these when writing the state description — do not invent meanings):
+- `Created` — WAF is enabled. The firewall is active and filtering requests.
+- `Disabled` — WAF is not enabled and no firewall policy exists. The site is unprotected.
+- `None` — no firewall policy has ever been provisioned. Same user-facing meaning as `Disabled`.
+- `Enabling` / `Disabling` — operation in progress; wait.
+- `Failed` — last enable/disable operation failed.
+
+Then run the transform:
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/manage-firewall/scripts/transform-firewall.js" \
+ --statusFile "<REVIEW_DIR>/firewall-status.json" \
+ --rulesFile "<REVIEW_DIR>/firewall-rules.json" \
+ --annotations "<REVIEW_DIR>/firewall-annotations.json"
+```
+
+Write the transform stdout to `<REVIEW_DIR>/manage-firewall.json` and stop. The transform emits `{ status, findings }`; the orchestrating skill handles presentation.
+
+### 5.2 Present summary
+
+Plain-language summary: firewall on/off, rule count, what changed, important gaps.
+
+### 5.3 Record skill usage
+
+> Reference: `${CLAUDE_PLUGIN_ROOT}/references/skill-tracking-reference.md`
+>
+> Use `--skillName "ManageFirewall"`.
+
+### 5.4 Offer follow-ups
+
+If a natural follow-up action exists based on the site's verified post-action state, suggest it. Do not offer actions that reduce security. If no meaningful follow-up exists, end the skill — do not ask just to ask.
+
+---
+
+## Constraints
+
+- **Plain language** — MUST NOT use technical jargon with the user. Use everyday language; explain the technical name only when asked.
+- **Eligibility** — MUST short-circuit on ineligible sites (non-production, unsupported region). The scripts detect these — read `references/commands.md` for the full error catalogue.
+- **Background ops** — MUST run enable/disable via `run_in_background`.
+- **Send only what changes** — `set-rules.js` payload MUST contain only new or modified rules.
+- **Rule naming** — PascalCase, letters and numbers only (e.g., `BlockCountries`, `AllowOfficeIP`).
+- **No company names** — use generic names in rule examples.
+- **Context-aware interactions** — every question, option, follow-up, and disclosure MUST reflect the site's current state:
+ - Never offer options that don't apply (e.g., "Remove a rule" when none exist).
+ - Acknowledge existing rules of the same type when offering to add a new one.
+ - Reference actual site page paths in descriptions when known from the project.
+ - Check new rules against existing rules for conflicts, overlaps, contradictions, and redundancy before presenting the plan.
+ - Show only the disclosure relevant to the action being taken.
+ - Never proactively suggest reducing protection.
+- **Preview is for change review only** — include `preview` only on options representing a concrete change the user needs to approve. Do not add to navigation or informational choices.
+
+## References
+
+- `references/commands.md` — script flags, response shapes, error catalogue, regional availability. Read § "Common error catalogue" when a script returns a non-zero exit code. Read § "Regional availability" during eligibility checks.
+- `references/rule-reference.md` — field-level schema for custom rules, match conditions, managed rule overrides, match variables, operators, and priority bands. Read when building a rule plan.
diff --git a/plugins/power-pages/skills/manage-firewall/references/commands.md b/plugins/power-pages/skills/manage-firewall/references/commands.md
new file mode 100644
index 000000000..d1cde8c0d
--- /dev/null
+++ b/plugins/power-pages/skills/manage-firewall/references/commands.md
@@ -0,0 +1,285 @@
+# Manage Web Application Firewall — Commands
+
+Reference for the helper scripts under `scripts/`. All scripts use the shared power-platform-api client, share the same authentication failure mode (exit code `2`), and support `--help` to display usage, flags, and exit codes.
+
+## Table of contents
+
+- [Identifiers — websiteId vs. portalId](#identifiers--websiteid-vs-portalid)
+- [`get-status.js`](#get-statusjs)
+- [`get-rules.js`](#get-rulesjs)
+- [`enable.js`](#enablejs)
+- [`disable.js`](#disablejs)
+- [`set-rules.js`](#set-rulesjs)
+- [`delete-rules.js`](#delete-rulesjs)
+- [`transform-firewall.js`](#transform-firewalljs)
+- [Common error catalogue](#common-error-catalogue)
+- [Body schema](#body-schema)
+
+---
+
+## Identifiers — websiteId vs. portalId
+
+Two different GUIDs identify a Power Pages site:
+
+| Identifier | Where it comes from | What it is |
+|------------|---------------------|------------|
+| `websiteId` | `.powerpages-site/website.yml` (`id` field), `pac pages list` ("Website Record ID") | Dataverse website record primary key. The user-facing identifier. |
+| `portalId` | `Id` field on the `/websites` Power Platform API response | The `{id}` segment in Power Platform API URL paths such as `/websites/{id}/enableWaf`. |
+
+The skill resolves `websiteId` → `portalId` once during prerequisites by reading `.powerpages-site/website.yml` and calling `${CLAUDE_PLUGIN_ROOT}/scripts/website.js --websiteId <guid>`. It reuses the resolved `portalId` for the rest of the run. The consumer scripts in this folder accept `--portalId` only — they never look up the site themselves.
+
+If `.powerpages-site/website.yml` does not exist, the site has not been deployed yet. The skill does **not** try to identify the site by name or URL (two sites in the same environment can share a name, and the URL changes when the subdomain is updated) — it directs the user to `/deploy-site` and stops.
+
+Run `node "${CLAUDE_PLUGIN_ROOT}/scripts/website.js" --help` for the full contract.
+
+---
+
+## `get-status.js`
+
+Returns the current firewall status (None/ Enabling / Created / Disabled / Disabling / Failed). **Only `Created` indicates the firewall is active/ enabled**.
+
+### Usage
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/manage-firewall/scripts/get-status.js" --portalId <portal-id>
+```
+
+### Response (stdout)
+
+```json
+{ "status": "ok", "value": "<status>" }
+```
+
+…or, when the feature is unavailable for this site:
+
+```json
+{ "status": "unsupported", "message": "Power Pages built-in WAF feature is not supported in <region>" }
+```
+
+The response JSON is written to stdout.
+
+### Errors
+
+| Status / `code` | Meaning |
+|-----------------|---------|
+| `400 / B022` | Region does not offer the firewall |
+| `400 / B023` | Trial site — convert to production first |
+| `400 / A001` | Site not found |
+
+---
+
+## `get-rules.js`
+
+Returns the full firewall configuration (managed rule sets and custom rules).
+
+### Usage
+
+> **Important:** call `get-status.js` first and only invoke this script when the WAF is enabled (i.e. `Created`). When `get-status.js` returns `Disabled`, `None`, or `Failed`, no policy is provisioned and this endpoint will return a 500. Treat that case as "no rules configured" without calling this script.
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/manage-firewall/scripts/get-rules.js" --portalId <portal-id> [--ruleType <name>]
+```
+
+### Parameters
+
+| Flag | Required | Description |
+|----------------|----------|-------------|
+| `--portalId` | Yes | Power Platform API portalId resolved during prerequisites |
+| `--ruleType` | No | Optional filter — `Custom` or `Managed`. Omit for both. |
+
+### Response (stdout)
+
+```json
+{ "status": "ok", "body": { "CustomRules": [...], "ManagedRules": [...] } }
+```
+
+---
+
+## `enable.js`
+
+Turns the firewall on. The underlying operation is asynchronous — the script polls the status endpoint until the value becomes `Created` (the only "enabled" terminal state — see [`get-status.js`](#get-statusjs)) or the timeout elapses.
+
+### Usage
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/manage-firewall/scripts/enable.js" --portalId <portal-id> [--timeoutMinutes <n>]
+```
+
+### Parameters
+
+| Flag | Required | Default | Description |
+|-----------------------|----------|---------|-------------|
+| `--portalId` | Yes | — | Power Platform API portalId resolved during prerequisites |
+| `--timeoutMinutes` | No | `15` | Maximum time to wait for the operation to complete. |
+
+### Response (stdout)
+
+```json
+{ "status": "enabled", "attempts": "<count>" }
+```
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| `0` | Enabled |
+| `2` | Sign-in required |
+| `3` | Polling timed out |
+| `4` | Unsupported (trial / region) |
+| `1` | Service or network failure |
+
+### Notes
+
+- The service may return `409 / B003` if a previous operation is still in progress. The script treats that as "wait and poll" rather than a hard failure.
+
+---
+
+## `disable.js`
+
+Mirror of `enable.js` — turns the firewall off and polls until status is `Disabled`. Same parameters and exit codes; stdout reports `{ "status": "disabled", "attempts": "<count>" }`.
+
+---
+
+## `set-rules.js`
+
+Creates or updates firewall rules. Send only the rules being added or modified. Existing rules not included in the payload are left untouched.
+
+### Usage
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/manage-firewall/scripts/set-rules.js" --portalId <portal-id> --data-inline '<json>'
+```
+
+### Parameters
+
+| Flag | Required | Description |
+|------------------|----------|-------------|
+| `--portalId` | Yes | Power Platform API portalId resolved during prerequisites |
+| `--data-inline` | Yes | JSON string with `CustomRules` and/or `ManagedRules` arrays. |
+
+### Payload shape
+
+The JSON MUST be an object with `CustomRules` and/or `ManagedRules` arrays. Do NOT pass a bare array.
+
+Both arrays are optional — omit one to leave that part of the configuration untouched. Within each array, include only the rules being created or updated; existing rules not in the payload are preserved by the service.
+
+See `rule-reference.md` for the full field-level schema: custom rules, match conditions, managed rule sets, and rule group overrides.
+
+### Response (stdout)
+
+```json
+{ "status": "ok", "body": { /* updated rule configuration */ } }
+```
+
+### Errors
+
+| Status / `code` | Meaning |
+|-----------------|---------|
+| `400 / B022` | Feature unavailable in region |
+| `400 / B023` | Trial site |
+| `400 / A010` | Invalid rule shape — service rejects payload |
+| `404 / A001` | Site not found |
+| `409 / B003` | Another operation is in progress — wait and retry after the in-flight operation completes |
+| `0` (no response) | Request timed out — retry after a delay |
+
+---
+
+## `delete-rules.js`
+
+Deletes one or more **custom** rules by name. Managed rule sets are not affected.
+
+### Usage
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/manage-firewall/scripts/delete-rules.js" --portalId <portal-id> --names <name1,name2,...>
+```
+
+### Response (stdout)
+
+```json
+{ "status": "accepted", "deleted": ["<rule-name>"] }
+```
+
+The deletion is asynchronous; the response is `202 Accepted`. To confirm the change, re-run `get-rules.js` after a short delay.
+
+---
+
+## `transform-firewall.js`
+
+Transforms `get-status.js` and `get-rules.js` stdout into the unified findings shape used by the consolidated security review. Read-only — does not call the service.
+
+### Usage
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/manage-firewall/scripts/transform-firewall.js" --statusFile <status-file> --rulesFile <rules-file>
+```
+
+### Parameters
+
+| Flag | Required | Description |
+|------|----------|-------------|
+| `--statusFile` | Yes | Path to a saved `get-status.js` stdout JSON file. |
+| `--rulesFile` | Yes | Path to a saved `get-rules.js` stdout JSON file. |
+
+### Response (stdout)
+
+```json
+{ "status": "ok", "findings": [ ] }
+```
+
+…or, when the firewall is not available for the site:
+
+```json
+{ "status": "unsupported", "findings": [ ] }
+```
+
+Each finding has the inventory shape `{ id, title, tag, details }` — no `severity` (the section is informational; the orchestrator does not roll these up into severity totals).
+
+---
+
+## Common error catalogue
+
+These error codes appear across the firewall scripts. Map them to friendly messages before showing them to the user.
+
+| Code | Script exit | Meaning | Friendly message |
+|--------|-------------|-----------------------------------------------------------------------|------------------|
+| `A001` | `1` | Portal not found | "I could not find that site." |
+| `A009` | `1` | Service-side failure | "Something went wrong on the service side. Try again in a few minutes." |
+| `A010` | `1` | Invalid input / schema validation failure | "Some part of the rule was not in the expected shape — try again." |
+| `A019` | `1` | Portal id is not a valid GUID | "The site identifier is not in the expected format." |
+| `A033` | `1` | Tenant mismatch | "The site belongs to a different tenant than your current session." |
+| `B001` | `1` | Edge infrastructure not provisioned | "The site does not have the front-door routing required for the firewall." |
+| `B003` | `1` * | Another WAF operation in progress | "Your last change is still being applied. I will wait and check again shortly." |
+| `B022` | `4` ** | Region not supported | "The firewall feature is not available in your region yet." |
+| `B023` | `4` ** | Trial portal — production required | "Your site needs to be a production site before you can turn on the firewall." |
+| `D004` | `1` | Caller not authorized | "Your account does not have permission for this. Ask an admin." |
+
+\* `B003` handling varies by script. `enable.js` and `disable.js` treat 409/B003 as "wait and poll" (no hard failure — the script continues to poll status until the in-flight operation settles). Other scripts (including `set-rules.js` and `delete-rules.js`) exit `1` — should wait and retry manually.
+
+\** `B022`/`B023` handling varies by script. `get-status.js` and `get-rules.js` return exit `0` with `{ "status": "unsupported" }` in the output (so the caller can include the finding in the report). `enable.js`, `disable.js`, `set-rules.js`, and `delete-rules.js` exit `4`.
+
+All scripts also share these exit codes:
+
+| Exit | Meaning |
+|------|---------|
+| `0` | Success |
+| `2` | Sign-in required (auth token missing or expired) |
+| `3` | Polling timed out (enable / disable only) |
+
+### Regional availability
+
+| Operation | Unavailable in |
+|-----------|----------------|
+| Enable / disable firewall | Singapore Local, China, UAE |
+| Managed rule configuration | GCC, GCC High, DoD, China, UAE |
+| Custom rule configuration | GCC, GCC High, DoD, China, UAE |
+
+When `website.js --websiteId` returns `null` during prerequisites, the skill stops with a local error before any consumer script runs.
+
+---
+
+## Body schema
+
+> **Case sensitivity:** custom rule fields use **camelCase**. Managed rule fields use **PascalCase**.
+
+See `rule-reference.md` for the full field-level schema: custom rules, match conditions, managed rule sets, and rule group overrides.
diff --git a/plugins/power-pages/skills/manage-firewall/references/rule-reference.md b/plugins/power-pages/skills/manage-firewall/references/rule-reference.md
new file mode 100644
index 000000000..b00c1941e
--- /dev/null
+++ b/plugins/power-pages/skills/manage-firewall/references/rule-reference.md
@@ -0,0 +1,203 @@
+# Rule Reference
+
+All values are placeholders — populate from the user's input, the site's existing rules, and `get-rules.js` output. Never hardcode IPs, countries, paths, or thresholds.
+
+## Table of contents
+
+- [Custom rule](#custom-rule)
+- [Match condition](#match-condition)
+- [Match variables](#match-variables)
+- [Operators](#operators)
+- [Managed rule set](#managed-rule-set)
+- [Rule group override](#rule-group-override)
+- [Rule override](#rule-override)
+- [Bot protection](#bot-protection)
+- [Priority guidance](#priority-guidance)
+- [Propagation delay](#propagation-delay)
+
+---
+
+## Custom rule
+
+One shape covers both standard and rate-limit rules. Set `ruleType` to `RateLimitRule` and add the two rate-limit fields when needed. Field **keys** use **camelCase**. The `name` field **value** must be PascalCase.
+
+```json
+{
+ "name": "<PascalCase-name>",
+ "priority": "<11–65000>",
+ "enabledState": "<Enabled|Disabled>",
+ "ruleType": "<MatchRule|RateLimitRule>",
+ "rateLimitDurationInMinutes": "<1|5>",
+ "rateLimitThreshold": "<integer-min-10>",
+ "matchConditions": [
+ {
+ "matchVariable": "<variable>",
+ "selector": "<when-required>",
+ "operator": "<operator>",
+ "negateCondition": false,
+ "matchValue": ["<value>"]
+ }
+ ],
+ "action": "<Allow|Block|Log|Redirect>"
+}
+```
+
+| Field | Type | Required | Valid values / format |
+|-------|------|----------|----------------------|
+| `name` | string | Yes | Letters and numbers only, starts with a letter, PascalCase. Case-insensitive unique — submitting an existing name replaces that rule. |
+| `priority` | integer | Yes | 11–65000. Lower = higher priority (first-match-wins). Auto-increments on conflict. |
+| `enabledState` | string | Yes | `"Enabled"`, `"Disabled"` |
+| `ruleType` | string | Yes | `"MatchRule"`, `"RateLimitRule"` |
+| `rateLimitDurationInMinutes` | integer | Only for `RateLimitRule` | `1` or `5` (no other values). |
+| `rateLimitThreshold` | integer | Only for `RateLimitRule` | Minimum 10. Requests per client in the duration window before the action fires. |
+| `matchConditions` | array | Yes | One or more match condition objects. All must match for the rule to fire (AND logic). |
+| `action` | string | Yes | `"Allow"`, `"Block"`, `"Log"`, `"Redirect"` |
+
+- Allow rules MUST use a lower priority number than the block rules they need to bypass.
+- Omit `rateLimitDurationInMinutes` and `rateLimitThreshold` for `MatchRule` — they are ignored.
+- To extend an existing rule's match values, submit the same rule name with the updated `matchValue` — only include that rule in the payload.
+
+---
+
+## Match condition
+
+Each object in the `matchConditions` array. Field keys use **camelCase**.
+
+```json
+{
+ "matchVariable": "<variable>",
+ "selector": "<header-or-param-name>",
+ "operator": "<operator>",
+ "negateCondition": false,
+ "matchValue": ["<value>"]
+}
+```
+
+| Field | Type | Required | Valid values / format |
+|-------|------|----------|----------------------|
+| `matchVariable` | string | Yes | See [Match variables](#match-variables). |
+| `selector` | string | Only for `RequestHeader`, `Cookies`, `PostArgs`, `QueryString` | Names which header, cookie, field, or parameter to inspect. Omit for other variables. |
+| `operator` | string | Yes | See [Operators](#operators). |
+| `negateCondition` | boolean | No | `true` or `false`. Default `false`. Set to `true` to invert the match. |
+| `matchValue` | array of strings | Yes | Format depends on operator: ISO 3166-1 alpha-2 codes for `GeoMatch`, CIDR notation or single IPs for `IPMatch`, strings for others. |
+
+- **`transforms` is not supported** The field exists in the schema but is not persisted when creating or updating rules. Do not include it in the payload.
+
+---
+
+## Match variables
+
+| Value | Requires `selector` | Description |
+|-------|---------------------|-------------|
+| `RemoteAddr` | No | Original client IP. Sourced from `X-Forwarded-For` when behind a proxy. |
+| `SocketAddr` | No | Direct-connection IP at the firewall edge — matches the proxy/load balancer, not the end user. |
+| `RequestUri` | No | Requested path and query string. |
+| `RequestHeader` | Yes | A specific HTTP request header. |
+| `RequestMethod` | No | The HTTP method. |
+| `QueryString` | Yes | A specific query string parameter. |
+| `RequestBody` | No | The request body content. |
+| `Cookies` | Yes | A specific cookie. |
+| `PostArgs` | Yes | A specific POST form field. |
+
+## Operators
+
+| Value | Compatible with | Description |
+|-------|-----------------|-------------|
+| `IPMatch` | `RemoteAddr`, `SocketAddr` | Matches IPs and CIDR ranges. |
+| `GeoMatch` | `RemoteAddr` | Matches ISO 3166-1 alpha-2 country codes. |
+| `Contains` | String variables | Substring match. |
+| `BeginsWith` | String variables | Prefix match. |
+| `EndsWith` | String variables | Suffix match. |
+| `RegEx` | String variables | Regular expression match. |
+| `Equal` | Any | Exact match. |
+| `LessThan` | Numeric comparisons | Less than. |
+| `GreaterThan` | Numeric comparisons | Greater than. |
+| `LessThanOrEqual` | Numeric comparisons | Less than or equal. |
+| `GreaterThanOrEqual` | Numeric comparisons | Greater than or equal. |
+| `Any` | Any | Matches everything — use for catch-all rules. |
+
+---
+
+## Managed rule set
+
+Retrieve `RuleSetType` and `RuleSetVersion` from `get-rules.js` output — never hardcode them. Field keys use **PascalCase**.
+
+```json
+{
+ "RuleSetType": "<from get-rules.js output>",
+ "RuleSetVersion": "<from get-rules.js output>",
+ "RuleGroupOverrides": []
+}
+```
+
+| Field | Type | Required | Valid values / format |
+|-------|------|----------|----------------------|
+| `RuleSetType` | string | Yes | Copy from `get-rules.js` output. |
+| `RuleSetVersion` | string | Yes | Copy from `get-rules.js` output. |
+| `RuleGroupOverrides` | array | No | Per-group overrides. See [Rule group override](#rule-group-override). |
+
+The managed rule set action is always Block — this cannot be changed. To disable a noisy rule, add an entry to `RuleGroupOverrides` rather than disabling the entire set. Managed rules configuration is not available in all regions — see `commands.md` § "Regional availability".
+
+## Rule group override
+
+Each object in the `RuleGroupOverrides` array. Field keys use **PascalCase**.
+
+```json
+{
+ "RuleGroupName": "<from get-rules.js output>",
+ "Rules": []
+}
+```
+
+| Field | Type | Required | Valid values / format |
+|-------|------|----------|----------------------|
+| `RuleGroupName` | string | Yes | The rule group to override. Get available names from `get-rules.js` output. |
+| `Rules` | array | No | Individual rule overrides. See [Rule override](#rule-override). |
+
+## Rule override
+
+Each object in the `Rules` array within a rule group override. Field keys use **PascalCase**.
+
+```json
+{
+ "RuleId": "<from get-rules.js output>",
+ "EnabledState": "<Enabled|Disabled>",
+ "Action": "<Allow|Block|Log|Redirect|AnomalyScoring>"
+}
+```
+
+| Field | Type | Required | Valid values / format |
+|-------|------|----------|----------------------|
+| `RuleId` | string | Yes | The specific rule id to override. Get available ids from `get-rules.js` output. |
+| `EnabledState` | string | No | `"Enabled"`, `"Disabled"`. Set to `"Disabled"` to suppress a false-positive managed rule. |
+| `Action` | string | No | `"Allow"`, `"Block"`, `"Log"`, `"Redirect"`, `"AnomalyScoring"`. `AnomalyScoring` applies to managed rule overrides only, not custom rules. |
+
+## Bot protection
+
+Bot protection is a managed rule category classifying automated traffic:
+
+| Group | Description |
+|-------|-------------|
+| Good bots | Search engine crawlers and known-friendly automation |
+| Bad bots | Known malicious scrapers, spam bots, and attack tools |
+| Unknown bots | Visitors that do not identify themselves |
+
+Use `RuleGroupOverrides` to change the action for individual bot categories.
+
+## Priority guidance
+
+Lower number = higher priority. Valid range: **11–65000**. Use these bands so rules layer predictably:
+
+| Range | Purpose |
+|--------------|-------------------------------------------------------|
+| `11`–`499` | Allow rules for trusted traffic |
+| `500`–`999` | Keep empty — reserved by this skill's band allocation |
+| `1000`–`1999`| IP and country block rules |
+| `2000`–`2999`| Path / URI pattern rules |
+| `3000`–`3999`| Rate-limit rules |
+
+When inserting a new rule, check existing rules and pick the next free slot in the matching band.
+
+## Propagation delay
+
+After creating or updating rules, changes may take **up to one hour** to propagate to all edge locations worldwide.
diff --git a/plugins/power-pages/skills/manage-firewall/scripts/delete-rules.js b/plugins/power-pages/skills/manage-firewall/scripts/delete-rules.js
new file mode 100644
index 000000000..94cab3780
--- /dev/null
+++ b/plugins/power-pages/skills/manage-firewall/scripts/delete-rules.js
@@ -0,0 +1,73 @@
+#!/usr/bin/env node
+
+const {
+ resolveContext,
+ request,
+ parseCliArgs,
+ fail,
+ hasErrorCode,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+
+const REQUEST_TIMEOUT_MS = 240_000; // 4 min — deletion exceeds the 15s default.
+
+const HELP = `delete-rules.js — Deletes custom firewall rules by name.
+
+Usage:
+ node delete-rules.js --portalId <portal-id> --names <name1,name2,...>
+
+Flags:
+ --portalId Power Platform API portal identifier (resolved during prerequisites)
+ --names Comma-separated list of custom rule names to delete
+ --help Show this help message
+
+Exit codes:
+ 0 Accepted (deletion is asynchronous)
+ 2 Sign-in required
+ 4 Unsupported
+ 1 Other failure
+
+Example:
+ node delete-rules.js --portalId <portal-id> --names <RuleName1>,<RuleName2>
+`;
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const args = parseCliArgs(process.argv);
+ const { portalId, names: namesArg } = args;
+ if (!portalId || !namesArg) {
+ fail('Usage: node delete-rules.js --portalId <portal-id> --names <name1,name2,...>', 1);
+ }
+
+ const names = namesArg
+ .split(',')
+ .map((n) => n.trim())
+ .filter(Boolean);
+ if (names.length === 0) fail('No rule names provided.', 1);
+
+ const ctx = resolveContext();
+ if (ctx.error) fail(ctx.error, 2);
+
+ const res = await request({
+ context: ctx,
+ method: 'PUT',
+ path: `/websites/${portalId}/deleteWafCustomRules`,
+ body: names,
+ timeout: REQUEST_TIMEOUT_MS,
+ });
+
+ if (hasErrorCode(res, 'B022', 'B023')) {
+ fail(`Firewall not available: ${res.error?.message || ''}`, 4);
+ }
+ if (!res.ok) {
+ fail(`Delete firewall rules failed (${res.statusCode}): ${res.error?.message || ''}`, 1);
+ }
+
+ process.stdout.write(JSON.stringify({ status: 'accepted', deleted: names }) + '\n');
+}
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/manage-firewall/scripts/disable.js b/plugins/power-pages/skills/manage-firewall/scripts/disable.js
new file mode 100644
index 000000000..39b285e70
--- /dev/null
+++ b/plugins/power-pages/skills/manage-firewall/scripts/disable.js
@@ -0,0 +1,99 @@
+#!/usr/bin/env node
+
+const {
+ resolveContext,
+ request,
+ pollUntil,
+ parseCliArgs,
+ parseTimeoutMs,
+ fail,
+ hasErrorCode,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+
+const DEFAULT_TIMEOUT_MIN = 15;
+const POLL_INTERVAL_MS = 30_000;
+
+const HELP = `disable.js — Turns off the web application firewall for a site.
+
+Usage:
+ node disable.js --portalId <portal-id> [--timeoutMinutes <n>]
+
+Flags:
+ --portalId Power Platform API portal identifier (resolved during prerequisites)
+ --timeoutMinutes Maximum wait time (default: ${DEFAULT_TIMEOUT_MIN})
+ --help Show this help message
+
+Exit codes:
+ 0 Disabled
+ 2 Sign-in required
+ 3 Polling timed out
+ 4 Unsupported (trial site or region restriction)
+ 1 Other failure
+
+Example:
+ node disable.js --portalId <portal-id>
+ node disable.js --portalId <portal-id> --timeoutMinutes <minutes>
+`;
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const args = parseCliArgs(process.argv);
+ const { portalId } = args;
+ if (!portalId) {
+ fail('Usage: node disable.js --portalId <portal-id> [--timeoutMinutes <n>]', 1);
+ }
+ const timeoutMs = parseTimeoutMs(args.timeoutMinutes, DEFAULT_TIMEOUT_MIN);
+
+ const ctx = resolveContext();
+ if (ctx.error) fail(ctx.error, 2);
+
+ const start = await request({
+ context: ctx,
+ method: 'POST',
+ path: `/websites/${portalId}/disableWaf`,
+ });
+ if (hasErrorCode(start, 'B022', 'B023')) {
+ fail(`Firewall not available for this site: ${start.error?.message || ''}`, 4);
+ }
+ if (hasErrorCode(start, 'B003')) {
+ process.stderr.write('A firewall change is already in progress; will wait for it to settle.\n');
+ } else if (start.statusCode !== 202) {
+ fail(`Disable firewall failed (${start.statusCode}): ${start.error?.message || ''}`, 1);
+ }
+
+ const poll = await pollUntil({
+ fetchStatus: async () => {
+ const r = await request({
+ context: ctx,
+ method: 'GET',
+ path: `/websites/${portalId}/getWafStatus`,
+ });
+ if (!r.ok) return { ok: false, error: r.error?.message || `${r.statusCode}` };
+ const raw = typeof r.body === 'string' ? r.body : r.body?.status;
+ const status = String(raw || '').toLowerCase();
+ if (status === 'failed') {
+ return { ok: false, error: 'disable operation reached the "Failed" terminal state' };
+ }
+ return { ok: true, body: status };
+ },
+ isDone: (status) => status === 'disabled',
+ timeoutMs,
+ intervalMs: POLL_INTERVAL_MS,
+ });
+
+ if (!poll.ok && poll.error === 'timeout') {
+ fail('Disable did not complete before timeout.', 3);
+ }
+ if (!poll.ok) fail(`Polling failed: ${poll.error}`, 1);
+
+ process.stdout.write(
+ JSON.stringify({ status: 'disabled', attempts: poll.attempts }) + '\n'
+ );
+}
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/manage-firewall/scripts/enable.js b/plugins/power-pages/skills/manage-firewall/scripts/enable.js
new file mode 100644
index 000000000..c0364ab19
--- /dev/null
+++ b/plugins/power-pages/skills/manage-firewall/scripts/enable.js
@@ -0,0 +1,102 @@
+#!/usr/bin/env node
+
+const {
+ resolveContext,
+ request,
+ pollUntil,
+ parseCliArgs,
+ parseTimeoutMs,
+ fail,
+ hasErrorCode,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+
+const DEFAULT_TIMEOUT_MIN = 15;
+const POLL_INTERVAL_MS = 30_000;
+
+const HELP = `enable.js — Turns on the web application firewall for a site.
+
+Usage:
+ node enable.js --portalId <portal-id> [--timeoutMinutes <n>]
+
+Flags:
+ --portalId Power Platform API portal identifier (resolved during prerequisites)
+ --timeoutMinutes Maximum wait time (default: ${DEFAULT_TIMEOUT_MIN})
+ --help Show this help message
+
+Exit codes:
+ 0 Enabled
+ 2 Sign-in required
+ 3 Polling timed out
+ 4 Unsupported (trial site or region restriction)
+ 1 Other failure
+
+Example:
+ node enable.js --portalId <portal-id>
+ node enable.js --portalId <portal-id> --timeoutMinutes <minutes>
+`;
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const args = parseCliArgs(process.argv);
+ const { portalId } = args;
+ if (!portalId) {
+ fail('Usage: node enable.js --portalId <portal-id> [--timeoutMinutes <n>]', 1);
+ }
+ const timeoutMs = parseTimeoutMs(args.timeoutMinutes, DEFAULT_TIMEOUT_MIN);
+
+ const ctx = resolveContext();
+ if (ctx.error) fail(ctx.error, 2);
+
+ const start = await request({
+ context: ctx,
+ method: 'POST',
+ path: `/websites/${portalId}/enableWaf`,
+ });
+ if (hasErrorCode(start, 'B022', 'B023')) {
+ fail(`Firewall not available for this site: ${start.error?.message || ''}`, 4);
+ }
+ if (hasErrorCode(start, 'B003')) {
+ // 409/B003 = a sibling enable/disable is mid-flight; observing its outcome is idempotent.
+ process.stderr.write('A firewall change is already in progress; will wait for it to settle.\n');
+ } else if (start.statusCode !== 202) {
+ fail(`Enable firewall failed (${start.statusCode}): ${start.error?.message || ''}`, 1);
+ }
+
+ const poll = await pollUntil({
+ fetchStatus: async () => {
+ const r = await request({
+ context: ctx,
+ method: 'GET',
+ path: `/websites/${portalId}/getWafStatus`,
+ });
+ if (!r.ok) return { ok: false, error: r.error?.message || `${r.statusCode}` };
+ const raw = typeof r.body === 'string' ? r.body : r.body?.status;
+ const status = String(raw || '').toLowerCase();
+ // Two terminal states: "created" (success) and "failed" (permanent error).
+ // Anything else is intermediate; keep polling.
+ if (status === 'failed') {
+ return { ok: false, error: 'enable operation reached the "Failed" terminal state' };
+ }
+ return { ok: true, body: status };
+ },
+ isDone: (status) => status === 'created',
+ timeoutMs,
+ intervalMs: POLL_INTERVAL_MS,
+ });
+
+ if (!poll.ok && poll.error === 'timeout') {
+ fail('Enable did not complete before timeout.', 3);
+ }
+ if (!poll.ok) fail(`Polling failed: ${poll.error}`, 1);
+
+ process.stdout.write(
+ JSON.stringify({ status: 'enabled', attempts: poll.attempts }) + '\n'
+ );
+}
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/manage-firewall/scripts/get-rules.js b/plugins/power-pages/skills/manage-firewall/scripts/get-rules.js
new file mode 100644
index 000000000..febdfc0a3
--- /dev/null
+++ b/plugins/power-pages/skills/manage-firewall/scripts/get-rules.js
@@ -0,0 +1,70 @@
+#!/usr/bin/env node
+
+const {
+ resolveContext,
+ request,
+ parseCliArgs,
+ fail,
+ isFeatureUnsupported,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+
+const HELP = `get-rules.js — Returns the firewall rules for a site (custom and managed).
+
+Usage:
+ node get-rules.js --portalId <portal-id> [--ruleType <name>]
+
+Flags:
+ --portalId Power Platform API portal identifier (resolved during prerequisites)
+ --ruleType Optional filter: Custom or Managed (omit for both)
+ --help Show this help message
+
+Exit codes:
+ 0 Success
+ 2 Sign-in required
+ 1 Other failure
+
+Example:
+ node get-rules.js --portalId <portal-id>
+ node get-rules.js --portalId <portal-id> --ruleType <Custom|Managed>
+`;
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const { portalId, ruleType } = parseCliArgs(process.argv);
+ if (!portalId) {
+ fail('Usage: node get-rules.js --portalId <portal-id> [--ruleType <name>]', 1);
+ }
+
+ const ctx = resolveContext();
+ if (ctx.error) fail(ctx.error, 2);
+
+ const res = await request({
+ context: ctx,
+ method: 'GET',
+ path: `/websites/${portalId}/getWafRules`,
+ query: ruleType ? { ruleType } : undefined,
+ });
+
+ if (isFeatureUnsupported(res, 'B022', 'B023')) {
+ process.stdout.write(
+ JSON.stringify({
+ status: 'unsupported',
+ message: res.error?.message || 'Firewall not available',
+ }) + '\n'
+ );
+ return;
+ }
+
+ if (!res.ok) {
+ fail(`Get firewall rules failed (${res.statusCode}): ${res.error?.message || ''}`, 1);
+ }
+
+ process.stdout.write(JSON.stringify({ status: 'ok', body: res.body || {} }) + '\n');
+}
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/manage-firewall/scripts/get-status.js b/plugins/power-pages/skills/manage-firewall/scripts/get-status.js
new file mode 100644
index 000000000..935dfe7db
--- /dev/null
+++ b/plugins/power-pages/skills/manage-firewall/scripts/get-status.js
@@ -0,0 +1,69 @@
+#!/usr/bin/env node
+
+const {
+ resolveContext,
+ request,
+ parseCliArgs,
+ fail,
+ isFeatureUnsupported,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+
+const HELP = `get-status.js — Returns the current firewall status for a site.
+
+Usage:
+ node get-status.js --portalId <portal-id>
+
+Flags:
+ --portalId Power Platform API portal identifier (resolved during prerequisites)
+ --help Show this help message
+
+Exit codes:
+ 0 Success (including unsupported region)
+ 2 Sign-in required
+ 1 Other failure
+
+Example:
+ node get-status.js --portalId <portal-id>
+`;
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const { portalId } = parseCliArgs(process.argv);
+ if (!portalId) {
+ fail('Usage: node get-status.js --portalId <portal-id>', 1);
+ }
+
+ const ctx = resolveContext();
+ if (ctx.error) fail(ctx.error, 2);
+
+ const res = await request({
+ context: ctx,
+ method: 'GET',
+ path: `/websites/${portalId}/getWafStatus`,
+ });
+
+ if (isFeatureUnsupported(res, 'B022', 'B023')) {
+ process.stdout.write(
+ JSON.stringify({
+ status: 'unsupported',
+ message: res.error?.message || 'Firewall not available for this site',
+ }) + '\n'
+ );
+ return;
+ }
+
+ if (!res.ok) {
+ fail(`Get firewall status failed (${res.statusCode}): ${res.error?.message || ''}`, 1);
+ }
+
+ // The service returns either the bare string ("Created") or { status: "Created" }.
+ const value = typeof res.body === 'string' ? res.body : res.body?.status;
+ process.stdout.write(JSON.stringify({ status: 'ok', value: value ?? null }) + '\n');
+}
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/manage-firewall/scripts/set-rules.js b/plugins/power-pages/skills/manage-firewall/scripts/set-rules.js
new file mode 100644
index 000000000..90764ec24
--- /dev/null
+++ b/plugins/power-pages/skills/manage-firewall/scripts/set-rules.js
@@ -0,0 +1,100 @@
+#!/usr/bin/env node
+
+const {
+ resolveContext,
+ request,
+ parseCliArgs,
+ fail,
+ hasErrorCode,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+
+// Service rejects rule names with hyphens, underscores, dots, or spaces (B021).
+// Enforce locally so callers get a clear local error before the round-trip.
+const RULE_NAME_RE = /^[a-zA-Z][a-zA-Z0-9]*$/;
+const REQUEST_TIMEOUT_MS = 240_000; // 4 min — rule creation exceeds the 15s default.
+
+const HELP = `set-rules.js — Creates or updates specific firewall rules.
+Only include the rules being added or modified; existing rules not in the payload are preserved.
+
+Usage:
+ node set-rules.js --portalId <portal-id> --data-inline '<json>'
+
+Flags:
+ --portalId Power Platform API portal identifier (resolved during prerequisites)
+ --data-inline JSON string with the CustomRules and/or ManagedRules to create or update
+ --help Show this help message
+
+Exit codes:
+ 0 Success
+ 2 Sign-in required
+ 4 Unsupported (trial site or region restriction)
+ 1 Other failure
+
+Example:
+ node set-rules.js --portalId <portal-id> --data-inline '<json-payload>'
+`;
+
+function validateRuleNames(payload) {
+ if (!Array.isArray(payload.CustomRules)) return;
+ for (const rule of payload.CustomRules) {
+ if (rule.name && !RULE_NAME_RE.test(rule.name)) {
+ fail(
+ `Invalid rule name "${rule.name}": must start with a letter and ` +
+ 'contain only letters and numbers.',
+ 1
+ );
+ }
+ }
+}
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const args = parseCliArgs(process.argv);
+ const portalId = args.portalId;
+ const dataInline = args['data-inline'] || args.dataInline;
+
+ if (!portalId || !dataInline) {
+ fail(
+ "Usage: node set-rules.js --portalId <portal-id> --data-inline '<json-payload>'",
+ 1
+ );
+ }
+
+ let payload;
+ try {
+ payload = JSON.parse(dataInline);
+ } catch (err) {
+ fail(`Failed to parse JSON: ${err.message}`, 1);
+ }
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
+ fail('--data-inline must be a JSON object containing CustomRules and/or ManagedRules.', 1);
+ }
+ validateRuleNames(payload);
+
+ const ctx = resolveContext();
+ if (ctx.error) fail(ctx.error, 2);
+
+ const res = await request({
+ context: ctx,
+ method: 'PUT',
+ path: `/websites/${portalId}/createWafRules`,
+ body: payload,
+ timeout: REQUEST_TIMEOUT_MS,
+ });
+
+ if (hasErrorCode(res, 'B022', 'B023')) {
+ fail(`Firewall not available: ${res.error?.message || ''}`, 4);
+ }
+ if (!res.ok) {
+ fail(`Set firewall rules failed (${res.statusCode}): ${res.error?.message || ''}`, 1);
+ }
+
+ process.stdout.write(JSON.stringify({ status: 'ok', body: res.body }) + '\n');
+}
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/manage-firewall/scripts/transform-firewall.js b/plugins/power-pages/skills/manage-firewall/scripts/transform-firewall.js
new file mode 100644
index 000000000..6fbc326f2
--- /dev/null
+++ b/plugins/power-pages/skills/manage-firewall/scripts/transform-firewall.js
@@ -0,0 +1,208 @@
+#!/usr/bin/env node
+
+const fs = require('fs');
+
+const RULE_TYPE_RATE_LIMIT = 'RateLimitRule';
+
+const HELP = `transform-firewall.js — Transform get-status.js + get-rules.js output into section findings.
+
+Usage:
+ node transform-firewall.js --statusFile <path> --rulesFile <path> [--annotations <path>]
+
+Flags:
+ --statusFile Path to a get-status.js stdout JSON file (required)
+ --rulesFile Path to a get-rules.js stdout JSON file (required)
+ --annotations Path to agent-provided annotations JSON (optional) — see "Annotations shape" below
+ --help Show this help message
+
+Annotations shape (all keys optional):
+ {
+ "state": {
+ "description": "Plain-language meaning of the current firewall state",
+ "fix": "Suggested action if the state indicates a genuine issue"
+ },
+ "rules": {
+ "<RuleName>": { "description": "Plain-language summary", "fix": "Optional fix" }
+ }
+ }
+
+Exit codes:
+ 0 Success (unified JSON on stdout)
+ 1 Invocation error (missing flags or unreadable file)
+
+Examples:
+ node transform-firewall.js --statusFile <status-file> --rulesFile <rules-file>
+ node transform-firewall.js --statusFile <status-file> --rulesFile <rules-file> --annotations <annotations-file>
+`;
+
+function getArg(name) {
+ const idx = process.argv.indexOf('--' + name);
+ return idx !== -1 && idx + 1 < process.argv.length ? process.argv[idx + 1] : null;
+}
+
+function readJson(filePath, label) {
+ if (!fs.existsSync(filePath)) {
+ process.stderr.write(`${label} not found: ${filePath}\n`);
+ process.exit(1);
+ }
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ } catch (err) {
+ process.stderr.write(`Failed to parse ${label} (${filePath}): ${err.message}\n`);
+ process.exit(1);
+ }
+}
+
+function bulletList(pairs) {
+ return pairs.map(([k, v]) => `- ${k}: ${v}`).join('\n');
+}
+
+function buildFinding(id, title, pairs, annotation) {
+ const detailParts = [];
+ if (annotation.description) detailParts.push(annotation.description);
+ detailParts.push(bulletList(pairs));
+ return {
+ id,
+ title,
+ details: detailParts.join('\n\n'),
+ ...(annotation.fix ? { fix: annotation.fix } : {}),
+ };
+}
+
+function customRulePairs(rule) {
+ const typeLabel =
+ rule.ruleType === RULE_TYPE_RATE_LIMIT
+ ? 'Custom rate-limit rule'
+ : `Custom ${rule.ruleType || 'rule'}`;
+ const pairs = [['Type', typeLabel]];
+ if (rule.ruleType === RULE_TYPE_RATE_LIMIT) {
+ pairs.push([
+ 'Threshold',
+ `${rule.rateLimitThreshold ?? '?'} requests / ${rule.rateLimitDurationInMinutes ?? '?'} min`,
+ ]);
+ }
+ pairs.push(['Action', rule.action || 'unknown']);
+ pairs.push(['Priority', rule.priority != null ? String(rule.priority) : 'unknown']);
+ pairs.push(['State', rule.enabledState || 'unknown']);
+ return pairs;
+}
+
+// Managed-rule responses arrive with dotted, flattened keys (e.g. `properties.ruleSetVersion`)
+// from the WAF endpoint, but fall back to nested `properties.*` if the service shape changes.
+function managedField(rule, key) {
+ return rule[`properties.${key}`] ?? rule.properties?.[key];
+}
+
+function managedRulePairs(rule) {
+ const groups = (() => {
+ const value = managedField(rule, 'ruleGroups');
+ return Array.isArray(value) ? value : [];
+ })();
+ const ruleCount = groups.reduce(
+ (sum, g) => sum + (Array.isArray(g.rules) ? g.rules.length : 0),
+ 0
+ );
+ const groupCount = groups.length;
+ return [
+ ['Type', 'Managed rule set'],
+ ['Version', managedField(rule, 'ruleSetVersion') || 'unknown'],
+ ['Rules', `${ruleCount} across ${groupCount} group${groupCount === 1 ? '' : 's'}`],
+ ['Provisioning state', managedField(rule, 'provisioningState') || 'unknown'],
+ ];
+}
+
+function transform(statusResponse, rulesResponse, annotations) {
+ const findings = [];
+ let counter = 1;
+
+ const unsupportedResponse =
+ statusResponse.status === 'unsupported'
+ ? statusResponse
+ : rulesResponse.status === 'unsupported'
+ ? rulesResponse
+ : null;
+ if (unsupportedResponse) {
+ findings.push({
+ id: `firewall-${counter++}`,
+ title: 'Firewall unsupported',
+ details: unsupportedResponse.message || 'Feature not available.',
+ });
+ return { status: 'unsupported', findings };
+ }
+
+ const stateAnnotation = annotations.state || {};
+ findings.push({
+ id: `firewall-${counter++}`,
+ title: `Firewall state: ${statusResponse.value ?? 'unknown'}`,
+ ...(stateAnnotation.description ? { details: stateAnnotation.description } : {}),
+ ...(stateAnnotation.fix ? { fix: stateAnnotation.fix } : {}),
+ });
+
+ const body = rulesResponse.body || {};
+ const customRules = Array.isArray(body.CustomRules) ? body.CustomRules : [];
+ const managedRules = Array.isArray(body.ManagedRules) ? body.ManagedRules : [];
+ const ruleAnnotations = annotations.rules || {};
+
+ // Missing priorities sort last so the comparator never returns NaN.
+ const priorityOf = (r) => (r.priority != null ? r.priority : Number.MAX_SAFE_INTEGER);
+ const sortedCustom = [...customRules].sort((a, b) => priorityOf(a) - priorityOf(b));
+ for (const rule of sortedCustom) {
+ findings.push(
+ buildFinding(
+ `firewall-${counter++}`,
+ rule.name,
+ customRulePairs(rule),
+ ruleAnnotations[rule.name] || {}
+ )
+ );
+ }
+
+ const sortedManaged = [...managedRules].sort((a, b) =>
+ (a.name || '').localeCompare(b.name || '')
+ );
+ for (const rule of sortedManaged) {
+ findings.push(
+ buildFinding(
+ `firewall-${counter++}`,
+ rule.name,
+ managedRulePairs(rule),
+ ruleAnnotations[rule.name] || {}
+ )
+ );
+ }
+
+ return { status: 'ok', findings };
+}
+
+function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return 0;
+ }
+
+ const statusFile = getArg('statusFile');
+ const rulesFile = getArg('rulesFile');
+ const annotationsFile = getArg('annotations');
+ if (!statusFile || !rulesFile) {
+ process.stderr.write(
+ 'Usage: node transform-firewall.js --statusFile <status-file> ' +
+ '--rulesFile <rules-file> [--annotations <annotations-file>]\n'
+ );
+ return 1;
+ }
+
+ const statusResponse = readJson(statusFile, 'status file');
+ const rulesResponse = readJson(rulesFile, 'rules file');
+ const annotations = annotationsFile ? readJson(annotationsFile, 'annotations file') : {};
+
+ process.stdout.write(
+ JSON.stringify(transform(statusResponse, rulesResponse, annotations)) + '\n'
+ );
+ return 0;
+}
+
+module.exports = { transform };
+
+if (require.main === module) {
+ process.exit(main());
+}
diff --git a/plugins/power-pages/skills/manage-headers/SKILL.md b/plugins/power-pages/skills/manage-headers/SKILL.md
new file mode 100644
index 000000000..0895e37c8
--- /dev/null
+++ b/plugins/power-pages/skills/manage-headers/SKILL.md
@@ -0,0 +1,209 @@
+---
+name: manage-headers
+description: >-
+ Inspects and configures the security headers a Power Pages site sends
+ to browsers — Content Security Policy, frame and clickjacking protection,
+ cross-origin sharing, cookie behavior, and related site settings.
+ Identifies gaps and walks the user through fixes. Use when the user
+ wants to review headers, fix CSP errors, allow embedding in another site,
+ control cross-origin access, harden cookie settings, or asks "are my
+ browser settings safe?", "fix my CSP", "set up CORS" — even if they only
+ mention a specific header name without saying "security headers".
+user-invocable: true
+argument-hint: "[optional: --review <out-dir>]"
+allowed-tools: Read, Write, Edit, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList
+model: opus
+---
+
+> **Plugin check**: Run `node "${CLAUDE_PLUGIN_ROOT}/scripts/check-version.js"` — if it outputs a message, show it to the user before proceeding.
+
+# Manage Headers
+
+Inspect and configure the HTTP security headers for a Power Pages site. Headers are configured as `HTTP/*` site settings stored in `.powerpages-site/site-settings/` YAML files.
+
+**Initial request:** $ARGUMENTS
+
+## Gotchas
+
+- **Site settings are YAML files.** Each header is a separate `.yml` file in `.powerpages-site/site-settings/`. The file name uses `-` instead of `/` (e.g., `HTTP/X-Frame-Options` → `http-x-frame-options.sitesetting.yml`).
+- **Absent = no header.** When a site setting is absent, the runtime omits that header entirely (except CSP on new sites — see headers-reference.md).
+- **HSTS and Cache-Control are platform-managed.** Do not try to set `HTTP/Strict-Transport-Security` — the runtime does not recognize it and the setting has no effect.
+- **Maker-mode bypasses headers.** Requests from Power Pages Studio skip all `HTTP/*` header emission. Verify headers in an incognito tab, not the studio preview.
+- **CSP is pass-through.** The runtime emits the value verbatim — it does NOT merge runtime sources automatically. The CSP MUST include Power Pages runtime hosts or the site breaks.
+- **CSP nonce.** When `script-src` contains `'nonce'`, the runtime replaces it per-request with `'nonce-<random>'` and auto-hashes inline event handlers. Scripts created dynamically via `document.createElement` do NOT receive the nonce.
+- **`SameSite=None` requires HTTPS.** The runtime sets `Secure` on every cookie over HTTPS automatically.
+- **CORS `*` is auto-specialized.** The runtime replaces `*` per-request with the specific requesting Origin — the browser sees a single-origin header, not a wildcard.
+
+## Workflow
+
+1. **Prerequisites** — Locate project, confirm site-settings directory exists
+2. **Inspect current headers** — Read site-setting YAML files, identify configured and missing headers
+3. **Assess and plan** — Identify gaps, present recommendations
+4. **Apply changes** — Edit existing settings or create new ones
+5. **Summarize** — Present results, record usage, offer follow-ups
+
+## Task Tracking
+
+Create tasks in four groups. Mark each `in_progress` when starting, `completed` when done.
+
+| Group | When to create | Tasks |
+|-------|----------------|-------|
+| 1 | At start | Check prerequisites |
+| 2 | After prerequisites pass | Inspect current headers · Assess and plan (skip "Assess and plan" in review mode) |
+| 3 | After user approves changes | Apply changes (skip in review mode OR if no changes were accepted) |
+| 4 | After apply or assess | Summarize (always) |
+
+---
+
+## 1. Prerequisites
+
+### 1.1 Locate the project, detect review mode
+
+Use `Glob` to find `**/powerpages.config.json`. If `$ARGUMENTS` contains `--review <out-dir>`, remember the output directory — Steps 3–4 are skipped and Step 5 writes JSON only.
+
+### 1.2 Verify site-settings directory
+
+Check that `.powerpages-site/site-settings/` exists. If not, the site has not been deployed yet — tell the user and recommend `/deploy-site`. Stop.
+
+---
+
+## 2. Inspect current headers
+
+Use `Glob` to find all `*.yml` files in `.powerpages-site/site-settings/`. Use `Read` to read each file and extract the `name` and `value` fields. Identify all settings with an `HTTP/` prefix — these are the configured headers.
+
+Compare against the recognized header catalogue in `references/headers-reference.md`. For each header in the catalogue:
+- **Present** — record its current value.
+- **Missing** — record it as absent and note the recommended value from headers-reference.md.
+
+For CSP specifically: if `HTTP/Content-Security-Policy` is present, scan the project's source files using `Glob` + `Read` to find external URLs and check whether they are covered by the policy. Identify the site's cloud environment via `pac auth who` to determine the correct Power Pages runtime host (see headers-reference.md § "Power-Pages-runtime sources a CSP must allow").
+
+---
+
+## 3. Assess and plan
+
+Skip in **review mode**.
+
+MUST use plain language only. Never lead with words like CSP, CORS, HSTS, or MIME sniffing — explain using everyday language:
+
+| Header concept | Plain-language name |
+|----------------|---------------------|
+| Content-Security-Policy | "which scripts and resources the browser is allowed to load" |
+| X-Frame-Options / frame-ancestors | "whether other websites can put your site inside a frame" |
+| X-Content-Type-Options | "stop the browser from guessing file types" |
+| CORS headers | "which other websites can call your site's data" |
+| SameSite cookies | "when the browser sends your sign-in cookie" |
+
+### Default approach
+
+Read `references/headers-reference.md` for recommended values and guidance. **Present the most important gaps first** — headers that are missing or misconfigured relative to the recommended values.
+
+For each finding, present via `AskUserQuestion`:
+- A plain-language explanation of why the change matters
+- The recommended value
+- Options: accept the recommendation, customize, or skip
+
+Do NOT present all headers at once — present the important gaps first. For headers already set to recommended values, mention them in the summary without requiring action.
+
+### CSP composition
+
+When the user needs a CSP (missing or incomplete), compose one using:
+1. The starter template from headers-reference.md
+2. The correct cloud-specific runtime host
+3. External URLs discovered from the project's source files — scan ALL source files, templates, scripts, etc.
+4. The `'nonce'` keyword for inline scripts
+
+When reviewing an existing CSP, validate:
+- All external URLs actually loaded by the site are covered in the policy
+- Runtime hosts are included for the site's cloud
+
+Present the composed or corrected CSP for review. Recommend starting in report-only mode (`HTTP/Content-Security-Policy-Report-Only`) before enforcing.
+
+---
+
+## 4. Apply changes
+
+Skip in **review mode**.
+
+For **existing** settings: use `Edit` on the YAML file directly — change the `value` field.
+
+For **new** settings: use the shared create script:
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "<setting-name>" \
+ --value "<value>" \
+ --description "<description>"
+```
+
+See `references/commands.md` for details.
+
+After all changes are applied, offer to deploy: "Ready to deploy these changes? They take effect after the next deploy." If yes, invoke `/deploy-site`.
+
+---
+
+## 5. Summarize
+
+### 5.1 Review mode
+
+First, read the configured `HTTP/*` site settings (from Step 2 — you already have them). Then write `<REVIEW_DIR>/header-annotations.json` with a plain-language description for each header and, when the configured value has a genuine issue (missing critical directive, weak value), a suggested fix. The transform script no longer hardcodes header descriptions — they come from you.
+
+```json
+{
+ "headers": {
+ "HTTP/<HeaderName>": { "description": "What this header does, in plain language.", "fix": "Optional fix if the configured value has a genuine issue." }
+ }
+}
+```
+
+Use `references/headers-reference.md` for authoritative descriptions and validation rules. Surface a `fix` **only** when the value has a real problem — do not editorialize on every header.
+
+Then run the transform:
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/manage-headers/scripts/transform-headers.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --annotations "<REVIEW_DIR>/header-annotations.json"
+```
+
+Write the stdout to `<REVIEW_DIR>/manage-headers.json` and stop. The transform emits `{ status, findings, details }`; the orchestrating skill handles presentation.
+
+### 5.2 Present summary
+
+Skip in **review mode**.
+
+Plain-language summary: what was changed, what gaps remain, and what is already well-configured.
+
+### 5.3 Record skill usage
+
+> Reference: `${CLAUDE_PLUGIN_ROOT}/references/skill-tracking-reference.md`
+>
+> Use `--skillName "ManageHeaders"`.
+
+### 5.4 Offer follow-ups
+
+If a natural follow-up exists based on findings, suggest it. If no meaningful follow-up exists, end the skill.
+
+---
+
+## Constraints
+
+- **Plain language** — MUST NOT use technical jargon with the user. Explain header names using everyday language.
+- **headers-reference.md is the source of truth** — recommended values and the recognized header catalogue live there. Read it before assessing.
+- **Context-aware interactions** — every recommendation MUST reflect the site's actual configuration and usage:
+ - Read the site's source files, integrations, and auth setup before recommending any value.
+ - Never recommend a value without verifying it will not break the site's functionality (see the "Context to verify" column in headers-reference.md).
+ - Acknowledge existing values when proposing changes — they may be intentional.
+ - For CSP, reference actual external URLs found in the project's source files.
+ - For CORS, verify the site's actual cross-origin consumers before scoping.
+ - For Cross-Origin-Opener-Policy, verify whether the site uses popup-based auth.
+ - For Cross-Origin-Resource-Policy, verify whether the site hosts Azure AD B2C custom login pages, is embedded cross-origin, or has integrations that load its resources. Leave absent or use `cross-origin` when unsure.
+- **Preview is for change review only** — include `preview` only on options that modify a setting value. Do not add to informational choices.
+- **Recommendations MUST NOT break the site** — before recommending a value, consider whether it would block resources the site actually uses. For CSP, always verify that runtime sources and project external URLs are included. For CORS, verify the site's actual cross-origin needs. When unsure, recommend report-only mode first.
+- **NEVER recommend broadening an existing policy** — if the user already has a tight CSP, CORS scope, or restrictive header value, do not suggest making it less restrictive. A working tight policy is better than a broad one. Never recommend `https:` wildcards in CSP directives — list specific hosts instead.
+- **Deploy after changes** — header changes only take effect after deploying. Always offer `/deploy-site` after applying changes.
+
+## References
+
+- `references/headers-reference.md` — recognized header catalogue, recommended values, CSP composition rules, runtime sources. Read before Step 2 (inspect) and Step 3 (assess) in **interactive** mode.
+- `references/commands.md` — shared `create-site-setting.js` usage. Read at Step 4 (apply) when creating new settings.
diff --git a/plugins/power-pages/skills/manage-headers/references/commands.md b/plugins/power-pages/skills/manage-headers/references/commands.md
new file mode 100644
index 000000000..588491221
--- /dev/null
+++ b/plugins/power-pages/skills/manage-headers/references/commands.md
@@ -0,0 +1,69 @@
+# Manage Headers — Commands
+
+## Table of contents
+
+- [`create-site-setting.js` (shared)](#create-site-settingjs-shared)
+- [`transform-headers.js`](#transform-headersjs)
+
+---
+
+## `create-site-setting.js` (shared)
+
+Use the shared script to create new `HTTP/*` site-setting YAML files:
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<project-root>" --name "<setting-name>" --value "<value>" --description "<description>"
+```
+
+The script generates a UUID, checks for duplicates, and writes the YAML file to `.powerpages-site/site-settings/`.
+
+To update an existing setting, use the `Edit` tool directly on the YAML file — do not use this script (it rejects duplicates).
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| `0` | Success — new YAML file created. |
+| `1` | Failure — duplicate setting, missing args, or write error. |
+
+The script validates inputs and exits with a descriptive error if arguments are missing or the setting already exists.
+
+---
+
+## `transform-headers.js`
+
+Reads every `HTTP/*` site-setting YAML in `.powerpages-site/site-settings/` and emits the unified findings shape used by the consolidated security review. Read-only — does not modify any file.
+
+### Usage
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/manage-headers/scripts/transform-headers.js" --projectRoot "<project-root>" [--annotations "<path>"]
+```
+
+### Parameters
+
+| Flag | Required | Description |
+|------|----------|-------------|
+| `--projectRoot` | Yes | Power Pages project root (the folder that contains `.powerpages-site/`). |
+| `--annotations` | No | Path to an agent-written annotations JSON file. Shape: `{ "headers": { "HTTP/<HeaderName>": { "description": "...", "fix": "..." } } }`. Used to add plain-language descriptions and optional fixes to the emitted findings. |
+
+### Response (stdout)
+
+```json
+{ "status": "ok", "findings": [ ], "details": {} }
+```
+
+…or, when `.powerpages-site/site-settings/` is absent:
+
+```json
+{ "status": "missing-settings", "findings": [], "details": {} }
+```
+
+Each finding has the inventory shape `{ id, title, details, fix? }` — no `severity` and no `tag` (the section is informational; the orchestrator does not roll these up into severity totals, and the header name already appears as the `title`). `details` contains the agent-supplied description (when annotations were passed) followed by the current value. `fix` is present only when the annotations file supplied one for that header.
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| `0` | Success (also returns `missing-settings` when `.powerpages-site/site-settings/` is absent). |
+| `1` | Invocation error (missing `--projectRoot`). |
diff --git a/plugins/power-pages/skills/manage-headers/references/headers-reference.md b/plugins/power-pages/skills/manage-headers/references/headers-reference.md
new file mode 100644
index 000000000..7ee1a4d4c
--- /dev/null
+++ b/plugins/power-pages/skills/manage-headers/references/headers-reference.md
@@ -0,0 +1,215 @@
+# Headers Reference
+
+Reference for the response headers and site settings the skill configures — what they do, how the runtime handles them, and what to verify before changing. Use this when inspecting the current setup and planning changes.
+
+## Table of contents
+
+- [Site-setting naming convention](#site-setting-naming-convention)
+- [Recognized header catalogue](#recognized-header-catalogue)
+- [Platform-managed headers (not settable)](#platform-managed-headers-not-settable)
+- [Default behavior when a setting is absent](#default-behavior-when-a-setting-is-absent)
+- [Content Security Policy](#content-security-policy)
+- [Frame embedding](#frame-embedding)
+- [Cross-Origin sharing](#cross-origin-sharing)
+- [Cookies](#cookies)
+- [Other security headers](#other-security-headers)
+- [Power-Pages-runtime sources a CSP must allow](#power-pages-runtime-sources-a-csp-must-allow)
+- [Deployment and caching](#deployment-and-caching)
+
+---
+
+## Site-setting naming convention
+
+Every HTTP header site-setting uses the prefix `HTTP/` followed by the header name. Examples: `HTTP/X-Frame-Options`, `HTTP/Content-Security-Policy`, `HTTP/Access-Control-Allow-Origin`.
+
+SameSite cookie settings use dynamic segments rather than a single header-named key:
+- `HTTP/SameSite/Default` — applies to every cookie unless overridden.
+- `HTTP/SameSite/<cookie-name>` — per-cookie override for the named cookie.
+
+Each site-setting is a separate YAML file under `.powerpages-site/site-settings/`. The file name uses `-` instead of `/` (e.g. `http-x-frame-options.sitesetting.yml`) because `/` is not a filename-safe character.
+
+---
+
+## Recognized header catalogue
+
+The runtime reads these `HTTP/*` site-settings and emits the corresponding response header. Names outside this catalogue are also emitted by the runtime as-is — review the inventory to spot typos or confirm that non-standard names are intentional.
+
+**CSP**
+- `HTTP/Content-Security-Policy`
+- `HTTP/Content-Security-Policy-Report-Only`
+- `HTTP/Content-Security-Policy/Inject-unsafe-eval` — boolean flag, not a header (see [CSP specifics](#csp-specifics))
+
+**CORS**
+- `HTTP/Access-Control-Allow-Origin`
+- `HTTP/Access-Control-Allow-Credentials`
+- `HTTP/Access-Control-Allow-Headers`
+- `HTTP/Access-Control-Allow-Methods`
+- `HTTP/Access-Control-Expose-Headers`
+- `HTTP/Access-Control-Max-Age`
+
+**Clickjacking / framing**
+- `HTTP/X-Frame-Options`
+
+**MIME sniffing / download**
+- `HTTP/X-Content-Type-Options`
+- `HTTP/X-Download-Options`
+- `HTTP/X-Permitted-Cross-Domain-Policies`
+
+**Cross-origin isolation**
+- `HTTP/Cross-Origin-Resource-Policy`
+- `HTTP/Cross-Origin-Opener-Policy`
+- `HTTP/Cross-Origin-Embedder-Policy`
+
+**Referrer / permissions / privacy**
+- `HTTP/Referrer-Policy`
+- `HTTP/Permissions-Policy`
+- `HTTP/X-DNS-Prefetch-Control`
+- `HTTP/X-XSS-Protection` — legacy; modern browsers ignore it but the runtime emits whatever value is set
+
+**Cookies**
+- `HTTP/SameSite/Default`
+- `HTTP/SameSite/<cookie-name>`
+
+---
+
+## Platform-managed headers (not settable)
+
+`Strict-Transport-Security` (HSTS) and `Cache-Control` are emitted by the runtime and cannot be overridden through site settings. Writing `HTTP/Strict-Transport-Security` has no effect — the runtime does not recognize it. HTTP to HTTPS redirect is enabled by default.
+
+Because these protections are platform-managed, the skill does not propose changes for them.
+
+---
+
+## Default behavior when a setting is absent
+
+When an `HTTP/<Header>` site-setting is absent, the runtime omits that header entirely. Always explicitly configure security headers as site-setting YAML files so they are reviewable in source control.
+
+---
+
+## Content Security Policy
+
+CSP runtime behavior:
+
+- **Pass-through.** The runtime emits `HTTP/Content-Security-Policy` verbatim. Power-Pages-runtime sources are NOT added automatically — the directive must include them explicitly (see [Power-Pages-runtime sources a CSP must allow](#power-pages-runtime-sources-a-csp-must-allow)). Missing a runtime source breaks the site.
+- **Nonce mechanism.** When `script-src` contains `'nonce'`, the runtime replaces it per-request with `'nonce-<random>'` and injects the attribute on Liquid-rendered inline `<script>` tags. Inline event handlers are auto-hashed. Dynamically created scripts (`document.createElement`) do NOT receive the nonce.
+- **`'unsafe-eval'` auto-injection.** `HTTP/Content-Security-Policy/Inject-unsafe-eval` (boolean, default `true`) auto-injects `'unsafe-eval'` into `script-src` when `'nonce'` is present. Runtime components require this. Setting to `false` may break runtime functionality — test in report-only mode first.
+- **Report-Only.** `HTTP/Content-Security-Policy-Report-Only` is a separate setting. Both can run simultaneously.
+
+---
+
+## Frame embedding
+
+- `HTTP/X-Frame-Options` — the runtime sets this to `SAMEORIGIN` by default.
+
+---
+
+## Cross-Origin sharing
+
+CORS runtime behavior:
+
+- **Omit `HTTP/Access-Control-Allow-Credentials` to disable.** The runtime emits whatever value is set — writing `false` produces a confusing header with no effect.
+- **`*` is auto-specialized.** The runtime replaces `*` per-request with the specific requesting Origin. This means `*` with credentials effectively works (per-origin response), unlike standard HTTP.
+- **CORS headers are applied to every response**, not only Web API responses.
+
+---
+
+## Cookies
+
+Cookie runtime behavior:
+
+- `HTTP/SameSite/Default` — applies to every cookie unless overridden.
+- `HTTP/SameSite/<cookie-name>` — per-cookie override.
+- The runtime sets `Secure` on every cookie over HTTPS, so `SameSite=None` works for HTTPS sites.
+- For iframe-embedding scenarios, use `HTTP/SameSite/<session-cookie-name>: None` on the specific cookies the embed needs.
+
+---
+
+## Other security headers
+
+Context to verify before changing:
+
+| Setting | Context to verify before changing |
+|---------|-----------------------------------|
+| `HTTP/X-Content-Type-Options` | The runtime serves known content types, so `nosniff` does not cause issues. |
+| `HTTP/Cross-Origin-Resource-Policy` | See CORP details below. |
+| `HTTP/Cross-Origin-Opener-Policy` | See COOP details below. |
+| `HTTP/Cross-Origin-Embedder-Policy` | `require-corp` breaks any cross-origin resource without explicit CORS headers. Only use when cross-origin isolation is specifically needed. |
+
+### CORP (`HTTP/Cross-Origin-Resource-Policy`)
+
+`same-origin` breaks:
+- Azure AD B2C custom login pages hosted on the site — B2C loads resources from the site cross-origin
+- Any cross-origin iframe embedding
+- Power BI or other integrations that load resources from the site
+
+`same-site` also breaks B2C flows — `b2clogin.com` and the site's domain are different registrable domains.
+
+Standard redirect-based auth (Entra ID, SAML) is NOT affected — those use top-level navigations, not sub-resource loading.
+
+Safest: leave absent or use `cross-origin`.
+
+### COOP (`HTTP/Cross-Origin-Opener-Policy`)
+
+`same-origin` breaks:
+- Popup-based OAuth flows
+- `window.opener` references between windows
+
+Standard redirect-based auth (Entra ID, SAML) is NOT affected.
+
+Verify whether the site uses popup-based auth before setting.
+
+---
+
+`HTTP/Referrer-Policy`, `HTTP/Permissions-Policy`, `HTTP/X-Download-Options`, `HTTP/X-Permitted-Cross-Domain-Policies`, and `HTTP/X-DNS-Prefetch-Control` are all pass-through — the runtime emits whatever value is set.
+
+---
+
+## Power-Pages-runtime sources a CSP must allow
+
+The runtime loads resources from these hosts. Any CSP deployed on the site must include them in the corresponding directives, or the site fails to render.
+
+**Required on `script-src`** — one cloud-specific runtime host plus the nonce keyword:
+
+| Site's cloud | Required `content.powerapps.*` host |
+|---|---|
+| Public / Commercial | `content.powerapps.com` |
+| US Government (GCC / GCC High) | `content.powerapps.us` |
+| US Department of Defense | `content.appsplatform.us` |
+| China | `content.powerapps.cn` |
+
+Include only the one that matches the site's cloud — adding the others over-allows and defeats the point of the CSP. Resolve the cloud via `pac auth who` (the `Cloud` field) before composing the directive.
+
+Also required on `script-src`:
+- `'nonce'` — enables the per-request nonce mechanism for inline Liquid-rendered scripts
+
+**Required on `style-src`**:
+- `'unsafe-inline'` (runtime platform limitation for certain out-of-the-box styles)
+
+**All other directives** (`style-src` hosts, `font-src`, `img-src`, `connect-src`, etc.): depends on the site's own content. Scan the project's source files, templates, scripts, etc. and add only the specific hosts the site actually uses. Do NOT use `https:` wildcards — they defeat the purpose of the CSP.
+
+### Starter directive template
+
+If the user is starting a CSP from scratch (with `<cloud-host>` replaced by the cloud-specific host from the table above):
+
+```
+default-src 'self';
+script-src 'self' 'nonce' <cloud-host>;
+style-src 'self' 'unsafe-inline';
+img-src 'self' data:;
+font-src 'self';
+connect-src 'self';
+frame-ancestors 'self';
+base-uri 'self';
+form-action 'self';
+object-src 'none';
+```
+
+Add specific external hosts to each directive based on the source file scan. Never use `https:` wildcards — list each host explicitly.
+
+---
+
+## Deployment and caching
+
+Header changes land in Dataverse via `/deploy-site`. The site-setting update triggers a soft restart (no downtime); new values take effect once the restart propagates. Verify after a short wait in an incognito browser tab or via `curl -I <site-url>`.
+
+**Maker-mode requests skip all `HTTP/*` header emission.** Requests from Power Pages Studio or other maker tools do not include headers configured via site settings. Viewing the site through maker tools will NOT show the configured headers. Always verify with a fresh browser tab that is not authenticated as a maker.
diff --git a/plugins/power-pages/skills/manage-headers/scripts/transform-headers.js b/plugins/power-pages/skills/manage-headers/scripts/transform-headers.js
new file mode 100644
index 000000000..1b0be31a7
--- /dev/null
+++ b/plugins/power-pages/skills/manage-headers/scripts/transform-headers.js
@@ -0,0 +1,132 @@
+#!/usr/bin/env node
+
+const fs = require('fs');
+const path = require('path');
+const { loadSiteSettings } = require('../../../scripts/lib/powerpages-config');
+
+const CSP_HEADER_NAMES = new Set([
+ 'HTTP/Content-Security-Policy',
+ 'HTTP/Content-Security-Policy-Report-Only',
+]);
+
+const EMPTY_RESULT = { status: 'ok', findings: [], details: {} };
+
+const HELP = `transform-headers.js — Emit HTTP/* site-setting inventory as section data.
+
+Usage:
+ node transform-headers.js --projectRoot <path> [--annotations <path>]
+
+Flags:
+ --projectRoot Power Pages project root (containing .powerpages-site/)
+ --annotations Path to agent-provided annotations JSON (optional)
+ --help Show this help message
+
+Annotations shape (all keys optional):
+ {
+ "headers": {
+ "HTTP/<HeaderName>": { "description": "Plain-language summary", "fix": "Optional fix" }
+ }
+ }
+
+Exit codes:
+ 0 Success (unified JSON on stdout — { status, findings, details })
+ 1 Invocation error (missing --projectRoot)
+
+Examples:
+ node transform-headers.js --projectRoot <project-root>
+ node transform-headers.js --projectRoot <project-root> --annotations <annotations-file>
+`;
+
+function getArg(name, argv) {
+ const idx = argv.indexOf('--' + name);
+ return idx !== -1 && idx + 1 < argv.length ? argv[idx + 1] : null;
+}
+
+function readJson(filePath, label) {
+ if (!fs.existsSync(filePath)) {
+ process.stderr.write(`${label} not found: ${filePath}\n`);
+ process.exit(1);
+ }
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ } catch (err) {
+ process.stderr.write(`Failed to parse ${label} (${filePath}): ${err.message}\n`);
+ process.exit(1);
+ }
+}
+
+// CSP values are long single-line strings; render one directive per line.
+function formatValue(name, value) {
+ if (!CSP_HEADER_NAMES.has(name)) return value;
+ const stripped = value.trim().replace(/^"|"$/g, '');
+ const directives = stripped
+ .split(';')
+ .map((d) => d.trim())
+ .filter(Boolean);
+ if (directives.length <= 1) return stripped;
+ return directives.map((d) => ` ${d};`).join('\n');
+}
+
+function buildFinding(rec, idx, annotation) {
+ // YAML scalars aren't always strings (booleans, numbers, nulls all pass through here).
+ const value = rec.value != null ? String(rec.value) : '';
+ const detailParts = [];
+ if (annotation.description) detailParts.push(annotation.description);
+ detailParts.push(
+ 'Current value:\n' + (value ? formatValue(rec.name, value) : ' (empty)')
+ );
+ return {
+ id: `headers-${idx + 1}`,
+ title: rec.name,
+ details: detailParts.join('\n\n'),
+ ...(annotation.fix ? { fix: annotation.fix } : {}),
+ };
+}
+
+function transform(records, annotations) {
+ const httpRecords = records
+ .filter((r) => r.name?.startsWith('HTTP/'))
+ .sort((a, b) => a.name.localeCompare(b.name));
+
+ const headerAnnotations = annotations.headers || {};
+ const findings = httpRecords.map((rec, i) =>
+ buildFinding(rec, i, headerAnnotations[rec.name] || {})
+ );
+
+ return { status: 'ok', findings, details: {} };
+}
+
+function main(argv = process.argv) {
+ if (argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return 0;
+ }
+
+ const projectRoot = getArg('projectRoot', argv);
+ const annotationsFile = getArg('annotations', argv);
+ if (!projectRoot) {
+ process.stderr.write(
+ 'Usage: node transform-headers.js --projectRoot <path> [--annotations <path>]\n'
+ );
+ return 1;
+ }
+
+ const siteSettingsDir = path.join(projectRoot, '.powerpages-site', 'site-settings');
+ if (!fs.existsSync(siteSettingsDir)) {
+ process.stdout.write(
+ JSON.stringify({ ...EMPTY_RESULT, status: 'missing-settings' }) + '\n'
+ );
+ return 0;
+ }
+
+ const records = loadSiteSettings(siteSettingsDir);
+ const annotations = annotationsFile ? readJson(annotationsFile, 'annotations file') : {};
+ process.stdout.write(JSON.stringify(transform(records, annotations)) + '\n');
+ return 0;
+}
+
+module.exports = { transform };
+
+if (require.main === module) {
+ process.exit(main());
+}
diff --git a/plugins/power-pages/skills/scan-site/SKILL.md b/plugins/power-pages/skills/scan-site/SKILL.md
new file mode 100644
index 000000000..fd1f2ac6a
--- /dev/null
+++ b/plugins/power-pages/skills/scan-site/SKILL.md
@@ -0,0 +1,241 @@
+---
+name: scan-site
+description: >-
+ Runs a security scan on a deployed Power Pages site, fetches the latest
+ scan report, and produces a plain-language summary. Scans the live site's
+ public surface for vulnerabilities and surfaces issues by severity. Use
+ when the user wants to scan, check, test, audit, or assess a published
+ site, find vulnerabilities on production, view the latest scan report,
+ see previous scan results, run a security audit, or asks "how safe is
+ my live site?", "is my site vulnerable?", "audit my production site" —
+ even if they say "find issues" or "check for problems" without mentioning
+ "scan" or "security".
+user-invocable: true
+argument-hint: "[optional: --review <out-dir>]"
+allowed-tools: Read, Write, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList
+model: opus
+---
+
+> **Plugin check**: Run `node "${CLAUDE_PLUGIN_ROOT}/scripts/check-version.js"` — if it outputs a message, show it to the user before proceeding.
+
+# Scan Site
+
+Run a security scan on a deployed Power Pages site, fetch the latest scan report, and surface findings in a plain-language summary. The scan runs server-side; duration depends on site size — small sites finish in minutes, large sites can take hours.
+
+This skill scans the live deployed site, not local source code.
+
+**Initial request:** $ARGUMENTS
+
+## Gotchas
+
+- **Website record id vs portal id.** `.powerpages-site/website.yml` stores the website record id, not the portal id. Every script takes `--portalId`. Resolve once via `website.js --websiteId` during prerequisites.
+- **Never resolve by name.** Site names can duplicate inside an environment; only the website record id is safe.
+- **`null` from the resolver** means the site is not deployed, or the authenticated profile points at a different environment.
+- **Scans are long-running.** Duration depends on site size — small sites finish in minutes, large sites can take hours. Poll in the background and increase `--timeoutMinutes` for large sites.
+- **Only one scan per site at a time.** A start while a scan is running returns `Z003` — `start-deep-scan.js` reports it as `{ "status": "already-running" }` (exit 0).
+- **Rate limits may apply.** The service may throttle repeated scans on the same site. When throttled, wait and retry later.
+- **No completed scan yet.** A fresh site or a site mid-scan has no completed report — `get-latest-report.js` returns `{ "status": "empty" }`.
+
+## Workflow
+
+1. **Prerequisites** — Locate project, confirm sign-in, identify site
+2. **Check scan state** — Detect whether a scan is currently running
+3. **Choose an action** — Context-aware recommendation (run new scan / show latest)
+4. **Run the scan** — Start and poll for completion
+5. **Fetch and summarize** — Get the report, present findings
+6. **Walk through follow-ups** — Route issues to the right downstream skill (only if the report contains issues)
+
+## Task Tracking
+
+Create tasks in four groups. Mark each `in_progress` when starting, `completed` when done.
+
+| Group | When to create | Tasks |
+|-------|----------------|-------|
+| 1 | At start | Check prerequisites |
+| 2 | After prerequisites pass | Check scan state · Choose an action (skip in review mode) |
+| 3 | After user confirms an action (or in review mode) | Run the scan (skip only if the user chose to view latest results in interactive mode) · Fetch and summarize (always) |
+| 4 | After fetch and summarize | Walk through follow-ups (only if the report contains issues AND not in review mode) |
+
+---
+
+## 1. Prerequisites
+
+### 1.1 Locate the project, detect review mode
+
+Use `Glob` to find `**/powerpages.config.json`. If `$ARGUMENTS` contains `--review <out-dir>`, remember the output directory — Step 3 (choose an action) is skipped, Step 4 (run scan) executes automatically (start a fresh scan or attach to a running one), Step 5 writes JSON only, and Step 6 (follow-ups) is skipped.
+
+### 1.2 Resolve site identifiers
+
+Read `.powerpages-site/website.yml` → extract `id` field → that is `<WEBSITE_ID>`.
+
+If missing, the site has not been deployed. Tell the user and recommend `/deploy-site`. Stop. Do **not** resolve by name or URL.
+
+Resolve to portalId:
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/scripts/website.js" --websiteId "<WEBSITE_ID>"
+```
+
+Capture `Id` (portalId), `Type`, `Name`, `WebsiteUrl`. If exit code `2` → sign-in required (`pac auth create` or `az login`). If `null` → site not found in this environment. Stop in either case.
+
+---
+
+## 2. Check scan state
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/scan-site/scripts/poll-deep-scan.js" --portalId "<PORTAL_ID>" --once
+```
+
+`--once` does a single status check, exits 0, and prints:
+
+- `{ "status": "ongoing" }` → a scan is currently running.
+- `{ "status": "idle" }` → no scan running.
+
+Then call `get-latest-report.js` to know whether a completed report exists:
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/scan-site/scripts/get-latest-report.js" --portalId "<PORTAL_ID>"
+```
+
+`{ "status": "ok" }` means a report is available. `{ "status": "empty" }` means no completed scan exists.
+
+---
+
+## 3. Choose an action
+
+Skip in **review mode** — go straight to Step 4 (which always runs in review mode).
+
+MUST use plain language only. Never use words like CSP, CORS, OWASP, hardening, or scan profile.
+
+### Default approach
+
+Analyze the site's current state and **recommend the single most relevant action**. Present the recommendation with a plain-language explanation of why. The user can accept or choose differently.
+
+- Scan running, no completed report → recommend waiting for the running scan to finish.
+- Scan running, report exists → recommend showing the latest results while the new scan continues.
+- Idle, no completed report → recommend running a new scan.
+- Idle, recent report exists → ask whether to use the existing report or run a fresh scan.
+
+If the site's state does not warrant a specific recommendation, do not force one — ask what the user wants to do.
+
+### Option rules
+
+When presenting options via `AskUserQuestion`:
+- Keep `label` to 1–5 words. Include `description` on every option.
+- For options that trigger a new scan, surface the relevant caveats inside that option's `description` so the user has them at decision time. Do not ask a separate confirmation question after the user picks the option.
+- Include `preview` only when the option represents a concrete change (starting a new scan). Do not add `preview` to "show latest" or informational choices.
+- Only show options that are actionable given the current state. If a scan is already running, do not offer "Start a new scan".
+- Mark "(Recommended)" only when the site's state justifies it.
+
+---
+
+## 4. Run the scan
+
+In **review mode**, always execute this step: if a scan is already running, attach to it and poll; otherwise start a fresh scan and poll. Do not ask — review mode runs end-to-end without user interaction.
+
+In interactive mode, skip if the user chose to view the latest results.
+
+Start the scan:
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/scan-site/scripts/start-deep-scan.js" --portalId "<PORTAL_ID>"
+```
+
+If stdout is `{ "status": "already-running" }`, skip ahead to polling — there is already a scan in progress.
+
+Then poll for completion:
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/scan-site/scripts/poll-deep-scan.js" --portalId "<PORTAL_ID>"
+```
+
+Run polling with `run_in_background: true` so the user can keep working. The script exits when the scan finishes or the timeout passes (default 20 minutes). If it times out, fetch whatever report is available and note the timeout in the summary.
+
+---
+
+## 5. Fetch and summarize
+
+### 5.1 Fetch and transform the report
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/scan-site/scripts/transform-report.js" --portalId "<PORTAL_ID>"
+```
+
+Parse the stdout JSON. The status field can be:
+
+- `ok` — a normal report with `findings` and `details`.
+- `empty` — no completed scan exists for this site (e.g., fresh site or scan still running). Record a single `info` finding explaining this and continue.
+- `malformed` — the API returned a response missing the `Rules` array. The transform emits a single `warning` finding describing this; surface it to the user and recommend re-running the scan.
+
+See `references/scan-reference.md` for the `Risk` → severity mapping the script applies.
+
+### 5.2 Review mode
+
+In **review mode**, skip the HTML report and write the transform stdout to `<REVIEW_DIR>/scan-site.json`. Then stop. The transform emits `{ status, findings, details }`; the orchestrating skill handles presentation.
+
+### 5.3 Render HTML report
+
+Skip in **review mode**.
+
+Render uses the same shared template as the consolidated security review. Build a single-section review-data payload, then render:
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/scripts/build-review-data.js" \
+ --reportName "Site Scan" \
+ --inputDir "<TEMP_DIR>" \
+ --siteName "<SITE_NAME>" \
+ --goalLabel "Live Site Scan" \
+ --scopeLabel "<SCOPE_LABEL>" \
+ --summary "<SUMMARY_TEXT>" \
+ --output "<TEMP_DIR>/data.json"
+
+node "${CLAUDE_PLUGIN_ROOT}/scripts/render-review.js" \
+ --data "<TEMP_DIR>/data.json" \
+ --output "<PROJECT_ROOT>/docs/site-scan-<YYYY-MM-DD-HHMMSS>.html"
+```
+
+`<TEMP_DIR>` should contain only `scan-site.json` (the transform output from Step 5.1) — `build-review-data.js` ignores intermediate files. The filename **must** include the local timestamp (e.g., `site-scan-2026-05-14-053805.html`). Delete `<TEMP_DIR>` after the render succeeds. Open the rendered HTML in the browser.
+
+### 5.4 Present summary
+
+Plain-language summary in the chat: total findings, count by severity, and what changed since the last scan if available. Do not lead with technical names.
+
+### 5.5 Record skill usage
+
+> Reference: `${CLAUDE_PLUGIN_ROOT}/references/skill-tracking-reference.md`
+>
+> Use `--skillName "ScanSite"`.
+
+---
+
+## 6. Walk through follow-ups
+
+Skip in **review mode**. Skip if the report has no issues.
+
+Group findings by which downstream skill can help:
+
+- Header / cookie issues → `/manage-headers`
+- WAF / firewall issues (block bots, rate-limit pages, restrict IPs/countries) → `/manage-firewall`
+- Permission issues → `/audit-permissions` to review existing table permissions, and/or `/create-webroles` to set up role-based access
+- Login or external identity issues → `/setup-auth`
+- Code-level issues (exposed debug pages, information leakage, source visible publicly) → suggest a manual code fix; there is no routed skill for these findings
+
+Suggest only the skills that match findings actually present in the report. If a finding does not map to any skill, surface it as a manual follow-up the user can act on. If no meaningful follow-up exists, end the skill — do not ask just to ask.
+
+---
+
+## Constraints
+
+- **Plain language** — MUST NOT use technical jargon with the user. Use everyday language; explain the technical name only when asked.
+- **Read-only** — this skill only runs scans and reads results. It never enables WAF, deletes scans, or changes site configuration.
+- **Background long-running calls** — start the scan, then poll via `run_in_background: true` so the user can continue working.
+- **Context-aware interactions** — every recommendation MUST reflect the site's current state:
+ - Never offer "Start a new scan" while one is already running.
+ - Never offer "Show latest results" when no completed report exists.
+ - Mark "(Recommended)" only when the state justifies it.
+- **Preview is for change review only** — include `preview` only on options that start a new scan. Do not add to navigation or informational choices.
+
+## References
+
+- `references/commands.md` — script flags, response shapes, error catalogue, operating notes. Read § "Common error catalogue" when a script returns a non-zero exit code.
+- `references/scan-reference.md` — field-level schema for the deep-scan report, alert risk values, rule statuses, and severity mapping. Read when normalizing findings.
diff --git a/plugins/power-pages/skills/scan-site/references/commands.md b/plugins/power-pages/skills/scan-site/references/commands.md
new file mode 100644
index 000000000..baca0542e
--- /dev/null
+++ b/plugins/power-pages/skills/scan-site/references/commands.md
@@ -0,0 +1,280 @@
+# Scan Site — Commands
+
+Reference for the helper scripts under `scripts/`. Every script is non-interactive, accepts flags only, and prints a JSON object on stdout. All scripts support `--help` to display usage, flags, examples, and exit codes. The first stage is always context resolution from the shared `power-platform-api` client, so every script can fail with exit code `2` ("sign-in required") before doing any work.
+
+## Shared exit codes
+
+Every script in this skill can exit with the following codes. Script-specific codes are documented in their own sections.
+
+| Code | Meaning |
+|------|---------|
+| `0` | Success. For `website.js`, a `null` response is still exit code 0 — the caller decides how to handle it. For `start-deep-scan.js`, a scan-already-running outcome (`Z003` / HTTP 204) is also exit 0 with `{ "status": "already-running" }`. |
+| `1` | General failure. Covers service errors, bad requests, authorization failures, and any other non-success response. The error message on stderr contains the HTTP status code and service error code. |
+| `2` | Sign-in required. Fix with `pac auth create` or `az login`. |
+| `3` | Polling timed out (`poll-deep-scan.js` only). |
+
+## Table of contents
+
+- [Identifiers — websiteId vs. portalId](#identifiers--websiteid-vs-portalid)
+- [Resolving the website — `website.js`](#resolving-the-website--websitejs)
+- [`start-deep-scan.js`](#start-deep-scanjs)
+- [`poll-deep-scan.js`](#poll-deep-scanjs)
+- [`get-latest-report.js`](#get-latest-reportjs)
+- [`transform-report.js`](#transform-reportjs)
+- [Common error catalogue](#common-error-catalogue)
+- [Operating notes](#operating-notes)
+
+---
+
+## Identifiers — websiteId vs. portalId
+
+Two different GUIDs identify a Power Pages site. Keep them straight:
+
+| Identifier | Where it comes from | What it is |
+|------------|---------------------|------------|
+| `websiteId` | `.powerpages-site/website.yml` (`id` field), `pac pages list` ("Website Record ID") | Dataverse website record primary key. The user-facing identifier. |
+| `portalId` | `Id` field on the `/websites` Power Platform API response | The `{id}` segment in Power Platform API URL paths such as `/websites/{id}/scan/...`. |
+
+These are **not** the same value. The skill resolves `websiteId` → `portalId` once during prerequisites (using `website.js --websiteId <guid>`) and reuses the resolved `portalId` for the rest of the run. The consumer scripts in this folder accept `--portalId` only — they never look up the site themselves.
+
+---
+
+## Resolving the website — `website.js`
+
+The shared `scripts/website.js` resolves a Dataverse `websiteId` (read from `.powerpages-site/website.yml`) to its full website record, which includes the `Id` field — the portalId.
+
+A missing `.powerpages-site/website.yml` means the site has not been deployed yet — direct the user to `/deploy-site`.
+
+### Usage
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/scripts/website.js" --websiteId <guid>
+```
+
+### Parameters
+
+| Flag | Required | Description |
+|----------------|----------|-------------|
+| `--websiteId` | Yes | Dataverse website record id to resolve. |
+
+The field projection includes `Id`, `Name`, `WebsiteRecordId`, `WebsiteUrl`, `Type`, `status`, `Subdomain`, `SiteVisibility`, `PortalWAFStatus`, `PortalAFDStatus`, and `TrialExpiringInDays`.
+
+### Response (stdout)
+
+A single matching website record (or `null` when no record matches). Pass the `Id` field as `--portalId` to every consumer script in this skill.
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| `0` | Success (`null` is also success — caller decides what to do). |
+| `2` | Sign-in required. |
+| `1` | Service error. |
+
+---
+
+## `start-deep-scan.js`
+
+Triggers an asynchronous deep scan. The service runs the scan in the background; use `poll-deep-scan.js` to wait for completion.
+
+### Usage
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/scan-site/scripts/start-deep-scan.js" --portalId <portal-id>
+```
+
+### Parameters
+
+| Flag | Required | Description |
+|----------------|----------|-------------|
+| `--portalId` | Yes | Power Platform API portalId resolved during prerequisites |
+
+### Response (stdout)
+
+```json
+{ "status": "started" }
+```
+
+…or, when a scan is already running:
+
+```json
+{ "status": "already-running" }
+```
+
+### Errors
+
+| Status / `code` | Meaning |
+|---------------------|---------|
+| `204` or `400 / Z003` | A scan is already running for this site. Treated as success (exit 0). |
+| `400 / A019` | Invalid portalId format. |
+| `404 / A001` | Site not found in this environment. |
+| `401 / D004` | Caller not authorized. |
+
+---
+
+## `poll-deep-scan.js`
+
+Polls the scan-status endpoint until the scan finishes or the timeout elapses.
+
+### Usage
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/scan-site/scripts/poll-deep-scan.js" --portalId <portal-id> [--timeoutMinutes <n>] [--intervalSeconds <n>]
+node "${CLAUDE_PLUGIN_ROOT}/skills/scan-site/scripts/poll-deep-scan.js" --portalId <portal-id> --once
+```
+
+### Parameters
+
+| Flag | Required | Default | Description |
+|-----------------------|----------|---------|-------------|
+| `--portalId` | Yes | — | Power Platform API portalId resolved during prerequisites |
+| `--timeoutMinutes` | No | `20` | Maximum time to wait. |
+| `--intervalSeconds` | No | `60` | Pause between status checks. |
+| `--once` | No | — | Single status check, no polling. Exits 0 with `{ "status": "ongoing" \| "idle" }`. |
+
+### Response (stdout)
+
+Polling mode:
+
+```json
+{ "status": "done", "elapsedSeconds": "<count>" }
+```
+
+…or, when the timeout passes:
+
+```json
+{ "status": "timeout", "elapsedSeconds": "<count>" }
+```
+
+Single-shot (`--once`) mode:
+
+```json
+{ "status": "<ongoing|idle>" }
+```
+
+The script also accepts `"true"` (string) and `1` (integer) as truthy variants of the status field. See `scan-reference.md` § "Scan progress" for the endpoint shape.
+
+### Exit codes
+
+| Code | Meaning |
+|------|---------|
+| `0` | Scan finished. |
+| `3` | Timeout. |
+| `2` | Sign-in required. |
+| `1` | Service error. |
+
+### Notes
+
+- Run with `run_in_background: true` so the user can keep working.
+- Progress lines are written to **stderr** every minute for monitoring; they are not user-facing.
+
+---
+
+## `get-latest-report.js`
+
+Fetches the latest completed deep-scan report. Outputs the full report JSON to stdout.
+
+### Usage
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/scan-site/scripts/get-latest-report.js" --portalId <portal-id>
+```
+
+### Parameters
+
+| Flag | Required | Description |
+|----------------|----------|-------------|
+| `--portalId` | Yes | Power Platform API portalId resolved during prerequisites |
+
+### Response (stdout)
+
+On success:
+
+```json
+{ "status": "ok", "body": { /* deep-scan report */ } }
+```
+
+When no scan has completed yet (HTTP 204 / `Z003`):
+
+```json
+{ "status": "empty" }
+```
+
+Treat `empty` as an `info` finding rather than an error.
+
+See `scan-reference.md` for the full field-level schema of the report body.
+
+### Errors
+
+| Status / `code` | Meaning |
+|---------------------|---------|
+| `204` | No completed scan exists yet — a scan may be running. Returns `{ "status": "empty" }` (exit 0). |
+| `400 / A001` | Site not found. |
+| `400 / A010` | Invalid input. |
+| `500 / A009` | Service-side failure. |
+
+---
+
+## `transform-report.js`
+
+Transforms a deep-scan report into the unified findings shape used by the consolidated security review.
+
+### Usage
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/skills/scan-site/scripts/transform-report.js" --portalId <portal-id>
+node "${CLAUDE_PLUGIN_ROOT}/skills/scan-site/scripts/transform-report.js" --reportFile <report-file>
+```
+
+### Parameters
+
+| Flag | Required | Description |
+|------|----------|-------------|
+| `--portalId` | One of the two | Power Platform API portalId. Fetches the latest report directly. |
+| `--reportFile` | One of the two | Path to a previously saved raw report JSON. Skips the API call. |
+
+### Response (stdout)
+
+Normal report:
+
+```json
+{ "status": "ok", "findings": [ ], "details": { "kind": "kv", "label": "Scan details", "entries": [ ] } }
+```
+
+No completed scan exists for this site (fresh site, or current scan still running). The script emits a single `info` finding so review-mode output never produces an empty section:
+
+```json
+{ "status": "empty", "findings": [{ "id": "scan-site-empty", "severity": "info", "title": "No completed scan report available", "details": "..." }], "details": {} }
+```
+
+API returned a response missing the `Rules` array — the report cannot be parsed. The script emits a single `warning` finding so the orchestrator can surface the failure:
+
+```json
+{ "status": "malformed", "findings": [{ "id": "scan-site-malformed", "severity": "warning", "title": "Scan report could not be parsed", "details": "..." }], "details": {} }
+```
+
+Each finding: `{ id, severity, category?, title, tag, location?, details, fix? }`. See `scan-reference.md` § "Severity mapping" for how `Risk` and `RuleStatus` map to `severity`.
+
+---
+
+## Common error catalogue
+
+These error codes appear in service responses. Map them to friendly messages before showing them to the user.
+
+| Code | Meaning | Exit code | Friendly message |
+|--------|---------------------------------------|-----------|------------------|
+| `A001` | Site does not exist | `1` | "I could not find that site in this environment." |
+| `A009` | Service-side failure | `1` | "Something went wrong on the service side. Try again in a few minutes." |
+| `A010` | Required value is missing or empty | `1` | "Some required value was missing — try again or pick the site again." |
+| `A019` | Site id is not a valid identifier | `1` | "The site identifier is not in the right format." |
+| `A033` | Tenant mismatch | `1` | "The signed-in account does not belong to the same tenant as the site." |
+| `D004` | Caller is not authorized | `1` | "Your account does not have permission to run this. Ask an admin." |
+| `Z003` | Scan already running | `0` | "A scan is already running for this site." |
+
+When `website.js --websiteId` returns `null`, the skill stops with a local error before any consumer script runs.
+
+## Operating notes
+
+- Only one scan per site at a time. Running two starts in quick succession returns `Z003`; treat that as a normal "already running" outcome.
+- When the scan finishes, the service sends an email notification to the admin. The report summary is also available in the Security workspace and can be downloaded as a PDF. Report summaries are supported in English (US) only.
+- Resolution is a single Power Platform API call during prerequisites. The rest of the workflow uses the cached portalId.
diff --git a/plugins/power-pages/skills/scan-site/references/scan-reference.md b/plugins/power-pages/skills/scan-site/references/scan-reference.md
new file mode 100644
index 000000000..8cc9a4ddd
--- /dev/null
+++ b/plugins/power-pages/skills/scan-site/references/scan-reference.md
@@ -0,0 +1,145 @@
+# Scan Reference
+
+Field-level schema for the scan report returned by `get-latest-report.js`. Use this when normalizing alerts into the unified report findings.
+
+> **Terminology**: the API returns **alerts** at the rule level. The skill normalizes them into **findings** in the unified report.
+
+## Table of contents
+
+- [Report envelope](#report-envelope)
+- [Rule](#rule)
+- [Alert](#alert)
+- [Risk values](#risk-values)
+- [Rule statuses](#rule-statuses)
+- [Severity mapping](#severity-mapping)
+- [Scan progress](#scan-progress)
+
+---
+
+## Report envelope
+
+The scan report returned by `get-latest-report.js` (under `body`). Field keys use **PascalCase**.
+
+```json
+{
+ "TotalRuleCount": <count>,
+ "FailedRuleCount": <count>,
+ "TotalAlertCount": <count>,
+ "UserName": "<account-or-null>",
+ "StartTime": "<iso-8601-utc>",
+ "EndTime": "<iso-8601-utc>",
+ "Rules": [ ]
+}
+```
+
+| Field | Type | Required | Valid values / format |
+|-------|------|----------|----------------------|
+| `TotalRuleCount` | integer | Yes | Total number of rules evaluated. |
+| `FailedRuleCount` | integer | Yes | Rules that produced one or more alerts. |
+| `TotalAlertCount` | integer | Yes | Total number of alerts across all rules. |
+| `UserName` | string \| null | No | Account that started the scan. `null` for anonymous scans. |
+| `StartTime` | string | Yes | ISO 8601 UTC timestamp (suffixed with `Z`). |
+| `EndTime` | string | Yes | ISO 8601 UTC timestamp (suffixed with `Z`). |
+| `Rules` | array | Yes | Per-rule results. See [Rule](#rule). May be empty. |
+
+---
+
+## Rule
+
+Each object in the `Rules` array. Field keys use **PascalCase**.
+
+```json
+{
+ "RuleId": "<id>",
+ "RuleName": "<name>",
+ "RuleStatus": "<RulePassed|RuleFailed|RuleNotRun|RuleTimedOut>",
+ "AlertsCount": <count>,
+ "Alerts": [ ]
+}
+```
+
+| Field | Type | Required | Valid values / format |
+|-------|------|----------|----------------------|
+| `RuleId` | string | Yes | Stable rule identifier. |
+| `RuleName` | string | Yes | Human-readable rule name. |
+| `RuleStatus` | string | Yes | See [Rule statuses](#rule-statuses). |
+| `AlertsCount` | integer | Yes | Number of alerts produced by this rule. `0` when the rule passed or did not run. |
+| `Alerts` | array | Yes | Findings produced by the rule. Empty array when `RuleStatus` is `RulePassed`, `RuleNotRun`, or `RuleTimedOut`. See [Alert](#alert). |
+
+---
+
+## Alert
+
+Each object in the `Alerts` array. Field keys use **PascalCase**.
+
+```json
+{
+ "AlertId": "<id>",
+ "AlertName": "<name>",
+ "Description": "<plain-language>",
+ "Mitigation": "<plain-language>",
+ "Risk": <0-3>,
+ "RuleId": "<id>",
+ "LearnMoreLink": [ ],
+ "CallToAction": [ ]
+}
+```
+
+| Field | Type | Required | Valid values / format |
+|-------|------|----------|----------------------|
+| `AlertId` | string | Yes | Stable alert identifier. |
+| `AlertName` | string | Yes | Short title for the finding. |
+| `Description` | string | Yes | What was detected, in plain language. |
+| `Mitigation` | string | Yes | Suggested fix, in plain language. |
+| `Risk` | integer | Yes | Severity as a numeric code. See [Risk values](#risk-values). |
+| `RuleId` | string | Yes | Identifier of the rule that produced this alert. |
+| `LearnMoreLink` | array of strings | No | URLs with background reading. May be absent or empty. |
+| `CallToAction` | array of strings | No | Suggested follow-up actions. May be absent or empty. |
+
+---
+
+## Risk values
+
+| Value | Meaning |
+|-------|---------|
+| `0` | Informational |
+| `1` | Low |
+| `2` | Medium |
+| `3` | High |
+
+There is no `Critical` value — `3` (High) is the maximum severity returned.
+
+## Rule statuses
+
+| Value | Meaning |
+|-------|---------|
+| `RulePassed` | Rule ran and produced no alerts. |
+| `RuleFailed` | Rule ran and produced one or more alerts. |
+| `RuleNotRun` | Rule did not run (e.g., not applicable to the site). |
+| `RuleTimedOut` | Rule started but did not finish within the time budget. |
+
+## Severity mapping
+
+`transform-report.js` maps each alert `Risk` to a finding `severity`, mirroring the Power Pages Studio classification:
+
+| Risk value | Studio label | `severity` |
+|------------|--------------|------------|
+| `3` (High) | Critical | `critical` |
+| `2` (Medium) | Warning | `warning` |
+| `1` (Low) | Warning | `warning` |
+| `0` (Informational) | Info | `info` |
+| missing | Warning | `warning` |
+
+`RulePassed` → `pass`. `RuleNotRun` / `RuleTimedOut` → `warning`.
+
+## Scan progress
+
+The scan-status check (used by `poll-deep-scan.js`) returns:
+
+```json
+{ "status": <true|false> }
+```
+
+| Field | Type | Required | Valid values / format |
+|-------|------|----------|----------------------|
+| `status` | boolean | Yes | `true` while a scan is running. `false` when idle. |
diff --git a/plugins/power-pages/skills/scan-site/scripts/get-latest-report.js b/plugins/power-pages/skills/scan-site/scripts/get-latest-report.js
new file mode 100644
index 000000000..1a09695d9
--- /dev/null
+++ b/plugins/power-pages/skills/scan-site/scripts/get-latest-report.js
@@ -0,0 +1,65 @@
+#!/usr/bin/env node
+
+const {
+ resolveContext,
+ request,
+ parseCliArgs,
+ fail,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+
+const REQUEST_TIMEOUT_MS = 240_000; // 4 min — report fetch can be slow when alerts are numerous.
+
+const HELP = `get-latest-report.js — Fetches the latest completed deep-scan report.
+
+Usage:
+ node get-latest-report.js --portalId <portal-id>
+
+Flags:
+ --portalId Power Platform API portal identifier (resolved during prerequisites)
+ --help Show this help message
+
+Exit codes:
+ 0 Success (also returns { status: "empty" } when no scan has completed)
+ 2 Sign-in required
+ 1 Other failure
+
+Example:
+ node get-latest-report.js --portalId <portal-id>
+`;
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const { portalId } = parseCliArgs(process.argv);
+ if (!portalId) {
+ fail('Usage: node get-latest-report.js --portalId <portal-id>', 1);
+ }
+
+ const ctx = resolveContext();
+ if (ctx.error) fail(ctx.error, 2);
+
+ const res = await request({
+ context: ctx,
+ method: 'GET',
+ path: `/websites/${portalId}/scan/deep/getLatestCompletedReport`,
+ timeout: REQUEST_TIMEOUT_MS,
+ });
+
+ // 204 means a scan is in progress and no completed report exists yet.
+ if (res.statusCode === 204) {
+ process.stdout.write(JSON.stringify({ status: 'empty' }) + '\n');
+ return;
+ }
+
+ if (!res.ok) {
+ fail(`Get latest report failed (${res.statusCode}): ${res.error?.message || ''}`, 1);
+ }
+
+ process.stdout.write(JSON.stringify({ status: 'ok', body: res.body || {} }) + '\n');
+}
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/scan-site/scripts/poll-deep-scan.js b/plugins/power-pages/skills/scan-site/scripts/poll-deep-scan.js
new file mode 100644
index 000000000..1b9827175
--- /dev/null
+++ b/plugins/power-pages/skills/scan-site/scripts/poll-deep-scan.js
@@ -0,0 +1,130 @@
+#!/usr/bin/env node
+
+const {
+ resolveContext,
+ request,
+ parseCliArgs,
+ parseTimeoutMs,
+ fail,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+
+const DEFAULT_TIMEOUT_MIN = 20;
+const DEFAULT_INTERVAL_SEC = 60;
+const PROGRESS_LOG_MS = 60_000;
+
+const HELP = `poll-deep-scan.js — Polls the deep-scan status endpoint until completion or timeout.
+
+Usage:
+ node poll-deep-scan.js --portalId <portal-id> [--timeoutMinutes <n>] [--intervalSeconds <n>]
+ node poll-deep-scan.js --portalId <portal-id> --once
+
+Flags:
+ --portalId Power Platform API portal identifier (resolved during prerequisites)
+ --timeoutMinutes Maximum wait time (default: ${DEFAULT_TIMEOUT_MIN})
+ --intervalSeconds Pause between status checks (default: ${DEFAULT_INTERVAL_SEC})
+ --once Single status check, no polling. Returns { "status": "ongoing" | "idle" } and exits 0.
+ --help Show this help message
+
+Exit codes:
+ 0 Scan completed (or single check returned current state when --once)
+ 3 Polling timed out
+ 2 Sign-in required
+ 1 Other failure
+
+Example:
+ node poll-deep-scan.js --portalId <portal-id>
+ node poll-deep-scan.js --portalId <portal-id> --once
+ node poll-deep-scan.js --portalId <portal-id> --timeoutMinutes <minutes>
+`;
+
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+// API may return status as boolean, "true"/"false" string, or 0/1 number.
+function isOngoing(body) {
+ return body?.status === true || body?.status === 'true' || body?.status === 1;
+}
+
+function parsePositiveSeconds(value, defaultSec, flagName) {
+ const seconds = value === undefined ? defaultSec : Number(value);
+ if (!Number.isFinite(seconds) || seconds <= 0) {
+ fail(`Invalid --${flagName} value "${value}". Must be a positive number.`, 1);
+ }
+ return seconds * 1000;
+}
+
+async function fetchOngoing(ctx, portalId) {
+ const res = await request({
+ context: ctx,
+ method: 'GET',
+ path: `/websites/${portalId}/scan/deep/isongoing`,
+ });
+ if (!res.ok) {
+ fail(`Status check failed (${res.statusCode}): ${res.error?.message || ''}`, 1);
+ }
+ return isOngoing(res.body);
+}
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const args = parseCliArgs(process.argv);
+ const { portalId, once } = args;
+ if (!portalId) {
+ fail(
+ 'Usage: node poll-deep-scan.js --portalId <portal-id> ' +
+ '[--timeoutMinutes <n>] [--intervalSeconds <n>] [--once]',
+ 1
+ );
+ }
+
+ const ctx = resolveContext();
+ if (ctx.error) fail(ctx.error, 2);
+
+ if (once) {
+ const ongoing = await fetchOngoing(ctx, portalId);
+ process.stdout.write(JSON.stringify({ status: ongoing ? 'ongoing' : 'idle' }) + '\n');
+ return;
+ }
+
+ const timeoutMs = parseTimeoutMs(args.timeoutMinutes, DEFAULT_TIMEOUT_MIN);
+ const intervalMs = parsePositiveSeconds(
+ args.intervalSeconds,
+ DEFAULT_INTERVAL_SEC,
+ 'intervalSeconds'
+ );
+ const startTime = Date.now();
+ const deadline = startTime + timeoutMs;
+ let lastLog = 0;
+
+ while (Date.now() < deadline) {
+ if (!(await fetchOngoing(ctx, portalId))) {
+ process.stdout.write(
+ JSON.stringify({
+ status: 'done',
+ elapsedSeconds: Math.round((Date.now() - startTime) / 1000),
+ }) + '\n'
+ );
+ return;
+ }
+ if (Date.now() - lastLog >= PROGRESS_LOG_MS) {
+ const elapsed = Math.round((Date.now() - startTime) / 1000);
+ process.stderr.write(`Scan still running (${elapsed}s elapsed)\n`);
+ lastLog = Date.now();
+ }
+ await sleep(intervalMs);
+ }
+
+ process.stdout.write(
+ JSON.stringify({
+ status: 'timeout',
+ elapsedSeconds: Math.round((Date.now() - startTime) / 1000),
+ }) + '\n'
+ );
+ process.exit(3);
+}
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/scan-site/scripts/start-deep-scan.js b/plugins/power-pages/skills/scan-site/scripts/start-deep-scan.js
new file mode 100644
index 000000000..fc39dba0e
--- /dev/null
+++ b/plugins/power-pages/skills/scan-site/scripts/start-deep-scan.js
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+
+const {
+ resolveContext,
+ request,
+ parseCliArgs,
+ fail,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+
+const HELP = `start-deep-scan.js — Triggers an asynchronous deep scan.
+
+Usage:
+ node start-deep-scan.js --portalId <portal-id>
+
+Flags:
+ --portalId Power Platform API portal identifier (resolved during prerequisites)
+ --help Show this help message
+
+Exit codes:
+ 0 Success (scan started, or one is already running)
+ 2 Sign-in required
+ 1 Other failure
+
+Example:
+ node start-deep-scan.js --portalId <portal-id>
+`;
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const { portalId } = parseCliArgs(process.argv);
+ if (!portalId) {
+ fail('Usage: node start-deep-scan.js --portalId <portal-id>', 1);
+ }
+
+ const ctx = resolveContext();
+ if (ctx.error) fail(ctx.error, 2);
+
+ const res = await request({
+ context: ctx,
+ method: 'POST',
+ path: `/websites/${portalId}/scan/deep/start`,
+ });
+
+ if (res.statusCode === 202) {
+ process.stdout.write(JSON.stringify({ status: 'started' }) + '\n');
+ return;
+ }
+ // 204 / 400+Z003 both mean a scan is already in flight.
+ if (res.statusCode === 204 || (res.statusCode === 400 && res.error?.code === 'Z003')) {
+ process.stdout.write(JSON.stringify({ status: 'already-running' }) + '\n');
+ return;
+ }
+ fail(`Start deep scan failed (${res.statusCode}): ${res.error?.message || ''}`, 1);
+}
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/scan-site/scripts/transform-report.js b/plugins/power-pages/skills/scan-site/scripts/transform-report.js
new file mode 100644
index 000000000..bccfd7ab9
--- /dev/null
+++ b/plugins/power-pages/skills/scan-site/scripts/transform-report.js
@@ -0,0 +1,246 @@
+#!/usr/bin/env node
+
+const fs = require('fs');
+const {
+ resolveContext,
+ request,
+ parseCliArgs,
+ fail,
+ runCli,
+} = require('../../../scripts/lib/power-platform-api');
+
+const REQUEST_TIMEOUT_MS = 240_000; // 4 min — report fetch is slow with many alerts.
+
+// Risk → severity per scan-reference.md "Severity mapping".
+const RISK_TO_BUCKET = {
+ 3: 'critical',
+ 2: 'warning',
+ 1: 'warning',
+ 0: 'info',
+};
+
+const RULE_STATUS_BUCKET = {
+ RulePassed: 'pass',
+ RuleNotRun: 'warning',
+ RuleTimedOut: 'warning',
+ RuleFailed: 'warning', // only reachable when RuleFailed has zero alerts.
+};
+
+const RULE_STATUS_DETAILS = {
+ RulePassed: 'Rule ran and produced no alerts.',
+ RuleTimedOut: 'Rule started but did not finish within the time budget.',
+ RuleNotRun: 'Rule did not run for this site.',
+ RuleFailed: 'Rule reported a failure with no alerts attached — verify the scan report.',
+};
+
+const HELP = `transform-report.js — Transforms a deep-scan report into findings JSON.
+
+Usage:
+ node transform-report.js --portalId <portal-id>
+ node transform-report.js --reportFile <path>
+
+Flags:
+ --portalId Power Platform API portal identifier (resolved during prerequisites)
+ --reportFile Path to a previously saved raw report JSON (skips the API call)
+ --help Show this help message
+
+Exit codes:
+ 0 Success (status "ok", "empty", or "malformed")
+ 2 Sign-in required (only --portalId)
+ 1 Other failure
+
+Examples:
+ node transform-report.js --portalId <portal-id>
+ node transform-report.js --reportFile <report-file>
+`;
+
+// API timestamps arrive as "2026-05-14T05:35:57.0236778Z"; render as
+// "2026-05-14 05:35:57 UTC". Returns "unknown" for missing values so the HTML
+// never displays the literal string "undefined".
+function formatTimestamp(iso) {
+ if (iso == null) return 'unknown';
+ const match = String(iso).match(/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})/);
+ return match ? `${match[1]} ${match[2]} UTC` : String(iso);
+}
+
+function formatNumOrDash(value) {
+ return value == null ? '—' : String(value);
+}
+
+function malformedReport() {
+ process.stderr.write(
+ 'transform-report.js: report body missing "Rules" array — emitting "malformed" status.\n'
+ );
+ return {
+ status: 'malformed',
+ findings: [
+ {
+ id: 'scan-site-malformed',
+ severity: 'warning',
+ title: 'Scan report could not be parsed',
+ details:
+ 'The deep-scan API returned a response without the expected "Rules" array. ' +
+ 'Re-run the scan; if the problem persists, contact support.',
+ },
+ ],
+ details: {},
+ };
+}
+
+function failedRuleFinding(rule, alerts, id) {
+ // Alerts with missing/invalid Risk are filtered before Math.max so worstRisk is
+ // never NaN. Per scan-reference.md, missing risk → "warning".
+ const validRisks = alerts.map((a) => a.Risk).filter((r) => RISK_TO_BUCKET[r] !== undefined);
+ const worstRisk = validRisks.length > 0 ? Math.max(...validRisks) : null;
+ const severity = worstRisk !== null ? RISK_TO_BUCKET[worstRisk] : 'warning';
+
+ const description = alerts[0]?.Description || 'No description provided.';
+ const alertList = alerts.map((a) => `- ${a?.AlertName || '(unnamed alert)'}`).join('\n');
+ const mitigations = alerts
+ .map(
+ (a) =>
+ `- ${a?.AlertName || '(unnamed alert)'}: ${a?.Mitigation || 'No mitigation provided.'}`
+ )
+ .join('\n');
+ const learnMore = alerts
+ .flatMap((a) => a?.LearnMoreLink || [])
+ .filter((url, i, arr) => arr.indexOf(url) === i);
+
+ const count = alerts.length;
+ return {
+ id,
+ severity,
+ title: rule.RuleName,
+ tag: rule.RuleId,
+ location: learnMore[0] ?? null,
+ details: `${description}\n\n${count} alert${count === 1 ? '' : 's'}:\n${alertList}`,
+ fix: mitigations,
+ };
+}
+
+function passthroughRuleFinding(rule, id) {
+ const severity = RULE_STATUS_BUCKET[rule.RuleStatus] || 'warning';
+ const details =
+ RULE_STATUS_DETAILS[rule.RuleStatus] ||
+ `Rule reported an unrecognized status "${rule.RuleStatus}" — verify the scan report.`;
+ return { id, severity, title: rule.RuleName, tag: rule.RuleId, details };
+}
+
+function transform(reportBody) {
+ if (!reportBody || !Array.isArray(reportBody.Rules)) {
+ return malformedReport();
+ }
+
+ const findings = [];
+ let counter = 1;
+
+ for (const rule of reportBody.Rules) {
+ const alerts = Array.isArray(rule.Alerts) ? rule.Alerts : [];
+ const id = `scan-site-${counter++}`;
+ if (rule.RuleStatus === 'RuleFailed' && alerts.length > 0) {
+ findings.push(failedRuleFinding(rule, alerts, id));
+ } else {
+ findings.push(passthroughRuleFinding(rule, id));
+ }
+ }
+
+ const scanDetails = {
+ kind: 'kv',
+ label: 'Scan details',
+ entries: [
+ { key: 'Started', value: formatTimestamp(reportBody.StartTime) },
+ { key: 'Ended', value: formatTimestamp(reportBody.EndTime) },
+ { key: 'Rules evaluated', value: formatNumOrDash(reportBody.TotalRuleCount) },
+ { key: 'Rules failed', value: formatNumOrDash(reportBody.FailedRuleCount) },
+ { key: 'Alerts', value: formatNumOrDash(reportBody.TotalAlertCount) },
+ ],
+ };
+
+ return { status: 'ok', findings, details: scanDetails };
+}
+
+function emptyReport() {
+ return {
+ status: 'empty',
+ findings: [
+ {
+ id: 'scan-site-empty',
+ severity: 'info',
+ title: 'No completed scan report available',
+ details:
+ 'The deep-scan service has no completed report for this site yet. ' +
+ 'Either no scan has been run, or a scan is currently in progress. ' +
+ 'Wait for the active scan to finish, or start a new scan via `/scan-site`.',
+ },
+ ],
+ details: {},
+ };
+}
+
+function readReportFile(filePath) {
+ if (!fs.existsSync(filePath)) {
+ process.stderr.write(`Report file not found: ${filePath}\n`);
+ process.exit(1);
+ }
+ try {
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ } catch (err) {
+ process.stderr.write(`Failed to parse ${filePath}: ${err.message}\n`);
+ process.exit(1);
+ }
+}
+
+async function fetchReportBody(portalId) {
+ const ctx = resolveContext();
+ if (ctx.error) fail(ctx.error, 2);
+
+ const res = await request({
+ context: ctx,
+ method: 'GET',
+ path: `/websites/${portalId}/scan/deep/getLatestCompletedReport`,
+ timeout: REQUEST_TIMEOUT_MS,
+ });
+
+ if (res.statusCode === 204) return null;
+ if (!res.ok) {
+ fail(`Get latest report failed (${res.statusCode}): ${res.error?.message || ''}`, 1);
+ }
+ return res.body;
+}
+
+async function main() {
+ if (process.argv.includes('--help')) {
+ process.stdout.write(HELP);
+ return;
+ }
+
+ const { portalId, reportFile } = parseCliArgs(process.argv);
+
+ let reportBody;
+ if (reportFile) {
+ const raw = readReportFile(reportFile);
+ if (raw.status === 'empty') {
+ process.stdout.write(JSON.stringify(emptyReport()) + '\n');
+ return;
+ }
+ // Accept either get-latest-report.js stdout ({ status, body }) or the bare body.
+ reportBody = 'body' in raw ? raw.body : raw;
+ } else if (portalId) {
+ reportBody = await fetchReportBody(portalId);
+ if (reportBody == null) {
+ process.stdout.write(JSON.stringify(emptyReport()) + '\n');
+ return;
+ }
+ } else {
+ process.stderr.write(
+ 'Usage: node transform-report.js --portalId <portal-id> | --reportFile <report-file>\n'
+ );
+ process.exit(1);
+ }
+
+ process.stdout.write(JSON.stringify(transform(reportBody)) + '\n');
+}
+
+module.exports = { transform, emptyReport };
+
+runCli(module, main);
diff --git a/plugins/power-pages/skills/security-review/SKILL.md b/plugins/power-pages/skills/security-review/SKILL.md
new file mode 100644
index 000000000..517e9a94c
--- /dev/null
+++ b/plugins/power-pages/skills/security-review/SKILL.md
@@ -0,0 +1,290 @@
+---
+name: security-review
+description: >-
+ Runs a guided, end-to-end security review of a Power Pages site and
+ consolidates every finding into one HTML report covering the live
+ site, browser headers, firewall, authentication, and role-based
+ permissions. Use when the user wants a full security review, a
+ release-readiness check before publishing, an access-and-config
+ check during development, live site monitoring, or asks open-ended
+ questions like "review my site security", "is my site safe to ship",
+ "do a security check", "monitor my site" — even if they do not name
+ the individual checks.
+user-invocable: true
+argument-hint: "[optional natural-language hint about the goal]"
+allowed-tools: Read, Write, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList, Skill, Agent
+model: opus
+---
+
+> **Plugin check**: Run `node "${CLAUDE_PLUGIN_ROOT}/scripts/check-version.js"` — if it outputs a message, show it to the user before proceeding.
+
+# Review Security
+
+Guide the user through a full security review of their Power Pages site. Runs the matching focused skills and assembles every finding into a single HTML report.
+
+The skill never asks the user technical questions. The conversation stays in plain language.
+
+**Initial request:** $ARGUMENTS
+
+## Workflow
+
+The skill has six phases. Phases 2–5 each map to one conversation beat with the user; phases 1 and 6 are silent setup and cleanup. See `references/flow.md` for the rationale behind each beat.
+
+| Phase | What happens | User-facing beat |
+|-------|--------------|------------------|
+| 1 — Prerequisites | Locate project, set up working folders | (silent setup) |
+| 2 — Scope | Capture goal — one question, three answers, plain language | Ask the goal |
+| 3 — Skills | Run the matching skills, surface progress | Scan in progress |
+| 4 — Report | Build the consolidated report — totals + per-section findings | Results summary + Findings |
+| 5 — Present | Present results, offer remediation follow-ups | Next steps and guidance |
+| 6 — Cleanup | Remove temporary files | (silent cleanup) |
+
+## Task Tracking
+
+Create tasks in three groups. Mark each `in_progress` when starting, `completed` when done.
+
+**Group 1 — create at the start of prerequisites:**
+
+| Task subject | activeForm |
+|--------------|------------|
+| Check prerequisites | Checking prerequisites |
+
+Only this one task. Do not create any other tasks until prerequisites complete.
+
+**Group 2 — create after prerequisites complete:**
+
+| Task subject | activeForm |
+|--------------|------------|
+| Capture goal | Capturing goal |
+
+**Group 3 — create after the goal is captured:**
+
+| Task subject | activeForm |
+|--------------|------------|
+| Run skills | Running checks |
+| Build the report | Building the report |
+| Present findings | Presenting findings |
+| Clean up | Cleaning up |
+
+---
+
+## 1. Prerequisites
+
+### 1.1 Locate the project
+
+Use `Glob` to find `**/powerpages.config.json`. If none is found, tell the user the site needs to be created first with `/create-site`, then stop.
+
+For the `monitor` and `release` goals (any goal that delegates to `scan-site` or `manage-firewall`), also confirm that `.powerpages-site/website.yml` exists. If it does not, the site has not been deployed yet — tell the user (in plain language) the site needs to be deployed once before a live security review can run, recommend `/deploy-site`, then stop. Do **not** try to identify the site by name or URL — different sites can share the same name.
+
+For the `access-config` goal, the deploy check is not required: authentication, web roles, and table permissions are read from local YAML alone.
+
+### 1.2 Prepare a temporary working folder
+
+Create a fresh working directory: `<SYSTEM_TEMP>/security-review/`. The folder holds JSON data files emitted by each skill in **review mode**. The folder is removed in the cleanup step.
+
+If the folder already exists from a previous interrupted run, delete its contents (not the folder itself) before continuing.
+
+### 1.3 Determine the docs output path
+
+The final HTML always lives at `<PROJECT_ROOT>/docs/security-review-<YYYY-MM-DD-HHMMSS>.html` using the local timestamp at the start of the run (e.g. `security-review-2026-05-14-053805.html`). Always include the timestamp — do not use a bare `security-review.html` name. This keeps each run's report distinct.
+
+---
+
+## 2. Capture goal
+
+### 2.1 Ask the goal
+
+Ask the user with a single `AskUserQuestion` call. If the user's initial request already answers it, skip and continue.
+
+**Question — What to review?**
+
+| Label | Description |
+|-------|-------------|
+| Access & config | Check authentication, web roles, and table permissions. Works on local files only. |
+| Release readiness | Full review before publishing — checks everything. (Recommended) |
+| Deployed site | Check the live site for issues. Requires deployment. |
+
+Goal mapping (internal):
+
+| Label | Goal id | Skills |
+|-------|---------|------------|
+| Access & config | `access-config` | audit-permissions, setup-auth (read-only) |
+| Release readiness | `release` | scan-site, manage-headers, manage-firewall, audit-permissions, setup-auth (read-only) |
+| Deployed site | `monitor` | scan-site |
+
+### 2.2 Capture the chosen skill set
+
+Build a `selectedSkills` list based on the answer. Always include the read-only check of `setup-auth` for the `access-config` and `release` goals (it consists of reading existing YAML, not running the skill itself — see § 3.2 below). This is the **Access & Data Security Validation** component.
+
+---
+
+## 3. Run the matching skills
+
+Spawn each selected skill as a background subagent via the `Agent` tool. Each subagent invokes its skill with the argument `--review <SYSTEM_TEMP>/security-review/`. Each skill handles its own authentication, error reporting, and progress.
+
+### 3.1 Skill invocation via subagents
+
+Skills run as **parallel subagents** using the `Agent` tool.
+
+**Default — launch every Agent-eligible skill in one parallel batch.** Spawn all selected subagents in a single message with multiple `Agent` tool calls so they start concurrently. Each subagent runs with `run_in_background: true`. The Agent-eligible set is `scan-site`, `manage-headers`, `manage-firewall` — these all support `--review` mode. `scan-site` is the slowest (server-side scan, several minutes); the others typically finish within seconds.
+
+**Fallback — staggered launch.** If the harness rejects a parallel-batch call for any reason, launch `scan-site` first and then the remaining skills in a follow-up message. This is a tool-affordance fallback, not the preferred path.
+
+**Inline checks (run while subagents work).** `audit-permissions` and `setup-auth` do not support `--review` and MUST NOT be launched via `Agent` — handle them inline as described in § 3.2.
+
+Wait for all subagents to complete before proceeding to the report-building step.
+
+### 3.1.1 Subagent prompt pattern
+
+Each subagent receives a self-contained prompt that includes:
+
+1. The skill to invoke and the `--review` argument with the temp directory path
+2. The project root path so the skill can locate site files
+3. Any scope/depth parameters captured in the scope capture step
+
+Example subagent call:
+
+```
+Agent({
+ description: "Run scan-site",
+ prompt: "Invoke the skill `scan-site` with argument `--review <SYSTEM_TEMP>/security-review/`. The Power Pages project root is <PROJECT_ROOT>. <any additional scope parameters>. Write the **transform script stdout verbatim** to <SYSTEM_TEMP>/security-review/scan-site.json. Do NOT synthesize, augment, or re-classify the findings. If the skill fails, write { \"status\": \"skipped\", \"reason\": \"<plain-language reason>\" } instead.",
+ run_in_background: true
+})
+```
+
+**Verbatim rule:** the subagent's output JSON must contain only the findings emitted by the skill's transform script. The orchestrator must not append findings, rewrite titles, add severity, or otherwise editorialize.
+
+### 3.1.2 Expected output
+
+After all subagents complete, expect JSON files at `<SYSTEM_TEMP>/security-review/<skill-name>.json`. Each file has the shape `{ status, findings, details? }` produced by the skill's transform script:
+
+```text
+<SYSTEM_TEMP>/security-review/
+├── scan-site.json
+├── manage-headers.json
+├── manage-firewall.json
+└── audit-permissions.json (when invoked)
+```
+
+If a skill's subagent fails or is skipped, write a placeholder file with shape `{ "status": "skipped", "reason": "<plain-language reason>" }`. The report-building step renders this as a single non-severity finding for that section (no `severity` field, to stay consistent with § 3.1.3).
+
+### 3.1.3 Severity policy
+
+Only findings that come from a tool that genuinely outputs severity may carry a `severity` field:
+
+| Section | Source | Severity allowed? |
+|---------|--------|-------------------|
+| `scan-site` | deep-scan (ZAP) | Yes |
+| `manage-headers` | `transform-headers.js` (inventory) | **No** |
+| `manage-firewall` | `transform-firewall.js` (inventory) | **No** |
+| `audit-permissions` | Web roles & table permissions audit | **No** |
+| `setup-auth` | Site settings & auth-related source code audit | **No** |
+
+For inventory sections, do **not** add `severity` to findings — not even `info`. The subagent and orchestrator must write the transform output **verbatim** without inserting opinionated severity-bearing findings. The `tag` field is **also** off-limits as a severity workaround: it is reserved for short mechanical identifiers from tools (e.g. ZAP rule ids, CWE codes) and MUST NOT carry severity-equivalent strings (`critical`, `warning`, `info`), since the report template renders it as a visible chip next to the title.
+
+### 3.1.4 Annotations policy (plain-language text)
+
+The transform scripts for `manage-firewall` and `manage-headers` produce only structured raw data — they do **not** hardcode plain-language descriptions. The subagent must generate an annotations JSON file and pass it to the transform via `--annotations`. The annotations supply:
+
+- Plain-language description per rule / per header
+- Optional suggested fix when a genuine issue is present
+
+See each skill's `SKILL.md` § 5.1 for the annotation file shape. The agent's job is to write accurate, terse descriptions based on the raw data — not to invent severities or fabricate issues.
+
+### 3.2 Skills without `--review` mode
+
+`audit-permissions` and `setup-auth` do not support `--review`. Handle them inline (not as background subagents):
+
+- **audit-permissions** — invoke via the `Skill` tool (not `Agent`). The skill audits **both web roles and table permissions** — capture both in its output. After it completes, read its output and write `<SYSTEM_TEMP>/security-review/audit-permissions.json` in the unified `{ status, findings, details? }` shape (mapping each audit finding into the common finding fields: `id`, `title`, `location`, `details`, `fix`).
+- **setup-auth** — do not invoke as a skill. Instead, read `.powerpages-site/site-settings/` YAML files directly and check for:
+ - identity provider configured? (`Authentication/OpenIdConnect/*/Authority`)
+ - profile redirect disabled? (`Authentication/Registration/ProfileRedirectEnabled = false`)
+ - cookie SameSite setting? (`HTTP/SameSite/Default`)
+
+Write the resulting findings to `<SYSTEM_TEMP>/security-review/setup-auth.json` in the same format.
+
+**Field policy for both sections** — these are inventory sections, not tool-output severities (see § 3.1.3):
+
+- **Do NOT include a `severity` field** on any finding.
+- **Do NOT include a `tag` field.** The `tag` field is reserved for short mechanical identifiers from tools (`HTTP/X-Frame-Options`, ZAP rule id `10055`, CWE codes). It MUST NOT carry severity-equivalent strings (`critical`, `warning`, `info`) — the report template renders `tag` as a visible chip next to the title, so stashing LLM-judged severity there would visually re-introduce the severity bucketing this section explicitly forbids.
+
+### 3.3 Status updates
+
+Tell the user that all checks are running in parallel. As each subagent completes, give a short progress line (e.g., "Code check finished — 2 important issues, 4 smaller ones."). Avoid technical jargon. Do not narrate skill internal steps. Once all subagents have finished, confirm that all checks are complete before moving to the report-building step.
+
+---
+
+## 4. Build the consolidated report
+
+### 4.1 Consolidate
+
+Write up to four plain-language next-step recommendations as a JSON string array to `<SYSTEM_TEMP>/security-review/next-steps.json`. Compose a 2–4 sentence plain-language `summary` of the overall state.
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/scripts/build-review-data.js" \
+ --reportName "Security Review" \
+ --inputDir "<SYSTEM_TEMP>/security-review/" \
+ --siteName "<SITE_NAME>" \
+ --goalLabel "<GOAL_LABEL>" \
+ --scopeLabel "<SCOPE_LABEL>" \
+ --summary "<SUMMARY_TEXT>" \
+ --nextStepsFile "<SYSTEM_TEMP>/security-review/next-steps.json" \
+ --output "<SYSTEM_TEMP>/security-review/security-review-data.json"
+```
+
+### 4.2 Render the master HTML
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/scripts/render-review.js" \
+ --output "<DOCS_PATH>" \
+ --data "<SYSTEM_TEMP>/security-review/security-review-data.json"
+```
+
+---
+
+## 5. Present and follow-ups
+
+### 5.1 Open in browser
+
+Open `<DOCS_PATH>` in the user's default browser.
+
+### 5.2 Record skill usage
+
+> Reference: `${CLAUDE_PLUGIN_ROOT}/references/skill-tracking-reference.md`
+>
+> Use `--skillName "SecurityReview"`.
+
+### 5.3 In-chat summary
+
+Show a short plain-language summary in the chat: counts of critical / warning / info findings, where the report lives. Then offer the next action with `AskUserQuestion`:
+
+| Question | Options |
+|----------|---------|
+| What would you like to do next? | Walk me through the fixes; Re-run the review; Done for now |
+
+If the user picks "walk me through", group critical findings by section and offer the matching focused skill for each (`/manage-headers`, `/manage-firewall`, `/audit-permissions`, etc.).
+
+If the user picks "re-run", invoke this skill again with the same goal and scope.
+
+---
+
+## 6. Clean up
+
+Delete the entire `<SYSTEM_TEMP>/security-review/` folder. The final HTML, located in `docs/`, must remain. Confirm to the user that temporary files have been removed.
+
+If the cleanup fails (file lock, permission), warn the user and continue — the report is already written and the temp folder can be removed manually later.
+
+---
+
+## Constraints
+
+- **Plain language with users** — never lead with technical terms.
+- **Parallel subagent delegation** — every selected skill runs as a parallel subagent via the `Agent` tool, launched in a single message. Perform the inline read-only `setup-auth` check while subagents work. Use the staggered launch (§ 3.1 fallback) only if the harness rejects the parallel-batch call.
+- **Single consolidated HTML** — never produce per-skill HTML reports during this run. Skills run in `--review` mode.
+- **Same look and feel** — rendering goes through the shared template at `${CLAUDE_PLUGIN_ROOT}/scripts/lib/templates/security-review-report.html` via `scripts/render-review.js`. Do not author per-skill HTML or duplicate the template; the generated report must match the existing audit-permissions report visually.
+- **Cleanup is mandatory** — the cleanup step is not optional. Failing to clean up is treated as a non-fatal warning, but the skill always tries.
+- **Never run destructive sub-actions automatically** — skills that propose changes (e.g., editing site settings, deleting WAF rules) must operate in read-only `--review` mode during this orchestration. Apply changes only via the explicit "walk me through fixes" follow-up, after the user picks an action.
+
+## References
+
+- `references/flow.md` — rationale and example phrasing for the conversation beats in phases 2–5
diff --git a/plugins/power-pages/skills/security-review/references/flow.md b/plugins/power-pages/skills/security-review/references/flow.md
new file mode 100644
index 000000000..fc605f8a3
--- /dev/null
+++ b/plugins/power-pages/skills/security-review/references/flow.md
@@ -0,0 +1,54 @@
+# Conversation beats
+
+Rationale and example phrasing for phases 2–5 of the `security-review` skill. SKILL.md owns the executable workflow; this file explains *why* each user-facing beat looks the way it does so future edits stay consistent.
+
+Phases 1 (prerequisites) and 6 (cleanup) are silent — no conversation beat.
+
+## Phase 2 — Ask the goal
+
+One question, three answers. The three goals match the most common reasons a user opens a Power Pages security review:
+
+| Goal | When to use it |
+|------|-----------------|
+| Access & config | Frequent checks during development — pre-commit / pre-PR safety check. Covers Access & Data Security Validation (authentication, roles, table permissions) on local YAML. |
+| Release readiness | Last comprehensive check before pushing to production. Adds live site scan, browser headers, and firewall on top of access checks. |
+| Deployed site | Detect runtime issues from real user traffic on a deployed site. |
+
+Authentication and authorization checks (**Access & Data Security Validation**) are the focus of Access & config and are also bundled into Release readiness rather than being a separate goal. Splitting them into their own option created confusion about when to use them versus the other goals.
+
+Why not start by asking the user which skills to run? Because most users — including engineers — do not know the skill names yet, and listing them upfront reads as menu-driven interrogation. Ask the *outcome* the user wants and let the skill pick the right skills.
+
+Why no follow-up "are you sure?" prompt? Because the user just answered that question by picking a goal — asking again is friction without information. Surface any duration caveats inside the in-progress status line in phase 3 instead.
+
+## Phase 3 — Scan in progress
+
+Skills run as **parallel subagents launched in one batch** (see SKILL.md § 3.1). Open with a single line that names the slow check up front, then post a short progress line as each subagent completes. Examples:
+
+- "Starting checks — the live site scan can take several minutes. You can keep working while it runs."
+- "Permissions check finished — 1 important issue, 2 smaller ones."
+- "Live site scan finished — no critical issues found."
+- "All checks are complete."
+
+Do not narrate per-rule progress. Do not list every file scanned. The user wants reassurance, not telemetry.
+
+## Phase 4 — Results summary and findings
+
+After all subagents complete, the skill builds the consolidated HTML and shows, in chat:
+
+- A one-line headline ("All clear", or "1 important item to address", or "3 critical and 5 warning findings").
+- A two-line context sentence ("We checked X, Y, Z. We found N important and M smaller issues.").
+- A pointer to the saved HTML report.
+
+Put detail in the report, not in the chat. The HTML carries the per-section findings cards (title, severity, location, why this matters, suggested fix); the chat just orients the user.
+
+## Phase 5 — Next steps and guidance
+
+After the user has had a moment with the report, offer the next action with one `AskUserQuestion`: walk through the criticals now, re-run after changes, or stop here. Pick the option list to match the current state — if there are zero criticals, the offer to "walk through criticals" is not the first option.
+
+Always end with concrete, actionable next steps. Examples:
+
+- "Fix the three critical items in **Browser headers** (`/manage-headers`)."
+- "Run the full live-site scan once the headers are deployed (`/scan-site`)."
+- "Add a rate-limit rule to your sign-in pages (`/manage-firewall`)."
+
+The next steps are also stored in the consolidated HTML so the user can refer back to them after the chat session is over.