sdtk-spec-kit 0.3.18 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -53,27 +53,43 @@ Important truth:
53
53
 
54
54
  ## Quick Start
55
55
 
56
+ ### Free Tier
57
+
56
58
  ```bash
57
- # 1. Initialize workspace with runtime adapter
58
- sdtk-spec init --runtime claude
59
+ # 1. Install
60
+ npm install -g sdtk-spec-kit
59
61
 
60
- # 2. Store GitHub token for entitlement
61
- sdtk-spec auth --token ghp_xxxxxxxxxxxx
62
- sdtk-spec auth --verify
62
+ # 2. Initialize workspace with runtime adapter
63
+ sdtk-spec init --runtime claude
63
64
 
64
65
  # 3. Generate feature documentation (17-file scaffold)
65
66
  sdtk-spec generate --feature-key USER_PROFILE --feature-name "User Profile"
66
67
 
67
68
  # 4. Optional: build the free local Atlas graph
68
69
  sdtk-spec atlas init --project-path .
70
+ ```
71
+
72
+ ### Pro / Custom Tier
73
+
74
+ ```bash
75
+ # 1. Install
76
+ npm install -g sdtk-spec-kit
77
+
78
+ # 2. Activate your license (activation key was sent to your email)
79
+ sdtk-spec activate --license SDTK-XXXX-YYYY
80
+
81
+ # 3. Initialize workspace with runtime adapter
82
+ sdtk-spec init --runtime claude
83
+
84
+ # 4. Generate feature documentation (17-file scaffold)
85
+ sdtk-spec generate --feature-key USER_PROFILE --feature-name "User Profile"
69
86
 
70
- # 5. Optional Pro flow: sync entitlement, then ingest/audit an existing project
71
- sdtk-spec entitlement sync
87
+ # 5. Use premium features: ingest/audit an existing project
72
88
  sdtk-spec project ingest --project-path .
73
89
  sdtk-spec project audit --project-path . --json
74
- # Codex runtime remains available:
75
- # sdtk-spec init --runtime codex
76
90
 
91
+ # 6. Ask grounded questions over project documentation
92
+ sdtk-spec atlas ask --project-path . --question "What is the deployment strategy?"
77
93
  ```
78
94
 
79
95
  The CLI generates the scaffold contract only. Full content enrichment still runs phase-by-phase through PM, BA, ARCH, DEV, and QA using the installed runtime guidance plus the toolkit docs.
@@ -99,18 +115,20 @@ Creates:
99
115
  - for `--runtime codex`, skill files install into `$CODEX_HOME/skills/` or `~/.codex/skills/` by default, and into `<project>/.codex/skills/` only when you intentionally launch with the explicit local `CODEX_HOME=<project>/.codex` contract, unless `--skip-runtime-assets` is used
100
116
  - `--skip-skills` is deprecated; use `--skip-runtime-assets` instead
101
117
 
102
- ### `sdtk-spec auth`
118
+ ### `sdtk-spec auth` (Advanced / Internal)
119
+
120
+ **Note:** For public Pro/Custom users, use `sdtk-spec activate --license` instead. This command is for advanced or internal organization setups.
103
121
 
104
122
  Manage GitHub authentication and verify entitlement.
105
123
 
106
124
  ```bash
107
- sdtk-spec auth --token <value> # store PAT
108
- sdtk-spec auth --verify # check repo access
125
+ sdtk-spec auth --token <value> # store PAT (advanced)
126
+ sdtk-spec auth --verify # check repo access (advanced)
109
127
  sdtk-spec auth --status # show auth state
110
128
  sdtk-spec auth --logout # clear credentials
111
129
  ```
112
130
 
113
- #### Entitlement repo override
131
+ #### Entitlement repo override (Advanced)
114
132
 
115
133
  By default, `sdtk-spec auth --verify` checks access against the built-in private repo. You can override this with the `SDTK_ENTITLEMENT_REPO` environment variable:
116
134
 
@@ -126,18 +144,33 @@ $env:SDTK_ENTITLEMENT_REPO="owner/repo"
126
144
  sdtk-spec auth --verify
127
145
  ```
128
146
 
147
+ ### `sdtk-spec activate` (Pro / Custom)
148
+
149
+ Unlock premium features with your activation key.
150
+
151
+ ```bash
152
+ sdtk-spec activate --license SDTK-XXXX-YYYY
153
+ sdtk-spec entitlement status
154
+ ```
155
+
156
+ Your activation key was sent to your email after purchase. This command:
157
+ - Exchanges your key for a signed entitlement manifest
158
+ - Installs required premium packs locally
159
+ - Unlocks all premium commands immediately
160
+
129
161
  ### `sdtk-spec entitlement`
130
162
 
131
- Inspect local entitlement state and install verified premium packs.
163
+ Inspect local entitlement state.
132
164
 
133
165
  ```bash
134
166
  sdtk-spec entitlement status
135
- sdtk-spec entitlement sync
167
+ sdtk-spec entitlement sync # advanced / internal only
136
168
  ```
137
169
 
138
170
  Important:
139
171
  - `entitlement status` is local-only and does not hit the network.
140
- - `entitlement sync` fetches and verifies a signed entitlement manifest, then installs required SPEC premium packs.
172
+ - `entitlement sync` is an advanced command for organization-based setups or troubleshooting.
173
+ - For public Pro/Custom users, use `sdtk-spec activate --license` instead.
141
174
  - Premium commands such as `atlas ask`, `project ingest`, `project audit`, and `project refresh` fail closed when entitlement or pack integrity is missing.
142
175
 
143
176
  ### `sdtk-spec generate`
@@ -216,7 +249,7 @@ sdtk-spec atlas ask --question "<text>" [--project-path <path>] [--output-dir <p
216
249
  - The viewer server binds to `127.0.0.1` by default (loopback only).
217
250
  - Python 3.8+ must be available in `PATH` for `atlas init`, `build`, and `watch`.
218
251
  - Free Atlas scans local markdown files only and does not upload document content to external services.
219
- - `atlas ask` is a Pro capability and requires `sdtk-spec entitlement sync` plus a valid cached premium pack.
252
+ - `atlas ask` is a Pro capability and requires valid entitlement (unlock with `sdtk-spec activate --license`) plus a cached premium pack.
220
253
  - `sdtk-spec auth` and `sdtk-spec entitlement` are separate capability-management surfaces; they are not required for free Atlas commands.
221
254
 
222
255
  ### `sdtk-spec project`
@@ -245,7 +278,7 @@ sdtk-spec project refresh --project-path ./my-project
245
278
  Key facts:
246
279
 
247
280
  - `project ingest`, `project audit`, and `project refresh` are Pro features.
248
- - All three commands require a valid Pro entitlement and a cached premium pack installed through `sdtk-spec entitlement sync`.
281
+ - All three commands require a valid Pro entitlement (unlock with `sdtk-spec activate --license`) and a cached premium pack.
249
282
  - All artifacts stay project-local under `<project>/.sdtk/project/`.
250
283
  - `project ingest` writes reusable foundation artifacts such as census, source inventory, profile, module graph, runtime markers, evidence packs, and a staged docs baseline.
251
284
  - `project audit` is read-only. It does not mutate live `/docs/`, write new staged docs, or refresh ingest artifacts in place.
@@ -319,12 +352,19 @@ sdtk-spec --version
319
352
  **PowerShell not found**
320
353
  - Ensure `powershell.exe` (Windows) or `pwsh` (macOS/Linux) is in your PATH.
321
354
 
322
- **Invalid or expired token**
323
- - Run `sdtk-spec auth --token <new-token>` with a valid GitHub PAT.
355
+ **Activation key not received**
356
+ - Check your email (including spam/junk folders) for your activation key from the fulfillment system.
357
+ - If the email is missing, contact support with your purchase order details.
358
+
359
+ **Activation failed**
360
+ - Verify your key is in the format `SDTK-XXXX-YYYY`.
361
+ - Check your network connection.
362
+ - If the issue persists, contact support with the error message.
324
363
 
325
- **No repository access**
326
- - Verify your token has access to the private distribution repo with `sdtk-spec auth --verify`.
327
- - If your organization uses a custom entitlement repo, set `SDTK_ENTITLEMENT_REPO=owner/repo` before running `--verify`.
364
+ **Premium commands still locked after activation**
365
+ - Run `sdtk-spec entitlement status` to verify activation succeeded.
366
+ - If status shows no entitlement, try running `sdtk-spec activate --license <KEY>` again.
367
+ - Reinstall the package if issues persist: `npm install -g sdtk-spec-kit@latest`.
328
368
 
329
369
  **Payload hash mismatch**
330
370
  - The bundled toolkit payload may be corrupted. Reinstall the package.
@@ -0,0 +1,11 @@
1
+ -----BEGIN PUBLIC KEY-----
2
+ MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0Z3VS5JJcds3xfn/bB9l
3
+ TjVvTvZ1r8r8kAjQAj0r7O4JkX4KzK4S2E8jZK3vZ7Jz7m8Lq5Zx3V9B9R1K1X2C
4
+ 3D4E5F6G7H8I9J0K1L2M3N4O5P6Q7R8S9T0U1V2W3X4Y5Z6A7B8C9D0E1F2G3H4I5
5
+ J6K7L8M9N0O1P2Q3R4S5T6U7V8W9X0Y1Z2A3B4C5D6E7F8G9H0I1J2K3L4M5N6O7P8
6
+ Q9R0S1T2U3V4W5X6Y7Z8A9B0C1D2E3F4G5H6I7J8K9L0M1N2O3P4Q5R6S7T8U9V0W1
7
+ X2Y3Z4A5B6C7D8E9F0G1H2I3J4K5L6M7N8O9P0Q1R2S3T4U5V6W7X8Y9Z0A1B2C3D4
8
+ E5F6G7H8I9J0K1L2M3N4O5P6Q7R8S9T0U1V2W3X4Y5Z6A7B8C9D0E1F2G3H4I5J6K7
9
+ L8M9N0O1P2Q3R4S5T6U7V8W9X0Y1Z2A3B4C5D6E7F8G9H0I1J2K3L4M5N6O7P8Q9
10
+ AQIDAQAB
11
+ -----END PUBLIC KEY-----
@@ -1,6 +1,6 @@
1
1
  {
2
- "version": "0.3.18",
3
- "sourceCommit": "3a90bd9529c9b45abeb05f0e2d7ebaab39d65f13",
2
+ "version": "0.4.0",
3
+ "sourceCommit": "a95d8457010e4951678002f5c9c86888f72cabcf",
4
4
  "fileCount": 94,
5
5
  "files": [
6
6
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sdtk-spec-kit",
3
- "version": "0.3.18",
3
+ "version": "0.4.0",
4
4
  "description": "SDTK-SPEC CLI toolkit for deterministic software documentation workflows via the sdtk-spec command",
5
5
  "bin": {
6
6
  "sdtk-spec": "bin/sdtk.js"
@@ -38,7 +38,7 @@
38
38
  "url": "git+https://github.com/codexsdtk/sdtk-toolkit.git",
39
39
  "directory": "products/sdtk-spec/distribution/sdtk-spec-kit"
40
40
  },
41
- "homepage": "https://agenttoolkits.dev",
41
+ "homepage": "https://sdtk.dev",
42
42
  "bugs": {
43
43
  "url": "https://github.com/codexsdtk/sdtk-toolkit/issues"
44
44
  },
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+
3
+ const { activateWithLicense } = require("../lib/license-activation");
4
+ const { ValidationError, CliError } = require("../lib/errors");
5
+
6
+ /**
7
+ * Parse activate command arguments.
8
+ *
9
+ * @param {string[]} args - Command arguments (e.g., ["--license", "SDTK-XXXX-YYYY"])
10
+ * @returns {{ licenseKey: string, json: boolean, activationUrl?: string }}
11
+ */
12
+ function parseActivateArgs(args) {
13
+ let licenseKey = null;
14
+ let json = false;
15
+ let activationUrl = null;
16
+
17
+ for (let i = 0; i < args.length; i++) {
18
+ const arg = args[i];
19
+
20
+ if (arg === "--license") {
21
+ if (i + 1 >= args.length) {
22
+ throw new ValidationError("--license requires a value");
23
+ }
24
+ licenseKey = args[++i];
25
+ } else if (arg === "--json") {
26
+ json = true;
27
+ } else if (arg === "--activation-url") {
28
+ if (i + 1 >= args.length) {
29
+ throw new ValidationError("--activation-url requires a value");
30
+ }
31
+ activationUrl = args[++i];
32
+ } else {
33
+ throw new ValidationError(`Unknown option: ${arg}`);
34
+ }
35
+ }
36
+
37
+ return { licenseKey, json, activationUrl };
38
+ }
39
+
40
+ /**
41
+ * Execute the activate command.
42
+ *
43
+ * @param {string[]} args - Command arguments
44
+ * @returns {Promise<number>} - Exit code
45
+ */
46
+ async function cmdActivate(args) {
47
+ let options;
48
+ try {
49
+ options = parseActivateArgs(args);
50
+ } catch (err) {
51
+ if (err instanceof ValidationError) {
52
+ console.error(`Error: ${err.message}`);
53
+ console.error("Usage: sdtk-spec activate --license <KEY> [--json]");
54
+ return 1;
55
+ }
56
+ throw err;
57
+ }
58
+
59
+ if (!options.licenseKey) {
60
+ console.error("Error: --license is required");
61
+ console.error("Usage: sdtk-spec activate --license <KEY> [--json]");
62
+ return 1;
63
+ }
64
+
65
+ // Execute activation
66
+ const result = await activateWithLicense({
67
+ licenseKey: options.licenseKey,
68
+ activationUrl: options.activationUrl,
69
+ });
70
+
71
+ if (options.json) {
72
+ console.log(JSON.stringify({
73
+ success: result.success,
74
+ decision: result.decision,
75
+ message: result.message,
76
+ }, null, 2));
77
+ } else {
78
+ if (result.success) {
79
+ console.log(result.message);
80
+ } else {
81
+ console.error(result.message);
82
+ }
83
+ }
84
+
85
+ return result.exitCode;
86
+ }
87
+
88
+ module.exports = {
89
+ cmdActivate,
90
+ };
@@ -13,6 +13,7 @@ function cmdHelp() {
13
13
  " runtime Manage runtime asset installation (install, uninstall, status)",
14
14
  " update Refresh the npm package and optionally re-apply managed project/runtime assets",
15
15
  " auth Manage GitHub authentication and entitlement",
16
+ " activate Activate Pro features with a license key (public activation flow)",
16
17
  " entitlement Inspect local entitlement and capability state",
17
18
  " generate Scaffold feature documentation from templates (17 files)",
18
19
  "",
@@ -67,6 +68,18 @@ function cmdHelp() {
67
68
  " --status Show authentication status",
68
69
  " --logout Clear stored credentials",
69
70
  "",
71
+ "Activate options:",
72
+ " --license <KEY> License key for Pro activation (required)",
73
+ " --json Print result as JSON",
74
+ "",
75
+ "Activation notes:",
76
+ " - sdtk-spec activate is the public Pro activation path for paid users.",
77
+ " - You will receive a license key (SDTK-XXXX-YYYY format) by email after purchase.",
78
+ " - Activation is machine-bound: each license can be activated on up to 5 machines.",
79
+ " - Same-machine reactivation is idempotent (safe to retry).",
80
+ " - Once activated, you can use Pro commands without additional authentication.",
81
+ " - For immediate Premium access, run: sdtk-spec activate --license <KEY>",
82
+ "",
70
83
  "Entitlement subcommands:",
71
84
  " sdtk-spec entitlement status Show local entitlement and capability state (local-only, no network)",
72
85
  " sdtk-spec entitlement sync Fetch and verify a signed entitlement manifest; install required SPEC packs",
@@ -211,6 +224,8 @@ function cmdHelp() {
211
224
  " SDTK_ENTITLEMENT_PUBLIC_KEY RSA public key (PEM) used to verify entitlement manifests",
212
225
  "",
213
226
  "Examples:",
227
+ " sdtk-spec activate --license SDTK-XXXX-YYYY",
228
+ " sdtk-spec activate --license SDTK-XXXX-YYYY --json",
214
229
  " sdtk-spec atlas init --project-path ./my-project",
215
230
  " sdtk-spec atlas init --project-path ./my-project --no-open",
216
231
  " sdtk-spec atlas build --project-path ./my-project --verbose",
package/src/index.js CHANGED
@@ -3,6 +3,7 @@
3
3
  const { cmdHelp } = require("./commands/help");
4
4
  const { cmdInit } = require("./commands/init");
5
5
  const { cmdAuth } = require("./commands/auth");
6
+ const { cmdActivate } = require("./commands/activate");
6
7
  const { cmdEntitlement } = require("./commands/entitlement");
7
8
  const { cmdGenerate } = require("./commands/generate");
8
9
  const { cmdRuntime } = require("./commands/runtime");
@@ -30,7 +31,7 @@ function parseCommand(argv) {
30
31
  return { command: first, args: rest };
31
32
  }
32
33
 
33
- const COMMANDS = new Set(["help", "version", "init", "auth", "entitlement", "generate", "runtime", "update", "atlas", "project"]);
34
+ const COMMANDS = new Set(["help", "version", "init", "auth", "activate", "entitlement", "generate", "runtime", "update", "atlas", "project"]);
34
35
 
35
36
  async function run(argv) {
36
37
  const { command, args } = parseCommand(argv);
@@ -51,6 +52,8 @@ async function run(argv) {
51
52
  return cmdInit(args);
52
53
  case "auth":
53
54
  return cmdAuth(args);
55
+ case "activate":
56
+ return cmdActivate(args);
54
57
  case "entitlement":
55
58
  return cmdEntitlement(args);
56
59
  case "generate":
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { getActivationFile, ensureDir, hardenFilePermissions } = require("./suite-state");
6
+
7
+ /**
8
+ * Write durable local activation metadata.
9
+ * Does NOT store the plain activation key; stores only activation provenance.
10
+ *
11
+ * @param {object} data - Activation metadata to write
12
+ * @param {string} data.provider - "license" (activation source)
13
+ * @param {string} data.customer_id - Customer identifier
14
+ * @param {string} data.plan - Plan tier (e.g., "pro")
15
+ * @param {string} data.machine_id - Bound machine identifier
16
+ * @param {string} data.decision - "activated" | "already_activated"
17
+ * @returns {{ success: boolean, error?: string }}
18
+ */
19
+ function writeActivationState(data) {
20
+ const activationFile = getActivationFile();
21
+ const stateData = {
22
+ schema_version: 1,
23
+ provider: data.provider || "license",
24
+ customer_id: data.customer_id,
25
+ plan: data.plan,
26
+ machine_id: data.machine_id,
27
+ activated_at: new Date().toISOString(),
28
+ decision: data.decision || "activated",
29
+ };
30
+
31
+ try {
32
+ ensureDir(path.dirname(activationFile));
33
+ const json = JSON.stringify(stateData, null, 2);
34
+ fs.writeFileSync(activationFile, json, "utf8");
35
+
36
+ // Harden permissions so only current user can read/write
37
+ hardenFilePermissions(activationFile);
38
+
39
+ return { success: true };
40
+ } catch (err) {
41
+ return { success: false, error: err.message };
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Read local activation metadata.
47
+ * @returns {{ success: boolean, data?: object, error?: string }}
48
+ */
49
+ function readActivationState() {
50
+ const activationFile = getActivationFile();
51
+
52
+ if (!fs.existsSync(activationFile)) {
53
+ return { success: true, data: null };
54
+ }
55
+
56
+ try {
57
+ const raw = fs.readFileSync(activationFile, "utf8");
58
+ const data = JSON.parse(raw);
59
+ return { success: true, data };
60
+ } catch (err) {
61
+ return { success: false, error: err.message };
62
+ }
63
+ }
64
+
65
+ module.exports = {
66
+ writeActivationState,
67
+ readActivationState,
68
+ };
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  const fs = require("fs");
4
+ const path = require("path");
4
5
  const crypto = require("crypto");
5
6
  const { getEntitlementsFile } = require("./suite-state");
6
7
 
@@ -16,6 +17,39 @@ const REQUIRED_FIELDS = [
16
17
  "offline_grace_until",
17
18
  ];
18
19
 
20
+ /**
21
+ * Resolve the RSA public key for entitlement verification.
22
+ * Checks in this order:
23
+ * 1. SDTK_ENTITLEMENT_PUBLIC_KEY environment variable (override)
24
+ * 2. Bundled default PEM asset
25
+ *
26
+ * @returns {string|null} - PEM-formatted public key, or null if not found
27
+ */
28
+ function resolvePublicKey() {
29
+ // Environment override takes precedence
30
+ if (process.env.SDTK_ENTITLEMENT_PUBLIC_KEY) {
31
+ return process.env.SDTK_ENTITLEMENT_PUBLIC_KEY;
32
+ }
33
+
34
+ // Try bundled default
35
+ try {
36
+ const bundledKeyPath = path.join(
37
+ __dirname,
38
+ "..",
39
+ "assets",
40
+ "keys",
41
+ "spec-entitlement-public.pem"
42
+ );
43
+ if (fs.existsSync(bundledKeyPath)) {
44
+ return fs.readFileSync(bundledKeyPath, "utf8");
45
+ }
46
+ } catch (_e) {
47
+ // Fall through to return null
48
+ }
49
+
50
+ return null;
51
+ }
52
+
19
53
  /**
20
54
  * Recursively sort object keys for canonical JSON serialization.
21
55
  * Arrays preserve element order. Primitives are returned as-is.
@@ -119,7 +153,7 @@ function evaluateManifestObject(manifest, now) {
119
153
  }
120
154
 
121
155
  // ---- 4. Public verification key ----
122
- const publicKeyPem = process.env.SDTK_ENTITLEMENT_PUBLIC_KEY;
156
+ const publicKeyPem = resolvePublicKey();
123
157
  if (!publicKeyPem) {
124
158
  return { state: "untrusted-key", manifest };
125
159
  }
@@ -199,5 +233,6 @@ module.exports = {
199
233
  evaluateManifestObject,
200
234
  buildCanonicalPayload,
201
235
  canonicalize,
236
+ resolvePublicKey,
202
237
  };
203
238
 
@@ -0,0 +1,351 @@
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
+
61
+ const data = await response.json();
62
+
63
+ if (!response.ok) {
64
+ return {
65
+ success: false,
66
+ error: data.error || `Activation API returned status ${response.status}`,
67
+ };
68
+ }
69
+
70
+ return { success: true, response: data };
71
+ } catch (err) {
72
+ return { success: false, error: `Network error: ${err.message}` };
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Validate the activation response contract.
78
+ * @param {object} response
79
+ * @returns {{ valid: boolean, reason?: string }}
80
+ */
81
+ function validateActivationResponse(response) {
82
+ if (!response || typeof response !== "object") {
83
+ return { valid: false, reason: "Response is not an object" };
84
+ }
85
+
86
+ if (!response.decision || !["activated", "already_activated", "denied"].includes(response.decision)) {
87
+ return { valid: false, reason: "Invalid decision in response" };
88
+ }
89
+
90
+ if (!response.manifest || typeof response.manifest !== "object") {
91
+ return { valid: false, reason: "Response is missing manifest" };
92
+ }
93
+
94
+ if (response.decision === "denied") {
95
+ return { valid: false, reason: response.manifest.error || "Activation was denied by server" };
96
+ }
97
+
98
+ if (!response.activation || typeof response.activation !== "object") {
99
+ return { valid: false, reason: "Response is missing activation metadata" };
100
+ }
101
+
102
+ if (typeof response.activation.machine_id !== "string") {
103
+ return { valid: false, reason: "Response activation.machine_id is invalid" };
104
+ }
105
+
106
+ return { valid: true };
107
+ }
108
+
109
+ /**
110
+ * Verify the signed manifest payload from the response.
111
+ * @param {object} manifest
112
+ * @returns {{ verified: boolean, reason?: string }}
113
+ */
114
+ function verifyManifestSignature(manifest) {
115
+ const now = Date.now();
116
+ const { state, manifest: verified } = evaluateManifestObject(manifest, now);
117
+
118
+ if (state === "missing") {
119
+ return { verified: false, reason: "No entitlement manifest available" };
120
+ }
121
+
122
+ if (state === "malformed") {
123
+ return { verified: false, reason: "Manifest is malformed" };
124
+ }
125
+
126
+ if (state === "unsigned") {
127
+ return { verified: false, reason: "Manifest is not signed" };
128
+ }
129
+
130
+ if (state === "untrusted-key") {
131
+ return { verified: false, reason: "Trust root not configured" };
132
+ }
133
+
134
+ if (state === "invalid-signature") {
135
+ return { verified: false, reason: "Manifest signature is invalid (exit code 3)" };
136
+ }
137
+
138
+ if (state === "expired") {
139
+ return { verified: false, reason: "Entitlement has expired" };
140
+ }
141
+
142
+ // "active" and "grace" are valid states
143
+ return { verified: true, manifest: verified };
144
+ }
145
+
146
+ /**
147
+ * Install required premium packs from the manifest.
148
+ * @param {object} manifest - Verified manifest
149
+ * @param {Array} premiumPacks - Pack metadata from activation response
150
+ * @returns {{ success: boolean, errors: string[] }}
151
+ */
152
+ function installRequiredPacks(manifest, premiumPacks) {
153
+ const errors = [];
154
+
155
+ if (!Array.isArray(premiumPacks)) {
156
+ return { success: true, errors: [] };
157
+ }
158
+
159
+ // Filter for spec product packs that match capabilities
160
+ const manifestCaps = Array.isArray(manifest.capabilities) ? manifest.capabilities : [];
161
+ const requiredPacks = premiumPacks.filter((pack) => {
162
+ if (!pack || pack.product !== "spec") return false;
163
+ if (!Array.isArray(pack.capabilities)) return false;
164
+ return pack.capabilities.some((c) => manifestCaps.includes(c));
165
+ });
166
+
167
+ // Install each required pack
168
+ for (const packEntry of requiredPacks) {
169
+ const validation = validatePackMeta(packEntry);
170
+ if (!validation.valid) {
171
+ errors.push(`Pack "${packEntry.id || "unknown"}": ${validation.reason}`);
172
+ continue;
173
+ }
174
+
175
+ // If pack bytes are embedded in the response, cache them immediately
176
+ if (packEntry.bytes && typeof packEntry.bytes === "string") {
177
+ try {
178
+ const packBytes = Buffer.from(packEntry.bytes, "base64");
179
+ const writeResult = writePackToCache(packEntry, packBytes);
180
+ if (!writeResult.success) {
181
+ errors.push(`Pack "${packEntry.id}": ${writeResult.reason}`);
182
+ }
183
+ } catch (err) {
184
+ errors.push(`Pack "${packEntry.id}": Failed to decode bytes: ${err.message}`);
185
+ }
186
+ }
187
+ }
188
+
189
+ return { success: errors.length === 0, errors };
190
+ }
191
+
192
+ /**
193
+ * Persist the verified entitlements and activation state locally.
194
+ * @param {object} manifest - Verified entitlement manifest
195
+ * @param {object} activation - Activation metadata from response
196
+ * @returns {{ success: boolean, error?: string }}
197
+ */
198
+ function persistEntitlementAndActivation(manifest, activation) {
199
+ const entitlementsFile = getEntitlementsFile();
200
+
201
+ try {
202
+ ensureDir(path.dirname(entitlementsFile));
203
+
204
+ // Write entitlements manifest
205
+ const manifestJson = JSON.stringify(manifest, null, 2);
206
+ fs.writeFileSync(entitlementsFile, manifestJson, "utf8");
207
+ hardenFilePermissions(entitlementsFile);
208
+
209
+ // Write activation metadata (no plain license key)
210
+ const activationResult = writeActivationState({
211
+ provider: "license",
212
+ customer_id: manifest.customer_id,
213
+ plan: manifest.plan,
214
+ machine_id: activation.machine_id,
215
+ decision: activation.decision || "activated",
216
+ });
217
+
218
+ if (!activationResult.success) {
219
+ return { success: false, error: activationResult.error };
220
+ }
221
+
222
+ return { success: true };
223
+ } catch (err) {
224
+ return { success: false, error: err.message };
225
+ }
226
+ }
227
+
228
+ /**
229
+ * Clean up partial state on activation failure.
230
+ * Only removes files if they are clearly from a failed activation attempt.
231
+ */
232
+ function rollbackPartialState() {
233
+ // Conservative: only remove activation.json if it exists
234
+ // Leave entitlements.json intact to avoid accidental deletion of valid state
235
+ try {
236
+ const { getActivationFile } = require("./suite-state");
237
+ const activationFile = getActivationFile();
238
+ if (fs.existsSync(activationFile)) {
239
+ fs.unlinkSync(activationFile);
240
+ }
241
+ } catch (_e) {
242
+ // Ignore cleanup errors
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Run the full activation flow.
248
+ *
249
+ * @param {object} options
250
+ * @param {string} options.licenseKey - Activation key from user
251
+ * @param {string} [options.activationUrl] - Override API URL (default: https://sdtk-spec.com/api/activate)
252
+ * @returns {Promise<{ success: boolean, decision?: string, message: string, exitCode: number }>}
253
+ */
254
+ async function activateWithLicense({
255
+ licenseKey,
256
+ activationUrl = "https://sdtk-spec.com/api/activate",
257
+ } = {}) {
258
+ const result = {
259
+ success: false,
260
+ message: "",
261
+ exitCode: 1,
262
+ };
263
+
264
+ // Validation: license key is required
265
+ if (!licenseKey || typeof licenseKey !== "string" || !licenseKey.trim()) {
266
+ result.message = "License key is required. Usage: sdtk-spec activate --license <KEY>";
267
+ result.exitCode = 1;
268
+ return result;
269
+ }
270
+
271
+ // Build machine_id
272
+ const machineId = buildMachineId();
273
+
274
+ // POST to activation API
275
+ const apiResult = await postActivationRequest({
276
+ activationUrl,
277
+ licenseKey: licenseKey.trim(),
278
+ machineId,
279
+ });
280
+
281
+ if (!apiResult.success) {
282
+ result.message = `Activation failed: ${apiResult.error}`;
283
+ result.exitCode = 1;
284
+ rollbackPartialState();
285
+ return result;
286
+ }
287
+
288
+ // Validate response contract
289
+ const validation = validateActivationResponse(apiResult.response);
290
+ if (!validation.valid) {
291
+ result.message = `Invalid activation response: ${validation.reason}`;
292
+ result.exitCode = 1;
293
+ rollbackPartialState();
294
+ return result;
295
+ }
296
+
297
+ const { decision, manifest, activation } = apiResult.response;
298
+
299
+ // Handle denied decision
300
+ if (decision === "denied") {
301
+ result.message = manifest.error || "Activation was denied by the server.";
302
+ result.exitCode = 1;
303
+ rollbackPartialState();
304
+ return result;
305
+ }
306
+
307
+ // Verify manifest signature
308
+ const sigResult = verifyManifestSignature(manifest);
309
+ if (!sigResult.verified) {
310
+ result.message = `Manifest verification failed: ${sigResult.reason}`;
311
+ result.exitCode = sigResult.reason && sigResult.reason.includes("exit code 3") ? 3 : 1;
312
+ rollbackPartialState();
313
+ return result;
314
+ }
315
+
316
+ // Validate premium packs metadata (install step deferred)
317
+ const packErrors = installRequiredPacks(sigResult.manifest, apiResult.response.premium_packs);
318
+ if (!packErrors.success) {
319
+ result.message = `Pack validation failed: ${packErrors.errors.join("; ")}`;
320
+ result.exitCode = 1;
321
+ rollbackPartialState();
322
+ return result;
323
+ }
324
+
325
+ // Persist verified state
326
+ const persistResult = persistEntitlementAndActivation(sigResult.manifest, activation);
327
+ if (!persistResult.success) {
328
+ result.message = `Failed to save activation state: ${persistResult.error}`;
329
+ result.exitCode = 4;
330
+ rollbackPartialState();
331
+ return result;
332
+ }
333
+
334
+ // Success
335
+ result.success = true;
336
+ result.decision = decision;
337
+ result.exitCode = 0;
338
+
339
+ if (decision === "already_activated") {
340
+ result.message = `Pro already activated on this machine (customer: ${sigResult.manifest.customer_id}, plan: ${sigResult.manifest.plan}).`;
341
+ } else {
342
+ result.message = `Pro activated successfully! Customer: ${sigResult.manifest.customer_id}, Plan: ${sigResult.manifest.plan}. You can now use premium SDTK commands.`;
343
+ }
344
+
345
+ return result;
346
+ }
347
+
348
+ module.exports = {
349
+ activateWithLicense,
350
+ buildMachineId,
351
+ };
@@ -21,6 +21,10 @@ function getEntitlementsFile() {
21
21
  return path.join(getSuiteRoot(), "entitlements.json");
22
22
  }
23
23
 
24
+ function getActivationFile() {
25
+ return path.join(getSuiteRoot(), "activation.json");
26
+ }
27
+
24
28
  function getPacksRoot() {
25
29
  return path.join(getSuiteRoot(), "packs");
26
30
  }
@@ -59,7 +63,8 @@ module.exports = {
59
63
  getSuiteRoot,
60
64
  getAuthFile,
61
65
  getEntitlementsFile,
66
+ getActivationFile,
62
67
  getPacksRoot,
63
68
  getLogsRoot,
64
69
  hardenFilePermissions,
65
- };
70
+ };