@clawchatsai/connector 0.1.47 → 0.1.49

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,88 @@
1
+ /**
2
+ * chunk-reassembly.ts — reassembly of chunked browser messages (rpc-chunk-req, gateway-msg-chunk)
3
+ *
4
+ * The browser splits messages over the DataChannel size limit into chunks
5
+ * { id, index, total, data }. Every field is checked and memory is bounded: per message,
6
+ * across all messages, and in time (a message not complete within 30 s is dropped).
7
+ */
8
+ /** One chunk's data: at most one DataChannel message. */
9
+ export const MAX_CHUNK_DATA_LENGTH = 64 * 1024;
10
+ /** One reassembled message (string length; uploads arrive base64-encoded). */
11
+ export const MAX_MESSAGE_LENGTH = 128 * 1024 * 1024;
12
+ /** All messages being reassembled at once. */
13
+ export const MAX_BUFFERED_LENGTH = 256 * 1024 * 1024;
14
+ export const MAX_CHUNKS = 4096;
15
+ const MAX_MESSAGES = 64;
16
+ const MAX_ID_LENGTH = 256;
17
+ const TTL_MS = 30_000;
18
+ export class ChunkReassembler {
19
+ limits;
20
+ bufs = new Map();
21
+ buffered = 0;
22
+ constructor(limits = { message: MAX_MESSAGE_LENGTH, buffered: MAX_BUFFERED_LENGTH }) {
23
+ this.limits = limits;
24
+ }
25
+ /**
26
+ * Add one chunk from a connection. Returns the whole message once every chunk is in,
27
+ * an error for an invalid chunk (that message is dropped), or null while waiting.
28
+ */
29
+ add(connectionId, msg) {
30
+ const { id, index, total, data } = msg;
31
+ if (typeof id !== 'string' || !id || id.length > MAX_ID_LENGTH)
32
+ return { error: 'bad id' };
33
+ if (!Number.isInteger(total) || total < 1 || total > MAX_CHUNKS)
34
+ return { error: 'bad total' };
35
+ if (!Number.isInteger(index) || index < 0 || index >= total)
36
+ return { error: 'bad index' };
37
+ if (typeof data !== 'string' || !data || data.length > MAX_CHUNK_DATA_LENGTH)
38
+ return { error: 'bad data' };
39
+ const key = `${connectionId}\0${id}`;
40
+ let buf = this.bufs.get(key);
41
+ if (!buf) {
42
+ if (this.bufs.size >= MAX_MESSAGES)
43
+ return { error: 'too many chunked messages in progress' };
44
+ const timer = setTimeout(() => this.drop(key), TTL_MS);
45
+ timer.unref?.();
46
+ buf = { connectionId, chunks: new Array(total), received: 0, total: total, length: 0, timer };
47
+ this.bufs.set(key, buf);
48
+ }
49
+ if (buf.total !== total) {
50
+ this.drop(key);
51
+ return { error: 'total changed' };
52
+ }
53
+ if (buf.chunks[index] !== undefined)
54
+ return null; // duplicate: keep the first
55
+ if (buf.length + data.length > this.limits.message) {
56
+ this.drop(key);
57
+ return { error: 'message too large' };
58
+ }
59
+ if (this.buffered + data.length > this.limits.buffered) {
60
+ this.drop(key);
61
+ return { error: 'too much data in progress' };
62
+ }
63
+ buf.chunks[index] = data;
64
+ buf.received++;
65
+ buf.length += data.length;
66
+ this.buffered += data.length;
67
+ if (buf.received < buf.total)
68
+ return null;
69
+ this.drop(key);
70
+ return { done: buf.chunks.join('') };
71
+ }
72
+ /** Forget a closed connection's partial messages. */
73
+ dropConnection(connectionId) {
74
+ for (const [key, buf] of this.bufs)
75
+ if (buf.connectionId === connectionId)
76
+ this.drop(key);
77
+ }
78
+ /** Characters held in partial messages (tests). */
79
+ get bufferedLength() { return this.buffered; }
80
+ drop(key) {
81
+ const buf = this.bufs.get(key);
82
+ if (!buf)
83
+ return;
84
+ clearTimeout(buf.timer);
85
+ this.buffered -= buf.length;
86
+ this.bufs.delete(key);
87
+ }
88
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * config-store.ts — reading and writing ~/.openclaw/clawchats/config.json
3
+ *
4
+ * Every write is atomic (temp file + fsync + rename): the service reads this file on every new
5
+ * browser connection, and a half-written file must never be seen. Writers that change one part
6
+ * of the file (a consumed backup code, a new TOTP secret) re-read it from disk and change only
7
+ * that part, so nobody writes back a stale copy (e.g. undoing a `reauth`).
8
+ */
9
+ import type { PluginConfig } from './plugin-config.js';
10
+ import type { AuthConfig } from './auth-handler.js';
11
+ /**
12
+ * Write a file so readers see either the old or the new content, never a partial one.
13
+ * `beforeRename` returning false abandons the write (returns false).
14
+ */
15
+ export declare function writeFileAtomic(file: string, data: string | Buffer, mode?: number, beforeRename?: () => boolean): boolean;
16
+ /** The config, or null when it is missing, unparseable or lacks the signaling credentials. */
17
+ export declare function readConfig(file: string): PluginConfig | null;
18
+ export declare function writeConfig(file: string, config: PluginConfig): void;
19
+ /**
20
+ * Read-modify-write: re-reads the config from disk, applies `mutate`, writes it atomically.
21
+ * If another process (CLI or service) changed the file meanwhile, starts over from its version
22
+ * instead of overwriting it. `mutate` may run more than once; returning false means "nothing to
23
+ * change" (no write). Returns null (no write) when there is no valid config on disk.
24
+ */
25
+ export declare function updateConfig(file: string, mutate: (cfg: PluginConfig) => boolean | void): PluginConfig | null;
26
+ /** Consume a backup code: remove its hash from the config on disk. False if it wasn't there. */
27
+ export declare function removeBackupCode(file: string, hash: string): boolean;
28
+ export type AuthConfigResult = {
29
+ ok: true;
30
+ config: AuthConfig;
31
+ }
32
+ /** missing: no usable config; needs-2fa: valid config without TOTP set up; invalid: TOTP fields malformed */
33
+ | {
34
+ ok: false;
35
+ reason: 'missing' | 'needs-2fa' | 'invalid';
36
+ };
37
+ /**
38
+ * The browser login settings, freshly read from disk. Only a complete schemaVersion 2 config
39
+ * with TOTP and a session secret allows logins; anything else refuses every browser.
40
+ */
41
+ export declare function readAuthConfig(file: string, devMode?: boolean): AuthConfigResult;
42
+ /**
43
+ * Identifies the login secrets a browser authenticated under. It changes on `reauth` (new TOTP
44
+ * secret and session secret) and authenticated connections from before are then closed.
45
+ */
46
+ export declare function authEpoch(config: AuthConfig): string;
@@ -0,0 +1,154 @@
1
+ /**
2
+ * config-store.ts — reading and writing ~/.openclaw/clawchats/config.json
3
+ *
4
+ * Every write is atomic (temp file + fsync + rename): the service reads this file on every new
5
+ * browser connection, and a half-written file must never be seen. Writers that change one part
6
+ * of the file (a consumed backup code, a new TOTP secret) re-read it from disk and change only
7
+ * that part, so nobody writes back a stale copy (e.g. undoing a `reauth`).
8
+ */
9
+ import * as crypto from 'node:crypto';
10
+ import * as fs from 'node:fs';
11
+ import * as path from 'node:path';
12
+ /**
13
+ * Write a file so readers see either the old or the new content, never a partial one.
14
+ * `beforeRename` returning false abandons the write (returns false).
15
+ */
16
+ export function writeFileAtomic(file, data, mode = 0o600, beforeRename) {
17
+ const dir = path.dirname(file);
18
+ fs.mkdirSync(dir, { recursive: true });
19
+ const tmp = path.join(dir, `.${path.basename(file)}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`);
20
+ let fd;
21
+ try {
22
+ fd = fs.openSync(tmp, 'wx', mode);
23
+ fs.writeFileSync(fd, data);
24
+ fs.fsyncSync(fd);
25
+ fs.closeSync(fd);
26
+ fd = undefined;
27
+ if (beforeRename && !beforeRename()) {
28
+ fs.unlinkSync(tmp);
29
+ return false;
30
+ }
31
+ fs.renameSync(tmp, file);
32
+ }
33
+ catch (e) {
34
+ if (fd !== undefined)
35
+ try {
36
+ fs.closeSync(fd);
37
+ }
38
+ catch { /* already closed */ }
39
+ try {
40
+ fs.unlinkSync(tmp);
41
+ }
42
+ catch { /* never created */ }
43
+ throw e;
44
+ }
45
+ // Make the rename itself durable. Not supported everywhere (Windows): best effort.
46
+ try {
47
+ const dfd = fs.openSync(dir, 'r');
48
+ try {
49
+ fs.fsyncSync(dfd);
50
+ }
51
+ finally {
52
+ fs.closeSync(dfd);
53
+ }
54
+ }
55
+ catch { /* best effort */ }
56
+ return true;
57
+ }
58
+ const readRaw = (file) => { try {
59
+ return fs.readFileSync(file, 'utf8');
60
+ }
61
+ catch {
62
+ return null;
63
+ } };
64
+ function parseConfig(raw) {
65
+ try {
66
+ const cfg = JSON.parse(raw ?? '');
67
+ if (!cfg || typeof cfg !== 'object' || !cfg.userId || !cfg.apiKey || !cfg.serverUrl)
68
+ return null;
69
+ return cfg;
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ }
75
+ /** The config, or null when it is missing, unparseable or lacks the signaling credentials. */
76
+ export function readConfig(file) {
77
+ return parseConfig(readRaw(file));
78
+ }
79
+ export function writeConfig(file, config) {
80
+ writeFileAtomic(file, JSON.stringify(config, null, 2));
81
+ }
82
+ /**
83
+ * Read-modify-write: re-reads the config from disk, applies `mutate`, writes it atomically.
84
+ * If another process (CLI or service) changed the file meanwhile, starts over from its version
85
+ * instead of overwriting it. `mutate` may run more than once; returning false means "nothing to
86
+ * change" (no write). Returns null (no write) when there is no valid config on disk.
87
+ */
88
+ export function updateConfig(file, mutate) {
89
+ for (let attempt = 0; attempt < 5; attempt++) {
90
+ const raw = readRaw(file);
91
+ const cfg = parseConfig(raw);
92
+ if (!cfg)
93
+ return null;
94
+ if (mutate(cfg) === false)
95
+ return cfg;
96
+ if (writeFileAtomic(file, JSON.stringify(cfg, null, 2), 0o600, () => readRaw(file) === raw))
97
+ return cfg;
98
+ }
99
+ throw new Error(`${file} keeps changing; try again`);
100
+ }
101
+ /** Consume a backup code: remove its hash from the config on disk. False if it wasn't there. */
102
+ export function removeBackupCode(file, hash) {
103
+ let removed = false;
104
+ updateConfig(file, (cfg) => {
105
+ const i = Array.isArray(cfg.backupCodeHashes) ? cfg.backupCodeHashes.indexOf(hash) : -1;
106
+ if (i < 0)
107
+ return false;
108
+ cfg.backupCodeHashes.splice(i, 1);
109
+ removed = true;
110
+ });
111
+ return removed;
112
+ }
113
+ const isStr = (v) => typeof v === 'string' && v.length > 0;
114
+ /**
115
+ * The browser login settings, freshly read from disk. Only a complete schemaVersion 2 config
116
+ * with TOTP and a session secret allows logins; anything else refuses every browser.
117
+ */
118
+ export function readAuthConfig(file, devMode = false) {
119
+ const cfg = readConfig(file);
120
+ if (!cfg)
121
+ return { ok: false, reason: fs.existsSync(file) ? 'invalid' : 'missing' };
122
+ if (!cfg.totp && !cfg.sessionSecret && (cfg.schemaVersion === undefined || cfg.schemaVersion < 2)) {
123
+ return { ok: false, reason: 'needs-2fa' };
124
+ }
125
+ const t = cfg.totp;
126
+ const g = cfg.google;
127
+ if (cfg.schemaVersion !== 2 || !isStr(cfg.userId)
128
+ || !t || typeof t !== 'object' || !isStr(t.secret)
129
+ || !isStr(cfg.sessionSecret) || !/^[0-9a-f]{64}$/i.test(cfg.sessionSecret)
130
+ || (cfg.backupCodeHashes !== undefined && (!Array.isArray(cfg.backupCodeHashes) || !cfg.backupCodeHashes.every(isStr)))
131
+ || (g !== undefined && (!g || typeof g !== 'object' || typeof g.clientId !== 'string'
132
+ || typeof g.authorizedSub !== 'string' || typeof g.authorizedEmail !== 'string'))) {
133
+ return { ok: false, reason: 'invalid' };
134
+ }
135
+ return {
136
+ ok: true,
137
+ config: {
138
+ userId: cfg.userId,
139
+ totp: t,
140
+ // No Google identity bound (dev installs): placeholder, Google check skipped
141
+ google: g ?? { clientId: 'dev-placeholder', authorizedSub: 'dev-placeholder', authorizedEmail: 'dev@localhost' },
142
+ sessionSecret: cfg.sessionSecret,
143
+ backupCodeHashes: cfg.backupCodeHashes,
144
+ devMode,
145
+ },
146
+ };
147
+ }
148
+ /**
149
+ * Identifies the login secrets a browser authenticated under. It changes on `reauth` (new TOTP
150
+ * secret and session secret) and authenticated connections from before are then closed.
151
+ */
152
+ export function authEpoch(config) {
153
+ return crypto.createHash('sha256').update(`${config.sessionSecret}\n${config.totp.secret}`).digest('hex').slice(0, 32);
154
+ }