@cclabsnz/sf-core 0.9.0 → 0.10.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 CHANGED
@@ -12,6 +12,24 @@ CycloneDX SBOM for the build.
12
12
 
13
13
  Nothing yet.
14
14
 
15
+ ## [0.10.0] — 2026-10-15
16
+
17
+ ### Added
18
+
19
+ - **`secureFs`, `SECURE_DIR_MODE`, `SECURE_FILE_MODE`.** Writes that create directories 0700 and
20
+ files 0600, for local stores that hold org data. `ensureSecureDir` also tightens a store root
21
+ that already exists; `mkdir` leaves an existing directory alone, since callers pass it
22
+ user-chosen output folders. The event baseline store and `getRawToFile` now write through it.
23
+ - **`SECURE_FS_RULES`**, an invariant that fails a package's build on a raw filesystem write
24
+ outside `secureFs`, including bare calls through a named import from `node:fs`.
25
+ - **`STRICT_CSP_META` and `INTERACTIVE_CSP_META`**, Content-Security-Policy meta tags for rendered
26
+ reports. Both forbid all network egress; the interactive one allows inline script.
27
+
28
+ ### Changed
29
+
30
+ - **`esc()` escapes single quotes** (`'` → `'`) and returns `''` for `null` or `undefined`.
31
+ Rendered HTML containing `'` changes, so consumer snapshot tests may need updating.
32
+
15
33
  ## [0.9.0] — 2026-10-12
16
34
 
17
35
  ### Changed
@@ -1,8 +1,8 @@
1
- import { createWriteStream } from 'node:fs';
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
@@ -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
- fs.mkdirSync(dir, { recursive: true });
166
+ secureFs.mkdirSync(dir, { recursive: true });
160
167
  const tmp = path.join(dir, `.${path.basename(filePath)}.${process.pid}.tmp`);
161
168
  try {
162
- fs.writeFileSync(tmp, body, 'utf-8');
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,8 @@ 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';
25
26
  export type { RiskLevel } from './findings/RiskLevel.js';
26
27
  export { RISK_LEVELS } from './findings/RiskLevel.js';
27
28
  export * from './platform/index.js';
package/lib/index.js CHANGED
@@ -13,7 +13,9 @@ 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';
17
19
  export { RISK_LEVELS } from './findings/RiskLevel.js';
18
20
  // --- Platform behaviour (API routing, Id validation, repositories) ---
19
21
  export * from './platform/index.js';
@@ -1,2 +1,4 @@
1
- export declare function esc(str: string): string;
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
- return str
4
+ if (str === null || str === undefined)
5
+ return '';
6
+ return String(str)
3
7
  .replace(/&/g, '&amp;')
4
8
  .replace(/</g, '&lt;')
5
9
  .replace(/>/g, '&gt;')
6
- .replace(/"/g, '&quot;');
10
+ .replace(/"/g, '&quot;')
11
+ .replace(/'/g, '&#39;');
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.9.0",
3
+ "version": "0.10.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",