@cclabsnz/sf-audit 1.16.0 → 1.17.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 (112) hide show
  1. package/CHANGELOG.md +118 -1
  2. package/README.md +94 -24
  3. package/config/scoring.sample.json +104 -5
  4. package/lib/apps/analyzeApps.d.ts +8 -2
  5. package/lib/apps/analyzeApps.js +7 -2
  6. package/lib/apps/apiLogSource.d.ts +39 -0
  7. package/lib/apps/apiLogSource.js +75 -0
  8. package/lib/apps/appResolver.js +30 -4
  9. package/lib/apps/grantedAccess.js +16 -3
  10. package/lib/apps/leastPrivilege.d.ts +3 -1
  11. package/lib/apps/leastPrivilege.js +7 -3
  12. package/lib/apps/permissionSetGenerator.d.ts +22 -0
  13. package/lib/apps/permissionSetGenerator.js +100 -0
  14. package/lib/apps/types.d.ts +6 -0
  15. package/lib/apps/usageCollector.d.ts +7 -1
  16. package/lib/apps/usageCollector.js +57 -26
  17. package/lib/chains/CapabilityRegistry.js +26 -0
  18. package/lib/chains/namedChains.js +95 -7
  19. package/lib/checks/CheckEngine.d.ts +3 -1
  20. package/lib/checks/CheckEngine.js +11 -3
  21. package/lib/checks/impl/ApexCrudFLSCheck.js +45 -10
  22. package/lib/checks/impl/ApexSharingCheck.js +16 -25
  23. package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.d.ts +10 -0
  24. package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.js +131 -0
  25. package/lib/checks/impl/ConnectedAppsCheck.js +47 -1
  26. package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.d.ts +10 -0
  27. package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.js +116 -0
  28. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.d.ts +10 -0
  29. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.js +75 -0
  30. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.d.ts +10 -0
  31. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.js +98 -0
  32. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.d.ts +10 -0
  33. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.js +73 -0
  34. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.d.ts +10 -0
  35. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.js +115 -0
  36. package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.d.ts +10 -0
  37. package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.js +227 -0
  38. package/lib/checks/impl/GuestExecutableApexCheck.d.ts +1 -1
  39. package/lib/checks/impl/GuestExecutableApexCheck.js +105 -14
  40. package/lib/checks/impl/HardcodedCredentialsCheck.js +7 -2
  41. package/lib/checks/impl/InboundEmailHandlerExposureCheck.d.ts +10 -0
  42. package/lib/checks/impl/InboundEmailHandlerExposureCheck.js +136 -0
  43. package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.d.ts +10 -0
  44. package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.js +84 -0
  45. package/lib/checks/impl/OrgWideEmailSpoofingCheck.d.ts +10 -0
  46. package/lib/checks/impl/OrgWideEmailSpoofingCheck.js +106 -0
  47. package/lib/checks/impl/PackagePostInstallSupplyChainCheck.d.ts +10 -0
  48. package/lib/checks/impl/PackagePostInstallSupplyChainCheck.js +89 -0
  49. package/lib/checks/impl/PlatformEventSubscriberContextCheck.d.ts +10 -0
  50. package/lib/checks/impl/PlatformEventSubscriberContextCheck.js +84 -0
  51. package/lib/checks/impl/RestrictionRulesIntegrityCheck.d.ts +10 -0
  52. package/lib/checks/impl/RestrictionRulesIntegrityCheck.js +105 -0
  53. package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.d.ts +10 -0
  54. package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.js +90 -0
  55. package/lib/checks/registry.js +30 -0
  56. package/lib/checks/support/apexAccess.d.ts +56 -0
  57. package/lib/checks/support/apexAccess.js +127 -0
  58. package/lib/checks/support/missingObject.d.ts +13 -0
  59. package/lib/checks/support/missingObject.js +35 -0
  60. package/lib/commands/audit/apps.d.ts +1 -0
  61. package/lib/commands/audit/apps.js +83 -29
  62. package/lib/commands/audit/diff.js +2 -2
  63. package/lib/commands/audit/history.js +2 -2
  64. package/lib/commands/audit/incident/report.js +2 -2
  65. package/lib/commands/audit/security.d.ts +3 -0
  66. package/lib/commands/audit/security.js +58 -9
  67. package/lib/commands/audit/timeline.js +2 -2
  68. package/lib/compliance/mapping.js +28 -7
  69. package/lib/findings/AuditResult.d.ts +8 -0
  70. package/lib/findings/CheckMeta.js +15 -0
  71. package/lib/findings/Finding.d.ts +4 -0
  72. package/lib/findings/ScoringConfig.d.ts +10 -8
  73. package/lib/findings/ScoringConfig.js +12 -5
  74. package/lib/findings/coverage.d.ts +28 -0
  75. package/lib/findings/coverage.js +30 -0
  76. package/lib/findings/exitCode.js +1 -1
  77. package/lib/findings/loadScoringConfig.js +51 -8
  78. package/lib/findings/scoring.js +14 -5
  79. package/lib/history/HistoryStore.js +9 -3
  80. package/lib/history/archivePolicy.d.ts +19 -0
  81. package/lib/history/archivePolicy.js +34 -0
  82. package/lib/incident/bundleIo.js +4 -3
  83. package/lib/incident/collect/collectBundle.d.ts +1 -1
  84. package/lib/incident/collect/collectBundle.js +4 -3
  85. package/lib/incident/collect/streamGuestLogs.d.ts +1 -1
  86. package/lib/incident/collect/streamGuestLogs.js +3 -2
  87. package/lib/incident/csv.js +4 -4
  88. package/lib/incident/render/evidence.js +3 -3
  89. package/lib/incident/render/html.js +2 -3
  90. package/lib/index.d.ts +2 -0
  91. package/lib/index.js +2 -0
  92. package/lib/lib/packageInfo.d.ts +6 -0
  93. package/lib/lib/packageInfo.js +19 -0
  94. package/lib/renderers/AttackChainDagRenderer.d.ts +7 -0
  95. package/lib/renderers/AttackChainDagRenderer.js +139 -0
  96. package/lib/renderers/ClientReportRenderer.d.ts +2 -0
  97. package/lib/renderers/ClientReportRenderer.js +34 -6
  98. package/lib/renderers/DiffHtmlRenderer.js +2 -7
  99. package/lib/renderers/HistoryRenderer.js +19 -11
  100. package/lib/renderers/HtmlRenderer.js +19 -6
  101. package/lib/renderers/MarkdownRenderer.js +7 -0
  102. package/lib/renderers/SarifRenderer.d.ts +43 -0
  103. package/lib/renderers/SarifRenderer.js +250 -0
  104. package/lib/report/ExecutivePriorities.js +1 -1
  105. package/lib/report/RemediationRoadmap.js +1 -1
  106. package/lib/waivers/WaiverLoader.d.ts +28 -0
  107. package/lib/waivers/WaiverLoader.js +103 -0
  108. package/lib/waivers/WaiverModel.d.ts +32 -0
  109. package/lib/waivers/WaiverModel.js +28 -0
  110. package/lib/waivers/applyWaivers.d.ts +22 -0
  111. package/lib/waivers/applyWaivers.js +85 -0
  112. package/package.json +3 -3
@@ -17,19 +17,42 @@ export async function resolveApps(appIds, soql, userIds) {
17
17
  const connApps = await soql
18
18
  .queryAll('SELECT Id, Name FROM ConnectedApplication')
19
19
  .catch(() => []);
20
+ const ecaApps = await soql
21
+ .queryAll('SELECT Id, DeveloperName, MasterLabel FROM ExternalClientApplication')
22
+ .catch(() => []);
20
23
  const menuByKey = new Map(menu.map((m) => [m.ApplicationId.slice(0, 15), m.Label ?? m.Name ?? '']));
21
24
  const connByKey = new Map(connApps.map((c) => [c.Id.slice(0, 15), c.Name]));
22
- // Only pay for LoginHistory if some ids are still unresolved after 1-3.
23
- const stillUnknown = appIds.filter((id) => !menuByKey.has(id.slice(0, 15)) && !connByKey.has(id.slice(0, 15)) && !lookupStandardApp(id));
25
+ const ecaByKey = new Map();
26
+ for (const e of ecaApps) {
27
+ const name = e.MasterLabel ?? e.DeveloperName ?? '';
28
+ ecaByKey.set(e.Id.slice(0, 15), name);
29
+ ecaByKey.set(e.Id, name);
30
+ if (e.DeveloperName)
31
+ ecaByKey.set(e.DeveloperName, name);
32
+ }
33
+ // Only pay for LoginHistory if some ids are still unresolved after 1-4.
34
+ const stillUnknown = appIds.filter((id) => !menuByKey.has(id.slice(0, 15)) &&
35
+ !connByKey.has(id.slice(0, 15)) &&
36
+ !ecaByKey.has(id.slice(0, 15)) &&
37
+ !ecaByKey.has(id) &&
38
+ !lookupStandardApp(id));
24
39
  let logins = [];
25
40
  if (stillUnknown.length > 0 && userIds.length > 0) {
26
41
  logins = await soql
27
- .queryAll(`SELECT Application, UserId FROM LoginHistory WHERE UserId IN (${userIds
42
+ .queryAll(`SELECT Application, ClientVersion, UserId FROM LoginHistory WHERE UserId IN (${userIds
28
43
  .map((u) => `'${u}'`)
29
44
  .join(',')}) AND LoginTime = LAST_N_DAYS:7`)
30
45
  .catch(() => []);
31
46
  }
32
- const loginNames = [...new Set(logins.map((l) => l.Application).filter((a) => a && a !== 'Browser' && a !== 'N/A'))];
47
+ // ClientVersion is only a fallback for rows with no usable Application: it is usually a version
48
+ // string ("58.0"), and counting it alongside Application would turn one login into two names and
49
+ // defeat the single-name inference below.
50
+ const meaningful = (a) => !!a && a !== 'Browser' && a !== 'N/A';
51
+ const loginNames = [
52
+ ...new Set(logins
53
+ .map((l) => meaningful(l.Application) ? l.Application : meaningful(l.ClientVersion) && !/^[\d.]+$/.test(l.ClientVersion) ? l.ClientVersion : null)
54
+ .filter(meaningful)),
55
+ ];
33
56
  return appIds.map((appId) => {
34
57
  const key = appId.slice(0, 15);
35
58
  const menuName = menuByKey.get(key);
@@ -38,6 +61,9 @@ export async function resolveApps(appIds, soql, userIds) {
38
61
  const connName = connByKey.get(key);
39
62
  if (connName)
40
63
  return { appId, name: connName, category: categorise(connName, null), confidence: 'resolved' };
64
+ const ecaName = ecaByKey.get(key) ?? ecaByKey.get(appId);
65
+ if (ecaName)
66
+ return { appId, name: ecaName, category: categorise(ecaName, null), confidence: 'resolved' };
41
67
  const std = lookupStandardApp(appId);
42
68
  if (std)
43
69
  return { appId, name: std.name, category: std.category, vendor: std.vendor, purpose: std.purpose, confidence: 'resolved' };
@@ -7,12 +7,25 @@ export async function computeGranted(appId, runAsUsers, soql, scope) {
7
7
  const psa = await soql
8
8
  .queryAll(`SELECT AssigneeId, PermissionSetId FROM PermissionSetAssignment WHERE AssigneeId IN (${inList(runAsUsers)})`)
9
9
  .catch(() => []);
10
- const psIds = [...new Set(psa.map((p) => p.PermissionSetId))];
11
- if (psIds.length === 0)
10
+ const psIds = new Set(psa.map((p) => p.PermissionSetId));
11
+ const users = await soql
12
+ .queryAll(`SELECT Id, ProfileId FROM User WHERE Id IN (${inList(runAsUsers)})`)
13
+ .catch(() => []);
14
+ const profileIds = [...new Set(users.map((u) => u.ProfileId).filter(Boolean))];
15
+ if (profileIds.length > 0) {
16
+ const profilePs = await soql
17
+ .queryAll(`SELECT Id, ProfileId FROM PermissionSet WHERE IsOwnedByProfile = true AND ProfileId IN (${inList(profileIds)})`)
18
+ .catch(() => []);
19
+ for (const p of profilePs) {
20
+ psIds.add(p.Id);
21
+ }
22
+ }
23
+ const allPsIds = [...psIds];
24
+ if (allPsIds.length === 0)
12
25
  return { appId, scope, objects: [], runAsUsers, multiUserInteractive };
13
26
  const perms = await soql
14
27
  .queryAll(`SELECT ParentId, SobjectType, PermissionsRead, PermissionsCreate, PermissionsEdit, PermissionsDelete
15
- FROM ObjectPermissions WHERE ParentId IN (${inList(psIds)}) AND PermissionsRead = true`)
28
+ FROM ObjectPermissions WHERE ParentId IN (${inList(allPsIds)}) AND PermissionsRead = true`)
16
29
  .catch(() => []);
17
30
  const byObject = new Map();
18
31
  for (const p of perms) {
@@ -2,5 +2,7 @@ import type { AppFinding, AppUsage, GrantedAccess, ResolvedApp } from './types.j
2
2
  export declare function buildFinding(app: ResolvedApp, used: AppUsage, granted: GrantedAccess, window: {
3
3
  since: number;
4
4
  attributionRatePct: number;
5
- }, soakDays: number): AppFinding;
5
+ }, soakDays: number,
6
+ /** Set when some API logs in the window could not be read: usage is then known to be incomplete. */
7
+ incompleteUsage?: string): AppFinding;
6
8
  //# sourceMappingURL=leastPrivilege.d.ts.map
@@ -1,4 +1,6 @@
1
- export function buildFinding(app, used, granted, window, soakDays) {
1
+ export function buildFinding(app, used, granted, window, soakDays,
2
+ /** Set when some API logs in the window could not be read: usage is then known to be incomplete. */
3
+ incompleteUsage) {
2
4
  const usedObjects = new Set(used.objects.map((o) => o.object));
3
5
  const usedVerbs = new Map(used.objects.map((o) => [o.object, new Set(o.verbs)]));
4
6
  const belowSoak = window.since < soakDays;
@@ -6,11 +8,13 @@ export function buildFinding(app, used, granted, window, soakDays) {
6
8
  notes.push(`Observed over ${window.since} day(s); RestApi attribution ${window.attributionRatePct}% — "used" is a lower bound.`);
7
9
  if (belowSoak)
8
10
  notes.push(`Window below the ${soakDays}-day soak threshold: revoke recommendations suppressed.`);
11
+ if (incompleteUsage)
12
+ notes.push(`Usage data incomplete (${incompleteUsage}): revoke recommendations suppressed.`);
9
13
  if (used.soapOnly)
10
14
  notes.push('SOAP usage present but not app-attributable; not treated as dormant.');
11
15
  if (granted.multiUserInteractive)
12
16
  notes.push('Interactive app with many run-as users; object delta not asserted.');
13
- const assertDelta = !belowSoak && !granted.multiUserInteractive;
17
+ const assertDelta = !belowSoak && !granted.multiUserInteractive && !incompleteUsage;
14
18
  const unusedObjects = assertDelta
15
19
  ? granted.objects.map((o) => o.object).filter((o) => !usedObjects.has(o)).sort()
16
20
  : [];
@@ -40,7 +44,7 @@ export function buildFinding(app, used, granted, window, soakDays) {
40
44
  used,
41
45
  granted,
42
46
  overGrant: { unusedObjects, unusedVerbs, scopeDowngrade, dormant },
43
- recommendation: { permissionSet: { objectPermissions } },
47
+ recommendation: { asserted: assertDelta, permissionSet: { objectPermissions } },
44
48
  notes,
45
49
  };
46
50
  }
@@ -0,0 +1,22 @@
1
+ import type { AppFinding } from './types.js';
2
+ /**
3
+ * Turns an app name into a valid metadata API name stem: starts with a letter, only alphanumerics and
4
+ * single underscores, no leading or trailing underscore. Length is capped by the caller.
5
+ */
6
+ export declare function sanitizePermissionSetName(name: string): string;
7
+ /**
8
+ * One API name per finding, unique case-insensitively (Salesforce API names and macOS/Windows file
9
+ * names both ignore case), each at most 80 characters.
10
+ */
11
+ export declare function permissionSetNames(findings: AppFinding[]): string[];
12
+ export declare function generatePermissionSetXml(finding: AppFinding): string;
13
+ /**
14
+ * Writes one .permissionset-meta.xml per finding whose recommendation is asserted. Findings held back
15
+ * (soak window, many interactive users, incomplete logs) are skipped: their observed usage is too thin
16
+ * to be a least-privilege grant. Local files only; nothing is deployed.
17
+ */
18
+ export declare function emitPermissionSets(findings: AppFinding[], targetDir: string): {
19
+ written: string[];
20
+ skipped: string[];
21
+ };
22
+ //# sourceMappingURL=permissionSetGenerator.d.ts.map
@@ -0,0 +1,100 @@
1
+ import { join } from 'node:path';
2
+ import { secureFs } from '@cclabsnz/sf-core';
3
+ const API_NAME_MAX = 80;
4
+ const LABEL_MAX = 80;
5
+ const NAME_SUFFIX = '_LeastPrivilege';
6
+ const LABEL_SUFFIX = ' Least Privilege';
7
+ // XML 1.0 forbids most C0 control characters even when escaped; drop them rather than emit invalid XML.
8
+ // eslint-disable-next-line no-control-regex
9
+ const XML_INVALID = /[\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]/g;
10
+ function xmlEscape(s) {
11
+ return s
12
+ .replace(XML_INVALID, '')
13
+ .replace(/&/g, '&amp;')
14
+ .replace(/</g, '&lt;')
15
+ .replace(/>/g, '&gt;')
16
+ .replace(/"/g, '&quot;')
17
+ .replace(/'/g, '&apos;');
18
+ }
19
+ /**
20
+ * Turns an app name into a valid metadata API name stem: starts with a letter, only alphanumerics and
21
+ * single underscores, no leading or trailing underscore. Length is capped by the caller.
22
+ */
23
+ export function sanitizePermissionSetName(name) {
24
+ let clean = name.replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_+|_+$/g, '');
25
+ if (!clean)
26
+ return 'App';
27
+ if (!/^[a-zA-Z]/.test(clean))
28
+ clean = `App_${clean}`;
29
+ return clean;
30
+ }
31
+ function fitName(stem, tail) {
32
+ const room = API_NAME_MAX - tail.length;
33
+ return `${stem.slice(0, room).replace(/_+$/, '')}${tail}`;
34
+ }
35
+ /**
36
+ * One API name per finding, unique case-insensitively (Salesforce API names and macOS/Windows file
37
+ * names both ignore case), each at most 80 characters.
38
+ */
39
+ export function permissionSetNames(findings) {
40
+ const taken = new Set();
41
+ return findings.map((f) => {
42
+ const stem = sanitizePermissionSetName(f.app.name || f.app.appId);
43
+ let candidate = fitName(stem, NAME_SUFFIX);
44
+ for (let n = 2; taken.has(candidate.toLowerCase()); n++)
45
+ candidate = fitName(stem, `${NAME_SUFFIX}_${n}`);
46
+ taken.add(candidate.toLowerCase());
47
+ return candidate;
48
+ });
49
+ }
50
+ export function generatePermissionSetXml(finding) {
51
+ const appName = (finding.app.name || finding.app.appId).replace(XML_INVALID, '');
52
+ const label = `${appName.slice(0, LABEL_MAX - LABEL_SUFFIX.length).trimEnd()}${LABEL_SUFFIX}`;
53
+ const perms = (finding.recommendation?.permissionSet?.objectPermissions ?? [])
54
+ .slice()
55
+ .sort((a, b) => a.object.localeCompare(b.object));
56
+ // Salesforce rejects edit/create without read and delete without edit, so imply the prerequisites.
57
+ const objectXml = perms
58
+ .map((p) => {
59
+ const edit = p.edit || p.delete;
60
+ const read = p.read || p.create || edit;
61
+ return ` <objectPermissions>
62
+ <allowCreate>${p.create}</allowCreate>
63
+ <allowDelete>${p.delete}</allowDelete>
64
+ <allowEdit>${edit}</allowEdit>
65
+ <allowRead>${read}</allowRead>
66
+ <modifyAllRecords>false</modifyAllRecords>
67
+ <object>${xmlEscape(p.object)}</object>
68
+ <viewAllRecords>false</viewAllRecords>
69
+ </objectPermissions>`;
70
+ })
71
+ .join('\n');
72
+ return `<?xml version="1.0" encoding="UTF-8"?>
73
+ <PermissionSet xmlns="http://soap.sforce.com/2006/04/metadata">
74
+ <description>${xmlEscape(`Generated by sf audit apps from usage observed over ${finding.window.since} day(s). Review before deploying.`)}</description>
75
+ <hasActivationRequired>false</hasActivationRequired>
76
+ <label>${xmlEscape(label)}</label>
77
+ ${objectXml ? objectXml + '\n' : ''}</PermissionSet>
78
+ `;
79
+ }
80
+ /**
81
+ * Writes one .permissionset-meta.xml per finding whose recommendation is asserted. Findings held back
82
+ * (soak window, many interactive users, incomplete logs) are skipped: their observed usage is too thin
83
+ * to be a least-privilege grant. Local files only; nothing is deployed.
84
+ */
85
+ export function emitPermissionSets(findings, targetDir) {
86
+ const emit = findings.filter((f) => f.recommendation.asserted);
87
+ const skipped = findings.filter((f) => !f.recommendation.asserted).map((f) => f.app.name || f.app.appId);
88
+ const written = [];
89
+ if (emit.length === 0)
90
+ return { written, skipped };
91
+ secureFs.mkdirSync(targetDir, { recursive: true });
92
+ const names = permissionSetNames(emit);
93
+ emit.forEach((f, i) => {
94
+ const filePath = join(targetDir, `${names[i]}.permissionset-meta.xml`);
95
+ secureFs.writeFileSync(filePath, generatePermissionSetXml(f));
96
+ written.push(filePath);
97
+ });
98
+ return { written, skipped };
99
+ }
100
+ //# sourceMappingURL=permissionSetGenerator.js.map
@@ -49,6 +49,12 @@ export interface AppFinding {
49
49
  dormant: boolean;
50
50
  };
51
51
  recommendation: {
52
+ /**
53
+ * False when the delta was not asserted (window below the soak threshold, many interactive run-as
54
+ * users, or incomplete log data): the permission set below then reflects partial observation only
55
+ * and must not be emitted as a deployable least-privilege grant.
56
+ */
57
+ asserted: boolean;
52
58
  permissionSet: {
53
59
  objectPermissions: {
54
60
  object: string;
@@ -5,5 +5,11 @@ export interface UsageResult {
5
5
  attributedRows: number;
6
6
  attributionRatePct: number;
7
7
  }
8
- export declare function collectUsage(restApiCsv: string, soapApiCsv?: string): UsageResult;
8
+ export interface CollectUsageOptions {
9
+ soapApiCsv?: string;
10
+ bulkApi2Csv?: string;
11
+ graphQlCsv?: string;
12
+ auraCsv?: string;
13
+ }
14
+ export declare function collectUsage(restApiCsv: string, optsOrSoap?: CollectUsageOptions | string): UsageResult;
9
15
  //# sourceMappingURL=usageCollector.d.ts.map
@@ -55,34 +55,65 @@ function verbOf(method) {
55
55
  return 'write';
56
56
  return 'read';
57
57
  }
58
- export function collectUsage(restApiCsv, soapApiCsv) {
59
- const rows = parseCsv(restApiCsv);
58
+ export function collectUsage(restApiCsv, optsOrSoap) {
59
+ const opts = typeof optsOrSoap === 'string'
60
+ ? { soapApiCsv: optsOrSoap }
61
+ : optsOrSoap ?? {};
60
62
  const byApp = new Map();
63
+ let totalRows = 0;
61
64
  let attributed = 0;
62
- for (const row of rows) {
63
- const appId = row.CONNECTED_APP_ID ?? '';
64
- if (!appId)
65
- continue;
66
- attributed++;
67
- let a = byApp.get(appId);
68
- if (!a) {
69
- a = { objects: new Map(), requests: 0, rows: 0, users: new Set() };
70
- byApp.set(appId, a);
71
- }
72
- a.requests++;
73
- a.rows += Number(row.ROWS_PROCESSED) || 0;
74
- if (row.USER_ID)
75
- a.users.add(row.USER_ID);
76
- const entity = row.ENTITY_NAME;
77
- if (entity) {
78
- const verbs = a.objects.get(entity) ?? new Set();
79
- verbs.add(verbOf(row.METHOD ?? row.METHOD_NAME ?? 'GET'));
80
- a.objects.set(entity, verbs);
65
+ const processFile = (csvText, entityGetter, verbGetter, rowsGetter) => {
66
+ if (!csvText)
67
+ return;
68
+ const rows = parseCsv(csvText);
69
+ totalRows += rows.length;
70
+ for (const row of rows) {
71
+ const appId = row.CONNECTED_APP_ID ?? '';
72
+ if (!appId)
73
+ continue;
74
+ attributed++;
75
+ let a = byApp.get(appId);
76
+ if (!a) {
77
+ a = { objects: new Map(), requests: 0, rows: 0, users: new Set() };
78
+ byApp.set(appId, a);
79
+ }
80
+ a.requests++;
81
+ a.rows += rowsGetter(row);
82
+ if (row.USER_ID)
83
+ a.users.add(row.USER_ID);
84
+ const entity = entityGetter(row);
85
+ if (entity) {
86
+ // Support comma-separated entities if present
87
+ const entityNames = entity.split(',').map((e) => e.trim()).filter(Boolean);
88
+ for (const ent of entityNames) {
89
+ const verbs = a.objects.get(ent) ?? new Set();
90
+ verbs.add(verbGetter(row));
91
+ a.objects.set(ent, verbs);
92
+ }
93
+ }
81
94
  }
82
- }
95
+ };
96
+ // 1. RestApi logs
97
+ processFile(restApiCsv, (r) => r.ENTITY_NAME, (r) => verbOf(r.METHOD ?? r.METHOD_NAME ?? 'GET'), (r) => Number(r.ROWS_PROCESSED) || 0);
98
+ // 2. BulkApi2 logs
99
+ processFile(opts.bulkApi2Csv, (r) => r.ENTITY_NAME, (r) => {
100
+ const op = (r.OPERATION ?? r.OPERATION_TYPE ?? '').toLowerCase();
101
+ if (op === 'delete' || op === 'harddelete' || op === 'hard_delete')
102
+ return 'delete';
103
+ if (op === 'insert' || op === 'update' || op === 'upsert')
104
+ return 'write';
105
+ return 'read';
106
+ }, (r) => Number(r.ROWS_PROCESSED || r.NUMBER_RECORDS_PROCESSED || 0) || 0);
107
+ // 3. GraphQlQueryExecution logs
108
+ processFile(opts.graphQlCsv, (r) => r.ENTITY_NAME || r.TARGET_ENTITY, (r) => {
109
+ const op = (r.OPERATION_TYPE ?? r.OPERATION ?? '').toLowerCase();
110
+ return op.includes('mutation') ? 'write' : 'read';
111
+ }, (r) => Number(r.ROWS_PROCESSED || r.ROW_COUNT || 0) || 0);
112
+ // 4. AuraRequest logs
113
+ processFile(opts.auraCsv, (r) => r.ENTITY_NAME, (r) => verbOf(r.METHOD_NAME ?? r.METHOD ?? 'GET'), (r) => Number(r.ROWS_PROCESSED || 0) || 0);
83
114
  const soapUsers = new Set();
84
- if (soapApiCsv) {
85
- for (const row of parseCsv(soapApiCsv))
115
+ if (opts.soapApiCsv) {
116
+ for (const row of parseCsv(opts.soapApiCsv))
86
117
  if (row.USER_ID)
87
118
  soapUsers.add(row.USER_ID);
88
119
  }
@@ -96,9 +127,9 @@ export function collectUsage(restApiCsv, soapApiCsv) {
96
127
  }));
97
128
  return {
98
129
  usage: usage.sort((x, y) => y.requests - x.requests),
99
- totalRows: rows.length,
130
+ totalRows,
100
131
  attributedRows: attributed,
101
- attributionRatePct: rows.length ? Math.round((100 * attributed) / rows.length) : 0,
132
+ attributionRatePct: totalRows ? Math.round((100 * attributed) / totalRows) : 0,
102
133
  };
103
134
  }
104
135
  //# sourceMappingURL=usageCollector.js.map
@@ -39,6 +39,8 @@ export const CAPABILITY_REGISTRY = {
39
39
  // New checks (Tasks 8–10)
40
40
  'guest-executable-apex-unprotected': { grants: ['code-exec', 'data-read-bulk', 'data-write'] },
41
41
  'guest-executable-apex-exposed': { grants: ['code-exec'] },
42
+ // Sharing still bounds which records a guest reaches; SYSTEM_MODE lifts only CRUD/FLS on them.
43
+ 'guest-executable-apex-system-mode': { grants: ['code-exec', 'data-read'] },
42
44
  'cors-wildcard-origin': { grants: ['credential-theft'] },
43
45
  'cors-broad-origin': { grants: ['credential-theft'] },
44
46
  'escalation-perms-found': { grants: ['priv-esc'] },
@@ -115,6 +117,7 @@ export const CAPABILITY_REGISTRY = {
115
117
  'apex-rest-without-sharing': { grants: ['code-exec', 'data-read', 'data-write'] },
116
118
  'apex-crud-fls-without-sharing': { grants: ['data-read', 'data-write'] },
117
119
  'apex-crud-fls-missing': { grants: ['data-read'] },
120
+ 'apex-crud-fls-system-mode': { grants: ['data-read'] },
118
121
  // A live session ID posted to an external endpoint. This is a credential leaving the org through
119
122
  // a supported feature rather than a flaw, which is exactly why it is easy to leave in place: the
120
123
  // receiving endpoint can act as the running user until the session expires.
@@ -151,6 +154,29 @@ export const CAPABILITY_REGISTRY = {
151
154
  // so the model stays correct if that ever becomes an either/or, and because a CRITICAL finding
152
155
  // silently granting nothing is precisely the failure this registry exists to prevent.
153
156
  'connected-app-full-scope-infinite-token': { grants: ['data-read-bulk', 'data-write'] },
157
+ // 14 New Checks capability hooks
158
+ 'genai-prompt-template-grounding-flow': { grants: ['data-read'] },
159
+ 'genai-prompt-template-grounding-apex': { grants: ['data-read'] },
160
+ 'genai-prompt-template-grounding-untrusted': { grants: ['data-read'] },
161
+ 'data-cloud-data-space-default-overshared': { grants: ['data-read-bulk'] },
162
+ 'data-cloud-data-share-target-unconstrained': { grants: ['data-read-bulk'] },
163
+ 'platform-event-subscriber-escalation': { grants: ['priv-esc', 'data-write'] },
164
+ 'flow-http-callout-hardcoded-secret': { grants: ['credential-theft', 'external-egress'] },
165
+ 'flow-http-callout-uncredentialed-endpoint': { grants: ['external-egress'] },
166
+ 'oauth-device-flow-enabled': { grants: ['credential-theft'] },
167
+ 'oauth-password-flow-enabled': { grants: ['credential-theft'] },
168
+ 'delegated-authentication-admin-assigned': { grants: ['org-takeover'] },
169
+ 'delegated-authentication-insecure-gateway': { grants: ['org-takeover'] },
170
+ 'delegated-administration-groups-active': { grants: ['priv-esc'] },
171
+ 'auth-provider-registration-handler-admin-exec': { grants: ['priv-esc', 'org-takeover'] },
172
+ 'auth-provider-registration-handler-unverified-email-linking': { grants: ['priv-esc', 'org-takeover'] },
173
+ 'inbound-email-handler-unauthenticated-execution': { grants: ['unauth-foothold', 'code-exec'] },
174
+ 'org-wide-email-spoofing-all-profiles': { grants: ['external-egress'] },
175
+ 'org-wide-email-spoofing-no-dkim': { grants: ['external-egress'] },
176
+ 'external-account-hierarchy-super-users': { grants: ['data-read-bulk'] },
177
+ 'external-account-hierarchy-active': { grants: ['data-read-bulk'] },
178
+ 'restriction-rules-inactive': { grants: ['data-read-bulk'] },
179
+ 'restriction-rules-conflicting': { grants: ['data-read-bulk'] },
154
180
  };
155
181
  /** Resolve the effective capabilities for a finding (inline overrides registry; passed/inconclusive yield nothing). */
156
182
  export function capabilitiesFor(finding) {
@@ -29,7 +29,7 @@ export const NAMED_CHAINS = [
29
29
  return null;
30
30
  const steps = byIds(active, [
31
31
  'guest-user-read-access', 'guest-user-write-access', 'guest-user-sharing-exposure', 'guest-user-baseline',
32
- 'guest-executable-apex-unprotected', 'guest-executable-apex-exposed',
32
+ 'guest-executable-apex-unprotected', 'guest-executable-apex-exposed', 'guest-executable-apex-system-mode',
33
33
  'guest-object-exposure-public-owd', 'guest-object-exposure-guest-owned',
34
34
  'guest-api-access-enabled', 'guest-api-hard-delete', 'classic-sites-active',
35
35
  'guest-user-visibility-view-all-users', 'guest-user-visibility-owd', 'guest-user-visibility-object-read',
@@ -39,8 +39,15 @@ export const NAMED_CHAINS = [
39
39
  // analogue of portal-exposed Apex running without sharing.
40
40
  'guest-record-access-policy-not-enforced',
41
41
  'flows-autolaunched-without-sharing', 'flows-screen-without-sharing',
42
+ // An open inbound email handler grants unauth-foothold, so it must appear whenever it
43
+ // is what opened the gate.
44
+ 'inbound-email-handler-unauthenticated-execution',
42
45
  ]);
43
- return steps.length >= 2 ? steps : null;
46
+ if (steps.length < 2)
47
+ return null;
48
+ // Internal-only weaknesses that widen what a foothold reaches. They join as evidence but
49
+ // never count toward the floor: without a guest-side step they describe no unauthenticated path.
50
+ return [...steps, ...byIds(active, ['data-cloud-data-space-default-overshared', 'restriction-rules-inactive'])];
44
51
  },
45
52
  },
46
53
  {
@@ -95,8 +102,21 @@ export const NAMED_CHAINS = [
95
102
  // An integration account holding Author Apex, Customize Application or user-management
96
103
  // permissions it does not use has the same escalation reach as users-author-apex above.
97
104
  'integration-least-privilege-escalation-permissions',
105
+ // Grants unauth-foothold, so it must appear whenever it is what opened the gate.
106
+ 'inbound-email-handler-unauthenticated-execution',
98
107
  ]);
99
- return steps.length >= 2 ? steps : null;
108
+ if (steps.length < 2)
109
+ return null;
110
+ // Further escalation paths. They join as evidence but never count toward the floor, so two of
111
+ // them alone, with no low-trust step, cannot claim a standard-user path to takeover.
112
+ return [
113
+ ...steps,
114
+ ...byIds(active, [
115
+ 'delegated-administration-groups-active',
116
+ 'auth-provider-registration-handler-admin-exec', 'auth-provider-registration-handler-unverified-email-linking',
117
+ 'delegated-authentication-admin-assigned', 'platform-event-subscriber-escalation',
118
+ ]),
119
+ ];
100
120
  },
101
121
  },
102
122
  {
@@ -113,6 +133,7 @@ export const NAMED_CHAINS = [
113
133
  'hardcoded-credentials-found', 'custom-labels-credential-value-match', 'custom-labels-credential-name-match',
114
134
  'debug-log-active-traces', 'cors-wildcard-origin', 'cors-broad-origin',
115
135
  'named-credentials-inventory', 'named-credentials-http-endpoint', 'remote-sites-inventory',
136
+ 'flow-http-callout-hardcoded-secret', 'oauth-device-flow-enabled', 'oauth-password-flow-enabled',
116
137
  // A user who can stand up connected apps and bypass API access control has provisioned
117
138
  // their own egress path.
118
139
  'separation-of-duties-external-exfil-channel',
@@ -194,18 +215,32 @@ export const NAMED_CHAINS = [
194
215
  title: 'SalesBleed pattern',
195
216
  severity: 'HIGH',
196
217
  narrative: 'An active agent can run open-ended record queries (the General CRM topic or Query Records action) and ' +
197
- 'the org has agent actions that send data out (Slack, email, external services) without user confirmation. ' +
218
+ 'the org has a way to send data out: agent actions that do so (Slack, email, external services) without ' +
219
+ 'user confirmation, or a CSP Trusted URL whose domain is parked or no longer resolves, which anyone can ' +
220
+ 'register and then receive whatever the agent puts in a link or image it returns. ' +
198
221
  'That is two of the three ingredients in SalesBleed (Zenity Labs, Sept 2026) and PipeLeak (Capsule ' +
199
222
  'Security, Apr 2026); the third, text an outsider wrote, arrives through Web-to-Lead, Web-to-Case, email or ' +
200
223
  'chat in almost every org. One injected instruction in a lead can query Accounts and send the result out.',
201
224
  remediation: 'Break any one link: remove open-ended querying from agents that read untrusted records, require user ' +
202
- 'confirmation on every outbound action, or keep the agent that queries separate from the agent that sends.',
225
+ 'confirmation on every outbound action, remove CSP Trusted URLs whose domains you no longer control, or ' +
226
+ 'keep the agent that queries separate from the agent that sends.',
203
227
  match(_present, active) {
204
228
  const reach = byPrefixes(active, ['agent-query-reach-']);
205
- const outbound = byIds(active, ['agent-outbound-actions-unconfirmed', 'agent-outbound-actions-unverified']);
229
+ // Egress: an outbound action that needs no confirmation, or a trusted domain anyone can claim.
230
+ const outbound = [
231
+ ...byIds(active, ['agent-outbound-actions-unconfirmed', 'agent-outbound-actions-unverified']),
232
+ ...byPrefixes(active, ['trusted-url-hygiene-parked-', 'trusted-url-hygiene-unresolvable-']),
233
+ ];
206
234
  if (reach.length === 0 || outbound.length === 0)
207
235
  return null;
208
- return [...reach, ...outbound];
236
+ // Where outsider text enters, when the org shows it. Evidence only: the chain fires without
237
+ // it, since Web-to-Lead, Web-to-Case and email exist in almost every org.
238
+ const untrusted = byIds(active, [
239
+ 'inbound-email-handler-unauthenticated-execution',
240
+ 'guest-user-write-access',
241
+ 'guest-object-exposure-guest-owned',
242
+ ]);
243
+ return [...untrusted, ...reach, ...outbound];
209
244
  },
210
245
  },
211
246
  {
@@ -402,6 +437,7 @@ export const NAMED_CHAINS = [
402
437
  'portal-exposed-apex-without-sharing',
403
438
  'flows-autolaunched-without-sharing', 'flows-screen-without-sharing',
404
439
  'apex-rest-without-sharing',
440
+ 'external-account-hierarchy-super-users', 'external-account-hierarchy-active',
405
441
  ]);
406
442
  if (reach.length === 0)
407
443
  return null;
@@ -544,5 +580,57 @@ export const NAMED_CHAINS = [
544
580
  return [...vector, ...weakened, ...targets];
545
581
  },
546
582
  },
583
+ {
584
+ id: 'inbound-email-rce',
585
+ title: 'Unauthenticated inbound email to privileged code execution',
586
+ severity: 'CRITICAL',
587
+ narrative: 'An unauthenticated inbound email service address with no sender allowlist and no SPF/DKIM verification ' +
588
+ 'accepts messages from any internet sender, executing Apex logic under a privileged running user or in a class ' +
589
+ 'that bypasses CRUD/FLS and sharing. Attackers can trigger unattended data manipulation or code execution without credentials.',
590
+ remediation: 'Populate AuthorizedSenders on each email service address, set AuthenticationFailureAction to reject spoofed email, ' +
591
+ 'and ensure email handler Apex classes enforce sharing, validate input, and execute as a dedicated least-privilege user.',
592
+ match(present, active) {
593
+ if (!has(present, 'unauth-foothold', 'code-exec'))
594
+ return null;
595
+ const vector = byIds(active, ['inbound-email-handler-unauthenticated-execution']);
596
+ if (vector.length === 0)
597
+ return null;
598
+ const followOn = byIds(active, [
599
+ 'apex-crud-fls-without-sharing', 'soql-injection-risk', 'portal-exposed-apex-without-sharing',
600
+ 'flows-autolaunched-without-sharing', 'users-modify-all-data', 'users-super-admin-combo',
601
+ 'privileged-access-shadow-admins',
602
+ ]);
603
+ return followOn.length > 0 ? [...vector, ...followOn] : null;
604
+ },
605
+ },
606
+ {
607
+ id: 'platform-event-priv-esc',
608
+ title: 'Guest or low-trust platform event publish to automated process escalation',
609
+ severity: 'CRITICAL',
610
+ narrative: 'A guest or portal user publishes a custom Platform Event that triggers an Apex trigger or Flow subscriber ' +
611
+ 'executing as the Automated Process system user or an administrator. This bypasses normal user sharing, CRUD, and FLS, ' +
612
+ 'providing an unauthenticated or low-trust path to system-context privilege escalation and state tampering.',
613
+ remediation: 'Revoke Create permissions on Platform Events from guest and Experience Cloud profiles. Configure ' +
614
+ 'PlatformEventSubscriberConfig to run event triggers as a dedicated least-privilege user rather than Automated Process or an admin.',
615
+ match(present, active) {
616
+ if (!hasAny(present, 'unauth-foothold', 'low-trust-authenticated'))
617
+ return null;
618
+ if (!hasAny(present, 'priv-esc', 'data-write'))
619
+ return null;
620
+ const escalation = byIds(active, ['platform-event-subscriber-escalation']);
621
+ if (escalation.length === 0)
622
+ return null;
623
+ const foothold = byIds(active, [
624
+ 'guest-user-read-access', 'guest-user-write-access', 'guest-user-sharing-exposure', 'guest-user-baseline',
625
+ 'sharing-model-external-read', 'sharing-model-external-write', 'experience-cloud-site-self-registration',
626
+ ]);
627
+ if (foothold.length === 0)
628
+ return null;
629
+ const targets = byIds(active, [
630
+ 'users-super-admin-combo', 'users-modify-all-data', 'privileged-access-shadow-admins',
631
+ ]);
632
+ return [...foothold, ...escalation, ...targets];
633
+ },
634
+ },
547
635
  ];
548
636
  //# sourceMappingURL=namedChains.js.map
@@ -2,11 +2,13 @@ import type { SecurityCheck } from './SecurityCheck.js';
2
2
  import type { AuditContext } from '@cclabsnz/sf-core';
3
3
  import type { AuditResult } from '../findings/AuditResult.js';
4
4
  import type { ScoringConfig } from '../findings/ScoringConfig.js';
5
+ import type { WaiverLoader } from '../waivers/WaiverLoader.js';
5
6
  export declare class CheckEngine {
6
7
  private readonly checks;
7
8
  private readonly ctx;
8
9
  private readonly scoringConfig?;
9
- constructor(checks: SecurityCheck[], ctx: AuditContext, scoringConfig?: ScoringConfig | undefined);
10
+ private readonly waiverLoader?;
11
+ constructor(checks: SecurityCheck[], ctx: AuditContext, scoringConfig?: ScoringConfig | undefined, waiverLoader?: WaiverLoader | undefined);
10
12
  run(onProgress?: (current: number, total: number, checkName: string) => void): Promise<AuditResult>;
11
13
  private validateCacheOrdering;
12
14
  }