@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
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class PlatformEventSubscriberContextCheck implements SecurityCheck {
4
+ readonly id = "platform-event-subscriber-context";
5
+ readonly name = "Platform Event Subscriber Context & Privilege Escalation";
6
+ readonly category = "Code Security";
7
+ readonly description = "Detects Platform Event subscribers executing in system context or as Admin while low-trust or guest users hold Publish permissions.";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=PlatformEventSubscriberContextCheck.d.ts.map
@@ -0,0 +1,84 @@
1
+ export class PlatformEventSubscriberContextCheck {
2
+ id = 'platform-event-subscriber-context';
3
+ name = 'Platform Event Subscriber Context & Privilege Escalation';
4
+ category = 'Code Security';
5
+ description = 'Detects Platform Event subscribers executing in system context or as Admin while low-trust or guest users hold Publish permissions.';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ const baseUrl = ctx.orgInfo.instanceUrl;
9
+ // ApexTrigger exists in every org, so a failure here is never "feature absent". It propagates
10
+ // and CheckEngine reports the check as inconclusive.
11
+ const triggers = await ctx.tooling.query("SELECT Id, Name, TableEnumOrId, Status FROM ApexTrigger WHERE Status = 'Active'");
12
+ // TableEnumOrId holds a standard object's name, but a custom object's (and so every custom
13
+ // platform event's) 01I Id. Resolve Ids to API names before testing for the __e suffix.
14
+ const ids = [...new Set(triggers.map((t) => t.TableEnumOrId).filter((v) => !v.includes('_') && v.startsWith('01I')))];
15
+ const nameById = new Map();
16
+ if (ids.length > 0) {
17
+ const defs = await ctx.tooling.query(`SELECT DurableId, QualifiedApiName FROM EntityDefinition WHERE DurableId IN (${ids.map((i) => `'${i.slice(0, 15)}'`).join(', ')})`);
18
+ for (const d of defs)
19
+ nameById.set(d.DurableId.slice(0, 15), d.QualifiedApiName);
20
+ }
21
+ const objectName = (t) => nameById.get(t.TableEnumOrId.slice(0, 15)) ?? t.TableEnumOrId;
22
+ const eventTriggers = triggers.filter((t) => objectName(t).endsWith('__e'));
23
+ if (eventTriggers.length === 0) {
24
+ findings.push({
25
+ id: 'platform-event-subscriber-context-ok',
26
+ category: this.category,
27
+ riskLevel: 'LOW',
28
+ passed: true,
29
+ title: 'No active triggers on custom Platform Events identified',
30
+ detail: 'Zero active Apex triggers subscribe to custom Platform Event objects (__e).',
31
+ remediation: 'When subscribing to Platform Events, ensure publish permissions are strictly scoped to internal authorized actors.',
32
+ });
33
+ return { findings };
34
+ }
35
+ // Low-trust profiles (guest, portal, Experience Cloud) holding Create on a subscribed event.
36
+ // ObjectPermissions.ParentId is a PermissionSet Id, so each profile is reached through the
37
+ // permission set it owns.
38
+ const eventObjectNames = new Set(eventTriggers.map(objectName));
39
+ const lowTrustProfilesWithCreate = [];
40
+ const profiles = await ctx.soql.queryAll("SELECT Id, Name, UserType FROM Profile WHERE UserType IN ('Guest', 'CspLitePortal', 'PowerPartner', 'CustomerSuccess', 'PowerCustomerSuccess')");
41
+ if (profiles.length > 0) {
42
+ const profileNameById = new Map(profiles.map((p) => [p.Id, p.Name]));
43
+ const owned = await ctx.soql.queryAll(`SELECT Id, ProfileId FROM PermissionSet WHERE IsOwnedByProfile = true AND ProfileId IN (${profiles.map((p) => `'${p.Id}'`).join(', ')})`);
44
+ const profileByPermSet = new Map(owned.map((ps) => [ps.Id, ps.ProfileId]));
45
+ const objectPerms = await ctx.soql.queryAll("SELECT Id, ParentId, SobjectType, PermissionsCreate FROM ObjectPermissions WHERE PermissionsCreate = true AND SobjectType LIKE '%__e'");
46
+ for (const op of objectPerms) {
47
+ const profileId = profileByPermSet.get(op.ParentId);
48
+ if (profileId && eventObjectNames.has(op.SobjectType)) {
49
+ lowTrustProfilesWithCreate.push(`${op.SobjectType} (${profileNameById.get(profileId) ?? profileId})`);
50
+ }
51
+ }
52
+ }
53
+ // If low-trust profiles have Create permission on any custom platform event subscribed to by Apex:
54
+ // This is an unauthenticated or portal-to-system privilege escalation bridge!
55
+ if (lowTrustProfilesWithCreate.length > 0) {
56
+ findings.push({
57
+ id: 'platform-event-subscriber-escalation',
58
+ category: this.category,
59
+ riskLevel: 'CRITICAL',
60
+ title: `${lowTrustProfilesWithCreate.length} Platform Event(s) publishable by low-trust users trigger system-mode subscribers`,
61
+ detail: 'Guest or Experience Cloud profiles hold Create (publish) permissions on custom Platform Events that have active Apex subscribers. By default, Platform Event triggers execute under the Automated Process system identity (bypassing user permissions and sharing), creating an unauthenticated-to-system-context privilege escalation bridge.',
62
+ remediation: 'Revoke Create permissions on Platform Events from guest and portal profiles, or configure PlatformEventSubscriberConfig to run subscribers as a dedicated, least-privileged service account with explicit input validation.',
63
+ affectedItems: lowTrustProfilesWithCreate.map((item) => ({
64
+ label: item,
65
+ url: `${baseUrl}/lightning/setup/EventObjects/home`,
66
+ note: 'Event publishable by low-trust actor executes as Automated Process or Admin',
67
+ })),
68
+ });
69
+ }
70
+ else {
71
+ findings.push({
72
+ id: 'platform-event-subscriber-context-ok',
73
+ category: this.category,
74
+ riskLevel: 'LOW',
75
+ passed: true,
76
+ title: 'Platform Event subscriber triggers are protected from low-trust publish escalation',
77
+ detail: `${eventTriggers.length} active Platform Event trigger(s) inspected; no guest or portal profiles hold Publish permissions on subscribed events.`,
78
+ remediation: 'Ensure low-trust profiles never receive Create permissions on custom Platform Events that execute privileged backend logic.',
79
+ });
80
+ }
81
+ return { findings };
82
+ }
83
+ }
84
+ //# sourceMappingURL=PlatformEventSubscriberContextCheck.js.map
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class RestrictionRulesIntegrityCheck implements SecurityCheck {
4
+ readonly id = "restriction-rules-integrity";
5
+ readonly name = "Restriction Rules Integrity & Conflict Detection";
6
+ readonly category = "Data Security";
7
+ readonly description = "Detects inactive or conflicting Restriction Rules on sensitive standard and custom objects.";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=RestrictionRulesIntegrityCheck.d.ts.map
@@ -0,0 +1,105 @@
1
+ import { isMissingObjectError } from '../support/missingObject.js';
2
+ export class RestrictionRulesIntegrityCheck {
3
+ id = 'restriction-rules-integrity';
4
+ name = 'Restriction Rules Integrity & Conflict Detection';
5
+ category = 'Data Security';
6
+ description = 'Detects inactive or conflicting Restriction Rules on sensitive standard and custom objects.';
7
+ async run(ctx) {
8
+ const findings = [];
9
+ const baseUrl = ctx.orgInfo.instanceUrl;
10
+ const rulesUrl = `${baseUrl}/lightning/setup/ObjectManager/home`;
11
+ let rules = [];
12
+ try {
13
+ rules = await ctx.tooling.query('SELECT Id, TargetEntity, Active, EnforcementType FROM RestrictionRule');
14
+ }
15
+ catch (err) {
16
+ if (isMissingObjectError(err)) {
17
+ findings.push({
18
+ id: 'restriction-rules-integrity-ok',
19
+ category: this.category,
20
+ riskLevel: 'LOW',
21
+ passed: true,
22
+ title: 'Restriction Rules are not enabled or no rules configured',
23
+ detail: 'RestrictionRule tooling object is not accessible or not in use.',
24
+ remediation: 'No action required.',
25
+ });
26
+ return { findings };
27
+ }
28
+ findings.push({
29
+ id: 'restriction-rules-integrity-inaccessible',
30
+ category: this.category,
31
+ riskLevel: 'INFO',
32
+ inconclusive: true,
33
+ title: 'Restriction Rules could not be queried',
34
+ detail: `Failed to query RestrictionRule: ${err instanceof Error ? err.message : String(err)}`,
35
+ remediation: 'Grant the audit user "View Setup and Configuration" and Tooling API access.',
36
+ });
37
+ return { findings };
38
+ }
39
+ if (rules.length === 0) {
40
+ findings.push({
41
+ id: 'restriction-rules-integrity-ok',
42
+ category: this.category,
43
+ riskLevel: 'LOW',
44
+ passed: true,
45
+ title: 'No Restriction Rules configured',
46
+ detail: 'Zero RestrictionRule records configured across standard and custom objects.',
47
+ remediation: 'When deploying Restriction Rules, ensure they remain active and avoid multiple conflicting rules on the same entity.',
48
+ });
49
+ return { findings };
50
+ }
51
+ // 1. Check for inactive restriction rules
52
+ const inactiveRules = rules.filter((r) => r.Active === false);
53
+ if (inactiveRules.length > 0) {
54
+ findings.push({
55
+ id: 'restriction-rules-inactive',
56
+ category: this.category,
57
+ riskLevel: 'HIGH',
58
+ title: `${inactiveRules.length} inactive Restriction Rule(s) detected`,
59
+ detail: 'Inactive Restriction Rules (often disabled temporarily during testing or maintenance and forgotten) leave the underlying object protected only by Org-Wide Defaults. If the object OWD is Public Read/Write or Public Read Only, deactivating the Restriction Rule immediately and silently exposes the entire table to all users.',
60
+ remediation: 'Re-activate necessary Restriction Rules or delete obsolete rules to prevent false assumptions of record isolation.',
61
+ affectedItems: inactiveRules.map((r) => ({
62
+ label: `${r.TargetEntity}: ${r.MasterLabel || r.Name || r.Id}`,
63
+ url: rulesUrl,
64
+ note: 'Restriction Rule is INACTIVE',
65
+ })),
66
+ });
67
+ }
68
+ // 2. Check for multiple active rules on the same TargetEntity (Salesforce anti-pattern)
69
+ const activeRulesByEntity = new Map();
70
+ for (const r of rules.filter((r) => r.Active === true)) {
71
+ const list = activeRulesByEntity.get(r.TargetEntity) ?? [];
72
+ list.push(r);
73
+ activeRulesByEntity.set(r.TargetEntity, list);
74
+ }
75
+ const conflictingEntities = [...activeRulesByEntity.entries()].filter(([, entityRules]) => entityRules.length > 1);
76
+ if (conflictingEntities.length > 0) {
77
+ findings.push({
78
+ id: 'restriction-rules-conflicting',
79
+ category: this.category,
80
+ riskLevel: 'HIGH',
81
+ title: `${conflictingEntities.length} object(s) have multiple active Restriction Rules (conflicting evaluation)`,
82
+ detail: 'Salesforce Restriction Rules evaluate with first-match / OR logic across multiple rules. Defining multiple active restriction rules on the same object creates non-deterministic or overly broad access where a user matching any one rule gains visibility, breaking least-privilege scoping.',
83
+ remediation: 'Consolidate multiple Restriction Rules per entity into a single unified rule with clear record and user criteria.',
84
+ affectedItems: conflictingEntities.map(([entity, entityRules]) => ({
85
+ label: `${entity} (${entityRules.length} active rules)`,
86
+ url: rulesUrl,
87
+ note: `Multiple rules: ${entityRules.map((r) => r.MasterLabel || r.Name || r.Id).join(', ')}`,
88
+ })),
89
+ });
90
+ }
91
+ if (inactiveRules.length === 0 && conflictingEntities.length === 0) {
92
+ findings.push({
93
+ id: 'restriction-rules-integrity-ok',
94
+ category: this.category,
95
+ riskLevel: 'LOW',
96
+ passed: true,
97
+ title: 'All Restriction Rules are active with single-rule entity isolation',
98
+ detail: `${rules.length} Restriction Rule(s) inspected; all rules are active and no entity-level rule conflicts detected.`,
99
+ remediation: 'Maintain single active restriction rules per object.',
100
+ });
101
+ }
102
+ return { findings };
103
+ }
104
+ }
105
+ //# sourceMappingURL=RestrictionRulesIntegrityCheck.js.map
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class ShieldTenantSecretLifecycleCheck implements SecurityCheck {
4
+ readonly id = "shield-tenant-secret-lifecycle";
5
+ readonly name = "Shield Platform Encryption Tenant Secret Lifecycle";
6
+ readonly category = "Data Security";
7
+ readonly description = "Monitors Shield TenantSecret rotation frequency (>365 days) and destroyed key status for cryptographic compliance.";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=ShieldTenantSecretLifecycleCheck.d.ts.map
@@ -0,0 +1,90 @@
1
+ import { isMissingObjectError } from '../support/missingObject.js';
2
+ export class ShieldTenantSecretLifecycleCheck {
3
+ id = 'shield-tenant-secret-lifecycle';
4
+ name = 'Shield Platform Encryption Tenant Secret Lifecycle';
5
+ category = 'Data Security';
6
+ description = 'Monitors Shield TenantSecret rotation frequency (>365 days) and destroyed key status for cryptographic compliance.';
7
+ async run(ctx) {
8
+ const findings = [];
9
+ const baseUrl = ctx.orgInfo.instanceUrl;
10
+ const keyMgmtUrl = `${baseUrl}/lightning/setup/PlatformEncryptionKeyManagement/home`;
11
+ let secrets = [];
12
+ try {
13
+ secrets = await ctx.soql.queryAll('SELECT Id, Status, Type, Version, CreatedDate FROM TenantSecret');
14
+ }
15
+ catch (err) {
16
+ if (isMissingObjectError(err)) {
17
+ findings.push({
18
+ id: 'shield-tenant-secret-not-enabled',
19
+ category: this.category,
20
+ riskLevel: 'LOW',
21
+ passed: true,
22
+ title: 'Shield Platform Encryption is not enabled or TenantSecret is not accessible',
23
+ detail: 'TenantSecret object is not available; Shield Platform Encryption is not licensed or enabled.',
24
+ remediation: 'No action required if Shield Platform Encryption is not in use.',
25
+ });
26
+ return { findings };
27
+ }
28
+ findings.push({
29
+ id: 'shield-tenant-secret-inaccessible',
30
+ category: this.category,
31
+ riskLevel: 'INFO',
32
+ inconclusive: true,
33
+ title: 'TenantSecret could not be queried',
34
+ detail: `Failed to query TenantSecret: ${err instanceof Error ? err.message : String(err)}`,
35
+ remediation: 'Grant the audit user "Manage Encryption Keys" or "View Setup and Configuration".',
36
+ });
37
+ return { findings };
38
+ }
39
+ if (secrets.length === 0) {
40
+ findings.push({
41
+ id: 'shield-tenant-secret-ok',
42
+ category: this.category,
43
+ riskLevel: 'LOW',
44
+ passed: true,
45
+ title: 'No active Shield TenantSecret keys generated',
46
+ detail: 'Zero TenantSecret records were returned.',
47
+ remediation: 'Generate tenant encryption secrets if Shield Platform Encryption is enabled.',
48
+ });
49
+ return { findings };
50
+ }
51
+ const now = Date.now();
52
+ const ONE_YEAR_MS = 365 * 24 * 60 * 60 * 1000;
53
+ const activeSecrets = secrets.filter((s) => s.Status.toLowerCase() === 'active');
54
+ const unrotatedSecrets = [];
55
+ for (const secret of activeSecrets) {
56
+ const createdTime = new Date(secret.CreatedDate).getTime();
57
+ if (now - createdTime > ONE_YEAR_MS) {
58
+ unrotatedSecrets.push(secret);
59
+ }
60
+ }
61
+ if (unrotatedSecrets.length > 0) {
62
+ findings.push({
63
+ id: 'shield-tenant-secret-unrotated',
64
+ category: this.category,
65
+ riskLevel: 'MEDIUM',
66
+ title: `${unrotatedSecrets.length} active Shield Tenant Secret(s) have not been rotated in >365 days`,
67
+ detail: 'Active Shield tenant encryption keys (Data, SearchIndex, EventBus) have exceeded the 365-day rotation window. Cryptographic key lifecycle standards (ISO/IEC 27001:2022 A.8.24, NZISM 17.2, HISO 10029) require cryptographic keys to be rotated at least annually to minimize key exposure and compromise blast radius.',
68
+ remediation: 'Generate a new Tenant Secret in Setup → Platform Encryption → Key Management and re-encrypt affected archive data if required by corporate compliance policies.',
69
+ affectedItems: unrotatedSecrets.map((s) => ({
70
+ label: `Type: ${s.Type || 'Data'}, Version: ${s.Version ?? 'N/A'}`,
71
+ url: keyMgmtUrl,
72
+ note: `Created on ${new Date(s.CreatedDate).toISOString().slice(0, 10)} (>365 days active)`,
73
+ })),
74
+ });
75
+ }
76
+ else {
77
+ findings.push({
78
+ id: 'shield-tenant-secret-ok',
79
+ category: this.category,
80
+ riskLevel: 'LOW',
81
+ passed: true,
82
+ title: 'Active Shield Tenant Secrets are rotated within cryptographic lifecycle standards',
83
+ detail: `${activeSecrets.length} active Tenant Secret(s) verified; all active keys were created or rotated within the last 365 days.`,
84
+ remediation: 'Continue regular annual tenant secret key rotation.',
85
+ });
86
+ }
87
+ return { findings };
88
+ }
89
+ }
90
+ //# sourceMappingURL=ShieldTenantSecretLifecycleCheck.js.map
@@ -101,6 +101,21 @@ import { AgentMonitoringCoverageCheck } from './impl/AgentMonitoringCoverageChec
101
101
  import { AgentQueryReachCheck } from './impl/AgentQueryReachCheck.js';
102
102
  import { AgentOutboundActionsCheck } from './impl/AgentOutboundActionsCheck.js';
103
103
  import { TrustedUrlHygieneCheck } from './impl/TrustedUrlHygieneCheck.js';
104
+ // 14 New Checks & Attack Chains
105
+ import { GenAiPromptTemplateGroundingCheck } from './impl/GenAiPromptTemplateGroundingCheck.js';
106
+ import { DataCloudDataSpaceIsolationCheck } from './impl/DataCloudDataSpaceIsolationCheck.js';
107
+ import { PlatformEventSubscriberContextCheck } from './impl/PlatformEventSubscriberContextCheck.js';
108
+ import { FlowHttpCalloutCredentialBypassCheck } from './impl/FlowHttpCalloutCredentialBypassCheck.js';
109
+ import { OauthDeviceAndAssetTokenFlowsCheck } from './impl/OauthDeviceAndAssetTokenFlowsCheck.js';
110
+ import { DelegatedAuthenticationExposureCheck } from './impl/DelegatedAuthenticationExposureCheck.js';
111
+ import { DelegatedAdministrationGroupsCheck } from './impl/DelegatedAdministrationGroupsCheck.js';
112
+ import { AuthProviderRegistrationHandlerCheck } from './impl/AuthProviderRegistrationHandlerCheck.js';
113
+ import { InboundEmailHandlerExposureCheck } from './impl/InboundEmailHandlerExposureCheck.js';
114
+ import { OrgWideEmailSpoofingCheck } from './impl/OrgWideEmailSpoofingCheck.js';
115
+ import { ExternalAccountHierarchyExposureCheck } from './impl/ExternalAccountHierarchyExposureCheck.js';
116
+ import { RestrictionRulesIntegrityCheck } from './impl/RestrictionRulesIntegrityCheck.js';
117
+ import { PackagePostInstallSupplyChainCheck } from './impl/PackagePostInstallSupplyChainCheck.js';
118
+ import { ShieldTenantSecretLifecycleCheck } from './impl/ShieldTenantSecretLifecycleCheck.js';
104
119
  // Order matters: a check's dependsOnCache must be satisfied by a preceding check's populatesCache.
105
120
  // CheckEngine.validateCacheOrdering() enforces this at startup.
106
121
  export const CHECKS = [
@@ -178,6 +193,21 @@ export const CHECKS = [
178
193
  new ExperienceCspCheck(), // Experience Cloud CSP / Lightning Web Security advisory
179
194
  new SandboxDataMaskingCheck(), // sandbox with populated (likely unmasked) PII
180
195
  new PrivilegedAccessCheck(), // writes: effectivePermissions; shadow-admin detection
196
+ // 14 New Checks across 5 Salesforce surfaces
197
+ new GenAiPromptTemplateGroundingCheck(), // Tooling: GenAiPromptTemplate (AI & Agents)
198
+ new DataCloudDataSpaceIsolationCheck(), // SOQL: DataSpace, DataShareTarget (Data Access & Sharing)
199
+ new PlatformEventSubscriberContextCheck(), // Tooling: PlatformEventSubscriberConfig (Apex & Code Security)
200
+ new FlowHttpCalloutCredentialBypassCheck(), // Tooling: Flow, ExternalServiceRegistration (Apex & Code Security)
201
+ new OauthDeviceAndAssetTokenFlowsCheck(), // Metadata: OauthOidcSettings (Identity & Authentication)
202
+ new DelegatedAuthenticationExposureCheck(), // Metadata: SecuritySettings (Identity & Authentication)
203
+ new DelegatedAdministrationGroupsCheck(), // SOQL: DelegateGroup (Users, Permissions & Privilege)
204
+ new AuthProviderRegistrationHandlerCheck(), // SOQL: AuthProvider, ApexClass (Identity & Authentication)
205
+ new InboundEmailHandlerExposureCheck(), // SOQL: EmailServicesFunction (Integrations)
206
+ new OrgWideEmailSpoofingCheck(), // SOQL: OrgWideEmailAddress, DkimKey (Integrations)
207
+ new ExternalAccountHierarchyExposureCheck(), // SOQL: User.IsPrmSuperUser (Guest & External-Facing Access)
208
+ new RestrictionRulesIntegrityCheck(), // Tooling: RestrictionRule (Data Access & Sharing)
209
+ new PackagePostInstallSupplyChainCheck(), // Tooling: InstalledSubscriberPackage (Integrations)
210
+ new ShieldTenantSecretLifecycleCheck(), // SOQL: TenantSecret (Data Access & Sharing)
181
211
  // AI & Agents block (v1.5) — Agentforce / GenAI. AgentInventoryCheck writes agentInventory,
182
212
  // agentUsers, agentAccess; the Phase 2 dependent checks are registered after it.
183
213
  new AgentInventoryCheck(), // writes: agentInventory, agentUsers, agentAccess
@@ -0,0 +1,56 @@
1
+ /**
2
+ * How an Apex class's record sharing and CRUD/FLS are controlled (spec/apex-access-mode.md).
3
+ *
4
+ * Record sharing follows the class's own sharing keyword. WITH SYSTEM_MODE and
5
+ * AccessLevel.SYSTEM_MODE switch off only CRUD/FLS for the operation they are on. A class with no
6
+ * keyword runs with its caller's sharing, and as an entry point (Aura, REST, guest) without it.
7
+ */
8
+ export type SharingKeyword = 'with' | 'without' | 'inherited' | 'none';
9
+ export declare const SYSTEM_MODE: RegExp;
10
+ /**
11
+ * The body with comments removed. A class's keywords and access modes are read from code only:
12
+ * a `without sharing` class with "with sharing" in a comment must not read as protected.
13
+ * String literals are kept (dynamic SOQL carries WITH SYSTEM_MODE inside one), and scanned past
14
+ * correctly, so `@RestResource(urlMapping='/x/*')` does not open a comment.
15
+ */
16
+ export declare function apexCode(body: string): string;
17
+ /** The code with string literals blanked, for matching declarations and enforcement that must not hide in text. */
18
+ export declare function codeWithoutStrings(body: string): string;
19
+ interface ClassDeclaration {
20
+ name: string;
21
+ /** The modifiers before `class`, from the previous statement or block boundary. */
22
+ modifiers: string;
23
+ /** The parent class named by `extends`, if any. */
24
+ parent?: string;
25
+ }
26
+ /**
27
+ * Every class declared in the body, outer and inner, found with literal patterns in one linear
28
+ * pass (a regex built around the name backtracked badly on long runs of words).
29
+ */
30
+ export declare function classDeclarations(body: string): ClassDeclaration[];
31
+ /**
32
+ * The sharing keyword on the declaration of `className` itself, or null when the body declares no
33
+ * class of that name (an interface, enum or trigger). Modifiers may sit on either side of the
34
+ * keyword (`public virtual without sharing class`, `global with sharing virtual class`).
35
+ */
36
+ export declare function sharingKeyword(className: string, body: string): SharingKeyword | null;
37
+ /** The class `className` extends, as written in its declaration (namespace and outer class stripped). */
38
+ export declare function parentClass(className: string, body: string): string | undefined;
39
+ /**
40
+ * The sharing a class actually runs with. A class with no keyword takes its parent's when it
41
+ * extends one: Apex classes inherit the sharing setting of the class they extend (spec MN-001).
42
+ * `lookup` returns a class body by name; unknown parents leave the keyword as declared.
43
+ */
44
+ export declare function effectiveSharing(className: string, body: string, lookup: (name: string) => string | undefined): SharingKeyword | null;
45
+ /** Whether the class's code (not its comments) uses SYSTEM_MODE anywhere. */
46
+ export declare function usesSystemMode(body: string): boolean;
47
+ /**
48
+ * Whether any class declared in the body, outer or inner, is `without sharing`. An inner class
49
+ * keeps its own keyword, so a `with sharing` class can still run queries without sharing through
50
+ * one (spec MN-002).
51
+ */
52
+ export declare function declaresWithoutSharing(body: string): boolean;
53
+ export declare const DML_AS_SYSTEM: RegExp;
54
+ export declare const DML_AS_USER: RegExp;
55
+ export {};
56
+ //# sourceMappingURL=apexAccess.d.ts.map
@@ -0,0 +1,127 @@
1
+ import { testApexPattern } from '@cclabsnz/sf-core';
2
+ export const SYSTEM_MODE = /\bWITH\s+SYSTEM_MODE\b|\bAccessLevel\s*\.\s*SYSTEM_MODE\b/i;
3
+ /**
4
+ * The body with comments removed. A class's keywords and access modes are read from code only:
5
+ * a `without sharing` class with "with sharing" in a comment must not read as protected.
6
+ * String literals are kept (dynamic SOQL carries WITH SYSTEM_MODE inside one), and scanned past
7
+ * correctly, so `@RestResource(urlMapping='/x/*')` does not open a comment.
8
+ */
9
+ export function apexCode(body) {
10
+ let out = '';
11
+ let i = 0;
12
+ while (i < body.length) {
13
+ const c = body[i];
14
+ const next = body[i + 1];
15
+ if (c === "'") {
16
+ let j = i + 1;
17
+ while (j < body.length && body[j] !== "'" && body[j] !== '\n')
18
+ j += body[j] === '\\' ? 2 : 1;
19
+ out += body.slice(i, j + 1);
20
+ i = j + 1;
21
+ }
22
+ else if (c === '/' && next === '/') {
23
+ while (i < body.length && body[i] !== '\n')
24
+ i++;
25
+ }
26
+ else if (c === '/' && next === '*') {
27
+ const end = body.indexOf('*/', i + 2);
28
+ out += ' ';
29
+ i = end === -1 ? body.length : end + 2;
30
+ }
31
+ else {
32
+ out += c;
33
+ i++;
34
+ }
35
+ }
36
+ return out;
37
+ }
38
+ /** The code with string literals blanked, for matching declarations and enforcement that must not hide in text. */
39
+ export function codeWithoutStrings(body) {
40
+ return apexCode(body).replace(/'(?:[^'\\\n]|\\.)*'/g, "''");
41
+ }
42
+ /**
43
+ * Every class declared in the body, outer and inner, found with literal patterns in one linear
44
+ * pass (a regex built around the name backtracked badly on long runs of words).
45
+ */
46
+ export function classDeclarations(body) {
47
+ const code = codeWithoutStrings(body);
48
+ const out = [];
49
+ const decl = /\bclass\s+(\w+)/gi;
50
+ for (let m = decl.exec(code); m !== null; m = decl.exec(code)) {
51
+ const start = Math.max(code.lastIndexOf(';', m.index), code.lastIndexOf('{', m.index), code.lastIndexOf('}', m.index)) + 1;
52
+ const end = code.indexOf('{', m.index);
53
+ const header = code.slice(m.index, end === -1 ? code.length : end);
54
+ out.push({
55
+ name: m[1],
56
+ modifiers: code.slice(start, m.index).toLowerCase(),
57
+ parent: /\bextends\s+([\w.]+)/i.exec(header)?.[1],
58
+ });
59
+ }
60
+ return out;
61
+ }
62
+ function keywordOf(modifiers) {
63
+ if (/\bwithout\s+sharing\b/.test(modifiers))
64
+ return 'without';
65
+ if (/\binherited\s+sharing\b/.test(modifiers))
66
+ return 'inherited';
67
+ if (/\bwith\s+sharing\b/.test(modifiers))
68
+ return 'with';
69
+ return 'none';
70
+ }
71
+ /**
72
+ * The sharing keyword on the declaration of `className` itself, or null when the body declares no
73
+ * class of that name (an interface, enum or trigger). Modifiers may sit on either side of the
74
+ * keyword (`public virtual without sharing class`, `global with sharing virtual class`).
75
+ */
76
+ export function sharingKeyword(className, body) {
77
+ const target = className.toLowerCase();
78
+ const own = classDeclarations(body).find((d) => d.name.toLowerCase() === target);
79
+ return own ? keywordOf(own.modifiers) : null;
80
+ }
81
+ /** The class `className` extends, as written in its declaration (namespace and outer class stripped). */
82
+ export function parentClass(className, body) {
83
+ const target = className.toLowerCase();
84
+ const parent = classDeclarations(body).find((d) => d.name.toLowerCase() === target)?.parent;
85
+ return parent?.split('.').pop();
86
+ }
87
+ /**
88
+ * The sharing a class actually runs with. A class with no keyword takes its parent's when it
89
+ * extends one: Apex classes inherit the sharing setting of the class they extend (spec MN-001).
90
+ * `lookup` returns a class body by name; unknown parents leave the keyword as declared.
91
+ */
92
+ export function effectiveSharing(className, body, lookup) {
93
+ let name = className;
94
+ let current = body;
95
+ const seen = new Set();
96
+ for (;;) {
97
+ const keyword = sharingKeyword(name, current);
98
+ if (keyword !== 'none')
99
+ return keyword;
100
+ const parent = parentClass(name, current);
101
+ if (!parent || seen.has(parent.toLowerCase()))
102
+ return keyword;
103
+ seen.add(parent.toLowerCase());
104
+ const parentBody = lookup(parent);
105
+ if (parentBody === undefined)
106
+ return keyword;
107
+ name = parent;
108
+ current = parentBody;
109
+ }
110
+ }
111
+ /** Whether the class's code (not its comments) uses SYSTEM_MODE anywhere. */
112
+ export function usesSystemMode(body) {
113
+ const code = apexCode(body);
114
+ return testApexPattern(code, SYSTEM_MODE) || testApexPattern(code, DML_AS_SYSTEM);
115
+ }
116
+ /**
117
+ * Whether any class declared in the body, outer or inner, is `without sharing`. An inner class
118
+ * keeps its own keyword, so a `with sharing` class can still run queries without sharing through
119
+ * one (spec MN-002).
120
+ */
121
+ export function declaresWithoutSharing(body) {
122
+ return classDeclarations(body).some((d) => keywordOf(d.modifiers) === 'without');
123
+ }
124
+ // Data-model access modes on DML: `insert as system rows;` / `update as user rows;`.
125
+ export const DML_AS_SYSTEM = /\b(?:insert|update|upsert|delete|undelete|merge)\s+as\s+system\b/i;
126
+ export const DML_AS_USER = /\b(?:insert|update|upsert|delete|undelete|merge)\s+as\s+user\b/i;
127
+ //# sourceMappingURL=apexAccess.js.map
@@ -0,0 +1,13 @@
1
+ /**
2
+ * True when a query failed because the object or feature does not exist in this org (an
3
+ * unlicensed cloud, a disabled feature): the evidence is genuinely absent, so the check may
4
+ * treat the result as empty.
5
+ *
6
+ * Anything else, a permission error above all, must be rethrown so CheckEngine reports the
7
+ * check as inconclusive. Swallowing it reads as "nothing found", which a report then states
8
+ * as a pass.
9
+ */
10
+ export declare function isMissingObjectError(err: unknown): boolean;
11
+ /** Run a query, returning [] only when the object does not exist in this org. Other errors propagate. */
12
+ export declare function queryIfPresent<T>(run: () => Promise<T[]>): Promise<T[]>;
13
+ //# sourceMappingURL=missingObject.d.ts.map
@@ -0,0 +1,35 @@
1
+ import { isApiError } from '@cclabsnz/sf-core';
2
+ /**
3
+ * True when a query failed because the object or feature does not exist in this org (an
4
+ * unlicensed cloud, a disabled feature): the evidence is genuinely absent, so the check may
5
+ * treat the result as empty.
6
+ *
7
+ * Anything else, a permission error above all, must be rethrown so CheckEngine reports the
8
+ * check as inconclusive. Swallowing it reads as "nothing found", which a report then states
9
+ * as a pass.
10
+ */
11
+ export function isMissingObjectError(err) {
12
+ if (isApiError(err)) {
13
+ if (/INVALID_TYPE|NOT_FOUND|MALFORMED_QUERY/i.test(err.errorCode))
14
+ return true;
15
+ if (err.statusCode === 404)
16
+ return true;
17
+ }
18
+ const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
19
+ return (msg.includes('not supported') ||
20
+ msg.includes('invalid type') ||
21
+ msg.includes('is not supported') ||
22
+ msg.includes('sobject type'));
23
+ }
24
+ /** Run a query, returning [] only when the object does not exist in this org. Other errors propagate. */
25
+ export async function queryIfPresent(run) {
26
+ try {
27
+ return await run();
28
+ }
29
+ catch (err) {
30
+ if (isMissingObjectError(err))
31
+ return [];
32
+ throw err;
33
+ }
34
+ }
35
+ //# sourceMappingURL=missingObject.js.map
@@ -10,6 +10,7 @@ export default class AuditAppsCommand extends SfCommand<AppFinding[]> {
10
10
  from: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
11
  soak: import("@oclif/core/interfaces").OptionFlag<number, import("@oclif/core/interfaces").CustomOptions>;
12
12
  format: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
13
+ 'emit-permset': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
13
14
  };
14
15
  run(): Promise<AppFinding[]>;
15
16
  }