revemaker 0.1.0__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.
- media_platform/__init__.py +5 -0
- media_platform/cli.py +1156 -0
- media_platform/hosted.json +3 -0
- media_platform/protocol.py +84 -0
- revemaker-0.1.0.dist-info/METADATA +51 -0
- revemaker-0.1.0.dist-info/RECORD +9 -0
- revemaker-0.1.0.dist-info/WHEEL +4 -0
- revemaker-0.1.0.dist-info/entry_points.txt +2 -0
- revemaker-0.1.0.dist-info/licenses/distribution/LICENSE +21 -0
media_platform/cli.py
ADDED
|
@@ -0,0 +1,1156 @@
|
|
|
1
|
+
"""The revemaker command line client (issue #57).
|
|
2
|
+
|
|
3
|
+
``revemaker login`` signs in through the browser (OAuth 2.1, loopback redirect,
|
|
4
|
+
PKCE S256, RFC 8707 ``resource``, RFC 9207 ``iss``); ``revemaker logout`` revokes the
|
|
5
|
+
grant on the server and removes the local copy; ``revemaker account`` shows the
|
|
6
|
+
plan and balance. Every command except ``login`` fails fast with
|
|
7
|
+
``auth_required`` when signed out and never opens a browser by itself.
|
|
8
|
+
|
|
9
|
+
It uses only the standard library, so it runs without the server's
|
|
10
|
+
dependencies. Credentials live in the macOS Keychain where available, else in a
|
|
11
|
+
``0600`` file under the user's config directory (on Windows, the user profile's
|
|
12
|
+
access control protects it). Tokens are never printed.
|
|
13
|
+
|
|
14
|
+
Run it as ``python3 -m media_platform.cli`` (``engineering/bin/revemaker`` is a shim),
|
|
15
|
+
or install the package that ``engineering/pyproject.toml`` builds (issue #99),
|
|
16
|
+
which ships only this module, ``protocol`` and the release's ``hosted.json``; a
|
|
17
|
+
checkout has none and keeps the local loopback default. The keychain service name
|
|
18
|
+
differs from the old ``media-cli`` entry, so the renamed CLI starts signed out (#319).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import argparse
|
|
24
|
+
import contextlib
|
|
25
|
+
import errno
|
|
26
|
+
import hashlib
|
|
27
|
+
import hmac
|
|
28
|
+
import http.client
|
|
29
|
+
import http.server
|
|
30
|
+
import json
|
|
31
|
+
import os
|
|
32
|
+
import platform
|
|
33
|
+
import re
|
|
34
|
+
import secrets
|
|
35
|
+
import shutil
|
|
36
|
+
import subprocess
|
|
37
|
+
import sys
|
|
38
|
+
import tempfile
|
|
39
|
+
import threading
|
|
40
|
+
import time
|
|
41
|
+
import urllib.error
|
|
42
|
+
import urllib.parse
|
|
43
|
+
import urllib.request
|
|
44
|
+
import uuid
|
|
45
|
+
import webbrowser
|
|
46
|
+
from collections.abc import Callable, Iterator, Mapping
|
|
47
|
+
from dataclasses import asdict, dataclass, replace
|
|
48
|
+
from pathlib import Path
|
|
49
|
+
from typing import IO, Any
|
|
50
|
+
|
|
51
|
+
from .protocol import DEVICE_GRANT, FIRST_PARTY_CLIENT_ID, MEDIA_EXTENSIONS, SCOPE_AUTOMATION, is_loopback, pkce_challenge
|
|
52
|
+
from .protocol import normalize_server_url as _server_origin
|
|
53
|
+
|
|
54
|
+
try:
|
|
55
|
+
import fcntl
|
|
56
|
+
except ImportError: # pragma: no cover
|
|
57
|
+
fcntl = None
|
|
58
|
+
import msvcrt
|
|
59
|
+
|
|
60
|
+
__version__ = "0.1.0"
|
|
61
|
+
WINDOWS = os.name == "nt"
|
|
62
|
+
|
|
63
|
+
SERVER_ENV = "MEDIA_SERVER_URL"
|
|
64
|
+
CONFIG_DIR_ENV = "MEDIA_CONFIG_DIR"
|
|
65
|
+
STORE_ENV = "MEDIA_CREDENTIAL_STORE"
|
|
66
|
+
LOCAL_SERVER = "http://127.0.0.1:8000"
|
|
67
|
+
HOSTED_FILE = Path(__file__).with_name("hosted.json")
|
|
68
|
+
KEYCHAIN_SERVICE = "revemaker-cli"
|
|
69
|
+
CREDENTIALS_FILE = "credentials.json"
|
|
70
|
+
LOCK_FILE = "credentials.lock"
|
|
71
|
+
|
|
72
|
+
LOGIN_TIMEOUT_SECONDS = 180.0
|
|
73
|
+
HTTP_TIMEOUT_SECONDS = 30.0
|
|
74
|
+
REFRESH_SKEW_SECONDS = 60
|
|
75
|
+
LISTENER_POLL_SECONDS = 0.1
|
|
76
|
+
MAX_BODY_BYTES = 1 << 20
|
|
77
|
+
TRANSFER_SECONDS = 150
|
|
78
|
+
MAX_TRANSFER_BYTES = 20 * 1024 * 1024
|
|
79
|
+
KEYCHAIN_SECONDS = 30
|
|
80
|
+
SHARING_RETRIES, SHARING_RETRY_SECONDS = 40, 0.05
|
|
81
|
+
LOCK_RETRY_SECONDS = 0.02
|
|
82
|
+
SCOPE = "account:read media:generate"
|
|
83
|
+
|
|
84
|
+
EXIT_ERROR = 1
|
|
85
|
+
EXIT_AUTH_REQUIRED = 3
|
|
86
|
+
|
|
87
|
+
_ERROR_CODE = re.compile(r"[a-z_]{1,40}")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def safe_code(value: object, default: str) -> str:
|
|
91
|
+
"""``value`` when it is a plain error code, else ``default``: nothing else from a reply is echoed."""
|
|
92
|
+
return value if isinstance(value, str) and _ERROR_CODE.fullmatch(value) else default
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class CliError(Exception):
|
|
96
|
+
"""A failure the user should see: a stable ``code``, a message and an exit status."""
|
|
97
|
+
|
|
98
|
+
def __init__(self, code: str, message: str, exit_code: int = EXIT_ERROR, action: dict | None = None) -> None:
|
|
99
|
+
super().__init__(message)
|
|
100
|
+
self.code = code
|
|
101
|
+
self.message = message
|
|
102
|
+
self.exit_code = exit_code
|
|
103
|
+
self.action = action
|
|
104
|
+
|
|
105
|
+
def body(self) -> dict:
|
|
106
|
+
body: dict[str, Any] = {"code": self.code, "message": self.message}
|
|
107
|
+
if self.action:
|
|
108
|
+
body["action"] = self.action
|
|
109
|
+
return body
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def auth_required(message: str = "You are not signed in. Run `revemaker login`.") -> CliError:
|
|
113
|
+
return CliError("auth_required", message, EXIT_AUTH_REQUIRED, {"kind": "sign_in"})
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def default_server() -> str:
|
|
117
|
+
"""The hosted origin the package was released for, else the local server."""
|
|
118
|
+
try:
|
|
119
|
+
value = json.loads(HOSTED_FILE.read_text(encoding="utf-8")).get("server_url")
|
|
120
|
+
except (OSError, ValueError, AttributeError):
|
|
121
|
+
return LOCAL_SERVER
|
|
122
|
+
return value if isinstance(value, str) and value else LOCAL_SERVER
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@dataclass(frozen=True)
|
|
126
|
+
class Credentials:
|
|
127
|
+
"""What one sign-in keeps. Bound to ``issuer``: never sent to another server.
|
|
128
|
+
|
|
129
|
+
``generation`` is the save order set by CredentialStore.save under the lock: the highest is current.
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
issuer: str
|
|
133
|
+
client_id: str
|
|
134
|
+
resource: str
|
|
135
|
+
access_token: str
|
|
136
|
+
access_expires_at: float
|
|
137
|
+
refresh_token: str
|
|
138
|
+
scope: str
|
|
139
|
+
generation: int = 0
|
|
140
|
+
|
|
141
|
+
def __repr__(self) -> str:
|
|
142
|
+
"""Redacted: a traceback or log line must not carry a token."""
|
|
143
|
+
return f"Credentials(issuer={self.issuer!r}, client_id={self.client_id!r}, tokens=<redacted>)"
|
|
144
|
+
|
|
145
|
+
@classmethod
|
|
146
|
+
def from_json(cls, value: object) -> Credentials | None:
|
|
147
|
+
if not isinstance(value, dict):
|
|
148
|
+
return None
|
|
149
|
+
try:
|
|
150
|
+
return cls(
|
|
151
|
+
str(value["issuer"]), str(value["client_id"]), str(value["resource"]),
|
|
152
|
+
str(value["access_token"]), float(value["access_expires_at"]),
|
|
153
|
+
str(value["refresh_token"]), str(value["scope"]), int(value.get("generation", 0)),
|
|
154
|
+
)
|
|
155
|
+
except (KeyError, TypeError, ValueError):
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class StoreError(Exception):
|
|
160
|
+
"""A credential store could not be read or written."""
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def ensure_private_dir(path: Path) -> None:
|
|
164
|
+
path.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
165
|
+
if path.stat().st_mode & 0o077:
|
|
166
|
+
os.chmod(path, 0o700)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _fsync_dir(path: Path) -> None:
|
|
170
|
+
"""Flush a directory entry; a no-op on Windows, where a directory cannot be opened as a file and the rename is already durable."""
|
|
171
|
+
if WINDOWS:
|
|
172
|
+
return
|
|
173
|
+
fd = os.open(path, os.O_RDONLY)
|
|
174
|
+
try:
|
|
175
|
+
os.fsync(fd)
|
|
176
|
+
finally:
|
|
177
|
+
os.close(fd)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _sharing_retry(action: Callable[[], Any]) -> Any:
|
|
181
|
+
"""``action()``, retried briefly on Windows, where a rename or open fails while
|
|
182
|
+
another process has the file open (a sharing violation, ``PermissionError``)."""
|
|
183
|
+
if WINDOWS:
|
|
184
|
+
for _ in range(SHARING_RETRIES):
|
|
185
|
+
try:
|
|
186
|
+
return action()
|
|
187
|
+
except PermissionError:
|
|
188
|
+
time.sleep(SHARING_RETRY_SECONDS)
|
|
189
|
+
return action()
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class FileStore:
|
|
193
|
+
"""``credentials.json`` (mode 0600, in a 0700 directory), written atomically.
|
|
194
|
+
Windows has no mode bits to check; the user profile's access control applies."""
|
|
195
|
+
|
|
196
|
+
name = "file"
|
|
197
|
+
|
|
198
|
+
def __init__(self, directory: Path) -> None:
|
|
199
|
+
self.directory = directory
|
|
200
|
+
self.path = directory / CREDENTIALS_FILE
|
|
201
|
+
|
|
202
|
+
def _read_all(self) -> dict[str, Any]:
|
|
203
|
+
try:
|
|
204
|
+
info = self.path.stat()
|
|
205
|
+
except FileNotFoundError:
|
|
206
|
+
return {}
|
|
207
|
+
except OSError as exc:
|
|
208
|
+
raise StoreError(f"{self.path} is not readable: {type(exc).__name__}") from None
|
|
209
|
+
if info.st_mode & 0o077 and not WINDOWS:
|
|
210
|
+
raise StoreError(f"{self.path} is readable by other users; run: chmod 600 {self.path}")
|
|
211
|
+
try:
|
|
212
|
+
data = json.loads(_sharing_retry(lambda: self.path.read_text(encoding="utf-8")))
|
|
213
|
+
except (OSError, ValueError) as exc:
|
|
214
|
+
raise StoreError(f"{self.path} is not readable: {type(exc).__name__}") from None
|
|
215
|
+
entries = data.get("credentials") if isinstance(data, dict) else None
|
|
216
|
+
if not isinstance(entries, dict):
|
|
217
|
+
raise StoreError(f"{self.path} is not a credentials file")
|
|
218
|
+
return entries
|
|
219
|
+
|
|
220
|
+
def load(self, issuer: str) -> Credentials | None:
|
|
221
|
+
return Credentials.from_json(self._read_all().get(issuer))
|
|
222
|
+
|
|
223
|
+
def _write_all(self, entries: dict[str, Any]) -> None:
|
|
224
|
+
if not entries:
|
|
225
|
+
with contextlib.suppress(FileNotFoundError):
|
|
226
|
+
_sharing_retry(self.path.unlink)
|
|
227
|
+
return
|
|
228
|
+
ensure_private_dir(self.directory)
|
|
229
|
+
fd, tmp = tempfile.mkstemp(dir=self.directory, prefix=".credentials-")
|
|
230
|
+
try:
|
|
231
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
232
|
+
json.dump({"version": 1, "credentials": entries}, handle)
|
|
233
|
+
handle.flush()
|
|
234
|
+
os.fsync(handle.fileno())
|
|
235
|
+
_sharing_retry(lambda: os.replace(tmp, self.path))
|
|
236
|
+
except BaseException:
|
|
237
|
+
with contextlib.suppress(FileNotFoundError):
|
|
238
|
+
os.unlink(tmp)
|
|
239
|
+
raise
|
|
240
|
+
_fsync_dir(self.directory)
|
|
241
|
+
|
|
242
|
+
def save(self, creds: Credentials) -> None:
|
|
243
|
+
try:
|
|
244
|
+
entries = self._read_all()
|
|
245
|
+
entries[creds.issuer] = asdict(creds)
|
|
246
|
+
self._write_all(entries)
|
|
247
|
+
except OSError as exc:
|
|
248
|
+
raise StoreError(f"cannot write {self.path}: {type(exc).__name__}") from None
|
|
249
|
+
|
|
250
|
+
def delete(self, issuer: str) -> None:
|
|
251
|
+
try:
|
|
252
|
+
entries = self._read_all()
|
|
253
|
+
if entries.pop(issuer, None) is not None:
|
|
254
|
+
self._write_all(entries)
|
|
255
|
+
except OSError as exc:
|
|
256
|
+
raise StoreError(f"cannot update {self.path}: {type(exc).__name__}") from None
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
Runner = Callable[..., "subprocess.CompletedProcess[str]"]
|
|
260
|
+
_KEYCHAIN_SAFE = re.compile(r"[A-Za-z0-9:/._\[\]-]+")
|
|
261
|
+
_ERR_SEC_ITEM_NOT_FOUND = 44
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
class KeychainStore:
|
|
265
|
+
"""The macOS Keychain through ``/usr/bin/security``.
|
|
266
|
+
|
|
267
|
+
A secret never goes on a command line (``ps`` shows those): ``add`` is sent
|
|
268
|
+
to ``security -i`` on stdin, as hex so no quoting can matter, and read back
|
|
269
|
+
to be sure it was stored (interactive mode can exit 0 after a failure).
|
|
270
|
+
"""
|
|
271
|
+
|
|
272
|
+
name = "keychain"
|
|
273
|
+
|
|
274
|
+
def __init__(self, service: str = KEYCHAIN_SERVICE, runner: Runner = subprocess.run, binary: str | None = None) -> None:
|
|
275
|
+
self.service = service
|
|
276
|
+
self._run = runner
|
|
277
|
+
self._binary = binary or shutil.which("security") or "/usr/bin/security"
|
|
278
|
+
|
|
279
|
+
@staticmethod
|
|
280
|
+
def available() -> bool:
|
|
281
|
+
return platform.system() == "Darwin" and shutil.which("security") is not None
|
|
282
|
+
|
|
283
|
+
def _security(self, *args: str, stdin: str | None = None) -> subprocess.CompletedProcess:
|
|
284
|
+
try:
|
|
285
|
+
return self._run(
|
|
286
|
+
[self._binary, *args], input=stdin, capture_output=True, text=True, timeout=KEYCHAIN_SECONDS, check=False
|
|
287
|
+
)
|
|
288
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
289
|
+
raise StoreError(f"keychain unavailable: {type(exc).__name__}") from None
|
|
290
|
+
|
|
291
|
+
def load(self, issuer: str) -> Credentials | None:
|
|
292
|
+
result = self._security("find-generic-password", "-s", self.service, "-a", issuer, "-w")
|
|
293
|
+
if result.returncode == _ERR_SEC_ITEM_NOT_FOUND:
|
|
294
|
+
return None
|
|
295
|
+
if result.returncode != 0:
|
|
296
|
+
raise StoreError("keychain read failed")
|
|
297
|
+
try:
|
|
298
|
+
return Credentials.from_json(json.loads(bytes.fromhex(result.stdout.strip()).decode("utf-8")))
|
|
299
|
+
except ValueError:
|
|
300
|
+
return None
|
|
301
|
+
|
|
302
|
+
def save(self, creds: Credentials) -> None:
|
|
303
|
+
if not _KEYCHAIN_SAFE.fullmatch(creds.issuer):
|
|
304
|
+
raise StoreError("keychain cannot hold this issuer name")
|
|
305
|
+
secret = json.dumps(asdict(creds)).encode("utf-8").hex()
|
|
306
|
+
command = f'add-generic-password -U -s "{self.service}" -a "{creds.issuer}" -w {secret}\n'
|
|
307
|
+
self._security("-i", stdin=command)
|
|
308
|
+
if self.load(creds.issuer) != creds:
|
|
309
|
+
raise StoreError("keychain write failed")
|
|
310
|
+
|
|
311
|
+
def delete(self, issuer: str) -> None:
|
|
312
|
+
result = self._security("delete-generic-password", "-s", self.service, "-a", issuer)
|
|
313
|
+
if result.returncode not in (0, _ERR_SEC_ITEM_NOT_FOUND):
|
|
314
|
+
raise StoreError("keychain delete failed")
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def lock_file(fd: int) -> None:
|
|
318
|
+
"""Block until this process holds the exclusive lock on ``fd``.
|
|
319
|
+
|
|
320
|
+
Windows polls non-blocking (LK_LOCK retries only once a second) on the first byte, which need not exist;
|
|
321
|
+
any error other than "held elsewhere" is final.
|
|
322
|
+
"""
|
|
323
|
+
if fcntl is not None:
|
|
324
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
325
|
+
return
|
|
326
|
+
while True: # pragma: no cover
|
|
327
|
+
os.lseek(fd, 0, os.SEEK_SET)
|
|
328
|
+
try:
|
|
329
|
+
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
|
|
330
|
+
return
|
|
331
|
+
except OSError as exc:
|
|
332
|
+
if exc.errno not in (errno.EACCES, errno.EDEADLK):
|
|
333
|
+
raise
|
|
334
|
+
time.sleep(LOCK_RETRY_SECONDS)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def unlock_file(fd: int) -> None:
|
|
338
|
+
if fcntl is not None:
|
|
339
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
340
|
+
return
|
|
341
|
+
os.lseek(fd, 0, os.SEEK_SET) # pragma: no cover
|
|
342
|
+
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) # pragma: no cover
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
class CredentialStore:
|
|
346
|
+
"""The keychain when it works, else the file. A save to one removes the entry
|
|
347
|
+
from the other (best effort; ``load`` prefers the newest either way)."""
|
|
348
|
+
|
|
349
|
+
def __init__(self, backends: list[Any], warn: Callable[[str], None] = lambda message: None) -> None:
|
|
350
|
+
self._backends = backends
|
|
351
|
+
self._warn = warn
|
|
352
|
+
|
|
353
|
+
def load(self, issuer: str) -> Credentials | None:
|
|
354
|
+
"""Every backend that can be read is consulted and the highest ``generation``
|
|
355
|
+
wins, so a copy a failed cleanup left behind in a recovered backend can never
|
|
356
|
+
hide a later save and resubmit a spent token. An unreadable backend is
|
|
357
|
+
skipped while another one answers."""
|
|
358
|
+
error: StoreError | None = None
|
|
359
|
+
found: list[Credentials] = []
|
|
360
|
+
for backend in self._backends:
|
|
361
|
+
try:
|
|
362
|
+
creds = backend.load(issuer)
|
|
363
|
+
except StoreError as exc:
|
|
364
|
+
error = error or exc
|
|
365
|
+
continue
|
|
366
|
+
if creds is not None:
|
|
367
|
+
found.append(creds)
|
|
368
|
+
if found:
|
|
369
|
+
return max(found, key=lambda creds: creds.generation)
|
|
370
|
+
if error is not None:
|
|
371
|
+
raise error
|
|
372
|
+
return None
|
|
373
|
+
|
|
374
|
+
def save(self, creds: Credentials, after: int = 0) -> Credentials:
|
|
375
|
+
"""Store ``creds`` as the newest generation and return what was stored. The
|
|
376
|
+
generation is one past the highest seen now or already read by the caller
|
|
377
|
+
(``after``, so a backend that fails between that read and this save still
|
|
378
|
+
ranks lower), and never below the wall clock in seconds."""
|
|
379
|
+
try:
|
|
380
|
+
seen = self.load(creds.issuer)
|
|
381
|
+
except StoreError:
|
|
382
|
+
seen = None
|
|
383
|
+
creds = replace(creds, generation=max((seen.generation if seen else 0) + 1, after + 1, int(time.time())))
|
|
384
|
+
last = self._backends[-1]
|
|
385
|
+
for backend in self._backends:
|
|
386
|
+
try:
|
|
387
|
+
backend.save(creds)
|
|
388
|
+
except StoreError as exc:
|
|
389
|
+
if backend is last:
|
|
390
|
+
raise
|
|
391
|
+
self._warn(f"warning: {exc}; using the next credential store")
|
|
392
|
+
continue
|
|
393
|
+
for other in self._backends:
|
|
394
|
+
if other is not backend:
|
|
395
|
+
with contextlib.suppress(StoreError):
|
|
396
|
+
other.delete(creds.issuer)
|
|
397
|
+
return creds
|
|
398
|
+
return None
|
|
399
|
+
|
|
400
|
+
def delete(self, issuer: str) -> None:
|
|
401
|
+
failures = []
|
|
402
|
+
for backend in self._backends:
|
|
403
|
+
try:
|
|
404
|
+
backend.delete(issuer)
|
|
405
|
+
except StoreError as exc:
|
|
406
|
+
failures.append(str(exc))
|
|
407
|
+
if failures:
|
|
408
|
+
raise StoreError("; ".join(failures))
|
|
409
|
+
|
|
410
|
+
@contextlib.contextmanager
|
|
411
|
+
def lock(self, directory: Path) -> Iterator[None]:
|
|
412
|
+
"""One refresh at a time across processes: a refresh token is single
|
|
413
|
+
use, so two racing refreshes would look like theft and revoke the grant."""
|
|
414
|
+
try:
|
|
415
|
+
ensure_private_dir(directory)
|
|
416
|
+
fd = os.open(directory / LOCK_FILE, os.O_RDWR | os.O_CREAT, 0o600)
|
|
417
|
+
except OSError as exc:
|
|
418
|
+
raise StoreError(f"cannot open {directory / LOCK_FILE}: {type(exc).__name__}") from None
|
|
419
|
+
try:
|
|
420
|
+
try:
|
|
421
|
+
lock_file(fd)
|
|
422
|
+
except OSError as exc:
|
|
423
|
+
raise StoreError(f"cannot lock {directory / LOCK_FILE}: {type(exc).__name__}") from None
|
|
424
|
+
try:
|
|
425
|
+
yield
|
|
426
|
+
finally:
|
|
427
|
+
unlock_file(fd)
|
|
428
|
+
finally:
|
|
429
|
+
os.close(fd)
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
433
|
+
"""Never follow a redirect: urllib would carry the Authorization header along."""
|
|
434
|
+
|
|
435
|
+
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
|
|
436
|
+
return None
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
@dataclass
|
|
440
|
+
class Response:
|
|
441
|
+
status: int
|
|
442
|
+
body: bytes
|
|
443
|
+
headers: Mapping[str, str]
|
|
444
|
+
|
|
445
|
+
def json(self) -> dict | None:
|
|
446
|
+
try:
|
|
447
|
+
value = json.loads(self.body.decode("utf-8"))
|
|
448
|
+
except ValueError:
|
|
449
|
+
return None
|
|
450
|
+
return value if isinstance(value, dict) else None
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def opener_for(url: str) -> urllib.request.OpenerDirector:
|
|
454
|
+
"""An opener that never follows a redirect and, for a loopback URL, never uses a proxy."""
|
|
455
|
+
handlers: list[Any] = [_NoRedirect]
|
|
456
|
+
if is_loopback(urllib.parse.urlsplit(url).hostname or ""):
|
|
457
|
+
handlers.append(urllib.request.ProxyHandler({}))
|
|
458
|
+
return urllib.request.build_opener(*handlers)
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def http_request(
|
|
462
|
+
method: str, url: str, *, form: Mapping[str, str] | None = None, token: str | None = None,
|
|
463
|
+
json_body: dict | None = None, data: bytes | None = None, headers: Mapping[str, str] | None = None,
|
|
464
|
+
timeout: float = HTTP_TIMEOUT_SECONDS, max_body_bytes: int = MAX_BODY_BYTES
|
|
465
|
+
) -> Response:
|
|
466
|
+
data = urllib.parse.urlencode(form).encode("ascii") if form is not None else data
|
|
467
|
+
if json_body is not None:
|
|
468
|
+
data = json.dumps(json_body).encode("utf-8")
|
|
469
|
+
request = urllib.request.Request(url, data=data, method=method)
|
|
470
|
+
request.add_header("Accept", "application/json")
|
|
471
|
+
if form is not None:
|
|
472
|
+
request.add_header("Content-Type", "application/x-www-form-urlencoded")
|
|
473
|
+
if json_body is not None:
|
|
474
|
+
request.add_header("Content-Type", "application/json")
|
|
475
|
+
for key, value in (headers or {}).items():
|
|
476
|
+
request.add_header(key, value)
|
|
477
|
+
if token:
|
|
478
|
+
request.add_header("Authorization", f"Bearer {token}")
|
|
479
|
+
try:
|
|
480
|
+
with opener_for(url).open(request, timeout=timeout) as reply:
|
|
481
|
+
return Response(reply.status, reply.read(max_body_bytes), dict(reply.headers))
|
|
482
|
+
except urllib.error.HTTPError as exc:
|
|
483
|
+
with exc:
|
|
484
|
+
return Response(exc.code, exc.read(max_body_bytes), dict(exc.headers))
|
|
485
|
+
except (urllib.error.URLError, OSError, ValueError) as exc:
|
|
486
|
+
raise CliError("network_error", f"cannot reach the server: {type(exc).__name__}") from None
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def normalize_server_url(value: str) -> str:
|
|
490
|
+
try:
|
|
491
|
+
return _server_origin(value)
|
|
492
|
+
except ValueError as exc:
|
|
493
|
+
raise CliError("invalid_server", str(exc)) from None
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def resource_for(issuer: str) -> str:
|
|
497
|
+
"""The RFC 8707 resource every token is bound to: the server's ``/v1`` door."""
|
|
498
|
+
return issuer + "/v1"
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
@dataclass(frozen=True)
|
|
502
|
+
class Endpoints:
|
|
503
|
+
issuer: str
|
|
504
|
+
authorization: str
|
|
505
|
+
token: str
|
|
506
|
+
revocation: str
|
|
507
|
+
device_authorization: str | None = None
|
|
508
|
+
|
|
509
|
+
@property
|
|
510
|
+
def resource(self) -> str:
|
|
511
|
+
return resource_for(self.issuer)
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def discover(server: str) -> Endpoints:
|
|
515
|
+
"""Read the authorization server metadata and refuse one that names another issuer (RFC 8414)."""
|
|
516
|
+
reply = http_request("GET", f"{server}/.well-known/oauth-authorization-server")
|
|
517
|
+
meta = reply.json() if reply.status == 200 else None
|
|
518
|
+
if meta is None:
|
|
519
|
+
raise CliError("server_error", f"{server} does not look like a revemaker server")
|
|
520
|
+
if meta.get("issuer") != server:
|
|
521
|
+
raise CliError("server_error", "the server's issuer does not match the URL it was reached at")
|
|
522
|
+
urls = []
|
|
523
|
+
for key in ("authorization_endpoint", "token_endpoint", "revocation_endpoint"):
|
|
524
|
+
value = meta.get(key)
|
|
525
|
+
if not isinstance(value, str) or not value.startswith(server + "/"):
|
|
526
|
+
raise CliError("server_error", f"the server metadata has a bad {key}")
|
|
527
|
+
urls.append(value)
|
|
528
|
+
device = meta.get("device_authorization_endpoint")
|
|
529
|
+
if device is not None and (not isinstance(device, str) or not device.startswith(server + "/")):
|
|
530
|
+
raise CliError("server_error", "the server metadata has a bad device_authorization_endpoint")
|
|
531
|
+
return Endpoints(server, *urls, device)
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
@dataclass
|
|
535
|
+
class Context:
|
|
536
|
+
out: IO[str]
|
|
537
|
+
err: IO[str]
|
|
538
|
+
json_mode: bool
|
|
539
|
+
opener: Callable[[str], bool]
|
|
540
|
+
clock: Callable[[], float]
|
|
541
|
+
login_timeout: float
|
|
542
|
+
server: str
|
|
543
|
+
config_dir: Path
|
|
544
|
+
store: CredentialStore
|
|
545
|
+
|
|
546
|
+
def say(self, text: str) -> None:
|
|
547
|
+
if not self.json_mode:
|
|
548
|
+
print(text, file=self.out)
|
|
549
|
+
|
|
550
|
+
def note(self, text: str) -> None:
|
|
551
|
+
print(text, file=self.err)
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def config_dir(env: Mapping[str, str]) -> Path:
|
|
555
|
+
if env.get(CONFIG_DIR_ENV):
|
|
556
|
+
return Path(env[CONFIG_DIR_ENV])
|
|
557
|
+
if env.get("XDG_CONFIG_HOME"):
|
|
558
|
+
return Path(env["XDG_CONFIG_HOME"]) / "revemaker"
|
|
559
|
+
return Path.home() / ".config" / "revemaker"
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def keychain_service(env: Mapping[str, str], directory: Path) -> str:
|
|
563
|
+
"""One Keychain item per config directory, so the refresh lock (kept in that
|
|
564
|
+
directory) covers exactly the clients that share a credential. The default
|
|
565
|
+
directory keeps the plain service name."""
|
|
566
|
+
if directory == config_dir({}):
|
|
567
|
+
return KEYCHAIN_SERVICE
|
|
568
|
+
return f"{KEYCHAIN_SERVICE}:{hashlib.sha256(str(directory.resolve()).encode()).hexdigest()[:16]}"
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def make_store(env: Mapping[str, str], directory: Path, warn: Callable[[str], None]) -> CredentialStore:
|
|
572
|
+
backends: list[Any] = []
|
|
573
|
+
if env.get(STORE_ENV) != "file" and KeychainStore.available():
|
|
574
|
+
backends.append(KeychainStore(keychain_service(env, directory)))
|
|
575
|
+
backends.append(FileStore(directory))
|
|
576
|
+
return CredentialStore(backends, warn)
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def _load(ctx: Context, issuer: str) -> Credentials | None:
|
|
580
|
+
try:
|
|
581
|
+
return ctx.store.load(issuer)
|
|
582
|
+
except StoreError as exc:
|
|
583
|
+
raise CliError("credential_store_error", str(exc)) from None
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def stored_credentials(ctx: Context) -> Credentials:
|
|
587
|
+
"""This server's credentials, or ``auth_required``: no network is touched first,
|
|
588
|
+
and a token is only ever sent to the issuer it was issued by."""
|
|
589
|
+
creds = _load(ctx, ctx.server)
|
|
590
|
+
if creds is None or creds.issuer != ctx.server or creds.resource != resource_for(ctx.server):
|
|
591
|
+
raise auth_required()
|
|
592
|
+
return creds
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def _save(ctx: Context, creds: Credentials, after: int = 0) -> Credentials:
|
|
596
|
+
try:
|
|
597
|
+
return ctx.store.save(creds, after)
|
|
598
|
+
except StoreError as exc:
|
|
599
|
+
raise CliError("credential_store_error", f"cannot store the credentials: {exc}") from None
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def token_credentials(ctx: Context, endpoints: Endpoints, reply: Response, fallback_refresh: str | None = None) -> Credentials:
|
|
603
|
+
"""Validate a token endpoint answer. Never echoes any part of the body."""
|
|
604
|
+
body = reply.json() or {}
|
|
605
|
+
access = body.get("access_token")
|
|
606
|
+
refresh = body.get("refresh_token", fallback_refresh)
|
|
607
|
+
expires_in = body.get("expires_in")
|
|
608
|
+
scope = body.get("scope", "")
|
|
609
|
+
bearer = str(body.get("token_type", "")).lower() == "bearer"
|
|
610
|
+
lifetime_ok = isinstance(expires_in, int) and not isinstance(expires_in, bool) and expires_in >= 1
|
|
611
|
+
usable = (
|
|
612
|
+
reply.status == 200 and bearer and lifetime_ok
|
|
613
|
+
and isinstance(access, str) and isinstance(refresh, str) and isinstance(scope, str)
|
|
614
|
+
)
|
|
615
|
+
if not usable:
|
|
616
|
+
raise CliError("server_error", "the token endpoint sent an unusable answer")
|
|
617
|
+
return Credentials(
|
|
618
|
+
endpoints.issuer, FIRST_PARTY_CLIENT_ID, endpoints.resource, access,
|
|
619
|
+
ctx.clock() + expires_in, refresh, scope,
|
|
620
|
+
)
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def oauth_error_code(reply: Response) -> str:
|
|
624
|
+
return safe_code((reply.json() or {}).get("error"), "unknown")
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def revoke(endpoints: Endpoints, creds: Credentials) -> Response:
|
|
628
|
+
"""Ask the server to end the grant behind ``creds`` (RFC 7009)."""
|
|
629
|
+
return http_request(
|
|
630
|
+
"POST", endpoints.revocation, form={"client_id": creds.client_id, "token": creds.refresh_token}
|
|
631
|
+
)
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def refresh_credentials(ctx: Context, endpoints: Endpoints, stale: Credentials) -> Credentials:
|
|
635
|
+
"""Trade the refresh token for a new pair and store the rotated one before anything uses it.
|
|
636
|
+
|
|
637
|
+
A pair another process already rotated while we waited for the lock is reused, and a dead grant
|
|
638
|
+
(revoked, expired or reused) is deleted locally.
|
|
639
|
+
"""
|
|
640
|
+
with ctx.store.lock(ctx.config_dir):
|
|
641
|
+
current = _load(ctx, endpoints.issuer)
|
|
642
|
+
if current is None:
|
|
643
|
+
raise auth_required()
|
|
644
|
+
if current.refresh_token != stale.refresh_token:
|
|
645
|
+
return current
|
|
646
|
+
reply = http_request("POST", endpoints.token, form={
|
|
647
|
+
"grant_type": "refresh_token", "client_id": current.client_id,
|
|
648
|
+
"refresh_token": current.refresh_token, "resource": endpoints.resource,
|
|
649
|
+
})
|
|
650
|
+
if reply.status in (400, 401) and oauth_error_code(reply) in ("invalid_grant", "invalid_client"):
|
|
651
|
+
with contextlib.suppress(StoreError):
|
|
652
|
+
ctx.store.delete(endpoints.issuer)
|
|
653
|
+
raise auth_required("Your session has ended. Run `revemaker login`.")
|
|
654
|
+
fresh = token_credentials(ctx, endpoints, reply, fallback_refresh=current.refresh_token)
|
|
655
|
+
return _save(ctx, fresh, current.generation)
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def authorized_call(ctx: Context, endpoints: Endpoints, method: str, path: str, json_body: dict | None = None) -> Response:
|
|
659
|
+
"""Call ``/v1`` with a fresh token, refreshing once if the server says the token is no good."""
|
|
660
|
+
creds = stored_credentials(ctx)
|
|
661
|
+
if creds.access_expires_at - REFRESH_SKEW_SECONDS <= ctx.clock():
|
|
662
|
+
creds = refresh_credentials(ctx, endpoints, creds)
|
|
663
|
+
request_options = {}
|
|
664
|
+
if json_body is not None:
|
|
665
|
+
request_options["json_body"] = json_body
|
|
666
|
+
if path == "/v1/video-imports":
|
|
667
|
+
request_options["timeout"] = 150
|
|
668
|
+
reply = http_request(method, endpoints.issuer + path, token=creds.access_token, **request_options)
|
|
669
|
+
if reply.status == 401:
|
|
670
|
+
creds = refresh_credentials(ctx, endpoints, creds)
|
|
671
|
+
reply = http_request(method, endpoints.issuer + path, token=creds.access_token, **request_options)
|
|
672
|
+
return reply
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
def fetch_account(ctx: Context, endpoints: Endpoints) -> dict:
|
|
676
|
+
reply = authorized_call(ctx, endpoints, "GET", "/v1/account")
|
|
677
|
+
body = reply.json()
|
|
678
|
+
if reply.status == 401:
|
|
679
|
+
raise auth_required("The server did not accept your session. Run `revemaker login`.")
|
|
680
|
+
if reply.status == 200 and body is not None:
|
|
681
|
+
return body
|
|
682
|
+
problem = body or {}
|
|
683
|
+
message = problem.get("message")
|
|
684
|
+
raise CliError(
|
|
685
|
+
safe_code(problem.get("code"), "server_error"),
|
|
686
|
+
message[:200] if isinstance(message, str) else f"the server answered {reply.status}",
|
|
687
|
+
)
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
def show_account(ctx: Context, account: dict, headline: str | None = None) -> None:
|
|
691
|
+
if ctx.json_mode:
|
|
692
|
+
print(json.dumps(account, sort_keys=True), file=ctx.out)
|
|
693
|
+
return
|
|
694
|
+
if headline:
|
|
695
|
+
ctx.say(headline)
|
|
696
|
+
ctx.say(f"Plan: {account.get('plan')} ({account.get('status')})")
|
|
697
|
+
ctx.say(f"Balance: {account.get('balance')} credits")
|
|
698
|
+
if account.get("account_status") not in (None, "active"):
|
|
699
|
+
ctx.say(f"Account: {account.get('account_status')}")
|
|
700
|
+
if account.get("resets_at"):
|
|
701
|
+
ctx.say(f"Resets: {account['resets_at']}")
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
_PAGE = (
|
|
705
|
+
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>revemaker CLI</title></head>"
|
|
706
|
+
"<body style=\"font:16px system-ui,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem\">"
|
|
707
|
+
"<h1>{title}</h1><p>{text}</p></body></html>"
|
|
708
|
+
)
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
class _CallbackServer(http.server.ThreadingHTTPServer):
|
|
712
|
+
daemon_threads = True
|
|
713
|
+
|
|
714
|
+
def __init__(self, state: str, issuer: str) -> None:
|
|
715
|
+
super().__init__(("127.0.0.1", 0), _CallbackHandler)
|
|
716
|
+
self.state = state
|
|
717
|
+
self.issuer = issuer
|
|
718
|
+
self.done = threading.Event()
|
|
719
|
+
self.lock = threading.Lock()
|
|
720
|
+
self.result: dict[str, str] | None = None
|
|
721
|
+
self.failure: CliError | None = None
|
|
722
|
+
|
|
723
|
+
@property
|
|
724
|
+
def redirect_uri(self) -> str:
|
|
725
|
+
return f"http://127.0.0.1:{self.server_address[1]}/callback"
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
class _CallbackHandler(http.server.BaseHTTPRequestHandler):
|
|
729
|
+
"""``timeout`` keeps a browser's idle pre-connection from holding a thread forever."""
|
|
730
|
+
|
|
731
|
+
server: _CallbackServer
|
|
732
|
+
timeout = 10
|
|
733
|
+
|
|
734
|
+
def log_message(self, format: str, *args: Any) -> None:
|
|
735
|
+
"""Silent: the request line carries the code."""
|
|
736
|
+
return
|
|
737
|
+
|
|
738
|
+
def _page(self, status: int, title: str, text: str) -> None:
|
|
739
|
+
body = _PAGE.format(title=title, text=text).encode("utf-8")
|
|
740
|
+
self.send_response(status)
|
|
741
|
+
for name, value in (
|
|
742
|
+
("Content-Type", "text/html; charset=utf-8"), ("Content-Length", str(len(body))),
|
|
743
|
+
("Cache-Control", "no-store"), ("Referrer-Policy", "no-referrer"),
|
|
744
|
+
("X-Content-Type-Options", "nosniff"),
|
|
745
|
+
("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'"),
|
|
746
|
+
("Connection", "close"),
|
|
747
|
+
):
|
|
748
|
+
self.send_header(name, value)
|
|
749
|
+
self.end_headers()
|
|
750
|
+
self.wfile.write(body)
|
|
751
|
+
|
|
752
|
+
def do_GET(self) -> None:
|
|
753
|
+
parts = urllib.parse.urlsplit(self.path)
|
|
754
|
+
port = self.server.server_address[1]
|
|
755
|
+
if parts.path != "/callback" or self.headers.get("Host") != f"127.0.0.1:{port}":
|
|
756
|
+
self._page(404, "Not found", "Nothing here.")
|
|
757
|
+
return
|
|
758
|
+
query = {k: v[0] for k, v in urllib.parse.parse_qs(parts.query, keep_blank_values=True).items()}
|
|
759
|
+
with self.server.lock:
|
|
760
|
+
if self.server.done.is_set():
|
|
761
|
+
self._page(400, "Already finished", "This sign-in has already finished. Return to the terminal.")
|
|
762
|
+
return
|
|
763
|
+
failure = self._check(query)
|
|
764
|
+
if failure is None:
|
|
765
|
+
self.server.result = query
|
|
766
|
+
else:
|
|
767
|
+
self.server.failure = failure
|
|
768
|
+
self.server.done.set()
|
|
769
|
+
if failure is None:
|
|
770
|
+
self._page(200, "Signed in", "You can close this tab and return to the terminal.")
|
|
771
|
+
else:
|
|
772
|
+
self._page(400, "Sign-in did not finish", "Return to the terminal for details. You can close this tab.")
|
|
773
|
+
|
|
774
|
+
def _check(self, query: dict[str, str]) -> CliError | None:
|
|
775
|
+
"""State first, then iss, then an error or a code; nothing is trusted before that."""
|
|
776
|
+
if not hmac.compare_digest(query.get("state", "").encode(), self.server.state.encode()):
|
|
777
|
+
return CliError("login_failed", "sign-in was refused: the response did not match this login (state)")
|
|
778
|
+
if not hmac.compare_digest(query.get("iss", "").encode(), self.server.issuer.encode()):
|
|
779
|
+
return CliError("login_failed", "sign-in was refused: the response came from an unexpected issuer (iss)")
|
|
780
|
+
if "error" in query:
|
|
781
|
+
return CliError("login_failed", f"sign-in was not completed ({safe_code(query['error'], 'unknown')})")
|
|
782
|
+
if not query.get("code"):
|
|
783
|
+
return CliError("login_failed", "sign-in was refused: the response had no authorization code")
|
|
784
|
+
return None
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
def run_login(ctx: Context) -> int:
|
|
788
|
+
endpoints = discover(ctx.server)
|
|
789
|
+
state = secrets.token_urlsafe(24)
|
|
790
|
+
verifier = secrets.token_urlsafe(48)
|
|
791
|
+
try:
|
|
792
|
+
listener = _CallbackServer(state, endpoints.issuer)
|
|
793
|
+
except OSError as exc:
|
|
794
|
+
raise CliError("login_failed", f"cannot listen on 127.0.0.1: {type(exc).__name__}") from None
|
|
795
|
+
thread = threading.Thread(target=listener.serve_forever, kwargs={"poll_interval": LISTENER_POLL_SECONDS}, daemon=True)
|
|
796
|
+
thread.start()
|
|
797
|
+
try:
|
|
798
|
+
url = endpoints.authorization + "?" + urllib.parse.urlencode({
|
|
799
|
+
"response_type": "code", "client_id": FIRST_PARTY_CLIENT_ID, "redirect_uri": listener.redirect_uri,
|
|
800
|
+
"state": state, "scope": SCOPE, "code_challenge": pkce_challenge(verifier),
|
|
801
|
+
"code_challenge_method": "S256", "resource": endpoints.resource,
|
|
802
|
+
})
|
|
803
|
+
ctx.note("Opening your browser to sign in...")
|
|
804
|
+
try:
|
|
805
|
+
opened = ctx.opener(url)
|
|
806
|
+
except Exception: # noqa: BLE001
|
|
807
|
+
opened = False
|
|
808
|
+
if not opened:
|
|
809
|
+
ctx.note(f"Could not open a browser. Open this address to continue:\n{url}")
|
|
810
|
+
if not listener.done.wait(ctx.login_timeout):
|
|
811
|
+
raise CliError("login_timeout", f"timed out after {ctx.login_timeout:g} seconds waiting for the browser")
|
|
812
|
+
if listener.failure is not None:
|
|
813
|
+
raise listener.failure
|
|
814
|
+
query = listener.result or {}
|
|
815
|
+
finally:
|
|
816
|
+
listener.shutdown()
|
|
817
|
+
listener.server_close()
|
|
818
|
+
|
|
819
|
+
reply = http_request("POST", endpoints.token, form={
|
|
820
|
+
"grant_type": "authorization_code", "client_id": FIRST_PARTY_CLIENT_ID, "code": query["code"],
|
|
821
|
+
"redirect_uri": listener.redirect_uri, "code_verifier": verifier, "resource": endpoints.resource,
|
|
822
|
+
})
|
|
823
|
+
if reply.status != 200 and reply.json() is not None:
|
|
824
|
+
raise CliError("login_failed", f"the server refused the sign-in ({oauth_error_code(reply)})")
|
|
825
|
+
return finish_login(ctx, endpoints, reply)
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
def finish_login(ctx: Context, endpoints: Endpoints, reply: Response) -> int:
|
|
829
|
+
"""Store the new grant, then end any older one so it cannot linger."""
|
|
830
|
+
creds = token_credentials(ctx, endpoints, reply)
|
|
831
|
+
with ctx.store.lock(ctx.config_dir):
|
|
832
|
+
try:
|
|
833
|
+
previous = ctx.store.load(endpoints.issuer)
|
|
834
|
+
except StoreError:
|
|
835
|
+
previous = None
|
|
836
|
+
_save(ctx, creds, previous.generation if previous else 0)
|
|
837
|
+
if previous is not None and previous.refresh_token != creds.refresh_token:
|
|
838
|
+
with contextlib.suppress(CliError):
|
|
839
|
+
revoke(endpoints, previous)
|
|
840
|
+
show_account(ctx, fetch_account(ctx, endpoints), headline="Signed in.")
|
|
841
|
+
return 0
|
|
842
|
+
|
|
843
|
+
|
|
844
|
+
def run_device_login(ctx: Context, automation: bool = False) -> int:
|
|
845
|
+
"""RFC 8628: no browser launcher or listening socket on this computer.
|
|
846
|
+
|
|
847
|
+
The deadline is the server's lifetime, not the loopback login timeout; polling slows after network timeouts.
|
|
848
|
+
"""
|
|
849
|
+
endpoints = discover(ctx.server)
|
|
850
|
+
if endpoints.device_authorization is None:
|
|
851
|
+
raise CliError("login_failed", "this server does not offer device sign-in")
|
|
852
|
+
reply = http_request("POST", endpoints.device_authorization, form={
|
|
853
|
+
"client_id": FIRST_PARTY_CLIENT_ID, "resource": endpoints.resource,
|
|
854
|
+
"scope": SCOPE + (" " + SCOPE_AUTOMATION if automation else ""),
|
|
855
|
+
})
|
|
856
|
+
if reply.status != 200:
|
|
857
|
+
raise CliError("login_failed", f"the server refused device sign-in ({oauth_error_code(reply)})")
|
|
858
|
+
body = reply.json() or {}
|
|
859
|
+
device, user = body.get("device_code"), body.get("user_code")
|
|
860
|
+
uri, expires, interval = body.get("verification_uri"), body.get("expires_in"), body.get("interval", 5)
|
|
861
|
+
if (not all(isinstance(v, str) and v and not any(ord(c) < 32 or ord(c) == 127 for c in v)
|
|
862
|
+
for v in (device, user, uri))
|
|
863
|
+
or not uri.startswith(endpoints.issuer + "/")
|
|
864
|
+
or any(not isinstance(v, int) or isinstance(v, bool) or v <= 0 for v in (expires, interval))):
|
|
865
|
+
raise CliError("server_error", "the device endpoint sent an unusable answer")
|
|
866
|
+
ctx.note(f"Open {uri} in a browser on any device. Enter code: {user}")
|
|
867
|
+
deadline = time.monotonic() + expires
|
|
868
|
+
while True:
|
|
869
|
+
remaining = deadline - time.monotonic()
|
|
870
|
+
if remaining <= interval:
|
|
871
|
+
time.sleep(max(remaining, 0))
|
|
872
|
+
raise CliError("expired_token", "device sign-in expired; run revemaker login --device again")
|
|
873
|
+
time.sleep(interval)
|
|
874
|
+
try:
|
|
875
|
+
reply = http_request("POST", endpoints.token, form={
|
|
876
|
+
"grant_type": DEVICE_GRANT,
|
|
877
|
+
"client_id": FIRST_PARTY_CLIENT_ID, "device_code": device, "resource": endpoints.resource,
|
|
878
|
+
})
|
|
879
|
+
except CliError as exc:
|
|
880
|
+
if exc.code != "network_error":
|
|
881
|
+
raise
|
|
882
|
+
interval *= 2
|
|
883
|
+
continue
|
|
884
|
+
if reply.status == 200:
|
|
885
|
+
return finish_login(ctx, endpoints, reply)
|
|
886
|
+
code = oauth_error_code(reply)
|
|
887
|
+
if code == "slow_down":
|
|
888
|
+
interval += 5
|
|
889
|
+
elif code != "authorization_pending":
|
|
890
|
+
raise CliError(code, f"device sign-in ended ({code}); run revemaker login --device to start again")
|
|
891
|
+
|
|
892
|
+
|
|
893
|
+
def run_logout(ctx: Context, local_only: bool) -> int:
|
|
894
|
+
with ctx.store.lock(ctx.config_dir):
|
|
895
|
+
creds = stored_credentials(ctx)
|
|
896
|
+
if not local_only:
|
|
897
|
+
reply = revoke(discover(ctx.server), creds)
|
|
898
|
+
if reply.status != 200:
|
|
899
|
+
raise CliError(
|
|
900
|
+
"revoke_failed",
|
|
901
|
+
"the server did not confirm the sign-out, so your credentials were kept; "
|
|
902
|
+
"try again, or run `revemaker logout --local` to remove them without the server",
|
|
903
|
+
)
|
|
904
|
+
try:
|
|
905
|
+
ctx.store.delete(creds.issuer)
|
|
906
|
+
except StoreError as exc:
|
|
907
|
+
raise CliError("credential_store_error", f"cannot remove the local credentials: {exc}") from None
|
|
908
|
+
if ctx.json_mode:
|
|
909
|
+
print(json.dumps({"signed_out": True, "revoked": not local_only}), file=ctx.out)
|
|
910
|
+
else:
|
|
911
|
+
ctx.say("Removed the local credentials (the server was not told)." if local_only else "Signed out.")
|
|
912
|
+
return 0
|
|
913
|
+
|
|
914
|
+
|
|
915
|
+
def run_account(ctx: Context) -> int:
|
|
916
|
+
"""Show the account; signed out fails before any network call."""
|
|
917
|
+
stored_credentials(ctx)
|
|
918
|
+
show_account(ctx, fetch_account(ctx, discover(ctx.server)))
|
|
919
|
+
return 0
|
|
920
|
+
|
|
921
|
+
|
|
922
|
+
def api_result(reply: Response) -> dict:
|
|
923
|
+
body = reply.json() or {}
|
|
924
|
+
if reply.status >= 400:
|
|
925
|
+
raise CliError(safe_code(body.get("code"), "server_error"),
|
|
926
|
+
str(body.get("message", "The server refused this request."))[:200],
|
|
927
|
+
action=body.get("action") if isinstance(body.get("action"), dict) else None)
|
|
928
|
+
return body
|
|
929
|
+
|
|
930
|
+
|
|
931
|
+
def check_transfer_url(url: str) -> None:
|
|
932
|
+
p = urllib.parse.urlsplit(url)
|
|
933
|
+
if not (p.scheme == "https" or (p.scheme == "http" and is_loopback(p.hostname or ""))):
|
|
934
|
+
raise CliError("unsafe_url", "The server returned an unsafe transfer URL.")
|
|
935
|
+
if p.username or p.password or not p.hostname:
|
|
936
|
+
raise CliError("unsafe_url", "The server returned an unsafe transfer URL.")
|
|
937
|
+
|
|
938
|
+
|
|
939
|
+
def transfer(method: str, url: str, *, data: bytes | None = None, headers=None) -> Response:
|
|
940
|
+
check_transfer_url(url)
|
|
941
|
+
return http_request(method, url, data=data, headers=headers, timeout=TRANSFER_SECONDS, max_body_bytes=MAX_TRANSFER_BYTES)
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
def with_key(ctx: Context, args, body: dict) -> dict:
|
|
945
|
+
"""``body`` with this run's idempotency key: the one given, or a new one printed to stderr first so a
|
|
946
|
+
lost reply can be retried with ``--idempotency-key`` (the server runs and charges once per key)."""
|
|
947
|
+
key = args.idempotency_key
|
|
948
|
+
if key is None:
|
|
949
|
+
key = str(uuid.uuid4())
|
|
950
|
+
print(f"idempotency key: {key} (retry this run with --idempotency-key {key})", file=ctx.err)
|
|
951
|
+
return {**body, "idempotency_key": key}
|
|
952
|
+
|
|
953
|
+
|
|
954
|
+
def write_new(path: Path, data: bytes) -> None:
|
|
955
|
+
try:
|
|
956
|
+
with path.open("xb") as file:
|
|
957
|
+
file.write(data)
|
|
958
|
+
except OSError:
|
|
959
|
+
raise CliError("file_error", "Cannot create output file (existing files are not overwritten).") from None
|
|
960
|
+
|
|
961
|
+
|
|
962
|
+
DOWNLOAD_CHUNK_BYTES = 1 << 20
|
|
963
|
+
|
|
964
|
+
|
|
965
|
+
def save_result(job: dict, path: Path) -> str:
|
|
966
|
+
"""Download a finished job's result through its signed URL into a new file at ``path``.
|
|
967
|
+
|
|
968
|
+
The body streams to disk, never whole into memory, and must be exactly the length the
|
|
969
|
+
storage declared. It lands in a temporary sibling first and is published only when
|
|
970
|
+
complete, so a failed save leaves nothing behind and an existing file is never replaced.
|
|
971
|
+
``os.link`` fails rather than replace a file, and on a file system without hard links
|
|
972
|
+
it fails too: copying into the final name could leave a partial file there.
|
|
973
|
+
"""
|
|
974
|
+
if job.get("status") != "done" or not isinstance(job.get("signed_url"), str):
|
|
975
|
+
if job.get("result_expired"):
|
|
976
|
+
raise CliError("result_expired", "The result is no longer available.")
|
|
977
|
+
raise CliError("result_not_ready", "The job has no result to download yet; ask again later.")
|
|
978
|
+
exists = CliError("file_error", "Cannot create output file (existing files are not overwritten).")
|
|
979
|
+
if path.exists():
|
|
980
|
+
raise exists
|
|
981
|
+
url = job["signed_url"]
|
|
982
|
+
check_transfer_url(url)
|
|
983
|
+
incomplete = CliError("download_failed", "Download incomplete; run `revemaker job` again for a fresh link.")
|
|
984
|
+
part = path.with_name(f".{path.name}.{secrets.token_hex(8)}.part")
|
|
985
|
+
try:
|
|
986
|
+
with opener_for(url).open(urllib.request.Request(url, method="GET"), timeout=TRANSFER_SECONDS) as reply:
|
|
987
|
+
length = reply.headers.get("Content-Length", "")
|
|
988
|
+
if reply.status != 200 or not length.isdigit() or int(length) == 0:
|
|
989
|
+
raise incomplete
|
|
990
|
+
expected, size = int(length), 0
|
|
991
|
+
with part.open("xb") as file:
|
|
992
|
+
while chunk := reply.read(min(DOWNLOAD_CHUNK_BYTES, expected + 1 - size)):
|
|
993
|
+
size += len(chunk)
|
|
994
|
+
if size > expected:
|
|
995
|
+
raise incomplete
|
|
996
|
+
file.write(chunk)
|
|
997
|
+
if size != expected:
|
|
998
|
+
raise incomplete
|
|
999
|
+
os.link(part, path)
|
|
1000
|
+
except (urllib.error.URLError, http.client.HTTPException, ConnectionError, TimeoutError):
|
|
1001
|
+
raise incomplete from None
|
|
1002
|
+
except FileExistsError:
|
|
1003
|
+
raise exists from None
|
|
1004
|
+
except OSError:
|
|
1005
|
+
raise CliError("file_error", "Cannot write the output file.") from None
|
|
1006
|
+
finally:
|
|
1007
|
+
with contextlib.suppress(OSError):
|
|
1008
|
+
part.unlink()
|
|
1009
|
+
return str(path)
|
|
1010
|
+
|
|
1011
|
+
|
|
1012
|
+
def run_media(ctx: Context, args) -> int:
|
|
1013
|
+
"""Run a media command; image-to-video's image and prompt are each optional, and the gate refuses a call with neither."""
|
|
1014
|
+
stored_credentials(ctx)
|
|
1015
|
+
endpoints = discover(ctx.server)
|
|
1016
|
+
def call(method, path, body=None):
|
|
1017
|
+
return api_result(authorized_call(ctx, endpoints, method, path, body))
|
|
1018
|
+
if args.command == "upload":
|
|
1019
|
+
path = Path(args.file)
|
|
1020
|
+
try:
|
|
1021
|
+
size = path.stat().st_size
|
|
1022
|
+
kind = args.type or MEDIA_EXTENSIONS.get(path.suffix.lower()) or "application/octet-stream"
|
|
1023
|
+
result = call("POST", "/v1/assets", {"filename": path.name, "size": size, "content_type": kind})
|
|
1024
|
+
reply = transfer("PUT", result["upload_url"], data=path.read_bytes(), headers=result.get("upload_headers"))
|
|
1025
|
+
if reply.status >= 400:
|
|
1026
|
+
raise CliError("upload_failed", "Upload failed; create a fresh upload before trying again.")
|
|
1027
|
+
result = call("GET", "/v1/assets/" + result["asset_id"])
|
|
1028
|
+
except OSError:
|
|
1029
|
+
raise CliError("file_error", "Cannot read the selected file.") from None
|
|
1030
|
+
elif args.command == "import-video":
|
|
1031
|
+
result = call("POST", "/v1/video-imports", {"url": args.url})
|
|
1032
|
+
elif args.command == "asset":
|
|
1033
|
+
result = call("GET", "/v1/assets/" + urllib.parse.quote(args.asset_id, safe=""))
|
|
1034
|
+
elif args.command == "transcribe":
|
|
1035
|
+
result = call("POST", "/v1/jobs/transcribe", with_key(ctx, args, {"asset_id": args.asset_id, "language": args.language}))
|
|
1036
|
+
elif args.command == "image-to-video":
|
|
1037
|
+
body = {name: value for name, value in (("image", args.asset_id), ("prompt", args.prompt), ("model", args.model))
|
|
1038
|
+
if value is not None}
|
|
1039
|
+
result = call("POST", "/v1/jobs/image-to-video", with_key(ctx, args, body))
|
|
1040
|
+
elif args.command == "job":
|
|
1041
|
+
result = call("GET", "/v1/jobs/" + urllib.parse.quote(args.job_id, safe=""))
|
|
1042
|
+
if args.output:
|
|
1043
|
+
result["saved_to"] = save_result(result, Path(args.output))
|
|
1044
|
+
else:
|
|
1045
|
+
result = call("POST", "/v1/jobs/" + urllib.parse.quote(args.job_id, safe="") + "/export",
|
|
1046
|
+
{"format": args.format, "script": args.script, "speakers": not args.no_speakers,
|
|
1047
|
+
"timestamps": not args.no_timestamps})
|
|
1048
|
+
if args.output:
|
|
1049
|
+
reply = transfer("GET", result["download_url"])
|
|
1050
|
+
if reply.status != 200 or len(reply.body) != result["size"]:
|
|
1051
|
+
raise CliError("download_failed", "Download incomplete; request a fresh export.")
|
|
1052
|
+
write_new(Path(args.output), reply.body)
|
|
1053
|
+
result["saved_to"] = args.output
|
|
1054
|
+
print(json.dumps(result, ensure_ascii=False, sort_keys=True), file=ctx.out)
|
|
1055
|
+
return 0
|
|
1056
|
+
|
|
1057
|
+
|
|
1058
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
1059
|
+
parser = argparse.ArgumentParser(prog="revemaker", description="revemaker command line client.")
|
|
1060
|
+
parser.add_argument("--version", action="version", version=f"revemaker {__version__}")
|
|
1061
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
1062
|
+
common.add_argument("--json", action="store_true", help="machine-readable output, errors included")
|
|
1063
|
+
common.add_argument("--server", help=f"server URL (default: ${SERVER_ENV} or {default_server()})")
|
|
1064
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
1065
|
+
login = commands.add_parser("login", parents=[common], help="sign in through the browser or a device code")
|
|
1066
|
+
login.add_argument("--device", action="store_true", help="show a code for approval in any browser")
|
|
1067
|
+
login.add_argument("--automation", action="store_true", help="request unattended access (requires --device and server opt-in)")
|
|
1068
|
+
logout = commands.add_parser("logout", parents=[common], help="revoke this sign-in and remove it from this computer")
|
|
1069
|
+
logout.add_argument("--local", action="store_true", help="remove local credentials without telling the server")
|
|
1070
|
+
commands.add_parser("account", parents=[common], help="show your plan and credit balance")
|
|
1071
|
+
upload = commands.add_parser("upload", parents=[common], help="upload a media file; poll its asset until ready")
|
|
1072
|
+
upload.add_argument("file")
|
|
1073
|
+
upload.add_argument("--type", help="media MIME type")
|
|
1074
|
+
imp = commands.add_parser("import-video", parents=[common], help="import a public HTTPS video, or the captions of a public YouTube URL")
|
|
1075
|
+
imp.add_argument("url")
|
|
1076
|
+
transcribe = commands.add_parser("transcribe", parents=[common], help="transcribe a ready asset: one call runs and charges")
|
|
1077
|
+
transcribe.add_argument("asset_id")
|
|
1078
|
+
transcribe.add_argument("--language", choices=("auto", "en", "es", "zh"), default="auto",
|
|
1079
|
+
help="YouTube captions require auto and keep their original language")
|
|
1080
|
+
transcribe.add_argument("--idempotency-key", help="retry key for this run; a new one is printed when omitted")
|
|
1081
|
+
video = commands.add_parser("image-to-video", parents=[common],
|
|
1082
|
+
help="make a video from an image, a prompt or both: one call runs and charges")
|
|
1083
|
+
video.add_argument("asset_id", nargs="?", help="optional: a ready image from `revemaker upload`, the first frame")
|
|
1084
|
+
video.add_argument("--prompt", help="optional: the motion and scene the video should show")
|
|
1085
|
+
video.add_argument("--model", choices=("standard", "lite", "premium"), help="omit for lite")
|
|
1086
|
+
video.add_argument("--idempotency-key", help="retry key for this run; a new one is printed when omitted")
|
|
1087
|
+
job = commands.add_parser("job", parents=[common], help="read a job's status and result")
|
|
1088
|
+
job.add_argument("job_id")
|
|
1089
|
+
job.add_argument("--output", help="save a finished result to this new file")
|
|
1090
|
+
export = commands.add_parser("export", parents=[common], help="export a finished transcript without retranscribing")
|
|
1091
|
+
export.add_argument("job_id")
|
|
1092
|
+
export.add_argument("--format", choices=("txt", "srt", "vtt"), default="txt")
|
|
1093
|
+
export.add_argument("--script", choices=("original", "zh-CN", "zh-TW"), default="original")
|
|
1094
|
+
export.add_argument("--no-speakers", action="store_true")
|
|
1095
|
+
export.add_argument("--no-timestamps", action="store_true")
|
|
1096
|
+
export.add_argument("--output")
|
|
1097
|
+
asset = commands.add_parser("asset", parents=[common], help="check upload readiness")
|
|
1098
|
+
asset.add_argument("asset_id")
|
|
1099
|
+
return parser
|
|
1100
|
+
|
|
1101
|
+
|
|
1102
|
+
def main(
|
|
1103
|
+
argv: list[str] | None = None,
|
|
1104
|
+
*,
|
|
1105
|
+
env: Mapping[str, str] | None = None,
|
|
1106
|
+
out: IO[str] | None = None,
|
|
1107
|
+
err: IO[str] | None = None,
|
|
1108
|
+
opener: Callable[[str], bool] | None = None,
|
|
1109
|
+
clock: Callable[[], float] = time.time,
|
|
1110
|
+
login_timeout: float = LOGIN_TIMEOUT_SECONDS,
|
|
1111
|
+
) -> int:
|
|
1112
|
+
"""Run the CLI and return its exit status.
|
|
1113
|
+
|
|
1114
|
+
A StoreError reaches the handler only from the refresh lock; reads and writes report their own.
|
|
1115
|
+
``server`` is set before any call can be refused, so a next-step URL is shown only on that origin
|
|
1116
|
+
and only when it is ASCII and printable: nothing that could drive the terminal.
|
|
1117
|
+
"""
|
|
1118
|
+
env = os.environ if env is None else env
|
|
1119
|
+
out, err = out or sys.stdout, err or sys.stderr
|
|
1120
|
+
args = build_parser().parse_args(argv)
|
|
1121
|
+
json_mode = bool(args.json)
|
|
1122
|
+
server = ""
|
|
1123
|
+
try:
|
|
1124
|
+
server = normalize_server_url(args.server or env.get(SERVER_ENV) or default_server())
|
|
1125
|
+
directory = config_dir(env)
|
|
1126
|
+
ctx = Context(
|
|
1127
|
+
out, err, json_mode, opener or webbrowser.open, clock, login_timeout, server, directory,
|
|
1128
|
+
make_store(env, directory, lambda message: print(message, file=err)),
|
|
1129
|
+
)
|
|
1130
|
+
if args.command == "login":
|
|
1131
|
+
if args.automation and not args.device:
|
|
1132
|
+
raise CliError("invalid_request", "--automation requires --device")
|
|
1133
|
+
return run_device_login(ctx, args.automation) if args.device else run_login(ctx)
|
|
1134
|
+
if args.command == "logout":
|
|
1135
|
+
return run_logout(ctx, args.local)
|
|
1136
|
+
if args.command == "account":
|
|
1137
|
+
return run_account(ctx)
|
|
1138
|
+
return run_media(ctx, args)
|
|
1139
|
+
except (CliError, StoreError) as exc:
|
|
1140
|
+
error = exc if isinstance(exc, CliError) else CliError("credential_store_error", str(exc))
|
|
1141
|
+
if json_mode:
|
|
1142
|
+
print(json.dumps(error.body(), sort_keys=True), file=out)
|
|
1143
|
+
else:
|
|
1144
|
+
print(f"error: {error.code}: {error.message}", file=err)
|
|
1145
|
+
url = (error.action or {}).get("url")
|
|
1146
|
+
if (isinstance(url, str) and server and url.startswith(server + "/")
|
|
1147
|
+
and url.isascii() and url.isprintable()):
|
|
1148
|
+
print(f"next step: {url}", file=err)
|
|
1149
|
+
return error.exit_code
|
|
1150
|
+
except KeyboardInterrupt:
|
|
1151
|
+
print("interrupted", file=err)
|
|
1152
|
+
return 130
|
|
1153
|
+
|
|
1154
|
+
|
|
1155
|
+
if __name__ == "__main__":
|
|
1156
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Wire contract the server, the standard-library CLI and the web frontends share
|
|
2
|
+
(issues #98, #99, #211).
|
|
3
|
+
|
|
4
|
+
The published CLI package ships this module, not ``config``: it holds nothing
|
|
5
|
+
but wire names and standard-library checks, so no server setting, model name
|
|
6
|
+
or plan amount reaches the package. Product frontends may import it (and the
|
|
7
|
+
other leaves listed in ``test_layering.FRONTEND_MAY_IMPORT``) but no server module.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import base64
|
|
13
|
+
import hashlib
|
|
14
|
+
import ipaddress
|
|
15
|
+
import urllib.parse
|
|
16
|
+
|
|
17
|
+
FIRST_PARTY_CLIENT_ID = "media-cli"
|
|
18
|
+
PLUGIN_CLIENT_ID = "revemaker-claude-code"
|
|
19
|
+
SITE_CLIENT_ID = "transcription-site"
|
|
20
|
+
SITE_SESSION_COOKIE = "transcription_session"
|
|
21
|
+
LOCAL_SITE_CLIENT_ID = "transcription-site-local"
|
|
22
|
+
PLUGIN_REDIRECT_URI = "http://localhost:38765/callback"
|
|
23
|
+
IMAGE_TYPES = ("image/png", "image/jpeg", "image/webp")
|
|
24
|
+
IMAGE_SUFFIXES = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}
|
|
25
|
+
ASSET_ID = r"ast_[0-9a-f]{32}"
|
|
26
|
+
JOB_ID = r"job_[0-9a-f]{32}"
|
|
27
|
+
ACTION_ID = r"act_[0-9a-f]{32}"
|
|
28
|
+
MAX_JSON_BODY_BYTES = 16 * 1024
|
|
29
|
+
SCOPE_AUTOMATION = "automation"
|
|
30
|
+
CREDIT_SCALE = 100
|
|
31
|
+
DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"
|
|
32
|
+
|
|
33
|
+
MEDIA_EXTENSIONS = {
|
|
34
|
+
".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp",
|
|
35
|
+
".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm", ".m4a": "audio/mp4",
|
|
36
|
+
".mp3": "audio/mpeg", ".wav": "audio/wav", ".flac": "audio/flac",
|
|
37
|
+
}
|
|
38
|
+
MEDIA_ALIASES = {
|
|
39
|
+
"audio/x-wav": "audio/wav", "audio/wave": "audio/wav", "audio/vnd.wave": "audio/wav",
|
|
40
|
+
"audio/x-flac": "audio/flac", "audio/x-m4a": "audio/mp4", "audio/m4a": "audio/mp4",
|
|
41
|
+
"audio/mp4a-latm": "audio/mp4", "audio/mp3": "audio/mpeg", "audio/x-mpeg": "audio/mpeg",
|
|
42
|
+
"image/jpg": "image/jpeg",
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
def credit_value(minor: int) -> int | float:
|
|
46
|
+
"""Publish an integer hundredth-credit amount as JSON credits."""
|
|
47
|
+
credits, remainder = divmod(minor, CREDIT_SCALE)
|
|
48
|
+
return credits if remainder == 0 else minor / CREDIT_SCALE
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def canonical_media_type(content_type: str) -> str:
|
|
52
|
+
return MEDIA_ALIASES.get(content_type, content_type)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def is_loopback(host: str) -> bool:
|
|
56
|
+
if host == "localhost":
|
|
57
|
+
return True
|
|
58
|
+
try:
|
|
59
|
+
return ipaddress.ip_address(host).is_loopback
|
|
60
|
+
except ValueError:
|
|
61
|
+
return False
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def pkce_challenge(verifier: str) -> str:
|
|
65
|
+
"""The S256 code challenge for a verifier (RFC 7636)."""
|
|
66
|
+
digest = hashlib.sha256(verifier.encode("ascii")).digest()
|
|
67
|
+
return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def normalize_server_url(value: str) -> str:
|
|
71
|
+
"""A server origin without its trailing slash. Raises ``ValueError`` unless it is a
|
|
72
|
+
bare https origin (http only on loopback); reading ``port`` raises it on a bad port."""
|
|
73
|
+
value = value.strip().rstrip("/")
|
|
74
|
+
try:
|
|
75
|
+
parts = urllib.parse.urlsplit(value)
|
|
76
|
+
parts.port # noqa: B018
|
|
77
|
+
except ValueError:
|
|
78
|
+
raise ValueError("the server URL is malformed (check the host and port)") from None
|
|
79
|
+
secure = parts.scheme == "https" or (parts.scheme == "http" and is_loopback(parts.hostname or ""))
|
|
80
|
+
if not secure or not parts.hostname or parts.path or parts.query or parts.fragment or parts.username or parts.password:
|
|
81
|
+
raise ValueError(
|
|
82
|
+
"the server URL must be an https origin (http only for 127.0.0.1 or localhost), e.g. https://media.example.com"
|
|
83
|
+
)
|
|
84
|
+
return value
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: revemaker
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: revemaker command line client: sign-in, video transcription and subtitle exports.
|
|
5
|
+
Project-URL: Homepage, https://revemaker.com
|
|
6
|
+
Project-URL: Privacy, https://revemaker.com/privacy
|
|
7
|
+
Author: Revemaker, Inc.
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: distribution/LICENSE
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Operating System :: MacOS
|
|
12
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
13
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Requires-Python: >=3.11
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# revemaker
|
|
19
|
+
|
|
20
|
+
Command line sign-in for the revemaker service, used by the revemaker plugin for Claude Code.
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
pipx install revemaker
|
|
24
|
+
revemaker login # opens your browser; revemaker login --device shows a code instead
|
|
25
|
+
revemaker account # your plan and balance
|
|
26
|
+
revemaker logout # ends this sign-in on the server and removes it here
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`revemaker` talks to the hosted service by default. Point it elsewhere with `--server URL` or the
|
|
30
|
+
`MEDIA_SERVER_URL` environment variable (an https origin; plain http only for 127.0.0.1 or localhost).
|
|
31
|
+
Add `--json` for machine-readable output, errors included.
|
|
32
|
+
|
|
33
|
+
Credentials are kept per server: in the macOS Keychain where available, otherwise in
|
|
34
|
+
`credentials.json` under `~/.config/revemaker` (`MEDIA_CONFIG_DIR` or `XDG_CONFIG_HOME` move it).
|
|
35
|
+
Tokens are never printed. Requires Python 3.11 or later on macOS, Linux or Windows.
|
|
36
|
+
|
|
37
|
+
## Video transcription
|
|
38
|
+
|
|
39
|
+
After sign-in, `revemaker upload clip.mp4` returns an asset (the type comes from the
|
|
40
|
+
extension; `--type` overrides it). Poll
|
|
41
|
+
`revemaker asset ASSET_ID` until ready, or use `revemaker import-video HTTPS_URL` for a
|
|
42
|
+
public media file, or a public YouTube URL, which returns the video's captions without speaker
|
|
43
|
+
labels (a refused import means uploading the file). `revemaker transcribe ASSET_ID --language auto` runs and
|
|
44
|
+
charges in one call. It prints a new idempotency key on stderr, or pass your own with
|
|
45
|
+
`--idempotency-key KEY`; the same key with the same arguments returns the same job and
|
|
46
|
+
charges nothing more. Poll `revemaker job JOB_ID`. Export with
|
|
47
|
+
`revemaker export JOB_ID --format srt --output subtitles.srt` or TXT/VTT. TXT accepts
|
|
48
|
+
`--no-timestamps`; all formats accept `--no-speakers` and
|
|
49
|
+
`--script original|zh-CN|zh-TW`. Exports reuse the result without retranscribing.
|
|
50
|
+
Existing output files are not overwritten. A lost reply must be retried with the same
|
|
51
|
+
key and arguments. An uncertain job must not be resubmitted.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
media_platform/__init__.py,sha256=Ko4Y64Hf9EQpPVR_L5cl5FHSVkMfRLvJI4_CAOhnjE8,228
|
|
2
|
+
media_platform/cli.py,sha256=7KiE0Lwd4lZXbUojrUYTaXvWlAN-HoQOcq8ctUG3Vgc,50200
|
|
3
|
+
media_platform/protocol.py,sha256=gnXRP5ily1OI13VamyqTJdbSouJTNjFa1E4ih0rO70I,3431
|
|
4
|
+
media_platform/hosted.json,sha256=chI16eUIoFytyWeUFULJGQw93CZhGSJDBQ5AICPWPRc,44
|
|
5
|
+
revemaker-0.1.0.dist-info/METADATA,sha256=RaMLnL5i7jvZoryCB2YfNN_V0zRUr3od6o7szkm9DKc,2558
|
|
6
|
+
revemaker-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
revemaker-0.1.0.dist-info/entry_points.txt,sha256=roi1EPq4lI-1bPFf0IBTQ-T8QbbNtN40HKdKv4WobKw,54
|
|
8
|
+
revemaker-0.1.0.dist-info/licenses/distribution/LICENSE,sha256=9CqYkAs1AN9FpmOqEr4PUZpD1j1EDVTzkEsERvGSas4,1072
|
|
9
|
+
revemaker-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Revemaker, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|