@commentkit/comment-kit 1.6.0 → 2.0.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/CHANGELOG.md +281 -597
- package/README.md +334 -154
- package/SECURITY.md +47 -46
- package/dist/node/THIRD_PARTY_NOTICES.txt +56 -0
- package/dist/node/browser.js +17 -0
- package/dist/node/cli/api.js +226 -0
- package/dist/node/cli/bin.js +18 -0
- package/dist/node/cli/credentials.js +268 -0
- package/dist/node/cli/doctor.js +725 -0
- package/dist/node/cli/format.js +54 -0
- package/dist/node/cli/init.js +372 -0
- package/dist/node/cli/main.js +519 -0
- package/dist/node/cli/mcp.js +114 -0
- package/dist/node/cli/open.js +20 -0
- package/dist/node/plugins/astro-B5y1Gtbf.js +31 -0
- package/dist/node/plugins/astro.js +26 -0
- package/dist/node/plugins/git-BIXLbL3f.js +92 -0
- package/dist/node/plugins/jsx-Bg4BdSph.js +7958 -0
- package/dist/node/plugins/next.js +48 -0
- package/dist/node/plugins/options-THop1K92.js +71 -0
- package/dist/node/plugins/transform-CKiAuSbk.js +1155 -0
- package/dist/node/plugins/vite-BdAYUW10.js +74 -0
- package/dist/node/plugins/vite.js +1 -0
- package/dist/node/plugins/webpack-R2U2DLlY.js +35 -0
- package/dist/node/plugins/webpack-loader.cjs +21 -0
- package/dist/node/plugins/webpack-loader.js +18 -0
- package/dist/node/plugins/webpack.js +1 -0
- package/dist/node/shared/endpoint.js +26 -0
- package/dist/node/shared/format.js +63 -0
- package/dist/node/types/astro.d.ts +11 -0
- package/dist/node/types/next.d.ts +34 -0
- package/dist/node/types/options.d.ts +59 -0
- package/dist/node/types/vite.d.ts +11 -0
- package/dist/node/types/webpack-loader.d.ts +22 -0
- package/dist/node/types/webpack.d.ts +27 -0
- package/dist/npm/THIRD_PARTY_NOTICES.txt +6 -6
- package/dist/npm/chunks/AgentSend-DxRJIYiz.js +68 -0
- package/dist/npm/chunks/Checklist-CnlfeSbc.js +282 -0
- package/dist/npm/chunks/Composer-B1bBVszY.js +725 -0
- package/dist/npm/chunks/Guest-vvNPz8h-.js +267 -0
- package/dist/npm/chunks/MarkupEditor-VCOXh9d2.js +338 -0
- package/dist/npm/chunks/Panel-F37vIL1K.js +1206 -0
- package/dist/npm/chunks/Settings-BGoZS2iV.js +231 -0
- package/dist/npm/chunks/Shortcuts-B2OMvczr.js +62 -0
- package/dist/npm/chunks/StyleEditor-CJ_d8Huf.js +46 -0
- package/dist/npm/chunks/StylePanel-yQzHHlY7.js +199 -0
- package/dist/npm/chunks/TaskFields-fmy6_HtK.js +289 -0
- package/dist/npm/chunks/ThreadCard-D51slKST.js +1113 -0
- package/dist/npm/chunks/Viewer-BOBadqmC.js +111 -0
- package/dist/npm/chunks/{agent-BDMQtOzH.js → agent-C1OQzBAm.js} +9 -9
- package/dist/npm/chunks/{anchor-BsradQhn.js → anchor-BsQNVkHj.js} +108 -85
- package/dist/npm/chunks/{ar-8tPch6W4.js → ar-CAJ3XT8e.js} +69 -19
- package/dist/npm/chunks/card-bits-CAnzrqx3.js +53 -0
- package/dist/npm/chunks/{client-EFTWxHbJ.js → client-kNAo2TTG.js} +282 -290
- package/dist/npm/chunks/confetti-CkBdSu19.js +49 -0
- package/dist/npm/chunks/context-B8UAzve0.js +20 -0
- package/dist/npm/chunks/context-BuMl7A07.js +48 -0
- package/dist/npm/chunks/{de-C63897uD.js → de-Dl18G48t.js} +60 -18
- package/dist/npm/chunks/dialog-GO04oC3D.js +3 -0
- package/dist/npm/chunks/dpop-U48QIQd7.js +96 -0
- package/dist/npm/chunks/drafts-B0ctr1g9.js +21 -0
- package/dist/npm/chunks/{es-CI2bSpvB.js → es-Dxk79lS9.js} +60 -18
- package/dist/npm/chunks/extension-CKFpPWmi.js +62 -0
- package/dist/npm/chunks/{extension-BST6LH1q.js → extension-E81hWyiT.js} +20 -12
- package/dist/npm/chunks/files-DyD5BZgp.js +114 -0
- package/dist/npm/chunks/{fr-rsVe-Lqk.js → fr-8BebGKYD.js} +118 -76
- package/dist/npm/chunks/{hi-cvwbSaWP.js → hi-BIN6Yy_p.js} +61 -19
- package/dist/npm/chunks/{i18n-C4v0M-6z.js → i18n-DOBt8e9U.js} +91 -56
- package/dist/npm/chunks/identify-CN-3xzqL.js +106 -0
- package/dist/npm/chunks/{it-C8tnV0BF.js → it-Cr6EwpPQ.js} +79 -37
- package/dist/npm/chunks/{ja-BWxDfC2f.js → ja-Iy3s5aur.js} +58 -16
- package/dist/npm/chunks/late-words-B2bmZceJ.js +12 -0
- package/dist/npm/chunks/live-CelVeZfP.js +85 -0
- package/dist/npm/chunks/locale-D8Q4Q2Nt.js +26 -0
- package/dist/npm/chunks/{nl-DNQ6eCht.js → nl-B84WHqqe.js} +61 -19
- package/dist/npm/chunks/page-key-DepmJzC1.js +62 -0
- package/dist/npm/chunks/{pick-CLyOdjnD.js → pick-yTyqtxN0.js} +45 -44
- package/dist/npm/chunks/pkce-ChKGSW_4.js +8 -0
- package/dist/npm/chunks/placement-BF_HOUDD.js +74 -0
- package/dist/npm/chunks/privacy-BWUGlHw5.js +57 -0
- package/dist/npm/chunks/{pt-BR-CkG7vpU2.js → pt-BR-DOkdlfoe.js} +60 -18
- package/dist/npm/chunks/{realtime-DIo-Wth4.js → realtime-C79zF50C.js} +14 -12
- package/dist/npm/chunks/report-CrIqQZDI.js +44 -0
- package/dist/npm/chunks/show-BgVC8gWY.js +97 -0
- package/dist/npm/chunks/signin-Dd1rb2BP.js +75 -0
- package/dist/npm/chunks/{source-CS7C6wJA.js → source-pXVve2Cx.js} +1 -1
- package/dist/npm/chunks/src-BTMy4Gyc.js +208 -0
- package/dist/npm/chunks/start-DtVlpt7p.js +1878 -0
- package/dist/npm/chunks/states-sfTbjZz8.js +3 -0
- package/dist/npm/chunks/upload-MgPYqPyE.js +42 -0
- package/dist/npm/chunks/uploads-D49mywwz.js +1146 -0
- package/dist/npm/chunks/wrap-Bl0gbnFa.js +69 -0
- package/dist/npm/chunks/{zh-CN-BKuZOLBE.js → zh-CN-Z5fQCb7G.js} +59 -17
- package/dist/npm/element.js +58 -21
- package/dist/npm/headless.js +7 -3
- package/dist/npm/index.js +3 -3
- package/dist/npm/react.js +18 -11
- package/dist/npm/svelte.js +28 -12
- package/dist/npm/types/adapters/react.d.ts +4 -1
- package/dist/npm/types/adapters/svelte.d.ts +4 -1
- package/dist/npm/types/adapters/vue.d.ts +35 -2
- package/dist/npm/types/anchor/index.d.ts +19 -0
- package/dist/npm/types/capture/privacy.d.ts +14 -0
- package/dist/npm/types/core/api.d.ts +20 -1
- package/dist/npm/types/core/auth.d.ts +40 -21
- package/dist/npm/types/core/client.d.ts +60 -4
- package/dist/npm/types/core/page-key.d.ts +42 -0
- package/dist/npm/types/core/types.d.ts +87 -4
- package/dist/npm/types/element.d.ts +17 -7
- package/dist/npm/types/headless.d.ts +2 -1
- package/dist/npm/types/index.d.ts +16 -6
- package/dist/npm/vue.js +44 -9
- package/package.json +88 -14
- package/dist/npm/chunks/AgentSend-2JPDseOo.js +0 -63
- package/dist/npm/chunks/Checklist-BpDXQebo.js +0 -257
- package/dist/npm/chunks/Composer-CAyj-c8e.js +0 -677
- package/dist/npm/chunks/Guest-ZdFmTcXI.js +0 -187
- package/dist/npm/chunks/MarkupEditor-BFplZwFy.js +0 -332
- package/dist/npm/chunks/Panel-BhZ4XRDR.js +0 -861
- package/dist/npm/chunks/Settings-SPG9EHUZ.js +0 -204
- package/dist/npm/chunks/Shortcuts-C28HVDw6.js +0 -58
- package/dist/npm/chunks/StyleEditor-ByZMtq10.js +0 -43
- package/dist/npm/chunks/StylePanel-Iwhce2tE.js +0 -197
- package/dist/npm/chunks/TaskFields-BsP_fVJg.js +0 -273
- package/dist/npm/chunks/ThreadCard-BzVZdDCb.js +0 -1030
- package/dist/npm/chunks/Viewer-CqtGrdD8.js +0 -108
- package/dist/npm/chunks/card-bits-Bna-g3Py.js +0 -124
- package/dist/npm/chunks/confetti-DTKpwF3O.js +0 -40
- package/dist/npm/chunks/drafts-akdBsOd0.js +0 -50
- package/dist/npm/chunks/extension-D-V3utTm.js +0 -53
- package/dist/npm/chunks/live-BCpJVBeN.js +0 -33
- package/dist/npm/chunks/report-BBrT3r89.js +0 -27
- package/dist/npm/chunks/src-C4FsVoUp.js +0 -148
- package/dist/npm/chunks/start-i9M-r3aH.js +0 -1800
- package/dist/npm/chunks/upload-DSv7EyBD.js +0 -41
- package/dist/npm/chunks/uploads-I01kdqQF.js +0 -1103
|
@@ -0,0 +1,725 @@
|
|
|
1
|
+
// `npx @commentkit/comment-kit doctor [url]`: find out, in plain words, why the widget is not showing.
|
|
2
|
+
// Node built-ins only. Every network call goes through an injectable fetch, so the tests run offline.
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { CliError, endpointFrom, Project } from "./api.js";
|
|
6
|
+
import { safeUrl } from "./format.js";
|
|
7
|
+
import { PLUGIN_IMPORT, plan } from "./init.js";
|
|
8
|
+
import { PUBLISHABLE_KEY } from "./main.js";
|
|
9
|
+
const TIMEOUT_MS = 10_000;
|
|
10
|
+
const MAX_PAGE_BYTES = 2 * 1024 * 1024;
|
|
11
|
+
const MAX_API_BYTES = 256 * 1024;
|
|
12
|
+
const MAX_REDIRECTS = 3;
|
|
13
|
+
const SDK = "@commentkit/comment-kit";
|
|
14
|
+
/**
|
|
15
|
+
* How to run this CLI: always the full package name. A bare `npx commentkit` runs this package only where it is
|
|
16
|
+
* installed; anywhere else npx would fetch an unrelated npm package named "commentkit".
|
|
17
|
+
*/
|
|
18
|
+
export const CLI = `npx ${SDK}`;
|
|
19
|
+
const KEY_VARS = ["NEXT_PUBLIC_COMMENTKIT_KEY", "VITE_COMMENTKIT_KEY", "PUBLIC_COMMENTKIT_KEY", "NUXT_PUBLIC_COMMENTKIT_KEY", "COMMENTKIT_KEY"];
|
|
20
|
+
/** A placeholder key for init's plan(): doctor only reads what it detects, it never writes. */
|
|
21
|
+
const PLAN_KEY = "pk_test_doctordoctordoctordoc";
|
|
22
|
+
const MARK = { pass: "✓", fail: "✗", warn: "!", info: "•" };
|
|
23
|
+
// ---------------------------------------------------------------------------------------------
|
|
24
|
+
// Small helpers
|
|
25
|
+
/** Text from a server or a page, safe for one terminal line: no control characters, bounded. */
|
|
26
|
+
export function clean(text, max = 120) {
|
|
27
|
+
const t = String(text ?? "").replace(/[\u0000-\u001f\u007f-\u009f---]/g, " ").replace(/\s+/g, " ").trim();
|
|
28
|
+
return t.length > max ? `${t.slice(0, max - 1)}…` : t;
|
|
29
|
+
}
|
|
30
|
+
/** A publishable key, shortened: it identifies a project and grants nothing, but there is no need to print it whole. */
|
|
31
|
+
export function maskKey(key) {
|
|
32
|
+
return key.length > 12 ? `${key.slice(0, 12)}…` : key;
|
|
33
|
+
}
|
|
34
|
+
function isLocalHost(host) {
|
|
35
|
+
const name = host.toLowerCase().replace(/^\[|\]$/g, "");
|
|
36
|
+
return ["localhost", "127.0.0.1", "::1"].includes(name) || name.endsWith(".localhost");
|
|
37
|
+
}
|
|
38
|
+
/** Hosts the widget treats as local development (src/activation.ts isLocalOrigin): shown without a share link. */
|
|
39
|
+
function isDevHost(host) {
|
|
40
|
+
return isLocalHost(host) || host.toLowerCase().endsWith(".test");
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The website to check: http or https only, no user name or password in it. Anything else
|
|
44
|
+
* (file:, javascript:, data:, chrome:, custom app schemes) is refused before any request is made.
|
|
45
|
+
*/
|
|
46
|
+
export function siteUrl(raw) {
|
|
47
|
+
let url;
|
|
48
|
+
try {
|
|
49
|
+
url = new URL(/^[a-z][a-z0-9+.-]*:/i.test(raw.trim()) ? raw.trim() : `https://${raw.trim()}`);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
throw new CliError(`“${clean(raw, 80)}” is not a website address. Give one like https://example.com.`, "invalid_url");
|
|
53
|
+
}
|
|
54
|
+
if (url.protocol !== "http:" && url.protocol !== "https:")
|
|
55
|
+
throw new CliError(`doctor checks websites only (http:// or https://), not ${clean(url.protocol, 20)} addresses.`, "invalid_url");
|
|
56
|
+
if (url.username || url.password)
|
|
57
|
+
throw new CliError("Leave the user name and password out of the address: doctor never sends credentials.", "invalid_url");
|
|
58
|
+
if (!url.hostname)
|
|
59
|
+
throw new CliError("That address has no host name.", "invalid_url");
|
|
60
|
+
return url;
|
|
61
|
+
}
|
|
62
|
+
async function readCapped(response, maxBytes) {
|
|
63
|
+
if (!response.body)
|
|
64
|
+
return { text: "", truncated: false };
|
|
65
|
+
const reader = response.body.getReader();
|
|
66
|
+
const chunks = [];
|
|
67
|
+
let size = 0;
|
|
68
|
+
let truncated = false;
|
|
69
|
+
for (;;) {
|
|
70
|
+
const { done, value } = await reader.read();
|
|
71
|
+
if (done)
|
|
72
|
+
break;
|
|
73
|
+
if (size + value.byteLength > maxBytes) {
|
|
74
|
+
chunks.push(value.subarray(0, maxBytes - size));
|
|
75
|
+
size = maxBytes;
|
|
76
|
+
truncated = true;
|
|
77
|
+
await reader.cancel().catch(() => undefined);
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
chunks.push(value);
|
|
81
|
+
size += value.byteLength;
|
|
82
|
+
}
|
|
83
|
+
const all = new Uint8Array(size);
|
|
84
|
+
let at = 0;
|
|
85
|
+
for (const chunk of chunks) {
|
|
86
|
+
all.set(chunk, at);
|
|
87
|
+
at += chunk.byteLength;
|
|
88
|
+
}
|
|
89
|
+
return { text: new TextDecoder("utf-8", { fatal: false }).decode(all), truncated };
|
|
90
|
+
}
|
|
91
|
+
function reason(error) {
|
|
92
|
+
if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError"))
|
|
93
|
+
return "no answer in time";
|
|
94
|
+
const cause = error instanceof Error ? error.cause : undefined;
|
|
95
|
+
const code = cause && typeof cause === "object" && "code" in cause ? String(cause.code) : "";
|
|
96
|
+
return clean(code || (error instanceof Error ? error.message : String(error)), 80);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* GET a page the way a first-time visitor would: no cookies or credentials, at most 3 redirects (each
|
|
100
|
+
* one checked like the address itself), one timeout for the whole thing, and at most `maxBytes` read.
|
|
101
|
+
*/
|
|
102
|
+
export async function fetchPage(start, fetchFn, { timeoutMs = TIMEOUT_MS, maxBytes = MAX_PAGE_BYTES } = {}) {
|
|
103
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
104
|
+
let url = start;
|
|
105
|
+
for (let redirects = 0;; redirects++) {
|
|
106
|
+
const response = await fetchFn(url.href, {
|
|
107
|
+
redirect: "manual",
|
|
108
|
+
credentials: "omit",
|
|
109
|
+
signal,
|
|
110
|
+
headers: { accept: "text/html,application/xhtml+xml;q=0.9,*/*;q=0.1", "user-agent": "commentkit-doctor" },
|
|
111
|
+
});
|
|
112
|
+
const location = response.headers.get("location");
|
|
113
|
+
if (response.status >= 300 && response.status < 400 && location) {
|
|
114
|
+
await response.body?.cancel().catch(() => undefined);
|
|
115
|
+
if (redirects >= MAX_REDIRECTS)
|
|
116
|
+
throw new CliError(`it redirects more than ${MAX_REDIRECTS} times`, "too_many_redirects");
|
|
117
|
+
url = siteUrl(new URL(location, url).href);
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
const { text, truncated } = await readCapped(response, maxBytes);
|
|
121
|
+
return { url, status: response.status, headers: response.headers, html: text, truncated, redirects };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/** Policies from header values and meta tags. A header value may hold several policies separated by commas. */
|
|
125
|
+
export function parseCsp(values) {
|
|
126
|
+
const policies = [];
|
|
127
|
+
for (const value of values) {
|
|
128
|
+
for (const text of value.split(",")) {
|
|
129
|
+
const policy = new Map();
|
|
130
|
+
for (const part of text.split(";")) {
|
|
131
|
+
const [name, ...sources] = part.trim().split(/\s+/).filter(Boolean);
|
|
132
|
+
if (!name || !/^[a-z-]+$/i.test(name))
|
|
133
|
+
continue;
|
|
134
|
+
const key = name.toLowerCase();
|
|
135
|
+
if (!policy.has(key))
|
|
136
|
+
policy.set(key, sources);
|
|
137
|
+
}
|
|
138
|
+
if (policy.size)
|
|
139
|
+
policies.push(policy);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return policies;
|
|
143
|
+
}
|
|
144
|
+
/** Content of every <meta http-equiv="Content-Security-Policy"> in the page. */
|
|
145
|
+
export function metaCsp(html) {
|
|
146
|
+
const found = [];
|
|
147
|
+
for (const [tag] of html.matchAll(/<meta\b[^>]*>/gi)) {
|
|
148
|
+
if (!/http-equiv\s*=\s*["']?content-security-policy["'\s>/]/i.test(tag))
|
|
149
|
+
continue;
|
|
150
|
+
const content = /\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(tag);
|
|
151
|
+
if (content)
|
|
152
|
+
found.push(decodeEntities(content[1] ?? content[2] ?? ""));
|
|
153
|
+
}
|
|
154
|
+
return found;
|
|
155
|
+
}
|
|
156
|
+
function decodeEntities(text) {
|
|
157
|
+
return text.replace(/&(#\d+|#x[0-9a-f]+|quot|apos|amp|lt|gt);/gi, (_, e) => {
|
|
158
|
+
const lower = e.toLowerCase();
|
|
159
|
+
if (lower.startsWith("#x"))
|
|
160
|
+
return String.fromCodePoint(parseInt(lower.slice(2), 16));
|
|
161
|
+
if (lower.startsWith("#"))
|
|
162
|
+
return String.fromCodePoint(Number(lower.slice(1)));
|
|
163
|
+
return { quot: '"', apos: "'", amp: "&", lt: "<", gt: ">" }[lower];
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
/** Which directive governs a request when the specific one is absent (CSP Level 3 fallback lists). */
|
|
167
|
+
const FALLBACK = {
|
|
168
|
+
script: ["script-src-elem", "script-src", "default-src"],
|
|
169
|
+
connect: ["connect-src", "default-src"],
|
|
170
|
+
img: ["img-src", "default-src"],
|
|
171
|
+
};
|
|
172
|
+
const DEFAULT_PORT = { "http:": "80", "https:": "443", "ws:": "80", "wss:": "443" };
|
|
173
|
+
const portOf = (url) => url.port || DEFAULT_PORT[url.protocol] || "";
|
|
174
|
+
/**
|
|
175
|
+
* Scheme matching from CSP3 ("scheme-part match"): http: also allows https:, ws: allows wss:, and
|
|
176
|
+
* secure web sockets are allowed by the matching http(s) scheme (browsers treat https: as allowing wss:).
|
|
177
|
+
*/
|
|
178
|
+
function schemeMatches(source, target) {
|
|
179
|
+
if (source === target)
|
|
180
|
+
return true;
|
|
181
|
+
if (source === "http:")
|
|
182
|
+
return target === "https:" || target === "ws:" || target === "wss:";
|
|
183
|
+
if (source === "https:")
|
|
184
|
+
return target === "wss:";
|
|
185
|
+
if (source === "ws:")
|
|
186
|
+
return target === "wss:";
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
/** Does one source expression allow `url` on a page at `page`? Keywords other than 'self' and * never match a URL. */
|
|
190
|
+
export function sourceMatches(source, url, page) {
|
|
191
|
+
const s = source.toLowerCase();
|
|
192
|
+
if (s === "*")
|
|
193
|
+
return ["http:", "https:", "ws:", "wss:"].includes(url.protocol);
|
|
194
|
+
if (s === "'self'")
|
|
195
|
+
return url.hostname === page.hostname && schemeMatches(page.protocol, url.protocol) && (portOf(url) === portOf(page) || (!url.port && !page.port));
|
|
196
|
+
if (s.startsWith("'"))
|
|
197
|
+
return false;
|
|
198
|
+
if (/^[a-z][a-z0-9+.-]*:$/.test(s))
|
|
199
|
+
return schemeMatches(s, url.protocol);
|
|
200
|
+
const m = /^(?:([a-z][a-z0-9+.-]*):\/\/)?(\*|(?:\*\.)?[a-z0-9_-]+(?:\.[a-z0-9_-]+)*)(?::(\*|\d+))?(\/[^?#]*)?$/.exec(s);
|
|
201
|
+
if (!m)
|
|
202
|
+
return false;
|
|
203
|
+
const [, scheme, host, port, path] = m;
|
|
204
|
+
if (!schemeMatches(scheme ? `${scheme}:` : page.protocol, url.protocol))
|
|
205
|
+
return false;
|
|
206
|
+
const target = url.hostname.toLowerCase();
|
|
207
|
+
if (host === "*") {
|
|
208
|
+
// A lone "*" with a scheme (https://*) matches any host.
|
|
209
|
+
}
|
|
210
|
+
else if (host.startsWith("*.")) {
|
|
211
|
+
if (!target.endsWith(host.slice(1)))
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
else if (host !== target)
|
|
215
|
+
return false;
|
|
216
|
+
if (port === "*") {
|
|
217
|
+
// any port
|
|
218
|
+
}
|
|
219
|
+
else if (port) {
|
|
220
|
+
if (port !== portOf(url))
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
else if (url.port && url.port !== DEFAULT_PORT[url.protocol])
|
|
224
|
+
return false;
|
|
225
|
+
if (path && path !== "/")
|
|
226
|
+
return path.endsWith("/") ? url.pathname.startsWith(path) : url.pathname === path;
|
|
227
|
+
return true;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Is `target` allowed by every policy (all of a page's policies are enforced together)? For the
|
|
231
|
+
* loader script, `nonce` is the nonce attribute on its tag. Without 'strict-dynamic' the loader's
|
|
232
|
+
* origin must be allowed by host anyway: the loader then imports the widget from the same place.
|
|
233
|
+
*/
|
|
234
|
+
export function cspAllows(policies, kind, target, pageUrl, nonce) {
|
|
235
|
+
const url = new URL(target);
|
|
236
|
+
const page = new URL(pageUrl);
|
|
237
|
+
for (const policy of policies) {
|
|
238
|
+
const directive = FALLBACK[kind].find((d) => policy.has(d));
|
|
239
|
+
if (!directive)
|
|
240
|
+
continue;
|
|
241
|
+
const sources = policy.get(directive);
|
|
242
|
+
if (kind === "script" && sources.some((s) => s.toLowerCase() === "'strict-dynamic'")) {
|
|
243
|
+
const nonces = sources.filter((s) => /^'nonce-[^']+'$/i.test(s)).map((s) => s.slice(7, -1));
|
|
244
|
+
if (!nonce || !nonces.includes(nonce))
|
|
245
|
+
return { allowed: false, directive, needsNonce: true };
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
if (!sources.some((s) => sourceMatches(s, url, page)))
|
|
249
|
+
return { allowed: false, directive, sources };
|
|
250
|
+
}
|
|
251
|
+
return { allowed: true, directive: null };
|
|
252
|
+
}
|
|
253
|
+
/** The directive for each kind that, once set, takes over from default-src for it alone. */
|
|
254
|
+
const SPECIFIC = { script: "script-src", connect: "connect-src", img: "img-src" };
|
|
255
|
+
/**
|
|
256
|
+
* What to change when `v` blocks `origin`. When only default-src decides, adding the host there would open it
|
|
257
|
+
* to every kind of request; the specific directive is the narrow fix, and it must repeat what default-src
|
|
258
|
+
* allows today, as a set directive replaces default-src for that kind.
|
|
259
|
+
*/
|
|
260
|
+
export function cspFix(v, kind, origin, where) {
|
|
261
|
+
if (v.directive !== "default-src")
|
|
262
|
+
return `Add ${origin} to ${v.directive} in ${where}.`;
|
|
263
|
+
const specific = SPECIFIC[kind];
|
|
264
|
+
const keep = (v.sources ?? []).filter((s) => s.toLowerCase() !== "'none'");
|
|
265
|
+
return `Add ${kind === "img" ? "an" : "a"} ${specific} directive to ${where}: ${[specific, ...keep, origin].join(" ")} (only default-src restricts this now; leave default-src as it is).`;
|
|
266
|
+
}
|
|
267
|
+
/** The name of the SDK's one Trusted Types policy (vite.config.ts, screenshot capture). */
|
|
268
|
+
export const TRUSTED_TYPES_POLICY = "commentkit-capture";
|
|
269
|
+
/**
|
|
270
|
+
* Whether the page's `trusted-types` directives let the SDK create its policy: each one that is set must name
|
|
271
|
+
* it or allow any name (`*`). `'allow-duplicates'` only lets a listed name be created twice; it allows no
|
|
272
|
+
* other name. Without a `trusted-types` directive any name may be created.
|
|
273
|
+
*/
|
|
274
|
+
export function trustedTypesAllowed(policies) {
|
|
275
|
+
for (const policy of policies) {
|
|
276
|
+
const sources = policy.get("trusted-types");
|
|
277
|
+
if (!sources)
|
|
278
|
+
continue;
|
|
279
|
+
if (!sources.some((s) => s === "*" || s === TRUSTED_TYPES_POLICY))
|
|
280
|
+
return { allowed: false, sources };
|
|
281
|
+
}
|
|
282
|
+
return { allowed: true, sources: null };
|
|
283
|
+
}
|
|
284
|
+
// ---------------------------------------------------------------------------------------------
|
|
285
|
+
// What the page's HTML says
|
|
286
|
+
/** The CDN loader tag: /cdn/v1/loader.js or a pinned /cdn/<version>/loader.js. */
|
|
287
|
+
const LOADER_TAG = /<script\b[^>]*\bsrc\s*=\s*["']?[^"'\s>]*\/cdn\/[^"'\s>/]+\/loader\.js[^>]*>/gi;
|
|
288
|
+
function attr(tag, name) {
|
|
289
|
+
const m = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`, "i").exec(tag);
|
|
290
|
+
return m ? decodeEntities(m[1] ?? m[2] ?? m[3] ?? "") : null;
|
|
291
|
+
}
|
|
292
|
+
export function findSdk(html, pageUrl) {
|
|
293
|
+
let loader = null;
|
|
294
|
+
for (const [tag] of html.matchAll(LOADER_TAG)) {
|
|
295
|
+
const raw = attr(tag, "src");
|
|
296
|
+
if (!raw)
|
|
297
|
+
continue;
|
|
298
|
+
let src;
|
|
299
|
+
try {
|
|
300
|
+
src = new URL(raw, pageUrl);
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
// Tag managers rebuild the tag with its address only, so loader.js?project=pk_… counts too (src/loader.ts).
|
|
306
|
+
const key = attr(tag, "data-project") ?? src.searchParams.get("project");
|
|
307
|
+
loader = { src: src.href, key: key || null, nonce: attr(tag, "nonce") };
|
|
308
|
+
break;
|
|
309
|
+
}
|
|
310
|
+
const markers = [];
|
|
311
|
+
if (/data-commentkit-host/.test(html))
|
|
312
|
+
markers.push("the widget's container");
|
|
313
|
+
if (html.includes(SDK))
|
|
314
|
+
markers.push(`the ${SDK} package name`);
|
|
315
|
+
const key = /\bpk_(?:live|test)_[a-z0-9]{20,40}\b/.exec(html)?.[0] ?? null;
|
|
316
|
+
if (!loader && key)
|
|
317
|
+
markers.push("your project key");
|
|
318
|
+
if (/\bdata-ck-src\s*=/.test(html))
|
|
319
|
+
markers.push("source locations from the build plugin");
|
|
320
|
+
return { loader, markers, key: loader ? null : key };
|
|
321
|
+
}
|
|
322
|
+
function readJson(file) {
|
|
323
|
+
try {
|
|
324
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
325
|
+
return parsed && typeof parsed === "object" ? parsed : null;
|
|
326
|
+
}
|
|
327
|
+
catch {
|
|
328
|
+
return null;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
/** KEY=value lines of an env file (quotes and `export` allowed). */
|
|
332
|
+
export function envValue(text, name) {
|
|
333
|
+
const m = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=\\s*(.*)$`, "m").exec(text);
|
|
334
|
+
if (!m)
|
|
335
|
+
return null;
|
|
336
|
+
return m[1].trim().replace(/\s+#.*$/, "").replace(/^(["'])(.*)\1$/, "$2");
|
|
337
|
+
}
|
|
338
|
+
function projectSetup(cwd, flagKey, env) {
|
|
339
|
+
const checks = [];
|
|
340
|
+
const pkg = readJson(join(cwd, "package.json"));
|
|
341
|
+
const htmlFiles = ["index.html", "public/index.html"].filter((f) => existsSync(join(cwd, f)));
|
|
342
|
+
const appFound = Boolean(pkg) || htmlFiles.length > 0;
|
|
343
|
+
// The same framework and entry-file detection init uses; plan() only reads files.
|
|
344
|
+
const p = plan(cwd, PLAN_KEY);
|
|
345
|
+
const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
|
|
346
|
+
const installed = readJson(join(cwd, "node_modules", SDK, "package.json"));
|
|
347
|
+
const installedVersion = typeof installed?.version === "string" ? clean(installed.version, 40) : null;
|
|
348
|
+
const html = htmlFiles.map((f) => ({ file: f, text: readFileSync(join(cwd, f), "utf8") }));
|
|
349
|
+
const htmlLoader = html.map((h) => ({ file: h.file, sdk: findSdk(h.text, "http://localhost/") })).find((h) => h.sdk.loader);
|
|
350
|
+
const bundled = Boolean(deps[SDK]);
|
|
351
|
+
const add = p.install[0]?.join(" ") ?? `npm install ${SDK}`;
|
|
352
|
+
if (!appFound) {
|
|
353
|
+
checks.push({ id: "setup.app", status: "info", message: "No package.json or index.html in this folder, so the project checks were skipped.", fix: `Run ${CLI} doctor in your app's folder to include them.` });
|
|
354
|
+
}
|
|
355
|
+
else if (bundled) {
|
|
356
|
+
checks.push(installedVersion
|
|
357
|
+
? { id: "setup.package", status: "pass", message: `${SDK} ${installedVersion} is installed (${p.label}).` }
|
|
358
|
+
: { id: "setup.package", status: "fail", message: `${SDK} is in package.json but not installed.`, fix: `Run your package manager's install (for example ${p.packageManager} install).` });
|
|
359
|
+
}
|
|
360
|
+
else if (htmlLoader) {
|
|
361
|
+
checks.push({ id: "setup.package", status: "pass", message: `The CommentKit script tag is in ${htmlLoader.file}.` });
|
|
362
|
+
}
|
|
363
|
+
else if (p.entry === "done") {
|
|
364
|
+
checks.push({ id: "setup.package", status: "pass", message: `The CommentKit script tag is in your ${p.label} app.` });
|
|
365
|
+
}
|
|
366
|
+
else {
|
|
367
|
+
checks.push({ id: "setup.package", status: "fail", message: `CommentKit is not installed in this ${p.label} app: no ${SDK} in package.json and no script tag.`, fix: p.framework === "html" ? `Run ${CLI} init, or add the script tag before </body> (https://commentkit.dev/docs).` : `Run ${CLI} init (or ${add}).` });
|
|
368
|
+
}
|
|
369
|
+
if (appFound && bundled) {
|
|
370
|
+
if (p.entry === "done")
|
|
371
|
+
checks.push({ id: "setup.widget", status: "pass", message: "The widget is added in your layout or entry file." });
|
|
372
|
+
else {
|
|
373
|
+
const where = p.entry ? p.entry.file : "your layout or entry file";
|
|
374
|
+
checks.push({ id: "setup.widget", status: "warn", message: `Could not find the widget in ${where}.`, fix: `If you call init() or render <CommentKit> somewhere else, ignore this; otherwise run ${CLI} init.` });
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
// The key: --key, then the env files init writes, then the environment, then the script tag.
|
|
378
|
+
let key = null;
|
|
379
|
+
let keySource = null;
|
|
380
|
+
let keyVar = null;
|
|
381
|
+
if (flagKey) {
|
|
382
|
+
key = flagKey;
|
|
383
|
+
keySource = "--key";
|
|
384
|
+
}
|
|
385
|
+
else {
|
|
386
|
+
const files = [...new Set([p.envFile, ".env.local", ".env", ".env.production", ".env.production.local", ".env.development"].filter(Boolean))];
|
|
387
|
+
const vars = [...new Set([p.envVar, ...KEY_VARS].filter(Boolean))];
|
|
388
|
+
outer: for (const file of files) {
|
|
389
|
+
if (!existsSync(join(cwd, file)))
|
|
390
|
+
continue;
|
|
391
|
+
const text = readFileSync(join(cwd, file), "utf8");
|
|
392
|
+
for (const name of vars) {
|
|
393
|
+
const value = envValue(text, name);
|
|
394
|
+
if (value) {
|
|
395
|
+
key = value;
|
|
396
|
+
keySource = `${file} (${name})`;
|
|
397
|
+
keyVar = name;
|
|
398
|
+
break outer;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
if (!key) {
|
|
403
|
+
const name = [p.envVar, ...KEY_VARS].find((n) => n && env[n]);
|
|
404
|
+
if (name) {
|
|
405
|
+
key = env[name];
|
|
406
|
+
keySource = `the environment variable ${name}`;
|
|
407
|
+
keyVar = name;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
if (!key && htmlLoader?.sdk.loader?.key) {
|
|
411
|
+
key = htmlLoader.sdk.loader.key;
|
|
412
|
+
keySource = htmlLoader.file;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
if (key && !PUBLISHABLE_KEY.test(key)) {
|
|
416
|
+
checks.push({ id: "setup.key", status: "fail", message: `The project key in ${keySource} is not a publishable key (it should look like pk_live_… or pk_test_…).`, fix: "Copy the key again from Setup in CommentKit." });
|
|
417
|
+
}
|
|
418
|
+
else if (key) {
|
|
419
|
+
checks.push({ id: "setup.key", status: "pass", message: `Project key ${maskKey(key)} found in ${keySource}.` });
|
|
420
|
+
if (keyVar && p.envVar && keyVar !== p.envVar && keyVar !== "COMMENTKIT_KEY") {
|
|
421
|
+
checks.push({ id: "setup.key-name", status: "warn", message: `${p.label} apps do not read ${keyVar}, so the widget gets no key.`, fix: `Rename it to ${p.envVar} in ${keySource.split(" ")[0]}.` });
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
else if (appFound) {
|
|
425
|
+
checks.push({ id: "setup.key", status: "fail", message: `No project key found${p.envFile ? ` in ${p.envFile}` : ""}${htmlFiles.length ? ` or ${htmlFiles[0]}` : ""}.`, fix: p.envVar ? `Run ${CLI} init, or add ${p.envVar}=pk_… to ${p.envFile} (the key is under Setup in CommentKit). If the key is written straight into your code, run ${CLI} doctor --key pk_… instead.` : `Run ${CLI} init, or put data-project="pk_…" on the script tag (the key is under Setup in CommentKit).` });
|
|
426
|
+
}
|
|
427
|
+
if (appFound && p.framework !== "html") {
|
|
428
|
+
const config = p.configFile ? readFileSync(join(cwd, p.configFile), "utf8") : "";
|
|
429
|
+
if (PLUGIN_IMPORT.test(config))
|
|
430
|
+
checks.push({ id: "setup.plugin", status: "pass", message: `The build plugin is set up in ${p.configFile}.` });
|
|
431
|
+
else
|
|
432
|
+
checks.push({ id: "setup.plugin", status: "info", message: "The build plugin is not set up. It is optional: it adds source file and line to feedback, so you and your coding agent land on the right code.", fix: `Run ${CLI} init to add it.` });
|
|
433
|
+
}
|
|
434
|
+
return { checks, key, keySource, installedVersion, bundled, appFound };
|
|
435
|
+
}
|
|
436
|
+
async function getJson(fetchFn, url, headers, timeoutMs) {
|
|
437
|
+
try {
|
|
438
|
+
const response = await fetchFn(url, { redirect: "error", credentials: "omit", signal: AbortSignal.timeout(timeoutMs), headers: { accept: "application/json", ...headers } });
|
|
439
|
+
const { text } = await readCapped(response, MAX_API_BYTES);
|
|
440
|
+
let json = {};
|
|
441
|
+
try {
|
|
442
|
+
const parsed = text ? JSON.parse(text) : {};
|
|
443
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
444
|
+
json = parsed;
|
|
445
|
+
}
|
|
446
|
+
catch {
|
|
447
|
+
// Not JSON (a proxy's error page): the status says enough.
|
|
448
|
+
}
|
|
449
|
+
return { status: response.status, json };
|
|
450
|
+
}
|
|
451
|
+
catch (error) {
|
|
452
|
+
return { error: reason(error) };
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* GET /widget/config. The API needs an Origin to find the website (no Origin answers 404, as for an
|
|
457
|
+
* unknown key), and localhost is always accepted, so the plain key check sends http://localhost.
|
|
458
|
+
* `sdk`: the installed SDK version, sent as the widget sends it (X-CommentKit-SDK), so a version CommentKit
|
|
459
|
+
* switched off answers `disabled_reason: version_blocked`. That answer comes before the key and website are
|
|
460
|
+
* checked, so the website check sends no version.
|
|
461
|
+
*/
|
|
462
|
+
async function widgetConfig(fetchFn, endpoint, key, origin, timeoutMs, sdk) {
|
|
463
|
+
return getJson(fetchFn, `${endpoint}/api/v1/widget/config?key=${encodeURIComponent(key)}`, { origin, ...(sdk ? { "x-commentkit-sdk": sdk } : {}) }, timeoutMs);
|
|
464
|
+
}
|
|
465
|
+
function unreachable(id, host, error) {
|
|
466
|
+
return { id, status: "fail", message: `Could not reach CommentKit at ${host} (${error}).`, fix: `Check your internet connection (or COMMENTKIT_ENDPOINT), then run ${CLI} doctor again.` };
|
|
467
|
+
}
|
|
468
|
+
function keyCheck(answer, key, host, sdk) {
|
|
469
|
+
if ("error" in answer)
|
|
470
|
+
return { check: unreachable("api.key", host, answer.error), config: null };
|
|
471
|
+
const { status, json } = answer;
|
|
472
|
+
if (status === 200) {
|
|
473
|
+
const config = json;
|
|
474
|
+
const name = clean(config.project?.name, 80) || "your project";
|
|
475
|
+
if (config.enabled === false && config.disabled_reason === "version_blocked")
|
|
476
|
+
return { config, check: { id: "api.key", status: "fail", message: `This SDK version${sdk ? ` (${clean(sdk, 40)})` : ""} has been switched off by CommentKit; update the package. Until then the widget stays hidden everywhere.`, fix: `npm install ${SDK}@latest, then deploy (sites with the /cdn/v1/ script tag get the fix by themselves).` } };
|
|
477
|
+
if (config.enabled === false)
|
|
478
|
+
return { config, check: { id: "api.key", status: "fail", message: `Feedback is paused for “${name}” (the kill switch is on), so the widget stays hidden everywhere.`, fix: "Turn feedback back on in the project's settings in CommentKit; it applies within a minute." } };
|
|
479
|
+
if (config.read_only === true)
|
|
480
|
+
return { config, check: { id: "api.key", status: "warn", message: `“${name}” is read-only: the widget shows existing feedback, but nobody can add new feedback (comments are turned off or the plan ended).`, fix: "Check the project's plan and settings in CommentKit." } };
|
|
481
|
+
return { config, check: { id: "api.key", status: "pass", message: `CommentKit knows the key ${maskKey(key)} (project “${name}”) and feedback is on.` } };
|
|
482
|
+
}
|
|
483
|
+
if (status === 404)
|
|
484
|
+
return { config: null, check: { id: "api.key", status: "fail", message: `CommentKit does not know the key ${maskKey(key)}.`, fix: "Copy the key again from Setup in CommentKit (pk_live_… for your live site, pk_test_… for staging)." } };
|
|
485
|
+
if (status === 429)
|
|
486
|
+
return { config: null, check: { id: "api.key", status: "warn", message: "CommentKit is getting too many requests from this network right now, so the key was not checked.", fix: `Run ${CLI} doctor again in a minute.` } };
|
|
487
|
+
return { config: null, check: { id: "api.key", status: "fail", message: `CommentKit answered HTTP ${status} when checking the key${json.detail ? `: ${clean(json.detail)}` : ""}.`, fix: `Run ${CLI} doctor again in a few minutes; if it keeps failing, contact CommentKit support.` } };
|
|
488
|
+
}
|
|
489
|
+
async function signedIn() {
|
|
490
|
+
try {
|
|
491
|
+
const project = await Project.connect();
|
|
492
|
+
const info = await project.request("");
|
|
493
|
+
return { name: info.data.name, keys: [info.data.publishable_keys?.live, info.data.publishable_keys?.test].filter((k) => typeof k === "string") };
|
|
494
|
+
}
|
|
495
|
+
catch (error) {
|
|
496
|
+
if (error instanceof CliError && error.code === "signed_out")
|
|
497
|
+
return null;
|
|
498
|
+
throw error;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
/** -1, 0 or 1 for two x.y.z versions (a prerelease sorts before its release). */
|
|
502
|
+
export function compareVersions(a, b) {
|
|
503
|
+
const parse = (v) => {
|
|
504
|
+
const [core, pre] = v.replace(/^v/, "").split("-", 2);
|
|
505
|
+
return { nums: core.split(".").map((n) => Number(n) || 0), pre: pre ?? null };
|
|
506
|
+
};
|
|
507
|
+
const x = parse(a);
|
|
508
|
+
const y = parse(b);
|
|
509
|
+
for (let i = 0; i < 3; i++) {
|
|
510
|
+
const d = (x.nums[i] ?? 0) - (y.nums[i] ?? 0);
|
|
511
|
+
if (d)
|
|
512
|
+
return Math.sign(d);
|
|
513
|
+
}
|
|
514
|
+
if (x.pre === y.pre)
|
|
515
|
+
return 0;
|
|
516
|
+
if (x.pre === null)
|
|
517
|
+
return 1;
|
|
518
|
+
if (y.pre === null)
|
|
519
|
+
return -1;
|
|
520
|
+
return x.pre < y.pre ? -1 : 1;
|
|
521
|
+
}
|
|
522
|
+
// ---------------------------------------------------------------------------------------------
|
|
523
|
+
// The run
|
|
524
|
+
export async function doctor(options, deps = {}) {
|
|
525
|
+
const env = deps.env ?? process.env;
|
|
526
|
+
const fetchFn = deps.fetch ?? ((url, init) => fetch(url, init));
|
|
527
|
+
const timeoutMs = deps.timeoutMs ?? TIMEOUT_MS;
|
|
528
|
+
const endpoint = endpointFrom(env.COMMENTKIT_ENDPOINT || undefined);
|
|
529
|
+
const ck = new URL(endpoint);
|
|
530
|
+
const host = ck.host;
|
|
531
|
+
// Refused before anything else happens: a bad address never reaches the network.
|
|
532
|
+
const site = options.url ? siteUrl(options.url) : null;
|
|
533
|
+
if (options.key !== undefined && !PUBLISHABLE_KEY.test(options.key))
|
|
534
|
+
throw new CliError("--key is not a publishable key (pk_live_… or pk_test_…).");
|
|
535
|
+
const checks = [];
|
|
536
|
+
const setup = projectSetup(options.cwd, options.key, env);
|
|
537
|
+
checks.push(...setup.checks);
|
|
538
|
+
// The page first: its script tag may carry the key when this folder has none.
|
|
539
|
+
let page = null;
|
|
540
|
+
let pageError = null;
|
|
541
|
+
if (site) {
|
|
542
|
+
try {
|
|
543
|
+
page = await fetchPage(site, fetchFn, { timeoutMs, maxBytes: deps.maxBytes ?? MAX_PAGE_BYTES });
|
|
544
|
+
}
|
|
545
|
+
catch (error) {
|
|
546
|
+
pageError = error instanceof CliError ? error.message : reason(error);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
const sdk = page ? findSdk(page.html, page.url.href) : null;
|
|
550
|
+
const pageKey = sdk?.loader?.key ?? sdk?.key ?? null;
|
|
551
|
+
const key = setup.key && PUBLISHABLE_KEY.test(setup.key) ? setup.key : pageKey && PUBLISHABLE_KEY.test(pageKey) ? pageKey : null;
|
|
552
|
+
if (!setup.appFound && !key)
|
|
553
|
+
checks.push({ id: "setup.key", status: "fail", message: "No project key to check: none in this folder" + (site ? " or on the page." : "."), fix: "Run doctor in your app's folder, or pass --key pk_… (the key is under Setup in CommentKit)." });
|
|
554
|
+
// 2. Sign-in (optional for doctor).
|
|
555
|
+
try {
|
|
556
|
+
const project = await (deps.project ?? signedIn)();
|
|
557
|
+
if (!project) {
|
|
558
|
+
checks.push({ id: "signin", status: "info", message: "The CLI is not signed in, so the check that the key belongs to your project was skipped.", fix: `Run ${CLI} login to include it.` });
|
|
559
|
+
}
|
|
560
|
+
else {
|
|
561
|
+
checks.push({ id: "signin", status: "pass", message: `The CLI is signed in to “${clean(project.name, 80)}”.` });
|
|
562
|
+
if (key && project.keys.length && !project.keys.includes(key)) {
|
|
563
|
+
checks.push({ id: "signin.key", status: "warn", message: `The key ${maskKey(key)} is not one of “${clean(project.name, 80)}”'s keys.`, fix: "If this app belongs to another project, ignore this; otherwise copy the key from Setup in CommentKit." });
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
catch (error) {
|
|
568
|
+
checks.push({ id: "signin", status: "warn", message: `Could not check the CLI's sign-in (${clean(error instanceof Error ? error.message : String(error), 160)}).`, fix: `Run ${CLI} status for details.` });
|
|
569
|
+
}
|
|
570
|
+
// 3. The key against the API.
|
|
571
|
+
let config = null;
|
|
572
|
+
let reachable = true;
|
|
573
|
+
if (key) {
|
|
574
|
+
const answer = await widgetConfig(fetchFn, endpoint, key, "http://localhost", timeoutMs, setup.installedVersion);
|
|
575
|
+
reachable = !("error" in answer);
|
|
576
|
+
const result = keyCheck(answer, key, host, setup.installedVersion);
|
|
577
|
+
config = result.config;
|
|
578
|
+
checks.push(result.check);
|
|
579
|
+
}
|
|
580
|
+
else if (setup.appFound) {
|
|
581
|
+
checks.push({ id: "api.key", status: "info", message: "Skipped the check with CommentKit: there is no valid project key." });
|
|
582
|
+
}
|
|
583
|
+
// 4. The website.
|
|
584
|
+
if (site) {
|
|
585
|
+
const shown = clean(safeUrl(site.href), 200);
|
|
586
|
+
// (a) Is the website on the project's allowed list? Same request, with the site's Origin.
|
|
587
|
+
const originKey = pageKey && PUBLISHABLE_KEY.test(pageKey) ? pageKey : key;
|
|
588
|
+
if (originKey && reachable) {
|
|
589
|
+
const origin = site.origin;
|
|
590
|
+
if (isLocalHost(site.hostname)) {
|
|
591
|
+
checks.push({ id: "site.origin", status: "pass", message: `${origin} is local: CommentKit always allows it for your team.` });
|
|
592
|
+
}
|
|
593
|
+
else {
|
|
594
|
+
const answer = await widgetConfig(fetchFn, endpoint, originKey, origin, timeoutMs);
|
|
595
|
+
if ("error" in answer)
|
|
596
|
+
checks.push(unreachable("site.origin", host, answer.error));
|
|
597
|
+
else if (answer.status === 403 && answer.json.code === "origin_not_allowed")
|
|
598
|
+
checks.push({ id: "site.origin", status: "fail", message: `${origin} is not on the project's list of allowed websites, so the widget will not load there.`, fix: "Add it in CommentKit under Project → Setup, step 1 (a project admin can)." });
|
|
599
|
+
else if (answer.status === 200) {
|
|
600
|
+
const environment = clean(answer.json.environment, 30);
|
|
601
|
+
checks.push({ id: "site.origin", status: "pass", message: `${origin} is on the project's allowed websites${environment ? ` (${environment})` : ""}.` });
|
|
602
|
+
config ??= answer.json;
|
|
603
|
+
}
|
|
604
|
+
else if (answer.status === 404)
|
|
605
|
+
checks.push({ id: "site.origin", status: "fail", message: `CommentKit does not know the key ${maskKey(originKey)} used on the page.`, fix: "Copy the key again from Setup in CommentKit." });
|
|
606
|
+
else
|
|
607
|
+
checks.push({ id: "site.origin", status: "warn", message: `Could not check whether ${origin} is allowed (HTTP ${answer.status}).`, fix: `Run ${CLI} doctor again in a minute.` });
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
// (d) Plain http on a real host: the page loads, but signing in to comment needs https.
|
|
611
|
+
if (site.protocol === "http:" && !isLocalHost(site.hostname)) {
|
|
612
|
+
checks.push({ id: "site.https", status: "warn", message: `${site.origin} uses plain http: reviewers cannot sign in to comment there.`, fix: "Serve the site over https." });
|
|
613
|
+
}
|
|
614
|
+
if (!page) {
|
|
615
|
+
checks.push({ id: "site.page", status: "fail", message: `Could not open ${shown} (${clean(pageError, 120)}).`, fix: `Check the address and that the site is up, then run ${CLI} doctor again.` });
|
|
616
|
+
}
|
|
617
|
+
else {
|
|
618
|
+
if (page.status >= 400)
|
|
619
|
+
checks.push({ id: "site.page", status: "warn", message: `${shown} answered HTTP ${page.status}; the checks below use that response.`, fix: "Check the address, or give the page where the widget should appear." });
|
|
620
|
+
if (page.truncated)
|
|
621
|
+
checks.push({ id: "site.size", status: "info", message: `The page is larger than ${Math.round((deps.maxBytes ?? MAX_PAGE_BYTES) / 1024 / 1024) || 1} MB; only the start was checked.` });
|
|
622
|
+
// (b) The loader tag, or signs of the bundled SDK.
|
|
623
|
+
if (sdk.loader) {
|
|
624
|
+
const loaderKey = sdk.loader.key;
|
|
625
|
+
if (!loaderKey)
|
|
626
|
+
checks.push({ id: "site.sdk", status: "fail", message: "The page has the CommentKit script tag, but without a project key.", fix: 'Add data-project="pk_…" to the script tag (the key is under Setup in CommentKit).' });
|
|
627
|
+
else if (!PUBLISHABLE_KEY.test(loaderKey))
|
|
628
|
+
checks.push({ id: "site.sdk", status: "fail", message: "The CommentKit script tag on the page has a key that is not a publishable key.", fix: "Copy the key again from Setup in CommentKit into data-project." });
|
|
629
|
+
else {
|
|
630
|
+
checks.push({ id: "site.sdk", status: "pass", message: `The page has the CommentKit script tag (key ${maskKey(loaderKey)}).` });
|
|
631
|
+
if (setup.key && PUBLISHABLE_KEY.test(setup.key) && setup.key !== loaderKey)
|
|
632
|
+
checks.push({ id: "site.key-match", status: "warn", message: `The page uses the key ${maskKey(loaderKey)}, this folder ${maskKey(setup.key)}.`, fix: "If the site is deployed from this folder, deploy again or use the same key." });
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
else if (sdk.markers.length) {
|
|
636
|
+
checks.push({ id: "site.sdk", status: "pass", message: `The page shows signs of the bundled SDK (${sdk.markers.join(", ")}).` });
|
|
637
|
+
}
|
|
638
|
+
else {
|
|
639
|
+
checks.push({ id: "site.sdk", status: "warn", message: "CommentKit is not in the page's HTML. An app that renders in the browser may add it later, so this is not certain.", fix: `Open the page and look for the Comment button; if it is missing, check that the widget is added to the page's layout (${CLI} init).` });
|
|
640
|
+
}
|
|
641
|
+
// (c) Content Security Policy: response header(s) and <meta http-equiv>.
|
|
642
|
+
const headerCsp = page.headers.get("content-security-policy");
|
|
643
|
+
const meta = metaCsp(page.html);
|
|
644
|
+
const policies = parseCsp([...(headerCsp ? [headerCsp] : []), ...meta]);
|
|
645
|
+
if (!policies.length) {
|
|
646
|
+
checks.push({ id: "site.csp", status: "pass", message: "The page has no Content Security Policy, so nothing blocks CommentKit." });
|
|
647
|
+
}
|
|
648
|
+
else {
|
|
649
|
+
const where = headerCsp && meta.length ? "the Content-Security-Policy header and <meta> tag" : headerCsp ? "the Content-Security-Policy header" : "the <meta http-equiv=\"Content-Security-Policy\"> tag";
|
|
650
|
+
const pageUrl = page.url.href;
|
|
651
|
+
// The loader comes from the CDN and imports the widget from the same folder (src/loader.ts).
|
|
652
|
+
// A bundled SDK is the site's own code, so script-src only matters for the script tag.
|
|
653
|
+
if (sdk.loader || !setup.bundled) {
|
|
654
|
+
const loaderSrc = sdk.loader?.src ?? `${endpoint}/cdn/v1/loader.js`;
|
|
655
|
+
const origin = new URL(loaderSrc).origin;
|
|
656
|
+
const v = cspAllows(policies, "script", loaderSrc, pageUrl, sdk.loader?.nonce ?? undefined);
|
|
657
|
+
if (v.allowed)
|
|
658
|
+
checks.push({ id: "site.csp.script", status: "pass", message: `The page's CSP lets the CommentKit script load from ${origin}.` });
|
|
659
|
+
else if (v.needsNonce)
|
|
660
|
+
checks.push({ id: "site.csp.script", status: "fail", message: `The page's CSP (${v.directive} with 'strict-dynamic') only runs scripts that carry its nonce, and the CommentKit script tag does not.`, fix: 'Add your page\'s nonce to the tag: <script nonce="…" src="…/loader.js" …>.' });
|
|
661
|
+
else
|
|
662
|
+
checks.push({ id: "site.csp.script", status: "fail", message: `The page's CSP blocks the CommentKit script: ${v.directive} does not allow ${origin}.`, fix: cspFix(v, "script", origin, where) });
|
|
663
|
+
}
|
|
664
|
+
// The widget calls the API on the CommentKit server (src/core/client.ts, endpoint).
|
|
665
|
+
const api = cspAllows(policies, "connect", `${endpoint}/api/v1/widget/config`, pageUrl);
|
|
666
|
+
if (api.allowed)
|
|
667
|
+
checks.push({ id: "site.csp.connect", status: "pass", message: `The page's CSP lets the widget talk to ${ck.origin}.` });
|
|
668
|
+
else
|
|
669
|
+
checks.push({ id: "site.csp.connect", status: "fail", message: `The page's CSP blocks the widget's requests: ${api.directive} does not allow ${ck.origin}.`, fix: cspFix(api, "connect", ck.origin, where) });
|
|
670
|
+
// Images: emoji are <img src="<endpoint>/cdn/emoji/<code>.svg"> (src/ui/format.tsx Emoji, base set in
|
|
671
|
+
// src/ui/mount.tsx from client.assets in src/core/client.ts); screenshot thumbnails are <img> from
|
|
672
|
+
// thumbnail_url (src/ui/ThreadCard.tsx). A blocked emoji falls back to the device's own, so a warning.
|
|
673
|
+
const img = cspAllows(policies, "img", `${endpoint}/cdn/emoji/1f44d.svg`, pageUrl);
|
|
674
|
+
if (img.allowed)
|
|
675
|
+
checks.push({ id: "site.csp.img", status: "pass", message: `The page's CSP lets screenshots and emoji load from ${ck.origin}.` });
|
|
676
|
+
else
|
|
677
|
+
checks.push({ id: "site.csp.img", status: "warn", message: `The page's CSP blocks images from ${ck.origin} (${img.directive}): screenshots and emoji will not show in the widget.`, fix: cspFix(img, "img", ck.origin, where) });
|
|
678
|
+
// Live updates: a web socket to the realtime host from /widget/config (src/core/realtime.ts).
|
|
679
|
+
const rt = config?.realtime;
|
|
680
|
+
if (rt && typeof rt.host === "string" && /^[a-z0-9.-]+$/i.test(rt.host)) {
|
|
681
|
+
const scheme = rt.scheme === "http" ? "ws" : "wss";
|
|
682
|
+
const port = typeof rt.port === "number" && rt.port !== (scheme === "wss" ? 443 : 80) ? `:${rt.port}` : "";
|
|
683
|
+
const socket = `${scheme}://${rt.host}${port}`;
|
|
684
|
+
const v = cspAllows(policies, "connect", `${socket}/app/x`, pageUrl);
|
|
685
|
+
if (v.allowed)
|
|
686
|
+
checks.push({ id: "site.csp.realtime", status: "pass", message: `The page's CSP allows live updates (${socket}).` });
|
|
687
|
+
else
|
|
688
|
+
checks.push({ id: "site.csp.realtime", status: "warn", message: `The page's CSP blocks live updates (${socket}); the widget still works, new feedback shows after a reload.`, fix: cspFix(v, "connect", socket, where) });
|
|
689
|
+
}
|
|
690
|
+
// Trusted Types: screenshots write one fixed string through the SDK's own policy (vite.config.ts), which
|
|
691
|
+
// the page's trusted-types directive must let it create. Without require-trusted-types-for nothing needs it.
|
|
692
|
+
if (policies.some((p) => p.has("require-trusted-types-for"))) {
|
|
693
|
+
const tt = trustedTypesAllowed(policies);
|
|
694
|
+
if (tt.allowed)
|
|
695
|
+
checks.push({ id: "site.csp.trusted-types", status: "pass", message: `The page requires Trusted Types; CommentKit supports that (it never writes HTML into the page, and its screenshots use one policy, ${TRUSTED_TYPES_POLICY}, that the page allows).` });
|
|
696
|
+
else
|
|
697
|
+
checks.push({ id: "site.csp.trusted-types", status: "warn", message: `The page requires Trusted Types and its trusted-types directive does not allow CommentKit's policy (${TRUSTED_TYPES_POLICY}): comments can be written, but screenshots will not be taken.`, fix: `Add ${TRUSTED_TYPES_POLICY} to trusted-types in ${where}: trusted-types ${[...tt.sources.filter((s) => s.toLowerCase() !== "'none'"), TRUSTED_TYPES_POLICY].join(" ")}` });
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
// Who sees the button on a real website: the widget stays hidden for visitors (src/activation.ts).
|
|
702
|
+
if (!isDevHost(site.hostname)) {
|
|
703
|
+
checks.push({ id: "site.visibility", status: "info", message: `On ${site.host} the Comment button is hidden from ordinary visitors. It appears after opening a share link, for signed-in reviewers, or after pressing Cmd+Shift+K (Ctrl+Shift+K on Windows).` });
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
// 5. Version: GET /sdk/latest is the newest stable SDK (public, no key needed). A canary rolling out is not
|
|
707
|
+
// offered: only what every site gets once it is stable.
|
|
708
|
+
if (reachable && setup.installedVersion) {
|
|
709
|
+
const answer = await getJson(fetchFn, `${endpoint}/api/v1/sdk/latest`, {}, timeoutMs);
|
|
710
|
+
const version = "error" in answer || answer.status !== 200 ? null : answer.json.version;
|
|
711
|
+
if (typeof version === "string" && /^\d+\.\d+\.\d+$/.test(version) && compareVersions(setup.installedVersion, version) < 0) {
|
|
712
|
+
checks.push({ id: "version", status: "info", message: `CommentKit ${version} is available; this app has ${setup.installedVersion}.`, fix: `Update when convenient: npm install ${SDK}@${version} (or your package manager's equivalent), then deploy.` });
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
return { ok: !checks.some((c) => c.status === "fail"), endpoint, url: site ? safeUrl(site.href) : null, checks };
|
|
716
|
+
}
|
|
717
|
+
/** The terminal report: one line per check, then a summary. */
|
|
718
|
+
export function render(result) {
|
|
719
|
+
const lines = [`CommentKit doctor (${result.endpoint})`, ""];
|
|
720
|
+
for (const c of result.checks)
|
|
721
|
+
lines.push(`${MARK[c.status]} ${c.message}${c.fix && c.status !== "pass" ? ` ${c.fix}` : ""}`);
|
|
722
|
+
const failed = result.checks.filter((c) => c.status === "fail").length;
|
|
723
|
+
lines.push("", failed ? `${failed} problem${failed === 1 ? "" : "s"} found. Fix the ✗ lines, then run ${CLI} doctor again.` : "Everything CommentKit needs is in place.");
|
|
724
|
+
return lines;
|
|
725
|
+
}
|