@cclabsnz/sf-audit 1.15.1 → 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 (119) hide show
  1. package/CHANGELOG.md +143 -1
  2. package/README.md +100 -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 +110 -3
  19. package/lib/checks/CheckEngine.d.ts +3 -1
  20. package/lib/checks/CheckEngine.js +11 -3
  21. package/lib/checks/impl/AgentInventoryCheck.js +8 -3
  22. package/lib/checks/impl/AgentOutboundActionsCheck.d.ts +13 -0
  23. package/lib/checks/impl/AgentOutboundActionsCheck.js +155 -0
  24. package/lib/checks/impl/AgentQueryReachCheck.d.ts +11 -0
  25. package/lib/checks/impl/AgentQueryReachCheck.js +88 -0
  26. package/lib/checks/impl/ApexCrudFLSCheck.js +45 -10
  27. package/lib/checks/impl/ApexSharingCheck.js +16 -25
  28. package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.d.ts +10 -0
  29. package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.js +131 -0
  30. package/lib/checks/impl/ConnectedAppsCheck.js +47 -1
  31. package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.d.ts +10 -0
  32. package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.js +116 -0
  33. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.d.ts +10 -0
  34. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.js +75 -0
  35. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.d.ts +10 -0
  36. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.js +98 -0
  37. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.d.ts +10 -0
  38. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.js +73 -0
  39. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.d.ts +10 -0
  40. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.js +115 -0
  41. package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.d.ts +10 -0
  42. package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.js +227 -0
  43. package/lib/checks/impl/GuestExecutableApexCheck.d.ts +1 -1
  44. package/lib/checks/impl/GuestExecutableApexCheck.js +105 -14
  45. package/lib/checks/impl/HardcodedCredentialsCheck.js +7 -2
  46. package/lib/checks/impl/InboundEmailHandlerExposureCheck.d.ts +10 -0
  47. package/lib/checks/impl/InboundEmailHandlerExposureCheck.js +136 -0
  48. package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.d.ts +10 -0
  49. package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.js +84 -0
  50. package/lib/checks/impl/OrgWideEmailSpoofingCheck.d.ts +10 -0
  51. package/lib/checks/impl/OrgWideEmailSpoofingCheck.js +106 -0
  52. package/lib/checks/impl/PackagePostInstallSupplyChainCheck.d.ts +10 -0
  53. package/lib/checks/impl/PackagePostInstallSupplyChainCheck.js +89 -0
  54. package/lib/checks/impl/PlatformEventSubscriberContextCheck.d.ts +10 -0
  55. package/lib/checks/impl/PlatformEventSubscriberContextCheck.js +84 -0
  56. package/lib/checks/impl/RestrictionRulesIntegrityCheck.d.ts +10 -0
  57. package/lib/checks/impl/RestrictionRulesIntegrityCheck.js +105 -0
  58. package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.d.ts +10 -0
  59. package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.js +90 -0
  60. package/lib/checks/registry.js +34 -0
  61. package/lib/checks/support/agentGraph.d.ts +49 -0
  62. package/lib/checks/support/agentGraph.js +87 -0
  63. package/lib/checks/support/apexAccess.d.ts +56 -0
  64. package/lib/checks/support/apexAccess.js +127 -0
  65. package/lib/checks/support/missingObject.d.ts +13 -0
  66. package/lib/checks/support/missingObject.js +35 -0
  67. package/lib/commands/audit/apps.d.ts +1 -0
  68. package/lib/commands/audit/apps.js +83 -29
  69. package/lib/commands/audit/diff.js +2 -2
  70. package/lib/commands/audit/history.js +2 -2
  71. package/lib/commands/audit/incident/report.js +2 -2
  72. package/lib/commands/audit/security.d.ts +3 -0
  73. package/lib/commands/audit/security.js +58 -9
  74. package/lib/commands/audit/timeline.js +2 -2
  75. package/lib/compliance/mapping.js +35 -7
  76. package/lib/findings/AuditResult.d.ts +8 -0
  77. package/lib/findings/CheckMeta.js +17 -0
  78. package/lib/findings/Finding.d.ts +4 -0
  79. package/lib/findings/ScoringConfig.d.ts +10 -8
  80. package/lib/findings/ScoringConfig.js +12 -5
  81. package/lib/findings/coverage.d.ts +28 -0
  82. package/lib/findings/coverage.js +30 -0
  83. package/lib/findings/exitCode.js +1 -1
  84. package/lib/findings/loadScoringConfig.js +51 -8
  85. package/lib/findings/scoring.js +14 -5
  86. package/lib/history/HistoryStore.js +9 -3
  87. package/lib/history/archivePolicy.d.ts +19 -0
  88. package/lib/history/archivePolicy.js +34 -0
  89. package/lib/incident/bundleIo.js +4 -3
  90. package/lib/incident/collect/collectBundle.d.ts +1 -1
  91. package/lib/incident/collect/collectBundle.js +4 -3
  92. package/lib/incident/collect/streamGuestLogs.d.ts +1 -1
  93. package/lib/incident/collect/streamGuestLogs.js +3 -2
  94. package/lib/incident/csv.js +4 -4
  95. package/lib/incident/render/evidence.js +3 -3
  96. package/lib/incident/render/html.js +2 -3
  97. package/lib/index.d.ts +2 -0
  98. package/lib/index.js +2 -0
  99. package/lib/lib/packageInfo.d.ts +6 -0
  100. package/lib/lib/packageInfo.js +19 -0
  101. package/lib/renderers/AttackChainDagRenderer.d.ts +7 -0
  102. package/lib/renderers/AttackChainDagRenderer.js +139 -0
  103. package/lib/renderers/ClientReportRenderer.d.ts +2 -0
  104. package/lib/renderers/ClientReportRenderer.js +34 -6
  105. package/lib/renderers/DiffHtmlRenderer.js +2 -7
  106. package/lib/renderers/HistoryRenderer.js +19 -11
  107. package/lib/renderers/HtmlRenderer.js +19 -6
  108. package/lib/renderers/MarkdownRenderer.js +7 -0
  109. package/lib/renderers/SarifRenderer.d.ts +43 -0
  110. package/lib/renderers/SarifRenderer.js +250 -0
  111. package/lib/report/ExecutivePriorities.js +1 -1
  112. package/lib/report/RemediationRoadmap.js +1 -1
  113. package/lib/waivers/WaiverLoader.d.ts +28 -0
  114. package/lib/waivers/WaiverLoader.js +103 -0
  115. package/lib/waivers/WaiverModel.d.ts +32 -0
  116. package/lib/waivers/WaiverModel.js +28 -0
  117. package/lib/waivers/applyWaivers.d.ts +22 -0
  118. package/lib/waivers/applyWaivers.js +85 -0
  119. package/package.json +3 -3
@@ -0,0 +1,75 @@
1
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ export const API_LOG_TYPES = ['RestApi', 'BulkApi2', 'GraphQlQueryExecution', 'AuraRequest'];
5
+ /** Thrown when the EventLogFile listing itself fails: there is no usage to analyze at all. */
6
+ export class ApiLogListingError extends Error {
7
+ permission;
8
+ constructor(message, permission) {
9
+ super(message);
10
+ this.permission = permission;
11
+ this.name = 'ApiLogListingError';
12
+ }
13
+ }
14
+ /**
15
+ * Lists and downloads the API EventLogFiles for the last `since` days. Read-only: one SOQL query and
16
+ * one REST GET per file. A failed listing throws (an empty result would read as "no usage"); a failed
17
+ * download is recorded in `failed` so the caller can flag the analysis as incomplete.
18
+ */
19
+ export async function downloadApiLogs(deps, since) {
20
+ const csv = { RestApi: '', BulkApi2: '', GraphQlQueryExecution: '', AuraRequest: '' };
21
+ let rows;
22
+ try {
23
+ rows = await deps.soql.queryAll(`SELECT Id, EventType FROM EventLogFile WHERE EventType IN (${API_LOG_TYPES.map((t) => `'${t}'`).join(', ')}) ` +
24
+ `AND LogDate = LAST_N_DAYS:${since} ORDER BY LogDate DESC`);
25
+ }
26
+ catch (e) {
27
+ const msg = e instanceof Error ? e.message : String(e);
28
+ const permission = /INSUFFICIENT_ACCESS|HTTP 403|INVALID_TYPE|not supported/i.test(msg);
29
+ throw new ApiLogListingError(permission
30
+ ? `Cannot list API event logs: EventLogFile is not readable (the running user needs View Event Log Files, and the org needs Event Monitoring). ${msg}`
31
+ : `Cannot list API event logs: ${msg}`, permission);
32
+ }
33
+ const failed = [];
34
+ if (rows.length === 0)
35
+ return { csv, listed: 0, failed };
36
+ // A private (0700) temp dir: raw logs hold org data and must not sit at a predictable shared path.
37
+ const dir = mkdtempSync(join(tmpdir(), 'sfaudit-apps-'));
38
+ try {
39
+ for (const r of rows) {
40
+ const tmp = join(dir, `${r.Id}.csv`);
41
+ try {
42
+ await deps.rest.getRawToFile(`/sobjects/EventLogFile/${r.Id}/LogFile`, tmp);
43
+ const content = readFileSync(tmp, 'utf-8');
44
+ if (API_LOG_TYPES.includes(r.EventType)) {
45
+ csv[r.EventType] += '\n' + content;
46
+ }
47
+ }
48
+ catch (e) {
49
+ failed.push({ id: r.Id, eventType: r.EventType, error: e instanceof Error ? e.message : String(e) });
50
+ }
51
+ finally {
52
+ rmSync(tmp, { force: true });
53
+ }
54
+ }
55
+ }
56
+ finally {
57
+ rmSync(dir, { recursive: true, force: true });
58
+ }
59
+ return { csv, listed: rows.length, failed };
60
+ }
61
+ /** Decides whether downloaded logs are complete, partial, or unusable. Never treats a failure as "no usage". */
62
+ export function assessLogCoverage(logs, since) {
63
+ if (logs.listed === 0)
64
+ return { empty: `No API EventLogFiles in the last ${since} day(s): there is no usage to compare against grants.` };
65
+ if (logs.failed.length === logs.listed) {
66
+ return {
67
+ fatal: `None of the ${logs.listed} API log file(s) could be downloaded (first error: ${logs.failed[0].error}). ` +
68
+ 'Refusing to report usage from no data.',
69
+ };
70
+ }
71
+ if (logs.failed.length > 0)
72
+ return { incomplete: `${logs.failed.length} of ${logs.listed} API log file(s) could not be downloaded` };
73
+ return {};
74
+ }
75
+ //# sourceMappingURL=apiLogSource.js.map
@@ -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) {