kiosk-server 0.6.1 → 0.6.28

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 (99) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +138 -0
  3. data/README.md +134 -102
  4. data/app/channels/kiosk_events.rb +30 -17
  5. data/app/controllers/kiosk/server/application_controller.rb +0 -1
  6. data/app/controllers/kiosk/server/assistants_controller.rb +13 -14
  7. data/app/controllers/kiosk/server/auth_controller.rb +3 -3
  8. data/app/controllers/kiosk/server/device_verify_controller.rb +0 -5
  9. data/app/controllers/kiosk/server/discovery_controller.rb +2 -7
  10. data/app/controllers/kiosk/server/kyc_callback_controller.rb +3 -1
  11. data/app/controllers/kiosk/server/oauth_device_authorization_controller.rb +8 -7
  12. data/app/controllers/kiosk/server/oauth_token_controller.rb +4 -1
  13. data/app/controllers/kiosk/server/payment_setup_controller.rb +3 -4
  14. data/app/controllers/kiosk/server/wire_controller.rb +2 -2
  15. data/app/models/kiosk/checkout_mandate.rb +0 -2
  16. data/app/models/kiosk/settlement.rb +0 -2
  17. data/app/models/kiosk/visit.rb +0 -2
  18. data/app/views/kiosk/server/assistants/show.html.erb +20 -24
  19. data/app/views/kiosk/server/device_verify/decided.html.erb +1 -0
  20. data/app/views/kiosk/server/device_verify/show.html.erb +1 -0
  21. data/app/views/layouts/kiosk/server/application.html.erb +14 -0
  22. data/lib/generators/kiosk/install/install_generator.rb +25 -64
  23. data/lib/generators/kiosk/install/templates/create_kiosk_device_authorizations.rb.tt +21 -12
  24. data/lib/generators/kiosk/install/templates/create_kiosk_events.rb.tt +15 -17
  25. data/lib/generators/kiosk/install/templates/create_kiosk_identity_tables.rb.tt +39 -10
  26. data/lib/generators/kiosk/install/templates/create_kiosk_kyc_attributes.rb.tt +16 -14
  27. data/lib/generators/kiosk/install/templates/create_kiosk_mandates.rb.tt +50 -14
  28. data/lib/generators/kiosk/install/templates/create_kiosk_pow_spent.rb.tt +7 -11
  29. data/lib/generators/kiosk/install/templates/create_kiosk_refunds.rb.tt +11 -11
  30. data/lib/generators/kiosk/install/templates/create_kiosk_revocations.rb.tt +7 -11
  31. data/lib/generators/kiosk/install/templates/create_kiosk_visits.rb.tt +10 -11
  32. data/lib/generators/kiosk/install/templates/initializer.rb.tt +13 -4
  33. data/lib/kiosk/payable.rb +1 -1
  34. data/lib/kiosk/server/account_binding.rb +14 -5
  35. data/lib/kiosk/server/account_holder_gate.rb +3 -1
  36. data/lib/kiosk/server/agent_identity_providers/default_agent_idp.rb +1 -1
  37. data/lib/kiosk/server/agent_rotation.rb +1 -1
  38. data/lib/kiosk/server/argument_decoder.rb +2 -2
  39. data/lib/kiosk/server/assistant_accounts.rb +38 -0
  40. data/lib/kiosk/server/auth_toll.rb +5 -5
  41. data/lib/kiosk/server/client.rb +1 -1
  42. data/lib/kiosk/server/client_assertion.rb +3 -2
  43. data/lib/kiosk/server/client_registration.rb +6 -2
  44. data/lib/kiosk/server/column_spending_cap.rb +1 -1
  45. data/lib/kiosk/server/configuration_extension.rb +15 -38
  46. data/lib/kiosk/server/current_request.rb +1 -1
  47. data/lib/kiosk/server/device_authorization.rb +1 -1
  48. data/lib/kiosk/server/device_authorization_stores.rb +1 -1
  49. data/lib/kiosk/server/device_code_grant.rb +2 -2
  50. data/lib/kiosk/server/dpop.rb +6 -1
  51. data/lib/kiosk/server/engine.rb +2 -2
  52. data/lib/kiosk/server/errors.rb +21 -7
  53. data/lib/kiosk/server/event_stores.rb +2 -2
  54. data/lib/kiosk/server/events.rb +4 -3
  55. data/lib/kiosk/server/events_connection.rb +23 -5
  56. data/lib/kiosk/server/events_replay.rb +79 -0
  57. data/lib/kiosk/server/executor/repeat.rb +1 -1
  58. data/lib/kiosk/server/executor/spending_cap.rb +8 -66
  59. data/lib/kiosk/server/executor.rb +10 -10
  60. data/lib/kiosk/server/failure_log.rb +3 -3
  61. data/lib/kiosk/server/handler_mixin.rb +9 -9
  62. data/lib/kiosk/server/handler_registrations.rb +1 -1
  63. data/lib/kiosk/server/handler_serving.rb +11 -11
  64. data/lib/kiosk/server/headers.rb +3 -3
  65. data/lib/kiosk/server/identity_resolution.rb +1 -1
  66. data/lib/kiosk/server/kyc.rb +5 -7
  67. data/lib/kiosk/server/kyc_verifier.rb +26 -27
  68. data/lib/kiosk/server/linked_assistants.rb +21 -16
  69. data/lib/kiosk/server/money.rb +41 -0
  70. data/lib/kiosk/server/oauth_answers.rb +1 -0
  71. data/lib/kiosk/server/oauth_error.rb +3 -0
  72. data/lib/kiosk/server/open_api.rb +9 -9
  73. data/lib/kiosk/server/page.rb +1 -1
  74. data/lib/kiosk/server/payment_claim.rb +3 -3
  75. data/lib/kiosk/server/pow_gate.rb +12 -33
  76. data/lib/kiosk/server/pow_spent_stores.rb +1 -1
  77. data/lib/kiosk/server/receipts.rb +4 -3
  78. data/lib/kiosk/server/reputation_factors.rb +12 -5
  79. data/lib/kiosk/server/request_validation.rb +2 -1
  80. data/lib/kiosk/server/result.rb +1 -1
  81. data/lib/kiosk/server/revocation_stores.rb +1 -1
  82. data/lib/kiosk/server/routing.rb +1 -1
  83. data/lib/kiosk/server/schemas/auth.schema.json +2 -2
  84. data/lib/kiosk/server/schemas/binding.schema.json +3 -3
  85. data/lib/kiosk/server/schemas/kyc.schema.json +22 -3
  86. data/lib/kiosk/server/schemas/mandates.schema.json +5 -5
  87. data/lib/kiosk/server/schemas/pow.schema.json +2 -2
  88. data/lib/kiosk/server/session_context.rb +2 -2
  89. data/lib/kiosk/server/tolled_calls.rb +46 -0
  90. data/lib/kiosk/server/verb_wire.rb +3 -3
  91. data/lib/kiosk/server/version.rb +1 -1
  92. data/lib/kiosk/server/well_known.rb +14 -11
  93. data/lib/kiosk/server/wire_rendering.rb +1 -1
  94. data/lib/kiosk/server.rb +6 -2
  95. metadata +9 -8
  96. data/lib/generators/kiosk/install/templates/create_kiosk_schema.rb.tt +0 -17
  97. data/lib/kiosk/server/schema_definitions.rb +0 -320
  98. data/lib/kiosk/server/settled_spend.rb +0 -21
  99. data/lib/kiosk/server/wrong_door.rb +0 -42
data/README.md CHANGED
@@ -8,28 +8,25 @@ The Kiosk Rails engine — host-side surface for [Kiosk](https://kiosk.tech).
8
8
  The full host-side surface is shipped and covered by the gem's own suite
9
9
  (`bundle exec rspec` in this directory runs it and prints how many examples that is):
10
10
 
11
- - **Wire-protocol controllers** — each verb route (`GET <mount>/<query-name>`, `POST <mount>/<action-name>`) reaches the operator's controller action that declares the verb, and `Kiosk::Handler` runs the wire's checks around it; `VerbController` refuses a verb route that no action answers; `WireController` serves the two reserved endpoints `GET <mount>/schema` and `POST <mount>/pay`; `VerbController` also serves `POST <mount>/payment_setup` against the payment provider port, and `PaymentSetupController` the page the provider returns the human to; `VerbController` serves `POST <mount>/request_kyc` against the KYC provider port, and `KycCallbackController` the provider's callback; `OpenApiController` serves a derived OpenAPI description of both at `GET <mount>/openapi.json`; `OauthRegistrationController` registers an assistant's public key (RFC 7591) and `OauthTokenController` gives a registered client an access token for a client assertion (RFC 7523) and a DPoP proof (the `client_credentials` grant); `AuthController` puts a new key on a client; every access token is bound to the client's registered key, and a call that carries one also carries a DPoP proof (RFC 9449) that `IdentityResolution` checks; JWKS backs stateless token verification.
12
- - **Account binding** — the claim/link ceremonies bind a registered client to an existing assistant-account holder's account: the RFC 8628 device authorization and token poll, each authenticated by a client assertion, a session-authenticated verify page and «Link an assistant» page (minimal overridable engine views), link-code mint/redeem, and unlink. The token endpoint gives the tokens; the durable `DeviceAuthorizationStores::ActiveRecord` store (migration 004) is the default.
11
+ - **Protocol controllers** — each operation's route (`GET <mount>/<query-name>`, `POST <mount>/<action-name>`) reaches the operator's controller action that declares the operation, and `Kiosk::Handler` runs the protocol's checks around it; `VerbController` refuses an operation's route that no action answers; `WireController` serves the two reserved paths `GET <mount>/schema` and `POST <mount>/pay`; `VerbController` also serves `POST <mount>/payment_setup` against the payment provider port, and `PaymentSetupController` the page the provider returns the human to; `VerbController` serves `POST <mount>/request_kyc` against the KYC provider port, and `KycCallbackController` the provider's callback; `OpenApiController` serves a derived OpenAPI description of both at `GET <mount>/openapi.json`; `OauthRegistrationController` registers an assistant's public key (RFC 7591) and `OauthTokenController` gives a registered client an access token for a client assertion (RFC 7523) and a DPoP proof (the `client_credentials` grant); `AuthController` puts a new key on a client; every access token is bound to the client's registered key, and a call that carries one also carries a DPoP proof (RFC 9449) that `IdentityResolution` checks; JWKS backs stateless token verification.
12
+ - **Account binding** — the claim/link ceremonies bind a registered client to an existing assistant-account holder's account: the RFC 8628 device authorization and token poll, each authenticated by a client assertion, a session-authenticated verify page and «Link an assistant» page (minimal overridable engine views with no inline script or style, so a Content-Security-Policy of `default-src 'self'` holds), link-code mint/redeem, and unlink. The token endpoint gives the tokens; the durable `DeviceAuthorizationStores::ActiveRecord` store (the `create_kiosk_device_authorizations` migration) is the default.
13
13
  - **`Kiosk::Server::Executor`** — dispatches resolved commands to the host's registered queries and Actions.
14
- - **`Kiosk::Handler`** — the mixin an operator includes into a controller of their own to declare verbs as ordinary Rails actions; each declaration's `kind` says whether it is a query or an action, so one controller may declare both. The engine registers the controllers in `app/controllers/kiosk/` at boot and after every reload (see [Declaring queries and actions](#declaring-queries-and-actions)).
14
+ - **`Kiosk::Handler`** — the mixin an operator includes into a controller of their own to declare operations as ordinary Rails actions; each declaration's `kind` says whether it is a query or an action, so one controller may declare both. The engine registers the controllers in `app/controllers/kiosk/` at boot and after every reload (see [Declaring queries and actions](#declaring-queries-and-actions)).
15
15
  - **`Kiosk::Server::PaymentClaim`** — the PSP decorator that keeps §11.6's operator half: one capture per payable row, and a paid state anchored to the capture (see [Payments](#payments)).
16
16
  - **Client registration and authentication** — `ClientRegistration`, `ClientAssertion`, `AssistantKey` (the one list of signing algorithms an assistant can use), `AuthToll`, and the pluggable agent-IdP resolve and mint per-agent identities.
17
- - **PoW gate** — `PowGate` enforces the reputation policy's N×PoW challenge-response (soft dependency on `kiosk-reputation`; zero overhead when no policy is set).
17
+ - **Proof-of-work toll** — `PowGate` asks the toll that the reputation policy sets, as N proof-of-work challenges (soft dependency on `kiosk-reputation`; zero overhead when no policy is set).
18
18
  - **`Kiosk::Server::WellKnown`** — pure-Ruby builder for `/.well-known/kiosk.json`.
19
19
  - **`Kiosk::Server::Headers`** + **`HeadersMiddleware`** — Rack middleware that injects `Kiosk-Server-Version`, `Kiosk-API-Version`, `Kiosk-Min-Client` on `/kiosk/*` responses.
20
20
  - **`IssuerMiddleware`** — answers `Kiosk.current_issuer` for each request: its origin when that is `c.issuer` or one of `c.additional_origins`, else `c.issuer`. Every origin served is its own operator.
21
- - **The audit sink** — `c.audit_sink` receives one `Kiosk::Server::ActionEvent` per action invocation, success and failure alike. The default is no sink, so no `ActionEvent` goes anywhere. The engine keeps its own state in the `kiosk` schema (agents, mandates, settlements, refunds, events, visits), but it writes no audit record there. See [The audit sink](#the-audit-sink).
22
- - **`Kiosk::Server::SchemaDefinitions`** — SQL generators for every table and helper that `bin/rails g kiosk:install` creates.
23
- - **`Kiosk::Server::Engine`** — the Rails engine: `kiosk` in `config/routes.rb` mounts it, drawing the full mount-prefixed PROTOCOL surface (the reserved wire, auth, JWKS, KYC, account binding), then one route per verb its block names — installs the root discovery routes when mounted, and auto-injects the headers and issuer middleware (see [Draw the routes](#draw-the-routes)).
24
- - **`Kiosk::Server::ConfigurationExtension`** — adds `mount_path`, `owner` (and the reputation/PoW slots) to `Kiosk::Configuration`.
21
+ - **The audit sink** — `c.audit_sink` receives one `Kiosk::Server::ActionEvent` per action invocation, success and failure alike. The default is no sink, so no `ActionEvent` goes anywhere. The engine keeps its own state in its `kiosk_*` tables (agents, mandates, settlements, refunds, events, visits), but it writes no audit record there. See [The audit sink](#the-audit-sink).
22
+ - **`Kiosk::Server::Engine`** — the Rails engine: `kiosk` in `config/routes.rb` mounts it, drawing the full mount-prefixed PROTOCOL surface (the reserved paths, auth, JWKS, KYC, account binding), then one route per operation its block names — installs the root discovery routes when mounted, and auto-injects the headers and issuer middleware (see [Draw the routes](#draw-the-routes)).
23
+ - **`Kiosk::Server::ConfigurationExtension`** — adds `mount_path`, `owner` (and the reputation and proof-of-work settings) to `Kiosk::Configuration`.
25
24
  - **`bin/rails g kiosk:install`** — the install generator lays down the initializer, the migrations and the `kiosk` block in `config/routes.rb` that mounts the engine.
26
25
 
27
- kiosk-server is a Rails gem: it depends on railties, actionpack, actioncable, activerecord and activesupport (`~> 8.1`), and `require "kiosk/server"` loads them. Pieces such as `WellKnown` and `SchemaDefinitions` still work without a BOOTED Rails app — they just need the framework on the load path.
26
+ kiosk-server is a Rails gem: it depends on railties, actionpack, actioncable, activerecord and activesupport (`~> 8.1`), and `require "kiosk/server"` loads them. `WellKnown` works without a BOOTED Rails app: it needs only the framework on the load path (see [The discovery document](#the-discovery-document-no-booted-rails-app-required)).
28
27
 
29
28
  ## Install
30
29
 
31
- > **Not on RubyGems yet** — so every `gem` line below carries `github: "kiosk-hq/kiosk"`, which is what makes it copy-pasteable today. Publication status and the canonical install are stated once, in the monorepo README's [Install](https://github.com/kiosk-hq/kiosk#install) section.
32
-
33
30
  ### Preconditions
34
31
 
35
32
  **Rails `~> 8.1`.** This gemspec pins `railties`, `actionpack`, `actioncable`,
@@ -38,23 +35,23 @@ that names a Rails gem is `kiosk-pay-stripe`, which pins `activerecord` at
38
35
  `~> 8.1`. **Rails 7.x and 8.0.x are excluded** — bundler refuses to resolve
39
36
  against an app on either, so for most "add Kiosk to an existing Rails app" this
40
37
  is the first thing to check, not a footnote. Older Rails lines are untested
41
- here, so they are not claimed; widening the floor means adding a CI leg first.
38
+ here, so they are not claimed; widening the floor means adding a CI job first.
42
39
 
43
40
  **Ruby `>= 4.0`**, which every Kiosk gemspec declares and CI runs.
44
41
 
45
- **PostgreSQL.** The kiosk schema, the identity tables and the optional RLS
46
- backstop are Postgres; no other database is supported.
42
+ **PostgreSQL.** Kiosk's `kiosk_*` tables and the optional RLS backstop are
43
+ Postgres; no other database is supported.
47
44
 
48
45
  ### The line
49
46
 
50
47
  ```ruby
51
- gem "kiosk-server", github: "kiosk-hq/kiosk"
48
+ gem "kiosk-server"
52
49
  ```
53
50
 
54
51
  Or, via the meta-gem:
55
52
 
56
53
  ```ruby
57
- gem "kiosk-all", github: "kiosk-hq/kiosk"
54
+ gem "kiosk-all"
58
55
  ```
59
56
 
60
57
  ## Configure
@@ -77,6 +74,10 @@ Kiosk.configure do |c|
77
74
  # nobody sets neither line, and then no token carries a `role` claim.
78
75
  c.registration_role = :customer
79
76
  c.owner = { name: "Acme Inc.", support: "support@acme.example" }
77
+ # The SHA-256 of the skill file that kiosk-server gives (Kiosk.configuration.skill_url):
78
+ # curl -fsS "$(bin/rails runner 'puts Kiosk.configuration.skill_url')" | shasum -a 256
79
+ # Without it, discovery advertises no skill pin. See "The skill pin" below.
80
+ c.skill_sha256 = "<the 64 hexadecimal characters that the command prints>"
80
81
  # The Ed25519 key that signs access tokens, checkouts and receipts (EdDSA):
81
82
  # openssl genpkey -algorithm ed25519 | base64
82
83
  c.signing_key = Base64.decode64(ENV.fetch("KIOSK_SIGNING_KEY_B64"))
@@ -95,19 +96,23 @@ Set a KYC provider adapter (a `kiosk-kyc-*` gem) and the engine serves
95
96
  `kyc_verification` topic, and records the verified attributes against the
96
97
  person. Declare the attributes your gated actions need; gate with
97
98
  `Kiosk::Server::Kyc.require!`, which refuses `403 kyc_required` until the
98
- calling principal holds them. An action that needs only some of them passes
99
+ calling customer holds them. An action that needs only some of them passes
99
100
  their names, `require!(%w[age_over_18])`, and may pass its own `detail:`.
100
101
 
101
102
  ```ruby
102
103
  Kiosk.configure do |c|
103
- c.kyc_provider = Kiosk::KycProviders::Prove.new(operator_id: "acme", intake_secret: ENV["PROVE_SECRET"])
104
- c.kyc_claims = %w[age_over_18]
105
- c.kyc_issuer = "https://kyc.example" # the `iss` the provider signs
106
- c.kyc_public_key = ENV["KYC_PUBLIC_KEY_PEM"]
107
- c.kyc_audience = "acme" # the `aud` it mints for you
104
+ c.kyc_claims = %w[age_over_18]
105
+ c.kyc_provider = Kiosk::KycProviders::Proveli.new(operator_id: "acme",
106
+ intake_secret: ENV.fetch("KIOSK_PROVELI_INTAKE_SECRET"),
107
+ public_key: ENV.fetch("KIOSK_PROVELI_PUBLIC_KEY_PEM"))
108
108
  end
109
109
  ```
110
110
 
111
+ The provider names the `iss` it signs, its Ed25519 public key and the `aud` it
112
+ mints for you, and the engine checks every attestation against them. To accept
113
+ attestations at `POST <mount>/agents/kyc` only, with no `request_kyc`, set
114
+ `c.kyc_provider = Kiosk::KycProviders::Base.new(issuer:, public_key:, audience:)`.
115
+
111
116
  ### Payments
112
117
 
113
118
  Set a PSP adapter (a `kiosk-pay-*` gem) and the engine serves `pay`. Wrap it in
@@ -141,7 +146,7 @@ whose unpaid value is `unpaid`.
141
146
  The model also includes `Kiosk::Payable`, which gives each row:
142
147
 
143
148
  - `payment_state`: `unpaid`, `pending` while a capture is in flight, `paid`, or
144
- `refunded`. Your per-user query publishes it, so a capture in flight never
149
+ `refunded`. Your query of the customer's own rows publishes it, so a capture in flight never
145
150
  reads as *not paid*. `Order.own.with_settlement(Kiosk::Settlement.own)` reads
146
151
  it for many rows in one query.
147
152
  - `checkout(lines)`: the `checkout_jwt` your action returns, which the
@@ -155,41 +160,55 @@ When the capture returns, the engine pushes `{"order_id": "…", "payment_state"
155
160
  "paid"}` to the row's owner on the `payment` topic. Refund through the claim,
156
161
  `refund(psp_reference:, amount_cents:, key:)`: `key` names this refund among
157
162
  the refunds of the charge, so a retry with the same key refunds once. It
158
- records the refund in `kiosk.refunds`, and recent spend leaves the refunded
159
- cents out. The spending cap gets the refunded amount back. When the refund
160
- returns the whole charge, set the row's status column to `refunded`, which is
161
- where `payment_state` reads it. Then call `announce(id, "refunded")` on the
163
+ records the refund in `kiosk_refunds`, and recent spend leaves the refunded
164
+ cents out. When the refund returns the whole charge, set the row's status
165
+ column to `refunded`, which is where `payment_state` reads it. Then call `announce(id, "refunded")` on the
162
166
  claim to push the same topic.
163
167
 
164
168
  A repeat of mandates whose capture did not complete runs the capture again
165
169
  under the same key, the checkout mandate's `reference`, so your PSP adapter must
166
170
  key its charge by it (`kiosk-pay-stripe` does). One checkout holds one live
167
171
  checkout mandate: a second pair for it answers `409 conflict`. A charge refused
168
- with no money moved marks the checkout mandate declined: it stops counting
169
- against `spending_cap` at once, a repeat of that pair answers `409 conflict`,
170
- and a new pair for the same checkout is accepted.
172
+ with no money moved marks the checkout mandate declined: a repeat of that pair
173
+ answers `409 conflict`, and a new pair for the same checkout is accepted.
171
174
 
172
175
  A settled `pay` answers the settlement and the two AP2 receipts,
173
176
  `checkout_receipt` and `payment_receipt`, which your origin signs EdDSA with
174
177
  `c.signing_key`. The payment receipt carries the card network's id of the charge
175
- when your PSP adapter's `capture` answers `network_confirmation_id`.
178
+ that your PSP adapter's `capture` answers as `network_confirmation_id`. When the
179
+ adapter answers none, the receipt carries `not reported by the payment provider`.
176
180
 
177
- Set `c.spending_cap = Kiosk::Server::ColumnSpendingCap.new` to cap what each
178
- assistant spends. The human sets the cap on `/kiosk/auth/assistants`: an amount
179
- in cents and a currency. The engine refuses a `pay` that passes the cap, or a
180
- `pay` in another currency, with `403 spending_cap_exceeded` before the capture.
181
+ Set `c.spending_cap = Kiosk::Server::ColumnSpendingCap.new` to cap what one
182
+ payment of each assistant may charge. The human sets the cap on
183
+ `/kiosk/auth/assistants`: an amount and a currency. The engine refuses a `pay`
184
+ whose checkout total is above the cap, or whose checkout is in another
185
+ currency, with `403 spending_cap_exceeded` before the capture. A cap of 0
186
+ stops the payments of that assistant.
181
187
 
182
188
  ### Proof of work
183
189
 
184
- Set a policy and the engine tolls the first call of each access token; the
185
- token then calls freely until it expires (`access_token_ttl`, 3600 seconds by
186
- default). With the ready-made policy, the more the customer spent here, the
187
- smaller the chance that a session pays the toll:
190
+ The toll needs two gems beside kiosk-server: `kiosk-reputation`, which holds
191
+ the policies and the challenges, and `kiosk-pow-equihash`, the proof-of-work
192
+ backend. Add both to your Gemfile and `require` them. Both tolls sign their
193
+ challenges with `c.pow_secret`.
194
+
195
+ **The call toll.** Set a policy and the engine asks it on each query, action
196
+ and `pay`. The engine counts each account's tolled calls since its last proof.
197
+ The assistants bound to one account share that count, and a new access token or
198
+ a key rotation keeps it. A binding adds the count of the assistant's previous
199
+ account to the count of its new account. With the ready-made policy, an account
200
+ solves a proof on every 10th call, and the more its customer spent here, the
201
+ more calls pass between two proofs.
202
+
203
+ **The registration toll.** `c.registration_pow_count` is the number of proofs
204
+ that a client registration, a link-code claim and the first token poll of each
205
+ device code cost. The default is 0, which asks for none.
188
206
 
189
207
  ```ruby
190
208
  Kiosk.configure do |c|
191
- c.pow_secret = ENV.fetch("KIOSK_POW_SECRET")
192
- c.reputation_policy = Kiosk::Reputation::Policies::RecentSpend.new(within: 1.week, cap: 100)
209
+ c.pow_secret = ENV.fetch("KIOSK_POW_SECRET")
210
+ c.reputation_policy = Kiosk::Reputation::Policies::RecentSpend.new(within: 1.week, cap: 100)
211
+ c.registration_pow_count = 1
193
212
  end
194
213
  ```
195
214
 
@@ -217,20 +236,23 @@ c.previous_signing_key = Base64.decode64(ENV.fetch("KIOSK_PREVIOUS_SIGNING_KEY_B
217
236
 
218
237
  ## Upgrading
219
238
 
220
- ### The schema
239
+ ### The tables
221
240
 
222
241
  `rails generate kiosk:install` emits the **genesis** — the whole current shape,
223
- as migrations. That is the fresh-install path. Migrations already in
242
+ as migrations. That is the fresh-install path. The migrations create Kiosk's
243
+ tables as `kiosk_*` tables in the schema `--schema` names, `public` by default;
244
+ `c.schema` names the same schema at run time. From 1.0, migrations already in
224
245
  `db/migrate/` are never re-emitted and never edited: a change to the Kiosk
225
- schema arrives as a new file you copy in and migrate, so `db:migrate` on your
226
- existing database transfers only what it has not run.
246
+ tables arrives as a new file you copy in and migrate, so `db:migrate` on your
247
+ existing database transfers only what it has not run. Before 1.0 a release may
248
+ replace the genesis; its changelog entry says so.
227
249
 
228
250
  Each MAJOR publishes its own genesis and drops the previous major's chain, so
229
251
  **an upgrade crossing a major stops at it.** Install that major, `bin/rails
230
252
  db:migrate`, then move on — one major at a time. A fresh install at any major
231
253
  gets that major's genesis and replays no history at all.
232
254
 
233
- MINOR and PATCH releases only ever add files to the chain.
255
+ From 1.0, MINOR and PATCH releases only ever add files to the chain.
234
256
 
235
257
  ### The configuration
236
258
 
@@ -253,11 +275,20 @@ The principle behind all three: generate as little as possible, derive at boot
253
275
  whatever can be derived, default whatever can be defaulted, and fail closed on
254
276
  what can be neither.
255
277
 
278
+ ### The skill pin
279
+
280
+ Each kiosk-server release gives the skill of its own version as
281
+ `skill_url`. Do not set `skill_url`. After an upgrade to a release with a
282
+ different skill, your `skill_sha256` is the digest of the old file, and an AI
283
+ assistant that checks the digest refuses the skill. The skill pin test of
284
+ `kiosk-test-support` (`Kiosk::TestHelpers::SkillPin`) fails in this case, and
285
+ its message tells you how to make the new digest.
286
+
256
287
 
257
288
  ## Multi-process deployments
258
289
 
259
- The PoW gate keeps spent challenge ids in `c.pow_spent_store`, by default
260
- `Kiosk::Server::PowSpentStores::ActiveRecord`: the `kiosk.pow_spent` table that
290
+ The toll keeps spent challenge ids in `c.pow_spent_store`, by default
291
+ `Kiosk::Server::PowSpentStores::ActiveRecord`: the `kiosk_pow_spent` table that
261
292
  `bin/rails g kiosk:install` lays down. Every process and every deploy shares it,
262
293
  so a proof is accepted once (kiosk.tech `protocol.md` §15.2). The token
263
294
  endpoint keeps the `jti` of each client assertion in the same store, so an
@@ -269,7 +300,7 @@ atomic operation (Redis `SET … NX EX`, or SQL `INSERT … ON CONFLICT`). A
269
300
  read-then-write reintroduces exactly the replay race the gate closes.
270
301
 
271
302
  Token revocation lives in `c.revocation_store`, by default
272
- `Kiosk::Server::RevocationStores::ActiveRecord`: the `kiosk.revocations` table,
303
+ `Kiosk::Server::RevocationStores::ActiveRecord`: the `kiosk_revocations` table,
273
304
  which `bin/rails g kiosk:install` lays down too. A key rotation, a rebind or an unlink
274
305
  stops the agent's older tokens in every process and after a restart, and a
275
306
  token of an unlinked agent stops at once. The contract is
@@ -277,7 +308,7 @@ token of an unlinked agent stops at once. The contract is
277
308
  `revoked?(agent_id:, iat:)`.
278
309
 
279
310
  Events live in `c.event_store`, by default `Kiosk::Server::EventStores::ActiveRecord`:
280
- the `kiosk.events` table from `bin/rails g kiosk:install`. The event stream runs
311
+ the `kiosk_events` table from `bin/rails g kiosk:install`. The event stream runs
281
312
  on the Action Cable adapter that `config/cable.yml` names for the environment. In
282
313
  production that adapter must be one every process shares, such as `solid_cable`
283
314
  in the host's Gemfile;
@@ -306,9 +337,9 @@ framework decided for your customers' data.
306
337
 
307
338
  | field | |
308
339
  |---|---|
309
- | `action` | the action's wire name |
310
- | `user_id` / `agent_id` | the principal, and the assistant credential that acted (nil when the caller is not an agent) |
311
- | `role` / `actor` | the active role (may be nil), and `"agent"` \| `"human"` \| `"service"` |
340
+ | `action` | the action's published name |
341
+ | `user_id` / `agent_id` | the customer, and the assistant credential that acted (nil when the caller is not an assistant) |
342
+ | `role` / `actor` | the active role (may be nil), and `"agent"` \| `"human"` |
312
343
  | `args` | **the arguments exactly as the handler received them** |
313
344
  | `status` | `"ok"` or `"error"` |
314
345
  | `error_class` / `error_message` | the raised error, untruncated, on the `"error"` branch |
@@ -318,10 +349,10 @@ framework decided for your customers' data.
318
349
  ### The arguments arrive unredacted, and the PII is yours
319
350
 
320
351
  `event.args` is verbatim: the delivery address, the passenger name, the cart,
321
- the booking reference — whatever your verb takes. **Kiosk does not redact them
352
+ the booking reference — whatever your action takes. **Kiosk does not redact them
322
353
  for you, and the moment you write them somewhere you are the data controller
323
354
  for whatever they contain** — retention, encryption at rest, access control and
324
- deletion requests are all yours. That is the deliberate shape of this seam:
355
+ deletion requests are all yours. That is deliberate:
325
356
  Kiosk gives you the capability and does not pretend to have made your privacy
326
357
  decisions for you.
327
358
 
@@ -368,21 +399,21 @@ a boot failure rather than an audit trail that silently was never there.
368
399
 
369
400
  Bundling the gem draws no route at all, and an origin with no mount answers
370
401
  nothing. `bin/rails g kiosk:install` writes the `kiosk` block into
371
- `config/routes.rb`; you name your verbs in it:
402
+ `config/routes.rb`; you name your operations in it:
372
403
 
373
404
  ```ruby
374
405
  # config/routes.rb
375
406
  Rails.application.routes.draw do
376
407
  kiosk do
377
408
  queries :catalog
378
- actions :place_order
409
+ actions :create_order
379
410
  end
380
411
  end
381
412
  ```
382
413
 
383
414
  `kiosk` mounts the engine at `Kiosk.configuration.mount_path`, then draws
384
415
  `GET <mount_path>/<name>` for each query and `POST <mount_path>/<name>` for each
385
- action. Each route reaches the controller action that declares the verb, and
416
+ action. Each route reaches the controller action that declares the operation, and
386
417
  `bin/rails routes` prints that action. A block-less `kiosk` only mounts.
387
418
 
388
419
  **The mount draws the PROTOCOL PLANE** — the paths whose shape is the spec's and
@@ -392,45 +423,45 @@ human back to (both answer `501 module_not_served` without a `payment_provider`)
392
423
  OAuth registration and token endpoints (`oauth/register`, `oauth/token`), the key
393
424
  rotation (`auth/rotate`), JWKS (`.well-known/jwks.json`), KYC (`agents/kyc`, and
394
425
  `request_kyc` and `kyc/callback`, which answer `501 module_not_served` without a
395
- `kyc_provider`) and the whole account-binding ceremony (the RFC 8628 claim wire,
426
+ `kyc_provider`) and the whole account-binding ceremony (the RFC 8628 claim paths,
396
427
  `auth/link`/`claim`/`unlink`, the verify and «Link an assistant» pages). The
397
428
  engine also installs the ROOT-relative discovery documents — `/agents.txt`,
398
429
  `/agents.json`, `/auth.md`,
399
- `/.well-known/{kiosk.json,api-catalog,oauth-authorization-server,ard.json}` and
430
+ `/.well-known/{kiosk.json,api-catalog,oauth-authorization-server,oauth-protected-resource,ard.json,ai-catalog.json}` and
400
431
  `/.well-known/agent-skills/index.json` — into the host app
401
432
  via `routes.append`, because the agents.txt standard and RFC 8615 place them at
402
433
  the origin root, outside any mount prefix. That install happens ONLY when the
403
434
  engine is mounted: merely bundling the gem adds no routes.
404
435
 
405
- **You name your OWN VERBS, and the METHOD FOLLOWS THE KIND** — GET for a
406
- `kind :query`, POST for a `kind :action`. That is what the protocol says a verb
407
- IS, so the routes state it instead of hiding it, and `bin/rails routes` prints
408
- your actual wire.
436
+ **You name your OWN OPERATIONS, and the METHOD FOLLOWS THE KIND** — GET for a
437
+ `kind :query`, POST for a `kind :action`. That is what the protocol says an
438
+ operation IS, so the routes state it instead of hiding it, and `bin/rails routes` prints
439
+ your actual protocol.
409
440
 
410
441
  **The mount comes FIRST.** Rails dispatches the first matching route, so
411
- everything the engine draws wins over every verb route and no verb of yours can
412
- shadow `schema`, `pay` or the auth plane. (You could not declare such a verb
413
- anyway — `Kiosk::Handler` refuses a reserved name at boot.)
442
+ everything the engine draws wins over every route of an operation, and no
443
+ operation of yours can shadow `schema`, `pay` or the auth plane. (You could not
444
+ declare such an operation anyway — `Kiosk::Handler` refuses a reserved name at boot.)
414
445
 
415
- A path under the mount that names no route — including a verb called with the
446
+ A path under the mount that names no route — including an operation called with the
416
447
  other method — matches nothing, so it is the ordinary 404 Rails answers at any
417
448
  unrouted path: no `code`, no `hint`. The mount-path middleware still stamps the
418
- version headers on it. If you want the wire's own `404 verb_not_found` there,
449
+ version headers on it. If you want the protocol's own `404 verb_not_found` there,
419
450
  draw a catch-all action of your own at the end of your routes; the engine does not
420
451
  draw one, because an assistant reads `GET <mount>/schema` before it dials.
421
- Declared-but-unrouted is the bug class this trade opens: every verb you declare
422
- needs its name in the block.
452
+ Declared-but-unrouted is the bug class this trade opens: every operation you
453
+ declare needs its name in the block.
423
454
 
424
455
  **The protocol plane comes from the mount and from nowhere else.** Copying those
425
456
  paths into your routes by hand is not a supported second way to draw them:
426
457
  the mount above the copy already answers, so the line is dead, and a protocol
427
458
  this gem keeps in step with the spec becomes a table you now own. Write your own
428
- verbs; mount the rest.
459
+ operations; mount the rest.
429
460
 
430
461
 
431
462
  ## Declaring queries and actions
432
463
 
433
- An assistant reaches a provider at ONE ENDPOINT PER VERB: a query is
464
+ An assistant reaches an operator at ONE PATH PER OPERATION: a query is
434
465
  `GET <mount>/<query-name>` with its arguments in the query string, an action is
435
466
  `POST <mount>/<action-name>` with its arguments in a JSON body. The operator
436
467
  decides what those names are and what they mean. `Kiosk::Handler` is the module
@@ -440,7 +471,7 @@ that lets a controller answer them, and you name each one in the `kiosk` block
440
471
  Kiosk ships a **mixin, not a base class**. Which superclass a handler controller
441
472
  has is your decision; the `include` is the whole contract.
442
473
 
443
- Which verb reaches a handler is a property of the **declaration**, not of the
474
+ Which HTTP method reaches a handler is a property of the **declaration**, not of the
444
475
  class: `kind :query` puts it on `GET`, `kind :action` on `POST`, and one
445
476
  controller may declare both — a resource you think of as one thing is one
446
477
  controller. Split when your domain splits.
@@ -492,29 +523,29 @@ end
492
523
 
493
524
  Put handler controllers in `app/controllers/kiosk/`. The engine loads that
494
525
  directory at boot and after every development reload, and each class that
495
- includes `Kiosk::Handler` registers its verbs, so an edited, added or removed
496
- verb lands without restarting the server.
526
+ includes `Kiosk::Handler` registers its operations, so an edited, added or
527
+ removed operation lands without restarting the server.
497
528
 
498
529
 
499
530
  ### What the macros do
500
531
 
501
532
  Each macro records a declaration; the **next `def`** claims all pending ones and
502
- becomes a wire verb. A method with no declarations above it is not a verb, so
503
- helper methods stay invisible to the wire.
533
+ becomes an operation. A method with no declarations above it is not an operation, so
534
+ helper methods stay invisible to the protocol.
504
535
 
505
536
  | macro | what it declares |
506
537
  | --- | --- |
507
- | `kind` | **Required.** `:query` (reached by `GET <mount>/<name>`) or `:action` (`POST <mount>/<name>`). A property of the declaration, so one controller may carry both. There is no default: either one would silently pick an HTTP method for you. `:action` is the DECLARATION name and nothing else: the wire command an action travels under is **`:run`**, so a `kind :action` verb reaches a reputation policy as `verb: :run` (`Kiosk::Handler` serves an action as `:run`; the reserved pay endpoint arrives as `:pay`). Branch on `:run` there, not on `:action` — see `kiosk-reputation`'s README. |
508
- | `reach` | Optional, and the default is the strong one. Whose rows this verb may touch (spec §7.2): `:principal` (default — only the caller's own, or rows that belong to no principal), `:published`, `:consented` or `:role`. Declare nothing and the verb is held to per-principal scoping absolutely; a departure costs one line and is published on the catalog, so an assistant can tell an open board from a scoping bug. |
509
- | `description` | Semantics **only**: what the verb does, how, and what it returns *in meaning*. Never a field list, a type, a required marker or a param name — those live in the schemas. |
510
- | `input_schema` | **Required.** JSON Schema for the params. The input contract: every name, type, enum and range — and the wire coerces and validates every call against it. A verb that takes nothing still declares the empty closed object. |
511
- | `output_schema` | **Required.** JSON Schema for what comes back, so an assistant knows the result shape without a call-and-observe probe — the only machine-readable statement of the answer, now that there is no response envelope. |
538
+ | `kind` | **Required.** `:query` (reached by `GET <mount>/<name>`) or `:action` (`POST <mount>/<name>`). A property of the declaration, so one controller may carry both. There is no default: either one would silently pick an HTTP method for you. `:action` is the DECLARATION name and nothing else: the protocol command an action travels under is **`:run`**, so a `kind :action` operation reaches a reputation policy as `verb: :run` (`Kiosk::Handler` serves an action as `:run`; the reserved `pay` path arrives as `:pay`). Branch on `:run` there, not on `:action` — see `kiosk-reputation`'s README. |
539
+ | `reach` | Optional, and the default is the strong one. Whose rows this operation may touch (spec §7.2): `:principal` (default — only the caller's own, or rows that belong to no customer), `:published`, `:consented` or `:role`. Declare nothing and the operation is held to per-customer scoping absolutely; a departure costs one line and is published on the catalog, so an assistant can tell an open board from a scoping bug. |
540
+ | `description` | Semantics **only**: what the operation does, how, and what it returns *in meaning*. Never a field list, a type, a required marker or a param name — those live in the schemas. |
541
+ | `input_schema` | **Required.** JSON Schema for the params. The input contract: every name, type, enum and range — and the protocol coerces and validates every call against it. An operation that takes nothing still declares the empty closed object. |
542
+ | `output_schema` | **Required.** JSON Schema for what comes back, so an assistant knows the result shape before it calls. The response has no envelope, so this is the only machine-readable statement of the answer. |
512
543
  | `example_params` | A params object an assistant can copy verbatim. |
513
544
  | `example_row` | A worked example of the result. |
514
- | `wire_name` | Optional. The name agents call the verb by, when it cannot be the method name. |
545
+ | `wire_name` | Optional. The published name that assistants call the operation by, when it cannot be the method name. |
515
546
 
516
547
  The **Required** rows are enforced at declaration time, not at request time: a
517
- verb that omits any of them raises an `ArgumentError` as its class body is read,
548
+ operation that omits any of them raises an `ArgumentError` as its class body is read,
518
549
  so the app fails to boot instead of publishing an incomplete contract.
519
550
 
520
551
  All of them surface in `GET <mount>/schema`, which is how an assistant discovers
@@ -541,15 +572,16 @@ with no restart and no deploy. The catalog's `?v=` version moves with it, and
541
572
  the discovery document republishes the new link within its own minute.
542
573
  `description`, `kind`, `reach` and `wire_name` are not resolvable — the first is
543
574
  prose semantics, two are routing facts fixed when the route is drawn, and
544
- `reach` is a security claim about the verb: one computed from your rows could
575
+ `reach` is a security claim about the operation: one computed from your rows could
545
576
  change under a caller between the catalog it read and the call it made.
546
577
 
547
578
 
548
579
  ### Two things to know
549
580
 
550
- **Draw verb routes with `kiosk` only.** A route you draw at a handler action
551
- yourself answers 404: the `kiosk` block names the verb that the action answers.
552
- `Kiosk::Handler` runs authentication, the argument check, the proof-of-work gate
581
+ **Draw the routes of operations with `kiosk` only.** A route you draw at a
582
+ handler action yourself answers 404: the `kiosk` block names the operation that
583
+ the action answers.
584
+ `Kiosk::Handler` runs authentication, the argument check, the proof-of-work toll
553
585
  and the transaction around the action, before your own `before_action` filters.
554
586
 
555
587
  ### What you get inside a handler
@@ -559,7 +591,7 @@ applies, `params` is `ActionController::Parameters`, and the answer is whatever
559
591
  you `render` — or the action's JSON template (a Jbuilder view, say), which is
560
592
  the one rendered whatever `Accept` the caller sent. On top of that:
561
593
 
562
- - `kiosk_identity` — the `Kiosk::Identity` the wire resolved (`user_id`,
594
+ - `kiosk_identity` — the `Kiosk::Identity` the protocol resolved (`user_id`,
563
595
  `agent_id`, `role`, `actor`). The four transaction-local GUCs are already applied to
564
596
  the connection, so SQL-side and RLS scoping work whether or not you read it.
565
597
  - `render_kiosk_page(rows, next_cursor:, total:)` — answer one page of a large
@@ -568,7 +600,7 @@ the one rendered whatever `Accept` the caller sent. On top of that:
568
600
  matching-row count as `X-Total-Count`. `Kiosk::Server::Cursor` has an offset
569
601
  helper; pass `total:` only when you know it.
570
602
  - `include Kiosk::Owned` — gives a model with a `user_id` column the scope
571
- `own`, the current principal's rows. `Kiosk.current_user_id` is the same id,
603
+ `own`, the signed-in customer's rows. `Kiosk.current_user_id` is the same id,
572
604
  for a column with another name.
573
605
  - `Kiosk.reader_zone(default = nil)` — the zone the caller declared in
574
606
  `Kiosk-Timezone`, else `default`.
@@ -584,24 +616,24 @@ the one rendered whatever `Accept` the caller sent. On top of that:
584
616
  records `pay` writes. `Kiosk::Settlement.own` is the caller's own;
585
617
  `Kiosk::Settlement.joins(:checkout_mandate).merge(Kiosk::CheckoutMandate.referencing(order_id: id))`
586
618
  is the settlement whose checkout names your row by the key your line items carry.
587
- - The handler runs inside the wire's GUC-scoped transaction, so raising rolls
588
- back — and so does rendering a non-2xx, which the seam converts into a raise.
619
+ - The handler runs inside the protocol's GUC-scoped transaction, so raising rolls
620
+ back — and so does rendering a non-2xx, which `Kiosk::Handler` converts into a raise.
589
621
 
590
- Errors are Rails' idiom, end to end. The error-**code** vocabulary is the wire
591
- contract — a closed table, not a class hierarchy. Mind which side of the seam
622
+ Errors are Rails' idiom, end to end. The error-**code** vocabulary is the protocol
623
+ contract — a closed table, not a class hierarchy. Mind which side of `Kiosk::Handler`
592
624
  you are on: a handler names a code the Rails way, under `error.code` in the body
593
- it renders, and the wire re-renders that as an RFC 9457
625
+ it renders, and the protocol re-renders that as an RFC 9457
594
626
  `application/problem+json` document whose `code` is a FLAT top-level member —
595
627
  `error.code` is the handler-side spelling, `code` is what travels and what an
596
628
  assistant branches on. Three Rails-native moves cover all of it:
597
629
 
598
- - `render json: {...}, status: :bad_request` — the status becomes its wire
630
+ - `render json: {...}, status: :bad_request` — the status becomes its protocol
599
631
  code (400 `bad_request`, 401 `unauthenticated`, 403 `forbidden`,
600
632
  404 `not_found`, 409 `conflict`, 422 `bad_request`, 429 `quota_exceeded`).
601
633
  - Raise what you would raise anyway. Any exception Rails knows a status for —
602
634
  `params.require`, `ActiveRecord::RecordNotFound`, anything your app
603
635
  registered in `config.action_dispatch.rescue_responses` (the same registry
604
- policy libraries use) — is mapped to that status' wire code by one
636
+ policy libraries use) — is mapped to that status' error code by one
605
637
  `rescue_from` the include installs. Your own `rescue_from` declarations win
606
638
  over it. Anything unregistered stays a 500 `action_failed`.
607
639
  **The CODE travels; the exception's own SENTENCE does not.** That branch is
@@ -623,18 +655,18 @@ assistant branches on. Three Rails-native moves cover all of it:
623
655
  raisable too.)
624
656
 
625
657
 
626
- ### The initializer holds configuration, not verbs
658
+ ### The initializer holds configuration, not operations
627
659
 
628
- There is no second way to declare a verb — no block you register from an
660
+ There is no second way to declare an operation — no block you register from an
629
661
  initializer. A block there cannot be reloaded, cannot be reached by your
630
662
  filters, `rescue_from` or strong parameters, and would teach — in the very file
631
663
  an adopter copies — that Rails does not apply to the surface you expose to
632
664
  assistants. Write a controller in `app/controllers/kiosk/`, and the initializer
633
665
  keeps what an initializer is for: the identity providers, the payment provider,
634
- the PoW gates.
666
+ the toll.
635
667
 
636
668
 
637
- ## Well-known endpoint (no booted Rails app required)
669
+ ## The discovery document (no booted Rails app required)
638
670
 
639
671
  ```ruby
640
672
  require "kiosk/server"
@@ -3,7 +3,7 @@
3
3
  require 'action_cable'
4
4
 
5
5
  # Top level, unsuffixed, because Action Cable constantizes the channel named
6
- # in a subscribe frame: this class name IS the wire's channel name.
6
+ # in a subscribe frame: this class name IS the protocol's channel name.
7
7
  #
8
8
  # {"command":"subscribe",
9
9
  # "identifier":"{\"channel\":\"KioskEvents\",\"topic\":\"todo\",\"subject\":\"list_4f1e…\"}"}
@@ -28,15 +28,14 @@ class KioskEvents < ActionCable::Channel::Base
28
28
  assign(declaration)
29
29
  return reject unless reachable?(declaration)
30
30
 
31
- open_stream!
32
- transmit(subscribed_frame)
31
+ transmit(open_delivery!)
33
32
  end
34
33
 
35
34
  # Action Cable confirms once the pubsub subscription is live, so replay
36
35
  # starts here: an event emitted before that reaches the client this way.
37
36
  def transmit_subscription_confirmation
38
37
  super
39
- replay!
38
+ @replay.confirmed
40
39
  end
41
40
 
42
41
  private
@@ -59,13 +58,10 @@ class KioskEvents < ActionCable::Channel::Base
59
58
  }
60
59
  end
61
60
 
62
- # Everything after `since`, or after the head read before the stream
63
- # opened. An event may arrive twice; delivery is at-least-once and the
64
- # client ignores an `id` it has seen.
65
- def replay!
66
- store.since(identity_key, since || @head).each do |event|
67
- transmit(event) if for_this_subscription?(event)
68
- end
61
+ # Replay and live delivery both come here, through {Kiosk::Server::EventsReplay}.
62
+ # An event can arrive twice; the client ignores an `id` it has seen.
63
+ def deliver(event)
64
+ transmit(event) if for_this_subscription?(event)
69
65
  end
70
66
 
71
67
  def since = params[:since]
@@ -80,17 +76,33 @@ class KioskEvents < ActionCable::Channel::Base
80
76
  (since.nil? || cursor?(since)) && (params[:subject].nil? || params[:subject].is_a?(String))
81
77
  end
82
78
 
83
- def open_stream!
84
- # Before the stream opens, so no event falls between head and stream.
79
+ # Reads head before the stream opens, so no event falls between head and
80
+ # stream. Returns the `subscribed` frame, built before the replay group
81
+ # counts this subscription.
82
+ def open_delivery!
85
83
  @head = store.head
84
+ subscribed_frame.tap do
85
+ @replay = connection.kiosk_replay_member(since || @head) { |event| deliver(event) }
86
+ open_stream!
87
+ end
88
+ end
86
89
 
87
- # Without `coder:` the block receives the raw broadcast String.
90
+ # Without `coder:` the block receives the raw broadcast String.
91
+ def open_stream!
88
92
  stream_from Kiosk::Server::EventsCable.stream_name(identity_key, @topic),
89
93
  coder: ActiveSupport::JSON do |event|
90
- transmit(event) if for_this_subscription?(event)
94
+ @replay.live(event)
95
+ rescue StandardError => e
96
+ logger&.error("[kiosk] events delivery failed for topic #{@topic.inspect}: #{e.class}: #{e.message}")
91
97
  end
92
98
  end
93
99
 
100
+ # On the pubsub's own thread, in the order it hands events over (spec
101
+ # Section 8.5.5). Action Cable's worker pool would reorder them.
102
+ def worker_pool_stream_handler(broadcasting, user_handler, coder: nil)
103
+ stream_handler(broadcasting, user_handler, coder:)
104
+ end
105
+
94
106
  def cursor?(value) = value.is_a?(Integer) && value.between?(0, MAX_CURSOR)
95
107
 
96
108
  # Its own topic (the replayed tail holds every topic) and, when named, its
@@ -124,14 +136,15 @@ class KioskEvents < ActionCable::Channel::Base
124
136
  end
125
137
 
126
138
  # Runs every REAUTHORISE_EVERY_SECONDS. A withdrawn reach is final for this
127
- # subscription, so the declaration is dropped and the frame sent once.
139
+ # subscription: the frame is sent once, and the subscription leaves the
140
+ # connection, so a later subscribe is judged again rather than confirmed as live.
128
141
  def reauthorise!
129
142
  return if @declaration.nil? || reachable?(@declaration)
130
143
 
131
144
  @declaration = nil
132
145
  # Braces required: bare pairs would be read as `transmit`'s keywords.
133
146
  transmit({ 'type' => 'unsubscribed', 'topic' => @topic, 'reason' => 'reach_revoked' })
134
- stop_all_streams
147
+ connection.subscriptions.remove_subscription(self)
135
148
  rescue StandardError => e
136
149
  logger&.error("[kiosk] events re-authorisation failed: #{e.class}: #{e.message}")
137
150
  end