Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.
Add the local page LAN settings API and security tests
Bowen Xueb975d8767a2a
diff --git a/freevideo_engine/agent/errors.py b/freevideo_engine/agent/errors.pyindex 21c3aed..9ec75f8 100644--- a/freevideo_engine/agent/errors.py+++ b/freevideo_engine/agent/errors.py@@ -17,6 +17,7 @@ CONFIRM = ContextVar('agent_confirm', default=None)ERRORS = {'forbidden': (403, False, 'This caller cannot write this session event.', 'Only the user may stop or continue a session or answer a confirmation; steps are written by the server.'),'session_full': (409, False, 'This session has reached its event limit.', 'Create a new session with POST /freevideo/agent/v1/sessions.'),+ 'lan_unavailable': (409, False, 'LAN settings require a launcher installation.', 'Complete installation in the FreeVideo launcher on this computer. 请在本机 FreeVideo 启动器中完成安装。'),'page_session_required': (403, False, 'A valid page session and CSRF header are required.', 'Reload the page served by this FreeVideo instance and repeat the action.'),'redirect_forbidden': (403, False, 'A credentialed request cannot follow a cross-origin redirect.', 'Connect directly to the intended FreeVideo instance using its verified HTTP or HTTPS endpoint.'),'method_not_allowed': (405, False, 'This method is not registered for the requested endpoint.', 'Read GET /freevideo/agent/v1/openapi.json and use the documented method.'),@@ -252,6 +253,7 @@ def safe_details(value):# One public sentence shared by conversation cards, HTTP and MCP. Backend text# is classified, never echoed: it can contain prompts, filenames or credentials.FAILURE_REASONS_ZH = {+ 'lan_unavailable': '局域网设置需要启动器安装记录','out_of_memory': '生成时显存或内存不足','insufficient_memory': '可用显存或内存不够生成这段内容','no_memory': '可用显存或内存不够生成这张图片',diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.pyindex da33e26..8320368 100644--- a/freevideo_engine/agent/routes.py+++ b/freevideo_engine/agent/routes.py@@ -465,13 +465,10 @@ def register():raise JobError('method_not_allowed' if any(p == suffix for _, p in contracts) else 'not_found', 'No contract')access.check(request, local=definition.get('local', False), lan=definition.get('lan', False))if definition.get('auth') is False and definition.get('local') and method not in ('GET', 'HEAD'):- session = page_sessions.get(request.cookies.get('freevideo_agent_page', ''))- csrf = request.headers.get('X-FreeVideo-CSRF', '')if proxy_identity.HEADER in request.headers:valid = definition.get('lan') and proxy_identity.check_csrf(request)else:- valid = (session is not None and session[1] >= time.monotonic() and csrf- and secrets.compare_digest(csrf.encode(), session[0].encode()))+ valid = valid_page_session(request)if not valid:raise JobError('page_session_required', 'Page session required')header = request.headers.get('Authorization', '')@@ -677,16 +674,19 @@ def register():async def body(request, **ignored):return request[body_key]+ def valid_page_session(request):+ page = page_sessions.get(request.cookies.get('freevideo_agent_page', ''))+ csrf = request.headers.get('X-FreeVideo-CSRF', '')+ return (page is not None and page[1] >= time.monotonic() and bool(csrf)+ and secrets.compare_digest(csrf.encode(), page[0].encode()))+def session_caller(request):"""guarded verifies supplied tokens; otherwise require a local page and CSRF."""header = request.headers.get('Authorization', '')given = header[7:].strip() if header[:7].lower() == 'bearer ' else request.headers.get('X-FreeVideo-Agent', '')if given:return 'agent'- page = page_sessions.get(request.cookies.get('freevideo_agent_page', ''))- csrf = request.headers.get('X-FreeVideo-CSRF', '')- if (page is not None and page[1] >= time.monotonic() and csrf- and secrets.compare_digest(csrf.encode(), page[0].encode())):+ if valid_page_session(request):access.check(request, local=True)return 'user'raise JobError('unauthorized', 'Token or valid page session required')@@ -699,7 +699,7 @@ def register():return path == '/freevideo/agent' or path.startswith('/freevideo/agent/')async def no_cross_site_headers(request, response):- if agent_path(request.path):+ if agent_path(request.path) or request.path in ('/freevideo/lan', '/api/freevideo/lan'):for key in list(response.headers):if key.lower().startswith('access-control-'):del response.headers[key]@@ -745,9 +745,52 @@ def register():response = reply(dict(csrf=page_sessions[current][0]))# The cookie follows the copy the page asked: its later calls go to the same one.response.set_cookie('freevideo_agent_page', current, httponly=True, samesite='Strict', secure=request.secure,- path=('/api' if request.path.startswith('/api/') else '') + '/freevideo/agent', max_age=12 * 3600)+ path=('/api' if request.path.startswith('/api/') else '') + '/freevideo', max_age=12 * 3600)return response+ # Page controls stay outside the Agent contract and never use its bearer token.+ # ComfyUI mirrors these routes under /api along with the other page routes.+ @routes.get('/freevideo/lan')+ @routes.post('/freevideo/lan')+ async def lan_settings(request):+ from .. import lan_page+ from ..comfy_bridge import installation_root+ identity = errors.REQUEST_ID.set('r-' + uuid.uuid4().hex)+ try:+ access.check(request, local=True)+ root = installation_root()+ if request.method == 'POST':+ if not valid_page_session(request):+ raise JobError('page_session_required', 'Page session required')+ value = await read_body(request, contract.MAX_BODY_BYTES)+ return reply(await asyncio.to_thread(lan_page.apply, root, value))+ return reply(await asyncio.to_thread(lan_page.read, root))+ except lan_page.InvalidRequest as error:+ field = error.field if error.field in ('enabled', 'password', '') else '<unknown>'+ row = contract.diagnostic('/' + field, error.allowed, error.got)+ if field == 'password' and not isinstance(error.got, str):+ row = contract.diagnostic('/password', error.allowed, None)+ row.update(got='<redacted>', message='/password must be %s.' % error.allowed)+ value = errors.validation([row])+ return reply({'error': value}, 422)+ except lan_page.LanUnavailable:+ return problem('lan_unavailable')+ except JobError as error:+ return reply({'error': error.view()}, errors.ERRORS[error.code][0])+ except (json.JSONDecodeError, UnicodeDecodeError, RecursionError):+ return problem('invalid_json')+ except specs.SpecError as error:+ return reply({'error': errors.validation(error.errors)}, 422)+ except web.HTTPException as error:+ return problem('too_large' if error.status == 413 else 'invalid_request')+ except OSError:+ return problem('storage_unavailable')+ except Exception:+ # Do not log exception text or request bodies from password controls.+ return problem('internal_error')+ finally:+ errors.REQUEST_ID.reset(identity)+def activity_item(row, *, card=False):view = jobs.view(row, detail=False)value = {k: view.get(k) for k in ('id', 'kind', 'status', 'label', 'project', 'client', 'take',diff --git a/freevideo_engine/comfy_launcher_runtime.py b/freevideo_engine/comfy_launcher_runtime.pyindex 271d9e6..ddcf4ed 100644--- a/freevideo_engine/comfy_launcher_runtime.py+++ b/freevideo_engine/comfy_launcher_runtime.py@@ -405,6 +405,19 @@ def address(hostname, port):return 'http://%s:%d' % ('[%s]' % hostname if ':' in hostname else hostname, port)+def lan_access_links(engine, port, *, password_set=None):+ """Use the same phone entry and authentication policy for launcher and page."""+ from .comfy_service import token+ from .proxy import local_addresses+ hosts = local_addresses()+ if not hosts:+ return []+ if password_set is None:+ password_set = lan_password.is_set(engine)+ suffix = '/m/' if password_set else '/m/?freevideo=launch&token=' + token(engine)+ return [address(host, port) + suffix for host in hosts]++def next_free_address(url, count=12):"""The next local address after this one that nothing listens or answers on, as setup.sh chooses."""parsed = urlsplit(url)@@ -743,13 +756,10 @@ class Controller:self.state = dict(self.state, selection=dict(self.selection), lan_status='stopped')def refresh_access_links(self):- from .comfy_service import token- from .proxy import local_addressesself.access_polled = time.monotonic()- secret = token(self.selection['engine'])password_set = lan_password.is_set(self.selection['engine'])- suffix = '/m/' if password_set else '/m/?freevideo=launch&token=' + secret- self.access_links = [address(host, self.selection['lan_port']) + suffix for host in local_addresses()]+ self.access_links = lan_access_links(self.selection['engine'], self.selection['lan_port'],+ password_set=password_set)self.state = dict(self.state, lan_status='' if self.access_links else 'no-address', lan_password_set=password_set)def check_access_proxy(self):diff --git a/freevideo_engine/lan_page.py b/freevideo_engine/lan_page.pynew file mode 100644index 0000000..ecdae41--- /dev/null+++ b/freevideo_engine/lan_page.py@@ -0,0 +1,75 @@+"""Local page LAN settings, independent of the HTTP server."""+import socket+import time++from . import lan_auth, lan_password+from .launcher_settings import Store, default_language+++class LanUnavailable(RuntimeError):+ """The launcher has not recorded an installation on this computer."""+++class InvalidRequest(ValueError):+ def __init__(self, field, allowed, got):+ self.field, self.allowed, self.got = field, allowed, got+ super().__init__('%s must be %s' % (field or 'body', allowed))+++def read(engine):+ installation = Store(engine).read().get('installation')+ flag = bool(installation and installation.get('lan_access') is True)+ port = installation.get('lan_port') if installation else None+ enabled = False+ if flag and port is not None:+ try:+ with socket.create_connection(('127.0.0.1', port), timeout=.3):+ enabled = True+ except OSError:+ pass+ password_set = lan_password.is_set(engine)+ auth = lan_auth.PasswordAuth(engine)+ auth.reload()+ link = ''+ if enabled:+ from .comfy_launcher_runtime import lan_access_links+ links = lan_access_links(engine, port, password_set=password_set)+ link = links[0] if links else ''+ return dict(available=installation is not None, enabled=enabled, starting=flag and not enabled,+ link=link, password_set=password_set, devices=len(auth.devices(time.time())),+ min_length=lan_password.MIN_LENGTH)+++def apply(engine, body):+ if not isinstance(body, dict) or not body:+ raise InvalidRequest('', 'a nonempty object containing enabled or password', body)+ for field in body:+ if field not in ('enabled', 'password'):+ raise InvalidRequest(field, 'absent (unknown field)', None)+ if 'enabled' in body and type(body['enabled']) is not bool:+ raise InvalidRequest('enabled', 'a boolean', body['enabled'])+ if 'password' in body:+ password = body['password']+ if password is not None and not isinstance(password, str):+ raise InvalidRequest('password', 'a string or null', password)+ if isinstance(password, str) and len(password) < lan_password.MIN_LENGTH:+ raise InvalidRequest('password', 'at least %d characters (min_length=%d)' % (+ lan_password.MIN_LENGTH, lan_password.MIN_LENGTH), password)+ store = Store(engine)+ with store.exclusive():+ saved = store.read()+ installation = saved.get('installation')+ if installation is None:+ raise LanUnavailable()+ # Validate the whole request and installation before changing authentication.+ if 'password' in body:+ if body['password'] is None:+ lan_password.remove(engine)+ else:+ lan_password.set_password(engine, body['password'])+ if 'enabled' in body:+ installation = dict(installation, lan_access=body['enabled'])+ # access.lan_enabled() checks the current top-level permission copies.+ saved['lan_access'] = body['enabled']+ store.write_locked(saved, saved.get('language', default_language()), installation, saved.get('setup'))+ return read(engine)diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.pyindex 978d66f..49556ca 100644--- a/freevideo_engine/launcher_session.py+++ b/freevideo_engine/launcher_session.py@@ -1,6 +1,7 @@"""Widget-independent state for the Qt launcher; uses the existing installer."""from copy import deepcopyfrom functools import lru_cache+import importlibimport jsonimport osfrom pathlib import Path@@ -11,7 +12,7 @@ import timefrom urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplitfrom . import __version__-from . import disk_space, lan_password+from . import disk_spacefrom .comfy_launcher_runtime import Controller, layout, local_url, loopback_url, managed_frontend, new_layout, queue_busyfrom .desktop_runtime import launcher_root, materialize_sourcefrom .download_settings import Probe, read as download_preferences, speed_text@@ -45,6 +46,11 @@ ARCHIVE_FAILURES = {@lru_cache(maxsize=4)+def _lan_password():+ # Resolved per call: the access module is optional and may be absent.+ return importlib.import_module('.lan_password', __package__)++def _qr_rows(text):from .qr_code import encodetry:@@ -2012,14 +2018,14 @@ class Session:"""(supported, set) for the optional LAN password; unsupported without the access module."""engine = (self.controller.selection or {}).get('engine')try:- from . import lan_password+ lan_password = _lan_password()return True, bool(engine) and bool(lan_password.is_set(engine))except (ImportError, OSError):return False, Falsedef lan_password_min(self):try:- from . import lan_password+ lan_password = _lan_password()return int(getattr(lan_password, 'MIN_LENGTH', 6))except (ImportError, OSError, TypeError, ValueError):return 6@@ -2029,7 +2035,7 @@ class Session:engine = (self.controller.selection or {}).get('engine')if not engine:return- from . import lan_password+ lan_password = _lan_password()if text is None:lan_password.remove(engine)else: