From c9ad20919709f949ee3f6bdc1629cb443e63a4b4 Mon Sep 17 00:00:00 2001
From: Adeel Ahmad
Date: Sat, 10 Oct 2026 20:28:45 +0000
Subject: [PATCH 1/4] feat(smb): share the file tree read-only over SMB
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01VkWr32dEQW7JiHkWwaAwSu
---
CHANGELOG.md | 3 +
docker-compose.prod.yml | 8 +
docker-compose.yml | 5 +
docs/smb.md | 68 ++
fastapi_backend/app/api/v1/routes/admin.py | 8 +
fastapi_backend/app/cli.py | 18 +-
fastapi_backend/app/domain/components.py | 14 +
fastapi_backend/app/domain/settings.py | 20 +
fastapi_backend/app/domain/smb_share.py | 617 ++++++++++++++++++
fastapi_backend/app/domain/store.py | 12 +
fastapi_backend/app/schemas/admin.py | 13 +
fastapi_backend/pyproject.toml | 4 +
.../tests/domain/test_smb_share.py | 168 +++++
fastapi_backend/uv.lock | 127 +++-
mkdocs.yml | 1 +
nextjs-frontend/app/openapi-client/index.ts | 4 +
nextjs-frontend/app/openapi-client/sdk.gen.ts | 16 +
.../components/settings/bodies.tsx | 43 ++
nextjs-frontend/components/settings/model.ts | 28 +
.../components/settings/settings-shell.tsx | 2 +
20 files changed, 1177 insertions(+), 2 deletions(-)
create mode 100644 docs/smb.md
create mode 100644 fastapi_backend/app/domain/smb_share.py
create mode 100644 fastapi_backend/tests/domain/test_smb_share.py
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0e9dfdd09..eddafebd5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,9 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version
## Unreleased
+- **The graph as files over SMB.** Settings → SMB share serves the file tree read-only to Finder, Linux and (on port
+ 445) Windows: each person signs in with a file access key and sees what the web app shows them, from the networks
+ an admin allows. Off by default; the SMB server (impacket) is fetched when it's turned on ([SMB share](docs/smb.md)).
- **The graph as files.** Graph nodes are folders, nested along its links: collections inside collections, topics
inside their broader topics, entities by type. Each folder holds its assets' files, with a `.json` sidecar of
metadata and a `.txt` of the text; everyone sees what the web app shows them. Browse and read it through the API
diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml
index fcea0984e..b6fbcbba7 100644
--- a/docker-compose.prod.yml
+++ b/docker-compose.prod.yml
@@ -28,6 +28,10 @@ x-backend: &backend
LENS_TUNNEL_ORIGIN: http://frontend:3000
# the web app's container (and the one running the tunnel): their X-Forwarded-For names the visitor, for throttles
LENS_TRUSTED_PROXY_HOSTS: frontend,backend,worker
+ # the SMB share of the file tree (docs/smb.md): listens on 4445 in the container; LENS_SMB_PORT is where it's
+ # published, for the address Settings shows
+ LENS_SMB_LISTEN: 0.0.0.0
+ LENS_SMB_PORT: ${LENS_SMB_PORT:-1445}
# Fedora (docs/fedora.md): empty keeps it off; with the fedora profile, http://fedora:8080/fcrepo/rest
LENS_FEDORA_URL: ${LENS_FEDORA_URL:-}
LENS_FEDORA_USER: ${LENS_FEDORA_USER:-}
@@ -103,6 +107,10 @@ services:
- "${LENS_SENSOR_BIND:-${LENS_BIND:-127.0.0.1}}:${LENS_MQTT_PORT:-1883}:1883"
- "${LENS_SENSOR_BIND:-${LENS_BIND:-127.0.0.1}}:${LENS_SYSLOG_PORT:-5514}:5514/udp"
- "${LENS_SENSOR_BIND:-${LENS_BIND:-127.0.0.1}}:${LENS_SYSLOG_PORT:-5514}:5514/tcp"
+ # the file tree over SMB (docs/smb.md), served only once it's turned on in Settings → SMB share, and then only
+ # to the networks allowed there. 1445 on this machine so an SMB server the host runs on 445 is never in the way
+ # (Windows only connects to 445: set LENS_SMB_PORT=445 for it).
+ - "${LENS_SHARE_BIND:-${LENS_BIND:-127.0.0.1}}:${LENS_SMB_PORT:-1445}:4445"
healthcheck:
disable: true
diff --git a/docker-compose.yml b/docker-compose.yml
index 07bf37855..7c8ada732 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -37,6 +37,10 @@ x-backend: &backend
LENS_TUNNEL_ORIGIN: http://frontend:3000
# the web app's container (and the one running the tunnel): their X-Forwarded-For names the visitor, for throttles
LENS_TRUSTED_PROXY_HOSTS: frontend,backend,worker
+ # the SMB share of the file tree (docs/smb.md): listens on 4445 in the container; LENS_SMB_PORT is where it's
+ # published, for the address Settings shows
+ LENS_SMB_LISTEN: 0.0.0.0
+ LENS_SMB_PORT: ${LENS_SMB_PORT:-1445}
CORS_ORIGINS: '["http://localhost:3000"]'
OPENAPI_OUTPUT_FILE: ./shared-data/openapi.json
# the volume shared with the matterbridge service (its config, written from Settings → Chat rooms)
@@ -87,6 +91,7 @@ services:
- "${LENS_SENSOR_BIND:-127.0.0.1}:${LENS_MQTT_PORT:-1883}:1883"
- "${LENS_SENSOR_BIND:-127.0.0.1}:${LENS_SYSLOG_PORT:-5514}:5514/udp"
- "${LENS_SENSOR_BIND:-127.0.0.1}:${LENS_SYSLOG_PORT:-5514}:5514/tcp"
+ - "${LENS_SHARE_BIND:-127.0.0.1}:${LENS_SMB_PORT:-1445}:4445" # the file tree over SMB, once turned on
healthcheck:
disable: true
diff --git a/docs/smb.md b/docs/smb.md
new file mode 100644
index 000000000..a14ea9a29
--- /dev/null
+++ b/docs/smb.md
@@ -0,0 +1,68 @@
+# SMB share
+
+Lens can serve [the file tree](file-tree.md) over SMB, the protocol Finder, Windows Explorer and Linux file managers
+use for network drives. Namespaces, collections, topics and entities are folders; assets are files inside them, with
+their metadata and text beside them. Everyone signs in as themselves and sees exactly what the web app shows them.
+
+*Status: built. Read-only.*
+
+## Turn it on
+
+Settings → SMB share → **Share the file tree over SMB**. It's off until an admin turns it on. The first time, a worker
+fetches the SMB server (impacket, about 15 MB), then starts serving within seconds; Settings says when it's running
+and shows the address.
+
+Sign in with a **file access key** (the same keys the S3 share takes): the key's id is the user name and its secret
+the password. Make one in Settings, keep the secret, and revoke the key to shut its access off: open sessions end
+within 30 seconds.
+
+| Where | How |
+| --- | --- |
+| macOS | Finder → Go → Connect to Server → `smb://:1445/LENS` |
+| Linux | `sudo mount -t cifs -o port=1445,username=,ro,vers=2.0 ///LENS /mnt/lens`, or `smb://:1445/LENS` in Files |
+| Windows | Explorer only connects to port 445: set `LENS_SMB_PORT=445` in `.env` first, then open `\\\LENS` |
+
+| Setting | Default | What it does |
+| --- | --- | --- |
+| `smb.enabled` | off | Serve the share |
+| `smb.allowed_networks` | private networks (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `127.0.0.0/8`, `100.64.0.0/10` for Tailscale, `fc00::/7`, `::1/128`) | Machines anywhere else are turned away before they can sign in; changes apply without a restart |
+| `smb.bind`, `smb.port` | `127.0.0.1`, `4445` | Startup settings only: where the worker listens (`LENS_SMB_LISTEN`, `LENS_SMB_LISTEN_PORT`). In Docker it listens on `0.0.0.0:4445` inside the worker container |
+
+With Docker, the worker container publishes the share on port **1445** of the host (`LENS_SMB_PORT` in `.env` picks
+another), so an SMB server the host already runs on 445 is never in the way. Like the web app, it's reachable from
+this machine only unless `LENS_BIND=0.0.0.0` (what `install.sh` sets on a server); `LENS_SHARE_BIND` opens the file
+shares on their own while the web app stays local.
+
+Agents read the share's state at `GET /api/v1/settings/smb/status` and turn it on or off with
+`PUT /api/v1/settings/smb` (`{"enabled": true}`), like every other setting.
+
+## What keeps it safe
+
+- **Off by default**, and nothing listens until an admin turns it on.
+- **Read-only.** Every call that would write, rename, delete or make a folder is refused before it reaches the tree.
+- **Per-person views.** A key opens its owner's view of the tree: the namespaces and collections they have a role in,
+ nothing else. A disabled account or a revoked key stops working within 30 seconds, mid-session too.
+- **No guests.** Anonymous and guest sessions get nothing; a share is only handed to a signed-in key.
+- **Allowed networks only.** A connection from anywhere else is closed before a byte of SMB is read.
+- **Hardened server.** Each connection gets its own random NTLM challenge; SMB1 is refused past the first
+ negotiation (clients move on to SMB 2); the NTLM responses impacket logs are kept out of Lens's log.
+- **Only the tree.** The server's file system is a stand-in that answers from the tree: no path reaches the disk.
+
+SMB 2.0 has no encryption on the wire. Keep the share on networks you trust (or a VPN such as Tailscale), and keep its
+port off the internet.
+
+## How it works
+
+The worker runs impacket's SMB server (pure Python; impacket's license is a modified Apache 1.1, and it's fetched only
+when the share is turned on, as the `smb` extra). impacket serves folders through Python's `os` module; in Lens, its
+`os` is a small read-only stand-in (`domain/smb_share.py`) that looks files up in the tree for the signed-in key's
+owner, and reads them as they stream (files in vaults are decrypted on the way; files in storage connections are
+fetched as they're read). One person's view of the tree is reused for a few seconds, so the many look-ups a file
+manager makes after listing a folder don't each ask the database again.
+
+## Refine later
+
+- SMB 3 with encryption on the wire (impacket speaks SMB 2.0.2).
+- Finder's Bonjour discovery, so the share shows up on its own.
+- Packaging for the Synology and QNAP compose files, which don't publish the port yet.
+- Writing: dropping a file into a collection's folder to import it.
diff --git a/fastapi_backend/app/api/v1/routes/admin.py b/fastapi_backend/app/api/v1/routes/admin.py
index b4fb20474..34319a114 100644
--- a/fastapi_backend/app/api/v1/routes/admin.py
+++ b/fastapi_backend/app/api/v1/routes/admin.py
@@ -26,6 +26,7 @@
matterbridge,
semantic,
settings,
+ smb_share,
sources,
speech,
store,
@@ -50,6 +51,7 @@
MailTestResult,
Removed,
SemanticStatus,
+ SmbStatus,
SpeechTestResult,
Started,
TelemetryStatus,
@@ -171,6 +173,12 @@ def remove_local_model(user: AdminWriter, cfg: Cfg, db: Db, model: str = Query(.
return Removed(removed=removed)
+@router.get("/settings/smb/status")
+def smb_status(user: AdminReader, cfg: Cfg, db: Db) -> SmbStatus:
+ """The file tree over SMB (Settings › SMB share): whether it's serving, to which networks, and how to connect."""
+ return SmbStatus.model_validate(smb_share.status(db, cfg))
+
+
@router.get("/settings/tunnel/status")
def tunnel_status(user: AdminReader, cfg: Cfg, db: Db) -> TunnelStatus:
"""How the Cloudflare tunnel (Settings › Remote access) is doing: its address, whether it's connected, and
diff --git a/fastapi_backend/app/cli.py b/fastapi_backend/app/cli.py
index 96cbc0797..8e0d95894 100644
--- a/fastapi_backend/app/cli.py
+++ b/fastapi_backend/app/cli.py
@@ -260,7 +260,22 @@ def platform_main(argv, config):
import threading
import time
- from .domain import auth, bridge, jobs, local_llm, notify, passkeys, routines, sensors, settings, sources, telemetry, tunnel, updates
+ from .domain import (
+ auth,
+ bridge,
+ jobs,
+ local_llm,
+ notify,
+ passkeys,
+ routines,
+ sensors,
+ settings,
+ smb_share,
+ sources,
+ telemetry,
+ tunnel,
+ updates,
+ )
ap = argparse.ArgumentParser(prog="lens")
sub = ap.add_subparsers(dest="cmd", required=True)
@@ -364,6 +379,7 @@ def password():
if not (a.steps or a.no_schedule): # and scans watched folders and runs routines, as `lens watch` does
routines.start(db, C, stop, log=print)
sensors.start(db, C, stop, log=print, name=wk.name) # and the sensor hub, while sensors are on
+ smb_share.start(db, C, stop, name=wk.name, log=print) # and the SMB share of the file tree, while it's on
bridge.start(db, C, stop, lambda: cfg, name=wk.name, log_fn=print) # and the chat-room bridge, while it's on
tunnel.start(db, C, stop, name=wk.name, log=print) # and the Cloudflare tunnel, while it's on
local_llm.start(db, C, stop, name=wk.name, log=print) # and the local chat model, while it's on
diff --git a/fastapi_backend/app/domain/components.py b/fastapi_backend/app/domain/components.py
index 6f53c352b..0b86430a2 100644
--- a/fastapi_backend/app/domain/components.py
+++ b/fastapi_backend/app/domain/components.py
@@ -496,6 +496,19 @@ def fetch(self, cfg, m, say):
pip_install(cfg, "msg", say)
+class Smb(Component):
+ """impacket, for the SMB share of the file tree (smb_share.py): fetched when the share is turned on."""
+
+ def needed(self, cfg, m):
+ return bool((cfg.get("smb") or {}).get("enabled"))
+
+ def present(self, cfg):
+ return importable("impacket.smbserver")
+
+ def fetch(self, cfg, m, say):
+ pip_install(cfg, "smb", say)
+
+
class Laya(Component):
"""laya-mlx and the chosen Laya model, for local decisions (decide.py) on Apple Silicon."""
@@ -642,6 +655,7 @@ def detail(self, cfg):
LAYA,
OllamaModel("llm-model", "Chat model", "the LLM provider's model, pulled on Ollama", section="llm"),
OllamaModel("embedding-model", "Embedding model", "search by meaning's model, pulled on Ollama", section="embeddings", steps={"embed"}),
+ Smb("smb", "SMB server", "shares the file tree over SMB, read-only (smb.enabled; impacket)", size_mb=15, license="Apache-1.1"),
Msg("msg", "Outlook .msg emails", "reads Outlook .msg files (extract-msg)", optional=True, license="GPL-3.0", size_mb=5),
]
BY_ID = {c.id: c for c in COMPONENTS}
diff --git a/fastapi_backend/app/domain/settings.py b/fastapi_backend/app/domain/settings.py
index ad1ed0554..30ed24698 100644
--- a/fastapi_backend/app/domain/settings.py
+++ b/fastapi_backend/app/domain/settings.py
@@ -55,6 +55,8 @@
"fedora": None,
"tunnel": None,
# bind is a startup setting only
+ # the SMB share of the file tree (smb_share.py): bind and port are startup settings only (Docker publishes the port)
+ "smb": ("enabled", "allowed_networks"),
"sensors": (
"enabled",
"mqtt",
@@ -421,6 +423,8 @@ def _check(section, key, value, default):
return _fedora_setting(key, value)
if section == "sensors":
return _sensor_setting(key, value)
+ if section == "smb":
+ return _smb_setting(key, value)
if section == "components":
return _component_setting(key, value)
if section == "mail" and key != "security":
@@ -908,6 +912,22 @@ def _sensor_setting(key, value):
return value
+def _smb_setting(key, value):
+ if key == "enabled":
+ if not isinstance(value, bool):
+ raise ValueError("smb.enabled is true or false")
+ return value
+ if not isinstance(value, list) or len(value) > 100:
+ raise ValueError("smb.allowed_networks is a list of networks like 192.168.1.0/24")
+ out = []
+ for v in value:
+ try:
+ out.append(str(ipaddress.ip_network(str(v).strip(), strict=False)))
+ except ValueError:
+ raise ValueError(f"smb.allowed_networks: {v} isn't a network like 192.168.1.0/24") from None
+ return list(dict.fromkeys(out))
+
+
TELEMETRY_RANGES = {"export_seconds": (5, 3600)}
SERVICE_RX = re.compile(r"^[A-Za-z0-9._-]{1,64}$")
TOKEN_RX = re.compile(r"^[A-Za-z0-9._~-]+$")
diff --git a/fastapi_backend/app/domain/smb_share.py b/fastapi_backend/app/domain/smb_share.py
new file mode 100644
index 000000000..f4e08c076
--- /dev/null
+++ b/fastapi_backend/app/domain/smb_share.py
@@ -0,0 +1,617 @@
+"""Lens as a read-only SMB share: Finder, Explorer and Linux mount the file tree of the graph like any network drive.
+
+What the share holds is the shared file tree (filetree.py, docs/file-tree.md): graph nodes are folders, nested by their links, with the
+assets as files at the leaves. Each person sees what they may see in Lens, nothing more, and nobody can write: every
+call that would change something is refused before it reaches the tree.
+
+The server is impacket's SMB server (Apache-style license, pure Python), run inside the worker while Settings ›
+File sharing › SMB is on. impacket serves folders on disk through `os`; here its module-level `os` is a small stand-in
+(VirtualOS) that answers from the tree, and nothing outside the share's virtual root can be named. On top of that the
+server is hardened for this use: a random NTLM challenge per connection, no guest or anonymous sessions, SMB1 refused
+past the negotiation (clients move to SMB2), the NTLM responses impacket logs at INFO kept out of the log, and
+connections only from the allowed networks.
+
+People sign in with a file access key from Settings › File sharing (the same key the S3 and WebDAV shares take): the
+key id is the user name and its secret the password. NTLM needs the server to know the password, which is why the
+key's secret is sealed rather than hashed. Revoking a key ends its sessions within KEY_SECONDS.
+
+Off by default. The port inside the container is 4445; docker-compose publishes it where the web app is
+(LENS_SHARE_BIND, else LENS_BIND: this machine only unless install.sh opened Lens to the network). Windows only
+talks to port 445: set LENS_SMB_PORT=445 for it. See docs/file-sharing.md.
+"""
+
+from __future__ import annotations
+
+import errno
+import ipaddress
+import itertools
+import logging
+import os as _os
+import posixpath
+import socket
+import stat as _stat
+import threading
+import time
+import types
+from dataclasses import dataclass
+
+from . import store
+
+R = store.R
+ROOT = "/lens-smb" # the share's virtual root: /lens-smb//
+SHARE = "LENS"
+PORT = 4445
+SERVICE_SECONDS = 10 # how often the worker follows the settings
+TREE_SECONDS = 10 # how long one person's view of the tree is reused
+KEY_SECONDS = 30 # how long a key lookup is trusted before it's checked again (so revoking takes effect)
+RETRY_SECONDS = 60 # after a port that couldn't be opened
+_WRITE = _os.O_WRONLY | _os.O_RDWR | _os.O_CREAT | _os.O_TRUNC | _os.O_APPEND
+
+
+@dataclass
+class Entry:
+ """One folder or file in the tree, as the share shows it (`source`: the tree's own entry, to read it by)."""
+
+ name: str
+ is_dir: bool
+ size: int = 0
+ mtime: float = 0.0
+ source: object = None
+
+
+# ---------- who is signed in ----------
+class Keys:
+ """File access keys, looked up when someone signs in and again every KEY_SECONDS while they stay connected.
+
+ `lookup(key_id)` answers {account, secret} or None (file_tree.lookup_key by default)."""
+
+ def __init__(self, lookup, touch=None):
+ self.lookup, self.touch = lookup, touch or (lambda key_id: None)
+ self.cache: dict[str, tuple[float, dict | None]] = {}
+ self.lock = threading.Lock()
+
+ def get(self, key_id):
+ key_id = (key_id or "").lower()
+ if not key_id:
+ return None
+ with self.lock:
+ hit = self.cache.get(key_id)
+ if hit and time.monotonic() - hit[0] < KEY_SECONDS:
+ return hit[1]
+ try:
+ row = self.lookup(key_id)
+ except Exception: # noqa: BLE001 - the database is away: nobody signs in rather than everybody
+ row = None
+ with self.lock:
+ self.cache[key_id] = (time.monotonic(), row)
+ return row
+
+
+class Credentials:
+ """What impacket checks a sign-in against ({name: (uid, lmhash, nthash)}), from the keys as asked."""
+
+ def __init__(self, keys: Keys):
+ self.keys = keys
+
+ def __len__(self):
+ return 1 # never empty: impacket lets anyone in when it has no credentials at all
+
+ def __contains__(self, name):
+ return self.keys.get(name) is not None
+
+ def __getitem__(self, name):
+ row = self.keys.get(name)
+ if row is None:
+ raise KeyError(name)
+ return (0, b"", nt_hash(row["secret"]))
+
+
+def nt_hash(secret: str) -> bytes:
+ """The NT hash NTLM checks a password with: MD4 of the UTF-16LE password."""
+ from Cryptodome.Hash import MD4 # impacket's dependency
+
+ return MD4.new(secret.encode("utf-16le")).digest()
+
+
+# ---------- the file system impacket sees ----------
+class VirtualOS(types.ModuleType):
+ """Just enough of `os` for impacket.smbserver, answered from the tree: read-only, and nothing outside ROOT.
+
+ Paths are ROOT//; the key says whose view of the tree it is (and is checked again as it ages)."""
+
+ def __init__(self, tree, keys: Keys):
+ super().__init__("os")
+ for k in ("O_RDONLY", "O_WRONLY", "O_RDWR", "O_CREAT", "O_TRUNC", "O_APPEND", "O_EXCL", "SEEK_SET", "SEEK_CUR", "SEEK_END"):
+ setattr(self, k, getattr(_os, k))
+ self.sep, self.name, self.O_BINARY = "/", "posix", 0
+ self.getpid, self.urandom, self.fspath, self.environ = _os.getpid, _os.urandom, _os.fspath, {}
+ self.tree, self.keys = tree, keys
+ self.fds: dict[int, list] = {}
+ self.lock = threading.Lock()
+ self.next_fd = itertools.count(1 << 20)
+ self.path = _Path(self)
+
+ def _where(self, p):
+ p = posixpath.normpath(_os.fspath(p) if not isinstance(p, bytes) else p.decode())
+ if p != ROOT and not p.startswith(ROOT + "/"):
+ raise PermissionError(errno.EACCES, "outside the share", p)
+ key_id, _, rel = p[len(ROOT) + 1 :].partition("/")
+ row = self.keys.get(key_id)
+ if row is None:
+ raise PermissionError(errno.EACCES, "signed out", p)
+ return row["account"], rel
+
+ def _entry(self, p):
+ if posixpath.normpath(_os.fspath(p)) == ROOT: # the parent of every key's folder (a listing's "..")
+ return None, None, Entry("", True)
+ account, rel = self._where(p)
+ e = self.tree.entry(account, rel)
+ if e is None:
+ raise FileNotFoundError(errno.ENOENT, "no such file or folder", p)
+ return account, rel, e
+
+ def stat(self, p, *a, **k):
+ _, _, e = self._entry(p)
+ mode = (_stat.S_IFDIR | 0o555) if e.is_dir else (_stat.S_IFREG | 0o444)
+ t = float(e.mtime or 0)
+ return _os.stat_result((mode, 0, 0, 1, 0, 0, int(e.size or 0), t, t, t))
+
+ def listdir(self, p):
+ account, rel, e = self._entry(p)
+ if account is None:
+ raise PermissionError(errno.EACCES, "not a share", p)
+ if not e.is_dir:
+ raise NotADirectoryError(errno.ENOTDIR, "not a folder", p)
+ return [c.name for c in self.tree.children(account, rel)]
+
+ def open(self, p, flags, mode=0o777, **k):
+ if flags & _WRITE:
+ raise PermissionError(errno.EROFS, "the share is read-only", p)
+ account, rel, e = self._entry(p)
+ if account is None:
+ raise PermissionError(errno.EACCES, "not a share", p)
+ reader = None if e.is_dir else self.tree.open(account, e)
+ with self.lock:
+ fd = next(self.next_fd)
+ self.fds[fd] = [reader, e, 0]
+ return fd
+
+ def _fd(self, fd):
+ f = self.fds.get(fd)
+ if f is None:
+ raise OSError(errno.EBADF, "bad file descriptor")
+ return f
+
+ def lseek(self, fd, pos, how):
+ f = self._fd(fd)
+ f[2] = max(0, pos if how == _os.SEEK_SET else (f[2] + pos if how == _os.SEEK_CUR else int(f[1].size or 0) + pos))
+ return f[2]
+
+ def read(self, fd, n):
+ f = self._fd(fd)
+ if f[0] is None:
+ raise IsADirectoryError(errno.EISDIR, "is a folder")
+ data = f[0].read(f[2], int(n)) or b""
+ f[2] += len(data)
+ return data
+
+ def close(self, fd):
+ with self.lock:
+ f = self.fds.pop(fd, None)
+ if f and f[0] is not None:
+ f[0].close()
+
+ def fsync(self, fd):
+ return None
+
+ def _read_only(self, *a, **k):
+ raise PermissionError(errno.EROFS, "the share is read-only")
+
+ write = remove = unlink = mkdir = makedirs = rmdir = rename = replace = utime = chmod = _read_only
+
+ def setreuid(self, *a):
+ return None
+
+ setregid = setreuid
+
+
+class _Path:
+ """os.path for VirtualOS: the pure functions of posixpath, and the ones that look at files ask the tree."""
+
+ join = staticmethod(posixpath.join)
+ basename = staticmethod(posixpath.basename)
+ dirname = staticmethod(posixpath.dirname)
+ normpath = staticmethod(posixpath.normpath)
+ splitext = staticmethod(posixpath.splitext)
+ commonprefix = staticmethod(posixpath.commonprefix)
+ sep = "/"
+
+ def __init__(self, vos):
+ self.vos = vos
+
+ @staticmethod
+ def realpath(p, *a, **k):
+ return posixpath.normpath(posixpath.join("/", _os.fspath(p)))
+
+ abspath = realpath
+
+ def _get(self, p):
+ try:
+ return self.vos._entry(p)[2]
+ except OSError:
+ return None
+
+ def exists(self, p):
+ return self._get(p) is not None
+
+ def isdir(self, p):
+ e = self._get(p)
+ return bool(e and e.is_dir)
+
+ def isfile(self, p):
+ e = self._get(p)
+ return bool(e and not e.is_dir)
+
+ def getsize(self, p):
+ return int(self.vos._entry(p)[2].size or 0)
+
+
+# ---------- the shared file tree (filetree.py) ----------
+class FileTree:
+ """filetree.Tree as the share needs it: entries by path for an account, and readers that stream a file onwards.
+
+ A person's Tree (who they are and what they may see) is made at most every TREE_SECONDS, so a folder listing and
+ the many look-ups an SMB client makes right after it don't each ask the database again."""
+
+ def __init__(self, db, cfg_fn):
+ self.db, self.cfg_fn = db, cfg_fn
+ self.trees: dict[str, tuple[float, object]] = {}
+ self.lock = threading.Lock()
+
+ def _tree(self, account):
+ from . import auth, filetree
+
+ with self.lock:
+ hit = self.trees.get(account)
+ if hit and time.monotonic() - hit[0] < TREE_SECONDS:
+ return hit[1]
+ row = auth.get_account(self.db, account)
+ if not row or row.get("disabled"):
+ raise PermissionError(errno.EACCES, "no such account")
+ t = filetree.Tree(self.db, self.cfg_fn(), filetree.Viewer.of(self.db, row))
+ with self.lock:
+ self.trees[account] = (time.monotonic(), t)
+ return t
+
+ @staticmethod
+ def _entry(e):
+ return Entry(e.name, bool(e.folder), int(e.size or 0), _seconds(e.modified), e)
+
+ def entry(self, account, path):
+ from . import filetree
+
+ try:
+ return self._entry(self._tree(account).stat(path))
+ except filetree.NotFound:
+ return None
+
+ def children(self, account, path):
+ from . import filetree
+
+ try:
+ return [self._entry(e) for e in self._tree(account).list(path)]
+ except (filetree.NotFound, filetree.NotAFolder):
+ return []
+
+ def open(self, account, e):
+ return Reader(lambda start, end: e.source.read(self.db, self.cfg_fn(), start, end), e.size)
+
+
+class Reader:
+ """Reads a file from `chunks(start, end)` (an iterator of bytes), going on from where the last read stopped, so
+ a client reading a file through moves along one stream; a jump starts a new one from there."""
+
+ def __init__(self, chunks, size):
+ self.chunks, self.size = chunks, int(size or 0)
+ self.it = None
+ self.at = 0 # where the stream is
+ self.buf = b""
+
+ def read(self, offset, n):
+ if offset >= self.size or n <= 0:
+ return b""
+ if self.it is None or offset != self.at:
+ self.close()
+ self.it, self.at, self.buf = iter(self.chunks(offset, self.size - 1)), offset, b""
+ while len(self.buf) < n:
+ chunk = next(self.it, None)
+ if not chunk:
+ break
+ self.buf += chunk
+ out, self.buf = self.buf[:n], self.buf[n:]
+ self.at += len(out)
+ return out
+
+ def close(self):
+ close = getattr(self.it, "close", None)
+ if close:
+ close()
+ self.it = None
+
+
+def _seconds(when):
+ if not when:
+ return 0.0
+ try:
+ import datetime as dt
+
+ return dt.datetime.fromisoformat(str(when).replace("Z", "+00:00")).timestamp()
+ except ValueError:
+ return 0.0
+
+
+# ---------- the server ----------
+def allowed(networks, address):
+ """Whether a client address is in one of the networks (an empty list allows none)."""
+ try:
+ ip = ipaddress.ip_address(str(address).split("%")[0])
+ except ValueError:
+ return False
+ if getattr(ip, "ipv4_mapped", None):
+ ip = ip.ipv4_mapped
+ for n in networks or ():
+ try:
+ if ip in ipaddress.ip_network(n, strict=False):
+ return True
+ except ValueError:
+ continue
+ return False
+
+
+def _impacket():
+ """impacket's server module with Lens's hooks in place (once): its `os` is VirtualOS, shares are per key."""
+ from impacket import smbserver
+
+ if not getattr(smbserver, "_lens", False):
+ logging.getLogger("impacket.smbserver").setLevel(logging.WARNING) # it logs NTLM responses at INFO
+ plain = smbserver.searchShare
+
+ def search_share(conn_id, share, server):
+ """The share for this session: the key's own view of the tree, or nothing for a guest."""
+ found = plain(conn_id, share, server)
+ if found is None or getattr(server, "keys", None) is None:
+ return found
+ key_id = (server.getConnectionData(conn_id, False).get("user_name") or "").lower()
+ if not key_id or server.keys.get(key_id) is None:
+ return None
+ if str(share).upper() == SHARE:
+ found["path"] = f"{ROOT}/{key_id}"
+ return found
+
+ smbserver.searchShare = search_share
+ smbserver._lens = True
+ return smbserver
+
+
+class Server:
+ """One SMB server on (bind, port), serving `tree` to holders of file access keys, in its own threads."""
+
+ def __init__(self, bind, port, tree, keys: Keys, networks=None, name="Lens", log=None):
+ smbserver = _impacket()
+ self.log = log or (lambda *a: None)
+ self.networks = list(networks if networks is not None else store.DEFAULTS["smb"]["allowed_networks"])
+ self.keys = keys
+ self.live: set = set() # open connections, closed when the server stops
+ self.lock = threading.Lock()
+ vos = VirtualOS(tree, keys)
+ smbserver.os = vos
+ outer = self
+
+ class LensSMB(smbserver.SMBSERVER):
+ local = threading.local()
+ daemon_threads, block_on_close = True, False
+
+ def process_request(self, request, client_address):
+ with outer.lock:
+ outer.live.add(request)
+ super().process_request(request, client_address)
+
+ def shutdown_request(self, request):
+ with outer.lock:
+ outer.live.discard(request)
+ super().shutdown_request(request)
+
+ def getSMBChallenge(self): # noqa: N802 - impacket's name
+ """A random challenge per connection (impacket's is fixed); one thread serves one connection."""
+ if getattr(self.local, "challenge", None) is None:
+ self.local.challenge = _os.urandom(8)
+ return self.local.challenge
+
+ def getCredentials(self): # noqa: N802
+ return creds
+
+ def verify_request(self, request, client_address):
+ ok = allowed(outer.networks, client_address[0])
+ if not ok:
+ outer.log(f"smb: refused {client_address[0]}: not in the allowed networks")
+ return ok
+
+ def processRequest(self, conn_id, data): # noqa: N802
+ if data[:4] == b"\xffSMB" and len(data) > 4 and data[4] != 0x72: # SMB1, past SMB_COM_NEGOTIATE
+ raise ConnectionAbortedError("SMB1 is not served")
+ return super().processRequest(conn_id, data)
+
+ creds = Credentials(keys)
+ cfg = smbserver.configparser.ConfigParser()
+ cfg.add_section("global")
+ for k, v in {
+ "server_name": name[:15] or "LENS",
+ "server_os": "Lens",
+ "server_domain": "LENS",
+ "log_file": "None",
+ "rpc_apis": "no",
+ "credentials_file": "",
+ "anonymous_logon": "False",
+ "SMB2Support": "True",
+ }.items():
+ cfg.set("global", k, v)
+ for share, path, comment, kind in (("IPC$", "", "", "3"), (SHARE, ROOT, "Lens: the graph as files (read-only)", "0")):
+ cfg.add_section(share)
+ for k, v in {"comment": comment, "read only": "yes", "share type": kind, "path": path}.items():
+ cfg.set(share, k, v)
+ self.server = LensSMB((bind, int(port)), config_parser=cfg, ipv6=":" in bind)
+ self.server.keys = keys
+ self.server.processConfigFile()
+ self.port = self.server.server_address[1]
+ self.extras = [smbserver.SRVSServer(), smbserver.WKSTServer()] # share lists for Explorer and Finder
+ for x in self.extras:
+ x.daemon = True
+ self.server.registerNamedPipe("srvsvc", ("127.0.0.1", self.extras[0].getListenPort()))
+ self.server.registerNamedPipe("wkssvc", ("127.0.0.1", self.extras[1].getListenPort()))
+ self.thread = None
+
+ def start(self):
+ for x in self.extras:
+ x.start()
+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True, name=f"smb-{self.port}")
+ self.thread.start()
+ return self
+
+ def stop(self):
+ """Stop listening and end every open session (turning SMB off, or moving it, disconnects people)."""
+ try:
+ self.server.shutdown()
+ finally:
+ self.server.server_close()
+ with self.lock:
+ live, self.live = list(self.live), set()
+ for sock in live:
+ try:
+ sock.shutdown(socket.SHUT_RDWR)
+ except OSError:
+ pass
+ for x in self.extras:
+ try:
+ x.server.server_close()
+ except Exception: # noqa: BLE001
+ pass
+
+
+# ---------- following the settings ----------
+def conf(cfg):
+ return {**store.DEFAULTS["smb"], **(cfg.get("smb") or {})}
+
+
+def _keys(db, cfg_fn):
+ from . import file_tree
+
+ return Keys(lambda key_id: file_tree.lookup_key(db, cfg_fn(), key_id), lambda key_id: file_tree.touch_key(db, key_id))
+
+
+class Runner:
+ """Runs the server while SMB is on, moves it when its port or networks change, and says how it's doing."""
+
+ def __init__(self, db, cfg_fn, name=None, log=None, tree=None, keys=None):
+ self.db, self.cfg_fn, self.log = db, cfg_fn, log or (lambda *a: None)
+ self.name = name or f"{socket.gethostname()}-{_os.getpid()}"
+ self.tree, self.keys = tree, keys
+ self.server: Server | None = None
+ self.want = None
+ self.error = None
+ self.retry = 0.0
+
+ def apply(self):
+ s = conf(self.cfg_fn())
+ want = (s["bind"], int(s["port"])) if s.get("enabled") else None
+ if self.server is not None:
+ self.server.networks = list(s.get("allowed_networks") or [])
+ if want == self.want and (self.server is not None or want is None or time.monotonic() < self.retry):
+ return
+ self.close()
+ self.want, self.error = want, None
+ if want is None:
+ return
+ try:
+ self.tree = self.tree or FileTree(self.db, self.cfg_fn)
+ self.keys = self.keys or _keys(self.db, self.cfg_fn)
+ self.server = Server(want[0], want[1], self.tree, self.keys, s.get("allowed_networks"), log=self.log).start()
+ self.log(f"smb: serving the file tree on port {self.server.port} (read-only)")
+ except (OSError, ImportError) as e:
+ self.error = (
+ f"port {want[1]}: {e.strerror or e}" if isinstance(e, OSError) else "impacket isn't installed (pip install impacket)"
+ )
+ self.retry = time.monotonic() + RETRY_SECONDS
+ self.log(f"smb: {self.error}")
+
+ def heartbeat(self):
+ if self.want is None:
+ self.db.q("DELETE $r", r=R("share_service", f"smb-{self.name}"))
+ return
+ d = {"kind": "smb", "process": self.name, "at": store.now(), "running": self.server is not None, "error": self.error}
+ if self.server is not None:
+ d["port"] = self.server.port
+ self.db.q("UPSERT $r CONTENT $d", r=R("share_service", f"smb-{self.name}"), d=store.clean(d))
+
+ def close(self):
+ if self.server is not None:
+ try:
+ self.server.stop()
+ except Exception: # noqa: BLE001
+ pass
+ self.server = None
+
+ def loop(self, stop):
+ while True:
+ try:
+ self.apply()
+ self.heartbeat()
+ except Exception as e: # noqa: BLE001 - keep following the settings
+ self.log(f"smb: {type(e).__name__}: {e}")
+ if stop.wait(SERVICE_SECONDS):
+ break
+ self.close()
+
+
+def start(db, cfg_fn, stop, name=None, log=None):
+ """The SMB share thread, until `stop` is set. It does nothing while SMB is off."""
+ r = Runner(db, cfg_fn, name, log)
+ threading.Thread(target=r.loop, args=(stop,), daemon=True, name="smb-share").start()
+ return r
+
+
+def published_port(cfg):
+ """The port clients use: where Docker publishes the share (LENS_SMB_PORT), else the one Lens listens on."""
+ try:
+ return int(_os.environ.get("LENS_SMB_PORT") or conf(cfg)["port"])
+ except ValueError:
+ return int(conf(cfg)["port"])
+
+
+def status(db, cfg):
+ """Whether SMB is on and served (by the workers heard from in the last minute), and how to connect to it."""
+ s = conf(cfg)
+ cut = time.time() - 60
+ rows = [r for r in db.rows("SELECT * FROM share_service WHERE kind = 'smb'") if _seconds(r.get("at")) >= cut]
+ running = [r for r in rows if r.get("running")]
+ error = next((r.get("error") for r in rows if r.get("error")), None)
+ port = published_port(cfg)
+ try:
+ import importlib.util
+
+ installed = importlib.util.find_spec("impacket") is not None
+ except (ImportError, ValueError):
+ installed = False
+ phase = "off" if not s.get("enabled") else "running" if running else "error" if error else "starting"
+ host = ""
+ return {
+ "enabled": bool(s.get("enabled")),
+ "phase": phase,
+ "port": port,
+ "share": SHARE,
+ "allowed_networks": list(s.get("allowed_networks") or []),
+ "error": error if phase != "running" else None,
+ "process": running[0].get("process") if running else None,
+ "installed": installed,
+ "address": f"smb://{host}{'' if port == 445 else f':{port}'}/{SHARE}",
+ "mount": f"sudo mount -t cifs -o port={port},username=,ro,vers=2.0 //{host}/{SHARE} /mnt/lens",
+ }
diff --git a/fastapi_backend/app/domain/store.py b/fastapi_backend/app/domain/store.py
index 75a8415d8..13a169c18 100644
--- a/fastapi_backend/app/domain/store.py
+++ b/fastapi_backend/app/domain/store.py
@@ -434,6 +434,16 @@ def labels():
# or open up arbitrary folders on the server. Local folders can only be watched inside local_roots.
"sources": {"rclone": None, "local_roots": [], "check_seconds": 15, "cache_dir": None},
"reports": {"audio": "link"},
+ # the read-only SMB share of the file tree (smb_share.py, docs/file-sharing.md): off until an admin turns it on, then
+ # served by `lens worker` to people signing in with a file access key, from allowed_networks only. bind and port
+ # are startup settings only: in Docker it listens on 0.0.0.0:4445 inside the container, published where the web
+ # app is (LENS_SHARE_BIND, else LENS_BIND) on LENS_SMB_PORT.
+ "smb": {
+ "enabled": False,
+ "bind": os.environ.get("LENS_SMB_LISTEN") or "127.0.0.1",
+ "port": int(os.environ.get("LENS_SMB_LISTEN_PORT") or 4445),
+ "allowed_networks": ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "127.0.0.0/8", "100.64.0.0/10", "fc00::/7", "::1/128"],
+ },
# sensors (sensors.py, docs/sensors.md): off until an admin turns them on. Then the MQTT hub and the syslog listener
# run in the process that runs routines (`lens worker`), on these ports; syslog is taken only from syslog_networks.
# store, raw_days, rollup_days, important_days and max_per_minute are what a stream sensor gets unless it has its own.
@@ -1099,6 +1109,8 @@ def close(self):
"DEFINE TABLE IF NOT EXISTS sensor_login SCHEMALESS",
"DEFINE INDEX IF NOT EXISTS sensor_login_name ON sensor_login FIELDS username UNIQUE",
"DEFINE TABLE IF NOT EXISTS sensor_service SCHEMALESS",
+ # the file-sharing servers running now (smb_share.py): one row per server and process, refreshed while it runs
+ "DEFINE TABLE IF NOT EXISTS share_service SCHEMALESS",
# the chat-room bridge (bridge.py): which process reads Matterbridge (bridge_state:lease); its conversations are
# chats with a `bridge` key (the room and person)
"DEFINE TABLE IF NOT EXISTS bridge_state SCHEMALESS",
diff --git a/fastapi_backend/app/schemas/admin.py b/fastapi_backend/app/schemas/admin.py
index 6743dc51c..222c4212e 100644
--- a/fastapi_backend/app/schemas/admin.py
+++ b/fastapi_backend/app/schemas/admin.py
@@ -46,6 +46,19 @@ class BridgeStatus(ResponseModel):
matterbridge: MatterbridgeStatus | None = Field(None, description="the Matterbridge Lens runs, when it runs one")
+class SmbStatus(ResponseModel):
+ enabled: bool
+ phase: Literal["off", "starting", "running", "error"]
+ port: int = Field(description="the port clients connect to (where Docker publishes it)")
+ share: str = Field(description="the share's name")
+ allowed_networks: list[str]
+ error: str | None = None
+ process: str | None = Field(None, description="the worker serving it")
+ installed: bool = Field(description="whether the SMB server (impacket) is installed here; it's fetched when the share is turned on")
+ address: str = Field(description="the address Finder and Linux file managers open (the machine's name filled in by the caller)")
+ mount: str = Field(description="the command that mounts it on Linux")
+
+
class TunnelStatus(ResponseModel):
mode: Literal["off", "quick", "token", "managed"]
running: bool = Field(description="cloudflared is running in a server process")
diff --git a/fastapi_backend/pyproject.toml b/fastapi_backend/pyproject.toml
index 784eade8f..8c5daa638 100644
--- a/fastapi_backend/pyproject.toml
+++ b/fastapi_backend/pyproject.toml
@@ -47,6 +47,9 @@ insightface = ["insightface", "onnxruntime"]
objects = ["onnxruntime"]
# Checking IIIF manifests against the official schema
validate = ["jsonschema"]
+# the SMB share of the file tree (smb_share.py): impacket's SMB server (a modified Apache 1.1 license); fetched when
+# Settings › SMB share is turned on
+smb = ["impacket>=0.13"]
# Outlook .msg emails (extract-msg is GPL-3.0; .eml needs nothing)
msg = ["extract-msg"]
@@ -74,6 +77,7 @@ dev = [
"onnxruntime>=1.18", # the objects tests run a small YOLOX-shaped model
"onnx>=1.23.2", # ... which they build
"mcp>=2.3.0", # the official MCP client, to test the MCP server with
+ "impacket>=0.13", # the SMB share's server, and the SMB client its tests sign in with
]
[tool.hatch.build.targets.wheel]
diff --git a/fastapi_backend/tests/domain/test_smb_share.py b/fastapi_backend/tests/domain/test_smb_share.py
new file mode 100644
index 000000000..dd7c0dd7e
--- /dev/null
+++ b/fastapi_backend/tests/domain/test_smb_share.py
@@ -0,0 +1,168 @@
+"""The SMB share (smb_share.py), end to end with impacket's own SMB client: a key's view, read-only, refusals."""
+
+from __future__ import annotations
+
+import io
+import posixpath
+
+import pytest
+
+pytest.importorskip("impacket")
+
+from impacket.smbconnection import SessionError, SMBConnection # noqa: E402
+
+from app.domain import smb_share # noqa: E402
+
+BIG = bytes(range(256)) * 4000
+
+
+class FakeTree:
+ """Two people's views: ada sees the 'pods' node, bob sees nothing."""
+
+ FILES = {"ada": {"Pods/Episode 1/audio.txt": b"hello lens\n", "Pods/big.bin": BIG}, "bob": {}}
+
+ def _dirs(self, account):
+ d = {""}
+ for p in self.FILES[account]:
+ parts = p.split("/")
+ d.update("/".join(parts[:i]) for i in range(1, len(parts)))
+ return d
+
+ def entry(self, account, path):
+ files = self.FILES[account]
+ if path in files:
+ return smb_share.Entry(posixpath.basename(path), False, len(files[path]), 1.7e9, path)
+ if path in self._dirs(account):
+ return smb_share.Entry(posixpath.basename(path), True, 0, 1.7e9)
+ return None
+
+ def children(self, account, path):
+ pre = f"{path}/" if path else ""
+ names = {p[len(pre) :].split("/")[0] for p in [*self.FILES[account], *self._dirs(account)] if p.startswith(pre) and p[len(pre) :]}
+ return [self.entry(account, pre + n) for n in sorted(names)]
+
+ def open(self, account, e):
+ data = self.FILES[account][e.source]
+ return smb_share.Reader(lambda start, end: (data[i : min(i + 1000, end + 1)] for i in range(start, end + 1, 1000)), len(data))
+
+
+KEYS = {"lk_ada": {"account": "ada", "secret": "ada-secret-1"}, "lk_bob": {"account": "bob", "secret": "bob-secret-2"}}
+
+
+@pytest.fixture
+def server():
+ keys = smb_share.Keys(lambda k: KEYS.get(k))
+ s = smb_share.Server("127.0.0.1", 0, FakeTree(), keys, ["127.0.0.0/8"]).start()
+ yield s, keys
+ s.stop()
+
+
+def connect(port, user, password):
+ c = SMBConnection("127.0.0.1", "127.0.0.1", sess_port=port)
+ c.login(user, password)
+ return c
+
+
+def test_reads_the_tree_as_its_key_sees_it(server):
+ s, _ = server
+ c = connect(s.port, "lk_ada", "ada-secret-1")
+ names = sorted(f.get_longname() for f in c.listPath(smb_share.SHARE, "*") if f.get_longname() not in (".", ".."))
+ assert names == ["Pods"]
+ inner = {f.get_longname(): f for f in c.listPath(smb_share.SHARE, "Pods\\*")}
+ assert inner["Episode 1"].is_directory() and inner["big.bin"].get_filesize() == len(BIG)
+ out = io.BytesIO()
+ c.getFile(smb_share.SHARE, "Pods\\big.bin", out.write)
+ assert out.getvalue() == BIG
+ out = io.BytesIO()
+ c.getFile(smb_share.SHARE, "Pods\\Episode 1\\audio.txt", out.write)
+ assert out.getvalue() == b"hello lens\n"
+ # bob signs in fine and sees an empty share, not ada's
+ b = connect(s.port, "lk_bob", "bob-secret-2")
+ assert [f.get_longname() for f in b.listPath(smb_share.SHARE, "*") if f.get_longname() not in (".", "..")] == []
+ with pytest.raises(SessionError):
+ b.getFile(smb_share.SHARE, "Pods\\big.bin", io.BytesIO().write)
+
+
+def test_nothing_can_be_written(server):
+ s, _ = server
+ c = connect(s.port, "lk_ada", "ada-secret-1")
+ with pytest.raises(SessionError):
+ c.putFile(smb_share.SHARE, "Pods\\new.txt", io.BytesIO(b"x").read)
+ with pytest.raises(SessionError):
+ c.createDirectory(smb_share.SHARE, "Pods\\new")
+ with pytest.raises(SessionError):
+ c.deleteFile(smb_share.SHARE, "Pods\\big.bin")
+ with pytest.raises(SessionError):
+ c.rename(smb_share.SHARE, "Pods\\big.bin", "Pods\\moved.bin")
+ assert len(FakeTree.FILES["ada"]) == 2
+
+
+def test_wrong_password_guest_and_revoked_keys_are_refused(server):
+ s, keys = server
+ with pytest.raises(SessionError):
+ connect(s.port, "lk_ada", "wrong")
+ with pytest.raises(SessionError):
+ connect(s.port, "nobody", "ada-secret-1")
+ guest = SMBConnection("127.0.0.1", "127.0.0.1", sess_port=s.port)
+ try:
+ guest.login("", "")
+ with pytest.raises(SessionError):
+ guest.listPath(smb_share.SHARE, "*")
+ except SessionError:
+ pass # refused at sign-in: also fine
+ # a revoked key stops working once the cached lookup ages out
+ c = connect(s.port, "lk_ada", "ada-secret-1")
+ gone = KEYS.pop("lk_ada")
+ try:
+ keys.cache.clear()
+ with pytest.raises(SessionError):
+ c.listPath(smb_share.SHARE, "*")
+ finally:
+ KEYS["lk_ada"] = gone
+
+
+def test_outside_the_allowed_networks_is_refused():
+ keys = smb_share.Keys(lambda k: KEYS.get(k))
+ s = smb_share.Server("127.0.0.1", 0, FakeTree(), keys, ["10.0.0.0/8"]).start()
+ try:
+ with pytest.raises(Exception): # noqa: B017 - the connection is closed before anything is said
+ connect(s.port, "lk_ada", "ada-secret-1")
+ finally:
+ s.stop()
+
+
+def test_virtual_os_never_reaches_the_disk():
+ vos = smb_share.VirtualOS(FakeTree(), smb_share.Keys(lambda k: KEYS.get(k)))
+ for p in ("/etc/passwd", "/lens-smb/../etc/passwd", "/lens-smb-other/x"):
+ with pytest.raises(PermissionError):
+ vos.stat(p)
+ assert not vos.path.exists(p)
+ with pytest.raises(PermissionError):
+ vos.open("/lens-smb/lk_ada/Pods/big.bin", smb_share._os.O_RDWR)
+ with pytest.raises(PermissionError):
+ vos.stat("/lens-smb/lk_nobody/Pods")
+
+
+def test_allowed():
+ nets = ["192.168.0.0/16", "::1/128"]
+ assert smb_share.allowed(nets, "192.168.1.5") and smb_share.allowed(nets, "::ffff:192.168.1.5") and smb_share.allowed(nets, "::1")
+ assert not smb_share.allowed(nets, "8.8.8.8") and not smb_share.allowed([], "127.0.0.1") and not smb_share.allowed(nets, "junk")
+
+
+def test_reader_streams_on_and_restarts_on_a_jump():
+ calls = []
+
+ def chunks(start, end):
+ calls.append(start)
+ return (BIG[i : min(i + 777, end + 1)] for i in range(start, end + 1, 777))
+
+ r = smb_share.Reader(chunks, len(BIG))
+ got = b"".join(r.read(o, 4096) for o in range(0, len(BIG), 4096))
+ assert got == BIG and calls == [0]
+ assert r.read(10, 5) == BIG[10:15] and calls == [0, 10]
+ assert r.read(len(BIG), 5) == b""
+ r.close()
+
+
+def test_nt_hash_matches_the_known_vector():
+ assert smb_share.nt_hash("password").hex() == "8846f7eaee8fb117ad06bdd830b7586c"
diff --git a/fastapi_backend/uv.lock b/fastapi_backend/uv.lock
index 89e664d29..8b28ad668 100644
--- a/fastapi_backend/uv.lock
+++ b/fastapi_backend/uv.lock
@@ -1075,6 +1075,23 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/06/cf/1731c0dd182ee35f80a39e63afb3d03056ea0dd561b7498932b10b2e34d9/filelock-4.0.7-py3-none-any.whl", hash = "sha256:a93c4d93269b339a6af4848342c7e940d0f9928ad95eff64764699e5f1bf8a6a", size = 109242, upload-time = "2026-09-29T23:04:04.696Z" },
]
+[[package]]
+name = "flask"
+version = "3.1.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "blinker" },
+ { name = "click" },
+ { name = "itsdangerous" },
+ { name = "jinja2" },
+ { name = "markupsafe" },
+ { name = "werkzeug" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/26/00/35d85dcce6c57fdc871f3867d465d780f302a175ea360f62533f12b27e2b/flask-3.1.3.tar.gz", hash = "sha256:0ef0e52b8a9cd932855379197dd8f94047b359ca0a78695144304cb45f87c9eb", size = 759004, upload-time = "2026-02-19T05:00:57.678Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7f/9c/34f6962f9b9e9c71f6e5ed806e0d0ff03c9d1b0b2340088a0cf4bce09b18/flask-3.1.3-py3-none-any.whl", hash = "sha256:f4bcbefc124291925f1a26446da31a5178f9483862233b23c0c96a20701f670c", size = 103424, upload-time = "2026-02-19T05:00:56.027Z" },
+]
+
[[package]]
name = "flatbuffers"
version = "25.12.19"
@@ -1490,6 +1507,27 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/ba/4b/87a794e51d150f62a55715c453c9afbf6103fe24afef6db26a929a8480b7/imageio-2.38.0-py3-none-any.whl", hash = "sha256:474ea3a39e36e0e8e02d81d7f10412aaecec7a2825e5fbc4f44cbcd7bb7cebfc", size = 328055, upload-time = "2026-09-28T07:44:06.169Z" },
]
+[[package]]
+name = "impacket"
+version = "0.13.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "charset-normalizer" },
+ { name = "flask" },
+ { name = "ldap3" },
+ { name = "ldapdomaindump" },
+ { name = "pyasn1" },
+ { name = "pyasn1-modules" },
+ { name = "pycryptodomex" },
+ { name = "pyopenssl" },
+ { name = "pyreadline3", marker = "sys_platform == 'win32'" },
+ { name = "six" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/67/f2/fb8e14eb0a234b20b63a6685da2caee2c4269b3925d572a3a447b83fc9df/impacket-0.13.1.tar.gz", hash = "sha256:ed91c802b6beff6546afd2262942bc1a188b4671fb91ec751d46a1d66d28c2cf", size = 1737704, upload-time = "2026-05-19T15:30:38.956Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/72/44/c28ecebffd4c08d4f2caf4f7d4fd3fd9eb0124dcf15e9bf8a1e20287bcb0/impacket-0.13.1-py3-none-any.whl", hash = "sha256:3e5349c1209cdd3b90bff6f8b61c0d89aea0f3dbba6ad02ad254b9d3ef2301d0", size = 1751974, upload-time = "2026-05-19T15:30:36.077Z" },
+]
+
[[package]]
name = "iniconfig"
version = "2.3.0"
@@ -1518,6 +1556,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/66/d4/7c030e73d3064e63fc7927fc9c0cb5b8c52e12a52442317e9d0ad3d7bb37/insightface-2.1-py3-none-any.whl", hash = "sha256:dcd58ee79d99d689572477315f3149353afd65a36dc575f597cbb217a7bde399", size = 1169452, upload-time = "2026-10-03T16:52:15.821Z" },
]
+[[package]]
+name = "itsdangerous"
+version = "2.2.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/9c/cb/8ac0172223afbccb63986cc25049b154ecfb5e85932587206f42317be31d/itsdangerous-2.2.0.tar.gz", hash = "sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173", size = 54410, upload-time = "2024-04-16T21:28:15.614Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/04/96/92447566d16df59b2a776c0fb82dbc4d9e07cd95062562af01e408583fc4/itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef", size = 16234, upload-time = "2024-04-16T21:28:14.499Z" },
+]
+
[[package]]
name = "jaconv"
version = "0.5.0"
@@ -1715,6 +1762,31 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/23/93/4e45e37f26c820216704b36b8e67cc55c490a7abd287a78a26a2c0e21386/lazy_loader-0.6-py3-none-any.whl", hash = "sha256:77253be3391b06124a0e16105bd663b6c54470af1a9ca8e1cf026f38d58ed056", size = 8791, upload-time = "2026-09-21T21:31:31.632Z" },
]
+[[package]]
+name = "ldap3"
+version = "2.9.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pyasn1" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/43/ac/96bd5464e3edbc61595d0d69989f5d9969ae411866427b2500a8e5b812c0/ldap3-2.9.1.tar.gz", hash = "sha256:f3e7fc4718e3f09dda568b57100095e0ce58633bcabbed8667ce3f8fbaa4229f", size = 398830, upload-time = "2021-07-18T06:34:21.786Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/4e/f6/71d6ec9f18da0b2201287ce9db6afb1a1f637dedb3f0703409558981c723/ldap3-2.9.1-py2.py3-none-any.whl", hash = "sha256:5869596fc4948797020d3f03b7939da938778a0f9e2009f7a072ccf92b8e8d70", size = 432192, upload-time = "2021-07-18T06:34:12.905Z" },
+]
+
+[[package]]
+name = "ldapdomaindump"
+version = "0.10.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "dnspython" },
+ { name = "ldap3" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/14/48/2757e0453f828e33f7b41e5489976fbe7d504d513e07da53eb904030a288/ldapdomaindump-0.10.0.tar.gz", hash = "sha256:cbc66b32a7787473ffd169c5319acde46c02fdc9d444556e6448e0def91d3299", size = 19445, upload-time = "2025-04-04T07:39:08.006Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8a/91/5a0015375d5bcc3667f92692e9a244803b9a0e4b651b29a5682e1647669a/ldapdomaindump-0.10.0-py3-none-any.whl", hash = "sha256:3797259596df7a5e1fda98388c96b1d94196f5da5551f1af1aaeedda0c9f5a11", size = 19084, upload-time = "2025-04-04T07:39:06.655Z" },
+]
+
[[package]]
name = "lens"
version = "0.7.0"
@@ -1779,6 +1851,9 @@ sensevoice = [
{ name = "torch" },
{ name = "torchaudio" },
]
+smb = [
+ { name = "impacket" },
+]
validate = [
{ name = "jsonschema" },
]
@@ -1796,6 +1871,7 @@ dev = [
{ name = "coverage" },
{ name = "coveralls" },
{ name = "httpx" },
+ { name = "impacket" },
{ name = "jsonschema" },
{ name = "mcp" },
{ name = "mkdocs-material", extra = ["imaging"] },
@@ -1821,6 +1897,7 @@ requires-dist = [
{ name = "fastapi-mail", specifier = ">=1.4.1,<2" },
{ name = "faster-whisper", marker = "extra == 'whisper'" },
{ name = "funasr", marker = "extra == 'sensevoice'" },
+ { name = "impacket", marker = "extra == 'smb'", specifier = ">=0.13" },
{ name = "insightface", marker = "extra == 'insightface'" },
{ name = "jinja2", specifier = ">=3.1" },
{ name = "jsonschema", marker = "extra == 'validate'" },
@@ -1855,13 +1932,14 @@ requires-dist = [
{ name = "torchaudio", marker = "extra == 'voices'" },
{ name = "webauthn", specifier = ">=3.0.1,<4" },
]
-provides-extras = ["sensevoice", "whisper", "mlx", "laya", "voices", "pyannote", "faces", "mac-ocr", "rapidocr", "doctr", "insightface", "objects", "validate", "msg"]
+provides-extras = ["sensevoice", "whisper", "mlx", "laya", "voices", "pyannote", "faces", "mac-ocr", "rapidocr", "doctr", "insightface", "objects", "validate", "smb", "msg"]
[package.metadata.requires-dev]
dev = [
{ name = "coverage", specifier = ">=7.6" },
{ name = "coveralls", specifier = ">=4.0.1,<5" },
{ name = "httpx", specifier = ">=0.27" },
+ { name = "impacket", specifier = ">=0.13" },
{ name = "jsonschema", specifier = ">=4.23" },
{ name = "mcp", specifier = ">=2.3.0" },
{ name = "mkdocs-material", specifier = ">=9.6.9" },
@@ -3422,6 +3500,32 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/18/3d/f9441a0d798bf2b1e645adc3265e55706aead1255ccdad3856dbdcffec14/pycryptodome-3.23.0-cp37-abi3-win_arm64.whl", hash = "sha256:11eeeb6917903876f134b56ba11abe95c0b0fd5e3330def218083c7d98bbcb3c", size = 1703675, upload-time = "2025-05-17T17:21:13.146Z" },
]
+[[package]]
+name = "pycryptodomex"
+version = "3.24.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/4c/25/214ea825a9031f5af2c8b2506ee16701a2560d4712165dd00098dd527bcb/pycryptodomex-3.24.0.tar.gz", hash = "sha256:0428f19f13452c6b89bbaf2c530f84f369873811dfa77f0cee0da4f40fb0474f", size = 4933136, upload-time = "2026-10-04T17:41:08.988Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0f/52/5235086483b462600958549b27683ccffbb4941ba512934efc5a14b71a39/pycryptodomex-3.24.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:abf768c285d289c4a0e0678f055663162c9d6257c79f5904fbd2692ade94da1c", size = 2475900, upload-time = "2026-10-04T17:39:26.374Z" },
+ { url = "https://files.pythonhosted.org/packages/9e/cd/eeed4b1a1eda71a78defe2c04ff37909461f9c04cd4bde23011d4350cbfb/pycryptodomex-3.24.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:c2f42f24d7112ebb93d3aed581d011c82c20101da7d7a6248145c530e99bd2eb", size = 1643488, upload-time = "2026-10-04T17:39:28.545Z" },
+ { url = "https://files.pythonhosted.org/packages/18/d2/22005d736858dddd3f7a5ddaf4a91dbb89292f0d9c503a9c13b1bb2ecfb8/pycryptodomex-3.24.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:e42a2e9531c40315290278d9eee93ea5031eda3c83969f5709ada51a1c7491b4", size = 2194768, upload-time = "2026-10-04T17:39:31.713Z" },
+ { url = "https://files.pythonhosted.org/packages/19/c4/c350bb48207ae2a6cca02eb45a2dafc3f2d0196b5b33b556cc9b6815e8cc/pycryptodomex-3.24.0-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c7055400f773856cd219680d15525c6fb147237534cbe5394a5f92f57f7efaed", size = 2280612, upload-time = "2026-10-04T17:39:34.828Z" },
+ { url = "https://files.pythonhosted.org/packages/fe/56/539e213fbd572f8e95cdef5a46b0c327c7b2412107c3dba73913cfd20753/pycryptodomex-3.24.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:e8a7463d346015b42a0fb9c9179ebb7cccfd86bf40199c6796b546ac7be0b85c", size = 2186291, upload-time = "2026-10-04T17:39:38.184Z" },
+ { url = "https://files.pythonhosted.org/packages/9b/f3/f8e73be610ef576c6ca98a78c8450a72f12c178bc89d3e94068e48115c97/pycryptodomex-3.24.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:f96e10f0edff9d4b6b253e0a78f7c819749521d3ffe6af0139e08fcd35384405", size = 2278371, upload-time = "2026-10-04T17:39:41.539Z" },
+ { url = "https://files.pythonhosted.org/packages/16/bd/99c89964c5017488992f412f8d645923d8ef996c7f35fc76b7fe019620e1/pycryptodomex-3.24.0-cp313-cp313t-win32.whl", hash = "sha256:3b6276fe007464502df796710fb57dcfeb813b6ccac0eabaf85100be1ad358f2", size = 1792741, upload-time = "2026-10-04T17:39:44.173Z" },
+ { url = "https://files.pythonhosted.org/packages/ca/d5/5a1e469c7eab20c21090d396342894d2f0e25d429eb4df2d9174a03cb226/pycryptodomex-3.24.0-cp313-cp313t-win_amd64.whl", hash = "sha256:88d37b28b450c06a03bd5570467c601fe8c7dbe493ca39771716f56fdbe35d6e", size = 1825623, upload-time = "2026-10-04T17:39:46.422Z" },
+ { url = "https://files.pythonhosted.org/packages/1b/fb/1ca14c7e5318125aff23cd19886a62c8eb9015caa373b5834216c60260a5/pycryptodomex-3.24.0-cp313-cp313t-win_arm64.whl", hash = "sha256:e635c7ac056f2a47d79e2bf7042fb3fc6d175f47796a954388a3cec1f2e082a4", size = 1759392, upload-time = "2026-10-04T17:39:48.676Z" },
+ { url = "https://files.pythonhosted.org/packages/bc/fd/b9186cea5e823f91f40904373cff30cdaea5dfe1863b4be0ed3bf51e4db6/pycryptodomex-3.24.0-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:ef2bd306328a8447d4d2af6037efddd67ef16630876ed3ec84babd16ca558941", size = 2476748, upload-time = "2026-10-04T17:40:17.326Z" },
+ { url = "https://files.pythonhosted.org/packages/65/c4/bf354a7c435da08ba9905a302dce8fac57a33b2ab1e51c78542b698b4b89/pycryptodomex-3.24.0-cp37-abi3-macosx_10_9_x86_64.whl", hash = "sha256:42c8221e3a4ca04b070cb388fca004815f6544951bfb2cc6c7958e293b7caf64", size = 1644339, upload-time = "2026-10-04T17:40:19.872Z" },
+ { url = "https://files.pythonhosted.org/packages/7b/ea/158d0ea838c92ba5d5081ce0f08e4af40d7278f7609ca007fca4d010aa4d/pycryptodomex-3.24.0-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:da9996407d03684221a4e1603b70fad97d8772185e5f75addcd97fcbc4c3281f", size = 2193232, upload-time = "2026-10-04T17:40:22.957Z" },
+ { url = "https://files.pythonhosted.org/packages/c8/9f/376b705a536c65fe41806babe5cdcfb076273a0d72dfbbb92073d3d9b10c/pycryptodomex-3.24.0-cp37-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:556e063b52f338bd924fe5c40692cc1f50cb0453bd1d6580b7ffff2eade1a894", size = 2279395, upload-time = "2026-10-04T17:40:25.777Z" },
+ { url = "https://files.pythonhosted.org/packages/d4/72/a0726c7165ba84d66923c3e5d5411c5abec9a9a4c1759a664e5cf8806a79/pycryptodomex-3.24.0-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:b6690bfae043c81108e28e31dc7e3afa8cb1b1eb0ba590fdbff2b66e4c6913e7", size = 2184779, upload-time = "2026-10-04T17:40:28.813Z" },
+ { url = "https://files.pythonhosted.org/packages/39/51/c5b9d8fc84d5cf67091a007b476e24f634252fb314472e27a58f3bd97458/pycryptodomex-3.24.0-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:5fa46af1281be707e0ec5878aea0f77d58d8d4b465f63f7385a71ae0080bfff9", size = 2276914, upload-time = "2026-10-04T17:40:31.23Z" },
+ { url = "https://files.pythonhosted.org/packages/c4/28/26f6d1b4257911bdab1c66c2a80e1193131bd8c02fa9ac04453cd45233c1/pycryptodomex-3.24.0-cp37-abi3-win32.whl", hash = "sha256:fab40542a863cc142a763aa92630d613925fe3e937bea3ba5fb735e0c42d4f96", size = 1792631, upload-time = "2026-10-04T17:40:33.61Z" },
+ { url = "https://files.pythonhosted.org/packages/4d/91/fa406bbeea093b53d314dfb0fd186658a69a398b73a3a609636b8402b5c3/pycryptodomex-3.24.0-cp37-abi3-win_amd64.whl", hash = "sha256:55f22d72250d7923aac3c2442ec6a1dd8774d2efa3bdcb0f68d5e137d372268e", size = 1825514, upload-time = "2026-10-04T17:40:36.059Z" },
+ { url = "https://files.pythonhosted.org/packages/10/b0/c53c7ac97c5deb721aa4f940309802c71ff5ac2fdeac473ce96754c69e5b/pycryptodomex-3.24.0-cp37-abi3-win_arm64.whl", hash = "sha256:908f92fbc307b642b65580d0295698f423b057018d87ae43d441f1d1a00674a2", size = 1759397, upload-time = "2026-10-04T17:40:38.641Z" },
+]
+
[[package]]
name = "pydantic"
version = "2.13.5"
@@ -3698,6 +3802,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/50/7f/d39f6e64375c2ffd50ea100e3c73af79085c880c2791eb7203bc61d8913f/pypdfium2-5.13.0-py3-none-win_arm64.whl", hash = "sha256:554a0b23376460af1410e3c915906895e2dac67a086b9e6ccde0643a795d3b0d", size = 3700026, upload-time = "2026-08-13T10:58:14.206Z" },
]
+[[package]]
+name = "pyreadline3"
+version = "3.5.6"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/b6/6d/f94028646d7bbe6d9d873c47ee7c246f2d29129d253f0d96cb6fcab70733/pyreadline3-3.5.6.tar.gz", hash = "sha256:61e53218b99656091ddb077df9e71f25850e72e030b6183b39c9b7e6e4f4a9bf", size = 100368, upload-time = "2026-05-14T17:55:04.471Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f7/5e/35c856e186b74678c24927847ad9895a51f1bc02a0c6126477a6c6040064/pyreadline3-3.5.6-py3-none-any.whl", hash = "sha256:8449b734232e42a5dcd74048e39b60db2839a4c38cf3ae2bf7707d58b5389c0d", size = 85243, upload-time = "2026-05-14T17:55:03.262Z" },
+]
+
[[package]]
name = "pytest"
version = "9.1.1"
@@ -5221,6 +5334,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/41/63/23572870e01836a98346075b9e17a8bc24a6ddd9800a3204ceee58677f3c/websockets-17.1-py3-none-any.whl", hash = "sha256:f221081107b8c48184d99f7019604486376e7ef826037e70aad6b02540732c23", size = 211134, upload-time = "2026-08-26T17:25:31.397Z" },
]
+[[package]]
+name = "werkzeug"
+version = "3.1.9"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "markupsafe" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/a4/34/4dd12fc8bb7d61c91467ec3efe415ffa7d5456f799954b40c5bbaeae470e/werkzeug-3.1.9.tar.gz", hash = "sha256:55ca7c70a75689be937aa27f8ff4b018f06ff4838fc73045560bf0f5a1291060", size = 940188, upload-time = "2026-09-27T18:33:41.637Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a1/38/df03f564f43cec2684823f3cccae1a652ee7face1cbaa76fb223096e64d7/werkzeug-3.1.9-py3-none-any.whl", hash = "sha256:6392e50c78460ba618e5b21f08a71f59c99ce99cdc6cf6e3dd7e6ccca8754fab", size = 228700, upload-time = "2026-09-27T18:33:39.685Z" },
+]
+
[[package]]
name = "win-unicode-console"
version = "0.5"
diff --git a/mkdocs.yml b/mkdocs.yml
index 10d285ab0..232bbadcf 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -90,6 +90,7 @@ nav:
- Graph history: graph-history.md
- Topics: topics.md
- The graph as files: file-tree.md
+ - SMB share: smb.md
- Linked data (RDF): rdf.md
- IIIF: iiif.md
- Fedora repository: fedora.md
diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts
index c0c5fe61b..418922cf6 100644
--- a/nextjs-frontend/app/openapi-client/index.ts
+++ b/nextjs-frontend/app/openapi-client/index.ts
@@ -2594,6 +2594,10 @@ export type {
SkipTopicCandidateErrors,
SkipTopicCandidateResponse,
SkipTopicCandidateResponses,
+ SmbStatus,
+ SmbStatusData,
+ SmbStatusResponse,
+ SmbStatusResponses,
Source,
SourceCreate,
SourceCreated,
diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts
index 9fd8e329a..12cd489ec 100644
--- a/nextjs-frontend/app/openapi-client/sdk.gen.ts
+++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts
@@ -1267,6 +1267,8 @@ import type {
SkipTopicCandidateData,
SkipTopicCandidateErrors,
SkipTopicCandidateResponses,
+ SmbStatusData,
+ SmbStatusResponses,
SpeakTextData,
SpeakTextErrors,
SpeakTextResponses,
@@ -2544,6 +2546,20 @@ export class Admin {
});
}
+ /**
+ * Smb Status
+ *
+ * The file tree over SMB (Settings › SMB share): whether it's serving, to which networks, and how to connect.
+ */
+ public static smbStatus(
+ options?: Options,
+ ): RequestResult {
+ return (options?.client ?? client).get({
+ url: "/api/v1/settings/smb/status",
+ ...options,
+ });
+ }
+
/**
* Tunnel Status
*
diff --git a/nextjs-frontend/components/settings/bodies.tsx b/nextjs-frontend/components/settings/bodies.tsx
index d773c4df8..c1331c01a 100644
--- a/nextjs-frontend/components/settings/bodies.tsx
+++ b/nextjs-frontend/components/settings/bodies.tsx
@@ -388,6 +388,8 @@ export function SectionBody({ ctx }: { ctx: BodyCtx }) {
return ;
case "sensors":
return ;
+ case "smb":
+ return ;
case "uploads":
return (
<>
@@ -905,6 +907,47 @@ function FedoraBody({ ctx }: { ctx: BodyCtx }) {
);
}
+function SmbBody({ ctx }: { ctx: BodyCtx }) {
+ const client = useApiClient();
+ const status = useQuery({
+ queryKey: ["smb-status"],
+ queryFn: () => data(Admin.smbStatus({ client })),
+ refetchInterval: 10_000,
+ });
+ const s = status.data;
+ const host = typeof window === "undefined" ? "" : window.location.hostname;
+ const fill = (x: string) => x.replaceAll("", host);
+ return (
+ <>
+ {s && s.enabled && (
+
+ {s.phase === "running" ? (
+ <>
+ Open {fill(s.address)} in Finder (Go › Connect to Server) or a Linux
+ file manager, or mount it with {fill(s.mount)}. Sign in with a file
+ access key: its id is the user name, its secret the password.
+ >
+ ) : (
+ (s.error ??
+ (s.installed ? "A worker starts it within seconds." : "Fetching the SMB server, then a worker starts it."))
+ )}
+
+ )}
+
+
+
+ With Docker, the worker container publishes it on port {s?.port ?? 1445} of this machine, reachable from this
+ machine only unless LENS_BIND or{" "}
+ LENS_SHARE_BIND opens it to the network. Windows only connects to port 445:
+ set LENS_SMB_PORT=445 in .env for it.
+
+ >
+ );
+}
+
function SensorsBody({ ctx }: { ctx: BodyCtx }) {
const client = useApiClient();
const status = useQuery({
diff --git a/nextjs-frontend/components/settings/model.ts b/nextjs-frontend/components/settings/model.ts
index 691f5f44c..e86e83c6e 100644
--- a/nextjs-frontend/components/settings/model.ts
+++ b/nextjs-frontend/components/settings/model.ts
@@ -84,6 +84,7 @@ export type SectionId =
| "telemetry"
| "fedora"
| "sensors"
+ | "smb"
| "uploads"
| "storage"
| "backups"
@@ -262,6 +263,13 @@ export const SECTIONS: SectionSpec[] = [
description:
"Off unless you turn it on. An MQTT hub and a syslog listener in Lens’s workers, so routers, DNS servers and devices can send to it; and how long what they send is kept.",
},
+ {
+ id: "smb",
+ label: "SMB share",
+ backend: ["smb"],
+ description:
+ "Off unless you turn it on. The graph as folders and files over SMB, read-only, for Finder, Explorer and Linux: each person signs in with a file access key and sees what they see in the web app.",
+ },
{
id: "uploads",
label: "Uploads",
@@ -1771,6 +1779,22 @@ export const FIELDS: FieldSpec[] = [
max: 365,
hint: "The oldest go when a new one is taken. Backups you take yourself stay until you delete them",
},
+ // SMB share (opt-in)
+ {
+ section: "smb",
+ key: "enabled",
+ label: "Share the file tree over SMB",
+ kind: "switch",
+ hint: "Read-only. Off: nothing listens",
+ },
+ {
+ section: "smb",
+ key: "allowed_networks",
+ label: "Networks it’s shared with",
+ kind: "lines",
+ mono: true,
+ hint: "One per line, like 192.168.1.0/24. Machines anywhere else are turned away before they sign in",
+ },
// Sensors (opt-in)
{
section: "sensors",
@@ -2523,6 +2547,10 @@ export function crossErrors(values: Record): Record !/^[0-9a-f.:]+(\/\d{1,3})?$/i.test(x));
if (badNet) e["notifications.networks"] = `“${badNet}” isn’t a network like 192.168.1.0/24`;
+ const mNets = values["smb.allowed_networks"] as string[] | undefined;
+ const badMNet = mNets?.find((x) => !/^[0-9a-f.:]+(\/\d{1,3})?$/i.test(x));
+ if (badMNet) e["smb.allowed_networks"] = `“${badMNet}” isn’t a network like 192.168.1.0/24`;
+ else if (mNets && mNets.length === 0) e["smb.allowed_networks"] = "List at least one network";
const sNets = values["sensors.syslog_networks"] as string[] | undefined;
const badSNet = sNets?.find((x) => !/^[0-9a-f.:]+(\/\d{1,3})?$/i.test(x));
if (badSNet) e["sensors.syslog_networks"] = `“${badSNet}” isn’t a network like 192.168.1.0/24`;
diff --git a/nextjs-frontend/components/settings/settings-shell.tsx b/nextjs-frontend/components/settings/settings-shell.tsx
index 2d308770f..60557aacd 100644
--- a/nextjs-frontend/components/settings/settings-shell.tsx
+++ b/nextjs-frontend/components/settings/settings-shell.tsx
@@ -35,6 +35,7 @@ import {
MessagesSquare,
PackageCheck,
RadioTower,
+ Network,
} from "lucide-react";
import Link from "next/link";
import { useCallback, useState } from "react";
@@ -83,6 +84,7 @@ const ICON: Record = {
telemetry: Activity,
fedora: Archive,
sensors: RadioTower,
+ smb: Network,
uploads: Upload,
storage: Database,
backups: DatabaseBackup,
From 59b74306bfcdad6fd1a659c95ea516e0daac4e14 Mon Sep 17 00:00:00 2001
From: Adeel Ahmad
Date: Sat, 10 Oct 2026 20:47:21 +0000
Subject: [PATCH 2/4] feat(smb): sign in with the S3 share's keys; share list,
threat model, worker and tree tests
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01VkWr32dEQW7JiHkWwaAwSu
---
fastapi_backend/app/domain/smb_share.py | 20 ++++--
.../tests/domain/test_smb_share.py | 68 +++++++++++++++++++
threat-model.json | 21 +++++-
threat-model.md | 4 ++
threat-model.yaml | 22 +++++-
5 files changed, 129 insertions(+), 6 deletions(-)
diff --git a/fastapi_backend/app/domain/smb_share.py b/fastapi_backend/app/domain/smb_share.py
index f4e08c076..4306b515e 100644
--- a/fastapi_backend/app/domain/smb_share.py
+++ b/fastapi_backend/app/domain/smb_share.py
@@ -63,7 +63,7 @@ class Entry:
class Keys:
"""File access keys, looked up when someone signs in and again every KEY_SECONDS while they stay connected.
- `lookup(key_id)` answers {account, secret} or None (file_tree.lookup_key by default)."""
+ `lookup(key_id)` answers {account, secret} or None (s3.lookup_key: the S3 share's keys)."""
def __init__(self, lookup, touch=None):
self.lookup, self.touch = lookup, touch or (lambda key_id: None)
@@ -84,6 +84,11 @@ def get(self, key_id):
row = None
with self.lock:
self.cache[key_id] = (time.monotonic(), row)
+ if row is not None:
+ try:
+ self.touch(key_id) # last used: at sign-in, then every KEY_SECONDS while connected
+ except Exception: # noqa: BLE001
+ pass
return row
@@ -191,7 +196,12 @@ def read(self, fd, n):
f = self._fd(fd)
if f[0] is None:
raise IsADirectoryError(errno.EISDIR, "is a folder")
- data = f[0].read(f[2], int(n)) or b""
+ try:
+ data = f[0].read(f[2], int(n)) or b""
+ except OSError:
+ raise
+ except Exception as e: # a locked vault, a storage connection that's away: the client sees "access denied"
+ raise PermissionError(errno.EACCES, f"can't be read now: {type(e).__name__}") from None
f[2] += len(data)
return data
@@ -466,6 +476,8 @@ def processRequest(self, conn_id, data): # noqa: N802
self.extras = [smbserver.SRVSServer(), smbserver.WKSTServer()] # share lists for Explorer and Finder
for x in self.extras:
x.daemon = True
+ self.extras[0].setServerConfig(cfg) # the shares it lists
+ self.extras[0].processConfigFile()
self.server.registerNamedPipe("srvsvc", ("127.0.0.1", self.extras[0].getListenPort()))
self.server.registerNamedPipe("wkssvc", ("127.0.0.1", self.extras[1].getListenPort()))
self.thread = None
@@ -503,9 +515,9 @@ def conf(cfg):
def _keys(db, cfg_fn):
- from . import file_tree
+ from . import s3
- return Keys(lambda key_id: file_tree.lookup_key(db, cfg_fn(), key_id), lambda key_id: file_tree.touch_key(db, key_id))
+ return Keys(lambda key_id: s3.lookup_key(db, cfg_fn(), key_id), lambda key_id: s3.touch(db, key_id))
class Runner:
diff --git a/fastapi_backend/tests/domain/test_smb_share.py b/fastapi_backend/tests/domain/test_smb_share.py
index dd7c0dd7e..9c4802a0c 100644
--- a/fastapi_backend/tests/domain/test_smb_share.py
+++ b/fastapi_backend/tests/domain/test_smb_share.py
@@ -166,3 +166,71 @@ def chunks(start, end):
def test_nt_hash_matches_the_known_vector():
assert smb_share.nt_hash("password").hex() == "8846f7eaee8fb117ad06bdd830b7586c"
+
+
+def test_serves_the_real_file_tree_per_person(db, cfg, folder):
+ """With filetree.py behind it: an admin sees every namespace, a viewer of 'pods' only that one, an outsider none."""
+ from tests.helpers import make_user, seed
+
+ a, _, _ = seed(db, cfg, folder)
+ admin = make_user(db, "admin@x.io", "admin password 1", admin=True)
+ viewer = make_user(db, "vi@x.io", "viewer password 1", roles={"pods": "viewer"})
+ outsider = make_user(db, "out@x.io", "outsider password 1")
+ keys = {"lkadmin": admin, "lkviewer": viewer, "lkout": outsider}
+ k = smb_share.Keys(lambda kid: {"account": keys[kid], "secret": f"{kid}-secret"} if kid in keys else None)
+ s = smb_share.Server("127.0.0.1", 0, smb_share.FileTree(db, lambda: cfg), k, ["127.0.0.0/8"]).start()
+ try:
+
+ def names(user, path="*"):
+ c = connect(s.port, user, f"{user}-secret")
+ return sorted(f.get_longname() for f in c.listPath(smb_share.SHARE, path) if f.get_longname() not in (".", ".."))
+
+ assert names("lkadmin") == ["calls", "pods"]
+ assert names("lkviewer") == ["pods"]
+ assert names("lkout") == []
+ files = names("lkviewer", "pods\\Collections\\General\\*")
+ assert f"ep1 [{a}].txt" in files
+ out = io.BytesIO()
+ connect(s.port, "lkviewer", "lkviewer-secret").getFile(smb_share.SHARE, f"pods\\Collections\\General\\ep1 [{a}].txt", out.write)
+ assert out.getvalue().decode().startswith("Alice: Welcome back.")
+ with pytest.raises(SessionError):
+ connect(s.port, "lkviewer", "lkviewer-secret").listPath(smb_share.SHARE, "calls\\*")
+ finally:
+ s.stop()
+
+
+def test_the_worker_follows_the_settings(db, cfg):
+ """Off: nothing listens. On: it serves, and says so in status. Off again: it stops and ends open sessions."""
+ live = {**cfg, "smb": {**cfg.get("smb", {}), "enabled": False, "bind": "127.0.0.1", "port": 0}}
+ r = smb_share.Runner(db, lambda: live, "w1", tree=FakeTree(), keys=smb_share.Keys(lambda k: KEYS.get(k)))
+ r.apply()
+ r.heartbeat()
+ assert r.server is None and smb_share.status(db, live)["phase"] == "off"
+ live["smb"]["enabled"] = True
+ r.apply()
+ r.heartbeat()
+ st = smb_share.status(db, live)
+ assert r.server is not None and st["phase"] == "running" and st["process"] == "w1" and st["share"] == "LENS"
+ c = connect(r.server.port, "lk_ada", "ada-secret-1")
+ assert [f.get_longname() for f in c.listPath(smb_share.SHARE, "*") if f.get_longname() not in (".", "..")] == ["Pods"]
+ live["smb"]["allowed_networks"] = ["10.0.0.0/8"] # applies to new connections without a restart
+ r.apply()
+ with pytest.raises(Exception): # noqa: B017
+ connect(r.server.port, "lk_ada", "ada-secret-1")
+ live["smb"]["enabled"] = False
+ r.apply()
+ r.heartbeat()
+ assert r.server is None and smb_share.status(db, live)["phase"] == "off"
+ with pytest.raises(Exception): # noqa: B017 - the open session was ended
+ c.listPath(smb_share.SHARE, "*")
+
+
+def test_smb_settings_are_checked():
+ from app.domain import settings
+
+ assert settings._smb_setting("allowed_networks", [" 192.168.1.7/24 ", "::1"]) == ["192.168.1.0/24", "::1/128"]
+ for bad in ("nope", ["not a network"]):
+ with pytest.raises(ValueError):
+ settings._smb_setting("allowed_networks", bad)
+ with pytest.raises(ValueError):
+ settings._smb_setting("enabled", "yes")
diff --git a/threat-model.json b/threat-model.json
index 5a165bd1c..4278a0123 100644
--- a/threat-model.json
+++ b/threat-model.json
@@ -123,7 +123,8 @@
{
"name": "optional",
"entry_points": [
- "MQTT 1883, syslog 5514, POST /sensors/push/{token}/{stream}"
+ "MQTT 1883, syslog 5514, POST /sensors/push/{token}/{stream}",
+ "SMB share (port 1445 on the host, 4445 in the worker)"
],
"touches": [
"network",
@@ -451,6 +452,15 @@
"provenance": "documented",
"source": "docs/sensors.md \"Sensors are off until an admin turns them on\""
},
+ {
+ "entry_point": "SMB share (port 1445 on the host, 4445 in the worker)",
+ "parameter": "SMB2 requests, NTLM sign-in with a file access key, client address",
+ "attacker_controllable": "yes",
+ "component": "optional",
+ "caller_must_enforce": "admin enables; operator firewalls",
+ "provenance": "documented",
+ "source": "docs/smb.md \"What keeps it safe\""
+ },
{
"entry_point": ".env, archive.yaml, LENS_*, ARCHIVE_SECRET_KEY, RCLONE_BINARY",
"parameter": "process configuration",
@@ -998,6 +1008,14 @@
"provenance": "documented",
"source": "docs/sensors.md \"Sensors are off until an admin turns them on\""
},
+ {
+ "property": "P-SMB",
+ "violation_symptom": "info-leak",
+ "severity_tier": "security",
+ "conditions": "the SMB share is off until an admin turns it on; read-only; per-person file access keys and views; no guests or SMB1; a random NTLM challenge per connection; allowed networks only",
+ "provenance": "documented",
+ "source": "docs/smb.md \"What keeps it safe\""
+ },
{
"property": "P-CHILD-SECRETS",
"violation_symptom": "info-leak",
@@ -1380,6 +1398,7 @@
"After a password change or suspected theft, revoke API tokens and app grants, or disable the account",
"List private networks in documents.web_networks or notifications.networks only on purpose",
"When sensors are on, firewall ports 1883 and 5514 or bind them to a private address",
+ "When the SMB share is on, list only your own networks, keep its port off the internet, and revoke file access keys you no longer use",
"Give the chat-room bridge its own low-role account",
"Run workers only on trusted hosts; they hold the DB credential",
"Pick model and speech servers you trust with transcripts and audio",
diff --git a/threat-model.md b/threat-model.md
index 5a1bc3ece..1113c025d 100644
--- a/threat-model.md
+++ b/threat-model.md
@@ -282,6 +282,7 @@ classified by gate only *(inferred, Q8)*; unread modules are listed in Q34.
| extensions (prompt, graph and `http` tools, hooks), custom nodes including `template` nodes (Q23) | tool spec, graph JSON, template text | yes, any writer for their own; sharing is gated | callback/code (declarative) | person enables only extensions they trust | *(documented, docs/assistant.md "other people's run only when an admin shared them")* |
| Python code tools, shipped and admin-created templates, workflows, pipelines, routines | Python, Jinja source, regexes | admin only | callback/code | admin is trusted | *(maintainer, 2026-10)* |
| MQTT 1883, syslog 5514, `POST /sensors/push/{token}/{stream}` | payloads, hub logins, token in the path | yes, once enabled | data, size/rate, x-credential | admin enables; operator firewalls | *(documented, docs/sensors.md "Sensors are off until an admin turns them on")* |
+| SMB share (port 1445 on the host, 4445 in the worker) | SMB2 requests, NTLM sign-in with a file access key, client address | yes, once enabled, from `smb.allowed_networks` | data, x-credential, x-network-source | admin enables; operator firewalls | *(documented, docs/smb.md "What keeps it safe")* |
| `.env`, `archive.yaml`, `LENS_*`, `ARCHIVE_SECRET_KEY`, `RCLONE_BINARY` | process configuration | no (operator) | x-env-config | keep unreadable to others | *(maintainer, 2026-10)* |
| workers and DB peers | DB credential, shared database rows | no (trusted peer) | x-peer | run peers on trusted hosts | *(inferred, Q9)* |
@@ -384,6 +385,7 @@ Every row is claimed, disclaimed, N/A with a reason, or unresolved. Family short
| Optional | Atomicity, recursion, serialization | N/A — flat, append-only readings stored as data | no multi-step state, nesting or object reconstruction | none | *(inferred, Q34)* |
| Optional | Callback / collaborator execution | claimed | tunnel token and llama-server key stay off command lines | P-CHILD-SECRETS | *(documented, docs/remote-access.md "in its environment, not on its command line")* |
| Optional | Reference lifecycle | claimed | each service off until an admin turns it on | P-SENSORS | *(documented, docs/sensors.md "Sensors are off until an admin turns them on")* |
+| Optional | Confidentiality | claimed | SMB share off until an admin turns it on; read-only; each key sees its owner's view; allowed networks only | P-SMB | *(documented, docs/smb.md "What keeps it safe")* |
| Optional | Concurrency; resource cost | disclaimed | MQTT and syslog connection counts, one thread per connection | N-VOLUME | *(documented, SECURITY.md "denial of service by sheer volume")* |
## 1.8 Assumptions and guarantees about outputs
@@ -499,6 +501,7 @@ Paths in the Voided by column are relative to `fastapi_backend/app/`. Searches c
| P-TELEMETRY | Telemetry is off unless turned on, has no built-in destination, and never sends content, names, addresses or error messages. | info-leak | security-critical | *(documented, docs/telemetry.md "Never sent")* | Voided by: none identified (not required for this symptom; no exhaustive search) |
| P-MODEL-CHECKSUM | Catalog GGUF models are pinned to a revision and checked against their SHA-256. | integrity-bypass | security-critical | *(documented, docs/local-models.md "checked against their SHA-256")* | Voided by: `hf:` references have no pin or hash — `domain/local_llm.py:138-139`. |
| P-SENSORS | Sensors are off until an admin enables them. MQTT needs a hub login unless `mqtt_anonymous` is on. Syslog hears only listed networks. | integrity-bypass | security-critical | *(documented, docs/sensors.md "Sensors are off until an admin turns them on")* | Voided by: `sensors.mqtt_anonymous` — `domain/sensors.py:984`; `sensors.syslog_networks`, `sensors.bind`. |
+| P-SMB | The SMB share is off until an admin turns it on. It is read-only, signs people in with their own file access keys and shows each only what they see in the web app, refuses guests and SMB1 sessions, gives every connection its own NTLM challenge, and closes connections from outside `smb.allowed_networks` before reading a byte. | info-leak | security-critical | *(documented, docs/smb.md "What keeps it safe")* | Voided by: `smb.allowed_networks` set wide; SMB 2.0 has no encryption on the wire, so a key's NTLM exchange and the files read can be watched on the network — `domain/smb_share.py`. |
| P-CHILD-SECRETS | The tunnel token reaches cloudflared in its environment, not its command line; llama-server gets its own random API key. | info-leak | correctness-only | *(documented, docs/remote-access.md "in its environment, not on its command line")* | Voided by: none identified (not required for this symptom; no exhaustive search) |
| P-REMOTE-NAMES | An IMAP message is named by mailbox validity and uid, so a rebuilt mailbox never serves another message under an old name. | wrong-output | correctness-only | *(documented, docs/processing.md "an old one never reads another message")* | Voided by: none identified (not required for this symptom; no exhaustive search) |
| P-NOTIFY | Each notification event is claimed once across processes and retried with backoff. | wrong-output | correctness-only | *(documented, docs/notifications.md "claimed once")* | Voided by: none identified (not required for this symptom; no exhaustive search) |
@@ -599,6 +602,7 @@ The operator (and, for the last rows, integrators that consume Lens output) must
| After a password change or suspected theft, revoke API tokens and app grants, or disable the account | N-REVOKE-TOKENS | *(inferred, Q3)* |
| List private networks in `documents.web_networks` or `notifications.networks` only on purpose | P-SSRF-GUARD, P-ADMIN-GUARD | *(documented, docs/configuration.md "loopback and cloud metadata addresses stay out")* |
| When sensors are on, firewall ports 1883 and 5514 or bind them to a private address | P-SENSORS, N-MQTT-SUBSCRIBE | *(documented, docs/sensors.md "Ways in")* |
+| When the SMB share is on, list only your own networks, keep its port off the internet, and revoke file access keys you no longer use | P-SMB | *(documented, docs/smb.md "What keeps it safe")* |
| Give the chat-room bridge its own low-role account | N-BRIDGE | *(documented, docs/chat-rooms.md "it reads only what that account can read")* |
| Run workers only on trusted hosts; they hold the DB credential | N-APP-LAYER | *(inferred, Q9)* |
| Pick model and speech servers you trust with transcripts and audio | §1.8 prompts | *(maintainer, 2026-10)* |
diff --git a/threat-model.yaml b/threat-model.yaml
index a80ae5597..f81a97af6 100644
--- a/threat-model.yaml
+++ b/threat-model.yaml
@@ -2,7 +2,7 @@
# Authority order: prose > yaml > json. Regenerate whenever the prose changes.
schema: threat-model-sidecar/v2
project: lens
-prose_version: "threat-model.md@sha256:42d9bc92f48ce93ea2d58412a61b086dde8ab4522af95f628304d1b33919832f"
+prose_version: "threat-model.md@sha256:94906ac9249700e5601f897fc83225e45c0620e1f2e5ef66359163344eb6f8e0"
model_status: under-review
triage_policy: strict
confidence: {documented: 201, maintainer: 46, inferred: 91, assumption: 8}
@@ -389,6 +389,16 @@ entry_points:
obligation_id: enable-and-firewall-sensors
caller_must_enforce: "admin enables; operator firewalls"
provenance: {kind: documented, source: 'docs/sensors.md "Sensors are off until an admin turns them on"'}
+ - id: "SMB share (port 1445 on the host, 4445 in the worker)"
+ component: optional
+ parameters:
+ - name: "SMB2 requests, NTLM sign-in with a file access key, client address"
+ attacker_controllable: true
+ x-condition: "once enabled, from smb.allowed_networks"
+ control_kinds: [data, x-credential, x-network-source]
+ obligation_id: enable-and-limit-smb
+ caller_must_enforce: "admin enables; operator firewalls"
+ provenance: {kind: documented, source: 'docs/smb.md "What keeps it safe"'}
- id: ".env, archive.yaml, LENS_*, ARCHIVE_SECRET_KEY, RCLONE_BINARY"
component: outbound
parameters:
@@ -523,6 +533,7 @@ contract_dimensions:
- {component: optional, dimension: serialization-reconstruction, status: not-applicable, conditions: "readings stored as data; no object reconstruction", provenance: {kind: inferred, question_id: Q34}}
- {component: optional, dimension: callback-execution, status: claimed, property_id: P-CHILD-SECRETS, conditions: "tunnel token and llama-server key stay off command lines", provenance: {kind: documented, source: 'docs/remote-access.md "in its environment, not on its command line"'}}
- {component: optional, dimension: reference-lifecycle, status: claimed, property_id: P-SENSORS, conditions: "each service off until an admin turns it on", provenance: {kind: documented, source: 'docs/sensors.md "Sensors are off until an admin turns them on"'}}
+ - {component: optional, dimension: confidentiality, status: claimed, property_id: P-SMB, conditions: "SMB share off until an admin turns it on; read-only; each key sees its owner's view; allowed networks only", provenance: {kind: documented, source: 'docs/smb.md "What keeps it safe"'}}
- {component: optional, dimension: concurrency-reentrancy, status: disclaimed, property_id: N-VOLUME, conditions: "MQTT and syslog connection counts, one thread per connection", provenance: {kind: documented, source: 'SECURITY.md "denial of service by sheer volume"'}}
- {component: optional, dimension: resource-complexity, status: disclaimed, property_id: N-VOLUME, conditions: "MQTT and syslog connection counts, one thread per connection", provenance: {kind: documented, source: 'SECURITY.md "denial of service by sheer volume"'}}
@@ -1384,6 +1395,14 @@ properties_claimed:
violation_symptoms: [integrity-bypass]
x-voided-by: "sensors.mqtt_anonymous (domain/sensors.py:984); sensors.syslog_networks, sensors.bind"
provenance: {kind: documented, source: 'docs/sensors.md "Sensors are off until an admin turns them on"'}
+ - id: P-SMB
+ kind: confidentiality
+ components: [optional]
+ tier: security-critical
+ conditions: "the SMB share is off until an admin turns it on; read-only; per-person file access keys and views; no guests or SMB1; a random NTLM challenge per connection; allowed networks only"
+ violation_symptoms: [info-leak]
+ x-voided-by: "smb.allowed_networks set wide; SMB 2.0 has no encryption on the wire (domain/smb_share.py)"
+ provenance: {kind: documented, source: 'docs/smb.md "What keeps it safe"'}
- id: P-CHILD-SECRETS
kind: confidentiality
components: [optional]
@@ -1516,6 +1535,7 @@ downstream_responsibilities:
- {id: dr-revoke-after-password-change, component: identity, statement: "After a password change or suspected theft, revoke API tokens and app grants, or disable the account", enforces: [N-REVOKE-TOKENS], provenance: {kind: inferred, question_id: Q3}}
- {id: dr-private-networks-on-purpose, component: outbound, statement: "List private networks in documents.web_networks or notifications.networks only on purpose", enforces: [P-SSRF-GUARD, P-ADMIN-GUARD], provenance: {kind: documented, source: 'docs/configuration.md "loopback and cloud metadata addresses stay out"'}}
- {id: dr-firewall-sensor-ports, component: optional, statement: "When sensors are on, firewall ports 1883 and 5514 or bind them to a private address", enforces: [P-SENSORS, N-MQTT-SUBSCRIBE, enable-and-firewall-sensors], provenance: {kind: documented, source: 'docs/sensors.md "Ways in"'}}
+ - {id: dr-limit-smb-share, component: optional, statement: "When the SMB share is on, list only your own networks, keep its port off the internet, and revoke file access keys you no longer use", enforces: [P-SMB, enable-and-limit-smb], provenance: {kind: documented, source: 'docs/smb.md "What keeps it safe"'}}
- {id: dr-bridge-own-account, component: outbound, statement: "Give the chat-room bridge its own low-role account", enforces: [N-BRIDGE], provenance: {kind: documented, source: 'docs/chat-rooms.md "it reads only what that account can read"'}}
- {id: dr-trusted-worker-hosts, component: authz, statement: "Run workers only on trusted hosts; they hold the DB credential", enforces: [N-APP-LAYER, trusted-peer-hosts], provenance: {kind: inferred, question_id: Q9}}
- {id: dr-trusted-model-servers, component: assistant, statement: "Pick model and speech servers you trust with transcripts and audio", enforces: [], x-protects: "§1.8 prompts", provenance: {kind: maintainer, date: "2026-10"}}
From 52c29fc5c8e5997b566129f5e215db93863a6059 Mon Sep 17 00:00:00 2001
From: Adeel Ahmad
Date: Sat, 10 Oct 2026 20:50:47 +0000
Subject: [PATCH 3/4] feat(smb): pick the published port with the install line,
not by editing .env
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01VkWr32dEQW7JiHkWwaAwSu
---
docker-compose.prod.yml | 2 +-
docs/smb.md | 6 +++---
install.sh | 2 ++
nextjs-frontend/components/settings/bodies.tsx | 2 +-
4 files changed, 7 insertions(+), 5 deletions(-)
diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml
index b6fbcbba7..2f3125218 100644
--- a/docker-compose.prod.yml
+++ b/docker-compose.prod.yml
@@ -109,7 +109,7 @@ services:
- "${LENS_SENSOR_BIND:-${LENS_BIND:-127.0.0.1}}:${LENS_SYSLOG_PORT:-5514}:5514/tcp"
# the file tree over SMB (docs/smb.md), served only once it's turned on in Settings → SMB share, and then only
# to the networks allowed there. 1445 on this machine so an SMB server the host runs on 445 is never in the way
- # (Windows only connects to 445: set LENS_SMB_PORT=445 for it).
+ # (Windows only connects to 445: install with LENS_SMB_PORT=445 for it; install.sh keeps it).
- "${LENS_SHARE_BIND:-${LENS_BIND:-127.0.0.1}}:${LENS_SMB_PORT:-1445}:4445"
healthcheck:
disable: true
diff --git a/docs/smb.md b/docs/smb.md
index a14ea9a29..ff078c8d2 100644
--- a/docs/smb.md
+++ b/docs/smb.md
@@ -20,7 +20,7 @@ within 30 seconds.
| --- | --- |
| macOS | Finder → Go → Connect to Server → `smb://:1445/LENS` |
| Linux | `sudo mount -t cifs -o port=1445,username=,ro,vers=2.0 ///LENS /mnt/lens`, or `smb://:1445/LENS` in Files |
-| Windows | Explorer only connects to port 445: set `LENS_SMB_PORT=445` in `.env` first, then open `\\\LENS` |
+| Windows | Explorer only connects to port 445: install with `LENS_SMB_PORT=445` in front of the install line (kept for later upgrades), then open `\\\LENS` |
| Setting | Default | What it does |
| --- | --- | --- |
@@ -28,8 +28,8 @@ within 30 seconds.
| `smb.allowed_networks` | private networks (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `127.0.0.0/8`, `100.64.0.0/10` for Tailscale, `fc00::/7`, `::1/128`) | Machines anywhere else are turned away before they can sign in; changes apply without a restart |
| `smb.bind`, `smb.port` | `127.0.0.1`, `4445` | Startup settings only: where the worker listens (`LENS_SMB_LISTEN`, `LENS_SMB_LISTEN_PORT`). In Docker it listens on `0.0.0.0:4445` inside the worker container |
-With Docker, the worker container publishes the share on port **1445** of the host (`LENS_SMB_PORT` in `.env` picks
-another), so an SMB server the host already runs on 445 is never in the way. Like the web app, it's reachable from
+With Docker, the worker container publishes the share on port **1445** of the host (`LENS_SMB_PORT=` in front of
+the install line picks another), so an SMB server the host already runs on 445 is never in the way. Like the web app, it's reachable from
this machine only unless `LENS_BIND=0.0.0.0` (what `install.sh` sets on a server); `LENS_SHARE_BIND` opens the file
shares on their own while the web app stays local.
diff --git a/install.sh b/install.sh
index f1425683f..0ba46a64e 100755
--- a/install.sh
+++ b/install.sh
@@ -331,6 +331,8 @@ setenv LENS_PORT "$PORT"
setenv FRONTEND_URL "http://$host:$PORT"
setenv LENS_REPO "$REPO"
setenv LENS_DIR "$DIR"
+# the SMB share's port on this machine (docs/smb.md), when the install line names one: kept for later runs
+case "${LENS_SMB_PORT:-}" in '' | *[!0-9]*) ;; *) setenv LENS_SMB_PORT "$LENS_SMB_PORT" ;; esac
# from the web installer (docs/configuration.md): the first namespace, and settings Lens saves once at its first start
for k in LENS_NAMESPACE LENS_SETUP_SETTINGS; do
eval "v=\${$k:-}"
diff --git a/nextjs-frontend/components/settings/bodies.tsx b/nextjs-frontend/components/settings/bodies.tsx
index c1331c01a..81afc2a80 100644
--- a/nextjs-frontend/components/settings/bodies.tsx
+++ b/nextjs-frontend/components/settings/bodies.tsx
@@ -942,7 +942,7 @@ function SmbBody({ ctx }: { ctx: BodyCtx }) {
With Docker, the worker container publishes it on port {s?.port ?? 1445} of this machine, reachable from this
machine only unless LENS_BIND or{" "}
LENS_SHARE_BIND opens it to the network. Windows only connects to port 445:
- set LENS_SMB_PORT=445 in .env for it.
+ install with LENS_SMB_PORT=445 in front of the install line for it.
>
);
From 83c76bf55cac23dbab996a0fab1ed3b2f520bc3e Mon Sep 17 00:00:00 2001
From: Adeel Ahmad
Date: Sat, 10 Oct 2026 22:02:42 +0000
Subject: [PATCH 4/4] chore(smb): regenerate the API client for the SMB share's
status
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01VkWr32dEQW7JiHkWwaAwSu
---
.../app/openapi-client/types.gen.ts | 75 ++++++++++++
nextjs-frontend/openapi.json | 108 ++++++++++++++++++
2 files changed, 183 insertions(+)
diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts
index cd5e91ce6..578de2bac 100644
--- a/nextjs-frontend/app/openapi-client/types.gen.ts
+++ b/nextjs-frontend/app/openapi-client/types.gen.ts
@@ -15103,6 +15103,65 @@ export type SimilarTopic = {
[key: string]: unknown;
};
+/**
+ * SmbStatus
+ */
+export type SmbStatus = {
+ /**
+ * Enabled
+ */
+ enabled: boolean;
+ /**
+ * Phase
+ */
+ phase: "off" | "starting" | "running" | "error";
+ /**
+ * Port
+ *
+ * the port clients connect to (where Docker publishes it)
+ */
+ port: number;
+ /**
+ * Share
+ *
+ * the share's name
+ */
+ share: string;
+ /**
+ * Allowed Networks
+ */
+ allowed_networks: Array;
+ /**
+ * Error
+ */
+ error?: string | null;
+ /**
+ * Process
+ *
+ * the worker serving it
+ */
+ process?: string | null;
+ /**
+ * Installed
+ *
+ * whether the SMB server (impacket) is installed here; it's fetched when the share is turned on
+ */
+ installed: boolean;
+ /**
+ * Address
+ *
+ * the address Finder and Linux file managers open (the machine's name filled in by the caller)
+ */
+ address: string;
+ /**
+ * Mount
+ *
+ * the command that mounts it on Linux
+ */
+ mount: string;
+ [key: string]: unknown;
+};
+
/**
* Source
*/
@@ -20010,6 +20069,22 @@ export type RemoveLocalModelResponses = {
export type RemoveLocalModelResponse = RemoveLocalModelResponses[keyof RemoveLocalModelResponses];
+export type SmbStatusData = {
+ body?: never;
+ path?: never;
+ query?: never;
+ url: "/api/v1/settings/smb/status";
+};
+
+export type SmbStatusResponses = {
+ /**
+ * Successful Response
+ */
+ 200: SmbStatus;
+};
+
+export type SmbStatusResponse = SmbStatusResponses[keyof SmbStatusResponses];
+
export type TunnelStatusData = {
body?: never;
path?: never;
diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json
index 0504d1752..6849dce39 100644
--- a/nextjs-frontend/openapi.json
+++ b/nextjs-frontend/openapi.json
@@ -2444,6 +2444,28 @@
}
}
},
+ "/api/v1/settings/smb/status": {
+ "get": {
+ "tags": [
+ "admin"
+ ],
+ "summary": "Smb Status",
+ "description": "The file tree over SMB (Settings \u203a SMB share): whether it's serving, to which networks, and how to connect.",
+ "operationId": "smb_status",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SmbStatus"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/v1/settings/tunnel/status": {
"get": {
"tags": [
@@ -51805,6 +51827,92 @@
],
"title": "SimilarTopic"
},
+ "SmbStatus": {
+ "properties": {
+ "enabled": {
+ "type": "boolean",
+ "title": "Enabled"
+ },
+ "phase": {
+ "type": "string",
+ "enum": [
+ "off",
+ "starting",
+ "running",
+ "error"
+ ],
+ "title": "Phase"
+ },
+ "port": {
+ "type": "integer",
+ "title": "Port",
+ "description": "the port clients connect to (where Docker publishes it)"
+ },
+ "share": {
+ "type": "string",
+ "title": "Share",
+ "description": "the share's name"
+ },
+ "allowed_networks": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Allowed Networks"
+ },
+ "error": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Error"
+ },
+ "process": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Process",
+ "description": "the worker serving it"
+ },
+ "installed": {
+ "type": "boolean",
+ "title": "Installed",
+ "description": "whether the SMB server (impacket) is installed here; it's fetched when the share is turned on"
+ },
+ "address": {
+ "type": "string",
+ "title": "Address",
+ "description": "the address Finder and Linux file managers open (the machine's name filled in by the caller)"
+ },
+ "mount": {
+ "type": "string",
+ "title": "Mount",
+ "description": "the command that mounts it on Linux"
+ }
+ },
+ "additionalProperties": true,
+ "type": "object",
+ "required": [
+ "enabled",
+ "phase",
+ "port",
+ "share",
+ "allowed_networks",
+ "installed",
+ "address",
+ "mount"
+ ],
+ "title": "SmbStatus"
+ },
"Source": {
"properties": {
"id": {