@cclabsnz/sf-audit 1.3.0 → 1.6.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 (102) hide show
  1. package/README.md +193 -12
  2. package/lib/api/MetadataClient.d.ts +4 -0
  3. package/lib/api/MetadataClient.js +2 -0
  4. package/lib/api/MetadataClientImpl.d.ts +8 -0
  5. package/lib/api/MetadataClientImpl.js +22 -0
  6. package/lib/api/RestClient.d.ts +2 -0
  7. package/lib/api/RestClientImpl.d.ts +2 -0
  8. package/lib/api/RestClientImpl.js +33 -0
  9. package/lib/apps/analyzeApps.d.ts +8 -0
  10. package/lib/apps/analyzeApps.js +19 -0
  11. package/lib/apps/appResolver.d.ts +4 -0
  12. package/lib/apps/appResolver.js +50 -0
  13. package/lib/apps/grantedAccess.d.ts +4 -0
  14. package/lib/apps/grantedAccess.js +36 -0
  15. package/lib/apps/leastPrivilege.d.ts +6 -0
  16. package/lib/apps/leastPrivilege.js +47 -0
  17. package/lib/apps/renderApps.d.ts +5 -0
  18. package/lib/apps/renderApps.js +23 -0
  19. package/lib/apps/standardAppCatalog.d.ts +11 -0
  20. package/lib/apps/standardAppCatalog.js +14 -0
  21. package/lib/apps/types.d.ts +64 -0
  22. package/lib/apps/types.js +2 -0
  23. package/lib/apps/usageCollector.d.ts +9 -0
  24. package/lib/apps/usageCollector.js +104 -0
  25. package/lib/chains/CapabilityRegistry.js +19 -0
  26. package/lib/chains/namedChains.js +67 -0
  27. package/lib/checks/eventLogAccess.d.ts +14 -0
  28. package/lib/checks/eventLogAccess.js +33 -0
  29. package/lib/checks/impl/AgentActionSurfaceCheck.d.ts +13 -0
  30. package/lib/checks/impl/AgentActionSurfaceCheck.js +125 -0
  31. package/lib/checks/impl/AgentChannelExposureCheck.d.ts +15 -0
  32. package/lib/checks/impl/AgentChannelExposureCheck.js +223 -0
  33. package/lib/checks/impl/AgentInventoryCheck.d.ts +15 -0
  34. package/lib/checks/impl/AgentInventoryCheck.js +228 -0
  35. package/lib/checks/impl/AgentMonitoringCoverageCheck.d.ts +12 -0
  36. package/lib/checks/impl/AgentMonitoringCoverageCheck.js +97 -0
  37. package/lib/checks/impl/AgentUserPrivilegeCheck.d.ts +13 -0
  38. package/lib/checks/impl/AgentUserPrivilegeCheck.js +204 -0
  39. package/lib/checks/impl/AuthProvidersCheck.d.ts +17 -0
  40. package/lib/checks/impl/AuthProvidersCheck.js +88 -0
  41. package/lib/checks/impl/ClassicSitesCheck.d.ts +17 -0
  42. package/lib/checks/impl/ClassicSitesCheck.js +65 -0
  43. package/lib/checks/impl/CspTrustedSitesCheck.d.ts +1 -0
  44. package/lib/checks/impl/CspTrustedSitesCheck.js +10 -1
  45. package/lib/checks/impl/DataExportAccessCheck.d.ts +19 -0
  46. package/lib/checks/impl/DataExportAccessCheck.js +79 -0
  47. package/lib/checks/impl/EncryptionCoverageCheck.d.ts +19 -0
  48. package/lib/checks/impl/EncryptionCoverageCheck.js +108 -0
  49. package/lib/checks/impl/EventMonitoringCheck.js +8 -5
  50. package/lib/checks/impl/ExperienceCspCheck.d.ts +18 -0
  51. package/lib/checks/impl/ExperienceCspCheck.js +57 -0
  52. package/lib/checks/impl/ExternalCredentialsCheck.d.ts +17 -0
  53. package/lib/checks/impl/ExternalCredentialsCheck.js +74 -0
  54. package/lib/checks/impl/GuestApiAccessCheck.d.ts +19 -0
  55. package/lib/checks/impl/GuestApiAccessCheck.js +113 -0
  56. package/lib/checks/impl/GuestObjectExposureCheck.d.ts +44 -0
  57. package/lib/checks/impl/GuestObjectExposureCheck.js +241 -0
  58. package/lib/checks/impl/GuestRecordAccessPolicyCheck.d.ts +34 -0
  59. package/lib/checks/impl/GuestRecordAccessPolicyCheck.js +120 -0
  60. package/lib/checks/impl/GuestSiteOptionsCheck.d.ts +18 -0
  61. package/lib/checks/impl/GuestSiteOptionsCheck.js +92 -0
  62. package/lib/checks/impl/GuestTrafficAnomalyCheck.d.ts +23 -0
  63. package/lib/checks/impl/GuestTrafficAnomalyCheck.js +343 -0
  64. package/lib/checks/impl/LoginAccessPolicyCheck.d.ts +26 -0
  65. package/lib/checks/impl/LoginAccessPolicyCheck.js +117 -0
  66. package/lib/checks/impl/LoginAnomalyCheck.d.ts +17 -0
  67. package/lib/checks/impl/LoginAnomalyCheck.js +98 -0
  68. package/lib/checks/impl/SandboxDataMaskingCheck.d.ts +17 -0
  69. package/lib/checks/impl/SandboxDataMaskingCheck.js +85 -0
  70. package/lib/checks/impl/SessionHardeningCheck.d.ts +21 -0
  71. package/lib/checks/impl/SessionHardeningCheck.js +134 -0
  72. package/lib/checks/impl/ThreatDetectionCheck.d.ts +17 -0
  73. package/lib/checks/impl/ThreatDetectionCheck.js +91 -0
  74. package/lib/checks/impl/TrustedUrlHygieneCheck.d.ts +16 -0
  75. package/lib/checks/impl/TrustedUrlHygieneCheck.js +198 -0
  76. package/lib/checks/registry.js +52 -0
  77. package/lib/commands/audit/apps.d.ts +16 -0
  78. package/lib/commands/audit/apps.js +64 -0
  79. package/lib/commands/audit/diff.js +9 -5
  80. package/lib/commands/audit/events/pull.d.ts +17 -0
  81. package/lib/commands/audit/events/pull.js +88 -0
  82. package/lib/commands/audit/security.d.ts +5 -0
  83. package/lib/commands/audit/security.js +47 -17
  84. package/lib/compliance/catalogs/index.js +2 -0
  85. package/lib/compliance/catalogs/owaspLlm.d.ts +3 -0
  86. package/lib/compliance/catalogs/owaspLlm.js +34 -0
  87. package/lib/compliance/mapping.js +46 -7
  88. package/lib/compliance/resolve.js +4 -3
  89. package/lib/compliance/types.d.ts +1 -1
  90. package/lib/context/AuditCache.d.ts +31 -0
  91. package/lib/context/AuditContext.d.ts +6 -0
  92. package/lib/events/EventBaselineStore.d.ts +16 -0
  93. package/lib/events/EventBaselineStore.js +55 -0
  94. package/lib/events/eventLogQuery.d.ts +21 -0
  95. package/lib/events/eventLogQuery.js +34 -0
  96. package/lib/events/pullEventLogs.d.ts +51 -0
  97. package/lib/events/pullEventLogs.js +79 -0
  98. package/lib/findings/CheckMeta.js +22 -0
  99. package/lib/lib/wire.d.ts +4 -2
  100. package/lib/lib/wire.js +5 -1
  101. package/lib/renderers/ClientReportRenderer.js +1 -1
  102. package/package.json +16 -2
@@ -0,0 +1,223 @@
1
+ export class AgentChannelExposureCheck {
2
+ id = 'agent-channel-exposure';
3
+ name = 'Agentforce Channel Exposure';
4
+ category = 'AI & Agents';
5
+ description = 'Correlates active Agentforce agents with the channels that reach them (Experience Cloud sites, embedded deployments, messaging channels) and flags guest-reachable exposure.';
6
+ dependsOnCache = ['agentInventory', 'agentAccess'];
7
+ async run(ctx) {
8
+ const findings = [];
9
+ const baseUrl = ctx.orgInfo.instanceUrl;
10
+ // Gate: only meaningful when the inventory was built successfully. Any other
11
+ // state (not-enabled / unknown) means we stay silent — same convention as the
12
+ // other AI & Agents dependent checks.
13
+ if (ctx.cache.agentAccess !== 'ok')
14
+ return { findings };
15
+ const inventory = ctx.cache.agentInventory ?? [];
16
+ const activeAgents = inventory.filter((a) => a.type === 'agent' && a.isActive);
17
+ if (activeAgents.length === 0)
18
+ return { findings };
19
+ // Discover channels. Each source is queried defensively: an org may lack any of
20
+ // these objects, and a missing object must never be read as "no exposure" in a
21
+ // way that hides a real surface — but equally we must not invent exposure we
22
+ // cannot support. We simply skip sources that are unavailable.
23
+ const guestSites = await this.queryGuestSites(ctx);
24
+ const messagingChannels = await this.queryMessagingChannels(ctx);
25
+ const embedded = await this.queryEmbeddedDeployments(ctx);
26
+ // Build the set of public (guest-reachable) channels.
27
+ const publicChannels = [];
28
+ for (const n of guestSites) {
29
+ publicChannels.push({
30
+ kind: 'experience-site',
31
+ id: n.Id,
32
+ label: n.Name,
33
+ note: `Live Experience Cloud site with an active guest user (path: ${n.UrlPathPrefix ?? '(default)'})`,
34
+ });
35
+ }
36
+ for (const e of embedded) {
37
+ // A deployment is public when it is bound to a live guest site OR carries no
38
+ // authenticated-site marker. We treat any embedded deployment discovered here
39
+ // as a public web surface (embedded chat is served to the public web).
40
+ const label = e.DeveloperName ?? e.DurableId ?? e.Id ?? 'Embedded deployment';
41
+ const boundAgent = e.AgentDeveloperName ?? e.BotDeveloperName ?? undefined;
42
+ publicChannels.push({
43
+ kind: 'embedded-deployment',
44
+ id: e.Id ?? e.DurableId ?? label,
45
+ label,
46
+ note: e.SiteName ? `Embedded deployment on site "${e.SiteName}"` : 'Embedded service deployment (web-reachable)',
47
+ boundAgentDeveloperName: boundAgent ?? undefined,
48
+ });
49
+ }
50
+ // Resolve agent->channel bindings from Tooling deployment configs where the
51
+ // platform exposes them. This is the only source that lets us assert exposure
52
+ // as fact rather than inference.
53
+ const bindings = await this.queryAgentChannelBindings(ctx);
54
+ // Merge Tooling bindings onto the embedded channels, and record a site-based
55
+ // binding as a public channel when the binding names a guest site.
56
+ const guestSiteIds = new Set(guestSites.map((n) => n.Id));
57
+ for (const b of bindings) {
58
+ if (!b.agentDeveloperName)
59
+ continue;
60
+ // Attach to any embedded channel with the same deployment developer name.
61
+ const match = publicChannels.find((c) => c.kind === 'embedded-deployment' && c.label === b.deploymentDeveloperName);
62
+ if (match) {
63
+ match.boundAgentDeveloperName = b.agentDeveloperName;
64
+ }
65
+ else if (b.siteId && guestSiteIds.has(b.siteId)) {
66
+ // Binding points an agent at a guest site directly.
67
+ const site = guestSites.find((n) => n.Id === b.siteId);
68
+ publicChannels.push({
69
+ kind: 'experience-site',
70
+ id: `${site.Id}:${b.agentDeveloperName}`,
71
+ label: site.Name,
72
+ note: `Live guest Experience Cloud site "${site.Name}" hosting agent "${b.agentDeveloperName}"`,
73
+ boundAgentDeveloperName: b.agentDeveloperName,
74
+ });
75
+ }
76
+ }
77
+ // Split into channels we could tie to a specific active agent (fact) vs public
78
+ // channels we discovered but could not map to an agent (inference required).
79
+ const activeByDevName = new Map(activeAgents.map((a) => [a.developerName, a]));
80
+ const mappedExposures = [];
81
+ const unmappedPublicChannels = [];
82
+ for (const c of publicChannels) {
83
+ const boundAgent = c.boundAgentDeveloperName
84
+ ? activeByDevName.get(c.boundAgentDeveloperName)
85
+ : undefined;
86
+ if (boundAgent) {
87
+ mappedExposures.push({ agent: boundAgent, channel: c });
88
+ }
89
+ else {
90
+ unmappedPublicChannels.push(c);
91
+ }
92
+ }
93
+ // Critical: a specific active agent hosted on a guest-reachable channel. This is
94
+ // asserted only where the agent->channel binding is a fact.
95
+ for (const { agent, channel } of mappedExposures) {
96
+ findings.push({
97
+ id: `agent-channel-exposure-guest-${agent.developerName}-${slug(channel.id)}`,
98
+ category: this.category,
99
+ riskLevel: 'CRITICAL',
100
+ title: `Active agent "${agent.label}" is reachable through a guest/public channel`,
101
+ detail: `The Agentforce agent "${agent.label}" (${agent.developerName}) is bound to ${channel.note}. ` +
102
+ `Unauthenticated visitors can send this agent input, so any prompt-injection payload reaches an agent ` +
103
+ `that executes with the data access of its run-as user${agent.runAsUserId ? ` (${agent.runAsUserId})` : ''}. ` +
104
+ `This is the exact combination behind the ForcedLeak pattern: public input channel plus a privileged agent identity.`,
105
+ remediation: 'Confirm this agent is intended to be publicly reachable. If so, tightly scope the run-as user (least privilege), review the agent action surface for write-capable actions, and ensure Event Monitoring / Transaction Security cover the agent. If not intended, remove the guest/public binding.',
106
+ affectedItems: [
107
+ {
108
+ label: `${agent.label} (${agent.developerName})`,
109
+ url: `${baseUrl}/lightning/setup/SetupNetworks/home`,
110
+ note: channel.note,
111
+ },
112
+ ],
113
+ });
114
+ }
115
+ // Info: agents that are active but not tied to any public channel we found — the
116
+ // internal-only inventory value. Reported once, listing the internal channels.
117
+ const publiclyExposedDevNames = new Set(mappedExposures.map((m) => m.agent.developerName));
118
+ const internalAgents = activeAgents.filter((a) => !publiclyExposedDevNames.has(a.developerName));
119
+ const internalChannels = messagingChannels.filter((m) => m.IsActive !== false);
120
+ if (internalAgents.length > 0 && unmappedPublicChannels.length === 0) {
121
+ findings.push({
122
+ id: 'agent-channel-exposure-internal',
123
+ category: this.category,
124
+ riskLevel: 'INFO',
125
+ title: `${internalAgents.length} active agent(s) on internal-only channels`,
126
+ detail: `${internalAgents.length} active agent(s) were not found on any guest-reachable Experience Cloud site or public embedded deployment. ` +
127
+ (internalChannels.length > 0
128
+ ? `${internalChannels.length} messaging channel(s) are configured (internal / authenticated inbound surfaces). `
129
+ : 'No public web channels were discovered. ') +
130
+ `Channel reachability in Salesforce is not always expressed in queryable metadata, so treat this as "no public exposure found" rather than a guarantee.`,
131
+ remediation: 'Confirm these agents are only exposed on authenticated/internal channels. Re-check after any new Experience Cloud site or embedded deployment goes live.',
132
+ affectedItems: internalAgents.map((a) => ({
133
+ label: `${a.label} (${a.developerName})`,
134
+ note: `active v${a.activeVersion ?? '?'}${a.runAsUserId ? ` | run-as: ${a.runAsUserId}` : ''}`,
135
+ })),
136
+ });
137
+ }
138
+ // Medium (honest inference): we found active agents AND public channels, but could
139
+ // not resolve which agent sits on which channel from queryable data. We state the
140
+ // two lists separately and say the mapping needs manual confirmation. We never
141
+ // claim a specific exposure we cannot support.
142
+ if (unmappedPublicChannels.length > 0) {
143
+ findings.push({
144
+ id: 'agent-channel-exposure-unmapped',
145
+ category: this.category,
146
+ riskLevel: 'MEDIUM',
147
+ title: `Public channel(s) and active agent(s) present, but the agent-to-channel mapping could not be confirmed`,
148
+ detail: `This org has ${activeAgents.length} active agent(s) and ${unmappedPublicChannels.length} guest-reachable / public channel(s), ` +
149
+ `but the platform did not expose a queryable binding tying a specific agent to a specific channel. ` +
150
+ `Whether any agent is actually reachable from these public channels needs manual confirmation in Setup ` +
151
+ `(Digital Experiences / Embedded Service deployments). The lists below are reported separately and are NOT asserted as a live exposure.`,
152
+ remediation: 'Manually confirm, for each public channel, whether an agent is deployed on it (Setup → Embedded Service Deployments and each Experience site\'s Agentforce configuration). Where an agent is publicly reachable, scope its run-as user to least privilege and review its action surface.',
153
+ affectedItems: [
154
+ ...activeAgents.map((a) => ({
155
+ label: `Active agent: ${a.label} (${a.developerName})`,
156
+ note: `run-as: ${a.runAsUserId ?? 'unknown'}`,
157
+ })),
158
+ ...unmappedPublicChannels.map((c) => ({
159
+ label: `Public channel: ${c.label}`,
160
+ note: c.note,
161
+ })),
162
+ ],
163
+ });
164
+ }
165
+ return { findings };
166
+ }
167
+ // Live Experience Cloud sites with an active guest user. Defensive: if Network is
168
+ // unavailable, return [] (we then simply cannot assert site exposure).
169
+ async queryGuestSites(ctx) {
170
+ try {
171
+ const rows = await ctx.soql.queryAll(`SELECT Id, Name, Status, UrlPathPrefix, GuestUserId
172
+ FROM Network
173
+ WHERE Status = 'Live'`);
174
+ return rows.filter((n) => n.GuestUserId !== null);
175
+ }
176
+ catch {
177
+ return [];
178
+ }
179
+ }
180
+ async queryMessagingChannels(ctx) {
181
+ try {
182
+ return await ctx.soql.queryAll(`SELECT Id, MasterLabel, ChannelType, IsActive FROM MessagingChannel`);
183
+ }
184
+ catch {
185
+ return [];
186
+ }
187
+ }
188
+ // Embedded Service deployment details (embedded chat / messaging for web). Query the
189
+ // standard object via SOQL; schema varies by release so we tolerate field/object
190
+ // absence and fall back to a minimal projection.
191
+ async queryEmbeddedDeployments(ctx) {
192
+ try {
193
+ return await ctx.soql.queryAll(`SELECT Id, DeveloperName, DurableId, Site, SiteName FROM EmbeddedServiceDetail`);
194
+ }
195
+ catch {
196
+ try {
197
+ return await ctx.soql.queryAll(`SELECT DurableId, DeveloperName FROM EmbeddedServiceDetail`);
198
+ }
199
+ catch {
200
+ return [];
201
+ }
202
+ }
203
+ }
204
+ // Best-effort agent->channel binding from Tooling deployment config. Returns [] if
205
+ // the objects/fields are not queryable in this org/release.
206
+ async queryAgentChannelBindings(ctx) {
207
+ try {
208
+ const rows = await ctx.tooling.query(`SELECT Id, DeveloperName, Site, AgentDeveloperName FROM EmbeddedServiceConfig`);
209
+ return rows.map((r) => ({
210
+ deploymentDeveloperName: r.DeveloperName ?? undefined,
211
+ agentDeveloperName: r.AgentDeveloperName ?? r.BotDeveloperName ?? undefined,
212
+ siteId: r.Site ?? undefined,
213
+ }));
214
+ }
215
+ catch {
216
+ return [];
217
+ }
218
+ }
219
+ }
220
+ function slug(s) {
221
+ return s.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'x';
222
+ }
223
+ //# sourceMappingURL=AgentChannelExposureCheck.js.map
@@ -0,0 +1,15 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class AgentInventoryCheck implements SecurityCheck {
4
+ readonly id = "agent-inventory";
5
+ readonly name = "Agentforce Agent Inventory";
6
+ readonly category = "AI & Agents";
7
+ readonly description = "Inventories Agentforce agents and classic Einstein Bots, their active versions, run-as users, and the users licensed to run agents.";
8
+ readonly populatesCache: readonly ["agentInventory", "agentUsers", "agentAccess"];
9
+ run(ctx: AuditContext): Promise<CheckResult>;
10
+ private classifyType;
11
+ private queryBotDefinitions;
12
+ private queryAgentUsers;
13
+ private queryRunAsUserStatus;
14
+ }
15
+ //# sourceMappingURL=AgentInventoryCheck.d.ts.map
@@ -0,0 +1,228 @@
1
+ import { isApiError } from '../../api/ApiError.js';
2
+ // BotDefinition.Type values that denote an Agentforce / GenAI agent rather than a
3
+ // classic Einstein Bot. Matched case-insensitively; anything else (typically 'Bot')
4
+ // is treated as a classic bot. LIKE-style matching so exact enum spellings across
5
+ // releases are not load-bearing.
6
+ const AGENT_TYPE_HINTS = ['agent', 'einsteinservice', 'einsteincopilot', 'genai', 'copilot'];
7
+ // Permission set license labels that grant Agentforce / Einstein Agent capability.
8
+ // Substring match so exact SKU names are not load-bearing.
9
+ const AGENT_LICENSE_HINTS = ['agentforce', 'einstein agent'];
10
+ // A Tooling error whose cause is "the object does not exist" (feature absent) rather
11
+ // than a transient/permission failure. Mirrors classifyEventLogAccessError's not-enabled arm.
12
+ function isMissingObjectError(err) {
13
+ if (isApiError(err)) {
14
+ if (/INVALID_TYPE|NOT_FOUND|MALFORMED_QUERY/i.test(err.errorCode))
15
+ return true;
16
+ if (err.statusCode === 404)
17
+ return true;
18
+ }
19
+ const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
20
+ return (msg.includes('not supported') ||
21
+ msg.includes('invalid type') ||
22
+ msg.includes('is not supported') ||
23
+ msg.includes('sobject type'));
24
+ }
25
+ export class AgentInventoryCheck {
26
+ id = 'agent-inventory';
27
+ name = 'Agentforce Agent Inventory';
28
+ category = 'AI & Agents';
29
+ description = 'Inventories Agentforce agents and classic Einstein Bots, their active versions, run-as users, and the users licensed to run agents.';
30
+ populatesCache = ['agentInventory', 'agentUsers', 'agentAccess'];
31
+ async run(ctx) {
32
+ const findings = [];
33
+ const baseUrl = ctx.orgInfo.instanceUrl;
34
+ // Step 1: BotDefinition is the entry query. If the object itself does not exist the
35
+ // org has no Agentforce/Bot feature — degrade to 'not-enabled' and stay silent.
36
+ let bots;
37
+ try {
38
+ bots = await this.queryBotDefinitions(ctx);
39
+ }
40
+ catch (e) {
41
+ if (isMissingObjectError(e)) {
42
+ ctx.cache.agentAccess = 'not-enabled';
43
+ }
44
+ else {
45
+ ctx.cache.agentAccess = 'unknown';
46
+ }
47
+ ctx.cache.agentInventory = [];
48
+ ctx.cache.agentUsers = [];
49
+ return { findings };
50
+ }
51
+ // Step 2+: active versions, planner definitions, and agent users. Any failure here
52
+ // (the objects exist, so this is not 'not-enabled') means we could not fully build the
53
+ // inventory — record 'unknown' and return no findings rather than assert a partial view.
54
+ let versions;
55
+ let agentUsers;
56
+ try {
57
+ versions = await ctx.tooling.query(`SELECT Id, BotDefinitionId, Status, VersionNumber FROM BotVersion WHERE Status = 'Active'`);
58
+ // GenAiPlannerDefinition is queried for completeness of the agent picture (Phase 2
59
+ // action-surface work joins on it); a failure here still counts as an incomplete build.
60
+ await ctx.tooling.query(`SELECT Id, DeveloperName, MasterLabel FROM GenAiPlannerDefinition`);
61
+ agentUsers = await this.queryAgentUsers(ctx);
62
+ }
63
+ catch (e) {
64
+ if (isMissingObjectError(e)) {
65
+ // BotDefinition existed but a GenAI object did not: the feature is partially present
66
+ // (e.g. classic bots without Agentforce). Treat as 'unknown' — we cannot vouch for a
67
+ // complete agent inventory — rather than 'not-enabled'.
68
+ ctx.cache.agentAccess = 'unknown';
69
+ }
70
+ else {
71
+ ctx.cache.agentAccess = 'unknown';
72
+ }
73
+ ctx.cache.agentInventory = [];
74
+ ctx.cache.agentUsers = [];
75
+ return { findings };
76
+ }
77
+ // Build the inventory. Active version = the BotVersion (per definition) with Status Active.
78
+ const activeVersionByBot = new Map();
79
+ for (const v of versions) {
80
+ const existing = activeVersionByBot.get(v.BotDefinitionId);
81
+ if (existing === undefined || v.VersionNumber > existing) {
82
+ activeVersionByBot.set(v.BotDefinitionId, v.VersionNumber);
83
+ }
84
+ }
85
+ const runAsIds = bots.map((b) => b.BotUserId).filter((id) => !!id);
86
+ const runAsStatus = await this.queryRunAsUserStatus(ctx, runAsIds);
87
+ const inventory = bots.map((b) => {
88
+ const activeVersion = activeVersionByBot.get(b.Id);
89
+ const runAsUserId = b.BotUserId ?? undefined;
90
+ const runAsUserActive = runAsUserId !== undefined && runAsStatus.has(runAsUserId)
91
+ ? runAsStatus.get(runAsUserId)
92
+ : undefined;
93
+ return {
94
+ developerName: b.DeveloperName,
95
+ label: b.MasterLabel,
96
+ type: this.classifyType(b.Type),
97
+ isActive: activeVersion !== undefined,
98
+ activeVersion,
99
+ runAsUserId,
100
+ runAsUserActive,
101
+ };
102
+ });
103
+ ctx.cache.agentInventory = inventory;
104
+ ctx.cache.agentUsers = agentUsers;
105
+ ctx.cache.agentAccess = 'ok';
106
+ const agents = inventory.filter((a) => a.type === 'agent');
107
+ const activeAgents = agents.filter((a) => a.isActive);
108
+ if (inventory.length === 0) {
109
+ // Feature present but nothing configured: no noise, cache already records 'ok'.
110
+ return { findings };
111
+ }
112
+ // Info: the inventory itself is the product.
113
+ findings.push({
114
+ id: 'agent-inventory-summary',
115
+ category: this.category,
116
+ riskLevel: 'INFO',
117
+ title: `Agentforce inventory: ${agents.length} agent(s), ${activeAgents.length} active, ${agentUsers.length} agent user(s)`,
118
+ detail: `Found ${inventory.length} bot/agent definition(s): ${agents.length} Agentforce agent(s) ` +
119
+ `(${activeAgents.length} with an active version) and ${inventory.length - agents.length} classic Einstein Bot(s). ` +
120
+ `${agentUsers.length} user(s) are licensed to run agents (Einstein Agent User profile or an Agentforce / Einstein Agent permission set license). ` +
121
+ `Each active agent executes as a run-as user whose data access defines the blast radius of a prompt injection.`,
122
+ remediation: 'Confirm every active agent is expected and documented, that its run-as user follows least privilege, and that the agent users list contains no stale accounts.',
123
+ affectedItems: inventory.map((a) => ({
124
+ label: `${a.label} (${a.developerName})`,
125
+ note: `${a.type === 'agent' ? 'Agentforce agent' : 'classic Einstein Bot'} | ` +
126
+ `${a.isActive ? `active v${a.activeVersion}` : 'no active version'}` +
127
+ (a.runAsUserId ? ` | run-as: ${a.runAsUserId}` : ''),
128
+ })),
129
+ });
130
+ // Medium: an active agent whose run-as user is inactive or frozen. The agent stays
131
+ // reachable but its identity is disabled — a latent misconfiguration and, if reactivated
132
+ // without review, a way to smuggle access back in.
133
+ const brokenRunAs = inventory.filter((a) => a.type === 'agent' && a.isActive && a.runAsUserActive === false);
134
+ for (const a of brokenRunAs) {
135
+ findings.push({
136
+ id: `agent-inventory-runas-inactive-${a.developerName}`,
137
+ category: this.category,
138
+ riskLevel: 'MEDIUM',
139
+ title: `Active agent "${a.label}" runs as an inactive or frozen user`,
140
+ detail: `The Agentforce agent "${a.label}" (${a.developerName}) has an active version but its run-as user ` +
141
+ `is inactive or frozen. Requests to the agent will fail, and if the user is later reactivated its ` +
142
+ `permissions take effect again without a fresh review.`,
143
+ remediation: 'Confirm the run-as user should be disabled. If the agent is still needed, assign an active, least-privilege run-as user; otherwise deactivate the agent version.',
144
+ affectedItems: [
145
+ {
146
+ label: `${a.label} (${a.developerName})`,
147
+ url: a.runAsUserId ? `${baseUrl}/${a.runAsUserId}` : undefined,
148
+ note: `run-as user ${a.runAsUserId ?? 'unknown'} is inactive/frozen`,
149
+ },
150
+ ],
151
+ });
152
+ }
153
+ return { findings };
154
+ }
155
+ classifyType(type) {
156
+ const t = (type ?? '').toLowerCase();
157
+ return AGENT_TYPE_HINTS.some((h) => t.includes(h)) ? 'agent' : 'classic-bot';
158
+ }
159
+ // BotDefinition query with a defensive fallback: if Type/BotUserId are not queryable in
160
+ // this org/release (MALFORMED_QUERY on the field), retry with the minimal field set rather
161
+ // than throw. A genuinely missing object still throws and is handled by the caller.
162
+ async queryBotDefinitions(ctx) {
163
+ try {
164
+ return await ctx.tooling.query(`SELECT Id, DeveloperName, MasterLabel, Type, BotUserId FROM BotDefinition`);
165
+ }
166
+ catch (e) {
167
+ if (isApiError(e) && /MALFORMED_QUERY|INVALID_FIELD/i.test(e.errorCode)) {
168
+ return ctx.tooling.query(`SELECT Id, DeveloperName, MasterLabel FROM BotDefinition`);
169
+ }
170
+ throw e;
171
+ }
172
+ }
173
+ // Users on the Einstein Agent User profile OR holding an Agentforce / Einstein Agent
174
+ // permission set license, with their PermissionSetAssignment ids and license labels.
175
+ async queryAgentUsers(ctx) {
176
+ const licenseLike = AGENT_LICENSE_HINTS.map((h) => `PermissionSetLicense.MasterLabel LIKE '%${h}%'`).join(' OR ');
177
+ // License assignments first, so the User filter can include those assignees.
178
+ const licenseAssigns = await ctx.soql.queryAll(`SELECT AssigneeId, PermissionSetLicense.MasterLabel
179
+ FROM PermissionSetLicenseAssign
180
+ WHERE ${licenseLike}
181
+ LIMIT 500`);
182
+ const licenseNamesByUser = new Map();
183
+ for (const a of licenseAssigns) {
184
+ const label = a.PermissionSetLicense?.MasterLabel;
185
+ if (!label)
186
+ continue;
187
+ const list = licenseNamesByUser.get(a.AssigneeId) ?? [];
188
+ list.push(label);
189
+ licenseNamesByUser.set(a.AssigneeId, list);
190
+ }
191
+ const licensedIds = [...licenseNamesByUser.keys()];
192
+ const idInClause = licensedIds.length
193
+ ? ` OR Id IN (${licensedIds.map((id) => `'${id}'`).join(',')})`
194
+ : '';
195
+ const users = await ctx.soql.queryAll(`SELECT Id, Username, IsActive, Profile.Name,
196
+ (SELECT PermissionSetId FROM PermissionSetAssignments)
197
+ FROM User
198
+ WHERE Profile.Name = 'Einstein Agent User'${idInClause}
199
+ LIMIT 500`);
200
+ return users.map((u) => ({
201
+ userId: u.Id,
202
+ username: u.Username,
203
+ profileName: u.Profile?.Name ?? '',
204
+ isActive: u.IsActive,
205
+ permissionSetIds: (u.PermissionSetAssignments?.records ?? []).map((r) => r.PermissionSetId),
206
+ permissionSetLicenseNames: licenseNamesByUser.get(u.Id) ?? [],
207
+ }));
208
+ }
209
+ // Resolve which run-as users are active (and not frozen). A frozen user has an active
210
+ // IsActive flag but a UserLogin.IsFrozen = true row, so exclude those from the "active" set.
211
+ async queryRunAsUserStatus(ctx, runAsIds) {
212
+ const status = new Map();
213
+ if (runAsIds.length === 0)
214
+ return status;
215
+ const idList = runAsIds.map((id) => `'${id}'`).join(',');
216
+ const rows = await ctx.soql.queryAll(`SELECT Id, IsActive
217
+ FROM User
218
+ WHERE Id IN (${idList})
219
+ AND Id NOT IN (SELECT UserId FROM UserLogin WHERE IsFrozen = true)`);
220
+ // Rows returned = active and not frozen. Any run-as id absent from the result set is
221
+ // therefore inactive or frozen.
222
+ const activeIds = new Set(rows.filter((r) => r.IsActive).map((r) => r.Id));
223
+ for (const id of runAsIds)
224
+ status.set(id, activeIds.has(id));
225
+ return status;
226
+ }
227
+ }
228
+ //# sourceMappingURL=AgentInventoryCheck.js.map
@@ -0,0 +1,12 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class AgentMonitoringCoverageCheck implements SecurityCheck {
4
+ readonly id = "agent-monitoring-coverage";
5
+ readonly name = "Agentforce Monitoring Coverage";
6
+ readonly category = "AI & Agents";
7
+ readonly description = "Flags orgs that run active Agentforce agents without Event Monitoring capture or Transaction Security policies to detect and respond to agent abuse.";
8
+ readonly dependsOnCache: readonly ["agentInventory", "agentAccess", "eventLogSummary"];
9
+ run(ctx: AuditContext): Promise<CheckResult>;
10
+ private hasEnabledTransactionSecurityPolicy;
11
+ }
12
+ //# sourceMappingURL=AgentMonitoringCoverageCheck.d.ts.map
@@ -0,0 +1,97 @@
1
+ export class AgentMonitoringCoverageCheck {
2
+ id = 'agent-monitoring-coverage';
3
+ name = 'Agentforce Monitoring Coverage';
4
+ category = 'AI & Agents';
5
+ description = 'Flags orgs that run active Agentforce agents without Event Monitoring capture or Transaction Security policies to detect and respond to agent abuse.';
6
+ // Depends on the agent inventory plus the event-log summary that EventMonitoringCheck
7
+ // populates. TransactionSecurityPolicy is queried directly (Tooling), not cached.
8
+ dependsOnCache = ['agentInventory', 'agentAccess', 'eventLogSummary'];
9
+ async run(ctx) {
10
+ const findings = [];
11
+ const baseUrl = ctx.orgInfo.instanceUrl;
12
+ // Gate: silent unless the agent inventory was built successfully.
13
+ if (ctx.cache.agentAccess !== 'ok')
14
+ return { findings };
15
+ const inventory = ctx.cache.agentInventory ?? [];
16
+ const activeAgents = inventory.filter((a) => a.type === 'agent' && a.isActive);
17
+ if (activeAgents.length === 0)
18
+ return { findings };
19
+ // Event capture signal, interpreted the same way SiemIntegrationCheck reads the
20
+ // EventLogSummary: capture exists only when the log is accessible AND has files.
21
+ // A blind log (not-enabled / no-permission) counts as "no capture" — there is no
22
+ // monitoring the agent's activity can be seen through.
23
+ const els = ctx.cache.eventLogSummary;
24
+ const hasEventCapture = !!els && els.accessible !== false && (els.totalFiles ?? 0) > 0;
25
+ // Transaction Security policies (real-time threat response). Defensive: a missing
26
+ // object / access failure is treated as "no policy" rather than throwing — the
27
+ // absence of detectable policy is what matters for this coverage check.
28
+ const hasTransactionSecurity = await this.hasEnabledTransactionSecurityPolicy(ctx);
29
+ const agentList = activeAgents
30
+ .map((a) => `${a.label} (${a.developerName})`)
31
+ .slice(0, 20)
32
+ .join(', ');
33
+ // High: agents run, nothing captures their activity, and no automated response
34
+ // exists. Point at the events pull command.
35
+ if (!hasEventCapture && !hasTransactionSecurity) {
36
+ findings.push({
37
+ id: 'agent-monitoring-coverage-none',
38
+ category: this.category,
39
+ riskLevel: 'HIGH',
40
+ title: `${activeAgents.length} active agent(s) run with no Event Monitoring capture and no Transaction Security policy`,
41
+ detail: `This org has ${activeAgents.length} active Agentforce agent(s) (${agentList}) but ` +
42
+ `Event Monitoring is not capturing any log files${els && els.accessible === false ? ' (the event log was not accessible to this audit)' : ''} ` +
43
+ `and no Transaction Security policy is enabled. Agent activity — including prompt injection, mass reads by the run-as user, ` +
44
+ `and data exfiltration — would leave no auditable trail and trigger no automated response. This is the monitoring gap in the ForcedLeak pattern.`,
45
+ remediation: 'Enable Event Monitoring (Setup → Event Monitoring Settings) and pull agent-relevant logs with `sf audit events pull` on a schedule, forwarding to a SIEM. Add Transaction Security policies for login and data-export anomalies so agent misuse triggers a real-time response.',
46
+ affectedItems: [
47
+ {
48
+ label: 'Event Monitoring',
49
+ url: `${baseUrl}/lightning/setup/EventLogFile/home`,
50
+ note: 'No event log files captured — run `sf audit events pull`',
51
+ },
52
+ {
53
+ label: 'Transaction Security Policies',
54
+ url: `${baseUrl}/lightning/setup/TransactionSecurityPolicies/home`,
55
+ note: 'No enabled policy — no automated response to agent abuse',
56
+ },
57
+ ],
58
+ });
59
+ return { findings };
60
+ }
61
+ // Low (partial): event logs exist but there is no Transaction Security policy — the
62
+ // activity is recorded but nothing responds in real time.
63
+ if (hasEventCapture && !hasTransactionSecurity) {
64
+ findings.push({
65
+ id: 'agent-monitoring-coverage-partial',
66
+ category: this.category,
67
+ riskLevel: 'LOW',
68
+ title: `Agent activity is logged but no Transaction Security policy provides real-time response`,
69
+ detail: `Event Monitoring is capturing log files, so ${activeAgents.length} active agent(s) leave an auditable trail. ` +
70
+ `However, no Transaction Security policy is enabled, so anomalies in agent-driven activity (bulk reads, off-hours access, ` +
71
+ `data export) are recorded after the fact but not blocked or alerted on in real time.`,
72
+ remediation: 'Add Transaction Security policies (Setup → Transaction Security Policies) for login anomalies and bulk data export so agent misuse is caught in real time, not only in retrospective log review.',
73
+ affectedItems: [
74
+ {
75
+ label: 'Transaction Security Policies',
76
+ url: `${baseUrl}/lightning/setup/TransactionSecurityPolicies/home`,
77
+ note: 'No enabled policy — add real-time response for agent activity',
78
+ },
79
+ ],
80
+ });
81
+ return { findings };
82
+ }
83
+ // Otherwise monitoring is adequate (capture present, or capture + policy). Silent.
84
+ return { findings };
85
+ }
86
+ async hasEnabledTransactionSecurityPolicy(ctx) {
87
+ try {
88
+ const policies = await ctx.tooling.query(`SELECT Id, State FROM TransactionSecurityPolicy WHERE State = 'Enabled'`);
89
+ return policies.length > 0;
90
+ }
91
+ catch {
92
+ // Object missing or inaccessible: no detectable policy.
93
+ return false;
94
+ }
95
+ }
96
+ }
97
+ //# sourceMappingURL=AgentMonitoringCoverageCheck.js.map
@@ -0,0 +1,13 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class AgentUserPrivilegeCheck implements SecurityCheck {
4
+ readonly id = "agent-user-privilege";
5
+ readonly name = "Agent User Privilege";
6
+ readonly category = "AI & Agents";
7
+ readonly description = "Flags Agentforce run-as / agent users whose effective access is over-broad: Modify/View All Data, write access to many objects, or read access to data classified as sensitive. An injected prompt can exfiltrate or mutate exactly what the agent user can reach.";
8
+ readonly dependsOnCache: readonly ["agentUsers", "agentAccess"];
9
+ run(ctx: AuditContext): Promise<CheckResult>;
10
+ private evaluateUser;
11
+ private querySensitiveObjects;
12
+ }
13
+ //# sourceMappingURL=AgentUserPrivilegeCheck.d.ts.map