factoryhub 0.1.2__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.
factoryhub/__init__.py ADDED
@@ -0,0 +1,109 @@
1
+ """factoryhub: share and run AI factories from Python.
2
+
3
+ import factoryhub
4
+
5
+ factoryhub.login() # a code you approve in your browser
6
+ saved = factoryhub.push("my-factory") # private to your account
7
+ factoryhub.pull("meeting-to-actions", dir="meeting") # every file checked
8
+ outcome = factoryhub.run("meeting-to-actions", {"notes": "..."})
9
+ factoryhub.verify_receipt("result.receipt.json", deliverable=open("result.md").read())
10
+
11
+ Every function takes ``base_url=``, ``token=`` and ``access_key=``; by default
12
+ they come from FACTORYHUB_BASE_URL, FACTORYHUB_TOKEN (then the saved login,
13
+ shared with the factoryhub CLI) and FACTORYHUB_ACCESS_KEY.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ __version__ = "0.1.2"
19
+
20
+ from pathlib import Path
21
+ from typing import Any, Callable, Iterable, List, Mapping, Optional, Union
22
+
23
+ from ._bundle import bundle_hash, from_envelope, read_folder
24
+ from ._canonical import canonical, sha256
25
+ from .credentials import credentials_path
26
+ from .hub import DEFAULT_HUB, OPT_IN_SCOPES, SCOPES, Hub, HubError, Pulled, RunResult
27
+ from .receipts import Verification, load_receipt, verify_receipt_with_keys
28
+
29
+ __all__ = [
30
+ "DEFAULT_HUB", "OPT_IN_SCOPES", "SCOPES", "Hub", "HubError", "Pulled", "RunResult", "Verification",
31
+ "login", "logout", "whoami", "push", "pull", "publish", "run", "follow_run", "runs", "verify_receipt",
32
+ "canonical", "sha256", "bundle_hash", "from_envelope", "read_folder", "credentials_path", "__version__",
33
+ ]
34
+
35
+
36
+ def _hub(base_url: Optional[str], token: Optional[str], access_key: Optional[str]) -> Hub:
37
+ return Hub(base_url, token=token, access_key=access_key)
38
+
39
+
40
+ def login(token: Optional[str] = None, *, scopes: Optional[Iterable[str]] = None, name: Optional[str] = None, days: Optional[int] = None,
41
+ on_code: Optional[Callable[[dict], None]] = None, save: bool = True, base_url: Optional[str] = None, access_key: Optional[str] = None) -> dict:
42
+ """Logs in by device code (or checks ``token``) and saves the token for the CLI and SDKs."""
43
+ return Hub(base_url, access_key=access_key).login(token, scopes=scopes, name=name, days=days, on_code=on_code, save=save)
44
+
45
+
46
+ def logout(*, base_url: Optional[str] = None, access_key: Optional[str] = None) -> bool:
47
+ """Revokes the saved token on the hub, then forgets it."""
48
+ return Hub(base_url, access_key=access_key).logout()
49
+
50
+
51
+ def whoami(*, base_url: Optional[str] = None, token: Optional[str] = None, access_key: Optional[str] = None) -> dict:
52
+ """The account and token the token acts for."""
53
+ return _hub(base_url, token, access_key).whoami()
54
+
55
+
56
+ def push(source: Union[str, Path, Mapping[str, str]], *, parent: Optional[str] = None, base_url: Optional[str] = None,
57
+ token: Optional[str] = None, access_key: Optional[str] = None) -> dict:
58
+ """Saves a factory folder to your account, privately. Nothing is published."""
59
+ return _hub(base_url, token, access_key).push(source, parent=parent)
60
+
61
+
62
+ def pull(factory_id: str, *, dir: Optional[Union[str, Path]] = None, force: bool = False, partial: bool = False, base_url: Optional[str] = None, # noqa: A002
63
+ token: Optional[str] = None, access_key: Optional[str] = None) -> Pulled:
64
+ """Downloads a factory you can open, checking every file's hash; with ``dir``, writes it there.
65
+
66
+ A bundle that cannot be checked whole is refused unless ``partial=True``.
67
+ """
68
+ return _hub(base_url, token, access_key).pull(factory_id, dir=dir, force=force, partial=partial)
69
+
70
+
71
+ def publish(factory_id: str, *, note: str = "", base_url: Optional[str] = None, token: Optional[str] = None, access_key: Optional[str] = None) -> dict:
72
+ """Publishes one of your factories: anyone can find and run it at once."""
73
+ return _hub(base_url, token, access_key).publish(factory_id, note=note)
74
+
75
+
76
+ def run(factory_id: str, inputs: Optional[Mapping[str, str]] = None, *, on_event: Optional[Callable[[dict], None]] = None,
77
+ on_decision: Optional[Callable[[dict], Optional[Mapping[str, str]]]] = None, base_url: Optional[str] = None,
78
+ token: Optional[str] = None, access_key: Optional[str] = None) -> dict:
79
+ """Runs a factory on factoryhub and follows it; ``on_decision`` relays the person's own decisions."""
80
+ return _hub(base_url, token, access_key).run(factory_id, inputs, on_event=on_event, on_decision=on_decision)
81
+
82
+
83
+ def follow_run(run_id: str, *, after: int = 0, on_event: Optional[Callable[[dict], None]] = None, every: float = 2.0,
84
+ base_url: Optional[str] = None, token: Optional[str] = None, access_key: Optional[str] = None) -> dict:
85
+ """Follows an existing hosted run and returns its outcome and cursor."""
86
+ return _hub(base_url, token, access_key).follow_run(run_id, after=after, on_event=on_event, every=every)
87
+
88
+
89
+ def runs(*, limit: Optional[int] = None, base_url: Optional[str] = None, token: Optional[str] = None, access_key: Optional[str] = None) -> List[dict]:
90
+ """Your recent hosted runs."""
91
+ return _hub(base_url, token, access_key).runs(limit=limit)
92
+
93
+
94
+ def verify_receipt(receipt: Union[Mapping[str, Any], str, Path], *, keys: Optional[List[dict]] = None, deliverable: Optional[str] = None,
95
+ base_url: Optional[str] = None, access_key: Optional[str] = None) -> Verification:
96
+ """Checks a run receipt's Ed25519 signature, offline when ``keys`` are given.
97
+
98
+ ``receipt`` is a dict, a JSON text or a path. With ``deliverable``, also
99
+ checks the text against the hash the receipt records. The same checks and
100
+ messages as the engine's verifyReceipt. Without ``keys``, it is checked as
101
+ a receipt from the hub at ``base_url``: on https://factory.mindburn.org
102
+ against the production keys pinned in this package, elsewhere against the
103
+ keys that hub publishes, and its issuer against the hub's host.
104
+ """
105
+ if keys is None:
106
+ return Hub(base_url, access_key=access_key).verify_receipt(receipt, deliverable=deliverable)
107
+ result = verify_receipt_with_keys(load_receipt(receipt), keys, deliverable)
108
+ result.trust = "given"
109
+ return result
factoryhub/_bundle.py ADDED
@@ -0,0 +1,259 @@
1
+ """Factory files and transfer bundles, read exactly as the engine reads them.
2
+
3
+ Ports ``ALLOWED_PATH``, ``normalizeFiles``, ``fromEnvelope`` and
4
+ ``bundleHash`` from packages/engine/src/factory-engine.mjs, and ``readFolder``
5
+ from packages/engine/lib/node.mjs. ``test/fixtures/sdk/bundles.json`` holds
6
+ the cases both implementations must agree on, messages included.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import re
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+ from typing import Any, Dict, List, Mapping, Optional
17
+
18
+ from ._canonical import canonical, js_slice, sha256, utf16_key, utf8
19
+
20
+ BUNDLE_FORMAT = "mindburn.factory.bundle/v1"
21
+ MAX_FILES = 60
22
+ MAX_BYTES = 400_000
23
+
24
+ _RESOURCE = "[a-z0-9][a-z0-9_-]{0,40}"
25
+ _PART = "[A-Za-z0-9][A-Za-z0-9_.-]{0,80}"
26
+ ALLOWED_PATH = re.compile(
27
+ "(?:"
28
+ + "|".join(
29
+ [
30
+ r"factory\.yaml",
31
+ r"flow\.yaml",
32
+ r"mindburn\.(?:package|requirements|tests|company|lock)\.yaml",
33
+ r"layout\.json",
34
+ r"(?:README|LICENSE|LICENCE|NOTICE|CHANGELOG)(?:\.(?:md|txt))?",
35
+ rf"agents/{_RESOURCE}/agent\.md",
36
+ rf"automations/{_RESOURCE}/automation\.md",
37
+ rf"scorers/{_RESOURCE}/scorer\.md",
38
+ rf"(?:runners|routers|webhooks)/{_RESOURCE}\.yaml",
39
+ rf"benchmarks/{_RESOURCE}/(?:suite\.yaml|tasks/{_RESOURCE}\.yaml)",
40
+ rf"(?:agents/{_RESOURCE}/)?skills/{_RESOURCE}/(?:{_PART}/){{0,6}}{_PART}\.md",
41
+ rf"(?:agents/{_RESOURCE}/)?skills/{_RESOURCE}\.ya?ml",
42
+ r"self-improvement/agent\.md",
43
+ rf"(?:profiles|flows|schemas|prompts|assets|examples|checks|fixtures|capabilities|policies|adapters|ui)/(?:{_PART}/){{0,6}}{_PART}\.(?:yaml|yml|json|md|txt|csv|svg)",
44
+ ]
45
+ )
46
+ + ")"
47
+ )
48
+ _UNSAFE_PATH = re.compile(r"^/|(^|/)\.\.?(/|$)|\\|[\x00-\x1f]")
49
+ _HEX64 = re.compile(r"[a-f0-9]{64}")
50
+ SOURCE_FOLDERS = frozenset(
51
+ "agents automations scorers runners routers webhooks benchmarks skills self-improvement "
52
+ "profiles flows schemas prompts assets examples checks fixtures capabilities policies adapters ui".split()
53
+ )
54
+ _GENERATED = frozenset(["RUNNING.md", "run.mjs", "factory-engine.mjs", "author-tests.mjs", "INPUTS.schema.json", "FACTORY-HUB.json"])
55
+
56
+
57
+ def allowed_path(path: str) -> bool:
58
+ return ALLOWED_PATH.fullmatch(path) is not None
59
+
60
+
61
+ def normalize_files(files: Mapping[str, Any]) -> Dict[str, str]:
62
+ """Windows line endings to \\n, paths in UTF-16 order: the engine's normalizeFiles."""
63
+ out = {path: str("" if content is None else content).replace("\r\n", "\n") for path, content in files.items()}
64
+ return {path: out[path] for path in sorted(out, key=utf16_key)}
65
+
66
+
67
+ def bundle_hash(files: Mapping[str, Any]) -> str:
68
+ """A factory's identity: the SHA-256 of its normalized files' canonical JSON."""
69
+ return sha256(canonical(normalize_files(files)))
70
+
71
+
72
+ @dataclass
73
+ class ReadBundle:
74
+ files: Dict[str, str]
75
+ problems: List[str]
76
+ left_out: List[str] = field(default_factory=list)
77
+ status: Optional[str] = None
78
+ warnings: List[str] = field(default_factory=list)
79
+
80
+
81
+ def _is_text_list(value: Any) -> bool:
82
+ return isinstance(value, list) and all(isinstance(item, str) for item in value)
83
+
84
+
85
+ def from_envelope(envelope: Any) -> ReadBundle:
86
+ """Reads a transfer bundle into files, checking paths, sizes and each file's SHA-256."""
87
+ if not isinstance(envelope, dict) or envelope.get("format") != BUNDLE_FORMAT or not isinstance(envelope.get("files"), list):
88
+ return ReadBundle({}, [f"This is not a {BUNDLE_FORMAT} file."], [], None, [])
89
+ problems: List[str] = []
90
+ valid_warnings = "warnings" not in envelope or _is_text_list(envelope["warnings"])
91
+ if not valid_warnings:
92
+ problems.append("Bundle warnings must be a list of text messages.")
93
+ valid_left_out = "left_out" not in envelope or _is_text_list(envelope["left_out"])
94
+ if not valid_left_out:
95
+ problems.append("Left-out paths must be a list of text paths.")
96
+ source = envelope.get("source")
97
+ if isinstance(source, dict) and "project" in source and not isinstance(source["project"], str):
98
+ problems.append("The source project name must be text.")
99
+ named = (envelope.get("left_out") or []) if valid_left_out else []
100
+ left_out = [js_slice(path, 120) for path in named[:MAX_FILES]]
101
+ files: Dict[str, str] = {}
102
+ total = 0
103
+ seen = set()
104
+ entries = envelope["files"]
105
+ if len(entries) > MAX_FILES:
106
+ problems.append(f"The bundle has {len(entries)} files; a factory bundle has at most {MAX_FILES}.")
107
+ for entry in entries[:MAX_FILES]:
108
+ if not isinstance(entry, dict) or not isinstance(entry.get("path"), str) or not isinstance(entry.get("content"), str):
109
+ problems.append("Every source entry needs a text path and text content.")
110
+ continue
111
+ path, content = entry["path"], entry["content"]
112
+ size = len(utf8(content))
113
+ total += size
114
+ if path in seen:
115
+ problems.append(f'"{js_slice(path, 80)}" appears more than once. Each file needs one exact version.')
116
+ continue
117
+ seen.add(path)
118
+ if not allowed_path(path):
119
+ if not path or _UNSAFE_PATH.search(path):
120
+ problems.append(f'"{js_slice(path, 80)}" is not a file a factory bundle may contain.')
121
+ elif js_slice(path, 120) not in left_out:
122
+ left_out.append(js_slice(path, 120))
123
+ continue
124
+ if "sha256" in entry:
125
+ recorded = entry["sha256"]
126
+ if not isinstance(recorded, str) or not _HEX64.fullmatch(recorded) or sha256(content) != recorded:
127
+ problems.append(f'"{path}" does not match its recorded checksum.')
128
+ continue
129
+ if "bytes" in entry:
130
+ recorded = entry["bytes"]
131
+ if isinstance(recorded, bool) or not isinstance(recorded, (int, float)) or recorded != size:
132
+ problems.append(f'"{path}" does not match its recorded byte length.')
133
+ continue
134
+ files[path] = content
135
+ if total > MAX_BYTES:
136
+ problems.append("The bundle is larger than 400,000 UTF-8 bytes.")
137
+ status = "inferred-draft" if envelope.get("status") == "inferred-draft" else "existing-source"
138
+ warnings = list(envelope.get("warnings") or [])[:10] if valid_warnings else []
139
+ return ReadBundle(normalize_files(files), problems, left_out, status, warnings)
140
+
141
+
142
+ def read_folder(root: str | os.PathLike[str]) -> Dict[str, str]:
143
+ """The files of a factory folder, as the engine's readFolder admits them."""
144
+ base = Path(root)
145
+ if not (base / "factory.yaml").is_file():
146
+ raise ValueError(f"{base} has no factory.yaml, so it is not a factory folder.")
147
+ files: Dict[str, str] = {}
148
+
149
+ def walk(folder: Path) -> None:
150
+ for entry in sorted(folder.iterdir(), key=lambda item: item.name):
151
+ name = entry.name
152
+ if name.startswith("."):
153
+ continue
154
+ rel = entry.relative_to(base).as_posix()
155
+ if entry.is_symlink():
156
+ if folder != base or name in SOURCE_FOLDERS or allowed_path(rel):
157
+ raise ValueError(f"Factory source cannot contain a symbolic link: {rel}")
158
+ continue
159
+ if entry.is_dir():
160
+ if name in SOURCE_FOLDERS or folder != base:
161
+ walk(entry)
162
+ continue
163
+ if folder == base and name in _GENERATED:
164
+ continue
165
+ if allowed_path(rel):
166
+ files[rel] = entry.read_text(encoding="utf-8")
167
+
168
+ walk(base)
169
+ return normalize_files(files)
170
+
171
+
172
+ PULL_MANIFEST = ".factoryhub-pull.json"
173
+ _NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
174
+
175
+
176
+ def _writable_root(folder: str | os.PathLike[str]) -> Path:
177
+ """The folder files are written into, made if missing; a folder that is a symbolic link is refused."""
178
+ root = Path(os.path.abspath(folder))
179
+ if root.is_symlink():
180
+ raise ValueError(f"Refusing to write into {root}: it is a symbolic link.")
181
+ if root.exists() and not root.is_dir():
182
+ raise ValueError(f"Refusing to write into {root}: it is not a folder.")
183
+ root.mkdir(parents=True, exist_ok=True)
184
+ return root
185
+
186
+
187
+ def _safe_target(root: Path, path: str) -> Path:
188
+ """The path for one file under ``root``; no folder on the way, nor the file, may be a symbolic link."""
189
+ target = Path(os.path.abspath(root / path))
190
+ if root not in target.parents:
191
+ raise ValueError(f"Refusing to write {path!r} outside {root}.")
192
+ current = root
193
+ for part in target.relative_to(root).parts[:-1]:
194
+ current = current / part
195
+ if current.is_symlink():
196
+ raise ValueError(f"Refusing to write {path!r}: {current.relative_to(root).as_posix()} is a symbolic link.")
197
+ if not current.exists():
198
+ current.mkdir()
199
+ elif not current.is_dir():
200
+ raise ValueError(f"Refusing to write {path!r}: {current.relative_to(root).as_posix()} is not a folder.")
201
+ if target.is_symlink():
202
+ raise ValueError(f"Refusing to write {path!r}: it is a symbolic link.")
203
+ if target.exists() and not target.is_file():
204
+ raise ValueError(f"Refusing to write {path!r}: it is not a plain file.")
205
+ return target
206
+
207
+
208
+ def _write_one(target: Path, content: str) -> None:
209
+ handle = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | _NOFOLLOW, 0o644)
210
+ with os.fdopen(handle, "w", encoding="utf-8", newline="") as stream:
211
+ stream.write(content)
212
+
213
+
214
+ def write_files(folder: str | os.PathLike[str], files: Mapping[str, str]) -> None:
215
+ """Writes checked factory files under a folder, never outside it and never through a symbolic link."""
216
+ for path in files:
217
+ if not allowed_path(path):
218
+ raise ValueError(f"Refusing to write {path!r}: it is not a factory file.")
219
+ root = _writable_root(folder)
220
+ for path, content in files.items():
221
+ _write_one(_safe_target(root, path), content)
222
+
223
+
224
+ def write_pulled(folder: str | os.PathLike[str], files: Mapping[str, str], *, replace: bool = False, record: Optional[Mapping[str, Any]] = None) -> List[str]:
225
+ """Writes a pulled factory and records what it wrote in PULL_MANIFEST.
226
+
227
+ With ``replace``, files an earlier pull recorded that the new version no
228
+ longer has are removed; no other file is ever deleted. Returns the
229
+ removed paths. The same rules as the engine's writePulled.
230
+ """
231
+ root = _writable_root(folder)
232
+ removed: List[str] = []
233
+ if replace:
234
+ for path in _read_manifest(root):
235
+ if path in files or not allowed_path(path):
236
+ continue
237
+ try:
238
+ target = _safe_target(root, path)
239
+ except ValueError:
240
+ continue
241
+ if target.is_file() and not target.is_symlink():
242
+ target.unlink()
243
+ removed.append(path)
244
+ write_files(root, files)
245
+ manifest = {"format": "factoryhub.pull/v1", **dict(record or {}), "files": list(files)}
246
+ _write_one(_safe_target(root, PULL_MANIFEST), json.dumps(manifest, indent=2) + "\n")
247
+ return removed
248
+
249
+
250
+ def _read_manifest(root: Path) -> List[str]:
251
+ path = root / PULL_MANIFEST
252
+ if path.is_symlink() or not path.is_file():
253
+ return []
254
+ try:
255
+ data = json.loads(path.read_text(encoding="utf-8"))
256
+ except ValueError:
257
+ return []
258
+ listed = data.get("files") if isinstance(data, dict) else None
259
+ return [item for item in listed if isinstance(item, str)] if isinstance(listed, list) else []
@@ -0,0 +1,118 @@
1
+ """Canonical JSON and hashes, byte for byte as the factoryhub engine makes them.
2
+
3
+ The engine (packages/engine/src/factory-engine.mjs) signs and hashes
4
+ ``canonical(value)``: object keys sorted at every level, no whitespace, each
5
+ key and string written by JavaScript's ``JSON.stringify``. For JSON data this
6
+ is the JSON Canonicalization Scheme (RFC 8785). Matching it from Python takes
7
+ four details JavaScript decides:
8
+
9
+ * keys sort by UTF-16 code units, not by code points;
10
+ * every number is an IEEE 754 double, written the way ``Number.prototype.toString`` writes it
11
+ (``1`` for ``1.0``, ``1e+21``, ``1e-7``), and NaN or infinity as ``null``;
12
+ * strings escape ``"``, ``\\``, the control characters and lone surrogates, and nothing else;
13
+ * text is hashed as UTF-8 with lone surrogates replaced by U+FFFD, as ``TextEncoder`` does.
14
+
15
+ ``test/fixtures/sdk/canonical.json`` holds the cases both implementations must agree on.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import hashlib
21
+ import math
22
+ import re
23
+ from typing import Any, Mapping
24
+
25
+ __all__ = ["canonical", "sha256", "utf8", "js_number", "js_slice", "utf16_key"]
26
+
27
+ _SAFE = 2**53
28
+ _SURROGATE = re.compile("[\ud800-\udfff]")
29
+ _ESCAPES = {'"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", "\t": "\\t"}
30
+ _NEEDS_ESCAPE = re.compile('["\\\\\x00-\x1f\ud800-\udfff]')
31
+
32
+
33
+ def utf8(text: str) -> bytes:
34
+ """UTF-8 as TextEncoder makes it: a lone surrogate becomes U+FFFD."""
35
+ return _SURROGATE.sub("�", text).encode("utf-8")
36
+
37
+
38
+ def sha256(text: str) -> str:
39
+ """The hex SHA-256 of a text's UTF-8 bytes, as the engine's sha256()."""
40
+ return hashlib.sha256(utf8(str(text))).hexdigest()
41
+
42
+
43
+ def utf16_key(text: str) -> bytes:
44
+ """A sort key that orders strings by UTF-16 code units, as Array.prototype.sort does."""
45
+ return text.encode("utf-16-be", "surrogatepass")
46
+
47
+
48
+ def js_slice(text: str, end: int) -> str:
49
+ """``text.slice(0, end)`` in JavaScript: counted in UTF-16 code units."""
50
+ units = text.encode("utf-16-le", "surrogatepass")
51
+ if len(units) <= end * 2:
52
+ return text
53
+ return units[: end * 2].decode("utf-16-le", "surrogatepass")
54
+
55
+
56
+ def js_number(value: float | int) -> str:
57
+ """A number as JavaScript's JSON.stringify writes it."""
58
+ if isinstance(value, int) and abs(value) <= _SAFE:
59
+ return str(value)
60
+ number = float(value)
61
+ if math.isnan(number) or math.isinf(number):
62
+ return "null"
63
+ if number == 0:
64
+ return "0"
65
+ sign = "-" if number < 0 else ""
66
+ mantissa, _, exponent = repr(abs(number)).partition("e")
67
+ whole, _, fraction = mantissa.partition(".")
68
+ power = int(exponent) if exponent else 0
69
+ if whole.strip("0"):
70
+ digits = (whole + fraction).lstrip("0")
71
+ point = len(whole.lstrip("0")) + power
72
+ else:
73
+ stripped = fraction.lstrip("0")
74
+ digits = stripped
75
+ point = power - (len(fraction) - len(stripped))
76
+ digits = digits.rstrip("0") or "0"
77
+ size = len(digits)
78
+ # ECMAScript Number::toString: value = 0.digits * 10^point.
79
+ if size <= point <= 21:
80
+ text = digits + "0" * (point - size)
81
+ elif 0 < point <= 21:
82
+ text = f"{digits[:point]}.{digits[point:]}"
83
+ elif -6 < point <= 0:
84
+ text = f"0.{'0' * -point}{digits}"
85
+ else:
86
+ shift = point - 1
87
+ mark = "+" if shift >= 0 else "-"
88
+ text = f"{digits[0]}{'.' + digits[1:] if size > 1 else ''}e{mark}{abs(shift)}"
89
+ return sign + text
90
+
91
+
92
+ def _escape(match: re.Match[str]) -> str:
93
+ char = match.group(0)
94
+ return _ESCAPES.get(char) or f"\\u{ord(char):04x}"
95
+
96
+
97
+ def _string(text: str) -> str:
98
+ return f'"{_NEEDS_ESCAPE.sub(_escape, text)}"'
99
+
100
+
101
+ def canonical(value: Any) -> str:
102
+ """The engine's canonical JSON of a value parsed from JSON."""
103
+ if value is None:
104
+ return "null"
105
+ if value is True:
106
+ return "true"
107
+ if value is False:
108
+ return "false"
109
+ if isinstance(value, (int, float)):
110
+ return js_number(value)
111
+ if isinstance(value, str):
112
+ return _string(value)
113
+ if isinstance(value, (list, tuple)):
114
+ return "[" + ",".join(canonical(item) for item in value) + "]"
115
+ if isinstance(value, Mapping):
116
+ keys = sorted((str(key) for key in value.keys()), key=utf16_key)
117
+ return "{" + ",".join(f"{_string(key)}:{canonical(value[key])}" for key in keys) + "}"
118
+ raise TypeError(f"canonical() takes JSON data, not {type(value).__name__}")
@@ -0,0 +1,174 @@
1
+ """Where factoryhub keeps personal access tokens; shared with the factoryhub CLI.
2
+
3
+ ``FACTORYHUB_TOKEN`` wins when it is set, for the production hub or the hub
4
+ ``FACTORYHUB_BASE_URL`` names; it is never sent to any other address.
5
+ Otherwise the token ``login()`` or ``factoryhub login`` stored for a hub
6
+ address, in ``${XDG_CONFIG_HOME:-~/.config}/factoryhub/credentials.json``: a
7
+ JSON object keyed by hub address. On macOS and Linux only the person may read
8
+ it (mode 0600), and a file others can read is refused, as ssh refuses a
9
+ readable key. On Windows no permissions are set: the file is as private as the
10
+ person's user folder. Each record keeps its origin: "device" for a token
11
+ received by device login, "pasted" for one passed in. Nothing here prints a
12
+ token.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import re
20
+ import stat
21
+ import zlib
22
+ import tempfile
23
+ import time
24
+ from dataclasses import dataclass
25
+ from datetime import datetime, timezone
26
+ from pathlib import Path
27
+ from typing import Any, Dict, Mapping, Optional
28
+
29
+ TOKEN_ENV = "FACTORYHUB_TOKEN"
30
+ # A personal access token as the hub mints it: fhpat_, 43 random base62
31
+ # characters and a 6-character base62 CRC-32 of everything before it. The hub
32
+ # refuses that shape with a wrong checksum without looking it up, so the
33
+ # client does too. Tokens made before the checksum (fhpat_ + 43 base64url) stay
34
+ # valid at the hub until GET /api/admin/token-formats counts none left; the
35
+ # client drops that shape in the release after the hub does (helm-tracker#373).
36
+ _CURRENT_TOKEN = re.compile(r"\Afhpat_[0-9A-Za-z]{49}\Z")
37
+ _OLDER_TOKEN = re.compile(r"\Afhpat_[A-Za-z0-9_-]{43}\Z")
38
+ _BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
39
+ #: What a token looks like, for messages that refuse one.
40
+ TOKEN_WORDS = "they start with fhpat_ and are 55 characters long (49 for one made before the checksum)"
41
+
42
+
43
+ def _base62(value: int, width: int = 6) -> str:
44
+ out = ""
45
+ while True:
46
+ value, digit = divmod(value, 62)
47
+ out = _BASE62[digit] + out
48
+ if value == 0:
49
+ return out.rjust(width, "0")
50
+
51
+
52
+ def is_token(value: Any) -> bool:
53
+ """Whether ``value`` is a personal access token the hub could have minted:
54
+ the current shape with its checksum right, or the older shape."""
55
+ if not isinstance(value, str):
56
+ return False
57
+ if _OLDER_TOKEN.fullmatch(value):
58
+ return True
59
+ return bool(_CURRENT_TOKEN.fullmatch(value)) and _base62(zlib.crc32(value[:-6].encode("utf-8"))) == value[-6:]
60
+ DEFAULT_HUB = "https://factory.mindburn.org"
61
+ _POSIX = os.name == "posix"
62
+ #: How private the credentials file is on this computer, for messages.
63
+ PRIVACY = "readable only by you (mode 0600)" if _POSIX else "protected only by your Windows user folder's permissions: factoryhub does not set file permissions on Windows"
64
+
65
+
66
+ def credentials_path(env: Optional[Mapping[str, str]] = None) -> Path:
67
+ env = os.environ if env is None else env
68
+ config = env.get("XDG_CONFIG_HOME") or os.path.join(env.get("HOME") or env.get("USERPROFILE") or str(Path.home()), ".config")
69
+ return Path(config) / "factoryhub" / "credentials.json"
70
+
71
+
72
+ def _read_all(env: Optional[Mapping[str, str]]) -> Dict[str, Any]:
73
+ path = credentials_path(env)
74
+ try:
75
+ info = path.stat()
76
+ except FileNotFoundError:
77
+ return {}
78
+ if _POSIX and info.st_mode & (stat.S_IRWXG | stat.S_IRWXO):
79
+ raise PermissionError(f'{path} can be read by other users of this computer, so factoryhub will not use it. Run "chmod 600 {path}" and try again.')
80
+ try:
81
+ data = json.loads(path.read_text(encoding="utf-8"))
82
+ except ValueError as error:
83
+ raise ValueError(f'{path} is not valid JSON. Delete it and log in again.') from error
84
+ return data if isinstance(data, dict) else {}
85
+
86
+
87
+ def _write_all(env: Optional[Mapping[str, str]], data: Dict[str, Any]) -> Path:
88
+ path = credentials_path(env)
89
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
90
+ # Created 0600 beside the file and renamed over it: never readable by
91
+ # others, never half written.
92
+ handle, temporary = tempfile.mkstemp(prefix=".credentials.", suffix=".tmp", dir=path.parent)
93
+ try:
94
+ if _POSIX:
95
+ os.fchmod(handle, 0o600)
96
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
97
+ stream.write(json.dumps(data, indent=2) + "\n")
98
+ os.replace(temporary, path)
99
+ except BaseException:
100
+ if os.path.exists(temporary):
101
+ os.unlink(temporary)
102
+ raise
103
+ return path
104
+
105
+
106
+ def stored_credential(base: str, env: Optional[Mapping[str, str]] = None) -> Optional[Dict[str, Any]]:
107
+ record = _read_all(env).get(base)
108
+ return record if isinstance(record, dict) and isinstance(record.get("token"), str) else None
109
+
110
+
111
+ def save_credential(base: str, record: Mapping[str, Any], env: Optional[Mapping[str, str]] = None) -> Path:
112
+ """Stores a token for one hub. ``record["origin"]`` is "device" or "pasted"."""
113
+ if not is_token(record.get("token")):
114
+ raise ValueError("That is not a factoryhub personal access token.")
115
+ if record.get("origin") not in ("device", "pasted"):
116
+ raise ValueError('A stored token needs its origin: "device" or "pasted".')
117
+ data = _read_all(env)
118
+ data[base] = {**record, "saved": datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")}
119
+ return _write_all(env, data)
120
+
121
+
122
+ def delete_credential(base: str, env: Optional[Mapping[str, str]] = None) -> bool:
123
+ data = _read_all(env)
124
+ if base not in data:
125
+ return False
126
+ del data[base]
127
+ if data:
128
+ _write_all(env, data)
129
+ else:
130
+ credentials_path(env).unlink(missing_ok=True)
131
+ return True
132
+
133
+
134
+ @dataclass
135
+ class ResolvedToken:
136
+ token: Optional[str]
137
+ source: Optional[str] # "env", "file" or None
138
+ record: Optional[Dict[str, Any]]
139
+ expired: bool = False
140
+ warning: Optional[str] = None
141
+
142
+
143
+ def _same_base(a: Optional[str], b: Optional[str]) -> bool:
144
+ return bool(a and b) and str(a).rstrip("/") == str(b).rstrip("/")
145
+
146
+
147
+ def env_token_goes_to(base: str, env: Mapping[str, str]) -> bool:
148
+ """Whether FACTORYHUB_TOKEN may be sent to ``base``: production, or the hub FACTORYHUB_BASE_URL names."""
149
+ return _same_base(base, DEFAULT_HUB) or _same_base(base, env.get("FACTORYHUB_BASE_URL"))
150
+
151
+
152
+ def _expired(expires: Any, now: float) -> bool:
153
+ if not isinstance(expires, str) or not expires:
154
+ return False
155
+ try:
156
+ moment = datetime.fromisoformat(expires.replace("Z", "+00:00"))
157
+ except ValueError:
158
+ return False
159
+ return moment.timestamp() <= now
160
+
161
+
162
+ def resolve_token(base: str, env: Optional[Mapping[str, str]] = None, now: Optional[float] = None) -> ResolvedToken:
163
+ env = os.environ if env is None else env
164
+ from_env = (env.get(TOKEN_ENV) or "").strip()
165
+ warning = None
166
+ if from_env and env_token_goes_to(base, env):
167
+ return ResolvedToken(from_env, "env", None)
168
+ if from_env:
169
+ warning = f"FACTORYHUB_TOKEN was not sent to {base.rstrip('/')}: it goes only to {DEFAULT_HUB} or to the address in FACTORYHUB_BASE_URL."
170
+ record = stored_credential(base, env)
171
+ if not record:
172
+ return ResolvedToken(None, None, None, warning=warning)
173
+ expired = _expired(record.get("expires"), time.time() if now is None else now)
174
+ return ResolvedToken(None if expired else record["token"], "file", record, expired, warning)