@cclabsnz/sf-audit 1.4.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 (54) hide show
  1. package/README.md +96 -11
  2. package/lib/api/RestClient.d.ts +1 -0
  3. package/lib/api/RestClientImpl.d.ts +1 -0
  4. package/lib/api/RestClientImpl.js +27 -0
  5. package/lib/apps/analyzeApps.d.ts +8 -0
  6. package/lib/apps/analyzeApps.js +19 -0
  7. package/lib/apps/appResolver.d.ts +4 -0
  8. package/lib/apps/appResolver.js +50 -0
  9. package/lib/apps/grantedAccess.d.ts +4 -0
  10. package/lib/apps/grantedAccess.js +36 -0
  11. package/lib/apps/leastPrivilege.d.ts +6 -0
  12. package/lib/apps/leastPrivilege.js +47 -0
  13. package/lib/apps/renderApps.d.ts +5 -0
  14. package/lib/apps/renderApps.js +23 -0
  15. package/lib/apps/standardAppCatalog.d.ts +11 -0
  16. package/lib/apps/standardAppCatalog.js +14 -0
  17. package/lib/apps/types.d.ts +64 -0
  18. package/lib/apps/types.js +2 -0
  19. package/lib/apps/usageCollector.d.ts +9 -0
  20. package/lib/apps/usageCollector.js +104 -0
  21. package/lib/chains/namedChains.js +45 -0
  22. package/lib/checks/impl/AgentActionSurfaceCheck.d.ts +13 -0
  23. package/lib/checks/impl/AgentActionSurfaceCheck.js +125 -0
  24. package/lib/checks/impl/AgentChannelExposureCheck.d.ts +15 -0
  25. package/lib/checks/impl/AgentChannelExposureCheck.js +223 -0
  26. package/lib/checks/impl/AgentInventoryCheck.d.ts +15 -0
  27. package/lib/checks/impl/AgentInventoryCheck.js +228 -0
  28. package/lib/checks/impl/AgentMonitoringCoverageCheck.d.ts +12 -0
  29. package/lib/checks/impl/AgentMonitoringCoverageCheck.js +97 -0
  30. package/lib/checks/impl/AgentUserPrivilegeCheck.d.ts +13 -0
  31. package/lib/checks/impl/AgentUserPrivilegeCheck.js +204 -0
  32. package/lib/checks/impl/CspTrustedSitesCheck.d.ts +1 -0
  33. package/lib/checks/impl/CspTrustedSitesCheck.js +10 -1
  34. package/lib/checks/impl/TrustedUrlHygieneCheck.d.ts +16 -0
  35. package/lib/checks/impl/TrustedUrlHygieneCheck.js +198 -0
  36. package/lib/checks/registry.js +19 -0
  37. package/lib/commands/audit/apps.d.ts +16 -0
  38. package/lib/commands/audit/apps.js +64 -0
  39. package/lib/commands/audit/security.d.ts +1 -0
  40. package/lib/commands/audit/security.js +7 -1
  41. package/lib/compliance/catalogs/index.js +2 -0
  42. package/lib/compliance/catalogs/owaspLlm.d.ts +3 -0
  43. package/lib/compliance/catalogs/owaspLlm.js +34 -0
  44. package/lib/compliance/mapping.js +19 -0
  45. package/lib/compliance/resolve.js +4 -3
  46. package/lib/compliance/types.d.ts +1 -1
  47. package/lib/context/AuditCache.d.ts +28 -0
  48. package/lib/context/AuditContext.d.ts +4 -0
  49. package/lib/events/pullEventLogs.js +3 -3
  50. package/lib/findings/CheckMeta.js +6 -0
  51. package/lib/lib/wire.d.ts +2 -2
  52. package/lib/lib/wire.js +2 -1
  53. package/lib/renderers/ClientReportRenderer.js +1 -1
  54. package/package.json +4 -1
@@ -0,0 +1,104 @@
1
+ function parseCsv(text) {
2
+ const lines = text.split(/\r?\n/).filter((l) => l.length > 0);
3
+ if (lines.length === 0)
4
+ return [];
5
+ const header = splitCsvLine(lines[0]);
6
+ const headerToken = header[0]; // e.g. "EVENT_TYPE"
7
+ const rows = [];
8
+ for (const line of lines.slice(1)) {
9
+ // Skip embedded header rows (from multi-file concatenation) and blank lines.
10
+ const firstCell = splitCsvLine(line)[0];
11
+ if (firstCell === headerToken)
12
+ continue;
13
+ const cells = splitCsvLine(line);
14
+ const row = {};
15
+ header.forEach((h, i) => (row[h] = cells[i] ?? ''));
16
+ rows.push(row);
17
+ }
18
+ return rows;
19
+ }
20
+ // Minimal RFC-4180 line splitter (handles quoted cells; EventLogFile has no embedded newlines
21
+ // in these columns). Sufficient for API/RestApi logs.
22
+ function splitCsvLine(line) {
23
+ const out = [];
24
+ let cur = '';
25
+ let inq = false;
26
+ for (let i = 0; i < line.length; i++) {
27
+ const c = line[i];
28
+ if (inq) {
29
+ if (c === '"' && line[i + 1] === '"') {
30
+ cur += '"';
31
+ i++;
32
+ }
33
+ else if (c === '"')
34
+ inq = false;
35
+ else
36
+ cur += c;
37
+ }
38
+ else if (c === '"')
39
+ inq = true;
40
+ else if (c === ',') {
41
+ out.push(cur);
42
+ cur = '';
43
+ }
44
+ else
45
+ cur += c;
46
+ }
47
+ out.push(cur);
48
+ return out;
49
+ }
50
+ function verbOf(method) {
51
+ const m = method.toUpperCase();
52
+ if (m === 'DELETE')
53
+ return 'delete';
54
+ if (m === 'POST' || m === 'PATCH' || m === 'PUT')
55
+ return 'write';
56
+ return 'read';
57
+ }
58
+ export function collectUsage(restApiCsv, soapApiCsv) {
59
+ const rows = parseCsv(restApiCsv);
60
+ const byApp = new Map();
61
+ 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);
81
+ }
82
+ }
83
+ const soapUsers = new Set();
84
+ if (soapApiCsv) {
85
+ for (const row of parseCsv(soapApiCsv))
86
+ if (row.USER_ID)
87
+ soapUsers.add(row.USER_ID);
88
+ }
89
+ const usage = [...byApp.entries()].map(([appId, a]) => ({
90
+ appId,
91
+ objects: [...a.objects.entries()].map(([object, verbs]) => ({ object, verbs: [...verbs].sort() })),
92
+ requests: a.requests,
93
+ rowsProcessed: a.rows,
94
+ userIds: [...a.users].sort(),
95
+ soapOnly: false,
96
+ }));
97
+ return {
98
+ usage: usage.sort((x, y) => y.requests - x.requests),
99
+ totalRows: rows.length,
100
+ attributedRows: attributed,
101
+ attributionRatePct: rows.length ? Math.round((100 * attributed) / rows.length) : 0,
102
+ };
103
+ }
104
+ //# sourceMappingURL=usageCollector.js.map
@@ -1,6 +1,9 @@
1
1
  const has = (s, ...caps) => caps.every((c) => s.has(c));
2
2
  const hasAny = (s, ...caps) => caps.some((c) => s.has(c));
3
3
  const byIds = (active, ids) => active.filter((f) => ids.includes(f.id));
4
+ // The AI & Agents findings carry dynamic id suffixes (userId, agent dev name, channel slug,
5
+ // domain), so their chain ingredients are matched by id prefix rather than exact id.
6
+ const byPrefixes = (active, prefixes) => active.filter((f) => prefixes.some((p) => f.id === p || f.id.startsWith(p)));
4
7
  export const NAMED_CHAINS = [
5
8
  {
6
9
  id: 'unauth-bulk-exfil',
@@ -102,6 +105,48 @@ export const NAMED_CHAINS = [
102
105
  return sink.length > 0 ? [...inj, ...sink] : null;
103
106
  },
104
107
  },
108
+ {
109
+ id: 'prompt-injection-blast-radius',
110
+ title: 'Prompt injection blast radius',
111
+ severity: 'CRITICAL',
112
+ narrative: 'A guest-reachable Agentforce channel lets an unauthenticated attacker send prompt-injection input to an ' +
113
+ 'agent that runs as an over-privileged user (Modify/View All Data or broad object write) and can drive ' +
114
+ 'write-capable actions. Public input, privileged identity, and state-changing actions are all present at ' +
115
+ 'once, so a single injected prompt can read, alter, or destroy data across the agent\'s reach.',
116
+ remediation: 'Break any one link: remove the guest/public binding, scope the agent run-as user to least privilege, ' +
117
+ 'or remove write-capable actions from the exposed agent (and add confirmation/guardrails where they must stay).',
118
+ match(_present, active) {
119
+ const channel = byPrefixes(active, ['agent-channel-exposure-guest-']);
120
+ const privilege = byPrefixes(active, [
121
+ 'agent-user-privilege-admin-', 'agent-user-privilege-broad-write-',
122
+ ]);
123
+ const actions = byIds(active, ['agent-action-surface-write']);
124
+ if (channel.length === 0 || privilege.length === 0 || actions.length === 0)
125
+ return null;
126
+ return [...channel, ...privilege, ...actions];
127
+ },
128
+ },
129
+ {
130
+ id: 'forcedleak-pattern',
131
+ title: 'ForcedLeak pattern',
132
+ severity: 'CRITICAL',
133
+ narrative: 'Active Agentforce agents run in an org that has a stale CSP-trusted domain (unresolvable or parked) on ' +
134
+ 'its allowlist and no Event Monitoring capture of agent activity. This is the exact ForcedLeak chain ' +
135
+ '(Noma Security, Sept 2025): an attacker registers the lapsed allowlisted domain, prompt-injects an agent ' +
136
+ 'into sending data to it, and nothing records or responds to the exfiltration.',
137
+ remediation: 'Remove or reclaim the stale trusted domain immediately, then enable Event Monitoring (and pull agent logs ' +
138
+ 'with `sf audit events pull`) plus a Transaction Security policy so agent-driven exfiltration is detected.',
139
+ match(_present, active) {
140
+ const agents = byIds(active, ['agent-inventory-summary']);
141
+ const staleUrl = byPrefixes(active, [
142
+ 'trusted-url-hygiene-unresolvable-', 'trusted-url-hygiene-parked-',
143
+ ]);
144
+ const noCapture = byIds(active, ['agent-monitoring-coverage-none']);
145
+ if (agents.length === 0 || staleUrl.length === 0 || noCapture.length === 0)
146
+ return null;
147
+ return [...agents, ...staleUrl, ...noCapture];
148
+ },
149
+ },
105
150
  {
106
151
  id: 'mfa-bypass-admin',
107
152
  title: 'MFA bypass to privileged compromise',
@@ -0,0 +1,13 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class AgentActionSurfaceCheck implements SecurityCheck {
4
+ readonly id = "agent-action-surface";
5
+ readonly name = "Agent Action Surface";
6
+ readonly category = "AI & Agents";
7
+ readonly description = "Inventories Agentforce topics and actions (GenAiPlugin / GenAiFunction), flagging write-capable actions (Apex/Flow that create, update, or delete) and agents with an unusually large action surface. Write-capable actions on an exposed agent let a prompt injection take actions, not just read data.";
8
+ readonly dependsOnCache: readonly ["agentInventory", "agentAccess"];
9
+ run(ctx: AuditContext): Promise<CheckResult>;
10
+ private isWriteCapable;
11
+ private queryWithFallback;
12
+ }
13
+ //# sourceMappingURL=AgentActionSurfaceCheck.d.ts.map
@@ -0,0 +1,125 @@
1
+ import { isApiError } from '../../api/ApiError.js';
2
+ // An agent carrying more than this many actions has a large, hard-to-review surface. Info
3
+ // only — a big surface is not a vulnerability by itself, but it is worth surfacing.
4
+ const ACTION_COUNT_THRESHOLD = 15;
5
+ // Invocation target types that create/update/delete (or are ambiguous enough that we treat
6
+ // them as write-capable). Apex and Flow can both mutate data; where the type string is
7
+ // unknown/ambiguous we deliberately err toward flagging and say so in the finding.
8
+ const WRITE_CAPABLE_TYPE_HINTS = ['apex', 'flow'];
9
+ function isMissingObjectError(err) {
10
+ if (isApiError(err)) {
11
+ if (/INVALID_TYPE|NOT_FOUND|MALFORMED_QUERY/i.test(err.errorCode))
12
+ return true;
13
+ if (err.statusCode === 404)
14
+ return true;
15
+ }
16
+ const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
17
+ return (msg.includes('not supported') ||
18
+ msg.includes('invalid type') ||
19
+ msg.includes('sobject type'));
20
+ }
21
+ export class AgentActionSurfaceCheck {
22
+ id = 'agent-action-surface';
23
+ name = 'Agent Action Surface';
24
+ category = 'AI & Agents';
25
+ description = 'Inventories Agentforce topics and actions (GenAiPlugin / GenAiFunction), flagging write-capable actions (Apex/Flow that create, update, or delete) and agents with an unusually large action surface. Write-capable actions on an exposed agent let a prompt injection take actions, not just read data.';
26
+ dependsOnCache = ['agentInventory', 'agentAccess'];
27
+ async run(ctx) {
28
+ const findings = [];
29
+ // Gate: only run when AgentInventoryCheck confirmed the agent queries succeeded.
30
+ if (ctx.cache.agentAccess !== 'ok')
31
+ return { findings };
32
+ const inventory = ctx.cache.agentInventory ?? [];
33
+ const activeAgents = inventory.filter((a) => a.type === 'agent' && a.isActive);
34
+ if (activeAgents.length === 0)
35
+ return { findings };
36
+ // Query the org-wide action surface. GenAiFunction and its *Definition twin are queried
37
+ // defensively (INVALID_TYPE on one falls back to the other); if neither resolves, the
38
+ // feature does not expose actions in this org and we degrade silently.
39
+ const functions = await this.queryWithFallback(ctx, 'GenAiFunction', 'SELECT Id, DeveloperName, MasterLabel, InvocationTarget, InvocationTargetType');
40
+ if (functions === null)
41
+ return { findings };
42
+ // Topics (plugins) are supplementary context; a failure here is non-fatal.
43
+ const plugins = (await this.queryWithFallback(ctx, 'GenAiPlugin', 'SELECT Id, DeveloperName, MasterLabel')) ?? [];
44
+ const baseUrl = ctx.orgInfo.instanceUrl;
45
+ const setupUrl = `${baseUrl}/lightning/setup/EinsteinCopilot/home`;
46
+ // Write-capable actions across the org. We cannot resolve which specific agent owns each
47
+ // action from Tooling alone (no reliable agent join here); Phase 3 chains correlate this
48
+ // finding with agent-channel-exposure. We therefore report the write surface against the
49
+ // active-agent population and say so explicitly.
50
+ const writeActions = functions.filter((f) => this.isWriteCapable(f));
51
+ if (writeActions.length > 0) {
52
+ const agentLabels = activeAgents.map((a) => `${a.label} (${a.developerName})`);
53
+ findings.push({
54
+ id: 'agent-action-surface-write',
55
+ category: this.category,
56
+ riskLevel: 'HIGH',
57
+ title: `${writeActions.length} write-capable agent action(s) present across ${activeAgents.length} active agent(s)`,
58
+ detail: `${writeActions.length} Agentforce action(s) invoke Apex or Flow, which can create, update, or ` +
59
+ `delete records. (Apex and Flow invocations are treated as write-capable; where an action's ` +
60
+ `invocation type is ambiguous it is flagged conservatively.) On an externally exposed agent, a ` +
61
+ `successful prompt injection can drive these actions to take state-changing operations, not just ` +
62
+ `read data. Actions: ${writeActions
63
+ .slice(0, 20)
64
+ .map((f) => `${f.MasterLabel ?? f.DeveloperName} [${(f.InvocationTargetType ?? 'unknown').toLowerCase()}]`)
65
+ .join(', ')}${writeActions.length > 20 ? `, and ${writeActions.length - 20} more` : ''}.`,
66
+ remediation: 'Review each write-capable action: confirm the operation is intended, add guardrails/confirmation ' +
67
+ 'where it mutates sensitive data, and ensure the agent exposing it is not reachable by untrusted users. ' +
68
+ 'Correlate with channel exposure to size the real risk.',
69
+ affectedItems: writeActions.map((f) => ({
70
+ label: f.MasterLabel ?? f.DeveloperName,
71
+ note: `${(f.InvocationTargetType ?? 'unknown').toLowerCase()} invocation` +
72
+ (f.InvocationTarget ? ` → ${f.InvocationTarget}` : '') +
73
+ ` | exposed via active agent(s): ${agentLabels.slice(0, 3).join(', ')}${agentLabels.length > 3 ? ', …' : ''}`,
74
+ })),
75
+ });
76
+ }
77
+ // Large action surface: informational. Reported at the org level because Tooling does not
78
+ // give us a per-agent action join; total actions and topics both inform review effort.
79
+ if (functions.length > ACTION_COUNT_THRESHOLD) {
80
+ findings.push({
81
+ id: 'agent-action-surface-count',
82
+ category: this.category,
83
+ riskLevel: 'INFO',
84
+ title: `Large agent action surface: ${functions.length} actions across ${plugins.length} topic(s)`,
85
+ detail: `The org exposes ${functions.length} Agentforce action(s) (threshold ${ACTION_COUNT_THRESHOLD}) across ` +
86
+ `${plugins.length} topic(s) and ${activeAgents.length} active agent(s). A large action surface is ` +
87
+ `harder to review and increases the chance a risky action is reachable through an agent. This is ` +
88
+ `informational, not a vulnerability by itself.`,
89
+ remediation: 'Periodically review the full action catalogue. Retire unused actions and keep each agent scoped to ' +
90
+ 'the minimum set of topics and actions it needs.',
91
+ affectedItems: [
92
+ {
93
+ label: `${functions.length} action(s)`,
94
+ url: setupUrl,
95
+ note: `${plugins.length} topic(s), ${activeAgents.length} active agent(s)`,
96
+ },
97
+ ],
98
+ });
99
+ }
100
+ return { findings };
101
+ }
102
+ isWriteCapable(f) {
103
+ const type = (f.InvocationTargetType ?? '').toLowerCase();
104
+ return WRITE_CAPABLE_TYPE_HINTS.some((h) => type.includes(h));
105
+ }
106
+ // Query `baseObject`, falling back to `${baseObject}Definition` when the Tooling client
107
+ // cannot address the base object (INVALID_TYPE etc.). Returns null only when BOTH the base
108
+ // and the *Definition twin are missing (feature absent → degrade silently).
109
+ async queryWithFallback(ctx, baseObject, selectClause) {
110
+ try {
111
+ return await ctx.tooling.query(`${selectClause} FROM ${baseObject}`);
112
+ }
113
+ catch (e1) {
114
+ if (!isMissingObjectError(e1))
115
+ return null;
116
+ try {
117
+ return await ctx.tooling.query(`${selectClause} FROM ${baseObject}Definition`);
118
+ }
119
+ catch {
120
+ return null;
121
+ }
122
+ }
123
+ }
124
+ }
125
+ //# sourceMappingURL=AgentActionSurfaceCheck.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 AgentChannelExposureCheck implements SecurityCheck {
4
+ readonly id = "agent-channel-exposure";
5
+ readonly name = "Agentforce Channel Exposure";
6
+ readonly category = "AI & Agents";
7
+ readonly description = "Correlates active Agentforce agents with the channels that reach them (Experience Cloud sites, embedded deployments, messaging channels) and flags guest-reachable exposure.";
8
+ readonly dependsOnCache: readonly ["agentInventory", "agentAccess"];
9
+ run(ctx: AuditContext): Promise<CheckResult>;
10
+ private queryGuestSites;
11
+ private queryMessagingChannels;
12
+ private queryEmbeddedDeployments;
13
+ private queryAgentChannelBindings;
14
+ }
15
+ //# sourceMappingURL=AgentChannelExposureCheck.d.ts.map
@@ -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