Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
f203b8b
Recording bar: opened again, it keeps listening to the microphone cho…
KBRASK Nov 30, 2026
6595c7e
Russian and Ukrainian: a one- or two-letter preposition, conjunction …
KBRASK Nov 30, 2026
3c2aebc
Interface text: in Russian, taking something out of a list or a queue…
KBRASK Nov 30, 2026
1f644ea
Character pictures: one 1x4 sheet of face close-up, front, side and b…
KBRASK Nov 30, 2026
7bc2840
Quality levels in the creation panel look ready to press: the levels …
KBRASK Nov 30, 2026
d60d5dc
Notices: on two rows the icon stands on the first line of words, not …
KBRASK Nov 30, 2026
7a7e4a1
Hover tips on a card sit next to their control: a feature card's butt…
KBRASK Nov 30, 2026
999e7d0
Settings, This computer: a value still being read shows a skeleton, o…
KBRASK Nov 30, 2026
3e558e2
Edit view: closing or reloading the page asks first while changes are…
KBRASK Nov 30, 2026
20445c2
Settings: the models card's title wraps (hyphenated where the languag…
KBRASK Nov 30, 2026
e162f57
Warm-up preloads the video model before the encoder when a video was …
KBRASK Nov 30, 2026
a3fad22
A saved edit's typed words and queued parts, and an unsent feedback t…
KBRASK Nov 30, 2026
2fd22ee
Edit view: removing Audio 2 takes the empty separated tracks with it
KBRASK Nov 30, 2026
6d9a057
Model reuse: earlier generations of the engine's sampling tables in a…
KBRASK Nov 30, 2026
0f17294
Model folders: only the checkpoint's own weight files are read
KBRASK Nov 30, 2026
ba15c45
Interface text: quotes are paired at any length; only names up to 32 …
KBRASK Nov 30, 2026
ba80289
Settings: the performance measurement is not offered on a Mac
KBRASK Nov 30, 2026
ae252ba
Launcher: the Smart App Control card says what it blocks, what can be…
KBRASK Nov 30, 2026
b664dd5
Streamed weights: a shard whose metadata change time alone moved duri…
KBRASK Nov 30, 2026
ddfa2b4
Prompt rewrite: a rewrite the user's own edit outdated says so instea…
KBRASK Nov 30, 2026
51f469d
Report-button checks (group A): each case starts from a forgotten las…
KBRASK Nov 30, 2026
eada134
Feature cards stay put: a narrow card decides how it lays out its exa…
KBRASK Nov 30, 2026
f3d7c46
Settings, This computer: the reading line's corners use the radius sc…
KBRASK Nov 30, 2026
086dea4
Access link: every change a signed-in browser makes carries its devic…
KBRASK Nov 30, 2026
13c6383
Editor: while a part generates, the edit view's Cancel stands on top …
KBRASK Nov 30, 2026
f267f71
A refresh of the tab the FreeVideo launcher opened brings FreeVideo's…
KBRASK Nov 30, 2026
cb68ebb
Page check: a launch whose workflow opens late is not reported as failed
KBRASK Nov 30, 2026
a583972
Windows launcher: starting ComfyUI no longer opens an error window
KBRASK Nov 30, 2026
f645d8c
Windows CI: the packaged launcher's smoke test checks that it never s…
KBRASK Nov 30, 2026
983cc7e
Uploads: a file whose name the engine cannot place goes with the exte…
KBRASK Nov 30, 2026
1ae94ac
Launcher: before installing, a connection, source or speed test choic…
KBRASK Nov 30, 2026
96665c0
Uploads: a refused file with no name of its own asks plainly for an i…
KBRASK Nov 30, 2026
729298a
Release 0.6.19: update notes
KBRASK Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 146 additions & 6 deletions freevideo_engine/access_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@
import os
import re
from pathlib import Path
import secrets
import ssl
from urllib.parse import urlencode, urlsplit
from urllib.parse import parse_qsl, urlencode, urlsplit

from aiohttp import ClientSession, ClientTimeout, DummyCookieJar, TCPConnector, WSMsgType, client_exceptions, web
from yarl import URL
Expand All @@ -37,6 +38,7 @@
'<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><meta name="referrer" content="same-origin"><title>FreeVideo</title><link rel="stylesheet" href="./theme.css"><link rel="stylesheet" href="./phone.css"></head><body class="fv-phone"><div id="phone"></div><script type="module" src="./phone.js"></script></body></html>')

COOKIE = 'freevideo_access'
PROOF_COOKIE = 'freevideo_proof'
DAYS = 30
LOGIN_PATH = '/m/login'
# All password-page text lives here; the lockout line matches web/phone_model.js.
Expand Down Expand Up @@ -110,6 +112,114 @@ def same_origin(request):
return False


# A signed-in browser sends its cookie with any request, also one another website makes it send, so a request that can
# change something needs the device's proof in proxy_identity.CSRF_HEADER. An API client that sends only its bearer token
# is not a browser and is not asked. The only change made before there is a device to prove is signing in. The proof is
# never put in an address (addresses end up in logs, histories and diagnostic reports): the one form the page posts
# (FORM_PROOF, it cannot send a header) carries it as a field, read and removed here.
SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS')
WITHOUT_PROOF = {('POST', LOGIN_PATH): 'signing in comes before there is a signed-in device to give a proof to'}
FORM_PROOF = frozenset(('/freevideo/library/download-zip', '/api/freevideo/library/download-zip'))
# What is read of such a form: the page splits a download into forms of at most 1 MiB (web/output_download.js).
FORM_PROOF_BYTES = 4 << 20
FORM_TOO_LARGE = 'This download asks for too many creations at once. Download them in smaller groups.'
PROOF_MISSING = 'This change has to come from the FreeVideo page opened with the access link. Reload the page and try again.'


async def needs_proof(request, secret):
"""True for a change from a signed-in browser that does not carry its device's proof ('too_large' for a form on
FORM_PROOF past FORM_PROOF_BYTES). Such a form proves itself with its proxy_identity.PROOF_FIELD, which is taken out
of the body it forwards (request['body'])."""
device = request.get('lan_device')
if request.method in SAFE_METHODS or not device or (request.method, request.path) in WITHOUT_PROOF:
return False
if proxy_identity.proof_matches(secret, device, request.headers.get(proxy_identity.CSRF_HEADER, '')):
return False
if request.method != 'POST' or request.path not in FORM_PROOF or request.content_type != 'application/x-www-form-urlencoded':
return True
data = b''
while len(data) <= FORM_PROOF_BYTES: # read() may give less than asked: read to the end, or past the limit
chunk = await request.content.read(FORM_PROOF_BYTES + 1 - len(data))
if not chunk:
break
data += chunk
if len(data) > FORM_PROOF_BYTES:
return 'too_large'
fields = parse_qsl(data.decode('utf-8', 'replace'), keep_blank_values=True)
offered = [value for name, value in fields if name == proxy_identity.PROOF_FIELD]
if len(offered) != 1 or not proxy_identity.proof_matches(secret, device, offered[0]):
return True
request['body'] = urlencode([(name, value) for name, value in fields if name != proxy_identity.PROOF_FIELD]).encode()
return False


# The first script of the signed-in page (injected into ComfyUI's page by inject_proof, served at PROOF_SCRIPT_PATH): it
# runs before every module, so every change the page makes through fetch or XMLHttpRequest to this server carries the
# device's proof (the freevideo_proof cookie), whoever holds a reference to fetch. A change refused for an old proof
# (FreeVideo restarted) is sent once more with the current one, which the refusal brought; when that fails too, the page
# hears 'freevideo-proof-expired' (web/proxy_proof.js says so). The wrappers name the functions they wrap
# (freevideoNative), so the page's check for other programs wrapping fetch still sees through them.
# scripts/test_proxy_page_proof.mjs runs this text.
PROOF_SCRIPT_PATH = '/m/proof.js'
PAGE_PROOF_SCRIPT = r"""(() => {
if (window.fetch && window.fetch.freevideoProof) return;
const COOKIE = /(?:^|;\s*)freevideo_proof=([0-9a-f]{64})(?:;|$)/, UNSAFE = /^(POST|PUT|PATCH|DELETE)$/i, HEADER = 'X-FreeVideo-CSRF';
const proof = () => { try { return COOKIE.exec(document.cookie || '')?.[1] || ''; } catch { return ''; } };
const own = url => { try { return new URL(url, location.href).origin === location.origin; } catch { return false; } };
const expired = async answer => {
if (!answer || answer.status !== 403) return false;
try { return (await answer.clone().json())?.error?.code === 'page_session_required'; } catch { return false; }
};
const native = window.fetch;
const proved = async function (input, init) {
let request;
try { request = new Request(input, init); } catch { return native.call(window, input, init); }
if (!UNSAFE.test(request.method) || !own(request.url) || !proof()) return native.call(window, input, init);
const send = () => {
const copy = request.clone();
const headers = new Headers(copy.headers);
headers.set(HEADER, proof());
return native.call(window, new Request(copy, {headers}));
};
const first = await send();
if (!await expired(first)) return first;
const again = await send();
if (await expired(again)) window.dispatchEvent(new CustomEvent('freevideo-proof-expired'));
return again;
};
proved.freevideoProof = true; proved.freevideoNative = native;
window.fetch = proved;
const XHR = window.XMLHttpRequest && window.XMLHttpRequest.prototype;
if (!XHR) return;
const open = XHR.open, send = XHR.send, header = XHR.setRequestHeader;
XHR.open = function (method, url, ...rest) {
this.__freevideoChange = UNSAFE.test(String(method)) && own(url);
this.__freevideoProved = false;
return open.call(this, method, url, ...rest);
};
// A request that names its proof itself keeps it (a second value would be joined to the first, and refused).
XHR.setRequestHeader = function (name, value) {
if (String(name).toLowerCase() === HEADER.toLowerCase()) this.__freevideoProved = true;
return header.call(this, name, value);
};
XHR.send = function (body) {
const value = this.__freevideoChange && !this.__freevideoProved ? proof() : '';
if (value) { try { header.call(this, HEADER, value); } catch { /* already sent */ } }
return send.call(this, body);
};
XHR.open.freevideoProof = XHR.send.freevideoProof = XHR.setRequestHeader.freevideoProof = true;
XHR.open.freevideoNative = open; XHR.send.freevideoNative = send; XHR.setRequestHeader.freevideoNative = header;
})();
"""
PROOF_TAG = b'<script src="' + PROOF_SCRIPT_PATH.encode() + b'"></script>'


def inject_proof(html):
"""ComfyUI's page with the proof script first in its head (unchanged when it has no head)."""
match = re.search(rb'<head(\s[^>]*)?>', html, re.IGNORECASE)
return html if match is None else html[:match.end()] + PROOF_TAG + html[match.end():]


# Hop-by-hop headers belong to one connection; Content-Length follows the body actually sent.
HOP_BY_HOP = frozenset(('connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'proxy-connection',
'te', 'trailer', 'transfer-encoding', 'upgrade', 'content-length'))
Expand Down Expand Up @@ -176,7 +286,7 @@ def forwarded(request):
continue
if lower == 'cookie':
value = '; '.join(part for part in value.split(';') if part.strip() and
part.split('=', 1)[0].strip() not in (COOKIE, DEVICE_COOKIE))
part.split('=', 1)[0].strip() not in (COOKIE, DEVICE_COOKIE, PROOF_COOKIE))
if not value:
continue
headers.append((name, value))
Expand All @@ -188,13 +298,22 @@ def create(upstream, token, engine=None):
sockets = 'ws' + upstream[len('http'):]
client = []
hop_secret = os.environ.pop(proxy_identity.ENV, '')
# The device proofs this proxy gives and checks: the hop secret, or one of its own when none was configured (the
# services behind it then trust nothing from it, and a browser still proves its changes here).
proof_secret = hop_secret or secrets.token_hex(32)
auth = PasswordAuth(engine)
login_lock = asyncio.Lock()

def browser_headers(response, request):
device = request.get('lan_device')
if device and request.path in ('/m/', '/m/csrf'):
response.headers['X-FreeVideo-CSRF'] = proxy_identity.csrf(hop_secret, device)
response.headers['X-FreeVideo-CSRF'] = proxy_identity.csrf(proof_secret, device)
if device:
# The signed-in page reads its proof here (web/proxy_proof.js), with no request of its own; this proxy never
# takes the cookie as a proof, and other websites can neither read it nor have it sent.
value = proxy_identity.csrf(proof_secret, device)
if request.cookies.get(PROOF_COOKIE) != value:
response.set_cookie(PROOF_COOKIE, value, httponly=False, samesite='Strict', secure=request.secure, path='/')
session = request.get('lan_session')
if session and session['remember']:
response.set_cookie(DEVICE_COOKIE, request.cookies[DEVICE_COOKIE], max_age=REMEMBER_SECONDS,
Expand Down Expand Up @@ -264,10 +383,22 @@ async def cleanup(app):
await client[0].close()

async def forward(request):
body = request.content if request.body_exists else None
body = request.get('body', request.content if request.body_exists else None)
# ComfyUI's page for a signed-in browser gets the proof script first (inject_proof): asked for uncompressed.
page = request.method == 'GET' and bool(request.get('lan_device')) and request.path in ('/', '/index.html')
headers = [(name, value) for name, value in forwarding_headers(request) if not (page and name.lower() == 'accept-encoding')]
if page:
headers.append(('Accept-Encoding', 'identity')) # the client would otherwise ask for a compressed answer itself
try:
async with client[0].request(request.method, URL(upstream + request.raw_path, encoded=True),
headers=forwarding_headers(request), data=body, allow_redirects=False) as reply:
headers=headers, data=body, allow_redirects=False) as reply:
if page and reply.status == 200 and reply.content_type == 'text/html' and not reply.headers.get('Content-Encoding'):
response = web.Response(status=200, body=inject_proof(await reply.read()))
for name, value in reply.headers.items():
if name.lower() not in HOP_BY_HOP and name.lower() not in ('content-length', 'etag', 'last-modified'):
response.headers.add(name, value)
response.headers['Cache-Control'] = 'no-store'
return browser_headers(response, request)
response = web.StreamResponse(status=reply.status, reason=reply.reason)
for name, value in reply.headers.items():
if name.lower() not in HOP_BY_HOP:
Expand Down Expand Up @@ -353,11 +484,20 @@ async def handle(request):
rest = [(k, v) for k, v in request.rel_url.query.items() if k != 'token']
location = request.path + ('?' + urlencode(rest) if rest else '')
return browser_headers(web.Response(status=303, headers={'Location': location}), request)
refused = await needs_proof(request, proof_secret)
if refused == 'too_large':
return browser_headers(web.json_response(dict(error=dict(code='request_too_large', message=FORM_TOO_LARGE)),
status=413, headers={'Cache-Control': 'no-store'}), request)
if refused:
return browser_headers(web.json_response(dict(error=dict(code='page_session_required', message=PROOF_MISSING)),
status=403, headers={'Cache-Control': 'no-store'}), request)
if request.path.startswith('/m/') and request.path != LOGIN_PATH and request.method in ('GET', 'HEAD'):
if not request.get('lan_device'):
return web.Response(status=403)
if request.path == '/m/csrf':
response = web.json_response(dict(csrf=proxy_identity.csrf(hop_secret, request['lan_device'])))
response = web.json_response(dict(csrf=proxy_identity.csrf(proof_secret, request['lan_device'])))
elif request.path == PROOF_SCRIPT_PATH:
response = web.Response(text=PAGE_PROOF_SCRIPT if request.method == 'GET' else '', content_type='text/javascript', charset='utf-8')
elif request.path == '/m/':
response = web.Response(text=PHONE_PAGE if request.method == 'GET' else '', content_type='text/html', charset='utf-8')
else:
Expand Down
41 changes: 24 additions & 17 deletions freevideo_engine/agent/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,18 @@
SCENE = dict(aspect='16:9', seconds=6)
PROP = dict(aspect='1:1', seconds=4)

# The sheet of every view a shot carries for each person, put together here from the card's own pictures: up to six
# equal cells (three to a row) on a light grey ground, each picture scaled whole and centred, no text.
SHEET_VERSION = 1
SHEET_ORDER = ('front', 'three_quarter', 'side', 'back', 'face') # then any other label, in card order
SHEET_CELL = (736, 828)
# The sheet of every view a shot carries for each person, put together here from the card's own pictures, as the
# new-character dialog draws its own (web/cast_photo.js SHEET): one row of four cells of one height on a light grey ground,
# the first cell (the face close-up) 1.4 times as wide as the other three (front, side, back), no text (compose_sheet says
# how each picture fits its cell). A card with fewer pictures keeps the same size; the cells it has no picture for stay ground.
SHEET_VERSION = 2
SHEET_ORDER = ('face', 'front', 'side', 'back', 'three_quarter') # then any other label, in card order
SHEET_CELLS = ((1030, 1302), (736, 1302), (736, 1302), (736, 1302))
SHEET_GAP = 48
SHEET_GROUND = (238, 238, 238)
SHEET_COLUMNS = 3
SHEET_MAX = 6
SHEET_SIZE = (SHEET_COLUMNS * SHEET_CELL[0] + (SHEET_COLUMNS + 1) * SHEET_GAP, 2 * SHEET_CELL[1] + 3 * SHEET_GAP) # 2400 x 1800
SHEET_MAX = len(SHEET_CELLS)
SHEET_FILL = .03 # how far a picture's shape may differ from its cell's and still fill it (a 4:5 close-up in the face cell)
SHEET_SIZE = (sum(width for width, _ in SHEET_CELLS) + (SHEET_MAX + 1) * SHEET_GAP, SHEET_CELLS[0][1] + 2 * SHEET_GAP) # 3478 x 1398
_SHEETS_SEEN = set()


Expand Down Expand Up @@ -1165,25 +1167,30 @@ def _sheet_intact(path):


def compose_sheet(pictures, out):
"""Write one PNG of these pictures (two to six, as file bytes or paths): always three columns by two rows of
equal cells, a light grey ground (cells with no picture stay empty), each picture scaled whole to fit its cell
and centred, nothing cropped, no text."""
"""Write one PNG of these pictures (two to four, as file bytes or paths), in the given order: always one row of the
four cells of SHEET_CELLS (the first one wider), a light grey ground (cells with no picture stay empty), no text.
A picture of about its cell's shape (within SHEET_FILL, as the views made for a card are) fills the cell, so the four
share their top and bottom edges, the few pixels over trimmed evenly from its sides; any other picture is scaled
whole to fit its cell and centred, nothing cropped."""
import io
from PIL import Image, ImageOps
(width, height), gap = SHEET_CELL, SHEET_GAP
gap = SHEET_GAP
sheet = Image.new('RGB', SHEET_SIZE, SHEET_GROUND)
for index, source in enumerate(pictures[:SHEET_MAX]):
left = gap
for (width, height), source in zip(SHEET_CELLS, pictures):
with Image.open(io.BytesIO(source) if isinstance(source, bytes) else source) as opened:
picture = ImageOps.exif_transpose(opened)
if picture.mode in ('RGBA', 'LA', 'P'):
flat = Image.new('RGB', picture.size, SHEET_GROUND)
picture = picture.convert('RGBA')
flat.paste(picture, mask=picture.getchannel('A'))
picture = flat
picture = ImageOps.contain(picture.convert('RGB'), (width, height), Image.LANCZOS)
row, column = divmod(index, SHEET_COLUMNS)
sheet.paste(picture, (gap + column * (width + gap) + (width - picture.width) // 2,
gap + row * (height + gap) + (height - picture.height) // 2))
picture = picture.convert('RGB')
shape = (picture.width / picture.height) / (width / height)
picture = (ImageOps.fit(picture, (width, height), Image.LANCZOS) if abs(shape - 1) <= SHEET_FILL
else ImageOps.contain(picture, (width, height), Image.LANCZOS))
sheet.paste(picture, (left + (width - picture.width) // 2, gap + (height - picture.height) // 2))
left += width + gap
sheet.save(out, format='PNG')


Expand Down
7 changes: 7 additions & 0 deletions freevideo_engine/bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -805,6 +805,13 @@ def plan(args, *, local_progress=None, stage=None):
directories = ([str(local_folder)] if local_folder else []) + libraries['roots']
from .local_models import library_roots
directories = library_roots(library_roots(directories) + saved_libraries, keep_first=True)
# Folders the person chose to skip for this check (one held too much to check), saved ones included.
skipped = libraries.get('skip', [])
if not isinstance(skipped, list) or any(not isinstance(path, str) for path in skipped):
raise ValueError('Invalid model library manifest')
if skipped:
left_out = set(library_roots(skipped, skip_missing=True))
directories = [path for path in directories if path not in left_out]
scan_library = lambda: scan_many(directories, needed, prior=previous_reuse, callback=local_progress)
elif saved_libraries:
from .local_models import library_roots
Expand Down
Loading