Repository navigation
Expand file tree
/
Copy pathremctl_runtime.py
More file actions
314 lines (268 loc) · 9.21 KB
/
Copy pathremctl_runtime.py
File metadata and controls
314 lines (268 loc) · 9.21 KB
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"""Shared runtime helpers for RemCTL scripts."""
from __future__ import annotations
import ipaddress
import os
import re
import shutil
import socket
import tempfile
from datetime import datetime, timedelta
from pathlib import Path
from urllib.parse import urlparse
DEFAULT_STORE_SUBPATH = Path(
"Library/Group Containers/group.com.apple.reminders/Container_v1/Stores"
)
TRUTHY = {"1", "true", "yes", "on"}
CAPABILITY_HOST_MODE_ENV = "REMCTL_CAPABILITY_HOST"
CAPABILITY_HOST_ACTIVE_ENV = "REMCTL_CAPABILITY_HOST_ACTIVE"
CAPABILITY_HOST_MODES = frozenset({"auto", "force", "direct"})
LOCAL_COMMANDS = frozenset(
{
"completion",
"doctor",
"list-symbols",
"mcp",
"onboard",
"permissions",
"setup",
}
)
HOSTED_COMMANDS = frozenset(
{
"add",
"delete",
"deleted",
"restore",
"done",
"edit",
"export",
"flag",
"flagged",
"group-create",
"group-delete",
"group-edit",
"group-info",
"groups",
"import",
"info",
"link",
"list-create",
"list-delete",
"list-edit",
"list-info",
"list-pin",
"list-rename",
"list-unpin",
"lists",
"location-lookup",
"open",
"overdue",
"reminder-move",
"search",
"section-create",
"section-delete",
"section-rename",
"sections",
"sharees",
"show",
"smart-list-create",
"smart-list-delete",
"smart-list-edit",
"smart-lists",
"stats",
"subtasks",
"tags",
"template-apply",
"template-create",
"template-delete",
"template-info",
"templates",
"today",
"undone",
"unflag",
"upcoming",
"urgent",
"workspace",
}
)
def env_bool(name: str, default: bool = False) -> bool:
value = os.environ.get(name)
if value is None:
return default
return value.strip().lower() in TRUTHY
def capability_host_mode(environ: dict[str, str] | None = None) -> str:
"""Return the requested execution mode after applying direct-only guards.
The host's internal child process always uses direct execution. A custom
Reminders store uses direct execution unless force mode requests the host,
which is an explicit configuration conflict.
"""
environment = os.environ if environ is None else environ
if environment.get(CAPABILITY_HOST_ACTIVE_ENV) == "1":
return "direct"
raw_mode = environment.get(CAPABILITY_HOST_MODE_ENV, "auto").strip().lower()
mode = raw_mode or "auto"
if mode not in CAPABILITY_HOST_MODES:
choices = ", ".join(sorted(CAPABILITY_HOST_MODES))
raise ValueError(
f"invalid {CAPABILITY_HOST_MODE_ENV} value {raw_mode!r}; expected {choices}"
)
if environment.get("REMCTL_STORE_DIR"):
if mode == "force":
raise ValueError(
"REMCTL_CAPABILITY_HOST=force conflicts with REMCTL_STORE_DIR; "
"custom stores can run only in auto or direct mode"
)
return "direct"
return mode
def capability_host_command_scope(command: str | None) -> str:
"""Classify one parsed command as local-only or permission-bearing."""
if command is None or command in HOSTED_COMMANDS:
return "hosted"
if command in LOCAL_COMMANDS:
return "local"
raise ValueError(f"unclassified RemCTL command: {command!r}")
def resolve_store_dir() -> Path:
override = os.environ.get("REMCTL_STORE_DIR")
if override:
return Path(override).expanduser()
return Path.home() / DEFAULT_STORE_SUBPATH
def resolve_config_dir(app_name: str = "remctl") -> Path:
override = os.environ.get("REMCTL_CONFIG_DIR")
if override:
return Path(override).expanduser()
xdg = os.environ.get("XDG_CONFIG_HOME")
base = Path(xdg).expanduser() if xdg else (Path.home() / ".config")
return base / app_name
def ensure_private_dir(path: Path) -> None:
path.mkdir(parents=True, exist_ok=True)
try:
path.chmod(0o700)
except OSError:
pass
def write_private_text_file(path: Path, text: str) -> None:
"""Publish complete private state without exposing a truncated token/config."""
ensure_private_dir(path.parent)
if path.is_symlink():
raise OSError(f"Refusing to overwrite a symbolic link: {path}")
fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
try:
with os.fdopen(fd, "w", encoding="utf-8") as fh:
fh.write(text)
fh.flush()
os.fsync(fh.fileno())
os.replace(temporary, path)
finally:
Path(temporary).unlink(missing_ok=True)
def resolve_binary_path(script_path: str, binary_name: str, env_var: str) -> Path:
override = os.environ.get(env_var)
if override:
return Path(override).expanduser()
script_dir = Path(script_path).resolve().parent
candidates = [
script_dir / binary_name,
script_dir / "bin" / binary_name,
Path.home() / "bin" / binary_name,
Path.home() / ".local" / "bin" / binary_name,
]
for candidate in candidates:
if candidate.exists():
return candidate
discovered = shutil.which(binary_name)
if discovered:
return Path(discovered)
return script_dir / binary_name
def start_of_day(now: datetime | None = None) -> datetime:
current = now or datetime.now()
return current.replace(hour=0, minute=0, second=0, microsecond=0)
def due_today_window(now: datetime | None = None) -> tuple[datetime, datetime]:
sod = start_of_day(now)
return sod, sod + timedelta(days=1)
def upcoming_window(days: int = 7, now: datetime | None = None) -> tuple[datetime, datetime]:
sod = start_of_day(now)
return sod, sod + timedelta(days=days + 1)
def mask_secret(secret: str, visible_chars: int = 4) -> str:
if len(secret) <= visible_chars * 2:
return "*" * len(secret)
return f"{secret[:visible_chars]}...{secret[-visible_chars:]}"
# Rich links can open an app (obsidian://, things:) as well as a website. These
# schemes read local files, run script, or reach file servers, so they stay out.
# remctl-private.m keeps the same list in blockedLinkSchemes().
BLOCKED_LINK_SCHEMES = frozenset({
"about", "afp", "blob", "data", "file", "ftp", "ftps", "javascript", "nfs",
"sftp", "smb", "ssh", "telnet", "vbscript", "vnc", "ws", "wss",
})
_URL_SCHEME = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*")
def rich_link_url_problem(url: str) -> str | None:
"""Say why a URL can't become a rich link, or return None when it can.
Web links must reach a public host. Any other scheme is an app link, which
Reminders opens in that app, unless it is in BLOCKED_LINK_SCHEMES.
"""
scheme, colon, rest = (url or "").partition(":")
if not colon or not rest or not _URL_SCHEME.fullmatch(scheme) or any(ch.isspace() or ord(ch) < 32 for ch in url):
return "needs a web URL (https://...) or an app link such as obsidian://open?vault=Notes."
scheme = scheme.lower()
if scheme in {"http", "https"}:
if not is_safe_remote_url(url):
return "must resolve to a public http or https host."
return None
if scheme in BLOCKED_LINK_SCHEMES:
return f"can't use {scheme}: links. Use a web URL or an app link such as obsidian://."
return None
def is_safe_remote_url(url: str) -> bool:
try:
parsed = urlparse(url)
except ValueError:
return False
if parsed.scheme not in {"http", "https"}:
return False
if parsed.username or parsed.password:
return False
try:
hostname = parsed.hostname
port = parsed.port or (443 if parsed.scheme == "https" else 80)
except ValueError:
return False
if not hostname or hostname.rstrip(".").endswith((".local", ".localhost")) or hostname.rstrip(".") == "localhost":
return False
# TUN proxies use this range for DNS placeholders. Never allow it as an
# explicit IP target, including legacy IPv4 spellings such as 0xc6120001.
literal = False
literal_host = hostname.rstrip(".")
try:
ipaddress.ip_address(literal_host)
literal = True
except ValueError:
try:
socket.inet_aton(literal_host)
literal = True
except OSError:
pass
try:
addrinfo = socket.getaddrinfo(
hostname,
port,
type=socket.SOCK_STREAM,
)
except socket.gaierror:
return False
if not addrinfo:
return False
for _, _, _, _, sockaddr in addrinfo:
ip = ipaddress.ip_address(sockaddr[0])
if not literal and ip.version == 4 and ip in ipaddress.ip_network("198.18.0.0/15"):
continue
if (
ip.is_private
or ip.is_loopback
or ip.is_link_local
or ip.is_multicast
or ip.is_reserved
or ip.is_unspecified
):
return False
return True
def is_safe_terminal_text(text: str) -> bool:
return not any(
ord(char) < 0x20 or 0x7F <= ord(char) <= 0x9F
for char in str(text)
)