@clawchatsai/connector 0.1.27 → 0.1.28
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/package.json +1 -1
- package/server/controllers/shares.js +143 -0
- package/server/controllers/shares.test.js +145 -0
- package/server/index.js +8 -0
- package/server/share/r2-setup.js +61 -0
- package/server/share/s3.js +50 -0
- package/server/share/viewer-decrypt.js +48 -0
- package/server/share/viewer-page.js +23 -0
- package/server/share/viewer.html +167 -0
package/package.json
CHANGED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// Share links (ClawChats extra), bring-your-own storage. The browser encrypts an artifact and sends only the
|
|
2
|
+
// ciphertext envelope here; the connector wraps it in a self-contained viewer page (share/viewer-page.js) and
|
|
3
|
+
// uploads that one HTML file to the user's own bucket (Cloudflare R2 today, any S3-compatible store later).
|
|
4
|
+
// The decryption key stays in the link fragment, so the storage provider can't read a share, and no
|
|
5
|
+
// ClawChats server is involved. Spec: clawchats repo, specs/sharing-and-artifacts.md.
|
|
6
|
+
//
|
|
7
|
+
// <dataDir>/share-storage.json derived S3 credentials + public URL (0600; never sent to the browser)
|
|
8
|
+
// <dataDir>/shares.json [{id, url, title, type, mode, createdAt, expiresAt}] (no keys)
|
|
9
|
+
import crypto from 'node:crypto';
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { send, sendError, parseBody } from '../util/http.js';
|
|
13
|
+
import { createS3Client } from '../share/s3.js';
|
|
14
|
+
import { setupR2 } from '../share/r2-setup.js';
|
|
15
|
+
import { buildSharePage } from '../share/viewer-page.js';
|
|
16
|
+
|
|
17
|
+
const ID_RE = /^[A-Za-z0-9_-]{22}$/;
|
|
18
|
+
const MAX_TITLE = 200;
|
|
19
|
+
const MAX_PAGE_BYTES = 5 * 1024 * 1024;
|
|
20
|
+
const TYPES = new Set(['html', 'svg', 'markdown', 'mermaid', 'csv', 'code']);
|
|
21
|
+
const SWEEP_MS = 60 * 60 * 1000;
|
|
22
|
+
const objectKey = id => `shares/${id}.html`;
|
|
23
|
+
|
|
24
|
+
export function validEnvelope(e) {
|
|
25
|
+
const b64u = s => typeof s === 'string' && /^[A-Za-z0-9_-]+$/.test(s);
|
|
26
|
+
if (!e || typeof e !== 'object' || e.v !== 1 || e.alg !== 'A256GCM' || !b64u(e.iv) || !b64u(e.ct)) return false;
|
|
27
|
+
if (e.kdf !== undefined) {
|
|
28
|
+
const k = e.kdf;
|
|
29
|
+
if (!k || k.name !== 'PBKDF2' || k.hash !== 'SHA-256' || !Number.isInteger(k.iter) || k.iter < 100000 || !b64u(k.salt)) return false;
|
|
30
|
+
}
|
|
31
|
+
return Object.keys(e).every(k => ['v', 'alg', 'iv', 'ct', 'kdf'].includes(k));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const newId = () => crypto.randomBytes(16).toString('base64url');
|
|
35
|
+
|
|
36
|
+
export function createShareHandlers({ dataDir, fetchImpl = globalThis.fetch, setup = setupR2, s3Factory = createS3Client, sweepTimer = true }) {
|
|
37
|
+
const storageFile = path.join(dataDir, 'share-storage.json');
|
|
38
|
+
const indexFile = path.join(dataDir, 'shares.json');
|
|
39
|
+
|
|
40
|
+
const writePrivate = (file, data) => {
|
|
41
|
+
const tmp = `${file}.tmp`;
|
|
42
|
+
fs.writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });
|
|
43
|
+
fs.renameSync(tmp, file);
|
|
44
|
+
};
|
|
45
|
+
const readStorage = () => { try { return JSON.parse(fs.readFileSync(storageFile, 'utf8')); } catch { return null; } };
|
|
46
|
+
const readIndex = () => { try { const v = JSON.parse(fs.readFileSync(indexFile, 'utf8')); return Array.isArray(v) ? v : []; } catch { return []; } };
|
|
47
|
+
const isExpired = r => !!r.expiresAt && Date.parse(r.expiresAt) <= Date.now();
|
|
48
|
+
const client = cfg => s3Factory(cfg, fetchImpl);
|
|
49
|
+
const publicInfo = cfg => cfg && { provider: cfg.provider, bucket: cfg.bucket, publicBaseUrl: cfg.publicBaseUrl };
|
|
50
|
+
|
|
51
|
+
// Delete expired shares from storage (the box runs 24/7, so the connector is the expiry clock).
|
|
52
|
+
async function sweep() {
|
|
53
|
+
const cfg = readStorage();
|
|
54
|
+
const rows = readIndex();
|
|
55
|
+
const expired = rows.filter(isExpired);
|
|
56
|
+
if (!cfg || !expired.length) return;
|
|
57
|
+
const s3 = client(cfg);
|
|
58
|
+
const gone = new Set();
|
|
59
|
+
for (const r of expired) {
|
|
60
|
+
try { const { status } = await s3.delete(objectKey(r.id)); if (status < 300 || status === 404) gone.add(r.id); } catch {}
|
|
61
|
+
}
|
|
62
|
+
if (gone.size) writePrivate(indexFile, readIndex().filter(r => !gone.has(r.id)));
|
|
63
|
+
}
|
|
64
|
+
if (sweepTimer) setInterval(() => sweep().catch(() => {}), SWEEP_MS).unref();
|
|
65
|
+
|
|
66
|
+
// GET /api/extras/shares → {configured, storage, shares}
|
|
67
|
+
async function handleList(req, res) {
|
|
68
|
+
await sweep().catch(() => {});
|
|
69
|
+
const cfg = readStorage();
|
|
70
|
+
return send(res, 200, {
|
|
71
|
+
configured: !!cfg,
|
|
72
|
+
storage: publicInfo(cfg),
|
|
73
|
+
shares: readIndex().filter(r => !isExpired(r)).sort((a, b) => b.createdAt.localeCompare(a.createdAt)),
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// POST /api/extras/shares/storage {token} → set up the user's R2 bucket, prove it works, save credentials
|
|
78
|
+
async function handleSetup(req, res) {
|
|
79
|
+
const { token } = await parseBody(req);
|
|
80
|
+
let cfg;
|
|
81
|
+
try { cfg = await setup(token, { fetchImpl }); } catch (err) { return sendError(res, err.code ? 400 : 502, err.message); }
|
|
82
|
+
const s3 = client(cfg);
|
|
83
|
+
const probe = `shares/.clawchats-setup-${newId()}.txt`;
|
|
84
|
+
const put = await s3.put(probe, 'ClawChats share storage test', { contentType: 'text/plain; charset=utf-8' });
|
|
85
|
+
await s3.delete(probe).catch(() => {});
|
|
86
|
+
if (put.status !== 200) return sendError(res, 502, `Your bucket refused a test upload (HTTP ${put.status}). Check the token has Admin Read & Write.`);
|
|
87
|
+
writePrivate(storageFile, cfg);
|
|
88
|
+
return send(res, 200, { storage: publicInfo(cfg) });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// DELETE /api/extras/shares/storage → forget the credentials (existing links keep working until deleted)
|
|
92
|
+
function handleForgetStorage(req, res) {
|
|
93
|
+
fs.rmSync(storageFile, { force: true });
|
|
94
|
+
return send(res, 200, { ok: true });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// POST /api/extras/shares {envelope, expiresAt?, title, type} → {share}
|
|
98
|
+
async function handleCreate(req, res) {
|
|
99
|
+
const cfg = readStorage();
|
|
100
|
+
if (!cfg) return sendError(res, 409, 'Connect your Cloudflare storage first');
|
|
101
|
+
const { envelope, expiresAt, title, type } = await parseBody(req);
|
|
102
|
+
if (!validEnvelope(envelope)) return sendError(res, 400, 'Missing or malformed encrypted envelope');
|
|
103
|
+
if (!TYPES.has(type)) return sendError(res, 400, 'Unsupported artifact type');
|
|
104
|
+
let expires = null;
|
|
105
|
+
if (expiresAt != null) {
|
|
106
|
+
const t = Date.parse(expiresAt);
|
|
107
|
+
if (!Number.isFinite(t) || t <= Date.now()) return sendError(res, 400, 'Expiry must be in the future');
|
|
108
|
+
expires = new Date(t).toISOString();
|
|
109
|
+
}
|
|
110
|
+
const page = buildSharePage(envelope);
|
|
111
|
+
if (Buffer.byteLength(page) > MAX_PAGE_BYTES) return sendError(res, 413, 'This artifact is too big to share (5 MB max)');
|
|
112
|
+
|
|
113
|
+
const id = newId();
|
|
114
|
+
const put = await client(cfg).put(objectKey(id), page, { contentType: 'text/html; charset=utf-8', cacheControl: 'no-cache' });
|
|
115
|
+
if (put.status !== 200) return sendError(res, 502, `Your storage refused the upload (HTTP ${put.status})`);
|
|
116
|
+
|
|
117
|
+
const share = {
|
|
118
|
+
id,
|
|
119
|
+
url: `${cfg.publicBaseUrl}/${objectKey(id)}`,
|
|
120
|
+
title: String(title || 'Shared artifact').slice(0, MAX_TITLE),
|
|
121
|
+
type,
|
|
122
|
+
mode: envelope.kdf ? 'password' : 'link',
|
|
123
|
+
createdAt: new Date().toISOString(),
|
|
124
|
+
expiresAt: expires,
|
|
125
|
+
};
|
|
126
|
+
writePrivate(indexFile, [share, ...readIndex()]);
|
|
127
|
+
sweep().catch(() => {});
|
|
128
|
+
return send(res, 201, { share });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// DELETE /api/extras/shares/:id → delete the page from the bucket, then from the index
|
|
132
|
+
async function handleRevoke(req, res, id) {
|
|
133
|
+
if (!ID_RE.test(id)) return sendError(res, 400, 'Bad share id');
|
|
134
|
+
const cfg = readStorage();
|
|
135
|
+
if (!cfg) return sendError(res, 409, 'Connect your Cloudflare storage first');
|
|
136
|
+
const { status } = await client(cfg).delete(objectKey(id));
|
|
137
|
+
if (status >= 300 && status !== 404) return sendError(res, 502, `Your storage refused the delete (HTTP ${status})`);
|
|
138
|
+
writePrivate(indexFile, readIndex().filter(r => r.id !== id));
|
|
139
|
+
return send(res, 200, { ok: true });
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return { handleList, handleSetup, handleForgetStorage, handleCreate, handleRevoke, sweep };
|
|
143
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { Readable } from 'node:stream';
|
|
7
|
+
import { createShareHandlers, validEnvelope } from './shares.js';
|
|
8
|
+
import { buildSharePage } from '../share/viewer-page.js';
|
|
9
|
+
import { decryptShare, needsPassword } from '../share/viewer-decrypt.js';
|
|
10
|
+
|
|
11
|
+
const CFG = { provider: 'r2', endpoint: 'https://acct.r2.cloudflarestorage.com', region: 'auto', bucket: 'clawchats-shares', accessKeyId: 'id', secretAccessKey: 'sk', publicBaseUrl: 'https://pub-x.r2.dev' };
|
|
12
|
+
const ENV = { v: 1, alg: 'A256GCM', iv: 'aaa', ct: 'bbb' };
|
|
13
|
+
|
|
14
|
+
function call(fn, body, ...args) {
|
|
15
|
+
const req = Readable.from(body === undefined ? [] : [Buffer.from(JSON.stringify(body))]);
|
|
16
|
+
return new Promise((resolve, reject) => {
|
|
17
|
+
const res = { writeHead(status) { this.status = status; }, end(data) { resolve({ status: this.status, body: JSON.parse(data) }); } };
|
|
18
|
+
Promise.resolve(fn(req, res, ...args)).catch(reject);
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function setup({ configured = true, putStatus = 200, deleteStatus = 204, setupImpl } = {}) {
|
|
23
|
+
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shares-'));
|
|
24
|
+
if (configured) fs.writeFileSync(path.join(dataDir, 'share-storage.json'), JSON.stringify(CFG));
|
|
25
|
+
const ops = [];
|
|
26
|
+
const s3Factory = cfg => ({
|
|
27
|
+
put: async (key, body, opts) => { ops.push({ op: 'put', key, body, opts, cfg }); return { status: putStatus }; },
|
|
28
|
+
delete: async key => { ops.push({ op: 'delete', key }); return { status: deleteStatus }; },
|
|
29
|
+
});
|
|
30
|
+
const h = createShareHandlers({ dataDir, s3Factory, setup: setupImpl || (async () => CFG), sweepTimer: false });
|
|
31
|
+
return { dataDir, ops, h };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Same envelope format as the browser (clawchats frontend/share/share-crypto.js).
|
|
35
|
+
async function encrypt(payload, password) {
|
|
36
|
+
const b64u = b => Buffer.from(b).toString('base64url');
|
|
37
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
38
|
+
let key, secret = null, kdf;
|
|
39
|
+
if (password) {
|
|
40
|
+
const salt = crypto.getRandomValues(new Uint8Array(16));
|
|
41
|
+
kdf = { name: 'PBKDF2', hash: 'SHA-256', iter: 600000, salt: b64u(salt) };
|
|
42
|
+
const base = await crypto.subtle.importKey('raw', new TextEncoder().encode(password), 'PBKDF2', false, ['deriveKey']);
|
|
43
|
+
key = await crypto.subtle.deriveKey({ name: 'PBKDF2', hash: 'SHA-256', iterations: 600000, salt }, base, { name: 'AES-GCM', length: 256 }, false, ['encrypt']);
|
|
44
|
+
} else {
|
|
45
|
+
const raw = crypto.getRandomValues(new Uint8Array(32));
|
|
46
|
+
secret = b64u(raw);
|
|
47
|
+
key = await crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['encrypt']);
|
|
48
|
+
}
|
|
49
|
+
const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(JSON.stringify(payload)));
|
|
50
|
+
return { envelope: { v: 1, alg: 'A256GCM', iv: b64u(iv), ct: b64u(ct), ...(kdf ? { kdf } : {}) }, secret };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
test('create uploads one self-contained HTML page to the user bucket and records the share without keys', async () => {
|
|
54
|
+
const { dataDir, ops, h } = setup();
|
|
55
|
+
const r = await call(h.handleCreate, { envelope: ENV, title: 'Login flow', type: 'mermaid' });
|
|
56
|
+
assert.equal(r.status, 201);
|
|
57
|
+
const { share } = r.body;
|
|
58
|
+
assert.match(share.id, /^[A-Za-z0-9_-]{22}$/);
|
|
59
|
+
assert.equal(share.url, `https://pub-x.r2.dev/shares/${share.id}.html`);
|
|
60
|
+
assert.equal(ops[0].key, `shares/${share.id}.html`);
|
|
61
|
+
assert.equal(ops[0].opts.contentType, 'text/html; charset=utf-8');
|
|
62
|
+
assert.ok(ops[0].body.includes('"ct":"bbb"'), 'ciphertext embedded');
|
|
63
|
+
assert.ok(!/\{\{(ENVELOPE_JSON|DECRYPT_JS)\}\}/.test(ops[0].body), 'no unfilled placeholders');
|
|
64
|
+
const saved = JSON.parse(fs.readFileSync(path.join(dataDir, 'shares.json'), 'utf8'));
|
|
65
|
+
assert.equal(saved[0].id, share.id);
|
|
66
|
+
assert.equal(fs.statSync(path.join(dataDir, 'shares.json')).mode & 0o777, 0o600);
|
|
67
|
+
const list = await call(h.handleList);
|
|
68
|
+
assert.equal(list.body.configured, true);
|
|
69
|
+
assert.deepEqual(list.body.storage, { provider: 'r2', bucket: 'clawchats-shares', publicBaseUrl: 'https://pub-x.r2.dev' });
|
|
70
|
+
assert.ok(!JSON.stringify(list.body).includes('sk'), 'credentials never leave the connector');
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test('without storage the list says so and create asks to connect', async () => {
|
|
74
|
+
const { h } = setup({ configured: false });
|
|
75
|
+
assert.equal((await call(h.handleList)).body.configured, false);
|
|
76
|
+
assert.equal((await call(h.handleCreate, { envelope: ENV, type: 'html' })).status, 409);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test('setup saves derived credentials (0600) after a successful test upload, and can be forgotten', async () => {
|
|
80
|
+
const { dataDir, ops, h } = setup({ configured: false });
|
|
81
|
+
const r = await call(h.handleSetup, { token: 't'.repeat(40) });
|
|
82
|
+
assert.equal(r.status, 200);
|
|
83
|
+
assert.equal(r.body.storage.publicBaseUrl, 'https://pub-x.r2.dev');
|
|
84
|
+
assert.deepEqual(ops.map(o => o.op), ['put', 'delete'], 'probe uploaded and removed');
|
|
85
|
+
const file = path.join(dataDir, 'share-storage.json');
|
|
86
|
+
assert.equal(fs.statSync(file).mode & 0o777, 0o600);
|
|
87
|
+
assert.equal((await call(h.handleForgetStorage)).status, 200);
|
|
88
|
+
assert.equal(fs.existsSync(file), false);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test('setup errors are reported and nothing is saved', async () => {
|
|
92
|
+
const bad = setup({ configured: false, setupImpl: async () => { throw Object.assign(new Error('Cloudflare rejected this token.'), { code: 'rejected' }); } });
|
|
93
|
+
assert.deepEqual(await call(bad.h.handleSetup, { token: 'x' }), { status: 400, body: { error: 'Cloudflare rejected this token.' } });
|
|
94
|
+
const refused = setup({ configured: false, putStatus: 403 });
|
|
95
|
+
assert.equal((await call(refused.h.handleSetup, { token: 't'.repeat(40) })).status, 502);
|
|
96
|
+
assert.equal(fs.existsSync(path.join(refused.dataDir, 'share-storage.json')), false);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test('rejects plaintext-looking or malformed envelopes, unknown types and past expiry before uploading', async () => {
|
|
100
|
+
const { ops, h } = setup();
|
|
101
|
+
assert.equal((await call(h.handleCreate, { envelope: { ...ENV, content: 'plain' }, type: 'html' })).status, 400);
|
|
102
|
+
assert.equal((await call(h.handleCreate, { envelope: { ...ENV, ct: 'no spaces!' }, type: 'html' })).status, 400);
|
|
103
|
+
assert.equal((await call(h.handleCreate, { envelope: ENV, type: 'exe' })).status, 400);
|
|
104
|
+
assert.equal((await call(h.handleCreate, { envelope: ENV, type: 'html', expiresAt: '2020-01-01' })).status, 400);
|
|
105
|
+
assert.equal(ops.length, 0);
|
|
106
|
+
assert.equal(validEnvelope({ ...ENV, kdf: { name: 'PBKDF2', hash: 'SHA-256', iter: 1000, salt: 'aa' } }), false, 'weak KDF refused');
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test('revoke deletes the page from the bucket and drops the row; a 404 still clears it', async () => {
|
|
110
|
+
const { dataDir, ops, h } = setup({ deleteStatus: 404 });
|
|
111
|
+
const { body } = await call(h.handleCreate, { envelope: ENV, type: 'html' });
|
|
112
|
+
assert.equal((await call(h.handleRevoke, undefined, body.share.id)).status, 200);
|
|
113
|
+
assert.deepEqual(ops[1], { op: 'delete', key: `shares/${body.share.id}.html` });
|
|
114
|
+
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dataDir, 'shares.json'), 'utf8')), []);
|
|
115
|
+
assert.equal((await call(h.handleRevoke, undefined, '../etc')).status, 400);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test('sweep deletes expired shares from the bucket and the list', async () => {
|
|
119
|
+
const { dataDir, ops, h } = setup();
|
|
120
|
+
const old = 'a'.repeat(22), keep = 'b'.repeat(22);
|
|
121
|
+
fs.writeFileSync(path.join(dataDir, 'shares.json'), JSON.stringify([
|
|
122
|
+
{ id: old, createdAt: '2026-01-01T00:00:00Z', expiresAt: '2026-01-02T00:00:00Z' },
|
|
123
|
+
{ id: keep, createdAt: '2026-01-01T00:00:00Z', expiresAt: null },
|
|
124
|
+
]));
|
|
125
|
+
const list = await call(h.handleList);
|
|
126
|
+
assert.deepEqual(list.body.shares.map(s => s.id), [keep]);
|
|
127
|
+
assert.deepEqual(ops, [{ op: 'delete', key: `shares/${old}.html` }]);
|
|
128
|
+
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dataDir, 'shares.json'), 'utf8')).map(s => s.id), [keep]);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test('share page embeds the envelope safely, and its decrypt code opens link and password shares', async () => {
|
|
132
|
+
const payload = { v: 1, kind: 'artifact', title: 'T', type: 'html', content: '</script><script>alert(1)</script>' };
|
|
133
|
+
const link = await encrypt(payload);
|
|
134
|
+
const page = buildSharePage({ ...link.envelope });
|
|
135
|
+
const m = page.match(/<script type="application\/json" id="share-envelope">([^<]*)<\/script>/);
|
|
136
|
+
assert.ok(m, 'envelope sits in its own JSON script element');
|
|
137
|
+
assert.deepEqual(JSON.parse(m[1]), link.envelope);
|
|
138
|
+
assert.ok(page.includes('async function decryptShare'), 'decrypt code inlined');
|
|
139
|
+
assert.ok(!/^export /m.test(page), 'no ES module syntax left in the inline script');
|
|
140
|
+
assert.deepEqual(await decryptShare(link.envelope, { secret: link.secret }), payload);
|
|
141
|
+
const pw = await encrypt(payload, 'correct horse battery');
|
|
142
|
+
assert.equal(needsPassword(pw.envelope), true);
|
|
143
|
+
assert.deepEqual(await decryptShare(pw.envelope, { password: 'correct horse battery' }), payload);
|
|
144
|
+
await assert.rejects(decryptShare(pw.envelope, { password: 'nope' }), { code: 'bad-password' });
|
|
145
|
+
});
|
package/server/index.js
CHANGED
|
@@ -15,6 +15,7 @@ import { handleStatic } from './controllers/static.js';
|
|
|
15
15
|
import { handleAgents } from './controllers/agents.js';
|
|
16
16
|
import { createTitleHandler, createTitler } from './controllers/title.js';
|
|
17
17
|
import { createSettingsHandlers } from './controllers/settings.js';
|
|
18
|
+
import { createShareHandlers } from './controllers/shares.js';
|
|
18
19
|
import { createWorkspaceStore } from './store/workspace-store.js';
|
|
19
20
|
import { createExtrasStore } from './store/extras-store.js';
|
|
20
21
|
import { createTeamStore } from './store/team-store.js';
|
|
@@ -40,6 +41,7 @@ export function createApp(config = {}) {
|
|
|
40
41
|
const gatewayUrl = config.gatewayUrl || GATEWAY_WS_URL;
|
|
41
42
|
const openaiApiKey = config.openaiApiKey || null;
|
|
42
43
|
const handleTitle = createTitleHandler(config.llm); // api.runtime.llm (plugin mode only)
|
|
44
|
+
const shares = createShareHandlers({ dataDir: DATA_DIR }); // share links → the user's own bucket
|
|
43
45
|
|
|
44
46
|
fs.mkdirSync(DATA_DIR, { recursive: true });
|
|
45
47
|
|
|
@@ -204,6 +206,12 @@ export function createApp(config = {}) {
|
|
|
204
206
|
broadcast(JSON.stringify({ type: 'clawchats', event: 'project-styles-changed' }));
|
|
205
207
|
return send(res, 200, { ok: true });
|
|
206
208
|
}
|
|
209
|
+
// Share links: browser-encrypted envelopes uploaded to the user's own bucket (controllers/shares.js)
|
|
210
|
+
if (method === 'GET' && urlPath === '/api/extras/shares') return await shares.handleList(req, res);
|
|
211
|
+
if (method === 'POST' && urlPath === '/api/extras/shares/storage') return await shares.handleSetup(req, res);
|
|
212
|
+
if (method === 'DELETE' && urlPath === '/api/extras/shares/storage') return shares.handleForgetStorage(req, res);
|
|
213
|
+
if (method === 'POST' && urlPath === '/api/extras/shares') return await shares.handleCreate(req, res);
|
|
214
|
+
if ((p = matchRoute(method, urlPath, 'DELETE /api/extras/shares/:id'))) return await shares.handleRevoke(req, res, p.id);
|
|
207
215
|
if (method === 'GET' && urlPath === '/api/extras/bookmarks') return send(res, 200, { bookmarks: extras.listBookmarks() });
|
|
208
216
|
if (method === 'POST' && urlPath === '/api/extras/bookmarks') {
|
|
209
217
|
const bookmark = extras.addBookmark(uuid(), await parseBody(req));
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// One-token setup for share links on the user's own Cloudflare R2: from a single R2 API token (Admin Read &
|
|
2
|
+
// Write), find the account, create the bucket, turn on its public r2.dev address, and derive S3 credentials
|
|
3
|
+
// (Cloudflare documents: Access Key ID = token id, Secret = SHA-256 of the token value). The raw token is not
|
|
4
|
+
// kept; the derived credentials are stored by the caller on this machine only.
|
|
5
|
+
import crypto from 'node:crypto';
|
|
6
|
+
|
|
7
|
+
export const BUCKET = 'clawchats-shares';
|
|
8
|
+
const API = 'https://api.cloudflare.com/client/v4';
|
|
9
|
+
|
|
10
|
+
export class SetupError extends Error {
|
|
11
|
+
constructor(message, code) { super(message); this.code = code; }
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export async function setupR2(token, { fetchImpl = globalThis.fetch } = {}) {
|
|
15
|
+
token = String(token || '').trim();
|
|
16
|
+
if (!/^[A-Za-z0-9_-]{30,}$/.test(token)) throw new SetupError('That doesn’t look like a Cloudflare API token. Copy the “Token value”.', 'bad-token');
|
|
17
|
+
|
|
18
|
+
const cf = async (path, init = {}) => {
|
|
19
|
+
const res = await fetchImpl(`${API}${path}`, {
|
|
20
|
+
...init,
|
|
21
|
+
headers: { authorization: `Bearer ${token}`, ...(init.body ? { 'content-type': 'application/json' } : {}) },
|
|
22
|
+
signal: AbortSignal.timeout(20000),
|
|
23
|
+
});
|
|
24
|
+
const data = await res.json().catch(() => ({}));
|
|
25
|
+
return { status: res.status, data };
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const accounts = await cf('/accounts');
|
|
29
|
+
if (accounts.status === 401 || accounts.status === 403 || !accounts.data.success) throw new SetupError('Cloudflare rejected this token. Create a new one and paste its “Token value”.', 'rejected');
|
|
30
|
+
const list = accounts.data.result || [];
|
|
31
|
+
if (list.length !== 1) throw new SetupError('This token sees more than one Cloudflare account. Create it as an account token for one account.', 'accounts');
|
|
32
|
+
const accountId = list[0].id;
|
|
33
|
+
|
|
34
|
+
// Token id = S3 Access Key ID. Account tokens verify under the account; user tokens under /user.
|
|
35
|
+
let verify = await cf(`/accounts/${accountId}/tokens/verify`);
|
|
36
|
+
if (!verify.data.success) verify = await cf('/user/tokens/verify');
|
|
37
|
+
const tokenId = verify.data.result?.id;
|
|
38
|
+
if (!verify.data.success || verify.data.result?.status !== 'active' || !tokenId) throw new SetupError('This token isn’t active.', 'inactive');
|
|
39
|
+
|
|
40
|
+
const created = await cf(`/accounts/${accountId}/r2/buckets`, { method: 'POST', body: JSON.stringify({ name: BUCKET }) });
|
|
41
|
+
const exists = created.status === 409 || (created.data.errors || []).some(e => /exist/i.test(e.message || ''));
|
|
42
|
+
if (!created.data.success && !exists) {
|
|
43
|
+
if (created.status === 403) throw new SetupError('This token can’t manage R2. Give it “Admin Read & Write” (or Workers R2 Storage: Edit).', 'permission');
|
|
44
|
+
throw new SetupError(`Couldn’t create the bucket: ${(created.data.errors || [])[0]?.message || `HTTP ${created.status}`}`, 'bucket');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const domain = await cf(`/accounts/${accountId}/r2/buckets/${BUCKET}/domains/managed`, { method: 'PUT', body: JSON.stringify({ enabled: true }) });
|
|
48
|
+
const host = domain.data.result?.domain;
|
|
49
|
+
if (!domain.data.success || !host) throw new SetupError(`Couldn’t turn on the bucket’s public address: ${(domain.data.errors || [])[0]?.message || `HTTP ${domain.status}`}`, 'domain');
|
|
50
|
+
|
|
51
|
+
return {
|
|
52
|
+
provider: 'r2',
|
|
53
|
+
accountId,
|
|
54
|
+
endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
|
|
55
|
+
region: 'auto',
|
|
56
|
+
bucket: BUCKET,
|
|
57
|
+
accessKeyId: tokenId,
|
|
58
|
+
secretAccessKey: crypto.createHash('sha256').update(token).digest('hex'),
|
|
59
|
+
publicBaseUrl: `https://${host}`,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Minimal S3 client (AWS Signature V4) for share links: PUT / DELETE / GET of one object. Works with any
|
|
2
|
+
// S3-compatible store; R2 uses region "auto". No SDK: the connector only ever needs these three calls.
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
|
|
5
|
+
const sha256Hex = data => crypto.createHash('sha256').update(data).digest('hex');
|
|
6
|
+
const hmac = (key, data) => crypto.createHmac('sha256', key).update(data).digest();
|
|
7
|
+
const encodeKey = key => key.split('/').map(encodeURIComponent).join('/');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @param {{endpoint: string, bucket: string, region?: string, accessKeyId: string, secretAccessKey: string}} cfg
|
|
11
|
+
* @param {typeof fetch} [fetchImpl]
|
|
12
|
+
*/
|
|
13
|
+
export function createS3Client(cfg, fetchImpl = globalThis.fetch) {
|
|
14
|
+
const endpoint = new URL(cfg.endpoint);
|
|
15
|
+
const region = cfg.region || 'auto';
|
|
16
|
+
|
|
17
|
+
async function request(method, key, { body = '', contentType, cacheControl, now = new Date() } = {}) {
|
|
18
|
+
const payload = typeof body === 'string' ? Buffer.from(body) : body;
|
|
19
|
+
const payloadHash = sha256Hex(payload);
|
|
20
|
+
const amzDate = now.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
|
|
21
|
+
const day = amzDate.slice(0, 8);
|
|
22
|
+
const path = `/${encodeURIComponent(cfg.bucket)}/${encodeKey(key)}`;
|
|
23
|
+
|
|
24
|
+
const headers = { host: endpoint.host, 'x-amz-content-sha256': payloadHash, 'x-amz-date': amzDate };
|
|
25
|
+
if (contentType) headers['content-type'] = contentType;
|
|
26
|
+
if (cacheControl) headers['cache-control'] = cacheControl;
|
|
27
|
+
const names = Object.keys(headers).sort();
|
|
28
|
+
const canonical = [method, path, '', ...names.map(n => `${n}:${headers[n]}`), '', names.join(';'), payloadHash].join('\n');
|
|
29
|
+
const scope = `${day}/${region}/s3/aws4_request`;
|
|
30
|
+
const toSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256Hex(canonical)].join('\n');
|
|
31
|
+
const kSigning = hmac(hmac(hmac(hmac(`AWS4${cfg.secretAccessKey}`, day), region), 's3'), 'aws4_request');
|
|
32
|
+
const signature = crypto.createHmac('sha256', kSigning).update(toSign).digest('hex');
|
|
33
|
+
headers.authorization = `AWS4-HMAC-SHA256 Credential=${cfg.accessKeyId}/${scope}, SignedHeaders=${names.join(';')}, Signature=${signature}`;
|
|
34
|
+
delete headers.host;
|
|
35
|
+
|
|
36
|
+
const res = await fetchImpl(`${endpoint.origin}${path}`, {
|
|
37
|
+
method,
|
|
38
|
+
headers,
|
|
39
|
+
body: method === 'PUT' ? payload : undefined,
|
|
40
|
+
signal: AbortSignal.timeout(20000),
|
|
41
|
+
});
|
|
42
|
+
return { status: res.status, text: await res.text().catch(() => '') };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return {
|
|
46
|
+
put: (key, body, opts) => request('PUT', key, { body, ...opts }),
|
|
47
|
+
delete: key => request('DELETE', key),
|
|
48
|
+
get: key => request('GET', key),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Decrypts a ClawChats share envelope. Inlined into every share page by viewer-page.js (the `export`
|
|
2
|
+
// keywords are stripped there), and imported directly by the tests. Mirrors the browser's encrypt side
|
|
3
|
+
// (clawchats frontend/share/share-crypto.js). No DOM use.
|
|
4
|
+
|
|
5
|
+
const b64uDecode = s => {
|
|
6
|
+
const b64 = s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4);
|
|
7
|
+
return Uint8Array.from(atob(b64), c => c.charCodeAt(0));
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export class ShareError extends Error {
|
|
11
|
+
constructor(code, message) { super(message); this.code = code; }
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
async function keyFromLinkSecret(secret) {
|
|
15
|
+
const raw = b64uDecode(secret);
|
|
16
|
+
if (raw.length !== 32) throw new ShareError('bad-key', 'This link is incomplete. Copy the full link, including the part after #.');
|
|
17
|
+
return crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['decrypt']);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function keyFromPassword(password, kdf) {
|
|
21
|
+
const base = await crypto.subtle.importKey('raw', new TextEncoder().encode(password), 'PBKDF2', false, ['deriveKey']);
|
|
22
|
+
return crypto.subtle.deriveKey(
|
|
23
|
+
{ name: 'PBKDF2', hash: kdf.hash, iterations: kdf.iter, salt: b64uDecode(kdf.salt) },
|
|
24
|
+
base, { name: 'AES-GCM', length: 256 }, false, ['decrypt']);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** True when the envelope needs a password instead of the link secret. */
|
|
28
|
+
export const needsPassword = envelope => !!envelope.kdf;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param {object} envelope {v, alg, kdf?, iv, ct}
|
|
32
|
+
* @param {{secret?: string, password?: string}} opts
|
|
33
|
+
* @returns {Promise<object>} the shared payload
|
|
34
|
+
*/
|
|
35
|
+
export async function decryptShare(envelope, { secret, password } = {}) {
|
|
36
|
+
if (envelope?.v !== 1 || envelope.alg !== 'A256GCM') throw new ShareError('unsupported', 'This share was made by a newer version of ClawChats.');
|
|
37
|
+
const key = envelope.kdf
|
|
38
|
+
? await keyFromPassword(password ?? '', envelope.kdf)
|
|
39
|
+
: await keyFromLinkSecret(secret ?? '');
|
|
40
|
+
let plain;
|
|
41
|
+
try {
|
|
42
|
+
plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: b64uDecode(envelope.iv) }, key, b64uDecode(envelope.ct));
|
|
43
|
+
} catch {
|
|
44
|
+
throw new ShareError(envelope.kdf ? 'bad-password' : 'bad-key',
|
|
45
|
+
envelope.kdf ? 'Wrong password.' : 'This link’s key doesn’t match. Copy the full link again.');
|
|
46
|
+
}
|
|
47
|
+
return JSON.parse(new TextDecoder().decode(plain));
|
|
48
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Builds the self-contained share page: viewer.html with the decrypt code and the ciphertext envelope
|
|
2
|
+
// inlined. One static HTML file per share, uploaded to the user's own bucket; no server logic anywhere.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
|
|
7
|
+
const dir = path.dirname(fileURLToPath(import.meta.url));
|
|
8
|
+
let template = null;
|
|
9
|
+
|
|
10
|
+
function load() {
|
|
11
|
+
if (template) return template;
|
|
12
|
+
const html = fs.readFileSync(path.join(dir, 'viewer.html'), 'utf8');
|
|
13
|
+
const decrypt = fs.readFileSync(path.join(dir, 'viewer-decrypt.js'), 'utf8').replace(/^export /gm, '');
|
|
14
|
+
template = html.replace('{{DECRYPT_JS}}', () => decrypt);
|
|
15
|
+
return template;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** @param {object} envelope validated ciphertext envelope ({v, alg, iv, ct, kdf?}) */
|
|
19
|
+
export function buildSharePage(envelope) {
|
|
20
|
+
// Escape "<" so the JSON can't close its <script> element, whatever it contains.
|
|
21
|
+
const json = JSON.stringify(envelope).replace(/</g, '\\u003c');
|
|
22
|
+
return load().replace('{{ENVELOPE_JSON}}', () => json);
|
|
23
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<meta name="robots" content="noindex, nofollow">
|
|
7
|
+
<meta name="referrer" content="no-referrer">
|
|
8
|
+
<!-- Self-contained ClawChats share page (built by the connector, server/share/viewer-page.js). The content
|
|
9
|
+
below is encrypted; the key is in the link after #, which browsers never send to a server. The
|
|
10
|
+
decrypted artifact renders in a sandboxed iframe (opaque origin) that inherits this policy:
|
|
11
|
+
no network access (connect-src 'none'). -->
|
|
12
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval' https://cdnjs.cloudflare.com; style-src 'unsafe-inline' https://cdnjs.cloudflare.com https://fonts.googleapis.com; font-src https://fonts.gstatic.com https://cdnjs.cloudflare.com data:; img-src data: blob: https:; media-src data: blob: https:; connect-src 'none'; frame-src 'self' blob: data:; base-uri 'none'; form-action 'none'">
|
|
13
|
+
<title>Shared from ClawChats</title>
|
|
14
|
+
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 32 32%27%3E%3Crect width=%2732%27 height=%2732%27 rx=%277%27 fill=%27%234f8cff%27/%3E%3Cpath d=%27M9 21l5-10 3 6 2-3 4 7z%27 fill=%27%23fff%27/%3E%3C/svg%3E">
|
|
15
|
+
<style>
|
|
16
|
+
:root { --bg:#0f1115; --panel:#171a21; --border:#2a2f3a; --text:#e6e8ee; --muted:#8b93a7; --primary:#4f8cff; --danger:#ff6b6b; color-scheme:dark; }
|
|
17
|
+
* { box-sizing:border-box; }
|
|
18
|
+
html, body { height:100%; margin:0; }
|
|
19
|
+
body { display:flex; flex-direction:column; background:var(--bg); color:var(--text); font:14px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif; }
|
|
20
|
+
.bar { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:10px 16px; background:var(--panel); border-bottom:1px solid var(--border); }
|
|
21
|
+
.bar-title { display:flex; align-items:center; gap:8px; min-width:0; }
|
|
22
|
+
.brand { font-weight:600; }
|
|
23
|
+
.sep { color:var(--muted); }
|
|
24
|
+
.title { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
|
25
|
+
.bar-actions { display:flex; align-items:center; gap:12px; flex-shrink:0; }
|
|
26
|
+
.meta { color:var(--muted); font-size:13px; }
|
|
27
|
+
.btn { padding:6px 12px; border:1px solid var(--border); border-radius:6px; background:transparent; color:var(--text); font:inherit; cursor:pointer; }
|
|
28
|
+
.btn:hover { background:#222733; }
|
|
29
|
+
.btn.primary { background:var(--primary); border-color:var(--primary); color:#fff; }
|
|
30
|
+
.btn:disabled { opacity:.6; cursor:default; }
|
|
31
|
+
main { flex:1; display:flex; min-height:0; }
|
|
32
|
+
#frame { flex:1; width:100%; border:0; background:#fff; }
|
|
33
|
+
.state { margin:auto; max-width:420px; padding:24px; text-align:center; color:var(--muted); }
|
|
34
|
+
.pw-form { display:flex; flex-direction:column; gap:10px; text-align:left; color:var(--text); }
|
|
35
|
+
.pw-row { display:flex; gap:8px; }
|
|
36
|
+
.pw-row input { flex:1; padding:8px 10px; border:1px solid var(--border); border-radius:6px; background:var(--bg); color:var(--text); font:inherit; }
|
|
37
|
+
.error { margin:0; color:var(--danger); }
|
|
38
|
+
.note { padding:6px 16px; color:var(--muted); font-size:12px; text-align:center; border-top:1px solid var(--border); }
|
|
39
|
+
</style>
|
|
40
|
+
</head>
|
|
41
|
+
<body>
|
|
42
|
+
<header class="bar">
|
|
43
|
+
<div class="bar-title"><span class="brand">ClawChats</span><span class="sep">/</span><span id="share-title" class="title">Shared artifact</span></div>
|
|
44
|
+
<div class="bar-actions"><span id="share-meta" class="meta"></span><button id="btn-download" class="btn" type="button" hidden>Download</button></div>
|
|
45
|
+
</header>
|
|
46
|
+
<main>
|
|
47
|
+
<section id="state" class="state">
|
|
48
|
+
<p id="state-text">Decrypting…</p>
|
|
49
|
+
<form id="pw-form" class="pw-form" hidden>
|
|
50
|
+
<label for="pw-input">This share is password protected.</label>
|
|
51
|
+
<div class="pw-row"><input id="pw-input" type="password" autocomplete="off" placeholder="Password"><button class="btn primary" type="submit">Unlock</button></div>
|
|
52
|
+
<p id="pw-error" class="error" hidden></p>
|
|
53
|
+
</form>
|
|
54
|
+
</section>
|
|
55
|
+
<iframe id="frame" title="Shared content" sandbox="allow-scripts allow-popups allow-popups-to-escape-sandbox" hidden></iframe>
|
|
56
|
+
</main>
|
|
57
|
+
<footer class="note">Shared by a ClawChats user. Don’t enter passwords or personal details into a shared page. Decrypted in your browser; stored encrypted in the sharer’s own storage.</footer>
|
|
58
|
+
<script type="application/json" id="share-envelope">{{ENVELOPE_JSON}}</script>
|
|
59
|
+
<script>
|
|
60
|
+
{{DECRYPT_JS}}
|
|
61
|
+
|
|
62
|
+
(() => {
|
|
63
|
+
const $ = id => document.getElementById(id);
|
|
64
|
+
const EXT = { html: 'html', svg: 'svg', markdown: 'md', mermaid: 'mmd', csv: 'csv', code: 'txt' };
|
|
65
|
+
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
66
|
+
const BASE_CSS = 'body{margin:0;padding:24px;font:15px/1.6 system-ui,-apple-system,"Segoe UI",sans-serif;color:#1f2328;background:#fff}'
|
|
67
|
+
+ 'pre{margin:0;white-space:pre-wrap;word-break:break-word;font:13px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}'
|
|
68
|
+
+ 'table{border-collapse:collapse;font-size:14px}td,th{border:1px solid #d0d7de;padding:6px 10px;text-align:left}th{background:#f6f8fa}'
|
|
69
|
+
+ '.md{max-width:820px;margin:0 auto}.md img{max-width:100%}.md pre{background:#f6f8fa;padding:12px;border-radius:6px;overflow:auto}'
|
|
70
|
+
+ '.md code{font:13px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.center{display:flex;justify-content:center}'
|
|
71
|
+
+ 'pre.mermaid{display:block;text-align:center;white-space:pre;font:inherit}';
|
|
72
|
+
const page = (body, head = '') => `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><style>${BASE_CSS}</style>${head}</head><body>${body}</body></html>`;
|
|
73
|
+
const lib = (src, sri) => `<script src="${src}" integrity="${sri}" crossorigin="anonymous"><\/script>`;
|
|
74
|
+
const MERMAID = lib('https://cdnjs.cloudflare.com/ajax/libs/mermaid/10.9.8/mermaid.min.js', 'sha384-N3QqR/7q+xm3BGX+CBbNI8AUmRRqcsDzToy+0z1NLDI0QmTKW8zvwLvqulJgk3dP');
|
|
75
|
+
const MARKED = lib('https://cdnjs.cloudflare.com/ajax/libs/marked/18.0.14/lib/marked.umd.min.js', 'sha384-J1VD5X/E72gORmmXiADelqS192/84qho9IALLC3d5oxjp1RgEN3He4ANyjqXyz10');
|
|
76
|
+
|
|
77
|
+
function csvTable(text) {
|
|
78
|
+
const rows = [];
|
|
79
|
+
let row = [], cell = '', q = false;
|
|
80
|
+
for (let i = 0; i < text.length; i++) {
|
|
81
|
+
const c = text[i];
|
|
82
|
+
if (q) {
|
|
83
|
+
if (c === '"' && text[i + 1] === '"') { cell += '"'; i++; }
|
|
84
|
+
else if (c === '"') q = false;
|
|
85
|
+
else cell += c;
|
|
86
|
+
} else if (c === '"') q = true;
|
|
87
|
+
else if (c === ',') { row.push(cell); cell = ''; }
|
|
88
|
+
else if (c === '\n' || c === '\r') {
|
|
89
|
+
if (c === '\r' && text[i + 1] === '\n') i++;
|
|
90
|
+
row.push(cell); rows.push(row); row = []; cell = '';
|
|
91
|
+
} else cell += c;
|
|
92
|
+
}
|
|
93
|
+
if (cell || row.length) { row.push(cell); rows.push(row); }
|
|
94
|
+
if (!rows.length) return '';
|
|
95
|
+
const [head, ...body] = rows;
|
|
96
|
+
return `<table><thead><tr>${head.map(h => `<th>${esc(h)}</th>`).join('')}</tr></thead><tbody>`
|
|
97
|
+
+ body.map(r => `<tr>${r.map(c => `<td>${esc(c)}</td>`).join('')}</tr>`).join('') + '</tbody></table>';
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// The artifact document for the sandboxed iframe. Untrusted content: it only ever goes into srcdoc.
|
|
101
|
+
function build(type, content) {
|
|
102
|
+
switch (type) {
|
|
103
|
+
case 'html': return String(content);
|
|
104
|
+
case 'svg': return page(`<div class="center">${content}</div>`);
|
|
105
|
+
case 'mermaid':
|
|
106
|
+
return page(`<pre class="mermaid">${esc(content)}</pre>`, MERMAID
|
|
107
|
+
+ '<script>addEventListener("DOMContentLoaded",()=>{mermaid.initialize({startOnLoad:false,securityLevel:"strict"});mermaid.run()})<\/script>');
|
|
108
|
+
case 'markdown':
|
|
109
|
+
return page('<article class="md" id="md"></article>', MARKED
|
|
110
|
+
+ `<script>addEventListener("DOMContentLoaded",()=>{document.getElementById("md").innerHTML=marked.parse(${JSON.stringify(String(content)).replace(/</g, '\\u003c')})})<\/script>`);
|
|
111
|
+
case 'csv': return page(csvTable(String(content)));
|
|
112
|
+
default: return page(`<pre>${esc(content)}</pre>`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function showState(text) { $('state').hidden = false; $('state-text').textContent = text; $('frame').hidden = true; }
|
|
117
|
+
|
|
118
|
+
function render(payload) {
|
|
119
|
+
const title = String(payload.title || 'Shared artifact').slice(0, 200);
|
|
120
|
+
document.title = `${title} · ClawChats`;
|
|
121
|
+
$('share-title').textContent = title;
|
|
122
|
+
const d = new Date(payload.createdAt);
|
|
123
|
+
if (!isNaN(d)) $('share-meta').textContent = `Shared ${d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })}`;
|
|
124
|
+
const btn = $('btn-download');
|
|
125
|
+
btn.hidden = false;
|
|
126
|
+
btn.onclick = () => {
|
|
127
|
+
const ext = payload.type === 'code' ? (payload.language || 'txt') : (EXT[payload.type] || 'txt');
|
|
128
|
+
const a = document.createElement('a');
|
|
129
|
+
a.href = URL.createObjectURL(new Blob([payload.content], { type: 'text/plain' }));
|
|
130
|
+
a.download = `${title.replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '') || 'artifact'}.${String(ext).replace(/\W/g, '') || 'txt'}`;
|
|
131
|
+
a.click();
|
|
132
|
+
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
|
|
133
|
+
};
|
|
134
|
+
const frame = $('frame');
|
|
135
|
+
frame.srcdoc = build(payload.type, payload.content);
|
|
136
|
+
frame.hidden = false;
|
|
137
|
+
$('state').hidden = true;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function main() {
|
|
141
|
+
let envelope;
|
|
142
|
+
try { envelope = JSON.parse($('share-envelope').textContent); } catch { return showState('This share is damaged.'); }
|
|
143
|
+
if (!needsPassword(envelope)) {
|
|
144
|
+
const secret = new URLSearchParams(location.hash.slice(1)).get('k');
|
|
145
|
+
if (!secret) return showState('This link is missing its key. Copy the full link, including the part after #.');
|
|
146
|
+
try { render(await decryptShare(envelope, { secret })); } catch (err) { showState(err.message); }
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
$('state-text').textContent = '';
|
|
150
|
+
const form = $('pw-form');
|
|
151
|
+
form.hidden = false;
|
|
152
|
+
$('pw-input').focus();
|
|
153
|
+
form.onsubmit = async e => {
|
|
154
|
+
e.preventDefault();
|
|
155
|
+
const btn = form.querySelector('button');
|
|
156
|
+
btn.disabled = true;
|
|
157
|
+
$('pw-error').hidden = true;
|
|
158
|
+
try { render(await decryptShare(envelope, { password: $('pw-input').value })); }
|
|
159
|
+
catch (err) { $('pw-error').textContent = err.message; $('pw-error').hidden = false; }
|
|
160
|
+
finally { btn.disabled = false; }
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
main();
|
|
164
|
+
})();
|
|
165
|
+
</script>
|
|
166
|
+
</body>
|
|
167
|
+
</html>
|