mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-11-22 05:27:07 +08:00
Copy was broken twice over. `langbot.api()` already resolves the unwrapped
payload (PageResponse.ok -> HTTP data -> resp.data.data -> the SDK's
resolve(data.data)), so `item.data.url` was always `undefined` and the page
copied an empty string. `writeText('')` resolves without throwing, so it also
never reached the fallback: the UI said "copied" while the clipboard stayed
empty.
The iframe is worse than assumed. It is a `blob:` document under
`sandbox="allow-scripts allow-forms"`, so its origin is opaque: `location.origin`
is "null", relative asset URLs do not load, and `navigator.clipboard` rejects
with NotAllowedError. `/list` returns relative URLs while `public_base_url` is
empty, so even a correct value would have pasted as an unusable path. URLs are
now made absolute against `location.ancestorOrigins[0]` before either the
clipboard or an `<img src>`, and copy reads `item.url` from the list cache
instead of making a redundant `/item` round trip.
Every other call had the same layer mistake: `res.error` is never set on a
resolved value, because failures reject the promise, so no failure ever
surfaced. All call sites now catch, and an empty URL toasts an error rather
than claiming success.
Verified in a real blob: iframe with the real sandbox: relative url -> absolute
-> clipboard read back byte for byte, and the same URL loads as the preview
(0 `/image` calls). Also passes with `navigator.clipboard` removed, proving the
execCommand tier is what carries it.
The host is untouched now, so this is plugin-only; the `allow-modals` flip is
dropped and the clear confirmation stays in-page.
Co-authored-by: multica-agent <github@multica.ai>
108 lines
3.6 KiB
Python
108 lines
3.6 KiB
Python
"""Remote-image fetching: bounded streaming and validation."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import contextlib
|
|
import threading
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
import pytest
|
|
|
|
PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 16
|
|
|
|
|
|
def run(coro):
|
|
return asyncio.run(coro)
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def serve(payload=PNG, *, status=200, content_type="image/png", send_length=True):
|
|
"""Serve ``payload`` from a throwaway local HTTP server."""
|
|
|
|
class Handler(BaseHTTPRequestHandler):
|
|
def do_GET(self): # noqa: N802 - http.server API
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", content_type)
|
|
if send_length:
|
|
self.send_header("Content-Length", str(len(payload)))
|
|
self.end_headers()
|
|
self.wfile.write(payload)
|
|
|
|
def log_message(self, *args): # silence test output
|
|
return None
|
|
|
|
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
host, port = httpd.server_address
|
|
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
|
|
thread.start()
|
|
try:
|
|
yield f"http://{host}:{port}/image.png"
|
|
finally:
|
|
httpd.shutdown()
|
|
httpd.server_close()
|
|
thread.join(timeout=2)
|
|
|
|
|
|
def test_add_from_url_stores_image(make_plugin):
|
|
async def scenario():
|
|
plugin, _ = make_plugin({"public_base_url": "http://localhost:5300"})
|
|
with serve() as url:
|
|
item = await plugin.add_sticker_from_url("remote-cat", url)
|
|
assert item["slug"] == "remote-cat"
|
|
assert item["mime"] == "image/png"
|
|
assert item["size"] == len(PNG)
|
|
assert item["url"].startswith("http://localhost:5300/api/v1/plugins/")
|
|
stored = await plugin.get_sticker_bytes("remote-cat")
|
|
assert stored is not None
|
|
assert stored[0] == PNG
|
|
run(scenario())
|
|
|
|
|
|
def test_add_from_url_rejects_non_http(make_plugin):
|
|
async def scenario():
|
|
plugin, _ = make_plugin()
|
|
with pytest.raises(ValueError, match="http"):
|
|
await plugin.add_sticker_from_url("cat", "ftp://example.com/cat.png")
|
|
with pytest.raises(ValueError, match="url is required"):
|
|
await plugin.add_sticker_from_url("cat", " ")
|
|
run(scenario())
|
|
|
|
|
|
def test_add_from_url_rejects_error_status(make_plugin):
|
|
async def scenario():
|
|
plugin, _ = make_plugin()
|
|
with serve(status=404) as url:
|
|
with pytest.raises(ValueError, match="status 404"):
|
|
await plugin.add_sticker_from_url("cat", url)
|
|
run(scenario())
|
|
|
|
|
|
def test_add_from_url_rejects_oversized_content_length(make_plugin):
|
|
async def scenario():
|
|
plugin, _ = make_plugin({"max_sticker_mb": 1})
|
|
big = PNG + b"\x00" * (2 * 1024 * 1024)
|
|
with serve(big) as url:
|
|
with pytest.raises(ValueError, match="larger than"):
|
|
await plugin.add_sticker_from_url("cat", url)
|
|
run(scenario())
|
|
|
|
|
|
def test_add_from_url_rejects_oversized_stream(make_plugin):
|
|
async def scenario():
|
|
plugin, _ = make_plugin({"max_sticker_mb": 1})
|
|
big = PNG + b"\x00" * (2 * 1024 * 1024)
|
|
with serve(big, send_length=False) as url:
|
|
with pytest.raises(ValueError, match="exceeds"):
|
|
await plugin.add_sticker_from_url("cat", url)
|
|
run(scenario())
|
|
|
|
|
|
def test_add_from_url_uses_declared_content_type(make_plugin):
|
|
async def scenario():
|
|
plugin, _ = make_plugin()
|
|
with serve(PNG, content_type="image/png; charset=binary") as url:
|
|
item = await plugin.add_sticker_from_url("cat", url)
|
|
assert item["mime"] == "image/png"
|
|
run(scenario())
|