@1agh/maude 0.50.0 → 0.51.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.
@@ -189,48 +189,96 @@ export function createCloudEndpoints(ctx: Ctx) {
189
189
  if (opened.status !== 200 || !opened.body?.token) {
190
190
  return { status: 502, json: { ok: false, error: 'The project could not be opened with this account.' } };
191
191
  }
192
+ return linkToWorkspace({ workspaceUrl: opened.body.url, projectToken: opened.body.token, role: opened.body.role });
193
+ },
192
194
 
193
- const workspaceUrl: string = opened.body.url;
194
- // The cell is a different host than the control plane — one direct call.
195
- let hubToken: string | null = null;
196
- try {
197
- const res = await fetch(`${workspaceUrl}/auth/login`, {
198
- method: 'POST',
199
- headers: { 'content-type': 'application/json' },
200
- body: JSON.stringify({ token: opened.body.token }),
201
- });
202
- const body: any = await res.json().catch(() => ({}));
203
- if (res.ok && body?.token) hubToken = body.token;
204
- } catch {
205
- /* handled below */
195
+ /**
196
+ * Attach via a one-time handoff code — the maude:// lane (Phase 17). The
197
+ * code came from an untrusted URL, so it is exchanged ONLY against the
198
+ * configured Maude Cloud address (never one the link names), and the
199
+ * workspace we then link is the one THAT exchange returns. Needs no
200
+ * personal token: the code itself proves the dashboard session.
201
+ */
202
+ async attachCode(code: string): Promise<CloudEndpointResult> {
203
+ if (typeof code !== 'string' || !/^mhc_[0-9a-f]{16,128}$/.test(code)) {
204
+ return { status: 400, json: { ok: false, error: 'That link is not valid.' } };
206
205
  }
207
- if (!hubToken) {
208
- return { status: 502, json: { ok: false, error: 'The workspace did not accept the sign-in. Try again in a minute.' } };
206
+ const exchanged = await cloudFetch('/auth/handoff/exchange', {
207
+ method: 'POST',
208
+ headers: { 'content-type': 'application/json' },
209
+ body: JSON.stringify({ code }),
210
+ });
211
+ if (exchanged.status !== 200 || !exchanged.body?.token) {
212
+ return {
213
+ status: 410,
214
+ json: {
215
+ ok: false,
216
+ error:
217
+ 'That link expired — it works once, for two minutes. Press “Open in Maude” on the project page again.',
218
+ },
219
+ };
209
220
  }
221
+ return linkToWorkspace({
222
+ workspaceUrl: exchanged.body.url,
223
+ projectToken: exchanged.body.token,
224
+ role: exchanged.body.role,
225
+ project: exchanged.body.project,
226
+ });
227
+ },
228
+ };
210
229
 
211
- const norm = normalizeUrl(workspaceUrl);
212
- saveHubCredential(norm, hubToken);
230
+ /** The shared tail of every attach: cell exchange → credential + linkedHub. */
231
+ async function linkToWorkspace({
232
+ workspaceUrl,
233
+ projectToken,
234
+ role,
235
+ project,
236
+ }: {
237
+ workspaceUrl: string;
238
+ projectToken: string;
239
+ role?: string;
240
+ project?: string;
241
+ }): Promise<CloudEndpointResult> {
242
+ // The cell is a different host than the control plane — one direct call.
243
+ let hubToken: string | null = null;
244
+ try {
245
+ const res = await fetch(`${workspaceUrl}/auth/login`, {
246
+ method: 'POST',
247
+ headers: { 'content-type': 'application/json' },
248
+ body: JSON.stringify({ token: projectToken }),
249
+ });
250
+ const body: any = await res.json().catch(() => ({}));
251
+ if (res.ok && body?.token) hubToken = body.token;
252
+ } catch {
253
+ /* handled below */
254
+ }
255
+ if (!hubToken) {
256
+ return { status: 502, json: { ok: false, error: 'The workspace did not accept the sign-in. Try again in a minute.' } };
257
+ }
213
258
 
214
- // Project side — linkedHub in .design/config.json (committed; no token).
215
- const cfgPath = join(ctx.paths.designRoot, 'config.json');
216
- let cfg: any = {};
217
- try {
218
- cfg = JSON.parse(readFileSync(cfgPath, 'utf8'));
219
- } catch {
220
- /* absent/malformed → start minimal */
221
- }
222
- cfg.linkedHub = { url: norm, linkedAt: Date.now() };
223
- writeFileSync(cfgPath, `${JSON.stringify(cfg, null, 2)}\n`, 'utf8');
259
+ const norm = normalizeUrl(workspaceUrl);
260
+ saveHubCredential(norm, hubToken);
224
261
 
225
- return {
226
- status: 200,
227
- json: {
228
- ok: true,
229
- url: norm,
230
- role: opened.body.role,
231
- note: 'Linked. Restart the studio server to start syncing.',
232
- },
233
- };
234
- },
235
- };
262
+ // Project side — linkedHub in .design/config.json (committed; no token).
263
+ const cfgPath = join(ctx.paths.designRoot, 'config.json');
264
+ let cfg: any = {};
265
+ try {
266
+ cfg = JSON.parse(readFileSync(cfgPath, 'utf8'));
267
+ } catch {
268
+ /* absent/malformed → start minimal */
269
+ }
270
+ cfg.linkedHub = { url: norm, linkedAt: Date.now() };
271
+ writeFileSync(cfgPath, `${JSON.stringify(cfg, null, 2)}\n`, 'utf8');
272
+
273
+ return {
274
+ status: 200,
275
+ json: {
276
+ ok: true,
277
+ url: norm,
278
+ role: role ?? null,
279
+ project: project ?? null,
280
+ note: 'Linked. Restart the studio server to start syncing.',
281
+ },
282
+ };
283
+ }
236
284
  }
@@ -0,0 +1,144 @@
1
+ // debug-bundle.ts — scrubbed diagnostic bundle for the Report-a-Bug dialog
2
+ // (feature-bug-report-button). Three pieces:
3
+ //
4
+ // 1. a 500-line in-memory log ring fed by a console tap (installLogRing) —
5
+ // the dev-server has no persistent log of its own, so the ring is what
6
+ // gives a report something to attach;
7
+ // 2. scrub() — the DETERMINISTIC redaction pass every log line goes through
8
+ // before it can leave the process. Privacy invariant (docs/report-schema.md):
9
+ // the scrubber runs server-side, has red/green tests, and is extended
10
+ // test-first — never "best-effort";
11
+ // 3. buildDebugBundle() — assembles the `maude-report/v1` server-side fields.
12
+ //
13
+ // The consuming route (`GET /_api/debug-bundle`, http.ts) is PRIVILEGED:
14
+ // main-origin only, absent from CANVAS_SAFE_API + startCanvasServer's routes
15
+ // (dual-allowlist rule, DDR-088) — a hub-pushed canvas must never read logs.
16
+
17
+ import { homedir } from 'node:os';
18
+
19
+ const RING_MAX = 500;
20
+ const ring: string[] = [];
21
+ let tapInstalled = false;
22
+
23
+ /** Append one line to the ring (public for tests + non-console callers). */
24
+ export function recordLogLine(line: string): void {
25
+ ring.push(line);
26
+ if (ring.length > RING_MAX) ring.splice(0, ring.length - RING_MAX);
27
+ }
28
+
29
+ /** Last `n` raw (UNSCRUBBED — caller must scrub) ring lines, oldest first. */
30
+ export function logRingLines(n = 200): string[] {
31
+ return ring.slice(-n);
32
+ }
33
+
34
+ function fmt(args: unknown[]): string {
35
+ return args
36
+ .map((a) => {
37
+ if (typeof a === 'string') return a;
38
+ if (a instanceof Error) return a.stack ?? a.message;
39
+ try {
40
+ return JSON.stringify(a);
41
+ } catch {
42
+ return String(a);
43
+ }
44
+ })
45
+ .join(' ');
46
+ }
47
+
48
+ /**
49
+ * Mirror console.log/warn/error into the ring. Original behavior preserved
50
+ * (stdout/stderr still get every line). Idempotent — safe to call from both
51
+ * the server boot and tests.
52
+ */
53
+ export function installLogRing(): void {
54
+ if (tapInstalled) return;
55
+ tapInstalled = true;
56
+ for (const level of ['log', 'warn', 'error'] as const) {
57
+ const original = console[level].bind(console);
58
+ console[level] = (...args: unknown[]) => {
59
+ recordLogLine(`[${level}] ${fmt(args)}`);
60
+ original(...args);
61
+ };
62
+ }
63
+ }
64
+
65
+ export interface ScrubOptions {
66
+ /** Absolute repo root → rewritten to `<project>/`. */
67
+ repoRoot?: string;
68
+ /** Home dir → rewritten to `~`. Defaults to os.homedir(). */
69
+ home?: string;
70
+ }
71
+
72
+ /**
73
+ * Deterministic redaction. Order matters: repoRoot first (it usually lives
74
+ * under home — scrubbing home first would leave `~/git/repo` variants that
75
+ * the repoRoot rule no longer matches), then home, then secret material,
76
+ * then emails.
77
+ */
78
+ export function scrub(text: string, opts: ScrubOptions = {}): string {
79
+ let out = text;
80
+
81
+ const repoRoot = opts.repoRoot?.replace(/\/+$/, '');
82
+ if (repoRoot) out = out.replaceAll(repoRoot, '<project>');
83
+
84
+ const home = (opts.home ?? homedir()).replace(/\/+$/, '');
85
+ if (home) out = out.replaceAll(home, '~');
86
+
87
+ // Known token shapes first (GitHub classic + fine-grained, Anthropic, JWTs).
88
+ out = out.replace(/\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]{8,}\b/g, '[redacted]');
89
+ out = out.replace(/\bsk-[A-Za-z0-9_-]{16,}\b/g, '[redacted]');
90
+ out = out.replace(
91
+ /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\b/g,
92
+ '[redacted]'
93
+ );
94
+ // Bearer headers, however they were logged.
95
+ out = out.replace(/\b(Bearer)\s+[^\s"']+/gi, '$1 [redacted]');
96
+ // key=value / "key": "value" forms for secret-shaped keys — keep the key,
97
+ // redact the value.
98
+ out = out.replace(
99
+ /\b(token|secret|password|passwd|api[_-]?key|authorization|access[_-]?key)("?\s*[:=]\s*"?)[^\s"',}]+/gi,
100
+ '$1$2[redacted]'
101
+ );
102
+
103
+ out = out.replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, '[email]');
104
+
105
+ return out;
106
+ }
107
+
108
+ export interface DebugBundle {
109
+ app: { maudeVersion: string; platform: string; arch: string };
110
+ context: { projectName: string | null; activeCanvas: string | null };
111
+ logs: { serverLogTail: string };
112
+ }
113
+
114
+ /**
115
+ * Assemble the server-side half of a `maude-report/v1` payload. Everything
116
+ * here is ALREADY scrubbed — the client treats the bundle as display+consent
117
+ * material and must not need to re-clean it. Canvas CONTENT never enters the
118
+ * bundle: `activeCanvas` is the relative path only.
119
+ */
120
+ export function buildDebugBundle(args: {
121
+ maudeVersion: string;
122
+ projectName: string | null;
123
+ activeCanvas: string | null;
124
+ repoRoot: string;
125
+ tailLines?: number;
126
+ }): DebugBundle {
127
+ const scrubOpts: ScrubOptions = { repoRoot: args.repoRoot };
128
+ return {
129
+ app: {
130
+ maudeVersion: args.maudeVersion,
131
+ platform: process.platform,
132
+ arch: process.arch,
133
+ },
134
+ context: {
135
+ projectName: args.projectName,
136
+ activeCanvas: args.activeCanvas ? scrub(args.activeCanvas, scrubOpts) : null,
137
+ },
138
+ logs: {
139
+ serverLogTail: logRingLines(args.tailLines ?? 200)
140
+ .map((l) => scrub(l, scrubOpts))
141
+ .join('\n'),
142
+ },
143
+ };
144
+ }