entitybind 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.
entitybind/device.py ADDED
@@ -0,0 +1,433 @@
1
+ """OAuth 2.0 Device Authorization Grant (RFC 8628) for `entitybind login`.
2
+
3
+ Core: POST {base}/v1/oauth/device_authorization, then poll {base}/v1/oauth/token.
4
+ AML: the same shape under {base}/aml/v1/oauth/.
5
+
6
+ The public client id is `entitybind-cli`. A started sign-in is saved to
7
+ `pending-logins.json` (mode 0600) before polling begins, so a process that is
8
+ interrupted, or that stops at `--timeout`, can be continued with
9
+ `entitybind login --resume` instead of asking the person to approve again.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ from collections.abc import Callable, Mapping
16
+ from dataclasses import asdict, dataclass, field
17
+ from typing import Any
18
+
19
+ from entitybind.credentials import Credential, utc_now_iso
20
+ from entitybind.errors import (
21
+ EXIT_SERVER,
22
+ ApiError,
23
+ AuthError,
24
+ CliError,
25
+ ConflictError,
26
+ NetworkError,
27
+ PendingError,
28
+ )
29
+ from entitybind.files import atomic_write, config_dir, ensure_private_dir
30
+ from entitybind.http import ApiClient
31
+ from entitybind.products import CLIENT_ID, Product
32
+
33
+ DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"
34
+ PENDING_FILE = "pending-logins.json"
35
+ DEFAULT_INTERVAL = 5.0
36
+ DEFAULT_EXPIRES_IN = 900.0
37
+ SLOW_DOWN_STEP = 5.0
38
+ MAX_TRANSIENT_FAILURES = 5
39
+ # Fields some servers add beside the RFC 6749 token response. Kept as metadata.
40
+ _TOKEN_METADATA = ("key_id", "tenant_id", "expires_at", "simulated_checks_only")
41
+
42
+
43
+ def oauth_path(product: Product, leaf: str) -> str:
44
+ return product.api_path(f"/oauth/{leaf}")
45
+
46
+
47
+ @dataclass
48
+ class DeviceAuthorization:
49
+ product: str
50
+ base_url: str
51
+ device_code: str
52
+ user_code: str
53
+ verification_uri: str
54
+ expires_at: float
55
+ interval: float = DEFAULT_INTERVAL
56
+ verification_uri_complete: str | None = None
57
+ scope: str | None = None
58
+ name: str | None = None
59
+
60
+ def public(self) -> dict[str, Any]:
61
+ """What a person (or an agent relaying to one) needs. No device code."""
62
+ record: dict[str, Any] = {
63
+ "verification_uri": self.verification_uri,
64
+ "user_code": self.user_code,
65
+ "expires_at": utc_now_iso(self.expires_at),
66
+ "interval": self.interval,
67
+ }
68
+ if self.verification_uri_complete:
69
+ record["verification_uri_complete"] = self.verification_uri_complete
70
+ return record
71
+
72
+
73
+ @dataclass
74
+ class TokenGrant:
75
+ access_token: str
76
+ token_type: str = "Bearer" # noqa: S105 - RFC 6749 token type name, not a secret
77
+ expires_in: float | None = None
78
+ refresh_token: str | None = None
79
+ scope: str | None = None
80
+ metadata: dict[str, Any] = field(default_factory=dict)
81
+
82
+
83
+ def _text(body: Mapping[str, Any], key: str) -> str | None:
84
+ value = body.get(key)
85
+ return value if isinstance(value, str) and value else None
86
+
87
+
88
+ def _number(value: Any) -> float | None:
89
+ if isinstance(value, bool):
90
+ return None
91
+ if isinstance(value, (int, float)):
92
+ return float(value)
93
+ if isinstance(value, str):
94
+ try:
95
+ return float(value)
96
+ except ValueError:
97
+ return None
98
+ return None
99
+
100
+
101
+ def start_device_authorization(
102
+ client: ApiClient,
103
+ product: Product,
104
+ base_url: str,
105
+ *,
106
+ scope: str | None,
107
+ name: str | None,
108
+ now: Callable[[], float],
109
+ ) -> DeviceAuthorization:
110
+ form = {"client_id": CLIENT_ID}
111
+ if scope:
112
+ form["scope"] = scope
113
+ if name:
114
+ form["name"] = name
115
+ try:
116
+ response = client.post(
117
+ oauth_path(product, "device_authorization"),
118
+ form=form,
119
+ with_idempotency=False,
120
+ authenticated=False,
121
+ )
122
+ except ApiError as error:
123
+ if error.status == 404:
124
+ raise CliError(
125
+ f"{base_url} does not offer device sign-in for {product.label}",
126
+ code="device_flow_unavailable",
127
+ exit_code=error.exit_code,
128
+ hint=f"create a key in the browser and set {product.key_env}",
129
+ ) from None
130
+ raise
131
+ body = response.body if isinstance(response.body, dict) else {}
132
+ device_code = _text(body, "device_code")
133
+ user_code = _text(body, "user_code")
134
+ verification_uri = _text(body, "verification_uri") or _text(body, "verification_url")
135
+ if not (device_code and user_code and verification_uri):
136
+ raise CliError(
137
+ "the device authorization response is missing device_code, user_code or "
138
+ "verification_uri",
139
+ code="invalid_device_response",
140
+ exit_code=EXIT_SERVER,
141
+ )
142
+ interval = max(1.0, _number(body.get("interval")) or DEFAULT_INTERVAL)
143
+ expires_in = _number(body.get("expires_in")) or DEFAULT_EXPIRES_IN
144
+ return DeviceAuthorization(
145
+ product=product.name,
146
+ base_url=base_url,
147
+ device_code=device_code,
148
+ user_code=user_code,
149
+ verification_uri=verification_uri,
150
+ verification_uri_complete=_text(body, "verification_uri_complete"),
151
+ expires_at=now() + expires_in,
152
+ interval=interval,
153
+ scope=scope,
154
+ name=name,
155
+ )
156
+
157
+
158
+ def parse_token(body: Any) -> TokenGrant:
159
+ if not isinstance(body, dict) or not _text(body, "access_token"):
160
+ raise CliError(
161
+ "the token response has no access_token",
162
+ code="invalid_token_response",
163
+ exit_code=EXIT_SERVER,
164
+ )
165
+ return TokenGrant(
166
+ access_token=str(body["access_token"]),
167
+ token_type=_text(body, "token_type") or "Bearer",
168
+ expires_in=_number(body.get("expires_in")),
169
+ refresh_token=_text(body, "refresh_token"),
170
+ scope=_text(body, "scope"),
171
+ metadata={key: body[key] for key in _TOKEN_METADATA if body.get(key) is not None},
172
+ )
173
+
174
+
175
+ def poll_for_token(
176
+ client: ApiClient,
177
+ product: Product,
178
+ authorization: DeviceAuthorization,
179
+ *,
180
+ deadline: float,
181
+ sleep: Callable[[float], None],
182
+ now: Callable[[], float],
183
+ poll_immediately: bool = False,
184
+ ) -> TokenGrant:
185
+ """Poll until approval, denial, expiry or `deadline`, honouring slow_down."""
186
+ interval = authorization.interval
187
+ next_poll = now() + (0.0 if poll_immediately else interval)
188
+ failures = 0
189
+ while True:
190
+ if next_poll > min(deadline, authorization.expires_at):
191
+ if deadline < authorization.expires_at:
192
+ raise PendingError(
193
+ "still waiting for the sign-in to be approved",
194
+ code="login_pending",
195
+ hint="run `entitybind login --resume` to keep waiting",
196
+ data={"authorization": authorization.public()},
197
+ )
198
+ raise PendingError(
199
+ "the sign-in code expired before it was approved",
200
+ code="login_expired",
201
+ hint="run `entitybind login` to start again",
202
+ )
203
+ delay = next_poll - now()
204
+ if delay > 0:
205
+ sleep(delay)
206
+ try:
207
+ response = client.post(
208
+ oauth_path(product, "token"),
209
+ form={
210
+ "grant_type": DEVICE_GRANT,
211
+ "device_code": authorization.device_code,
212
+ "client_id": CLIENT_ID,
213
+ },
214
+ with_idempotency=False,
215
+ authenticated=False,
216
+ )
217
+ except ApiError as error:
218
+ refusal = error
219
+ except NetworkError:
220
+ failures += 1
221
+ if failures > MAX_TRANSIENT_FAILURES:
222
+ raise
223
+ next_poll = now() + interval
224
+ continue
225
+ else:
226
+ body = response.body
227
+ error_body = isinstance(body, dict) and _text(body, "error") is not None
228
+ if not error_body or body.get("access_token"):
229
+ return parse_token(body)
230
+ # A non-standard 200 carrying an RFC 6749 error body is read as the refusal it is.
231
+ code = str(body["error"])
232
+ refusal = ApiError(400, _text(body, "error_description") or code, code=code, body=body)
233
+ if refusal.code == "authorization_pending":
234
+ next_poll = now() + interval
235
+ continue
236
+ if refusal.code == "slow_down":
237
+ interval += SLOW_DOWN_STEP
238
+ next_poll = now() + interval
239
+ continue
240
+ if refusal.code == "access_denied":
241
+ raise AuthError("the sign-in request was denied", code="access_denied")
242
+ if refusal.code == "expired_token":
243
+ raise PendingError(
244
+ "the sign-in code expired before it was approved",
245
+ code="login_expired",
246
+ hint="run `entitybind login` to start again",
247
+ )
248
+ if refusal.status >= 500 or refusal.status == 429:
249
+ failures += 1
250
+ if failures > MAX_TRANSIENT_FAILURES:
251
+ raise refusal
252
+ next_poll = now() + interval
253
+ continue
254
+ raise AuthError(f"sign-in failed: {refusal.message}", code=refusal.code or "login_failed")
255
+
256
+
257
+ def credential_from_grant(
258
+ product: Product, base_url: str, grant: TokenGrant, *, now: float
259
+ ) -> Credential:
260
+ expires_at = grant.metadata.get("expires_at")
261
+ if not isinstance(expires_at, str):
262
+ expires_at = utc_now_iso(now + grant.expires_in) if grant.expires_in else None
263
+ key_id = grant.metadata.get("key_id")
264
+ tenant_id = grant.metadata.get("tenant_id")
265
+ return Credential(
266
+ product=product.name,
267
+ base_url=base_url,
268
+ api_key=grant.access_token,
269
+ token_type=grant.token_type,
270
+ scope=grant.scope,
271
+ key_id=str(key_id) if key_id is not None else None,
272
+ tenant_id=str(tenant_id) if tenant_id is not None else None,
273
+ expires_at=expires_at,
274
+ refresh_token=grant.refresh_token,
275
+ obtained_at=utc_now_iso(now),
276
+ )
277
+
278
+
279
+ def refresh_credential(
280
+ client: ApiClient, product: Product, credential: Credential, *, now: float
281
+ ) -> Credential:
282
+ """Exchange a stored refresh token for a new access token (RFC 6749 §6)."""
283
+ if not credential.refresh_token:
284
+ raise AuthError("this credential cannot be refreshed", hint="run `entitybind login` again")
285
+ try:
286
+ response = client.post(
287
+ oauth_path(product, "token"),
288
+ form={
289
+ "grant_type": "refresh_token",
290
+ "refresh_token": credential.refresh_token,
291
+ "client_id": credential.client_id,
292
+ },
293
+ with_idempotency=False,
294
+ authenticated=False,
295
+ )
296
+ except ApiError as error:
297
+ if error.status in (400, 401):
298
+ raise AuthError(
299
+ "the stored sign-in has expired",
300
+ code=error.code or "invalid_grant",
301
+ hint="run `entitybind login` again",
302
+ ) from None
303
+ raise
304
+ grant = parse_token(response.body)
305
+ credential.api_key = grant.access_token
306
+ if grant.refresh_token:
307
+ credential.refresh_token = grant.refresh_token
308
+ if grant.expires_in:
309
+ credential.expires_at = utc_now_iso(now + grant.expires_in)
310
+ if grant.scope:
311
+ credential.scope = grant.scope
312
+ return credential
313
+
314
+
315
+ def revoke_token(client: ApiClient, product: Product, token: str) -> bool:
316
+ """RFC 7009 revocation. Best effort: the server answers 200 even for unknown tokens."""
317
+ try:
318
+ client.post(
319
+ oauth_path(product, "revoke"),
320
+ form={"token": token, "client_id": CLIENT_ID},
321
+ with_idempotency=False,
322
+ authenticated=False,
323
+ )
324
+ except (ApiError, NetworkError):
325
+ return False
326
+ return True
327
+
328
+
329
+ @dataclass
330
+ class Revocation:
331
+ """What `logout --revoke` established about a stored key."""
332
+
333
+ confirmed: bool
334
+ detail: str
335
+ cause: CliError | None = None
336
+
337
+
338
+ def _no_longer_authenticates(client: ApiClient, product: Product) -> Revocation:
339
+ """Present the key once more: only a 401 shows that it no longer works."""
340
+ try:
341
+ client.get(product.api_path("/credential"))
342
+ except ApiError as error:
343
+ if error.status == 401:
344
+ return Revocation(True, "the key no longer authenticates")
345
+ return Revocation(
346
+ False, f"the check did not confirm it (HTTP {error.status}, {error.code})", error
347
+ )
348
+ except NetworkError as error:
349
+ return Revocation(False, f"the server could not be reached ({error.code})", error)
350
+ return Revocation(False, "the key still authenticates")
351
+
352
+
353
+ def revoke_key(client: ApiClient, product: Product, api_key: str) -> Revocation:
354
+ """Revoke a stored key on the server, and confirm it is revoked.
355
+
356
+ AML: `DELETE /aml/v1/credential`, the key revoking itself. Core: RFC 7009
357
+ `POST /v1/oauth/revoke`, which answers 200 whether or not it revoked
358
+ anything, so the key is then presented to `GET /v1/credential`. `client`
359
+ must carry `api_key` as its bearer credential.
360
+ """
361
+ if product.name == "aml":
362
+ try:
363
+ client.delete(product.api_path("/credential"))
364
+ except ApiError as error:
365
+ if error.status == 401:
366
+ return Revocation(True, "the key no longer authenticates")
367
+ return Revocation(
368
+ False, f"the server refused (HTTP {error.status}, {error.code})", error
369
+ )
370
+ except NetworkError as error:
371
+ return Revocation(False, f"the server could not be reached ({error.code})", error)
372
+ return Revocation(True, "the server revoked it")
373
+ revoke_token(client, product, api_key)
374
+ return _no_longer_authenticates(client, product)
375
+
376
+
377
+ class PendingStore:
378
+ """Started sign-ins, so `login --resume` can finish one later."""
379
+
380
+ def __init__(self, env: Mapping[str, str]) -> None:
381
+ self.directory = config_dir(env)
382
+ self.path = self.directory / PENDING_FILE
383
+
384
+ def _read(self) -> dict[str, Any]:
385
+ if not self.path.exists():
386
+ return {"version": 1, "pending": {}}
387
+ try:
388
+ data = json.loads(self.path.read_text(encoding="utf-8"))
389
+ except ValueError:
390
+ raise ConflictError(
391
+ f"{self.path} is not valid JSON; delete it and run `entitybind login` again",
392
+ code="pending_unreadable",
393
+ ) from None
394
+ if not isinstance(data, dict) or not isinstance(data.get("pending"), dict):
395
+ return {"version": 1, "pending": {}}
396
+ return data
397
+
398
+ def _write(self, data: dict[str, Any]) -> None:
399
+ ensure_private_dir(self.directory)
400
+ atomic_write(self.path, json.dumps(data, indent=2, sort_keys=True) + "\n", mode=0o600)
401
+
402
+ def get(self, product: Product, base_url: str) -> DeviceAuthorization | None:
403
+ bucket = self._read()["pending"].get(product.name)
404
+ record = bucket.get(base_url) if isinstance(bucket, dict) else None
405
+ if not isinstance(record, dict):
406
+ return None
407
+ try:
408
+ return DeviceAuthorization(**record)
409
+ except TypeError:
410
+ return None
411
+
412
+ def put(self, authorization: DeviceAuthorization) -> None:
413
+ data = self._read()
414
+ bucket = data["pending"].get(authorization.product)
415
+ if not isinstance(bucket, dict):
416
+ bucket = {}
417
+ data["pending"][authorization.product] = bucket
418
+ bucket[authorization.base_url] = asdict(authorization)
419
+ self._write(data)
420
+
421
+ def delete(self, product: Product, base_url: str) -> None:
422
+ if not self.path.exists():
423
+ return
424
+ data = self._read()
425
+ bucket = data["pending"].get(product.name)
426
+ if isinstance(bucket, dict) and base_url in bucket:
427
+ del bucket[base_url]
428
+ if not bucket:
429
+ del data["pending"][product.name]
430
+ if data["pending"]:
431
+ self._write(data)
432
+ else:
433
+ self.path.unlink(missing_ok=True)
entitybind/errors.py ADDED
@@ -0,0 +1,184 @@
1
+ """Exit codes and the errors that carry them.
2
+
3
+ The exit codes are a published contract: scripts and coding agents branch on
4
+ them, so a number never changes meaning between releases.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ EXIT_OK = 0
12
+ EXIT_USAGE = 2
13
+ EXIT_AUTH = 3
14
+ EXIT_PAYMENT = 4
15
+ EXIT_NOT_FOUND = 5
16
+ EXIT_CONFLICT = 6
17
+ EXIT_RATE_LIMITED = 7
18
+ EXIT_SERVER = 8
19
+ EXIT_PENDING = 9
20
+
21
+ EXIT_CODES: dict[int, str] = {
22
+ EXIT_OK: "ok",
23
+ EXIT_USAGE: "usage error or invalid request",
24
+ EXIT_AUTH: "authentication or permission",
25
+ EXIT_PAYMENT: "payment or entitlement",
26
+ EXIT_NOT_FOUND: "not found",
27
+ EXIT_CONFLICT: "conflict",
28
+ EXIT_RATE_LIMITED: "rate limited",
29
+ EXIT_SERVER: "server or network error",
30
+ EXIT_PENDING: "still pending or timed out",
31
+ }
32
+
33
+ # Refusals that a payment, a plan change or an entitlement would lift. They can
34
+ # arrive as 401, 403 or 429, so the code decides, not the status alone.
35
+ _ENTITLEMENT_PREFIXES = (
36
+ "plan_",
37
+ "billing_",
38
+ "evaluation_",
39
+ "credit",
40
+ "quota",
41
+ "entitlement",
42
+ "payment",
43
+ "subscription",
44
+ "trial_",
45
+ "depth_",
46
+ "spend_",
47
+ )
48
+ _ENTITLEMENT_MARKERS = (
49
+ "insufficient_credits",
50
+ "credit_limit",
51
+ "payment_required",
52
+ "upgrade_required",
53
+ "plan_limit",
54
+ )
55
+
56
+
57
+ def is_entitlement_code(code: str | None) -> bool:
58
+ value = (code or "").lower()
59
+ if not value or value == "rate_limited":
60
+ return False
61
+ return value.startswith(_ENTITLEMENT_PREFIXES) or any(
62
+ marker in value for marker in _ENTITLEMENT_MARKERS
63
+ )
64
+
65
+
66
+ def exit_code_for_status(status: int, code: str | None = None) -> int:
67
+ """Map an HTTP refusal to the CLI's exit code."""
68
+ if status == 402:
69
+ return EXIT_PAYMENT
70
+ if status in (401, 403):
71
+ return EXIT_PAYMENT if is_entitlement_code(code) else EXIT_AUTH
72
+ if status == 429:
73
+ return EXIT_PAYMENT if is_entitlement_code(code) else EXIT_RATE_LIMITED
74
+ if status in (404, 410):
75
+ return EXIT_NOT_FOUND
76
+ if status in (409, 412):
77
+ return EXIT_CONFLICT
78
+ if status == 202:
79
+ return EXIT_PENDING
80
+ if 400 <= status < 500:
81
+ return EXIT_USAGE
82
+ return EXIT_SERVER
83
+
84
+
85
+ class CliError(Exception):
86
+ """A failure the CLI reports and exits on. Never carries a secret."""
87
+
88
+ exit_code = EXIT_SERVER
89
+ default_code = "cli_error"
90
+
91
+ def __init__(
92
+ self,
93
+ message: str,
94
+ *,
95
+ code: str | None = None,
96
+ exit_code: int | None = None,
97
+ hint: str | None = None,
98
+ data: dict[str, Any] | None = None,
99
+ ) -> None:
100
+ super().__init__(message)
101
+ self.message = message
102
+ self.code = code or self.default_code
103
+ if exit_code is not None:
104
+ self.exit_code = exit_code
105
+ self.hint = hint
106
+ self.data = data or {}
107
+
108
+ def to_json(self) -> dict[str, Any]:
109
+ error: dict[str, Any] = {"code": self.code, "message": self.message}
110
+ if self.hint:
111
+ error["hint"] = self.hint
112
+ error.update(self.data)
113
+ return {"error": error, "exit_code": self.exit_code}
114
+
115
+
116
+ class UsageError(CliError):
117
+ exit_code = EXIT_USAGE
118
+ default_code = "usage_error"
119
+
120
+
121
+ class AuthError(CliError):
122
+ exit_code = EXIT_AUTH
123
+ default_code = "not_authenticated"
124
+
125
+
126
+ class NotFoundError(CliError):
127
+ exit_code = EXIT_NOT_FOUND
128
+ default_code = "not_found"
129
+
130
+
131
+ class ConflictError(CliError):
132
+ exit_code = EXIT_CONFLICT
133
+ default_code = "conflict"
134
+
135
+
136
+ class PendingError(CliError):
137
+ exit_code = EXIT_PENDING
138
+ default_code = "still_pending"
139
+
140
+
141
+ class NetworkError(CliError):
142
+ exit_code = EXIT_SERVER
143
+ default_code = "network_error"
144
+
145
+
146
+ class ApiError(CliError):
147
+ """A non-success HTTP response, with the server's own error fields."""
148
+
149
+ default_code = "http_error"
150
+
151
+ def __init__(
152
+ self,
153
+ status: int,
154
+ message: str,
155
+ *,
156
+ code: str | None = None,
157
+ correlation_id: str | None = None,
158
+ remediation: Any = None,
159
+ details: Any = None,
160
+ retry_after: float | None = None,
161
+ body: Any = None,
162
+ ) -> None:
163
+ super().__init__(message, code=code, exit_code=exit_code_for_status(status, code))
164
+ self.status = status
165
+ self.correlation_id = correlation_id
166
+ self.remediation = remediation
167
+ self.details = details
168
+ self.retry_after = retry_after
169
+ self.body = body
170
+
171
+ def to_json(self) -> dict[str, Any]:
172
+ error: dict[str, Any] = {"code": self.code, "message": self.message}
173
+ if self.correlation_id:
174
+ error["correlation_id"] = self.correlation_id
175
+ if self.remediation is not None:
176
+ error["remediation"] = self.remediation
177
+ if self.details is not None:
178
+ error["details"] = self.details
179
+ if self.retry_after is not None:
180
+ error["retry_after"] = self.retry_after
181
+ if self.hint:
182
+ error["hint"] = self.hint
183
+ error.update({key: value for key, value in self.data.items() if key not in error})
184
+ return {"error": error, "status": self.status, "exit_code": self.exit_code}
entitybind/files.py ADDED
@@ -0,0 +1,78 @@
1
+ """Atomic file writes and the directories this client reads and writes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import os
7
+ import stat
8
+ import sys
9
+ import tempfile
10
+ from collections.abc import Mapping
11
+ from pathlib import Path
12
+
13
+ POSIX = os.name == "posix"
14
+
15
+
16
+ def home_dir(env: Mapping[str, str]) -> Path:
17
+ for name in ("HOME", "USERPROFILE"):
18
+ value = env.get(name)
19
+ if value:
20
+ return Path(value)
21
+ return Path.home()
22
+
23
+
24
+ def config_dir(env: Mapping[str, str]) -> Path:
25
+ """`$XDG_CONFIG_HOME/entitybind`, defaulting to `~/.config/entitybind`.
26
+
27
+ The same location on every platform, so the Python and npm clients share
28
+ one credentials file.
29
+ """
30
+ base = env.get("XDG_CONFIG_HOME")
31
+ root = Path(base) if base else home_dir(env) / ".config"
32
+ return root / "entitybind"
33
+
34
+
35
+ def ensure_private_dir(path: Path) -> None:
36
+ path.mkdir(mode=0o700, parents=True, exist_ok=True)
37
+ if POSIX:
38
+ with contextlib.suppress(OSError):
39
+ os.chmod(path, 0o700)
40
+
41
+
42
+ def existing_mode(path: Path) -> int | None:
43
+ try:
44
+ return stat.S_IMODE(path.stat().st_mode)
45
+ except FileNotFoundError:
46
+ return None
47
+
48
+
49
+ def atomic_write(path: Path, text: str, *, mode: int) -> Path:
50
+ """Write `text` to `path` so a reader sees the old file or the new one.
51
+
52
+ The temporary file is created next to the target (same filesystem) with
53
+ owner-only permissions, flushed to disk, given `mode` and renamed over the
54
+ target. A symlinked target keeps its link: the write lands on the file the
55
+ link points to.
56
+ """
57
+ target = path.resolve() if path.is_symlink() else path
58
+ target.parent.mkdir(parents=True, exist_ok=True)
59
+ handle, temporary = tempfile.mkstemp(
60
+ prefix=f".{target.name}.", suffix=".tmp", dir=target.parent
61
+ )
62
+ try:
63
+ with os.fdopen(handle, "w", encoding="utf-8", newline="\n") as stream:
64
+ stream.write(text)
65
+ stream.flush()
66
+ os.fsync(stream.fileno())
67
+ if POSIX:
68
+ os.chmod(temporary, mode)
69
+ os.replace(temporary, target)
70
+ except BaseException:
71
+ with contextlib.suppress(FileNotFoundError):
72
+ os.unlink(temporary)
73
+ raise
74
+ return target
75
+
76
+
77
+ def is_windows() -> bool:
78
+ return sys.platform.startswith("win")