omo-web 0.1.4 → 0.1.7

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/dist/server.js CHANGED
@@ -29,7 +29,7 @@ __export(exports_iso, {
29
29
 
30
30
  // src/main.ts
31
31
  import { homedir } from "os";
32
- import { delimiter, join as join10, resolve as resolve9 } from "path";
32
+ import { delimiter, join as join11, resolve as resolve10 } from "path";
33
33
 
34
34
  // packaging/npm/locale.js
35
35
  var system = process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || Intl.DateTimeFormat().resolvedOptions().locale;
@@ -38,7 +38,8 @@ var cliTr = (zh, en) => cliLocale === "zh-CN" ? zh : en;
38
38
 
39
39
  // src/server.ts
40
40
  import { createHmac as createHmac5 } from "crypto";
41
- import { resolve as resolve8 } from "path";
41
+ import { resolve as resolve9 } from "path";
42
+ import { fileURLToPath } from "url";
42
43
 
43
44
  // node_modules/zod/v4/core/util.js
44
45
  function getEnumValues(entries) {
@@ -11630,6 +11631,16 @@ class Sessions {
11630
11631
  throw new WebError(404, "session_not_found", "\u627E\u4E0D\u5230\u8FD9\u4E2A\u4F1A\u8BDD\u3002");
11631
11632
  return row;
11632
11633
  }
11634
+ async authorizeAttachment(id) {
11635
+ try {
11636
+ await this.#requireRowWorkspace(this.#row(id));
11637
+ } catch (error) {
11638
+ if (error instanceof WebError && error.code === "workspace_refused") {
11639
+ throw new WebError(404, "session_not_found", "\u627E\u4E0D\u5230\u8FD9\u4E2A\u4F1A\u8BDD\u3002");
11640
+ }
11641
+ throw error;
11642
+ }
11643
+ }
11633
11644
  #route(id) {
11634
11645
  return this.#binding(id).route;
11635
11646
  }
@@ -11640,6 +11651,23 @@ class Sessions {
11640
11651
  throw new WebError(409, "session_not_open", "\u4F1A\u8BDD\u672A\u63A5\u5165\u5F15\u64CE\uFF0C\u8BF7\u5148\u6062\u590D\u4F1A\u8BDD\u3002");
11641
11652
  return live;
11642
11653
  }
11654
+ async attachmentBinding(input) {
11655
+ const matches = [...this.#live.entries()].filter(([, live]) => live.runtime?.sessionId === input.sessionId && live.runtime.sessionFile === input.sessionFile && live.runtime.cwd === input.cwd);
11656
+ if (matches.length !== 1)
11657
+ throw new WebError(403, "attachment_refused", "\u65E0\u6CD5\u4ECE\u6B64\u4F1A\u8BDD\u53D1\u9001\u8BE5\u6587\u4EF6\u3002");
11658
+ const [id, live] = matches[0];
11659
+ const row = this.#row(id);
11660
+ const verify = async () => {
11661
+ const current = () => !this.#stopping && this.engine.status.online && this.#live.get(id) === live && this.#rows.get(id) === row && !this.#releasing.has(id) && live.runtime !== undefined && !this.#treeWrites.get(live.runtime)?.pending;
11662
+ if (!current())
11663
+ throw new WebError(403, "attachment_refused", "\u65E0\u6CD5\u4ECE\u6B64\u4F1A\u8BDD\u53D1\u9001\u8BE5\u6587\u4EF6\u3002");
11664
+ await this.#requireRowWorkspace(row);
11665
+ if (!current())
11666
+ throw new WebError(403, "attachment_refused", "\u65E0\u6CD5\u4ECE\u6B64\u4F1A\u8BDD\u53D1\u9001\u8BE5\u6587\u4EF6\u3002");
11667
+ };
11668
+ await verify();
11669
+ return { id, verify };
11670
+ }
11643
11671
  #workspaceKeyForRow(row) {
11644
11672
  return row.workspaceKey ?? (this.workspaces instanceof WorkspaceAccess ? this.workspaces.launchKey(row.cwd) : undefined);
11645
11673
  }
@@ -12002,10 +12030,10 @@ ${source.nativeSessionId}`;
12002
12030
  }
12003
12031
  }
12004
12032
  async#resumeCliSource(source, nameHint) {
12005
- const existing = [...this.#rows.values()].find((row) => row.cwd === source.cwd && row.nativeId === source.nativeSessionId);
12006
- if (existing) {
12007
- await this.#resume(existing);
12008
- return this.#view(this.#row(existing.id));
12033
+ const existing = this.findAlias(source.nativeSessionId, source.cwd, source.workspaceKey);
12034
+ if (existing !== undefined) {
12035
+ await this.#resume(this.#row(existing));
12036
+ return this.#view(this.#row(existing));
12009
12037
  }
12010
12038
  const id = sessionKey.parse(crypto.randomUUID());
12011
12039
  const trimmed = nameHint.trim().slice(0, 120);
@@ -12938,15 +12966,376 @@ ${source.nativeSessionId}`;
12938
12966
  }
12939
12967
  }
12940
12968
 
12969
+ // src/send-file.ts
12970
+ import { constants as constants6 } from "fs";
12971
+ import { lstat as lstat8, mkdir as mkdir2, open as open7, readdir as readdir4, realpath as realpath8, rename as rename2, unlink as unlink3, writeFile as writeFile3 } from "fs/promises";
12972
+ import { basename as basename3, dirname as dirname5, isAbsolute as isAbsolute2, join as join8, relative, resolve as resolve6, sep as sep3 } from "path";
12973
+ import { createHash as createHash3, timingSafeEqual as timingSafeEqual3 } from "crypto";
12974
+ import { Database } from "bun:sqlite";
12975
+
12976
+ // src/attachment-range.ts
12977
+ var HUGE = Number.POSITIVE_INFINITY;
12978
+ function parseOffset(digits) {
12979
+ const value = Number(digits);
12980
+ if (!Number.isSafeInteger(value))
12981
+ return HUGE;
12982
+ return value;
12983
+ }
12984
+ function compareDigits(a, b) {
12985
+ const x = a.replace(/^0+/, "") || "0";
12986
+ const y = b.replace(/^0+/, "") || "0";
12987
+ if (x.length !== y.length)
12988
+ return x.length < y.length ? -1 : 1;
12989
+ if (x === y)
12990
+ return 0;
12991
+ return x < y ? -1 : 1;
12992
+ }
12993
+ function selectAttachmentRange(headers, size, etag) {
12994
+ if (!Number.isSafeInteger(size) || size < 0)
12995
+ return { kind: "full" };
12996
+ const raw = headers.get("range");
12997
+ if (raw === null)
12998
+ return { kind: "full" };
12999
+ const ifRange = headers.get("if-range");
13000
+ if (ifRange !== null && ifRange !== etag)
13001
+ return { kind: "full" };
13002
+ const unitMatch = /^([A-Za-z]+)\s*=\s*([\s\S]*)$/.exec(raw.trim());
13003
+ if (unitMatch === null)
13004
+ return { kind: "full" };
13005
+ if (unitMatch[1].toLowerCase() !== "bytes")
13006
+ return { kind: "full" };
13007
+ const spec = unitMatch[2].trim();
13008
+ if (spec.includes(","))
13009
+ return { kind: "full" };
13010
+ const suffix = /^\s*-\s*(\d+)\s*$/.exec(spec);
13011
+ if (suffix !== null) {
13012
+ const length = parseOffset(suffix[1]);
13013
+ if (length === 0 || size === 0)
13014
+ return { kind: "unsatisfiable" };
13015
+ if (length === HUGE || length >= size) {
13016
+ return { kind: "partial", start: 0, end: size - 1 };
13017
+ }
13018
+ return { kind: "partial", start: size - length, end: size - 1 };
13019
+ }
13020
+ const open = /^(\d+)\s*-\s*$/.exec(spec);
13021
+ if (open !== null) {
13022
+ const start = parseOffset(open[1]);
13023
+ if (start === HUGE || start >= size)
13024
+ return { kind: "unsatisfiable" };
13025
+ return { kind: "partial", start, end: size - 1 };
13026
+ }
13027
+ const closed = /^(\d+)\s*-\s*(\d+)\s*$/.exec(spec);
13028
+ if (closed === null)
13029
+ return { kind: "full" };
13030
+ if (compareDigits(closed[1], closed[2]) > 0)
13031
+ return { kind: "full" };
13032
+ const start = parseOffset(closed[1]);
13033
+ if (start === HUGE || start >= size)
13034
+ return { kind: "unsatisfiable" };
13035
+ const end = parseOffset(closed[2]);
13036
+ const clamped = end === HUGE || end >= size ? size - 1 : end;
13037
+ return { kind: "partial", start, end: clamped };
13038
+ }
13039
+
13040
+ // src/send-file.ts
13041
+ var attachmentId = uuid2().regex(/^[a-f0-9-]+$/u);
13042
+ var displayControls2 = /[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}]/u;
13043
+ var nameSchema = string2().min(1).max(255).refine((name) => !displayControls2.test(name) && !/[:/\\]/u.test(name));
13044
+ var receiptSchema = strictObject({
13045
+ omoWebAttachment: literal(1),
13046
+ id: attachmentId,
13047
+ name: nameSchema,
13048
+ size: number2().int().nonnegative()
13049
+ });
13050
+ var metadataSchema = strictObject({ sessionId: sessionKey, receipt: receiptSchema });
13051
+ var registrationSchema = strictObject({
13052
+ sessionId: string2().min(1).max(200),
13053
+ sessionFile: string2().min(1).max(4096),
13054
+ cwd: string2().min(1).max(4096),
13055
+ path: string2().min(1).max(4096)
13056
+ });
13057
+ var refused3 = () => new WebError(403, "attachment_refused", "\u65E0\u6CD5\u4ECE\u6B64\u4F1A\u8BDD\u53D1\u9001\u8BE5\u6587\u4EF6\u3002");
13058
+ var missing = () => new WebError(404, "attachment_not_found", "\u627E\u4E0D\u5230\u6B64\u9644\u4EF6\u3002");
13059
+ var quotaExceeded = () => new WebError(507, "attachment_quota_exceeded", "\u9644\u4EF6\u5B58\u50A8\u914D\u989D\u4E0D\u8DB3\u3002");
13060
+ function privateDirectory(info) {
13061
+ return info.isDirectory() && (process.platform === "win32" || info.uid === process.getuid?.() && (info.mode & 63) === 0);
13062
+ }
13063
+
13064
+ class AttachmentStore {
13065
+ #dataDir;
13066
+ #directory = "";
13067
+ #used = 0n;
13068
+ #quota;
13069
+ #queue = Promise.resolve();
13070
+ #lock;
13071
+ #identity;
13072
+ constructor(dataDir, quotaBytes) {
13073
+ this.#dataDir = resolve6(dataDir);
13074
+ this.#quota = quotaBytes === undefined ? undefined : BigInt(quotaBytes);
13075
+ }
13076
+ async load() {
13077
+ await mkdir2(this.#dataDir, { recursive: true, mode: 448 });
13078
+ this.#directory = join8(await realpath8(this.#dataDir), "attachments");
13079
+ await mkdir2(this.#directory, { recursive: true, mode: 448 });
13080
+ const directory = await lstat8(this.#directory);
13081
+ if (!privateDirectory(directory) || await realpath8(this.#directory) !== this.#directory)
13082
+ throw refused3();
13083
+ const lockPath = join8(dirname5(this.#directory), ".attachments-lock.sqlite");
13084
+ const lockFile = await open7(lockPath, constants6.O_CREAT | constants6.O_RDWR | constants6.O_NOFOLLOW, 384);
13085
+ try {
13086
+ if (!(await lockFile.stat()).isFile())
13087
+ throw refused3();
13088
+ } finally {
13089
+ await lockFile.close();
13090
+ }
13091
+ const lock = new Database(lockPath);
13092
+ try {
13093
+ lock.exec("BEGIN EXCLUSIVE");
13094
+ this.#used = 0n;
13095
+ for (const entry of await readdir4(this.#directory, { withFileTypes: true })) {
13096
+ if (!entry.isFile())
13097
+ throw refused3();
13098
+ if (this.#quota !== undefined) {
13099
+ this.#used += (await lstat8(join8(this.#directory, entry.name), { bigint: true })).size;
13100
+ }
13101
+ }
13102
+ this.#identity = { dev: directory.dev, ino: directory.ino };
13103
+ await this.#verifyDirectory();
13104
+ this.#lock = lock;
13105
+ } catch (error) {
13106
+ lock.close();
13107
+ throw error;
13108
+ }
13109
+ }
13110
+ async close() {
13111
+ await this.#queue;
13112
+ this.#lock?.close();
13113
+ this.#lock = undefined;
13114
+ this.#identity = undefined;
13115
+ }
13116
+ async#verifyDirectory() {
13117
+ if (!this.#identity)
13118
+ throw refused3();
13119
+ const directory = await lstat8(this.#directory);
13120
+ if (!privateDirectory(directory) || directory.dev !== this.#identity.dev || directory.ino !== this.#identity.ino || await realpath8(this.#directory) !== this.#directory)
13121
+ throw refused3();
13122
+ }
13123
+ register(input, binding, signal) {
13124
+ const operation = this.#queue.then(() => this.#copy(input, binding, signal));
13125
+ this.#queue = operation.then(() => {
13126
+ return;
13127
+ }, () => {
13128
+ return;
13129
+ });
13130
+ return operation;
13131
+ }
13132
+ async#copy(input, binding, signal) {
13133
+ signal?.throwIfAborted();
13134
+ await binding.verify();
13135
+ await this.#verifyDirectory();
13136
+ if (displayControls2.test(input.path) || !nameSchema.safeParse(basename3(input.path)).success || process.platform === "win32" && input.path.replace(/^[a-z]:/iu, "").includes(":"))
13137
+ throw refused3();
13138
+ const workspace = resolve6(input.cwd);
13139
+ const source = resolve6(workspace, input.path);
13140
+ const local = relative(workspace, source);
13141
+ if (!local || local === ".." || local.startsWith(`..${sep3}`) || isAbsolute2(local) || await realpath8(workspace) !== workspace || await realpath8(source) !== source)
13142
+ throw refused3();
13143
+ const name = basename3(source);
13144
+ const before = await lstat8(source, { bigint: true });
13145
+ if (!before.isFile() || before.nlink > 1n || before.size > BigInt(Number.MAX_SAFE_INTEGER))
13146
+ throw refused3();
13147
+ const size = Number(before.size);
13148
+ const identity = (a, b) => a.dev === b.dev && a.ino === b.ino && a.nlink === b.nlink && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs && a.mode === b.mode;
13149
+ const id = crypto.randomUUID();
13150
+ const receipt = { omoWebAttachment: 1, id, name, size };
13151
+ const metadata = JSON.stringify({ sessionId: binding.id, receipt });
13152
+ const metadataSize = BigInt(Buffer.byteLength(metadata));
13153
+ if (this.#quota !== undefined && this.#used + before.size + metadataSize > this.#quota)
13154
+ throw quotaExceeded();
13155
+ const stage = join8(this.#directory, `${id}.stage`);
13156
+ const blob = join8(this.#directory, `${id}.blob`);
13157
+ const sourceFile = await open7(source, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
13158
+ let staged = false;
13159
+ let reserved = false;
13160
+ let attemptedMetadata = false;
13161
+ try {
13162
+ if (!identity(before, await sourceFile.stat({ bigint: true })))
13163
+ throw refused3();
13164
+ const target = await open7(stage, "wx", 384);
13165
+ staged = true;
13166
+ this.#used += before.size + metadataSize;
13167
+ reserved = true;
13168
+ try {
13169
+ const buffer = Buffer.allocUnsafe(64 * 1024);
13170
+ let offset = 0;
13171
+ while (offset < size) {
13172
+ signal?.throwIfAborted();
13173
+ const { bytesRead } = await sourceFile.read(buffer, 0, Math.min(buffer.length, size - offset), offset);
13174
+ if (!bytesRead)
13175
+ throw refused3();
13176
+ await target.writeFile(buffer.subarray(0, bytesRead));
13177
+ offset += bytesRead;
13178
+ }
13179
+ await target.sync();
13180
+ } finally {
13181
+ await target.close();
13182
+ }
13183
+ if (!identity(before, await sourceFile.stat({ bigint: true })) || !identity(before, await lstat8(source, { bigint: true })) || await realpath8(source) !== source)
13184
+ throw refused3();
13185
+ await binding.verify();
13186
+ await this.#verifyDirectory();
13187
+ signal?.throwIfAborted();
13188
+ await rename2(stage, blob);
13189
+ staged = false;
13190
+ attemptedMetadata = true;
13191
+ await writeFile3(join8(this.#directory, `${id}.json`), metadata, { flag: "wx", mode: 384 });
13192
+ return receipt;
13193
+ } finally {
13194
+ await sourceFile.close();
13195
+ if (staged) {
13196
+ await this.#verifyDirectory();
13197
+ await unlink3(stage);
13198
+ this.#used -= before.size;
13199
+ }
13200
+ if (reserved && !attemptedMetadata)
13201
+ this.#used -= metadataSize;
13202
+ }
13203
+ }
13204
+ async download(sessionId, id, requestHeaders = new Headers) {
13205
+ await this.#verifyDirectory();
13206
+ const parsed = attachmentId.safeParse(id);
13207
+ if (!parsed.success)
13208
+ throw missing();
13209
+ const path = join8(this.#directory, `${parsed.data}.json`);
13210
+ let data;
13211
+ try {
13212
+ const metadata = await open7(path, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
13213
+ try {
13214
+ const info = await metadata.stat();
13215
+ if (!info.isFile() || info.size > 4096)
13216
+ throw missing();
13217
+ const bytes = Buffer.alloc(info.size);
13218
+ let offset = 0;
13219
+ while (offset < bytes.length) {
13220
+ const { bytesRead } = await metadata.read(bytes, offset, bytes.length - offset, offset);
13221
+ if (!bytesRead)
13222
+ throw missing();
13223
+ offset += bytesRead;
13224
+ }
13225
+ if ((await metadata.stat()).size !== info.size)
13226
+ throw missing();
13227
+ data = JSON.parse(bytes.toString("utf8"));
13228
+ } finally {
13229
+ await metadata.close();
13230
+ }
13231
+ } catch (error) {
13232
+ if (error instanceof WebError)
13233
+ throw error;
13234
+ if (error instanceof SyntaxError || error instanceof Error && "code" in error && error.code === "ENOENT")
13235
+ throw missing();
13236
+ throw error;
13237
+ }
13238
+ const meta = metadataSchema.safeParse(data);
13239
+ if (!meta.success || meta.data.sessionId !== sessionId || meta.data.receipt.id !== id)
13240
+ throw missing();
13241
+ await this.#verifyDirectory();
13242
+ const blob = join8(this.#directory, `${id}.blob`);
13243
+ const file = await open7(blob, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK).catch((error) => {
13244
+ if (error.code === "ENOENT")
13245
+ throw missing();
13246
+ throw error;
13247
+ });
13248
+ const info = await file.stat({ bigint: true }).finally(() => file.close());
13249
+ const { name, size } = meta.data.receipt;
13250
+ if (!info.isFile() || info.nlink !== 1n || info.size !== BigInt(size))
13251
+ throw missing();
13252
+ const etag = `"${createHash3("sha256").update(`${id}:${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`).digest("hex")}"`;
13253
+ const range = selectAttachmentRange(requestHeaders, size, etag);
13254
+ const headers = new Headers({
13255
+ "Accept-Ranges": "bytes",
13256
+ ETag: etag,
13257
+ "Cache-Control": "no-store",
13258
+ "X-Content-Type-Options": "nosniff"
13259
+ });
13260
+ if (range.kind === "unsatisfiable") {
13261
+ headers.set("Content-Range", `bytes */${size}`);
13262
+ return new Response(null, { status: 416, headers });
13263
+ }
13264
+ const encoded = encodeURIComponent(name).replace(/[!'()*]/gu, (value) => `%${value.charCodeAt(0).toString(16).toUpperCase()}`);
13265
+ const end = range.kind === "partial" ? range.end + 1 : size;
13266
+ const offset = range.kind === "partial" ? range.start : 0;
13267
+ headers.set("Content-Type", "application/octet-stream");
13268
+ headers.set("Content-Disposition", `attachment; filename="download"; filename*=UTF-8''${encoded}`);
13269
+ headers.set("Content-Length", String(end - offset));
13270
+ if (range.kind === "partial")
13271
+ headers.set("Content-Range", `bytes ${offset}-${end - 1}/${size}`);
13272
+ if (offset === end)
13273
+ return new Response(null, { headers });
13274
+ await this.#verifyDirectory();
13275
+ const current = await lstat8(blob, { bigint: true });
13276
+ if (!current.isFile() || current.nlink !== 1n || current.dev !== info.dev || current.ino !== info.ino || current.size !== info.size || current.mtimeNs !== info.mtimeNs || current.ctimeNs !== info.ctimeNs)
13277
+ throw missing();
13278
+ const body = Bun.file(blob).slice(offset, end);
13279
+ return new Response(body, { status: range.kind === "partial" ? 206 : 200, headers });
13280
+ }
13281
+ }
13282
+ async function startSendFile(dataDir, resolveBinding, quotaBytes) {
13283
+ const store = new AttachmentStore(dataDir, quotaBytes);
13284
+ await store.load();
13285
+ const secret = crypto.randomUUID() + crypto.randomUUID();
13286
+ const secretBytes = Buffer.from(`Bearer ${secret}`);
13287
+ let server;
13288
+ try {
13289
+ server = Bun.serve({
13290
+ hostname: "127.0.0.1",
13291
+ port: 0,
13292
+ maxRequestBodySize: 8192,
13293
+ async fetch(request, listener) {
13294
+ try {
13295
+ const auth = Buffer.from(request.headers.get("authorization") ?? "");
13296
+ if (request.method !== "POST" || new URL(request.url).pathname !== "/register" || request.headers.get("host") !== listener.url.host || request.headers.has("origin") || request.headers.has("sec-fetch-site") || auth.length !== secretBytes.length || !timingSafeEqual3(auth, secretBytes) || request.headers.get("content-type") !== "application/json")
13297
+ throw refused3();
13298
+ const text = await request.text();
13299
+ if (Buffer.byteLength(text) > 8192)
13300
+ throw refused3();
13301
+ const input = registrationSchema.parse(JSON.parse(text));
13302
+ const binding = await resolveBinding(input);
13303
+ listener.timeout(request, 0);
13304
+ return Response.json(await store.register(input, binding, request.signal), { headers: { "Cache-Control": "no-store" } });
13305
+ } catch (error) {
13306
+ if (!(error instanceof Error))
13307
+ throw error;
13308
+ if (request.signal.aborted)
13309
+ return new Response(null, { status: 408 });
13310
+ if (error instanceof WebError && error.code === "attachment_quota_exceeded") {
13311
+ return Response.json({ code: error.code }, { status: error.status });
13312
+ }
13313
+ const expected = error instanceof WebError || error instanceof ZodError || error instanceof SyntaxError || "code" in error && ["ENOENT", "EACCES", "EPERM", "ENOTDIR", "ELOOP", "ENAMETOOLONG"].includes(String(error.code));
13314
+ if (!expected)
13315
+ console.error("OmO Web attachment registration failed", error);
13316
+ return Response.json({ error: "File registration refused" }, { status: expected ? 403 : 500 });
13317
+ }
13318
+ }
13319
+ });
13320
+ } catch (error) {
13321
+ await store.close();
13322
+ throw error;
13323
+ }
13324
+ return { store, url: new URL("/register", server.url).href, secret, async stop() {
13325
+ await server.stop(true);
13326
+ await store.close();
13327
+ } };
13328
+ }
13329
+
12941
13330
  // src/terminal-sessions.ts
12942
- import { createHash as createHash4, createHmac as createHmac4, randomBytes as randomBytes5 } from "crypto";
13331
+ import { createHash as createHash5, createHmac as createHmac4, randomBytes as randomBytes5 } from "crypto";
12943
13332
 
12944
13333
  // src/terminal-registry.ts
12945
- import { createHash as createHash3 } from "crypto";
12946
- import { constants as constants6 } from "fs";
12947
- import { lstat as lstat8, open as open7, opendir as opendir2 } from "fs/promises";
13334
+ import { createHash as createHash4 } from "crypto";
13335
+ import { constants as constants7 } from "fs";
13336
+ import { lstat as lstat9, open as open8, opendir as opendir2 } from "fs/promises";
12948
13337
  import { tmpdir as tmpdir2 } from "os";
12949
- import { basename as basename3, dirname as dirname5, join as join8, resolve as resolve6 } from "path";
13338
+ import { basename as basename4, dirname as dirname6, join as join9, resolve as resolve7 } from "path";
12950
13339
  var registryName = /^[0-9a-f]{16}$/;
12951
13340
  var socketName = /^t-[0-9a-f]{16}\.sock$/;
12952
13341
  var MAX_REGISTRY_ENTRIES = 256;
@@ -12954,7 +13343,7 @@ var MAX_SOCKET_PATH_BYTES = 103;
12954
13343
  var MAX_REGISTRY_BYTES = 8192;
12955
13344
  var SECRET_BYTES = 32;
12956
13345
  var uid = process.getuid?.();
12957
- var hash = (value) => createHash3("sha256").update(value).digest("hex");
13346
+ var hash = (value) => createHash4("sha256").update(value).digest("hex");
12958
13347
  var manifest = object({
12959
13348
  layout: literal(2),
12960
13349
  registry_version: literal(1),
@@ -12988,16 +13377,16 @@ async function fileOperation(operation) {
12988
13377
  throw error;
12989
13378
  }
12990
13379
  }
12991
- var stat2 = (path) => fileOperation(lstat8(path, { bigint: true }));
13380
+ var stat2 = (path) => fileOperation(lstat9(path, { bigint: true }));
12992
13381
  var inode = (info) => `${info.dev}:${info.ino}`;
12993
13382
  var version2 = (info) => `${inode(info)}:${info.uid}:${info.mode}:${info.nlink}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
12994
13383
  var permissions = (info) => Number(info.mode & 0o7777n);
12995
13384
  var owned = (info) => uid !== undefined && info.uid === BigInt(uid);
12996
13385
  async function directoryChain(path, privateEnd) {
12997
13386
  const chain = [];
12998
- for (let current = path;; current = dirname5(current)) {
13387
+ for (let current = path;; current = dirname6(current)) {
12999
13388
  chain.unshift(current);
13000
- if (dirname5(current) === current)
13389
+ if (dirname6(current) === current)
13001
13390
  break;
13002
13391
  }
13003
13392
  const ids = [];
@@ -13021,7 +13410,7 @@ async function protectedFile(path, maxBytes) {
13021
13410
  const before = await stat2(path);
13022
13411
  if (!before || !valid(before))
13023
13412
  return;
13024
- const handle = await fileOperation(open7(path, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK));
13413
+ const handle = await fileOperation(open8(path, constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK));
13025
13414
  if (!handle)
13026
13415
  return;
13027
13416
  try {
@@ -13062,8 +13451,8 @@ async function registryFile(path, schema) {
13062
13451
  async function discoverTerminalRegistry(agentDir) {
13063
13452
  if (!agentDir || uid === undefined || process.platform === "win32")
13064
13453
  return;
13065
- const profile = resolve6(agentDir);
13066
- const directory = join8(profile, "rpc-host-daemon");
13454
+ const profile = resolve7(agentDir);
13455
+ const directory = join9(profile, "rpc-host-daemon");
13067
13456
  if (!await directoryChain(directory, true) || !await directoryChain(profile, false))
13068
13457
  return;
13069
13458
  const dir = await fileOperation(opendir2(directory));
@@ -13085,43 +13474,43 @@ async function discoverTerminalRegistry(agentDir) {
13085
13474
  }
13086
13475
  }
13087
13476
  async function registeredTerminal(registry, name) {
13088
- const dir = join8(registry.directory, name);
13477
+ const dir = join9(registry.directory, name);
13089
13478
  const directoryId = await directoryChain(dir, true);
13090
13479
  if (!directoryId || !await directoryChain(registry.directory, true))
13091
13480
  return;
13092
- const endpointFile = await registryFile(join8(dir, "endpoint.json"), manifest);
13481
+ const endpointFile = await registryFile(join9(dir, "endpoint.json"), manifest);
13093
13482
  if (!endpointFile)
13094
13483
  return;
13095
13484
  const socket = endpointFile.value.socket;
13096
- const filename = basename3(socket);
13485
+ const filename = basename4(socket);
13097
13486
  if (!socketName.test(filename) || hash(socket).slice(0, 16) !== name)
13098
13487
  return;
13099
- const primary = join8(registry.profile, "rpc", "tui", filename);
13488
+ const primary = join9(registry.profile, "rpc", "tui", filename);
13100
13489
  if (Buffer.byteLength(primary) <= MAX_SOCKET_PATH_BYTES) {
13101
13490
  if (socket !== primary)
13102
13491
  return;
13103
13492
  } else {
13104
13493
  const fallbackName = `senpi-rpc-${hash(registry.profile).slice(0, 8)}`;
13105
- const scopedRoot = join8(tmpdir2(), fallbackName);
13106
- const scoped = join8(scopedRoot, "tui", filename);
13107
- const fallback = Buffer.byteLength(scoped) <= MAX_SOCKET_PATH_BYTES ? scopedRoot : join8("/tmp", fallbackName);
13108
- if (socket !== join8(fallback, "tui", filename) || !await directoryChain(fallback, true))
13494
+ const scopedRoot = join9(tmpdir2(), fallbackName);
13495
+ const scoped = join9(scopedRoot, "tui", filename);
13496
+ const fallback = Buffer.byteLength(scoped) <= MAX_SOCKET_PATH_BYTES ? scopedRoot : join9("/tmp", fallbackName);
13497
+ if (socket !== join9(fallback, "tui", filename) || !await directoryChain(fallback, true))
13109
13498
  return;
13110
13499
  }
13111
13500
  if (Buffer.byteLength(socket) > MAX_SOCKET_PATH_BYTES)
13112
13501
  return;
13113
- const socketDir = dirname5(socket);
13502
+ const socketDir = dirname6(socket);
13114
13503
  const socketDirectoryId = await directoryChain(socketDir, true);
13115
13504
  if (!socketDirectoryId)
13116
13505
  return;
13117
- const owner = await registryFile(join8(dir, "host.pid"), pointer);
13506
+ const owner = await registryFile(join9(dir, "host.pid"), pointer);
13118
13507
  if (!owner)
13119
13508
  return;
13120
13509
  const instance = owner.value.instance_id;
13121
13510
  if (filename !== `t-${hash(instance).slice(0, 16)}.sock` || owner.value.generation_dir !== `generations/${instance}`)
13122
13511
  return;
13123
- const generations = join8(dir, "generations");
13124
- const generationDir = join8(generations, instance);
13512
+ const generations = join9(dir, "generations");
13513
+ const generationDir = join9(generations, instance);
13125
13514
  const generationDirectoryId = await directoryChain(generationDir, true);
13126
13515
  if (!generationDirectoryId || !await directoryChain(generations, true))
13127
13516
  return;
@@ -13135,7 +13524,7 @@ async function registeredTerminal(registry, name) {
13135
13524
  } finally {
13136
13525
  await fileOperation(entries.close());
13137
13526
  }
13138
- const current = await registryFile(join8(generationDir, "host.pid"), generation);
13527
+ const current = await registryFile(join9(generationDir, "host.pid"), generation);
13139
13528
  if (!current || current.value.instance_id !== instance || current.value.socket !== socket || current.value.pid !== owner.value.writer.pid || current.value.writer.pid !== owner.value.writer.pid || current.value.processStartTime !== owner.value.writer.startTime || current.value.writer.startTime !== owner.value.writer.startTime)
13140
13529
  return;
13141
13530
  const socketInfo = await stat2(socket);
@@ -13278,7 +13667,7 @@ class TerminalSessions {
13278
13667
  const { state } = await this.#refresh(slot.candidate, peer);
13279
13668
  this.#ensureSelected(slot);
13280
13669
  const { message, mode, clientMessageId, expectedTurnId } = checked.data;
13281
- const fingerprint = createHash4("sha256").update(JSON.stringify([mode, message, expectedTurnId])).digest("hex");
13670
+ const fingerprint = createHash5("sha256").update(JSON.stringify([mode, message, expectedTurnId])).digest("hex");
13282
13671
  const key = `${id}:${clientMessageId}`;
13283
13672
  const prior = this.#receipts.get(key);
13284
13673
  if (prior) {
@@ -13688,9 +14077,9 @@ class TerminalSessions {
13688
14077
  }
13689
14078
 
13690
14079
  // src/web-access.ts
13691
- import { createHash as createHash5, timingSafeEqual as timingSafeEqual3, X509Certificate } from "crypto";
13692
- import { constants as constants7 } from "fs";
13693
- import { open as open8 } from "fs/promises";
14080
+ import { createHash as createHash6, timingSafeEqual as timingSafeEqual4, X509Certificate } from "crypto";
14081
+ import { constants as constants8 } from "fs";
14082
+ import { open as open9 } from "fs/promises";
13694
14083
  import { isIP } from "net";
13695
14084
  import { createSecureContext } from "tls";
13696
14085
 
@@ -13729,7 +14118,7 @@ function isRemoteAddress(host) {
13729
14118
 
13730
14119
  // packaging/npm/windows-password.js
13731
14120
  import { execFile } from "child_process";
13732
- import { join as join9, resolve as resolve7 } from "path";
14121
+ import { join as join10, resolve as resolve8 } from "path";
13733
14122
  var identity2 = String.raw`
13734
14123
  $ErrorActionPreference = 'Stop'
13735
14124
  $path = $env:OMO_WEB_ACL_PATH
@@ -13737,12 +14126,12 @@ $sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
13737
14126
  $sidType = [System.Security.Principal.SecurityIdentifier]
13738
14127
  `;
13739
14128
  function powershell(script, path, input = "") {
13740
- const executable = join9(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
14129
+ const executable = join10(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
13741
14130
  const encoded = Buffer.from(`${identity2}
13742
14131
  ${script}`, "utf16le").toString("base64");
13743
14132
  return new Promise((accept, reject) => {
13744
14133
  const child = execFile(executable, ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], {
13745
- env: { ...process.env, OMO_WEB_ACL_PATH: resolve7(path) },
14134
+ env: { ...process.env, OMO_WEB_ACL_PATH: resolve8(path) },
13746
14135
  encoding: "buffer",
13747
14136
  timeout: 8000,
13748
14137
  maxBuffer: 4096,
@@ -13849,7 +14238,7 @@ async function fileBytes(path, setting) {
13849
14238
  try {
13850
14239
  if (useWindowsACL)
13851
14240
  return await readWindowsPasswordFile(path);
13852
- await using file = await open8(path, constants7.O_RDONLY | constants7.O_NONBLOCK);
14241
+ await using file = await open9(path, constants8.O_RDONLY | constants8.O_NONBLOCK);
13853
14242
  const stat = await file.stat();
13854
14243
  if (!stat.isFile() || password && (stat.mode & 63) !== 0) {
13855
14244
  throw new WebAccessConfigError(setting, password ? cliTr("\u9700\u8981\u4EC5\u5C5E\u4E3B\u53EF\u8BBF\u95EE\u7684\u5E38\u89C4\u6587\u4EF6\uFF08\u4F8B\u5982 0600\uFF09\u3002", "Use a regular file accessible only to its owner (for example, mode 0600).") : cliTr("\u9700\u8981\u5E38\u89C4\u6587\u4EF6\u3002", "Use a regular file."));
@@ -13942,7 +14331,7 @@ async function loadWebAccess(env, port) {
13942
14331
  }
13943
14332
  weakPassword = password.length < recommendedPasswordLength;
13944
14333
  const credentials = Buffer.from(`omo:${password}`).toString("base64");
13945
- digest = createHash5("sha256").update(credentials).digest();
14334
+ digest = createHash6("sha256").update(credentials).digest();
13946
14335
  }
13947
14336
  const limiter = exposed && digest ? authFailureLimiter() : undefined;
13948
14337
  return {
@@ -13967,7 +14356,7 @@ async function loadWebAccess(env, port) {
13967
14356
  if (retryAfter !== undefined) {
13968
14357
  return new Response(null, { status: 429, headers: { ...headers, "Retry-After": String(retryAfter) } });
13969
14358
  }
13970
- if (!encoded || encoded.length < 8 || encoded.length > 176 || !timingSafeEqual3(createHash5("sha256").update(encoded).digest(), digest)) {
14359
+ if (!encoded || encoded.length < 8 || encoded.length > 176 || !timingSafeEqual4(createHash6("sha256").update(encoded).digest(), digest)) {
13971
14360
  if (source)
13972
14361
  limiter?.record(source);
13973
14362
  return new Response(null, { status: 401, headers: { ...headers, "WWW-Authenticate": 'Basic realm="OmO Web"' } });
@@ -13976,7 +14365,7 @@ async function loadWebAccess(env, port) {
13976
14365
  if (request.method === "POST") {
13977
14366
  const provided = request.headers.get("X-OmO-Token") ?? "";
13978
14367
  const bytes = provided.length === token.length ? Buffer.from(provided) : undefined;
13979
- if (requestOrigin === null || bytes?.length !== token.length || !timingSafeEqual3(bytes, token)) {
14368
+ if (requestOrigin === null || bytes?.length !== token.length || !timingSafeEqual4(bytes, token)) {
13980
14369
  throw new WebError(403, "token_refused", "\u8BF7\u5237\u65B0\u9875\u9762\u540E\u91CD\u8BD5\u3002");
13981
14370
  }
13982
14371
  } else if (request.method !== "GET") {
@@ -14158,15 +14547,35 @@ async function startApp(settings) {
14158
14547
  publish(refresh);
14159
14548
  };
14160
14549
  const terminals = new TerminalSessions(profile, workspaces, (id) => fanout({ type: "cli-live", id }));
14161
- const cliProfileDir = profile === undefined ? undefined : resolve8(profile);
14550
+ const cliProfileDir = profile === undefined ? undefined : resolve9(profile);
14162
14551
  const { OMO_WEB_PASSWORD_FILE: _passwordFile, ...engineEnv } = process.env;
14163
- const engine = new Engine(settings.engineCommand, root, (event) => sessions.event(event), (status) => {
14552
+ let extensionPath;
14553
+ let attachmentQuota;
14554
+ if (settings.sendFile) {
14555
+ const raw = settings.webEnv?.OMO_WEB_ATTACHMENT_QUOTA_BYTES;
14556
+ if (raw !== undefined) {
14557
+ const bytes = Number(raw);
14558
+ if (!/^[0-9]+$/u.test(raw) || bytes < 1 || !Number.isSafeInteger(bytes)) {
14559
+ throw new WebAccessConfigError("OMO_WEB_ATTACHMENT_QUOTA_BYTES", "Expected a positive whole number of bytes, or leave it unset.");
14560
+ }
14561
+ attachmentQuota = bytes;
14562
+ }
14563
+ const extension = new URL("../native/web-send-file.mjs", import.meta.url);
14564
+ if (!await Bun.file(extension).exists())
14565
+ throw new WebError(500, "missing_extension", "\u7F3A\u5C11\u6587\u4EF6\u53D1\u9001\u6269\u5C55\u3002");
14566
+ extensionPath = fileURLToPath(extension);
14567
+ }
14568
+ const sendFile = extensionPath ? await startSendFile(settings.dataDir, (input) => sessions.attachmentBinding(input), attachmentQuota) : undefined;
14569
+ const command = extensionPath ? [...settings.engineCommand, "--extension", extensionPath] : settings.engineCommand;
14570
+ const sendFileEnv = sendFile ? { OMO_WEB_SEND_FILE_BRIDGE: sendFile.url, OMO_WEB_SEND_FILE_SECRET: sendFile.secret } : {};
14571
+ const engine = new Engine(command, root, (event) => sessions.event(event), (status) => {
14164
14572
  if (!status.online)
14165
14573
  sessions.disconnected();
14166
14574
  if (clients.size)
14167
14575
  fanout({ type: "engine", engine: browserEngineStatus(status) });
14168
- }, undefined, cliProfileDir === undefined ? { env: engineEnv } : { privateHost: true, env: {
14576
+ }, undefined, cliProfileDir === undefined ? { env: { ...engineEnv, ...sendFileEnv } } : { privateHost: true, env: {
14169
14577
  ...engineEnv,
14578
+ ...sendFileEnv,
14170
14579
  OMO_CODING_AGENT_DIR: cliProfileDir,
14171
14580
  SENPI_CODING_AGENT_DIR: cliProfileDir,
14172
14581
  PI_CODING_AGENT_DIR: cliProfileDir,
@@ -14178,7 +14587,12 @@ async function startApp(settings) {
14178
14587
  sameProfile: cliProfileDir !== undefined,
14179
14588
  ...cliProfileDir === undefined ? {} : { profileDir: cliProfileDir }
14180
14589
  });
14181
- await sessions.load();
14590
+ try {
14591
+ await sessions.load();
14592
+ } catch (error) {
14593
+ await sendFile?.stop();
14594
+ throw error;
14595
+ }
14182
14596
  async function selectedHistory(id) {
14183
14597
  const selected = id === undefined ? undefined : historySessions.get(id);
14184
14598
  if (!selected || selected.workspaceKey === undefined || await workspaces.exact(selected.cwd) !== selected.workspaceKey) {
@@ -14368,6 +14782,12 @@ async function startApp(settings) {
14368
14782
  const dag = /^\/api\/sessions\/([a-z0-9-]+)\/native-runtime\/dag\/([a-f0-9]{64})$/u.exec(pathname);
14369
14783
  if (request.method === "GET" && dag?.[2])
14370
14784
  return json(await sessions.nativeDag(sessionKey.parse(dag[1]), dag[2]));
14785
+ const attachment = /^\/api\/sessions\/([a-z0-9-]+)\/attachments\/([a-f0-9-]+)$/u.exec(pathname);
14786
+ if (request.method === "GET" && attachment?.[2] && sendFile) {
14787
+ const id = sessionKey.parse(attachment[1]);
14788
+ await sessions.authorizeAttachment(id);
14789
+ return await sendFile.store.download(id, attachment[2], request.headers);
14790
+ }
14371
14791
  const route = /^\/api\/sessions\/([a-z0-9-]+)(?:\/(options|model-preview|details|queue|tree|branch-runtime|instructions|capabilities|activity|native-runtime|workbench-status|actions|branch-options|branches|handoff|last-assistant|transcript(?:\/content)?))?$/i.exec(pathname);
14372
14792
  if (route) {
14373
14793
  const id = sessionKey.parse(route[1]);
@@ -14465,14 +14885,20 @@ async function startApp(settings) {
14465
14885
  return json({ code: "internal_error", error: "OmO Web \u51FA\u73B0\u9519\u8BEF\uFF1B\u8BF7\u67E5\u770B\u672C\u673A\u7EC8\u7AEF\u3002" }, 500);
14466
14886
  }
14467
14887
  };
14468
- const server = Bun.serve({
14469
- hostname: access.hostname,
14470
- port: settings.port,
14471
- ...access.tls === undefined ? {} : { tls: access.tls },
14472
- idleTimeout: 10,
14473
- maxRequestBodySize: MAX_REQUEST_BYTES,
14474
- fetch
14475
- });
14888
+ let server;
14889
+ try {
14890
+ server = Bun.serve({
14891
+ hostname: access.hostname,
14892
+ port: settings.port,
14893
+ ...access.tls === undefined ? {} : { tls: access.tls },
14894
+ idleTimeout: 10,
14895
+ maxRequestBodySize: MAX_REQUEST_BYTES,
14896
+ fetch
14897
+ });
14898
+ } catch (error) {
14899
+ await sendFile?.stop();
14900
+ throw error;
14901
+ }
14476
14902
  const url = access.origin === undefined ? server.url : new URL(access.origin);
14477
14903
  const heartbeat = setInterval(() => publish(encoder.encode(`: keepalive
14478
14904
 
@@ -14491,7 +14917,7 @@ async function startApp(settings) {
14491
14917
  sessions.stop();
14492
14918
  for (const client of clients)
14493
14919
  disconnect(client);
14494
- await Promise.all([server.stop(true), engine.stop()]);
14920
+ await Promise.all([server.stop(true), engine.stop(), sendFile?.stop()]);
14495
14921
  })();
14496
14922
  return closing;
14497
14923
  }
@@ -14504,20 +14930,21 @@ if (!Number.isInteger(port) || port < 0 || port > 65535) {
14504
14930
  console.error(`OmO Web config: OMO_WEB_PORT: ${cliTr("\u7AEF\u53E3\u5FC5\u987B\u662F 0\u201365535 \u7684\u6574\u6570\u3002", "Expected an integer from 0 to 65535.")}`);
14505
14931
  process.exit(1);
14506
14932
  }
14507
- var missing = await missingWebAssets();
14508
- if (missing.length) {
14509
- console.error(cliTr(`OmO Web \u65E0\u6CD5\u542F\u52A8\uFF1A\u7F3A\u5C11\u9759\u6001\u8D44\u6E90 ${missing.join("\u3001")}\u3002\u6E90\u7801\u8FD0\u884C bun run build\uFF1B\u53D1\u884C\u5305\u91CD\u65B0\u6821\u9A8C\u5E76\u89E3\u538B\u3002`, `OmO Web cannot start: missing assets ${missing.join(", ")}. Run bun run build in a source checkout, or verify and re-extract the release.`));
14933
+ var missing2 = await missingWebAssets();
14934
+ if (missing2.length) {
14935
+ console.error(cliTr(`OmO Web \u65E0\u6CD5\u542F\u52A8\uFF1A\u7F3A\u5C11\u9759\u6001\u8D44\u6E90 ${missing2.join("\u3001")}\u3002\u6E90\u7801\u8FD0\u884C bun run build\uFF1B\u53D1\u884C\u5305\u91CD\u65B0\u6821\u9A8C\u5E76\u89E3\u538B\u3002`, `OmO Web cannot start: missing assets ${missing2.join(", ")}. Run bun run build in a source checkout, or verify and re-extract the release.`));
14510
14936
  process.exit(1);
14511
14937
  }
14512
14938
  var configured = process.env.OMO_WEB_WORKSPACES;
14513
- var workspaces = configured ? configured.split(delimiter).filter(Boolean).map((path) => resolve9(path)) : [process.cwd()];
14514
- var cliProfile = process.env.OMO_WEB_CLI_AGENT_DIR ?? (process.env.OMO_CODING_AGENT_DIR || process.env.SENPI_CODING_AGENT_DIR || process.env.PI_CODING_AGENT_DIR || join10(homedir(), ".omo", "agent"));
14939
+ var workspaces = configured ? configured.split(delimiter).filter(Boolean).map((path) => resolve10(path)) : [process.cwd()];
14940
+ var cliProfile = process.env.OMO_WEB_CLI_AGENT_DIR ?? (process.env.OMO_CODING_AGENT_DIR || process.env.SENPI_CODING_AGENT_DIR || process.env.PI_CODING_AGENT_DIR || join11(homedir(), ".omo", "agent"));
14515
14941
  var app = await startApp({
14516
14942
  port,
14517
14943
  webEnv: process.env,
14518
- dataDir: resolve9(process.env.OMO_WEB_DATA ?? join10(homedir(), ".omo-web")),
14944
+ dataDir: resolve10(process.env.OMO_WEB_DATA ?? join11(homedir(), ".omo-web")),
14519
14945
  workspaces,
14520
- ...cliProfile.trim() ? { cliAgentDir: resolve9(cliProfile) } : {},
14946
+ sendFile: true,
14947
+ ...cliProfile.trim() ? { cliAgentDir: resolve10(cliProfile) } : {},
14521
14948
  engineCommand: [
14522
14949
  process.env.OMO_WEB_BIN || "omo",
14523
14950
  "--mode",