@cclabsnz/sf-core 0.9.0 → 0.11.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.
- package/CHANGELOG.md +36 -0
- package/lib/api/RestClientImpl.js +4 -4
- package/lib/api/index.d.ts +1 -0
- package/lib/api/index.js +1 -0
- package/lib/api/soqlBind.d.ts +60 -0
- package/lib/api/soqlBind.js +188 -0
- package/lib/context/AuditCache.d.ts +2 -0
- package/lib/crypto/bundleCrypto.d.ts +20 -0
- package/lib/crypto/bundleCrypto.js +96 -0
- package/lib/events/EventBaselineStore.js +9 -2
- package/lib/fs/secureFs.d.ts +42 -0
- package/lib/fs/secureFs.js +105 -0
- package/lib/index.d.ts +3 -1
- package/lib/index.js +5 -1
- package/lib/platform/index.d.ts +1 -1
- package/lib/platform/index.js +1 -1
- package/lib/platform/salesforceId.d.ts +20 -0
- package/lib/platform/salesforceId.js +54 -0
- package/lib/renderers/html-utils.d.ts +3 -1
- package/lib/renderers/html-utils.js +7 -2
- package/lib/testing/invariants.d.ts +6 -0
- package/lib/testing/invariants.js +21 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -12,6 +12,42 @@ CycloneDX SBOM for the build.
|
|
|
12
12
|
|
|
13
13
|
Nothing yet.
|
|
14
14
|
|
|
15
|
+
## [0.11.0] — 2026-10-16
|
|
16
|
+
|
|
17
|
+
### Added
|
|
18
|
+
|
|
19
|
+
- **`soql` tagged template** and binders `soqlId`, `soqlIds`, `soqlDate`, `soqlString`, `soqlLike`,
|
|
20
|
+
`soqlRaw`, `escapeSoqlString`, `escapeSoqlLike`. Strings are always quoted and escaped; nothing
|
|
21
|
+
is inferred from a value's shape. A placeholder inside template-supplied quotes is escaped
|
|
22
|
+
without re-quoting, and only a string may go there. `undefined`, exponent-form numbers and an
|
|
23
|
+
unterminated literal are errors (`SoqlBindError`).
|
|
24
|
+
- **`chunkApexBody` and `testApexPattern`**, which run a pattern window by window over large Apex
|
|
25
|
+
bodies. This caps polynomial backtracking; it does not make an exponential pattern safe.
|
|
26
|
+
Matches longer than the overlap that straddle a window boundary are missed.
|
|
27
|
+
- **`ApexClassBody.symbolTable`**, for checks that can use a class's compiled SymbolTable.
|
|
28
|
+
- **`encryptWithPassphrase`, `decryptWithPassphrase`, `isEncryptedBuffer`, `DecryptionError`,
|
|
29
|
+
`ENCRYPTED_MAGIC`**: AES-256-GCM encryption at rest with a scrypt key (N=2^15, r=8, p=3). The
|
|
30
|
+
scrypt parameters are stored in an authenticated header, and out-of-range values are refused
|
|
31
|
+
before any key derivation.
|
|
32
|
+
|
|
33
|
+
## [0.10.0] — 2026-10-15
|
|
34
|
+
|
|
35
|
+
### Added
|
|
36
|
+
|
|
37
|
+
- **`secureFs`, `SECURE_DIR_MODE`, `SECURE_FILE_MODE`.** Writes that create directories 0700 and
|
|
38
|
+
files 0600, for local stores that hold org data. `ensureSecureDir` also tightens a store root
|
|
39
|
+
that already exists; `mkdir` leaves an existing directory alone, since callers pass it
|
|
40
|
+
user-chosen output folders. The event baseline store and `getRawToFile` now write through it.
|
|
41
|
+
- **`SECURE_FS_RULES`**, an invariant that fails a package's build on a raw filesystem write
|
|
42
|
+
outside `secureFs`, including bare calls through a named import from `node:fs`.
|
|
43
|
+
- **`STRICT_CSP_META` and `INTERACTIVE_CSP_META`**, Content-Security-Policy meta tags for rendered
|
|
44
|
+
reports. Both forbid all network egress; the interactive one allows inline script.
|
|
45
|
+
|
|
46
|
+
### Changed
|
|
47
|
+
|
|
48
|
+
- **`esc()` escapes single quotes** (`'` → `'`) and returns `''` for `null` or `undefined`.
|
|
49
|
+
Rendered HTML containing `'` changes, so consumer snapshot tests may need updating.
|
|
50
|
+
|
|
15
51
|
## [0.9.0] — 2026-10-12
|
|
16
52
|
|
|
17
53
|
### Changed
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { mkdir, rm, stat } from 'node:fs/promises';
|
|
1
|
+
import { rm, stat } from 'node:fs/promises';
|
|
3
2
|
import { dirname } from 'node:path';
|
|
4
3
|
import { Readable } from 'node:stream';
|
|
5
4
|
import { pipeline } from 'node:stream/promises';
|
|
5
|
+
import { secureFs } from '../fs/secureFs.js';
|
|
6
6
|
export class RestClientImpl {
|
|
7
7
|
conn;
|
|
8
8
|
constructor(conn) {
|
|
@@ -31,9 +31,9 @@ export class RestClientImpl {
|
|
|
31
31
|
if (!res.ok || !res.body) {
|
|
32
32
|
throw new Error(`Download failed for ${normalised} (HTTP ${res.status})`);
|
|
33
33
|
}
|
|
34
|
-
await mkdir(dirname(destPath), { recursive: true });
|
|
34
|
+
await secureFs.mkdir(dirname(destPath), { recursive: true });
|
|
35
35
|
try {
|
|
36
|
-
await pipeline(Readable.fromWeb(res.body), createWriteStream(destPath));
|
|
36
|
+
await pipeline(Readable.fromWeb(res.body), secureFs.createWriteStream(destPath));
|
|
37
37
|
}
|
|
38
38
|
catch (err) {
|
|
39
39
|
await rm(destPath, { force: true }); // never leave a partial file behind
|
package/lib/api/index.d.ts
CHANGED
|
@@ -6,4 +6,5 @@ export { isApiError } from './ApiError.js';
|
|
|
6
6
|
export { SoqlClientImpl } from './SoqlClientImpl.js';
|
|
7
7
|
export { ToolingClientImpl } from './ToolingClientImpl.js';
|
|
8
8
|
export { RestClientImpl } from './RestClientImpl.js';
|
|
9
|
+
export { soql, soqlId, soqlIds, soqlDate, soqlString, soqlRaw, escapeSoqlString, escapeSoqlLike, soqlLike, SafeSoqlFragment, SoqlBindError, } from './soqlBind.js';
|
|
9
10
|
//# sourceMappingURL=index.d.ts.map
|
package/lib/api/index.js
CHANGED
|
@@ -2,4 +2,5 @@ export { isApiError } from './ApiError.js';
|
|
|
2
2
|
export { SoqlClientImpl } from './SoqlClientImpl.js';
|
|
3
3
|
export { ToolingClientImpl } from './ToolingClientImpl.js';
|
|
4
4
|
export { RestClientImpl } from './RestClientImpl.js';
|
|
5
|
+
export { soql, soqlId, soqlIds, soqlDate, soqlString, soqlRaw, escapeSoqlString, escapeSoqlLike, soqlLike, SafeSoqlFragment, SoqlBindError, } from './soqlBind.js';
|
|
5
6
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export declare class SoqlBindError extends Error {
|
|
2
|
+
constructor(message: string);
|
|
3
|
+
}
|
|
4
|
+
/** Marker class for explicitly pre-sanitized or raw SOQL fragments */
|
|
5
|
+
export declare class SafeSoqlFragment {
|
|
6
|
+
readonly text: string;
|
|
7
|
+
constructor(text: string);
|
|
8
|
+
toString(): string;
|
|
9
|
+
}
|
|
10
|
+
/** Escapes a string for safe inclusion in a SOQL single-quoted string literal. */
|
|
11
|
+
export declare function escapeSoqlString(val: string): string;
|
|
12
|
+
/**
|
|
13
|
+
* Validates that `val` is a valid 15- or 18-character Salesforce ID and wraps it in quotes.
|
|
14
|
+
* Throws `SoqlBindError` if invalid.
|
|
15
|
+
*/
|
|
16
|
+
export declare function soqlId(val: string): SafeSoqlFragment;
|
|
17
|
+
/**
|
|
18
|
+
* Validates a list of Salesforce IDs and formats them as a comma-separated tuple for `IN (...)`.
|
|
19
|
+
* Throws `SoqlBindError` if any ID is invalid.
|
|
20
|
+
*/
|
|
21
|
+
export declare function soqlIds(ids: readonly string[]): SafeSoqlFragment;
|
|
22
|
+
/**
|
|
23
|
+
* Formats a Date or ISO string into a safe SOQL date/datetime literal.
|
|
24
|
+
* Throws `SoqlBindError` if invalid.
|
|
25
|
+
*/
|
|
26
|
+
export declare function soqlDate(d: Date | string): SafeSoqlFragment;
|
|
27
|
+
/**
|
|
28
|
+
* Wraps a string in single quotes after escaping backslashes and single quotes.
|
|
29
|
+
*/
|
|
30
|
+
export declare function soqlString(s: string): SafeSoqlFragment;
|
|
31
|
+
/**
|
|
32
|
+
* Marks a string fragment as pre-validated raw SOQL (e.g. static allowlisted field names or operators).
|
|
33
|
+
* Must be used judiciously.
|
|
34
|
+
*/
|
|
35
|
+
export declare function soqlRaw(raw: string): SafeSoqlFragment;
|
|
36
|
+
/**
|
|
37
|
+
* Escapes a value for use inside a SOQL LIKE pattern: quotes and backslashes as for any string,
|
|
38
|
+
* plus `%` and `_`, which LIKE would otherwise treat as wildcards.
|
|
39
|
+
*/
|
|
40
|
+
export declare function escapeSoqlLike(val: string): string;
|
|
41
|
+
/**
|
|
42
|
+
* A quoted LIKE pattern matching `val` literally, with wildcards only where asked for:
|
|
43
|
+
* soqlLike(name, 'contains') gives '%<name>%'.
|
|
44
|
+
*/
|
|
45
|
+
export declare function soqlLike(val: string, match?: 'contains' | 'startsWith' | 'endsWith' | 'exact'): SafeSoqlFragment;
|
|
46
|
+
/**
|
|
47
|
+
* Tagged template literal for building injection-safe SOQL queries.
|
|
48
|
+
*
|
|
49
|
+
* Example:
|
|
50
|
+
* ```ts
|
|
51
|
+
* const query = soql`SELECT Id, Name FROM User WHERE Id = ${userId} AND IsActive = ${true}`;
|
|
52
|
+
* ```
|
|
53
|
+
*
|
|
54
|
+
* Strings are quoted and escaped; Dates become unquoted datetime literals (use soqlDate for a
|
|
55
|
+
* date from a string); arrays become IN lists. A placeholder may also sit inside quotes the
|
|
56
|
+
* template supplies, as in `LIKE '%${x}%'`; the string is then escaped but not re-quoted, and
|
|
57
|
+
* `%` and `_` in it still act as wildcards (use soqlLike to match them literally).
|
|
58
|
+
*/
|
|
59
|
+
export declare function soql(strings: TemplateStringsArray, ...values: unknown[]): string;
|
|
60
|
+
//# sourceMappingURL=soqlBind.d.ts.map
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
// src/api/soqlBind.ts
|
|
2
|
+
import { isSalesforceId } from '../platform/salesforceId.js';
|
|
3
|
+
export class SoqlBindError extends Error {
|
|
4
|
+
constructor(message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = 'SoqlBindError';
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
/** Marker class for explicitly pre-sanitized or raw SOQL fragments */
|
|
10
|
+
export class SafeSoqlFragment {
|
|
11
|
+
text;
|
|
12
|
+
constructor(text) {
|
|
13
|
+
this.text = text;
|
|
14
|
+
}
|
|
15
|
+
toString() {
|
|
16
|
+
return this.text;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/** Escapes a string for safe inclusion in a SOQL single-quoted string literal. */
|
|
20
|
+
export function escapeSoqlString(val) {
|
|
21
|
+
return val.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Validates that `val` is a valid 15- or 18-character Salesforce ID and wraps it in quotes.
|
|
25
|
+
* Throws `SoqlBindError` if invalid.
|
|
26
|
+
*/
|
|
27
|
+
export function soqlId(val) {
|
|
28
|
+
if (!isSalesforceId(val)) {
|
|
29
|
+
throw new SoqlBindError(`Invalid Salesforce ID for SOQL bind: '${val}'`);
|
|
30
|
+
}
|
|
31
|
+
return new SafeSoqlFragment(`'${val}'`);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Validates a list of Salesforce IDs and formats them as a comma-separated tuple for `IN (...)`.
|
|
35
|
+
* Throws `SoqlBindError` if any ID is invalid.
|
|
36
|
+
*/
|
|
37
|
+
export function soqlIds(ids) {
|
|
38
|
+
if (!Array.isArray(ids) || ids.length === 0) {
|
|
39
|
+
throw new SoqlBindError('soqlIds requires a non-empty array of Salesforce IDs');
|
|
40
|
+
}
|
|
41
|
+
for (const id of ids) {
|
|
42
|
+
if (!isSalesforceId(id)) {
|
|
43
|
+
throw new SoqlBindError(`Invalid Salesforce ID in list for SOQL bind: '${id}'`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return new SafeSoqlFragment(`(${ids.map((id) => `'${id}'`).join(', ')})`);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Formats a Date or ISO string into a safe SOQL date/datetime literal.
|
|
50
|
+
* Throws `SoqlBindError` if invalid.
|
|
51
|
+
*/
|
|
52
|
+
export function soqlDate(d) {
|
|
53
|
+
if (d instanceof Date) {
|
|
54
|
+
if (isNaN(d.getTime())) {
|
|
55
|
+
throw new SoqlBindError('Invalid Date object for SOQL bind');
|
|
56
|
+
}
|
|
57
|
+
return new SafeSoqlFragment(d.toISOString());
|
|
58
|
+
}
|
|
59
|
+
if (typeof d === 'string') {
|
|
60
|
+
if (/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d{3})?Z)?$/.test(d)) {
|
|
61
|
+
return new SafeSoqlFragment(d);
|
|
62
|
+
}
|
|
63
|
+
throw new SoqlBindError(`Invalid date string for SOQL bind: '${d}'`);
|
|
64
|
+
}
|
|
65
|
+
throw new SoqlBindError(`Expected Date or string for SOQL date bind, got ${typeof d}`);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Wraps a string in single quotes after escaping backslashes and single quotes.
|
|
69
|
+
*/
|
|
70
|
+
export function soqlString(s) {
|
|
71
|
+
if (typeof s !== 'string') {
|
|
72
|
+
throw new SoqlBindError(`Expected string for SOQL string bind, got ${typeof s}`);
|
|
73
|
+
}
|
|
74
|
+
return new SafeSoqlFragment(`'${escapeSoqlString(s)}'`);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Marks a string fragment as pre-validated raw SOQL (e.g. static allowlisted field names or operators).
|
|
78
|
+
* Must be used judiciously.
|
|
79
|
+
*/
|
|
80
|
+
export function soqlRaw(raw) {
|
|
81
|
+
return new SafeSoqlFragment(raw);
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Escapes a value for use inside a SOQL LIKE pattern: quotes and backslashes as for any string,
|
|
85
|
+
* plus `%` and `_`, which LIKE would otherwise treat as wildcards.
|
|
86
|
+
*/
|
|
87
|
+
export function escapeSoqlLike(val) {
|
|
88
|
+
// One pass over every character SOQL treats specially in a LIKE literal.
|
|
89
|
+
return val.replace(/[\\'%_]/g, (c) => `\\${c}`);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* A quoted LIKE pattern matching `val` literally, with wildcards only where asked for:
|
|
93
|
+
* soqlLike(name, 'contains') gives '%<name>%'.
|
|
94
|
+
*/
|
|
95
|
+
export function soqlLike(val, match = 'contains') {
|
|
96
|
+
if (typeof val !== 'string') {
|
|
97
|
+
throw new SoqlBindError(`Expected string for SOQL LIKE bind, got ${typeof val}`);
|
|
98
|
+
}
|
|
99
|
+
const body = escapeSoqlLike(val);
|
|
100
|
+
const lead = match === 'contains' || match === 'endsWith' ? '%' : '';
|
|
101
|
+
const trail = match === 'contains' || match === 'startsWith' ? '%' : '';
|
|
102
|
+
return new SafeSoqlFragment(`'${lead}${body}${trail}'`);
|
|
103
|
+
}
|
|
104
|
+
/** True when `text` ends inside an open single-quoted SOQL literal (an odd count of unescaped quotes). */
|
|
105
|
+
function insideStringLiteral(text) {
|
|
106
|
+
let open = false;
|
|
107
|
+
for (let i = 0; i < text.length; i++) {
|
|
108
|
+
if (text[i] === '\\') {
|
|
109
|
+
i++; // skip the escaped character
|
|
110
|
+
}
|
|
111
|
+
else if (text[i] === "'") {
|
|
112
|
+
open = !open;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return open;
|
|
116
|
+
}
|
|
117
|
+
function formatNumber(val) {
|
|
118
|
+
const text = String(val);
|
|
119
|
+
if (!Number.isFinite(val) || /e/i.test(text)) {
|
|
120
|
+
// SOQL has no exponent notation; 1e21 would be sent as "1e+21" and fail.
|
|
121
|
+
throw new SoqlBindError(`Number not representable in SOQL: ${text}`);
|
|
122
|
+
}
|
|
123
|
+
return text;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Formats one bound value. Strings are always escaped; outside a literal they are also quoted.
|
|
127
|
+
* Inside a literal the developer has supplied the quotes, so only a string is allowed there.
|
|
128
|
+
* Nothing is inferred from a string's shape: a date-like or Id-like string is still a string.
|
|
129
|
+
*/
|
|
130
|
+
function formatBindValue(val, inLiteral) {
|
|
131
|
+
if (inLiteral) {
|
|
132
|
+
if (typeof val === 'string')
|
|
133
|
+
return escapeSoqlString(val);
|
|
134
|
+
throw new SoqlBindError(`Only strings can be bound inside a quoted SOQL literal; got ${val instanceof SafeSoqlFragment ? 'a SOQL fragment' : typeof val}. Remove the quotes around the placeholder.`);
|
|
135
|
+
}
|
|
136
|
+
if (val instanceof SafeSoqlFragment)
|
|
137
|
+
return val.text;
|
|
138
|
+
if (typeof val === 'number')
|
|
139
|
+
return formatNumber(val);
|
|
140
|
+
if (typeof val === 'boolean')
|
|
141
|
+
return val ? 'true' : 'false';
|
|
142
|
+
if (val instanceof Date) {
|
|
143
|
+
if (Number.isNaN(val.getTime()))
|
|
144
|
+
throw new SoqlBindError('Invalid Date for SOQL bind');
|
|
145
|
+
return val.toISOString();
|
|
146
|
+
}
|
|
147
|
+
if (typeof val === 'string')
|
|
148
|
+
return `'${escapeSoqlString(val)}'`;
|
|
149
|
+
if (Array.isArray(val)) {
|
|
150
|
+
if (val.length === 0)
|
|
151
|
+
throw new SoqlBindError('Empty array cannot be bound to a SOQL IN clause');
|
|
152
|
+
if (val.every((x) => typeof x === 'string'))
|
|
153
|
+
return `(${val.map((x) => `'${escapeSoqlString(x)}'`).join(', ')})`;
|
|
154
|
+
if (val.every((x) => typeof x === 'number'))
|
|
155
|
+
return `(${val.map(formatNumber).join(', ')})`;
|
|
156
|
+
throw new SoqlBindError('Array bind in SOQL must contain only strings or only numbers');
|
|
157
|
+
}
|
|
158
|
+
if (val === null)
|
|
159
|
+
return 'null';
|
|
160
|
+
// undefined is almost always a missing variable, and binding it as null would silently widen
|
|
161
|
+
// or narrow the query.
|
|
162
|
+
throw new SoqlBindError(`Unsupported value for SOQL bind: ${val === undefined ? 'undefined' : typeof val}`);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Tagged template literal for building injection-safe SOQL queries.
|
|
166
|
+
*
|
|
167
|
+
* Example:
|
|
168
|
+
* ```ts
|
|
169
|
+
* const query = soql`SELECT Id, Name FROM User WHERE Id = ${userId} AND IsActive = ${true}`;
|
|
170
|
+
* ```
|
|
171
|
+
*
|
|
172
|
+
* Strings are quoted and escaped; Dates become unquoted datetime literals (use soqlDate for a
|
|
173
|
+
* date from a string); arrays become IN lists. A placeholder may also sit inside quotes the
|
|
174
|
+
* template supplies, as in `LIKE '%${x}%'`; the string is then escaped but not re-quoted, and
|
|
175
|
+
* `%` and `_` in it still act as wildcards (use soqlLike to match them literally).
|
|
176
|
+
*/
|
|
177
|
+
export function soql(strings, ...values) {
|
|
178
|
+
let result = '';
|
|
179
|
+
for (let i = 0; i < strings.length; i++) {
|
|
180
|
+
result += strings[i];
|
|
181
|
+
if (i < values.length)
|
|
182
|
+
result += formatBindValue(values[i], insideStringLiteral(result));
|
|
183
|
+
}
|
|
184
|
+
if (insideStringLiteral(result))
|
|
185
|
+
throw new SoqlBindError('Unterminated string literal in SOQL template');
|
|
186
|
+
return result;
|
|
187
|
+
}
|
|
188
|
+
//# sourceMappingURL=soqlBind.js.map
|
|
@@ -7,6 +7,8 @@ export interface HealthCheckRisk {
|
|
|
7
7
|
export interface ApexClassBody {
|
|
8
8
|
name: string;
|
|
9
9
|
body: string;
|
|
10
|
+
/** The class's compiled SymbolTable when the org returned one; managed classes may have this without a body. */
|
|
11
|
+
symbolTable?: unknown;
|
|
10
12
|
}
|
|
11
13
|
export interface VfPageBody {
|
|
12
14
|
name: string;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Passphrase encryption for files that hold org data at rest (incident bundles).
|
|
3
|
+
*
|
|
4
|
+
* Format, version 1:
|
|
5
|
+
*
|
|
6
|
+
* 'SFEB' | version (1) | log2(N) (1) | r (1) | p (1) | salt (16) | iv (12) | tag (16) | ciphertext
|
|
7
|
+
*
|
|
8
|
+
* AES-256-GCM with a key from scrypt. The scrypt parameters travel in the header so they can be
|
|
9
|
+
* raised later without stranding existing files, and the whole header is authenticated as GCM
|
|
10
|
+
* additional data, so altering any byte of it fails decryption.
|
|
11
|
+
*/
|
|
12
|
+
export declare const ENCRYPTED_MAGIC: Buffer<ArrayBuffer>;
|
|
13
|
+
export declare class DecryptionError extends Error {
|
|
14
|
+
constructor(message?: string);
|
|
15
|
+
}
|
|
16
|
+
/** Whether `buf` starts with this format's header. Says nothing about whether it will decrypt. */
|
|
17
|
+
export declare function isEncryptedBuffer(buf: Buffer): boolean;
|
|
18
|
+
export declare function encryptWithPassphrase(plaintext: Buffer | string, passphrase: string): Buffer;
|
|
19
|
+
export declare function decryptWithPassphrase(encrypted: Buffer, passphrase: string): Buffer;
|
|
20
|
+
//# sourceMappingURL=bundleCrypto.d.ts.map
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from 'node:crypto';
|
|
2
|
+
/**
|
|
3
|
+
* Passphrase encryption for files that hold org data at rest (incident bundles).
|
|
4
|
+
*
|
|
5
|
+
* Format, version 1:
|
|
6
|
+
*
|
|
7
|
+
* 'SFEB' | version (1) | log2(N) (1) | r (1) | p (1) | salt (16) | iv (12) | tag (16) | ciphertext
|
|
8
|
+
*
|
|
9
|
+
* AES-256-GCM with a key from scrypt. The scrypt parameters travel in the header so they can be
|
|
10
|
+
* raised later without stranding existing files, and the whole header is authenticated as GCM
|
|
11
|
+
* additional data, so altering any byte of it fails decryption.
|
|
12
|
+
*/
|
|
13
|
+
export const ENCRYPTED_MAGIC = Buffer.from('SFEB\x01', 'ascii'); // 'SFEB' + format version 1
|
|
14
|
+
/** OWASP's scrypt option N=2^15, r=8, p=3: about 32 MiB and ~0.1-0.2 s per derivation. */
|
|
15
|
+
const DEFAULT_KDF = { log2N: 15, r: 8, p: 3 };
|
|
16
|
+
/** Bounds accepted when reading a header, so a crafted file cannot demand unbounded memory or time. */
|
|
17
|
+
const KDF_LIMITS = { log2N: [14, 20], r: [1, 16], p: [1, 16] };
|
|
18
|
+
const MAX_KDF_MEMORY = 1024 * 1024 * 1024;
|
|
19
|
+
const SALT_LEN = 16;
|
|
20
|
+
const IV_LEN = 12;
|
|
21
|
+
const TAG_LEN = 16;
|
|
22
|
+
const HEADER_LEN = ENCRYPTED_MAGIC.length + 3 + SALT_LEN + IV_LEN; // authenticated as AAD
|
|
23
|
+
const MIN_LEN = HEADER_LEN + TAG_LEN;
|
|
24
|
+
export class DecryptionError extends Error {
|
|
25
|
+
constructor(message = 'Failed to decrypt data: invalid passphrase or corrupted payload') {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = 'DecryptionError';
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** Whether `buf` starts with this format's header. Says nothing about whether it will decrypt. */
|
|
31
|
+
export function isEncryptedBuffer(buf) {
|
|
32
|
+
return buf.length >= MIN_LEN && buf.subarray(0, ENCRYPTED_MAGIC.length).equals(ENCRYPTED_MAGIC);
|
|
33
|
+
}
|
|
34
|
+
// One passphrase decrypts every file of a bundle, each with its own salt, and readers revisit
|
|
35
|
+
// files. Caching derived keys keeps that from re-running scrypt. Entries are keyed by salt and
|
|
36
|
+
// parameters and hold the passphrase they were derived from, compared directly: no fast hash of
|
|
37
|
+
// the passphrase is ever computed.
|
|
38
|
+
const keyCache = new Map();
|
|
39
|
+
const KEY_CACHE_LIMIT = 256;
|
|
40
|
+
function deriveKey(passphrase, salt, log2N, r, p) {
|
|
41
|
+
const id = `${salt.toString('hex')}:${log2N}:${r}:${p}`;
|
|
42
|
+
const hit = keyCache.get(id);
|
|
43
|
+
if (hit && hit.passphrase === passphrase)
|
|
44
|
+
return hit.key;
|
|
45
|
+
const N = 2 ** log2N;
|
|
46
|
+
const key = scryptSync(passphrase, salt, 32, { N, r, p, maxmem: Math.min(MAX_KDF_MEMORY, 256 * N * r) });
|
|
47
|
+
if (keyCache.size >= KEY_CACHE_LIMIT)
|
|
48
|
+
keyCache.delete(keyCache.keys().next().value);
|
|
49
|
+
keyCache.set(id, { passphrase, key });
|
|
50
|
+
return key;
|
|
51
|
+
}
|
|
52
|
+
function requirePassphrase(passphrase) {
|
|
53
|
+
if (typeof passphrase !== 'string' || passphrase.length === 0) {
|
|
54
|
+
throw new TypeError('A non-empty passphrase is required');
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
export function encryptWithPassphrase(plaintext, passphrase) {
|
|
58
|
+
requirePassphrase(passphrase);
|
|
59
|
+
const { log2N, r, p } = DEFAULT_KDF;
|
|
60
|
+
const salt = randomBytes(SALT_LEN);
|
|
61
|
+
const iv = randomBytes(IV_LEN);
|
|
62
|
+
const header = Buffer.concat([ENCRYPTED_MAGIC, Buffer.from([log2N, r, p]), salt, iv]);
|
|
63
|
+
const cipher = createCipheriv('aes-256-gcm', deriveKey(passphrase, salt, log2N, r, p), iv, { authTagLength: TAG_LEN });
|
|
64
|
+
cipher.setAAD(header);
|
|
65
|
+
const data = Buffer.isBuffer(plaintext) ? plaintext : Buffer.from(plaintext, 'utf-8');
|
|
66
|
+
const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]);
|
|
67
|
+
return Buffer.concat([header, cipher.getAuthTag(), ciphertext]);
|
|
68
|
+
}
|
|
69
|
+
export function decryptWithPassphrase(encrypted, passphrase) {
|
|
70
|
+
requirePassphrase(passphrase);
|
|
71
|
+
if (!isEncryptedBuffer(encrypted)) {
|
|
72
|
+
throw new DecryptionError('Buffer is not in recognized SFEB encrypted format');
|
|
73
|
+
}
|
|
74
|
+
let o = ENCRYPTED_MAGIC.length;
|
|
75
|
+
const [log2N, r, p] = [encrypted[o++], encrypted[o++], encrypted[o++]];
|
|
76
|
+
const within = (v, [lo, hi]) => v >= lo && v <= hi;
|
|
77
|
+
if (!within(log2N, KDF_LIMITS.log2N) || !within(r, KDF_LIMITS.r) || !within(p, KDF_LIMITS.p)) {
|
|
78
|
+
throw new DecryptionError('Encrypted header carries key-derivation parameters outside the accepted range');
|
|
79
|
+
}
|
|
80
|
+
const salt = encrypted.subarray(o, (o += SALT_LEN));
|
|
81
|
+
const iv = encrypted.subarray(o, (o += IV_LEN));
|
|
82
|
+
const header = encrypted.subarray(0, HEADER_LEN);
|
|
83
|
+
const tag = encrypted.subarray(o, (o += TAG_LEN));
|
|
84
|
+
const ciphertext = encrypted.subarray(o);
|
|
85
|
+
try {
|
|
86
|
+
// A pinned tag length stops a truncated tag from being accepted.
|
|
87
|
+
const decipher = createDecipheriv('aes-256-gcm', deriveKey(passphrase, salt, log2N, r, p), iv, { authTagLength: TAG_LEN });
|
|
88
|
+
decipher.setAAD(header);
|
|
89
|
+
decipher.setAuthTag(tag);
|
|
90
|
+
return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
throw new DecryptionError();
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
//# sourceMappingURL=bundleCrypto.js.map
|
|
@@ -17,10 +17,17 @@
|
|
|
17
17
|
import * as fs from 'node:fs';
|
|
18
18
|
import * as os from 'node:os';
|
|
19
19
|
import * as path from 'node:path';
|
|
20
|
+
import { secureFs } from '../fs/secureFs.js';
|
|
20
21
|
export class EventBaselineStore {
|
|
21
22
|
root;
|
|
22
23
|
constructor(root) {
|
|
23
24
|
this.root = root ?? EventBaselineStore.defaultRoot();
|
|
25
|
+
try {
|
|
26
|
+
secureFs.ensureSecureDir(this.root);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
// Non-fatal if root cannot be created immediately
|
|
30
|
+
}
|
|
24
31
|
}
|
|
25
32
|
static defaultRoot() {
|
|
26
33
|
return path.join(os.homedir(), '.sf', 'event-baseline');
|
|
@@ -156,10 +163,10 @@ function nonEmpty(filePath) {
|
|
|
156
163
|
*/
|
|
157
164
|
function writeAtomic(filePath, body) {
|
|
158
165
|
const dir = path.dirname(filePath);
|
|
159
|
-
|
|
166
|
+
secureFs.mkdirSync(dir, { recursive: true });
|
|
160
167
|
const tmp = path.join(dir, `.${path.basename(filePath)}.${process.pid}.tmp`);
|
|
161
168
|
try {
|
|
162
|
-
|
|
169
|
+
secureFs.writeFileSync(tmp, body, 'utf-8');
|
|
163
170
|
fs.renameSync(tmp, filePath);
|
|
164
171
|
}
|
|
165
172
|
catch (err) {
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as fsp from 'node:fs/promises';
|
|
3
|
+
/**
|
|
4
|
+
* POSIX permissions for local sensitive storage:
|
|
5
|
+
* - Directories: 0700 (drwx------) readable/writable/traversable only by the owner
|
|
6
|
+
* - Files: 0600 (-rw-------) readable/writable only by the owner
|
|
7
|
+
*/
|
|
8
|
+
export declare const SECURE_DIR_MODE = 448;
|
|
9
|
+
export declare const SECURE_FILE_MODE = 384;
|
|
10
|
+
export declare const secureFs: {
|
|
11
|
+
/**
|
|
12
|
+
* Synchronously creates a directory (and, with `recursive`, any missing parents) with mode 0o700.
|
|
13
|
+
* A directory that already exists is left as it is: callers pass user-chosen output paths here, and
|
|
14
|
+
* tightening someone's existing folder is not ours to do. Store roots use ensureSecureDir instead.
|
|
15
|
+
*/
|
|
16
|
+
mkdirSync(dirPath: fs.PathLike, options?: fs.MakeDirectoryOptions): string | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* Asynchronously creates a directory with mode 0o700. Existing directories are left as they are.
|
|
19
|
+
*/
|
|
20
|
+
mkdir(dirPath: fs.PathLike, options?: fs.MakeDirectoryOptions): Promise<string | undefined>;
|
|
21
|
+
/**
|
|
22
|
+
* Synchronously writes data to a file with mode 0o600.
|
|
23
|
+
*/
|
|
24
|
+
writeFileSync(filePath: fs.PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: fs.WriteFileOptions): void;
|
|
25
|
+
/**
|
|
26
|
+
* Asynchronously writes data to a file with mode 0o600.
|
|
27
|
+
*/
|
|
28
|
+
writeFile(filePath: fs.PathLike | fsp.FileHandle, data: string | NodeJS.ArrayBufferView, options?: fs.WriteFileOptions): Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* Creates a write stream with mode 0o600.
|
|
31
|
+
*/
|
|
32
|
+
createWriteStream(filePath: fs.PathLike, options?: Parameters<typeof fs.createWriteStream>[1]): fs.WriteStream;
|
|
33
|
+
/**
|
|
34
|
+
* Ensures a directory exists with 0o700 permissions.
|
|
35
|
+
*/
|
|
36
|
+
ensureSecureDir(dirPath: string): void;
|
|
37
|
+
/**
|
|
38
|
+
* Asynchronously ensures a directory exists with 0o700 permissions.
|
|
39
|
+
*/
|
|
40
|
+
ensureSecureDirAsync(dirPath: string): Promise<void>;
|
|
41
|
+
};
|
|
42
|
+
//# sourceMappingURL=secureFs.d.ts.map
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// src/fs/secureFs.ts
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
import * as fsp from 'node:fs/promises';
|
|
4
|
+
/**
|
|
5
|
+
* POSIX permissions for local sensitive storage:
|
|
6
|
+
* - Directories: 0700 (drwx------) readable/writable/traversable only by the owner
|
|
7
|
+
* - Files: 0600 (-rw-------) readable/writable only by the owner
|
|
8
|
+
*/
|
|
9
|
+
export const SECURE_DIR_MODE = 0o700;
|
|
10
|
+
export const SECURE_FILE_MODE = 0o600;
|
|
11
|
+
function safeChmodSync(path, mode) {
|
|
12
|
+
try {
|
|
13
|
+
fs.chmodSync(path, mode);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
// Non-fatal on Windows, read-only filesystems, or EPERM
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
async function safeChmod(path, mode) {
|
|
20
|
+
try {
|
|
21
|
+
await fsp.chmod(path, mode);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
// Non-fatal on Windows, read-only filesystems, or EPERM
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export const secureFs = {
|
|
28
|
+
/**
|
|
29
|
+
* Synchronously creates a directory (and, with `recursive`, any missing parents) with mode 0o700.
|
|
30
|
+
* A directory that already exists is left as it is: callers pass user-chosen output paths here, and
|
|
31
|
+
* tightening someone's existing folder is not ours to do. Store roots use ensureSecureDir instead.
|
|
32
|
+
*/
|
|
33
|
+
mkdirSync(dirPath, options) {
|
|
34
|
+
return fs.mkdirSync(dirPath, { ...options, mode: SECURE_DIR_MODE }); // invariant:allow
|
|
35
|
+
},
|
|
36
|
+
/**
|
|
37
|
+
* Asynchronously creates a directory with mode 0o700. Existing directories are left as they are.
|
|
38
|
+
*/
|
|
39
|
+
async mkdir(dirPath, options) {
|
|
40
|
+
return fsp.mkdir(dirPath, { ...options, mode: SECURE_DIR_MODE }); // invariant:allow
|
|
41
|
+
},
|
|
42
|
+
/**
|
|
43
|
+
* Synchronously writes data to a file with mode 0o600.
|
|
44
|
+
*/
|
|
45
|
+
writeFileSync(// invariant:allow — method definition, not a call
|
|
46
|
+
filePath, data, options) {
|
|
47
|
+
if (typeof options === 'string') {
|
|
48
|
+
fs.writeFileSync(filePath, data, { encoding: options, mode: SECURE_FILE_MODE }); // invariant:allow
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
fs.writeFileSync(filePath, data, { ...options, mode: SECURE_FILE_MODE }); // invariant:allow
|
|
52
|
+
}
|
|
53
|
+
if (typeof filePath === 'string' || Buffer.isBuffer(filePath) || filePath instanceof URL) {
|
|
54
|
+
safeChmodSync(filePath, SECURE_FILE_MODE);
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
/**
|
|
58
|
+
* Asynchronously writes data to a file with mode 0o600.
|
|
59
|
+
*/
|
|
60
|
+
async writeFile(// invariant:allow — method definition, not a call
|
|
61
|
+
filePath, data, options) {
|
|
62
|
+
if (typeof options === 'string') {
|
|
63
|
+
await fsp.writeFile(filePath, data, { encoding: options, mode: SECURE_FILE_MODE }); // invariant:allow
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
await fsp.writeFile(filePath, data, { ...options, mode: SECURE_FILE_MODE }); // invariant:allow
|
|
67
|
+
}
|
|
68
|
+
if (typeof filePath === 'string' || Buffer.isBuffer(filePath) || filePath instanceof URL) {
|
|
69
|
+
await safeChmod(filePath, SECURE_FILE_MODE);
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
/**
|
|
73
|
+
* Creates a write stream with mode 0o600.
|
|
74
|
+
*/
|
|
75
|
+
createWriteStream(filePath, options) {
|
|
76
|
+
if (typeof options === 'string') {
|
|
77
|
+
return fs.createWriteStream(filePath, { encoding: options, mode: SECURE_FILE_MODE }); // invariant:allow
|
|
78
|
+
}
|
|
79
|
+
return fs.createWriteStream(filePath, { ...options, mode: SECURE_FILE_MODE }); // invariant:allow
|
|
80
|
+
},
|
|
81
|
+
/**
|
|
82
|
+
* Ensures a directory exists with 0o700 permissions.
|
|
83
|
+
*/
|
|
84
|
+
ensureSecureDir(dirPath) {
|
|
85
|
+
if (fs.existsSync(dirPath)) {
|
|
86
|
+
safeChmodSync(dirPath, SECURE_DIR_MODE);
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
this.mkdirSync(dirPath, { recursive: true });
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
/**
|
|
93
|
+
* Asynchronously ensures a directory exists with 0o700 permissions.
|
|
94
|
+
*/
|
|
95
|
+
async ensureSecureDirAsync(dirPath) {
|
|
96
|
+
try {
|
|
97
|
+
await fsp.access(dirPath);
|
|
98
|
+
await safeChmod(dirPath, SECURE_DIR_MODE);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
await this.mkdir(dirPath, { recursive: true });
|
|
102
|
+
}
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
//# sourceMappingURL=secureFs.js.map
|
package/lib/index.d.ts
CHANGED
|
@@ -21,7 +21,9 @@ export { SKIP_REASONS, isSkipReason, emptyCoverage, readCoverageManifest, } from
|
|
|
21
21
|
export type { Branding, BrandingOverrides } from './report/branding.js';
|
|
22
22
|
export { DEFAULT_BRANDING, resolveBranding } from './report/branding.js';
|
|
23
23
|
export { fontFaceCss, firaFontFaceCss } from './report/fonts.js';
|
|
24
|
-
export { esc } from './renderers/html-utils.js';
|
|
24
|
+
export { esc, STRICT_CSP_META, INTERACTIVE_CSP_META } from './renderers/html-utils.js';
|
|
25
|
+
export { secureFs, SECURE_DIR_MODE, SECURE_FILE_MODE } from './fs/secureFs.js';
|
|
26
|
+
export { ENCRYPTED_MAGIC, DecryptionError, isEncryptedBuffer, encryptWithPassphrase, decryptWithPassphrase, } from './crypto/bundleCrypto.js';
|
|
25
27
|
export type { RiskLevel } from './findings/RiskLevel.js';
|
|
26
28
|
export { RISK_LEVELS } from './findings/RiskLevel.js';
|
|
27
29
|
export * from './platform/index.js';
|
package/lib/index.js
CHANGED
|
@@ -13,7 +13,11 @@ export { pullRealtimeEvents, MAX_RTE_ROWS, buildRealtimeQuery, describeFields, c
|
|
|
13
13
|
export { SKIP_REASONS, isSkipReason, emptyCoverage, readCoverageManifest, } from './events/CaptureManifest.js';
|
|
14
14
|
export { DEFAULT_BRANDING, resolveBranding } from './report/branding.js';
|
|
15
15
|
export { fontFaceCss, firaFontFaceCss } from './report/fonts.js';
|
|
16
|
-
export { esc } from './renderers/html-utils.js';
|
|
16
|
+
export { esc, STRICT_CSP_META, INTERACTIVE_CSP_META } from './renderers/html-utils.js';
|
|
17
|
+
// --- Filesystem security ---
|
|
18
|
+
export { secureFs, SECURE_DIR_MODE, SECURE_FILE_MODE } from './fs/secureFs.js';
|
|
19
|
+
// --- Encryption at rest ---
|
|
20
|
+
export { ENCRYPTED_MAGIC, DecryptionError, isEncryptedBuffer, encryptWithPassphrase, decryptWithPassphrase, } from './crypto/bundleCrypto.js';
|
|
17
21
|
export { RISK_LEVELS } from './findings/RiskLevel.js';
|
|
18
22
|
// --- Platform behaviour (API routing, Id validation, repositories) ---
|
|
19
23
|
export * from './platform/index.js';
|
package/lib/platform/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { isSalesforceId, describeSalesforceError, usableApexBody, qualifiedName, } from './salesforceId.js';
|
|
1
|
+
export { isSalesforceId, describeSalesforceError, usableApexBody, qualifiedName, chunkApexBody, testApexPattern, } from './salesforceId.js';
|
|
2
2
|
export { mapWithConcurrency } from './concurrency.js';
|
|
3
3
|
export { FlowRepository } from './flowRepository.js';
|
|
4
4
|
export type { FlowDefinitionRecord, FlowTriggerRecord, FlowVersionRef, SelectedFlowVersions, ActiveFlowVersion, } from './flowRepository.js';
|
package/lib/platform/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Platform-behaviour layer: how Salesforce actually answers, kept in one place so a plugin
|
|
2
2
|
// cannot rediscover it by shipping the bug first.
|
|
3
|
-
export { isSalesforceId, describeSalesforceError, usableApexBody, qualifiedName, } from './salesforceId.js';
|
|
3
|
+
export { isSalesforceId, describeSalesforceError, usableApexBody, qualifiedName, chunkApexBody, testApexPattern, } from './salesforceId.js';
|
|
4
4
|
export { mapWithConcurrency } from './concurrency.js';
|
|
5
5
|
export { FlowRepository } from './flowRepository.js';
|
|
6
6
|
export { ApexRepository } from './apexRepository.js';
|
|
@@ -26,4 +26,24 @@ export declare function describeSalesforceError(e: unknown, maxLength?: number):
|
|
|
26
26
|
export declare function usableApexBody(body: string | null | undefined): string | null;
|
|
27
27
|
/** `ns__Name` for namespaced components, plain `Name` otherwise. */
|
|
28
28
|
export declare function qualifiedName(name: string, namespacePrefix: string | null | undefined): string;
|
|
29
|
+
/**
|
|
30
|
+
* Splits Apex source into overlapping windows so a pattern is never run over an unbounded body.
|
|
31
|
+
*
|
|
32
|
+
* This caps the cost of patterns whose backtracking grows polynomially with input length, which
|
|
33
|
+
* on a multi-megabyte generated class can stall an audit. It does NOT make a pattern with
|
|
34
|
+
* exponential backtracking safe: such a pattern can hang on a few dozen characters, and must be
|
|
35
|
+
* rewritten instead.
|
|
36
|
+
*
|
|
37
|
+
* Defaults: 50,000 characters per window, 2,000 characters of overlap.
|
|
38
|
+
*/
|
|
39
|
+
export declare function chunkApexBody(body: string, chunkSize?: number, overlap?: number): string[];
|
|
40
|
+
/**
|
|
41
|
+
* Whether `regex` matches anywhere in `body`, testing window by window (see chunkApexBody).
|
|
42
|
+
*
|
|
43
|
+
* Only correct for patterns whose matches are at most `overlap` characters long: a longer match
|
|
44
|
+
* that straddles a window boundary is missed. Anchors (`^`, `$`) and `\b` at a window's edge see
|
|
45
|
+
* the edge, not the neighbouring source, so prefer patterns that do not depend on them there.
|
|
46
|
+
* The regex's lastIndex is left at 0.
|
|
47
|
+
*/
|
|
48
|
+
export declare function testApexPattern(body: string, regex: RegExp, chunkSize?: number, overlap?: number): boolean;
|
|
29
49
|
//# sourceMappingURL=salesforceId.d.ts.map
|
|
@@ -38,4 +38,58 @@ export function usableApexBody(body) {
|
|
|
38
38
|
export function qualifiedName(name, namespacePrefix) {
|
|
39
39
|
return namespacePrefix ? `${namespacePrefix}__${name}` : name;
|
|
40
40
|
}
|
|
41
|
+
/**
|
|
42
|
+
* Splits Apex source into overlapping windows so a pattern is never run over an unbounded body.
|
|
43
|
+
*
|
|
44
|
+
* This caps the cost of patterns whose backtracking grows polynomially with input length, which
|
|
45
|
+
* on a multi-megabyte generated class can stall an audit. It does NOT make a pattern with
|
|
46
|
+
* exponential backtracking safe: such a pattern can hang on a few dozen characters, and must be
|
|
47
|
+
* rewritten instead.
|
|
48
|
+
*
|
|
49
|
+
* Defaults: 50,000 characters per window, 2,000 characters of overlap.
|
|
50
|
+
*/
|
|
51
|
+
export function chunkApexBody(body, chunkSize = 50_000, overlap = 2_000) {
|
|
52
|
+
if (!Number.isInteger(chunkSize) || chunkSize <= 0) {
|
|
53
|
+
throw new RangeError(`chunkSize must be a positive integer, got ${chunkSize}`);
|
|
54
|
+
}
|
|
55
|
+
if (!Number.isInteger(overlap) || overlap < 0 || overlap >= chunkSize) {
|
|
56
|
+
// An overlap at or above the chunk size would step one character at a time.
|
|
57
|
+
throw new RangeError(`overlap must be an integer from 0 to chunkSize - 1, got ${overlap}`);
|
|
58
|
+
}
|
|
59
|
+
if (!body)
|
|
60
|
+
return [];
|
|
61
|
+
if (body.length <= chunkSize)
|
|
62
|
+
return [body];
|
|
63
|
+
const chunks = [];
|
|
64
|
+
const step = chunkSize - overlap;
|
|
65
|
+
for (let i = 0; i < body.length; i += step) {
|
|
66
|
+
chunks.push(body.slice(i, i + chunkSize));
|
|
67
|
+
if (i + chunkSize >= body.length)
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
return chunks;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Whether `regex` matches anywhere in `body`, testing window by window (see chunkApexBody).
|
|
74
|
+
*
|
|
75
|
+
* Only correct for patterns whose matches are at most `overlap` characters long: a longer match
|
|
76
|
+
* that straddles a window boundary is missed. Anchors (`^`, `$`) and `\b` at a window's edge see
|
|
77
|
+
* the edge, not the neighbouring source, so prefer patterns that do not depend on them there.
|
|
78
|
+
* The regex's lastIndex is left at 0.
|
|
79
|
+
*/
|
|
80
|
+
export function testApexPattern(body, regex, chunkSize = 50_000, overlap = 2_000) {
|
|
81
|
+
if (!body)
|
|
82
|
+
return false;
|
|
83
|
+
try {
|
|
84
|
+
for (const chunk of chunkApexBody(body, chunkSize, overlap)) {
|
|
85
|
+
regex.lastIndex = 0;
|
|
86
|
+
if (regex.test(chunk))
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
regex.lastIndex = 0;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
41
95
|
//# sourceMappingURL=salesforceId.js.map
|
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
export declare
|
|
1
|
+
export declare const STRICT_CSP_META = "<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:;\">";
|
|
2
|
+
export declare const INTERACTIVE_CSP_META = "<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; font-src data:;\">";
|
|
3
|
+
export declare function esc(str: unknown): string;
|
|
2
4
|
//# sourceMappingURL=html-utils.d.ts.map
|
|
@@ -1,8 +1,13 @@
|
|
|
1
|
+
export const STRICT_CSP_META = '<meta http-equiv="Content-Security-Policy" content="default-src \'none\'; style-src \'unsafe-inline\'; img-src data:; font-src data:;">';
|
|
2
|
+
export const INTERACTIVE_CSP_META = '<meta http-equiv="Content-Security-Policy" content="default-src \'none\'; script-src \'unsafe-inline\'; style-src \'unsafe-inline\'; img-src data:; font-src data:;">';
|
|
1
3
|
export function esc(str) {
|
|
2
|
-
|
|
4
|
+
if (str === null || str === undefined)
|
|
5
|
+
return '';
|
|
6
|
+
return String(str)
|
|
3
7
|
.replace(/&/g, '&')
|
|
4
8
|
.replace(/</g, '<')
|
|
5
9
|
.replace(/>/g, '>')
|
|
6
|
-
.replace(/"/g, '"')
|
|
10
|
+
.replace(/"/g, '"')
|
|
11
|
+
.replace(/'/g, ''');
|
|
7
12
|
}
|
|
8
13
|
//# sourceMappingURL=html-utils.js.map
|
|
@@ -36,6 +36,12 @@ export declare const ORG_WRITE_RULES: readonly InvariantRule[];
|
|
|
36
36
|
* must not fetch script, styles or fonts from a third party when a client opens it).
|
|
37
37
|
*/
|
|
38
38
|
export declare const NETWORK_EGRESS_RULES: readonly InvariantRule[];
|
|
39
|
+
/**
|
|
40
|
+
* Filesystem write tokens. All persistent writes to local stores (history, incidents, event baselines)
|
|
41
|
+
* must go through secureFs to ensure 0700 dir and 0600 file POSIX permissions.
|
|
42
|
+
* Raw un-moded fs.writeFile / mkdir / createWriteStream calls outside secureFs are forbidden.
|
|
43
|
+
*/
|
|
44
|
+
export declare const SECURE_FS_RULES: readonly InvariantRule[];
|
|
39
45
|
/** Recursively collect `.ts` source files (excluding declaration files) under `dir`. */
|
|
40
46
|
export declare function collectSourceFiles(dir: string): string[];
|
|
41
47
|
/**
|
|
@@ -36,6 +36,27 @@ export const NETWORK_EGRESS_RULES = [
|
|
|
36
36
|
],
|
|
37
37
|
['websocket client', /\bnew\s+WebSocket\s*\(|(?:from\s+|require\()\s*['"]ws['"]/i],
|
|
38
38
|
];
|
|
39
|
+
/**
|
|
40
|
+
* Filesystem write tokens. All persistent writes to local stores (history, incidents, event baselines)
|
|
41
|
+
* must go through secureFs to ensure 0700 dir and 0600 file POSIX permissions.
|
|
42
|
+
* Raw un-moded fs.writeFile / mkdir / createWriteStream calls outside secureFs are forbidden.
|
|
43
|
+
*/
|
|
44
|
+
export const SECURE_FS_RULES = [
|
|
45
|
+
['raw fs.writeFileSync call (use secureFs.writeFileSync)', /\bfs\.writeFileSync\s*\(/],
|
|
46
|
+
['raw fs.writeFile call (use secureFs.writeFile)', /\bfs(?:\.promises)?\.writeFile\s*\(/],
|
|
47
|
+
['raw fs.mkdirSync call (use secureFs.mkdirSync)', /\bfs\.mkdirSync\s*\(/],
|
|
48
|
+
['raw fs.mkdir call (use secureFs.mkdir)', /\bfs(?:\.promises)?\.mkdir\s*\(/],
|
|
49
|
+
['raw fs.createWriteStream call (use secureFs.createWriteStream)', /\bfs\.createWriteStream\s*\(/],
|
|
50
|
+
['raw fsp.writeFile call (use secureFs.writeFile)', /\bfsp\.writeFile\s*\(/],
|
|
51
|
+
['raw fsp.mkdir call (use secureFs.mkdir)', /\bfsp\.mkdir\s*\(/],
|
|
52
|
+
['raw fs.appendFile call', /\b(?:fs|fsp)(?:\.promises)?\.appendFile(?:Sync)?\s*\(/],
|
|
53
|
+
// Named imports (`import { mkdir } from 'node:fs/promises'`) call the same functions bare. Calls
|
|
54
|
+
// only — the negative lookahead skips typed method definitions such as secureFs's own `mkdir(dirPath: …)`.
|
|
55
|
+
[
|
|
56
|
+
'bare fs write call via named import (use secureFs)',
|
|
57
|
+
/(?<![.\w$])(?:writeFileSync|writeFile|mkdirSync|mkdir|createWriteStream|appendFileSync|appendFile)\s*\((?!\s*\w+\??\s*:)/,
|
|
58
|
+
],
|
|
59
|
+
];
|
|
39
60
|
/** Recursively collect `.ts` source files (excluding declaration files) under `dir`. */
|
|
40
61
|
export function collectSourceFiles(dir) {
|
|
41
62
|
const out = [];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cclabsnz/sf-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Shared platform layer for CloudCounsel Salesforce sf plugins — API clients, org context, event log pull, report shell, and versioned IR schemas.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|