spatial-computing 0.16.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.
Files changed (143) hide show
  1. {spatial_computing-0.16.0/spatial_computing.egg-info → spatial_computing-0.17.0}/PKG-INFO +2 -2
  2. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/README.md +1 -1
  3. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/pyproject.toml +1 -1
  4. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/__init__.py +1 -1
  5. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/cli.py +5 -1
  6. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/core/registry.py +1 -1
  7. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/billing.py +13 -1
  8. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/db.py +10 -3
  9. spatial_computing-0.17.0/spatial/platform/oidc.py +124 -0
  10. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/pdf.py +4 -3
  11. spatial_computing-0.17.0/spatial/platform/qr.py +196 -0
  12. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/server.py +68 -1
  13. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/service.py +279 -37
  14. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/static/app.js +40 -24
  15. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/static/style.css +2 -0
  16. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/totp.py +2 -1
  17. spatial_computing-0.17.0/spatial/platform/vat.py +93 -0
  18. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/runtime/desktop/__init__.py +16 -4
  19. spatial_computing-0.17.0/spatial/runtime/desktop/start.sh +16 -0
  20. {spatial_computing-0.16.0 → spatial_computing-0.17.0/spatial_computing.egg-info}/PKG-INFO +2 -2
  21. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial_computing.egg-info/SOURCES.txt +5 -0
  22. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_platform2.py +189 -2
  23. spatial_computing-0.17.0/tests/test_qr.py +37 -0
  24. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_runtime.py +96 -2
  25. spatial_computing-0.17.0/tests/test_sso.py +216 -0
  26. spatial_computing-0.16.0/spatial/runtime/desktop/start.sh +0 -11
  27. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/LICENSE +0 -0
  28. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/setup.cfg +0 -0
  29. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/ai/__init__.py +0 -0
  30. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/ai/kvcache.py +0 -0
  31. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/ai/llm.py +0 -0
  32. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/compute/__init__.py +0 -0
  33. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/compute/cost.py +0 -0
  34. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/compute/detect.py +0 -0
  35. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/compute/monitor.py +0 -0
  36. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/compute/scheduler.py +0 -0
  37. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/compute/taskqueue.py +0 -0
  38. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/compute/worker.py +0 -0
  39. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/compute/workloads.py +0 -0
  40. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/core/__init__.py +0 -0
  41. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/core/auth.py +0 -0
  42. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/core/energy.py +0 -0
  43. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/core/ledger.py +0 -0
  44. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/core/model.py +0 -0
  45. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/core/protocol.py +0 -0
  46. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/fabric/__init__.py +0 -0
  47. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/fabric/cuda.py +0 -0
  48. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/fabric/devices.py +0 -0
  49. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/fabric/metal.py +0 -0
  50. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/fabric/metal_mandel.swift +0 -0
  51. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/fabric/metal_run.swift +0 -0
  52. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/fleet/__init__.py +0 -0
  53. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/fleet/agent.py +0 -0
  54. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/fleet/alerts.py +0 -0
  55. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/fleet/dashboard.py +0 -0
  56. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/fleet/ha.py +0 -0
  57. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/fleet/hub.py +0 -0
  58. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/holographic/__init__.py +0 -0
  59. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/holographic/cgh.py +0 -0
  60. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/holographic/model.py +0 -0
  61. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/intelligence/__init__.py +0 -0
  62. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/intelligence/predictor.py +0 -0
  63. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/interconnect/__init__.py +0 -0
  64. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/interconnect/collectives.py +0 -0
  65. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/interconnect/comm.py +0 -0
  66. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/interconnect/model.py +0 -0
  67. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/interconnect/tasks.py +0 -0
  68. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/kernel/__init__.py +0 -0
  69. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/kernel/dsl.py +0 -0
  70. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/kernel/library.py +0 -0
  71. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/memory/__init__.py +0 -0
  72. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/memory/fararray.py +0 -0
  73. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/memory/pageserver.py +0 -0
  74. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/memory/secure.py +0 -0
  75. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/memory/shared.py +0 -0
  76. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/memory/tiered.py +0 -0
  77. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/__init__.py +0 -0
  78. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/mailer.py +0 -0
  79. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/security.py +0 -0
  80. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/static/fonts/DMMono-normal-400.woff2 +0 -0
  81. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/static/fonts/DMMono-normal-500.woff2 +0 -0
  82. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/static/fonts/InstrumentSerif-italic-400.woff2 +0 -0
  83. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/static/fonts/InstrumentSerif-normal-400.woff2 +0 -0
  84. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/static/fonts/Inter-normal-400.woff2 +0 -0
  85. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/static/fonts/Inter-normal-500.woff2 +0 -0
  86. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/static/fonts/Inter-normal-600.woff2 +0 -0
  87. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/static/fonts.css +0 -0
  88. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/static/index.html +0 -0
  89. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/platform/static/logo.svg +0 -0
  90. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/q/__init__.py +0 -0
  91. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/q/__main__.py +0 -0
  92. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/q/backends/__init__.py +0 -0
  93. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/q/codegen.py +0 -0
  94. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/q/compiler.py +0 -0
  95. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/q/ir.py +0 -0
  96. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/q/lexer.py +0 -0
  97. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/q/parser.py +0 -0
  98. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/q/qir.py +0 -0
  99. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/q/runtime.py +0 -0
  100. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/q/sim.py +0 -0
  101. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/runtime/__init__.py +0 -0
  102. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/runtime/desktop/Dockerfile +0 -0
  103. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/runtime/envs.py +0 -0
  104. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/runtime/inspect.py +0 -0
  105. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/runtime/microvm.py +0 -0
  106. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/runtime/planner.py +0 -0
  107. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/runtime/runner.py +0 -0
  108. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/runtime/toolchain.py +0 -0
  109. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/scientific/__init__.py +0 -0
  110. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/scientific/jobs.py +0 -0
  111. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/simulation/__init__.py +0 -0
  112. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/simulation/heat.py +0 -0
  113. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/simulation/nbody.py +0 -0
  114. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/unified/__init__.py +0 -0
  115. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/unified/model.py +0 -0
  116. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/unified/planner.py +0 -0
  117. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial/unified/providers.py +0 -0
  118. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial_computing.egg-info/dependency_links.txt +0 -0
  119. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial_computing.egg-info/entry_points.txt +0 -0
  120. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial_computing.egg-info/requires.txt +0 -0
  121. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/spatial_computing.egg-info/top_level.txt +0 -0
  122. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_auth.py +0 -0
  123. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_compute.py +0 -0
  124. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_core.py +0 -0
  125. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_dashboard.py +0 -0
  126. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_domains.py +0 -0
  127. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_engines.py +0 -0
  128. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_fabric.py +0 -0
  129. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_fleet.py +0 -0
  130. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_ha.py +0 -0
  131. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_hardening.py +0 -0
  132. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_interconnect.py +0 -0
  133. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_kernel.py +0 -0
  134. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_memory.py +0 -0
  135. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_optimizer.py +0 -0
  136. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_platform.py +0 -0
  137. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_q.py +0 -0
  138. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_quorum.py +0 -0
  139. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_unified.py +0 -0
  140. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_v02.py +0 -0
  141. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_v03.py +0 -0
  142. {spatial_computing-0.16.0 → spatial_computing-0.17.0}/tests/test_v05.py +0 -0
  143. {spatial_computing-0.16.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.16.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.16.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).
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.16.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).
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.16.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"
@@ -3,4 +3,4 @@
3
3
  Status of every engine is declared in spatial.core.registry and must be backed
4
4
  by a test or benchmark before being set to OPERATIONAL.
5
5
  """
6
- __version__ = "0.16.0"
6
+ __version__ = "0.17.0"
@@ -106,11 +106,13 @@ 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
+ if d.view_url:
115
+ print(f"view-only link (watch, cannot type or click): {d.view_url}", flush=True)
114
116
  print("Ctrl+C removes it", flush=True)
115
117
  try:
116
118
  while True:
@@ -340,6 +342,8 @@ def main(argv=None):
340
342
  p.set_defaults(fn=cmd_fleet)
341
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)")
342
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")
343
347
  p.set_defaults(fn=cmd_desktop)
344
348
  p = sub.add_parser("platform", help="account service: sign up, sign in, apps, API keys, usage, billing (`spatial platform serve --help`)")
345
349
  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; roles are fixed; tax is a rate table, not a compliance engine; e-mail tested against a local SMTP stand-in, payments against a fake Stripe API only"),
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,8 +14,10 @@ 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 '');
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
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);
19
21
  CREATE TABLE IF NOT EXISTS invites(
20
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,
21
23
  created REAL NOT NULL, expires REAL NOT NULL, accepted REAL);
@@ -38,7 +40,10 @@ CREATE TABLE IF NOT EXISTS offsets(name TEXT PRIMARY KEY, value INTEGER NOT NULL
38
40
  CREATE TABLE IF NOT EXISTS invoices(
39
41
  id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, period TEXT NOT NULL, amount_usd REAL NOT NULL, status TEXT NOT NULL,
40
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,
41
- billing TEXT, seller TEXT);
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);
42
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);
43
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,
44
49
  attempts INTEGER NOT NULL DEFAULT 0, next_try REAL NOT NULL DEFAULT 0, last_error TEXT);
@@ -80,7 +85,9 @@ class DB:
80
85
  ADD = {"users": [("email_verified", "INTEGER NOT NULL DEFAULT 0"), ("totp_secret", "TEXT"), ("totp_enabled", "INTEGER NOT NULL DEFAULT 0"),
81
86
  ("totp_last_step", "INTEGER NOT NULL DEFAULT 0"), ("recovery", "TEXT NOT NULL DEFAULT '[]'"), ("personal_org", "INTEGER")],
82
87
  "apps": [("org_id", "INTEGER")],
83
- "invoices": [("org_id", "INTEGER"), ("number", "TEXT"), ("subtotal_usd", "REAL"), ("tax_rate", "REAL"), ("tax_usd", "REAL"), ("billing", "TEXT"), ("seller", "TEXT")],
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 ''")],
84
91
  "outbox": [("attempts", "INTEGER NOT NULL DEFAULT 0"), ("next_try", "REAL NOT NULL DEFAULT 0"), ("last_error", "TEXT")]}
85
92
 
86
93
  def _migrate(self) -> None:
@@ -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,12 @@ 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
- pg.text(R - 150, 790, "INVOICE", 18, True)
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
62
  pg.text(R - 150, 744, "Period: " + inv["period"], 9)
62
- pg.text(R - 150, 731, "Status: " + inv["status"].upper(), 9, True)
63
+ pg.text(R - 150, 731, ("Refers to " + inv["refers_to"]) if credit else "Status: " + inv["status"].upper(), 9, True)
63
64
  y = 690
64
65
  pg.text(L, y, "Billed to", 9, True)
65
66
  c = inv["customer"]
@@ -82,4 +83,4 @@ def invoice_pdf(inv: dict) -> bytes:
82
83
  for ln in inv["note"].splitlines()[:5]:
83
84
  pg.text(L, y, ln, 9); y -= 12
84
85
  pg.text(L, 40, "Usage is metered per finished task on the Spatial Computing fleet.", 8)
85
- return build([pg], f"Invoice {inv['number']}")
86
+ 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>')
@@ -18,6 +18,7 @@ import threading
18
18
  import time
19
19
  from http import cookies
20
20
  from pathlib import Path
21
+ import urllib.parse
21
22
  from urllib.parse import parse_qs, urlparse
22
23
 
23
24
  from ..core.auth import Authorizer, authorizer_from_file
@@ -66,8 +67,14 @@ def make_handler(pf: Platform, secure_cookies: bool):
66
67
  route("PUT", "/api/admin/pricing", "admin_pricing")
67
68
  route("PUT", "/api/admin/company", "admin_company")
68
69
  route("POST", "/api/admin/test-mail", "admin_test_mail")
70
+ route("GET", "/api/admin/invoices", "admin_invoices")
71
+ route("POST", r"/api/admin/invoices/(\d+)/credit", "admin_credit")
72
+ route("GET", r"/api/credit-notes/(\d+)/pdf", "credit_pdf")
69
73
  route("GET", "/api/admin/mail", "admin_mail")
70
74
  route("POST", "/api/login/2fa", "login_2fa", auth=False, csrf=False)
75
+ route("GET", "/api/sso/config", "sso_config", auth=False)
76
+ route("GET", "/api/sso/start", "sso_start", auth=False)
77
+ route("GET", "/api/sso/callback", "sso_callback", auth=False)
71
78
  route("POST", "/api/2fa/setup", "totp_setup", cookie_only=True)
72
79
  route("POST", "/api/2fa/enable", "totp_enable", cookie_only=True)
73
80
  route("POST", "/api/2fa/disable", "totp_disable", cookie_only=True)
@@ -78,6 +85,8 @@ def make_handler(pf: Platform, secure_cookies: bool):
78
85
  route("GET", "/api/org", "org_get")
79
86
  route("PATCH", "/api/org", "org_update")
80
87
  route("DELETE", "/api/org", "org_delete", cookie_only=True)
88
+ route("POST", "/api/org/roles", "roles_create")
89
+ route("DELETE", r"/api/org/roles/([a-z][a-z0-9-]{0,29})", "roles_delete")
81
90
  route("POST", "/api/org/invites", "invites_create")
82
91
  route("DELETE", r"/api/org/invites/(\d+)", "invites_revoke")
83
92
  route("PATCH", r"/api/org/members/(\d+)", "members_role")
@@ -235,7 +244,7 @@ def make_handler(pf: Platform, secure_cookies: bool):
235
244
  user, csrf = s
236
245
  out = {"user": pf.user_view(user) if user else None, "csrf": csrf, "hub": pf.hub_public, "payments": pf.stripe.configured, "docs": pf.docs_url}
237
246
  if user:
238
- out.update(orgs=pf.list_orgs(user), org=user.org_id, role=user["role"], require_verified=pf.require_verified)
247
+ out.update(orgs=pf.list_orgs(user), org=user.org_id, role=user["role"], perms=sorted(user["perms"]), require_verified=pf.require_verified)
239
248
  self._json(200, out)
240
249
 
241
250
  def h_signup(self, g, u, s):
@@ -252,6 +261,33 @@ def make_handler(pf: Platform, secure_cookies: bool):
252
261
  return self._json(200, {"needs_2fa": True, "ticket": e.ticket})
253
262
  self._json(200, {"user": user, "csrf": csrf}, self._set_cookie(token))
254
263
 
264
+ def h_sso_config(self, g, u, s):
265
+ self._json(200, pf.sso_config())
266
+
267
+ def _redirect(self, location: str, extra: dict | None = None):
268
+ self.send_response(302)
269
+ self.send_header("Location", location)
270
+ self.send_header("Cache-Control", "no-store")
271
+ for k, v in (extra or {}).items():
272
+ self.send_header(k, v)
273
+ self.send_header("Content-Length", "0")
274
+ self.end_headers()
275
+
276
+ def h_sso_start(self, g, u, s):
277
+ self._redirect(pf.sso_start(self._ip()))
278
+
279
+ def h_sso_callback(self, g, u, s):
280
+ q = parse_qs(u.query)
281
+ try:
282
+ if q.get("error"):
283
+ raise ApiError(401, "single sign-on was cancelled or refused by the provider")
284
+ token, csrf, user = pf.sso_callback((q.get("code") or [""])[0], (q.get("state") or [""])[0], self._ip(), self.headers.get("User-Agent", ""))
285
+ except TwoFactorRequired as e:
286
+ return self._redirect("/#/2fa/" + e.ticket)
287
+ except ApiError as e:
288
+ return self._redirect("/#/login?sso_error=" + urllib.parse.quote(e.message))
289
+ self._redirect("/#/", self._set_cookie(token))
290
+
255
291
  def h_login_2fa(self, g, u, s):
256
292
  d = self._data()
257
293
  token, csrf, user = pf.login_2fa(d.get("ticket"), d.get("code"), self._ip(), self.headers.get("User-Agent", ""))
@@ -292,6 +328,14 @@ def make_handler(pf: Platform, secure_cookies: bool):
292
328
  pf.delete_org(s[0])
293
329
  self._json(200, {"ok": True})
294
330
 
331
+ def h_roles_create(self, g, u, s):
332
+ d = self._data()
333
+ self._json(201, {"role": pf.create_role(s[0], d.get("name"), d.get("perms"))})
334
+
335
+ def h_roles_delete(self, g, u, s):
336
+ pf.delete_role(s[0], g[0])
337
+ self._json(200, {"ok": True})
338
+
295
339
  def h_invites_create(self, g, u, s):
296
340
  d = self._data()
297
341
  self._json(201, {"invite": pf.invite(s[0], d.get("email"), d.get("role", "member"))})
@@ -327,6 +371,17 @@ def make_handler(pf: Platform, secure_cookies: bool):
327
371
  def h_admin_test_mail(self, g, u, s):
328
372
  self._json(200, pf.admin_test_mail(s[0], self._data().get("to")))
329
373
 
374
+ def h_admin_invoices(self, g, u, s):
375
+ self._json(200, self._page(u, pf.admin_invoices(s[0], 500), "invoices"))
376
+
377
+ def h_admin_credit(self, g, u, s):
378
+ d = self._data()
379
+ self._json(201, {"credit_note": pf.admin_credit_note(s[0], int(g[0]), d.get("amount_usd"), d.get("reason"))})
380
+
381
+ def h_credit_pdf(self, g, u, s):
382
+ pdf, name = pf.credit_note_pdf(s[0], int(g[0]))
383
+ self._send(200, pdf, "application/pdf", {"Content-Disposition": f'attachment; filename="{name}"'})
384
+
330
385
  def h_admin_mail(self, g, u, s):
331
386
  self._json(200, {"mail": pf.admin_mail(s[0])})
332
387
 
@@ -485,6 +540,11 @@ def main(argv=None):
485
540
  ap.add_argument("--smtp-from", default="no-reply@localhost")
486
541
  ap.add_argument("--smtp-ssl", action="store_true", help="implicit TLS (port 465) instead of STARTTLS")
487
542
  ap.add_argument("--smtp-no-starttls", action="store_true", help="plain SMTP, for a local relay only")
543
+ ap.add_argument("--oidc-issuer", help="OpenID Connect provider URL (enables 'Sign in with ...'); the client secret goes in OIDC_CLIENT_SECRET")
544
+ ap.add_argument("--oidc-client-id")
545
+ ap.add_argument("--oidc-name", default="Single sign-on", help="label of the sign-in button")
546
+ ap.add_argument("--oidc-domains", default="", help="comma list: only these e-mail domains may sign in this way")
547
+ ap.add_argument("--oidc-no-create", action="store_true", help="only existing accounts may sign in this way")
488
548
  ap.add_argument("--require-verified", choices=["auto", "yes", "no"], default="auto", help="e-mail verification before keys and jobs (auto: only when SMTP is configured)")
489
549
  ap.add_argument("--dev-outbox", action="store_true", help="expose /api/dev/outbox (reset links) for local development")
490
550
  a = ap.parse_args(argv)
@@ -501,6 +561,13 @@ def main(argv=None):
501
561
  a.public_url or f"http://{a.host}:{a.port}", smtp=smtp, docs_url=a.docs_url,
502
562
  require_verified={"auto": None, "yes": True, "no": False}[a.require_verified])
503
563
  pf.dev_outbox = a.dev_outbox
564
+ if a.oidc_issuer:
565
+ from .oidc import Oidc
566
+ secret = os.environ.get("OIDC_CLIENT_SECRET", "")
567
+ if not (a.oidc_client_id and secret):
568
+ raise SystemExit("--oidc-issuer needs --oidc-client-id and the OIDC_CLIENT_SECRET environment variable")
569
+ pf.oidc = Oidc(a.oidc_issuer, a.oidc_client_id, secret, f"{pf.public_url}/api/sso/callback", a.oidc_name,
570
+ tuple(d.strip().lower() for d in a.oidc_domains.split(",") if d.strip()), not a.oidc_no_create)
504
571
  srv = serve(pf, a.host, a.port, a.allow_remote, a.secure_cookies)
505
572
 
506
573
  def ingest_loop():