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.

power-pages: privacy-safe completion telemetry for audit-permissions (#712)

jagdeepms2425e30a29ffb3
diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.md
index a175f7453..48cacd520 100644
--- a/plugins/power-pages/AGENTS.md
+++ b/plugins/power-pages/AGENTS.md
@@ -505,6 +505,7 @@ This plugin ships 1DS telemetry for skill starts, approved create-site/localizat
- **Optional telemetry enrichment must load non-fatally.** `detect-site-framework` is required in its own `try/catch` that degrades to `null`, *not* in the hooks' mandatory require block. Bundling optional enrichment there would widen the blast radius of any packaging slip or syntax error from "no framework" to **no telemetry at all**. Apply the same separation to any future optional field.
- **Detection cost scales with the entry count of cwd.** A child miss performs one directory enumeration and at most two marker checks per immediate subdirectory; direct or upward site hits do not scan children. Typical directories cost single-digit ms against the hook's much larger PAC/agent-info work. It runs only *after* the hard-disabled / `isProvisioned` gates; user opt-out still builds the event because the local diagnostic mirror is retained.
- **`eventInfo` keys are independent.** Build the object unconditionally and assign it only when non-empty. Never nest a new key inside the `pacAuth.objectId` guard: that both drops the key on unauthenticated runs and throws on `undefined`, which the fail-closed wrapper swallows into *no event at all*.
+- **`audit-permissions` completion telemetry (`eventInfo.auditPermissions`).** `scripts/emit-audit-permissions-telemetry.js` emits one `audit_permissions_run_completed` event per run. `--action start` only writes local run state (a random UUID v4 run id and a monotonic start time) and emits nothing; the generic skill invocation event remains the start signal. Success is recorded only after `validate-audit.js` accepts the final HTML report. The payload is built from zeroed counters over `FINDINGS_DATA` and `SCORECARD_DATA` only, and must pass `scripts/lib/audit-telemetry-gate.js` (exact keys, enum or UUID v4 strings only, size caps) immediately before dispatch; a rejection sends nothing and does not consume the run. The event omits `orgId`, `tenantId`, `aadObjectId`, and `framework`, so it routes to the configured default region, and the repo kill switch writes no run state at all. The schema is documented in `shared/telemetry/README.md`; change that entry, the gate, and its tests together.
- **The bundled lib copy is CI-guarded.** `scripts/tests/telemetry-lib-copy.test.js` asserts byte-equality with `shared/telemetry/lib` (skipping when `shared/` is absent, i.e. an installed plugin) and exercises the copy's defensive branches — `shared/telemetry/tests` runs in its own workflow (`shared-telemetry-tests`), which compares this copy's bytes with the source whenever either changes but exercises only the source's behavior.
See `shared/telemetry/README.md` for the integration guide.
diff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.md
index 7583075b4..e00bf4de2 100644
--- a/plugins/power-pages/README.md
+++ b/plugins/power-pages/README.md
@@ -612,6 +612,16 @@ This plugin sends usage telemetry by default to help Microsoft improve it.
Events include skill name, plugin/PAC/agent versions, OS/Node versions, session and correlation IDs, and, when PAC is signed in, the Dataverse organization GUID and Entra tenant GUID.
When PAC exposes the signed-in user's Entra object ID, Power Pages stores it under `eventInfo.aadObjectId`; otherwise that field is omitted.
When you are working in a Power Pages code site, the site's SPA framework (`react`, `vue`, `angular`, or `astro`) is recorded under `eventInfo.framework`; that field is omitted otherwise. It names the scaffold only, never your site or its location.
+The generic skill invocation event records when `audit-permissions` starts. Its
+completion event records a random per-run ID, success or failure, elapsed
+duration, and aggregate report metrics under `eventInfo.auditPermissions`. A
+successful run means the final HTML report was generated and passed semantic
+validation. The aggregate metrics contain only fixed major/minor counts,
+category scores, dimension counts, and root-cause counts. They never include
+site, environment, tenant, user, table, role, permission, path, finding text, or
+report content. This identity-free completion event uses the configured default
+telemetry region.
+Events do not include file paths, prompts, tool inputs, site names, Dataverse URLs, credentials, usernames, or hostnames.
It also records approved create-site and localization choices, canonical locales, public localization package/version choices, stable validation failure codes, and localization completion data.
Events do not include file paths, prompts, tool inputs, site names, free-text requirements, Dataverse URLs, credentials, usernames, hostnames, private-use locale subtags, evidence URLs, or raw errors.
diff --git a/plugins/power-pages/scripts/emit-audit-permissions-telemetry.js b/plugins/power-pages/scripts/emit-audit-permissions-telemetry.js
new file mode 100644
index 000000000..da471c38b
--- /dev/null
+++ b/plugins/power-pages/scripts/emit-audit-permissions-telemetry.js
@@ -0,0 +1,471 @@
+#!/usr/bin/env node
+"use strict";
+
+const crypto = require("node:crypto");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const { isDeepStrictEqual } = require("node:util");
+
+const {
+ deriveAuditMetrics,
+ validateAuditMetrics,
+ validateReport,
+} = require("./lib/audit-report-validation");
+const { pick } = require("./lib/telemetry/lib/events");
+const { fireAndForget } = require("./lib/telemetry/lib/emit-spawn");
+const { readAiAgent } = require("./lib/telemetry/lib/agent-info");
+const {
+ EVENT_COMPLETED,
+ FAILURE_STAGES: FAILURE_STAGE_LIST,
+ UUID_V4_RE,
+ assertSafeOutgoingEvent,
+ isSafeContextToken,
+} = require("./lib/audit-telemetry-gate");
+
+const PLUGIN_ROOT = path.resolve(__dirname, "..");
+const TELEMETRY_DIR = path.join(__dirname, "lib", "telemetry");
+const DEFAULT_CONFIG_DIR = path.join(os.homedir(), ".power-platform-skills");
+const RUN_STATE_VERSION = 1;
+const METRICS_SCHEMA_VERSION = 1;
+const MAX_STATE_AGE_MS = 14 * 24 * 60 * 60 * 1000;
+const UUID_RE = UUID_V4_RE;
+const FAILURE_STAGES = new Set(FAILURE_STAGE_LIST);
+
+function parseArgs(argv) {
+ const args = {};
+ for (let index = 2; index < argv.length; index += 1) {
+ const token = argv[index];
+ if (!token.startsWith("--")) continue;
+ const value = argv[index + 1];
+ if (value !== undefined && !value.startsWith("--")) {
+ args[token.slice(2)] = value;
+ index += 1;
+ } else {
+ args[token.slice(2)] = true;
+ }
+ }
+ return args;
+}
+
+function configDir(env = process.env) {
+ return env.POWER_PLATFORM_SKILLS_CONFIG_DIR || DEFAULT_CONFIG_DIR;
+}
+
+function runsDir(dir) {
+ return path.join(dir, "telemetry", "power-pages", "audit-runs");
+}
+
+function statePath(dir, auditRunId) {
+ if (!UUID_RE.test(auditRunId)) throw new Error("invalid_run_id");
+ return path.join(runsDir(dir), `${auditRunId}.json`);
+}
+
+function completionPath(dir, auditRunId) {
+ if (!UUID_RE.test(auditRunId)) throw new Error("invalid_run_id");
+ return path.join(runsDir(dir), `${auditRunId}.completed`);
+}
+
+function readPluginVersion() {
+ try {
+ const manifest = JSON.parse(
+ fs.readFileSync(path.join(PLUGIN_ROOT, ".claude-plugin", "plugin.json"), "utf8")
+ );
+ return typeof manifest.version === "string" ? manifest.version : "unknown";
+ } catch {
+ return "unknown";
+ }
+}
+
+function readTelemetryConfig(env = process.env) {
+ const ikeyPath =
+ env.POWER_PLATFORM_SKILLS_IKEY_JSON ||
+ path.join(TELEMETRY_DIR, "ikey.json");
+ try {
+ const cfg = JSON.parse(fs.readFileSync(ikeyPath, "utf8"));
+ return {
+ cfg,
+ ikeyPath,
+ eventStreamName: typeof cfg.event_stream_name === "string" ? cfg.event_stream_name : "",
+ };
+ } catch {
+ return { cfg: null, ikeyPath, eventStreamName: "" };
+ }
+}
+
+// Repo kill switch, mirroring the shared dispatcher's isDisabledByConfig(): a
+// missing/unreadable ikey.json or `"disabled": true` means telemetry is HARD
+// OFF, which the shared contract defines as zero side effects (no local mirror,
+// no POST). Run-state files live under the telemetry directory, so they must
+// not be written either. This is intentionally NOT the user opt-out: an
+// opted-out user still gets the local mirror, so run state remains valid there.
+function isHardDisabled(telemetry) {
+ return !telemetry.cfg || telemetry.cfg.disabled === true;
+}
+
+function osFriendlyName(platform) {
+ if (platform === "win32") return "Windows";
+ if (platform === "darwin") return "Mac";
+ if (platform === "linux") return "Linux";
+ return platform;
+}
+
+function eventContext(sessionId, eventInfo, outcome, durationMs) {
+ const agent = readAiAgent();
+ const fields = {
+ pluginName: "power-pages",
+ pluginVersion: readPluginVersion(),
+ sessionId,
+ correlationId: crypto.randomUUID(),
+ osName: osFriendlyName(process.platform),
+ osVersion: os.release(),
+ nodeVersion: `v${String(process.versions.node).split(".")[0]}`,
+ skillName: "audit-permissions",
+ eventInfo,
+ };
+ // Agent name/version come from host env vars (AI_AGENT_NAME can be any
+ // string). Omit them unless they are plain product tokens, so an unusual host
+ // value is dropped here instead of making the outbound gate reject the event.
+ if (isSafeContextToken(agent.aiAgentName)) fields.aiAgentName = agent.aiAgentName;
+ if (isSafeContextToken(agent.aiAgentVersion)) fields.aiAgentVersion = agent.aiAgentVersion;
+ if (outcome !== undefined) fields.outcome = outcome;
+ if (durationMs !== undefined) fields.durationMs = durationMs;
+ return fields;
+}
+
+// Builds the single audit-permissions telemetry event. Run start is local state
+// only, so the completion event is the only shape this emitter produces.
+function buildCompletionEvent(eventStreamName, input) {
+ const data = pick(input, [
+ "pluginName",
+ "pluginVersion",
+ "sessionId",
+ "correlationId",
+ "osName",
+ "osVersion",
+ "nodeVersion",
+ "pacCliVersion",
+ "aiAgentName",
+ "aiAgentVersion",
+ "eventInfo",
+ "skillName",
+ "outcome",
+ "durationMs",
+ ]);
+ return {
+ name: eventStreamName,
+ data: {
+ eventName: EVENT_COMPLETED,
+ eventType: "Trace",
+ severity: data.outcome === "failure" ? "Error" : "Info",
+ ...data,
+ },
+ };
+}
+
+function dispatch(event, telemetry, env = process.env, emit = fireAndForget) {
+ // Last line of defense: nothing reaches the shared dispatcher (local mirror
+ // or collector) unless the complete event passes the closed outbound schema.
+ // Callers also run the gate earlier, before any irreversible state change.
+ assertSafeOutgoingEvent(event);
+ emit(event, {
+ // The audit completion event intentionally carries no PAC identity. The
+ // existing Power Pages resolver therefore selects the configured default region.
+ cloud: "",
+ configDir: configDir(env),
+ fakeProbe: env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || "",
+ ikeyJsonPath: telemetry.ikeyPath,
+ });
+}
+
+function writeState(filePath, state) {
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, JSON.stringify(state), {
+ encoding: "utf8",
+ flag: "wx",
+ mode: 0o600,
+ });
+}
+
+function readState(filePath) {
+ const state = JSON.parse(fs.readFileSync(filePath, "utf8"));
+ const expectedKeys = ["auditRunId", "sessionId", "startedMonotonicNs", "startedAt", "version"];
+ const actualKeys = Object.keys(state).sort();
+ if (
+ actualKeys.length !== expectedKeys.length ||
+ actualKeys.some((key, index) => key !== [...expectedKeys].sort()[index]) ||
+ state.version !== RUN_STATE_VERSION ||
+ !UUID_RE.test(state.auditRunId) ||
+ !UUID_RE.test(state.sessionId) ||
+ typeof state.startedMonotonicNs !== "string" ||
+ !/^[0-9]+$/.test(state.startedMonotonicNs) ||
+ typeof state.startedAt !== "string"
+ ) {
+ throw new Error("invalid_run_state");
+ }
+ return state;
+}
+
+function pruneRunState(dir, now = Date.now()) {
+ let entries;
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ if (!entry.isFile() || !/^[0-9a-f-]+\.(?:json|completed)$/i.test(entry.name)) continue;
+ const filePath = path.join(dir, entry.name);
+ try {
+ if (now - fs.statSync(filePath).mtimeMs > MAX_STATE_AGE_MS) {
+ fs.rmSync(filePath, { force: true });
+ }
+ } catch {
+ // State retention is best-effort and cannot affect an audit.
+ }
+ }
+}
+
+function beginRun(options = {}) {
+ const env = options.env || process.env;
+ // No run id when hard-disabled: the skill then skips completion telemetry
+ // entirely, exactly as it does when initialization fails.
+ if (isHardDisabled(readTelemetryConfig(env))) return { auditRunId: null, disabled: true };
+ const dir = configDir(env);
+ const auditRunId = (options.randomUUID || crypto.randomUUID)();
+ const sessionId = (options.randomUUID || crypto.randomUUID)();
+ const startedMonotonicNs = (options.monotonicNow || process.hrtime.bigint)();
+ const state = {
+ version: RUN_STATE_VERSION,
+ auditRunId,
+ sessionId,
+ startedAt: new Date(options.wallClockNow ? options.wallClockNow() : Date.now()).toISOString(),
+ startedMonotonicNs: startedMonotonicNs.toString(),
+ };
+ const filePath = statePath(dir, auditRunId);
+ writeState(filePath, state);
+ pruneRunState(path.dirname(filePath), options.wallClockNow ? options.wallClockNow() : Date.now());
+ return { auditRunId };
+}
+
+function acquireCompletion(dir, auditRunId) {
+ const filePath = completionPath(dir, auditRunId);
+ fs.writeFileSync(filePath, "", { encoding: "utf8", flag: "wx", mode: 0o600 });
+ return filePath;
+}
+
+function durationFromState(state, monotonicNow = process.hrtime.bigint) {
+ const elapsedNs = monotonicNow() - BigInt(state.startedMonotonicNs);
+ if (elapsedNs < 0n) throw new Error("invalid_duration");
+ const elapsedMs = elapsedNs / 1_000_000n;
+ return Number(elapsedMs > BigInt(Number.MAX_SAFE_INTEGER) ? BigInt(Number.MAX_SAFE_INTEGER) : elapsedMs);
+}
+
+function successPayload(args) {
+ if (!args.data || !args.report) throw new Error("missing_success_input");
+ let report;
+ try {
+ report = validateReport(path.resolve(args.report));
+ } catch {
+ const error = new Error("report_validation");
+ error.failureStage = "report_validation";
+ throw error;
+ }
+ let data;
+ let metrics;
+ try {
+ data = JSON.parse(fs.readFileSync(path.resolve(args.data), "utf8"));
+ metrics = deriveAuditMetrics(data);
+ validateAuditMetrics(metrics);
+ } catch {
+ const error = new Error("metrics_validation");
+ error.failureStage = "metrics_validation";
+ throw error;
+ }
+ if (
+ !isDeepStrictEqual(report.findings, data.FINDINGS_DATA) ||
+ !isDeepStrictEqual(report.scorecard, data.SCORECARD_DATA)
+ ) {
+ const error = new Error("report_data_mismatch");
+ error.failureStage = "metrics_validation";
+ throw error;
+ }
+ const payload = {
+ schemaVersion: METRICS_SCHEMA_VERSION,
+ auditRunId: args.runId,
+ reportGenerated: true,
+ ...metrics,
+ };
+ validateLifecyclePayload(payload, "success");
+ return payload;
+}
+
+function failurePayload(runId, failureStage) {
+ if (!FAILURE_STAGES.has(failureStage)) throw new Error("invalid_failure_stage");
+ const payload = {
+ schemaVersion: METRICS_SCHEMA_VERSION,
+ auditRunId: runId,
+ reportGenerated: false,
+ failureStage,
+ };
+ validateLifecyclePayload(payload, "failure");
+ return payload;
+}
+
+function validateLifecyclePayload(payload, outcome) {
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
+ throw new Error("invalid_lifecycle_payload");
+ }
+ if (!UUID_RE.test(payload.auditRunId || "") || payload.schemaVersion !== METRICS_SCHEMA_VERSION) {
+ throw new Error("invalid_lifecycle_identity");
+ }
+ if (outcome === "failure") {
+ const keys = Object.keys(payload).sort();
+ const expected = ["auditRunId", "failureStage", "reportGenerated", "schemaVersion"].sort();
+ if (keys.length !== expected.length || keys.some((key, index) => key !== expected[index])) {
+ throw new Error("invalid_failure_payload");
+ }
+ if (payload.reportGenerated !== false || !FAILURE_STAGES.has(payload.failureStage)) {
+ throw new Error("invalid_failure_payload");
+ }
+ return payload;
+ }
+ if (outcome !== "success" || payload.reportGenerated !== true) {
+ throw new Error("invalid_success_payload");
+ }
+ const {
+ auditRunId,
+ reportGenerated,
+ ...metrics
+ } = payload;
+ void auditRunId;
+ void reportGenerated;
+ validateAuditMetrics(metrics);
+ return payload;
+}
+
+function completeRun(args, options = {}) {
+ const env = options.env || process.env;
+ const dir = configDir(env);
+ if (!UUID_RE.test(args.runId || "")) throw new Error("invalid_run_id");
+ // The kill switch can be flipped between start and completion. When it is,
+ // discard this run's state and write no completion marker or event.
+ if (isHardDisabled(readTelemetryConfig(env))) {
+ try {
+ fs.rmSync(statePath(dir, args.runId), { force: true });
+ } catch {
+ // Best-effort cleanup; never affects the audit.
+ }
+ return { auditRunId: args.runId, disabled: true };
+ }
+ if (fs.existsSync(completionPath(dir, args.runId))) {
+ const error = new Error("already_completed");
+ error.code = "EEXIST";
+ throw error;
+ }
+ const state = readState(statePath(dir, args.runId));
+ if (state.auditRunId !== args.runId) throw new Error("run_state_mismatch");
+
+ // Validate caller input and compute the duration BEFORE claiming the
+ // completion marker. Claiming first would let a mistyped failure stage (or a
+ // negative cross-reboot duration) consume the run's single completion slot
+ // without emitting a terminal event, so a corrected retry could never record it.
+ let outcome = args.outcome;
+ let auditPermissions;
+ if (outcome === "success") {
+ try {
+ auditPermissions = successPayload(args);
+ } catch (error) {
+ outcome = "failure";
+ auditPermissions = failurePayload(
+ args.runId,
+ FAILURE_STAGES.has(error?.failureStage) ? error.failureStage : "metrics_validation"
+ );
+ }
+ } else if (outcome === "failure") {
+ auditPermissions = failurePayload(args.runId, args.failureStage);
+ } else {
+ throw new Error("invalid_outcome");
+ }
+
+ const durationMs = durationFromState(state, options.monotonicNow);
+ const telemetry = readTelemetryConfig(env);
+ const event = buildCompletionEvent(
+ telemetry.eventStreamName,
+ eventContext(
+ state.sessionId,
+ { auditPermissions },
+ outcome,
+ durationMs
+ )
+ );
+ // Run the outbound gate before claiming the single completion slot: a
+ // rejected event must not consume the run. dispatch() re-runs the same gate
+ // immediately before handing the event to the shared dispatcher.
+ assertSafeOutgoingEvent(event);
+ acquireCompletion(dir, args.runId);
+ dispatch(event, telemetry, env, options.emit);
+ try {
+ fs.rmSync(statePath(dir, args.runId), { force: true });
+ } catch {
+ // The completion tombstone still prevents a duplicate terminal event.
+ }
+ return {
+ auditRunId: args.runId,
+ durationMs,
+ outcome,
+ reportGenerated: auditPermissions.reportGenerated,
+ };
+}
+
+function fixedFailure(code) {
+ process.stderr.write(`${JSON.stringify({ status: "error", code })}\n`);
+ process.exitCode = 1;
+}
+
+function main() {
+ const args = parseArgs(process.argv);
+ try {
+ if (args.action === "start") {
+ const started = beginRun();
+ const output = started.disabled
+ ? { status: "disabled" }
+ : { status: "started", auditRunId: started.auditRunId };
+ process.stdout.write(`${JSON.stringify(output)}\n`);
+ return;
+ }
+ if (args.action === "complete") {
+ const result = completeRun({
+ runId: args.runId,
+ outcome: args.outcome,
+ data: args.data,
+ report: args.report,
+ failureStage: args.failureStage,
+ });
+ const output = result.disabled ? { status: "disabled" } : { status: "completed", ...result };
+ process.stdout.write(`${JSON.stringify(output)}\n`);
+ return;
+ }
+ fixedFailure("AUDIT_TELEMETRY_USAGE");
+ } catch (error) {
+ const duplicate = error && error.code === "EEXIST" && args.action === "complete";
+ fixedFailure(duplicate ? "AUDIT_TELEMETRY_ALREADY_COMPLETED" : "AUDIT_TELEMETRY_FAILED");
+ }
+}
+
+if (require.main === module) {
+ main();
+}
+
+module.exports = {
+ FAILURE_STAGES,
+ beginRun,
+ buildCompletionEvent,
+ completeRun,
+ durationFromState,
+ failurePayload,
+ parseArgs,
+ pruneRunState,
+ successPayload,
+ validateLifecyclePayload,
+};
diff --git a/plugins/power-pages/scripts/lib/audit-report-validation.js b/plugins/power-pages/scripts/lib/audit-report-validation.js
new file mode 100644
index 000000000..2498c2e0f
--- /dev/null
+++ b/plugins/power-pages/scripts/lib/audit-report-validation.js
@@ -0,0 +1,385 @@
+"use strict";
+
+const fs = require("node:fs");
+
+const PREFIXES = Object.freeze({
+ "intent-coverage": "IC",
+ "privilege-calibration": "PC",
+ "scope-correctness": "SC",
+ "role-completeness": "RC",
+ "table-coverage": "TC",
+ "anonymous-access-hygiene": "AH",
+ "data-model-alignment": "DM",
+ "internal-consistency": "IS",
+ "security-posture": "SP",
+});
+
+const DIMENSIONS = Object.freeze({
+ "intent-coverage": Object.freeze({ key: "intentCoverage", category: "underExposure" }),
+ "privilege-calibration": Object.freeze({ key: "privilegeCalibration", category: "overExposure" }),
+ "scope-correctness": Object.freeze({ key: "scopeCorrectness", category: "correctness" }),
+ "role-completeness": Object.freeze({ key: "roleCompleteness", category: "underExposure" }),
+ "table-coverage": Object.freeze({ key: "tableCoverage", category: "underExposure" }),
+ "anonymous-access-hygiene": Object.freeze({ key: "anonymousAccessHygiene", category: "overExposure" }),
+ "data-model-alignment": Object.freeze({ key: "dataModelAlignment", category: "correctness" }),
+ "internal-consistency": Object.freeze({ key: "internalConsistency", category: "correctness" }),
+ "security-posture": Object.freeze({ key: "securityPosture", category: "overExposure" }),
+});
+
+const CATEGORIES = Object.freeze([
+ Object.freeze({
+ id: "over-exposure",
+ key: "overExposure",
+ name: /^Over-Exposure/i,
+ dimensions: ["privilege-calibration", "anonymous-access-hygiene", "security-posture"],
+ }),
+ Object.freeze({
+ id: "under-exposure",
+ key: "underExposure",
+ name: /^Under-Exposure/i,
+ dimensions: ["intent-coverage", "table-coverage", "role-completeness"],
+ }),
+ Object.freeze({
+ id: "correctness",
+ key: "correctness",
+ name: /^Correctness/i,
+ dimensions: ["scope-correctness", "data-model-alignment", "internal-consistency"],
+ }),
+]);
+
+const ROOT_CAUSES = Object.freeze([
+ "permissions",
+ "mixed",
+ "data-model",
+ "webapi-code",
+ "webapi-settings",
+]);
+
+const SCORING_STATUSES = Object.freeze(["complete", "partial"]);
+const VERDICTS = Object.freeze(["safe_to_go", "needs_revision", "not_scored"]);
+
+const ROOT_CAUSE_KEYS = Object.freeze({
+ permissions: "permissions",
+ mixed: "mixed",
+ "data-model": "dataModel",
+ "webapi-code": "webApiCode",
+ "webapi-settings": "webApiSettings",
+});
+
+function round(value) {
+ return Math.round(value * 100) / 100;
+}
+
+function scoreFromIssues(major, minor) {
+ return round(5 - 4 * Math.tanh(0.2 * (major + 0.25 * minor)));
+}
+
+function countIssues(issues) {
+ const major = issues.filter((issue) => issue.severity === "major").length;
+ const minor = issues.filter((issue) => issue.severity === "minor").length;
+ return { major, minor, total: major + minor };
+}
+
+function requireText(record, fields, label) {
+ for (const field of fields) {
+ if (typeof record[field] !== "string" || !record[field].trim()) {
+ throw new Error(`${label} needs a non-empty ${field}.`);
+ }
+ }
+}
+
+function validateFindings(findings) {
+ if (!Array.isArray(findings)) throw new Error("FINDINGS must be an array.");
+ const ids = new Set();
+ for (const finding of findings) {
+ if (!finding || typeof finding !== "object" || Array.isArray(finding)) {
+ throw new Error("Each FINDINGS entry must be an object.");
+ }
+ const prefix = PREFIXES[finding.dimension];
+ if (!prefix) throw new Error(`Finding ${finding.id} has invalid dimension ${finding.dimension}.`);
+ if (!new RegExp(`^${prefix}[1-9][0-9]*$`).test(finding.id)) {
+ throw new Error(`Finding ${finding.id} must use the ${prefix} prefix for ${finding.dimension}.`);
+ }
+ if (ids.has(finding.id)) throw new Error(`Finding ${finding.id} is listed more than once.`);
+ ids.add(finding.id);
+ if (!["major", "minor"].includes(finding.severity)) {
+ throw new Error(`Finding ${finding.id} has invalid severity ${finding.severity}.`);
+ }
+ requireText(finding, ["title", "reasoning", "fix"], `Finding ${finding.id}`);
+ if (finding.severity === "major") {
+ if (!ROOT_CAUSES.includes(finding.rootCause)) {
+ throw new Error(`Major finding ${finding.id} has invalid rootCause ${finding.rootCause}.`);
+ }
+ requireText(finding, ["rootCauseReason"], `Major finding ${finding.id}`);
+ } else if (finding.rootCause !== undefined || finding.rootCauseReason !== undefined) {
+ throw new Error(`Minor finding ${finding.id} must not carry a root cause.`);
+ }
+ }
+}
+
+function validateScorecard(scorecard, findings) {
+ if (scorecard === null) return;
+ const categories = scorecard?.categories;
+ if (!Array.isArray(categories) || categories.length !== CATEGORIES.length) {
+ throw new Error(`SCORECARD.categories must contain exactly ${CATEGORIES.length} entries.`);
+ }
+ CATEGORIES.forEach((category, index) => {
+ const entry = categories[index];
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
+ throw new Error(`SCORECARD.categories[${index}] must be an object.`);
+ }
+ if (!category.name.test(String(entry.name || ""))) {
+ throw new Error(`SCORECARD.categories[${index}] must be ${category.id}, found ${entry.name}.`);
+ }
+ if (typeof entry.score !== "number" || !Number.isFinite(entry.score) || entry.score < 1 || entry.score > 5) {
+ throw new Error(`${entry.name} score must be a finite number from 1 through 5.`);
+ }
+ const counts = countIssues(findings.filter((finding) => category.dimensions.includes(finding.dimension)));
+ const expected = scoreFromIssues(counts.major, counts.minor);
+ if (entry.score !== expected) {
+ throw new Error(`${entry.name} score is ${entry.score}; expected ${expected}.`);
+ }
+ });
+}
+
+function validateAuditData(data) {
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
+ throw new Error("Audit data must be an object.");
+ }
+ if (!Object.prototype.hasOwnProperty.call(data, "FINDINGS_DATA")) {
+ throw new Error("Audit data has no FINDINGS_DATA.");
+ }
+ if (!Object.prototype.hasOwnProperty.call(data, "SCORECARD_DATA")) {
+ throw new Error("Audit data has no SCORECARD_DATA.");
+ }
+ validateFindings(data.FINDINGS_DATA);
+ validateScorecard(data.SCORECARD_DATA, data.FINDINGS_DATA);
+}
+
+function scriptText(html) {
+ return [...html.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi)].map((match) => match[1]).join("\n");
+}
+
+function readConst(script, name) {
+ const matches = [...script.matchAll(new RegExp(`^const ${name} = (.*)$`, "gm"))];
+ if (matches.length === 0) throw new Error(`Audit report has no ${name} data.`);
+ if (matches.length > 1) throw new Error(`Audit report declares ${name} more than once.`);
+ const json = matches[0][1].trim().replace(/;$/, "");
+ try {
+ return JSON.parse(json);
+ } catch {
+ throw new Error(`Audit report ${name} data is not valid JSON.`);
+ }
+}
+
+function validateSummary(html, scorecard, majorCount) {
+ const match = html.match(/id="summaryBox"[^>]*>([\s\S]*?)<\/div>/);
+ if (!match) throw new Error("Audit report has no SUMMARY.");
+ const states = (phrase) => match[1].toLowerCase().includes(phrase.toLowerCase());
+ if (scorecard === null) {
+ if (states("Safe to go") || states("Needs revision")) {
+ throw new Error("SUMMARY must not state a verdict when scoring was skipped.");
+ }
+ return null;
+ }
+ const [expected, opposite] = majorCount === 0 ? ["Safe to go", "Needs revision"] : ["Needs revision", "Safe to go"];
+ if (!states(expected) || states(opposite)) {
+ throw new Error(`SUMMARY must state the verdict "${expected}" and not "${opposite}".`);
+ }
+ return expected;
+}
+
+function validateReport(reportPath) {
+ const html = fs.readFileSync(reportPath, "utf8");
+ if (/__(?:(?:HTML|ATTR|JSON|RAW)_)?(?:SITE_NAME|AUDIT_DESC|SUMMARY|FINDINGS_DATA|INVENTORY_DATA|SCORECARD_DATA)__/.test(html)) {
+ throw new Error("Audit report has unreplaced data placeholders.");
+ }
+ const script = scriptText(html);
+ const findings = readConst(script, "FINDINGS");
+ validateFindings(findings);
+ const inventory = readConst(script, "INVENTORY");
+ if (!Array.isArray(inventory)) throw new Error("INVENTORY must be an array.");
+ const scorecard = readConst(script, "SCORECARD");
+ validateScorecard(scorecard, findings);
+ const issueCounts = countIssues(findings);
+ return {
+ findings,
+ scorecard,
+ issueCounts,
+ verdict: validateSummary(html, scorecard, issueCounts.major),
+ };
+}
+
+function zeroCounts() {
+ return { major: 0, minor: 0 };
+}
+
+function deriveAuditMetrics(data) {
+ validateAuditData(data);
+
+ const categories = Object.fromEntries(CATEGORIES.map((category) => [category.key, zeroCounts()]));
+ const dimensions = Object.fromEntries(
+ Object.values(DIMENSIONS).map((dimension) => [dimension.key, zeroCounts()])
+ );
+ const majorRootCauses = Object.fromEntries(Object.values(ROOT_CAUSE_KEYS).map((key) => [key, 0]));
+
+ for (const finding of data.FINDINGS_DATA) {
+ const dimension = DIMENSIONS[finding.dimension];
+ dimensions[dimension.key][finding.severity] += 1;
+ categories[dimension.category][finding.severity] += 1;
+ if (finding.severity === "major") {
+ majorRootCauses[ROOT_CAUSE_KEYS[finding.rootCause]] += 1;
+ }
+ }
+
+ const issueCounts = countIssues(data.FINDINGS_DATA);
+ const complete = data.SCORECARD_DATA !== null;
+ const metrics = {
+ schemaVersion: 1,
+ scoringStatus: complete ? "complete" : "partial",
+ verdict: complete ? (issueCounts.major === 0 ? "safe_to_go" : "needs_revision") : "not_scored",
+ majorIssueCount: issueCounts.major,
+ minorIssueCount: issueCounts.minor,
+ totalIssueCount: issueCounts.total,
+ categories,
+ dimensions,
+ majorRootCauses,
+ };
+ if (complete) {
+ metrics.scores = Object.fromEntries(
+ CATEGORIES.map((category, index) => [category.key, data.SCORECARD_DATA.categories[index].score])
+ );
+ }
+ validateAuditMetrics(metrics);
+ return metrics;
+}
+
+function assertPlainObject(value, label) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ throw new Error(`${label} must be an object.`);
+ }
+}
+
+function assertExactKeys(value, expected, label) {
+ assertPlainObject(value, label);
+ const actual = Object.keys(value).sort();
+ const wanted = [...expected].sort();
+ if (actual.length !== wanted.length || actual.some((key, index) => key !== wanted[index])) {
+ throw new Error(`${label} has invalid properties.`);
+ }
+}
+
+function assertCount(value, label) {
+ if (!Number.isInteger(value) || value < 0) {
+ throw new Error(`${label} must be a non-negative integer.`);
+ }
+}
+
+function validateCountMap(map, expectedKeys, label) {
+ assertExactKeys(map, expectedKeys, label);
+ for (const key of expectedKeys) {
+ assertExactKeys(map[key], ["major", "minor"], `${label}.${key}`);
+ assertCount(map[key].major, `${label}.${key}.major`);
+ assertCount(map[key].minor, `${label}.${key}.minor`);
+ }
+}
+
+function validateAuditMetrics(metrics) {
+ assertPlainObject(metrics, "Audit metrics");
+ const complete = metrics.scoringStatus === "complete";
+ const expectedKeys = [
+ "schemaVersion",
+ "scoringStatus",
+ "verdict",
+ "majorIssueCount",
+ "minorIssueCount",
+ "totalIssueCount",
+ "categories",
+ "dimensions",
+ "majorRootCauses",
+ ...(complete ? ["scores"] : []),
+ ];
+ assertExactKeys(metrics, expectedKeys, "Audit metrics");
+ if (metrics.schemaVersion !== 1) throw new Error("Audit metrics schemaVersion must be 1.");
+ if (!SCORING_STATUSES.includes(metrics.scoringStatus)) {
+ throw new Error("Audit metrics scoringStatus is invalid.");
+ }
+ if (!VERDICTS.includes(metrics.verdict)) {
+ throw new Error("Audit metrics verdict is invalid.");
+ }
+ for (const key of ["majorIssueCount", "minorIssueCount", "totalIssueCount"]) {
+ assertCount(metrics[key], `Audit metrics.${key}`);
+ }
+ if (metrics.totalIssueCount !== metrics.majorIssueCount + metrics.minorIssueCount) {
+ throw new Error("Audit metrics totalIssueCount is inconsistent.");
+ }
+
+ const categoryKeys = CATEGORIES.map((category) => category.key);
+ const dimensionKeys = Object.values(DIMENSIONS).map((dimension) => dimension.key);
+ validateCountMap(metrics.categories, categoryKeys, "Audit metrics.categories");
+ validateCountMap(metrics.dimensions, dimensionKeys, "Audit metrics.dimensions");
+
+ assertExactKeys(metrics.majorRootCauses, Object.values(ROOT_CAUSE_KEYS), "Audit metrics.majorRootCauses");
+ for (const [key, value] of Object.entries(metrics.majorRootCauses)) {
+ assertCount(value, `Audit metrics.majorRootCauses.${key}`);
+ }
+
+ const dimensionMajor = Object.values(metrics.dimensions).reduce((sum, value) => sum + value.major, 0);
+ const dimensionMinor = Object.values(metrics.dimensions).reduce((sum, value) => sum + value.minor, 0);
+ if (dimensionMajor !== metrics.majorIssueCount || dimensionMinor !== metrics.minorIssueCount) {
+ throw new Error("Audit metrics dimension totals are inconsistent.");
+ }
+ const rootCauseTotal = Object.values(metrics.majorRootCauses).reduce((sum, value) => sum + value, 0);
+ if (rootCauseTotal !== metrics.majorIssueCount) {
+ throw new Error("Audit metrics root-cause total is inconsistent.");
+ }
+ for (const category of CATEGORIES) {
+ const expected = category.dimensions.reduce(
+ (counts, name) => {
+ const values = metrics.dimensions[DIMENSIONS[name].key];
+ counts.major += values.major;
+ counts.minor += values.minor;
+ return counts;
+ },
+ zeroCounts()
+ );
+ const actual = metrics.categories[category.key];
+ if (actual.major !== expected.major || actual.minor !== expected.minor) {
+ throw new Error(`Audit metrics ${category.key} category total is inconsistent.`);
+ }
+ }
+
+ if (complete) {
+ if (metrics.verdict !== (metrics.majorIssueCount === 0 ? "safe_to_go" : "needs_revision")) {
+ throw new Error("Audit metrics verdict is inconsistent.");
+ }
+ assertExactKeys(metrics.scores, categoryKeys, "Audit metrics.scores");
+ for (const [key, score] of Object.entries(metrics.scores)) {
+ if (typeof score !== "number" || !Number.isFinite(score) || score < 1 || score > 5) {
+ throw new Error(`Audit metrics.scores.${key} must be a finite number from 1 through 5.`);
+ }
+ }
+ } else if (metrics.verdict !== "not_scored") {
+ throw new Error("Partial audit metrics must use the not_scored verdict.");
+ }
+
+ return metrics;
+}
+
+module.exports = {
+ CATEGORIES,
+ DIMENSIONS,
+ PREFIXES,
+ ROOT_CAUSES,
+ ROOT_CAUSE_KEYS,
+ SCORING_STATUSES,
+ VERDICTS,
+ countIssues,
+ deriveAuditMetrics,
+ scoreFromIssues,
+ validateAuditData,
+ validateAuditMetrics,
+ validateFindings,
+ validateReport,
+ validateScorecard,
+};
diff --git a/plugins/power-pages/scripts/lib/audit-telemetry-gate.js b/plugins/power-pages/scripts/lib/audit-telemetry-gate.js
new file mode 100644
index 000000000..ea8d1a8f3
--- /dev/null
+++ b/plugins/power-pages/scripts/lib/audit-telemetry-gate.js
@@ -0,0 +1,217 @@
+"use strict";
+
+// Final outbound gate for audit-permissions completion telemetry.
+//
+// This is the LAST check before an event is handed to the bundled shared
+// dispatcher (fireAndForget). That dispatcher re-filters top-level fields
+// against its FIELD_TYPES allowlist, but it validates `eventInfo` only as "some
+// object" and never inspects nested keys or values. Without this gate, a future
+// bug that copied a finding title, table name, or path into
+// `eventInfo.auditPermissions` would reach the local mirror and the collector.
+//
+// The gate is deliberately a VALIDATOR, not a sanitizer: it never rewrites or
+// drops parts of an event. Any mismatch rejects the whole event (fail closed),
+// because a partially "cleaned" event would still prove that something
+// unexpected tried to get through. Error messages are fixed strings and never
+// echo a rejected value, so a rejection cannot itself become a leak.
+//
+// Rules:
+// - only `audit_permissions_run_completed` is accepted; run start is local
+// state only and emits nothing, so no other event shape may pass
+// - envelope and top-level keys are a closed set with typed, bounded values
+// - `eventInfo` contains exactly `auditPermissions`
+// - `auditPermissions` matches an exact shape for success or failure
+// - NO free-form text anywhere in `auditPermissions`: every string must be a
+// known enum value, or a UUID v4 in the `auditRunId` slot
+// - serialized size caps on `eventInfo` and the whole event
+
+const {
+ SCORING_STATUSES,
+ VERDICTS,
+ validateAuditMetrics,
+} = require("./audit-report-validation");
+
+const EVENT_COMPLETED = "audit_permissions_run_completed";
+const METRICS_SCHEMA_VERSION = 1;
+
+const FAILURE_STAGES = Object.freeze([
+ "site_verification",
+ "configuration_gathering",
+ "schema_validation",
+ "relationship_discovery",
+ "audit_checks",
+ "scoring",
+ "root_cause_attribution",
+ "report_rendering",
+ "report_validation",
+ "metrics_validation",
+ "unknown_controlled_failure",
+]);
+
+// crypto.randomUUID() always produces RFC 4122 version 4, variant 10xx, e.g.
+// 5d0602d4-01f1-40e0-aa89-102b70ba4bda
+// Only lowercase hex is accepted because randomUUID() never emits uppercase.
+const UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
+
+// Standard context values (plugin/OS/agent versions and names) are short
+// product tokens such as "2.7.2", "Mac", "25.0.0", "6.5.0-1025-azure",
+// "10.0.26200", "Copilot CLI", "Claude Code". The charset excludes '/', '\',
+// ':', '@', and quotes, so a path, URL, UPN, or JSON fragment cannot pass.
+const CONTEXT_TOKEN_RE = /^[A-Za-z0-9 ._+-]{1,64}$/;
+const NODE_MAJOR_RE = /^v[0-9]{1,3}$/;
+const STREAM_NAME_RE = /^[A-Za-z0-9_]{0,64}$/;
+
+const MAX_EVENT_INFO_BYTES = 2048;
+const MAX_EVENT_BYTES = 4096;
+
+const COMMON_KEYS = Object.freeze([
+ "eventName",
+ "eventType",
+ "severity",
+ "pluginName",
+ "pluginVersion",
+ "sessionId",
+ "correlationId",
+ "osName",
+ "osVersion",
+ "nodeVersion",
+ "skillName",
+ "eventInfo",
+ "outcome",
+ "durationMs",
+]);
+const OPTIONAL_CONTEXT_KEYS = Object.freeze(["pacCliVersion", "aiAgentName", "aiAgentVersion"]);
+
+// Every string that may legitimately appear in `auditPermissions`, other than
+// the run id. Anything else is treated as free-form text and rejected.
+const ALLOWED_PAYLOAD_STRINGS = new Set([...SCORING_STATUSES, ...VERDICTS, ...FAILURE_STAGES]);
+
+function reject(code) {
+ throw new Error(`outgoing_event_rejected:${code}`);
+}
+
+function isPlainObject(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
+ const proto = Object.getPrototypeOf(value);
+ return proto === Object.prototype || proto === null;
+}
+
+function hasExactKeys(value, required, optional = []) {
+ if (!isPlainObject(value)) return false;
+ const allowed = new Set([...required, ...optional]);
+ const keys = Object.keys(value);
+ return keys.every((key) => allowed.has(key)) && required.every((key) => keys.includes(key));
+}
+
+function byteLength(value) {
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
+}
+
+// Walk the payload and reject any free-form text, array, or non-finite number.
+// Structure is checked separately; this is a value-level backstop that holds
+// even if a structural rule were loosened by mistake.
+function assertNoFreeFormValues(value, key, depth) {
+ if (depth > 4) reject("payload_too_deep");
+ if (typeof value === "string") {
+ if (key === "auditRunId") {
+ if (!UUID_V4_RE.test(value)) reject("run_id");
+ return;
+ }
+ if (!ALLOWED_PAYLOAD_STRINGS.has(value)) reject("free_form_string");
+ return;
+ }
+ if (typeof value === "number") {
+ if (!Number.isFinite(value) || value < 0) reject("number");
+ return;
+ }
+ if (typeof value === "boolean") return;
+ if (Array.isArray(value)) reject("array");
+ if (!isPlainObject(value)) reject("value_type");
+ for (const [childKey, child] of Object.entries(value)) {
+ assertNoFreeFormValues(child, childKey, depth + 1);
+ }
+}
+
+function assertPayloadShape(payload, outcome) {
+ if (!isPlainObject(payload)) reject("payload");
+ if (payload.schemaVersion !== METRICS_SCHEMA_VERSION) reject("schema_version");
+ if (typeof payload.auditRunId !== "string" || !UUID_V4_RE.test(payload.auditRunId)) {
+ reject("run_id");
+ }
+
+ if (outcome === "failure") {
+ if (!hasExactKeys(payload, ["schemaVersion", "auditRunId", "reportGenerated", "failureStage"])) {
+ reject("failure_shape");
+ }
+ if (payload.reportGenerated !== false) reject("failure_report_generated");
+ if (!FAILURE_STAGES.includes(payload.failureStage)) reject("failure_stage");
+ return;
+ }
+
+ // Success: the only route to `outcome: success` is a validated report.
+ if (payload.reportGenerated !== true) reject("success_report_generated");
+ const { schemaVersion, auditRunId, reportGenerated, ...metrics } = payload;
+ void auditRunId;
+ void reportGenerated;
+ try {
+ validateAuditMetrics({ schemaVersion, ...metrics });
+ } catch {
+ reject("success_metrics");
+ }
+}
+
+function assertContext(data) {
+ if (data.eventType !== "Trace") reject("event_type");
+ if (data.pluginName !== "power-pages") reject("plugin_name");
+ if (data.skillName !== "audit-permissions") reject("skill_name");
+ if (!UUID_V4_RE.test(String(data.sessionId))) reject("session_id");
+ if (!UUID_V4_RE.test(String(data.correlationId))) reject("correlation_id");
+ if (!NODE_MAJOR_RE.test(String(data.nodeVersion))) reject("node_version");
+ for (const key of ["pluginVersion", "osName", "osVersion"]) {
+ if (typeof data[key] !== "string" || !CONTEXT_TOKEN_RE.test(data[key])) reject(key);
+ }
+ for (const key of OPTIONAL_CONTEXT_KEYS) {
+ if (data[key] !== undefined && (typeof data[key] !== "string" || !CONTEXT_TOKEN_RE.test(data[key]))) {
+ reject(key);
+ }
+ }
+}
+
+// Throws on any violation; returns the (unchanged) event when it is safe.
+function assertSafeOutgoingEvent(event) {
+ if (!hasExactKeys(event, ["name", "data"])) reject("envelope");
+ if (typeof event.name !== "string" || !STREAM_NAME_RE.test(event.name)) reject("stream_name");
+
+ const data = event.data;
+ if (!isPlainObject(data)) reject("data");
+ if (data.eventName !== EVENT_COMPLETED) reject("event_name");
+ if (!hasExactKeys(data, COMMON_KEYS, OPTIONAL_CONTEXT_KEYS)) reject("keys");
+ if (data.outcome !== "success" && data.outcome !== "failure") reject("outcome");
+ if (data.severity !== (data.outcome === "failure" ? "Error" : "Info")) reject("severity");
+ if (!Number.isSafeInteger(data.durationMs) || data.durationMs < 0) reject("duration");
+
+ assertContext(data);
+
+ if (!hasExactKeys(data.eventInfo, ["auditPermissions"])) reject("event_info");
+ const payload = data.eventInfo.auditPermissions;
+ assertPayloadShape(payload, data.outcome);
+ assertNoFreeFormValues(payload, "", 0);
+
+ if (byteLength(data.eventInfo) > MAX_EVENT_INFO_BYTES) reject("event_info_size");
+ if (byteLength(event) > MAX_EVENT_BYTES) reject("event_size");
+ return event;
+}
+
+function isSafeContextToken(value) {
+ return typeof value === "string" && CONTEXT_TOKEN_RE.test(value);
+}
+
+module.exports = {
+ EVENT_COMPLETED,
+ FAILURE_STAGES,
+ MAX_EVENT_BYTES,
+ MAX_EVENT_INFO_BYTES,
+ UUID_V4_RE,
+ assertSafeOutgoingEvent,
+ isSafeContextToken,
+};
diff --git a/plugins/power-pages/scripts/tests/audit-permissions-telemetry.test.js b/plugins/power-pages/scripts/tests/audit-permissions-telemetry.test.js
new file mode 100644
index 000000000..6af8baf42
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/audit-permissions-telemetry.test.js
@@ -0,0 +1,437 @@
+"use strict";
+
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const { spawnSync } = require("node:child_process");
+
+const {
+ deriveAuditMetrics,
+ validateAuditMetrics,
+} = require("../lib/audit-report-validation");
+const {
+ beginRun,
+ completeRun,
+} = require("../emit-audit-permissions-telemetry");
+
+const RUN_ID = "11111111-1111-4111-8111-111111111111";
+const SESSION_ID = "22222222-2222-4222-8222-222222222222";
+const SCRIPT_PATH = path.join(__dirname, "..", "emit-audit-permissions-telemetry.js");
+const PRIVATE_SENTINELS = [
+ "SITE_SECRET_123",
+ "TABLE_SECRET_123",
+ "ROLE_SECRET_123",
+ "/private/site/path",
+ "https://private.example",
+];
+
+function makeTempDir(t) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "audit-telemetry-"));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const ikeyPath = path.join(dir, "ikey.json");
+ fs.writeFileSync(
+ ikeyPath,
+ JSON.stringify({
+ disabled: false,
+ event_stream_name: "PagesAIPluginEvent",
+ instrumentationKey: "test-key",
+ collector_url: "https://example.invalid/OneCollector/1.0/",
+ }),
+ "utf8"
+ );
+ return {
+ dir,
+ env: {
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: dir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,
+ },
+ };
+}
+
+function findings() {
+ return [
+ {
+ id: "AH1",
+ severity: "major",
+ dimension: "anonymous-access-hygiene",
+ title: `Public access to ${PRIVATE_SENTINELS[1]}`,
+ table: PRIVATE_SENTINELS[1],
+ permission: PRIVATE_SENTINELS[2],
+ reasoning: `Found in ${PRIVATE_SENTINELS[3]}`,
+ fix: `Review ${PRIVATE_SENTINELS[4]}`,
+ details: PRIVATE_SENTINELS[0],
+ rootCause: "permissions",
+ rootCauseReason: `Permission references ${PRIVATE_SENTINELS[2]}`,
+ },
+ {
+ id: "IS1",
+ severity: "minor",
+ dimension: "internal-consistency",
+ title: "Missing plan",
+ reasoning: "The plan is missing.",
+ fix: "Create the plan.",
+ },
+ ];
+}
+
+function scorecard() {
+ return {
+ categories: [
+ { name: "Over-Exposure (Security)", score: 4.21 },
+ { name: "Under-Exposure (Usability & Coverage)", score: 5 },
+ { name: "Correctness (Validity & Alignment)", score: 4.8 },
+ ],
+ reportPaths: [{ label: PRIVATE_SENTINELS[0], path: PRIVATE_SENTINELS[3] }],
+ };
+}
+
+function auditData() {
+ return {
+ SITE_NAME: PRIVATE_SENTINELS[0],
+ AUDIT_DESC: PRIVATE_SENTINELS[4],
+ SUMMARY: PRIVATE_SENTINELS[2],
+ FINDINGS_DATA: findings(),
+ INVENTORY_DATA: [{
+ name: PRIVATE_SENTINELS[2],
+ table: PRIVATE_SENTINELS[1],
+ roles: [PRIVATE_SENTINELS[2]],
+ }],
+ SCORECARD_DATA: scorecard(),
+ };
+}
+
+function reportHtml(data) {
+ return "<!doctype html><html><body>" +
+ '<div id="summaryBox">Sensitive access exists. Needs revision.</div>' +
+ "<script>\n" +
+ `const FINDINGS = ${JSON.stringify(data.FINDINGS_DATA)};\n` +
+ `const INVENTORY = ${JSON.stringify(data.INVENTORY_DATA)};\n` +
+ `const SCORECARD = ${JSON.stringify(data.SCORECARD_DATA)};\n` +
+ "</script></body></html>";
+}
+
+function writeAuditArtifacts(dir, data = auditData()) {
+ const dataPath = path.join(dir, "audit-data.json");
+ const reportPath = path.join(dir, "permissions-audit.html");
+ fs.writeFileSync(dataPath, JSON.stringify(data), "utf8");
+ fs.writeFileSync(reportPath, reportHtml(data), "utf8");
+ return { dataPath, reportPath };
+}
+
+function uuidSequence(...values) {
+ let index = 0;
+ return () => values[index++];
+}
+
+function sleep(ms) {
+ const wait = new Int32Array(new SharedArrayBuffer(4));
+ Atomics.wait(wait, 0, 0, ms);
+}
+
+function latestMirror(configDir) {
+ const sessionsDir = path.join(configDir, "telemetry", "power-pages", "sessions");
+ let entries;
+ try {
+ entries = fs.readdirSync(sessionsDir, { withFileTypes: true });
+ } catch {
+ return null;
+ }
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ const candidate = path.join(sessionsDir, entry.name, "events.jsonl");
+ if (fs.existsSync(candidate)) return candidate;
+ }
+ return null;
+}
+
+function waitForMirror(configDir, timeoutMs = 5000) {
+ const deadline = Date.now() + timeoutMs;
+ let mirror = latestMirror(configDir);
+ while (!mirror && Date.now() < deadline) {
+ sleep(25);
+ mirror = latestMirror(configDir);
+ }
+ return mirror;
+}
+
+test("derives a closed aggregate metric shape without private report values", () => {
+ const metrics = deriveAuditMetrics(auditData());
+ assert.deepEqual(metrics.categories, {
+ overExposure: { major: 1, minor: 0 },
+ underExposure: { major: 0, minor: 0 },
+ correctness: { major: 0, minor: 1 },
+ });
+ assert.equal(metrics.majorRootCauses.permissions, 1);
+ assert.equal(metrics.scores.overExposure, 4.21);
+ const serialized = JSON.stringify(metrics);
+ for (const sentinel of PRIVATE_SENTINELS) {
+ assert.doesNotMatch(serialized, new RegExp(sentinel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")));
+ }
+ assert.throws(
+ () => validateAuditMetrics({ ...metrics, siteName: PRIVATE_SENTINELS[0] }),
+ /invalid properties/
+ );
+});
+
+test("initializes run state and emits successful completion with measured duration", (t) => {
+ const { dir, env } = makeTempDir(t);
+ const { dataPath, reportPath } = writeAuditArtifacts(dir);
+ const emitted = [];
+ const emit = (event, options) => emitted.push({ event, options });
+
+ const started = beginRun({
+ env,
+ randomUUID: uuidSequence(RUN_ID, SESSION_ID),
+ monotonicNow: () => 1_000_000_000n,
+ wallClockNow: () => 1_000,
+ });
+ const completed = completeRun({
+ runId: started.auditRunId,
+ outcome: "success",
+ data: dataPath,
+ report: reportPath,
+ }, {
+ env,
+ emit,
+ monotonicNow: () => 3_500_000_000n,
+ });
+
+ assert.equal(completed.outcome, "success");
+ assert.equal(completed.reportGenerated, true);
+ assert.equal(completed.durationMs, 2500);
+ assert.equal(emitted.length, 1);
+
+ const terminal = emitted[0];
+ assert.equal(terminal.event.data.eventName, "audit_permissions_run_completed");
+ assert.equal(terminal.event.data.eventInfo.auditPermissions.auditRunId, RUN_ID);
+ assert.equal(terminal.event.data.outcome, "success");
+ assert.equal(terminal.event.data.durationMs, 2500);
+ assert.equal(terminal.options.cloud, "");
+ assert.equal("routingOrgId" in terminal.options, false);
+
+ const serialized = JSON.stringify(emitted.map(({ event }) => event));
+ for (const sentinel of PRIVATE_SENTINELS) {
+ assert.doesNotMatch(serialized, new RegExp(sentinel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")));
+ }
+});
+
+test("emits a closed failure payload and rejects a duplicate completion", (t) => {
+ const { env } = makeTempDir(t);
+ const emitted = [];
+ const emit = (event) => emitted.push(event);
+ beginRun({
+ env,
+ randomUUID: uuidSequence(RUN_ID, SESSION_ID),
+ monotonicNow: () => 5_000_000_000n,
+ });
+ const completed = completeRun({
+ runId: RUN_ID,
+ outcome: "failure",
+ failureStage: "report_rendering",
+ }, {
+ env,
+ emit,
+ monotonicNow: () => 5_750_000_000n,
+ });
+ assert.deepEqual(completed, {
+ auditRunId: RUN_ID,
+ durationMs: 750,
+ outcome: "failure",
+ reportGenerated: false,
+ });
+ const payload = emitted[0].data.eventInfo.auditPermissions;
+ assert.deepEqual(payload, {
+ schemaVersion: 1,
+ auditRunId: RUN_ID,
+ reportGenerated: false,
+ failureStage: "report_rendering",
+ });
+ assert.throws(
+ () => completeRun({
+ runId: RUN_ID,
+ outcome: "failure",
+ failureStage: "report_rendering",
+ }, {
+ env,
+ emit,
+ monotonicNow: () => 6_000_000_000n,
+ }),
+ (error) => error && error.code === "EEXIST"
+ );
+});
+
+test("converts invalid success metrics into a fixed metrics-validation failure", (t) => {
+ const { dir, env } = makeTempDir(t);
+ const data = auditData();
+ const artifacts = writeAuditArtifacts(dir, data);
+ data.SCORECARD_DATA.categories[0].score = 5;
+ fs.writeFileSync(artifacts.dataPath, JSON.stringify(data), "utf8");
+ const emitted = [];
+ beginRun({
+ env,
+ randomUUID: uuidSequence(RUN_ID, SESSION_ID),
+ monotonicNow: () => 10_000_000_000n,
+ });
+ const completed = completeRun({
+ runId: RUN_ID,
+ outcome: "success",
+ data: artifacts.dataPath,
+ report: artifacts.reportPath,
+ }, {
+ env,
+ emit: (event) => emitted.push(event),
+ monotonicNow: () => 11_000_000_000n,
+ });
+ assert.equal(completed.outcome, "failure");
+ assert.equal(completed.reportGenerated, false);
+ assert.equal(
+ emitted[0].data.eventInfo.auditPermissions.failureStage,
+ "metrics_validation"
+ );
+ assert.equal(emitted[0].data.eventInfo.auditPermissions.scores, undefined);
+});
+
+test("an invalid completion does not consume the run, so a corrected retry still records it", (t) => {
+ const { env } = makeTempDir(t);
+ const emitted = [];
+ const emit = (event) => emitted.push(event);
+ beginRun({
+ env,
+ randomUUID: uuidSequence(RUN_ID, SESSION_ID),
+ monotonicNow: () => 1_000_000_000n,
+ });
+
+ assert.throws(
+ () => completeRun(
+ { runId: RUN_ID, outcome: "failure", failureStage: "typo_stage" },
+ { env, emit, monotonicNow: () => 2_000_000_000n }
+ ),
+ /invalid_failure_stage/
+ );
+ assert.throws(
+ () => completeRun(
+ { runId: RUN_ID, outcome: "bogus" },
+ { env, emit, monotonicNow: () => 2_000_000_000n }
+ ),
+ /invalid_outcome/
+ );
+ // Monotonic clock moved backwards (e.g. reboot between start and complete).
+ assert.throws(
+ () => completeRun(
+ { runId: RUN_ID, outcome: "failure", failureStage: "audit_checks" },
+ { env, emit, monotonicNow: () => 1n }
+ ),
+ /invalid_duration/
+ );
+ assert.equal(emitted.length, 0, "run initialization and rejected completions must not emit");
+
+ const completed = completeRun(
+ { runId: RUN_ID, outcome: "failure", failureStage: "audit_checks" },
+ { env, emit, monotonicNow: () => 2_000_000_000n }
+ );
+ assert.equal(completed.outcome, "failure");
+ assert.equal(completed.durationMs, 1000);
+ assert.equal(emitted.length, 1);
+ assert.equal(emitted[0].data.eventInfo.auditPermissions.failureStage, "audit_checks");
+});
+
+function auditRunsDir(configDir) {
+ return path.join(configDir, "telemetry", "power-pages", "audit-runs");
+}
+
+for (const [label, ikeyContent] of [
+ ["disabled: true", JSON.stringify({ disabled: true, event_stream_name: "PagesAIPluginEvent" })],
+ ["an unreadable ikey.json", "{ not json"],
+]) {
+ test(`kill switch (${label}) writes no run state and returns no run id`, (t) => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "audit-killswitch-"));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const ikeyPath = path.join(dir, "ikey.json");
+ fs.writeFileSync(ikeyPath, ikeyContent, "utf8");
+ const result = spawnSync(process.execPath, [SCRIPT_PATH, "--action", "start"], {
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ PATH: "",
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: dir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,
+ },
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(JSON.parse(result.stdout), { status: "disabled" });
+ assert.equal(fs.existsSync(path.join(dir, "telemetry")), false, "no telemetry files may be written");
+ });
+}
+
+test("kill switch flipped mid-run discards state without a marker or event", (t) => {
+ const { dir, env } = makeTempDir(t);
+ const emitted = [];
+ const emit = (event) => emitted.push(event);
+ beginRun({
+ env,
+ randomUUID: uuidSequence(RUN_ID, SESSION_ID),
+ monotonicNow: () => 1_000_000_000n,
+ });
+ assert.ok(fs.existsSync(path.join(auditRunsDir(dir), `${RUN_ID}.json`)));
+
+ fs.writeFileSync(env.POWER_PLATFORM_SKILLS_IKEY_JSON, JSON.stringify({ disabled: true }), "utf8");
+ const result = completeRun(
+ { runId: RUN_ID, outcome: "failure", failureStage: "audit_checks" },
+ { env, emit, monotonicNow: () => 2_000_000_000n }
+ );
+ assert.deepEqual(result, { auditRunId: RUN_ID, disabled: true });
+ assert.equal(emitted.length, 0);
+ assert.deepEqual(fs.readdirSync(auditRunsDir(dir)), [], "state removed and no completion marker written");
+});
+
+test("start emits nothing and opt-out keeps completion local", (t) => {
+ const { dir, env } = makeTempDir(t);
+ const probePath = path.join(dir, "probe.json");
+ const result = spawnSync(process.execPath, [SCRIPT_PATH, "--action", "start"], {
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ ...env,
+ PATH: "",
+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: probePath,
+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "1",
+ },
+ });
+ assert.equal(result.status, 0, result.stderr);
+ const start = JSON.parse(result.stdout);
+ assert.equal(start.status, "started");
+ assert.match(start.auditRunId, /^[0-9a-f-]{36}$/i);
+ assert.equal(latestMirror(dir), null, "run initialization must not emit telemetry");
+ assert.equal(fs.existsSync(probePath), false);
+
+ const completionResult = spawnSync(process.execPath, [
+ SCRIPT_PATH,
+ "--action",
+ "complete",
+ "--runId",
+ start.auditRunId,
+ "--outcome",
+ "failure",
+ "--failureStage",
+ "audit_checks",
+ ], {
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ ...env,
+ PATH: "",
+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: probePath,
+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "1",
+ },
+ });
+ assert.equal(completionResult.status, 0, completionResult.stderr);
+
+ const mirror = waitForMirror(dir);
+ assert.ok(mirror, "opted-out lifecycle event should remain in the local mirror");
+ const record = JSON.parse(fs.readFileSync(mirror, "utf8").trim());
+ assert.equal(record.data.eventName, "audit_permissions_run_completed");
+ assert.equal(record.data.eventInfo.auditPermissions.auditRunId, start.auditRunId);
+ assert.equal(fs.existsSync(probePath), false, "opt-out must suppress the collector POST");
+});
diff --git a/plugins/power-pages/scripts/tests/audit-telemetry-gate.test.js b/plugins/power-pages/scripts/tests/audit-telemetry-gate.test.js
new file mode 100644
index 000000000..1da215b07
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/audit-telemetry-gate.test.js
@@ -0,0 +1,282 @@
+"use strict";
+
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+
+const { deriveAuditMetrics } = require("../lib/audit-report-validation");
+const {
+ MAX_EVENT_INFO_BYTES,
+ assertSafeOutgoingEvent,
+} = require("../lib/audit-telemetry-gate");
+const {
+ beginRun,
+ buildCompletionEvent,
+ completeRun,
+} = require("../emit-audit-permissions-telemetry");
+
+const RUN_ID = "11111111-1111-4111-8111-111111111111";
+const SESSION_ID = "22222222-2222-4222-8222-222222222222";
+const CORRELATION_ID = "33333333-3333-4333-8333-333333333333";
+const SECRET = "SITE_SECRET_123";
+
+function context(eventInfo, outcome, durationMs) {
+ return {
+ pluginName: "power-pages",
+ pluginVersion: "2.7.2",
+ sessionId: SESSION_ID,
+ correlationId: CORRELATION_ID,
+ osName: "Mac",
+ osVersion: "25.0.0",
+ nodeVersion: "v22",
+ skillName: "audit-permissions",
+ aiAgentName: "Copilot CLI",
+ aiAgentVersion: "1.0.3",
+ eventInfo,
+ outcome,
+ durationMs,
+ };
+}
+
+function metricsData() {
+ return {
+ FINDINGS_DATA: [
+ {
+ id: "AH1",
+ severity: "major",
+ dimension: "anonymous-access-hygiene",
+ title: "t",
+ reasoning: "r",
+ fix: "f",
+ rootCause: "permissions",
+ rootCauseReason: "x",
+ },
+ ],
+ SCORECARD_DATA: {
+ categories: [
+ { name: "Over-Exposure (Security)", score: 4.21 },
+ { name: "Under-Exposure (Usability & Coverage)", score: 5 },
+ { name: "Correctness (Validity & Alignment)", score: 5 },
+ ],
+ },
+ };
+}
+
+function successEvent() {
+ const auditPermissions = {
+ schemaVersion: 1,
+ auditRunId: RUN_ID,
+ reportGenerated: true,
+ ...deriveAuditMetrics(metricsData()),
+ };
+ return buildCompletionEvent(
+ "PagesAIPluginEvent",
+ context({ auditPermissions }, "success", 42731)
+ );
+}
+
+function failureEvent() {
+ return buildCompletionEvent(
+ "PagesAIPluginEvent",
+ context(
+ {
+ auditPermissions: {
+ schemaVersion: 1,
+ auditRunId: RUN_ID,
+ reportGenerated: false,
+ failureStage: "report_validation",
+ },
+ },
+ "failure",
+ 9124
+ )
+ );
+}
+
+function rejects(mutate, label) {
+ for (const make of [successEvent, failureEvent]) {
+ const event = make();
+ const applied = mutate(event);
+ if (applied === false) continue;
+ assert.throws(
+ () => assertSafeOutgoingEvent(event),
+ (error) => {
+ assert.match(error.message, /^outgoing_event_rejected:[A-Za-z_]+$/, label);
+ assert.doesNotMatch(error.message, new RegExp(SECRET), `${label}: message must not echo values`);
+ return true;
+ },
+ label
+ );
+ }
+}
+
+test("accepts the real success and failure completion events", () => {
+ assert.doesNotThrow(() => assertSafeOutgoingEvent(successEvent()));
+ assert.doesNotThrow(() => assertSafeOutgoingEvent(failureEvent()));
+});
+
+test("rejects extra keys at every level", () => {
+ rejects((e) => { e.siteName = SECRET; }, "envelope key");
+ rejects((e) => { e.data.siteName = SECRET; }, "top-level key");
+ rejects((e) => { e.data.orgId = RUN_ID; }, "orgId");
+ rejects((e) => { e.data.tenantId = RUN_ID; }, "tenantId");
+ rejects((e) => { e.data.eventInfo.framework = "react"; }, "eventInfo.framework");
+ rejects((e) => { e.data.eventInfo.aadObjectId = RUN_ID; }, "eventInfo.aadObjectId");
+ rejects((e) => { e.data.eventInfo.auditPermissions.table = SECRET; }, "payload key");
+ rejects((e) => {
+ if (!e.data.eventInfo.auditPermissions.dimensions) return false;
+ e.data.eventInfo.auditPermissions.dimensions.tableCoverage.table = SECRET;
+ return true;
+ }, "nested payload key");
+});
+
+test("rejects free-form text in enum and identifier slots", () => {
+ rejects((e) => {
+ if (!e.data.eventInfo.auditPermissions.verdict) return false;
+ e.data.eventInfo.auditPermissions.verdict = SECRET;
+ return true;
+ }, "verdict text");
+ rejects((e) => {
+ if (e.data.outcome !== "failure") return false;
+ e.data.eventInfo.auditPermissions.failureStage = SECRET;
+ return true;
+ }, "failureStage text");
+ rejects((e) => { e.data.eventInfo.auditPermissions.auditRunId = SECRET; }, "run id text");
+ rejects((e) => {
+ e.data.eventInfo.auditPermissions.auditRunId = "11111111-1111-1111-8111-111111111111";
+ }, "non-v4 run id");
+ rejects((e) => { e.data.sessionId = SECRET; }, "session id text");
+ rejects((e) => { e.data.correlationId = SECRET; }, "correlation id text");
+});
+
+test("rejects paths, URLs, and UPNs in standard context fields", () => {
+ rejects((e) => { e.data.osVersion = "/Users/maker/contoso-site"; }, "path");
+ rejects((e) => { e.data.aiAgentName = "https://private.example"; }, "url");
+ rejects((e) => { e.data.pluginVersion = "[email protected]"; }, "upn");
+ rejects((e) => { e.data.nodeVersion = "v22 /tmp"; }, "node version");
+ rejects((e) => { e.name = "Pages/Event"; }, "stream name");
+});
+
+test("rejects arrays, bad numbers, and wrong value types", () => {
+ rejects((e) => { e.data.eventInfo.auditPermissions.extra = [SECRET]; }, "array");
+ rejects((e) => {
+ if (e.data.outcome !== "success") return false;
+ e.data.eventInfo.auditPermissions.majorIssueCount = -1;
+ return true;
+ }, "negative count");
+ rejects((e) => {
+ if (e.data.outcome !== "success") return false;
+ e.data.eventInfo.auditPermissions.scores.overExposure = Number.NaN;
+ return true;
+ }, "NaN score");
+ rejects((e) => { e.data.durationMs = -5; }, "negative duration");
+ rejects((e) => { e.data.durationMs = 1.5; }, "fractional duration");
+ rejects((e) => { e.data.eventInfo = SECRET; }, "eventInfo string");
+});
+
+test("rejects inconsistent lifecycle combinations", () => {
+ rejects((e) => { e.data.eventName = "audit_permissions_run_started"; }, "start event");
+ rejects((e) => { e.data.eventName = "skill_started"; }, "other event");
+ rejects((e) => {
+ e.data.outcome = e.data.outcome === "success" ? "failure" : "success";
+ }, "outcome/payload mismatch");
+ rejects((e) => { e.data.severity = e.data.severity === "Info" ? "Error" : "Info"; }, "severity");
+ rejects((e) => {
+ if (e.data.outcome !== "success") return false;
+ e.data.eventInfo.auditPermissions.reportGenerated = false;
+ return true;
+ }, "success without report");
+});
+
+test("worst-case realistic success payload stays inside the size budget", () => {
+ const event = successEvent();
+ const payload = event.data.eventInfo.auditPermissions;
+ // Large counters are the only way a valid payload grows.
+ for (const map of [payload.categories, payload.dimensions]) {
+ for (const counts of Object.values(map)) {
+ counts.major = 999999;
+ counts.minor = 999999;
+ }
+ }
+ const size = Buffer.byteLength(JSON.stringify(event.data.eventInfo), "utf8");
+ assert.ok(size < MAX_EVENT_INFO_BYTES, `payload ${size} bytes must stay below ${MAX_EVENT_INFO_BYTES}`);
+});
+
+function makeTempEnv(t, streamName) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "audit-gate-"));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const ikeyPath = path.join(dir, "ikey.json");
+ const writeIkey = (name) => fs.writeFileSync(
+ ikeyPath,
+ JSON.stringify({ disabled: false, event_stream_name: name }),
+ "utf8"
+ );
+ writeIkey(streamName);
+ return {
+ dir,
+ writeIkey,
+ env: { POWER_PLATFORM_SKILLS_CONFIG_DIR: dir, POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath },
+ };
+}
+
+test("a gate rejection sends nothing and does not consume the run", (t) => {
+ // An invalid stream name makes the otherwise-valid event fail the gate.
+ const { dir, env, writeIkey } = makeTempEnv(t, "Pages/Event");
+ const emitted = [];
+ const emit = (event) => emitted.push(event);
+ let next = 0;
+ const ids = [RUN_ID, SESSION_ID];
+ beginRun({ env, randomUUID: () => ids[next++], monotonicNow: () => 1_000_000_000n });
+
+ assert.throws(
+ () => completeRun(
+ { runId: RUN_ID, outcome: "failure", failureStage: "audit_checks" },
+ { env, emit, monotonicNow: () => 2_000_000_000n }
+ ),
+ /outgoing_event_rejected:stream_name/
+ );
+ assert.equal(emitted.length, 0, "a rejected event must never reach the dispatcher");
+ assert.equal(
+ fs.existsSync(path.join(dir, "telemetry", "power-pages", "audit-runs", `${RUN_ID}.completed`)),
+ false,
+ "a rejected event must not claim the completion slot"
+ );
+
+ writeIkey("PagesAIPluginEvent");
+ const completed = completeRun(
+ { runId: RUN_ID, outcome: "failure", failureStage: "audit_checks" },
+ { env, emit, monotonicNow: () => 2_000_000_000n }
+ );
+ assert.equal(completed.outcome, "failure");
+ assert.equal(emitted.length, 1);
+});
+
+test("an unsafe host agent name is omitted rather than leaked or blocking the event", (t) => {
+ const { env } = makeTempEnv(t, "PagesAIPluginEvent");
+ const previous = { name: process.env.AI_AGENT_NAME, version: process.env.AI_AGENT_VERSION };
+ process.env.AI_AGENT_NAME = `/Users/maker/${SECRET}`;
+ process.env.AI_AGENT_VERSION = "1.0.0";
+ t.after(() => {
+ for (const [key, value] of [["AI_AGENT_NAME", previous.name], ["AI_AGENT_VERSION", previous.version]]) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ });
+
+ const emitted = [];
+ const emit = (event) => emitted.push(event);
+ let next = 0;
+ const ids = [RUN_ID, SESSION_ID];
+ beginRun({ env, randomUUID: () => ids[next++], monotonicNow: () => 1_000_000_000n });
+ completeRun(
+ { runId: RUN_ID, outcome: "failure", failureStage: "audit_checks" },
+ { env, emit, monotonicNow: () => 2_000_000_000n }
+ );
+
+ assert.equal(emitted.length, 1);
+ assert.equal(emitted[0].data.aiAgentName, undefined);
+ assert.equal(emitted[0].data.aiAgentVersion, "1.0.0");
+ assert.doesNotMatch(JSON.stringify(emitted[0]), new RegExp(SECRET));
+});
diff --git a/plugins/power-pages/scripts/tests/validate-audit.test.js b/plugins/power-pages/scripts/tests/validate-audit.test.js
index 56468a366..b4f807bad 100644
--- a/plugins/power-pages/scripts/tests/validate-audit.test.js
+++ b/plugins/power-pages/scripts/tests/validate-audit.test.js
@@ -1,5 +1,6 @@
const test = require('node:test');
const assert = require('node:assert/strict');
+const fs = require('node:fs');
const { spawnSync } = require('child_process');
const path = require('path');
@@ -14,6 +15,17 @@ const VALIDATOR_PATH = path.join(
'scripts',
'validate-audit.js'
);
+const ENABLED_TEST_TELEMETRY = {
+ disabled: false,
+ event_stream_name: 'PagesAIPluginEvent',
+ instrumentationKey: 'test-key',
+ collector_url: 'https://example.invalid/OneCollector/1.0/',
+};
+const TELEMETRY_SCRIPT_PATH = path.join(
+ __dirname,
+ '..',
+ 'emit-audit-permissions-telemetry.js'
+);
function validFindings() {
return [
@@ -196,3 +208,155 @@ test('hook mode never blocks, even with an invalid earlier report', (t) => {
assert.equal(outcome.status, 0, outcome.stderr);
assert.equal(outcome.stderr, '');
});
+
+test('validated report and source data record successful lifecycle completion together', (t) => {
+ const projectRoot = createTempProject(t);
+ const configDir = path.join(projectRoot, '.telemetry-test');
+ const ikeyPath = writeProjectFile(
+ projectRoot,
+ '.telemetry-test/ikey.json',
+ JSON.stringify(ENABLED_TEST_TELEMETRY)
+ );
+ const env = {
+ ...process.env,
+ PATH: '',
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,
+ // Enabled config so run state is created, but opted out so nothing is POSTed.
+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: '1',
+ };
+ const started = spawnSync(process.execPath, [TELEMETRY_SCRIPT_PATH, '--action', 'start'], {
+ encoding: 'utf8',
+ env,
+ });
+ assert.equal(started.status, 0, started.stderr);
+ const auditRunId = JSON.parse(started.stdout).auditRunId;
+
+ const findings = validFindings();
+ const scorecard = validScorecard();
+ const reportPath = writeReport(projectRoot, { findings, scorecard });
+ const dataPath = writeProjectFile(
+ projectRoot,
+ 'audit-data.json',
+ JSON.stringify({
+ FINDINGS_DATA: findings,
+ SCORECARD_DATA: scorecard,
+ })
+ );
+ const outcome = spawnSync(process.execPath, [
+ VALIDATOR_PATH,
+ '--report', reportPath,
+ '--data', dataPath,
+ '--auditRunId', auditRunId,
+ ], {
+ encoding: 'utf8',
+ env,
+ });
+ assert.equal(outcome.status, 0, outcome.stderr);
+ const result = JSON.parse(outcome.stdout);
+ assert.equal(result.valid, true);
+ assert.equal(result.telemetryStatus, 'recorded_success');
+ assert.ok(fs.existsSync(path.join(
+ configDir,
+ 'telemetry',
+ 'power-pages',
+ 'audit-runs',
+ `${auditRunId}.completed`
+ )));
+});
+
+test('valid report with unreconcilable source data is recorded as a failed run', (t) => {
+ const projectRoot = createTempProject(t);
+ const configDir = path.join(projectRoot, '.telemetry-test');
+ const ikeyPath = writeProjectFile(
+ projectRoot,
+ '.telemetry-test/ikey.json',
+ JSON.stringify(ENABLED_TEST_TELEMETRY)
+ );
+ const env = {
+ ...process.env,
+ PATH: '',
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,
+ // Enabled config so run state is created, but opted out so nothing is POSTed.
+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: '1',
+ };
+ const started = spawnSync(process.execPath, [TELEMETRY_SCRIPT_PATH, '--action', 'start'], {
+ encoding: 'utf8',
+ env,
+ });
+ assert.equal(started.status, 0, started.stderr);
+ const auditRunId = JSON.parse(started.stdout).auditRunId;
+
+ const reportPath = writeReport(projectRoot);
+ // The data file no longer matches the rendered report (one finding dropped).
+ const dataPath = writeProjectFile(
+ projectRoot,
+ 'audit-data.json',
+ JSON.stringify({ FINDINGS_DATA: validFindings().slice(0, 1), SCORECARD_DATA: null })
+ );
+ const outcome = spawnSync(process.execPath, [
+ VALIDATOR_PATH,
+ '--report', reportPath,
+ '--data', dataPath,
+ '--auditRunId', auditRunId,
+ ], {
+ encoding: 'utf8',
+ env,
+ });
+ assert.equal(outcome.status, 0, outcome.stderr);
+ const result = JSON.parse(outcome.stdout);
+ assert.equal(result.valid, true, 'the report itself remains valid');
+ assert.equal(result.telemetryStatus, 'recorded_failure');
+});
+
+test('a telemetry module that cannot load never breaks report validation or the hook', (t) => {
+ const projectRoot = createTempProject(t);
+ // Preload that makes loading the telemetry emitter throw, standing in for any
+ // load failure (missing file, syntax error, partial install).
+ const preload = writeProjectFile(
+ projectRoot,
+ 'break-telemetry.js',
+ "const Module = require('module');\n" +
+ 'const load = Module._load;\n' +
+ 'Module._load = function (request, ...rest) {\n' +
+ " if (/emit-audit-permissions-telemetry/.test(request)) throw new Error('simulated load failure');\n" +
+ ' return load.call(this, request, ...rest);\n' +
+ '};\n'
+ );
+ const run = (args, input) => spawnSync(process.execPath, ['--require', preload, VALIDATOR_PATH, ...args], {
+ input,
+ encoding: 'utf8',
+ env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: '1' },
+ });
+
+ const findings = validFindings();
+ const scorecard = validScorecard();
+ const reportPath = writeReport(projectRoot, { findings, scorecard });
+
+ // Report-only validation must not even load telemetry.
+ let outcome = run(['--report', reportPath]);
+ assert.equal(outcome.status, 0, outcome.stderr);
+ assert.equal(JSON.parse(outcome.stdout).telemetryStatus, 'not_requested');
+
+ // The PostToolUse(Skill) hook must still approve.
+ outcome = run([], JSON.stringify({ cwd: projectRoot }));
+ assert.equal(outcome.status, 0, outcome.stderr);
+ assert.equal(outcome.stderr, '');
+
+ // When telemetry is requested, the load failure is contained and reported.
+ const dataPath = writeProjectFile(
+ projectRoot,
+ 'audit-data.json',
+ JSON.stringify({ FINDINGS_DATA: findings, SCORECARD_DATA: scorecard })
+ );
+ outcome = run([
+ '--report', reportPath,
+ '--data', dataPath,
+ '--auditRunId', '11111111-1111-4111-8111-111111111111',
+ ]);
+ assert.equal(outcome.status, 0, outcome.stderr);
+ const result = JSON.parse(outcome.stdout);
+ assert.equal(result.valid, true, 'the report stays valid when telemetry cannot load');
+ assert.equal(result.telemetryStatus, 'failed');
+});
diff --git a/plugins/power-pages/skills/audit-permissions/SKILL.md b/plugins/power-pages/skills/audit-permissions/SKILL.md
index 30ac1b490..19d82acf6 100644
--- a/plugins/power-pages/skills/audit-permissions/SKILL.md
+++ b/plugins/power-pages/skills/audit-permissions/SKILL.md
@@ -41,6 +41,44 @@ The skill has two parts:
**Important:** Do NOT ask the user questions during analysis. Autonomously gather all data, then present findings.
+## Audit completion telemetry
+
+At the very start of Step 1, before site verification, initialize local run state:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/emit-audit-permissions-telemetry.js" --action start
+```
+
+Parse the JSON stdout and retain its `auditRunId` as `<AUDIT_RUN_ID>` for this invocation. The command does not emit a telemetry event; the existing generic skill invocation event is the start signal. The local run state provides the opaque random ID and start time needed for completion telemetry. Never derive the ID from, or replace it with, a site, environment, tenant, user, path, or report value.
+
+Telemetry is best-effort and must never block the audit. If the initialization command fails or returns no `auditRunId`, continue the audit without completion telemetry. Do not invent an id and do not search local state for the latest run.
+
+On every controlled terminal failure after a run id was returned, close the run before stopping:
+
+```bash
+node "${PLUGIN_ROOT}/scripts/emit-audit-permissions-telemetry.js" \
+ --action complete \
+ --runId "<AUDIT_RUN_ID>" \
+ --outcome failure \
+ --failureStage "<FAILURE_STAGE>"
+```
+
+Use exactly one of these fixed failure stages:
+
+- `site_verification`
+- `configuration_gathering`
+- `schema_validation`
+- `relationship_discovery`
+- `audit_checks`
+- `scoring`
+- `root_cause_attribution`
+- `report_rendering`
+- `report_validation`
+- `metrics_validation`
+- `unknown_controlled_failure`
+
+Do not pass error messages, paths, table names, finding content, or other user/site data to the telemetry script. A telemetry completion failure does not change the audit outcome and must not trigger a second completion attempt.
+
## Task Tracking
At the start of Step 1, create all tasks upfront using `TaskCreate`. Mark each task `in_progress` when starting and `completed` when done.
@@ -70,6 +108,8 @@ Use `Glob` to find:
If no `.powerpages-site` folder exists, stop and tell the user to deploy first using `/deploy-site`.
If no table permissions exist, note this as a critical finding (the site may have no data access configured) and continue the audit — there may still be code references that need permissions.
+Before stopping because `.powerpages-site` is absent, close completion telemetry with `failureStage: site_verification` as described above.
+
---
## Step 2: Gather Configuration
@@ -707,14 +747,21 @@ The render script refuses to overwrite existing files. Before calling it, check
Run the semantic validator on the rendered report:
```bash
-node "${PLUGIN_ROOT}/skills/audit-permissions/scripts/validate-audit.js" --report "<OUTPUT_PATH>"
+node "${PLUGIN_ROOT}/skills/audit-permissions/scripts/validate-audit.js" \
+ --report "<OUTPUT_PATH>" \
+ --data "<DATA_JSON_PATH>" \
+ --auditRunId "<AUDIT_RUN_ID>"
```
-Do not present or copy a report until validation succeeds. The validator reads `FINDINGS_DATA`, `INVENTORY_DATA`, and `SCORECARD_DATA` from the report and checks unique issue ids whose prefix matches the dimension, major/minor severities, non-empty `title`/`reasoning`/`fix`, a valid `rootCause` and `rootCauseReason` on every major finding (and none on minor findings), that the inventory is an array, the three category scores recomputed from the findings, that `SUMMARY` states the verdict matching the major count (and neither verdict phrase on a partial audit), and leftover placeholders.
+When local run initialization returned no run id, omit `--data` and `--auditRunId`; report validation must still run.
+
+Do not present or copy a report until validation succeeds. The validator reads `FINDINGS_DATA`, `INVENTORY_DATA`, and `SCORECARD_DATA` from the report and checks unique issue ids whose prefix matches the dimension, major/minor severities, non-empty `title`/`reasoning`/`fix`, a valid `rootCause` and `rootCauseReason` on every major finding (and none on minor findings), that the inventory is an array, the three category scores recomputed from the findings, that `SUMMARY` states the verdict matching the major count (and neither verdict phrase on a partial audit), and leftover placeholders. When the run id and data path are supplied, the same deterministic command revalidates the source data, derives the closed aggregate metrics, and records successful completion and elapsed duration.
If validation fails, delete the report you just rendered, fix the named problem in the data file, render again to the same path, and rerun the validator. Do not repeat evidence gathering to fix a validation error.
-Delete the temporary `audit-data.json` and `audit-evidence.json` files after validation succeeds.
+The validator reports `telemetryStatus` as `recorded_success`, `recorded_failure` (the report is valid but its source data could not be reconciled, so the run was recorded with `failureStage: metrics_validation`), `disabled` (telemetry is hard-disabled for this plugin, so nothing was recorded), `failed`, or `not_requested`. Telemetry is best-effort: none of `recorded_failure`, `disabled`, or `failed` invalidates the report. Do not retry with a reduced payload and do not expose report data in diagnostic output.
+
+Delete the temporary `audit-data.json` and `audit-evidence.json` files only after report validation succeeds. The telemetry status does not affect cleanup.
### 7.5 Open in Browser
diff --git a/plugins/power-pages/skills/audit-permissions/scripts/validate-audit.js b/plugins/power-pages/skills/audit-permissions/scripts/validate-audit.js
index e66bbc336..2be3bd319 100644
--- a/plugins/power-pages/skills/audit-permissions/scripts/validate-audit.js
+++ b/plugins/power-pages/skills/audit-permissions/scripts/validate-audit.js
@@ -1,153 +1,16 @@
#!/usr/bin/env node
-const fs = require('fs');
const path = require('path');
const { approve, runValidation } = require('../../../scripts/lib/validation-helpers');
+const { validateReport } = require('../../../scripts/lib/audit-report-validation');
-const PREFIXES = {
- 'intent-coverage': 'IC',
- 'privilege-calibration': 'PC',
- 'scope-correctness': 'SC',
- 'role-completeness': 'RC',
- 'table-coverage': 'TC',
- 'anonymous-access-hygiene': 'AH',
- 'data-model-alignment': 'DM',
- 'internal-consistency': 'IS',
- 'security-posture': 'SP',
-};
-const CATEGORIES = [
- {
- id: 'over-exposure',
- name: /^Over-Exposure/i,
- dimensions: ['privilege-calibration', 'anonymous-access-hygiene', 'security-posture'],
- },
- {
- id: 'under-exposure',
- name: /^Under-Exposure/i,
- dimensions: ['intent-coverage', 'table-coverage', 'role-completeness'],
- },
- {
- id: 'correctness',
- name: /^Correctness/i,
- dimensions: ['scope-correctness', 'data-model-alignment', 'internal-consistency'],
- },
-];
-const ROOT_CAUSES = ['permissions', 'mixed', 'data-model', 'webapi-code', 'webapi-settings'];
-
-function round(value) {
- return Math.round(value * 100) / 100;
-}
-
-function scoreFromIssues(major, minor) {
- return round(5 - 4 * Math.tanh(0.2 * (major + 0.25 * minor)));
-}
-
-function countIssues(issues) {
- const major = issues.filter((issue) => issue.severity === 'major').length;
- const minor = issues.filter((issue) => issue.severity === 'minor').length;
- return { major, minor, total: major + minor };
-}
-
-function requireText(record, fields, label) {
- for (const field of fields) {
- if (typeof record[field] !== 'string' || !record[field].trim()) {
- throw new Error(`${label} needs a non-empty ${field}.`);
- }
- }
-}
-
-function validateFindings(findings) {
- if (!Array.isArray(findings)) throw new Error('FINDINGS must be an array.');
- const ids = new Set();
- for (const finding of findings) {
- const prefix = PREFIXES[finding.dimension];
- if (!prefix) throw new Error(`Finding ${finding.id} has invalid dimension ${finding.dimension}.`);
- if (!new RegExp(`^${prefix}[1-9][0-9]*$`).test(finding.id)) {
- throw new Error(`Finding ${finding.id} must use the ${prefix} prefix for ${finding.dimension}.`);
- }
- if (ids.has(finding.id)) throw new Error(`Finding ${finding.id} is listed more than once.`);
- ids.add(finding.id);
- if (!['major', 'minor'].includes(finding.severity)) {
- throw new Error(`Finding ${finding.id} has invalid severity ${finding.severity}.`);
- }
- requireText(finding, ['title', 'reasoning', 'fix'], `Finding ${finding.id}`);
- if (finding.severity === 'major') {
- if (!ROOT_CAUSES.includes(finding.rootCause)) {
- throw new Error(`Major finding ${finding.id} has invalid rootCause ${finding.rootCause}.`);
- }
- requireText(finding, ['rootCauseReason'], `Major finding ${finding.id}`);
- } else if (finding.rootCause !== undefined || finding.rootCauseReason !== undefined) {
- throw new Error(`Minor finding ${finding.id} must not carry a root cause.`);
- }
- }
-}
-
-function validateScorecard(scorecard, findings) {
- if (scorecard === null) return;
- const categories = scorecard?.categories;
- if (!Array.isArray(categories) || categories.length !== CATEGORIES.length) {
- throw new Error(`SCORECARD.categories must contain exactly ${CATEGORIES.length} entries.`);
- }
- CATEGORIES.forEach((category, index) => {
- const entry = categories[index];
- if (!category.name.test(String(entry?.name || ''))) {
- throw new Error(`SCORECARD.categories[${index}] must be ${category.id}, found ${entry?.name}.`);
- }
- const counts = countIssues(findings.filter((finding) => category.dimensions.includes(finding.dimension)));
- const expected = scoreFromIssues(counts.major, counts.minor);
- if (entry.score !== expected) {
- throw new Error(`${entry.name} score is ${entry.score}; expected ${expected}.`);
- }
- });
-}
-
-function scriptText(html) {
- return [...html.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi)].map((match) => match[1]).join('\n');
-}
-
-// Rendered JSON stays on one line, so a line-start match can't come from inside a value.
-function readConst(script, name) {
- const matches = [...script.matchAll(new RegExp(`^const ${name} = (.*)$`, 'gm'))];
- if (matches.length === 0) throw new Error(`Audit report has no ${name} data.`);
- if (matches.length > 1) throw new Error(`Audit report declares ${name} more than once.`);
- const json = matches[0][1].trim().replace(/;$/, '');
- try {
- return JSON.parse(json);
- } catch {
- throw new Error(`Audit report ${name} data is not valid JSON.`);
- }
-}
-
-function validateSummary(html, scorecard, majorCount) {
- const match = html.match(/id="summaryBox"[^>]*>([\s\S]*?)<\/div>/);
- if (!match) throw new Error('Audit report has no SUMMARY.');
- const states = (phrase) => match[1].toLowerCase().includes(phrase.toLowerCase());
- if (scorecard === null) {
- if (states('Safe to go') || states('Needs revision')) {
- throw new Error('SUMMARY must not state a verdict when scoring was skipped.');
- }
- return null;
- }
- const [expected, opposite] = majorCount === 0 ? ['Safe to go', 'Needs revision'] : ['Needs revision', 'Safe to go'];
- if (!states(expected) || states(opposite)) {
- throw new Error(`SUMMARY must state the verdict "${expected}" and not "${opposite}".`);
- }
- return expected;
-}
-
-function validateReport(reportPath) {
- const html = fs.readFileSync(reportPath, 'utf8');
- if (/__(?:(?:HTML|ATTR|JSON|RAW)_)?(?:SITE_NAME|AUDIT_DESC|SUMMARY|FINDINGS_DATA|INVENTORY_DATA|SCORECARD_DATA)__/.test(html)) {
- throw new Error('Audit report has unreplaced data placeholders.');
- }
- const script = scriptText(html);
- const findings = readConst(script, 'FINDINGS');
- validateFindings(findings);
- if (!Array.isArray(readConst(script, 'INVENTORY'))) throw new Error('INVENTORY must be an array.');
- const scorecard = readConst(script, 'SCORECARD');
- validateScorecard(scorecard, findings);
- const issueCounts = countIssues(findings);
- return { issueCounts, verdict: validateSummary(html, scorecard, issueCounts.major) };
+// Telemetry is best-effort, so it is loaded only when a completion is actually
+// recorded. A top-level require would make report validation and the
+// PostToolUse(Skill) hook depend on the telemetry module: any load failure
+// (missing file, syntax error, partial install) would crash this script before
+// validateReport runs. Loading here keeps that failure inside the caller's try.
+function completeRun(...args) {
+ return require('../../../scripts/emit-audit-permissions-telemetry').completeRun(...args);
}
function fail(error) {
@@ -162,12 +25,41 @@ if (reportFlagIndex >= 0 && (!process.argv[reportFlagIndex + 1] || process.argv[
fail(new Error('Usage: validate-audit.js --report <path>'));
}
const explicitReport = reportFlagIndex >= 0 ? process.argv[reportFlagIndex + 1] : positionalReport;
+const runFlagIndex = process.argv.indexOf('--auditRunId');
+const dataFlagIndex = process.argv.indexOf('--data');
+const auditRunId = runFlagIndex >= 0 ? process.argv[runFlagIndex + 1] : null;
+const dataPath = dataFlagIndex >= 0 ? process.argv[dataFlagIndex + 1] : null;
if (explicitReport) {
try {
const reportPath = path.resolve(explicitReport);
const summary = validateReport(reportPath);
- process.stdout.write(`${JSON.stringify({ valid: true, reportPath, ...summary })}\n`);
+ let telemetryStatus = 'not_requested';
+ if (auditRunId && dataPath) {
+ try {
+ // completeRun downgrades to a metrics_validation failure when the source
+ // data cannot be reconciled with the report, so report what was recorded.
+ const completion = completeRun({
+ runId: auditRunId,
+ outcome: 'success',
+ data: path.resolve(dataPath),
+ report: reportPath,
+ });
+ telemetryStatus = completion.disabled
+ ? 'disabled'
+ : completion.outcome === 'success' ? 'recorded_success' : 'recorded_failure';
+ } catch {
+ // A validated report remains successful even if optional telemetry fails.
+ telemetryStatus = 'failed';
+ }
+ }
+ process.stdout.write(`${JSON.stringify({
+ valid: true,
+ reportPath,
+ issueCounts: summary.issueCounts,
+ verdict: summary.verdict,
+ telemetryStatus,
+ })}\n`);
} catch (error) {
fail(error);
}
diff --git a/shared/telemetry/README.md b/shared/telemetry/README.md
index b567ed916..7c66208ff 100644
--- a/shared/telemetry/README.md
+++ b/shared/telemetry/README.md
@@ -63,7 +63,7 @@ choice cannot override `disabled: true`.
| Plugin | Committed state | Current behavior | Plugin-specific fields |
|---|---|---|---|
-| Power Pages | `disabled: false` | Enabled and default-on for transmission. Organization-based geo routing selects a regional collector; without an organization ID, the configured US default is used. Events are written to the local mirror even after a user transmission opt-out. | `eventInfo.aadObjectId` when PAC exposes the signed-in user's Entra object ID; `eventInfo.framework` when the Power Pages code-site framework can be determined. |
+| Power Pages | `disabled: false` | Enabled and default-on for transmission. Organization-based geo routing selects a regional collector; without an organization ID, the configured US default is used. Events are written to the local mirror even after a user transmission opt-out. | `eventInfo.aadObjectId` when PAC exposes the signed-in user's Entra object ID; `eventInfo.framework` when the Power Pages code-site framework can be determined; `eventInfo.auditPermissions` (aggregate, identity-free) on the `audit-permissions` completion event. |
| Mobile Apps | `disabled: false` | Enabled and default-on for transmission. Its project environment selects the regional collector. Until that cluster is resolved, events remain in the local mirror and are not transmitted. | `eventInfo.invocationSource`; random per-project `eventInfo.appInstanceId` (or `null` outside a prepared project); optional validated checkpoint `eventInfo.additionalInfo`; and `eventInfo.appInsightsSelection`. |
| Model Apps | `disabled: false` | Enabled and default-on for transmission. A public-cloud organization is geo-routed to the US or EU collector (US default only without an organization ID; an organization whose geo cannot be determined is not transmitted); a sovereign or internal PAC cloud is routed from the cloud stamp alone, never to a public collector; an unrecognized cloud, or a signed-in organization with no cloud, is not transmitted. Events are written to the local mirror even after a user transmission opt-out. | No signed-in user object ID. The base event can include `orgId` and `tenantId` when PAC is signed in. |
| Power Automate | `disabled: false` | Enabled and default-on for transmission. Its resolver returns a destination only for public cloud, so sovereign-cloud events stay in the local mirror. Organization-based geo routing selects the US or EU collector; without an organization ID, the configured US default is used. Events are written to the local mirror even after a user transmission opt-out. | `eventInfo.aadObjectId` when PAC exposes the signed-in user's Entra object ID. The plugin's bundled MCP server and CLI emit on the same stream and additionally record `outcome`, `durationMs`, `errorClass`, and `errorCode`, a random per-invocation `correlationId` and per-process `sessionId`, and `envId`/`envLocation`/`envRegion`. Error messages are never recorded. |
@@ -132,6 +132,12 @@ Every event carries a fixed allowlist enforced by `lib/events.js`. Field names m
- `aadObjectId` — the signed-in user's stable Entra ID / AAD directory object ID, parsed from `pac auth who`, when available. Omitted when `pac auth who` does not surface an object ID.
- `framework` — the SPA framework of the Power Pages **code site** the skill is running against, drawn from the closed set `react`, `vue`, `angular`, `astro`. Omitted unless the working directory resolves to a site with a `powerpages.config.json`.
+ - `auditPermissions` — present only on the `audit_permissions_run_completed` event, emitted once per `audit-permissions` run when it produces its HTML report or reaches a controlled failure. It is built by a deterministic allowlist-only emitter (`plugins/power-pages/scripts/emit-audit-permissions-telemetry.js`) and must pass a closed outbound gate (`plugins/power-pages/scripts/lib/audit-telemetry-gate.js`) immediately before dispatch; raw report values are never copied into it. Every string is a fixed enum value or a random UUID v4, and every number is a bounded count, score, or version.
+ - Always: `schemaVersion` (`1`), `auditRunId` (random per-run UUID v4, not derived from any site, user, or environment value), and `reportGenerated` (boolean).
+ - Success (`outcome: success`, `reportGenerated: true`, recorded only after the final HTML report passes semantic validation): `scoringStatus` (`complete` | `partial`), `verdict` (`safe_to_go` | `needs_revision` | `not_scored`), `majorIssueCount`, `minorIssueCount`, `totalIssueCount`, `categories` (`overExposure`, `underExposure`, `correctness`, each `{ major, minor }`), `dimensions` (`intentCoverage`, `privilegeCalibration`, `scopeCorrectness`, `roleCompleteness`, `tableCoverage`, `anonymousAccessHygiene`, `dataModelAlignment`, `internalConsistency`, `securityPosture`, each `{ major, minor }`), `majorRootCauses` (`permissions`, `mixed`, `dataModel`, `webApiCode`, `webApiSettings`, each a count), and, when scoring is complete, `scores` (`overExposure`, `underExposure`, `correctness`, each 1–5).
+ - Failure (`outcome: failure`, `reportGenerated: false`): `failureStage` only, one of `site_verification`, `configuration_gathering`, `schema_validation`, `relationship_discovery`, `audit_checks`, `scoring`, `root_cause_attribution`, `report_rendering`, `report_validation`, `metrics_validation`, or `unknown_controlled_failure`.
+
+ The completion event also carries the top-level `outcome` and `durationMs` fields. It deliberately omits `orgId`, `tenantId`, `aadObjectId`, and `framework`, so it routes to the configured default region, and it never includes site, environment, table, role, permission, path, finding, or report text.
Each key is omitted independently when its source is unavailable; `eventInfo` itself is omitted only when every key would be absent.