aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-node/src/meshbay_node/config.py
blob: e4444d3368e16ff78c03792fbef015699df99aa3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""
MeshBay Node configuration.

Config file: ~/.config/meshbay/node.toml
All values have sensible defaults and can be overridden by env vars
prefixed with MESHBAY_ (e.g. MESHBAY_HUB_URL).
"""

import logging
import os
from dataclasses import dataclass, field
from pathlib import Path

try:
    import tomllib   # Python 3.11+
except ImportError:
    import tomli as tomllib   # type: ignore[no-redef]

log = logging.getLogger(__name__)

DEFAULT_CONFIG_PATH = Path.home() / ".config" / "meshbay" / "node.toml"

EXAMPLE_CONFIG = """\
# MeshBay Node configuration — multi-group example
# See: https://meshbay.org/docs/node-config

[hub]
url      = "https://meshbay.org"
username = "myusername"

[node]
quic_port = 19010  # QUIC (MNP) — LAN, port-forwarded, hub-less direct access
ui_port  = 18000   # local admin UI (127.0.0.1 only)

# One-time codes. An invitation waits for someone to read their messages; an
# operator pairing code is typed during the SSH session that printed it.
invite_ttl_hours = 168   # 7 days
pair_ttl_hours   = 24

# Browser and native clients reach this node over WebRTC DataChannel via hub
# signaling — no inbound port to open. QUIC is the optional direct path.

# Multiple groups — each with its own directory
[[groups]]
id          = ""    # set after joining
name        = "My Media"
shared_dir  = "/home/user/Media"
quic_port   = 19010

[[groups]]
id          = ""
name        = "Public Archive"
shared_dir  = "/home/user/Archive"
quic_port   = 19012
visibility  = "public"       # discoverable on the hub
# join_policy = "open"       # anyone the hub says is a member gets the group key,
                             # with no pairing code. Only for groups where that is
                             # genuinely intended: it means the hub can join too.

[keystore]
# unlock_file = "~/.config/meshbay/unlock.key"
# or set MESHBAY_UNLOCK_KEY env var

# Operator authority is not configured here. Run `meshbay-node operator pair` and
# enter the code in your browser: the node pins that browser's key, and invites
# and file deletion are signed with it.
"""


@dataclass
class HubConfig:
    url:      str = "https://meshbay.org"
    username: str = ""


@dataclass
class NodeConfig:
    quic_port:  int = 19010
    ui_port:    int = 18000
    # How long a one-time code stays usable. Invitations travel through a human
    # conversation and are answered days later; operator pairing happens during
    # the SSH session that printed it.
    invite_ttl_hours: int = 168   # 7 days
    pair_ttl_hours:   int = 24


@dataclass
class GroupConfig:
    id:         str = ""
    name:       str = ""
    shared_dir: str = ""
    visibility: str = "private"   # public|private — discoverability, not admission
    # Admission. "invite" (default) means a newcomer needs a one-time pairing code
    # before the node wraps the group key for them; "open" means the node pins
    # whoever turns up first (TOFU) and serves them.
    #
    # Deliberately read from THIS file and never from the hub: a hub that could
    # declare a group open would walk into any group it liked. Being findable
    # (`visibility`) and being open (`join_policy`) are different questions.
    join_policy: str = "invite"   # invite|open
    quic_port:  int = 19010       # QUIC MNP port


@dataclass
class KeystoreConfig:
    path:        Path = field(default_factory=lambda: DEFAULT_CONFIG_PATH.parent / "keystore.enc")
    unlock_file: Path | None = None


@dataclass
class Config:
    hub:      HubConfig      = field(default_factory=HubConfig)
    node:     NodeConfig     = field(default_factory=NodeConfig)
    groups:   list[GroupConfig] = field(default_factory=list)
    keystore: KeystoreConfig = field(default_factory=KeystoreConfig)
    data_dir: Path = field(default_factory=lambda: Path.home() / ".local" / "share" / "meshbay")

    # Back-compat: single-group access
    @property
    def group(self) -> GroupConfig:
        return self.groups[0] if self.groups else GroupConfig()


def load_config(path: Path = DEFAULT_CONFIG_PATH) -> Config:
    """
    Load config from TOML file. Supports both single [group] and
    multiple [[groups]] sections. Env vars override file values.
    """
    cfg = Config()

    if path.exists():
        raw = tomllib.loads(path.read_text())

        hub = raw.get("hub", {})
        cfg.hub.url      = hub.get("url",      cfg.hub.url)
        cfg.hub.username = hub.get("username", cfg.hub.username)

        nd = raw.get("node", {})
        # `port` (TCP+TLS) and `http_port` no longer exist — both listeners were removed
        # in Phase 11.5 (findings C1, C6). Regenerate node.toml with `meshbay-node init`.
        cfg.node.quic_port = nd.get("quic_port", cfg.node.quic_port)
        cfg.node.ui_port   = nd.get("ui_port",   cfg.node.ui_port)
        cfg.node.invite_ttl_hours = int(
            nd.get("invite_ttl_hours", cfg.node.invite_ttl_hours))
        cfg.node.pair_ttl_hours = int(
            nd.get("pair_ttl_hours", cfg.node.pair_ttl_hours))

        # Multi-group: [[groups]] array
        if "groups" in raw:
            for g in raw["groups"]:
                cfg.groups.append(GroupConfig(
                    id=g.get("id", ""),
                    name=g.get("name", ""),
                    shared_dir=g.get("shared_dir", ""),
                    visibility=g.get("visibility", "private"),
                    join_policy=g.get("join_policy", "invite"),
                    quic_port=g.get("quic_port", cfg.node.quic_port),
                ))
        # Back-compat: single [group] section
        elif "group" in raw:
            grp = raw["group"]
            cfg.groups.append(GroupConfig(
                id=grp.get("id", ""),
                name=grp.get("name", ""),
            ))

        if "data_dir" in raw:
            cfg.data_dir = Path(raw["data_dir"]).expanduser().resolve()

        if "admin_pk_ed25519" in raw:
            # Removed, not merely unused: a key named here granted operator
            # authority, and dropping it silently would refuse invites and file
            # deletion with a signature error that looks like something else.
            log.warning(
                "admin_pk_ed25519 in %s is ignored — operator authority now comes "
                "from the roster. Run `meshbay-node operator pair` and delete the "
                "line.", path)

        ks = raw.get("keystore", {})
        if "path" in ks:
            cfg.keystore.path = Path(ks["path"]).expanduser()
        if "unlock_file" in ks:
            cfg.keystore.unlock_file = Path(ks["unlock_file"]).expanduser()

    # Env var overrides
    if url  := os.environ.get("MESHBAY_HUB_URL"):
        cfg.hub.url = url
    if user := os.environ.get("MESHBAY_USERNAME"):
        cfg.hub.username = user
    if port := os.environ.get("MESHBAY_QUIC_PORT"):
        cfg.node.quic_port = int(port)

    return cfg


def write_example_config(path: Path = DEFAULT_CONFIG_PATH) -> None:
    """Write an example config file if none exists."""
    if not path.exists():
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(EXAMPLE_CONFIG)