@kometolabs/mcp-analytics-receiver 0.0.0-stage → 0.1.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.
@@ -0,0 +1,216 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { pathToFileURL } from 'node:url';
3
+
4
+ const dashboardUID = 'mcp-analytics-overview';
5
+ const organizationId = 1;
6
+
7
+ // Only our own messages leave this script. Grafana responses and transport errors
8
+ // can contain credentials or request data and must never become log messages.
9
+ export class ViewerSetupError extends Error {}
10
+
11
+ function fail(message) { throw new ViewerSetupError(message); }
12
+
13
+ function baseURL(value, name) {
14
+ let url;
15
+ try { url = new URL(value); } catch { fail(`${name} must be an HTTP or HTTPS URL.`); }
16
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
17
+ fail(`${name} must be an HTTP or HTTPS URL without credentials, query, or fragment.`);
18
+ }
19
+ return url.href.replace(/\/+$/, '');
20
+ }
21
+
22
+ function login(value, name) {
23
+ if (typeof value !== 'string' || !value.trim() || value !== value.trim() || /[:\x00-\x1f\x7f]/.test(value)) {
24
+ fail(`${name} must be a nonempty login without surrounding whitespace, colons, or control characters.`);
25
+ }
26
+ return value;
27
+ }
28
+
29
+ function password(value, name) {
30
+ if (typeof value !== 'string' || !value.length) fail(`${name} is required.`);
31
+ return value;
32
+ }
33
+
34
+ function duration(value, fallback, name) {
35
+ const result = value ?? fallback;
36
+ if (!Number.isSafeInteger(result) || result <= 0) fail(`${name} must be a positive integer.`);
37
+ return result;
38
+ }
39
+
40
+ function validateConfig(input) {
41
+ const config = {
42
+ url: baseURL(input.url ?? 'http://grafana:3000', 'GRAFANA_URL'),
43
+ publicUrl: baseURL(input.publicUrl ?? 'http://localhost:3100', 'GRAFANA_PUBLIC_URL'),
44
+ adminUser: login(input.adminUser ?? 'admin', 'GRAFANA_ADMIN_USER'),
45
+ adminPassword: password(input.adminPassword, 'GRAFANA_ADMIN_PASSWORD'),
46
+ viewerUser: login(input.viewerUser ?? 'viewer', 'GRAFANA_VIEWER_USER'),
47
+ viewerPassword: password(input.viewerPassword ?? 'local-demo-viewer', 'GRAFANA_VIEWER_PASSWORD'),
48
+ readinessTimeoutMs: duration(input.readinessTimeoutMs, 120_000, 'readinessTimeoutMs'),
49
+ requestTimeoutMs: duration(input.requestTimeoutMs, 5_000, 'requestTimeoutMs'),
50
+ pollIntervalMs: duration(input.pollIntervalMs, 1_000, 'pollIntervalMs'),
51
+ };
52
+ if (config.adminUser.toLowerCase() === config.viewerUser.toLowerCase()) {
53
+ fail('GRAFANA_VIEWER_USER must be different from GRAFANA_ADMIN_USER.');
54
+ }
55
+ return config;
56
+ }
57
+
58
+ export function viewerURLs(publicUrl = 'http://localhost:3100') {
59
+ const base = baseURL(publicUrl, 'GRAFANA_PUBLIC_URL');
60
+ const dashboard = new URL(`${base}/d/${dashboardUID}/mcp-analytics?kiosk=1`);
61
+ const login = new URL(`${base}/login`);
62
+ login.searchParams.set('redirectTo', `${dashboard.pathname}${dashboard.search}`);
63
+ return { dashboardUrl: dashboard.href, loginUrl: login.href };
64
+ }
65
+
66
+ export function configFromEnv(env = process.env) {
67
+ return {
68
+ url: env.GRAFANA_URL,
69
+ publicUrl: env.GRAFANA_PUBLIC_URL,
70
+ adminUser: env.GRAFANA_ADMIN_USER,
71
+ adminPassword: env.GRAFANA_ADMIN_PASSWORD,
72
+ viewerUser: env.GRAFANA_VIEWER_USER,
73
+ viewerPassword: env.GRAFANA_VIEWER_PASSWORD,
74
+ };
75
+ }
76
+
77
+ function userId(value) {
78
+ const id = Number(value);
79
+ if (!Number.isSafeInteger(id) || id <= 0) fail('Grafana returned an invalid user identity.');
80
+ return id;
81
+ }
82
+
83
+ function assertManagedViewer(user, viewerUser, expectedId) {
84
+ const id = userId(user?.id);
85
+ if (user.isGrafanaAdmin !== false || user.isAdmin === true) {
86
+ fail('Refusing to manage a Grafana server administrator as the Viewer.');
87
+ }
88
+ if (typeof user.login !== 'string' || user.login.toLowerCase() !== viewerUser.toLowerCase() ||
89
+ (expectedId !== undefined && id !== expectedId)) {
90
+ fail('Grafana returned a different user than the configured Viewer.');
91
+ }
92
+ if (user.isDisabled === true || user.isExternal === true) {
93
+ fail('The configured Viewer must be an enabled, locally managed Grafana user.');
94
+ }
95
+ return id;
96
+ }
97
+
98
+ export async function setupViewer(input = {}, { fetchImpl = fetch, sleep = delay, now = Date.now } = {}) {
99
+ // Complete validation before the first request or any account mutation.
100
+ const config = validateConfig(input);
101
+ const basic = (user, secret) => `Basic ${Buffer.from(`${user}:${secret}`).toString('base64')}`;
102
+ const adminAuth = basic(config.adminUser, config.adminPassword);
103
+ const viewerAuth = basic(config.viewerUser, config.viewerPassword);
104
+
105
+ async function request(method, path, { auth = adminAuth, body, statuses = [200], json = false,
106
+ operation = 'Grafana request', timeoutMs = config.requestTimeoutMs } = {}) {
107
+ const controller = new AbortController();
108
+ let timer;
109
+ try {
110
+ return await Promise.race([
111
+ (async () => {
112
+ const response = await fetchImpl(`${config.url}${path}`, {
113
+ method, redirect: 'error', signal: controller.signal,
114
+ headers: { Accept: 'application/json', ...(auth ? { Authorization: auth } : {}),
115
+ ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
116
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
117
+ });
118
+ if (!statuses.includes(response.status)) fail(`${operation} failed (HTTP ${response.status}).`);
119
+ let data;
120
+ if (json && response.status >= 200 && response.status < 300) {
121
+ try { data = await response.json(); } catch { fail(`${operation} returned invalid JSON.`); }
122
+ }
123
+ return { status: response.status, data };
124
+ })(),
125
+ new Promise((_, reject) => {
126
+ timer = setTimeout(() => {
127
+ controller.abort();
128
+ reject(new ViewerSetupError(`${operation} timed out.`));
129
+ }, timeoutMs);
130
+ }),
131
+ ]);
132
+ } catch (error) {
133
+ if (error instanceof ViewerSetupError) throw error;
134
+ fail(`${operation} could not connect to Grafana.`);
135
+ } finally { clearTimeout(timer); }
136
+ }
137
+
138
+ const deadline = now() + config.readinessTimeoutMs;
139
+ let ready = false;
140
+ while (now() < deadline) {
141
+ try {
142
+ const health = await request('GET', '/api/health', { auth: null, json: true,
143
+ operation: 'Grafana health check', timeoutMs: Math.min(config.requestTimeoutMs, deadline - now()),
144
+ statuses: [200, 500, 502, 503, 504] });
145
+ if (health.status === 200 && health.data?.database === 'ok' && now() < deadline) {
146
+ const dashboard = await request('GET', `/api/dashboards/uid/${dashboardUID}`, { json: true,
147
+ operation: 'Analytics dashboard readiness check',
148
+ timeoutMs: Math.min(config.requestTimeoutMs, deadline - now()), statuses: [200, 404, 502, 503, 504] });
149
+ if (dashboard.status === 200 && dashboard.data?.dashboard?.uid === dashboardUID) { ready = true; break; }
150
+ }
151
+ } catch (error) {
152
+ // Startup and provisioning may briefly refuse connections or time out.
153
+ // Authentication and other HTTP failures need an immediate, actionable exit.
154
+ if (!(error instanceof ViewerSetupError) || !/could not connect|timed out/.test(error.message)) throw error;
155
+ }
156
+ const remaining = deadline - now();
157
+ if (remaining > 0) await sleep(Math.min(config.pollIntervalMs, remaining));
158
+ }
159
+ if (!ready) fail('Grafana and the analytics dashboard did not become ready before the timeout.');
160
+
161
+ const lookupPath = `/api/users/lookup?loginOrEmail=${encodeURIComponent(config.viewerUser)}`;
162
+ let lookup = await request('GET', lookupPath, { json: true, statuses: [200, 404], operation: 'Viewer lookup' });
163
+ let createdId;
164
+ if (lookup.status === 404) {
165
+ const created = await request('POST', '/api/admin/users', { json: true,
166
+ operation: 'Viewer creation', body: { login: config.viewerUser, password: config.viewerPassword,
167
+ name: 'Analytics viewer', OrgId: organizationId } });
168
+ createdId = userId(created.data?.id);
169
+ lookup = await request('GET', lookupPath, { json: true, operation: 'Created Viewer lookup' });
170
+ }
171
+ const id = assertManagedViewer(lookup.data, config.viewerUser, createdId);
172
+
173
+ const members = await request('GET', `/api/orgs/${organizationId}/users`, {
174
+ json: true, operation: 'Viewer organization lookup' });
175
+ if (!Array.isArray(members.data)) fail('Grafana returned an invalid organization membership list.');
176
+ const membership = members.data.find(member => Number(member.userId) === id);
177
+ if (!membership) {
178
+ await request('POST', `/api/orgs/${organizationId}/users`, { operation: 'Viewer organization assignment',
179
+ body: { loginOrEmail: config.viewerUser, role: 'Viewer' } });
180
+ } else if (membership.role !== 'Viewer') {
181
+ await request('PATCH', `/api/orgs/${organizationId}/users/${id}`, {
182
+ operation: 'Viewer role assignment', body: { role: 'Viewer' } });
183
+ }
184
+
185
+ let current = await request('GET', '/api/user', { auth: viewerAuth, json: true,
186
+ statuses: [200, 401], operation: 'Viewer authentication' });
187
+ if (current.status === 401) {
188
+ // This named account is managed by this setup. Apply the configured password
189
+ // on an existing volume, so the documented credentials remain authoritative.
190
+ await request('PUT', `/api/admin/users/${id}/password`, {
191
+ operation: 'Viewer password update', body: { password: config.viewerPassword } });
192
+ current = await request('GET', '/api/user', { auth: viewerAuth, json: true,
193
+ operation: 'Viewer authentication after password update' });
194
+ }
195
+ assertManagedViewer(current.data, config.viewerUser, id);
196
+ if (Number(current.data.orgId) !== organizationId) {
197
+ await request('POST', `/api/user/using/${organizationId}`, { auth: viewerAuth,
198
+ operation: 'Viewer active organization update' });
199
+ }
200
+ await request('PUT', '/api/user/preferences', { auth: viewerAuth, operation: 'Viewer preferences update',
201
+ body: { theme: 'dark', homeDashboardUID: dashboardUID, timezone: 'utc' } });
202
+
203
+ return { viewerUser: config.viewerUser, userId: id, ...viewerURLs(config.publicUrl) };
204
+ }
205
+
206
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
207
+ try {
208
+ const result = await setupViewer(configFromEnv());
209
+ console.log(`Grafana Viewer ready: ${result.viewerUser}`);
210
+ console.log(`Dashboard: ${result.dashboardUrl}`);
211
+ console.log(`Login: ${result.loginUrl}`);
212
+ } catch (error) {
213
+ console.error(error instanceof ViewerSetupError ? error.message : 'Grafana Viewer setup failed.');
214
+ process.exitCode = 1;
215
+ }
216
+ }