@le-space/rootfs 0.6.39 → 0.6.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@le-space/rootfs",
3
- "version": "0.6.39",
3
+ "version": "0.6.41",
4
4
  "description": "Shared rootfs contract parsing, reference profile assets, and build helpers.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -24,6 +24,20 @@ ENV_FILE = os.environ.get("ENV_FILE", "/etc/default/orbitdb-relay")
24
24
  DESCRIBE_SCRIPT = os.environ.get(
25
25
  "DESCRIBE_SCRIPT", "/usr/local/sbin/orbitdb-relay-describe.py"
26
26
  )
27
+ # The initial registration publish (triggered once by configure.sh) must not
28
+ # give up before the browser path is dialable: Caddy's ACME can only complete
29
+ # after the 2n6 DNS record propagates publicly (observed up to ~6-10 min under
30
+ # load), while a single describe run waits at most its own 240 s window. The
31
+ # next timer firing is 20 min away, so a one-shot publish leaves a dead zone
32
+ # in which the registration advertises no browser-dialable address. Retry
33
+ # describe+publish until a secure browser address exists or this deadline
34
+ # passes (then publish whatever is available, matching the old behaviour).
35
+ PUBLISH_RETRY_TIMEOUT_SECONDS = int(
36
+ os.environ.get("BOOTSTRAP_PUBLISH_RETRY_TIMEOUT_SECONDS", "900")
37
+ )
38
+ PUBLISH_RETRY_INTERVAL_SECONDS = int(
39
+ os.environ.get("BOOTSTRAP_PUBLISH_RETRY_INTERVAL_SECONDS", "15")
40
+ )
27
41
  DEFAULT_API_HOST = os.environ.get("ALEPH_BOOTSTRAP_API_HOST", "https://api.aleph.im")
28
42
  DEFAULT_CHANNEL = os.environ.get("ALEPH_BOOTSTRAP_CHANNEL", "simple-todo")
29
43
  DEFAULT_REF = os.environ.get("ALEPH_BOOTSTRAP_REF", "simple-todo-bootstrap")
@@ -78,6 +92,20 @@ def is_browser_dialable(addr: str) -> bool:
78
92
  )
79
93
 
80
94
 
95
+ def is_secure_browser_dialable(addr: str) -> bool:
96
+ """Mirror of the consumer-side address policy (testkit/app): a secure
97
+ websocket, or webtransport/webrtc-direct carrying a certhash. Plain /ws
98
+ does not count — an HTTPS page cannot dial it."""
99
+ normalized = addr.lower()
100
+ if "/tls/ws" in normalized or "/wss" in normalized:
101
+ return True
102
+ if (
103
+ "/webtransport" in normalized or "/webrtc-direct" in normalized
104
+ ) and "/certhash/" in normalized:
105
+ return True
106
+ return False
107
+
108
+
81
109
  def is_public_multiaddr(addr: str) -> bool:
82
110
  parts = split_multiaddr(addr)
83
111
  if not parts:
@@ -603,6 +631,62 @@ def main() -> None:
603
631
  )
604
632
  return
605
633
 
634
+ deadline = time.monotonic() + PUBLISH_RETRY_TIMEOUT_SECONDS
635
+ result: dict[str, object] | None = None
636
+ while True:
637
+ result = attempt_publish(
638
+ env_values,
639
+ publisher_private_key,
640
+ publisher_address,
641
+ registration_id,
642
+ channel,
643
+ ref,
644
+ post_type,
645
+ api_host,
646
+ require_secure_browser_dialable=True,
647
+ )
648
+ if result is not None:
649
+ break
650
+ if time.monotonic() >= deadline:
651
+ # Deadline passed without a secure browser address — publish what
652
+ # exists anyway (probe addresses still serve the Actions path).
653
+ result = attempt_publish(
654
+ env_values,
655
+ publisher_private_key,
656
+ publisher_address,
657
+ registration_id,
658
+ channel,
659
+ ref,
660
+ post_type,
661
+ api_host,
662
+ require_secure_browser_dialable=False,
663
+ )
664
+ break
665
+ time.sleep(PUBLISH_RETRY_INTERVAL_SECONDS)
666
+
667
+ if result is None:
668
+ print(json_dumps({"status": "skipped", "reason": "no public browser multiaddrs"}))
669
+ return
670
+ print(json_dumps(result))
671
+
672
+
673
+ def attempt_publish(
674
+ env_values: dict[str, str],
675
+ publisher_private_key: str,
676
+ publisher_address: str,
677
+ registration_id: str | None,
678
+ channel: str,
679
+ ref: str,
680
+ post_type: str,
681
+ api_host: str,
682
+ require_secure_browser_dialable: bool,
683
+ ) -> dict[str, object] | None:
684
+ """One describe→publish cycle. Returns the result record when a
685
+ registration was published, or None when the caller should retry (no
686
+ public addresses yet, or — while `require_secure_browser_dialable` — none
687
+ of them is dialable from an HTTPS page). Nothing is published on the
688
+ retry path: an early registration without a browser-dialable address
689
+ makes consumers resolve too soon and fail."""
606
690
  describe = subprocess.run([DESCRIBE_SCRIPT], check=True, capture_output=True, text=True)
607
691
  metadata = json.loads(describe.stdout.strip() or "{}")
608
692
  peer_id = metadata.get("peer_id")
@@ -614,14 +698,22 @@ def main() -> None:
614
698
  metadata.get("browser_bootstrap_multiaddrs") or [], browser_only=True
615
699
  )
616
700
 
701
+ now_ms = int(time.time() * 1000)
617
702
  now_seconds = now_ms / 1000
618
703
  profile = env_values.get("ALEPH_BOOTSTRAP_PROFILE", DEFAULT_PROFILE).strip() or DEFAULT_PROFILE
619
704
  version = env_values.get("ALEPH_BOOTSTRAP_VERSION", "").strip() or None
620
705
  published_multiaddrs = select_compact_multiaddrs(browser_multiaddrs or multiaddrs)
706
+ # Intentionally left empty: consumers read content.multiaddrs (fallback),
707
+ # and the relayProof signature is byte-order-sensitive — populating
708
+ # browserMultiaddrs would change the signed payload shape. Cadence, not
709
+ # wire format, is what this retry loop fixes.
621
710
  published_browser_multiaddrs: list[str] = []
622
711
  if not published_multiaddrs:
623
- print(json_dumps({"status": "skipped", "reason": "no public browser multiaddrs"}))
624
- return
712
+ return None
713
+ if require_secure_browser_dialable and not any(
714
+ is_secure_browser_dialable(addr) for addr in published_multiaddrs
715
+ ):
716
+ return None
625
717
 
626
718
  owner_authorization = load_owner_authorization(
627
719
  env_values,
@@ -684,24 +776,20 @@ def main() -> None:
684
776
  api_host, publisher_address, publisher_private_key, previous_hashes, channel
685
777
  )
686
778
 
687
- print(
688
- json_dumps(
689
- {
690
- "status": "published",
691
- "httpStatus": http_status,
692
- "itemHash": unsigned_message["item_hash"],
693
- "sender": publisher_address,
694
- "peerId": peer_id,
695
- "publishedMultiaddrs": published_multiaddrs,
696
- "publishedBrowserMultiaddrs": published_browser_multiaddrs or published_multiaddrs,
697
- "forgottenHashes": previous_hashes,
698
- "forgetStaleOlderThanSeconds": STALE_RECORD_MAX_AGE_SECONDS,
699
- "ownerAuthorizationPresent": owner_authorization is not None,
700
- "forgetResponse": forget_response[1] if forget_response else None,
701
- "response": response,
702
- }
703
- )
704
- )
779
+ return {
780
+ "status": "published",
781
+ "httpStatus": http_status,
782
+ "itemHash": unsigned_message["item_hash"],
783
+ "sender": publisher_address,
784
+ "peerId": peer_id,
785
+ "publishedMultiaddrs": published_multiaddrs,
786
+ "publishedBrowserMultiaddrs": published_browser_multiaddrs or published_multiaddrs,
787
+ "forgottenHashes": previous_hashes,
788
+ "forgetStaleOlderThanSeconds": STALE_RECORD_MAX_AGE_SECONDS,
789
+ "ownerAuthorizationPresent": owner_authorization is not None,
790
+ "forgetResponse": forget_response[1] if forget_response else None,
791
+ "response": response,
792
+ }
705
793
 
706
794
 
707
795
  if __name__ == "__main__":
@@ -120,7 +120,15 @@ write_caddyfile() {
120
120
  https://${hostname} {
121
121
  tls {
122
122
  issuer acme {
123
- disable_tlsalpn_challenge
123
+ # Solve the ACME challenge over TLS-ALPN-01 on :443, NOT HTTP-01.
124
+ # HTTP-01 needs a plaintext listener on :80, but the guest's setup
125
+ # server frees :80 after configuration and Caddy only binds :443, so
126
+ # Let's Encrypt's HTTP-01 probe gets a 503 and no cert is ever issued —
127
+ # browsers then dial wss://.../443 and fail with ERR_SSL_PROTOCOL_ERROR.
128
+ # :443 is already bound and CRN-port-mapped, so TLS-ALPN-01 succeeds
129
+ # (verified live: cert issued in ~45 s). Do NOT flip this back to
130
+ # disable_tlsalpn_challenge — that was b8b8c53 and it broke provisioning.
131
+ disable_http_challenge
124
132
  }
125
133
  }
126
134
 
@@ -1,6 +1,9 @@
1
1
  #!/usr/bin/env python3
2
2
  import json
3
3
  import os
4
+ import re
5
+ import socket
6
+ import ssl
4
7
  import time
5
8
  import urllib.error
6
9
  import urllib.request
@@ -8,11 +11,64 @@ import urllib.request
8
11
 
9
12
  ENV_FILE = os.environ.get("ENV_FILE", "/etc/default/orbitdb-relay")
10
13
  METRICS_PORT = int(os.environ.get("METRICS_PORT", "9090"))
14
+ CADDY_HTTPS_PORT = int(os.environ.get("CADDY_HTTPS_PORT", "443"))
11
15
  WAIT_TIMEOUT_SECONDS = int(os.environ.get("DESCRIBE_WAIT_TIMEOUT_SECONDS", "240"))
12
16
  WAIT_INTERVAL_SECONDS = float(os.environ.get("DESCRIBE_WAIT_INTERVAL_SECONDS", "2"))
13
17
  AUTOTLS_EXTRA_WAIT_SECONDS = int(os.environ.get("DESCRIBE_AUTOTLS_EXTRA_WAIT_SECONDS", "120"))
14
18
 
15
19
 
20
+ def tls_endpoint_serves(hostname: str, port: int) -> bool:
21
+ """True only once the local listener on `port` serves a publicly-trusted
22
+ TLS certificate for `hostname`.
23
+
24
+ The recurring failure shape ("advertise before the certificate serves"):
25
+ an address is announced as browser-dialable while its Let's Encrypt cert
26
+ is still being acquired, so browsers dialing it fail the TLS handshake
27
+ with net::ERR_SSL_PROTOCOL_ERROR. This bit twice — first for Caddy's 2n6
28
+ proxy (cert acquired asynchronously after the caddy restart), then for
29
+ libp2p AutoTLS (multiaddrs appear before the *.libp2p.direct cert is
30
+ live). Verify the real browser-facing certificate with a TLS handshake to
31
+ the local listener using the public hostname as SNI — done locally so
32
+ hairpin-NAT to the VM's own public IP is irrelevant, and validated
33
+ against the system CA store so any self-signed placeholder (Caddy's
34
+ pre-ACME fallback) is rejected.
35
+ """
36
+ if not hostname:
37
+ return False
38
+ context = ssl.create_default_context()
39
+ try:
40
+ with socket.create_connection(("127.0.0.1", port), timeout=8) as raw:
41
+ with context.wrap_socket(raw, server_hostname=hostname) as tls:
42
+ # A validated peer cert here means the handshake a browser
43
+ # will perform against this hostname succeeds too.
44
+ return bool(tls.getpeercert())
45
+ except (ssl.SSLError, OSError, ValueError):
46
+ return False
47
+
48
+
49
+ def caddy_cert_serves(hostname: str) -> bool:
50
+ return tls_endpoint_serves(hostname, CADDY_HTTPS_PORT)
51
+
52
+
53
+ def autotls_cert_serves(autotls_addrs: list[str]) -> bool:
54
+ """Verify the AutoTLS *.libp2p.direct certificate actually serves.
55
+
56
+ The libp2p WebSocket listener terminates the AutoTLS certificate itself,
57
+ so a CA-validated handshake to 127.0.0.1:<port> with the libp2p.direct
58
+ hostname as SNI proves what a browser's wss:// dial will experience. Both
59
+ the hostname AND the port must come from the multiaddr — the TLS is
60
+ served on the announced port (e.g. .../tcp/24007/tls/ws/...), NOT on the
61
+ plain-ws upstream Caddy proxies to.
62
+ """
63
+ for addr in autotls_addrs:
64
+ host_match = re.search(r"/dns[46]/([^/]+)/", addr) or re.search(r"/sni/([^/]+)/", addr)
65
+ port_match = re.search(r"/tcp/(\d+)/", addr)
66
+ if host_match and port_match:
67
+ if tls_endpoint_serves(host_match.group(1), int(port_match.group(1))):
68
+ return True
69
+ return False
70
+
71
+
16
72
  def parse_env_file(path: str) -> dict[str, str]:
17
73
  values: dict[str, str] = {}
18
74
  if not os.path.exists(path):
@@ -153,9 +209,39 @@ def main() -> None:
153
209
  all_multiaddrs = normalize_multiaddrs(multiaddrs_payload)
154
210
  grouped = build_grouped_multiaddrs(env_values, all_multiaddrs, peer_id)
155
211
  proxy_hostname = env_values.get("PROXY_HOSTNAME", "").strip()
156
- if grouped["autotls_wss_multiaddrs"]:
157
- break
158
- if proxy_hostname and grouped["proxy_wss_multiaddrs"] and time.monotonic() - started_at >= AUTOTLS_EXTRA_WAIT_SECONDS:
212
+
213
+ # Symmetric certificate gate for BOTH browser paths. Whichever of
214
+ # Caddy/2n6 and libp2p AutoTLS finishes its ACME first varies per
215
+ # VM; breaking on the mere *presence* of AutoTLS multiaddrs made
216
+ # the outcome a per-VM coin flip — a fast AutoTLS zone produced an
217
+ # acknowledgement containing only libp2p.direct addresses whose
218
+ # cert was not serving yet (ERR_SSL_PROTOCOL_ERROR in browsers),
219
+ # while the verifiable 2n6 address never made it in. Only
220
+ # cert-verified addresses are advertised, and the wait ends as
221
+ # soon as at least one verified browser path exists.
222
+ proxy_cert_ready = bool(
223
+ proxy_hostname
224
+ and grouped["proxy_wss_multiaddrs"]
225
+ and caddy_cert_serves(proxy_hostname)
226
+ )
227
+ autotls_cert_ready = bool(
228
+ grouped["autotls_wss_multiaddrs"]
229
+ and autotls_cert_serves(grouped["autotls_wss_multiaddrs"])
230
+ )
231
+
232
+ unverified: set[str] = set()
233
+ if grouped["proxy_wss_multiaddrs"] and not proxy_cert_ready:
234
+ unverified.update(grouped["proxy_wss_multiaddrs"])
235
+ if grouped["autotls_wss_multiaddrs"] and not autotls_cert_ready:
236
+ unverified.update(grouped["autotls_wss_multiaddrs"])
237
+ if unverified:
238
+ grouped["browser_bootstrap_multiaddrs"] = [
239
+ addr
240
+ for addr in grouped["browser_bootstrap_multiaddrs"]
241
+ if addr not in unverified
242
+ ]
243
+
244
+ if proxy_cert_ready or autotls_cert_ready:
159
245
  break
160
246
  if not proxy_hostname and time.monotonic() - started_at >= AUTOTLS_EXTRA_WAIT_SECONDS:
161
247
  break