spatial-computing 0.15.0__tar.gz → 0.17.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.
- {spatial_computing-0.15.0/spatial_computing.egg-info → spatial_computing-0.17.0}/PKG-INFO +2 -2
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/README.md +1 -1
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/pyproject.toml +2 -1
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/__init__.py +1 -1
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/cli.py +24 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/core/registry.py +2 -2
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/platform/billing.py +46 -2
- spatial_computing-0.17.0/spatial/platform/db.py +107 -0
- spatial_computing-0.17.0/spatial/platform/mailer.py +57 -0
- spatial_computing-0.17.0/spatial/platform/oidc.py +124 -0
- spatial_computing-0.17.0/spatial/platform/pdf.py +86 -0
- spatial_computing-0.17.0/spatial/platform/qr.py +196 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/platform/server.py +219 -17
- spatial_computing-0.17.0/spatial/platform/service.py +1323 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/platform/static/app.js +147 -24
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/platform/static/style.css +7 -0
- spatial_computing-0.17.0/spatial/platform/totp.py +49 -0
- spatial_computing-0.17.0/spatial/platform/vat.py +93 -0
- spatial_computing-0.17.0/spatial/runtime/desktop/Dockerfile +11 -0
- spatial_computing-0.17.0/spatial/runtime/desktop/__init__.py +97 -0
- spatial_computing-0.17.0/spatial/runtime/desktop/start.sh +16 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0/spatial_computing.egg-info}/PKG-INFO +2 -2
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial_computing.egg-info/SOURCES.txt +12 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_platform.py +3 -1
- spatial_computing-0.17.0/tests/test_platform2.py +641 -0
- spatial_computing-0.17.0/tests/test_qr.py +37 -0
- spatial_computing-0.17.0/tests/test_runtime.py +245 -0
- spatial_computing-0.17.0/tests/test_sso.py +216 -0
- spatial_computing-0.15.0/spatial/platform/db.py +0 -61
- spatial_computing-0.15.0/spatial/platform/service.py +0 -666
- spatial_computing-0.15.0/tests/test_runtime.py +0 -122
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/LICENSE +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/setup.cfg +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/ai/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/ai/kvcache.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/ai/llm.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/compute/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/compute/cost.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/compute/detect.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/compute/monitor.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/compute/scheduler.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/compute/taskqueue.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/compute/worker.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/compute/workloads.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/core/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/core/auth.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/core/energy.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/core/ledger.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/core/model.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/core/protocol.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/fabric/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/fabric/cuda.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/fabric/devices.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/fabric/metal.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/fabric/metal_mandel.swift +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/fabric/metal_run.swift +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/fleet/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/fleet/agent.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/fleet/alerts.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/fleet/dashboard.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/fleet/ha.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/fleet/hub.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/holographic/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/holographic/cgh.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/holographic/model.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/intelligence/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/intelligence/predictor.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/interconnect/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/interconnect/collectives.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/interconnect/comm.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/interconnect/model.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/interconnect/tasks.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/kernel/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/kernel/dsl.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/kernel/library.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/memory/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/memory/fararray.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/memory/pageserver.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/memory/secure.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/memory/shared.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/memory/tiered.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/platform/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/platform/security.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/platform/static/fonts/DMMono-normal-400.woff2 +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/platform/static/fonts/DMMono-normal-500.woff2 +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/platform/static/fonts/InstrumentSerif-italic-400.woff2 +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/platform/static/fonts/InstrumentSerif-normal-400.woff2 +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/platform/static/fonts/Inter-normal-400.woff2 +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/platform/static/fonts/Inter-normal-500.woff2 +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/platform/static/fonts/Inter-normal-600.woff2 +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/platform/static/fonts.css +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/platform/static/index.html +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/platform/static/logo.svg +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/q/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/q/__main__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/q/backends/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/q/codegen.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/q/compiler.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/q/ir.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/q/lexer.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/q/parser.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/q/qir.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/q/runtime.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/q/sim.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/runtime/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/runtime/envs.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/runtime/inspect.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/runtime/microvm.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/runtime/planner.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/runtime/runner.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/runtime/toolchain.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/scientific/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/scientific/jobs.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/simulation/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/simulation/heat.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/simulation/nbody.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/unified/__init__.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/unified/model.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/unified/planner.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial/unified/providers.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial_computing.egg-info/dependency_links.txt +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial_computing.egg-info/entry_points.txt +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial_computing.egg-info/requires.txt +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/spatial_computing.egg-info/top_level.txt +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_auth.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_compute.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_core.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_dashboard.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_domains.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_engines.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_fabric.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_fleet.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_ha.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_hardening.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_interconnect.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_kernel.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_memory.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_optimizer.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_q.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_quorum.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_unified.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_v02.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_v03.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_v05.py +0 -0
- {spatial_computing-0.15.0 → spatial_computing-0.17.0}/tests/test_v07.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: spatial-computing
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.17.0
|
|
4
4
|
Summary: Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, hybrid quantum language)
|
|
5
5
|
Author: Spatial Computing contributors
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -37,7 +37,7 @@ Dynamic: license-file
|
|
|
37
37
|
|
|
38
38
|
One objective for the whole infrastructure: get every job done correctly at the lowest cost, and prove it. Spatial Computing prices every way to run a job across compute, memory, runtime, quantum, AI, science and a fleet of machines, picks the cheapest, and records the estimate next to what really happened. A gain is claimed only when it is measured. It does not add RAM, cores or GPUs: it compares execution strategies on the hardware you have, trades one resource for another in numbers, and says plainly what it cannot do.
|
|
39
39
|
|
|
40
|
-
> **Status: v0.
|
|
40
|
+
> **Status: v0.17.0, early-stage open-source toolkit.** Everything here was built and measured on a single 2017 MacBook Pro (Intel i7-7660U, 2 cores, 16 GB). Nothing has been proven on a second machine, a data-center GPU or a real quantum computer. See [Limitations](docs/LIMITATIONS.md) and the [site](https://spatial-computing-ecru.vercel.app).
|
|
41
41
|
|
|
42
42
|
[Français](README.fr.md)
|
|
43
43
|
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
One objective for the whole infrastructure: get every job done correctly at the lowest cost, and prove it. Spatial Computing prices every way to run a job across compute, memory, runtime, quantum, AI, science and a fleet of machines, picks the cheapest, and records the estimate next to what really happened. A gain is claimed only when it is measured. It does not add RAM, cores or GPUs: it compares execution strategies on the hardware you have, trades one resource for another in numbers, and says plainly what it cannot do.
|
|
6
6
|
|
|
7
|
-
> **Status: v0.
|
|
7
|
+
> **Status: v0.17.0, early-stage open-source toolkit.** Everything here was built and measured on a single 2017 MacBook Pro (Intel i7-7660U, 2 cores, 16 GB). Nothing has been proven on a second machine, a data-center GPU or a real quantum computer. See [Limitations](docs/LIMITATIONS.md) and the [site](https://spatial-computing-ecru.vercel.app).
|
|
8
8
|
|
|
9
9
|
[Français](README.fr.md)
|
|
10
10
|
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "spatial-computing"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.17.0"
|
|
8
8
|
description = "Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, hybrid quantum language)"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "Apache-2.0"
|
|
@@ -34,6 +34,7 @@ include = ["spatial*"]
|
|
|
34
34
|
[tool.setuptools.package-data]
|
|
35
35
|
"spatial.fabric" = ["*.swift"]
|
|
36
36
|
"spatial.platform" = ["static/*", "static/fonts/*"]
|
|
37
|
+
"spatial.runtime.desktop" = ["Dockerfile", "start.sh"]
|
|
37
38
|
|
|
38
39
|
[tool.pytest.ini_options]
|
|
39
40
|
testpaths = ["tests"]
|
|
@@ -103,6 +103,25 @@ def cmd_agent(a):
|
|
|
103
103
|
return 0
|
|
104
104
|
|
|
105
105
|
|
|
106
|
+
def cmd_desktop(a):
|
|
107
|
+
from .runtime.desktop import DesktopError, start
|
|
108
|
+
try:
|
|
109
|
+
d = start(a.app, clipboard=not a.no_clipboard, view_only_link=a.view_link)
|
|
110
|
+
except DesktopError as e:
|
|
111
|
+
print(f"spatial: {e}", file=sys.stderr)
|
|
112
|
+
return 1
|
|
113
|
+
print(f"desktop ({a.app}, {d.runtime}), loopback only: {d.url}", flush=True)
|
|
114
|
+
if d.view_url:
|
|
115
|
+
print(f"view-only link (watch, cannot type or click): {d.view_url}", flush=True)
|
|
116
|
+
print("Ctrl+C removes it", flush=True)
|
|
117
|
+
try:
|
|
118
|
+
while True:
|
|
119
|
+
time.sleep(3600)
|
|
120
|
+
except KeyboardInterrupt:
|
|
121
|
+
d.stop()
|
|
122
|
+
return 0
|
|
123
|
+
|
|
124
|
+
|
|
106
125
|
def cmd_platform(a):
|
|
107
126
|
from .platform import server
|
|
108
127
|
rest = [x for x in a.rest if x != "serve"] if a.rest[:1] == ["serve"] else a.rest
|
|
@@ -321,6 +340,11 @@ def main(argv=None):
|
|
|
321
340
|
p.add_argument("--workload"); p.add_argument("--params", default="{}"); p.add_argument("--needs", default="{}")
|
|
322
341
|
p.add_argument("--task-id", type=int)
|
|
323
342
|
p.set_defaults(fn=cmd_fleet)
|
|
343
|
+
p = sub.add_parser("desktop", help="run a graphical Linux app (xterm, xclock, mousepad) in a container and open it in your browser (noVNC, loopback only)")
|
|
344
|
+
p.add_argument("app", nargs="?", default="xterm", choices=["xterm", "xclock", "mousepad"])
|
|
345
|
+
p.add_argument("--no-clipboard", action="store_true", help="no copy and paste between your machine and the desktop")
|
|
346
|
+
p.add_argument("--view-link", action="store_true", help="also print a view-only link for people who only need to watch")
|
|
347
|
+
p.set_defaults(fn=cmd_desktop)
|
|
324
348
|
p = sub.add_parser("platform", help="account service: sign up, sign in, apps, API keys, usage, billing (`spatial platform serve --help`)")
|
|
325
349
|
p.add_argument("rest", nargs=argparse.REMAINDER)
|
|
326
350
|
p.set_defaults(fn=cmd_platform)
|
|
@@ -40,7 +40,7 @@ ENGINES: list[Engine] = [
|
|
|
40
40
|
"CUDA C and HIP generated, never compiled or run; two kernel shapes (2-D map, whole-grid sum with shared memory), no tiling or tensor cores"),
|
|
41
41
|
Engine("platform", "Console and account service", "spatial.platform", Status.FIRST_COMPONENTS,
|
|
42
42
|
"tests/test_platform.py (14 tests, real hub and agent), a driven browser session",
|
|
43
|
-
"one process with SQLite; no
|
|
43
|
+
"one process with SQLite; no SAML; tax tools are not a compliance engine; e-mail tested against a local SMTP stand-in, payments against a fake Stripe API only"),
|
|
44
44
|
Engine("planner", "Spatial Planner (the one objective)", "spatial.unified", Status.OPERATIONAL_PROTOTYPE,
|
|
45
45
|
"tests/test_unified.py",
|
|
46
46
|
"estimates come from probes and measured constants on one machine; calibration is a median of past ratios; no learned model; fleet and QPU pricing need the caller's prices"),
|
|
@@ -49,7 +49,7 @@ ENGINES: list[Engine] = [
|
|
|
49
49
|
"validated on one machine (agents on loopback); HA: active/standby for two hubs, majority election (election safety, no replicated log) for three or more, tested on one machine with simulated clocks; dashboard is read-only and local; recommendations are estimates; never applies changes by itself"),
|
|
50
50
|
Engine("runtime", "Spatial Runtime Engine", "spatial.runtime", Status.OPERATIONAL_PROTOTYPE,
|
|
51
51
|
"tests/test_runtime.py, benchmarks/bench_runtime.py",
|
|
52
|
-
"Windows: one console program and one GUI window (Notepad) under Wine, nothing more; containers: static Linux ELF, tested with Docker (Colima) and Podman;
|
|
52
|
+
"Windows: one console program and one GUI window (Notepad) under Wine, nothing more; containers: static Linux ELF, tested with Docker (Colima) and Podman; Linux GUI apps stream through a container and noVNC (three allow-listed apps)"),
|
|
53
53
|
Engine("q", "SPATIAL Q", "spatial.q", Status.OPERATIONAL_PROTOTYPE,
|
|
54
54
|
"tests/test_q.py, benchmarks/bench_q.py",
|
|
55
55
|
"no real QPU executed (OpenQASM 3 and QIR export only); simulator limited by RAM"),
|
|
@@ -18,17 +18,50 @@ from dataclasses import dataclass, field
|
|
|
18
18
|
|
|
19
19
|
DEFAULT_PRICING = {
|
|
20
20
|
"currency": "usd",
|
|
21
|
-
"note": "Example price list:
|
|
21
|
+
"note": "Example price list: the operator has not set real prices yet.",
|
|
22
22
|
"free_compute_hours_per_month": 1.0,
|
|
23
23
|
"compute_usd_per_hour": 0.10, # per hour of task wall time on the fleet
|
|
24
|
-
"min_invoice_usd": 0.50, # below this the period
|
|
24
|
+
"min_invoice_usd": 0.50, # below this the period is waived (no tiny charges)
|
|
25
|
+
"tax_label": "VAT",
|
|
26
|
+
"tax_rate_percent": 0.0, # default rate added to every invoice
|
|
27
|
+
"tax_by_country": {}, # {"FR": 20, "DE": 19}: overrides the default rate by the customer's billing country
|
|
28
|
+
"check_vat_with_vies": False, # ask the European Commission's VIES service when a customer saves a VAT id
|
|
29
|
+
"no_tax_with_vat_id_abroad": False, # simplified B2B reverse charge: a customer with a VAT id outside the seller's country pays no tax
|
|
25
30
|
}
|
|
26
31
|
|
|
32
|
+
PRICING_KEYS = {"currency": str, "note": str, "free_compute_hours_per_month": (int, float), "compute_usd_per_hour": (int, float), "min_invoice_usd": (int, float),
|
|
33
|
+
"tax_label": str, "tax_rate_percent": (int, float), "tax_by_country": dict, "no_tax_with_vat_id_abroad": bool, "check_vat_with_vies": bool}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def validate_pricing(d: dict) -> dict:
|
|
37
|
+
"""Return a clean pricing dict or raise ValueError. Bounds keep a typo from charging 1000x."""
|
|
38
|
+
out = dict(DEFAULT_PRICING)
|
|
39
|
+
for k, v in d.items():
|
|
40
|
+
if k not in PRICING_KEYS:
|
|
41
|
+
raise ValueError(f"unknown pricing field '{k}'")
|
|
42
|
+
if isinstance(v, bool) != (PRICING_KEYS[k] is bool) or not isinstance(v, PRICING_KEYS[k]):
|
|
43
|
+
raise ValueError(f"'{k}' has the wrong type")
|
|
44
|
+
out[k] = v
|
|
45
|
+
if not (isinstance(out["currency"], str) and len(out["currency"]) == 3 and out["currency"].isalpha()):
|
|
46
|
+
raise ValueError("currency must be a 3-letter code")
|
|
47
|
+
for k, lo, hi in (("free_compute_hours_per_month", 0, 100000), ("compute_usd_per_hour", 0, 1000), ("min_invoice_usd", 0, 1000), ("tax_rate_percent", 0, 50)):
|
|
48
|
+
if not lo <= out[k] <= hi:
|
|
49
|
+
raise ValueError(f"'{k}' must be between {lo} and {hi}")
|
|
50
|
+
for c, r in out["tax_by_country"].items():
|
|
51
|
+
if not (isinstance(c, str) and len(c) == 2 and c.isalpha() and isinstance(r, (int, float)) and not isinstance(r, bool) and 0 <= r <= 50):
|
|
52
|
+
raise ValueError("tax_by_country must map 2-letter country codes to rates between 0 and 50")
|
|
53
|
+
out["tax_by_country"] = {c.upper(): r for c, r in out["tax_by_country"].items()}
|
|
54
|
+
out["currency"] = out["currency"].lower()
|
|
55
|
+
return out
|
|
56
|
+
|
|
27
57
|
|
|
28
58
|
@dataclass
|
|
29
59
|
class Pricing:
|
|
30
60
|
data: dict = field(default_factory=lambda: dict(DEFAULT_PRICING))
|
|
31
61
|
|
|
62
|
+
def __post_init__(self):
|
|
63
|
+
self.data = {**DEFAULT_PRICING, **self.data} # fields added in later versions keep their defaults
|
|
64
|
+
|
|
32
65
|
@classmethod
|
|
33
66
|
def load(cls, path: str | None) -> "Pricing":
|
|
34
67
|
d = dict(DEFAULT_PRICING)
|
|
@@ -84,6 +117,17 @@ class Stripe:
|
|
|
84
117
|
raise PaymentError(f"payment provider error: {type(e).__name__}") from e
|
|
85
118
|
return r["url"], r["id"]
|
|
86
119
|
|
|
120
|
+
def refund(self, payment_intent: str, amount_usd: float) -> str:
|
|
121
|
+
"""Refund part of a card payment through Stripe. Returns the refund id."""
|
|
122
|
+
if not self.key:
|
|
123
|
+
raise PaymentError("payments are not configured on this server (no STRIPE_SECRET_KEY)")
|
|
124
|
+
form = urllib.parse.urlencode({"payment_intent": payment_intent, "amount": str(int(round(amount_usd * 100)))}).encode()
|
|
125
|
+
req = urllib.request.Request(self.base + "/v1/refunds", data=form, method="POST", headers={"Authorization": f"Bearer {self.key}", "Content-Type": "application/x-www-form-urlencoded"})
|
|
126
|
+
try:
|
|
127
|
+
return json.load(urllib.request.urlopen(req, timeout=15))["id"]
|
|
128
|
+
except Exception as e:
|
|
129
|
+
raise PaymentError(f"payment provider error: {type(e).__name__}") from e
|
|
130
|
+
|
|
87
131
|
def verify_webhook(self, payload: bytes, header: str, tolerance_s: int = 300, now: float | None = None) -> dict:
|
|
88
132
|
"""Check the Stripe-Signature header (t=..,v1=hmac_sha256(secret, 't.payload')) and return the event."""
|
|
89
133
|
if not self.whsec:
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""SQLite store. One connection guarded by a lock: enough for one service process; swap for Postgres behind
|
|
2
|
+
the same functions when you need several."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sqlite3
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
SCHEMA = """
|
|
10
|
+
CREATE TABLE IF NOT EXISTS users(
|
|
11
|
+
id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL, name TEXT NOT NULL, pw_hash TEXT NOT NULL,
|
|
12
|
+
created REAL NOT NULL, is_admin INTEGER NOT NULL DEFAULT 0, failed INTEGER NOT NULL DEFAULT 0, locked_until REAL NOT NULL DEFAULT 0,
|
|
13
|
+
email_verified INTEGER NOT NULL DEFAULT 0, totp_secret TEXT, totp_enabled INTEGER NOT NULL DEFAULT 0, totp_last_step INTEGER NOT NULL DEFAULT 0,
|
|
14
|
+
recovery TEXT NOT NULL DEFAULT '[]', personal_org INTEGER);
|
|
15
|
+
CREATE TABLE IF NOT EXISTS orgs(
|
|
16
|
+
id INTEGER PRIMARY KEY, name TEXT NOT NULL, created REAL NOT NULL, personal INTEGER NOT NULL DEFAULT 0,
|
|
17
|
+
billing_name TEXT NOT NULL DEFAULT '', billing_address TEXT NOT NULL DEFAULT '', billing_country TEXT NOT NULL DEFAULT '', vat_id TEXT NOT NULL DEFAULT '', vat_status TEXT NOT NULL DEFAULT '');
|
|
18
|
+
CREATE TABLE IF NOT EXISTS members(org_id INTEGER NOT NULL, user_id INTEGER NOT NULL, role TEXT NOT NULL, created REAL NOT NULL, PRIMARY KEY(org_id, user_id));
|
|
19
|
+
CREATE TABLE IF NOT EXISTS org_roles(org_id INTEGER NOT NULL, name TEXT NOT NULL, perms TEXT NOT NULL, created REAL NOT NULL, PRIMARY KEY(org_id, name));
|
|
20
|
+
CREATE TABLE IF NOT EXISTS sso_states(state_hash TEXT PRIMARY KEY, nonce TEXT NOT NULL, verifier TEXT NOT NULL, expires REAL NOT NULL, ip TEXT);
|
|
21
|
+
CREATE TABLE IF NOT EXISTS invites(
|
|
22
|
+
id INTEGER PRIMARY KEY, org_id INTEGER NOT NULL, email TEXT NOT NULL, role TEXT NOT NULL, token_hash TEXT UNIQUE NOT NULL, invited_by INTEGER NOT NULL,
|
|
23
|
+
created REAL NOT NULL, expires REAL NOT NULL, accepted REAL);
|
|
24
|
+
CREATE TABLE IF NOT EXISTS verifications(token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL, expires REAL NOT NULL);
|
|
25
|
+
CREATE TABLE IF NOT EXISTS challenges(token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL, expires REAL NOT NULL, attempts INTEGER NOT NULL DEFAULT 0, ip TEXT, ua TEXT);
|
|
26
|
+
CREATE TABLE IF NOT EXISTS settings(key TEXT PRIMARY KEY, value TEXT NOT NULL, updated REAL NOT NULL);
|
|
27
|
+
CREATE TABLE IF NOT EXISTS counters(name TEXT PRIMARY KEY, value INTEGER NOT NULL);
|
|
28
|
+
CREATE TABLE IF NOT EXISTS sessions(
|
|
29
|
+
token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL, csrf TEXT NOT NULL, created REAL NOT NULL, expires REAL NOT NULL, ip TEXT, ua TEXT);
|
|
30
|
+
CREATE TABLE IF NOT EXISTS apps(
|
|
31
|
+
id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, name TEXT NOT NULL, description TEXT NOT NULL DEFAULT '',
|
|
32
|
+
budget_usd REAL, created REAL NOT NULL, deleted REAL, org_id INTEGER);
|
|
33
|
+
CREATE TABLE IF NOT EXISTS api_keys(
|
|
34
|
+
id INTEGER PRIMARY KEY, app_id INTEGER NOT NULL, name TEXT NOT NULL, kind TEXT NOT NULL, cred_name TEXT NOT NULL,
|
|
35
|
+
hint TEXT NOT NULL, created REAL NOT NULL, expires REAL NOT NULL, revoked REAL);
|
|
36
|
+
CREATE TABLE IF NOT EXISTS usage(
|
|
37
|
+
id INTEGER PRIMARY KEY, app_id INTEGER NOT NULL, ts REAL NOT NULL, workload TEXT, node TEXT, ok INTEGER, seconds REAL NOT NULL);
|
|
38
|
+
CREATE INDEX IF NOT EXISTS usage_app_ts ON usage(app_id, ts);
|
|
39
|
+
CREATE TABLE IF NOT EXISTS offsets(name TEXT PRIMARY KEY, value INTEGER NOT NULL);
|
|
40
|
+
CREATE TABLE IF NOT EXISTS invoices(
|
|
41
|
+
id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, period TEXT NOT NULL, amount_usd REAL NOT NULL, status TEXT NOT NULL,
|
|
42
|
+
lines TEXT NOT NULL, created REAL NOT NULL, paid REAL, provider_ref TEXT, org_id INTEGER, number TEXT, subtotal_usd REAL, tax_rate REAL, tax_usd REAL,
|
|
43
|
+
billing TEXT, seller TEXT, payment_ref TEXT, credited_usd REAL NOT NULL DEFAULT 0);
|
|
44
|
+
CREATE TABLE IF NOT EXISTS credit_notes(
|
|
45
|
+
id INTEGER PRIMARY KEY, org_id INTEGER NOT NULL, invoice_id INTEGER NOT NULL, number TEXT NOT NULL, subtotal_usd REAL NOT NULL, tax_usd REAL NOT NULL,
|
|
46
|
+
total_usd REAL NOT NULL, reason TEXT NOT NULL, created REAL NOT NULL, status TEXT NOT NULL, refund_ref TEXT, created_by INTEGER);
|
|
47
|
+
CREATE TABLE IF NOT EXISTS resets(token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL, expires REAL NOT NULL, used INTEGER NOT NULL DEFAULT 0);
|
|
48
|
+
CREATE TABLE IF NOT EXISTS outbox(id INTEGER PRIMARY KEY, to_addr TEXT NOT NULL, subject TEXT NOT NULL, body TEXT NOT NULL, created REAL NOT NULL, sent REAL,
|
|
49
|
+
attempts INTEGER NOT NULL DEFAULT 0, next_try REAL NOT NULL DEFAULT 0, last_error TEXT);
|
|
50
|
+
CREATE TABLE IF NOT EXISTS tokens(
|
|
51
|
+
id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, name TEXT NOT NULL, token_hash TEXT UNIQUE NOT NULL, hint TEXT NOT NULL,
|
|
52
|
+
scope TEXT NOT NULL, created REAL NOT NULL, expires REAL NOT NULL, last_used REAL, revoked REAL);
|
|
53
|
+
CREATE TABLE IF NOT EXISTS events(id INTEGER PRIMARY KEY, ts REAL NOT NULL, user_id INTEGER, kind TEXT NOT NULL, detail TEXT);
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class DB:
|
|
58
|
+
def __init__(self, path: str = ":memory:"):
|
|
59
|
+
self.conn = sqlite3.connect(path, check_same_thread=False, isolation_level=None)
|
|
60
|
+
self.conn.row_factory = sqlite3.Row
|
|
61
|
+
self.lock = threading.RLock()
|
|
62
|
+
with self.lock:
|
|
63
|
+
self.conn.execute("PRAGMA journal_mode=WAL")
|
|
64
|
+
self.conn.execute("PRAGMA foreign_keys=ON")
|
|
65
|
+
self.conn.executescript(SCHEMA)
|
|
66
|
+
self._migrate()
|
|
67
|
+
|
|
68
|
+
def q(self, sql: str, args=()) -> list[sqlite3.Row]:
|
|
69
|
+
with self.lock:
|
|
70
|
+
return self.conn.execute(sql, args).fetchall()
|
|
71
|
+
|
|
72
|
+
def one(self, sql: str, args=()):
|
|
73
|
+
r = self.q(sql, args)
|
|
74
|
+
return r[0] if r else None
|
|
75
|
+
|
|
76
|
+
def x(self, sql: str, args=()) -> int:
|
|
77
|
+
with self.lock:
|
|
78
|
+
cur = self.conn.execute(sql, args)
|
|
79
|
+
return cur.lastrowid
|
|
80
|
+
|
|
81
|
+
def event(self, user_id, kind: str, detail: str = "") -> None:
|
|
82
|
+
self.x("INSERT INTO events(ts,user_id,kind,detail) VALUES(?,?,?,?)", (time.time(), user_id, kind, detail[:500]))
|
|
83
|
+
|
|
84
|
+
# ------------------------------------------------------------------ migration of databases created by older versions
|
|
85
|
+
ADD = {"users": [("email_verified", "INTEGER NOT NULL DEFAULT 0"), ("totp_secret", "TEXT"), ("totp_enabled", "INTEGER NOT NULL DEFAULT 0"),
|
|
86
|
+
("totp_last_step", "INTEGER NOT NULL DEFAULT 0"), ("recovery", "TEXT NOT NULL DEFAULT '[]'"), ("personal_org", "INTEGER")],
|
|
87
|
+
"apps": [("org_id", "INTEGER")],
|
|
88
|
+
"invoices": [("org_id", "INTEGER"), ("number", "TEXT"), ("subtotal_usd", "REAL"), ("tax_rate", "REAL"), ("tax_usd", "REAL"), ("billing", "TEXT"), ("seller", "TEXT"),
|
|
89
|
+
("payment_ref", "TEXT"), ("credited_usd", "REAL NOT NULL DEFAULT 0")],
|
|
90
|
+
"orgs": [("vat_status", "TEXT NOT NULL DEFAULT ''")],
|
|
91
|
+
"outbox": [("attempts", "INTEGER NOT NULL DEFAULT 0"), ("next_try", "REAL NOT NULL DEFAULT 0"), ("last_error", "TEXT")]}
|
|
92
|
+
|
|
93
|
+
def _migrate(self) -> None:
|
|
94
|
+
for table, cols in self.ADD.items():
|
|
95
|
+
have = {r["name"] for r in self.conn.execute(f"PRAGMA table_info({table})")}
|
|
96
|
+
for name, decl in cols:
|
|
97
|
+
if name not in have:
|
|
98
|
+
self.conn.execute(f"ALTER TABLE {table} ADD COLUMN {name} {decl}")
|
|
99
|
+
# the unique (user_id, period) constraint of the first version is replaced by (org_id, period)
|
|
100
|
+
self.conn.execute("CREATE UNIQUE INDEX IF NOT EXISTS invoices_org_period ON invoices(org_id, period)")
|
|
101
|
+
now = time.time()
|
|
102
|
+
for u in self.conn.execute("SELECT id, name FROM users WHERE personal_org IS NULL").fetchall(): # one personal organisation per user
|
|
103
|
+
oid = self.conn.execute("INSERT INTO orgs(name,created,personal) VALUES(?,?,1)", (u["name"] + "'s workspace", now)).lastrowid
|
|
104
|
+
self.conn.execute("INSERT INTO members(org_id,user_id,role,created) VALUES(?,?,?,?)", (oid, u["id"], "owner", now))
|
|
105
|
+
self.conn.execute("UPDATE users SET personal_org=? WHERE id=?", (oid, u["id"]))
|
|
106
|
+
self.conn.execute("UPDATE apps SET org_id=(SELECT personal_org FROM users WHERE users.id=apps.user_id) WHERE org_id IS NULL")
|
|
107
|
+
self.conn.execute("UPDATE invoices SET org_id=(SELECT personal_org FROM users WHERE users.id=invoices.user_id) WHERE org_id IS NULL")
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Outgoing e-mail: a queue in the database, delivered by SMTP with retries. Nothing is sent without SMTP settings;
|
|
2
|
+
messages then stay in the outbox (visible to the operator) instead of being lost."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import smtplib
|
|
6
|
+
import ssl
|
|
7
|
+
import time
|
|
8
|
+
from email.message import EmailMessage
|
|
9
|
+
|
|
10
|
+
MAX_ATTEMPTS = 6
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Mailer:
|
|
14
|
+
def __init__(self, db, smtp: dict | None, clock=time.time):
|
|
15
|
+
self.db, self.smtp, self.clock = db, smtp, clock
|
|
16
|
+
|
|
17
|
+
def queue(self, to: str, subject: str, body: str) -> int:
|
|
18
|
+
mid = self.db.x("INSERT INTO outbox(to_addr,subject,body,created,next_try) VALUES(?,?,?,?,?)", (to, subject, body, self.clock(), 0))
|
|
19
|
+
self.deliver(mid)
|
|
20
|
+
return mid
|
|
21
|
+
|
|
22
|
+
def _send(self, to: str, subject: str, body: str) -> None:
|
|
23
|
+
c = self.smtp
|
|
24
|
+
m = EmailMessage(); m["From"], m["To"], m["Subject"] = c["from"], to, subject; m.set_content(body)
|
|
25
|
+
if c.get("ssl"):
|
|
26
|
+
s = smtplib.SMTP_SSL(c["host"], c.get("port", 465), timeout=15, context=ssl.create_default_context())
|
|
27
|
+
else:
|
|
28
|
+
s = smtplib.SMTP(c["host"], c.get("port", 587), timeout=15)
|
|
29
|
+
with s:
|
|
30
|
+
if c.get("starttls", True) and not c.get("ssl"):
|
|
31
|
+
s.starttls(context=ssl.create_default_context())
|
|
32
|
+
if c.get("user"):
|
|
33
|
+
s.login(c["user"], c["password"])
|
|
34
|
+
s.send_message(m)
|
|
35
|
+
|
|
36
|
+
def deliver(self, mid: int) -> bool:
|
|
37
|
+
r = self.db.one("SELECT * FROM outbox WHERE id=?", (mid,))
|
|
38
|
+
if not r or r["sent"] is not None or not self.smtp:
|
|
39
|
+
return False
|
|
40
|
+
try:
|
|
41
|
+
self._send(r["to_addr"], r["subject"], r["body"])
|
|
42
|
+
except Exception as e:
|
|
43
|
+
n = r["attempts"] + 1
|
|
44
|
+
self.db.x("UPDATE outbox SET attempts=?, last_error=?, next_try=? WHERE id=?",
|
|
45
|
+
(n, f"{type(e).__name__}: {e}"[:200], self.clock() + min(3600, 30 * 2 ** n), mid))
|
|
46
|
+
return False
|
|
47
|
+
self.db.x("UPDATE outbox SET sent=?, attempts=attempts+1, last_error=NULL WHERE id=?", (self.clock(), mid))
|
|
48
|
+
return True
|
|
49
|
+
|
|
50
|
+
def flush(self) -> int:
|
|
51
|
+
"""Retry unsent messages that are due (called every minute by the service). Returns how many were sent."""
|
|
52
|
+
if not self.smtp:
|
|
53
|
+
return 0
|
|
54
|
+
n = 0
|
|
55
|
+
for r in self.db.q("SELECT id FROM outbox WHERE sent IS NULL AND attempts<? AND next_try<=? ORDER BY id LIMIT 50", (MAX_ATTEMPTS, self.clock())):
|
|
56
|
+
n += self.deliver(r["id"])
|
|
57
|
+
return n
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Single sign-on with OpenID Connect (authorization code flow + PKCE), for an identity provider the operator configures
|
|
2
|
+
(Google, Microsoft Entra, Okta, Keycloak, ...). The ID token is verified here: RS256 signature against the provider's published
|
|
3
|
+
keys, issuer, audience, expiry, nonce. Only the standard library and `cryptography` (already a dependency of the wire protocol).
|
|
4
|
+
SAML is not implemented."""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import base64
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import secrets
|
|
11
|
+
import time
|
|
12
|
+
import urllib.parse
|
|
13
|
+
import urllib.request
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
|
|
16
|
+
from cryptography.exceptions import InvalidSignature
|
|
17
|
+
from cryptography.hazmat.primitives import hashes
|
|
18
|
+
from cryptography.hazmat.primitives.asymmetric import padding, rsa
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class OidcError(Exception):
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def b64d(s: str) -> bytes:
|
|
26
|
+
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def b64e(b: bytes) -> str:
|
|
30
|
+
return base64.urlsafe_b64encode(b).decode().rstrip("=")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def pkce_pair() -> tuple[str, str]:
|
|
34
|
+
verifier = b64e(secrets.token_bytes(48))
|
|
35
|
+
return verifier, b64e(hashlib.sha256(verifier.encode()).digest())
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class Oidc:
|
|
40
|
+
issuer: str
|
|
41
|
+
client_id: str
|
|
42
|
+
client_secret: str
|
|
43
|
+
redirect_uri: str
|
|
44
|
+
name: str = "Single sign-on"
|
|
45
|
+
allowed_domains: tuple = ()
|
|
46
|
+
auto_create: bool = True
|
|
47
|
+
timeout: float = 10.0
|
|
48
|
+
_disc: dict | None = field(default=None, repr=False)
|
|
49
|
+
_jwks: dict = field(default_factory=dict, repr=False)
|
|
50
|
+
|
|
51
|
+
def __post_init__(self):
|
|
52
|
+
if not (self.issuer.startswith("https://") or self.issuer.startswith("http://127.0.0.1") or self.issuer.startswith("http://localhost")):
|
|
53
|
+
raise OidcError("the issuer must be an https URL (plain http is accepted for localhost only)")
|
|
54
|
+
|
|
55
|
+
def _get(self, url: str) -> dict:
|
|
56
|
+
return json.load(urllib.request.urlopen(url, timeout=self.timeout))
|
|
57
|
+
|
|
58
|
+
def discovery(self) -> dict:
|
|
59
|
+
if self._disc is None:
|
|
60
|
+
d = self._get(self.issuer.rstrip("/") + "/.well-known/openid-configuration")
|
|
61
|
+
if d.get("issuer", "").rstrip("/") != self.issuer.rstrip("/"):
|
|
62
|
+
raise OidcError("the provider's discovery document names a different issuer")
|
|
63
|
+
self._disc = d
|
|
64
|
+
return self._disc
|
|
65
|
+
|
|
66
|
+
def authorize_url(self, state: str, nonce: str, challenge: str) -> str:
|
|
67
|
+
q = {"response_type": "code", "client_id": self.client_id, "redirect_uri": self.redirect_uri, "scope": "openid email profile",
|
|
68
|
+
"state": state, "nonce": nonce, "code_challenge": challenge, "code_challenge_method": "S256"}
|
|
69
|
+
return self.discovery()["authorization_endpoint"] + "?" + urllib.parse.urlencode(q)
|
|
70
|
+
|
|
71
|
+
def exchange(self, code: str, verifier: str) -> str:
|
|
72
|
+
body = urllib.parse.urlencode({"grant_type": "authorization_code", "code": code, "redirect_uri": self.redirect_uri, "client_id": self.client_id,
|
|
73
|
+
"client_secret": self.client_secret, "code_verifier": verifier}).encode()
|
|
74
|
+
req = urllib.request.Request(self.discovery()["token_endpoint"], data=body, method="POST", headers={"Content-Type": "application/x-www-form-urlencoded"})
|
|
75
|
+
try:
|
|
76
|
+
r = json.load(urllib.request.urlopen(req, timeout=self.timeout))
|
|
77
|
+
except Exception as e:
|
|
78
|
+
raise OidcError(f"the provider refused the code ({type(e).__name__})") from e
|
|
79
|
+
if "id_token" not in r:
|
|
80
|
+
raise OidcError("the provider returned no id_token")
|
|
81
|
+
return r["id_token"]
|
|
82
|
+
|
|
83
|
+
def _key(self, kid: str | None, refresh: bool = False):
|
|
84
|
+
if refresh or not self._jwks:
|
|
85
|
+
self._jwks = {k.get("kid"): k for k in self._get(self.discovery()["jwks_uri"]).get("keys", []) if k.get("kty") == "RSA"}
|
|
86
|
+
k = self._jwks.get(kid) if kid else (next(iter(self._jwks.values())) if len(self._jwks) == 1 else None)
|
|
87
|
+
if k is None and not refresh:
|
|
88
|
+
return self._key(kid, True) # the provider may have rotated its keys
|
|
89
|
+
if k is None:
|
|
90
|
+
raise OidcError("no matching signing key at the provider")
|
|
91
|
+
return rsa.RSAPublicNumbers(int.from_bytes(b64d(k["e"]), "big"), int.from_bytes(b64d(k["n"]), "big")).public_key()
|
|
92
|
+
|
|
93
|
+
def verify(self, id_token: str, nonce: str, now: float | None = None) -> dict:
|
|
94
|
+
"""Return the verified claims or raise OidcError."""
|
|
95
|
+
now = now if now is not None else time.time()
|
|
96
|
+
try:
|
|
97
|
+
h64, p64, s64 = id_token.split(".")
|
|
98
|
+
header, claims = json.loads(b64d(h64)), json.loads(b64d(p64))
|
|
99
|
+
except Exception:
|
|
100
|
+
raise OidcError("malformed id_token")
|
|
101
|
+
if header.get("alg") != "RS256": # never 'none', never a symmetric algorithm
|
|
102
|
+
raise OidcError("unsupported signing algorithm")
|
|
103
|
+
try:
|
|
104
|
+
self._key(header.get("kid")).verify(b64d(s64), f"{h64}.{p64}".encode(), padding.PKCS1v15(), hashes.SHA256())
|
|
105
|
+
except InvalidSignature:
|
|
106
|
+
raise OidcError("bad id_token signature")
|
|
107
|
+
if claims.get("iss", "").rstrip("/") != self.issuer.rstrip("/"):
|
|
108
|
+
raise OidcError("wrong issuer")
|
|
109
|
+
aud = claims.get("aud")
|
|
110
|
+
aud = aud if isinstance(aud, list) else [aud]
|
|
111
|
+
if self.client_id not in aud or (len(aud) > 1 and claims.get("azp") != self.client_id):
|
|
112
|
+
raise OidcError("wrong audience")
|
|
113
|
+
if not isinstance(claims.get("exp"), (int, float)) or claims["exp"] < now - 30:
|
|
114
|
+
raise OidcError("the id_token expired")
|
|
115
|
+
if isinstance(claims.get("iat"), (int, float)) and claims["iat"] > now + 300:
|
|
116
|
+
raise OidcError("the id_token was issued in the future")
|
|
117
|
+
if not secrets.compare_digest(str(claims.get("nonce", "")), nonce):
|
|
118
|
+
raise OidcError("wrong nonce")
|
|
119
|
+
email = (claims.get("email") or "").strip().lower()
|
|
120
|
+
if not email or claims.get("email_verified") is not True:
|
|
121
|
+
raise OidcError("the provider did not confirm the e-mail address")
|
|
122
|
+
if self.allowed_domains and email.rsplit("@", 1)[-1] not in self.allowed_domains:
|
|
123
|
+
raise OidcError("this e-mail domain is not allowed to sign in here")
|
|
124
|
+
return {"email": email, "name": (claims.get("name") or email.split("@")[0])[:80], "sub": claims.get("sub")}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""A minimal PDF writer for invoices: one or more A4 pages of Helvetica text, no images, no external libraries.
|
|
2
|
+
Text is encoded as WinAnsi (Latin-1 range); other characters are replaced by '?'."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _esc(s: str) -> str:
|
|
7
|
+
s = s.encode("cp1252", "replace").decode("cp1252")
|
|
8
|
+
return s.replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Page:
|
|
12
|
+
def __init__(self):
|
|
13
|
+
self.ops: list[str] = []
|
|
14
|
+
|
|
15
|
+
def text(self, x: float, y: float, s: str, size: float = 10, bold: bool = False) -> None:
|
|
16
|
+
self.ops.append(f"BT /{'F2' if bold else 'F1'} {size:g} Tf {x:g} {y:g} Td ({_esc(s)}) Tj ET")
|
|
17
|
+
|
|
18
|
+
def line(self, x1: float, y1: float, x2: float, y2: float, w: float = 0.6) -> None:
|
|
19
|
+
self.ops.append(f"{w:g} w {x1:g} {y1:g} m {x2:g} {y2:g} l S")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def build(pages: list[Page], title: str = "Invoice") -> bytes:
|
|
23
|
+
objs: list[bytes] = []
|
|
24
|
+
add = lambda b: (objs.append(b), len(objs))[1]
|
|
25
|
+
add(b"<< /Type /Catalog /Pages 2 0 R >>") # 1
|
|
26
|
+
kids = " ".join(f"{5 + 2 * i} 0 R" for i in range(len(pages)))
|
|
27
|
+
add(f"<< /Type /Pages /Kids [{kids}] /Count {len(pages)} >>".encode()) # 2
|
|
28
|
+
add(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>") # 3
|
|
29
|
+
add(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>") # 4
|
|
30
|
+
for i, p in enumerate(pages):
|
|
31
|
+
content = "\n".join(p.ops).encode("latin-1", "replace")
|
|
32
|
+
add(f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 3 0 R /F2 4 0 R >> >> /Contents {6 + 2 * i} 0 R >>".encode())
|
|
33
|
+
add(b"<< /Length " + str(len(content)).encode() + b" >>\nstream\n" + content + b"\nendstream")
|
|
34
|
+
info = add(f"<< /Title ({_esc(title)}) /Producer (Spatial Computing) >>".encode())
|
|
35
|
+
out = bytearray(b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n")
|
|
36
|
+
offs = []
|
|
37
|
+
for n, o in enumerate(objs, 1):
|
|
38
|
+
offs.append(len(out))
|
|
39
|
+
out += f"{n} 0 obj\n".encode() + o + b"\nendobj\n"
|
|
40
|
+
xref = len(out)
|
|
41
|
+
out += f"xref\n0 {len(objs) + 1}\n0000000000 65535 f \n".encode()
|
|
42
|
+
for o in offs:
|
|
43
|
+
out += f"{o:010d} 00000 n \n".encode()
|
|
44
|
+
out += f"trailer\n<< /Size {len(objs) + 1} /Root 1 0 R /Info {info} 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode()
|
|
45
|
+
return bytes(out)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def invoice_pdf(inv: dict) -> bytes:
|
|
49
|
+
"""inv: number, period, issued (str), status, seller {name,address,vat_id}, customer {name,address,country,vat_id}, lines [{description, qty, unit, amount}],
|
|
50
|
+
subtotal, tax_rate, tax, total, currency, note."""
|
|
51
|
+
pg = Page()
|
|
52
|
+
L, R, y = 50, 545, 790
|
|
53
|
+
pg.text(L, y, inv["seller"].get("name") or "Spatial Computing", 16, True)
|
|
54
|
+
for ln in (inv["seller"].get("address") or "").splitlines()[:4]:
|
|
55
|
+
y -= 13; pg.text(L, y, ln, 9)
|
|
56
|
+
if inv["seller"].get("vat_id"):
|
|
57
|
+
y -= 13; pg.text(L, y, "VAT ID: " + inv["seller"]["vat_id"], 9)
|
|
58
|
+
credit = inv.get("kind") == "credit"
|
|
59
|
+
pg.text(R - 150, 790, "CREDIT NOTE" if credit else "INVOICE", 18, True)
|
|
60
|
+
pg.text(R - 150, 770, "No. " + inv["number"], 10, True)
|
|
61
|
+
pg.text(R - 150, 757, "Issued: " + inv["issued"], 9)
|
|
62
|
+
pg.text(R - 150, 744, "Period: " + inv["period"], 9)
|
|
63
|
+
pg.text(R - 150, 731, ("Refers to " + inv["refers_to"]) if credit else "Status: " + inv["status"].upper(), 9, True)
|
|
64
|
+
y = 690
|
|
65
|
+
pg.text(L, y, "Billed to", 9, True)
|
|
66
|
+
c = inv["customer"]
|
|
67
|
+
for ln in [c.get("name") or "-", *(c.get("address") or "").splitlines()[:4], c.get("country") or "", ("VAT ID: " + c["vat_id"]) if c.get("vat_id") else ""]:
|
|
68
|
+
if ln:
|
|
69
|
+
y -= 13; pg.text(L, y, ln, 10)
|
|
70
|
+
y = 590
|
|
71
|
+
pg.line(L, y + 14, R, y + 14, 1)
|
|
72
|
+
pg.text(L, y, "Description", 9, True); pg.text(330, y, "Quantity", 9, True); pg.text(400, y, "Unit price", 9, True); pg.text(490, y, "Amount", 9, True)
|
|
73
|
+
pg.line(L, y - 5, R, y - 5)
|
|
74
|
+
cur = inv["currency"].upper()
|
|
75
|
+
for l in inv["lines"]:
|
|
76
|
+
y -= 18
|
|
77
|
+
pg.text(L, y, l["description"][:48], 10); pg.text(330, y, l["qty"], 10); pg.text(400, y, l["unit"], 10); pg.text(490, y, f"{l['amount']:.2f} {cur}", 10)
|
|
78
|
+
y -= 14; pg.line(L, y, R, y)
|
|
79
|
+
for label, val, bold in (("Subtotal", inv["subtotal"], False), (f"Tax ({inv['tax_rate']:g}%)", inv["tax"], False), ("Total", inv["total"], True)):
|
|
80
|
+
y -= 18; pg.text(400, y, label, 10, bold); pg.text(490, y, f"{val:.2f} {cur}", 10, bold)
|
|
81
|
+
if inv.get("note"):
|
|
82
|
+
y -= 40
|
|
83
|
+
for ln in inv["note"].splitlines()[:5]:
|
|
84
|
+
pg.text(L, y, ln, 9); y -= 12
|
|
85
|
+
pg.text(L, 40, "Usage is metered per finished task on the Spatial Computing fleet.", 8)
|
|
86
|
+
return build([pg], f"{'Credit note' if credit else 'Invoice'} {inv['number']}")
|