@typecad/framework-zephyr 1.0.0-alpha.16 → 1.0.0-alpha.19

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 (210) hide show
  1. package/LICENSE +202 -21
  2. package/README.md +49 -87
  3. package/dist/as-built.d.ts +2 -2
  4. package/dist/as-built.js +2 -2
  5. package/dist/audit.d.ts +111 -0
  6. package/dist/audit.js +416 -0
  7. package/dist/boardgen.d.ts +1 -9
  8. package/dist/boardgen.js +288 -47
  9. package/dist/chips/resolve.js +20 -0
  10. package/dist/chips/types.d.ts +22 -1
  11. package/dist/debug-codegen.js +1 -1
  12. package/dist/display/bindings.d.ts +55 -0
  13. package/dist/display/bindings.js +316 -0
  14. package/dist/display/gfx.d.ts +2 -3
  15. package/dist/display/gfx.js +166 -154
  16. package/dist/display/index.js +20 -1
  17. package/dist/display/mipi-dbi-host.d.ts +9 -0
  18. package/dist/display/mipi-dbi-host.js +174 -0
  19. package/dist/display/profiles.d.ts +109 -4
  20. package/dist/display/profiles.js +270 -7
  21. package/dist/display/touch-adapter.js +119 -49
  22. package/dist/display/ui-adapter-eink.d.ts +2 -0
  23. package/dist/display/ui-adapter-eink.js +4 -0
  24. package/dist/display/ui-adapter-gray.d.ts +8 -0
  25. package/dist/display/ui-adapter-gray.js +170 -0
  26. package/dist/display/ui-adapter-mono.d.ts +13 -0
  27. package/dist/display/ui-adapter-mono.js +230 -0
  28. package/dist/display/ui-adapter-native.d.ts +10 -0
  29. package/dist/display/ui-adapter-native.js +295 -0
  30. package/dist/display/ui-adapter-shared.d.ts +11 -0
  31. package/dist/display/ui-adapter-shared.js +122 -0
  32. package/dist/display/ui-adapter.js +510 -558
  33. package/dist/doctor.js +4 -4
  34. package/dist/dt-config/custom-board.js +2 -2
  35. package/dist/dt-config/kconfig.d.ts +62 -1
  36. package/dist/dt-config/kconfig.js +141 -38
  37. package/dist/dt-config/overlay.d.ts +15 -2
  38. package/dist/dt-config/overlay.js +433 -18
  39. package/dist/framework.manifest.d.ts +10 -4
  40. package/dist/framework.manifest.js +133 -17
  41. package/dist/index.d.ts +2 -0
  42. package/dist/index.js +14 -6
  43. package/dist/licenses.d.ts +2 -2
  44. package/dist/licenses.js +13 -92
  45. package/dist/lowering/can.d.ts +25 -0
  46. package/dist/lowering/can.js +97 -0
  47. package/dist/lowering/clock.d.ts +17 -0
  48. package/dist/lowering/clock.js +58 -0
  49. package/dist/lowering/fs.js +1 -1
  50. package/dist/lowering/gpio.js +0 -32
  51. package/dist/lowering/hid.d.ts +27 -0
  52. package/dist/lowering/hid.js +244 -0
  53. package/dist/lowering/http.js +264 -32
  54. package/dist/lowering/i2c.d.ts +8 -0
  55. package/dist/lowering/i2c.js +137 -5
  56. package/dist/lowering/i2s.d.ts +27 -0
  57. package/dist/lowering/i2s.js +98 -0
  58. package/dist/lowering/index.d.ts +9 -1
  59. package/dist/lowering/index.js +25 -1
  60. package/dist/lowering/interrupts.js +6 -0
  61. package/dist/lowering/matrix.d.ts +15 -0
  62. package/dist/lowering/matrix.js +63 -0
  63. package/dist/lowering/mqtt.js +110 -8
  64. package/dist/lowering/power.d.ts +3 -2
  65. package/dist/lowering/power.js +20 -45
  66. package/dist/lowering/pwm.js +25 -0
  67. package/dist/lowering/sensor.d.ts +2 -2
  68. package/dist/lowering/sensor.js +8 -4
  69. package/dist/lowering/strip.d.ts +16 -0
  70. package/dist/lowering/strip.js +70 -0
  71. package/dist/lowering/thread.js +5 -1
  72. package/dist/lowering/trace.d.ts +44 -0
  73. package/dist/lowering/trace.js +239 -0
  74. package/dist/lowering/uart.js +6 -1
  75. package/dist/lowering/usb.d.ts +3 -1
  76. package/dist/lowering/usb.js +16 -13
  77. package/dist/lowering/wdt.js +2 -29
  78. package/dist/sbom.d.ts +181 -0
  79. package/dist/sbom.js +901 -0
  80. package/dist/sdk/board-catalog-sync.d.ts +1 -3
  81. package/dist/sdk/board-catalog-sync.js +4 -10
  82. package/dist/strategy.d.ts +82 -46
  83. package/dist/strategy.js +639 -182
  84. package/dist/tmp-probe.d.ts +2 -0
  85. package/dist/tmp-probe.js +9 -0
  86. package/dist/toolchain/debug-config.d.ts +50 -90
  87. package/dist/toolchain/debug-config.js +239 -510
  88. package/dist/toolchain/env-check.d.ts +1 -3
  89. package/dist/toolchain/env-check.js +2 -7
  90. package/dist/toolchain/index.d.ts +28 -3
  91. package/dist/toolchain/index.js +498 -62
  92. package/dist/toolchain/runners.d.ts +16 -0
  93. package/dist/toolchain/runners.js +75 -0
  94. package/dist/toolchain/scaffold.d.ts +5 -2
  95. package/dist/toolchain/scaffold.js +79 -15
  96. package/dist/toolchain/west-discover.d.ts +6 -0
  97. package/dist/toolchain/west-discover.js +36 -13
  98. package/dist/toolchain/west-spawn.js +8 -2
  99. package/dist/west-inventory.d.ts +25 -0
  100. package/dist/west-inventory.js +97 -0
  101. package/installer/README.md +328 -328
  102. package/installer/install.sh +2 -2
  103. package/installer/templates/project/.typecad/activate-zephyr.ps1 +1 -1
  104. package/installer/templates/project/.typecad/activate-zephyr.sh +1 -1
  105. package/installer/templates/project/.vscode/settings.json +1 -1
  106. package/installer/templates/project/README.md +2 -2
  107. package/package.json +5 -5
  108. package/src/as-built.ts +206 -206
  109. package/src/audit.ts +529 -0
  110. package/src/boardgen.ts +265 -50
  111. package/src/chips/resolve.ts +21 -0
  112. package/src/chips/types.ts +10 -1
  113. package/src/display/bindings.ts +347 -0
  114. package/src/display/gfx.ts +318 -306
  115. package/src/display/index.ts +87 -70
  116. package/src/display/mipi-dbi-host.ts +183 -0
  117. package/src/display/profiles.ts +458 -139
  118. package/src/display/touch-adapter.ts +119 -49
  119. package/src/display/ui-adapter-eink.ts +13 -0
  120. package/src/display/ui-adapter-gray.ts +178 -0
  121. package/src/display/ui-adapter-mono.ts +238 -0
  122. package/src/display/ui-adapter-native.ts +304 -0
  123. package/src/display/ui-adapter-shared.ts +125 -0
  124. package/src/display/ui-adapter.ts +732 -781
  125. package/src/doctor.ts +4 -4
  126. package/src/dt-config/custom-board.ts +2 -2
  127. package/src/dt-config/kconfig.ts +647 -505
  128. package/src/dt-config/overlay.ts +1475 -1058
  129. package/src/framework.manifest.ts +659 -535
  130. package/src/index.ts +16 -6
  131. package/src/licenses.ts +346 -425
  132. package/src/lowering/can.ts +140 -0
  133. package/src/lowering/clock.ts +91 -0
  134. package/src/lowering/fs.ts +135 -135
  135. package/src/lowering/gpio.ts +0 -33
  136. package/src/lowering/hid.ts +261 -0
  137. package/src/lowering/http.ts +264 -32
  138. package/src/lowering/i2c.ts +142 -5
  139. package/src/lowering/i2s.ts +143 -0
  140. package/src/lowering/index.ts +18 -1
  141. package/src/lowering/interrupts.ts +6 -0
  142. package/src/lowering/matrix.ts +70 -0
  143. package/src/lowering/mqtt.ts +109 -8
  144. package/src/lowering/power.ts +41 -0
  145. package/src/lowering/pwm.ts +192 -167
  146. package/src/lowering/sensor.ts +159 -155
  147. package/src/lowering/strip.ts +81 -0
  148. package/src/lowering/thread.ts +5 -1
  149. package/src/lowering/trace.ts +270 -0
  150. package/src/lowering/uart.ts +6 -1
  151. package/src/lowering/usb.ts +16 -13
  152. package/src/lowering/wdt.ts +2 -25
  153. package/src/sbom.ts +1117 -0
  154. package/src/sdk/board-catalog-sync.ts +4 -25
  155. package/src/strategy.ts +2680 -2309
  156. package/src/toolchain/debug-config.ts +262 -522
  157. package/src/toolchain/env-check.ts +279 -285
  158. package/src/toolchain/index.ts +1792 -1359
  159. package/src/toolchain/runners.ts +80 -0
  160. package/src/toolchain/scaffold.ts +355 -296
  161. package/src/toolchain/west-discover.ts +35 -13
  162. package/src/toolchain/west-spawn.ts +174 -168
  163. package/src/west-inventory.ts +102 -0
  164. package/dist/async/timer-polyfill.d.ts +0 -10
  165. package/dist/async/timer-polyfill.js +0 -95
  166. package/dist/chips/board-overrides.d.ts +0 -7
  167. package/dist/chips/board-overrides.js +0 -11
  168. package/dist/chips/esp32.d.ts +0 -2
  169. package/dist/chips/esp32.js +0 -71
  170. package/dist/chips/esp32s3.d.ts +0 -2
  171. package/dist/chips/esp32s3.js +0 -103
  172. package/dist/chips/soc/.d.ts +0 -2
  173. package/dist/chips/soc/.js +0 -129
  174. package/dist/chips/soc/esp32.d.ts +0 -2
  175. package/dist/chips/soc/esp32.js +0 -120
  176. package/dist/chips/soc/esp32c3.d.ts +0 -2
  177. package/dist/chips/soc/esp32c3.js +0 -90
  178. package/dist/chips/soc/esp32c6.d.ts +0 -2
  179. package/dist/chips/soc/esp32c6.js +0 -109
  180. package/dist/chips/soc/esp32s3.d.ts +0 -2
  181. package/dist/chips/soc/esp32s3.js +0 -189
  182. package/dist/chips/soc/index.d.ts +0 -2
  183. package/dist/chips/soc/index.js +0 -23
  184. package/dist/chips/soc/nrf52840.d.ts +0 -2
  185. package/dist/chips/soc/nrf52840.js +0 -130
  186. package/dist/chips/soc/rp2040.d.ts +0 -2
  187. package/dist/chips/soc/rp2040.js +0 -141
  188. package/dist/chips/soc/rp2350a.d.ts +0 -2
  189. package/dist/chips/soc/rp2350a.js +0 -145
  190. package/dist/chips/soc/samd21g18a.d.ts +0 -2
  191. package/dist/chips/soc/samd21g18a.js +0 -143
  192. package/dist/chips/soc/stm32f411xe.d.ts +0 -2
  193. package/dist/chips/soc/stm32f411xe.js +0 -251
  194. package/dist/chips/xiao-ble.d.ts +0 -2
  195. package/dist/chips/xiao-ble.js +0 -100
  196. package/dist/lowering/pulse.d.ts +0 -7
  197. package/dist/lowering/pulse.js +0 -51
  198. package/dist/lowering/tone.d.ts +0 -10
  199. package/dist/lowering/tone.js +0 -63
  200. package/dist/lowering/worker-backing.d.ts +0 -14
  201. package/dist/lowering/worker-backing.js +0 -79
  202. package/dist/lowering/worker.d.ts +0 -6
  203. package/dist/lowering/worker.js +0 -14
  204. package/dist/sdk/board-data.generated.d.ts +0 -2
  205. package/dist/sdk/board-data.generated.js +0 -4
  206. package/dist/sdk/catalog-walker.d.ts +0 -90
  207. package/dist/sdk/catalog-walker.js +0 -682
  208. package/dist/sdk/dts-reader.d.ts +0 -83
  209. package/dist/sdk/dts-reader.js +0 -596
  210. package/src/debug-codegen.ts +0 -207
package/src/audit.ts ADDED
@@ -0,0 +1,529 @@
1
+ // ---------------------------------------------------------------------------
2
+ // @typecad/framework-zephyr — security baseline audit
3
+ //
4
+ // `typecad-hal audit` — evaluate the last build's MERGED Kconfig
5
+ // (<buildDir>/zephyr/.config, the as-built truth nothing else reads) against
6
+ // a curated Zephyr security baseline, in the spirit of the EU Cyber
7
+ // Resilience Act's essential requirements (secure by default, attack surface
8
+ // minimised, no hard-coded credentials, functioning crypto underpinnings).
9
+ //
10
+ // Architecture mirrors the AUTOSAR compliance module and the sbom command:
11
+ // rules are DATA evaluated over facts, never board-name branches; justified
12
+ // exceptions are DEVIATIONS recorded in a committed waiver file
13
+ // (.typecad-hal/audit-waivers.json) rather than suppressed findings; the
14
+ // presenter never calls process.exit() and sets process.exitCode under
15
+ // --strict only for unwaived high/medium findings. A machine-readable
16
+ // sidecar (<buildDir>/security-audit.json) is written on every run — the
17
+ // input the CRA technical file and the future VEX/audit feed consume.
18
+ // ---------------------------------------------------------------------------
19
+
20
+ import { readFileSync, readdirSync, mkdirSync, writeFileSync } from 'node:fs';
21
+ import * as path from 'node:path';
22
+ import * as ui from '@typecad/cuttlefish/utils/ui';
23
+ import { loadTypecadConfig } from '@typecad/cuttlefish/config-loader';
24
+ import type { ReadFile } from '@typecad/cuttlefish/api/shared';
25
+ import { findCompileCommandsPath } from './west-inventory.js';
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // Merged-config parsing
29
+ // ---------------------------------------------------------------------------
30
+
31
+ export type KconfigValue = string | number | boolean;
32
+
33
+ /** Parse a merged Kconfig file: `CONFIG_X=y` (true), `# CONFIG_X is not set`
34
+ * (explicit false), `CONFIG_X=123` / `CONFIG_X="s"` (value). Comment blocks
35
+ * and everything else are ignored. Absent symbols are simply not in the map
36
+ * (Kconfig default applies — treat as "not enabled" for y/n symbols). */
37
+ export function parseMergedConfig(text: string): Map<string, KconfigValue> {
38
+ const out = new Map<string, KconfigValue>();
39
+ for (const line of text.split(/\r?\n/)) {
40
+ const notSet = line.match(/^#\s*CONFIG_([A-Z0-9_]+) is not set$/);
41
+ if (notSet) {
42
+ out.set(`CONFIG_${notSet[1]}`, false);
43
+ continue;
44
+ }
45
+ const set = line.match(/^CONFIG_([A-Z0-9_]+)=(.*)$/);
46
+ if (set) {
47
+ const raw = set[2].trim();
48
+ if (raw === 'y') out.set(`CONFIG_${set[1]}`, true);
49
+ else if (raw === 'n') out.set(`CONFIG_${set[1]}`, false);
50
+ else if (/^-?\d+$/.test(raw)) out.set(`CONFIG_${set[1]}`, Number(raw));
51
+ else if (/^".*"$/s.test(raw)) out.set(`CONFIG_${set[1]}`, raw.slice(1, -1));
52
+ else out.set(`CONFIG_${set[1]}`, raw);
53
+ }
54
+ }
55
+ return out;
56
+ }
57
+
58
+ /** Sweep a resolved devicetree for every `compatible` string — the enabled
59
+ * hardware the firmware actually wired (attack-surface inventory input).
60
+ * Multi-string compatibles ("a,b", "a,b-fallback") contribute EVERY entry
61
+ * (the fallback binds the same node); nodes marked status = "disabled"
62
+ * contribute nothing. Node scoping is a brace-depth walk: every block is a
63
+ * node, and only its OWN properties (nested child blocks stripped) decide
64
+ * its status/compatibles. */
65
+ export function sweepCompatibles(dtsText: string): string[] {
66
+ const found = new Set<string>();
67
+ // The block's own properties: the text with nested child blocks removed.
68
+ const ownProps = (body: string): string => {
69
+ let out = '';
70
+ let depth = 0;
71
+ for (const ch of body) {
72
+ if (ch === '{') { depth++; continue; }
73
+ if (ch === '}') { depth--; continue; }
74
+ if (depth === 0) out += ch;
75
+ }
76
+ return out;
77
+ };
78
+ // Visit EVERY node block (advancing past '{' only, so nested nodes are
79
+ // found by later iterations too).
80
+ let i = 0;
81
+ while (i < dtsText.length) {
82
+ const open = dtsText.indexOf('{', i);
83
+ if (open < 0) break;
84
+ let depth = 1;
85
+ let j = open + 1;
86
+ while (j < dtsText.length && depth > 0) {
87
+ const c = dtsText[j];
88
+ if (c === '{') depth++;
89
+ else if (c === '}') depth--;
90
+ j++;
91
+ }
92
+ const props = ownProps(dtsText.slice(open + 1, Math.min(j, dtsText.length) - (depth === 0 ? 1 : 0)));
93
+ if (!/status\s*=\s*"disabled"/.test(props)) {
94
+ for (const m of props.matchAll(/compatible\s*=\s*((?:"[^"]*"\s*,?\s*)+)/g)) {
95
+ for (const s of m[1].matchAll(/"([^"]+)"/g)) found.add(s[1]);
96
+ }
97
+ }
98
+ i = open + 1;
99
+ }
100
+ return [...found].sort();
101
+ }
102
+
103
+ // ---------------------------------------------------------------------------
104
+ // Facts + rules
105
+ // ---------------------------------------------------------------------------
106
+
107
+ export interface SecurityFacts {
108
+ config: Map<string, KconfigValue>;
109
+ compatibles: string[];
110
+ }
111
+
112
+ const on = (f: SecurityFacts, name: string): boolean => f.config.get(name) === true;
113
+ const anyOn = (f: SecurityFacts, ...names: string[]): boolean => names.some((n) => on(f, n));
114
+
115
+ export type AuditSeverity = 'high' | 'medium' | 'low';
116
+
117
+ export interface AuditFinding {
118
+ rule: string;
119
+ title: string;
120
+ severity: AuditSeverity;
121
+ requirement: string;
122
+ remediation: string;
123
+ /** The as-built evidence line(s) that triggered the rule. */
124
+ evidence: string;
125
+ }
126
+
127
+ export interface AuditRule {
128
+ id: string;
129
+ title: string;
130
+ severity: AuditSeverity;
131
+ /** CRA essential-requirement paraphrase this rule maps to. */
132
+ requirement: string;
133
+ remediation: string;
134
+ /** Returns the evidence string when the rule fires, else null. */
135
+ evaluate: (facts: SecurityFacts) => string | null;
136
+ }
137
+
138
+ /**
139
+ * The Zephyr security baseline. Rules read ONLY config/devicetree facts —
140
+ * never a board name or SoC family (all-boards-are-equal). Every rule must
141
+ * be waivable with a recorded justification: real products have real
142
+ * exceptions, and a conformity assessor wants to see them documented, not
143
+ * hidden.
144
+ */
145
+ export const SECURITY_RULES: readonly AuditRule[] = [
146
+ {
147
+ id: 'zephyr.gdbstub',
148
+ title: 'remote debug stub compiled into the image',
149
+ severity: 'high',
150
+ requirement: 'Annex I 1.2(a) — attack surface minimised; no remotely exploitable debug interfaces',
151
+ remediation: 'disable CONFIG_GDBSTUB for production builds (gate it behind a debug build type)',
152
+ evaluate: (f) => (on(f, 'CONFIG_GDBSTUB') ? 'CONFIG_GDBSTUB=y' : null),
153
+ },
154
+ {
155
+ id: 'zephyr.bt-fixed-passkey',
156
+ title: 'static Bluetooth pairing passkey (hard-coded credential)',
157
+ severity: 'high',
158
+ requirement: 'Annex I 1.2(f) — no hard-coded credentials; unique per-device secrets',
159
+ remediation: 'remove CONFIG_BT_FIXED_PASSKEY and use per-device pairing (just-in-time/numeric comparison)',
160
+ evaluate: (f) => {
161
+ const v = f.config.get('CONFIG_BT_FIXED_PASSKEY');
162
+ return typeof v === 'number' ? `CONFIG_BT_FIXED_PASSKEY=${v}` : null;
163
+ },
164
+ },
165
+ {
166
+ id: 'zephyr.entropy-missing',
167
+ title: 'crypto/networking enabled without a hardware entropy source',
168
+ severity: 'high',
169
+ requirement: 'Annex I 1.2(c) — cryptographic primitives backed by proper randomness',
170
+ remediation: 'enable CONFIG_ENTROPY_GENERATOR (the board SoC entropy driver) — keys and nonces '
171
+ + 'derived without it are predictable',
172
+ evaluate: (f) => {
173
+ if (on(f, 'CONFIG_ENTROPY_GENERATOR')) return null;
174
+ const consumers = ['CONFIG_BT', 'CONFIG_NETWORKING', 'CONFIG_MBEDTLS', 'CONFIG_TINYCRYPT'].filter(
175
+ (n) => on(f, n),
176
+ );
177
+ if (consumers.length === 0) return null;
178
+ return '# CONFIG_ENTROPY_GENERATOR is not set (while '
179
+ + consumers.map((c) => `${c}=y`).join(', ')
180
+ + ')';
181
+ },
182
+ },
183
+ {
184
+ id: 'zephyr.shell-enabled',
185
+ title: 'interactive shell compiled in',
186
+ severity: 'high',
187
+ requirement: 'Annex I 1.2(a) — attack surface minimised; no unnecessary interactive interfaces',
188
+ remediation: 'disable CONFIG_SHELL for production builds, or restrict it to a debug build type',
189
+ evaluate: (f) => (on(f, 'CONFIG_SHELL') ? 'CONFIG_SHELL=y' : null),
190
+ },
191
+ {
192
+ id: 'zephyr.network-no-tls',
193
+ title: 'network stack enabled without a TLS library',
194
+ severity: 'medium',
195
+ requirement: 'Annex I 1.2(c)/(e) — confidential communication over networks',
196
+ remediation: 'enable CONFIG_MBEDTLS (mbedTLS SSL) for networked firmware, or document why the '
197
+ + 'traffic may stay in cleartext',
198
+ evaluate: (f) =>
199
+ on(f, 'CONFIG_NETWORKING') && !on(f, 'CONFIG_MBEDTLS')
200
+ ? 'CONFIG_NETWORKING=y, # CONFIG_MBEDTLS is not set'
201
+ : null,
202
+ },
203
+ {
204
+ id: 'zephyr.watchdog-absent',
205
+ title: 'no watchdog configured',
206
+ severity: 'medium',
207
+ requirement: 'Annex I 1.3(b) — resilience and availability of essential functions',
208
+ remediation: 'enable CONFIG_WATCHDOG and feed it from the app (hal: `new Watchdog(...)` on a '
209
+ + 'watchdog-capable board) so hangs recover instead of bricking the product',
210
+ evaluate: (f) => (on(f, 'CONFIG_WATCHDOG') ? null : '# CONFIG_WATCHDOG is not set'),
211
+ },
212
+ {
213
+ id: 'zephyr.console-enabled',
214
+ title: 'diagnostic console enabled',
215
+ severity: 'low',
216
+ requirement: 'Annex I 1.2(a) — attack surface minimised (informational: consoles are often '
217
+ + 'intentional in the field)',
218
+ remediation: 'if the console is not needed in production, disable it (CONFIG_UART_CONSOLE / '
219
+ + 'CONFIG_USB_CONSOLE / CONFIG_RTT_CONSOLE)',
220
+ evaluate: (f) => {
221
+ const which = ['CONFIG_UART_CONSOLE', 'CONFIG_USB_CONSOLE', 'CONFIG_RTT_CONSOLE'].filter((n) =>
222
+ on(f, n),
223
+ );
224
+ return which.length > 0 ? which.join(', ') + ' enabled' : null;
225
+ },
226
+ },
227
+ {
228
+ id: 'zephyr.hardening-off',
229
+ title: 'compiler hardening stack not enabled',
230
+ severity: 'low',
231
+ requirement: 'Annex I 1.2(b) — reduce exploitability of residual vulnerabilities',
232
+ remediation: 'enable CONFIG_HARDENING (stack canaries and friends) unless the overhead is '
233
+ + 'measured to matter',
234
+ evaluate: (f) => (on(f, 'CONFIG_HARDENING') ? null : 'CONFIG_HARDENING not enabled'),
235
+ },
236
+ ];
237
+
238
+ /** Evaluate the baseline over the facts. Order follows rule severity. */
239
+ export function evaluateSecurityRules(facts: SecurityFacts): AuditFinding[] {
240
+ const order: Record<AuditSeverity, number> = { high: 0, medium: 1, low: 2 };
241
+ const findings: AuditFinding[] = [];
242
+ for (const rule of SECURITY_RULES) {
243
+ const evidence = rule.evaluate(facts);
244
+ if (evidence !== null) {
245
+ findings.push({
246
+ rule: rule.id,
247
+ title: rule.title,
248
+ severity: rule.severity,
249
+ requirement: rule.requirement,
250
+ remediation: rule.remediation,
251
+ evidence,
252
+ });
253
+ }
254
+ }
255
+ findings.sort((a, b) => order[a.severity] - order[b.severity]);
256
+ return findings;
257
+ }
258
+
259
+ // ---------------------------------------------------------------------------
260
+ // Waivers (recorded deviations, committed with the project)
261
+ // ---------------------------------------------------------------------------
262
+
263
+ export interface AuditWaiver {
264
+ rule: string;
265
+ justification: string;
266
+ date?: string;
267
+ }
268
+
269
+ export function parseWaiverFile(text: string | undefined): { waivers: AuditWaiver[]; error?: string } {
270
+ if (!text) return { waivers: [] };
271
+ try {
272
+ const parsed = JSON.parse(text) as { waivers?: unknown };
273
+ if (!parsed || !Array.isArray(parsed.waivers)) {
274
+ return { waivers: [], error: 'waiver file must be `{ "waivers": [...] }` — ignored' };
275
+ }
276
+ const waivers: AuditWaiver[] = [];
277
+ for (const w of parsed.waivers) {
278
+ if (
279
+ w &&
280
+ typeof w === 'object' &&
281
+ typeof (w as AuditWaiver).rule === 'string' &&
282
+ typeof (w as AuditWaiver).justification === 'string'
283
+ ) {
284
+ const entry = w as AuditWaiver;
285
+ if (entry.justification.trim().length === 0) {
286
+ return { waivers: [], error: `waiver for ${entry.rule} has an empty justification — ignored` };
287
+ }
288
+ waivers.push(entry);
289
+ }
290
+ }
291
+ return { waivers };
292
+ } catch {
293
+ return { waivers: [], error: 'waiver file is not valid JSON — ignored' };
294
+ }
295
+ }
296
+
297
+ /** Find .typecad-hal/audit-waivers.json, walking up from `cwd` (bounded). */
298
+ export function findWaiverFile(readFile: ReadFile, cwd: string): string | undefined {
299
+ let dir = path.resolve(cwd);
300
+ for (let i = 0; i < 5; i++) {
301
+ const p = path.join(dir, '.typecad-hal', 'audit-waivers.json');
302
+ if (readFile(p)) return p;
303
+ const parent = path.dirname(dir);
304
+ if (parent === dir) break;
305
+ dir = parent;
306
+ }
307
+ return undefined;
308
+ }
309
+
310
+ // ---------------------------------------------------------------------------
311
+ // Runner seam (test injection; no west needed — the audit reads the build)
312
+ // ---------------------------------------------------------------------------
313
+
314
+ export interface AuditRunner {
315
+ cwd?: string;
316
+ /** The last build's compile_commands.json path, or undefined. */
317
+ compileCommandsPath?: () => string | undefined;
318
+ readFile: ReadFile;
319
+ }
320
+
321
+ function defaultAuditRunner(cwd = process.cwd()): AuditRunner {
322
+ const readFile: ReadFile = (p) => {
323
+ try {
324
+ return readFileSync(p, 'utf8');
325
+ } catch {
326
+ return undefined;
327
+ }
328
+ };
329
+ const readdir = (d: string): string[] => {
330
+ try {
331
+ return readdirSync(d);
332
+ } catch {
333
+ return [];
334
+ }
335
+ };
336
+ return {
337
+ cwd,
338
+ compileCommandsPath: () => findCompileCommandsPath(readFile, readdir, cwd),
339
+ readFile,
340
+ };
341
+ }
342
+
343
+ // ---------------------------------------------------------------------------
344
+ // Report
345
+ // ---------------------------------------------------------------------------
346
+
347
+ export interface AuditReport {
348
+ schema: 'typecad-hal/security-audit@1';
349
+ generated: string;
350
+ buildDir: string;
351
+ summary: {
352
+ console: 'uart' | 'usb' | 'rtt' | 'none';
353
+ shell: boolean;
354
+ network: boolean;
355
+ bluetooth: boolean;
356
+ usbDevice: boolean;
357
+ entropy: boolean;
358
+ watchdog: boolean;
359
+ hardware: string[];
360
+ };
361
+ findings: AuditFinding[];
362
+ deviations: (AuditFinding & { justification: string; date?: string })[];
363
+ rulesEvaluated: number;
364
+ waiverFile?: string;
365
+ }
366
+
367
+ export function buildAuditReport(args: {
368
+ buildDir: string;
369
+ facts: SecurityFacts;
370
+ findings: AuditFinding[];
371
+ deviations: (AuditFinding & { justification: string; date?: string })[];
372
+ generated?: string;
373
+ waiverFile?: string;
374
+ }): AuditReport {
375
+ const f = args.facts;
376
+ const consoleType = on(f, 'CONFIG_UART_CONSOLE')
377
+ ? 'uart'
378
+ : on(f, 'CONFIG_USB_CONSOLE')
379
+ ? 'usb'
380
+ : on(f, 'CONFIG_RTT_CONSOLE')
381
+ ? 'rtt'
382
+ : 'none';
383
+ return {
384
+ schema: 'typecad-hal/security-audit@1',
385
+ generated: args.generated ?? new Date().toISOString(),
386
+ buildDir: args.buildDir,
387
+ summary: {
388
+ console: consoleType,
389
+ shell: on(f, 'CONFIG_SHELL'),
390
+ network: on(f, 'CONFIG_NETWORKING'),
391
+ bluetooth: on(f, 'CONFIG_BT'),
392
+ usbDevice: anyOn(f, 'CONFIG_USB_DEVICE_STACK', 'CONFIG_USB_DEVICE_DRIVER'),
393
+ entropy: on(f, 'CONFIG_ENTROPY_GENERATOR'),
394
+ watchdog: on(f, 'CONFIG_WATCHDOG'),
395
+ hardware: f.compatibles,
396
+ },
397
+ findings: args.findings,
398
+ deviations: args.deviations,
399
+ rulesEvaluated: SECURITY_RULES.length,
400
+ waiverFile: args.waiverFile,
401
+ };
402
+ }
403
+
404
+ /** Options accepted by `runAuditPresenter` (structurally compatible with the
405
+ * parsed `typecad-hal audit` CLI options). */
406
+ export interface AuditPresenterOptions {
407
+ /** Exit 1 on any unwaived high/medium finding. */
408
+ strict?: boolean;
409
+ /** Print only the JSON report (clean CI pipe); the sidecar is still written. */
410
+ json?: boolean;
411
+ }
412
+
413
+ let testRunner: AuditRunner | undefined;
414
+
415
+ /** @internal Test-only override of the default runner. */
416
+ export function __setAuditRunnerForTest(runner: AuditRunner | undefined): void {
417
+ testRunner = runner;
418
+ }
419
+
420
+ function printFinding(f: AuditFinding, waived?: string): void {
421
+ // ui.printWarning already stamps its own "! " marker.
422
+ ui.printWarning(`${waived ? 'waived ' : ''}[${f.severity}] ${f.rule} — ${f.title}`);
423
+ ui.printInfo(` requirement: ${f.requirement}`);
424
+ ui.printInfo(` evidence: ${f.evidence}`);
425
+ ui.printInfo(` fix: ${f.remediation}`);
426
+ if (waived) ui.printInfo(` waived: ${waived}`);
427
+ }
428
+
429
+ /** `typecad-hal audit` presenter. */
430
+ export function runAuditPresenter(options: AuditPresenterOptions): void {
431
+ const runner = testRunner ?? defaultAuditRunner();
432
+ const cwd = runner.cwd ?? process.cwd();
433
+
434
+ const ccPath = runner.compileCommandsPath ? runner.compileCommandsPath() : undefined;
435
+ const buildDir = ccPath ? path.dirname(ccPath) : undefined;
436
+ const configText = buildDir ? runner.readFile(path.join(buildDir, 'zephyr', '.config')) : undefined;
437
+ if (!buildDir || configText === undefined) {
438
+ ui.printError(
439
+ 'No build found — audit reads the merged zephyr/.config of the last build. Run typecad-hal build first.',
440
+ );
441
+ process.exitCode = 1;
442
+ return;
443
+ }
444
+ const dtsText = runner.readFile(path.join(buildDir, 'zephyr', 'zephyr.dts'));
445
+ const facts: SecurityFacts = {
446
+ config: parseMergedConfig(configText),
447
+ compatibles: dtsText ? sweepCompatibles(dtsText) : [],
448
+ };
449
+
450
+ const all = evaluateSecurityRules(facts);
451
+ const waiverPath = findWaiverFile(runner.readFile, cwd);
452
+ const { waivers, error: waiverError } = parseWaiverFile(
453
+ waiverPath ? runner.readFile(waiverPath) : undefined,
454
+ );
455
+ const waivedByRule = new Map(waivers.map((w) => [w.rule, w]));
456
+ const findings = all.filter((f) => !waivedByRule.has(f.rule));
457
+ const deviations = all
458
+ .filter((f) => waivedByRule.has(f.rule))
459
+ .map((f) => ({ ...f, ...(waivedByRule.get(f.rule) as AuditWaiver) }));
460
+
461
+ const report = buildAuditReport({ buildDir, facts, findings, deviations, waiverFile: waiverPath });
462
+
463
+ // Sidecar first (best-effort, never fatal), then the human/JSON surface.
464
+ try {
465
+ mkdirSync(buildDir, { recursive: true });
466
+ writeFileSync(path.join(buildDir, 'security-audit.json'), JSON.stringify(report, null, 2) + '\n');
467
+ } catch {
468
+ /* best-effort sidecar */
469
+ }
470
+
471
+ // --strict: unwaived high/medium findings fail. Waived findings are
472
+ // recorded deviations, not failures.
473
+ const failing = findings.filter((f) => f.severity === 'high' || f.severity === 'medium');
474
+ if (options.strict && failing.length > 0) {
475
+ process.exitCode = 1;
476
+ }
477
+
478
+ if (options.json) {
479
+ console.log(JSON.stringify(report, null, 2));
480
+ return;
481
+ }
482
+
483
+ ui.printHeader();
484
+ ui.printStep('Auditing the merged build configuration (security baseline)');
485
+
486
+ let boardTarget: string | undefined;
487
+ try {
488
+ boardTarget = loadTypecadConfig(process.cwd())?.buildTarget;
489
+ } catch {
490
+ /* best-effort */
491
+ }
492
+ if (boardTarget) ui.printInfo(`board ............. ${boardTarget}`);
493
+
494
+ const s = report.summary;
495
+ ui.printInfo(
496
+ `surface ........... console ${s.console} · shell ${s.shell ? 'ON' : 'off'} · net ${s.network ? 'ON' : 'off'} · ` +
497
+ `BLE ${s.bluetooth ? 'ON' : 'off'} · USB device ${s.usbDevice ? 'ON' : 'off'}`,
498
+ );
499
+ ui.printInfo(
500
+ `underpinnings ..... entropy ${s.entropy ? 'ok' : 'OFF'} · watchdog ${s.watchdog ? 'ok' : 'OFF'} · ` +
501
+ `${s.hardware.length} wired compatible(s)`,
502
+ );
503
+ if (waiverError) ui.printWarning(`waiver file: ${waiverError}`);
504
+
505
+ for (const f of findings) printFinding(f);
506
+ for (const d of deviations) {
507
+ printFinding(d, `${d.justification}${d.date ? ` (${d.date})` : ''}`);
508
+ }
509
+
510
+ if (all.length === 0) {
511
+ ui.printSuccess(`baseline clean — ${report.rulesEvaluated} rules evaluated, 0 findings.`);
512
+ } else {
513
+ ui.printWarning(
514
+ `${findings.length} finding(s) (${failing.length} unwaived high/medium), ` +
515
+ `${deviations.length} waived deviation(s).`,
516
+ );
517
+ }
518
+ if (waiverPath) {
519
+ ui.printInfo(`waivers .......... ${waiverPath}`);
520
+ }
521
+ ui.printInfo(`sidecar .......... ${path.join(buildDir, 'security-audit.json')}`);
522
+ if (options.strict) {
523
+ ui.printInfo(
524
+ failing.length > 0
525
+ ? '--strict .......... FAIL (unwaived high/medium findings above)'
526
+ : '--strict .......... pass',
527
+ );
528
+ }
529
+ }