@typecad/framework-zephyr 1.0.0-alpha.18 → 1.0.0-alpha.20

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 (114) hide show
  1. package/dist/audit.d.ts +111 -0
  2. package/dist/audit.js +416 -0
  3. package/dist/boardgen.js +63 -5
  4. package/dist/chips/resolve.js +20 -0
  5. package/dist/chips/types.d.ts +21 -0
  6. package/dist/display/bindings.d.ts +55 -0
  7. package/dist/display/bindings.js +316 -0
  8. package/dist/display/gfx.d.ts +2 -3
  9. package/dist/display/gfx.js +166 -154
  10. package/dist/display/index.js +20 -1
  11. package/dist/display/mipi-dbi-host.d.ts +9 -0
  12. package/dist/display/mipi-dbi-host.js +174 -0
  13. package/dist/display/profiles.d.ts +109 -4
  14. package/dist/display/profiles.js +270 -7
  15. package/dist/display/touch-adapter.js +118 -48
  16. package/dist/display/ui-adapter-eink.d.ts +2 -0
  17. package/dist/display/ui-adapter-eink.js +4 -0
  18. package/dist/display/ui-adapter-gray.d.ts +8 -0
  19. package/dist/display/ui-adapter-gray.js +170 -0
  20. package/dist/display/ui-adapter-mono.d.ts +13 -0
  21. package/dist/display/ui-adapter-mono.js +230 -0
  22. package/dist/display/ui-adapter-native.d.ts +10 -0
  23. package/dist/display/ui-adapter-native.js +295 -0
  24. package/dist/display/ui-adapter-shared.d.ts +11 -0
  25. package/dist/display/ui-adapter-shared.js +122 -0
  26. package/dist/display/ui-adapter.js +53 -101
  27. package/dist/dt-config/kconfig.d.ts +62 -1
  28. package/dist/dt-config/kconfig.js +123 -26
  29. package/dist/dt-config/overlay.d.ts +13 -0
  30. package/dist/dt-config/overlay.js +431 -16
  31. package/dist/framework.manifest.d.ts +9 -3
  32. package/dist/framework.manifest.js +123 -10
  33. package/dist/index.d.ts +2 -0
  34. package/dist/index.js +9 -1
  35. package/dist/licenses.js +5 -84
  36. package/dist/lowering/can.d.ts +25 -0
  37. package/dist/lowering/can.js +97 -0
  38. package/dist/lowering/clock.d.ts +17 -0
  39. package/dist/lowering/clock.js +58 -0
  40. package/dist/lowering/hid.d.ts +27 -0
  41. package/dist/lowering/hid.js +244 -0
  42. package/dist/lowering/i2c.d.ts +8 -0
  43. package/dist/lowering/i2c.js +140 -0
  44. package/dist/lowering/i2s.d.ts +27 -0
  45. package/dist/lowering/i2s.js +98 -0
  46. package/dist/lowering/index.d.ts +9 -1
  47. package/dist/lowering/index.js +25 -1
  48. package/dist/lowering/matrix.d.ts +15 -0
  49. package/dist/lowering/matrix.js +63 -0
  50. package/dist/lowering/power.d.ts +10 -0
  51. package/dist/lowering/power.js +35 -0
  52. package/dist/lowering/pwm.js +25 -0
  53. package/dist/lowering/sensor.d.ts +2 -2
  54. package/dist/lowering/sensor.js +8 -4
  55. package/dist/lowering/strip.d.ts +16 -0
  56. package/dist/lowering/strip.js +70 -0
  57. package/dist/lowering/thread.js +5 -1
  58. package/dist/lowering/trace.d.ts +44 -0
  59. package/dist/lowering/trace.js +239 -0
  60. package/dist/lowering/uart.js +6 -1
  61. package/dist/lowering/usb.d.ts +3 -1
  62. package/dist/lowering/usb.js +6 -3
  63. package/dist/sbom.d.ts +181 -0
  64. package/dist/sbom.js +901 -0
  65. package/dist/strategy.d.ts +60 -2
  66. package/dist/strategy.js +485 -25
  67. package/dist/toolchain/index.d.ts +12 -1
  68. package/dist/toolchain/index.js +115 -27
  69. package/dist/toolchain/scaffold.d.ts +4 -1
  70. package/dist/toolchain/scaffold.js +67 -3
  71. package/dist/west-inventory.d.ts +25 -0
  72. package/dist/west-inventory.js +97 -0
  73. package/package.json +6 -6
  74. package/src/audit.ts +529 -0
  75. package/src/boardgen.ts +54 -5
  76. package/src/chips/resolve.ts +21 -0
  77. package/src/chips/types.ts +576 -567
  78. package/src/display/bindings.ts +347 -0
  79. package/src/display/gfx.ts +318 -306
  80. package/src/display/index.ts +87 -70
  81. package/src/display/mipi-dbi-host.ts +183 -0
  82. package/src/display/profiles.ts +458 -139
  83. package/src/display/touch-adapter.ts +274 -204
  84. package/src/display/ui-adapter-eink.ts +13 -0
  85. package/src/display/ui-adapter-gray.ts +178 -0
  86. package/src/display/ui-adapter-mono.ts +238 -0
  87. package/src/display/ui-adapter-native.ts +304 -0
  88. package/src/display/ui-adapter-shared.ts +125 -0
  89. package/src/display/ui-adapter.ts +51 -100
  90. package/src/dt-config/kconfig.ts +647 -511
  91. package/src/dt-config/overlay.ts +433 -16
  92. package/src/framework.manifest.ts +131 -10
  93. package/src/index.ts +11 -1
  94. package/src/licenses.ts +5 -84
  95. package/src/lowering/can.ts +140 -0
  96. package/src/lowering/clock.ts +91 -0
  97. package/src/lowering/hid.ts +261 -0
  98. package/src/lowering/i2c.ts +146 -0
  99. package/src/lowering/i2s.ts +143 -0
  100. package/src/lowering/index.ts +18 -1
  101. package/src/lowering/matrix.ts +70 -0
  102. package/src/lowering/power.ts +41 -0
  103. package/src/lowering/pwm.ts +192 -167
  104. package/src/lowering/sensor.ts +159 -155
  105. package/src/lowering/strip.ts +81 -0
  106. package/src/lowering/thread.ts +5 -1
  107. package/src/lowering/trace.ts +270 -0
  108. package/src/lowering/uart.ts +6 -1
  109. package/src/lowering/usb.ts +224 -221
  110. package/src/sbom.ts +1117 -0
  111. package/src/strategy.ts +440 -25
  112. package/src/toolchain/index.ts +117 -28
  113. package/src/toolchain/scaffold.ts +62 -3
  114. package/src/west-inventory.ts +102 -0
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
+ }
package/src/boardgen.ts CHANGED
@@ -986,14 +986,32 @@ export function buildModule(
986
986
  ts.push('');
987
987
  ts.push('// Hardware this board actually has — unavailable hardware is not importable.');
988
988
  if (wdtNodeLabel) ts.push(`export { Watchdog } from '@typecad/hal/core';`);
989
- if (siliconPwm.length > 0 || pwmLedSpecs.length > 0 || pwmMatrix) ts.push(`export { PWM } from '@typecad/hal/core';`);
989
+ if (siliconPwm.length > 0 || pwmLedSpecs.length > 0 || pwmMatrix) ts.push(`export { PWM, Servo } from '@typecad/hal/core';`);
990
990
  if (siliconAdc.length > 0) ts.push(`export { ADC } from '@typecad/hal/core';`);
991
991
  if (siliconDac.length > 0) ts.push(`export { DAC } from '@typecad/hal/core';`);
992
- if (buses.i2c.length > 0) ts.push(`export { I2CTarget } from '@typecad/hal/core';`);
992
+ // The responder rides the same wired-bus fact as I2CTarget — target-mode
993
+ // support is a controller-driver property discovered at registration
994
+ // (-ENOSYS prints loudly), never a board-name gate.
995
+ if (buses.i2c.length > 0) ts.push(`export { I2CTarget, I2CResponder } from '@typecad/hal/core';`);
993
996
  if (buses.spi.length > 0) ts.push(`export { SPITarget } from '@typecad/hal/core';`);
994
997
  if (buses.uart.length > 0) ts.push(`export { UART } from '@typecad/hal/core';`);
995
998
  if (hwtimerControllers.length > 0) ts.push(`export { Counter } from '@typecad/hal/core';`);
996
- if (hasUsb) ts.push(`export { USBConsole } from '@typecad/hal/core';`);
999
+ // Clock rides the same free-counter facts (the zephyr,rtc-counter shim
1000
+ // wraps the counter when the board ships no hardware rtc alias).
1001
+ if (hwtimerControllers.length > 0) ts.push(`export { Clock } from '@typecad/hal/core';`);
1002
+ // CAN rides the harvested controller nodes (ESP32 TWAI, STM32 bxCAN,
1003
+ // NXP FlexCAN…); a SoC with none exports nothing.
1004
+ if ((entry.canNodes ?? []).length > 0) ts.push(`export { CAN } from '@typecad/hal/core';`);
1005
+ // I2S rides the harvested i2s@ controllers.
1006
+ if ((entry.i2sNodes ?? []).length > 0) ts.push(`export { I2S } from '@typecad/hal/core';`);
1007
+ // Power rides the SoC's declared cpu-power-states (both the ESP32 family's
1008
+ // standby + soft-off pair and STM32's suspend-to-idle count; a SoC with no
1009
+ // declared states exports nothing).
1010
+ if ((entry.powerStates ?? []).length > 0) ts.push(`export { Power } from '@typecad/hal/core';`);
1011
+ // KEY/MOUSE are ungated token tables — the derived always-available
1012
+ // re-export line above already carries them on every board; only the HID
1013
+ // device classes ride the USB gate.
1014
+ if (hasUsb) ts.push(`export { USBConsole, Keyboard, Mouse } from '@typecad/hal/core';`);
997
1015
  // Store/File: a persisted backend needs a storage region — either the
998
1016
  // board's own storage_partition (harvested reg) or a synthesizable one
999
1017
  // (flash size known, no existing partition to collide with).
@@ -1107,12 +1125,15 @@ export function buildModule(
1107
1125
  // GPIO driver API (`gpio_pin_configure` flags + `gpio_pin_interrupt_configure`):
1108
1126
  // every GPIO controller implements them, so they are universally true —
1109
1127
  // a platform fact, not a per-pad one. Analog/PWM ride the harvested
1110
- // silicon routes (honest per-pad facts).
1128
+ // silicon routes (honest per-pad facts); PWM counts both route kinds —
1129
+ // fixed pinctrl routes AND any-pad matrices (ESP32 LEDC, nRF psel), the
1130
+ // same set union the pin JSDoc and the PWM export gate read, so the
1131
+ // hover annotation and the capability flag cannot disagree.
1111
1132
  constants[`pins.all.${i}.capabilities.digitalInput`] = true;
1112
1133
  constants[`pins.all.${i}.capabilities.digitalOutput`] = true;
1113
1134
  constants[`pins.all.${i}.capabilities.analogInput`] = siliconAdcPins.has(p.halPin);
1114
1135
  constants[`pins.all.${i}.capabilities.analogOutput`] = siliconDacPins.has(p.halPin);
1115
- constants[`pins.all.${i}.capabilities.pwm`] = siliconPwmPins.has(p.halPin);
1136
+ constants[`pins.all.${i}.capabilities.pwm`] = siliconPwmPins.has(p.halPin) || (matrixPwmPins?.has(p.halPin) ?? false);
1116
1137
  constants[`pins.all.${i}.capabilities.interrupt`] = true;
1117
1138
  constants[`pins.all.${i}.capabilities.pullUp`] = true;
1118
1139
  constants[`pins.all.${i}.capabilities.pullDown`] = true;
@@ -1121,6 +1142,34 @@ export function buildModule(
1121
1142
  constants[`pins.all.${i}.capabilities.touch`] = false;
1122
1143
  constants[`pins.all.${i}.capabilities.openDrain`] = true;
1123
1144
  });
1145
+ // CPU power states — the harvested PM capability facts (which levels
1146
+ // exist, their idle timing, and whether the automatic policy may enter
1147
+ // them; ESP32's soft-off is explicit-entry only).
1148
+ const powerStates = entry.powerStates ?? [];
1149
+ powerStates.forEach((ps, i) => {
1150
+ constants[`zephyr.power.states.${i}.name`] = ps.name;
1151
+ if (ps.minResidencyUs !== undefined) constants[`zephyr.power.states.${i}.minResidencyUs`] = ps.minResidencyUs;
1152
+ if (ps.exitLatencyUs !== undefined) constants[`zephyr.power.states.${i}.exitLatencyUs`] = ps.exitLatencyUs;
1153
+ constants[`zephyr.power.states.${i}.enabled`] = ps.enabled;
1154
+ });
1155
+ if (powerStates.length > 0) {
1156
+ constants['zephyr.power.softOff'] = powerStates.some((ps) => ps.name === 'soft-off');
1157
+ }
1158
+ if (entry.rtcWakeTimer) constants['zephyr.power.wakeTimer'] = true;
1159
+ // CAN controllers — the harvested labeled nodes (the CAN class gate). The
1160
+ // ESP32 TWAI pads ride along: loopback overlays route both TWAI functions
1161
+ // onto the TX pad.
1162
+ (entry.canNodes ?? []).forEach((c, i) => {
1163
+ constants[`zephyr.can.controllers.${i}.nodeLabel`] = c.nodeLabel;
1164
+ constants[`zephyr.can.controllers.${i}.compatible`] = c.compatible;
1165
+ if (c.txPad !== undefined) constants[`zephyr.can.controllers.${i}.txPad`] = c.txPad;
1166
+ if (c.rxPad !== undefined) constants[`zephyr.can.controllers.${i}.rxPad`] = c.rxPad;
1167
+ });
1168
+ // I2S controllers — the harvested labeled nodes (the I2S class gate).
1169
+ (entry.i2sNodes ?? []).forEach((c, i) => {
1170
+ constants[`zephyr.i2s.controllers.${i}.nodeLabel`] = c.nodeLabel;
1171
+ constants[`zephyr.i2s.controllers.${i}.compatible`] = c.compatible;
1172
+ });
1124
1173
  constants['peripherals.i2c.count'] = buses.i2c.length;
1125
1174
  constants['peripherals.spi.count'] = buses.spi.length;
1126
1175
  constants['peripherals.uart.count'] = buses.uart.length;
@@ -230,6 +230,24 @@ export function resolveChipFromBoard(
230
230
  // (+ optional vid/pid for the device descriptor).
231
231
  const usbController = bc.get('zephyr.usb.controller') as string | undefined;
232
232
  const usbCdcInstances = bc.get('zephyr.usb.cdcInstances') as number | undefined;
233
+ const wakeTimer = bc.get('zephyr.power.wakeTimer') as boolean | undefined;
234
+ const i2sControllers: { nodeLabel: string; compatible: string }[] = [];
235
+ for (let ii = 0; bc.get(`zephyr.i2s.controllers.${ii}.nodeLabel`) !== undefined; ii++) {
236
+ i2sControllers.push({
237
+ nodeLabel: String(bc.get(`zephyr.i2s.controllers.${ii}.nodeLabel`)),
238
+ compatible: String(bc.get(`zephyr.i2s.controllers.${ii}.compatible`)),
239
+ });
240
+ }
241
+ const canControllers: { nodeLabel: string; compatible: string; txPad?: number; rxPad?: number }[] = [];
242
+ for (let ci = 0; bc.get(`zephyr.can.controllers.${ci}.nodeLabel`) !== undefined; ci++) {
243
+ canControllers.push({
244
+ nodeLabel: String(bc.get(`zephyr.can.controllers.${ci}.nodeLabel`)),
245
+ compatible: String(bc.get(`zephyr.can.controllers.${ci}.compatible`)),
246
+ ...(bc.get(`zephyr.can.controllers.${ci}.txPad`) !== undefined ? { txPad: Number(bc.get(`zephyr.can.controllers.${ci}.txPad`)) } : {}),
247
+ ...(bc.get(`zephyr.can.controllers.${ci}.rxPad`) !== undefined ? { rxPad: Number(bc.get(`zephyr.can.controllers.${ci}.rxPad`)) } : {}),
248
+ });
249
+ }
250
+
233
251
  const usbVid = bc.get('zephyr.usb.vid') as string | undefined;
234
252
  const usbPid = bc.get('zephyr.usb.pid') as string | undefined;
235
253
  // Optional 1200-baud touch-to-reset data (BOSSA-bootloader boards).
@@ -367,6 +385,9 @@ export function resolveChipFromBoard(
367
385
  ...(storageOffset != null && storageSize != null
368
386
  ? { storage: { offset: storageOffset, size: storageSize, ...(storagePreexisting ? { preexisting: true } : {}) } }
369
387
  : {}),
388
+ ...(wakeTimer ? { powerWakeTimer: true } : {}),
389
+ ...(canControllers.length > 0 ? { can: { controllers: canControllers } } : {}),
390
+ ...(i2sControllers.length > 0 ? { i2s: { controllers: i2sControllers } } : {}),
370
391
  ...(usbController && usbCdcInstances && usbCdcInstances > 0
371
392
  ? {
372
393
  usb: {