@cclabsnz/sf-audit 1.22.0 → 1.24.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 (37) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/PERMISSIONS.md +16 -2
  3. package/docs/permissionset/SF_Audit_MFA.permissionset-meta.xml +36 -0
  4. package/lib/chains/CapabilityRegistry.js +16 -8
  5. package/lib/chains/ChainEngine.js +10 -2
  6. package/lib/chains/namedChains.d.ts +1 -0
  7. package/lib/chains/namedChains.js +59 -26
  8. package/lib/checks/impl/ApexCrudFLSCheck.js +12 -3
  9. package/lib/checks/impl/ApexRestEndpointCheck.js +15 -7
  10. package/lib/checks/impl/ApexSharingCheck.js +19 -8
  11. package/lib/checks/impl/FlowsWithoutSharingCheck.d.ts +1 -1
  12. package/lib/checks/impl/FlowsWithoutSharingCheck.js +17 -12
  13. package/lib/checks/impl/GuestExecutableApexCheck.js +18 -9
  14. package/lib/checks/impl/GuestObjectExposureCheck.d.ts +6 -7
  15. package/lib/checks/impl/GuestObjectExposureCheck.js +123 -38
  16. package/lib/checks/impl/GuestSiteOptionsCheck.js +40 -6
  17. package/lib/checks/impl/GuestUserAccessCheck.d.ts +1 -0
  18. package/lib/checks/impl/GuestUserAccessCheck.js +88 -57
  19. package/lib/checks/impl/GuestUserVisibilityCheck.d.ts +9 -6
  20. package/lib/checks/impl/GuestUserVisibilityCheck.js +59 -66
  21. package/lib/checks/impl/HardcodedCredentialsCheck.js +3 -1
  22. package/lib/checks/impl/MfaMethodStrengthCheck.js +6 -5
  23. package/lib/checks/impl/MfaRegistrationCheck.d.ts +1 -1
  24. package/lib/checks/impl/MfaRegistrationCheck.js +67 -18
  25. package/lib/checks/impl/PublicGroupSharingCheck.js +7 -2
  26. package/lib/checks/impl/ReleaseUpdatesCheck.js +1 -1
  27. package/lib/checks/impl/SsoEnforcementCheck.js +6 -4
  28. package/lib/checks/support/apexAccess.d.ts +21 -1
  29. package/lib/checks/support/apexAccess.js +55 -0
  30. package/lib/checks/support/guestShares.d.ts +39 -0
  31. package/lib/checks/support/guestShares.js +113 -0
  32. package/lib/findings/CheckMeta.js +2 -2
  33. package/lib/preflight/permissions.d.ts +1 -1
  34. package/lib/preflight/permissions.js +10 -2
  35. package/lib/renderers/ClientReportRenderer.d.ts +2 -0
  36. package/lib/renderers/ClientReportRenderer.js +18 -3
  37. package/package.json +3 -2
@@ -9,7 +9,10 @@ export class PublicGroupSharingCheck {
9
9
  const findings = [];
10
10
  const baseUrl = ctx.orgInfo.instanceUrl;
11
11
  const sharingRulesUrl = `${baseUrl}/lightning/setup/SecuritySharing/page`;
12
- const groups = await ctx.soql.queryAll("SELECT Id, Name, Type FROM Group WHERE Type = 'AllInternal'");
12
+ const groups = await ctx.soql.queryAll(
13
+ // The All Internal Users group is the one Group of Type 'Organization' (DeveloperName
14
+ // AllInternalUsers). There is no 'AllInternal' type: a filter on it matched nothing.
15
+ "SELECT Id, Name, Type FROM Group WHERE Type = 'Organization'");
13
16
  if (groups.length === 0) {
14
17
  findings.push({
15
18
  id: 'public-group-sharing-none',
@@ -30,12 +33,14 @@ export class PublicGroupSharingCheck {
30
33
  // simply not permitted; either way the check did not see it, and the conclusion has to say
31
34
  // so rather than count silence as evidence of no sharing.
32
35
  const unreadable = [];
36
+ // Sharing rules write RowCause 'Rule'; there is no 'SharingRule' value, and a filter on it
37
+ // matched no row.
33
38
  for (const shareTable of SHARE_TABLES) {
34
39
  try {
35
40
  const result = await ctx.soql.query(`SELECT UserOrGroupId, COUNT(Id) cnt
36
41
  FROM ${shareTable}
37
42
  WHERE UserOrGroupId IN (${groupIdList})
38
- AND RowCause = 'SharingRule'
43
+ AND RowCause = 'Rule'
39
44
  GROUP BY UserOrGroupId`);
40
45
  for (const r of result.records) {
41
46
  if (r.cnt > 0) {
@@ -13,7 +13,7 @@ export class ReleaseUpdatesCheck {
13
13
  // Current orgs expose Release Updates as Tooling ReleaseUpdate; CriticalUpdate is the older
14
14
  // object, absent from current releases. Use whichever this org serves.
15
15
  if (await fieldsOf(ctx, 'ReleaseUpdate', 'tooling')) {
16
- const rows = await ctx.tooling.query("SELECT Id, DeveloperName, Title, Description, DueDate, Status FROM ReleaseUpdate WHERE Status IN ('Invocable', 'Revoked')");
16
+ const rows = await ctx.tooling.query("SELECT Id, DeveloperName, Title, Description, DueDate, Status FROM ReleaseUpdate WHERE Status = 'Invocable'");
17
17
  pendingUpdates = rows.map((r) => ({
18
18
  Id: r.Id,
19
19
  Name: r.Title || r.DeveloperName,
@@ -8,14 +8,16 @@ export class SsoEnforcementCheck {
8
8
  const baseUrl = ctx.orgInfo.instanceUrl;
9
9
  try {
10
10
  // Single query: recent credential logins over the past 30 days.
11
- // Presence of 'Username-Password' logins is direct evidence that SBS-AUTH-001
12
- // (org-wide SSO enforcement) is not fully applied.
11
+ // Logins with Salesforce credentials are direct evidence that SBS-AUTH-001 (org-wide SSO
12
+ // enforcement) is not fully applied. LoginSubType records them, through the UI or the OAuth
13
+ // username-password flow; LoginType has no 'Username-Password' value, so a filter on it
14
+ // matched nothing and every org passed.
13
15
  const result = await ctx.soql.queryAll(
14
16
  // LoginHistory carries no Username field and no User relationship; names are resolved below.
15
- `SELECT Id, UserId, LoginType, LoginTime
17
+ `SELECT Id, UserId, LoginType, LoginSubType, LoginTime
16
18
  FROM LoginHistory
17
19
  WHERE LoginTime > LAST_N_DAYS:30
18
- AND LoginType = 'Username-Password'
20
+ AND LoginSubType IN ('UI Username-Password', 'OAuth Username-Password')
19
21
  ORDER BY LoginTime DESC
20
22
  LIMIT 300`);
21
23
  const records = result;
@@ -1,9 +1,11 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
1
2
  /**
2
3
  * How an Apex class's record sharing and CRUD/FLS are controlled (spec/apex-access-mode.md).
3
4
  *
4
5
  * Record sharing follows the class's own sharing keyword. WITH SYSTEM_MODE and
5
6
  * 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
+ * keyword runs with its caller's sharing, and as an entry point (Aura, REST, guest) without it,
8
+ * unless it is compiled at API 67.0 or later (Summer '26), where an omitted keyword means with sharing.
7
9
  */
8
10
  export type SharingKeyword = 'with' | 'without' | 'inherited' | 'none';
9
11
  export declare const SYSTEM_MODE: RegExp;
@@ -42,6 +44,24 @@ export declare function parentClass(className: string, body: string): string | u
42
44
  * `lookup` returns a class body by name; unknown parents leave the keyword as declared.
43
45
  */
44
46
  export declare function effectiveSharing(className: string, body: string, lookup: (name: string) => string | undefined): SharingKeyword | null;
47
+ /** From Summer '26 (API 67.0), a class compiled at this version or later with no sharing keyword runs with sharing. */
48
+ export declare const OMITTED_SHARING_ENFORCED_FROM = 67;
49
+ /**
50
+ * Whether a class whose effective sharing is 'none' still enforces sharing because every class
51
+ * that decides it (the class, and each parent it inherits from while none declares a keyword) is
52
+ * compiled at API 67.0 or later. A class whose version is unknown, such as a parent outside the
53
+ * org's own code, keeps the old default: the answer errs towards reporting.
54
+ */
55
+ export declare function omittedSharingEnforced(className: string, body: string, lookup: (name: string) => string | undefined, versionOf: (name: string) => number | undefined): boolean;
56
+ /** Each org-local Apex class's API version, keyed by lower-cased name; empty when it cannot be read. */
57
+ export declare function apexApiVersions(ctx: AuditContext): Promise<Map<string, number>>;
58
+ /**
59
+ * Whether a keyword-less class can be entered only through @AuraEnabled methods. Since the "Use with
60
+ * sharing for @AuraEnabled Apex Controllers with Implicit Sharing" update (enforced from Winter '21),
61
+ * an Aura or LWC call into a class with no keyword runs with sharing, so such a class does not run
62
+ * without sharing whatever its API version. A class that can also be entered another way can.
63
+ */
64
+ export declare function enteredOnlyThroughAura(body: string): boolean;
45
65
  /** Whether the class's code (not its comments) uses SYSTEM_MODE anywhere. */
46
66
  export declare function usesSystemMode(body: string): boolean;
47
67
  /**
@@ -108,6 +108,61 @@ export function effectiveSharing(className, body, lookup) {
108
108
  current = parentBody;
109
109
  }
110
110
  }
111
+ /** From Summer '26 (API 67.0), a class compiled at this version or later with no sharing keyword runs with sharing. */
112
+ export const OMITTED_SHARING_ENFORCED_FROM = 67;
113
+ /**
114
+ * Whether a class whose effective sharing is 'none' still enforces sharing because every class
115
+ * that decides it (the class, and each parent it inherits from while none declares a keyword) is
116
+ * compiled at API 67.0 or later. A class whose version is unknown, such as a parent outside the
117
+ * org's own code, keeps the old default: the answer errs towards reporting.
118
+ */
119
+ export function omittedSharingEnforced(className, body, lookup, versionOf) {
120
+ let name = className;
121
+ let current = body;
122
+ const seen = new Set();
123
+ for (;;) {
124
+ // A parent whose body is unreadable may declare without sharing, which the child would inherit.
125
+ if (current === undefined)
126
+ return false;
127
+ // A class that declares a keyword decides the sharing itself, whatever its version.
128
+ const keyword = sharingKeyword(name, current);
129
+ if (keyword !== 'none' && keyword !== null)
130
+ return keyword !== 'without';
131
+ if ((versionOf(name) ?? 0) < OMITTED_SHARING_ENFORCED_FROM)
132
+ return false;
133
+ const parent = parentClass(name, current);
134
+ if (!parent || seen.has(parent.toLowerCase()))
135
+ return true;
136
+ seen.add(parent.toLowerCase());
137
+ name = parent;
138
+ current = lookup(parent);
139
+ }
140
+ }
141
+ /** Each org-local Apex class's API version, keyed by lower-cased name; empty when it cannot be read. */
142
+ export async function apexApiVersions(ctx) {
143
+ try {
144
+ const rows = await ctx.soql.queryAll('SELECT Name, ApiVersion FROM ApexClass WHERE NamespacePrefix = null');
145
+ return new Map((rows ?? []).filter((r) => r?.Name).map((r) => [r.Name.toLowerCase(), Number(r.ApiVersion)]));
146
+ }
147
+ catch {
148
+ return new Map();
149
+ }
150
+ }
151
+ // Ways into a class other than an Aura/LWC call: REST, SOAP, Visualforce remoting, flow actions
152
+ // (@InvocableMethod, @InvocableVariable), and Visualforce controllers, which use ApexPages, return a
153
+ // PageReference, or expose properties (`{ get; set; }`, `get { ... }`) that a page reads. A
154
+ // controller with none of these cannot be told apart from Aura-only code, so the list errs wide.
155
+ const NON_AURA_ENTRY = /@RemoteAction\b|@RestResource\b|@Http(?:Get|Post|Put|Patch|Delete)\b|\bwebservice\b|@Invocable(?:Method|Variable)\b|\bApexPages\s*\.|\bPageReference\b|\bget\s*[;{]/i;
156
+ /**
157
+ * Whether a keyword-less class can be entered only through @AuraEnabled methods. Since the "Use with
158
+ * sharing for @AuraEnabled Apex Controllers with Implicit Sharing" update (enforced from Winter '21),
159
+ * an Aura or LWC call into a class with no keyword runs with sharing, so such a class does not run
160
+ * without sharing whatever its API version. A class that can also be entered another way can.
161
+ */
162
+ export function enteredOnlyThroughAura(body) {
163
+ const code = codeWithoutStrings(body);
164
+ return /@AuraEnabled\b/i.test(code) && !NON_AURA_ENTRY.test(code);
165
+ }
111
166
  /** Whether the class's code (not its comments) uses SYSTEM_MODE anywhere. */
112
167
  export function usesSystemMode(body) {
113
168
  const code = apexCode(body);
@@ -0,0 +1,39 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ /**
3
+ * How records are shared with unauthenticated guest users, read from share tables.
4
+ *
5
+ * Since Winter '21 the only new way to share a record with a guest is a guest user sharing rule:
6
+ * its rows carry RowCause 'GuestRule' and name the site's guest user group (Group Type
7
+ * 'GuestUserGroup'), not the guest user (seen on a live org, test/fixtures/org/guest-share); the
8
+ * parent or person-account access it implies carries 'GuestParentImplicit' / 'GuestPersonImplicit'
9
+ * (AccountShare picklist values). Those rows are counted whoever they name. Access granted before Winter '21 was not
10
+ * removed: manual and Apex-managed shares to a guest user, and a guest's membership of a public
11
+ * group or queue, still give access until someone cleans them up. So rows naming a guest user
12
+ * (other than its ownership, which is reported on its own) or a group a guest belongs to count too.
13
+ */
14
+ export declare const GUEST_ROW_CAUSES: readonly ['GuestRule', 'GuestParentImplicit', 'GuestPersonImplicit'];
15
+ export interface GuestPrincipals {
16
+ users: string[];
17
+ /**
18
+ * Groups whose members are guests: each site's guest user group (Group Type 'GuestUserGroup',
19
+ * whose membership GroupMember does not list), and public groups and queues a guest user belongs
20
+ * to. Empty when neither can be read.
21
+ */
22
+ groups: string[];
23
+ }
24
+ export declare function guestPrincipals(ctx: AuditContext, guestIds: string[]): Promise<GuestPrincipals>;
25
+ /**
26
+ * Ground-truth read confirmation via UserRecordAccess on up to 200 sample records (the most one
27
+ * UserRecordAccess query takes), from both ends of the object's history. UserRecordAccess takes one
28
+ * user per query, and each site has its own guest user with its own guest sharing rules, so every
29
+ * guest user is asked. True when any guest reads any sampled record; null when the object has no
30
+ * record to sample; 'failed' when a query fails.
31
+ */
32
+ export declare function guestReadsSample(ctx: AuditContext, obj: string, guestIds: string[]): Promise<boolean | null | 'failed'>;
33
+ /** The WHERE condition matching every share row that gives a guest user access to a record. */
34
+ export declare function guestShareWhere(p: GuestPrincipals): string;
35
+ /** The share table of an object: AccountShare for standard objects, Foo__Share for Foo__c. */
36
+ export declare function shareTableOf(obj: string): string;
37
+ /** Share rows giving guests access to the object's records; null when it has no readable share table. */
38
+ export declare function guestShareCount(ctx: AuditContext, obj: string, p: GuestPrincipals): Promise<number | null>;
39
+ //# sourceMappingURL=guestShares.d.ts.map
@@ -0,0 +1,113 @@
1
+ /**
2
+ * How records are shared with unauthenticated guest users, read from share tables.
3
+ *
4
+ * Since Winter '21 the only new way to share a record with a guest is a guest user sharing rule:
5
+ * its rows carry RowCause 'GuestRule' and name the site's guest user group (Group Type
6
+ * 'GuestUserGroup'), not the guest user (seen on a live org, test/fixtures/org/guest-share); the
7
+ * parent or person-account access it implies carries 'GuestParentImplicit' / 'GuestPersonImplicit'
8
+ * (AccountShare picklist values). Those rows are counted whoever they name. Access granted before Winter '21 was not
9
+ * removed: manual and Apex-managed shares to a guest user, and a guest's membership of a public
10
+ * group or queue, still give access until someone cleans them up. So rows naming a guest user
11
+ * (other than its ownership, which is reported on its own) or a group a guest belongs to count too.
12
+ */
13
+ export const GUEST_ROW_CAUSES = ['GuestRule', 'GuestParentImplicit', 'GuestPersonImplicit'];
14
+ const quote = (ids) => ids.map((i) => `'${i}'`).join(', ');
15
+ export async function guestPrincipals(ctx, guestIds) {
16
+ if (guestIds.length === 0)
17
+ return { users: [], groups: [] };
18
+ const groups = new Set();
19
+ try {
20
+ const guestGroups = await ctx.soql.queryAll("SELECT Id FROM Group WHERE Type = 'GuestUserGroup'");
21
+ for (const g of guestGroups ?? [])
22
+ if (g?.Id)
23
+ groups.add(g.Id);
24
+ }
25
+ catch {
26
+ // Not readable: shares naming a guest user group are then found only through UserRecordAccess.
27
+ }
28
+ // A group that contains a group a guest belongs to gives the guest its access too, so membership
29
+ // is followed outwards until no new group appears (bounded, in case of a cycle or a deep tree).
30
+ let frontier = [...guestIds, ...groups];
31
+ for (let depth = 0; depth < MAX_GROUP_DEPTH && frontier.length > 0; depth++) {
32
+ let rows;
33
+ try {
34
+ rows = await ctx.soql.queryAll(`SELECT GroupId FROM GroupMember WHERE UserOrGroupId IN (${quote(frontier)})`);
35
+ }
36
+ catch {
37
+ break; // Not readable: legacy group membership is then found only through UserRecordAccess.
38
+ }
39
+ frontier = [...new Set((rows ?? []).map((r) => r?.GroupId).filter((g) => Boolean(g) && !groups.has(g)))];
40
+ for (const g of frontier)
41
+ groups.add(g);
42
+ }
43
+ return { users: guestIds, groups: [...groups] };
44
+ }
45
+ /** How many levels of nested public groups are followed. */
46
+ const MAX_GROUP_DEPTH = 5;
47
+ /**
48
+ * Up to 200 record Ids to probe: the 100 most recently changed and the 100 least recently changed,
49
+ * so a share whose criteria match only new (or only old) records is not missed by an unordered
50
+ * sample that happens to read one end. Falls back to an unordered sample when the object cannot be
51
+ * ordered by SystemModstamp.
52
+ */
53
+ async function sampleIds(ctx, obj) {
54
+ try {
55
+ const [newest, oldest] = await Promise.all([
56
+ ctx.soql.query(`SELECT Id FROM ${obj} ORDER BY SystemModstamp DESC LIMIT 100`),
57
+ ctx.soql.query(`SELECT Id FROM ${obj} ORDER BY SystemModstamp ASC LIMIT 100`),
58
+ ]);
59
+ return [...new Set([...(newest.records ?? []), ...(oldest.records ?? [])].map((r) => r.Id))];
60
+ }
61
+ catch {
62
+ const sample = await ctx.soql.query(`SELECT Id FROM ${obj} LIMIT 200`);
63
+ return (sample.records ?? []).map((r) => r.Id);
64
+ }
65
+ }
66
+ /**
67
+ * Ground-truth read confirmation via UserRecordAccess on up to 200 sample records (the most one
68
+ * UserRecordAccess query takes), from both ends of the object's history. UserRecordAccess takes one
69
+ * user per query, and each site has its own guest user with its own guest sharing rules, so every
70
+ * guest user is asked. True when any guest reads any sampled record; null when the object has no
71
+ * record to sample; 'failed' when a query fails.
72
+ */
73
+ export async function guestReadsSample(ctx, obj, guestIds) {
74
+ try {
75
+ const ids = await sampleIds(ctx, obj);
76
+ if (ids.length === 0)
77
+ return null;
78
+ const inIds = quote(ids);
79
+ for (const guestId of guestIds) {
80
+ const access = await ctx.soql.queryAll(`SELECT RecordId, HasReadAccess FROM UserRecordAccess WHERE UserId = '${guestId}' AND RecordId IN (${inIds})`);
81
+ if (access.some((a) => a.HasReadAccess === true))
82
+ return true;
83
+ }
84
+ return false;
85
+ }
86
+ catch {
87
+ return 'failed';
88
+ }
89
+ }
90
+ /** The WHERE condition matching every share row that gives a guest user access to a record. */
91
+ export function guestShareWhere(p) {
92
+ const parts = [`RowCause IN (${GUEST_ROW_CAUSES.map((c) => `'${c}'`).join(', ')})`];
93
+ if (p.users.length > 0)
94
+ parts.push(`(UserOrGroupId IN (${quote(p.users)}) AND RowCause != 'Owner')`);
95
+ if (p.groups.length > 0)
96
+ parts.push(`UserOrGroupId IN (${quote(p.groups)})`);
97
+ return parts.join(' OR ');
98
+ }
99
+ /** The share table of an object: AccountShare for standard objects, Foo__Share for Foo__c. */
100
+ export function shareTableOf(obj) {
101
+ return obj.endsWith('__c') ? `${obj.slice(0, -3)}__Share` : `${obj}Share`;
102
+ }
103
+ /** Share rows giving guests access to the object's records; null when it has no readable share table. */
104
+ export async function guestShareCount(ctx, obj, p) {
105
+ try {
106
+ const r = await ctx.soql.query(`SELECT COUNT() FROM ${shareTableOf(obj)} WHERE ${guestShareWhere(p)}`);
107
+ return r.totalSize;
108
+ }
109
+ catch {
110
+ return null;
111
+ }
112
+ }
113
+ //# sourceMappingURL=guestShares.js.map
@@ -69,7 +69,7 @@ export const CHECK_META = {
69
69
  'public-content-exposure': { effort: 'quick', impact: 'Documents marked externally available and public static resources are retrievable without authentication by anyone with the URL.' },
70
70
  'privileged-access': { effort: 'moderate', impact: 'Shadow admins hold full org control outside the admin profile, so a single takeover bypasses admin-focused monitoring and owns everything.' },
71
71
  'separation-of-duties': { effort: 'moderate', impact: 'A single user holding a toxic permission combination can self-escalate, commit fraud, or tamper undetected with no second party to stop them.' },
72
- 'guest-object-exposure': { effort: 'moderate', impact: 'Grades guest-readable objects by ACTUAL UI-API reachability: objects the UI API models are bulk-readable unauthenticated via GraphQL (CRITICAL, incl. guest-owned records under a Private OWD, enabling mass PII exfiltration without login); objects readable only in the sharing model but not UI-API-modelled (Calendar, AuthSession, etc.) are separated as MEDIUM defense-in-depth, with UserRecordAccess as ground-truth read confirmation.' },
72
+ 'guest-object-exposure': { effort: 'moderate', impact: 'Grades guest-readable objects by ACTUAL UI-API reachability: objects the UI API models whose records the guest owns are bulk-readable unauthenticated via GraphQL (CRITICAL, enabling mass PII exfiltration without login); records shared with guests whatever the OWD (guest sharing rules, legacy manual, Apex or group shares, or a read UserRecordAccess confirms) are HIGH, for the org to confirm they are meant to be public; a public external OWD without a confirmed guest read is MEDIUM, since secure guest record access means the OWD alone gives guests nothing; objects readable only in the sharing model but not UI-API-modelled (Calendar, AuthSession, etc.) are MEDIUM defense-in-depth.' },
73
73
  'guest-site-options': { effort: 'quick', impact: 'Guest file access and member visibility let unauthenticated visitors download public files and enumerate site members.' },
74
74
  'threat-detection': { effort: 'moderate', impact: 'Without Guest User Anomaly storage, malicious guest bulk-reads are never flagged and cannot be reconstructed after the fact.' },
75
75
  'guest-record-access-policy': { effort: 'quick', impact: 'Without "Secure guest user record access" enforced, guests own the records they submit and can read them under a Private OWD, turning a public form into an unauthenticated bulk-read surface.' },
@@ -79,7 +79,7 @@ export const CHECK_META = {
79
79
  'classic-sites': { effort: 'moderate', impact: 'Active classic Visualforce sites expose a second unauthenticated guest surface that the Experience Cloud checks never inspect.' },
80
80
  'auth-providers': { effort: 'moderate', impact: 'Unvetted social/SAML identity providers with just-in-time provisioning can let attackers federate in or auto-create over-privileged users.' },
81
81
  'guest-api-access': { effort: 'quick', impact: 'A guest user with API access can drive the raw REST/Bulk API, turning readable objects into scriptable mass extraction (and Hard Delete into irreversible destruction) without login.' },
82
- 'guest-user-visibility': { effort: 'quick', impact: 'A guest holding View All Users, or a public external OWD on User, hands unauthenticated visitors the full staff roster — a ready-made target list for phishing and credential stuffing against named admins.' },
82
+ 'guest-user-visibility': { effort: 'quick', impact: 'A guest holding View All Users hands unauthenticated visitors the full staff roster — a ready-made target list for phishing and credential stuffing against named admins. A public external OWD on User shows the same roster to every logged-in portal or community user (not to guests, whose OWD is always Private).' },
83
83
  'external-credentials': { effort: 'moderate', impact: 'Callouts with no or custom authentication can be spoofed or leak a static secret, exposing the integrated system and the data crossing it.' },
84
84
  'login-anomaly': { effort: 'quick', impact: 'An account logging in from many distinct IPs signals credential sharing or compromise; caught late, it means an attacker already has a working session.' },
85
85
  'session-hardening': { effort: 'quick', impact: 'Weak clickjack/CSRF/session-lock/XSS settings let attackers hijack authenticated sessions via framing, forged requests, or injected script.' },
@@ -1,6 +1,6 @@
1
1
  import type { AuditCache } from '@cclabsnz/sf-core';
2
2
  import type { SecurityCheck } from '../checks/SecurityCheck.js';
3
- export type AuditPermission = 'ApiEnabled' | 'ViewSetup' | 'ViewAllUsers' | 'ViewHealthCheckScreen' | 'AuthorApex' | 'ViewEventLogFiles';
3
+ export type AuditPermission = 'ApiEnabled' | 'ViewSetup' | 'ViewAllUsers' | 'ViewHealthCheckScreen' | 'AuthorApex' | 'ViewEventLogFiles' | 'ManageTwoFactor';
4
4
  export interface PermissionSpec {
5
5
  /** Field on UserPermissionAccess carrying the effective grant. */
6
6
  readonly field: string;
@@ -16,9 +16,17 @@ export const AUDIT_PERMISSIONS = {
16
16
  ViewAllUsers: {
17
17
  field: 'PermissionsViewAllUsers',
18
18
  label: 'View All Users',
19
- impact: 'Enumerates every User, PermissionSetAssignment and TwoFactorInfo org-wide. Without it the user, ' +
19
+ impact: 'Enumerates every User and PermissionSetAssignment org-wide. Without it the user, ' +
20
20
  'admin and MFA checks under-count and miss accounts outside the role hierarchy.',
21
- cacheKeys: ['mfaRegistrations', 'effectivePermissions'],
21
+ cacheKeys: ['effectivePermissions'],
22
+ },
23
+ ManageTwoFactor: {
24
+ field: 'PermissionsManageTwoFactor',
25
+ label: 'Manage MFA in API (optional)',
26
+ impact: 'Shows TwoFactorMethodsInfo, which records each user\'s MFA methods. Without it MFA registration and method ' +
27
+ 'strength are inconclusive. Salesforce grants it only with user-management permissions, so it is optional ' +
28
+ 'and not in the read-only permission set (PERMISSIONS.md).',
29
+ cacheKeys: ['mfaRegistrations'],
22
30
  },
23
31
  ViewHealthCheckScreen: {
24
32
  field: 'PermissionsViewHealthCheck',
@@ -28,6 +28,8 @@ export declare class ClientReportRenderer implements AuditRenderer {
28
28
  private stepMeta;
29
29
  private steps;
30
30
  private chainSlide;
31
+ /** Why a chain is rated above or below its steps, so the rating never looks like an error. */
32
+ private ratingNote;
31
33
  private potentialSlide;
32
34
  private roadmapPage;
33
35
  private worst;
@@ -479,7 +479,7 @@ ${head}<div class="content">${s.body}</div>
479
479
  const cheap = big.filter((x) => x.a.effort !== 'project').map((x) => x.n);
480
480
  const costly = big.filter((x) => x.a.effort === 'project').map((x) => x.n);
481
481
  const headline = realMax === 0 ? 'None of these actions removes critical or high-severity risk'
482
- : cheap.length && costly.length ? `Action${cheap.length === 1 ? '' : 's'} ${nums(cheap)} ${verb(cheap.length, 'is', 'are')} the cheapest large risk reduction${cheap.length === 1 ? '' : 's'}; ${nums(costly)} ${verb(costly.length, 'removes', 'remove')} as much but ${verb(costly.length, 'needs', 'need')} project funding`
482
+ : cheap.length && costly.length ? `Action${cheap.length === 1 ? '' : 's'} ${nums(cheap)} ${verb(cheap.length, 'is', 'are')} the cheapest large risk reduction${cheap.length === 1 ? '' : 's'}; ${nums(costly)} also ${verb(costly.length, 'removes', 'remove')} large risk but ${verb(costly.length, 'needs', 'need')} project funding`
483
483
  : cheap.length ? `Action${cheap.length === 1 ? '' : 's'} ${nums(cheap)} remove${cheap.length === 1 ? 's' : ''} the most risk for days of work or less`
484
484
  : `The largest risk reductions (${nums(costly)}) need project funding`;
485
485
  const key = shown.map((a, i) => `<li><span class="num w${a.wave}">${i + 1}</span><span>${esc(a.title)}</span><span class="e">${EFFORT_LABEL[a.effort]}</span></li>`).join('');
@@ -644,9 +644,24 @@ ${pts}<div class="yl"><span>Risk removed →</span></div><div class="xl"><span>U
644
644
  <div class="narr"><p>${esc(c.narrative)}</p></div>
645
645
  <div class="breaks"><p><strong>Breaks the chain:</strong> ${esc(c.abuseCase.breakPoint)}</p></div>
646
646
  <div class="full"><p><strong>Full remediation:</strong> ${esc(c.remediation)}</p></div></div></div>`,
647
- source: `Steps run in attack order. Steps marked ✂ are the break point: fixing all of them stops the chain. References point to the findings appendix.`,
647
+ source: `${this.ratingNote(c)}Steps run in attack order. Steps marked ✂ are the break point: fixing all of them stops the chain. References point to the findings appendix.`,
648
648
  };
649
649
  }
650
+ /** Why a chain is rated above or below its steps, so the rating never looks like an error. */
651
+ ratingNote(c) {
652
+ const steps = c.steps.map((s) => s.severity).filter((x) => !!x);
653
+ if (!steps.length)
654
+ return '';
655
+ const worst = steps.reduce((a, b) => (SEV_RANK[b] < SEV_RANK[a] ? b : a));
656
+ const chain = cap(c.severity.toLowerCase());
657
+ if (SEV_RANK[c.severity] < SEV_RANK[worst]) {
658
+ return `Rated ${chain} as a path; its steps are rated up to ${worst.toLowerCase()}. `;
659
+ }
660
+ if (SEV_RANK[c.severity] > SEV_RANK[worst]) {
661
+ return `Rated ${chain} as a path; its ${worst.toLowerCase()} step is also counted on its own in the findings and the grade. `;
662
+ }
663
+ return '';
664
+ }
650
665
  potentialSlide(list) {
651
666
  const rows = list.map(({ c, i }) => `<tr><td style="width:56px;color:var(--accent);font-weight:700">${this.labels[i]}</td><td><strong>${esc(c.title)}</strong><div style="font-size:13.5px;margin-top:4px;color:#3a434d">${esc(c.narrative)}</div><div class="muted" style="font-size:13px;margin-top:4px">${c.steps.map((s) => title(s.title || s.findingId)).join(' → ')}</div></td><td style="width:42%"><div class="breaks potential" style="margin-top:0"><p><strong>Recommended fixes:</strong> ${esc(c.remediation)}</p></div></td></tr>`).join('');
652
667
  return {
@@ -753,7 +768,7 @@ ${this.footer(b)}`,
753
768
  ? ` · <a href="https://${esc(b.website.replace(/^https?:\/\//, ''))}">${esc(b.website.replace(/^https?:\/\//, ''))}</a>`
754
769
  : '';
755
770
  return `<footer><span class="lbl">Scope &amp; Liability</span>
756
- Read-only, point-in-time configuration review: not a penetration test, not a code audit. The grade is a prioritisation aid, not a certification. Validate findings before remediation. © ${new Date().getFullYear()} ${esc(b.firmName)} · ${esc(b.contact)}${site}<br>${toolCreditHtml('executive-report')}</footer>`;
771
+ Read-only, point-in-time review of configuration, metadata, selected records and event logs, including pattern-based static checks of Apex and Flow: not a penetration test and not a code review. The grade is a prioritisation aid, not a certification. Confirm each finding in the org before changing production. © ${new Date().getFullYear()} ${esc(b.firmName)} · ${esc(b.contact)}${site}<br>${toolCreditHtml('executive-report')}</footer>`;
757
772
  }
758
773
  }
759
774
  //# sourceMappingURL=ClientReportRenderer.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cclabsnz/sf-audit",
3
- "version": "1.22.0",
3
+ "version": "1.24.0",
4
4
  "description": "Read-only Salesforce security audit for the sf CLI: 109 checks, attack-chain correlation, A-F risk grading, compliance mapping, free EventLogFile capture, and Guest User Anomaly investigation.",
5
5
  "keywords": [
6
6
  "salesforce",
@@ -116,7 +116,8 @@
116
116
  "brace-expansion": "^5.0.11",
117
117
  "fast-uri@3": "^3.1.9",
118
118
  "browserslist": "^4.28.7",
119
- "@istanbuljs/load-nyc-config>js-yaml": "^4.1.1"
119
+ "@istanbuljs/load-nyc-config>js-yaml": "^4.1.1",
120
+ "jest-config>deepmerge": "4.1.1"
120
121
  }
121
122
  }
122
123
  }