Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions desktop/src-tauri/src/resource_layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ pub const DATA_FILES: &[&str] = &[
"scripts/alden_messenger_runtime.py",
"scripts/alden_messenger_quality.py",
"scripts/alden_messenger_factory.py",
"scripts/alden_platform_identity.py",
"scripts/alden_collect.py",
"scripts/alden_collection_scheduler.py",
"scripts/alden_realtime_collection.py",
Expand Down
1 change: 1 addition & 0 deletions desktop/src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@
"bundle-resources/scripts/alden_messenger_runtime.py": "scripts/alden_messenger_runtime.py",
"bundle-resources/scripts/alden_messenger_quality.py": "scripts/alden_messenger_quality.py",
"bundle-resources/scripts/alden_messenger_factory.py": "scripts/alden_messenger_factory.py",
"bundle-resources/scripts/alden_platform_identity.py": "scripts/alden_platform_identity.py",
"bundle-resources/scripts/alden_collect.py": "scripts/alden_collect.py",
"bundle-resources/scripts/alden_collection_scheduler.py": "scripts/alden_collection_scheduler.py",
"bundle-resources/scripts/alden_realtime_collection.py": "scripts/alden_realtime_collection.py",
Expand Down
79 changes: 79 additions & 0 deletions docs/evaluation/messenger-source-loader-20261024.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Messenger SDK source execution and package completeness

The installed messenger factory could not import: the desktop resource list
omitted `alden_platform_identity.py`, which the runtime imports. The previous
dependency regression covered selected top-level imports but did not seed the
knowledge MCP entry point or traverse its conditional imports. The regression
now follows those paths and a separate isolated Python process imports the
staged messenger modules without a checkout, SDK load or native framework call.
The identity module is included in both desktop resource lists. The immutable
auto-reply worker does not import this messenger factory; its manifest and
activation/proof contract are unchanged.

An independent controlled test also reproduced a code-loader mismatch. CPython
`-B` disables cache **writes**; it can still execute an unchecked-hash `.pyc`.
The former loader hashed `.py` files and then used the ordinary import loader.
A fixture with a different harmless return marker in the cache passed its source
hash/origin checks while executing the cached code. This is a bounded regression,
not evidence of actual malicious SDK execution on the user's machine. The
current shared SDK's qualification failure prevents its production load.

The factory now snapshots the eight fixed source files with regular-file,
owner, size and no-follow checks. It retains the original all-SDK health gate
and requires unchanged source snapshots across that qualification. It analyzes
all local imports, including function-local imports, and accepts only the known
closed dependency set. It compiles the captured bytes directly, initializes
dependencies first, and never places the SDK directory on global `sys.path` or
invokes the ordinary bytecode-cache loader. Each file is bounded to 1 MiB.

Only modules created by this invocation are removed on failure; an existing
owner's modules are retained. Loaded attestations are published after source,
module identity/origin and API checks pass. A changed/deleted attested module
cannot silently reload. Dependency cycles are an explicit unsupported contract
requiring review. Cleanup is not a sandbox or a rollback of arbitrary module
side effects, stdlib imports or external writes. The approved SDK remains trusted
code; this change binds its executed Python bytes, not its publisher authenticity
or every native-library/filesystem race after a request has been delivered.

```mermaid
stateDiagram-v2
[*] --> SourceSnapshot
SourceSnapshot --> Rejected: missing / symlink / FIFO / oversized
SourceSnapshot --> WholeSdkQualification: regular bounded source bytes
WholeSdkQualification --> Rejected: existing integrity/receipt gate fails
WholeSdkQualification --> SourceComparison: health accepted
SourceComparison --> Rejected: source changed
SourceComparison --> ClosedImports: same captured bytes
ClosedImports --> Rejected: new dependency / cycle / foreign module
ClosedImports --> CompiledSnapshots
CompiledSnapshots --> InitializingOwnedModules
InitializingOwnedModules --> CleanupOwnedModules: initialization fails
InitializingOwnedModules --> FinalValidation
FinalValidation --> CleanupOwnedModules: changed source / origin / API
FinalValidation --> AttestedModules: all checks pass
CleanupOwnedModules --> Rejected
AttestedModules --> [*]
```

This diagram summarizes implemented transitions, not a formal proof of safety,
termination, operating-system permissions or message consent. Tests exercise
the old cache substitution, root and dependency caches, source changes during
qualification/initialization, initialization/API failure cleanup, foreign module
ownership, missing attested modules, unsupported cycles and unsafe file kinds.
Existing account/root/source-authority/cancellation and stdio MCP regressions
remain in place. Tests use private synthetic SDKs and harmless return markers,
never live messages or sends.

Current acquisition remains a separate unresolved requirement. The production
target registry has no native KakaoTalk/Telegram targets. The shared Kakao SDK
still fails its original whole-installation gate; source comparison of just the
reader's eight Python modules does not qualify the other skills or authorize a
global manifest rewrite. Telegram's probe still rejects the changed app/decoder
contract. Its context-specific consent and message visibility/expiry rules also
remain unchanged. No account switch, permission grant, source DB bypass, native
send, global SDK patch or production frontier activation follows from this fix.

Run affected checks with the pinned Python and `-B`. The existing CI factory and
launcher suites include these regressions. Actual bundle import, installed
resource hashes/signature, SDK gate readback, source qualification and eventual
live collection are distinct delivery evidence; local tests do not replace them.
122 changes: 96 additions & 26 deletions scripts/alden_messenger_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@
import ast
import hashlib
import importlib
import importlib.util
import json
import os
from pathlib import Path
import stat
import subprocess
import sys
import threading
Expand All @@ -14,13 +17,23 @@
SDK = Path.home() / '.agents/skills/aside-kakao-local-db/scripts'
SDK_MODULES = ('sqlcipher_adapter', 'media_context', 'room_participants', 'message_visibility',
'emoticon_confirmation', 'message_confirmation', 'room_catalog', 'full_chat_reader')
MAX_SDK_SOURCE_BYTES = 1024 * 1024
_loaded = {}
_import_lock = threading.Lock()


def load_kakao_sdk():
if not sys.dont_write_bytecode:
raise SourceBlocked('kakao_sdk_requires_no_bytecode')
with _import_lock:
snapshot = _sdk_source_snapshot()
_verify_sdk_installation()
if _sdk_source_snapshot() != snapshot:
raise SourceBlocked('kakao_sdk_loaded_revision_unverified')
return _load_verified_sdk(snapshot)


def _verify_sdk_installation():
try:
result = subprocess.run([sys.executable, '-B', str(SDK / 'skill_health.py')],
capture_output=True, text=True, timeout=10, check=False)
Expand All @@ -34,26 +47,49 @@ def load_kakao_sdk():
or any(type(report.get(key)) is not int or report[key] != 0 for key in
('chat_messages_read', 'identity_cache_reads', 'credential_reads', 'native_actions', 'send_calls', 'writes'))):
raise SourceBlocked('kakao_sdk_integrity_unverified')
with _import_lock:
return _load_verified_sdk()


def _load_verified_sdk():
folder = SDK.resolve(strict=True)
fingerprints, sources = {}, {}
def _sdk_source_snapshot():
"""Bounded regular source files, never Python's bytecode-cache loader."""
try:
folder = SDK.resolve(strict=True)
sources = {}
for name in SDK_MODULES:
path = folder / (name + '.py')
descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
with os.fdopen(descriptor, 'rb') as handle:
before = os.fstat(handle.fileno())
if (not stat.S_ISREG(before.st_mode) or before.st_uid != os.geteuid()
or before.st_size > MAX_SDK_SOURCE_BYTES):
raise SourceBlocked('kakao_sdk_module_unavailable')
raw = handle.read(MAX_SDK_SOURCE_BYTES + 1)
after = os.fstat(handle.fileno())
stamp = lambda info: (info.st_dev, info.st_ino, info.st_mode, info.st_uid, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
if len(raw) != before.st_size or stamp(before) != stamp(after):
raise SourceBlocked('kakao_sdk_loaded_revision_unverified')
sources[name] = raw
return folder, sources
except (OSError, RuntimeError) as error:
if isinstance(error, SourceBlocked):
raise
raise SourceBlocked('kakao_sdk_module_unavailable') from error


def _load_verified_sdk(snapshot):
folder, sources = snapshot
fingerprints, baseline = {}, {}
for name in SDK_MODULES:
path = folder / (name + '.py')
if path.is_symlink() or not path.is_file():
raise SourceBlocked('kakao_sdk_module_unavailable')
sources[name] = path.read_bytes()
fingerprint = hashlib.sha256(sources[name]).hexdigest()
fingerprints[name] = (path, fingerprint)
present = sys.modules.get(name)
if present is not None and _loaded.get(name) != (present, fingerprint):
baseline[name] = present
if ((present is not None or name in _loaded)
and _loaded.get(name) != (present, fingerprint)):
raise SourceBlocked('kakao_sdk_loaded_revision_unverified')
# Function-local imports participate too. A changed dependency contract
# requires review rather than silently adding an untracked lazy module.
pending, closure = ['full_chat_reader'], set()
pending, closure, dependencies = ['full_chat_reader'], set(), {}
while pending:
name = pending.pop()
if name in closure:
Expand All @@ -65,31 +101,65 @@ def _load_verified_sdk():
tree = ast.parse(sources[name])
except (SyntaxError, ValueError) as error:
raise SourceBlocked('kakao_sdk_dependency_contract_changed') from error
dependencies[name] = set()
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom) and node.level:
raise SourceBlocked('kakao_sdk_dependency_contract_changed')
imports = [alias.name.split('.')[0] for alias in node.names] if isinstance(node, ast.Import) else (
[node.module.split('.')[0]] if isinstance(node, ast.ImportFrom) and node.module else [])
pending.extend(value for value in imports if (folder / (value + '.py')).is_file() or (folder / value).is_dir())
local = {value for value in imports if (folder / (value + '.py')).is_file() or (folder / value).is_dir()}
dependencies[name].update(local)
pending.extend(local)
if closure != set(SDK_MODULES):
raise SourceBlocked('kakao_sdk_dependency_contract_changed')
sys.path.insert(0, str(folder))
# -B prevents writing caches, but Python may still execute an existing pyc.
# Compile the exact hash-checked snapshots and load the closed dependency
# graph first. Never add the SDK directory to the process-wide import path.
try:
module = importlib.import_module('full_chat_reader')
for name in SDK_MODULES:
importlib.import_module(name)
finally:
sys.path.remove(str(folder))
for name, (path, fingerprint) in fingerprints.items():
present = sys.modules.get(name)
if present is None or Path(present.__file__).resolve() != path:
raise SourceBlocked('kakao_sdk_module_origin_invalid')
if hashlib.sha256(path.read_bytes()).hexdigest() != fingerprint:
code = {name: compile(source, str(fingerprints[name][0]), 'exec', dont_inherit=True)
for name, source in sources.items()}
except (SyntaxError, ValueError) as error:
raise SourceBlocked('kakao_sdk_dependency_contract_changed') from error
created, visiting = {}, set()
def load(name):
if name in visiting:
raise SourceBlocked('kakao_sdk_dependency_cycle')
if name in sys.modules:
present = sys.modules[name]
if present is not created.get(name, baseline[name]):
raise SourceBlocked('kakao_sdk_loaded_revision_unverified')
return present
visiting.add(name)
for dependency in sorted(dependencies[name]):
load(dependency)
visiting.remove(name)
spec = importlib.util.spec_from_loader(name, loader=None, origin=str(fingerprints[name][0]))
value = importlib.util.module_from_spec(spec)
value.__file__ = str(fingerprints[name][0])
value.__cached__ = None
sys.modules[name] = value
created[name] = value
exec(code[name], value.__dict__)
return value
try:
module = load('full_chat_reader')
for name, (path, fingerprint) in fingerprints.items():
present = sys.modules.get(name)
if present is None or present is not created.get(name, baseline[name]) or Path(present.__file__).resolve() != path:
raise SourceBlocked('kakao_sdk_module_origin_invalid')
if _sdk_source_snapshot() != snapshot:
raise SourceBlocked('kakao_sdk_loaded_revision_unverified')
_loaded[name] = (present, fingerprint)
if (not callable(getattr(module, 'snapshot', None)) or not callable(getattr(module, 'resolve_identity', None))
or getattr(module.snapshot, 'supports_exact_confirmation', False) is not True):
raise SourceBlocked('kakao_sdk_contract_unavailable')
if (not callable(getattr(module, 'snapshot', None)) or not callable(getattr(module, 'resolve_identity', None))
or getattr(module.snapshot, 'supports_exact_confirmation', False) is not True):
raise SourceBlocked('kakao_sdk_contract_unavailable')
except BaseException:
# Failed initialization never becomes an attestation or poisons a later
# request. Keep modules owned before this call exactly as they were.
for name, value in created.items():
if sys.modules.get(name) is value:
del sys.modules[name]
raise
_loaded.update({name: (sys.modules[name], fingerprint) for name, (_, fingerprint) in fingerprints.items()})
return module


Expand Down
33 changes: 32 additions & 1 deletion tests/test_alden_desktop_launchers.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import ast
import json
import os
import plistlib
import re
import signal
import subprocess
import sys
import tempfile
import time
import unittest
Expand Down Expand Up @@ -850,6 +852,7 @@ def test_staged_python_entrypoint_dependencies_are_complete_and_staging_lists_ma
"scripts/auto_reply_ax_ui.py",
"scripts/alden_browser_use.py",
"scripts/auto_reply_metrics.py",
"scripts/alden_knowledge_mcp.py",
)
pending = [seed for seed in seeds if (ROOT / seed).is_file()]
resolved: set[str] = set()
Expand All @@ -864,7 +867,7 @@ def test_staged_python_entrypoint_dependencies_are_complete_and_staging_lists_ma
filename=relative_path,
)
imported_modules: list[str] = []
for node in tree.body:
for node in ast.walk(tree):
if isinstance(node, ast.Import):
imported_modules.extend(alias.name for alias in node.names)
elif (
Expand All @@ -887,6 +890,34 @@ def test_staged_python_entrypoint_dependencies_are_complete_and_staging_lists_ma
msg=f"staged entry scripts require unstaged local modules: {missing}",
)

def test_staged_messenger_imports_without_checkout_or_native_source_reads(self) -> None:
resources = json.loads(read_repo_file('desktop/src-tauri/tauri.conf.json'))['bundle']['resources']
with tempfile.TemporaryDirectory() as temporary:
folder = Path(temporary)
for source, destination in resources.items():
if destination.startswith('scripts/') and destination.endswith('.py'):
staged = folder / destination
staged.parent.mkdir(parents=True, exist_ok=True)
original = ROOT / 'scripts' / Path(source).name
staged.write_bytes(original.read_bytes())
script = '''import sys,json
from pathlib import Path
sys.path.insert(0,sys.argv[1])
import alden_messenger_factory as factory
import alden_messenger_runtime as runtime
import alden_platform_identity as identity
for module in (factory,runtime,identity):
assert Path(module.__file__).parent == Path(sys.argv[1])
assert identity._frameworks.cache_info().currsize == 0
assert not any(name in sys.modules for name in factory.SDK_MODULES)
print(json.dumps({'staged_imports':3,'native_frameworks_loaded':0,'canonical_reader_modules_loaded':0}))
'''
run = subprocess.run([sys.executable,'-I','-B','-c',script,str(folder/'scripts')],
cwd=folder,capture_output=True,text=True,timeout=15)
self.assertEqual(run.returncode,0,run.stderr)
self.assertEqual(json.loads(run.stdout),{'staged_imports':3,'native_frameworks_loaded':0,'canonical_reader_modules_loaded':0})
self.assertEqual(list(folder.rglob('*.pyc')),[])

def test_primary_and_compat_shell_scripts_pass_sh_syntax_check(self) -> None:
scripts = (
"scripts/build-alden-desktop.sh",
Expand Down
Loading