Skip to content

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.

Remove the local page LAN settings API for now

Bowen Xued4ecec6cfbbc
diff --git a/freevideo_engine/agent/errors.py b/freevideo_engine/agent/errors.py
index 9ec75f8..21c3aed 100644
--- a/freevideo_engine/agent/errors.py
+++ b/freevideo_engine/agent/errors.py
@@ -17,7 +17,6 @@ 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.'),
@@ -253,7 +252,6 @@ 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.py
index 4c2892f..5d62fbe 100644
--- a/freevideo_engine/agent/routes.py
+++ b/freevideo_engine/agent/routes.py
@@ -459,10 +459,13 @@ 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 = valid_page_session(request)
+ valid = (session is not None and session[1] >= time.monotonic() and csrf
+ and secrets.compare_digest(csrf.encode(), session[0].encode()))
if not valid:
raise JobError('page_session_required', 'Page session required')
header = request.headers.get('Authorization', '')
@@ -666,19 +669,16 @@ 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'
- if valid_page_session(request):
+ 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())):
access.check(request, local=True)
return 'user'
raise JobError('unauthorized', 'Token or valid page session required')
@@ -691,7 +691,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) or request.path in ('/freevideo/lan', '/api/freevideo/lan'):
+ if agent_path(request.path):
for key in list(response.headers):
if key.lower().startswith('access-control-'):
del response.headers[key]
@@ -737,52 +737,9 @@ 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', max_age=12 * 3600)
+ path=('/api' if request.path.startswith('/api/') else '') + '/freevideo/agent', 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.py
index ddcf4ed..271d9e6 100644
--- a/freevideo_engine/comfy_launcher_runtime.py
+++ b/freevideo_engine/comfy_launcher_runtime.py
@@ -405,19 +405,6 @@ 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)
@@ -756,10 +743,13 @@ 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_addresses
self.access_polled = time.monotonic()
+ secret = token(self.selection['engine'])
password_set = lan_password.is_set(self.selection['engine'])
- self.access_links = lan_access_links(self.selection['engine'], self.selection['lan_port'],
- password_set=password_set)
+ 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.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.py
deleted file mode 100644
index ecdae41..0000000
--- a/freevideo_engine/lan_page.py
+++ /dev/null
@@ -1,75 +0,0 @@
-"""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)