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: graded, consistent audit-permissions with root-cause labels (#663)

jagdeepms24fb08c32a56ff
diff --git a/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md b/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md
index c694ae9e4..2cb1f8e19 100644
--- a/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md
+++ b/plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md
@@ -80,7 +80,7 @@ For skills that process multiple entities (e.g., audit-permissions auditing many
|-------|--------|-------------------|
| `/deploy-site` | 6 phases (prereqs → auth → env → build/upload → verify → summarize) | None |
| `/integrate-webapi` | 7 phases (prereqs → analyze → plan → implement → verify → permissions → deploy) | Per-table tasks in Phase 4 |
-| `/audit-permissions` | 7 phases (prereqs → discover → analyze → audit → cross-check → report → present) | Per-table tasks in Phase 4 (checklist A-K) |
+| `/audit-permissions` | 8 phases (verify → gather → discover → audit → score → root cause → report → present) | Per-table tasks in Phase 4 (checklist A-K) |
| `/create-site` | 8 phases (prereqs → gather → plan → scaffold → implement → validate → deploy → summarize) | None |
> **Acceptance criterion:** Every linear skill must create all phase tasks upfront at Phase 1 start. A branching skill must create all path-agnostic tasks upfront and append the selected branch's tasks as soon as the branch is known. Each task must have `subject`, `activeForm`, and `description`. Tasks must be marked `in_progress` when starting and `completed` when done.
@@ -112,7 +112,7 @@ After implementation, always run a standalone verification phase that:
|-------|-------------------|----------------|
| `/deploy-site` | Phase 5 | Upload succeeded, site responds, activation status |
| `/integrate-webapi` | Phase 5 | File inventory matches plan, all imports resolve, build passes |
-| `/audit-permissions` | Phase 6 | Findings report generated, all tables audited, cross-checks complete |
+| `/audit-permissions` | Phase 7 | Report rendered and passes `validate-audit.js`, all tables audited, cross-checks complete |
| `/create-site` | Phase 6 | All pages render, design foundations applied, build passes |
| `/create-webroles` | PostToolUse hook | Web role YAML validates (schema, naming conventions, booleans) |
diff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.md
index b4ce50f49..3bfe38e51 100644
--- a/plugins/power-pages/README.md
+++ b/plugins/power-pages/README.md
@@ -211,11 +211,11 @@ Adds login/logout functionality and role-based authorization to your site.
> "Check my table permissions for security issues"
-Audits existing table permissions on a deployed or in-progress site by analyzing them against the site code and live Dataverse metadata. Produces a visual HTML audit report grouped by severity with suggested fixes.
+Audits existing table permissions on a deployed or in-progress site against the site code and local metadata, querying live Dataverse relationship metadata only when a reachable flow has unresolved dependencies. Produces a visual HTML audit report with a verdict, category scores, and suggested fixes.
-- Findings grouped as critical / warning / info / pass
-- Cross-references code usage, web roles, and Dataverse schema
-- Suggests concrete fixes for each issue
+- Each issue rated **major** or **minor**, with a Safe to go / Needs revision verdict and 1–5 scores for over-exposure, under-exposure, and correctness
+- Each major issue labelled permissions-only or caused upstream (data model, site code, or Web API settings)
+- Cross-references code usage, web roles, sign-up settings, and Dataverse schema, and suggests a concrete fix for each issue
#### `/scan-site`
diff --git a/plugins/power-pages/references/approval-gates.md b/plugins/power-pages/references/approval-gates.md
index aaad5a3aa..d2b46be0e 100644
--- a/plugins/power-pages/references/approval-gates.md
+++ b/plugins/power-pages/references/approval-gates.md
@@ -612,7 +612,7 @@ Template-path note: when Phase 1.5 selects and installs a template, the workflow
| ID | Kind | Category | Phase | Trigger / question | Cancel leaves |
|---|---|---|---|---|---|
-| `audit-permissions:6.fix-offer` | gate | plan | 6 | Audit complete — *"Would you like me to fix any of these issues? Yes / No"* — declining leaves the audit report untouched; accepting routes to the table-permissions-architect agent | nothing |
+| `audit-permissions:6.fix-offer` | gate | plan | 8 | Audit complete — *"Would you like me to fix any of these issues? Yes / No"* — declining leaves the audit report untouched; accepting routes to the table-permissions-architect agent | nothing |
---
diff --git a/plugins/power-pages/scripts/render-audit-report.js b/plugins/power-pages/scripts/render-audit-report.js
index 99eb39b65..d89b54255 100644
--- a/plugins/power-pages/scripts/render-audit-report.js
+++ b/plugins/power-pages/scripts/render-audit-report.js
@@ -6,7 +6,7 @@
* node render-audit-report.js --output <path> --data <json-file>
*
* Required keys in the JSON data file:
- * SITE_NAME, AUDIT_DESC, SUMMARY, FINDINGS_DATA, INVENTORY_DATA
+ * SITE_NAME, AUDIT_DESC, SUMMARY, FINDINGS_DATA, INVENTORY_DATA, SCORECARD_DATA (object or null)
*/
const path = require('path');
@@ -25,5 +25,5 @@ renderTemplate({
templatePath: path.join(__dirname, '..', 'skills', 'audit-permissions', 'assets', 'audit-report.html'),
outputPath: path.resolve(args.output),
dataPath: path.resolve(args.data),
- requiredKeys: ['SITE_NAME', 'AUDIT_DESC', 'SUMMARY', 'FINDINGS_DATA', 'INVENTORY_DATA'],
+ requiredKeys: ['SITE_NAME', 'AUDIT_DESC', 'SUMMARY', 'FINDINGS_DATA', 'INVENTORY_DATA', 'SCORECARD_DATA'],
});
diff --git a/plugins/power-pages/scripts/tests/render-audit-report.test.js b/plugins/power-pages/scripts/tests/render-audit-report.test.js
new file mode 100644
index 000000000..225ebafd8
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/render-audit-report.test.js
@@ -0,0 +1,82 @@
+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 scriptPath = path.join(__dirname, '..', 'render-audit-report.js');
+const validatorPath = path.join(__dirname, '..', '..', 'skills', 'audit-permissions', 'scripts', 'validate-audit.js');
+
+const SAMPLE_DATA = {
+ SITE_NAME: 'Contoso Portal',
+ AUDIT_DESC: 'Security audit of table permissions for Contoso Portal',
+ SUMMARY: 'One major issue: anonymous users can read staff contact details. Needs revision.',
+ FINDINGS_DATA: [{
+ id: 'AH1',
+ severity: 'major',
+ dimension: 'anonymous-access-hygiene',
+ title: 'Staff contact details readable by Anonymous',
+ table: 'contoso_staff',
+ reasoning: 'Staff-Public-Read grants Anonymous Global read.',
+ fix: 'Restrict the permission to a staff role.',
+ rootCause: 'permissions',
+ rootCauseReason: 'The anonymous Global read grant alone exposes the data.',
+ }],
+ INVENTORY_DATA: [{
+ name: 'Staff - Public Read',
+ table: 'contoso_staff',
+ scope: 'Global',
+ roles: ['Anonymous Users'],
+ read: true,
+ create: false,
+ write: false,
+ delete: false,
+ append: false,
+ appendto: false,
+ }],
+ SCORECARD_DATA: {
+ categories: [
+ { name: 'Over-Exposure (Security)', score: 4.21 },
+ { name: 'Under-Exposure (Usability & Coverage)', score: 5 },
+ { name: 'Correctness (Validity & Alignment)', score: 5 },
+ ],
+ reportPaths: [{ label: 'HTML report', path: 'docs/permissions-audit.html' }],
+ },
+};
+
+function render(t, data) {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'audit-report-'));
+ t.after(() => fs.rmSync(tempDir, { recursive: true, force: true }));
+ const dataPath = path.join(tempDir, 'audit-data.json');
+ const outputPath = path.join(tempDir, 'permissions-audit.html');
+ fs.writeFileSync(dataPath, JSON.stringify(data), 'utf8');
+ const result = spawnSync(process.execPath, [scriptPath, '--output', outputPath, '--data', dataPath], { encoding: 'utf8' });
+ return { result, outputPath };
+}
+
+test('renders a report with a scorecard that passes validation', (t) => {
+ const { result, outputPath } = render(t, SAMPLE_DATA);
+ assert.equal(result.status, 0, result.stderr);
+ const html = fs.readFileSync(outputPath, 'utf8');
+ assert.doesNotMatch(html, /__(?:JSON_)?SCORECARD_DATA__/);
+ assert.match(html, /const SCORECARD = \{/);
+ const validation = spawnSync(process.execPath, [validatorPath, '--report', outputPath], { encoding: 'utf8' });
+ assert.equal(validation.status, 0, validation.stderr);
+});
+
+test('renders a null scorecard when scoring was skipped', (t) => {
+ const { result, outputPath } = render(t, { ...SAMPLE_DATA, SCORECARD_DATA: null });
+ assert.equal(result.status, 0, result.stderr);
+ const html = fs.readFileSync(outputPath, 'utf8');
+ assert.match(html, /const SCORECARD = null;/);
+ assert.match(html, /id="ovPartialWrap"[\s\S]*Partial audit:/);
+});
+
+test('fails when SCORECARD_DATA is missing', (t) => {
+ const { SCORECARD_DATA, ...withoutScorecard } = SAMPLE_DATA;
+ const { result, outputPath } = render(t, withoutScorecard);
+ assert.notEqual(result.status, 0);
+ assert.match(result.stderr, /Missing required keys in data file: SCORECARD_DATA/);
+ assert.equal(fs.existsSync(outputPath), false);
+});
diff --git a/plugins/power-pages/scripts/tests/validate-audit.test.js b/plugins/power-pages/scripts/tests/validate-audit.test.js
new file mode 100644
index 000000000..56468a366
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/validate-audit.test.js
@@ -0,0 +1,198 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { spawnSync } = require('child_process');
+const path = require('path');
+
+const { createTempProject, writeProjectFile } = require('./test-utils');
+
+const VALIDATOR_PATH = path.join(
+ __dirname,
+ '..',
+ '..',
+ 'skills',
+ 'audit-permissions',
+ 'scripts',
+ 'validate-audit.js'
+);
+
+function validFindings() {
+ return [
+ {
+ id: 'AH1',
+ severity: 'major',
+ dimension: 'anonymous-access-hygiene',
+ title: 'Staff contact details readable by Anonymous',
+ reasoning: 'Staff-Public-Read grants Anonymous Global read.',
+ fix: 'Restrict the permission to a staff role.',
+ rootCause: 'permissions',
+ rootCauseReason: 'The anonymous Global read grant alone exposes the data.',
+ },
+ {
+ id: 'IS1',
+ severity: 'minor',
+ dimension: 'internal-consistency',
+ title: 'No permission plan document',
+ reasoning: 'docs/permissions-plan.html is missing.',
+ fix: 'Add a permission plan.',
+ },
+ ];
+}
+
+function validScorecard() {
+ 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: 'HTML report', path: 'docs/permissions-audit.html' }],
+ };
+}
+
+function reportHtml(findings, scorecard, inventory = [], summary = 'Roles are well separated, but staff contacts are public. Needs revision.') {
+ return `<!doctype html><html><body><div class="card" id="summaryBox">${summary}</div><script>\n` +
+ `const FINDINGS = ${JSON.stringify(findings)};\n` +
+ `const INVENTORY = ${JSON.stringify(inventory)};\n` +
+ `const SCORECARD = ${JSON.stringify(scorecard)};\n` +
+ '</script></body></html>';
+}
+
+function writeReport(projectRoot, { findings = validFindings(), scorecard = validScorecard(), html } = {}) {
+ return writeProjectFile(projectRoot, 'docs/permissions-audit.html', html ?? reportHtml(findings, scorecard));
+}
+
+function runReport(reportPath) {
+ return spawnSync(process.execPath, [VALIDATOR_PATH, '--report', reportPath], { encoding: 'utf8' });
+}
+
+function runHook(cwd) {
+ return spawnSync(process.execPath, [VALIDATOR_PATH], {
+ input: JSON.stringify({ cwd }),
+ encoding: 'utf8',
+ });
+}
+
+function expectFailure(t, { findings: mutateFindings, scorecard: mutateScorecard }, pattern) {
+ const projectRoot = createTempProject(t);
+ const findings = validFindings();
+ const scorecard = validScorecard();
+ mutateFindings?.(findings);
+ mutateScorecard?.(scorecard);
+ const outcome = runReport(writeReport(projectRoot, { findings, scorecard }));
+ assert.equal(outcome.status, 1, outcome.stdout);
+ assert.match(outcome.stderr, pattern);
+}
+
+test('valid report passes', (t) => {
+ const projectRoot = createTempProject(t);
+ const outcome = runReport(writeReport(projectRoot));
+ assert.equal(outcome.status, 0, outcome.stderr);
+ const summary = JSON.parse(outcome.stdout);
+ assert.equal(summary.valid, true);
+ assert.deepEqual(summary.issueCounts, { major: 1, minor: 1, total: 2 });
+ assert.equal(summary.verdict, 'Needs revision');
+});
+
+test('recomputes category scores from the findings', (t) => {
+ expectFailure(t, { scorecard: (s) => { s.categories[0].score = 3.5; } }, /Over-Exposure \(Security\) score is 3\.5; expected 4\.21/);
+ expectFailure(t, { findings: (f) => { f[1].severity = 'major'; f[1].rootCause = 'permissions'; f[1].rootCauseReason = 'x'; } }, /Correctness \(Validity & Alignment\) score is 4\.8; expected 4\.21/);
+ expectFailure(t, { scorecard: (s) => { s.categories.reverse(); } }, /categories\[0\] must be over-exposure/);
+ expectFailure(t, { scorecard: (s) => { s.categories.pop(); } }, /must contain exactly 3/);
+});
+
+test('skips the score check when scoring was skipped', (t) => {
+ const projectRoot = createTempProject(t);
+ const html = reportHtml(validFindings(), null, [], 'Partial audit: the data model was missing.');
+ const outcome = runReport(writeReport(projectRoot, { html }));
+ assert.equal(outcome.status, 0, outcome.stderr);
+ assert.equal(JSON.parse(outcome.stdout).verdict, null);
+});
+
+test('requires the summary to state the computed verdict', (t) => {
+ const projectRoot = createTempProject(t);
+ const minorOnly = validFindings().slice(1);
+ const minorScorecard = validScorecard();
+ minorScorecard.categories[0].score = 5;
+ const cases = [
+ [reportHtml(validFindings(), validScorecard(), [], 'Staff contacts are public. Safe to go.'), /must state the verdict "Needs revision"/],
+ [reportHtml(minorOnly, minorScorecard, [], 'Only a missing plan. Needs revision.'), /must state the verdict "Safe to go"/],
+ [reportHtml(validFindings(), null, [], 'Partial audit. Needs revision.'), /must not state a verdict/],
+ [reportHtml(validFindings(), validScorecard()).replace(/<div[^>]*summaryBox[^>]*>.*?<\/div>/, ''), /no SUMMARY/],
+ ];
+ for (const [html, pattern] of cases) {
+ const outcome = runReport(writeReport(projectRoot, { html }));
+ assert.equal(outcome.status, 1, outcome.stdout);
+ assert.match(outcome.stderr, pattern);
+ }
+ const outcome = runReport(writeReport(projectRoot, { html: reportHtml(minorOnly, minorScorecard, [], 'Only a missing plan. Safe to go.') }));
+ assert.equal(outcome.status, 0, outcome.stderr);
+});
+
+test('rejects malformed findings', (t) => {
+ expectFailure(t, { findings: (f) => { f[1].id = 'SP1'; } }, /SP1 must use the IS prefix/);
+ expectFailure(t, { findings: (f) => { f[1].dimension = 'unknown'; } }, /invalid dimension unknown/);
+ expectFailure(t, { findings: (f) => { f[1].severity = 'info'; } }, /invalid severity info/);
+ expectFailure(t, { findings: (f) => { f[1] = { ...f[0] }; } }, /AH1 is listed more than once/);
+ expectFailure(t, { findings: (f) => { f[1].fix = ''; } }, /IS1 needs a non-empty fix/);
+ expectFailure(t, { findings: (f) => { delete f[0].title; } }, /AH1 needs a non-empty title/);
+ expectFailure(t, { findings: (f) => { f[0].reasoning = ' '; } }, /AH1 needs a non-empty reasoning/);
+});
+
+test('requires a root cause on major findings only', (t) => {
+ expectFailure(t, { findings: (f) => { f[0].rootCause = 'unknown'; } }, /AH1 has invalid rootCause unknown/);
+ expectFailure(t, { findings: (f) => { delete f[0].rootCause; } }, /AH1 has invalid rootCause undefined/);
+ expectFailure(t, { findings: (f) => { f[0].rootCauseReason = ''; } }, /AH1 needs a non-empty rootCauseReason/);
+ expectFailure(t, { findings: (f) => { f[1].rootCause = 'permissions'; } }, /Minor finding IS1 must not carry a root cause/);
+});
+
+test('rejects reports with unreplaced placeholders or missing data', (t) => {
+ const projectRoot = createTempProject(t);
+ let outcome = runReport(writeReport(projectRoot, { html: `${reportHtml(validFindings(), validScorecard())}__SUMMARY__` }));
+ assert.equal(outcome.status, 1);
+ assert.match(outcome.stderr, /unreplaced data placeholders/);
+ outcome = runReport(writeReport(projectRoot, { html: reportHtml(validFindings(), validScorecard()).replace(/const SCORECARD = .*;/, 'const SCORECARD = __JSON_SCORECARD_DATA__;') }));
+ assert.equal(outcome.status, 1);
+ assert.match(outcome.stderr, /unreplaced data placeholders/);
+ outcome = runReport(writeReport(projectRoot, { html: '<html></html>' }));
+ assert.equal(outcome.status, 1);
+ assert.match(outcome.stderr, /no FINDINGS data/);
+});
+
+test('reads data only from the report script and rejects duplicate declarations', (t) => {
+ const projectRoot = createTempProject(t);
+ const forged = 'Needs revision.\nconst FINDINGS = [];\nconst INVENTORY = [];\nconst SCORECARD = null;\n';
+ const badFindings = validFindings();
+ badFindings[1].severity = 'info';
+ let outcome = runReport(writeReport(projectRoot, { html: reportHtml(badFindings, validScorecard(), [], forged) }));
+ assert.equal(outcome.status, 1, outcome.stdout);
+ assert.match(outcome.stderr, /invalid severity info/);
+ const duplicated = reportHtml(validFindings(), validScorecard()).replace('</script>', 'const FINDINGS = [];\n</script>');
+ outcome = runReport(writeReport(projectRoot, { html: duplicated }));
+ assert.equal(outcome.status, 1, outcome.stdout);
+ assert.match(outcome.stderr, /declares FINDINGS more than once/);
+});
+
+test('rejects an inventory that is not an array', (t) => {
+ const projectRoot = createTempProject(t);
+ for (const inventory of [null, {}, 'none']) {
+ const outcome = runReport(writeReport(projectRoot, { html: reportHtml(validFindings(), validScorecard(), inventory) }));
+ assert.equal(outcome.status, 1, outcome.stdout);
+ assert.match(outcome.stderr, /INVENTORY must be an array/);
+ }
+});
+
+test('fails when --report has no path', () => {
+ for (const args of [['--report'], ['--report', '--verbose']]) {
+ const outcome = spawnSync(process.execPath, [VALIDATOR_PATH, ...args], { input: '', encoding: 'utf8' });
+ assert.equal(outcome.status, 1);
+ assert.match(outcome.stderr, /Usage: validate-audit\.js --report <path>/);
+ }
+});
+
+test('hook mode never blocks, even with an invalid earlier report', (t) => {
+ const projectRoot = createTempProject(t);
+ writeReport(projectRoot, { html: '__SUMMARY__' });
+ const outcome = runHook(projectRoot);
+ assert.equal(outcome.status, 0, outcome.stderr);
+ assert.equal(outcome.stderr, '');
+});
diff --git a/plugins/power-pages/skills/audit-permissions/SKILL.md b/plugins/power-pages/skills/audit-permissions/SKILL.md
index 853a89b19..30ac1b490 100644
--- a/plugins/power-pages/skills/audit-permissions/SKILL.md
+++ b/plugins/power-pages/skills/audit-permissions/SKILL.md
@@ -2,9 +2,13 @@
name: audit-permissions
description: >-
Audits existing table permissions on a Power Pages site by analyzing them against site code
- and Dataverse metadata. Generates an HTML audit report with findings grouped by severity
- (critical, warning, info, pass) and suggests fixes for issues found. Use when the user wants
- to review, verify, or check table permissions for security issues.
+ and Dataverse metadata, then GRADES the configuration with deterministic 1–5 scores across
+ 3 security/usability/correctness categories (9 dimensions). Detection is anchored by a
+ recurring-issue catalog so findings and severities stay consistent run-to-run. Generates an
+ HTML report with an at-a-glance verdict and per-category scores in the Overview plus a
+ single list of **major/minor** issues (each major issue labelled permissions-only or upstream-caused with a short justification), and suggested fixes.
+ Use when the user wants to review, verify, check, score,
+ or grade table permissions for security issues.
user-invocable: true
argument-hint: "[optional: specific table or concern]"
allowed-tools: Read, Write, Bash, Glob, Grep, AskUserQuestion, TaskCreate, TaskUpdate, TaskList, Agent
@@ -15,17 +19,25 @@ model: opus
# Audit Permissions
-Audit existing table permissions on a Power Pages code site. Analyze permissions against the site code and Dataverse metadata, then generate a visual HTML audit report with findings, reasoning, and suggested fixes.
+Audit existing table permissions on a Power Pages code site. Analyze permissions against the site code and Dataverse metadata, then generate a visual HTML report with **deterministic 1–5 category scores**, an advisory verdict, findings, reasoning, and suggested fixes.
+
+The skill has two parts:
+
+1. **Audit checks** (evidence + remediation) — the per-table A–K checklist that compares every permission against real code usage and Dataverse metadata. It is the **primary issue detector**: it catches concrete, code-grounded problems (missing CRUD, append/appendto, `$expand` gaps, broken parent chains, over-provisioned grants) and emits each as a **major/minor** issue with concrete evidence and a fix.
+2. **Scoring** (reproducible result) — a **3-category** rubric (9 dimensions) anchored by a **recurring-issue catalog** of fixed detection triggers + severities, followed by a **single consolidation** into root causes and **one batched root-cause attribution** pass for major issues. It turns the findings into **pure-formula 1–5 category scores** so two runs on the same configuration yield the same numbers.
+
+> **Golden rule of scoring:** you only ever **find and label issues** (`major` / `minor`). You do NOT invent the numeric score. The 1–5 numbers come from a **fixed formula** applied to the issue counts (see [Appendix A](#appendix-a--scoring-model)). Same issue set ⇒ same score.
## Workflow
1. **Verify Site Deployment** — Check that `.powerpages-site` folder and table permissions exist
-2. **Gather Configuration** — Read all web roles, table permissions, and site code
-3. **Run Local Schema Validation** — Use the shared validator to detect invalid permission/site-setting YAML before deeper analysis
-4. **Analyze & Discover** — Query Dataverse for relationships and lookup columns using deterministic scripts
-5. **Run Audit Checks** — Compare permissions against code usage and best practices
-6. **Generate Report** — Create the HTML audit report and display in browser
-7. **Present Findings & Track** — Summarize findings, record skill usage, and ask user if they want to fix issues
+2. **Gather Configuration** — Read web roles, table permissions, site code, run the shared schema validator, and build the deterministic preflight cross-reference
+3. **Analyze & Discover** — Query Dataverse for relationships and lookup columns using deterministic scripts
+4. **Run Audit Checks** — Compare permissions against code usage and best practices (A–K checklist)
+5. **Score the Configuration** — Detect/label issues by the 3 categories using the recurring-issue catalog, consolidate to distinct root causes (major/minor), compute the 1–5 category scores and the verdict
+6. **Root-cause attribution** — In a single batched pass, label every major issue as permissions-only or caused by an upstream artifact, with a one-sentence justification shown in the report
+7. **Generate Report** — Create the HTML report (score overview + findings + inventory) and validate it
+8. **Present Findings & Track** — Summarize, record skill usage, and ask the user if they want to fix issues
**Important:** Do NOT ask the user questions during analysis. Autonomously gather all data, then present findings.
@@ -36,11 +48,12 @@ At the start of Step 1, create all tasks upfront using `TaskCreate`. Mark each t
| Task subject | activeForm | Description |
|-------------|------------|-------------|
| Verify site deployment | Verifying site deployment | Check .powerpages-site folder and table permissions exist |
-| Gather configuration | Gathering configuration | Read web roles, table permissions, and site code |
-| Run local schema validation | Validating local permissions schema | Run shared validator against existing table permission and site setting YAML |
+| Gather configuration | Gathering configuration | Read web roles, table permissions, site code; run validator; build preflight |
| Discover relationships | Discovering relationships | Query Dataverse for lookup columns and relationships |
| Run audit checks | Running audit checks | Create per-table tasks and run checklist (A–K) for each table, then cross-validate |
-| Generate audit report | Generating audit report | Create HTML report and display in browser |
+| Score configuration | Scoring configuration | Detect/label by the 3 categories via the recurring-issue catalog, consolidate to root causes, compute 1–5 scores |
+| Root-cause attribution | Attributing root causes | Label every major issue permissions-only or upstream-caused in a single pass |
+| Generate report | Generating report | Create and validate the HTML report and display it in browser |
| Present findings | Presenting findings | Summarize results, record usage, and offer to fix issues |
**Note:** The "Run audit checks" phase creates **additional per-table tasks** dynamically in Step 4.2. These per-table tasks track the systematic A–K checklist for each table independently.
@@ -61,35 +74,81 @@ If no table permissions exist, note this as a critical finding (the site may hav
## Step 2: Gather Configuration
+### Single-pass performance contract
+
+Gather all local evidence in **one bounded pass** before making judgments:
+
+1. Read web roles, table permissions, site settings, and `.datamodel-manifest.json` in grouped operations.
+2. Scan source files once for API operations, entity sets, selects, filters, lookups, expands, uploads, routes, imports, and feature/auth gates. Prefer one grouped search plus targeted reads of only the matching regions; never read an entire source tree file-by-file.
+3. Locate the permission plan once. Extract all authorization-relevant statements in one operation into `planClaims`; do not reopen or re-extract the plan later.
+4. Freeze these facts in `audit-evidence.json`. Steps 4–6 consume only this ledger plus any gated Dataverse results.
+
+Do not rescan source code or the plan to gain confidence. A second read is allowed only when a specific ledger field is missing and the exact file/region needed is known. Record the added evidence once, then continue. Never perform multiple searches for differently worded versions of the same plan claim.
+
### 2.1 Read Web Roles
-Read all files matching `**/.powerpages-site/web-roles/*.yml`. Extract `id`, `name`, `anonymoususersrole`, `authenticatedusersrole` from each.
+Read all files matching `**/.powerpages-site/web-roles/*.yml`. Keys may carry a publisher prefix — try `mspp_<key>`, then `adx_<key>`, then the bare `<key>` (first found wins). Extract `id`, `name`, `anonymoususersrole`, `authenticatedusersrole` from each. If YAML fails to parse or its root isn't an object, record a **parse error** (feeds preflight `IS`).
### 2.2 Read Table Permissions
-Read all files matching `**/.powerpages-site/table-permissions/*.tablepermission.yml`. For each permission, extract:
+Read all files matching `**/.powerpages-site/table-permissions/*.tablepermission.yml`. Using the same prefix rule, for each permission extract:
- `entityname` (permission name)
- `entitylogicalname` (table)
-- `scope` (numeric code)
+- `scope` (numeric code) → map to a label: `756150000 = Global`, `756150001 = Contact`, `756150002 = Account`, `756150003 = Parent`, `756150004 = Self`; anything else → `Unknown(<code>)`; missing → scope `-1`, label `Unknown`
- `read`, `create`, `write`, `delete`, `append`, `appendto` (boolean flags)
-- `adx_entitypermission_webrole` (array of web role UUIDs)
+- `adx_entitypermission_webrole` (array of web role UUIDs) → resolve each GUID to a role name via §2.1; unresolved → mark `<unresolved:…>`
- `contactrelationship`, `accountrelationship` (if Contact/Account scope)
- `parententitypermission`, `parentrelationship` (if parent scope)
+Record a **parse error** on failure (feeds preflight `IS`).
+
### 2.3 Analyze Site Code
-Search the site source code for:
+In the single source pass, search the site source code for:
- Web API calls (`/_api/`)
- Lookup bindings (`@odata.bind`)
- File uploads (`uploadFileColumn`, `uploadFile`, `upload*Photo`, `upload*Image`)
- `$expand` usage (`$expand`, `buildExpandClause`, `ExpandOption`)
-Also check for `.datamodel-manifest.json` in the project root for the authoritative table list.
+Also check for `.datamodel-manifest.json` in the project root for the authoritative table list. It has `{ environmentUrl?, tables: [{ logicalName, displayName, status?, columns: [{ logicalName, type }] }] }`. If missing or `tables` isn't an array, treat the data model as absent.
+
+Additionally scan **Web API artifacts** (used by the root-cause attribution in Step 6 — best-effort):
+
+- **Central client**: present if any of `src/shared/powerPagesApi.ts(x)` or `src/lib/powerPagesApi.ts` exists.
+- **Service files** under `src/shared/services/**` (`.ts/.tsx/.js/.jsx`): record which data-model table logical names and which HTTP methods (`GET/POST/PATCH/PUT/DELETE`) appear in each.
+- **Wildcard column selects**: record every occurrence of `$select=*` (or a `$select` whose value is `*`) in any scanned source file, together with its file path and the table being queried.
+- **Type files** under `src/types/**`: extract property names of the first `interface`/`type` literal; infer the table from filename/content when possible.
+- **Web API site settings** in `.powerpages-site/site-settings/` (files named `Webapi-*` / `Webapi/*`): parse `name` + `value`. Split `name` on `/`: `Webapi/<entitySet>/enabled` → kind `enabled`; `.../fields` → kind `fields`; `Webapi/error` → `error`; else `other`. `webapiEnabledEntitySets` = entity sets whose `enabled` value is exactly `"true"`. For every `fields` setting also record **`isWildcard`** — true when the trimmed value is `*`, or when any comma-separated entry is `*`. A list that names column logical names is NOT a wildcard, however long it is.
+
+Also scan **authentication/registration site settings** in `.powerpages-site/site-settings/` regardless of filename. Parse `name` + `value` for settings under `Authentication/Registration/`, including `Enabled`, `OpenRegistrationEnabled`, `ExternalLoginEnabled`, and `InvitationEnabled`. Also parse each external provider's `Authentication/<Type>/<Provider>/RegistrationEnabled`; a configured provider (any settings under `Authentication/<Type>/<Provider>/`) without that setting counts as `true`, the server default. Compare names case-insensitively and treat a value as enabled only when its trimmed value is case-insensitively `"true"`. Record missing settings as `unknown`, not `false`.
+
+Build an **audience reachability profile** before judging permissions:
+
+- A role with `authenticatedusersrole: true` is automatically assigned to every signed-in site user; it is a broad baseline role, not proof of staff, employee, teacher, parent, or other trusted-persona membership.
+- **Open registration** is proven when `OpenRegistrationEnabled` is `true` and either local registration is on (`Authentication/Registration/Enabled` is `true`) or `ExternalLoginEnabled` is not `false` (missing counts as `true`, the server default) and at least one configured external provider's `RegistrationEnabled` is `true`. External-only sites often omit `Authentication/Registration/Enabled`. With open registration, any visitor can create an account and enter that broad Authenticated Users audience.
+- External login or invitation enablement may provide additional entry paths, but do not assume they are open to the public without supporting configuration evidence.
+- Carry this profile into every per-table scope and audience check. Do not evaluate a role name or permission in isolation from how users acquire that role.
Build a map of: which tables are referenced in code, which CRUD operations are performed on each, which lookup relationships are used, and which related tables are fetched via `$expand` (these need read permissions too).
+Also build a **capability matrix** before judging missing access. One row per authorization-relevant capability:
+
+`persona | route/component | reachability | table | operation | current grant | plan claim | evidence`
+
+Classify `reachability` mechanically:
+
+- `reachable` — the page/component is registered in the deployed router or invoked by another reachable component, and no explicit feature flag or authorization gate disables it for that persona.
+- `disabled` — an explicit false feature flag, server-side authorization gate, build exclusion, or unreachable/unregistered component prevents the capability from running.
+- `ambiguous` — code exists but neither reachability nor exclusion can be established.
+
+A UI condition based on the signed-in user's own data (for example an `isAccountAdmin` field or a role flag on their profile record) never makes a capability `disabled` — it identifies the persona that uses it. Plan or comment wording such as "deferred", "future phase" or "not yet supported" never makes a routed capability `disabled` or `ambiguous`.
+
+Use this evidence precedence everywhere in the audit: **reachable implementation > explicit runtime gate/build exclusion > implementation plan > comments/names**. A plan cannot make a routed, callable feature hypothetical merely by calling its persona "back-office." Conversely, dead, unregistered, explicitly disabled, or server-gated code does not establish a required portal permission. If reachability is ambiguous and conflicts with the plan, emit at most one **minor** `internal-consistency` issue for the conflict; do not presume a broken flow.
+
+After the source pass, do not reopen routes, pages, services, or the permission plan during scoring. Reachability and plan claims are frozen ledger facts, not questions to reconsider in Step 5.
+
### 2.4 Run Shared Schema Validator
Run the shared validator against the existing site:
@@ -98,30 +157,59 @@ Run the shared validator against the existing site:
node "${PLUGIN_ROOT}/scripts/validate-permissions-schema.js" --projectRoot "<PROJECT_ROOT>"
```
-Parse the JSON output and carry the findings into the audit. Treat:
+Parse the JSON output and carry the findings into the audit as **major/minor** issues. Map:
-- `error` findings as **critical**
-- `warning` findings as **warning**
-- `info` findings as **info**
+- `error` findings → **major** issue
+- `warning` findings → **major** issue (unless purely forward-looking/cosmetic → **minor**)
+- `info` findings → **minor** issue
-These findings should be included in the final audit report even if the later code/Dataverse analysis also finds additional issues.
+These findings should be included in the final report even if the later code/Dataverse analysis also finds additional issues. Exception: drop the validator's "no associated web roles" warning for a Parent-scope child permission whose parent chain is valid (see check B).
-If the validator reports wildcard field access in a `Webapi/<table>/fields` setting, add this
-critical finding to the report:
+If the validator reports wildcard field access in a `Webapi/<table>/fields` setting, add this finding as a **major** `security-posture` issue (one per affected setting):
-- **Severity:** `critical`
- **Title:** `Unsupported wildcard Web API fields for <table>`
- **Reasoning:** The fields setting uses wildcard access, which is unsupported beginning September 14, 2026
- **Fix:** Replace the wildcard using `${PLUGIN_ROOT}/references/webapi-field-allowlist.md`: LogicalNames for ordinary columns, `_<LogicalName>_value` for lookup reads, and exact Navigation Properties used by `@odata.bind`
- **Details:** Include the site-setting file path and setting name from the validator finding
-After Step 3.1 determines the environment URL, if this audit is running locally with Dataverse access available, rerun the shared validator with live relationship verification enabled and merge any additional findings:
+After Step 3.1 determines the environment URL, rerun the shared validator with live relationship verification only when the Step 3 discovery gate is open. Merge any additional findings:
```bash
node "${PLUGIN_ROOT}/scripts/validate-permissions-schema.js" --projectRoot "<PROJECT_ROOT>" --validate-dataverse-relationships --envUrl "<envUrl>"
```
-Use this Dataverse-backed relationship validation only for local runs. Do **not** require it in CI or other offline contexts.
+Use this Dataverse-backed relationship validation only for local runs that need relationship evidence. Do **not** require it in CI or other offline contexts, and do not run it for Global-only/read-only designs with no relationship-dependent reachable flow.
+
+### 2.5 Deterministic preflight cross-reference (grader ground truth)
+
+Purely mechanical cross-checks over the parsed YAML + data model + Web API artifacts. **Emit ALL that apply.** Number IDs per prefix in encounter order (`IS1`, `IS2`, `DM1`, …). These are **ground truth**: carry them into the right dimension's issue list in Step 5 and never drop or downgrade them.
+
+| Condition | id prefix | dimension | severity |
+|---|---|---|---|
+| Web-role YAML parse error | IS | internal-consistency | major |
+| Table-permission YAML parse error | IS | internal-consistency | major |
+| Permission references a web-role GUID not defined in any role | IS | internal-consistency | major |
+| Web role has a **blank id** | IS | internal-consistency | major |
+| Permission has a **blank `entitylogicalname`** | DM | data-model-alignment | major |
+| Permission grants **no privileges** (all 6 CRUD bits false) | TC | table-coverage | major |
+| Permission has **no scope** (`scope < 0`) | SC | scope-correctness | major |
+| Permission scope code **unrecognized** (`Unknown(code)`) | SC | scope-correctness | minor |
+| Permission grants **write/create/delete to an Anonymous role** | AH | anonymous-access-hygiene | major |
+| Permission targets a table **not in the data model** (only when a valid data-model manifest exists) | DM | data-model-alignment | major |
+| Web API site-setting YAML parse error | IS | internal-consistency | major |
+| `-enabled` entity set with **no matching `-fields`** whitelist | IS | internal-consistency | major |
+| `-fields` whitelist with **no matching `-enabled`** setting | IS | internal-consistency | major |
+| Type file declaring 1–6 properties absent from the data model (only when a valid data-model manifest exists) | DM | data-model-alignment | minor |
+
+---
+
+### 2.6 Freeze the Evidence Ledger
+
+`<OUTPUT_DIR>` is `<PROJECT_ROOT>/docs/` when working in a website (a project root with `powerpages.config.json`); otherwise it is the system temp directory. The temporary files and the final report all go there.
+
+Before running judgment-based checks, write a temporary `<OUTPUT_DIR>/audit-evidence.json` containing the normalized facts gathered so far: roles, permissions, data-model tables/columns, service operations, route/component reachability, capability matrix, lookup/expand usage, client-side row filters, implementation-plan claims, authentication reachability, and preflight issues. Sort tables, permissions, routes, and capabilities by stable identifiers.
+
+Steps 4–6 MUST reason from this ledger instead of rescanning and selectively rediscovering evidence. If live Dataverse discovery adds facts in Step 3, append those facts and rewrite the ledger once before Step 4. Do not change a `reachability` classification during scoring unless new evidence is added to the ledger. Delete `audit-evidence.json` after the final HTML report passes validation.
---
@@ -129,6 +217,17 @@ Use this Dataverse-backed relationship validation only for local runs. Do **not*
Use deterministic Node.js scripts for all Dataverse API calls. These scripts handle auth token acquisition, HTTP requests, and JSON parsing consistently.
+### Dataverse discovery gate
+
+Before calling `pac env who` or any Dataverse query script, compute `needsLiveDiscovery`. It is `true` only when at least one reachable capability has one of these unresolved dependencies:
+
+- Contact, Account, or Parent scope whose relationship name must be verified
+- create/write code that binds or changes a lookup
+- `$expand` or related-table access whose target cannot be resolved from local metadata
+- file/image upload whose relationship or target metadata is unresolved
+
+It is `false` when none of those dependencies apply — for example, Global-only/read-only flows, explicit Administrator-only CRUD unused by reachable site code, and cases fully resolved by the manifest and local source. When `false`, skip all of Step 3, record `liveDiscovery: "not-needed"` in the evidence ledger, and continue to Step 4. When `true`, first confirm the active Dataverse environment URL matches the manifest environment URL; if it does not, skip live queries and record the mismatch instead of querying the wrong environment.
+
### 3.1 Get Environment URL
```bash
@@ -178,7 +277,7 @@ If any script exits with code 1, skip the API-dependent checks and note which ch
## Step 4: Run Audit Checks
-Use per-table task tracking to systematically run every audit check. Each check produces a finding with severity, title, reasoning, and a suggested fix. Findings can be `critical`, `warning`, `info`, or `pass`.
+Use per-table task tracking to systematically run every audit check. **These code- and Dataverse-grounded checks are the primary issue detectors** — they catch concrete problems (missing CRUD, append/appendto, `$expand` gaps, broken parent chains, over-provisioned grants) that rubric judgment alone would miss, which is what makes the issue set richer and the score more faithful. Each failed check emits **one provisional candidate** (title, responsible table, evidence, and a suggested fix); Step 5 assigns its final **major**/**minor** severity and dimension. A check that passes produces **no candidate**. Where a check says to search the service code, look the fact up in the evidence ledger (Step 2.6); search the source only when the ledger lacks it.
### 4.1 Build Audit Inventory
@@ -213,7 +312,9 @@ Use `TaskList` at any point to review progress and see which tables still need a
### 4.3 Per-Table Audit Checklist
-For each table, mark its task `in_progress` and run through the following checks **in order**. For every finding, note the **specific evidence** (file path, permission name, code pattern) that supports it. Skip checks that don't apply to this table.
+For each table, mark its task `in_progress` and run through the following checks **in order**. For every issue, note the **specific evidence** (file path, permission name, code pattern) that supports it. Skip checks that don't apply to this table.
+
+**Do not finalize severity or dimension in Step 4.** Each check below carries a provisional audit tier (`critical`, `warning`, or `info`) and emits a factual candidate as `{ sourceId, auditTier, title, table, reasoning, fix, evidence, reachability? }`. A check that passes yields no candidate. Step 5 is the **only** place that assigns the final `major|minor` severity and canonical dimension, using fixed catalog rules before generic policy. This prevents whichever audit path runs first from locking in a different score.
**A. Permission Existence**
@@ -240,6 +341,7 @@ Does the permission have web role(s) assigned?
- **Title:** `Permission <name> has no web role association`
- **Reasoning:** A permission without a web role has no effect — no users will receive this access
- **Fix:** Associate with the appropriate web role
+- Exception: a Parent-scope (`756150003`) child permission may leave its roles empty — it inherits role association through the parent chain. Raise no finding when its `parententitypermission` resolves to an existing permission; a broken chain is reported by check I.
- If roles are assigned → `pass`
**C. Scope Appropriateness**
@@ -247,12 +349,18 @@ Does the permission have web role(s) assigned?
Is the scope the least-privileged option that fits?
- Search the service code for scope-relevant patterns: contact-scoped filters (`getCurrentContactId`, `_contactid_value`, `contactid`) and account-scoped filters (`_accountid_value`, `parentcustomerid`)
+- For EACH Global-read permission, resolve every assigned role and apply the Step 2.3 audience reachability profile. Then inspect the table's selected/whitelisted columns, data-model columns, UI purpose, and implementation plan to determine whether the data is explicitly public or intended for a narrower persona.
+- **Mandatory cross-artifact trigger, evaluated separately per affected table:** emit a finding when ALL four conditions hold: (1) open registration is proven (Step 2.3 audience reachability profile); (2) the assigned web role has `authenticatedusersrole: true`, so every registered account receives it; (3) that role is attached to this table's permission with `read: true` and Global scope; and (4) the table carries per-person, roster, grade, contact, or internal operational data, or the site intent limits it to staff/teachers/another purpose-specific persona → finding:
+ - **Severity:** `critical`
+ - **Title:** `Self-registered users can read all <table> records`
+ - **Reasoning:** State the full evidence chain: registration setting(s) → automatic Authenticated Users membership → permission role binding → Global scope → exposed columns/intended audience. Authentication alone does not establish trusted-persona membership.
+ - **Fix:** Remove the baseline Authenticated Users role from this permission and assign a purpose-specific role provisioned only to verified users; where access is record-relative, use Contact, Account, Parent, or Self scope instead of Global.
- If Global scope (`756150000`) with `write` or `delete` enabled → finding:
- **Severity:** `warning`
- **Title:** `Global scope with write/delete on <table>`
- **Reasoning:** Any user with this role can modify/delete any record in this table
- **Fix:** Narrow to Contact or Account scope, or remove write/delete if not needed
-- If Global scope with only `read` → `pass` (acceptable for public reference data)
+- If Global scope has only `read`, pass ONLY when the table and exposed columns are explicitly public/non-sensitive and every assigned role is an intended audience. Otherwise evaluate it under the mandatory trigger above and recurring issues C3/C4; read-only access can still be a major confidentiality exposure.
- If code uses contact-scoped filters but permission uses Global → finding:
- **Severity:** `warning`
- **Title:** `Scope could be narrower for <table>`
@@ -406,14 +514,101 @@ Use `TaskList` to review all completed audits, then mark the "Compile audit find
---
-## Step 5: Generate Report
+## Step 5: Score the Configuration
+
+This is the **scoring overlay**. You already have the evidence: the audit issues (Step 4) and the deterministic preflight issues (Step 2.5). Now turn them into a category-organized issue set and a reproducible 1–5 score. The audit checks supply most of the detected issues; the **recurring-issue catalog** below plus the **grader severity policy** ([Appendix C](#appendix-c--severity-policy--auditgrader-bridge)) finalize `major`/`minor`; the **formula** ([Appendix A](#appendix-a--scoring-model)) decides the number. Detection and scoring are organized by **CATEGORY** (each category owns 3 dimensions — [Appendix A](#appendix-a--scoring-model) / [Appendix B](#appendix-b--the-9-dimensions)).
+
+### 5.1 Detect & label issues by category (catalog-anchored)
+
+Assess the **3 categories**; within each, reason across its 3 dimensions together. Populate each issue from three sources:
+
+1. **Preflight issues** (Step 2.5) — keep each with its **fixed id, dimension, and severity** verbatim.
+2. **Audit candidates** (Step 4, plus the Step 1 no-permissions observation) — these are factual observations, not final labels. Match each candidate against the recurring catalog first. Only unmatched candidates use the generic [Appendix C](#appendix-c--severity-policy--auditgrader-bridge) policy. Step 5 assigns every final severity and dimension exactly once.
+3. **Recurring-issue catalog + rubric judgment** — run the catalog below as a CHECKLIST, then add anything the A–K checks didn't already cover (e.g., an entirely read-only management site → an intent-coverage failure).
+
+**RECURRING ISSUE CATALOG — DETECTION + SEVERITY (the primary lever for run-to-run consistency).** Test EACH pattern against the artifacts; whenever a pattern's TRIGGER holds, raise exactly ONE issue for it in the stated dimension with the FIXED severity — on every run, no matter how obvious or minor it seems. Match on the described SHAPE, not on specific table/role names (names in parentheses are illustrations). **Patterns are evaluated PER affected table-group and are NOT mutually exclusive**: if one table hits a MAJOR pattern and a different table hits a similar MINOR pattern (e.g. C2 on a PII table AND C14 minor on a draft-content table), raise BOTH as separate issues — the ordering only resolves severity WITHIN one table-group, it never suppresses a finding on a different table.
+
+- **[C1]** Anonymous write, create, or delete — raised by the preflight `AH` row (Step 2.5); do not raise it again here.
+- **[C2]** PII / contact columns (email, phone, guardian or parent contact, address) readable by the Anonymous role → dim `anonymous-access-hygiene` · **major**.
+- **[C3]** A role has GLOBAL-scope access to a per-person / per-owner table carrying PII or sensitive operational data (personal records, contact PII, grades, rosters) — reaching every record. Mutating grant → `privilege-calibration`; read-only → `security-posture` · **major**. This explicitly includes the baseline Authenticated Users role: when open registration lets any visitor acquire that role, treat it as a broad external audience, not as trusted staff. Evaluate and emit this pattern separately for each affected table; do not merge Student and Teacher (or other disjoint table exposures) into one issue.
+- **[C4]** A role is granted access (any CRUD) beyond its natural need-to-know / need-to-act → dim `privilege-calibration` · **major** only when the extra access reaches another audience's sensitive records (PII, confidential, financial); otherwise **minor**. C4 never applies to a case covered by C3, C9, C16, C17 or C18.
+- **[C5]** The site requires authoring/management but NO role has any Create/Write/Delete on ANY table (entirely read-only) — raise ONCE for the whole site → dim `intent-coverage` · **major** *(if the authoring is expected to be performed by the intentionally-omitted `Administrators` role, do NOT raise it — see the ADMINISTRATORS EXCEPTION below)*.
+- **[C6]** A table the site clearly needs to expose (referenced by service/UI code, or an obvious end-user entity) has NO permission granting the required access → dim `table-coverage` · **major** *(if the only missing grant would be for the `Administrators` role, do NOT raise it — see the ADMINISTRATORS EXCEPTION)*.
+- **[C7]** The site needs purpose-specific personas (e.g. distinct student / teacher / staff / admin audiences) but only generic Anonymous/Authenticated roles exist → dim `role-completeness` · **major** *(a missing `Administrators` role/persona is NOT a gap — see the ADMINISTRATORS EXCEPTION)*.
+- **[C8]** A web role is defined but referenced by NO table permission (orphaned) while every persona the site needs is still served by another role → dim `role-completeness` · **minor**.
+- **[C9]** GLOBAL-scope READ of inherently-public / non-sensitive shared reference data (announcements, facilities, public faculty/leadership listings) is the correct scope → **no issue**. Record the public audience in the inventory/context, but do not lower the security score or require a fix.
+- **[C10]** A scope/permission that only matters under a HYPOTHETICAL future change ("if guardians authenticate later, a Contact or Parent scope would be better") → dim `scope-correctness` · **minor**.
+- **[C11]** No `permissions-plan.html` present, or only a generic/boilerplate plan ("Global is the broadest scope") → dim `internal-consistency` · **minor**.
+- **[C12]** A data-model table with no permission whose user-facing status is genuinely unclear — the implementation plan or data model describes it as user-facing, but no code uses it (likely a planned feature never built) → dim `table-coverage` · **minor**. Clearly backend/system tables with no permission are correct, so raise no issue.
+- **[C13]** Wildcard `*` column exposure — a Web API query with `$select=*`, or any other column list set to `*` → dim `security-posture` · **major**, one issue per affected table. A `Webapi/<table>/fields` wildcard is reported through the Step 2.4 validator finding instead. An explicitly enumerated column list is never this issue, however long.
+- **[C14]** A portal-readable table mixes allowed and restricted rows, and the only separation is a client-controlled `$filter`/query predicate. Client filtering is not an authorization boundary. If bypass exposes **sensitive or confidential content** (PII, credentials/secrets, financial/health data, internal staff or agent notes, private case details, security data) → dim `security-posture` · **major**. If bypass exposes only non-sensitive content that is merely unpublished, draft, or workflow-incomplete → dim `security-posture` · **minor**. If Dataverse permissions, column security, a server-side endpoint, or a separate protected table enforces the separation, C14 does not trigger.
+- **[C15]** A purpose-specific persona has at least one `reachable` portal capability but lacks the persona web role and the permissions needed across that capability's tables/operations → emit exactly ONE consolidated dim `role-completeness` · **major** issue. Absorb the resulting missing-table and missing-operation symptoms into it. If the persona role exists and only one table is uncovered, use C6 `table-coverage`; if the table permission exists and only an operation bit is missing, use `intent-coverage`. `disabled` code does not trigger C15. `ambiguous` code conflicting with the plan produces only the minor `internal-consistency` issue described in Step 2.3.
+- **[C16]** **Staff shared work queue** — a staff/back-office persona role (not Anonymous, not the baseline Authenticated Users role) has Global scope on a shared work-queue table (cases, tickets, requests, tasks) or its child tables. If the role's reachable pages read or update those records across owners → **no issue** (do NOT raise C3 or C4). Global write/create that no reachable staff page uses → fold into the role's C18 issue (**minor**). Global delete that no reachable staff page performs → dim `privilege-calibration` · **major**. Any mutation by Anonymous or a customer/baseline role stays C1/C3 **major**.
+- **[C17]** **Child-table parity** — a child-table permission (comments, attachments, notes, escalations) whose reach equals the same role's grant on the parent table (for example Global child under a Global parent, or Parent scope under it) → **no issue**. A child grant broader than the role's parent grant → apply C3 (**major** when the child holds sensitive content).
+- **[C18]** **Unused grants** — permissions that no reachable code uses for a role (unused tables, unused create/write/delete bits, unneeded append/appendto), including explicit Administrators permissions → emit exactly ONE issue per role, dim `privilege-calibration` · **minor**, listing every unused grant. Do not split it per table. A C16 unused delete stays a separate **major** issue.
+
+**ADMINISTRATORS EXCEPTION (respect strongly).** By design, a site should **not** create table permissions for the `Administrators` web role — admin authoring normally happens outside the portal (the model-driven app or Dataverse directly), so explicit Administrators CRUD permissions are unnecessary and add security noise. The `Administrators` web role does not bypass table permissions for portal data access. Therefore:
+- The **absence** of Administrators table permissions is CORRECT when no `reachable` site code performs the admin work — NEVER raise a missing-permission, table-coverage, role-completeness, or entirely-read-only issue *solely* because the `Administrators` role lacks table permissions. This includes an under-exposure gap (C5 read-only site, C6 missing grant, C7 missing persona) that exists only because the authoring/CRUD belongs to the intentionally-omitted `Administrators` role.
+- If `reachable` site code performs admin-only CRUD through the portal (for example a routed admin page calling the Web API) with no grant, the exception does not apply: raise C6 or C15 as for any other role.
+- This exception applies ONLY to the `Administrators` role and ONLY to under-exposure/usability gaps. It NEVER downgrades an over-exposure (security) finding — if Administrators (or any role) actually holds an over-broad grant, score it by the security rules as usual.
+
+**NOVEL ISSUES (not covered by C1–C18):** still detect them — do NOT restrict yourself to the catalog. Assign severity by the [Appendix C](#appendix-c--severity-policy--auditgrader-bridge) security-first policy. A novel issue is NOT automatically minor: if it exposes data to the wrong audience, over-scopes access, or breaks a required flow, it is **major**.
+
+Number LLM-derived issue ids per canonical dimension prefix (`IC`, `PC`, `SC`, `RC`, `TC`, `AH`, `DM`, `IS`, `SP`). Within each dimension, continue after the highest preflight id already used for that prefix (or start at 1 when there is none), so generated ids never collide with fixed preflight ids. The issue id prefix MUST match the issue's final dimension after consolidation. Record each issue as `{id, dimension, severity, title, reasoning, fix}` plus the evidence that supports it — the shape of a report finding (Step 7.2). **Do not assign a per-dimension 1–5 score** — scoring happens at the category level after consolidation.
+
+### 5.2 Consolidate to distinct root causes (major/minor)
+
+Consolidate the full pooled issue list into **distinct root causes**, then classify each into exactly ONE category by **dominant impact**. The number of issues after this step equals the number of root causes.
+
+- **Merge** issues describing the SAME underlying misconfiguration on the same table(s) for the same audience into ONE — even across dimensions/categories. Never let a broad description ("all tables Global") absorb separate per-table exposures; C3 issues stay one per affected table. Enumerate all impacts in the description; set severity to the **highest** among merged.
+- **One category per root cause — by DOMINANT IMPACT:** over-exposure = too much access (data exposed to the wrong audience, anonymous mutation, PII readable too widely, Global on per-owner data); under-exposure = too little access (missing required CRUD flow, user-facing table with no permission, missing persona/role); correctness = structural (references a table absent from the model, dangling role link, wrong/invalid scope, missing design doc). When a root cause could touch two categories, pick its WORST real-world consequence. Reassign the merged issue a `dimension` within the chosen category.
+- **Under-exposure dimension tie-breaker (first match wins):** missing persona role spanning one or more reachable capabilities → `role-completeness`; existing persona role but missing table permission → `table-coverage`; existing role and table permission but missing CRUD/append bit → `intent-coverage`. Never choose among these dimensions by prose emphasis.
+- **Plan/code conflict tie-breaker:** for `reachable` capabilities, implementation wins and the applicable C6/C7/C15 issue remains major; for `disabled` capabilities, the plan wins and no under-exposure issue is raised; for `ambiguous` capabilities, raise only the minor `internal-consistency` conflict.
+- **Do NOT merge distinct exposures on different tables.** Two exposure/PII issues on DISJOINT table sets, or with different audiences/severities, are SEPARATE root causes — keep BOTH (e.g. anonymous-PII on student/teacher tables (major) vs over-broad Global read of public announcements/facilities (minor)). Only merge on the same tables. When in doubt, keep separate. C16 and C18 are one issue per role by definition.
+- **Preserve every preflight issue** (Step 2.5) as its own standalone issue with its fixed id + severity. If an audit/rubric issue duplicates a preflight one, merge it **into** the preflight issue (keep the preflight id; severity is the higher of the two).
+- Never invent new problems; every consolidated issue traces to at least one source issue. Never downgrade a major to shrink the count.
+
+The consolidated issues are what feed scoring and all later phases. Re-bucket each under its (possibly reassigned) dimension. **This single consolidated `major`/`minor` list is the one issue set for everything downstream** — it becomes the report's `FINDINGS_DATA` (Step 7.2), the Overview's Major/Minor counts, and the input to the score. One issue set, one tally, so more issues ⇒ lower score.
+
+### 5.3 Compute scores (pure formula)
+
+Apply [Appendix A](#appendix-a--scoring-model) exactly: one 1–5 score per category from its pooled issues (no overall score), the verdict from the major count, and issue counts `{ major, minor, total }` over all consolidated issues.
+
+### 5.4 Verdict (prose)
+
+Write a **2–3 sentence** grader verdict: the top thing the config gets right, the top thing it gets wrong, and the verdict. State the verdict verbatim — **"Safe to go"** when there are **zero major** issues, **"Needs revision"** when there is **at least one major** issue. Minor issues never change it. **Do NOT tell the user whether to deploy, release, or ship** — the verdict summarises the findings; the decision is theirs. Prose only. Use it as the report's `SUMMARY` (Step 7.2).
+
+If the data-model manifest is missing (`SCORECARD_DATA` is `null`), skip the verdict: write a 2–3 sentence summary that says this is a partial audit, and use neither verdict phrase.
+
+---
+
+## Step 6: Root-cause Attribution (batched)
+
+Analyze **all MAJOR issues in a SINGLE batched pass** (after consolidation; skip minors). The site evidence is shared, so classify every major issue together in one reasoning step. For each, decide whether it is purely a permissions-design fault or is caused, wholly or partly, by an upstream artifact. Be **conservative — default to `permissions`** unless upstream evidence is clear (false upstream attribution is worse than missing one).
-### 5.1 Determine Output Location
+Root-cause values:
+- `permissions` — genuine permission-design issue; nothing upstream forces it. Fix it in the permission or web-role YAML.
+- `data-model` — the manifest is missing a table/column or uses a wrong publisher prefix.
+- `webapi-code` — site code (`src/shared/services/*`, `src/types/*`, pages) references tables/columns in a way that forces the permission shape or relies on a browser-side rule.
+- `webapi-settings` — `Webapi-*-enabled` / `-fields` YAML forces the grant (or gap).
+- `mixed` — an upstream cause AND a permissions-side mistake both contribute.
+
+For each major issue decide `rootCause` and write `explanation`; they become the finding's `rootCause` and `rootCauseReason` in Step 7.2.
+
+`explanation` is shown to the user next to the major issue, so write **one plain-language sentence** that justifies the label: for `permissions`, say why the permission configuration alone is at fault; otherwise, name the specific upstream file or setting and what it forces.
+
+---
+
+## Step 7: Generate Report
+
+### 7.1 Determine Output Location
- **If working in context of a website** (project root with `powerpages.config.json` exists): write to `<PROJECT_ROOT>/docs/permissions-audit.html`
- **Otherwise**: write to the system temp directory
-### 5.2 Prepare Data
+This folder is the `<OUTPUT_DIR>` defined in Step 2.6.
+
+### 7.2 Prepare Data
**Do NOT generate HTML manually or read/modify the template yourself.** Use the `render-audit-report.js` script which mechanically reads the template and replaces placeholder tokens with your data.
@@ -425,33 +620,43 @@ Write a temporary JSON data file (e.g., `<OUTPUT_DIR>/audit-data.json`) with the
"AUDIT_DESC": "Security audit of table permissions for Contoso Portal",
"SUMMARY": "2-3 sentence summary of the audit results",
"FINDINGS_DATA": [/* array of finding objects */],
- "INVENTORY_DATA": [/* array of current permission objects */]
+ "INVENTORY_DATA": [/* array of current permission objects */],
+ "SCORECARD_DATA": {/* grader overlay — see below; use null if scoring was skipped */}
}
```
-**FINDINGS_DATA format:**
+`SITE_NAME`, `AUDIT_DESC`, `SUMMARY`, `FINDINGS_DATA`, `INVENTORY_DATA` are the **required** keys the render script validates. `SCORECARD_DATA` is an extra key the enhanced template consumes — **always include it** (object or `null`) so no placeholder is left unreplaced. In `SCORECARD_DATA.reportPaths`, list the absolute path to the HTML report — the Overview tab renders it so the user can open the report.
+
+**FINDINGS_DATA format** — this is the single consolidated **major/minor** issue list from Step 5.2 (one entry per issue; it is exactly what the score is computed from). Use the canonical issue id from Step 5 (e.g. `AH1`). For **major** issues, copy `rootCause` and `explanation` from that issue's Step 6 entry; omit both fields for minor issues:
```json
{
- "id": "f1",
- "severity": "critical",
- "title": "Missing permission for cra5b_product",
- "table": "cra5b_product",
- "scope": null,
- "permission": null,
- "reasoning": "The table cra5b_product is referenced in src/services/productService.ts with GET requests to /_api/cra5b_products, but no table permission exists for this table.",
- "fix": "Create a table permission with Global scope and read-only access for the Anonymous Users role.",
- "details": "Referenced in: src/services/productService.ts (line 23), src/components/ProductList.tsx (line 45)"
+ "id": "AH1",
+ "severity": "major",
+ "title": "Staff email/phone readable by Anonymous",
+ "table": "contoso_staff",
+ "dimension": "anonymous-access-hygiene",
+ "scope": "Global",
+ "permission": "Staff - Public Read",
+ "reasoning": "Staff email/phone are in the $select and the Webapi field whitelist, and Staff-Public-Read grants the Anonymous role Global read — public internet can read staff PII.",
+ "fix": "Restrict staff read to a purpose-specific role assigned only to verified users, or drop contoso_email/contoso_phone from the whitelist and $select.",
+ "details": "Staff-Public-Read.tablepermission.yml; Webapi-contoso_staff-fields.sitesetting.yml; src/shared/services/staffService.ts:85",
+ "rootCause": "mixed",
+ "rootCauseReason": "The anonymous Global read grant is a permission mistake, and the Web API fields setting also whitelists contoso_email and contoso_phone."
}
```
-- `severity`: One of `critical`, `warning`, `info`, `pass`
-- `table`: The table logical name this finding relates to (or `null` for general findings)
+- `id`: The canonical issue id from Step 5 — the same id used in Step 6.
+- `severity`: **`major`** or **`minor`** — the only two tiers (never critical/warning/info/pass).
+- `table`: The table logical name this issue relates to (or `null` for general issues)
+- `dimension`: The grader dimension the issue rolls up to (via the Appendix C bridge)
- `scope`: The current scope if applicable (numeric code or friendly name), or `null`
-- `permission`: The permission name if this finding is about an existing permission, or `null`
+- `permission`: The permission name if this issue is about an existing permission, or `null`
- `reasoning`: Detailed explanation of why this is an issue — reference specific code files, line patterns, or Dataverse metadata
-- `fix`: Actionable suggestion for how to resolve the issue (or `null` for `pass` findings)
+- `fix`: Actionable suggestion for how to resolve the issue
- `details`: Additional context like file references, column names, or relationship details
+- `rootCause`: Major issues only — the Step 6 root cause (`permissions`, `mixed`, `data-model`, `webapi-code`, or `webapi-settings`)
+- `rootCauseReason`: Major issues only — the Step 6 `explanation`, one sentence justifying the root cause
**INVENTORY_DATA format:**
@@ -470,7 +675,24 @@ Write a temporary JSON data file (e.g., `<OUTPUT_DIR>/audit-data.json`) with the
}
```
-### 5.3 Render the HTML File
+**SCORECARD_DATA format** (from Step 5; the report reads only these fields):
+
+```json
+{
+ "categories": [
+ { "name": "Over-Exposure (Security)", "score": 3.10 },
+ { "name": "Under-Exposure (Usability & Coverage)", "score": 4.21 },
+ { "name": "Correctness (Validity & Alignment)", "score": 3.48 }
+ ],
+ "reportPaths": [
+ { "label": "HTML report", "path": "<PROJECT_ROOT>/docs/permissions-audit.html" }
+ ]
+}
+```
+
+The report surfaces this data automatically. The **Overview** tab leads with the **Audit Summary**, then an **Issues** row (**major** and **minor** counts — the single problem tally, which is exactly what drives the score) and a **Verdict** section (**Safe to go** / **Needs revision**, computed from the major count in `FINDINGS_DATA`, plus the per-category 1–5 score bars), plus the report paths. Every issue is **major** or **minor** — there is no critical/warning/info/pass tier anywhere in the report. The **Issues** tab lists each major/minor issue with its evidence and fix; each major issue also shows a root-cause badge (**Permissions only**, **Permissions + upstream**, or **Upstream: data model / site code / Web API settings**) and the one-sentence justification.
+
+### 7.3 Render the HTML File
Run the render script (it creates the output directory if needed):
@@ -478,52 +700,184 @@ Run the render script (it creates the output directory if needed):
node "${PLUGIN_ROOT}/scripts/render-audit-report.js" --output "<OUTPUT_PATH>" --data "<DATA_JSON_PATH>"
```
-The render script refuses to overwrite existing files. Before calling it, check if the default output path (`<PROJECT_ROOT>/docs/permissions-audit.html`) already exists. If it does, choose a new descriptive filename based on context — e.g., `permissions-audit-apr-2026.html`, `permissions-audit-post-migration.html`. Pass the chosen name via `--output`.
+The render script refuses to overwrite existing files. Before calling it, check if the default output path (`<PROJECT_ROOT>/docs/permissions-audit.html`) already exists. If it does, choose a new descriptive filename based on context — e.g., `permissions-audit-apr-2026.html`, `permissions-audit-post-migration.html`. Pass the chosen name via `--output`, and use the same path in `reportPaths`.
+
+### 7.4 Validate the report
+
+Run the semantic validator on the rendered report:
+
+```bash
+node "${PLUGIN_ROOT}/skills/audit-permissions/scripts/validate-audit.js" --report "<OUTPUT_PATH>"
+```
+
+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.
+
+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 data JSON file after the script succeeds.
+Delete the temporary `audit-data.json` and `audit-evidence.json` files after validation succeeds.
-### 5.4 Open in Browser
+### 7.5 Open in Browser
-Open the actual output path in the user's default browser.
+Open the actual HTML output path in the user's default browser.
---
-## Step 6: Present Findings & Track
+## Step 8: Present Findings & Track
-### 6.1 Record Skill Usage
+### 8.1 Record Skill Usage
> Reference: `${PLUGIN_ROOT}/references/skill-tracking-reference.md`
Follow the skill tracking instructions in the reference to record this skill's usage. Use `--skillName "AuditPermissions"`.
-### 6.2 Present Summary
+### 8.2 Present Summary
<!-- gate: audit-permissions:6.fix-offer | category=plan | cancel-leaves=nothing -->
-> 🚦 **Gate (plan · audit-permissions:6.fix-offer):** Offer to apply auto-fixes for critical/warning findings. The audit report has already been written; declining here just leaves the HTML report in place — no Dataverse / filesystem mutation.
+> 🚦 **Gate (plan · audit-permissions:6.fix-offer):** Offer to apply auto-fixes for major/minor issues. The report has already been written; declining here just leaves the HTML report in place — no Dataverse / filesystem mutation.
>
-> **Trigger:** Phase 6 has tallied findings and the HTML report is saved.
+> **Trigger:** Phase 8 has tallied findings and the report is saved.
> **Why we ask:** Tooling could silently invoke the table-permissions-architect agent — accept-by-default would write or mutate permission YAML against the user's intent.
-> **Cancel leaves:** Nothing — the audit report stays at its saved path. No web-role / table-permission files written.
+> **Cancel leaves:** Nothing — the report stays at its saved path. No web-role / table-permission files written.
Present a summary to the user:
-1. **Critical findings count** — these need immediate attention
-2. **Warning findings count** — should be addressed
-3. **Report location** — where the HTML file was saved
-4. **Ask the user** using `AskUserQuestion`: "Would you like me to fix any of these issues? I can create or update table permissions to resolve the critical and warning findings."
+1. **Verdict** — when `SCORECARD_DATA` is non-null, show **Safe to go** or **Needs revision** plus the three category scores; otherwise state that this is a partial audit and omit both verdict phrases and scores.
+2. **Major issues count** — these need immediate attention
+3. **Minor issues count** — nice-to-have / forward-looking
+4. **Report location** — where the HTML report was saved
+5. **Ask the user** using `AskUserQuestion`: "Would you like me to fix any of these issues? I can create or update table permissions to resolve the major issues."
If the user wants fixes applied:
-- **For 403 / Web API access issues** (missing table permissions, missing CRUD flags, incorrect scope, missing append/appendto, missing `$expand` read coverage — any finding that would result in a 403 Forbidden response from the Power Pages Web API): Spawn the **table-permissions-architect** agent using the `Agent` tool. Pass it a prompt that includes the specific tables, the required CRUD flags, scope recommendations, and relationship details from the audit findings. The agent will analyze the site, propose a permissions plan, and create the correct table permission YAML files after user approval. Example prompt: `"Create table permissions for the following tables based on audit findings: <table1> needs Global scope with read:true; <table2> needs Parent scope under <parent_table> with read:true, create:true, append:true; <table3> needs appendto:true for lookups from <source_table>. The site project root is <PROJECT_ROOT>."`
-- **For non-permission issues** (e.g., unused permissions, scope narrowing suggestions, informational findings): explain what manual changes are needed or suggest running `/integrate-webapi` so the Web API settings architect can address site-setting-level issues.
+- **For 403 / Web API access issues** (missing table permissions, missing CRUD flags, incorrect scope, missing append/appendto, missing `$expand` read coverage — any finding that would result in a 403 Forbidden response from the Power Pages Web API): Spawn the **table-permissions-architect** agent using the `Agent` tool. Pass it a prompt that includes the specific tables, the required CRUD flags, scope recommendations, and relationship details from the findings. The agent will analyze the site, propose a permissions plan, and create the correct table permission YAML files after user approval. Example prompt: `"Create table permissions for the following tables based on audit findings: <table1> needs Global scope with read:true; <table2> needs Parent scope under <parent_table> with read:true, create:true, append:true; <table3> needs appendto:true for lookups from <source_table>. The site project root is <PROJECT_ROOT>."`
+- **For non-permission issues** (e.g., unused permissions, scope-narrowing suggestions, other minor issues): explain what manual changes are needed or suggest running `/integrate-webapi` so the Web API settings architect can address site-setting-level issues.
+
+---
+
+## Appendix A — Scoring model
+
+Scoring is a **pure function of the consolidated issues** — reproduce it exactly.
+
+### Categories
+
+| Category | Dimensions |
+|---|---|
+| **Over-Exposure (Security)** | privilege-calibration, anonymous-access-hygiene, security-posture |
+| **Under-Exposure (Usability & Coverage)** | intent-coverage, table-coverage, role-completeness |
+| **Correctness (Validity & Alignment)** | scope-correctness, data-model-alignment, internal-consistency |
+
+### Score-from-issues formula
+
+For a set of issues, let `nMajor` and `nMinor` be the counts. Then:
+
+```
+load = 1.0 * nMajor + 0.25 * nMinor
+penalty = tanh(0.2 * load) # tanh maps [0,∞) → [0,1); penalty(0)=0
+score = 5 - 4 * penalty # 0 issues → 5.00 ; grows → 1.00
+score = round(score * 100) / 100 # 2 decimals
+```
+
+Constants: `MAJOR_LOAD = 1.0`, `MINOR_LOAD = 0.25`, `PENALTY_STEEPNESS = 0.2`.
+
+- **Category score** = `scoreFromIssues(pooled deduplicated issues of that category's dimensions)`. The category is the scoring unit — do NOT average per-dimension scores.
+- **There is no overall score.** The three category scores are reported side by side and never combined into a single number.
+
+Reference points (0.2 steepness): 0 issues → 5.00; 1 major → 4.21; 2 major → 3.48; 3 major → 2.85; 1 minor → 4.80; the first major always hurts most (diminishing returns).
+
+### Final verdict
+
+The verdict is driven by **severity**, not by any score:
+
+| Condition | Verdict | Meaning |
+|---|---|---|
+| **0 major issues** | **Safe to go** | No major issues were identified. |
+| **≥ 1 major issue** | **Needs revision** | One or more major issues were identified; review and address them. |
+
+Minor issues never change the verdict — they are still recorded and still lower their category score, but they are left to the user's judgement. State the verdict phrase verbatim in Step 5.4 and in the report.
+
+The verdict is **advisory**. It summarises what the audit found; it is not an approval or a release gate, and the decision to act on it rests with the human reviewer. Never instruct the user to deploy or not deploy.
+
+---
+
+## Appendix B — The 9 dimensions
+
+Use each dimension's definition to decide where an issue belongs. Order is canonical for output.
+
+**1. Intent Coverage** — `IC` · *Under-Exposure* — Does every authorization-relevant capability in the request map to at least one (role × table × op) grant? **Usability rule:** if the request implies managing/authoring records but NO role has ANY Create/Write/Delete on the relevant tables (read-only everywhere), that's a coverage FAILURE → a **major** issue.
+
+**2. Privilege Calibration** — `PC` · *Over-Exposure* — Per (role, table, op): is each CRUD bit right-sized — not over- or under-granted?
+
+**3. Scope Correctness** — `SC` · *Correctness* — Does scope (Global/Contact/Account/Parent/Self) match the data-ownership model? Per-user → Contact; public bulletin → Global; child records reached through a parent record → Parent; the user's own contact record → Self.
+
+**4. Role Completeness** — `RC` · *Under-Exposure* — Are all personas implied by the request present as web roles? Spurious roles? Anonymous + Authenticated correct?
+
+**5. Table Coverage (Permissions)** — `TC` · *Under-Exposure* — Every user-facing table has ≥1 permission; system/non-user-facing tables correctly excluded.
+
+**6. Anonymous Access Hygiene** — `AH` · *Over-Exposure* — Anonymous gets minimal read only where the request implies public content; no anonymous write/create/delete unless justified.
+
+**7. Data Model Alignment** — `DM` · *Correctness* — Every table referenced in a permission resolves to a real data-model table; no phantom/misnamed tables.
+
+**8. Internal Consistency** — `IS` · *Correctness* — YAML valid; every web-role GUID in a permission resolves; `permissions-plan.html` aligns with the YAML.
+
+**9. Security Posture** — `SP` · *Over-Exposure* — Overall least-privilege. No surprising broad grants on sensitive tables (Contact, system tables); no avoidable delete/write on shared records. If Web API field whitelists exist, check they don't broadly expose sensitive PII columns.
+
+---
+
+## Appendix C — Severity policy & audit↔grader bridge
+
+### Severity policy (apply rules IN ORDER; first match wins)
+
+Only two severities exist: **major** (a real problem — breaks the site or leaks data, or a genuinely sub-optimal config that should be fixed) and **minor** (cosmetic / forward-looking / nice-to-have). There is no "info" tier in the grader (audit `info` findings map to `minor`).
+
+**Default stance — SECURITY FIRST / LEAST PRIVILEGE.** Access should be granted only where the role's real-world use case requires it, scoped as narrowly as possible. Reaching or mutating records beyond that need is **over-granted → major**, even for an otherwise-"authorized" role.
+
+1. **Realized vs hypothetical.** Major = the problem is true **right now** (a flow is broken, or data is exposed to an audience that shouldn't see it). Minor = only matters under a hypothetical future change, or is cosmetic. Tell-tale minor language: "if … later", "could", "should be revisited".
+2. **Need-to-know / over-scope.** Major = a role can read/mutate records **beyond its need** — EITHER an unauthorized audience (Anonymous, or a role outside the data's intended audience) reaches it, OR an authorized role gets **Global** scope over per-owner / per-relationship data (personal records, PII, grades, rosters, guardian contact) so it reaches **every** record instead of its own subset. Especially severe for PII (email, phone, guardian contact, addresses). Minor = over-broad scope only on genuinely **public/shared reference** data (announcements, facilities, public directory). Staff roles working a shared work queue follow C16, and child tables matching their parent's reach follow C17.
+3. **Mutation vs read.** Major = an unwanted **mutating** grant (write/create/delete for a role that shouldn't have it; anonymous mutation is always major). An over-broad **read** is minor unless rule (2) makes it major. Absence of needed mutation (a management/authoring site with NO Create/Write/Delete anywhere) is a broken flow → major under rule (1).
+
+**Anchor examples.** The recurring-issue catalog (C1–C18, Step 5.1) is the primary anchor set — label any case it covers exactly as the catalog says. Two further recurring cases:
+- Global-scope read of PII-bearing internal tables by staff/teacher/admin → **major** (r2).
+- A role with **Global** scope over per-owner operational data beyond need (a teacher who can read/edit ALL students' grades, not just their own class) → **major** (r2).
+
+### Audit finding → grader dimension bridge
+
+Map each Step-4 finding into a dimension, then apply the severity policy above to set `major`/`minor`. (Audit `critical` almost always → `major`; audit `info` → `minor`; audit `warning` → apply the policy.)
+
+| Audit check / finding | Grader dimension | Typical grader severity |
+|---|---|---|
+| A. Missing permission for referenced table | intent-coverage (+ table-coverage) | major |
+| A. Unused permission (not referenced in code) | privilege-calibration (C18, one issue per role) | minor |
+| B. Permission has no web role | role-completeness | major; none for a Parent-scope child with a valid parent chain |
+| C. Global scope with write/delete | privilege-calibration / security-posture | major, except staff shared work queues (C16) and child-table parity (C17) |
+| C. Scope could be narrower | scope-correctness | major if per-owner/PII, else minor |
+| D. Missing read | intent-coverage | major |
+| E. Missing create · F. Missing write · G. Missing delete | intent-coverage | major |
+| E/F/G. Enabled-but-not-used | privilege-calibration (C18, one issue per role) | minor |
+| F. File upload but write disabled | intent-coverage | major |
+| F. Write without read | privilege-calibration | major |
+| H. Missing append · H2. Missing appendto | privilege-calibration / intent-coverage | major |
+| H. Append enabled but not needed | privilege-calibration (C18, one issue per role) | minor |
+| I. Broken parent chain | internal-consistency | major |
+| J. Missing read on `$expand` table | intent-coverage | major |
+| PII readable by anonymous | anonymous-access-hygiene / security-posture | major |
+| Schema-validator `error` / `warning` / `info` | internal-consistency (or the specific dimension) | error→major, warning→policy, info→minor |
---
## Critical Constraints
-- **Read-only analysis**: This skill only reads existing configuration and code. It does NOT modify any files unless the user explicitly asks to fix issues.
+- **Read-only analysis**: This skill only reads existing configuration and code. It does NOT modify any files unless the user explicitly asks to fix issues (Step 8). Scoring and report generation are all non-mutating.
+- **Never invent the score**: always derive it from consolidated issue counts via [Appendix A](#appendix-a--scoring-model). Same issues ⇒ same score.
+- **Preflight issues are ground truth**: carry Step-2.5 issues (id, dimension) through consolidation and scoring; never drop or downgrade them — a merged duplicate may only raise the severity.
+- **One issue per root cause**: do not split a single root cause into multiple issues; do not over-merge independent problems.
+- **Final labels happen once**: Step 4 emits factual candidates; Step 5 alone assigns final severity, dimension, and issue id.
+- **Reachability beats prose**: routed/callable portal behavior outranks contradictory plan text; explicit runtime/build exclusion outranks dormant source code; ambiguity is minor correctness, not presumed under-exposure.
+- **Client filters are not authorization**: classify bypassable restricted rows by content sensitivity — confidential/sensitive exposure is major, non-sensitive draft/workflow exposure is minor.
+- **Least privilege / security first** governs dimension severities (Appendix C) and the recurring-issue catalog (Step 5.1). A staff role is NOT entitled to every record — only its related records.
+- **Administrators need no table permissions** unless reachable site code performs admin-only CRUD: otherwise never flag their absence; see the ADMINISTRATORS EXCEPTION in Step 5.1.
- **Deterministic API calls**: Always use the Node.js scripts (`query-table-lookups.js`, `query-table-relationships.js`) for Dataverse API queries — never use inline PowerShell `Invoke-RestMethod` calls.
-- **No questions during analysis**: Autonomously gather all data, run checks, and present findings. Only ask the user at the end about fixing issues.
+- **No questions during analysis**: Autonomously gather all data, run checks, score, and present findings. Only ask the user at the end about fixing issues.
- **Security**: Never log or display auth tokens. The scripts handle token acquisition internally via `getAuthToken()`.
-- **Graceful degradation**: If Dataverse API scripts fail (exit code 1), skip API-dependent checks (H/H2 append/appendto validation, I parent chain integrity) and note in the report which checks were skipped.
+- **Graceful degradation**: If Dataverse API scripts fail (exit code 1), skip API-dependent checks (H/H2 append/appendto validation, I parent chain integrity) and note in the report which checks were skipped. If the data-model manifest is missing, still emit the audit findings; set `SCORECARD_DATA` to `null` rather than fabricating a score — the report then shows a partial-audit notice instead of a verdict and scores, and `SUMMARY` states no verdict (Step 5.4).
+- **Don't invent files or tables** not present in the inputs.
diff --git a/plugins/power-pages/skills/audit-permissions/assets/audit-report.html b/plugins/power-pages/skills/audit-permissions/assets/audit-report.html
index 51eff461b..96862525b 100644
--- a/plugins/power-pages/skills/audit-permissions/assets/audit-report.html
+++ b/plugins/power-pages/skills/audit-permissions/assets/audit-report.html
@@ -68,10 +68,21 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi
/* Severity badges */
.severity{font-size:9px;font-weight:700;padding:3px 8px;border-radius:3px;font-family:var(--mono);display:inline-block;text-transform:uppercase;letter-spacing:0.5px;}
+.sev-legend{font-size:11px;color:var(--text-dim);line-height:1.75;margin-top:10px;}
+.sev-legend b{font-weight:700;}
.severity-critical{color:var(--critical);background:var(--critical-bg);border:1px solid var(--critical-border);}
.severity-warning{color:var(--warning);background:var(--warning-bg);border:1px solid var(--warning-border);}
.severity-info{color:var(--info);background:var(--info-bg);border:1px solid var(--info-border);}
.severity-pass{color:var(--pass);background:var(--pass-bg);border:1px solid var(--pass-border);}
+.severity-major{color:var(--critical);background:var(--critical-bg);border:1px solid var(--critical-border);}
+.severity-minor{color:var(--warning);background:var(--warning-bg);border:1px solid var(--warning-border);}
+
+/* Root-cause badges */
+.rc{font-size:10px;font-weight:600;padding:2px 8px;border-radius:10px;display:inline-block;white-space:nowrap;}
+.rc-permissions{color:var(--accent);background:var(--accent-bg);border:1px solid var(--accent-border);}
+.rc-mixed{color:var(--purple);background:var(--purple-bg);border:1px solid var(--purple-border);}
+.rc-upstream{color:var(--info);background:var(--info-bg);border:1px solid var(--info-border);}
+.rootcause-block{background:var(--surface2);border-left:2px solid var(--purple);border-radius:var(--radius-sm);padding:10px 14px;margin-top:10px;font-size:12px;color:var(--text);line-height:1.7;}
/* Finding cards */
.finding-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);margin-bottom:12px;transition:box-shadow 0.2s;overflow:hidden;}
@@ -144,7 +155,7 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi
<div class="layout">
<div class="sidebar">
<button class="nav-btn active" data-tab="overview"><span class="nav-icon">&#9673;</span> Overview</button>
- <button class="nav-btn" data-tab="findings"><span class="nav-icon">&#9888;</span> Findings
+ <button class="nav-btn" data-tab="findings"><span class="nav-icon">&#9888;</span> Issues
<span class="nav-badge" id="navFindingsCount" style="background:var(--critical-bg);color:var(--critical);"></span>
</button>
<button class="nav-btn" data-tab="inventory"><span class="nav-icon">&#9638;</span> Inventory</button>
@@ -157,22 +168,50 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi
<h2>Audit Overview</h2>
<p class="section-desc">__AUDIT_DESC__</p>
+ <h3>Audit Summary</h3>
+ <div class="card" id="summaryBox" style="line-height:1.75;">__SUMMARY__</div>
+
+ <h3 style="margin-top:18px;">Issues</h3>
<div class="stats-grid">
- <div class="stat-card" style="--accent-color:var(--critical)"><div class="stat-num" style="color:var(--critical)" id="statCritical">0</div><div class="stat-label">Critical</div></div>
- <div class="stat-card"><div class="stat-num" style="color:var(--warning)" id="statWarning">0</div><div class="stat-label">Warning</div></div>
- <div class="stat-card"><div class="stat-num" style="color:var(--info)" id="statInfo">0</div><div class="stat-label">Info</div></div>
- <div class="stat-card"><div class="stat-num" style="color:var(--pass)" id="statPassed">0</div><div class="stat-label">Passed</div></div>
+ <div class="stat-card" style="--accent-color:var(--critical)"><div class="stat-num" style="color:var(--critical)" id="statMajor">0</div><div class="stat-label">Major</div></div>
+ <div class="stat-card"><div class="stat-num" style="color:var(--warning)" id="statMinor">0</div><div class="stat-label">Minor</div></div>
+ </div>
+ <div class="sev-legend">
+ <div><b style="color:var(--critical)">Major</b> &mdash; breaks a flow or exposes data to the wrong audience.</div>
+ <div><b style="color:var(--warning)">Minor</b> &mdash; cosmetic, forward-looking, or nice-to-have.</div>
</div>
- <h3>Audit Summary</h3>
- <div class="card" id="summaryBox" style="line-height:1.75;">__SUMMARY__</div>
+
+ <div id="ovScoreWrap" style="display:none;">
+ <h3>Verdict</h3>
+ <div style="margin:4px 0 2px;">
+ <span id="ovVerdict" style="font-size:30px;font-weight:800;line-height:1.2;">&mdash;</span>
+ </div>
+ <div id="ovVerdictNote" style="font-size:11px;color:var(--text-dim);margin-bottom:4px;">&nbsp;</div>
+ <h3 style="margin-top:18px;">Category Scores</h3>
+ <div class="card" id="ovCategoryBox" style="line-height:1.7;"></div>
+ </div>
+
+ <div id="ovPartialWrap" style="display:none;">
+ <h3>Verdict</h3>
+ <div class="card" style="line-height:1.7;"><strong>Partial audit:</strong> the data model was not available, so no verdict or scores were produced. The issues listed were found from the permissions, web roles, site code, and site settings.</div>
+ </div>
+
+ <div id="ovReportWrap" style="display:none;">
+ <h3>Full evaluation reports</h3>
+ <div class="card" id="ovReportBox" style="line-height:1.9;"></div>
+ </div>
</div>
<!-- FINDINGS -->
<div class="section" id="tab-findings">
- <h2>Findings</h2>
+ <h2>Issues</h2>
<p class="section-desc" id="findingsDesc"></p>
+ <div class="sev-legend" style="margin-bottom:14px;">
+ <div><b style="color:var(--critical)">Major</b> &mdash; breaks a flow or exposes data to the wrong audience.</div>
+ <div><b style="color:var(--warning)">Minor</b> &mdash; cosmetic, forward-looking, or nice-to-have.</div>
+ </div>
<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;">
<div class="filter-bar" id="filterBar" style="margin-bottom:0;"></div>
<button class="filter-btn" id="expandAllBtn" style="white-space:nowrap;">Expand All</button>
@@ -233,11 +272,14 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi
<script>
// Data populated by the audit-permissions skill
const FINDINGS = __JSON_FINDINGS_DATA__;
-// Each finding: { id, severity (critical|warning|info|pass), title, table, scope, permission, reasoning, fix, details }
+// Each finding: { id, severity (major|minor), title, table, scope, permission, reasoning, fix, details, rootCause, rootCauseReason }
const INVENTORY = __JSON_INVENTORY_DATA__;
// Each item: { name, table, scope, roles, read, create, write, delete, append, appendto }
+const SCORECARD = __JSON_SCORECARD_DATA__;
+// null when scoring was skipped, else { categories:[{name,score}], reportPaths:[{label,path}] }
+
// Tab navigation
document.querySelectorAll('.nav-btn').forEach(btn => {
btn.addEventListener('click', () => {
@@ -252,31 +294,44 @@ document.querySelectorAll('.nav-btn').forEach(btn => {
function esc(s) { if (!s) return ''; return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;'); }
function escAttr(s) { return String(s || '').replace(/[^a-zA-Z0-9_.-]/g, ''); }
const sevConfig = {
- critical: { color: 'var(--critical)', label: 'CRITICAL', icon: '\u2716' },
- warning: { color: 'var(--warning)', label: 'WARNING', icon: '\u26A0' },
- info: { color: 'var(--info)', label: 'INFO', icon: '\u2139' },
- pass: { color: 'var(--pass)', label: 'PASSED', icon: '\u2714' }
+ major: { color: 'var(--critical)', label: 'MAJOR' },
+ minor: { color: 'var(--warning)', label: 'MINOR' }
};
const scopeNames = { 756150000:'Global', 756150001:'Contact', 756150002:'Account', 756150003:'Parent', 756150004:'Self' };
function scopeName(s) { return scopeNames[s] || s; }
+// Root cause (Step 6) of each major finding.
+const rootCauseConfig = {
+ 'permissions': { label: 'Permissions only', cls: 'rc-permissions' },
+ 'mixed': { label: 'Permissions + upstream', cls: 'rc-mixed' },
+ 'data-model': { label: 'Upstream: data model', cls: 'rc-upstream' },
+ 'webapi-code': { label: 'Upstream: site code', cls: 'rc-upstream' },
+ 'webapi-settings': { label: 'Upstream: Web API settings', cls: 'rc-upstream' }
+};
+function rootCauseOf(f) {
+ const cfg = rootCauseConfig[f.rootCause];
+ return cfg ? { cfg: cfg, reason: f.rootCauseReason || '' } : null;
+}
+
// Stats
-const criticalCount = FINDINGS.filter(f => f.severity === 'critical').length;
-const warningCount = FINDINGS.filter(f => f.severity === 'warning').length;
-const infoCount = FINDINGS.filter(f => f.severity === 'info').length;
-const passCount = FINDINGS.filter(f => f.severity === 'pass').length;
-const issueCount = criticalCount + warningCount + infoCount;
-
-document.getElementById('statCritical').textContent = criticalCount;
-document.getElementById('statWarning').textContent = warningCount;
-document.getElementById('statInfo').textContent = infoCount;
-document.getElementById('statPassed').textContent = passCount;
+const majorCount = FINDINGS.filter(f => f.severity === 'major').length;
+const minorCount = FINDINGS.filter(f => f.severity === 'minor').length;
+const issueCount = majorCount + minorCount;
+
+document.getElementById('statMajor').textContent = majorCount;
+document.getElementById('statMinor').textContent = minorCount;
document.getElementById('navFindingsCount').textContent = issueCount > 0 ? issueCount : '';
document.getElementById('findingsDesc').textContent =
- FINDINGS.length + ' check' + (FINDINGS.length !== 1 ? 's' : '') +
- ' \u2014 ' + criticalCount + ' critical, ' + warningCount + ' warning, ' + infoCount + ' info, ' + passCount + ' passed.';
+ FINDINGS.length + ' issue' + (FINDINGS.length !== 1 ? 's' : '') +
+ ' \u2014 ' + majorCount + ' major, ' + minorCount + ' minor.' +
+ (function () {
+ const labelled = FINDINGS.filter(f => f.severity === 'major').map(rootCauseOf).filter(Boolean);
+ if (!labelled.length) return '';
+ const permOnly = labelled.filter(r => r.cfg === rootCauseConfig.permissions).length;
+ return ' Of the major issues, ' + permOnly + ' are permissions only and ' + (labelled.length - permOnly) + ' involve upstream artifacts.';
+ })();
document.getElementById('invDesc').textContent =
INVENTORY.length + ' table permission' + (INVENTORY.length !== 1 ? 's' : '') + ' currently configured.';
@@ -285,8 +340,8 @@ document.getElementById('invDesc').textContent =
let activeFilter = 'all';
function renderFilterBar() {
const c = document.getElementById('filterBar');
- const counts = { all: FINDINGS.length, critical: criticalCount, warning: warningCount, info: infoCount, pass: passCount };
- const labels = { all: 'All', critical: 'Critical', warning: 'Warning', info: 'Info', pass: 'Passed' };
+ const counts = { all: FINDINGS.length, major: majorCount, minor: minorCount };
+ const labels = { all: 'All', major: 'Major', minor: 'Minor' };
let html = '';
Object.entries(labels).forEach(([key, label]) => {
if (counts[key] === 0 && key !== 'all') return;
@@ -305,22 +360,25 @@ function renderFindings() {
const c = document.getElementById('findingsContainer');
const filtered = activeFilter === 'all' ? FINDINGS : FINDINGS.filter(f => f.severity === activeFilter);
- const order = { critical: 0, warning: 1, info: 2, pass: 3 };
+ const order = { major: 0, minor: 1 };
const sorted = [...filtered].sort((a, b) => (order[a.severity] ?? 99) - (order[b.severity] ?? 99));
let html = '';
sorted.forEach(f => {
- const sev = sevConfig[f.severity] || sevConfig.info;
+ const sev = sevConfig[f.severity] || sevConfig.minor;
const fid = escAttr(f.id);
const fsev = escAttr(f.severity);
+ const rc = rootCauseOf(f);
html += '<div class="finding-card" id="finding-' + fid + '">' +
'<div class="finding-header">' +
'<span class="severity severity-' + fsev + '">' + esc(sev.label) + '</span>' +
'<span class="finding-title">' + esc(f.title) + '</span>' +
+ (rc ? '<span class="rc ' + rc.cfg.cls + '">' + esc(rc.cfg.label) + '</span>' : '') +
(f.table ? '<span class="finding-table">' + esc(f.table) + '</span>' : '') +
'<span class="finding-chevron">&#9654;</span>' +
'</div>' +
'<div class="finding-body">' +
+ (rc ? '<div style="margin-top:10px;"><div class="field-label">Root cause</div><div class="rootcause-block"><span class="rc ' + rc.cfg.cls + '">' + esc(rc.cfg.label) + '</span>' + (rc.reason ? ' ' + esc(rc.reason) : '') + '</div></div>' : '') +
(f.permission ? '<div style="margin-top:10px;font-size:12px;"><span class="field-label">Permission:</span> <span style="font-weight:600;color:var(--text-bright)">' + esc(f.permission) + '</span></div>' : '') +
(f.scope ? '<div style="margin-top:6px;font-size:12px;"><span class="field-label">Scope:</span> <span class="scope-tag scope-' + escAttr(scopeName(f.scope)) + '" style="font-size:10px;padding:1px 6px;min-width:auto;">' + esc(scopeName(f.scope)) + '</span></div>' : '') +
(f.details ? '<div style="margin-top:10px;font-size:12px;color:var(--text);line-height:1.7;">' + esc(f.details) + '</div>' : '') +
@@ -331,7 +389,7 @@ function renderFindings() {
});
if (sorted.length === 0) {
- html = '<div style="text-align:center;padding:40px;color:var(--text-dim);font-size:14px;">No findings for this filter.</div>';
+ html = '<div style="text-align:center;padding:40px;color:var(--text-dim);font-size:14px;">No issues for this filter.</div>';
}
c.innerHTML = html;
}
@@ -370,6 +428,56 @@ function renderInventory() {
c.innerHTML = html;
}
+// Render grader score into the Overview tab (no separate scorecard tab)
+function renderOverviewScore() {
+ if (!SCORECARD) {
+ var partial = document.getElementById('ovPartialWrap');
+ if (partial) partial.style.display = '';
+ return;
+ }
+ var S = SCORECARD;
+
+ var ovWrap = document.getElementById('ovScoreWrap');
+ if (ovWrap) ovWrap.style.display = '';
+ var set = function(id, val){ var el = document.getElementById(id); if (el) el.textContent = val; };
+ // Reuses the Major tally from FINDINGS so the verdict can never contradict the Issues row.
+ var safe = majorCount === 0;
+ var vEl = document.getElementById('ovVerdict');
+ if (vEl) {
+ vEl.textContent = safe ? 'Safe to go' : 'Needs revision';
+ vEl.style.color = safe ? 'var(--pass)' : 'var(--critical)';
+ }
+ set('ovVerdictNote', safe
+ ? 'No major issues identified.'
+ : majorCount + ' major issue' + (majorCount === 1 ? '' : 's') + ' identified.');
+
+ var catHtml = (S.categories || []).map(function(c){
+ var pct = Math.max(0, Math.min(100, ((c.score||0)/5)*100));
+ return '<div style="margin-bottom:12px;">' +
+ '<div style="display:flex;justify-content:space-between;font-size:13px;margin-bottom:4px;">' +
+ '<span style="color:var(--text-bright);font-weight:600;">' + esc(c.name) + '</span>' +
+ '<span style="font-family:var(--mono);color:var(--accent);">' + (typeof c.score==='number'?c.score.toFixed(2):esc(c.score)) + ' / 5.00</span>' +
+ '</div>' +
+ '<div style="height:8px;background:var(--accent-bg);border-radius:4px;overflow:hidden;"><div style="height:100%;width:' + pct + '%;background:var(--accent);"></div></div>' +
+ '</div>';
+ }).join('') || '<div style="color:var(--text-dim);">No category data.</div>';
+ var cbox = document.getElementById('ovCategoryBox'); if (cbox) cbox.innerHTML = catHtml;
+
+ // Full evaluation report paths
+ var paths = (Array.isArray(S.reportPaths) ? S.reportPaths : []).filter(function(p){
+ return p && typeof p.path === 'string' && p.path;
+ });
+ var rWrap = document.getElementById('ovReportWrap');
+ var rBox = document.getElementById('ovReportBox');
+ if (paths.length && rBox) {
+ if (rWrap) rWrap.style.display = '';
+ rBox.innerHTML = paths.map(function(p){
+ return '<div><span style="color:var(--text-dim);font-size:12px;">' + esc(p.label || 'Report') + ':</span> ' +
+ '<code style="font-size:12px;color:var(--accent);background:var(--accent-bg);padding:1px 6px;border-radius:3px;border:1px solid var(--accent-border);word-break:break-all;">' + esc(p.path || '') + '</code></div>';
+ }).join('');
+ }
+}
+
document.getElementById('expandAllBtn').addEventListener('click', toggleExpandAll);
// Event delegation — no inline onclick handlers
@@ -384,6 +492,7 @@ document.addEventListener('click', function(e) {
renderFilterBar();
renderFindings();
renderInventory();
+renderOverviewScore();
</script>
<footer style="position:fixed;bottom:0;left:0;right:0;text-align:center;padding:10px;font-size:12px;color:#605e5c;border-top:1px solid #c8c6c4;background:#ffffff;z-index:100;">AI-generated content may be incorrect</footer>
</body>
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 732c8cbe8..e66bbc336 100644
--- a/plugins/power-pages/skills/audit-permissions/scripts/validate-audit.js
+++ b/plugins/power-pages/skills/audit-permissions/scripts/validate-audit.js
@@ -1,33 +1,177 @@
#!/usr/bin/env node
-// Validates that the permissions audit report was generated.
-// Runs as a PostToolUse(Skill) hook to verify the skill produced output.
-
const fs = require('fs');
const path = require('path');
-const { approve, block, runValidation, findPath, findProjectRoot } = require('../../../scripts/lib/validation-helpers');
-
-runValidation((cwd) => {
- const projectRoot = findProjectRoot(cwd);
- if (!projectRoot) approve(); // Not a Power Pages project — not an audit session
-
- // Check if audit report was generated in docs/
- const docsReport = path.join(projectRoot, 'docs', 'permissions-audit.html');
- if (fs.existsSync(docsReport)) {
- const content = fs.readFileSync(docsReport, 'utf8');
- if (content.includes('__FINDINGS_DATA__') || content.includes('__INVENTORY_DATA__')) {
- block('Audit report has unreplaced placeholders — data was not populated.');
+const { approve, runValidation } = require('../../../scripts/lib/validation-helpers');
+
+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}.`);
}
- approve();
}
+}
- // Check temp directory as fallback
- const tempDir = process.env.TEMP || process.env.TMP || '/tmp';
- const tempReport = path.join(tempDir, 'permissions-audit.html');
- if (fs.existsSync(tempReport)) {
- approve();
+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}.`);
+ }
+ });
+}
- // No report found — this may not be an audit session, so don't block
- approve();
-});
+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) };
+}
+
+function fail(error) {
+ const message = error instanceof Error ? error.message : String(error);
+ process.stderr.write(`Audit validation failed: ${message}\n`);
+ process.exit(1);
+}
+
+const reportFlagIndex = process.argv.indexOf('--report');
+const positionalReport = process.argv.slice(2).find((argument) => !argument.startsWith('-'));
+if (reportFlagIndex >= 0 && (!process.argv[reportFlagIndex + 1] || process.argv[reportFlagIndex + 1].startsWith('-'))) {
+ fail(new Error('Usage: validate-audit.js --report <path>'));
+}
+const explicitReport = reportFlagIndex >= 0 ? process.argv[reportFlagIndex + 1] : positionalReport;
+
+if (explicitReport) {
+ try {
+ const reportPath = path.resolve(explicitReport);
+ const summary = validateReport(reportPath);
+ process.stdout.write(`${JSON.stringify({ valid: true, reportPath, ...summary })}\n`);
+ } catch (error) {
+ fail(error);
+ }
+} else {
+ // The PostToolUse(Skill) hook fires before the audit writes its report, so it can only see a previous run; Step 7.4 validates the new report.
+ runValidation(() => approve());
+}