Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9fbfd94cd7 |
@@ -0,0 +1,58 @@
|
||||
KRONIC ADMINISTRATION V2 - development build
|
||||
Based on the original source and patches through Kronic Room Identity V1.
|
||||
Extract directly inside /home/admin/mediaserver (or the actual application root).
|
||||
Back up source and both account/media databases first; use a consistent SQLite
|
||||
backup, or stop the services before copying. Restart both media and chat services
|
||||
and refresh browsers. No dependencies or config changes. New tables are created
|
||||
additively in the existing account DB. Existing accounts and grants are not reset.
|
||||
|
||||
New /admin tabs:
|
||||
- Media Access: select a non-platform-admin account; choose six media categories
|
||||
and named indexed libraries. Uncheck inherit to save an explicit allowlist.
|
||||
New libraries are denied until selected. Inherit removes the instance allowlist,
|
||||
not room restrictions. Existing accounts without a new policy behave as before.
|
||||
- Room Templates: save category/library allowlists, AI chat/tools ceilings and
|
||||
role action ceilings. Select a template at room creation or explicitly apply it
|
||||
to an existing room. Copy, not live reference. Editing a template does not
|
||||
silently update rooms. Existing group member inheritance on room creation is
|
||||
unchanged. Applying a template does NOT grant missing user or group permissions.
|
||||
- Instance Settings: optional instance name, login title/subtitle, powered-by
|
||||
credit, permission for room owners to rename, and per-room icon/accent settings.
|
||||
Leave instance name blank for generic login. Room names still use the existing
|
||||
Rename control, internal room IDs unchanged. Room icons are emoji/short text;
|
||||
image upload, custom logos and full themes are not implemented.
|
||||
|
||||
IMPORTANT AUTHORIZATION BEHAVIOR
|
||||
Media and AI ceilings intersect across all assigned enabled rooms, as in the
|
||||
existing restrictive room media permission model; room switching does not select
|
||||
an independent media ACL. This is conservative and can restrict adults who also
|
||||
belong to a kids room. Use per-user restrictions rather than room templates if
|
||||
that is not desired. Platform admin retains full access. Role action ceilings
|
||||
apply within the individual room and cannot override the global role policy.
|
||||
A separate selected-room entitlement model would require further API/session work.
|
||||
Existing media-enabled group entitlement is still required. Named-library controls
|
||||
cover indexed movie/TV libraries; Music, IPTV, Tube and Twitch are category-level.
|
||||
Individual channels/tracks, room member caps, media/screen sharing feature switches,
|
||||
and per-domain branding are not included. Existing LiveKit screen shares cannot
|
||||
be content-filtered by library ACLs. Already-open playback streams may continue
|
||||
until restarted. Cached old UI state may be visible until refresh.
|
||||
|
||||
Restricted accounts cannot access Balroc remote device discovery/control or
|
||||
unrestricted Balroc fallback, or global cast/scan controls. Local AI media search
|
||||
uses the same library authorization checks; ordinary Balroc fallback is blocked
|
||||
for restricted accounts until that separate tool server supports granular access.
|
||||
External player links are now signed with the issuing user's ID and check that
|
||||
user's active entitlement and source permissions again on redemption. Previously
|
||||
issued links are invalidated. Links remain bearer URLs: anyone with a valid link
|
||||
can use it until expiration or issuer access is revoked. Do not share them with
|
||||
restricted users. No claim of DRM or complete parental-control isolation.
|
||||
|
||||
Tests: python test_admin_upgrade.py (temporary SQLite databases, mock media
|
||||
search and extracted HTTP route checks). Python compilation and JS syntax checks
|
||||
passed. Previous room identity simulated routing tests passed. Not tested against
|
||||
a live Kronic deployment, reverse proxy, Balroc, or physical mobile browser.
|
||||
Test with a disposable restricted account before granting access to children.
|
||||
Check category and library browse, direct denied playback and thumbnail URLs,
|
||||
AI search and direct remote requests, role management, template edits, and
|
||||
room picker/login in both frontends. Back up prior files for rollback; new DB
|
||||
policy tables may be left in place but older code does NOT enforce them.
|
||||
@@ -0,0 +1,2 @@
|
||||
Kronic Media History V1 (requires Admin V2 and room-title V2.1)
|
||||
Back up the application and both SQLite databases using SQLite backup or with services stopped. Extract into ~/mediaserver, restart the media server, refresh admin and all open desktop/mobile pages. Instance Settings > Media history: choose room, choose modes, save. Room templates also have history defaults. Existing shared history is untouched. Newly scoped histories start empty; changing scopes does not copy or erase data. Returning to a previous scope restores its records. Personal mode spans rooms using personal mode for that account. Group mode spans rooms using group mode for the same parent group. Old templates without history settings leave current room settings unchanged when applied. Removing a template leaves history settings intact. New templates copy their history settings on creation/application. Only existing history features are scoped: Tube recently/continue watching and movie/TV resume positions. No music/IPTV/Twitch history subsystem exists in this source. Shared cache, cache jobs and metadata are not private history and are not isolated. Remote player history outside Kronic is unchanged. This is not a media permissions upgrade. Every history API request must include an assigned room ID, automatically attached by the updated app.js; stale clients must refresh. Tests: run python test_history_scopes.py using your existing venv. Tests use temporary databases; library_index initializes its configured database on import as usual. Live browser testing outstanding.
|
||||
@@ -0,0 +1,32 @@
|
||||
Kronic room-scoped media permissions v1
|
||||
|
||||
Target: Kronic original source + patches through kronic-media-history-v1.zip.
|
||||
Extract in ~/mediaserver, NOT in its parent directory. Back up replaced files first.
|
||||
Restart the media server and refresh/reopen desktop and mobile tabs.
|
||||
No database migration or permission reset is required.
|
||||
|
||||
The previous implementation intersected the room templates and room_media_permissions
|
||||
of all assigned rooms. The new HTTP authorization binds each request to a selected
|
||||
room and verifies active membership. Instance account restrictions remain global.
|
||||
Group media entitlement is checked only for the selected room's parent group.
|
||||
Both template and per-user room restrictions are applied only in the selected room.
|
||||
Requests without room context only fall back automatically for a single assigned room.
|
||||
The browser sends X-Kronic-Room for API calls and kronic_room for local media URLs;
|
||||
this ID is not trusted as authorization. Simultaneous tabs have independent scopes.
|
||||
Existing platform administrator bypass remains intact.
|
||||
|
||||
Global library management, cast and unrestricted remote Balroc tools retain the
|
||||
previous conservative cross-room restriction gate because they can alter shared
|
||||
state and are not scoped to a room. Local AI access and searches are scoped to
|
||||
selected-room permissions; local AI conversation identifiers are also room-bound.
|
||||
Previously issued external M3U playback URLs no longer validate; regenerate them.
|
||||
New signed URLs bind to the issuing account and room and recheck permissions.
|
||||
They are still bearer URLs until expiry. Active streams are not forcibly cut off
|
||||
when permissions change; subsequent requests recheck membership and permissions.
|
||||
|
||||
Tests: run with your usual Python environment from ~/mediaserver:
|
||||
python test_room_access_scope.py
|
||||
python test_admin_upgrade.py
|
||||
python test_history_scopes.py
|
||||
Tests use temporary SQLite databases and simulated request objects, not your live
|
||||
account or media databases. This patch has not been browser-tested in your deployment.
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Safe minimal Kronic v8 installer. No Balroc files or JS overwritten."""
|
||||
from __future__ import annotations
|
||||
import argparse
|
||||
import datetime
|
||||
import pathlib
|
||||
import py_compile
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
p=argparse.ArgumentParser(description='Install Kronic AI media conversational context v8')
|
||||
p.add_argument('root',nargs='?',default='/home/admin/mediaserver')
|
||||
p.add_argument('--check',action='store_true')
|
||||
a=p.parse_args()
|
||||
root=pathlib.Path(a.root).expanduser().resolve()
|
||||
server=root/'stream_server.py'
|
||||
oldmodule=root/'ai_command_media_extended.py'
|
||||
newmodule=root/'ai_command_context.py'
|
||||
source=pathlib.Path(__file__).parent/'BLADE-A/home/admin/mediaserver/ai_command_context.py'
|
||||
for file in (server,oldmodule,root/'ai_command_media.py',source):
|
||||
if not file.is_file():sys.exit(f'Missing required source {file}. Nothing changed.')
|
||||
if '_explicit_youtube_request' not in oldmodule.read_text():
|
||||
sys.exit('Requires YouTube routing v7 in ai_command_media_extended.py. Nothing changed.')
|
||||
if newmodule.is_file() and 'Per-user, per-AI-window media follow-ups' not in newmodule.read_text():
|
||||
sys.exit('ai_command_context.py already exists but is not this module. Nothing changed.')
|
||||
s=server.read_text()
|
||||
if 'from ai_command_context import resolve as resolve_ai_media' in s:
|
||||
print('Conversation routing already installed; no patch necessary.')
|
||||
sys.exit(0)
|
||||
old='from ai_command_media_extended import resolve as resolve_ai_media'
|
||||
if s.count(old)!=1:
|
||||
sys.exit(f'Expected a single v4-v7 resolver import, found {s.count(old)}. Nothing changed.')
|
||||
start=s.find('response = None if route[\'mode\'] == \'remote\' else resolve_ai_media(')
|
||||
if start<0:
|
||||
# Support pre-v5 branch, but leave remote routing alone.
|
||||
start=s.find('response = resolve_ai_media(')
|
||||
if start<0:sys.exit('Cannot identify AI media call site; nothing changed.')
|
||||
end=s.find('\n )',start)
|
||||
if end<0:sys.exit('AI media resolver call layout differs; nothing changed.')
|
||||
call=s[start:end]
|
||||
if call.count('iptv_list_channels=iptv_list_channels,')!=1:
|
||||
sys.exit('Cannot locate media keyword arguments; nothing changed.')
|
||||
if 'window_id=' in call:sys.exit('window_id already passed; refusing duplicate change.')
|
||||
patched=s.replace(old,'from ai_command_context import resolve as resolve_ai_media',1)
|
||||
# Exact call signature changed without touching the user/account auth, remote selector, or frontend.
|
||||
patched=patched.replace(call,call.replace('iptv_list_channels=iptv_list_channels,','iptv_list_channels=iptv_list_channels,\n window_id=window_id,'),1)
|
||||
py_compile.compile(str(source),doraise=True)
|
||||
import ast
|
||||
ast.parse(patched,filename=str(server))
|
||||
if a.check:
|
||||
print('CHECK OK: server patch and new module compatible; no files changed.')
|
||||
sys.exit(0)
|
||||
backup=root/('backup-ai-context-v8-'+datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))
|
||||
backup.mkdir(parents=True,exist_ok=False)
|
||||
shutil.copy2(server,backup/'stream_server.py')
|
||||
if newmodule.is_file():shutil.copy2(newmodule,backup/'ai_command_context.py')
|
||||
shutil.copy2(source,newmodule)
|
||||
server.write_text(patched)
|
||||
print('Installed:',newmodule)
|
||||
print('Updated:',server)
|
||||
print('Backup:',backup)
|
||||
print('Restart: sudo systemctl restart mediaserver.service')
|
||||
@@ -0,0 +1,26 @@
|
||||
KRONIC BORG — STAGE 2: REVERSIBLE UI SHELL
|
||||
|
||||
1. Back up your working mediaserver directory (especially html/index.html).
|
||||
2. Extract this archive to a temporary directory on your server.
|
||||
3. cd /home/admin/mediaserver
|
||||
4. python /path/to/extracted/install_borg_ui.py
|
||||
5. Hard-refresh your Kronic Media browser tab. Restart mediaserver.service if it caches HTML.
|
||||
|
||||
The script:
|
||||
- backs up html/index.html with a timestamp;
|
||||
- adds the room backdrop, navigation rail and floating media container;
|
||||
- copies CSS/borg_shell.css and JS/borg_shell.js;
|
||||
- preserves all existing Media DOM ids (#content, #toolbar, #breadcrumb, video player, etc.) and JS/app.js.
|
||||
|
||||
This is UI SHELL STAGE ONLY.
|
||||
- Chat avatar and voice UI are placeholders, not wired to port 8001 yet.
|
||||
- Libraries and Manage call original Media buttons.
|
||||
- Movies, TV, Music, IPTV, Tube, Twitch buttons open the media window but do not yet change media section. Wiring depends on the CURRENT live JS/app.js navigation functions.
|
||||
- Media's existing topbar is kept for backward compatibility until the sidebar fully replaces it.
|
||||
- No Python, DB, LiveKit, or systemd changes.
|
||||
|
||||
To roll back:
|
||||
cp html/index.html.borg-backup-<timestamp> html/index.html
|
||||
rm CSS/borg_shell.css JS/borg_shell.js
|
||||
|
||||
This should be deployed first to a test copy if possible. The supplied archive snapshot may differ from the deployed HTML/CSS.
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"id": "demo-audio",
|
||||
"name": "Kronic Demo Audio",
|
||||
"version": "0.1.0",
|
||||
"description": "Example Kronic Helper module catalogue entry.",
|
||||
"package": "demo-audio-0.1.0.zip",
|
||||
"sha256": "cde332433ce5f2102983d77569a2644786fa813bf403c2a685161634468051cc",
|
||||
"platforms": [
|
||||
"windows-x86_64",
|
||||
"linux-x86_64"
|
||||
],
|
||||
"requires_helper": ">=0.1.0",
|
||||
"capabilities": {
|
||||
"rnnoise": true,
|
||||
"fpga": false
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 760 KiB |
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Repair v8 chat->context resolver wiring without replacing existing sources."""
|
||||
import argparse
|
||||
import ast
|
||||
import datetime
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument('--root', default='/home/admin/mediaserver')
|
||||
p.add_argument('--check', action='store_true')
|
||||
a = p.parse_args()
|
||||
root = Path(a.root).expanduser().resolve()
|
||||
server = root / 'stream_server.py'
|
||||
context = root / 'ai_command_context.py'
|
||||
if not server.is_file() or not context.is_file():
|
||||
sys.exit('ERROR: stream_server.py or ai_command_context.py missing. No changes.')
|
||||
s = server.read_text()
|
||||
ctx = context.read_text()
|
||||
if 'def resolve(' not in ctx or 'window_id=' not in ctx:
|
||||
sys.exit('ERROR: unexpected ai_command_context.py API. No changes.')
|
||||
context_import = 'from ai_command_context import resolve as resolve_ai_media'
|
||||
legacy_import = 'from ai_command_media_extended import resolve as resolve_ai_media'
|
||||
if context_import not in s and legacy_import not in s:
|
||||
sys.exit('ERROR: unknown resolver import. No changes.')
|
||||
if context_import in s and re.search(r"resolve_ai_media\s*\([\s\S]{0,750}?window_id\s*=\s*window_id", s):
|
||||
print("Already wired: chat handler passes window_id to v8 context resolver.")
|
||||
sys.exit(0)
|
||||
pattern = re.compile(r'(?P<prefix>response\s*=\s*(?:None\s+if\s+route\[.mode.\]\s*==\s*.remote.\s+else\s+)?resolve_ai_media\s*\()(?P<args>.*?iptv_list_channels=iptv_list_channels,\s*)(?P<close>\))', re.S)
|
||||
matches = list(pattern.finditer(s))
|
||||
if len(matches) != 1:
|
||||
sys.exit(f'ERROR: expected one chat resolver call, found {len(matches)}. No changes.')
|
||||
m = matches[0]
|
||||
args = m.group('args')
|
||||
if 'window_id=' in args and context_import in s:
|
||||
print('Already wired: chat handler passes window_id to v8 context resolver.')
|
||||
sys.exit(0)
|
||||
if 'window_id=' in args:
|
||||
sys.exit('ERROR: call has window_id but import is not context resolver. No changes.')
|
||||
if args.count('iptv_list_channels=iptv_list_channels') != 1:
|
||||
sys.exit('ERROR: resolver arguments unexpected. No changes.')
|
||||
if not re.search(r'\bwindow_id\b', s[:m.start()]):
|
||||
sys.exit('ERROR: window_id variable not initialized before resolver call. No changes.')
|
||||
if context_import in s and legacy_import in s:
|
||||
sys.exit('ERROR: both resolver imports exist. No changes.')
|
||||
newargs = re.sub(r'(iptv_list_channels=iptv_list_channels\s*,?)', lambda match: match.group(1).rstrip().rstrip(',') + ',\n window_id=window_id,', args, count=1)
|
||||
updated = s[:m.start('args')] + newargs + s[m.end('args'):]
|
||||
if legacy_import in updated:
|
||||
if updated.count(legacy_import) != 1:
|
||||
sys.exit('ERROR: duplicate legacy imports. No changes.')
|
||||
updated = updated.replace(legacy_import, context_import, 1)
|
||||
try:
|
||||
ast.parse(updated, filename=str(server))
|
||||
except SyntaxError as exc:
|
||||
sys.exit(f'ERROR: patch failed Python parse: {exc}. No changes.')
|
||||
print('CHECK OK: resolved chat call and v8 context import; syntax valid.')
|
||||
if a.check:
|
||||
sys.exit(0)
|
||||
backup = root / ('backup-ai-context-wiring-' + datetime.datetime.now().strftime('%Y%m%d-%H%M%S-%f'))
|
||||
backup.mkdir()
|
||||
shutil.copy2(server, backup / 'stream_server.py')
|
||||
server.write_text(updated)
|
||||
print('UPDATED:', server)
|
||||
print('BACKUP:', backup)
|
||||
print('Restart: sudo systemctl restart mediaserver.service')
|
||||
@@ -0,0 +1,63 @@
|
||||
import tempfile,time,ast,re,hashlib,hmac
|
||||
import room_access_scope as ras
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse,parse_qs
|
||||
import media_accounts as m, admin_policies as p, library_index as l, ai_command_access as ai
|
||||
|
||||
def deny(fn):
|
||||
try: fn()
|
||||
except m.AccountError as e: assert e.status in (400,403,404);return
|
||||
raise AssertionError('Denied operation unexpectedly allowed')
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
m.configure_accounts(Path(d)/'accounts.db');m.initialize_account_database();l.DB_PATH=Path(d)/'library.db';l.init_db()
|
||||
now=int(time.time())
|
||||
with m.open_database() as db:
|
||||
for uid,name in [(1,'admin'),(2,'kid'),(3,'adult')]:
|
||||
db.execute('INSERT INTO users(id,username,email,password_hash,status,is_platform_admin,created_at) VALUES(?,?,?,?,?,?,?)',(uid,name,name+'@example.test','none','active',int(uid==1),now))
|
||||
db.execute('INSERT INTO user_sessions(token_hash,user_id,created_at,expires_at,last_seen_at) VALUES(?,?,?,?,?)',(m._session_hash(name),uid,now,now+3600,now))
|
||||
db.execute("INSERT INTO groups(id,name,slug,created_at) VALUES(1,'Family','family',?)",(now,))
|
||||
for uid in (1,2,3):db.execute('INSERT INTO group_memberships(group_id,user_id,role,created_at) VALUES(1,?,?,?)',(uid,'owner' if uid==1 else 'member',now))
|
||||
db.execute("INSERT INTO managed_rooms(id,group_id,room_name,display_name,created_at) VALUES(1,1,'kids','Pickle Jokes',?)",(now,))
|
||||
db.execute("INSERT INTO room_memberships(room_id,user_id,role,created_at) VALUES(1,2,'member',?)",(now,))
|
||||
for folder in ('kids','adult','shows'): (Path(d)/folder).mkdir()
|
||||
kids=l.add_media_source('Kids movies',str(Path(d)/'kids'),'movies');adult=l.add_media_source('Adult movies',str(Path(d)/'adult'),'movies');shows=l.add_media_source('Kids shows',str(Path(d)/'shows'),'shows')
|
||||
ks=l.get_media_source(kids);ad=l.get_media_source(adult)
|
||||
assert p.appearance()['name']=='' and p.source_allowed(2,ad)
|
||||
payload={'user_id':2,'types':['movies','tv'],'libraries':[kids,shows]}
|
||||
deny(lambda:p.save_user('kid',payload));deny(lambda:p.save_user('admin',{**payload,'user_id':1}));deny(lambda:p.save_user('admin',{**payload,'libraries':[9999]}))
|
||||
assert p.save_user('admin',payload)['ok'];assert p.source_allowed(2,ks);assert not p.source_allowed(2,ad);assert not m.allowed_media_libraries(2)['tube'];assert p.source_allowed(1,ad);assert p.source_allowed(3,ad)
|
||||
deny(lambda:p.enforce_source(2,ad));deny(lambda:p.enforce_source(2,None));p.enforce_source(2,ks)
|
||||
p.enforce_external_owner(2,{'source_id':kids});deny(lambda:p.enforce_external_owner(2,{'source_id':adult}))
|
||||
# Check the actual AI resolver using simulated search results.
|
||||
import ai_command_media_extended as resolver
|
||||
resolver.search_media=lambda *a,**k:[{'id':10,'source_id':kids,'title':'Test Film Kids','effective_title':'Test Film Kids'},{'id':11,'source_id':adult,'title':'Test Film Adult','effective_title':'Test Film Adult'}]
|
||||
reply=resolver.resolve('Find the movie Test Film',2,True,youtube_search=lambda *a,**k:{'items':[]},music_list_tracks=lambda *a,**k:[],iptv_list_channels=lambda *a,**k:[])
|
||||
assert reply and [i['id'] for i in reply['results']]==[10], reply
|
||||
# Actual route guard extracted from server; simulated HTTP request with real policy database.
|
||||
tree=ast.parse(Path('stream_server.py').read_text());cl=next(n for n in tree.body if isinstance(n,ast.ClassDef) and n.name=='StreamingHandler');names={'globally_restricted','check_media_path_access','_external_stream_signature','_external_stream_authorized'}
|
||||
env=dict(globals(),AccountError=m.AccountError,allowed_media_libraries=m.allowed_media_libraries,enforce_media_library=m.enforce_media_library,get_media_source=l.get_media_source,get_media_by_id=lambda i:{'source_id':{10:kids,11:adult}[i]},EXTERNAL_STREAM_SECRET=b'test')
|
||||
exec(compile(ast.Module(body=[n for n in cl.body if isinstance(n,ast.FunctionDef) and n.name in names],type_ignores=[]),'route-tests','exec'),env)
|
||||
H=type('H',(),{n:env[n] for n in names});h=H()
|
||||
for path in ['/play/11','/play/+11','/stream/11','/stream/+11','/thumbnail/11','/external/11.m3u','/api/media/11/mediainfo','/api/media/+11/mediainfo',f'/api/sources/{adult}/samples',f'/api/sources/+{adult}/samples',f'/api/search?source_id={adult}','/api/youtube/search','/api/cast/status']:
|
||||
h.path=path;deny(lambda:h.check_media_path_access(2))
|
||||
for path in ['/play/10','/stream/10','/thumbnail/10','/api/media/10/mediainfo',f'/api/sources/{kids}/samples']:
|
||||
h.path=path;h.check_media_path_access(2)
|
||||
sig=h._external_stream_signature(10,now+60,2);assert h._external_stream_authorized(10,now+60,sig,2);assert not h._external_stream_authorized(10,now+60,sig,3)
|
||||
ai.admin_set_ai_access('admin',{'user_id':2,'can_chat':True,'can_use_tools':True});assert ai.access_for_token('kid')['can_use_tools']
|
||||
tpl={'name':'Kids','types':['movies'],'libraries':[kids],'roles':{'admin':['media_access']},'ai_chat':False,'ai_tools':False};deny(lambda:p.save_template('kid',tpl));p.save_template('admin',tpl)
|
||||
tid=p.snapshot('admin')['templates'][0]['id'];p.apply_template('admin',{'room_id':1,'template_id':tid});assert not m.allowed_media_libraries(2)['tv'];assert not ai.access_for_token('kid')['can_chat']
|
||||
new_room=m.admin_create_managed_room('admin',1,{'room_name':'template-test','display_name':'Template test','template_id':tid})['roomId']
|
||||
assert p.snapshot('admin')['room_policies'][str(new_room)]['libraries']==[kids]
|
||||
p.apply_template('admin',{'room_id':new_room,'template_id':None})
|
||||
p.save_template('admin',{**tpl,'types':['movies','tv'],'libraries':[kids,adult,shows],'ai_chat':True});assert not m.allowed_media_libraries(2)['tv'] # snapshot stays unchanged
|
||||
deny(lambda:p.apply_template('admin',{'room_id':1,'template_id':999}));assert not m.allowed_media_libraries(2)['tv'] # rollback
|
||||
p.apply_template('admin',{'room_id':1,'template_id':None});assert m.allowed_media_libraries(2)['tv'];assert not p.source_allowed(2,ad)
|
||||
p.save_user('admin',{'user_id':2,'inherit':True});assert p.source_allowed(2,ad)
|
||||
# role restrictions using actual chat policy function and shared database
|
||||
ct=ast.parse(Path('kronic-chat/accounts.py').read_text());ns={'json':__import__('json')};exec(compile(ast.Module(body=[n for n in ct.body if (isinstance(n,ast.Assign) and any(isinstance(t,ast.Name) and t.id in ('ROOM_PERMISSION_ACTIONS','DEFAULT_ROOM_ROLE_POLICY') for t in n.targets)) or (isinstance(n,ast.FunctionDef) and n.name=='room_policy_for_role')],type_ignores=[]),'chat-role-test','exec'),ns)
|
||||
p.apply_template('admin',{'room_id':1,'template_id':tid});
|
||||
with m.open_database() as db:
|
||||
role=ns['room_policy_for_role'](db,'admin',1);assert role['media_access'] and not role['user_permissions']
|
||||
deny(lambda:p.save_appearance('kid',{}));p.save_appearance('admin',{'name':'','login_title':'Welcome','login_subtitle':'Private rooms','allow_owner_rename':False});assert not p.appearance()['allow_owner_rename']
|
||||
p.save_room_appearance('admin',{'room_id':1,'accent':'#365b86','icon':'🥒'});assert p.appearance(1)['room']['icon']=='🥒';deny(lambda:p.save_room_appearance('admin',{'room_id':1,'accent':'</style>'}))
|
||||
print('PASS: real temporary SQLite policies, admin-only writes, library/category restrictions, direct path guards, external link owner recheck and tamper resistance, template snapshot/rollback/removal, AI ceilings, room role ceilings, branding validation.')
|
||||
@@ -0,0 +1,40 @@
|
||||
import tempfile,time
|
||||
from pathlib import Path
|
||||
import media_accounts as m, library_index as l, history_scopes as h, admin_policies as p
|
||||
|
||||
def deny(fn):
|
||||
try: fn()
|
||||
except m.AccountError as e: assert e.status in (400,403,404);return
|
||||
raise AssertionError('Expected denial')
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
m.configure_accounts(Path(d)/'accounts.db');m.initialize_account_database();l.DB_PATH=Path(d)/'library.db';l.init_db()
|
||||
now=int(time.time())
|
||||
with m.open_database() as db:
|
||||
for uid,name in [(1,'admin'),(2,'kid'),(3,'adult')]:
|
||||
db.execute('INSERT INTO users(id,username,email,password_hash,status,is_platform_admin,created_at) VALUES(?,?,?,?,?,?,?)',(uid,name,name+'@example.test','none','active',int(uid==1),now))
|
||||
db.execute('INSERT INTO user_sessions(token_hash,user_id,created_at,expires_at,last_seen_at) VALUES(?,?,?,?,?)',(m._session_hash(name),uid,now,now+3600,now))
|
||||
db.execute("INSERT INTO groups(id,name,slug,created_at) VALUES(1,'Family','family',?)",(now,))
|
||||
for uid in (1,2,3):db.execute('INSERT INTO group_memberships(group_id,user_id,role,created_at) VALUES(1,?,?,?)',(uid,'owner' if uid==1 else 'member',now))
|
||||
for rid,name in [(1,'kids'),(2,'adult')]:db.execute('INSERT INTO managed_rooms(id,group_id,room_name,display_name,created_at) VALUES(?,1,?,?,?)',(rid,name,name,now))
|
||||
for rid,uid in [(1,2),(2,3),(1,1),(2,1)]:db.execute('INSERT INTO room_memberships(room_id,user_id,role,created_at) VALUES(?,?,?,?)',(rid,uid,'member',now))
|
||||
assert h.resolve('kid','1','tube')=='shared'
|
||||
h.record_watch('shared','v','old shared')
|
||||
deny(lambda:h.admin_save('kid',{'room_id':1,'history':{'tube':'room'}}))
|
||||
deny(lambda:h.resolve('kid','2','tube'));deny(lambda:h.resolve('kid',None,'tube'))
|
||||
h.admin_save('admin',{'room_id':1,'history':{'tube':'room','movies':'room','tv':'off'}})
|
||||
assert h.resolve('kid','1','tube')=='room:1' and h.resolve('adult','2','tube')=='shared'
|
||||
assert h.history('room:1')==[]
|
||||
h.record_watch('room:1','v','kids title');h.save_progress('room:1','tube','v',45,100)
|
||||
assert h.history('room:1')[0]['position_seconds']==45 and h.history('shared')[0]['title']=='old shared'
|
||||
assert h.get_progress('shared','tube','v')['position_seconds']==0
|
||||
h.save_progress('room:2','tube','v',80,100);h.reset_progress('room:1','tube','v');assert h.get_progress('room:2','tube','v')['position_seconds']==80
|
||||
assert h.get_progress('room:1','tube','v')['position_seconds']==0
|
||||
h.save_progress('room:1','movies',42,90,120);assert h.get_progress('room:2','movies',42)['position_seconds']==0
|
||||
assert h.resolve('kid','1','tv') is None;h.record_watch(None,'x','off');assert h.history(None)==[]
|
||||
h.admin_save('admin',{'room_id':1,'history':{'tube':'group','movies':'user'}})
|
||||
assert h.resolve('kid','1','tube')=='group:1' and h.resolve('kid','1','movies')=='user:2'
|
||||
p.save_template('admin',{'name':'isolated','types':[],'libraries':[],'history':{'tube':'room'}})
|
||||
tid=p.snapshot('admin')['templates'][0]['id'];p.apply_template('admin',{'room_id':2,'template_id':tid});assert h.resolve('adult','2','tube')=='room:2'
|
||||
p.save_template('admin',{'name':'isolated','types':[],'libraries':[],'history':{'tube':'off'}});assert h.resolve('adult','2','tube')=='room:2'
|
||||
print('History scope tests passed')
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Regression for a multi-room member losing music outside restricted rooms."""
|
||||
import ast
|
||||
import hashlib
|
||||
import hmac
|
||||
import tempfile
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
import media_accounts as m
|
||||
import admin_policies as p
|
||||
import library_index as l
|
||||
import room_access_scope as ras
|
||||
import ai_command_access as ai
|
||||
import history_scopes as hs
|
||||
|
||||
|
||||
def deny(fn, status=403):
|
||||
try:
|
||||
fn()
|
||||
except m.AccountError as e:
|
||||
assert e.status == status, (e.status, e.detail)
|
||||
return
|
||||
raise AssertionError('Expected denial')
|
||||
|
||||
|
||||
class Request:
|
||||
def __init__(self, path='/api/auth/media-context', headers=None, token='adult'):
|
||||
self.path=path
|
||||
self.headers={'Host':'example.test', **(headers or {})}
|
||||
self.token=token
|
||||
def get_session_token(self): return self.token
|
||||
|
||||
|
||||
@ras.isolated_request
|
||||
def request_context(request):
|
||||
ras.bind_request(request)
|
||||
return m.media_context(request.token)
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
m.configure_accounts(Path(d)/'accounts.db'); m.initialize_account_database()
|
||||
l.DB_PATH=Path(d)/'library.db'; l.init_db()
|
||||
now=int(time.time())
|
||||
with m.open_database() as db:
|
||||
for uid,name,admin in [(1,'admin',1),(2,'adult',0),(3,'other',0),(4,'single',0)]:
|
||||
db.execute('INSERT INTO users(id,username,email,password_hash,status,is_platform_admin,created_at) VALUES(?,?,?,?,?,?,?)',(uid,name,name+'@example.test','none','active',admin,now))
|
||||
db.execute('INSERT INTO user_sessions(token_hash,user_id,created_at,expires_at,last_seen_at) VALUES(?,?,?,?,?)',(m._session_hash(name),uid,now,now+3600,now))
|
||||
for gid,name,media in [(1,'main',1),(2,'kids',1),(3,'hangout',0),(4,'unassigned',1)]:
|
||||
db.execute('INSERT INTO groups(id,name,slug,media_enabled,created_at) VALUES(?,?,?,?,?)',(gid,name,name,media,now))
|
||||
db.execute('INSERT INTO managed_rooms(id,group_id,room_name,display_name,created_at) VALUES(?,?,?,?,?)',(gid,gid,name,name,now))
|
||||
for rid,uid,role in [(1,2,'owner'),(2,2,'member'),(3,2,'owner'),(4,3,'owner'),(1,4,'member'),(1,1,'owner')]:
|
||||
db.execute('INSERT INTO group_memberships(group_id,user_id,role,created_at) VALUES(?,?,?,?)',(rid,uid,role,now))
|
||||
db.execute('INSERT INTO room_memberships(room_id,user_id,role,created_at) VALUES(?,?,?,?)',(rid,uid,role,now))
|
||||
db.execute('CREATE TABLE room_media_permissions (room_id INTEGER, user_id INTEGER, library_key TEXT, enabled INTEGER, PRIMARY KEY(room_id,user_id,library_key))')
|
||||
db.execute("INSERT INTO room_media_permissions VALUES(2,2,'music',0)")
|
||||
db.execute("INSERT INTO room_media_permissions VALUES(2,2,'twitch',0)")
|
||||
for name in ('adult','kids'): (Path(d)/name).mkdir()
|
||||
adult=l.add_media_source('Adult movies',str(Path(d)/'adult'),'movies')
|
||||
kids=l.add_media_source('Kids movies',str(Path(d)/'kids'),'movies')
|
||||
ad=l.get_media_source(adult); ks=l.get_media_source(kids)
|
||||
p.save_template('admin',{'name':'Kids','types':['movies','music','twitch'],'libraries':[kids],'ai_chat':False,'ai_tools':False})
|
||||
tid=p.snapshot('admin')['templates'][0]['id']; p.apply_template('admin',{'room_id':2,'template_id':tid})
|
||||
ai.admin_set_ai_access('admin',{'user_id':2,'can_chat':True,'can_use_tools':True})
|
||||
# Reproduce the original global intersection.
|
||||
assert not m.allowed_media_libraries(2)['music']
|
||||
main=Request(headers={'X-Kronic-Room':'1'}); child=Request(headers={'X-Kronic-Room':'2'}); hangout=Request(headers={'X-Kronic-Room':'3'})
|
||||
assert all(request_context(main)['allowedLibraries'].values())
|
||||
c=request_context(child); assert c['hasMediaAccess'] and not c['allowedLibraries']['music'] and not c['allowedLibraries']['twitch'] and not c['allowedLibraries']['tv']
|
||||
assert not request_context(hangout)['hasMediaAccess']
|
||||
assert not any(request_context(hangout)['allowedLibraries'].values())
|
||||
assert ras.current(2) is None
|
||||
deny(lambda:request_context(Request(headers={'X-Kronic-Room':'4'})))
|
||||
deny(lambda:request_context(Request()))
|
||||
deny(lambda:request_context(Request(headers={'X-Kronic-Room':'invalid'})),400)
|
||||
deny(lambda:request_context(Request(headers={'X-Kronic-Room':'1','Referer':'https://example.test/?room=kids'})))
|
||||
deny(lambda:request_context(Request('/api/music/overview?kronic_room=2',{'X-Kronic-Room':'1'})),400)
|
||||
deny(lambda:request_context(Request('/api/music/overview?kronic_room=1&kronic_room=2')),400)
|
||||
assert request_context(Request(headers={'Referer':'https://example.test/?room=main'}))['allowedLibraries']['music']
|
||||
assert request_context(Request('/api/music/tracks/7/audio?kronic_room=1'))['allowedLibraries']['music']
|
||||
assert request_context(Request(token='single'))['allowedLibraries']['music']
|
||||
deny(lambda:request_context(Request('/api/music/overview?kronic_room=4')))
|
||||
# Global account restriction still wins in every selected room.
|
||||
p.save_user('admin',{'user_id':2,'types':['movies','tube'],'libraries':[adult,kids]})
|
||||
assert not request_context(main)['allowedLibraries']['music']
|
||||
assert not request_context(child)['allowedLibraries']['music']
|
||||
p.save_user('admin',{'user_id':2,'inherit':True})
|
||||
# Simultaneous tabs must not overwrite one another's scope.
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
result=list(pool.map(lambda req:request_context(req)['allowedLibraries']['music'],[main,child]*6))
|
||||
assert result==[True,False]*6
|
||||
# Exercise real backend route guard and external signature code without
|
||||
# starting ffmpeg, resolver, or live chat services.
|
||||
tree=ast.parse(Path(__file__).with_name('stream_server.py').read_text())
|
||||
cl=next(n for n in tree.body if isinstance(n,ast.ClassDef) and n.name=='StreamingHandler')
|
||||
names={'require_media_session','globally_restricted','check_media_path_access','_external_stream_signature','_external_stream_authorized'}
|
||||
env=dict(globals(),AccountError=m.AccountError,require_media_access=m.require_media_access,allowed_media_libraries=m.allowed_media_libraries,enforce_media_library=m.enforce_media_library,get_media_source=l.get_media_source,get_media_by_id=lambda i:{'source_id':{10:adult,11:kids}[i]},EXTERNAL_STREAM_SECRET=b'test')
|
||||
exec(compile(ast.Module(body=[n for n in cl.body if isinstance(n,ast.FunctionDef) and n.name in names],type_ignores=[]),'route-tests','exec'),env)
|
||||
H=type('H',(Request,),{n:env[n] for n in names})
|
||||
@ras.isolated_request
|
||||
def guard(req): return req.require_media_session()
|
||||
for path in ('/api/music/overview','/api/music/tracks/7/audio','/api/twitch/overview','/play/10','/stream/10','/thumbnail/10','/external/10.m3u','/api/media/10/progress'):
|
||||
guard(H(path+'?kronic_room=1'))
|
||||
deny(lambda:guard(H(path+'?kronic_room=2')))
|
||||
deny(lambda:guard(H(path+'?kronic_room=3')))
|
||||
guard(H('/play/11?kronic_room=2'))
|
||||
deny(lambda:guard(H('/api/cast/status?kronic_room=1')))
|
||||
@ras.isolated_request
|
||||
def ai_and_library(rid):
|
||||
ras.bind(2,rid)
|
||||
return ai.access_for_token('adult')['can_chat'],p.source_allowed(2,ad),p.source_allowed(2,ks)
|
||||
assert ai_and_library(1)==(True,True,True)
|
||||
assert ai_and_library(2)==(False,False,True)
|
||||
h=H(); sig=h._external_stream_signature(10,now+60,2,1)
|
||||
assert h._external_stream_authorized(10,now+60,sig,2,1)
|
||||
assert not h._external_stream_authorized(10,now+60,sig,2,2)
|
||||
assert not h._external_stream_authorized(10,now+60,sig,3,1)
|
||||
@ras.isolated_request
|
||||
def external(rid):
|
||||
ras.bind(2,rid);p.enforce_external_owner(2,{'source_id':adult})
|
||||
external(1);deny(lambda:external(2));deny(lambda:external(3));deny(lambda:external(4))
|
||||
# History stays scoped independently of the media policy.
|
||||
hs.admin_save('admin',{'room_id':2,'history':{'movies':'room'}})
|
||||
assert hs.resolve('adult','1','movies')=='shared' and hs.resolve('adult','2','movies')=='room:2'
|
||||
# Revoked membership and disabled room fail on subsequent requests.
|
||||
with m.open_database() as db: db.execute('DELETE FROM room_memberships WHERE room_id=2 AND user_id=2')
|
||||
deny(lambda:request_context(child))
|
||||
with m.open_database() as db: db.execute('UPDATE managed_rooms SET enabled=0 WHERE id=1')
|
||||
deny(lambda:request_context(main))
|
||||
print('PASS: multi-room categories, library allowlists, group media entitlement, global account restrictions, verified selectors, concurrent tabs, direct media routes, AI ceilings, external link scope, history and membership revocation.')
|
||||
Reference in New Issue
Block a user