ai_co_discuss 0.5.29 → 0.5.30

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/backend/server.py CHANGED
@@ -115,9 +115,13 @@ MEDIA_TICKET_SECONDS = 600
115
115
  # A project page the computer's own browser opens in a tab keeps reading the files beside it (lazy images, scripts) for
116
116
  # this long; its address is a random ticket naming the project folder, never a path.
117
117
  PAGE_TICKET_SECONDS = 12 * 3600
118
- # The page runs as an opaque origin (no allow-same-origin), so it can read nothing of this site; it may run its scripts,
119
- # open pop-ups and dialogs, and load anything from the folder or the web. No forms: a write to this site needs its origin.
120
- PAGE_POLICY = "sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox allow-modals allow-downloads"
118
+ # The most script the page may ask to put into the opened file (the preview's selection bridge).
119
+ MAX_PAGE_INJECT_BYTES = 8 * 1024
120
+ # A page is served on its own origin, `p<folder hash>.localhost:<port>` (browsers send *.localhost to this computer), so it
121
+ # runs as it would opened from disk, with its own storage (2026-11-26 user #12484: as a sandboxed opaque origin it could
122
+ # not use localStorage and its script stopped, leaving an empty page), yet shares nothing with this site's origin; on that
123
+ # host this server answers page files alone (`page_host_request`).
124
+ PAGE_HOST = re.compile(r"p([0-9a-f]{16})\.localhost:(\d+)")
121
125
  MAX_MEDIA_TICKETS = 64
122
126
  MAX_TEXT_LENGTH = 32000
123
127
  SESSION_ID_PATTERN = re.compile(r"[0-9A-Za-z_-]{8,128}")
@@ -2458,6 +2462,11 @@ def attachment_path(database, attachment):
2458
2462
  return root / attachment["id"]
2459
2463
 
2460
2464
 
2465
+ def page_host(root, port):
2466
+ """The origin host a project folder's pages are served on: one per folder, so pages of a folder keep their storage."""
2467
+ return f"p{hashlib.sha256(str(root).lower().encode('utf-8')).hexdigest()[:16]}.localhost:{port}"
2468
+
2469
+
2461
2470
  def thumbnail_path(database, attachment):
2462
2471
  """Where the smaller copy of an image attachment is kept, beside the original."""
2463
2472
  return attachment_path(database, {"id": attachment["id"] + THUMBNAIL_SUFFIX})
@@ -3740,6 +3749,10 @@ class DiscussionHandler(BaseHTTPRequestHandler):
3740
3749
  def dispatch_routes(self, method, parsed, params, parts, text_mode):
3741
3750
  """Route one request and map validation, permission and lookup errors to their status codes."""
3742
3751
  try:
3752
+ if self.page_host_request():
3753
+ if parts[:3] == ["api", "local", "page"] and len(parts) >= 5 and method == "GET":
3754
+ return self.serve_page_ticket(parts[3], parts[4:])
3755
+ raise LookupError(Text('地址不存在'))
3743
3756
  if self.entry_refused(method, parsed):
3744
3757
  return None
3745
3758
  try:
@@ -3752,8 +3765,6 @@ class DiscussionHandler(BaseHTTPRequestHandler):
3752
3765
  self.bridged = self.relay_bridge(parts)
3753
3766
  if parts[:3] == ["api", "local", "media"] and len(parts) == 4 and method == "GET":
3754
3767
  return self.serve_media_ticket(parts[3])
3755
- if parts[:3] == ["api", "local", "page"] and len(parts) >= 5 and method == "GET":
3756
- return self.serve_page_ticket(parts[3], parts[4:])
3757
3768
  if parts[:2] == ["api", "local"]:
3758
3769
  return self.handle_local_launch(parts, method)
3759
3770
  if parts == ["api", "updates"] and method == "GET":
@@ -4018,7 +4029,10 @@ class DiscussionHandler(BaseHTTPRequestHandler):
4018
4029
  """
4019
4030
  if not re.search(r"\.html?$", str(payload.get("path", "")), re.I):
4020
4031
  raise ValueError(Text('只能打开 HTML 文件'))
4021
- status, result = self.local_command_result("room-media", {**{key: value for key, value in payload.items() if key != "page"}, "download": True})
4032
+ inject = payload.get("inject") or ""
4033
+ if not isinstance(inject, str) or len(inject.encode("utf-8")) > MAX_PAGE_INJECT_BYTES:
4034
+ raise ValueError(Text('页面附加脚本无效'))
4035
+ status, result = self.local_command_result("room-media", {**{key: value for key, value in payload.items() if key not in ("page", "inject")}, "download": True})
4022
4036
  if status != 200:
4023
4037
  return self.respond(result, status)
4024
4038
  root, path = Path(result["directory"]).resolve(), Path(result["file"]).resolve()
@@ -4030,17 +4044,30 @@ class DiscussionHandler(BaseHTTPRequestHandler):
4030
4044
  del tickets[key]
4031
4045
  while len(tickets) >= MAX_MEDIA_TICKETS:
4032
4046
  del tickets[next(iter(tickets))]
4033
- tickets[ticket] = (root, now + PAGE_TICKET_SECONDS)
4047
+ # `inject`: a script the computer's own page asked to put into this file alone, after its doctype (the
4048
+ # preview's selection bridge, so a passage chosen in the page can go into the conversation).
4049
+ tickets[ticket] = (root, now + PAGE_TICKET_SECONDS, path, inject)
4034
4050
  relative = "/".join(quote(part) for part in path.relative_to(root).parts)
4035
- return self.respond({"url": f"/api/local/page/{ticket}/{relative}"})
4051
+ return self.respond({"url": f"http://{page_host(root, self.server.server_port)}/api/local/page/{ticket}/{relative}"})
4052
+
4053
+ def page_host_request(self):
4054
+ """Whether a loopback request names a page origin; such a host reaches nothing of this site but page files."""
4055
+ match = PAGE_HOST.fullmatch(self.headers.get("Host", ""))
4056
+ if not match:
4057
+ return False
4058
+ if not self.server.local_site or self.client_address[0] != "127.0.0.1" or int(match[2]) != self.server.server_port:
4059
+ raise LookupError(Text('地址不存在'))
4060
+ return True
4036
4061
 
4037
4062
  def serve_page_ticket(self, ticket, parts):
4038
- """Serve one file of the project folder a page ticket names, sandboxed; nothing outside the folder."""
4063
+ """Serve one file of the project folder a page ticket names, on that folder's own origin; nothing outside it."""
4039
4064
  with self.server.media_lock:
4040
4065
  item = self.server.page_tickets.get(ticket)
4041
4066
  if not item or item[1] <= time.time():
4042
4067
  raise LookupError(Text('页面地址已过期,请重新打开文件'))
4043
4068
  root = item[0]
4069
+ if self.headers.get("Host", "") != page_host(root, self.server.server_port):
4070
+ raise LookupError(Text('文件不存在'))
4044
4071
  names = [unquote(part) for part in parts]
4045
4072
  if any(name in ("", ".", "..") or ":" in name or "\\" in name for name in names):
4046
4073
  raise LookupError(Text('文件不存在'))
@@ -4050,7 +4077,12 @@ class DiscussionHandler(BaseHTTPRequestHandler):
4050
4077
  content_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
4051
4078
  if content_type.startswith("text/") or content_type in ("application/javascript", "application/json"):
4052
4079
  content_type += "; charset=utf-8"
4053
- self.send_file(path, content_type, path.name, "inline", policy=PAGE_POLICY)
4080
+ if item[3] and path == item[2]:
4081
+ text = path.read_bytes().decode("utf-8", errors="replace")
4082
+ doctype = re.match(r"\ufeff?\s*<!doctype[^>]*>", text, re.I)
4083
+ at = doctype.end() if doctype else 0
4084
+ return self.send_file(None, content_type, path.name, "inline", data=(text[:at] + item[3] + text[at:]).encode("utf-8"), policy="")
4085
+ self.send_file(path, content_type, path.name, "inline", policy="")
4054
4086
 
4055
4087
  def serve_media_ticket(self, ticket):
4056
4088
  """Stream the project media file a ticket names, refusing it once expired or changed since it was checked."""
@@ -4730,7 +4762,7 @@ class DiscussionHandler(BaseHTTPRequestHandler):
4730
4762
  def send_file(self, path, content_type, file_name, disposition, extra=None, data=None, policy="default-src 'none'; sandbox"):
4731
4763
  """Send one stored file, or the single byte range a player asks for, never as executable content.
4732
4764
 
4733
- `policy` is the Content-Security-Policy; a project page opened in its own tab runs sandboxed (PAGE_POLICY).
4765
+ `policy` is the Content-Security-Policy; none for a project page served on its own origin (PAGE_HOST).
4734
4766
  """
4735
4767
  size = path.stat().st_size if data is None else len(data)
4736
4768
  start, end, status = 0, size - 1, 200
@@ -4757,7 +4789,8 @@ class DiscussionHandler(BaseHTTPRequestHandler):
4757
4789
  for name, value in (extra or {}).items():
4758
4790
  self.send_header(name, value)
4759
4791
  self.send_header("X-Content-Type-Options", "nosniff")
4760
- self.send_header("Content-Security-Policy", policy)
4792
+ if policy:
4793
+ self.send_header("Content-Security-Policy", policy)
4761
4794
  self.send_header("Cache-Control", "no-store")
4762
4795
  self.send_header("Referrer-Policy", "no-referrer")
4763
4796
  self.end_headers()
@@ -139,6 +139,7 @@
139
139
  "附件上传者须与凭据身份一致": "Attachment uploader must match the credential identity",
140
140
  "附件内容不完整": "Attachment content is incomplete",
141
141
  "缩略图不符合要求": "The thumbnail does not meet the requirements",
142
+ "页面附加脚本无效": "The script to add to the page is invalid",
142
143
  "只能打开 HTML 文件": "Only HTML files can be opened",
143
144
  "页面地址已过期,请重新打开文件": "The page address has expired. Open the file again.",
144
145
  "文件不存在": "The file does not exist",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.5.29",
3
+ "version": "0.5.30",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
package/web/app.js CHANGED
@@ -6354,10 +6354,11 @@ async function read_room_media(room_id, path, root = 0, on_progress = () => {},
6354
6354
  * it, sandboxed (the local website's page ticket); null where the page is not this computer's own (another device, a
6355
6355
  * connected website), which reads the page through `read_room_page` instead (user 2026-11-26, #12397).
6356
6356
  */
6357
- async function local_page_url(room_id, path, root = 0) {
6357
+ async function local_page_url(room_id, path, root = 0, inject = "") {
6358
6358
  if (state.remote_rooms || SHARE) return null;
6359
- const answer = await local_launch_request("room-media", { room_id, path, root, page: true, token: localStorage.getItem(`discuss-access:${room_id}`) });
6360
- return answer.url && answer.url.startsWith("/api/local/page/") ? `${local_connection?.endpoint || ""}${answer.url}` : null;
6359
+ const answer = await local_launch_request("room-media", { room_id, path, root, page: true, ...(inject ? { inject } : {}), token: localStorage.getItem(`discuss-access:${room_id}`) });
6360
+ // The computer's website names the page on its own origin (a *.localhost host), so it is opened as given.
6361
+ return /^http:\/\/p[0-9a-f]{16}\.localhost:\d+\/api\/local\/page\//.test(answer.url || "") ? answer.url : null;
6361
6362
  }
6362
6363
 
6363
6364
  /**