sendproof-core 0.1.0.alpha.1

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 (229) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.md +55 -0
  4. data/lib/sendproof/assets.rb +70 -0
  5. data/lib/sendproof/attribution.rb +98 -0
  6. data/lib/sendproof/capture.rb +66 -0
  7. data/lib/sendproof/clock.rb +54 -0
  8. data/lib/sendproof/configuration.rb +241 -0
  9. data/lib/sendproof/data_store.rb +34 -0
  10. data/lib/sendproof/dynamodb/store.rb +183 -0
  11. data/lib/sendproof/dynamodb.rb +17 -0
  12. data/lib/sendproof/elasticsearch/store.rb +24 -0
  13. data/lib/sendproof/elasticsearch.rb +17 -0
  14. data/lib/sendproof/firestore/interceptor.rb +38 -0
  15. data/lib/sendproof/firestore/store.rb +150 -0
  16. data/lib/sendproof/firestore.rb +99 -0
  17. data/lib/sendproof/handler.rb +23 -0
  18. data/lib/sendproof/identity.rb +37 -0
  19. data/lib/sendproof/limits.rb +113 -0
  20. data/lib/sendproof/middleware.rb +68 -0
  21. data/lib/sendproof/mongo/engine.rb +692 -0
  22. data/lib/sendproof/mongo/guarded.rb +100 -0
  23. data/lib/sendproof/mongo/plain.rb +45 -0
  24. data/lib/sendproof/mongo/store.rb +54 -0
  25. data/lib/sendproof/mongo/subscriber.rb +21 -0
  26. data/lib/sendproof/mongo.rb +41 -0
  27. data/lib/sendproof/mongoid/store.rb +58 -0
  28. data/lib/sendproof/mongoid.rb +65 -0
  29. data/lib/sendproof/observed_request.rb +108 -0
  30. data/lib/sendproof/opensearch/store.rb +21 -0
  31. data/lib/sendproof/opensearch.rb +17 -0
  32. data/lib/sendproof/operation_matcher.rb +28 -0
  33. data/lib/sendproof/pool_hooks.rb +80 -0
  34. data/lib/sendproof/preview_request.rb +44 -0
  35. data/lib/sendproof/preview_transport.rb +331 -0
  36. data/lib/sendproof/protocol.rb +81 -0
  37. data/lib/sendproof/provider.rb +83 -0
  38. data/lib/sendproof/recorder.rb +298 -0
  39. data/lib/sendproof/redaction.rb +98 -0
  40. data/lib/sendproof/redis/commands.rb +76 -0
  41. data/lib/sendproof/redis/store.rb +205 -0
  42. data/lib/sendproof/redis.rb +18 -0
  43. data/lib/sendproof/search/middleware.rb +39 -0
  44. data/lib/sendproof/search/store.rb +213 -0
  45. data/lib/sendproof/search.rb +82 -0
  46. data/lib/sendproof/stores/classify.rb +346 -0
  47. data/lib/sendproof/stores/guard.rb +127 -0
  48. data/lib/sendproof/stores/tables.rb +1328 -0
  49. data/lib/sendproof/stores.rb +12 -0
  50. data/lib/sendproof/trace_store.rb +110 -0
  51. data/lib/sendproof/transaction_control.rb +187 -0
  52. data/lib/sendproof/ui/action-bar.js +91 -0
  53. data/lib/sendproof/ui/api.js +239 -0
  54. data/lib/sendproof/ui/app.css +848 -0
  55. data/lib/sendproof/ui/app.js +742 -0
  56. data/lib/sendproof/ui/autofill.js +137 -0
  57. data/lib/sendproof/ui/code-copy.js +71 -0
  58. data/lib/sendproof/ui/code-picker.js +149 -0
  59. data/lib/sendproof/ui/commands.js +197 -0
  60. data/lib/sendproof/ui/components.js +77 -0
  61. data/lib/sendproof/ui/context-bar.js +82 -0
  62. data/lib/sendproof/ui/copy.js +92 -0
  63. data/lib/sendproof/ui/coverage-popover.js +35 -0
  64. data/lib/sendproof/ui/crumb-fit.js +80 -0
  65. data/lib/sendproof/ui/deprecation.js +164 -0
  66. data/lib/sendproof/ui/display-settings.js +175 -0
  67. data/lib/sendproof/ui/doc-diff.js +209 -0
  68. data/lib/sendproof/ui/docs-view.js +347 -0
  69. data/lib/sendproof/ui/favicon.png +0 -0
  70. data/lib/sendproof/ui/favicon.svg +1 -0
  71. data/lib/sendproof/ui/field-help.js +52 -0
  72. data/lib/sendproof/ui/field-modules.js +23 -0
  73. data/lib/sendproof/ui/fields/controls.js +179 -0
  74. data/lib/sendproof/ui/fields/dom.js +36 -0
  75. data/lib/sendproof/ui/fields/infer.js +71 -0
  76. data/lib/sendproof/ui/fields/lookup-source.js +63 -0
  77. data/lib/sendproof/ui/fields/lookup.js +285 -0
  78. data/lib/sendproof/ui/fields/render.js +496 -0
  79. data/lib/sendproof/ui/fields/select.js +175 -0
  80. data/lib/sendproof/ui/fields/validate.js +363 -0
  81. data/lib/sendproof/ui/fields/validation-formats.js +164 -0
  82. data/lib/sendproof/ui/fields/validation-references.js +68 -0
  83. data/lib/sendproof/ui/fields/validation-values.js +137 -0
  84. data/lib/sendproof/ui/generate-menu.js +44 -0
  85. data/lib/sendproof/ui/generate.js +184 -0
  86. data/lib/sendproof/ui/header-editor.js +777 -0
  87. data/lib/sendproof/ui/headers.js +188 -0
  88. data/lib/sendproof/ui/highlight.js +257 -0
  89. data/lib/sendproof/ui/history-popover.js +24 -0
  90. data/lib/sendproof/ui/i18n.js +253 -0
  91. data/lib/sendproof/ui/icons.js +87 -0
  92. data/lib/sendproof/ui/index.html +70 -0
  93. data/lib/sendproof/ui/issues.js +187 -0
  94. data/lib/sendproof/ui/json-view.js +166 -0
  95. data/lib/sendproof/ui/lang-icons.js +62 -0
  96. data/lib/sendproof/ui/layout.js +262 -0
  97. data/lib/sendproof/ui/listbox.js +334 -0
  98. data/lib/sendproof/ui/locales/ar-capture.js +366 -0
  99. data/lib/sendproof/ui/locales/ar-stores.js +116 -0
  100. data/lib/sendproof/ui/locales/ar.js +561 -0
  101. data/lib/sendproof/ui/locales/cs-capture.js +442 -0
  102. data/lib/sendproof/ui/locales/cs-stores.js +116 -0
  103. data/lib/sendproof/ui/locales/cs.js +689 -0
  104. data/lib/sendproof/ui/locales/da-capture.js +347 -0
  105. data/lib/sendproof/ui/locales/da-stores.js +116 -0
  106. data/lib/sendproof/ui/locales/da.js +522 -0
  107. data/lib/sendproof/ui/locales/de-capture.js +347 -0
  108. data/lib/sendproof/ui/locales/de-stores.js +116 -0
  109. data/lib/sendproof/ui/locales/de.js +519 -0
  110. data/lib/sendproof/ui/locales/el-capture.js +347 -0
  111. data/lib/sendproof/ui/locales/el-stores.js +116 -0
  112. data/lib/sendproof/ui/locales/el.js +520 -0
  113. data/lib/sendproof/ui/locales/en-capture.js +349 -0
  114. data/lib/sendproof/ui/locales/en-stores.js +95 -0
  115. data/lib/sendproof/ui/locales/en.js +522 -0
  116. data/lib/sendproof/ui/locales/es-capture.js +353 -0
  117. data/lib/sendproof/ui/locales/es-stores.js +116 -0
  118. data/lib/sendproof/ui/locales/es.js +525 -0
  119. data/lib/sendproof/ui/locales/fa-capture.js +348 -0
  120. data/lib/sendproof/ui/locales/fa-stores.js +116 -0
  121. data/lib/sendproof/ui/locales/fa.js +521 -0
  122. data/lib/sendproof/ui/locales/fi-capture.js +347 -0
  123. data/lib/sendproof/ui/locales/fi-stores.js +116 -0
  124. data/lib/sendproof/ui/locales/fi.js +523 -0
  125. data/lib/sendproof/ui/locales/fr-capture.js +353 -0
  126. data/lib/sendproof/ui/locales/fr-stores.js +116 -0
  127. data/lib/sendproof/ui/locales/fr.js +525 -0
  128. data/lib/sendproof/ui/locales/he-capture.js +358 -0
  129. data/lib/sendproof/ui/locales/he-stores.js +116 -0
  130. data/lib/sendproof/ui/locales/he.js +529 -0
  131. data/lib/sendproof/ui/locales/hi-capture.js +348 -0
  132. data/lib/sendproof/ui/locales/hi-stores.js +116 -0
  133. data/lib/sendproof/ui/locales/hi.js +523 -0
  134. data/lib/sendproof/ui/locales/id-capture.js +347 -0
  135. data/lib/sendproof/ui/locales/id-stores.js +116 -0
  136. data/lib/sendproof/ui/locales/id.js +521 -0
  137. data/lib/sendproof/ui/locales/it-capture.js +361 -0
  138. data/lib/sendproof/ui/locales/it-stores.js +116 -0
  139. data/lib/sendproof/ui/locales/it.js +523 -0
  140. data/lib/sendproof/ui/locales/ja-capture.js +346 -0
  141. data/lib/sendproof/ui/locales/ja-stores.js +116 -0
  142. data/lib/sendproof/ui/locales/ja.js +521 -0
  143. data/lib/sendproof/ui/locales/ko-capture.js +346 -0
  144. data/lib/sendproof/ui/locales/ko-stores.js +116 -0
  145. data/lib/sendproof/ui/locales/ko.js +522 -0
  146. data/lib/sendproof/ui/locales/nb-capture.js +349 -0
  147. data/lib/sendproof/ui/locales/nb-stores.js +116 -0
  148. data/lib/sendproof/ui/locales/nb.js +521 -0
  149. data/lib/sendproof/ui/locales/nl-capture.js +355 -0
  150. data/lib/sendproof/ui/locales/nl-stores.js +116 -0
  151. data/lib/sendproof/ui/locales/nl.js +520 -0
  152. data/lib/sendproof/ui/locales/pl-capture.js +432 -0
  153. data/lib/sendproof/ui/locales/pl-stores.js +116 -0
  154. data/lib/sendproof/ui/locales/pl.js +528 -0
  155. data/lib/sendproof/ui/locales/pt-BR-capture.js +350 -0
  156. data/lib/sendproof/ui/locales/pt-BR-stores.js +116 -0
  157. data/lib/sendproof/ui/locales/pt-BR.js +523 -0
  158. data/lib/sendproof/ui/locales/pt-PT-capture.js +350 -0
  159. data/lib/sendproof/ui/locales/pt-PT-stores.js +116 -0
  160. data/lib/sendproof/ui/locales/pt-PT.js +523 -0
  161. data/lib/sendproof/ui/locales/ru-capture.js +437 -0
  162. data/lib/sendproof/ui/locales/ru-stores.js +116 -0
  163. data/lib/sendproof/ui/locales/ru.js +624 -0
  164. data/lib/sendproof/ui/locales/sv-capture.js +349 -0
  165. data/lib/sendproof/ui/locales/sv-stores.js +116 -0
  166. data/lib/sendproof/ui/locales/sv.js +518 -0
  167. data/lib/sendproof/ui/locales/th-capture.js +347 -0
  168. data/lib/sendproof/ui/locales/th-stores.js +116 -0
  169. data/lib/sendproof/ui/locales/th.js +521 -0
  170. data/lib/sendproof/ui/locales/tr-capture.js +348 -0
  171. data/lib/sendproof/ui/locales/tr-stores.js +116 -0
  172. data/lib/sendproof/ui/locales/tr.js +521 -0
  173. data/lib/sendproof/ui/locales/uk-capture.js +442 -0
  174. data/lib/sendproof/ui/locales/uk-stores.js +116 -0
  175. data/lib/sendproof/ui/locales/uk.js +630 -0
  176. data/lib/sendproof/ui/locales/vi-capture.js +346 -0
  177. data/lib/sendproof/ui/locales/vi-stores.js +116 -0
  178. data/lib/sendproof/ui/locales/vi.js +523 -0
  179. data/lib/sendproof/ui/locales/zh-Hans-capture.js +347 -0
  180. data/lib/sendproof/ui/locales/zh-Hans-stores.js +116 -0
  181. data/lib/sendproof/ui/locales/zh-Hans.js +523 -0
  182. data/lib/sendproof/ui/locales/zh-Hant-capture.js +346 -0
  183. data/lib/sendproof/ui/locales/zh-Hant-stores.js +116 -0
  184. data/lib/sendproof/ui/locales/zh-Hant.js +522 -0
  185. data/lib/sendproof/ui/manifest.json +866 -0
  186. data/lib/sendproof/ui/markdown.js +39 -0
  187. data/lib/sendproof/ui/model-view.js +182 -0
  188. data/lib/sendproof/ui/navigation.js +233 -0
  189. data/lib/sendproof/ui/operation-header.js +76 -0
  190. data/lib/sendproof/ui/operations.js +7 -0
  191. data/lib/sendproof/ui/overview-view.js +63 -0
  192. data/lib/sendproof/ui/personas.js +59 -0
  193. data/lib/sendproof/ui/popover.js +71 -0
  194. data/lib/sendproof/ui/preview-false.js +108 -0
  195. data/lib/sendproof/ui/request-editor.js +496 -0
  196. data/lib/sendproof/ui/response-metadata.js +354 -0
  197. data/lib/sendproof/ui/response-viewer.js +618 -0
  198. data/lib/sendproof/ui/result-blocked.js +155 -0
  199. data/lib/sendproof/ui/result-capture.js +25 -0
  200. data/lib/sendproof/ui/result-database.js +185 -0
  201. data/lib/sendproof/ui/result-effects.js +176 -0
  202. data/lib/sendproof/ui/result-headers.js +106 -0
  203. data/lib/sendproof/ui/result-logs.js +408 -0
  204. data/lib/sendproof/ui/result-states.js +213 -0
  205. data/lib/sendproof/ui/results.js +371 -0
  206. data/lib/sendproof/ui/router.js +118 -0
  207. data/lib/sendproof/ui/schema-model.js +336 -0
  208. data/lib/sendproof/ui/schema-tree.js +344 -0
  209. data/lib/sendproof/ui/schema.js +397 -0
  210. data/lib/sendproof/ui/security.js +31 -0
  211. data/lib/sendproof/ui/seeded-menu.js +69 -0
  212. data/lib/sendproof/ui/settings.js +93 -0
  213. data/lib/sendproof/ui/shortcuts-sheet.js +73 -0
  214. data/lib/sendproof/ui/shortcuts.js +190 -0
  215. data/lib/sendproof/ui/sidebar.js +289 -0
  216. data/lib/sendproof/ui/signin.js +259 -0
  217. data/lib/sendproof/ui/snippets.js +530 -0
  218. data/lib/sendproof/ui/store-marks.js +47 -0
  219. data/lib/sendproof/ui/stores.js +131 -0
  220. data/lib/sendproof/ui/styles.css +971 -0
  221. data/lib/sendproof/ui/toggletip.js +53 -0
  222. data/lib/sendproof/ui/uuid.js +10 -0
  223. data/lib/sendproof/ui/view.js +122 -0
  224. data/lib/sendproof/ui/views.css +653 -0
  225. data/lib/sendproof/version.rb +9 -0
  226. data/lib/sendproof/workbench.rb +102 -0
  227. data/lib/sendproof-core.rb +3 -0
  228. data/lib/sendproof.rb +121 -0
  229. metadata +292 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b6529a27eec0d1fbd4148f1cffd9e0d8066da654d1be13690af6ce3fe79f12c9
4
+ data.tar.gz: 0a94e3230502d6f251fe5053a219c9332b90391eb65dc0ff32616b5176aebc20
5
+ SHA512:
6
+ metadata.gz: 32af50e0c717af11e2c1dabeb4bcfd1866940d5ac332fd87482139cfd50a82f5c2f69e05fbd84e55aa5c7b9c6322914c842c5192e37c397747d7eed3633a4c0e
7
+ data.tar.gz: 7ddd3d9aaae71a86f759b215d54ce6dbd09d49b4c61da8dae1edfc52bb2b496d8216abc24d9cbc135e0ba6fc3d4176e499962d9dd7a662bb28f1fa4ab7716c44
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sendproof contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # sendproof-core
2
+
3
+ Framework-neutral Rack core of [Sendproof](https://github.com/mprync/sendproof) (bench protocol v1). It serves the embedded workbench UI under `/sendproof/`, answers discovery, runs rollback previews through your application, and stores observed-send traces.
4
+
5
+ Most Rails users want [`sendproof-rails`](../sendproof-rails/README.md). Use the core directly for Sinatra, Roda, Hanami or any Rack app.
6
+
7
+ ```ruby
8
+ # config.ru
9
+ use Sendproof::Middleware,
10
+ environments: %w[development], environment: ENV.fetch("RACK_ENV"),
11
+ open_api_url: "/openapi.json",
12
+ identity: ->(request) { (u = request.session[:user]) && { name: u["name"], subject: u["id"] } },
13
+ preview_operations: [%w[POST /items], %w[PATCH /items/{id}]],
14
+ providers: [Sendproof::ActiveRecord::Provider.new]
15
+ run App
16
+ ```
17
+
18
+ Place the middleware after session and authentication middleware and before the router.
19
+
20
+ ## What you wire up
21
+
22
+ 1. **Handler hook.** Wrap the endpoint handler (after authentication and authorization) in `Sendproof::Handler.around(env, eligible: true) { ... }`. The preview transaction, observed-send capture and "did the handler run" decision are anchored there. Without it a Rack-only application cannot be previewed. `sendproof-rails` does this for every controller action.
23
+ 2. **Operations.** `preview_operations` is a list of `[verb, "/path/{param}"]` (or a callable). The default resolver matches requests against it. Adapters can set `target_resolver` (`method, path, env -> :eligible | :ineligible | nil`).
24
+ 3. **Provider.** Register exactly one object responding to `available?`, `database`, `begin_preview(context)` and optionally `begin_observation(context)`. See `Sendproof::Provider` for the session contract (`changes`, `rollback!`, `close`).
25
+ 4. **Identity (optional).** `identity` returns `{name:, role:, subject:}`. The `subject` owns observed-send traces; without one no trace is recorded.
26
+
27
+ 5. **Data stores (optional).** `config.data_store(store)` registers a hook for MongoDB, Redis, DynamoDB, Elasticsearch, OpenSearch or Firestore (`require "sendproof/mongoid"`, `"sendproof/mongo"`, `"sendproof/redis"`, `"sendproof/dynamodb"`, `"sendproof/elasticsearch"`, `"sendproof/opensearch"`, `"sendproof/firestore"`; see [data-stores.md](../data-stores.md)). A store is any object with `system`, `describe` and, optionally, `begin_preview(context, recorder)` and `finish_preview(recorder)` (`Sendproof::DataStore`). With stores registered the SQL provider is optional. Operations you know write to a guarded store are listed in `preview_unavailable` (`method`, `path`, `reason`, `stores`) and left out of `preview_operations`; discovery reports them with the binding (`framework`) and the provider's `database_system`.
28
+
29
+ ## Recording side effects
30
+
31
+ ```ruby
32
+ # Returns true in a preview (skip it). In an observed send it records "delivered" and returns false.
33
+ unless Sendproof.record_email("Welcome", from: "noreply@example.test", to: [user.email], subject: "Hi", text: "…")
34
+ Mailer.deliver(...)
35
+ end
36
+ Sendproof.deliver(:job, "Index item") { IndexJob.perform_later(id) } # skipped in preview
37
+ Sendproof.log("Warning", "stock below threshold")
38
+ ```
39
+
40
+ ## Configuration
41
+
42
+ | Option | Default | Notes |
43
+ | --- | --- | --- |
44
+ | `environments` | none | Environments in which anything is served. |
45
+ | `open_api_url` | required | Same-origin path of the OpenAPI document. |
46
+ | `open_api_document(name, url)` | | Extra documents for the picker. |
47
+ | `auth_provider(label, kind, url)` | | `cookie` (password JSON), `personas`, or a host sign-in page. |
48
+ | `field_module(url)` | | Host-served ES module with custom field renderers. |
49
+ | `authorize` | allow | `request -> truthy` gate for workbench routes and previews. |
50
+ | `include_sql_parameter_values` | development only | Secret-looking names are always `[REDACTED]`. |
51
+ | `trace_ttl` / `trace_clock` | 300 s / monotonic | A test can inject a clock or a short TTL. |
52
+ | `exception_status` | none | `error -> 4xx` turns a framework-handled exception into a confirmed inner response. |
53
+ | `ui_directory` | embedded bundle | Directory with `manifest.json` from `tools/pack-ui.mjs`. |
54
+
55
+ Limits match the .NET adapter: 500 logs, 100 effects, 200 changes, 32 log properties, 64 SQL parameters, 1 MiB preview response, 8 traces per owner and 32 in total.
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sendproof
4
+ # Serves the packed UI bundle (manifest.json plus files) embedded in the gem.
5
+ #
6
+ # The bundle is produced by +tools/pack-ui.mjs+ (+rake ui:pack+) and is never edited here.
7
+ # Each file's SHA-256 is verified against the manifest before it is served.
8
+ class Assets
9
+ DEFAULT_DIRECTORY = File.expand_path("ui", __dir__)
10
+
11
+ # Raised when the bundle is missing or a file does not match its manifest entry.
12
+ class BundleError < StandardError; end
13
+
14
+ Asset = Struct.new(:body, :content_type, :sha256)
15
+
16
+ attr_reader :directory
17
+
18
+ def initialize(directory = nil)
19
+ @directory = File.expand_path(directory || DEFAULT_DIRECTORY)
20
+ @mutex = Mutex.new
21
+ @cache = {}
22
+ @manifest = nil
23
+ end
24
+
25
+ # @return [Hash] the parsed manifest: +version+, +bundleHash+ and +files+
26
+ def manifest
27
+ @manifest ||= begin
28
+ path = File.join(directory, "manifest.json")
29
+ raise BundleError, "The Sendproof UI bundle is missing (#{path}). Run `rake ui:pack`." unless File.file?(path)
30
+
31
+ JSON.parse(File.read(path))
32
+ end
33
+ end
34
+
35
+ # @return [Asset, nil] nil for names outside the manifest
36
+ def find(name)
37
+ entry = manifest.fetch("files", {})[name]
38
+ return nil unless entry
39
+
40
+ @mutex.synchronize { @cache[name] ||= load_asset(name, entry) }
41
+ end
42
+
43
+ # Rack response for +name+, honouring +If-None-Match+; nil when unknown.
44
+ def serve(name, request)
45
+ asset = find(name) or return nil
46
+
47
+ etag = %("#{asset.sha256}")
48
+ headers = { "content-type" => asset.content_type, "cache-control" => "no-cache",
49
+ "x-content-type-options" => "nosniff", "etag" => etag }
50
+ return [304, headers, []] if request.get_header("HTTP_IF_NONE_MATCH") == etag
51
+
52
+ headers["content-length"] = asset.body.bytesize.to_s
53
+ [200, headers, request.head? ? [] : [asset.body]]
54
+ end
55
+
56
+ private
57
+
58
+ def load_asset(name, entry)
59
+ path = File.join(directory, name)
60
+ raise BundleError, "#{name} is listed in the manifest but missing." unless File.file?(path)
61
+
62
+ body = File.binread(path)
63
+ unless Digest::SHA256.hexdigest(body) == entry["sha256"] && body.bytesize == entry["bytes"]
64
+ raise BundleError, "#{name} does not match its manifest entry."
65
+ end
66
+
67
+ Asset.new(body.freeze, entry["contentType"], entry["sha256"])
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sendproof
4
+ # Which request a data-store write belongs to, and what happens to a write that belongs to none.
5
+ #
6
+ # A store hook finds its request through {Capture}, which is thread- and fiber-local: a write sent from
7
+ # a thread or fiber the handler started, or from a client's own background threads (Firestore's
8
+ # +BulkWriter+), carries no request. While any Preview is open such a write is treated as that Preview's
9
+ # write: it is refused before it is sent, and every open Preview is blocked (409) whatever the store's
10
+ # mode (spec/data-stores.md, "Writes the binding can't attribute to a request").
11
+ #
12
+ # A write is attributed when it runs inside a Preview or observed send, inside any request that passed
13
+ # through {Middleware}, or inside {Sendproof.detached}, the mark for background work such as a job
14
+ # worker running in the same process.
15
+ module Attribution
16
+ KEY = :sendproof_attribution
17
+
18
+ @open = {}.compare_by_identity
19
+ @lock = Mutex.new
20
+
21
+ class << self
22
+ # Marks the block as a request {Middleware} handles, so its writes never fail a Preview.
23
+ def request(&) = mark(:request, &)
24
+
25
+ # Marks the block as work that belongs to no request (see {Sendproof.detached}).
26
+ def detached(&) = mark(:detached, &)
27
+
28
+ # @return [Boolean] whether a write sent now belongs to a request, or was marked detached
29
+ def attributed? = !Capture.current.nil? || !Thread.current[KEY].nil?
30
+
31
+ # Registers a Preview for the time its handler and cleanup run.
32
+ # @param recorder [Recorder]
33
+ def open(recorder)
34
+ @lock.synchronize { @open[recorder] = true }
35
+ end
36
+
37
+ # Removes a Preview registered with {open}.
38
+ def close(recorder)
39
+ @lock.synchronize { @open.delete(recorder) }
40
+ end
41
+
42
+ # Called by a store hook, before it sends, for each write outside a Preview. A write that belongs to
43
+ # no request while a Preview is open is refused, and the error is raised so the write is never sent.
44
+ # Every open Preview is marked blocked (409), whatever the store's mode: nothing reached the store, so
45
+ # there is nothing a rollback could have missed. Does nothing for an attributed write or when no
46
+ # Preview is open.
47
+ #
48
+ # @param store [String] the store id, such as +"redis"+
49
+ # @param operation [String] the command or action name
50
+ # @raise [PreviewWriteBlocked] when the write is refused
51
+ def refuse_unattributed(store, operation)
52
+ return if attributed?
53
+
54
+ inherited = Capture.inherited_preview
55
+ return refuse_inherited(inherited, store, operation) if inherited
56
+
57
+ open = @lock.synchronize { @open.keys }
58
+ return if open.empty?
59
+
60
+ why = "A #{Stores::Guard.store_name(store)} #{operation} was sent outside any request while a Preview ran " \
61
+ "(from a thread or fiber the handler started, or from background work), so Sendproof refused it: it can't " \
62
+ "tell it apart from the Preview's own writes. Mark background work with Sendproof.detached."
63
+ reason = Stores::Guard.write_reason(store)
64
+ open.each do |recorder|
65
+ recorder.block(store: store, operation: operation, detail: reason)
66
+ recorder.db(system: store, operation: operation, blocked: true)
67
+ end
68
+ raise PreviewWriteBlocked.new(store, operation, "#{reason}. #{why}")
69
+ end
70
+
71
+ private
72
+
73
+ # A write from a thread or fiber a Preview's handler started: it is that Preview's write. While the
74
+ # Preview is open it blocks it (409); once it ended, it is refused for as long as the thread lives,
75
+ # since nothing could take it back.
76
+ def refuse_inherited(recorder, store, operation)
77
+ reason = Stores::Guard.write_reason(store)
78
+ if recorder.active?
79
+ recorder.block(store: store, operation: operation, detail: reason)
80
+ recorder.db(system: store, operation: operation, blocked: true)
81
+ raise PreviewWriteBlocked.new(store, operation, "#{reason}. It was sent from a thread or fiber the Preview's handler started.")
82
+ end
83
+
84
+ why = "A #{Stores::Guard.store_name(store)} #{operation} was sent from a thread or fiber a Preview's handler started, " \
85
+ "after that Preview ended, so Sendproof refused it. Mark background work with Sendproof.detached."
86
+ raise PreviewWriteBlocked.new(store, operation, "#{reason}. #{why}")
87
+ end
88
+
89
+ def mark(kind)
90
+ previous = Thread.current[KEY]
91
+ Thread.current[KEY] = kind
92
+ yield
93
+ ensure
94
+ Thread.current[KEY] = previous
95
+ end
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sendproof
4
+ # Holds the {Recorder} for the request running on the current thread (or fiber).
5
+ #
6
+ # Work started on other threads is not attributed to the request, with one exception: a Preview also
7
+ # marks the fiber storage of its handler, which every thread and fiber the handler starts inherits. Store
8
+ # hooks read that mark through {inherited_preview}, so a write such a thread sends, during the Preview or
9
+ # long after it ended, is refused (spec/data-stores.md, "Writes the binding can't attribute to a request").
10
+ module Capture
11
+ KEY = :sendproof_recorder
12
+ # Fiber storage, which Thread.new and Fiber.new copy into the thread or fiber they create.
13
+ INHERITED = :sendproof_preview
14
+
15
+ module_function
16
+
17
+ # @return [Recorder, nil]
18
+ def current
19
+ Thread.current[KEY]
20
+ end
21
+
22
+ # The preview this code runs inside, even after the preview's recorder finished. Store hooks use
23
+ # it so a write a handler sends late (after its response settled) is still refused, never sent
24
+ # unguarded.
25
+ #
26
+ # @return [Recorder, nil]
27
+ def preview
28
+ recorder = current
29
+ recorder if recorder&.rollback?
30
+ end
31
+
32
+ # The Preview whose handler started this thread or fiber (or an ancestor of it), even after that
33
+ # Preview ended. Only store hooks consult it, and only for a write with no request of its own.
34
+ #
35
+ # @return [Recorder, nil]
36
+ def inherited_preview = Fiber[INHERITED]
37
+
38
+ # Makes +recorder+ current for the block, restoring the previous one afterwards. A Preview's recorder
39
+ # is also left in the fiber storage that threads and fibers started inside the block inherit.
40
+ def with(recorder)
41
+ previous = Thread.current[KEY]
42
+ previous_inherited = Fiber[INHERITED]
43
+ PoolHooks.install if recorder&.rollback?
44
+ Thread.current[KEY] = recorder
45
+ Fiber[INHERITED] = recorder&.rollback? ? recorder : nil
46
+ yield
47
+ ensure
48
+ Thread.current[KEY] = previous
49
+ Fiber[INHERITED] = previous_inherited
50
+ end
51
+
52
+ # Runs the block with no inherited Preview: the start of a pool task, which belongs to whoever posted
53
+ # it, not to the Preview that was running when the pool thread happened to be created ({PoolHooks}).
54
+ def without_inherited
55
+ previous = Fiber[INHERITED]
56
+ return yield if previous.nil?
57
+
58
+ begin
59
+ Fiber[INHERITED] = nil
60
+ yield
61
+ ensure
62
+ Fiber[INHERITED] = previous
63
+ end
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sendproof
4
+ # Monotonic time helpers and the per-request phase clock behind Server-Timing.
5
+ module Clock
6
+ module_function
7
+
8
+ # @return [Float] monotonic seconds
9
+ def now
10
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
11
+ end
12
+
13
+ # @return [Float] milliseconds since +started+
14
+ def elapsed_ms(started, finished = now)
15
+ (finished - started) * 1000.0
16
+ end
17
+
18
+ # Records when a request began and when its handler ran, to report the auth, handler and serialize phases.
19
+ class Request
20
+ attr_reader :started
21
+
22
+ def initialize(started = Clock.now)
23
+ @started = started
24
+ @handler_start = nil
25
+ @handler_end = nil
26
+ end
27
+
28
+ def start_handler
29
+ @handler_start ||= Clock.now
30
+ end
31
+
32
+ def end_handler
33
+ @handler_end ||= Clock.now
34
+ end
35
+
36
+ # @return [Hash] auth, handler, db, queryCount and serialize
37
+ def read(db_ms, queries, serialize_ms, extra_serialize_ms = 0.0)
38
+ handler_start = @handler_start || @started
39
+ handler_end = @handler_end || Clock.now
40
+ {
41
+ auth: Clock.elapsed_ms(@started, handler_start),
42
+ handler: [0.0, Clock.elapsed_ms(handler_start, handler_end) - db_ms - serialize_ms].max,
43
+ db: db_ms, queryCount: queries, serialize: serialize_ms + extra_serialize_ms
44
+ }
45
+ end
46
+ end
47
+
48
+ # @return [String] the Server-Timing header value for a timing hash
49
+ def server_timing(timing)
50
+ format('auth;dur=%<auth>.3f, handler;dur=%<handler>.3f, db;dur=%<db>.3f;desc="%<queryCount>d queries", ' \
51
+ "serialize;dur=%<serialize>.3f", timing)
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,241 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "set"
4
+
5
+ module Sendproof
6
+ # Host configuration for the workbench. Everything is opt-in: with no environments listed,
7
+ # the middleware passes every request through untouched.
8
+ class Configuration
9
+ # @return [String, nil] display name; defaults to "API"
10
+ attr_writer :api_name
11
+ # @return [String] the environment label, such as "development"
12
+ attr_writer :environment
13
+ # @return [String, nil] same-origin path of the primary OpenAPI document (required when enabled)
14
+ attr_accessor :open_api_url
15
+ # @return [Numeric] trace retention in seconds (default 300)
16
+ attr_accessor :trace_ttl
17
+ # @return [#call] monotonic clock in seconds, injectable for tests
18
+ attr_accessor :trace_clock
19
+ # @return [Boolean, nil] whether SQL parameter values are captured; nil means "only in development"
20
+ attr_accessor :include_sql_parameter_values
21
+ # @return [#call, nil] +request -> identity+ ({Identity.from} input); nil means anonymous
22
+ attr_accessor :identity
23
+ # @return [#call, nil] +request -> truthy+ gate for workbench routes and previews
24
+ attr_accessor :authorize
25
+ # @return [#call, nil] +method, path, env -> :eligible, :ineligible or nil+ (nil: no such endpoint)
26
+ attr_accessor :target_resolver
27
+ # @return [#call, nil] +error -> Integer, nil+ mapping an exception to a handled client-error status
28
+ attr_accessor :exception_status
29
+ # @return [String, nil] directory with the packed UI bundle; defaults to the one embedded in the gem
30
+ attr_accessor :ui_directory
31
+ # @return [#warn, #error, nil] where adapter problems are logged
32
+ attr_accessor :logger
33
+ # @return [String] the web framework named in capabilities +binding+, so the workbench shows the
34
+ # +preview: false+ snippet in the host's own language ("Rack" unless an adapter says otherwise)
35
+ attr_writer :framework
36
+ attr_reader :environments, :documents, :field_modules, :auth_providers, :providers, :data_stores
37
+
38
+ def initialize(**options)
39
+ @environments = Set.new
40
+ @documents = []
41
+ @field_modules = []
42
+ @auth_providers = []
43
+ @providers = []
44
+ @data_stores = []
45
+ @preview_operations = []
46
+ @preview_unavailable = []
47
+ @trace_ttl = 300
48
+ @trace_clock = Clock.method(:now)
49
+ @environment = "development"
50
+ options.each { |name, value| public_send(:"#{name}=", value) }
51
+ end
52
+
53
+ def api_name = @api_name || "API"
54
+ def environment = @environment.to_s
55
+ def framework = @framework || "Rack"
56
+
57
+ # Replaces the environments in which the workbench and preview are served. Production is never implied.
58
+ def environments=(list)
59
+ @environments = Set.new(Array(list).map { |name| name.to_s.downcase })
60
+ end
61
+
62
+ # @return [Boolean]
63
+ def enabled?
64
+ environments.include?(environment.downcase)
65
+ end
66
+
67
+ # Adds a named same-origin OpenAPI document to the document selector.
68
+ def open_api_document(name, url)
69
+ @documents.reject! { |document| document[:name].casecmp?(name) }
70
+ @documents << { name: name, url: local_url!(url) }
71
+ end
72
+
73
+ # Loads a host-served ES module with custom field renderers.
74
+ def field_module(url)
75
+ url = local_url!(url)
76
+ @field_modules << url unless @field_modules.include?(url)
77
+ end
78
+
79
+ # Advertises a host-managed sign-in integration. +url+ may be nil for non-interactive handlers.
80
+ # Use kind +cookie+ for a password JSON endpoint and +personas+ for a development persona list.
81
+ def auth_provider(label, kind, url)
82
+ @auth_providers << { label: label, kind: kind, url: url.nil? ? nil : local_url!(url) }
83
+ end
84
+
85
+ # Replaces the registered providers.
86
+ def providers=(list)
87
+ @providers = Array(list)
88
+ end
89
+
90
+ # Registers a persistence provider. Exactly one available provider must own a request.
91
+ def use(provider)
92
+ @providers << provider
93
+ provider
94
+ end
95
+
96
+ # Registers a data store hook (+Sendproof::Redis::Store+, +Sendproof::DynamoDB::Store+,
97
+ # +Sendproof::Mongoid::Store+ ...): any object with the {DataStore} methods. A Preview then also
98
+ # guards that store, and capabilities list it under +dataStores+.
99
+ def data_store(store)
100
+ unless store.respond_to?(:describe) && store.respond_to?(:system)
101
+ raise ConfigurationError, "A data store needs +system+ and +describe+; use Sendproof::Redis::Store, " \
102
+ "Sendproof::DynamoDB::Store or Sendproof::Mongoid::Store."
103
+ end
104
+
105
+ @data_stores << store
106
+ store
107
+ end
108
+
109
+ # Replaces the registered data stores.
110
+ def data_stores=(list)
111
+ @data_stores = []
112
+ Array(list).each { |store| data_store(store) }
113
+ end
114
+
115
+ # Operations marked +preview: false+, or a callable returning them. Each is a hash with +:method+,
116
+ # +:path+, +:reason+ and optionally +:stores+. Rails adapters read them from the controllers.
117
+ def preview_unavailable=(operations)
118
+ @preview_unavailable = operations
119
+ end
120
+
121
+ # @return [Array<Hash>] unique, sorted +{method:, path:, reason:, stores:}+ entries advertised in
122
+ # capabilities +previewUnavailable+
123
+ def unavailable_operations
124
+ source = unavailable_source
125
+ source = source.call if source.respond_to?(:call)
126
+ Array(source).map do |entry|
127
+ operation = { method: entry[:method].to_s.upcase, path: entry[:path], reason: entry[:reason].to_s }
128
+ operation[:stores] = Array(entry[:stores]).map(&:to_s) if entry[:stores] && !Array(entry[:stores]).empty?
129
+ operation
130
+ end.uniq.sort_by { |operation| [operation[:path], operation[:method]] }
131
+ end
132
+
133
+ # The provider that owns a preview: the one available SQL provider, or, when the host registered
134
+ # data stores but no SQL provider, a provider with no database so the stores alone carry the preview.
135
+ # @return [#begin_preview, nil]
136
+ def preview_provider
137
+ provider || (data_stores.empty? || !providers.empty? ? nil : Provider::None.new)
138
+ end
139
+
140
+ # Static operations, or a callable returning them. Each is +[verb, path_template]+.
141
+ def preview_operations=(operations)
142
+ @preview_operations = operations
143
+ end
144
+
145
+ # @return [Array<Hash>] unique, sorted +{method:, path:}+ entries advertised in discovery
146
+ def operations
147
+ operations_source.map { |verb, path| { method: verb.to_s.upcase, path: path } }
148
+ .uniq.sort_by { |operation| [operation[:path], operation[:method]] }
149
+ end
150
+
151
+ # Finds out whether +method path+ is a preview-enabled endpoint.
152
+ # @return [Symbol, nil] +:eligible+, +:ineligible+ or nil when nothing matches
153
+ def resolve_target(method, path, env)
154
+ return target_resolver.call(method, path, env) if target_resolver
155
+
156
+ @matcher ||= {}
157
+ key = operations.map { |operation| operation.values_at(:method, :path) }
158
+ matcher = (@matcher[key] ||= OperationMatcher.new(key))
159
+ matcher.resolve(method, path) ? :eligible : nil
160
+ end
161
+
162
+ # @return [Boolean] whether SQL parameter values may be shown
163
+ def sql_parameter_values?
164
+ include_sql_parameter_values.nil? ? environment.casecmp?("development") : include_sql_parameter_values
165
+ end
166
+
167
+ # @return [#begin_preview, nil] the single available provider, or nil
168
+ def provider
169
+ return nil unless providers.length == 1
170
+
171
+ providers.first.available? ? providers.first : nil
172
+ end
173
+
174
+ # @return [Identity, nil]
175
+ def identity_for(request)
176
+ Identity.from(identity&.call(request))
177
+ end
178
+
179
+ # @return [Boolean] whether the request may use the workbench
180
+ def authorized?(request)
181
+ authorize.nil? || authorize.call(request) ? true : false
182
+ end
183
+
184
+ # @return [TraceStore]
185
+ def trace_store
186
+ @trace_store ||= TraceStore.new(ttl: trace_ttl, clock: trace_clock)
187
+ end
188
+
189
+ # Maps an exception to a handled client-error status, or nil when it is a server failure.
190
+ def status_for_error(error)
191
+ status = exception_status&.call(error)
192
+ status if status.is_a?(Integer) && status >= 400 && status < 500
193
+ end
194
+
195
+ # @return [Assets]
196
+ def assets
197
+ @assets ||= Assets.new(ui_directory)
198
+ end
199
+
200
+ # Raises {ConfigurationError} when an enabled workbench lacks what discovery requires.
201
+ def validate!
202
+ return unless enabled?
203
+ raise ConfigurationError, "Sendproof open_api_url must be set to a same-origin path." if open_api_url.nil?
204
+
205
+ local_url!(open_api_url)
206
+ end
207
+
208
+ private
209
+
210
+ # Raw +[verb, path]+ pairs; adapters override this to discover operations.
211
+ def operations_source
212
+ @preview_operations.respond_to?(:call) ? @preview_operations.call : @preview_operations
213
+ end
214
+
215
+ # The marked operations; adapters override this to discover them from their routes.
216
+ def unavailable_source
217
+ @preview_unavailable
218
+ end
219
+
220
+ # Accepts only application-relative paths. Discovery hands these URLs to the browser, which
221
+ # loads field modules as scripts and follows sign-in links, so anything a browser could resolve
222
+ # off-origin (+//host+, a backslash, a tab or newline it strips, a fragment) or that climbs out
223
+ # of the mount with dot segments is refused.
224
+ def local_url!(url)
225
+ url = url.to_s
226
+ return url if local_url?(url)
227
+
228
+ raise ConfigurationError, "Use an application-relative, same-origin path (got #{url.inspect})."
229
+ end
230
+
231
+ def local_url?(url)
232
+ raw = url.b
233
+ path = raw.split("?", 2).first.to_s
234
+ decoded = path.gsub(/%\h\h/n) { |escape| escape[1..].hex.chr }
235
+ segments = decoded.split("/")
236
+ path.start_with?("/") && !decoded.start_with?("//") && !raw.include?("#") && !raw.include?("\\") &&
237
+ !decoded.include?("\\") && !raw.match?(/[\x00-\x20\x7f]/n) && !decoded.match?(/[\x00-\x1f\x7f]/n) &&
238
+ !segments.include?(".") && !segments.include?("..")
239
+ end
240
+ end
241
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Sendproof
4
+ # Base class and contract for a data-store hook (spec/data-stores.md). Register one with
5
+ # {Configuration#data_store}. Subclassing is optional; any object with these methods works.
6
+ #
7
+ # A store runs in one of two modes. +:preview+ stores join the Preview: their writes run in a
8
+ # transaction the hook aborts after the handler. +:guard+ stores can't roll back: reads run and
9
+ # the first write blocks the Preview before any byte of it reaches the store.
10
+ class DataStore
11
+ # @return [String] the store id: +"mongodb"+, +"redis"+ or +"dynamodb"+
12
+ def system
13
+ raise NotImplementedError, "#{self.class} must implement system"
14
+ end
15
+
16
+ # What capabilities +dataStores+ lists for this store.
17
+ # @return [Hash] +:system+, +:mode+ (+:preview+ or +:guard+), optionally +:name+ and +:reason+
18
+ def describe
19
+ raise NotImplementedError, "#{self.class} must implement describe"
20
+ end
21
+
22
+ # Prepares a Preview before the handler runs: a +preview+-mode store starts its session and
23
+ # transaction here. Runs with the preview's recorder current.
24
+ # @param context [ProviderContext]
25
+ # @param recorder [Recorder]
26
+ def begin_preview(_context, _recorder); end
27
+
28
+ # Finishes a Preview after the handler and before SQL rolls back: captures changes, then aborts
29
+ # the store's transaction. Raise when it can't be proven aborted; the Preview then answers 500.
30
+ # Must be safe to call when {#begin_preview} failed or never ran.
31
+ # @param recorder [Recorder]
32
+ def finish_preview(_recorder); end
33
+ end
34
+ end