shiftmydata 0.1.0__tar.gz
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.
- shiftmydata-0.1.0/.gitignore +31 -0
- shiftmydata-0.1.0/PKG-INFO +67 -0
- shiftmydata-0.1.0/README.md +42 -0
- shiftmydata-0.1.0/pyproject.toml +51 -0
- shiftmydata-0.1.0/src/shiftmydata/__init__.py +3 -0
- shiftmydata-0.1.0/src/shiftmydata/__main__.py +3 -0
- shiftmydata-0.1.0/src/shiftmydata/api.py +274 -0
- shiftmydata-0.1.0/src/shiftmydata/cli.py +380 -0
- shiftmydata-0.1.0/src/shiftmydata/dpop.py +79 -0
- shiftmydata-0.1.0/src/shiftmydata/store.py +80 -0
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
.env
|
|
2
|
+
.env.*
|
|
3
|
+
!.env.example
|
|
4
|
+
ops/secrets/*
|
|
5
|
+
!ops/secrets/.gitkeep
|
|
6
|
+
*.pem
|
|
7
|
+
*.key
|
|
8
|
+
|
|
9
|
+
__pycache__/
|
|
10
|
+
*.py[cod]
|
|
11
|
+
.venv/
|
|
12
|
+
.pytest_cache/
|
|
13
|
+
.mypy_cache/
|
|
14
|
+
.ruff_cache/
|
|
15
|
+
.coverage
|
|
16
|
+
htmlcov/
|
|
17
|
+
|
|
18
|
+
node_modules/
|
|
19
|
+
dist/
|
|
20
|
+
*.tsbuildinfo
|
|
21
|
+
.vite/
|
|
22
|
+
|
|
23
|
+
.DS_Store
|
|
24
|
+
.idea/
|
|
25
|
+
.vscode/
|
|
26
|
+
|
|
27
|
+
# Agents' git worktrees: their work reaches main as merged branches, never as files here.
|
|
28
|
+
.claude/worktrees/
|
|
29
|
+
|
|
30
|
+
# wrangler run from the repo root caches the account here
|
|
31
|
+
.wrangler/
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: shiftmydata
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: ShiftMyData from the command line: list, copy and sync between your clouds.
|
|
5
|
+
Project-URL: Homepage, https://shiftmydata.com
|
|
6
|
+
Project-URL: Documentation, https://shiftmydata.com/developers/
|
|
7
|
+
Author: ShiftMyData
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
Keywords: backup,cli,cloud,shiftmydata,sync,transfer
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: System :: Archiving :: Backup
|
|
15
|
+
Classifier: Topic :: Utilities
|
|
16
|
+
Requires-Python: >=3.11
|
|
17
|
+
Requires-Dist: cryptography>=43
|
|
18
|
+
Requires-Dist: httpx>=0.27
|
|
19
|
+
Requires-Dist: keyring>=25
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: mypy>=1.11; extra == 'dev'
|
|
22
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
23
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# shiftmydata
|
|
27
|
+
|
|
28
|
+
ShiftMyData from the command line: list, copy, sync and save between your clouds.
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
pipx install shiftmydata # or: uv tool install shiftmydata
|
|
32
|
+
shiftmydata login # opens shiftmydata.com; check the code and allow
|
|
33
|
+
shiftmydata clouds
|
|
34
|
+
shiftmydata ls "My Drive:Projects"
|
|
35
|
+
shiftmydata cp "My Drive:Projects" "Dropbox:Backup/Projects" --watch
|
|
36
|
+
shiftmydata cp ./report.pdf "My Drive:Reports"
|
|
37
|
+
shiftmydata cp "My Drive:Reports/report.pdf" .
|
|
38
|
+
shiftmydata sync "My Drive:Photos" "OneDrive:Photos" --max-delete 50
|
|
39
|
+
shiftmydata save https://example.com/file.zip "My Drive:Downloads"
|
|
40
|
+
shiftmydata save https://example.com/article "My Drive:Reading" --as page
|
|
41
|
+
shiftmydata jobs
|
|
42
|
+
shiftmydata schedules
|
|
43
|
+
shiftmydata run "Nightly backup"
|
|
44
|
+
shiftmydata trigger "Nightly backup" --signed
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
A place is `CLOUD:PATH`: the cloud's name as the Clouds page shows it (or its id), then the
|
|
48
|
+
folder. Every command takes `--json`.
|
|
49
|
+
|
|
50
|
+
## How it signs in
|
|
51
|
+
|
|
52
|
+
`login` uses the device flow: it shows a short code and opens shiftmydata.com, where you check
|
|
53
|
+
the code and choose what the CLI may do. The sign-in is bound to a key made on this machine
|
|
54
|
+
(DPoP): the key stays in the system keyring (Keychain, Credential Manager or Secret Service),
|
|
55
|
+
or in `~/.config/shiftmydata` readable only by you when there is no keyring. A copied token is
|
|
56
|
+
useless without it. `logout` revokes the sign-in and forgets the key. To see or remove the CLI's
|
|
57
|
+
access from the website, go to Account, Developers.
|
|
58
|
+
|
|
59
|
+
`--profile NAME` keeps several sign-ins apart.
|
|
60
|
+
|
|
61
|
+
## Development
|
|
62
|
+
|
|
63
|
+
```sh
|
|
64
|
+
cd cli
|
|
65
|
+
uv venv && uv pip install -e ".[dev]"
|
|
66
|
+
ruff check . && mypy --strict src
|
|
67
|
+
```
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# shiftmydata
|
|
2
|
+
|
|
3
|
+
ShiftMyData from the command line: list, copy, sync and save between your clouds.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pipx install shiftmydata # or: uv tool install shiftmydata
|
|
7
|
+
shiftmydata login # opens shiftmydata.com; check the code and allow
|
|
8
|
+
shiftmydata clouds
|
|
9
|
+
shiftmydata ls "My Drive:Projects"
|
|
10
|
+
shiftmydata cp "My Drive:Projects" "Dropbox:Backup/Projects" --watch
|
|
11
|
+
shiftmydata cp ./report.pdf "My Drive:Reports"
|
|
12
|
+
shiftmydata cp "My Drive:Reports/report.pdf" .
|
|
13
|
+
shiftmydata sync "My Drive:Photos" "OneDrive:Photos" --max-delete 50
|
|
14
|
+
shiftmydata save https://example.com/file.zip "My Drive:Downloads"
|
|
15
|
+
shiftmydata save https://example.com/article "My Drive:Reading" --as page
|
|
16
|
+
shiftmydata jobs
|
|
17
|
+
shiftmydata schedules
|
|
18
|
+
shiftmydata run "Nightly backup"
|
|
19
|
+
shiftmydata trigger "Nightly backup" --signed
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
A place is `CLOUD:PATH`: the cloud's name as the Clouds page shows it (or its id), then the
|
|
23
|
+
folder. Every command takes `--json`.
|
|
24
|
+
|
|
25
|
+
## How it signs in
|
|
26
|
+
|
|
27
|
+
`login` uses the device flow: it shows a short code and opens shiftmydata.com, where you check
|
|
28
|
+
the code and choose what the CLI may do. The sign-in is bound to a key made on this machine
|
|
29
|
+
(DPoP): the key stays in the system keyring (Keychain, Credential Manager or Secret Service),
|
|
30
|
+
or in `~/.config/shiftmydata` readable only by you when there is no keyring. A copied token is
|
|
31
|
+
useless without it. `logout` revokes the sign-in and forgets the key. To see or remove the CLI's
|
|
32
|
+
access from the website, go to Account, Developers.
|
|
33
|
+
|
|
34
|
+
`--profile NAME` keeps several sign-ins apart.
|
|
35
|
+
|
|
36
|
+
## Development
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
cd cli
|
|
40
|
+
uv venv && uv pip install -e ".[dev]"
|
|
41
|
+
ruff check . && mypy --strict src
|
|
42
|
+
```
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "shiftmydata"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "ShiftMyData from the command line: list, copy and sync between your clouds."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.11"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
authors = [{ name = "ShiftMyData" }]
|
|
9
|
+
keywords = ["shiftmydata", "cloud", "transfer", "backup", "sync", "cli"]
|
|
10
|
+
classifiers = [
|
|
11
|
+
"Environment :: Console",
|
|
12
|
+
"Intended Audience :: End Users/Desktop",
|
|
13
|
+
"Operating System :: OS Independent",
|
|
14
|
+
"Programming Language :: Python :: 3",
|
|
15
|
+
"Topic :: System :: Archiving :: Backup",
|
|
16
|
+
"Topic :: Utilities",
|
|
17
|
+
]
|
|
18
|
+
dependencies = [
|
|
19
|
+
"httpx>=0.27",
|
|
20
|
+
"cryptography>=43",
|
|
21
|
+
"keyring>=25",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://shiftmydata.com"
|
|
26
|
+
Documentation = "https://shiftmydata.com/developers/"
|
|
27
|
+
|
|
28
|
+
[project.scripts]
|
|
29
|
+
shiftmydata = "shiftmydata.cli:main"
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
dev = ["pytest>=8", "ruff>=0.6", "mypy>=1.11"]
|
|
33
|
+
|
|
34
|
+
[build-system]
|
|
35
|
+
requires = ["hatchling>=1.25"]
|
|
36
|
+
build-backend = "hatchling.build"
|
|
37
|
+
|
|
38
|
+
[tool.hatch.build.targets.wheel]
|
|
39
|
+
packages = ["src/shiftmydata"]
|
|
40
|
+
|
|
41
|
+
[tool.ruff]
|
|
42
|
+
line-length = 96
|
|
43
|
+
target-version = "py311"
|
|
44
|
+
|
|
45
|
+
[tool.ruff.lint]
|
|
46
|
+
select = ["E", "F", "I", "B", "BLE", "UP", "S", "SIM", "RUF", "PL"]
|
|
47
|
+
ignore = ["S101", "PLR0911", "PLR0913", "PLR2004", "PLW0603"]
|
|
48
|
+
|
|
49
|
+
[tool.mypy]
|
|
50
|
+
strict = true
|
|
51
|
+
python_version = "3.11"
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""Talking to ShiftMyData's public API: the device sign-in, refreshing, and every call with a
|
|
2
|
+
DPoP proof (competitor-parity-2, 9.1). The same ``/api/v1`` the apps and integrations use."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import contextlib
|
|
7
|
+
import time
|
|
8
|
+
from collections.abc import Callable, Iterator
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, BinaryIO
|
|
11
|
+
from urllib.parse import quote
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
from . import store
|
|
16
|
+
from .dpop import ProofKey
|
|
17
|
+
|
|
18
|
+
DEFAULT_BASE = "https://shiftmydata.com"
|
|
19
|
+
CLIENT_ID = "shiftmydata-cli"
|
|
20
|
+
SCOPE = (
|
|
21
|
+
"profile clouds:read files:read files:write transfers:read transfers:write "
|
|
22
|
+
"schedules:read schedules:write workspaces:read workspaces:write offline_access"
|
|
23
|
+
)
|
|
24
|
+
#: A token this close to its end is renewed before use.
|
|
25
|
+
REFRESH_AHEAD = 60
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ApiError(Exception):
|
|
29
|
+
"""The server refused, in its own words."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, status: int, message: str) -> None:
|
|
32
|
+
super().__init__(message)
|
|
33
|
+
self.status = status
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class SignedOut(ApiError):
|
|
37
|
+
def __init__(self, message: str = "Not signed in. Run: shiftmydata login") -> None:
|
|
38
|
+
super().__init__(401, message)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Client:
|
|
42
|
+
def __init__(self, base: str = DEFAULT_BASE, profile: str = "default") -> None:
|
|
43
|
+
self.base = base.rstrip("/")
|
|
44
|
+
self.profile = profile
|
|
45
|
+
self._http = httpx.Client(timeout=httpx.Timeout(60.0, connect=10.0), trust_env=True)
|
|
46
|
+
saved = store.load("key", profile)
|
|
47
|
+
self.key = ProofKey.from_pem(saved["pem"]) if saved else None
|
|
48
|
+
self.session = store.load("session", profile)
|
|
49
|
+
|
|
50
|
+
def close(self) -> None:
|
|
51
|
+
self._http.close()
|
|
52
|
+
|
|
53
|
+
# --- signing in ---------------------------------------------------------------------------
|
|
54
|
+
|
|
55
|
+
def login(self, show: Callable[[str, str], None]) -> dict[str, Any]:
|
|
56
|
+
"""The device flow (RFC 8628): a code to type in a browser, then a DPoP-bound token."""
|
|
57
|
+
key = ProofKey.new()
|
|
58
|
+
start = self._form(
|
|
59
|
+
"/api/oauth/device_authorization", {"client_id": CLIENT_ID, "scope": SCOPE}
|
|
60
|
+
)
|
|
61
|
+
show(str(start["verification_uri_complete"]), str(start["user_code"]))
|
|
62
|
+
interval = int(start.get("interval") or 5)
|
|
63
|
+
deadline = time.monotonic() + int(start.get("expires_in") or 600)
|
|
64
|
+
while time.monotonic() < deadline:
|
|
65
|
+
time.sleep(interval)
|
|
66
|
+
url = f"{self.base}/api/oauth/token"
|
|
67
|
+
response = self._http.post(
|
|
68
|
+
url,
|
|
69
|
+
data={
|
|
70
|
+
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
|
|
71
|
+
"device_code": start["device_code"],
|
|
72
|
+
"client_id": CLIENT_ID,
|
|
73
|
+
},
|
|
74
|
+
headers={"DPoP": key.proof("POST", url)},
|
|
75
|
+
)
|
|
76
|
+
body: dict[str, Any] = _json(response)
|
|
77
|
+
if response.status_code == 200:
|
|
78
|
+
self.key = key
|
|
79
|
+
store.save("key", self.profile, {"pem": key.pem()})
|
|
80
|
+
self._keep(body)
|
|
81
|
+
return body
|
|
82
|
+
error = str(body.get("error") or "")
|
|
83
|
+
if error == "slow_down":
|
|
84
|
+
interval += 5
|
|
85
|
+
elif error != "authorization_pending":
|
|
86
|
+
raise ApiError(
|
|
87
|
+
response.status_code, str(body.get("error_description") or error)
|
|
88
|
+
)
|
|
89
|
+
raise ApiError(400, "The code expired before it was used. Run login again.")
|
|
90
|
+
|
|
91
|
+
def logout(self) -> None:
|
|
92
|
+
if self.session and self.key:
|
|
93
|
+
url = f"{self.base}/api/oauth/revoke"
|
|
94
|
+
for kind in ("refresh_token", "access_token"):
|
|
95
|
+
token = self.session.get(kind)
|
|
96
|
+
if token:
|
|
97
|
+
# Signed out here either way, whether the server heard or not.
|
|
98
|
+
with contextlib.suppress(httpx.HTTPError):
|
|
99
|
+
self._http.post(
|
|
100
|
+
url,
|
|
101
|
+
data={"token": token, "client_id": CLIENT_ID},
|
|
102
|
+
headers={"DPoP": self.key.proof("POST", url)},
|
|
103
|
+
)
|
|
104
|
+
store.forget("session", self.profile)
|
|
105
|
+
store.forget("key", self.profile)
|
|
106
|
+
self.session = None
|
|
107
|
+
self.key = None
|
|
108
|
+
|
|
109
|
+
def _keep(self, body: dict[str, Any]) -> None:
|
|
110
|
+
self.session = {
|
|
111
|
+
"access_token": body["access_token"],
|
|
112
|
+
"refresh_token": body.get("refresh_token")
|
|
113
|
+
or (self.session or {}).get("refresh_token"),
|
|
114
|
+
"expires_at": time.time() + int(body.get("expires_in") or 600),
|
|
115
|
+
"scope": body.get("scope", ""),
|
|
116
|
+
}
|
|
117
|
+
store.save("session", self.profile, self.session)
|
|
118
|
+
|
|
119
|
+
def _token(self, force: bool = False) -> str:
|
|
120
|
+
if not self.session or not self.key:
|
|
121
|
+
raise SignedOut
|
|
122
|
+
if force or float(self.session.get("expires_at") or 0) - time.time() < REFRESH_AHEAD:
|
|
123
|
+
refresh = self.session.get("refresh_token")
|
|
124
|
+
if not refresh:
|
|
125
|
+
raise SignedOut("Your sign-in has ended. Run: shiftmydata login")
|
|
126
|
+
url = f"{self.base}/api/oauth/token"
|
|
127
|
+
response = self._http.post(
|
|
128
|
+
url,
|
|
129
|
+
data={
|
|
130
|
+
"grant_type": "refresh_token",
|
|
131
|
+
"refresh_token": refresh,
|
|
132
|
+
"client_id": CLIENT_ID,
|
|
133
|
+
},
|
|
134
|
+
headers={"DPoP": self.key.proof("POST", url)},
|
|
135
|
+
)
|
|
136
|
+
if response.status_code != 200:
|
|
137
|
+
store.forget("session", self.profile)
|
|
138
|
+
self.session = None
|
|
139
|
+
raise SignedOut("Your sign-in has ended. Run: shiftmydata login")
|
|
140
|
+
self._keep(_json(response))
|
|
141
|
+
return str(self.session["access_token"])
|
|
142
|
+
|
|
143
|
+
# --- calls --------------------------------------------------------------------------------
|
|
144
|
+
|
|
145
|
+
def call(
|
|
146
|
+
self,
|
|
147
|
+
method: str,
|
|
148
|
+
path: str,
|
|
149
|
+
*,
|
|
150
|
+
params: dict[str, Any] | None = None,
|
|
151
|
+
json: Any = None,
|
|
152
|
+
content: bytes | None = None,
|
|
153
|
+
headers: dict[str, str] | None = None,
|
|
154
|
+
stream: bool = False,
|
|
155
|
+
) -> httpx.Response:
|
|
156
|
+
url = f"{self.base}{path}"
|
|
157
|
+
for attempt in (0, 1):
|
|
158
|
+
token = self._token(force=attempt == 1)
|
|
159
|
+
assert self.key is not None
|
|
160
|
+
sent = {
|
|
161
|
+
"Authorization": f"DPoP {token}",
|
|
162
|
+
"DPoP": self.key.proof(method, url, token),
|
|
163
|
+
**(headers or {}),
|
|
164
|
+
}
|
|
165
|
+
request = self._http.build_request(
|
|
166
|
+
method, url, params=params, json=json, content=content, headers=sent
|
|
167
|
+
)
|
|
168
|
+
response = self._http.send(request, stream=stream)
|
|
169
|
+
if response.status_code == 401 and attempt == 0:
|
|
170
|
+
response.close()
|
|
171
|
+
continue
|
|
172
|
+
if response.status_code >= 400:
|
|
173
|
+
body = _json(response) if not stream else {}
|
|
174
|
+
raise ApiError(response.status_code, _message(body, response.status_code))
|
|
175
|
+
return response
|
|
176
|
+
raise SignedOut
|
|
177
|
+
|
|
178
|
+
def get(self, route: str, **params: Any) -> Any:
|
|
179
|
+
clean = {k: v for k, v in params.items() if v is not None}
|
|
180
|
+
return _json(self.call("GET", f"/api/v1{route}", params=clean))
|
|
181
|
+
|
|
182
|
+
def post(self, path: str, body: Any = None, *, idempotency: str | None = None) -> Any:
|
|
183
|
+
headers = {"Idempotency-Key": idempotency} if idempotency else None
|
|
184
|
+
return _json(self.call("POST", f"/api/v1{path}", json=body, headers=headers))
|
|
185
|
+
|
|
186
|
+
def pages(self, route: str, **params: Any) -> Iterator[dict[str, Any]]:
|
|
187
|
+
cursor: str | None = None
|
|
188
|
+
while True:
|
|
189
|
+
page = self.get(route, cursor=cursor, **params)
|
|
190
|
+
yield from page.get("items") or []
|
|
191
|
+
cursor = page.get("next_cursor")
|
|
192
|
+
if not cursor:
|
|
193
|
+
return
|
|
194
|
+
|
|
195
|
+
# --- files --------------------------------------------------------------------------------
|
|
196
|
+
|
|
197
|
+
def upload(
|
|
198
|
+
self, cloud: str, folder: str, local: Path, progress: Callable[[int, int], None]
|
|
199
|
+
) -> Any:
|
|
200
|
+
size = local.stat().st_size
|
|
201
|
+
session = _json(
|
|
202
|
+
self.call(
|
|
203
|
+
"POST",
|
|
204
|
+
f"/api/v1/clouds/{cloud}/uploads",
|
|
205
|
+
params={"name": local.name, "size": size, "path": folder},
|
|
206
|
+
)
|
|
207
|
+
)
|
|
208
|
+
offset = int(session.get("received") or 0)
|
|
209
|
+
piece = int(session.get("piece_bytes") or 8 * 1024 * 1024)
|
|
210
|
+
with local.open("rb") as handle:
|
|
211
|
+
handle.seek(offset)
|
|
212
|
+
while offset < size:
|
|
213
|
+
data = handle.read(piece)
|
|
214
|
+
answer = _json(
|
|
215
|
+
self.call(
|
|
216
|
+
"PUT",
|
|
217
|
+
f"/api/v1/clouds/{cloud}/uploads/{session['id']}",
|
|
218
|
+
params={"offset": offset},
|
|
219
|
+
content=data,
|
|
220
|
+
headers={"Content-Type": "application/octet-stream"},
|
|
221
|
+
)
|
|
222
|
+
)
|
|
223
|
+
offset = int(answer.get("received") or offset + len(data))
|
|
224
|
+
progress(offset, size)
|
|
225
|
+
return _json(
|
|
226
|
+
self.call("POST", f"/api/v1/clouds/{cloud}/uploads/{session['id']}/complete")
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
def download(
|
|
230
|
+
self, cloud: str, path: str, out: BinaryIO, progress: Callable[[int], None]
|
|
231
|
+
) -> int:
|
|
232
|
+
response = self.call(
|
|
233
|
+
"GET", f"/api/v1/clouds/{cloud}/files/content", params={"path": path}, stream=True
|
|
234
|
+
)
|
|
235
|
+
done = 0
|
|
236
|
+
try:
|
|
237
|
+
for chunk in response.iter_bytes():
|
|
238
|
+
out.write(chunk)
|
|
239
|
+
done += len(chunk)
|
|
240
|
+
progress(done)
|
|
241
|
+
finally:
|
|
242
|
+
response.close()
|
|
243
|
+
return done
|
|
244
|
+
|
|
245
|
+
def _form(self, path: str, fields: dict[str, str]) -> dict[str, Any]:
|
|
246
|
+
response = self._http.post(f"{self.base}{path}", data=fields)
|
|
247
|
+
body: dict[str, Any] = _json(response)
|
|
248
|
+
if response.status_code >= 400:
|
|
249
|
+
raise ApiError(response.status_code, _message(body, response.status_code))
|
|
250
|
+
return body
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _json(response: httpx.Response) -> Any:
|
|
254
|
+
if not response.content:
|
|
255
|
+
return {}
|
|
256
|
+
try:
|
|
257
|
+
return response.json()
|
|
258
|
+
except ValueError:
|
|
259
|
+
return {}
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _message(body: Any, status: int) -> str:
|
|
263
|
+
if isinstance(body, dict):
|
|
264
|
+
for key in ("detail", "error_description", "message", "error"):
|
|
265
|
+
value = body.get(key)
|
|
266
|
+
if isinstance(value, str) and value:
|
|
267
|
+
return value
|
|
268
|
+
if isinstance(value, list) and value and isinstance(value[0], dict):
|
|
269
|
+
return str(value[0].get("msg") or value[0])
|
|
270
|
+
return f"The server answered {status}."
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def quote_path(path: str) -> str:
|
|
274
|
+
return quote(path, safe="/")
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
"""``shiftmydata``: the commands (competitor-parity-2, 9.1).
|
|
2
|
+
|
|
3
|
+
A place is written ``CLOUD:PATH`` -- the cloud by its name as the Clouds page shows it, or its
|
|
4
|
+
id -- or as a local path for ``cp``. Every command takes ``--json`` for scripts.
|
|
5
|
+
|
|
6
|
+
shiftmydata login
|
|
7
|
+
shiftmydata clouds
|
|
8
|
+
shiftmydata ls "My Drive:Projects"
|
|
9
|
+
shiftmydata cp "My Drive:Projects" "Dropbox:Backup/Projects" # a transfer
|
|
10
|
+
shiftmydata cp ./report.pdf "My Drive:Reports" # upload
|
|
11
|
+
shiftmydata cp "My Drive:Reports/report.pdf" ./ # download
|
|
12
|
+
shiftmydata sync "My Drive:Photos" "OneDrive:Photos" --watch
|
|
13
|
+
shiftmydata save https://example.com/file.zip "My Drive:Downloads"
|
|
14
|
+
shiftmydata jobs | job ID | cancel ID
|
|
15
|
+
shiftmydata schedules | run SCHEDULE | trigger SCHEDULE [--signed]
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import argparse
|
|
21
|
+
import contextlib
|
|
22
|
+
import json
|
|
23
|
+
import sys
|
|
24
|
+
import time
|
|
25
|
+
import uuid
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
from . import __version__
|
|
30
|
+
from .api import DEFAULT_BASE, ApiError, Client
|
|
31
|
+
|
|
32
|
+
_FINISHED = {"succeeded", "failed", "cancelled"}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def main(argv: list[str] | None = None) -> int:
|
|
36
|
+
parser = _parser()
|
|
37
|
+
args = parser.parse_args(argv)
|
|
38
|
+
if not getattr(args, "run", None):
|
|
39
|
+
parser.print_help()
|
|
40
|
+
return 2
|
|
41
|
+
client = Client(args.base, args.profile)
|
|
42
|
+
try:
|
|
43
|
+
return int(args.run(client, args) or 0)
|
|
44
|
+
except ApiError as exc:
|
|
45
|
+
print(f"shiftmydata: {exc}", file=sys.stderr)
|
|
46
|
+
return 1
|
|
47
|
+
except KeyboardInterrupt:
|
|
48
|
+
return 130
|
|
49
|
+
finally:
|
|
50
|
+
client.close()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _parser() -> argparse.ArgumentParser:
|
|
54
|
+
parser = argparse.ArgumentParser(
|
|
55
|
+
prog="shiftmydata", description="ShiftMyData from the command line."
|
|
56
|
+
)
|
|
57
|
+
parser.add_argument("--version", action="version", version=f"shiftmydata {__version__}")
|
|
58
|
+
parser.add_argument("--base", default=DEFAULT_BASE, help=argparse.SUPPRESS)
|
|
59
|
+
parser.add_argument("--profile", default="default", help="keep several sign-ins apart")
|
|
60
|
+
parser.add_argument("--json", action="store_true", help="answer in JSON, for scripts")
|
|
61
|
+
sub = parser.add_subparsers()
|
|
62
|
+
|
|
63
|
+
def command(name: str, run: Any, text: str) -> argparse.ArgumentParser:
|
|
64
|
+
one = sub.add_parser(name, help=text, description=text)
|
|
65
|
+
one.set_defaults(run=run)
|
|
66
|
+
one.add_argument("--json", action="store_true", default=argparse.SUPPRESS)
|
|
67
|
+
return one
|
|
68
|
+
|
|
69
|
+
command("login", _login, "Sign in through your browser.")
|
|
70
|
+
command("logout", _logout, "Sign out and forget this machine's key.")
|
|
71
|
+
command("whoami", _whoami, "Who is signed in, and what is left of the allowance.")
|
|
72
|
+
command("clouds", _clouds, "Your connected clouds.")
|
|
73
|
+
ls = command("ls", _ls, "List a folder.")
|
|
74
|
+
ls.add_argument("place", help="CLOUD:PATH")
|
|
75
|
+
cp = command("cp", _cp, "Copy between clouds, upload a local file, or download one.")
|
|
76
|
+
cp.add_argument("source")
|
|
77
|
+
cp.add_argument("destination")
|
|
78
|
+
cp.add_argument("--watch", action="store_true", help="follow a transfer until it ends")
|
|
79
|
+
sync = command("sync", _sync, "Make the destination match the source (deletes there too).")
|
|
80
|
+
sync.add_argument("source")
|
|
81
|
+
sync.add_argument("destination")
|
|
82
|
+
sync.add_argument(
|
|
83
|
+
"--max-delete", type=int, help="stop rather than delete more files than this"
|
|
84
|
+
)
|
|
85
|
+
sync.add_argument("--watch", action="store_true")
|
|
86
|
+
save = command("save", _save, "Save something on the web into a folder.")
|
|
87
|
+
save.add_argument("url")
|
|
88
|
+
save.add_argument("destination", help="CLOUD:PATH")
|
|
89
|
+
save.add_argument(
|
|
90
|
+
"--as", dest="kind", choices=["file", "video", "page", "image"], default="file"
|
|
91
|
+
)
|
|
92
|
+
save.add_argument("--name")
|
|
93
|
+
command("jobs", _jobs, "Recent transfers.")
|
|
94
|
+
job = command("job", _job, "One transfer, followed until it ends with --watch.")
|
|
95
|
+
job.add_argument("id")
|
|
96
|
+
job.add_argument("--watch", action="store_true")
|
|
97
|
+
cancel = command("cancel", _cancel, "Cancel a transfer.")
|
|
98
|
+
cancel.add_argument("id")
|
|
99
|
+
command("schedules", _schedules, "Your schedules.")
|
|
100
|
+
run = command("run", _run_schedule, "Run a schedule now.")
|
|
101
|
+
run.add_argument("schedule", help="its name or id")
|
|
102
|
+
trigger = command("trigger", _trigger, "Make a trigger URL for a schedule.")
|
|
103
|
+
trigger.add_argument("schedule", help="its name or id")
|
|
104
|
+
trigger.add_argument(
|
|
105
|
+
"--signed", action="store_true", help="callers must sign their request"
|
|
106
|
+
)
|
|
107
|
+
return parser
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# --- output -----------------------------------------------------------------------------------
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _out(args: argparse.Namespace, value: Any, lines: list[str]) -> int:
|
|
114
|
+
if args.json:
|
|
115
|
+
print(json.dumps(value, indent=2, default=str))
|
|
116
|
+
else:
|
|
117
|
+
for line in lines:
|
|
118
|
+
print(line)
|
|
119
|
+
return 0
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _size(n: int) -> str:
|
|
123
|
+
size = float(n)
|
|
124
|
+
for unit in ("B", "KB", "MB", "GB", "TB"):
|
|
125
|
+
if size < 1024 or unit == "TB":
|
|
126
|
+
return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
|
|
127
|
+
size /= 1024
|
|
128
|
+
return f"{n} B"
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# --- places -----------------------------------------------------------------------------------
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _cloud_id(client: Client, name: str) -> str:
|
|
135
|
+
try:
|
|
136
|
+
uuid.UUID(name)
|
|
137
|
+
return name
|
|
138
|
+
except ValueError:
|
|
139
|
+
pass
|
|
140
|
+
clouds = client.get("/clouds")
|
|
141
|
+
found = [c for c in clouds if str(c.get("name", "")).casefold() == name.casefold()]
|
|
142
|
+
if len(found) != 1:
|
|
143
|
+
known = ", ".join(str(c.get("name")) for c in clouds)
|
|
144
|
+
raise ApiError(404, f"No single cloud is called {name!r}. Yours: {known}")
|
|
145
|
+
return str(found[0]["id"])
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _place(client: Client, text: str) -> tuple[str, str] | None:
|
|
149
|
+
"""``CLOUD:PATH`` as (cloud id, path), or None for a local path."""
|
|
150
|
+
if (
|
|
151
|
+
":" not in text
|
|
152
|
+
or Path(text).exists()
|
|
153
|
+
or (len(text) > 1 and text[1] == ":" and len(text.split(":", 1)[0]) == 1)
|
|
154
|
+
):
|
|
155
|
+
return None
|
|
156
|
+
cloud, _, path = text.partition(":")
|
|
157
|
+
return _cloud_id(client, cloud), path.strip("/")
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
# --- commands ---------------------------------------------------------------------------------
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _login(client: Client, args: argparse.Namespace) -> int:
|
|
164
|
+
def show(url: str, code: str) -> None:
|
|
165
|
+
print(f"Open {url}\nand check the code {code} matches. Waiting…", file=sys.stderr)
|
|
166
|
+
import webbrowser # noqa: PLC0415
|
|
167
|
+
|
|
168
|
+
# The address is printed either way; a machine without a browser just reads it.
|
|
169
|
+
with contextlib.suppress(webbrowser.Error):
|
|
170
|
+
webbrowser.open(url)
|
|
171
|
+
|
|
172
|
+
client.login(show)
|
|
173
|
+
me = client.get("/me")
|
|
174
|
+
return _out(args, me, [f"Signed in as {me.get('email')}."])
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _logout(client: Client, args: argparse.Namespace) -> int:
|
|
178
|
+
client.logout()
|
|
179
|
+
return _out(args, {"signed_out": True}, ["Signed out."])
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _whoami(client: Client, args: argparse.Namespace) -> int:
|
|
183
|
+
me = client.get("/me")
|
|
184
|
+
summary = client.get("/me/summary")
|
|
185
|
+
left = (
|
|
186
|
+
"unlimited"
|
|
187
|
+
if summary.get("unlimited")
|
|
188
|
+
else _size(int(summary.get("allowance_remaining_bytes") or 0))
|
|
189
|
+
)
|
|
190
|
+
return _out(args, {"me": me, "summary": summary}, [f"{me.get('email')} · {left} left"])
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _clouds(client: Client, args: argparse.Namespace) -> int:
|
|
194
|
+
clouds = client.get("/clouds")
|
|
195
|
+
lines = [
|
|
196
|
+
f"{c['name']:<32} {c.get('provider_label', ''):<24} {c.get('status', '')}"
|
|
197
|
+
for c in clouds
|
|
198
|
+
]
|
|
199
|
+
return _out(args, clouds, lines)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _ls(client: Client, args: argparse.Namespace) -> int:
|
|
203
|
+
place = _place(client, args.place)
|
|
204
|
+
if place is None:
|
|
205
|
+
raise ApiError(400, "ls takes CLOUD:PATH")
|
|
206
|
+
items = list(client.pages(f"/clouds/{place[0]}/files", path=place[1]))
|
|
207
|
+
lines = [_entry(item) for item in items]
|
|
208
|
+
return _out(args, items, lines)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _transfer(
|
|
212
|
+
client: Client, args: argparse.Namespace, mode: str, extra: dict[str, Any]
|
|
213
|
+
) -> int:
|
|
214
|
+
source, dest = _place(client, args.source), _place(client, args.destination)
|
|
215
|
+
if source is None or dest is None:
|
|
216
|
+
raise ApiError(400, f"{mode} takes two CLOUD:PATH places")
|
|
217
|
+
job = client.post(
|
|
218
|
+
"/transfers",
|
|
219
|
+
{
|
|
220
|
+
"source_cloud_id": source[0],
|
|
221
|
+
"source_path": source[1],
|
|
222
|
+
"destination_cloud_id": dest[0],
|
|
223
|
+
"destination_path": dest[1],
|
|
224
|
+
"mode": mode,
|
|
225
|
+
**extra,
|
|
226
|
+
},
|
|
227
|
+
idempotency=str(uuid.uuid4()),
|
|
228
|
+
)
|
|
229
|
+
if getattr(args, "watch", False):
|
|
230
|
+
return _follow(client, args, str(job["id"]))
|
|
231
|
+
return _out(args, job, [f"Started {job['id']} ({mode})."])
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _cp(client: Client, args: argparse.Namespace) -> int:
|
|
235
|
+
source, dest = _place(client, args.source), _place(client, args.destination)
|
|
236
|
+
if source and dest:
|
|
237
|
+
return _transfer(client, args, "copy", {})
|
|
238
|
+
if source is None and dest is not None:
|
|
239
|
+
local = Path(args.source)
|
|
240
|
+
if not local.is_file():
|
|
241
|
+
raise ApiError(400, f"{local} is not a file")
|
|
242
|
+
|
|
243
|
+
def shown(done: int, total: int) -> None:
|
|
244
|
+
if not args.json:
|
|
245
|
+
print(f"\r{_size(done)} of {_size(total)}", end="", file=sys.stderr, flush=True)
|
|
246
|
+
|
|
247
|
+
uploaded = client.upload(dest[0], dest[1], local, shown)
|
|
248
|
+
if not args.json:
|
|
249
|
+
print(file=sys.stderr)
|
|
250
|
+
return _out(args, uploaded, [f"Uploaded to {uploaded.get('path')}."])
|
|
251
|
+
if source is not None and dest is None:
|
|
252
|
+
target = Path(args.destination)
|
|
253
|
+
if target.is_dir():
|
|
254
|
+
target = target / Path(source[1]).name
|
|
255
|
+
with target.open("wb") as handle:
|
|
256
|
+
got = client.download(
|
|
257
|
+
source[0],
|
|
258
|
+
source[1],
|
|
259
|
+
handle,
|
|
260
|
+
lambda done: (
|
|
261
|
+
None
|
|
262
|
+
if args.json
|
|
263
|
+
else print(f"\r{_size(done)}", end="", file=sys.stderr, flush=True)
|
|
264
|
+
),
|
|
265
|
+
)
|
|
266
|
+
if not args.json:
|
|
267
|
+
print(file=sys.stderr)
|
|
268
|
+
return _out(
|
|
269
|
+
args, {"path": str(target), "size": got}, [f"Saved {target} ({_size(got)})."]
|
|
270
|
+
)
|
|
271
|
+
raise ApiError(400, "cp needs at least one CLOUD:PATH")
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _sync(client: Client, args: argparse.Namespace) -> int:
|
|
275
|
+
extra = {"max_delete": args.max_delete} if args.max_delete is not None else {}
|
|
276
|
+
return _transfer(client, args, "sync", extra)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _save(client: Client, args: argparse.Namespace) -> int:
|
|
280
|
+
dest = _place(client, args.destination)
|
|
281
|
+
if dest is None:
|
|
282
|
+
raise ApiError(400, "save takes a URL and CLOUD:PATH")
|
|
283
|
+
job = client.post(
|
|
284
|
+
"/saves",
|
|
285
|
+
{
|
|
286
|
+
"url": args.url,
|
|
287
|
+
"destination_cloud_id": dest[0],
|
|
288
|
+
"destination_path": dest[1],
|
|
289
|
+
"kind": args.kind,
|
|
290
|
+
"name": args.name,
|
|
291
|
+
},
|
|
292
|
+
idempotency=str(uuid.uuid4()),
|
|
293
|
+
)
|
|
294
|
+
return _out(args, job, [f"Saving: {job['id']}."])
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _entry(item: dict[str, Any]) -> str:
|
|
298
|
+
if item.get("folder"):
|
|
299
|
+
return f"{'-':>10} {item['name']}/"
|
|
300
|
+
return f"{_size(int(item.get('size') or 0)):>10} {item['name']}"
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _line(job: dict[str, Any]) -> str:
|
|
304
|
+
total = int(job.get("bytes_total") or 0)
|
|
305
|
+
done = int(job.get("bytes_done") or 0)
|
|
306
|
+
share = f" {done * 100 // total}%" if total else ""
|
|
307
|
+
route = f"{job.get('source_path', '')} -> {job.get('destination_path', '')}"
|
|
308
|
+
return f"{job['id']} {job['status']:<10}{share:<5} {job.get('kind', '')} {route}"
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _jobs(client: Client, args: argparse.Namespace) -> int:
|
|
312
|
+
page = client.get("/transfers", limit=25)
|
|
313
|
+
items = page.get("items") or []
|
|
314
|
+
return _out(args, items, [_line(job) for job in items])
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _follow(client: Client, args: argparse.Namespace, job_id: str) -> int:
|
|
318
|
+
while True:
|
|
319
|
+
job = client.get(f"/transfers/{job_id}")
|
|
320
|
+
if not args.json:
|
|
321
|
+
print(f"\r{_line(job)}", end="", file=sys.stderr, flush=True)
|
|
322
|
+
if job["status"] in _FINISHED:
|
|
323
|
+
if not args.json:
|
|
324
|
+
print(file=sys.stderr)
|
|
325
|
+
_out(args, job, [f"{job['status']}: {job.get('error') or 'done'}"])
|
|
326
|
+
return 0 if job["status"] == "succeeded" else 1
|
|
327
|
+
time.sleep(3)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _job(client: Client, args: argparse.Namespace) -> int:
|
|
331
|
+
if args.watch:
|
|
332
|
+
return _follow(client, args, args.id)
|
|
333
|
+
job = client.get(f"/transfers/{args.id}")
|
|
334
|
+
return _out(args, job, [_line(job)])
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _cancel(client: Client, args: argparse.Namespace) -> int:
|
|
338
|
+
job = client.post(f"/transfers/{args.id}/cancel")
|
|
339
|
+
return _out(args, job, [_line(job)])
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _schedule_id(client: Client, name: str) -> str:
|
|
343
|
+
try:
|
|
344
|
+
uuid.UUID(name)
|
|
345
|
+
return name
|
|
346
|
+
except ValueError:
|
|
347
|
+
pass
|
|
348
|
+
found = [
|
|
349
|
+
s
|
|
350
|
+
for s in client.pages("/schedules")
|
|
351
|
+
if str(s.get("name", "")).casefold() == name.casefold()
|
|
352
|
+
]
|
|
353
|
+
if len(found) != 1:
|
|
354
|
+
raise ApiError(404, f"No single schedule is called {name!r}.")
|
|
355
|
+
return str(found[0]["id"])
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _schedules(client: Client, args: argparse.Namespace) -> int:
|
|
359
|
+
items = list(client.pages("/schedules"))
|
|
360
|
+
lines = [
|
|
361
|
+
f"{s['name']:<36} {'on ' if s.get('enabled') else 'off'} "
|
|
362
|
+
f"next {s.get('next_run_at') or '-'}"
|
|
363
|
+
for s in items
|
|
364
|
+
]
|
|
365
|
+
return _out(args, items, lines)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _run_schedule(client: Client, args: argparse.Namespace) -> int:
|
|
369
|
+
job = client.post(f"/schedules/{_schedule_id(client, args.schedule)}/run")
|
|
370
|
+
return _out(args, job, [f"Started {job.get('id')}."])
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _trigger(client: Client, args: argparse.Namespace) -> int:
|
|
374
|
+
made = client.post(
|
|
375
|
+
f"/schedules/{_schedule_id(client, args.schedule)}/trigger", {"signed": args.signed}
|
|
376
|
+
)
|
|
377
|
+
lines = [f"URL: {made.get('url')}"]
|
|
378
|
+
if made.get("signing_secret"):
|
|
379
|
+
lines.append(f"Signing secret (shown once): {made['signing_secret']}")
|
|
380
|
+
return _out(args, made, lines)
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""DPoP proofs (RFC 9449): every request says it comes from the key the sign-in is bound to.
|
|
2
|
+
|
|
3
|
+
The key is a P-256 key made on this machine at the first sign-in and kept in the OS keyring
|
|
4
|
+
(:mod:`shiftmydata.store`); a copied access token is useless without it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import time
|
|
13
|
+
import uuid
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
17
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
18
|
+
from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def b64url(raw: bytes) -> str:
|
|
22
|
+
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ProofKey:
|
|
26
|
+
def __init__(self, key: ec.EllipticCurvePrivateKey) -> None:
|
|
27
|
+
self._key = key
|
|
28
|
+
numbers = key.public_key().public_numbers()
|
|
29
|
+
self.jwk = {
|
|
30
|
+
"kty": "EC",
|
|
31
|
+
"crv": "P-256",
|
|
32
|
+
"x": b64url(numbers.x.to_bytes(32, "big")),
|
|
33
|
+
"y": b64url(numbers.y.to_bytes(32, "big")),
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
@classmethod
|
|
37
|
+
def new(cls) -> ProofKey:
|
|
38
|
+
return cls(ec.generate_private_key(ec.SECP256R1()))
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def from_pem(cls, pem: str) -> ProofKey:
|
|
42
|
+
key = serialization.load_pem_private_key(pem.encode(), password=None)
|
|
43
|
+
if not isinstance(key, ec.EllipticCurvePrivateKey):
|
|
44
|
+
raise ValueError("the stored key is not a P-256 key")
|
|
45
|
+
return cls(key)
|
|
46
|
+
|
|
47
|
+
def pem(self) -> str:
|
|
48
|
+
return self._key.private_bytes(
|
|
49
|
+
serialization.Encoding.PEM,
|
|
50
|
+
serialization.PrivateFormat.PKCS8,
|
|
51
|
+
serialization.NoEncryption(),
|
|
52
|
+
).decode()
|
|
53
|
+
|
|
54
|
+
def thumbprint(self) -> str:
|
|
55
|
+
"""RFC 7638: what the server binds a code and its tokens to."""
|
|
56
|
+
canonical = json.dumps(
|
|
57
|
+
{k: self.jwk[k] for k in ("crv", "kty", "x", "y")}, separators=(",", ":")
|
|
58
|
+
)
|
|
59
|
+
return b64url(hashlib.sha256(canonical.encode()).digest())
|
|
60
|
+
|
|
61
|
+
def proof(self, method: str, url: str, access_token: str | None = None) -> str:
|
|
62
|
+
"""A one-minute proof for one request. ``url`` without its query string."""
|
|
63
|
+
header = {"typ": "dpop+jwt", "alg": "ES256", "jwk": self.jwk}
|
|
64
|
+
claims: dict[str, Any] = {
|
|
65
|
+
"jti": str(uuid.uuid4()),
|
|
66
|
+
"htm": method.upper(),
|
|
67
|
+
"htu": url.split("?", 1)[0],
|
|
68
|
+
"iat": int(time.time()),
|
|
69
|
+
}
|
|
70
|
+
if access_token:
|
|
71
|
+
claims["ath"] = b64url(hashlib.sha256(access_token.encode()).digest())
|
|
72
|
+
signing_input = ".".join(
|
|
73
|
+
b64url(json.dumps(part, separators=(",", ":")).encode())
|
|
74
|
+
for part in (header, claims)
|
|
75
|
+
)
|
|
76
|
+
der = self._key.sign(signing_input.encode(), ec.ECDSA(hashes.SHA256()))
|
|
77
|
+
r, s = decode_dss_signature(der)
|
|
78
|
+
signature = r.to_bytes(32, "big") + s.to_bytes(32, "big")
|
|
79
|
+
return f"{signing_input}.{b64url(signature)}"
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Where the sign-in lives: the OS keyring (Keychain, Credential Manager, Secret Service).
|
|
2
|
+
|
|
3
|
+
When no keyring is available (a bare server), a file readable only by this user under
|
|
4
|
+
``~/.config/shiftmydata`` instead, and the CLI says so once.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import stat
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
SERVICE = "shiftmydata"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _file(name: str) -> Path:
|
|
21
|
+
base = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / SERVICE
|
|
22
|
+
return base / f"{name}.json"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _keyring() -> Any:
|
|
26
|
+
try:
|
|
27
|
+
import keyring # noqa: PLC0415 -- optional at run time
|
|
28
|
+
from keyring.backends.fail import Keyring as Failing # noqa: PLC0415
|
|
29
|
+
|
|
30
|
+
if isinstance(keyring.get_keyring(), Failing):
|
|
31
|
+
return None
|
|
32
|
+
return keyring
|
|
33
|
+
except Exception: # noqa: BLE001 - any keyring trouble means "use the file"
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def load(name: str, profile: str) -> dict[str, Any] | None:
|
|
38
|
+
ring = _keyring()
|
|
39
|
+
raw: str | None = None
|
|
40
|
+
if ring is not None:
|
|
41
|
+
try:
|
|
42
|
+
raw = ring.get_password(SERVICE, f"{profile}:{name}")
|
|
43
|
+
except Exception: # noqa: BLE001
|
|
44
|
+
raw = None
|
|
45
|
+
if raw is None:
|
|
46
|
+
path = _file(f"{profile}-{name}")
|
|
47
|
+
if path.exists():
|
|
48
|
+
raw = path.read_text(encoding="utf-8")
|
|
49
|
+
if not raw:
|
|
50
|
+
return None
|
|
51
|
+
value = json.loads(raw)
|
|
52
|
+
return value if isinstance(value, dict) else None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def save(name: str, profile: str, value: dict[str, Any]) -> None:
|
|
56
|
+
raw = json.dumps(value)
|
|
57
|
+
ring = _keyring()
|
|
58
|
+
if ring is not None:
|
|
59
|
+
try:
|
|
60
|
+
ring.set_password(SERVICE, f"{profile}:{name}", raw)
|
|
61
|
+
except Exception: # noqa: BLE001 - a locked or broken keyring: the file instead
|
|
62
|
+
ring = None
|
|
63
|
+
else:
|
|
64
|
+
return
|
|
65
|
+
path = _file(f"{profile}-{name}")
|
|
66
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
67
|
+
path.write_text(raw, encoding="utf-8")
|
|
68
|
+
if sys.platform != "win32":
|
|
69
|
+
path.chmod(stat.S_IRUSR | stat.S_IWUSR)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def forget(name: str, profile: str) -> None:
|
|
73
|
+
ring = _keyring()
|
|
74
|
+
if ring is not None:
|
|
75
|
+
# Nothing stored there is fine.
|
|
76
|
+
with contextlib.suppress(Exception):
|
|
77
|
+
ring.delete_password(SERVICE, f"{profile}:{name}")
|
|
78
|
+
path = _file(f"{profile}-{name}")
|
|
79
|
+
if path.exists():
|
|
80
|
+
path.unlink()
|