@zero2webmaster/starter-kit 0.2.0 → 0.2.1

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,472 @@
1
+ // z2w-starter-kit runtime license check.
2
+ //
3
+ // Implements the contract in directives/license-check.md. v0.3.0 introduction.
4
+ // The CLI phones home to the z2w-license-server WordPress plugin on
5
+ // zero2webmaster.com to validate paid-tier licenses, gates paid features
6
+ // (--with-init, Pro SEO baseline) on the result, and respects the
7
+ // snapshot-permanence client mapping table that lets cancelled subscribers
8
+ // keep using the AGENTS snapshot they paid for without pulling Templates
9
+ // updates.
10
+ //
11
+ // Three patterns the rest of the file is built around:
12
+ //
13
+ // 1. Pure evaluator. evaluateLicense(state, now) maps server status +
14
+ // time-since-last-check to a {allowPaidFeatures, allowTemplatesUpdates,
15
+ // reason, warning} record. No I/O. Trivially testable.
16
+ //
17
+ // 2. Test seams. RuntimeOptions exposes configDir / fetchImpl / now / uuid /
18
+ // licenseApiBase so the unit tests can stub HTTP, freeze time, point at
19
+ // a sandbox config dir, and pin UUID generation. Mirrors templates.ts.
20
+ //
21
+ // 3. checkLicense never throws on network or 5xx — it persists whatever new
22
+ // state is appropriate (advancing lastCheckAttempt, possibly persisting
23
+ // Retry-After) and returns {networkOk:false}. The N-day ceiling in
24
+ // evaluateLicense is the bounded grace window.
25
+ import { promises as fs } from "node:fs";
26
+ import * as path from "node:path";
27
+ import * as os from "node:os";
28
+ import { randomUUID } from "node:crypto";
29
+ export const DEFAULT_LICENSE_API_BASE = process.env["Z2W_LICENSE_API_BASE"] ??
30
+ "https://zero2webmaster.com/wp-json/z2w/v1";
31
+ export const PRODUCT_SLUG = "z2w-starter-kit";
32
+ export const DEFAULT_CONFIG_DIR = path.join(os.homedir(), ".config", "z2w");
33
+ export const LICENSE_FILE_NAME = "license";
34
+ /** 24h local cache: skip /license/check if last attempt is within this window. */
35
+ export const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
36
+ /** Past this many days of consecutive check failures, the CLI declines paid features. */
37
+ export const N_DAY_CEILING = 14;
38
+ /** Past this many days of consecutive check failures, the CLI warns (but still allows). */
39
+ export const N_DAY_WARN_THRESHOLD = Math.floor(N_DAY_CEILING / 2);
40
+ const MS_PER_DAY = 24 * 60 * 60 * 1000;
41
+ /**
42
+ * License-key format. Matches `Z2W_License_Manager::is_valid_format()` exactly:
43
+ * `Z2W-` literal + 4-letter alpha PREFIX (from license-server's `slug_prefix_map`)
44
+ * + three 4-char alphanumeric segments. Server rejects any other shape at
45
+ * REST `validate_callback` with HTTP 400, so we mirror it here for immediate
46
+ * local feedback.
47
+ */
48
+ const LICENSE_KEY_PATTERN = /^Z2W-[A-Z]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;
49
+ export class LicenseError extends Error {
50
+ constructor(message) {
51
+ super(message);
52
+ this.name = "LicenseError";
53
+ }
54
+ }
55
+ // ---------------------------------------------------------------------------
56
+ // Pure evaluator — the §6 snapshot-permanence mapping table
57
+ // ---------------------------------------------------------------------------
58
+ /**
59
+ * Maps stored license state + current time to a paid-feature decision. Pure
60
+ * function — no I/O, no side effects. The runtime check writes new state to
61
+ * disk first and THEN calls this; the unit tests pin every row in the
62
+ * directive §8 failure matrix against this function alone.
63
+ */
64
+ export function evaluateLicense(state, now = Date.now()) {
65
+ if (state === null) {
66
+ return {
67
+ allowPaidFeatures: false,
68
+ allowTemplatesUpdates: true,
69
+ reason: "no-license",
70
+ warning: "This is a paid feature. Run `z2w-starter-kit license set <key>` first.",
71
+ daysSinceLastCheck: null,
72
+ };
73
+ }
74
+ const lastSuccessMs = state.lastSuccessfulCheck
75
+ ? Date.parse(state.lastSuccessfulCheck)
76
+ : NaN;
77
+ if (!Number.isFinite(lastSuccessMs)) {
78
+ return {
79
+ allowPaidFeatures: false,
80
+ allowTemplatesUpdates: false,
81
+ reason: "never-checked",
82
+ warning: "License has never been successfully verified. Run `z2w-starter-kit license refresh`.",
83
+ daysSinceLastCheck: null,
84
+ };
85
+ }
86
+ const daysSinceLastCheck = Math.max(0, Math.floor((now - lastSuccessMs) / MS_PER_DAY));
87
+ if (daysSinceLastCheck > N_DAY_CEILING) {
88
+ return {
89
+ allowPaidFeatures: false,
90
+ allowTemplatesUpdates: false,
91
+ reason: "check-failing-past-ceiling",
92
+ warning: `License check has been failing for ${daysSinceLastCheck} days, past the ` +
93
+ `${N_DAY_CEILING}-day grace window. Run \`z2w-starter-kit license refresh\` ` +
94
+ `when network is restored.`,
95
+ daysSinceLastCheck,
96
+ };
97
+ }
98
+ const status = state.cachedStatus;
99
+ if (status === "revoked") {
100
+ return {
101
+ allowPaidFeatures: false,
102
+ allowTemplatesUpdates: false,
103
+ reason: "revoked-blocked",
104
+ warning: "This license has been revoked. Paid features are disabled. Contact support.",
105
+ daysSinceLastCheck,
106
+ };
107
+ }
108
+ if (status === "suspended") {
109
+ return {
110
+ allowPaidFeatures: true,
111
+ allowTemplatesUpdates: false,
112
+ reason: "suspended-snapshot-only",
113
+ warning: "Subscription is suspended (typically a billing issue). The AGENTS snapshot " +
114
+ "you have remains usable. Contact support to resolve.",
115
+ daysSinceLastCheck,
116
+ };
117
+ }
118
+ if (status === "expired") {
119
+ return {
120
+ allowPaidFeatures: true,
121
+ allowTemplatesUpdates: false,
122
+ reason: "expired-snapshot-only",
123
+ warning: "Subscription has expired. The AGENTS snapshot you have remains usable. " +
124
+ "Re-subscribe at zero2webmaster.com to resume updates.",
125
+ daysSinceLastCheck,
126
+ };
127
+ }
128
+ // status === "active" (or unknown — treated as active inside the grace window).
129
+ if (daysSinceLastCheck > N_DAY_WARN_THRESHOLD) {
130
+ return {
131
+ allowPaidFeatures: true,
132
+ allowTemplatesUpdates: true,
133
+ reason: "check-failing-past-warn",
134
+ warning: `License check has been failing for ${daysSinceLastCheck} days. Run ` +
135
+ `\`z2w-starter-kit license refresh\` when network is restored.`,
136
+ daysSinceLastCheck,
137
+ };
138
+ }
139
+ if (state.lastCheckAttempt && state.lastSuccessfulCheck) {
140
+ const attemptMs = Date.parse(state.lastCheckAttempt);
141
+ if (Number.isFinite(attemptMs) && attemptMs > lastSuccessMs) {
142
+ return {
143
+ allowPaidFeatures: true,
144
+ allowTemplatesUpdates: true,
145
+ reason: "check-failing-within-grace",
146
+ warning: null,
147
+ daysSinceLastCheck,
148
+ };
149
+ }
150
+ }
151
+ return {
152
+ allowPaidFeatures: true,
153
+ allowTemplatesUpdates: true,
154
+ reason: "active",
155
+ warning: null,
156
+ daysSinceLastCheck,
157
+ };
158
+ }
159
+ // ---------------------------------------------------------------------------
160
+ // Storage — ~/.config/z2w/license (JSON, atomic, 0600)
161
+ // ---------------------------------------------------------------------------
162
+ function licenseFilePath(configDir) {
163
+ return path.join(configDir, LICENSE_FILE_NAME);
164
+ }
165
+ export async function loadLicenseState(opts = {}) {
166
+ const dir = opts.configDir ?? DEFAULT_CONFIG_DIR;
167
+ const filePath = licenseFilePath(dir);
168
+ let raw;
169
+ try {
170
+ raw = await fs.readFile(filePath, "utf8");
171
+ }
172
+ catch (err) {
173
+ if (err.code === "ENOENT")
174
+ return null;
175
+ return null;
176
+ }
177
+ try {
178
+ const parsed = JSON.parse(raw);
179
+ if (typeof parsed !== "object" || parsed === null)
180
+ return null;
181
+ const candidate = parsed;
182
+ if (candidate.version !== 1)
183
+ return null;
184
+ if (typeof candidate.key !== "string" || candidate.key.length === 0)
185
+ return null;
186
+ if (typeof candidate.productSlug !== "string")
187
+ return null;
188
+ if (typeof candidate.machineId !== "string" || candidate.machineId.length === 0)
189
+ return null;
190
+ return {
191
+ version: 1,
192
+ key: candidate.key,
193
+ productSlug: candidate.productSlug,
194
+ machineId: candidate.machineId,
195
+ lastSuccessfulCheck: typeof candidate.lastSuccessfulCheck === "string" ? candidate.lastSuccessfulCheck : null,
196
+ lastCheckAttempt: typeof candidate.lastCheckAttempt === "string" ? candidate.lastCheckAttempt : null,
197
+ cachedStatus: isServerStatus(candidate.cachedStatus) ? candidate.cachedStatus : null,
198
+ cachedExpiresAt: typeof candidate.cachedExpiresAt === "string" ? candidate.cachedExpiresAt : null,
199
+ retryAfter: typeof candidate.retryAfter === "string" ? candidate.retryAfter : null,
200
+ };
201
+ }
202
+ catch {
203
+ return null;
204
+ }
205
+ }
206
+ export async function saveLicenseState(state, opts = {}) {
207
+ const dir = opts.configDir ?? DEFAULT_CONFIG_DIR;
208
+ const filePath = licenseFilePath(dir);
209
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
210
+ const tmp = `${filePath}.tmp`;
211
+ await fs.writeFile(tmp, JSON.stringify(state, null, 2), { encoding: "utf8", mode: 0o600 });
212
+ await fs.rename(tmp, filePath);
213
+ }
214
+ export async function clearLicenseState(opts = {}) {
215
+ const dir = opts.configDir ?? DEFAULT_CONFIG_DIR;
216
+ const filePath = licenseFilePath(dir);
217
+ try {
218
+ await fs.unlink(filePath);
219
+ }
220
+ catch (err) {
221
+ if (err.code !== "ENOENT")
222
+ throw err;
223
+ }
224
+ }
225
+ async function postEndpoint(endpoint, payload, opts) {
226
+ const apiBase = (opts.licenseApiBase ?? DEFAULT_LICENSE_API_BASE).replace(/\/+$/, "");
227
+ const url = `${apiBase}/license/${endpoint}`;
228
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
229
+ if (typeof fetchImpl !== "function") {
230
+ throw new LicenseError("fetch() is not available in this runtime. Upgrade to Node 20+ or pass opts.fetchImpl.");
231
+ }
232
+ let response;
233
+ try {
234
+ response = await fetchImpl(url, {
235
+ method: "POST",
236
+ headers: {
237
+ "Content-Type": "application/json",
238
+ Accept: "application/json",
239
+ },
240
+ body: JSON.stringify(payload),
241
+ });
242
+ }
243
+ catch (err) {
244
+ throw new LicenseError(`Network error contacting ${url}: ${err.message}`);
245
+ }
246
+ const retryAfterHeader = response.headers.get("retry-after");
247
+ let body = null;
248
+ try {
249
+ const text = await response.text();
250
+ body = text ? JSON.parse(text) : null;
251
+ }
252
+ catch {
253
+ body = null;
254
+ }
255
+ return {
256
+ ok: response.ok,
257
+ status: response.status,
258
+ retryAfterHeader,
259
+ body,
260
+ };
261
+ }
262
+ function computeRetryAfter(headerValue, now) {
263
+ if (!headerValue)
264
+ return null;
265
+ const seconds = Number(headerValue);
266
+ if (Number.isFinite(seconds) && seconds >= 0) {
267
+ return new Date(now + seconds * 1000).toISOString();
268
+ }
269
+ const httpDate = Date.parse(headerValue);
270
+ if (Number.isFinite(httpDate)) {
271
+ return new Date(httpDate).toISOString();
272
+ }
273
+ return null;
274
+ }
275
+ function isServerStatus(value) {
276
+ return (value === "active" ||
277
+ value === "expired" ||
278
+ value === "suspended" ||
279
+ value === "revoked");
280
+ }
281
+ function extractServerMessage(body, fallback) {
282
+ return body?.data?.message ?? body?.message ?? fallback;
283
+ }
284
+ // ---------------------------------------------------------------------------
285
+ // Public API — activate, check, deactivate, runtimeLicenseCheck
286
+ // ---------------------------------------------------------------------------
287
+ export function isValidLicenseKey(key) {
288
+ return LICENSE_KEY_PATTERN.test(key);
289
+ }
290
+ /** Masks a license key for diagnostic display: "Z2W-ABCD-...-WXYZ". */
291
+ export function maskKey(key) {
292
+ if (typeof key !== "string" || key.length < 12)
293
+ return "****";
294
+ return `${key.slice(0, 8)}-...-${key.slice(-4)}`;
295
+ }
296
+ /**
297
+ * Activates a license on this machine. On 2xx, persists state including a
298
+ * fresh `lastSuccessfulCheck`. On error, throws LicenseError without writing.
299
+ */
300
+ export async function activateLicense(key, opts = {}) {
301
+ const now = (opts.now ?? Date.now)();
302
+ const uuidImpl = opts.uuid ?? (() => randomUUID());
303
+ const existing = await loadLicenseState(opts);
304
+ const machineId = existing?.machineId ?? uuidImpl();
305
+ const response = await postEndpoint("activate", { license_key: key, plugin_slug: PRODUCT_SLUG, site_url: machineId }, opts);
306
+ if (!response.ok) {
307
+ throw new LicenseError(`License activation failed (${response.status}): ${extractServerMessage(response.body, "no server message")}`);
308
+ }
309
+ const serverStatusRaw = response.body?.data?.status;
310
+ const serverStatus = isServerStatus(serverStatusRaw)
311
+ ? serverStatusRaw
312
+ : "active";
313
+ const expiresAt = response.body?.data?.expires_at ?? null;
314
+ const nowIso = new Date(now).toISOString();
315
+ const state = {
316
+ version: 1,
317
+ key,
318
+ productSlug: PRODUCT_SLUG,
319
+ machineId,
320
+ lastSuccessfulCheck: nowIso,
321
+ lastCheckAttempt: nowIso,
322
+ cachedStatus: serverStatus,
323
+ cachedExpiresAt: expiresAt,
324
+ retryAfter: null,
325
+ };
326
+ await saveLicenseState(state, opts);
327
+ return { state, status: serverStatus };
328
+ }
329
+ /**
330
+ * Calls /license/check and updates state accordingly. Never throws on network
331
+ * failure / 5xx / 429 — bumps `lastCheckAttempt`, persists `retryAfter` if
332
+ * the server sent one, and returns `networkOk: false`. Throws only when no
333
+ * license is configured (callers should handle that ahead of time).
334
+ *
335
+ * Honors a previously-persisted Retry-After by short-circuiting the network
336
+ * call until the persisted deadline passes.
337
+ */
338
+ export async function checkLicense(opts = {}) {
339
+ const existing = await loadLicenseState(opts);
340
+ if (existing === null) {
341
+ throw new LicenseError("No license configured. Run `z2w-starter-kit license set <key>` first.");
342
+ }
343
+ const now = (opts.now ?? Date.now)();
344
+ const nowIso = new Date(now).toISOString();
345
+ if (existing.retryAfter) {
346
+ const retryAt = Date.parse(existing.retryAfter);
347
+ if (Number.isFinite(retryAt) && now < retryAt) {
348
+ return {
349
+ state: existing,
350
+ status: existing.cachedStatus,
351
+ networkOk: false,
352
+ message: `Rate-limited until ${existing.retryAfter}; using cached status.`,
353
+ };
354
+ }
355
+ }
356
+ let response;
357
+ try {
358
+ response = await postEndpoint("check", {
359
+ license_key: existing.key,
360
+ plugin_slug: existing.productSlug,
361
+ site_url: existing.machineId,
362
+ }, opts);
363
+ }
364
+ catch (err) {
365
+ const state = { ...existing, lastCheckAttempt: nowIso };
366
+ await saveLicenseState(state, opts);
367
+ return {
368
+ state,
369
+ status: existing.cachedStatus,
370
+ networkOk: false,
371
+ message: err.message,
372
+ };
373
+ }
374
+ if (response.status === 429) {
375
+ const retryAfterIso = computeRetryAfter(response.retryAfterHeader, now);
376
+ const state = {
377
+ ...existing,
378
+ lastCheckAttempt: nowIso,
379
+ retryAfter: retryAfterIso,
380
+ };
381
+ await saveLicenseState(state, opts);
382
+ return {
383
+ state,
384
+ status: existing.cachedStatus,
385
+ networkOk: false,
386
+ message: extractServerMessage(response.body, "Rate-limited (429)."),
387
+ };
388
+ }
389
+ if (!response.ok) {
390
+ const state = { ...existing, lastCheckAttempt: nowIso };
391
+ await saveLicenseState(state, opts);
392
+ return {
393
+ state,
394
+ status: existing.cachedStatus,
395
+ networkOk: false,
396
+ message: extractServerMessage(response.body, `HTTP ${response.status}`),
397
+ };
398
+ }
399
+ const serverStatusRaw = response.body?.data?.status;
400
+ if (!isServerStatus(serverStatusRaw)) {
401
+ const state = { ...existing, lastCheckAttempt: nowIso };
402
+ await saveLicenseState(state, opts);
403
+ return {
404
+ state,
405
+ status: existing.cachedStatus,
406
+ networkOk: false,
407
+ message: "Server returned 2xx but no recognized status field.",
408
+ };
409
+ }
410
+ const state = {
411
+ version: 1,
412
+ key: existing.key,
413
+ productSlug: existing.productSlug,
414
+ machineId: existing.machineId,
415
+ lastSuccessfulCheck: nowIso,
416
+ lastCheckAttempt: nowIso,
417
+ cachedStatus: serverStatusRaw,
418
+ cachedExpiresAt: response.body?.data?.expires_at ?? null,
419
+ retryAfter: null,
420
+ };
421
+ await saveLicenseState(state, opts);
422
+ return { state, status: serverStatusRaw, networkOk: true, message: null };
423
+ }
424
+ /**
425
+ * Deactivates the local license. Attempts to notify the server (so the
426
+ * activation slot frees up) but clears local state even if the server call
427
+ * fails — the user has decided to deactivate, and a stuck server-side
428
+ * activation isn't a reason to block them.
429
+ */
430
+ export async function deactivateLicense(opts = {}) {
431
+ const existing = await loadLicenseState(opts);
432
+ if (existing === null) {
433
+ throw new LicenseError("No license configured.");
434
+ }
435
+ try {
436
+ await postEndpoint("deactivate", {
437
+ license_key: existing.key,
438
+ plugin_slug: existing.productSlug,
439
+ site_url: existing.machineId,
440
+ }, opts);
441
+ }
442
+ catch {
443
+ // Swallow — clearing local state is the user-meaningful operation.
444
+ }
445
+ await clearLicenseState(opts);
446
+ }
447
+ /**
448
+ * The orchestrator paid-feature gates call. Reads stored state; if cache is
449
+ * stale (>24h since last attempt), phones home; runs the pure evaluator
450
+ * against whatever state ends up persisted. Never throws — returns a
451
+ * well-formed evaluation in every case so call sites can switch on
452
+ * `allowPaidFeatures` cleanly.
453
+ */
454
+ export async function runtimeLicenseCheck(opts = {}) {
455
+ const now = (opts.now ?? Date.now)();
456
+ const state = await loadLicenseState(opts);
457
+ if (state === null) {
458
+ return evaluateLicense(null, now);
459
+ }
460
+ const lastAttemptMs = state.lastCheckAttempt ? Date.parse(state.lastCheckAttempt) : NaN;
461
+ const cacheIsFresh = Number.isFinite(lastAttemptMs) && now - lastAttemptMs < CACHE_TTL_MS;
462
+ if (cacheIsFresh) {
463
+ return evaluateLicense(state, now);
464
+ }
465
+ try {
466
+ const { state: newState } = await checkLicense(opts);
467
+ return evaluateLicense(newState, now);
468
+ }
469
+ catch {
470
+ return evaluateLicense(state, now);
471
+ }
472
+ }
@@ -1,4 +1,4 @@
1
- import type { BrandPreset, DbStrategy, ProjectType } from "./index.js";
1
+ import type { BrandPreset, BriefSections, DbStrategy, ProjectType } from "./index.js";
2
2
  export interface ParsedBrief {
3
3
  slug: string | null;
4
4
  description: string | null;
@@ -10,6 +10,8 @@ export interface ParsedBrief {
10
10
  hasWebUi: boolean | null;
11
11
  hasCron: boolean | null;
12
12
  participateInBulletin: boolean | null;
13
+ /** Free-text planning sections lifted verbatim from the brief, if any. */
14
+ briefSections: BriefSections | undefined;
13
15
  raw: string;
14
16
  }
15
17
  /**
@@ -17,9 +19,25 @@ export interface ParsedBrief {
17
19
  * section heading (any style) or end of brief.
18
20
  */
19
21
  export declare function extractSection(brief: string, name: string): string | null;
22
+ /**
23
+ * Expand a leading `~` / `~/` to the user's home directory. Briefs and
24
+ * confirm-screen entries routinely carry `~/Desktop/...` paths, which the
25
+ * shell would expand on a command line but which arrive literal here. Without
26
+ * this, `inferTargetPath` rejected every tilde path as non-absolute (a
27
+ * contributor to the 2026-06-03 "Target path [unset]" dogfood finding).
28
+ */
29
+ export declare function expandHome(p: string): string;
20
30
  export declare function kebabCase(input: string): string;
21
31
  export declare function isValidSlug(slug: string): boolean;
22
32
  export declare function githubOrgForBrand(brand: BrandPreset): string | null;
33
+ /**
34
+ * Lift the free-text planning sections out of the brief so they can flow into
35
+ * the scaffolded ROADMAP.md + README.md (per [[instantiate-z2w-project]]
36
+ * SKILL Step 1a.4) instead of being discarded after field inference. Only
37
+ * sections actually present in the brief appear in the result; returns
38
+ * `undefined` when none are found (the wizard/`--input` shape).
39
+ */
40
+ export declare function extractBriefSections(brief: string): BriefSections | undefined;
23
41
  /**
24
42
  * Parse a pasted project-instantiation brief into a ParsedBrief. Every field
25
43
  * that cannot be inferred deterministically is left as `null` — the