sdtk-spec-kit 0.3.16 → 0.3.17

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.
@@ -0,0 +1,355 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const http = require("http");
5
+ const net = require("net");
6
+ const path = require("path");
7
+ const { spawn, execFile } = require("child_process");
8
+ const { DependencyError, CliError } = require("./errors");
9
+ const { resolveBuilderPath } = require("./atlas-config");
10
+ const { openBrowser } = require("./browser-open");
11
+
12
+ const HEALTH_CHECK_RETRIES = 20;
13
+ const HEALTH_CHECK_INTERVAL_MS = 300;
14
+
15
+ /**
16
+ * Find an available Python executable.
17
+ * Returns 'python3' on Unix, 'python' on Windows as first try.
18
+ *
19
+ * @returns {Promise<string>} Resolved python executable name.
20
+ */
21
+ function findPython() {
22
+ return new Promise((resolve, reject) => {
23
+ const candidates = process.platform === "win32"
24
+ ? ["python", "python3"]
25
+ : ["python3", "python"];
26
+
27
+ let idx = 0;
28
+ function tryNext() {
29
+ if (idx >= candidates.length) {
30
+ reject(
31
+ new DependencyError(
32
+ "Python not found. Install Python 3.8+ and ensure it is in PATH.\n" +
33
+ "Atlas build requires Python to run the local builder."
34
+ )
35
+ );
36
+ return;
37
+ }
38
+ const candidate = candidates[idx++];
39
+ execFile(candidate, ["--version"], { timeout: 5000 }, (err) => {
40
+ if (!err) {
41
+ resolve(candidate);
42
+ } else {
43
+ tryNext();
44
+ }
45
+ });
46
+ }
47
+ tryNext();
48
+ });
49
+ }
50
+
51
+ /**
52
+ * Run the Atlas Python builder with explicit project/output args.
53
+ *
54
+ * @param {Object} config - Resolved AtlasConfig.
55
+ * @returns {Promise<{ docCount: number, nodeCount: number, edgeCount: number, generated: string }>}
56
+ */
57
+ async function runBuild(config) {
58
+ const builderPath = resolveBuilderPath();
59
+ if (!fs.existsSync(builderPath)) {
60
+ throw new DependencyError(
61
+ `Atlas builder not found: ${builderPath}\n` +
62
+ "This is a packaging error. Reinstall sdtk-spec-kit."
63
+ );
64
+ }
65
+
66
+ const pythonExe = await findPython();
67
+
68
+ const args = [
69
+ builderPath,
70
+ "--project-root",
71
+ config.projectPath,
72
+ "--output-dir",
73
+ config.outputDir,
74
+ ];
75
+
76
+ for (const sr of config.scanRoots) {
77
+ args.push("--scan-root", sr);
78
+ }
79
+
80
+ for (const ex of config.excludes) {
81
+ args.push("--exclude", ex);
82
+ }
83
+
84
+ if (config.verbose) {
85
+ args.push("--verbose");
86
+ }
87
+
88
+ return new Promise((resolve, reject) => {
89
+ const child = spawn(pythonExe, args, {
90
+ stdio: ["ignore", "pipe", "pipe"],
91
+ });
92
+
93
+ let stdout = "";
94
+ let stderr = "";
95
+
96
+ child.stdout.on("data", (chunk) => {
97
+ const text = chunk.toString();
98
+ stdout += text;
99
+ // Stream output unless silent
100
+ process.stdout.write(text);
101
+ });
102
+
103
+ child.stderr.on("data", (chunk) => {
104
+ const text = chunk.toString();
105
+ stderr += text;
106
+ process.stderr.write(text);
107
+ });
108
+
109
+ child.on("error", (err) => {
110
+ if (err.code === "ENOENT") {
111
+ reject(
112
+ new DependencyError(
113
+ `Python executable not found: ${pythonExe}\n` +
114
+ "Install Python 3.8+ and ensure it is in PATH."
115
+ )
116
+ );
117
+ } else {
118
+ reject(new CliError(`Failed to start Atlas builder: ${err.message}`));
119
+ }
120
+ });
121
+
122
+ child.on("close", (code) => {
123
+ if (code !== 0) {
124
+ reject(
125
+ new CliError(
126
+ `Atlas build failed (exit code ${code}).\n` +
127
+ (stderr ? `Builder error output:\n${stderr}` : "See output above for details.")
128
+ )
129
+ );
130
+ return;
131
+ }
132
+
133
+ // Parse result JSON from stdout line
134
+ const resultLine = stdout.split("\n").find((l) => l.startsWith("[atlas:result] "));
135
+ if (resultLine) {
136
+ try {
137
+ const result = JSON.parse(resultLine.replace("[atlas:result] ", ""));
138
+ resolve({
139
+ docCount: result.doc_count || 0,
140
+ nodeCount: result.node_count || 0,
141
+ edgeCount: result.edge_count || 0,
142
+ generated: result.generated || "",
143
+ });
144
+ return;
145
+ } catch (_) {
146
+ // fall through to defaults
147
+ }
148
+ }
149
+
150
+ resolve({ docCount: 0, nodeCount: 0, edgeCount: 0, generated: "" });
151
+ });
152
+ });
153
+ }
154
+
155
+ /**
156
+ * Check whether a port is in use (server is listening).
157
+ *
158
+ * @param {string} host
159
+ * @param {number} port
160
+ * @returns {Promise<boolean>}
161
+ */
162
+ function isPortOpen(host, port) {
163
+ return new Promise((resolve) => {
164
+ const socket = net.createConnection({ host, port, timeout: 500 });
165
+ socket.once("connect", () => {
166
+ socket.destroy();
167
+ resolve(true);
168
+ });
169
+ socket.once("error", () => resolve(false));
170
+ socket.once("timeout", () => {
171
+ socket.destroy();
172
+ resolve(false);
173
+ });
174
+ });
175
+ }
176
+
177
+ /**
178
+ * Wait for the local server to become reachable.
179
+ *
180
+ * @param {string} host
181
+ * @param {number} port
182
+ * @returns {Promise<void>}
183
+ */
184
+ async function waitForServer(host, port) {
185
+ for (let i = 0; i < HEALTH_CHECK_RETRIES; i++) {
186
+ const ok = await isPortOpen(host, port);
187
+ if (ok) return;
188
+ await new Promise((r) => setTimeout(r, HEALTH_CHECK_INTERVAL_MS));
189
+ }
190
+ throw new CliError(
191
+ `Atlas viewer server did not start on http://${host}:${port}\n` +
192
+ "Try passing a different --port if the port is occupied."
193
+ );
194
+ }
195
+
196
+ /**
197
+ * Start a lightweight Node.js static file server for the atlas output dir.
198
+ * Binds to loopback by default. Prevents path traversal outside outputDir/projectPath.
199
+ *
200
+ * @param {string} host
201
+ * @param {number} port
202
+ * @param {string} outputDir - Directory to serve static atlas files from.
203
+ * @param {string} projectPath - Project root for /api/note path traversal bound.
204
+ * @returns {Promise<http.Server>}
205
+ */
206
+ function startAtlasServer(host, port, outputDir, projectPath) {
207
+ return new Promise((resolve, reject) => {
208
+ const MIME_TYPES = {
209
+ ".html": "text/html; charset=utf-8",
210
+ ".js": "application/javascript; charset=utf-8",
211
+ ".json": "application/json; charset=utf-8",
212
+ ".css": "text/css; charset=utf-8",
213
+ ".md": "text/plain; charset=utf-8",
214
+ ".txt": "text/plain; charset=utf-8",
215
+ };
216
+
217
+ const server = http.createServer((req, res) => {
218
+ const url = req.url || "/";
219
+
220
+ // Health check endpoint
221
+ if (url === "/api/health" || url === "/api/health/") {
222
+ res.writeHead(200, { "Content-Type": "application/json" });
223
+ res.end(JSON.stringify({ ok: true }));
224
+ return;
225
+ }
226
+
227
+ // Serve full note content with path traversal protection
228
+ if (url.startsWith("/api/note")) {
229
+ const qs = new URL(url, `http://${host}:${port}`).searchParams;
230
+ const notePath = qs.get("path");
231
+ if (!notePath) {
232
+ res.writeHead(400, { "Content-Type": "application/json" });
233
+ res.end(JSON.stringify({ error: "Missing path parameter" }));
234
+ return;
235
+ }
236
+
237
+ // Path traversal protection: resolve and verify it stays within projectPath
238
+ const projectRoot = projectPath || outputDir;
239
+ const resolved = path.resolve(projectRoot, notePath);
240
+ if (!resolved.startsWith(projectRoot + path.sep) && resolved !== projectRoot) {
241
+ res.writeHead(403, { "Content-Type": "application/json" });
242
+ res.end(JSON.stringify({ error: "Access denied" }));
243
+ return;
244
+ }
245
+
246
+ if (!fs.existsSync(resolved)) {
247
+ res.writeHead(404, { "Content-Type": "application/json" });
248
+ res.end(JSON.stringify({ error: "Not found" }));
249
+ return;
250
+ }
251
+
252
+ try {
253
+ const content = fs.readFileSync(resolved, "utf-8");
254
+ res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
255
+ res.end(content);
256
+ } catch (err) {
257
+ res.writeHead(500, { "Content-Type": "application/json" });
258
+ res.end(JSON.stringify({ error: "Read error" }));
259
+ }
260
+ return;
261
+ }
262
+
263
+ // Static files from outputDir
264
+ let filePath = url.split("?")[0];
265
+ if (filePath === "/" || filePath === "") {
266
+ filePath = "/viewer.html";
267
+ }
268
+
269
+ const resolved = path.resolve(outputDir, filePath.replace(/^\/+/, ""));
270
+ // Path traversal protection: must stay inside outputDir
271
+ if (!resolved.startsWith(outputDir + path.sep) && resolved !== outputDir) {
272
+ res.writeHead(403, { "Content-Type": "text/plain" });
273
+ res.end("403 Forbidden");
274
+ return;
275
+ }
276
+
277
+ if (!fs.existsSync(resolved) || fs.statSync(resolved).isDirectory()) {
278
+ res.writeHead(404, { "Content-Type": "text/plain" });
279
+ res.end("404 Not Found");
280
+ return;
281
+ }
282
+
283
+ const ext = path.extname(resolved).toLowerCase();
284
+ const contentType = MIME_TYPES[ext] || "application/octet-stream";
285
+
286
+ try {
287
+ const data = fs.readFileSync(resolved);
288
+ res.writeHead(200, { "Content-Type": contentType });
289
+ res.end(data);
290
+ } catch (err) {
291
+ res.writeHead(500, { "Content-Type": "text/plain" });
292
+ res.end("500 Internal Server Error");
293
+ }
294
+ });
295
+
296
+ server.once("error", (err) => {
297
+ if (err.code === "EADDRINUSE") {
298
+ reject(
299
+ new CliError(
300
+ `Port ${port} is already in use on ${host}.\n` +
301
+ "Pass --port <number> to use a different port, or stop the process using that port."
302
+ )
303
+ );
304
+ } else {
305
+ reject(new CliError(`Atlas server error: ${err.message}`));
306
+ }
307
+ });
308
+
309
+ server.listen(port, host, () => {
310
+ resolve(server);
311
+ });
312
+ });
313
+ }
314
+
315
+ /**
316
+ * Open or reuse the local Atlas viewer server and optionally launch a browser.
317
+ *
318
+ * @param {Object} config - Resolved AtlasConfig.
319
+ * @param {boolean} noOpen - If true, skip browser launch.
320
+ * @returns {Promise<{ url: string, server: http.Server | null }>}
321
+ */
322
+ async function openViewer(config, noOpen = false) {
323
+ const { host, port, outputDir } = config;
324
+ const viewerUrl = `http://${host}:${port}/viewer.html`;
325
+
326
+ // Check if a server is already running on this port
327
+ const alreadyRunning = await isPortOpen(host, port);
328
+
329
+ let server = null;
330
+ if (!alreadyRunning) {
331
+ console.log(`[atlas] Starting local atlas viewer on http://${host}:${port} ...`);
332
+ server = await startAtlasServer(host, port, outputDir, config.projectPath);
333
+ await waitForServer(host, port);
334
+ console.log(`[atlas] Viewer server ready: ${viewerUrl}`);
335
+ } else {
336
+ console.log(`[atlas] Reusing existing server at http://${host}:${port}`);
337
+ }
338
+
339
+ if (!noOpen) {
340
+ console.log("[atlas] Opening viewer in default browser...");
341
+ await openBrowser(viewerUrl);
342
+ } else {
343
+ console.log(`[atlas] Viewer URL: ${viewerUrl}`);
344
+ console.log("[atlas] --no-open specified; skipping browser launch.");
345
+ }
346
+
347
+ return { url: viewerUrl, server };
348
+ }
349
+
350
+ module.exports = {
351
+ runBuild,
352
+ openViewer,
353
+ startAtlasServer,
354
+ findPython,
355
+ };
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+
3
+ const { execFile } = require("child_process");
4
+
5
+ /**
6
+ * Open a URL in the default system browser.
7
+ * Cross-platform: Windows, macOS, Linux.
8
+ *
9
+ * @param {string} url
10
+ * @returns {Promise<void>}
11
+ */
12
+ function openBrowser(url) {
13
+ return new Promise((resolve) => {
14
+ let cmd;
15
+ let args;
16
+
17
+ if (process.platform === "win32") {
18
+ // On Windows: cmd /c start "" <url>
19
+ cmd = "cmd";
20
+ args = ["/c", "start", "", url];
21
+ } else if (process.platform === "darwin") {
22
+ cmd = "open";
23
+ args = [url];
24
+ } else {
25
+ cmd = "xdg-open";
26
+ args = [url];
27
+ }
28
+
29
+ execFile(cmd, args, { windowsHide: true }, (err) => {
30
+ if (err) {
31
+ // Non-fatal: browser open failure should not crash the CLI
32
+ console.error(`[atlas] Warning: could not open browser: ${err.message}`);
33
+ }
34
+ resolve();
35
+ });
36
+ });
37
+ }
38
+
39
+ module.exports = { openBrowser };
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Frozen SPEC premium capability registry (BK-075).
5
+ * These identifiers are locked now so later premium command families
6
+ * (Atlas Ask, project ingest/refresh/audit) share one canonical namespace.
7
+ *
8
+ * Free SPEC capabilities (spec.core.generate, spec.atlas.build, spec.atlas.open, etc.)
9
+ * are NOT listed here; they are never gated by this helper.
10
+ */
11
+ const SPEC_PREMIUM_CAPABILITIES = Object.freeze([
12
+ "spec.atlas.ask",
13
+ "spec.project.ingest",
14
+ "spec.project.refresh",
15
+ "spec.project.audit",
16
+ ]);
17
+
18
+ /**
19
+ * Integrity/trust failure states that must block premium execution
20
+ * and map to CLI exit code 3 (IntegrityError).
21
+ */
22
+ const INTEGRITY_FAILURE_STATES = new Set([
23
+ "malformed",
24
+ "unsigned",
25
+ "invalid-signature",
26
+ "untrusted-key",
27
+ ]);
28
+
29
+ /**
30
+ * Check whether a required capability is permitted under the current entitlement state.
31
+ *
32
+ * Decision table:
33
+ * integrity failure state ↁEallowed:false, exitCode:3
34
+ * missing / expired ↁEallowed:false, exitCode:1 (user-actionable denial)
35
+ * active or grace, cap present ↁEallowed:true, exitCode:0
36
+ * active or grace, cap absent ↁEallowed:false, exitCode:1
37
+ *
38
+ * @param {string} capability - The required capability identifier.
39
+ * @param {{ state: string, manifest: object|null }} entitlementState
40
+ * @returns {{ allowed: boolean, reason: string|null, exitCode: number }}
41
+ */
42
+ function checkCapability(capability, entitlementState) {
43
+ const { state, manifest } = entitlementState;
44
+
45
+ // Trust/integrity failures block premium execution unconditionally.
46
+ if (INTEGRITY_FAILURE_STATES.has(state)) {
47
+ return {
48
+ allowed: false,
49
+ reason:
50
+ `Entitlement manifest trust failure: ${state}. ` +
51
+ `Run "sdtk-spec entitlement status" for details.`,
52
+ exitCode: 3,
53
+ };
54
+ }
55
+
56
+ // No valid entitlement present.
57
+ if (state === "missing" || state === "expired") {
58
+ return {
59
+ allowed: false,
60
+ reason:
61
+ `No valid entitlement for capability "${capability}". ` +
62
+ `A Pro subscription is required.`,
63
+ exitCode: 1,
64
+ };
65
+ }
66
+
67
+ if (state !== "active" && state !== "grace") {
68
+ return {
69
+ allowed: false,
70
+ reason:
71
+ `Entitlement manifest trust failure: unexpected state "${state}". ` +
72
+ `Run "sdtk-spec entitlement status" for details.`,
73
+ exitCode: 3,
74
+ };
75
+ }
76
+
77
+ // Active or grace: check the capabilities list.
78
+ const caps =
79
+ manifest && Array.isArray(manifest.capabilities)
80
+ ? manifest.capabilities
81
+ : [];
82
+
83
+ if (!caps.includes(capability)) {
84
+ return {
85
+ allowed: false,
86
+ reason: `Capability "${capability}" is not included in your current entitlement.`,
87
+ exitCode: 1,
88
+ };
89
+ }
90
+
91
+ return { allowed: true, reason: null, exitCode: 0 };
92
+ }
93
+
94
+ module.exports = {
95
+ SPEC_PREMIUM_CAPABILITIES,
96
+ checkCapability,
97
+ };
98
+
@@ -0,0 +1,203 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const crypto = require("crypto");
5
+ const { getEntitlementsFile } = require("./suite-state");
6
+
7
+ // Required manifest fields excluding signature (checked separately)
8
+ const REQUIRED_FIELDS = [
9
+ "schema_version",
10
+ "customer_id",
11
+ "plan",
12
+ "products",
13
+ "capabilities",
14
+ "issued_at",
15
+ "expires_at",
16
+ "offline_grace_until",
17
+ ];
18
+
19
+ /**
20
+ * Recursively sort object keys for canonical JSON serialization.
21
+ * Arrays preserve element order. Primitives are returned as-is.
22
+ *
23
+ * @param {*} value
24
+ * @returns {*}
25
+ */
26
+ function canonicalize(value) {
27
+ if (Array.isArray(value)) {
28
+ return value.map(canonicalize);
29
+ }
30
+ if (value !== null && typeof value === "object") {
31
+ const sorted = {};
32
+ for (const key of Object.keys(value).sort()) {
33
+ sorted[key] = canonicalize(value[key]);
34
+ }
35
+ return sorted;
36
+ }
37
+ return value;
38
+ }
39
+
40
+ /**
41
+ * Build the canonical signed payload from a manifest.
42
+ * Removes the `signature` field, recursively sorts object keys,
43
+ * and returns a UTF-8 Buffer suitable for RSA-SHA256 verification.
44
+ *
45
+ * @param {object} manifest
46
+ * @returns {Buffer}
47
+ */
48
+ function buildCanonicalPayload(manifest) {
49
+ // eslint-disable-next-line no-unused-vars
50
+ const { signature: _sig, ...rest } = manifest;
51
+ return Buffer.from(JSON.stringify(canonicalize(rest)), "utf8");
52
+ }
53
+
54
+ /**
55
+ * Evaluate the trust/time state of a parsed manifest object.
56
+ * Performs all validation steps except file I/O.
57
+ * Shared by loadEntitlementState (file-cache path) and the sync module (remote manifest path).
58
+ *
59
+ * Possible states:
60
+ * malformed - structural validation failure or missing required field
61
+ * unsigned - signature field absent or empty
62
+ * untrusted-key - SDTK_ENTITLEMENT_PUBLIC_KEY not set (manifest cannot be verified)
63
+ * invalid-signature - RSA-SHA256 verification failed
64
+ * active - verified, current time < expires_at
65
+ * grace - verified, expires_at <= now < offline_grace_until
66
+ * expired - verified, now >= offline_grace_until
67
+ *
68
+ * @param {*} manifest - Value parsed from JSON (may be any type)
69
+ * @param {number} now - Current epoch ms (injectable for deterministic tests)
70
+ * @returns {{ state: string, manifest: object|null }}
71
+ */
72
+ function evaluateManifestObject(manifest, now) {
73
+ if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) {
74
+ return { state: "malformed", manifest: null };
75
+ }
76
+
77
+ // ---- 1. Required fields (excluding signature) ----
78
+ for (const field of REQUIRED_FIELDS) {
79
+ if (!(field in manifest)) {
80
+ return { state: "malformed", manifest };
81
+ }
82
+ }
83
+
84
+ // ---- 2. Structural field validation ----
85
+ if (typeof manifest.schema_version !== "number") {
86
+ return { state: "malformed", manifest };
87
+ }
88
+ if (typeof manifest.customer_id !== "string" || !manifest.customer_id) {
89
+ return { state: "malformed", manifest };
90
+ }
91
+ if (typeof manifest.plan !== "string" || !manifest.plan) {
92
+ return { state: "malformed", manifest };
93
+ }
94
+ if (
95
+ !manifest.products ||
96
+ typeof manifest.products !== "object" ||
97
+ Array.isArray(manifest.products)
98
+ ) {
99
+ return { state: "malformed", manifest };
100
+ }
101
+ if (!Array.isArray(manifest.capabilities)) {
102
+ return { state: "malformed", manifest };
103
+ }
104
+ if (
105
+ typeof manifest.issued_at !== "string" ||
106
+ typeof manifest.expires_at !== "string" ||
107
+ typeof manifest.offline_grace_until !== "string"
108
+ ) {
109
+ return { state: "malformed", manifest };
110
+ }
111
+
112
+ // ---- 3. Signature field ----
113
+ if (
114
+ !("signature" in manifest) ||
115
+ !manifest.signature ||
116
+ typeof manifest.signature !== "string"
117
+ ) {
118
+ return { state: "unsigned", manifest };
119
+ }
120
+
121
+ // ---- 4. Public verification key ----
122
+ const publicKeyPem = process.env.SDTK_ENTITLEMENT_PUBLIC_KEY;
123
+ if (!publicKeyPem) {
124
+ return { state: "untrusted-key", manifest };
125
+ }
126
+
127
+ // ---- 5. RSA-SHA256 verification ----
128
+ let verified = false;
129
+ try {
130
+ const payload = buildCanonicalPayload(manifest);
131
+ const sigBuffer = Buffer.from(manifest.signature, "base64");
132
+ const verifier = crypto.createVerify("RSA-SHA256");
133
+ verifier.update(payload);
134
+ verified = verifier.verify(publicKeyPem, sigBuffer);
135
+ } catch (_e) {
136
+ return { state: "invalid-signature", manifest };
137
+ }
138
+
139
+ if (!verified) {
140
+ return { state: "invalid-signature", manifest };
141
+ }
142
+
143
+ // ---- 6. Time-based state ----
144
+ const expiresAt = new Date(manifest.expires_at).getTime();
145
+ const graceUntil = new Date(manifest.offline_grace_until).getTime();
146
+
147
+ if (isNaN(expiresAt) || isNaN(graceUntil)) {
148
+ return { state: "malformed", manifest };
149
+ }
150
+
151
+ if (now < expiresAt) {
152
+ return { state: "active", manifest };
153
+ }
154
+ if (now < graceUntil) {
155
+ return { state: "grace", manifest };
156
+ }
157
+ return { state: "expired", manifest };
158
+ }
159
+
160
+ /**
161
+ * Load and evaluate the cached entitlement manifest trust state.
162
+ *
163
+ * Possible states:
164
+ * missing - no cached file exists
165
+ * malformed - JSON parse failure or missing required field
166
+ * unsigned - signature field absent or empty
167
+ * untrusted-key - SDTK_ENTITLEMENT_PUBLIC_KEY not set (manifest cannot be verified)
168
+ * invalid-signature - RSA-SHA256 verification failed
169
+ * active - verified, current time < expires_at
170
+ * grace - verified, expires_at <= now < offline_grace_until
171
+ * expired - verified, now >= offline_grace_until
172
+ *
173
+ * @param {number} [nowMs] - Current epoch ms (injectable for deterministic tests)
174
+ * @returns {{ state: string, manifest: object|null }}
175
+ */
176
+ function loadEntitlementState(nowMs) {
177
+ const filePath = getEntitlementsFile();
178
+ const now = nowMs !== undefined ? nowMs : Date.now();
179
+
180
+ // ---- Missing ----
181
+ if (!fs.existsSync(filePath)) {
182
+ return { state: "missing", manifest: null };
183
+ }
184
+
185
+ // ---- Parse ----
186
+ let manifest;
187
+ try {
188
+ const raw = fs.readFileSync(filePath, "utf8");
189
+ manifest = JSON.parse(raw);
190
+ } catch (_e) {
191
+ return { state: "malformed", manifest: null };
192
+ }
193
+
194
+ return evaluateManifestObject(manifest, now);
195
+ }
196
+
197
+ module.exports = {
198
+ loadEntitlementState,
199
+ evaluateManifestObject,
200
+ buildCanonicalPayload,
201
+ canonicalize,
202
+ };
203
+