satsgate 0.1.1__py3-none-any.whl

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.
satsgate/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Umbrella command for a self-hosted satsgate paywall."""
2
+
3
+ __version__ = "0.1.1"
satsgate/__main__.py ADDED
@@ -0,0 +1,92 @@
1
+ """Console entry: `satsgate` and `python -m satsgate`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from satsgate import __version__
9
+ from satsgate.init import InitOptions, run_init
10
+ from satsgate_proxy import __version__ as proxy_version
11
+ from satsgate_sdk import __version__ as sdk_version
12
+
13
+
14
+ def version_line() -> str:
15
+ return f"satsgate {__version__}\nsatsgate-sdk {sdk_version}\nsatsgate-proxy {proxy_version}\n"
16
+
17
+
18
+ def build_parser() -> argparse.ArgumentParser:
19
+ parser = argparse.ArgumentParser(prog="satsgate", description="Set up a self-hosted satsgate paywall.")
20
+ parser.add_argument("--version", action="store_true", help="Print the satsgate, SDK, and proxy versions.")
21
+ sub = parser.add_subparsers(dest="command")
22
+ init = sub.add_parser("init", help="Write a paywall config for a Lightning Address.")
23
+ init.add_argument("--json", action="store_true", help="Print one JSON object and do not prompt.")
24
+ init.add_argument("--api-url", default=None, help="Core API URL. Defaults to SATSGATE_API_URL or the public API.")
25
+ init.add_argument("--lightning-address", default=None, help="Lightning Address that receives payments.")
26
+ init.add_argument("--want-usdc", action="store_true", help="Offer USDC test mode when the EVM payee is verified.")
27
+ init.add_argument("--docker", action="store_true", help="Also write docker-compose.satsgate.yml.")
28
+ init.add_argument(
29
+ "--framework",
30
+ choices=("fastapi", "express", "nginx", "none"),
31
+ default=None,
32
+ help="Origin check to copy next to the config.",
33
+ )
34
+ init.add_argument("--path", default="/paid/**", help="Route path. Default: /paid/**.")
35
+ init.add_argument("--upstream", default="http://127.0.0.1:3000", help="Origin base URL.")
36
+ init.add_argument(
37
+ "--public-url",
38
+ default="http://127.0.0.1:8080",
39
+ help="Buyer-facing proxy URL used when USDC test mode is on. Buyers need a public URL.",
40
+ )
41
+ init.add_argument("--yaml-out", default=None, help="Config path. Default: satsgate-proxy.yaml.")
42
+ init.add_argument("--new-account", action="store_true", help="Open another account even if one is saved.")
43
+ init.add_argument(
44
+ "--replace-api-key",
45
+ action="store_true",
46
+ help="With --new-account, replace SATSGATE_API_KEY with a key for the new account.",
47
+ )
48
+ init.add_argument(
49
+ "--replace-lightning-address",
50
+ action="store_true",
51
+ help="Replace a different Lightning Address already saved on the account.",
52
+ )
53
+ return parser
54
+
55
+
56
+ def options_from(args: argparse.Namespace) -> InitOptions:
57
+ want = True if args.want_usdc else None
58
+ return InitOptions(
59
+ api_url=args.api_url,
60
+ lightning_address=args.lightning_address,
61
+ want_usdc=want,
62
+ json_mode=bool(args.json),
63
+ docker=bool(args.docker),
64
+ framework=args.framework,
65
+ path=args.path,
66
+ upstream=args.upstream,
67
+ public_url=args.public_url,
68
+ yaml_out=args.yaml_out,
69
+ new_account=bool(args.new_account),
70
+ replace_lightning_address=bool(args.replace_lightning_address),
71
+ replace_api_key=bool(args.replace_api_key),
72
+ )
73
+
74
+
75
+ def run(argv: list[str] | None = None) -> int:
76
+ parser = build_parser()
77
+ args = parser.parse_args(argv)
78
+ if args.version:
79
+ sys.stdout.write(version_line())
80
+ return 0
81
+ if args.command != "init":
82
+ parser.print_help(sys.stderr)
83
+ return 2
84
+ return run_init(options_from(args))
85
+
86
+
87
+ def main(argv: list[str] | None = None) -> None:
88
+ raise SystemExit(run(argv))
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()
satsgate/files.py ADDED
@@ -0,0 +1,160 @@
1
+ """Atomic local files for `satsgate init`. Never follow a symlink."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import stat
8
+ import subprocess
9
+ import tempfile
10
+ from pathlib import Path
11
+
12
+ ACCOUNT_KEY = "SATSGATE_ACCOUNT_KEY"
13
+ API_KEY = "SATSGATE_API_KEY"
14
+ ORIGIN_SECRET = "SATSGATE_ORIGIN_SECRET"
15
+ ENV_KEYS = (API_KEY, ORIGIN_SECRET)
16
+ _ASSIGN = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$")
17
+
18
+
19
+ class FileRefusal(Exception):
20
+ def __init__(self, code: str, message: str) -> None:
21
+ super().__init__(message)
22
+ self.code = code
23
+
24
+
25
+ def permissions_restricted() -> bool:
26
+ """POSIX can lock a file to the owner. Windows cannot, and says so."""
27
+ return os.name != "nt"
28
+
29
+
30
+ def mode_of(path: Path) -> int:
31
+ return stat.S_IMODE(path.lstat().st_mode)
32
+
33
+
34
+ def refuse_symlink(path: Path) -> None:
35
+ if path.is_symlink():
36
+ raise FileRefusal("symlink_refused", f"{path.name} is a symlink")
37
+
38
+
39
+ def ensure_dir(path: Path, mode: int = 0o700) -> bool:
40
+ refuse_symlink(path)
41
+ path.mkdir(parents=True, exist_ok=True)
42
+ if not permissions_restricted():
43
+ return False
44
+ os.chmod(path, mode)
45
+ return mode_of(path) == mode
46
+
47
+
48
+ def atomic_write(path: Path, text: str, *, mode: int = 0o600) -> bool:
49
+ """Replace `path` by rename. A symlink is refused and its target is not opened."""
50
+ refuse_symlink(path)
51
+ path.parent.mkdir(parents=True, exist_ok=True)
52
+ fd, name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent))
53
+ tmp = Path(name)
54
+ closed = False
55
+ try:
56
+ os.write(fd, text.encode("utf-8"))
57
+ if permissions_restricted():
58
+ os.fchmod(fd, mode)
59
+ os.close(fd)
60
+ closed = True
61
+ os.replace(tmp, path)
62
+ tmp = None
63
+ finally:
64
+ if not closed:
65
+ os.close(fd)
66
+ if tmp is not None:
67
+ tmp.unlink(missing_ok=True)
68
+ if not permissions_restricted():
69
+ return False
70
+ os.chmod(path, mode)
71
+ return mode_of(path) == mode
72
+
73
+
74
+ def read_text(path: Path) -> str:
75
+ refuse_symlink(path)
76
+ return path.read_text(encoding="utf-8")
77
+
78
+
79
+ def unquote(value: str) -> str:
80
+ text = value.strip()
81
+ if len(text) >= 2 and text[0] == text[-1] and text[0] in {'"', "'"}:
82
+ return text[1:-1]
83
+ return text
84
+
85
+
86
+ def parse_env(text: str) -> dict[str, str]:
87
+ found: dict[str, str] = {}
88
+ for line in text.splitlines():
89
+ stripped = line.strip()
90
+ if not stripped or stripped.startswith("#"):
91
+ continue
92
+ match = _ASSIGN.match(stripped)
93
+ if match is not None:
94
+ found[match.group(1)] = unquote(match.group(2))
95
+ return found
96
+
97
+
98
+ def merge_env(text: str, updates: dict[str, str], *, replace: set[str]) -> tuple[str, dict[str, str]]:
99
+ """Append missing keys. A different value is a conflict unless `replace` names it.
100
+
101
+ On conflict the original text is returned unchanged.
102
+ """
103
+ lines = text.splitlines(keepends=True)
104
+ seen: set[str] = set()
105
+ conflicts: dict[str, str] = {}
106
+ rewritten: list[str] = []
107
+ for line in lines:
108
+ match = _ASSIGN.match(line.strip())
109
+ key = match.group(1) if match is not None else None
110
+ if key in updates and key not in seen:
111
+ seen.add(key)
112
+ current = unquote(match.group(2)) if match is not None else ""
113
+ if current == updates[key]:
114
+ rewritten.append(line if line.endswith("\n") else line + "\n")
115
+ elif key in replace:
116
+ prefix = "export " if line.strip().startswith("export ") else ""
117
+ rewritten.append(f"{prefix}{key}={updates[key]}\n")
118
+ else:
119
+ conflicts[key] = current
120
+ rewritten.append(line if line.endswith("\n") else line + "\n")
121
+ else:
122
+ rewritten.append(line if line.endswith("\n") else line + "\n")
123
+ if conflicts:
124
+ return text, conflicts
125
+ body = "".join(rewritten)
126
+ missing = [key for key in updates if key not in seen]
127
+ if missing:
128
+ if body and not body.endswith("\n"):
129
+ body += "\n"
130
+ for key in updates:
131
+ if key in missing:
132
+ body += f"{key}={updates[key]}\n"
133
+ return body, {}
134
+
135
+
136
+ def inside_work_tree(cwd: Path) -> bool:
137
+ try:
138
+ proc = subprocess.run(
139
+ ["git", "rev-parse", "--is-inside-work-tree"],
140
+ cwd=str(cwd),
141
+ check=False,
142
+ capture_output=True,
143
+ text=True,
144
+ )
145
+ except OSError:
146
+ return False
147
+ return proc.returncode == 0 and proc.stdout.strip() == "true"
148
+
149
+
150
+ def env_is_ignored(cwd: Path) -> bool:
151
+ try:
152
+ proc = subprocess.run(
153
+ ["git", "check-ignore", "-q", "--", ".env"],
154
+ cwd=str(cwd),
155
+ check=False,
156
+ capture_output=True,
157
+ )
158
+ except OSError:
159
+ return False
160
+ return proc.returncode == 0