@cclabsnz/sf-core 0.10.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 +18 -0
- 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/index.d.ts +1 -0
- package/lib/index.js +2 -0
- 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/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -12,6 +12,24 @@ 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
|
+
|
|
15
33
|
## [0.10.0] — 2026-10-15
|
|
16
34
|
|
|
17
35
|
### Added
|
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
|
package/lib/index.d.ts
CHANGED
|
@@ -23,6 +23,7 @@ export { DEFAULT_BRANDING, resolveBranding } from './report/branding.js';
|
|
|
23
23
|
export { fontFaceCss, firaFontFaceCss } from './report/fonts.js';
|
|
24
24
|
export { esc, STRICT_CSP_META, INTERACTIVE_CSP_META } from './renderers/html-utils.js';
|
|
25
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';
|
|
26
27
|
export type { RiskLevel } from './findings/RiskLevel.js';
|
|
27
28
|
export { RISK_LEVELS } from './findings/RiskLevel.js';
|
|
28
29
|
export * from './platform/index.js';
|
package/lib/index.js
CHANGED
|
@@ -16,6 +16,8 @@ export { fontFaceCss, firaFontFaceCss } from './report/fonts.js';
|
|
|
16
16
|
export { esc, STRICT_CSP_META, INTERACTIVE_CSP_META } from './renderers/html-utils.js';
|
|
17
17
|
// --- Filesystem security ---
|
|
18
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';
|
|
19
21
|
export { RISK_LEVELS } from './findings/RiskLevel.js';
|
|
20
22
|
// --- Platform behaviour (API routing, Id validation, repositories) ---
|
|
21
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
|
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",
|