sdtk-spec-kit 0.4.4 → 0.4.5

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 (127) hide show
  1. package/README.md +369 -376
  2. package/assets/atlas/build_atlas.py +880 -880
  3. package/assets/atlas/doc_atlas_viewer_template.html +3796 -3782
  4. package/assets/atlas/vendor/mermaid.min.js +2029 -2029
  5. package/assets/keys/spec-entitlement-public.pem +11 -11
  6. package/assets/manifest/toolkit-bundle.manifest.json +178 -178
  7. package/assets/manifest/toolkit-bundle.sha256.txt +83 -83
  8. package/assets/toolkit/toolkit/AGENTS.md +247 -245
  9. package/assets/toolkit/toolkit/README.md +50 -50
  10. package/assets/toolkit/toolkit/SDTK_TOOLKIT.md +207 -208
  11. package/assets/toolkit/toolkit/install.ps1 +21 -21
  12. package/assets/toolkit/toolkit/runtimes/claude/CLAUDE_TEMPLATE.md +92 -92
  13. package/assets/toolkit/toolkit/runtimes/codex/CODEX_TEMPLATE.md +70 -70
  14. package/assets/toolkit/toolkit/scripts/agents/run-claude-task.ps1 +332 -332
  15. package/assets/toolkit/toolkit/scripts/agents/run-codex-task.ps1 +618 -618
  16. package/assets/toolkit/toolkit/scripts/agents/validate-mailbox-formal-artifact.py +86 -86
  17. package/assets/toolkit/toolkit/scripts/init-feature.ps1 +262 -262
  18. package/assets/toolkit/toolkit/scripts/install-codex-skills.ps1 +209 -209
  19. package/assets/toolkit/toolkit/scripts/uninstall-claude-skills.ps1 +139 -139
  20. package/assets/toolkit/toolkit/scripts/uninstall-codex-skills.ps1 +143 -143
  21. package/assets/toolkit/toolkit/sdtk-spec.config.json +27 -27
  22. package/assets/toolkit/toolkit/sdtk-spec.config.profiles.example.json +49 -49
  23. package/assets/toolkit/toolkit/session/SDTK_ACTIVE_BOOTSTRAP.md +47 -47
  24. package/assets/toolkit/toolkit/session/SDTK_AGENT_WORKING_RULES.md +49 -49
  25. package/assets/toolkit/toolkit/skills/sdtk-api-design-spec/SKILL.md +111 -111
  26. package/assets/toolkit/toolkit/skills/sdtk-api-design-spec/scripts/generate_api_design_detail.py +732 -732
  27. package/assets/toolkit/toolkit/skills/sdtk-api-doc/SKILL.md +79 -79
  28. package/assets/toolkit/toolkit/skills/sdtk-arch/SKILL.md +85 -85
  29. package/assets/toolkit/toolkit/skills/sdtk-ba/SKILL.md +46 -46
  30. package/assets/toolkit/toolkit/skills/sdtk-design-layout/SKILL.md +91 -91
  31. package/assets/toolkit/toolkit/skills/sdtk-design-layout/scripts/render_design_layout_images.py +246 -246
  32. package/assets/toolkit/toolkit/skills/sdtk-dev/prompts/code-quality-reviewer.md +34 -34
  33. package/assets/toolkit/toolkit/skills/sdtk-dev/prompts/implementer.md +60 -60
  34. package/assets/toolkit/toolkit/skills/sdtk-dev/prompts/spec-reviewer.md +41 -41
  35. package/assets/toolkit/toolkit/skills/sdtk-dev-backend/SKILL.md +80 -80
  36. package/assets/toolkit/toolkit/skills/sdtk-dev-frontend/SKILL.md +80 -80
  37. package/assets/toolkit/toolkit/skills/sdtk-mailbox-dispatch/SKILL.md +2 -2
  38. package/assets/toolkit/toolkit/skills/sdtk-orchestrator/SKILL.md +17 -17
  39. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/SKILL.md +106 -106
  40. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/references/excel-image-export.md +50 -50
  41. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/references/figma-mcp.md +53 -53
  42. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/references/numbering-rules.md +28 -28
  43. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/scripts/renumber_flow_action_spec_global.py +136 -136
  44. package/assets/toolkit/toolkit/skills/sdtk-screen-design-spec/scripts/validate_flow_action_spec_numbering.py +414 -414
  45. package/assets/toolkit/toolkit/skills/sdtk-test-case-spec/SKILL.md +110 -110
  46. package/assets/toolkit/toolkit/skills/sdtk-test-case-spec/scripts/validate_test_case_spec.py +97 -97
  47. package/assets/toolkit/toolkit/skills/skills.catalog.yaml +330 -330
  48. package/assets/toolkit/toolkit/skills-claude/api-design-spec/SKILL.md +116 -116
  49. package/assets/toolkit/toolkit/skills-claude/api-doc/SKILL.md +87 -87
  50. package/assets/toolkit/toolkit/skills-claude/arch/SKILL.md +59 -59
  51. package/assets/toolkit/toolkit/skills-claude/ba/SKILL.md +67 -67
  52. package/assets/toolkit/toolkit/skills-claude/design-layout/SKILL.md +91 -91
  53. package/assets/toolkit/toolkit/skills-claude/dev-backend/SKILL.md +73 -73
  54. package/assets/toolkit/toolkit/skills-claude/dev-frontend/SKILL.md +73 -73
  55. package/assets/toolkit/toolkit/skills-claude/mailbox-dispatch/SKILL.md +2 -2
  56. package/assets/toolkit/toolkit/skills-claude/orchestrator/SKILL.md +40 -40
  57. package/assets/toolkit/toolkit/skills-claude/pm/SKILL.md +88 -88
  58. package/assets/toolkit/toolkit/skills-claude/qa/SKILL.md +58 -58
  59. package/assets/toolkit/toolkit/skills-claude/screen-design-spec/SKILL.md +112 -112
  60. package/assets/toolkit/toolkit/skills-claude/test-case-spec/SKILL.md +115 -115
  61. package/assets/toolkit/toolkit/templates/README.md +68 -68
  62. package/assets/toolkit/toolkit/templates/docs/api/API_DESIGN_CREATION_RULES.md +21 -21
  63. package/assets/toolkit/toolkit/templates/docs/api/API_DESIGN_DETAIL_TEMPLATE.md +67 -67
  64. package/assets/toolkit/toolkit/templates/docs/api/API_DESIGN_FLOWCHART_CREATION_RULES.md +468 -468
  65. package/assets/toolkit/toolkit/templates/docs/api/API_ENDPOINTS_TEMPLATE.md +228 -228
  66. package/assets/toolkit/toolkit/templates/docs/api/FEATURE_API_TEMPLATE.yaml +20 -20
  67. package/assets/toolkit/toolkit/templates/docs/api/FLOWCHART_CREATION_RULES.md +20 -20
  68. package/assets/toolkit/toolkit/templates/docs/api/YAML_CREATION_RULES.md +128 -128
  69. package/assets/toolkit/toolkit/templates/docs/api/feature_api_flow_list_TEMPLATE.txt +12 -12
  70. package/assets/toolkit/toolkit/templates/docs/architecture/ARCH_DESIGN_TEMPLATE.md +107 -107
  71. package/assets/toolkit/toolkit/templates/docs/design/DESIGN_LAYOUT_TEMPLATE.md +60 -60
  72. package/assets/toolkit/toolkit/templates/docs/dev/OPS_HANDOFF_CREATION_RULES.md +369 -369
  73. package/assets/toolkit/toolkit/templates/docs/discovery/REQUIREMENT_TEMPLATE.md +155 -155
  74. package/assets/toolkit/toolkit/templates/docs/product/BACKLOG_TEMPLATE.md +50 -50
  75. package/assets/toolkit/toolkit/templates/docs/product/CONDENSED_UPSTREAM_INPUT_TEMPLATE.md +276 -276
  76. package/assets/toolkit/toolkit/templates/docs/product/PRD_TEMPLATE.md +66 -66
  77. package/assets/toolkit/toolkit/templates/docs/product/PROJECT_INITIATION_TEMPLATE.md +98 -98
  78. package/assets/toolkit/toolkit/templates/docs/qa/TEST_CASE_CREATION_RULES.md +129 -129
  79. package/assets/toolkit/toolkit/templates/docs/qa/TEST_CASE_TEMPLATE.md +104 -104
  80. package/assets/toolkit/toolkit/templates/docs/specs/BA_SPEC_TEMPLATE.md +139 -139
  81. package/assets/toolkit/toolkit/templates/docs/specs/FLOW_ACTION_SPEC_TEMPLATE.md +197 -197
  82. package/assets/toolkit/toolkit/templates/handoffs/ARCH_TO_DEV.md +31 -31
  83. package/assets/toolkit/toolkit/templates/handoffs/BA_TO_ARCH.md +28 -28
  84. package/assets/toolkit/toolkit/templates/handoffs/DEV_STAGE1_SPEC_REVIEW.md +26 -26
  85. package/assets/toolkit/toolkit/templates/handoffs/DEV_STAGE2_CODE_QUALITY_REVIEW.md +20 -20
  86. package/assets/toolkit/toolkit/templates/handoffs/DEV_TO_QA.md +33 -33
  87. package/assets/toolkit/toolkit/templates/handoffs/PM_TO_BA.md +29 -29
  88. package/assets/toolkit/toolkit/templates/handoffs/QA_RELEASE_DECISION.md +26 -26
  89. package/assets/toolkit/toolkit/templates/mailbox/AGENT_TASK_TEMPLATE.md +76 -76
  90. package/bin/sdtk.js +15 -15
  91. package/package.json +48 -48
  92. package/src/commands/activate.js +90 -90
  93. package/src/commands/analyze.js +11 -0
  94. package/src/commands/atlas.js +341 -352
  95. package/src/commands/auth.js +85 -85
  96. package/src/commands/entitlement.js +163 -163
  97. package/src/commands/generate.js +209 -147
  98. package/src/commands/help.js +41 -33
  99. package/src/commands/init.js +15 -15
  100. package/src/commands/project.js +51 -51
  101. package/src/commands/runtime.js +239 -239
  102. package/src/index.js +9 -6
  103. package/src/lib/activation-state.js +68 -68
  104. package/src/lib/args.js +116 -116
  105. package/src/lib/atlas-config.js +200 -200
  106. package/src/lib/atlas-runner.js +435 -355
  107. package/src/lib/browser-open.js +39 -39
  108. package/src/lib/capabilities.js +92 -92
  109. package/src/lib/entitlements.js +238 -238
  110. package/src/lib/errors.js +41 -41
  111. package/src/lib/github-access.js +143 -143
  112. package/src/lib/legacy-auth-migration.js +55 -55
  113. package/src/lib/license-activation.js +375 -375
  114. package/src/lib/powershell.js +85 -85
  115. package/src/lib/premium-loader.js +126 -126
  116. package/src/lib/premium-packs.js +331 -331
  117. package/src/lib/premium-sync.js +235 -235
  118. package/src/lib/project-audit.js +332 -332
  119. package/src/lib/project-config.js +108 -108
  120. package/src/lib/project-ingest.js +450 -450
  121. package/src/lib/project-refresh.js +666 -666
  122. package/src/lib/requirement-analysis.js +396 -0
  123. package/src/lib/scope.js +83 -83
  124. package/src/lib/state.js +73 -73
  125. package/src/lib/suite-state.js +70 -70
  126. package/src/lib/toolkit-payload.js +99 -99
  127. package/src/lib/atlas-ask.js +0 -170
@@ -1,375 +1,375 @@
1
- "use strict";
2
-
3
- const fs = require("fs");
4
- const os = require("os");
5
- const crypto = require("crypto");
6
- const path = require("path");
7
- const { getEntitlementsFile, ensureDir, hardenFilePermissions } = require("./suite-state");
8
- const { resolvePublicKey, evaluateManifestObject } = require("./entitlements");
9
- const {
10
- validatePackMeta,
11
- writePackToCache,
12
- } = require("./premium-packs");
13
- const {
14
- writeActivationState,
15
- } = require("./activation-state");
16
-
17
- /**
18
- * Generate a deterministic machine_id from local machine facts.
19
- * Bounded to handle Windows and POSIX systems.
20
- *
21
- * @returns {string}
22
- */
23
- function buildMachineId() {
24
- // Use hostname + platform + cpu count for determinism across same machine
25
- const hostname = os.hostname();
26
- const platform = process.platform;
27
- const cpus = os.cpus().length;
28
- const combined = `${hostname}-${platform}-${cpus}`;
29
- return crypto.createHash("sha256").update(combined).digest("hex").substring(0, 16);
30
- }
31
-
32
- /**
33
- * POST an activation request to the backend API.
34
- * @param {object} options
35
- * @param {string} options.activationUrl - Base activation API URL
36
- * @param {string} options.licenseKey - Activation license key
37
- * @param {string} options.machineId - Bound machine identifier
38
- * @returns {Promise<{ success: boolean, response?: object, error?: string }>}
39
- */
40
- async function postActivationRequest({
41
- activationUrl,
42
- licenseKey,
43
- machineId,
44
- }) {
45
- const pkg = require("../../package.json");
46
- const body = {
47
- license_key: licenseKey,
48
- machine_id: machineId,
49
- cli_version: pkg.version,
50
- os: process.platform,
51
- hostname: os.hostname(),
52
- };
53
-
54
- try {
55
- const response = await fetch(activationUrl, {
56
- method: "POST",
57
- headers: { "Content-Type": "application/json" },
58
- body: JSON.stringify(body),
59
- });
60
- const rawText = await response.text();
61
- let data = null;
62
- if (rawText) {
63
- try {
64
- data = JSON.parse(rawText);
65
- } catch (_err) {
66
- data = null;
67
- }
68
- }
69
-
70
- if (!response.ok) {
71
- const deniedReason =
72
- data &&
73
- data.decision === "denied" &&
74
- data.manifest &&
75
- typeof data.manifest.error === "string"
76
- ? data.manifest.error
77
- : null;
78
- return {
79
- success: false,
80
- error:
81
- deniedReason ||
82
- (data && typeof data.error === "string" ? data.error : null) ||
83
- `Activation API returned status ${response.status}`,
84
- };
85
- }
86
-
87
- if (!data || typeof data !== "object") {
88
- return {
89
- success: false,
90
- error: "Activation API returned a non-JSON response",
91
- };
92
- }
93
-
94
- return { success: true, response: data };
95
- } catch (err) {
96
- return { success: false, error: `Network error: ${err.message}` };
97
- }
98
- }
99
-
100
- /**
101
- * Validate the activation response contract.
102
- * @param {object} response
103
- * @returns {{ valid: boolean, reason?: string }}
104
- */
105
- function validateActivationResponse(response) {
106
- if (!response || typeof response !== "object") {
107
- return { valid: false, reason: "Response is not an object" };
108
- }
109
-
110
- if (!response.decision || !["activated", "already_activated", "denied"].includes(response.decision)) {
111
- return { valid: false, reason: "Invalid decision in response" };
112
- }
113
-
114
- if (!response.manifest || typeof response.manifest !== "object") {
115
- return { valid: false, reason: "Response is missing manifest" };
116
- }
117
-
118
- if (response.decision === "denied") {
119
- return { valid: false, reason: response.manifest.error || "Activation was denied by server" };
120
- }
121
-
122
- if (!response.activation || typeof response.activation !== "object") {
123
- return { valid: false, reason: "Response is missing activation metadata" };
124
- }
125
-
126
- if (typeof response.activation.machine_id !== "string") {
127
- return { valid: false, reason: "Response activation.machine_id is invalid" };
128
- }
129
-
130
- return { valid: true };
131
- }
132
-
133
- /**
134
- * Verify the signed manifest payload from the response.
135
- * @param {object} manifest
136
- * @returns {{ verified: boolean, reason?: string }}
137
- */
138
- function verifyManifestSignature(manifest) {
139
- const now = Date.now();
140
- const { state, manifest: verified } = evaluateManifestObject(manifest, now);
141
-
142
- if (state === "missing") {
143
- return { verified: false, reason: "No entitlement manifest available" };
144
- }
145
-
146
- if (state === "malformed") {
147
- return { verified: false, reason: "Manifest is malformed" };
148
- }
149
-
150
- if (state === "unsigned") {
151
- return { verified: false, reason: "Manifest is not signed" };
152
- }
153
-
154
- if (state === "untrusted-key") {
155
- return { verified: false, reason: "Trust root not configured" };
156
- }
157
-
158
- if (state === "invalid-signature") {
159
- return { verified: false, reason: "Manifest signature is invalid (exit code 3)" };
160
- }
161
-
162
- if (state === "expired") {
163
- return { verified: false, reason: "Entitlement has expired" };
164
- }
165
-
166
- // "active" and "grace" are valid states
167
- return { verified: true, manifest: verified };
168
- }
169
-
170
- /**
171
- * Install required premium packs from the manifest.
172
- * @param {object} manifest - Verified manifest
173
- * @param {Array} premiumPacks - Pack metadata from activation response
174
- * @returns {{ success: boolean, errors: string[] }}
175
- */
176
- function installRequiredPacks(manifest, premiumPacks) {
177
- const errors = [];
178
-
179
- if (!Array.isArray(premiumPacks)) {
180
- return { success: true, errors: [] };
181
- }
182
-
183
- // Filter for spec product packs that match capabilities
184
- const manifestCaps = Array.isArray(manifest.capabilities) ? manifest.capabilities : [];
185
- const requiredPacks = premiumPacks.filter((pack) => {
186
- if (!pack || pack.product !== "spec") return false;
187
- if (!Array.isArray(pack.capabilities)) return false;
188
- return pack.capabilities.some((c) => manifestCaps.includes(c));
189
- });
190
-
191
- // Install each required pack
192
- for (const packEntry of requiredPacks) {
193
- const validation = validatePackMeta(packEntry);
194
- if (!validation.valid) {
195
- errors.push(`Pack "${packEntry.id || "unknown"}": ${validation.reason}`);
196
- continue;
197
- }
198
-
199
- // If pack bytes are embedded in the response, cache them immediately
200
- if (packEntry.bytes && typeof packEntry.bytes === "string") {
201
- try {
202
- const packBytes = Buffer.from(packEntry.bytes, "base64");
203
- const writeResult = writePackToCache(packEntry, packBytes);
204
- if (!writeResult.success) {
205
- errors.push(`Pack "${packEntry.id}": ${writeResult.reason}`);
206
- }
207
- } catch (err) {
208
- errors.push(`Pack "${packEntry.id}": Failed to decode bytes: ${err.message}`);
209
- }
210
- }
211
- }
212
-
213
- return { success: errors.length === 0, errors };
214
- }
215
-
216
- /**
217
- * Persist the verified entitlements and activation state locally.
218
- * @param {object} manifest - Verified entitlement manifest
219
- * @param {object} activation - Activation metadata from response
220
- * @returns {{ success: boolean, error?: string }}
221
- */
222
- function persistEntitlementAndActivation(manifest, activation) {
223
- const entitlementsFile = getEntitlementsFile();
224
-
225
- try {
226
- ensureDir(path.dirname(entitlementsFile));
227
-
228
- // Write entitlements manifest
229
- const manifestJson = JSON.stringify(manifest, null, 2);
230
- fs.writeFileSync(entitlementsFile, manifestJson, "utf8");
231
- hardenFilePermissions(entitlementsFile);
232
-
233
- // Write activation metadata (no plain license key)
234
- const activationResult = writeActivationState({
235
- provider: "license",
236
- customer_id: manifest.customer_id,
237
- plan: manifest.plan,
238
- machine_id: activation.machine_id,
239
- decision: activation.decision || "activated",
240
- });
241
-
242
- if (!activationResult.success) {
243
- return { success: false, error: activationResult.error };
244
- }
245
-
246
- return { success: true };
247
- } catch (err) {
248
- return { success: false, error: err.message };
249
- }
250
- }
251
-
252
- /**
253
- * Clean up partial state on activation failure.
254
- * Only removes files if they are clearly from a failed activation attempt.
255
- */
256
- function rollbackPartialState() {
257
- // Conservative: only remove activation.json if it exists
258
- // Leave entitlements.json intact to avoid accidental deletion of valid state
259
- try {
260
- const { getActivationFile } = require("./suite-state");
261
- const activationFile = getActivationFile();
262
- if (fs.existsSync(activationFile)) {
263
- fs.unlinkSync(activationFile);
264
- }
265
- } catch (_e) {
266
- // Ignore cleanup errors
267
- }
268
- }
269
-
270
- /**
271
- * Run the full activation flow.
272
- *
273
- * @param {object} options
274
- * @param {string} options.licenseKey - Activation key from user
275
- * @param {string} [options.activationUrl] - Override API URL (default: https://sdtk.dev/api/activate)
276
- * @returns {Promise<{ success: boolean, decision?: string, message: string, exitCode: number }>}
277
- */
278
- async function activateWithLicense({
279
- licenseKey,
280
- activationUrl = process.env.SDTK_ACTIVATION_URL || "https://sdtk.dev/api/activate",
281
- } = {}) {
282
- const result = {
283
- success: false,
284
- message: "",
285
- exitCode: 1,
286
- };
287
-
288
- // Validation: license key is required
289
- if (!licenseKey || typeof licenseKey !== "string" || !licenseKey.trim()) {
290
- result.message = "License key is required. Usage: sdtk-spec activate --license <KEY>";
291
- result.exitCode = 1;
292
- return result;
293
- }
294
-
295
- // Build machine_id
296
- const machineId = buildMachineId();
297
-
298
- // POST to activation API
299
- const apiResult = await postActivationRequest({
300
- activationUrl,
301
- licenseKey: licenseKey.trim(),
302
- machineId,
303
- });
304
-
305
- if (!apiResult.success) {
306
- result.message = `Activation failed: ${apiResult.error}`;
307
- result.exitCode = 1;
308
- rollbackPartialState();
309
- return result;
310
- }
311
-
312
- // Validate response contract
313
- const validation = validateActivationResponse(apiResult.response);
314
- if (!validation.valid) {
315
- result.message = `Invalid activation response: ${validation.reason}`;
316
- result.exitCode = 1;
317
- rollbackPartialState();
318
- return result;
319
- }
320
-
321
- const { decision, manifest, activation } = apiResult.response;
322
-
323
- // Handle denied decision
324
- if (decision === "denied") {
325
- result.message = manifest.error || "Activation was denied by the server.";
326
- result.exitCode = 1;
327
- rollbackPartialState();
328
- return result;
329
- }
330
-
331
- // Verify manifest signature
332
- const sigResult = verifyManifestSignature(manifest);
333
- if (!sigResult.verified) {
334
- result.message = `Manifest verification failed: ${sigResult.reason}`;
335
- result.exitCode = sigResult.reason && sigResult.reason.includes("exit code 3") ? 3 : 1;
336
- rollbackPartialState();
337
- return result;
338
- }
339
-
340
- // Validate premium packs metadata (install step deferred)
341
- const packErrors = installRequiredPacks(sigResult.manifest, apiResult.response.premium_packs);
342
- if (!packErrors.success) {
343
- result.message = `Pack validation failed: ${packErrors.errors.join("; ")}`;
344
- result.exitCode = 1;
345
- rollbackPartialState();
346
- return result;
347
- }
348
-
349
- // Persist verified state
350
- const persistResult = persistEntitlementAndActivation(sigResult.manifest, activation);
351
- if (!persistResult.success) {
352
- result.message = `Failed to save activation state: ${persistResult.error}`;
353
- result.exitCode = 4;
354
- rollbackPartialState();
355
- return result;
356
- }
357
-
358
- // Success
359
- result.success = true;
360
- result.decision = decision;
361
- result.exitCode = 0;
362
-
363
- if (decision === "already_activated") {
364
- result.message = `Pro already activated on this machine (customer: ${sigResult.manifest.customer_id}, plan: ${sigResult.manifest.plan}).`;
365
- } else {
366
- result.message = `Pro activated successfully! Customer: ${sigResult.manifest.customer_id}, Plan: ${sigResult.manifest.plan}. You can now use premium SDTK commands.`;
367
- }
368
-
369
- return result;
370
- }
371
-
372
- module.exports = {
373
- activateWithLicense,
374
- buildMachineId,
375
- };
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const os = require("os");
5
+ const crypto = require("crypto");
6
+ const path = require("path");
7
+ const { getEntitlementsFile, ensureDir, hardenFilePermissions } = require("./suite-state");
8
+ const { resolvePublicKey, evaluateManifestObject } = require("./entitlements");
9
+ const {
10
+ validatePackMeta,
11
+ writePackToCache,
12
+ } = require("./premium-packs");
13
+ const {
14
+ writeActivationState,
15
+ } = require("./activation-state");
16
+
17
+ /**
18
+ * Generate a deterministic machine_id from local machine facts.
19
+ * Bounded to handle Windows and POSIX systems.
20
+ *
21
+ * @returns {string}
22
+ */
23
+ function buildMachineId() {
24
+ // Use hostname + platform + cpu count for determinism across same machine
25
+ const hostname = os.hostname();
26
+ const platform = process.platform;
27
+ const cpus = os.cpus().length;
28
+ const combined = `${hostname}-${platform}-${cpus}`;
29
+ return crypto.createHash("sha256").update(combined).digest("hex").substring(0, 16);
30
+ }
31
+
32
+ /**
33
+ * POST an activation request to the backend API.
34
+ * @param {object} options
35
+ * @param {string} options.activationUrl - Base activation API URL
36
+ * @param {string} options.licenseKey - Activation license key
37
+ * @param {string} options.machineId - Bound machine identifier
38
+ * @returns {Promise<{ success: boolean, response?: object, error?: string }>}
39
+ */
40
+ async function postActivationRequest({
41
+ activationUrl,
42
+ licenseKey,
43
+ machineId,
44
+ }) {
45
+ const pkg = require("../../package.json");
46
+ const body = {
47
+ license_key: licenseKey,
48
+ machine_id: machineId,
49
+ cli_version: pkg.version,
50
+ os: process.platform,
51
+ hostname: os.hostname(),
52
+ };
53
+
54
+ try {
55
+ const response = await fetch(activationUrl, {
56
+ method: "POST",
57
+ headers: { "Content-Type": "application/json" },
58
+ body: JSON.stringify(body),
59
+ });
60
+ const rawText = await response.text();
61
+ let data = null;
62
+ if (rawText) {
63
+ try {
64
+ data = JSON.parse(rawText);
65
+ } catch (_err) {
66
+ data = null;
67
+ }
68
+ }
69
+
70
+ if (!response.ok) {
71
+ const deniedReason =
72
+ data &&
73
+ data.decision === "denied" &&
74
+ data.manifest &&
75
+ typeof data.manifest.error === "string"
76
+ ? data.manifest.error
77
+ : null;
78
+ return {
79
+ success: false,
80
+ error:
81
+ deniedReason ||
82
+ (data && typeof data.error === "string" ? data.error : null) ||
83
+ `Activation API returned status ${response.status}`,
84
+ };
85
+ }
86
+
87
+ if (!data || typeof data !== "object") {
88
+ return {
89
+ success: false,
90
+ error: "Activation API returned a non-JSON response",
91
+ };
92
+ }
93
+
94
+ return { success: true, response: data };
95
+ } catch (err) {
96
+ return { success: false, error: `Network error: ${err.message}` };
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Validate the activation response contract.
102
+ * @param {object} response
103
+ * @returns {{ valid: boolean, reason?: string }}
104
+ */
105
+ function validateActivationResponse(response) {
106
+ if (!response || typeof response !== "object") {
107
+ return { valid: false, reason: "Response is not an object" };
108
+ }
109
+
110
+ if (!response.decision || !["activated", "already_activated", "denied"].includes(response.decision)) {
111
+ return { valid: false, reason: "Invalid decision in response" };
112
+ }
113
+
114
+ if (!response.manifest || typeof response.manifest !== "object") {
115
+ return { valid: false, reason: "Response is missing manifest" };
116
+ }
117
+
118
+ if (response.decision === "denied") {
119
+ return { valid: false, reason: response.manifest.error || "Activation was denied by server" };
120
+ }
121
+
122
+ if (!response.activation || typeof response.activation !== "object") {
123
+ return { valid: false, reason: "Response is missing activation metadata" };
124
+ }
125
+
126
+ if (typeof response.activation.machine_id !== "string") {
127
+ return { valid: false, reason: "Response activation.machine_id is invalid" };
128
+ }
129
+
130
+ return { valid: true };
131
+ }
132
+
133
+ /**
134
+ * Verify the signed manifest payload from the response.
135
+ * @param {object} manifest
136
+ * @returns {{ verified: boolean, reason?: string }}
137
+ */
138
+ function verifyManifestSignature(manifest) {
139
+ const now = Date.now();
140
+ const { state, manifest: verified } = evaluateManifestObject(manifest, now);
141
+
142
+ if (state === "missing") {
143
+ return { verified: false, reason: "No entitlement manifest available" };
144
+ }
145
+
146
+ if (state === "malformed") {
147
+ return { verified: false, reason: "Manifest is malformed" };
148
+ }
149
+
150
+ if (state === "unsigned") {
151
+ return { verified: false, reason: "Manifest is not signed" };
152
+ }
153
+
154
+ if (state === "untrusted-key") {
155
+ return { verified: false, reason: "Trust root not configured" };
156
+ }
157
+
158
+ if (state === "invalid-signature") {
159
+ return { verified: false, reason: "Manifest signature is invalid (exit code 3)" };
160
+ }
161
+
162
+ if (state === "expired") {
163
+ return { verified: false, reason: "Entitlement has expired" };
164
+ }
165
+
166
+ // "active" and "grace" are valid states
167
+ return { verified: true, manifest: verified };
168
+ }
169
+
170
+ /**
171
+ * Install required premium packs from the manifest.
172
+ * @param {object} manifest - Verified manifest
173
+ * @param {Array} premiumPacks - Pack metadata from activation response
174
+ * @returns {{ success: boolean, errors: string[] }}
175
+ */
176
+ function installRequiredPacks(manifest, premiumPacks) {
177
+ const errors = [];
178
+
179
+ if (!Array.isArray(premiumPacks)) {
180
+ return { success: true, errors: [] };
181
+ }
182
+
183
+ // Filter for spec product packs that match capabilities
184
+ const manifestCaps = Array.isArray(manifest.capabilities) ? manifest.capabilities : [];
185
+ const requiredPacks = premiumPacks.filter((pack) => {
186
+ if (!pack || pack.product !== "spec") return false;
187
+ if (!Array.isArray(pack.capabilities)) return false;
188
+ return pack.capabilities.some((c) => manifestCaps.includes(c));
189
+ });
190
+
191
+ // Install each required pack
192
+ for (const packEntry of requiredPacks) {
193
+ const validation = validatePackMeta(packEntry);
194
+ if (!validation.valid) {
195
+ errors.push(`Pack "${packEntry.id || "unknown"}": ${validation.reason}`);
196
+ continue;
197
+ }
198
+
199
+ // If pack bytes are embedded in the response, cache them immediately
200
+ if (packEntry.bytes && typeof packEntry.bytes === "string") {
201
+ try {
202
+ const packBytes = Buffer.from(packEntry.bytes, "base64");
203
+ const writeResult = writePackToCache(packEntry, packBytes);
204
+ if (!writeResult.success) {
205
+ errors.push(`Pack "${packEntry.id}": ${writeResult.reason}`);
206
+ }
207
+ } catch (err) {
208
+ errors.push(`Pack "${packEntry.id}": Failed to decode bytes: ${err.message}`);
209
+ }
210
+ }
211
+ }
212
+
213
+ return { success: errors.length === 0, errors };
214
+ }
215
+
216
+ /**
217
+ * Persist the verified entitlements and activation state locally.
218
+ * @param {object} manifest - Verified entitlement manifest
219
+ * @param {object} activation - Activation metadata from response
220
+ * @returns {{ success: boolean, error?: string }}
221
+ */
222
+ function persistEntitlementAndActivation(manifest, activation) {
223
+ const entitlementsFile = getEntitlementsFile();
224
+
225
+ try {
226
+ ensureDir(path.dirname(entitlementsFile));
227
+
228
+ // Write entitlements manifest
229
+ const manifestJson = JSON.stringify(manifest, null, 2);
230
+ fs.writeFileSync(entitlementsFile, manifestJson, "utf8");
231
+ hardenFilePermissions(entitlementsFile);
232
+
233
+ // Write activation metadata (no plain license key)
234
+ const activationResult = writeActivationState({
235
+ provider: "license",
236
+ customer_id: manifest.customer_id,
237
+ plan: manifest.plan,
238
+ machine_id: activation.machine_id,
239
+ decision: activation.decision || "activated",
240
+ });
241
+
242
+ if (!activationResult.success) {
243
+ return { success: false, error: activationResult.error };
244
+ }
245
+
246
+ return { success: true };
247
+ } catch (err) {
248
+ return { success: false, error: err.message };
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Clean up partial state on activation failure.
254
+ * Only removes files if they are clearly from a failed activation attempt.
255
+ */
256
+ function rollbackPartialState() {
257
+ // Conservative: only remove activation.json if it exists
258
+ // Leave entitlements.json intact to avoid accidental deletion of valid state
259
+ try {
260
+ const { getActivationFile } = require("./suite-state");
261
+ const activationFile = getActivationFile();
262
+ if (fs.existsSync(activationFile)) {
263
+ fs.unlinkSync(activationFile);
264
+ }
265
+ } catch (_e) {
266
+ // Ignore cleanup errors
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Run the full activation flow.
272
+ *
273
+ * @param {object} options
274
+ * @param {string} options.licenseKey - Activation key from user
275
+ * @param {string} [options.activationUrl] - Override API URL (default: https://sdtk.dev/api/activate)
276
+ * @returns {Promise<{ success: boolean, decision?: string, message: string, exitCode: number }>}
277
+ */
278
+ async function activateWithLicense({
279
+ licenseKey,
280
+ activationUrl = process.env.SDTK_ACTIVATION_URL || "https://sdtk.dev/api/activate",
281
+ } = {}) {
282
+ const result = {
283
+ success: false,
284
+ message: "",
285
+ exitCode: 1,
286
+ };
287
+
288
+ // Validation: license key is required
289
+ if (!licenseKey || typeof licenseKey !== "string" || !licenseKey.trim()) {
290
+ result.message = "License key is required. Usage: sdtk-spec activate --license <KEY>";
291
+ result.exitCode = 1;
292
+ return result;
293
+ }
294
+
295
+ // Build machine_id
296
+ const machineId = buildMachineId();
297
+
298
+ // POST to activation API
299
+ const apiResult = await postActivationRequest({
300
+ activationUrl,
301
+ licenseKey: licenseKey.trim(),
302
+ machineId,
303
+ });
304
+
305
+ if (!apiResult.success) {
306
+ result.message = `Activation failed: ${apiResult.error}`;
307
+ result.exitCode = 1;
308
+ rollbackPartialState();
309
+ return result;
310
+ }
311
+
312
+ // Validate response contract
313
+ const validation = validateActivationResponse(apiResult.response);
314
+ if (!validation.valid) {
315
+ result.message = `Invalid activation response: ${validation.reason}`;
316
+ result.exitCode = 1;
317
+ rollbackPartialState();
318
+ return result;
319
+ }
320
+
321
+ const { decision, manifest, activation } = apiResult.response;
322
+
323
+ // Handle denied decision
324
+ if (decision === "denied") {
325
+ result.message = manifest.error || "Activation was denied by the server.";
326
+ result.exitCode = 1;
327
+ rollbackPartialState();
328
+ return result;
329
+ }
330
+
331
+ // Verify manifest signature
332
+ const sigResult = verifyManifestSignature(manifest);
333
+ if (!sigResult.verified) {
334
+ result.message = `Manifest verification failed: ${sigResult.reason}`;
335
+ result.exitCode = sigResult.reason && sigResult.reason.includes("exit code 3") ? 3 : 1;
336
+ rollbackPartialState();
337
+ return result;
338
+ }
339
+
340
+ // Validate premium packs metadata (install step deferred)
341
+ const packErrors = installRequiredPacks(sigResult.manifest, apiResult.response.premium_packs);
342
+ if (!packErrors.success) {
343
+ result.message = `Pack validation failed: ${packErrors.errors.join("; ")}`;
344
+ result.exitCode = 1;
345
+ rollbackPartialState();
346
+ return result;
347
+ }
348
+
349
+ // Persist verified state
350
+ const persistResult = persistEntitlementAndActivation(sigResult.manifest, activation);
351
+ if (!persistResult.success) {
352
+ result.message = `Failed to save activation state: ${persistResult.error}`;
353
+ result.exitCode = 4;
354
+ rollbackPartialState();
355
+ return result;
356
+ }
357
+
358
+ // Success
359
+ result.success = true;
360
+ result.decision = decision;
361
+ result.exitCode = 0;
362
+
363
+ if (decision === "already_activated") {
364
+ result.message = `Pro already activated on this machine (customer: ${sigResult.manifest.customer_id}, plan: ${sigResult.manifest.plan}).`;
365
+ } else {
366
+ result.message = `Pro activated successfully! Customer: ${sigResult.manifest.customer_id}, Plan: ${sigResult.manifest.plan}. You can now use premium SDTK commands.`;
367
+ }
368
+
369
+ return result;
370
+ }
371
+
372
+ module.exports = {
373
+ activateWithLicense,
374
+ buildMachineId,
375
+ };