spatial-computing 0.16.0__tar.gz → 0.18.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.16.0/spatial_computing.egg-info → spatial_computing-0.18.0}/PKG-INFO +3 -2
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/README.md +1 -1
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/pyproject.toml +2 -2
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/__init__.py +1 -1
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/cli.py +13 -3
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/core/registry.py +1 -1
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/billing.py +13 -1
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/db.py +14 -5
- spatial_computing-0.18.0/spatial/platform/invoice_rules.py +71 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/mailer.py +6 -2
- spatial_computing-0.18.0/spatial/platform/oidc.py +124 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/pdf.py +16 -8
- spatial_computing-0.18.0/spatial/platform/qr.py +196 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/server.py +112 -5
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/service.py +419 -71
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/static/app.js +73 -32
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/static/style.css +2 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/totp.py +2 -1
- spatial_computing-0.18.0/spatial/platform/ubl.py +127 -0
- spatial_computing-0.18.0/spatial/platform/vat.py +93 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/runtime/desktop/Dockerfile +1 -1
- spatial_computing-0.18.0/spatial/runtime/desktop/__init__.py +135 -0
- spatial_computing-0.18.0/spatial/runtime/desktop/start.sh +16 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0/spatial_computing.egg-info}/PKG-INFO +3 -2
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial_computing.egg-info/SOURCES.txt +8 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial_computing.egg-info/requires.txt +1 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_platform2.py +379 -2
- spatial_computing-0.18.0/tests/test_qr.py +37 -0
- spatial_computing-0.18.0/tests/test_real_servers.py +176 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_runtime.py +130 -2
- spatial_computing-0.18.0/tests/test_sso.py +216 -0
- spatial_computing-0.16.0/spatial/runtime/desktop/__init__.py +0 -85
- spatial_computing-0.16.0/spatial/runtime/desktop/start.sh +0 -11
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/LICENSE +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/setup.cfg +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/ai/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/ai/kvcache.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/ai/llm.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/compute/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/compute/cost.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/compute/detect.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/compute/monitor.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/compute/scheduler.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/compute/taskqueue.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/compute/worker.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/compute/workloads.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/core/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/core/auth.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/core/energy.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/core/ledger.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/core/model.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/core/protocol.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/fabric/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/fabric/cuda.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/fabric/devices.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/fabric/metal.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/fabric/metal_mandel.swift +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/fabric/metal_run.swift +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/fleet/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/fleet/agent.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/fleet/alerts.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/fleet/dashboard.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/fleet/ha.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/fleet/hub.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/holographic/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/holographic/cgh.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/holographic/model.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/intelligence/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/intelligence/predictor.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/interconnect/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/interconnect/collectives.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/interconnect/comm.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/interconnect/model.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/interconnect/tasks.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/kernel/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/kernel/dsl.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/kernel/library.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/memory/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/memory/fararray.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/memory/pageserver.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/memory/secure.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/memory/shared.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/memory/tiered.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/security.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/static/fonts/DMMono-normal-400.woff2 +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/static/fonts/DMMono-normal-500.woff2 +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/static/fonts/InstrumentSerif-italic-400.woff2 +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/static/fonts/InstrumentSerif-normal-400.woff2 +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/static/fonts/Inter-normal-400.woff2 +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/static/fonts/Inter-normal-500.woff2 +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/static/fonts/Inter-normal-600.woff2 +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/static/fonts.css +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/static/index.html +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/platform/static/logo.svg +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/q/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/q/__main__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/q/backends/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/q/codegen.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/q/compiler.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/q/ir.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/q/lexer.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/q/parser.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/q/qir.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/q/runtime.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/q/sim.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/runtime/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/runtime/envs.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/runtime/inspect.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/runtime/microvm.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/runtime/planner.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/runtime/runner.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/runtime/toolchain.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/scientific/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/scientific/jobs.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/simulation/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/simulation/heat.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/simulation/nbody.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/unified/__init__.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/unified/model.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/unified/planner.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial/unified/providers.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial_computing.egg-info/dependency_links.txt +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial_computing.egg-info/entry_points.txt +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/spatial_computing.egg-info/top_level.txt +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_auth.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_compute.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_core.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_dashboard.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_domains.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_engines.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_fabric.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_fleet.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_ha.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_hardening.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_interconnect.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_kernel.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_memory.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_optimizer.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_platform.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_q.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_quorum.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_unified.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_v02.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_v03.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.0}/tests/test_v05.py +0 -0
- {spatial_computing-0.16.0 → spatial_computing-0.18.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.18.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
|
|
@@ -29,6 +29,7 @@ Requires-Dist: qiskit>=2.0; extra == "qpu"
|
|
|
29
29
|
Requires-Dist: qiskit-ibm-runtime>=0.40; extra == "qpu"
|
|
30
30
|
Provides-Extra: dev
|
|
31
31
|
Requires-Dist: pytest>=8; extra == "dev"
|
|
32
|
+
Requires-Dist: lxml>=5; extra == "dev"
|
|
32
33
|
Dynamic: license-file
|
|
33
34
|
|
|
34
35
|
# Spatial Computing
|
|
@@ -37,7 +38,7 @@ Dynamic: license-file
|
|
|
37
38
|
|
|
38
39
|
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
40
|
|
|
40
|
-
> **Status: v0.
|
|
41
|
+
> **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
42
|
|
|
42
43
|
[Français](README.fr.md)
|
|
43
44
|
|
|
@@ -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.18.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"
|
|
@@ -18,7 +18,7 @@ dependencies = ["numpy>=1.26,<2.2", "psutil>=5.9", "numba>=0.59,<0.62", "lz4>=4.
|
|
|
18
18
|
quantum = ["qiskit>=2.0", "qiskit-aer>=0.17", "qiskit-qasm3-import>=0.5", "pyqir>=0.10"]
|
|
19
19
|
build = ["ziglang>=0.13"]
|
|
20
20
|
qpu = ["qiskit>=2.0", "qiskit-ibm-runtime>=0.40"]
|
|
21
|
-
dev = ["pytest>=8"]
|
|
21
|
+
dev = ["pytest>=8", "lxml>=5"]
|
|
22
22
|
|
|
23
23
|
[project.urls]
|
|
24
24
|
Homepage = "https://spatial-computing-ecru.vercel.app"
|
|
@@ -106,11 +106,18 @@ def cmd_agent(a):
|
|
|
106
106
|
def cmd_desktop(a):
|
|
107
107
|
from .runtime.desktop import DesktopError, start
|
|
108
108
|
try:
|
|
109
|
-
d = start(a.app)
|
|
109
|
+
d = start(a.app, clipboard=not a.no_clipboard, view_only_link=a.view_link)
|
|
110
110
|
except DesktopError as e:
|
|
111
111
|
print(f"spatial: {e}", file=sys.stderr)
|
|
112
112
|
return 1
|
|
113
113
|
print(f"desktop ({a.app}, {d.runtime}), loopback only: {d.url}", flush=True)
|
|
114
|
+
for f in a.upload:
|
|
115
|
+
try:
|
|
116
|
+
print(f"uploaded {f} to {d.upload(f)}", flush=True)
|
|
117
|
+
except DesktopError as e:
|
|
118
|
+
print(f"spatial: {e}", file=sys.stderr)
|
|
119
|
+
if d.view_url:
|
|
120
|
+
print(f"view-only link (watch, cannot type or click): {d.view_url}", flush=True)
|
|
114
121
|
print("Ctrl+C removes it", flush=True)
|
|
115
122
|
try:
|
|
116
123
|
while True:
|
|
@@ -338,8 +345,11 @@ def main(argv=None):
|
|
|
338
345
|
p.add_argument("--workload"); p.add_argument("--params", default="{}"); p.add_argument("--needs", default="{}")
|
|
339
346
|
p.add_argument("--task-id", type=int)
|
|
340
347
|
p.set_defaults(fn=cmd_fleet)
|
|
341
|
-
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)")
|
|
342
|
-
p.add_argument("app", nargs="?", default="xterm", choices=["xterm", "xclock", "mousepad"])
|
|
348
|
+
p = sub.add_parser("desktop", help="run a graphical Linux app (xterm, xclock, xcalc, mousepad) in a container and open it in your browser (noVNC, loopback only)")
|
|
349
|
+
p.add_argument("app", nargs="?", default="xterm", choices=["xterm", "xclock", "xcalc", "mousepad"])
|
|
350
|
+
p.add_argument("--no-clipboard", action="store_true", help="no copy and paste between your machine and the desktop")
|
|
351
|
+
p.add_argument("--view-link", action="store_true", help="also print a view-only link for people who only need to watch")
|
|
352
|
+
p.add_argument("--upload", action="append", default=[], metavar="FILE", help="copy this file into the desktop's ~/transfer folder (repeatable, 16 MiB each)")
|
|
343
353
|
p.set_defaults(fn=cmd_desktop)
|
|
344
354
|
p = sub.add_parser("platform", help="account service: sign up, sign in, apps, API keys, usage, billing (`spatial platform serve --help`)")
|
|
345
355
|
p.add_argument("rest", nargs=argparse.REMAINDER)
|
|
@@ -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;
|
|
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"),
|
|
@@ -25,11 +25,12 @@ DEFAULT_PRICING = {
|
|
|
25
25
|
"tax_label": "VAT",
|
|
26
26
|
"tax_rate_percent": 0.0, # default rate added to every invoice
|
|
27
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
|
|
28
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
|
|
29
30
|
}
|
|
30
31
|
|
|
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),
|
|
32
|
-
"tax_label": str, "tax_rate_percent": (int, float), "tax_by_country": dict, "no_tax_with_vat_id_abroad": bool}
|
|
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}
|
|
33
34
|
|
|
34
35
|
|
|
35
36
|
def validate_pricing(d: dict) -> dict:
|
|
@@ -116,6 +117,17 @@ class Stripe:
|
|
|
116
117
|
raise PaymentError(f"payment provider error: {type(e).__name__}") from e
|
|
117
118
|
return r["url"], r["id"]
|
|
118
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
|
+
|
|
119
131
|
def verify_webhook(self, payload: bytes, header: str, tolerance_s: int = 300, now: float | None = None) -> dict:
|
|
120
132
|
"""Check the Stripe-Signature header (t=..,v1=hmac_sha256(secret, 't.payload')) and return the event."""
|
|
121
133
|
if not self.whsec:
|
|
@@ -14,11 +14,14 @@ CREATE TABLE IF NOT EXISTS users(
|
|
|
14
14
|
recovery TEXT NOT NULL DEFAULT '[]', personal_org INTEGER);
|
|
15
15
|
CREATE TABLE IF NOT EXISTS orgs(
|
|
16
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 ''
|
|
18
|
-
|
|
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
|
+
billing_city TEXT NOT NULL DEFAULT '', billing_postal TEXT NOT NULL DEFAULT '', billing_email TEXT NOT NULL DEFAULT '');
|
|
19
|
+
CREATE TABLE IF NOT EXISTS members(org_id INTEGER NOT NULL, user_id INTEGER NOT NULL, role TEXT NOT NULL, created REAL NOT NULL, app_ids TEXT, PRIMARY KEY(org_id, user_id));
|
|
20
|
+
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));
|
|
21
|
+
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);
|
|
19
22
|
CREATE TABLE IF NOT EXISTS invites(
|
|
20
23
|
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,
|
|
21
|
-
created REAL NOT NULL, expires REAL NOT NULL, accepted REAL);
|
|
24
|
+
created REAL NOT NULL, expires REAL NOT NULL, accepted REAL, app_ids TEXT);
|
|
22
25
|
CREATE TABLE IF NOT EXISTS verifications(token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL, expires REAL NOT NULL);
|
|
23
26
|
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);
|
|
24
27
|
CREATE TABLE IF NOT EXISTS settings(key TEXT PRIMARY KEY, value TEXT NOT NULL, updated REAL NOT NULL);
|
|
@@ -38,7 +41,10 @@ CREATE TABLE IF NOT EXISTS offsets(name TEXT PRIMARY KEY, value INTEGER NOT NULL
|
|
|
38
41
|
CREATE TABLE IF NOT EXISTS invoices(
|
|
39
42
|
id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, period TEXT NOT NULL, amount_usd REAL NOT NULL, status TEXT NOT NULL,
|
|
40
43
|
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,
|
|
41
|
-
billing TEXT, seller TEXT);
|
|
44
|
+
billing TEXT, seller TEXT, payment_ref TEXT, credited_usd REAL NOT NULL DEFAULT 0);
|
|
45
|
+
CREATE TABLE IF NOT EXISTS credit_notes(
|
|
46
|
+
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,
|
|
47
|
+
total_usd REAL NOT NULL, reason TEXT NOT NULL, created REAL NOT NULL, status TEXT NOT NULL, refund_ref TEXT, created_by INTEGER);
|
|
42
48
|
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);
|
|
43
49
|
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,
|
|
44
50
|
attempts INTEGER NOT NULL DEFAULT 0, next_try REAL NOT NULL DEFAULT 0, last_error TEXT);
|
|
@@ -80,7 +86,10 @@ class DB:
|
|
|
80
86
|
ADD = {"users": [("email_verified", "INTEGER NOT NULL DEFAULT 0"), ("totp_secret", "TEXT"), ("totp_enabled", "INTEGER NOT NULL DEFAULT 0"),
|
|
81
87
|
("totp_last_step", "INTEGER NOT NULL DEFAULT 0"), ("recovery", "TEXT NOT NULL DEFAULT '[]'"), ("personal_org", "INTEGER")],
|
|
82
88
|
"apps": [("org_id", "INTEGER")],
|
|
83
|
-
"invoices": [("org_id", "INTEGER"), ("number", "TEXT"), ("subtotal_usd", "REAL"), ("tax_rate", "REAL"), ("tax_usd", "REAL"), ("billing", "TEXT"), ("seller", "TEXT")
|
|
89
|
+
"invoices": [("org_id", "INTEGER"), ("number", "TEXT"), ("subtotal_usd", "REAL"), ("tax_rate", "REAL"), ("tax_usd", "REAL"), ("billing", "TEXT"), ("seller", "TEXT"),
|
|
90
|
+
("payment_ref", "TEXT"), ("credited_usd", "REAL NOT NULL DEFAULT 0")],
|
|
91
|
+
"orgs": [("vat_status", "TEXT NOT NULL DEFAULT ''"), ("billing_city", "TEXT NOT NULL DEFAULT ''"), ("billing_postal", "TEXT NOT NULL DEFAULT ''"), ("billing_email", "TEXT NOT NULL DEFAULT ''")],
|
|
92
|
+
"members": [("app_ids", "TEXT")], "invites": [("app_ids", "TEXT")],
|
|
84
93
|
"outbox": [("attempts", "INTEGER NOT NULL DEFAULT 0"), ("next_try", "REAL NOT NULL DEFAULT 0"), ("last_error", "TEXT")]}
|
|
85
94
|
|
|
86
95
|
def _migrate(self) -> None:
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""What an invoice must carry, by the seller's country, and the legal mentions printed on it. A SMALL table for the countries a
|
|
2
|
+
first customer is most likely to be in (FR, DE, ES, IT, NL, BE, GB): it covers the mandatory fields commonly listed by those tax
|
|
3
|
+
authorities, not every rule. It is a checklist for the operator, not legal advice."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
COMPANY_FIELDS = {
|
|
7
|
+
"name": "company name", "address": "address", "city": "city", "postal_code": "postal code", "country": "country",
|
|
8
|
+
"vat_id": "VAT identification number", "registration_no": "company registration number", "legal_form": "legal form",
|
|
9
|
+
"share_capital": "share capital", "tax_no": "national tax number", "iban": "IBAN", "bic": "BIC",
|
|
10
|
+
}
|
|
11
|
+
COMPANY_FORMS_WITH_CAPITAL = {"SAS", "SARL", "SA", "SASU", "EURL", "SCA", "SNC", "GMBH", "AG", "UG", "SL", "SLU", "SRL", "BV", "NV", "LTD"}
|
|
12
|
+
|
|
13
|
+
# fields that must be present on every invoice, by seller country (the base list applies everywhere)
|
|
14
|
+
BASE = ["name", "address", "city", "postal_code", "country"]
|
|
15
|
+
BY_COUNTRY = {
|
|
16
|
+
"FR": ["registration_no", "legal_form"], # SIREN and form; capital added below for companies
|
|
17
|
+
"DE": [], # vat_id OR tax_no, checked separately
|
|
18
|
+
"ES": ["vat_id"], "IT": ["vat_id"], "NL": ["vat_id", "registration_no"], "BE": ["vat_id"],
|
|
19
|
+
"GB": ["registration_no"], # company number for limited companies
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
REVERSE_CHARGE = {
|
|
23
|
+
"FR": "Autoliquidation de la TVA (art. 283-2 du CGI, art. 196 de la directive 2006/112/CE).",
|
|
24
|
+
"DE": "Steuerschuldnerschaft des Leistungsempfängers (Reverse Charge, Art. 196 MwStSystRL).",
|
|
25
|
+
"ES": "Inversión del sujeto pasivo (art. 196 Directiva 2006/112/CE).",
|
|
26
|
+
"IT": "Inversione contabile (art. 196 Direttiva 2006/112/CE).",
|
|
27
|
+
"NL": "BTW verlegd (art. 196 Richtlijn 2006/112/EG).",
|
|
28
|
+
"BE": "Autoliquidation / BTW verlegd (art. 196 directive 2006/112/CE).",
|
|
29
|
+
}
|
|
30
|
+
REVERSE_CHARGE_DEFAULT = "Reverse charge: VAT to be accounted for by the customer (Article 196, Directive 2006/112/EC)."
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def required(company: dict, taxed: bool) -> list[str]:
|
|
34
|
+
"""Names of company fields that are required but empty."""
|
|
35
|
+
cc = (company.get("country") or "").upper()
|
|
36
|
+
need = list(BASE) + list(BY_COUNTRY.get(cc, []))
|
|
37
|
+
if taxed and "vat_id" not in need:
|
|
38
|
+
need.append("vat_id")
|
|
39
|
+
if cc == "FR" and (company.get("legal_form") or "").upper().replace(" ", "") in COMPANY_FORMS_WITH_CAPITAL:
|
|
40
|
+
need.append("share_capital")
|
|
41
|
+
missing = [f for f in need if not (company.get(f) or "").strip()]
|
|
42
|
+
if cc == "DE" and not ((company.get("vat_id") or "").strip() or (company.get("tax_no") or "").strip()):
|
|
43
|
+
missing.append("vat_id or tax_no")
|
|
44
|
+
return missing
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def reverse_charge_text(seller_country: str) -> str:
|
|
48
|
+
return REVERSE_CHARGE.get((seller_country or "").upper(), REVERSE_CHARGE_DEFAULT)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def mentions(seller: dict, customer: dict, tax_rate: float, reverse_charge: bool, due: str) -> list[str]:
|
|
52
|
+
"""Mentions printed at the foot of the invoice."""
|
|
53
|
+
out = []
|
|
54
|
+
cc = (seller.get("country") or "").upper()
|
|
55
|
+
if reverse_charge:
|
|
56
|
+
out.append(reverse_charge_text(cc))
|
|
57
|
+
elif tax_rate == 0 and seller.get("tax_exempt_note"):
|
|
58
|
+
out.append(seller["tax_exempt_note"])
|
|
59
|
+
if cc == "FR":
|
|
60
|
+
out.append("Pénalités de retard : trois fois le taux d'intérêt légal. Indemnité forfaitaire pour frais de recouvrement : 40 EUR (art. L441-10 du Code de commerce).")
|
|
61
|
+
if seller.get("registration_no"):
|
|
62
|
+
form = " ".join(x for x in [seller.get("legal_form"), ("au capital de " + seller["share_capital"]) if seller.get("share_capital") else ""] if x)
|
|
63
|
+
out.append(f"{seller.get('name', '')} {form} - SIREN {seller['registration_no']}".strip())
|
|
64
|
+
elif cc == "DE":
|
|
65
|
+
out.append("Leistungszeitraum: siehe Rechnungsperiode. " + ("Steuernummer: " + seller["tax_no"] if seller.get("tax_no") else ""))
|
|
66
|
+
elif cc == "GB" and seller.get("registration_no"):
|
|
67
|
+
out.append(f"Registered in England and Wales, company number {seller['registration_no']}.")
|
|
68
|
+
out.append(f"Payment due by {due}.")
|
|
69
|
+
if seller.get("legal_footer"):
|
|
70
|
+
out.append(seller["legal_footer"])
|
|
71
|
+
return [m.strip() for m in out if m.strip()]
|
|
@@ -19,16 +19,20 @@ class Mailer:
|
|
|
19
19
|
self.deliver(mid)
|
|
20
20
|
return mid
|
|
21
21
|
|
|
22
|
+
def _tls(self) -> ssl.SSLContext:
|
|
23
|
+
"""Verified TLS: system CAs, or the operator's own CA file (a private relay with an internal certificate). Never unverified."""
|
|
24
|
+
return ssl.create_default_context(cafile=self.smtp.get("ca_file") or None)
|
|
25
|
+
|
|
22
26
|
def _send(self, to: str, subject: str, body: str) -> None:
|
|
23
27
|
c = self.smtp
|
|
24
28
|
m = EmailMessage(); m["From"], m["To"], m["Subject"] = c["from"], to, subject; m.set_content(body)
|
|
25
29
|
if c.get("ssl"):
|
|
26
|
-
s = smtplib.SMTP_SSL(c["host"], c.get("port", 465), timeout=15, context=
|
|
30
|
+
s = smtplib.SMTP_SSL(c["host"], c.get("port", 465), timeout=15, context=self._tls())
|
|
27
31
|
else:
|
|
28
32
|
s = smtplib.SMTP(c["host"], c.get("port", 587), timeout=15)
|
|
29
33
|
with s:
|
|
30
34
|
if c.get("starttls", True) and not c.get("ssl"):
|
|
31
|
-
s.starttls(context=
|
|
35
|
+
s.starttls(context=self._tls())
|
|
32
36
|
if c.get("user"):
|
|
33
37
|
s.login(c["user"], c["password"])
|
|
34
38
|
s.send_message(m)
|
|
@@ -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")}
|
|
@@ -55,11 +55,14 @@ def invoice_pdf(inv: dict) -> bytes:
|
|
|
55
55
|
y -= 13; pg.text(L, y, ln, 9)
|
|
56
56
|
if inv["seller"].get("vat_id"):
|
|
57
57
|
y -= 13; pg.text(L, y, "VAT ID: " + inv["seller"]["vat_id"], 9)
|
|
58
|
-
|
|
58
|
+
credit = inv.get("kind") == "credit"
|
|
59
|
+
pg.text(R - 150, 790, "CREDIT NOTE" if credit else "INVOICE", 18, True)
|
|
59
60
|
pg.text(R - 150, 770, "No. " + inv["number"], 10, True)
|
|
60
61
|
pg.text(R - 150, 757, "Issued: " + inv["issued"], 9)
|
|
61
|
-
pg.text(R - 150, 744, "Period: " + inv["period"], 9)
|
|
62
|
-
|
|
62
|
+
pg.text(R - 150, 744, "Period: " + inv.get("period_start", inv["period"]) + (" to " + inv["period_end"] if inv.get("period_end") else ""), 9)
|
|
63
|
+
if inv.get("due") and inv.get("kind") != "credit":
|
|
64
|
+
pg.text(R - 150, 718, "Due: " + inv["due"], 9, True)
|
|
65
|
+
pg.text(R - 150, 731, ("Refers to " + inv["refers_to"]) if credit else "Status: " + inv["status"].upper(), 9, True)
|
|
63
66
|
y = 690
|
|
64
67
|
pg.text(L, y, "Billed to", 9, True)
|
|
65
68
|
c = inv["customer"]
|
|
@@ -77,9 +80,14 @@ def invoice_pdf(inv: dict) -> bytes:
|
|
|
77
80
|
y -= 14; pg.line(L, y, R, y)
|
|
78
81
|
for label, val, bold in (("Subtotal", inv["subtotal"], False), (f"Tax ({inv['tax_rate']:g}%)", inv["tax"], False), ("Total", inv["total"], True)):
|
|
79
82
|
y -= 18; pg.text(400, y, label, 10, bold); pg.text(490, y, f"{val:.2f} {cur}", 10, bold)
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
83
|
+
y -= 30
|
|
84
|
+
pay = [x for x in [("IBAN: " + inv["seller"]["iban"]) if inv["seller"].get("iban") else "", ("BIC: " + inv["seller"]["bic"]) if inv["seller"].get("bic") else ""] if x]
|
|
85
|
+
if pay and inv.get("kind") != "credit":
|
|
86
|
+
pg.text(L, y, "Payment details", 9, True); y -= 13
|
|
87
|
+
pg.text(L, y, " ".join(pay), 9); y -= 18
|
|
88
|
+
for ln in ([inv["note"]] if inv.get("note") else []) + list(inv.get("mentions", [])):
|
|
89
|
+
while ln:
|
|
90
|
+
pg.text(L, y, ln[:105], 8); ln = ln[105:]; y -= 11
|
|
91
|
+
y -= 2
|
|
84
92
|
pg.text(L, 40, "Usage is metered per finished task on the Spatial Computing fleet.", 8)
|
|
85
|
-
return build([pg], f"Invoice {inv['number']}")
|
|
93
|
+
return build([pg], f"{'Credit note' if credit else 'Invoice'} {inv['number']}")
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""A small QR Code encoder (ISO/IEC 18004): byte mode, error correction level M, versions 1 to 10 (up to 213 bytes).
|
|
2
|
+
Enough for an otpauth:// link. Output: a square matrix of booleans (True = dark) or an SVG string."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
# version -> (ec codewords per block, [(number of blocks, data codewords per block), ...]) for level M
|
|
6
|
+
EC_M = {1: (10, [(1, 16)]), 2: (16, [(1, 28)]), 3: (26, [(1, 44)]), 4: (18, [(2, 32)]), 5: (24, [(2, 43)]), 6: (16, [(4, 27)]),
|
|
7
|
+
7: (18, [(4, 31)]), 8: (22, [(2, 38), (2, 39)]), 9: (22, [(3, 36), (2, 37)]), 10: (26, [(4, 43), (1, 44)])}
|
|
8
|
+
ALIGN = {1: [], 2: [6, 18], 3: [6, 22], 4: [6, 26], 5: [6, 30], 6: [6, 34], 7: [6, 22, 38], 8: [6, 24, 42], 9: [6, 26, 46], 10: [6, 28, 50]}
|
|
9
|
+
M_BITS = 0b00 # level M format bits
|
|
10
|
+
|
|
11
|
+
# GF(256) with the QR primitive polynomial 0x11D
|
|
12
|
+
EXP, LOG = [0] * 512, [0] * 256
|
|
13
|
+
_x = 1
|
|
14
|
+
for _i in range(255):
|
|
15
|
+
EXP[_i], LOG[_x] = _x, _i
|
|
16
|
+
_x <<= 1
|
|
17
|
+
if _x & 0x100:
|
|
18
|
+
_x ^= 0x11D
|
|
19
|
+
for _i in range(255, 512):
|
|
20
|
+
EXP[_i] = EXP[_i - 255]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _gmul(a: int, b: int) -> int:
|
|
24
|
+
return 0 if a == 0 or b == 0 else EXP[LOG[a] + LOG[b]]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _rs_generator(n: int) -> list[int]:
|
|
28
|
+
g = [1]
|
|
29
|
+
for i in range(n):
|
|
30
|
+
ng = [0] * (len(g) + 1)
|
|
31
|
+
for j, c in enumerate(g):
|
|
32
|
+
ng[j] ^= c
|
|
33
|
+
ng[j + 1] ^= _gmul(c, EXP[i])
|
|
34
|
+
g = ng
|
|
35
|
+
return g
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _rs_remainder(data: list[int], n: int) -> list[int]:
|
|
39
|
+
gen = _rs_generator(n)
|
|
40
|
+
res = [0] * n
|
|
41
|
+
for b in data:
|
|
42
|
+
f = b ^ res[0]
|
|
43
|
+
res = res[1:] + [0]
|
|
44
|
+
if f:
|
|
45
|
+
for i in range(n):
|
|
46
|
+
res[i] ^= _gmul(gen[i + 1], f)
|
|
47
|
+
return res
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _capacity(v: int) -> int:
|
|
51
|
+
ec, groups = EC_M[v]
|
|
52
|
+
return sum(n * d for n, d in groups)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _bch(value: int, poly: int, deg: int) -> int:
|
|
56
|
+
v = value << deg
|
|
57
|
+
pl = poly.bit_length()
|
|
58
|
+
while v.bit_length() >= pl:
|
|
59
|
+
v ^= poly << (v.bit_length() - pl)
|
|
60
|
+
return v
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _codewords(data: bytes, v: int) -> list[int]:
|
|
64
|
+
cap = _capacity(v)
|
|
65
|
+
bits: list[int] = []
|
|
66
|
+
put = lambda val, n: bits.extend((val >> (n - 1 - i)) & 1 for i in range(n))
|
|
67
|
+
put(0b0100, 4)
|
|
68
|
+
put(len(data), 8 if v < 10 else 16)
|
|
69
|
+
for b in data:
|
|
70
|
+
put(b, 8)
|
|
71
|
+
put(0, min(4, cap * 8 - len(bits)))
|
|
72
|
+
while len(bits) % 8:
|
|
73
|
+
bits.append(0)
|
|
74
|
+
cw = [int("".join(map(str, bits[i:i + 8])), 2) for i in range(0, len(bits), 8)]
|
|
75
|
+
pad = [0xEC, 0x11]
|
|
76
|
+
while len(cw) < cap:
|
|
77
|
+
cw.append(pad[(len(cw) - len(bits) // 8) % 2])
|
|
78
|
+
ec, groups = EC_M[v]
|
|
79
|
+
blocks, pos = [], 0
|
|
80
|
+
for n, d in groups:
|
|
81
|
+
for _ in range(n):
|
|
82
|
+
blocks.append(cw[pos:pos + d]); pos += d
|
|
83
|
+
ecs = [_rs_remainder(b, ec) for b in blocks]
|
|
84
|
+
out = []
|
|
85
|
+
for i in range(max(len(b) for b in blocks)):
|
|
86
|
+
out += [b[i] for b in blocks if i < len(b)]
|
|
87
|
+
for i in range(ec):
|
|
88
|
+
out += [e[i] for e in ecs]
|
|
89
|
+
return out
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _mask_fn(m: int):
|
|
93
|
+
return [lambda r, c: (r + c) % 2 == 0, lambda r, c: r % 2 == 0, lambda r, c: c % 3 == 0, lambda r, c: (r + c) % 3 == 0,
|
|
94
|
+
lambda r, c: (r // 2 + c // 3) % 2 == 0, lambda r, c: (r * c) % 2 + (r * c) % 3 == 0,
|
|
95
|
+
lambda r, c: ((r * c) % 2 + (r * c) % 3) % 2 == 0, lambda r, c: ((r + c) % 2 + (r * c) % 3) % 2 == 0][m]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _build(v: int, cw: list[int], mask: int) -> list[list[bool]]:
|
|
99
|
+
n = 17 + 4 * v
|
|
100
|
+
mat = [[False] * n for _ in range(n)]
|
|
101
|
+
fn = [[False] * n for _ in range(n)] # function modules (not data)
|
|
102
|
+
|
|
103
|
+
def setm(r, c, val, f=True):
|
|
104
|
+
mat[r][c] = val
|
|
105
|
+
if f:
|
|
106
|
+
fn[r][c] = True
|
|
107
|
+
for (r0, c0) in ((0, 0), (0, n - 7), (n - 7, 0)): # finder patterns
|
|
108
|
+
for dr in range(-1, 8):
|
|
109
|
+
for dc in range(-1, 8):
|
|
110
|
+
r, c = r0 + dr, c0 + dc
|
|
111
|
+
if 0 <= r < n and 0 <= c < n:
|
|
112
|
+
dark = 0 <= dr <= 6 and 0 <= dc <= 6 and (dr in (0, 6) or dc in (0, 6) or (2 <= dr <= 4 and 2 <= dc <= 4))
|
|
113
|
+
setm(r, c, dark)
|
|
114
|
+
pts = ALIGN[v]
|
|
115
|
+
for r in pts: # alignment patterns
|
|
116
|
+
for c in pts:
|
|
117
|
+
if fn[r][c]:
|
|
118
|
+
continue
|
|
119
|
+
for dr in range(-2, 3):
|
|
120
|
+
for dc in range(-2, 3):
|
|
121
|
+
setm(r + dr, c + dc, max(abs(dr), abs(dc)) != 1)
|
|
122
|
+
for i in range(8, n - 8): # timing patterns
|
|
123
|
+
setm(6, i, i % 2 == 0); setm(i, 6, i % 2 == 0)
|
|
124
|
+
setm(n - 8, 8, True) # the dark module
|
|
125
|
+
fmt = ((M_BITS << 3 | mask) << 10 | _bch(M_BITS << 3 | mask, 0x537, 10)) ^ 0x5412
|
|
126
|
+
for i in range(15):
|
|
127
|
+
bit = (fmt >> i) & 1 == 1
|
|
128
|
+
r1, c1 = (i, 8) if i < 6 else (i + 1, 8) if i < 8 else (8, 14 - i) if i < 9 else (8, 14 - i)
|
|
129
|
+
if i < 6: setm(i, 8, bit)
|
|
130
|
+
elif i < 8: setm(i + 1, 8, bit)
|
|
131
|
+
elif i == 8: setm(8, 7, bit)
|
|
132
|
+
else: setm(8, 14 - i, bit)
|
|
133
|
+
if i < 8: setm(8, n - 1 - i, bit)
|
|
134
|
+
else: setm(n - 15 + i, 8, bit)
|
|
135
|
+
if v >= 7: # version information
|
|
136
|
+
vi = v << 12 | _bch(v, 0x1F25, 12)
|
|
137
|
+
for i in range(18):
|
|
138
|
+
bit = (vi >> i) & 1 == 1
|
|
139
|
+
setm(i // 3, n - 11 + i % 3, bit); setm(n - 11 + i % 3, i // 3, bit)
|
|
140
|
+
bits = [(b >> (7 - i)) & 1 for b in cw for i in range(8)]
|
|
141
|
+
k, up, c = 0, True, n - 1
|
|
142
|
+
mf = _mask_fn(mask)
|
|
143
|
+
while c > 0:
|
|
144
|
+
if c == 6:
|
|
145
|
+
c -= 1
|
|
146
|
+
for step in range(n):
|
|
147
|
+
r = n - 1 - step if up else step
|
|
148
|
+
for cc in (c, c - 1):
|
|
149
|
+
if not fn[r][cc]:
|
|
150
|
+
bit = bits[k] == 1 if k < len(bits) else False
|
|
151
|
+
k += 1
|
|
152
|
+
mat[r][cc] = bit != mf(r, cc)
|
|
153
|
+
up = not up
|
|
154
|
+
c -= 2
|
|
155
|
+
return mat
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _penalty(mat: list[list[bool]]) -> int:
|
|
159
|
+
n, score = len(mat), 0
|
|
160
|
+
for rows in (mat, [list(col) for col in zip(*mat)]): # rule 1 (runs) and rule 3 (finder-like) on rows and columns
|
|
161
|
+
for row in rows:
|
|
162
|
+
run = 1
|
|
163
|
+
for i in range(1, n):
|
|
164
|
+
if row[i] == row[i - 1]:
|
|
165
|
+
run += 1
|
|
166
|
+
else:
|
|
167
|
+
score += run - 2 if run >= 5 else 0; run = 1
|
|
168
|
+
score += run - 2 if run >= 5 else 0
|
|
169
|
+
s = "".join("1" if x else "0" for x in row)
|
|
170
|
+
score += 40 * (s.count("10111010000") + s.count("00001011101"))
|
|
171
|
+
for r in range(n - 1): # rule 2 (2x2 blocks)
|
|
172
|
+
for c in range(n - 1):
|
|
173
|
+
if mat[r][c] == mat[r][c + 1] == mat[r + 1][c] == mat[r + 1][c + 1]:
|
|
174
|
+
score += 3
|
|
175
|
+
dark = sum(sum(r) for r in mat)
|
|
176
|
+
score += 10 * (abs(dark * 100 // (n * n) - 50) // 5) # rule 4 (balance)
|
|
177
|
+
return score
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def matrix(text: str, mask: int | None = None) -> list[list[bool]]:
|
|
181
|
+
data = text.encode()
|
|
182
|
+
v = next((v for v in EC_M if len(data) <= _capacity(v) - (2 if v < 10 else 3)), None)
|
|
183
|
+
if v is None:
|
|
184
|
+
raise ValueError("text too long for this encoder (213 bytes at most)")
|
|
185
|
+
cw = _codewords(data, v)
|
|
186
|
+
if mask is not None:
|
|
187
|
+
return _build(v, cw, mask)
|
|
188
|
+
return min((_build(v, cw, m) for m in range(8)), key=_penalty)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def svg(text: str, box: int = 6, border: int = 4) -> str:
|
|
192
|
+
m = matrix(text)
|
|
193
|
+
n = len(m) + 2 * border
|
|
194
|
+
rects = "".join(f'<rect x="{(c + border) * box}" y="{(r + border) * box}" width="{box}" height="{box}"/>' for r, row in enumerate(m) for c, d in enumerate(row) if d)
|
|
195
|
+
return (f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {n * box} {n * box}" shape-rendering="crispEdges">'
|
|
196
|
+
f'<rect width="100%" height="100%" fill="#fff"/><g fill="#000">{rects}</g></svg>')
|