@cclabsnz/sf-audit 1.17.0 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/PERMISSIONS.md +139 -0
  3. package/README.md +4 -2
  4. package/docs/permissionset/SF_Audit_ReadOnly.permissionset-meta.xml +54 -0
  5. package/lib/chains/ChainEngine.js +11 -1
  6. package/lib/chains/namedChains.js +42 -24
  7. package/lib/checks/CheckEngine.js +55 -24
  8. package/lib/checks/impl/AgentUserPrivilegeCheck.js +5 -4
  9. package/lib/checks/impl/AnonymousApexAuditCheck.js +41 -8
  10. package/lib/checks/impl/ApexSharingCheck.js +3 -1
  11. package/lib/checks/impl/ApiClientPermissionCheck.js +21 -5
  12. package/lib/checks/impl/AuditTrailCheck.js +23 -8
  13. package/lib/checks/impl/CertificateExpiryCheck.js +2 -1
  14. package/lib/checks/impl/ConnectedAppScopeCheck.js +61 -5
  15. package/lib/checks/impl/ConnectedAppsCheck.js +13 -4
  16. package/lib/checks/impl/ContentLinksCheck.js +33 -9
  17. package/lib/checks/impl/CorsAllowlistCheck.js +3 -2
  18. package/lib/checks/impl/DataClassificationCheck.js +15 -13
  19. package/lib/checks/impl/DebugLogAccessCheck.js +4 -4
  20. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.js +3 -2
  21. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.js +8 -1
  22. package/lib/checks/impl/DeploymentIdentityCheck.js +32 -5
  23. package/lib/checks/impl/EmailSecurityCheck.d.ts +1 -1
  24. package/lib/checks/impl/EmailSecurityCheck.js +14 -34
  25. package/lib/checks/impl/EncryptionCoverageCheck.js +21 -15
  26. package/lib/checks/impl/EnhancedDomainsCheck.js +17 -2
  27. package/lib/checks/impl/EscalationPermsCheck.d.ts +2 -0
  28. package/lib/checks/impl/EscalationPermsCheck.js +88 -21
  29. package/lib/checks/impl/ExperienceCloudSiteCheck.js +56 -5
  30. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.js +7 -15
  31. package/lib/checks/impl/ExternalCredentialsCheck.js +6 -3
  32. package/lib/checks/impl/FailedLoginCheck.js +36 -9
  33. package/lib/checks/impl/FieldHistoryTrackingCheck.js +14 -11
  34. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.js +2 -2
  35. package/lib/checks/impl/GuestRecordAccessPolicyCheck.js +52 -11
  36. package/lib/checks/impl/HealthCheckCheck.js +1 -0
  37. package/lib/checks/impl/HighAssuranceSessionCheck.js +16 -11
  38. package/lib/checks/impl/InactiveUsersCheck.js +1 -1
  39. package/lib/checks/impl/InboundEmailHandlerExposureCheck.js +5 -5
  40. package/lib/checks/impl/IntegrationLeastPrivilegeCheck.js +7 -6
  41. package/lib/checks/impl/InternalUserMfaCheck.js +26 -8
  42. package/lib/checks/impl/IpRestrictionsCheck.js +35 -16
  43. package/lib/checks/impl/LoginAccessPolicyCheck.js +5 -4
  44. package/lib/checks/impl/LoginAnomalyCheck.js +10 -7
  45. package/lib/checks/impl/LoginSessionCheck.js +2 -0
  46. package/lib/checks/impl/MfaEnforcementCheck.js +23 -6
  47. package/lib/checks/impl/MfaMethodStrengthCheck.js +18 -3
  48. package/lib/checks/impl/MfaRegistrationCheck.js +4 -3
  49. package/lib/checks/impl/MyDomainLoginPolicyCheck.js +23 -10
  50. package/lib/checks/impl/OutboundMessagesCheck.js +48 -6
  51. package/lib/checks/impl/PlatformEventSubscriberContextCheck.js +5 -1
  52. package/lib/checks/impl/PrivilegedAccessCheck.js +12 -5
  53. package/lib/checks/impl/ReleaseUpdatesCheck.js +18 -3
  54. package/lib/checks/impl/RemoteSitesCheck.js +4 -4
  55. package/lib/checks/impl/RestrictionRulesIntegrityCheck.js +3 -3
  56. package/lib/checks/impl/SeparationOfDutiesCheck.js +14 -3
  57. package/lib/checks/impl/SoapLoginApiAuthCheck.js +20 -8
  58. package/lib/checks/impl/SsoEnforcementCheck.js +16 -5
  59. package/lib/checks/impl/TransactionSecurityPolicyCheck.js +5 -5
  60. package/lib/checks/impl/TrustedIPRangesCheck.js +18 -9
  61. package/lib/checks/impl/UsersAndAdminsCheck.js +24 -4
  62. package/lib/checks/permCatalog.js +1 -1
  63. package/lib/checks/support/missingObject.js +3 -1
  64. package/lib/checks/support/schema.d.ts +17 -0
  65. package/lib/checks/support/schema.js +41 -0
  66. package/lib/commands/audit/apps.js +3 -1
  67. package/lib/commands/audit/events/pull.js +3 -1
  68. package/lib/commands/audit/incident/collect.js +3 -1
  69. package/lib/commands/audit/security.js +9 -3
  70. package/lib/findings/AuditResult.d.ts +2 -0
  71. package/lib/findings/coverage.d.ts +6 -0
  72. package/lib/findings/coverage.js +12 -0
  73. package/lib/findings/scoring.js +51 -9
  74. package/lib/preflight/permissionMap.d.ts +2 -20
  75. package/lib/preflight/permissionMap.js +2 -43
  76. package/lib/preflight/permissions.d.ts +25 -0
  77. package/lib/preflight/permissions.js +50 -0
  78. package/lib/renderers/ClientReportRenderer.js +3 -3
  79. package/lib/renderers/HtmlRenderer.js +6 -2
  80. package/lib/renderers/MarkdownRenderer.js +6 -3
  81. package/lib/report/RemediationRoadmap.d.ts +5 -1
  82. package/lib/report/RemediationRoadmap.js +6 -2
  83. package/package.json +4 -2
@@ -10,7 +10,9 @@ import { isApiError } from '@cclabsnz/sf-core';
10
10
  */
11
11
  export function isMissingObjectError(err) {
12
12
  if (isApiError(err)) {
13
- if (/INVALID_TYPE|NOT_FOUND|MALFORMED_QUERY/i.test(err.errorCode))
13
+ // MALFORMED_QUERY is a bug in the query, never an absent feature: treating it as "no rows"
14
+ // would report an unchecked area as clean.
15
+ if (/INVALID_TYPE|NOT_FOUND/i.test(err.errorCode))
14
16
  return true;
15
17
  if (err.statusCode === 404)
16
18
  return true;
@@ -0,0 +1,17 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ /**
3
+ * Which fields an object has in this org, by describe (a GET, so read-only).
4
+ *
5
+ * Use it before querying a field that only some editions, licences or releases carry, such as a
6
+ * permission like PermissionsManageEventLogFiles. Querying an absent field fails the whole query;
7
+ * describing first lets a check say "not available in this org" instead of failing, and never
8
+ * lets the absence read as a pass.
9
+ */
10
+ export type Api = 'soql' | 'tooling';
11
+ /** The object's field names, or null when this API does not serve the object in this org. */
12
+ export declare function fieldsOf(ctx: AuditContext, object: string, api?: Api): Promise<ReadonlySet<string> | null>;
13
+ /** The subset of `wanted` the object has, in the order given. Empty when the object is absent. */
14
+ export declare function presentFields(ctx: AuditContext, object: string, wanted: readonly string[], api?: Api): Promise<string[]>;
15
+ /** True when the object has the field. */
16
+ export declare function hasField(ctx: AuditContext, object: string, field: string, api?: Api): Promise<boolean>;
17
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1,41 @@
1
+ import { isApiError } from '@cclabsnz/sf-core';
2
+ const cache = new WeakMap();
3
+ function isNotFound(err) {
4
+ if (isApiError(err) && (err.statusCode === 404 || /NOT_FOUND|INVALID_TYPE/i.test(err.errorCode)))
5
+ return true;
6
+ const msg = err instanceof Error ? err.message : String(err);
7
+ return /NOT_FOUND|requested resource does not exist|is not supported/i.test(msg);
8
+ }
9
+ /** The object's field names, or null when this API does not serve the object in this org. */
10
+ export function fieldsOf(ctx, object, api = 'soql') {
11
+ let perCtx = cache.get(ctx);
12
+ if (!perCtx) {
13
+ perCtx = new Map();
14
+ cache.set(ctx, perCtx);
15
+ }
16
+ const key = `${api}:${object}`;
17
+ let pending = perCtx.get(key);
18
+ if (!pending) {
19
+ const path = api === 'tooling' ? `/tooling/sobjects/${object}/describe` : `/sobjects/${object}/describe`;
20
+ pending = ctx.rest
21
+ .get(path)
22
+ .then((d) => new Set((d.fields ?? []).map((f) => f.name)))
23
+ .catch((err) => {
24
+ if (isNotFound(err))
25
+ return null;
26
+ throw err;
27
+ });
28
+ perCtx.set(key, pending);
29
+ }
30
+ return pending;
31
+ }
32
+ /** The subset of `wanted` the object has, in the order given. Empty when the object is absent. */
33
+ export async function presentFields(ctx, object, wanted, api = 'soql') {
34
+ const fields = await fieldsOf(ctx, object, api);
35
+ return fields ? wanted.filter((f) => fields.has(f)) : [];
36
+ }
37
+ /** True when the object has the field. */
38
+ export async function hasField(ctx, object, field, api = 'soql') {
39
+ return (await fieldsOf(ctx, object, api))?.has(field) ?? false;
40
+ }
41
+ //# sourceMappingURL=schema.js.map
@@ -31,7 +31,9 @@ export default class AuditAppsCommand extends SfCommand {
31
31
  };
32
32
  async run() {
33
33
  const { flags } = await this.parse(AuditAppsCommand);
34
- const conn = flags['target-org'].getConnection('62.0');
34
+ // No pinned version: the org's own API version, so fields and objects added since an
35
+ // older release are visible. A pin at 62.0 hid every newer permission field.
36
+ const conn = flags['target-org'].getConnection();
35
37
  const orgInfo = await resolveOrgInfo(conn);
36
38
  const ctx = buildAuditContext(conn, orgInfo);
37
39
  let restApiCsv = '';
@@ -35,7 +35,9 @@ export default class AuditEventsPullCommand extends SfCommand {
35
35
  };
36
36
  async run() {
37
37
  const { flags } = await this.parse(AuditEventsPullCommand);
38
- const conn = flags['target-org'].getConnection('62.0');
38
+ // No pinned version: the org's own API version, so fields and objects added since an
39
+ // older release are visible. A pin at 62.0 hid every newer permission field.
40
+ const conn = flags['target-org'].getConnection();
39
41
  const orgInfo = await resolveOrgInfo(conn);
40
42
  const ctx = buildAuditContext(conn, orgInfo);
41
43
  const store = new EventBaselineStore(flags.output);
@@ -23,7 +23,9 @@ export default class AuditIncidentCollectCommand extends SfCommand {
23
23
  };
24
24
  async run() {
25
25
  const { flags } = await this.parse(AuditIncidentCollectCommand);
26
- const conn = flags['target-org'].getConnection('62.0');
26
+ // No pinned version: the org's own API version, so fields and objects added since an
27
+ // older release are visible. A pin at 62.0 hid every newer permission field.
28
+ const conn = flags['target-org'].getConnection();
27
29
  const orgInfo = await resolveOrgInfo(conn);
28
30
  const ctx = buildAuditContext(conn, orgInfo);
29
31
  const dir = flags.output ?? path.join(defaultIncidentRoot(), orgInfo.id, new Date().toISOString().replace(/[:.]/g, '-'));
@@ -17,7 +17,7 @@ import { isCiEnvironment, shouldArchiveHistory } from '../../history/archivePoli
17
17
  import { EXIT_FINDINGS, EXIT_INCONCLUSIVE, resolveExitCode, violationsFor } from '../../findings/exitCode.js';
18
18
  import { buildDigest } from '../../findings/digest.js';
19
19
  import { WaiverLoader, DEFAULT_WAIVER_FILE } from '../../waivers/WaiverLoader.js';
20
- import { coverageSummary } from '../../findings/coverage.js';
20
+ import { coverageSummary, coverageAdvice } from '../../findings/coverage.js';
21
21
  const RENDERERS = {
22
22
  html: new HtmlRenderer(),
23
23
  md: new MarkdownRenderer(),
@@ -107,7 +107,9 @@ export default class SecurityAuditCommand extends SfCommand {
107
107
  // no report after the (potentially long) run completes.
108
108
  const checksToRun = this.resolveChecks(flags.checks);
109
109
  const formats = this.resolveFormats(flags.format);
110
- const conn = flags['target-org'].getConnection('62.0');
110
+ // No pinned version: the org's own API version, so fields and objects added since an
111
+ // older release are visible. A pin at 62.0 hid every newer permission field.
112
+ const conn = flags['target-org'].getConnection();
111
113
  const orgInfo = await resolveOrgInfo(conn);
112
114
  const ctx = buildAuditContext(conn, orgInfo, {
113
115
  resolveDomains: flags['resolve-domains'],
@@ -215,10 +217,14 @@ export default class SecurityAuditCommand extends SfCommand {
215
217
  }
216
218
  this.log('─────────────────────────────');
217
219
  this.log(` Score: ${result.healthScore}/100 Grade: ${result.grade}`);
220
+ if (result.gradeReason)
221
+ this.log(` Why: ${result.gradeReason}`);
218
222
  if (result.coverage) {
219
223
  this.log(` ${coverageSummary(result.coverage)}`);
220
- if (result.coverage.notAssessed.length > 0)
224
+ if (result.coverage.notAssessed.length > 0) {
221
225
  this.log(` Not assessed: ${result.coverage.notAssessed.join(', ')}`);
226
+ this.log(` ${coverageAdvice(result.coverage)}`);
227
+ }
222
228
  }
223
229
  if (result.waivedFindings && result.waivedFindings.length > 0) {
224
230
  this.log('─────────────────────────────');
@@ -14,6 +14,8 @@ export interface AuditResult {
14
14
  metrics: OrgMetrics;
15
15
  healthScore: number;
16
16
  grade: 'A' | 'B' | 'C' | 'D' | 'F';
17
+ /** What set the grade, e.g. "F: 2 CRITICAL findings (D allows none)". Absent on results stored by older versions. */
18
+ gradeReason?: string;
17
19
  attackChains?: AttackChain[];
18
20
  /** Findings covered by an approved waiver, also present in `findings` with `waived: true`. */
19
21
  waivedFindings?: Finding[];
@@ -25,4 +25,10 @@ export declare function evidenceCoverage(findings: readonly Finding[]): Evidence
25
25
  export declare function coverageSummary(coverage: EvidenceCoverage & {
26
26
  gradeCapped?: boolean;
27
27
  }): string;
28
+ /**
29
+ * What a reader should do about unassessed checks, or '' when every check gathered evidence.
30
+ * Inconclusive is not one cause: each finding quotes what the org said, and only an access
31
+ * error is fixed by granting permissions.
32
+ */
33
+ export declare function coverageAdvice(coverage: EvidenceCoverage): string;
28
34
  //# sourceMappingURL=coverage.d.ts.map
@@ -27,4 +27,16 @@ export function coverageSummary(coverage) {
27
27
  const base = `Evidence coverage ${coverage.percent}% (${coverage.checksAssessed} of ${coverage.checksRun} checks)`;
28
28
  return coverage.gradeCapped ? `${base}; grade capped at B, below the ${MIN_COVERAGE_FOR_A}% needed for an A` : base;
29
29
  }
30
+ /**
31
+ * What a reader should do about unassessed checks, or '' when every check gathered evidence.
32
+ * Inconclusive is not one cause: each finding quotes what the org said, and only an access
33
+ * error is fixed by granting permissions.
34
+ */
35
+ export function coverageAdvice(coverage) {
36
+ if (coverage.notAssessed.length === 0)
37
+ return '';
38
+ return ('Each unassessed check has an inconclusive finding quoting what the org returned. Where the cause is access, ' +
39
+ '`sf audit preflight` lists the permissions the audit user is missing, and PERMISSIONS.md ' +
40
+ '(https://github.com/cclabsnz/sf-audit-plugin/blob/main/PERMISSIONS.md) has the read-only permission set to assign.');
41
+ }
30
42
  //# sourceMappingURL=coverage.js.map
@@ -12,24 +12,63 @@ function meetsConditions(conditions, healthScore, criticalCount, highCount, medi
12
12
  return false;
13
13
  return true;
14
14
  }
15
+ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
16
+ /**
17
+ * Why the audit got this grade: the first condition of the next better grade it failed, or, for
18
+ * an A, that it met every condition. Thresholds come from the scoring config, so custom ones are
19
+ * explained in their own terms.
20
+ */
21
+ function explainGrade(grade, config, healthScore, counts, gradeCapped, coveragePercent) {
22
+ if (gradeCapped) {
23
+ return `B: evidence coverage ${coveragePercent}% is below the ${MIN_COVERAGE_FOR_A}% needed for an A`;
24
+ }
25
+ const order = ['A', 'B', 'C', 'D', 'F'];
26
+ const better = order[order.indexOf(grade) - 1];
27
+ if (!better)
28
+ return `A: health score ${healthScore}/100 with no condition for a higher grade unmet`;
29
+ const t = config.gradeThresholds[better];
30
+ // "3 CRITICAL findings", or "5 CRITICAL (3 findings, 2 attack chains)" when chains count too.
31
+ const what = (n, level) => {
32
+ const c = counts.chains[level];
33
+ return c === 0 ? plural(n, `${level} finding`) : `${n} ${level} (${plural(n - c, 'finding')}, ${plural(c, 'attack chain')})`;
34
+ };
35
+ const allows = (max) => (max === 0 ? 'none' : `at most ${max}`);
36
+ if (t.maxCritical !== undefined && counts.criticalCount > t.maxCritical) {
37
+ return `${grade}: ${what(counts.criticalCount, 'CRITICAL')} (${better} allows ${allows(t.maxCritical)})`;
38
+ }
39
+ if (t.maxHigh !== undefined && counts.highCount > t.maxHigh) {
40
+ return `${grade}: ${what(counts.highCount, 'HIGH')} (${better} allows ${allows(t.maxHigh)})`;
41
+ }
42
+ if (t.maxMedium !== undefined && counts.mediumCount > t.maxMedium) {
43
+ return `${grade}: ${what(counts.mediumCount, 'MEDIUM')} (${better} allows ${allows(t.maxMedium)})`;
44
+ }
45
+ if (t.minScore !== undefined && healthScore < t.minScore) {
46
+ return `${grade}: health score ${healthScore}/100 (${better} needs ${t.minScore})`;
47
+ }
48
+ return `${grade}: did not meet the conditions for ${better}`;
49
+ }
15
50
  export function buildAuditResult(ctx, findings, metrics, config = DEFAULT_SCORING_CONFIG, attackChains = []) {
16
51
  // Passed, inconclusive and waived findings carry no penalty — exclude from numerator.
17
- // They remain in maxPossible so a broad passing audit still dilutes real failures.
52
+ // Passed findings remain in maxPossible so a broad passing audit still dilutes real failures.
53
+ // Unassessed ones do not: a check that gathered no evidence must not improve the score.
54
+ const unassessed = (f) => Boolean(f.inconclusive || f.notAssessed);
18
55
  const totalScore = findings.reduce((sum, f) => {
19
- if (f.passed || f.inconclusive || f.waived)
56
+ if (f.passed || f.waived || unassessed(f))
20
57
  return sum;
21
58
  return sum + (f.checkId !== undefined ? (config.checkWeights[f.checkId] ?? config.riskScores[f.riskLevel]) : config.riskScores[f.riskLevel]);
22
59
  }, 0);
23
60
  const chainScore = attackChains.reduce((sum, c) => sum + config.riskScores[c.severity], 0);
24
61
  const totalWithChains = totalScore + chainScore;
25
- const maxPossible = (findings.length + attackChains.length) * 10;
62
+ const maxPossible = (findings.filter((f) => !unassessed(f)).length + attackChains.length) * 10;
26
63
  const healthScore = Math.max(0, 100 - Math.round((totalWithChains / Math.max(maxPossible, 1)) * 100));
27
- const chainCrit = attackChains.filter((c) => c.severity === 'CRITICAL').length;
28
- const chainHigh = attackChains.filter((c) => c.severity === 'HIGH').length;
29
- const chainMed = attackChains.filter((c) => c.severity === 'MEDIUM').length;
30
- const criticalCount = findings.filter((f) => f.riskLevel === 'CRITICAL' && !f.waived).length + chainCrit;
31
- const highCount = findings.filter((f) => f.riskLevel === 'HIGH' && !f.waived).length + chainHigh;
32
- const mediumCount = findings.filter((f) => f.riskLevel === 'MEDIUM' && !f.waived).length + chainMed;
64
+ // Only open findings and named chains set the grade. A potential chain is inferred from
65
+ // capability overlap, not matched to a known attack, so it is reported but does not grade.
66
+ const named = attackChains.filter((c) => c.confidence !== 'potential');
67
+ const open = findings.filter((f) => !f.waived && !f.passed && !unassessed(f));
68
+ const count = (level) => open.filter((f) => f.riskLevel === level).length + named.filter((c) => c.severity === level).length;
69
+ const criticalCount = count('CRITICAL');
70
+ const highCount = count('HIGH');
71
+ const mediumCount = count('MEDIUM');
33
72
  const grades = ['A', 'B', 'C', 'D'];
34
73
  let grade = 'F';
35
74
  for (const g of grades) {
@@ -44,6 +83,8 @@ export function buildAuditResult(ctx, findings, metrics, config = DEFAULT_SCORIN
44
83
  const gradeCapped = grade === 'A' && coverage.percent < MIN_COVERAGE_FOR_A;
45
84
  if (gradeCapped)
46
85
  grade = 'B';
86
+ const chainCount = (level) => named.filter((c) => c.severity === level).length;
87
+ const gradeReason = explainGrade(grade, config, healthScore, { criticalCount, highCount, mediumCount, chains: { CRITICAL: chainCount('CRITICAL'), HIGH: chainCount('HIGH'), MEDIUM: chainCount('MEDIUM') } }, gradeCapped, coverage.percent);
47
88
  return {
48
89
  generatedAt: new Date(),
49
90
  orgId: ctx.orgInfo.id,
@@ -56,6 +97,7 @@ export function buildAuditResult(ctx, findings, metrics, config = DEFAULT_SCORIN
56
97
  metrics: { ...EMPTY_METRICS, ...metrics },
57
98
  healthScore,
58
99
  grade,
100
+ gradeReason,
59
101
  attackChains,
60
102
  waivedFindings: waivedFindings.length > 0 ? waivedFindings : undefined,
61
103
  coverage: { ...coverage, gradeCapped },
@@ -1,24 +1,6 @@
1
- import type { AuditCache } from '@cclabsnz/sf-core';
2
1
  import type { SecurityCheck } from '../checks/SecurityCheck.js';
3
- export type AuditPermission = 'ApiEnabled' | 'ViewSetup' | 'ViewAllUsers' | 'ViewHealthCheckScreen' | 'AuthorApex' | 'ViewEventLogFiles';
4
- export interface PermissionSpec {
5
- /** Field on UserPermissionAccess carrying the effective grant. */
6
- readonly field: string;
7
- readonly label: string;
8
- /** What the audit loses without it. */
9
- readonly impact: string;
10
- /**
11
- * Cache keys whose producers and consumers need this permission. The affected
12
- * check list is derived from the registry via these keys rather than hand-written,
13
- * so a check added later is covered without touching this file.
14
- *
15
- * Empty for permissions too broad to attribute to specific checks.
16
- */
17
- readonly cacheKeys: ReadonlyArray<keyof AuditCache>;
18
- /** The audit cannot run at all without this. */
19
- readonly blocking?: boolean;
20
- }
21
- export declare const AUDIT_PERMISSIONS: Readonly<Record<AuditPermission, PermissionSpec>>;
2
+ export { AUDIT_PERMISSIONS, type AuditPermission, type PermissionSpec } from './permissions.js';
3
+ import { type AuditPermission } from './permissions.js';
22
4
  export interface MissingPermission {
23
5
  permission: AuditPermission;
24
6
  label: string;
@@ -1,47 +1,6 @@
1
1
  import { CHECKS } from '../checks/registry.js';
2
- export const AUDIT_PERMISSIONS = {
3
- ApiEnabled: {
4
- field: 'PermissionsApiEnabled',
5
- label: 'API Enabled',
6
- impact: 'All access is via SOQL/Tooling/REST. Without it the audit cannot run at all.',
7
- cacheKeys: [],
8
- blocking: true,
9
- },
10
- ViewSetup: {
11
- field: 'PermissionsViewSetup',
12
- label: 'View Setup and Configuration',
13
- impact: 'Reads the bulk of the surface — connected apps, remote sites, CSP, named credentials, auth config, ' +
14
- 'Experience sites, and Tooling metadata. Most setup and configuration checks return inconclusive without it.',
15
- cacheKeys: [],
16
- },
17
- ViewAllUsers: {
18
- field: 'PermissionsViewAllUsers',
19
- label: 'View All Users',
20
- impact: 'Enumerates every User, PermissionSetAssignment and TwoFactorInfo org-wide. Without it the user, ' +
21
- 'admin and MFA checks under-count and miss accounts outside the role hierarchy.',
22
- cacheKeys: ['mfaRegistrations', 'effectivePermissions'],
23
- },
24
- ViewHealthCheckScreen: {
25
- field: 'PermissionsViewHealthCheck',
26
- label: 'View Health Check',
27
- impact: 'Reads SecurityHealthCheck and its risks. Health Check and password/session baselines are inconclusive without it.',
28
- cacheKeys: ['healthCheckRisks'],
29
- },
30
- AuthorApex: {
31
- field: 'PermissionsAuthorApex',
32
- label: 'Author Apex (read-only use)',
33
- impact: 'The only standard gate exposing ApexClass/ApexTrigger/ApexPage Body via the Tooling API. ' +
34
- 'Grants no ability to modify org data. The code-security checks are inconclusive without it.',
35
- cacheKeys: ['apexBodies', 'vfPageBodies'],
36
- },
37
- ViewEventLogFiles: {
38
- field: 'PermissionsViewEventLogFiles',
39
- label: 'View Event Log Files',
40
- impact: 'Reads EventLogFile. Whether login and API activity is monitored cannot be established without it.',
41
- cacheKeys: ['eventLogSummary'],
42
- },
43
- };
44
- const usesKey = (check, key) => (check.dependsOnCache?.includes(key) ?? false) || (check.populatesCache?.includes(key) ?? false);
2
+ export { AUDIT_PERMISSIONS } from './permissions.js';
3
+ import { AUDIT_PERMISSIONS, usesKey } from './permissions.js';
45
4
  /** Check ids that need `permission`, derived from the registry's declared cache wiring. */
46
5
  export function checksRequiring(permission, checks = CHECKS) {
47
6
  const { cacheKeys } = AUDIT_PERMISSIONS[permission];
@@ -0,0 +1,25 @@
1
+ import type { AuditCache } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck } from '../checks/SecurityCheck.js';
3
+ export type AuditPermission = 'ApiEnabled' | 'ViewSetup' | 'ViewAllUsers' | 'ViewHealthCheckScreen' | 'AuthorApex' | 'ViewEventLogFiles';
4
+ export interface PermissionSpec {
5
+ /** Field on UserPermissionAccess carrying the effective grant. */
6
+ readonly field: string;
7
+ readonly label: string;
8
+ /** What the audit loses without it. */
9
+ readonly impact: string;
10
+ /**
11
+ * Cache keys whose producers and consumers need this permission. The affected
12
+ * check list is derived from the registry via these keys rather than hand-written,
13
+ * so a check added later is covered without touching this file.
14
+ *
15
+ * Empty for permissions too broad to attribute to specific checks.
16
+ */
17
+ readonly cacheKeys: ReadonlyArray<keyof AuditCache>;
18
+ /** The audit cannot run at all without this. */
19
+ readonly blocking?: boolean;
20
+ }
21
+ export declare const AUDIT_PERMISSIONS: Readonly<Record<AuditPermission, PermissionSpec>>;
22
+ export declare const usesKey: (check: SecurityCheck, key: keyof AuditCache) => boolean;
23
+ /** Labels of the permissions this check's declared cache wiring needs; empty when none is attributable. */
24
+ export declare function permissionLabelsFor(check: SecurityCheck): string[];
25
+ //# sourceMappingURL=permissions.d.ts.map
@@ -0,0 +1,50 @@
1
+ export const AUDIT_PERMISSIONS = {
2
+ ApiEnabled: {
3
+ field: 'PermissionsApiEnabled',
4
+ label: 'API Enabled',
5
+ impact: 'All access is via SOQL/Tooling/REST. Without it the audit cannot run at all.',
6
+ cacheKeys: [],
7
+ blocking: true,
8
+ },
9
+ ViewSetup: {
10
+ field: 'PermissionsViewSetup',
11
+ label: 'View Setup and Configuration',
12
+ impact: 'Reads the bulk of the surface — connected apps, remote sites, CSP, named credentials, auth config, ' +
13
+ 'Experience sites, and Tooling metadata. Most setup and configuration checks return inconclusive without it.',
14
+ cacheKeys: [],
15
+ },
16
+ ViewAllUsers: {
17
+ field: 'PermissionsViewAllUsers',
18
+ label: 'View All Users',
19
+ impact: 'Enumerates every User, PermissionSetAssignment and TwoFactorInfo org-wide. Without it the user, ' +
20
+ 'admin and MFA checks under-count and miss accounts outside the role hierarchy.',
21
+ cacheKeys: ['mfaRegistrations', 'effectivePermissions'],
22
+ },
23
+ ViewHealthCheckScreen: {
24
+ field: 'PermissionsViewHealthCheck',
25
+ label: 'View Health Check',
26
+ impact: 'Reads SecurityHealthCheck and its risks. Health Check and password/session baselines are inconclusive without it.',
27
+ cacheKeys: ['healthCheckRisks'],
28
+ },
29
+ AuthorApex: {
30
+ field: 'PermissionsAuthorApex',
31
+ label: 'Author Apex (read-only use)',
32
+ impact: 'The only standard gate exposing ApexClass/ApexTrigger/ApexPage Body via the Tooling API. ' +
33
+ 'Grants no ability to modify org data. The code-security checks are inconclusive without it.',
34
+ cacheKeys: ['apexBodies', 'vfPageBodies'],
35
+ },
36
+ ViewEventLogFiles: {
37
+ field: 'PermissionsViewEventLogFiles',
38
+ label: 'View Event Log Files',
39
+ impact: 'Reads EventLogFile. Whether login and API activity is monitored cannot be established without it.',
40
+ cacheKeys: ['eventLogSummary'],
41
+ },
42
+ };
43
+ export const usesKey = (check, key) => (check.dependsOnCache?.includes(key) ?? false) || (check.populatesCache?.includes(key) ?? false);
44
+ /** Labels of the permissions this check's declared cache wiring needs; empty when none is attributable. */
45
+ export function permissionLabelsFor(check) {
46
+ return Object.values(AUDIT_PERMISSIONS)
47
+ .filter((spec) => spec.cacheKeys.some((k) => usesKey(check, k)))
48
+ .map((spec) => spec.label);
49
+ }
50
+ //# sourceMappingURL=permissions.js.map
@@ -6,7 +6,7 @@ import { selectPriorities } from '../report/ExecutivePriorities.js';
6
6
  import { buildRoadmap } from '../report/RemediationRoadmap.js';
7
7
  import { buildComplianceMatrix } from '../report/ComplianceMatrix.js';
8
8
  import { renderAttackChainDagSvg } from './AttackChainDagRenderer.js';
9
- import { coverageSummary } from '../findings/coverage.js';
9
+ import { coverageSummary, coverageAdvice } from '../findings/coverage.js';
10
10
  const SEV_COLOR = {
11
11
  CRITICAL: '#7d3a3a', HIGH: '#a35a2a', MEDIUM: '#8a6d1f', LOW: '#3a5a82', INFO: '#636770',
12
12
  };
@@ -144,7 +144,7 @@ ${this.footer(b)}
144
144
  const waived = r.findings.filter((f) => f.waived).length;
145
145
  const waivedNote = waived ? `, with ${waived} waived as accepted risk` : '';
146
146
  return `${this.sectionHead(numStr, 'Executive Summary')}
147
- <p>This audit assessed the org’s security configuration and scored it <strong>${r.healthScore}/100 (Grade ${esc(r.grade)})</strong> across ${active} active finding${active === 1 ? '' : 's'}${incon ? `, with ${incon} inconclusive (insufficient access)` : ''}${waivedNote}. The priorities below are the highest-impact items to address first; the remediation roadmap groups every fix by effort. See Scope &amp; Liability for the basis and limits of this assessment.</p>${this.coverageNote(r)}`;
147
+ <p>This audit assessed the org’s security configuration and scored it <strong>${r.healthScore}/100 (Grade ${esc(r.grade)})</strong>${r.gradeReason ? `, a grade set by ${esc(r.gradeReason.replace(/^[A-F]: /, ''))},` : ''} across ${active} active finding${active === 1 ? '' : 's'}${incon ? `, with ${incon} inconclusive (no evidence gathered)` : ''}${waivedNote}. The priorities below are the highest-impact items to address first; the remediation roadmap groups every fix by effort. See Scope &amp; Liability for the basis and limits of this assessment.</p>${this.coverageNote(r)}`;
148
148
  }
149
149
  prioritiesSection(priorities, chainIds, numStr) {
150
150
  const head = this.sectionHead(numStr, 'Executive Priorities');
@@ -164,7 +164,7 @@ ${impact}${chained}<p><strong>Fix:</strong> ${esc(f.remediation)}</p></div>`;
164
164
  const c = r.coverage;
165
165
  if (!c || c.notAssessed.length === 0)
166
166
  return '';
167
- return `<p class="muted">${esc(coverageSummary(c))}. The checks that gathered no evidence are listed as inconclusive in the findings appendix; their areas are unassessed, not clean.</p>`;
167
+ return `<p class="muted">${esc(coverageSummary(c))}. The checks that gathered no evidence are listed as inconclusive in the findings appendix; their areas are unassessed, not clean. ${esc(coverageAdvice(c))}</p>`;
168
168
  }
169
169
  waiversSection(waived, numStr) {
170
170
  const items = waived
@@ -1,6 +1,6 @@
1
1
  import { esc, firaFontFaceCss, INTERACTIVE_CSP_META } from '@cclabsnz/sf-core';
2
2
  import { renderAttackChainDagSvg } from './AttackChainDagRenderer.js';
3
- import { coverageSummary } from '../findings/coverage.js';
3
+ import { coverageSummary, coverageAdvice } from '../findings/coverage.js';
4
4
  const RISK_COLORS = {
5
5
  CRITICAL: '#dc2626',
6
6
  HIGH: '#ea580c',
@@ -128,9 +128,12 @@ function buildDashboard(result, counts) {
128
128
  const waivedBanner = result.waivedFindings?.length
129
129
  ? `<div class="waived-banner" style="background:#0f291e;border:1px solid #16a34a;border-radius:8px;padding:12px 16px;margin-bottom:20px;color:#dcfce7;font-size:13px;"><strong>Accepted risks:</strong> ${result.waivedFindings.length} finding(s) waived under an approved waiver and excluded from the score.</div>`
130
130
  : '';
131
+ const gradeReasonLine = result.gradeReason
132
+ ? `<div class="grade-reason" style="margin-top:10px;font-size:12px;color:#94a3b8">Why ${esc(result.grade)}: ${esc(result.gradeReason.replace(/^[A-F]: /, ''))}</div>`
133
+ : '';
131
134
  const cov = result.coverage;
132
135
  const coverageLine = cov
133
- ? `<div class="coverage${cov.gradeCapped ? ' is-capped' : ''}" style="margin-top:10px;font-size:12px;color:${cov.gradeCapped ? '#fbbf24' : '#94a3b8'}">${esc(coverageSummary(cov))}${cov.notAssessed.length ? `<br>Not assessed: ${cov.notAssessed.map((id) => `<code>${esc(id)}</code>`).join(', ')}` : ''}</div>`
136
+ ? `<div class="coverage${cov.gradeCapped ? ' is-capped' : ''}" style="margin-top:10px;font-size:12px;color:${cov.gradeCapped ? '#fbbf24' : '#94a3b8'}">${esc(coverageSummary(cov))}${cov.notAssessed.length ? `<br>Not assessed: ${cov.notAssessed.map((id) => `<code>${esc(id)}</code>`).join(', ')}<br>${esc(coverageAdvice(cov))}` : ''}</div>`
134
137
  : '';
135
138
  return `
136
139
  ${waivedBanner}
@@ -140,6 +143,7 @@ function buildDashboard(result, counts) {
140
143
  <div class="gauge-wrap">
141
144
  ${gauge}
142
145
  </div>
146
+ ${gradeReasonLine}
143
147
  ${coverageLine}
144
148
  </div>
145
149
  <div class="dash-risk-panel">
@@ -1,4 +1,4 @@
1
- import { coverageSummary } from '../findings/coverage.js';
1
+ import { coverageSummary, coverageAdvice } from '../findings/coverage.js';
2
2
  function escapeMdCell(s) {
3
3
  return s.replace(/\\/g, '\\\\').replace(/\|/g, '\\|').replace(/\n/g, ' ');
4
4
  }
@@ -11,12 +11,15 @@ export class MarkdownRenderer {
11
11
  lines.push(`**Org:** ${result.orgName} (${result.orgId})`);
12
12
  lines.push(`**Generated:** ${result.generatedAt.toISOString()}`);
13
13
  lines.push(`**Instance:** ${result.instance} | **Type:** ${result.orgType}${result.isSandbox ? ' (Sandbox)' : ''}`);
14
- lines.push(`**Health Score:** ${result.healthScore}/100 | **Grade:** ${result.grade}`);
14
+ lines.push(`**Health Score:** ${result.healthScore}/100 | **Grade:** ${result.grade}${result.gradeReason ? ` (${result.gradeReason})` : ''}`);
15
15
  if (result.coverage) {
16
16
  lines.push('');
17
17
  lines.push(`**${coverageSummary(result.coverage)}**`);
18
- if (result.coverage.notAssessed.length > 0)
18
+ if (result.coverage.notAssessed.length > 0) {
19
19
  lines.push(`Not assessed: ${result.coverage.notAssessed.map((id) => `\`${id}\``).join(', ')}`);
20
+ lines.push('');
21
+ lines.push(coverageAdvice(result.coverage));
22
+ }
20
23
  }
21
24
  lines.push('');
22
25
  if (result.attackChains && result.attackChains.length > 0) {
@@ -4,6 +4,10 @@ export interface Roadmap {
4
4
  moderate: Finding[];
5
5
  project: Finding[];
6
6
  }
7
- /** Group active findings into effort tiers, risk-sorted within each. Unknown checkId → moderate. */
7
+ /**
8
+ * Group the findings that ask for a change into effort tiers, risk-sorted within each. Unknown
9
+ * checkId → moderate. INFO findings (inventories, advisories) and not-assessed ones (a check that
10
+ * failed or saw nothing) ask for no change, so they stay in the appendix and the coverage line.
11
+ */
8
12
  export declare function buildRoadmap(findings: Finding[]): Roadmap;
9
13
  //# sourceMappingURL=RemediationRoadmap.d.ts.map
@@ -1,10 +1,14 @@
1
1
  import { getCheckMeta } from '../findings/CheckMeta.js';
2
2
  const RANK = { CRITICAL: 0, HIGH: 1, MEDIUM: 2, LOW: 3, INFO: 4 };
3
- /** Group active findings into effort tiers, risk-sorted within each. Unknown checkId → moderate. */
3
+ /**
4
+ * Group the findings that ask for a change into effort tiers, risk-sorted within each. Unknown
5
+ * checkId → moderate. INFO findings (inventories, advisories) and not-assessed ones (a check that
6
+ * failed or saw nothing) ask for no change, so they stay in the appendix and the coverage line.
7
+ */
4
8
  export function buildRoadmap(findings) {
5
9
  const out = { quick: [], moderate: [], project: [] };
6
10
  for (const f of findings) {
7
- if (f.passed || f.inconclusive || f.waived)
11
+ if (f.passed || f.inconclusive || f.waived || f.notAssessed || f.riskLevel === 'INFO')
8
12
  continue;
9
13
  const effort = (f.checkId && getCheckMeta(f.checkId)?.effort) || 'moderate';
10
14
  out[effort].push(f);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cclabsnz/sf-audit",
3
- "version": "1.17.0",
3
+ "version": "1.18.0",
4
4
  "description": "Read-only Salesforce security audit for the sf CLI: 109 checks, attack-chain correlation, A-F risk grading, compliance mapping, free EventLogFile capture, and Guest User Anomaly investigation.",
5
5
  "keywords": [
6
6
  "salesforce",
@@ -72,7 +72,7 @@
72
72
  "url": "https://github.com/cclabsnz/sf-audit-plugin/issues"
73
73
  },
74
74
  "engines": {
75
- "node": ">=18.0.0"
75
+ "node": ">=22.0.0"
76
76
  },
77
77
  "oclif": {
78
78
  "bin": "sf",
@@ -101,6 +101,8 @@
101
101
  "files": [
102
102
  "/lib",
103
103
  "/CHANGELOG.md",
104
+ "/PERMISSIONS.md",
105
+ "/docs/permissionset",
104
106
  "/messages",
105
107
  "/config",
106
108
  "!/lib/**/*.map"