studio-engine 0.135.2 → 0.137.0

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 (34) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +64 -11
  3. data/README.md +10 -0
  4. data/app/assets/javascripts/studio/cropper-1.6.2.min.js +10 -0
  5. data/app/assets/javascripts/studio/page_transition_reveal.js +3 -0
  6. data/app/assets/stylesheets/studio/cropper-1.6.2.min.css +9 -0
  7. data/app/controllers/concerns/studio/connection_flow.rb +215 -0
  8. data/app/controllers/concerns/studio/error_handling.rb +58 -1
  9. data/app/controllers/studio/connections_controller.rb +13 -0
  10. data/app/helpers/studio/page_header_helper.rb +26 -0
  11. data/app/helpers/studio_navbar_helper.rb +22 -0
  12. data/app/javascript/studio/application.js +1 -0
  13. data/app/javascript/studio/cropper.js +2 -2
  14. data/app/javascript/studio/page_header_self_styled.js +194 -0
  15. data/app/javascript/studio/page_transitions.js +42 -11
  16. data/app/javascript/studio/reload_visits.js +93 -0
  17. data/app/models/studio/connection.rb +137 -0
  18. data/app/models/studio/user_session.rb +216 -21
  19. data/app/views/layouts/_navbar.html.erb +11 -4
  20. data/app/views/studio/_cropper_assets.html.erb +14 -9
  21. data/app/views/studio/_legal_page.html.erb +52 -0
  22. data/app/views/studio/_page_header.html.erb +12 -2
  23. data/app/views/studio/page_header/_assets.html.erb +151 -0
  24. data/db/migrate/20261108120000_add_device_revocation_to_studio_user_sessions.rb +28 -0
  25. data/db/migrate/20261108130000_create_studio_connections.rb +35 -0
  26. data/lib/generators/studio/connections/connections_generator.rb +93 -0
  27. data/lib/studio/connections/stand_in.rb +89 -0
  28. data/lib/studio/connections.rb +483 -0
  29. data/lib/studio/engine.rb +14 -1
  30. data/lib/studio/host_schema.rb +53 -2
  31. data/lib/studio/page_header.rb +11 -2
  32. data/lib/studio/version.rb +1 -1
  33. data/lib/studio.rb +70 -0
  34. metadata +16 -1
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Studio
4
+ # The self-styled page header (docs/PAGE_HEADER.md, "In a plain-CSS app").
5
+ #
6
+ # studio/_page_header is styled by the engine's Tailwind layer (engine.css). An app
7
+ # that does not build that layer sets `config.page_header_self_styled = true`, and
8
+ # the row then brings its own scoped CSS and its small script, once per page, as
9
+ # the site footer does (studio/site_footer/_assets).
10
+ #
11
+ # Prefixed for the reason Studio::GeoHelper gives: every helper module is included
12
+ # into every view.
13
+ module PageHeaderHelper
14
+ # The styles and the script, once per page, where Studio.page_header_self_styled
15
+ # says this view wants them. nil otherwise, so a Tailwind app's row is unchanged
16
+ # to the byte. studio/_page_header calls it; a layout may call it too, to put
17
+ # the assets in <head>.
18
+ def studio_page_header_assets
19
+ return if @_studio_page_header_assets_rendered
20
+ return unless Studio::PageHeader.self_styled?(self)
21
+
22
+ @_studio_page_header_assets_rendered = true
23
+ render "studio/page_header/assets"
24
+ end
25
+ end
26
+ end
@@ -37,6 +37,28 @@ module StudioNavbarHelper
37
37
  "@click": "$store.modals && ($event.preventDefault(), #{open})" }
38
38
  end
39
39
 
40
+ # Any h1 opening tag, as the page's own heading.
41
+ PAGE_H1 = /<h1[\s>]/i
42
+
43
+ # Records that this page draws its own h1 (studio/_page_header calls it).
44
+ # Views render before their layout, so the navbar reads the mark when the
45
+ # layout draws it. Call it from a view that draws its page h1 somewhere the
46
+ # navbar cannot see: a content_for block, or a fragment the layout renders.
47
+ def studio_page_h1!
48
+ content_for(:studio_page_h1, "1") unless content_for?(:studio_page_h1)
49
+ end
50
+
51
+ # Whether the page carries an h1 of its own, so the navbar draws the brand
52
+ # as a div and the page keeps one h1. True when a view recorded one
53
+ # (studio_page_h1!), or when the rendered page body (the layout's yield)
54
+ # holds an h1 tag: a hand-written heading, or a page header served from a
55
+ # fragment cache, which replays its HTML but not its content_for.
56
+ def studio_page_has_h1?
57
+ return true if content_for?(:studio_page_h1)
58
+
59
+ content_for?(:layout) && content_for(:layout).to_s.match?(PAGE_H1)
60
+ end
61
+
40
62
  # Studio.navbar_items as partial specs ({ partial:, locals: }), [] for none.
41
63
  # Resolved once per render pass: the desktop bar and the phone row both ask.
42
64
  def studio_navbar_items
@@ -19,6 +19,7 @@ import IdentityMiniController from "studio/controllers/identity_mini_controller"
19
19
  import { startPinnedStack } from "studio/pinned_stack"
20
20
  import { installAlpineShims } from "studio/alpine_shims"
21
21
  import { installStudioLoader } from "studio/loader"
22
+ import "studio/reload_visits"
22
23
  import "studio/in_page_links"
23
24
 
24
25
  installAlpineShims()
@@ -17,8 +17,8 @@
17
17
  // Alpine.store('modals').open('crop-photo',
18
18
  // { imageUrl, aspectRatio: 3, maxWidth: 900, transparent: false })
19
19
  //
20
- // Cropper.js is the page's own global (studio/_cropper_assets loads it from
21
- // cdnjs on a page that can open the modal). A page where it never arrives says
20
+ // Cropper.js is the page's own global (studio/_cropper_assets loads the
21
+ // engine's vendored copy on a page that can open the modal). A page where it never arrives says
22
22
  // so in the modal's error line; the button never takes a press that does
23
23
  // nothing.
24
24
  //
@@ -0,0 +1,194 @@
1
+ // studio/page_header_self_styled: the page-header controller's work for an app with no
2
+ // Stimulus and no import map (config.page_header_self_styled, docs/PAGE_HEADER.md, "In a
3
+ // plain-CSS app"). studio/page_header/_assets loads it by its own module tag, once per
4
+ // page, beside the row's scoped CSS.
5
+ //
6
+ // For every studio/_page_header on the page it:
7
+ // - marks the row data-stuck once it has left its place in the flow, so the CSS gives
8
+ // it the bar;
9
+ // - marks which ends of the tabs hide a tab (data-fade-start, data-fade-end);
10
+ // - scrolls the open tab into view inside the tabs on load;
11
+ // - keeps each Links menu's aria-expanded in step with its popover, walks into the list
12
+ // on ArrowDown, and places the list where the browser has no anchor positioning.
13
+ //
14
+ // With no pinned stack on the page (window.studioPinnedStack), it also publishes
15
+ // --nav-bottom from the document's first <header>, when that header is sticky or fixed,
16
+ // so the row sticks under the app's own masthead. An app whose CSS sets --nav-bottom or
17
+ // --pin-page-top keeps its own value.
18
+ //
19
+ // IT IMPORTS NOTHING, because a plain app may have no import map. The five measurements
20
+ // below are studio/page_header's, copied; test/javascript/page_header_self_styled.test.mjs
21
+ // holds the copies to the originals. It boots only in a browser, so the test can load it
22
+ // as a data: module. A module runs once per document, so a Turbo visit rescans on
23
+ // turbo:load.
24
+
25
+ export function isStuck(rowTop, restTop) {
26
+ return rowTop - restTop > 0.5
27
+ }
28
+
29
+ export function sentinelMarksThePlace(parentDisplay) {
30
+ return !/flex|grid/.test(parentDisplay)
31
+ }
32
+
33
+ export function hiddenEnds({ scrollLeft, clientWidth, scrollWidth }) {
34
+ return {
35
+ start: scrollLeft > 1,
36
+ end: scrollLeft + clientWidth < scrollWidth - 1
37
+ }
38
+ }
39
+
40
+ export function revealBy(box, tab, margin = 32) {
41
+ if (tab.left < box.left) return tab.left - box.left - margin
42
+ if (tab.right > box.right) return tab.right - box.right + margin
43
+ return 0
44
+ }
45
+
46
+ export function menuPlacement(button, list, viewport, gap = 8) {
47
+ const below = viewport.height - button.bottom
48
+ const above = button.top
49
+ const top = below < list.height + gap && above > below
50
+ ? Math.max(gap, button.top - list.height - 4)
51
+ : button.bottom + 4
52
+ const left = Math.min(
53
+ Math.max(gap, button.right - list.width),
54
+ Math.max(gap, viewport.width - list.width - gap)
55
+ )
56
+ return { top, left }
57
+ }
58
+
59
+ // The bottom edge, in px, of the app's own masthead: the first header, when it is sticky
60
+ // or fixed. 0 for any other header, or none.
61
+ export function mastheadBottom(position, bottom) {
62
+ return position === "sticky" || position === "fixed" ? Math.max(0, bottom) : 0
63
+ }
64
+
65
+ function anchorsSupported() {
66
+ return typeof CSS !== "undefined" && !!CSS.supports &&
67
+ CSS.supports("anchor-name: --a") && CSS.supports("position-anchor: --a")
68
+ }
69
+
70
+ function boot() {
71
+ if (window.studioPageHeaderSelfStyled) {
72
+ window.studioPageHeaderSelfStyled.scan()
73
+ return
74
+ }
75
+
76
+ const root = document.documentElement
77
+ let rows = []
78
+ let frame = null
79
+ let ownsNavBottom = null
80
+
81
+ const publishNavBottom = () => {
82
+ if (window.studioPinnedStack) return
83
+ if (ownsNavBottom === null) {
84
+ const computed = getComputedStyle(root)
85
+ ownsNavBottom = !root.style.getPropertyValue("--nav-bottom") &&
86
+ !computed.getPropertyValue("--nav-bottom").trim() &&
87
+ !computed.getPropertyValue("--pin-page-top").trim()
88
+ }
89
+ if (!ownsNavBottom) return
90
+ const header = document.querySelector("header")
91
+ const bottom = header ? mastheadBottom(getComputedStyle(header).position, header.getBoundingClientRect().bottom) : 0
92
+ const value = `${Math.round(bottom * 100) / 100}px`
93
+ if (root.style.getPropertyValue("--nav-bottom") !== value) root.style.setProperty("--nav-bottom", value)
94
+ }
95
+
96
+ // The top of the row's place in the flow. In a flex or grid parent only the row can
97
+ // say, so it is unstuck for one read; no frame paints in between.
98
+ const restTop = ({ sentinel, row }) => {
99
+ if (sentinelMarksThePlace(getComputedStyle(sentinel.parentElement).display)) {
100
+ return sentinel.getBoundingClientRect().top
101
+ }
102
+ row.style.position = "static"
103
+ const top = row.getBoundingClientRect().top
104
+ row.style.position = ""
105
+ return top
106
+ }
107
+
108
+ const placeMenu = (button, list) => {
109
+ const place = menuPlacement(button.getBoundingClientRect(), list.getBoundingClientRect(),
110
+ { width: window.innerWidth, height: window.innerHeight })
111
+ list.style.top = `${place.top}px`
112
+ list.style.left = `${place.left}px`
113
+ list.style.right = "auto"
114
+ }
115
+
116
+ const sync = () => {
117
+ publishNavBottom()
118
+ rows = rows.filter((item) => item.row.isConnected)
119
+ for (const item of rows) {
120
+ item.row.toggleAttribute("data-stuck", isStuck(item.row.getBoundingClientRect().top, restTop(item)))
121
+ if (!anchorsSupported()) {
122
+ for (const { button, list } of item.menus) {
123
+ if (list.matches(":popover-open")) placeMenu(button, list)
124
+ }
125
+ }
126
+ if (!item.tabs) continue
127
+ const ends = hiddenEnds(item.tabs)
128
+ item.tabs.toggleAttribute("data-fade-start", ends.start)
129
+ item.tabs.toggleAttribute("data-fade-end", ends.end)
130
+ }
131
+ }
132
+
133
+ const schedule = () => {
134
+ if (frame) return
135
+ frame = requestAnimationFrame(() => {
136
+ frame = null
137
+ sync()
138
+ })
139
+ }
140
+
141
+ // A disclosure, not role="menu": the popover opens, closes on Escape and gives focus
142
+ // back with no script. This keeps aria-expanded honest and adds ArrowDown.
143
+ const wireMenu = (menu) => {
144
+ const button = menu.querySelector("[popovertarget]")
145
+ const list = menu.querySelector("[popover]")
146
+ if (!button || !list) return null
147
+ button.setAttribute("aria-expanded", "false")
148
+ list.addEventListener("toggle", (event) => {
149
+ const open = event.newState === "open"
150
+ button.setAttribute("aria-expanded", String(open))
151
+ if (open) {
152
+ if (!anchorsSupported()) placeMenu(button, list)
153
+ return
154
+ }
155
+ if (document.activeElement === document.body || list.contains(document.activeElement)) button.focus()
156
+ })
157
+ button.addEventListener("keydown", (event) => {
158
+ if (event.key !== "ArrowDown") return
159
+ event.preventDefault()
160
+ if (!list.matches(":popover-open")) list.showPopover?.()
161
+ list.querySelector("a")?.focus()
162
+ })
163
+ return { button, list }
164
+ }
165
+
166
+ const wire = (sentinel) => {
167
+ if (sentinel.hasAttribute("data-page-header-live")) return
168
+ const row = sentinel.nextElementSibling
169
+ if (!row || !row.classList.contains("page-header")) return
170
+ sentinel.setAttribute("data-page-header-live", "")
171
+ const tabs = row.querySelector(".page-header-tabs")
172
+ const menus = [...row.querySelectorAll(".page-header-menu")].map(wireMenu).filter(Boolean)
173
+ if (tabs) {
174
+ tabs.addEventListener("scroll", schedule, { passive: true })
175
+ const open = tabs.querySelector("[aria-current]")
176
+ if (open) tabs.scrollLeft += revealBy(tabs.getBoundingClientRect(), open.getBoundingClientRect())
177
+ }
178
+ rows.push({ sentinel, row, tabs, menus })
179
+ }
180
+
181
+ const scan = () => {
182
+ document.querySelectorAll(".page-header-sentinel").forEach(wire)
183
+ sync()
184
+ }
185
+
186
+ window.studioPageHeaderSelfStyled = { scan }
187
+ window.addEventListener("scroll", schedule, { passive: true })
188
+ window.addEventListener("resize", schedule, { passive: true })
189
+ document.addEventListener("turbo:load", scan)
190
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", scan)
191
+ else scan()
192
+ }
193
+
194
+ if (typeof window !== "undefined" && typeof document !== "undefined") boot()
@@ -106,6 +106,15 @@ export function leaveStyle(win, style) {
106
106
  }
107
107
  }
108
108
 
109
+ // A skip the engine chooses. Chrome rejects the skipped transition's `ready` with "Transition
110
+ // was skipped" and leaves the rejection unhandled (measured: a pageerror whenever nothing
111
+ // awaits `ready`). This skip is the engine's own decision, so that one rejection is expected
112
+ // and handled here. A transition the engine did not skip is never touched.
113
+ export function skipOwnTransition(transition) {
114
+ if (transition.ready && typeof transition.ready.catch === "function") transition.ready.catch(() => {})
115
+ transition.skipTransition()
116
+ }
117
+
109
118
  // A slow image must not hold a click: past the cap the swap goes ahead.
110
119
  export function withCap(promise, ms, timer = setTimeout) {
111
120
  return Promise.race([promise, new Promise((done) => timer(done, ms))])
@@ -210,9 +219,11 @@ export function installPageTransitions(doc) {
210
219
 
211
220
  doc.addEventListener("turbo:visit", (event) => {
212
221
  root.dataset.pageTransitionVisit = ""
213
- // Turbo opens its view transition before it reads turbo-visit-control. A response it will
214
- // not render gets no turbo:before-render, so this stands, and that transition draws nothing.
215
- // The full load after it plays the one motion. Left alone while a motion is still running.
222
+ // A response Turbo will not render gets no turbo:before-render, so this stands. Turbo
223
+ // opens no transition for it (studio/reload_visits takes the meta out of what it parses),
224
+ // and should one open on a path that guard does not see (a frame's reload visit), this
225
+ // makes it draw nothing. The full load after it plays the one motion. Left alone while a
226
+ // motion is still running.
216
227
  if (!root.dataset.pageTransition) root.dataset.pageTransition = STILL
217
228
  target = new URL(event.detail.url).pathname
218
229
  // A GET that redirects: Turbo renders the response, then replaces to the final address
@@ -231,17 +242,37 @@ export function installPageTransitions(doc) {
231
242
 
232
243
  // A page never visited: read its names from the response, ahead of the old page's picture.
233
244
  // Only a page with names of its own can share one, so every other page skips the parse.
245
+ //
246
+ // TURBO READS THE PAGE THROUGH THIS READ. Turbo starts its view transition one frame after
247
+ // its own read of the response resolves, and the browser takes the old page's picture then:
248
+ // the morph's name must be down by that moment. Turbo's responseHTML getter is a fresh
249
+ // response.clone().text() on each access, and nothing orders this module's read before
250
+ // Turbo's, so this read is put in its place (studio/reload_visits does the same): the read
251
+ // Turbo awaits is the one that has already named the morph. Measured without it: under an
252
+ // 8x CPU throttle, 2 of 6 visits started the transition with no name, and nothing morphed.
234
253
  doc.addEventListener("turbo:before-fetch-response", (event) => {
235
254
  if (event.target && event.target.tagName === "TURBO-FRAME") return
236
255
  if (!morphNames(doc).size) return
237
256
  const { fetchResponse } = event.detail
238
- Promise.resolve(fetchResponse.responseHTML).then((html) => {
239
- if (!html) return
240
- const names = morphNames(new win.DOMParser().parseFromString(html, "text/html"))
241
- const path = new URL(fetchResponse.response.url).pathname
242
- known.set(path, names)
243
- if (target && (path === target || fetchResponse.redirected)) predict(names)
244
- }).catch(() => {})
257
+ const named = Promise.resolve(fetchResponse.responseHTML).then((html) => {
258
+ try {
259
+ if (!html) return html
260
+ const names = morphNames(new win.DOMParser().parseFromString(html, "text/html"))
261
+ const path = new URL(fetchResponse.response.url).pathname
262
+ known.set(path, names)
263
+ if (target && (path === target || fetchResponse.redirected)) predict(names)
264
+ } catch {
265
+ // A page this module cannot read morphs nothing; Turbo still renders it.
266
+ }
267
+ return html
268
+ })
269
+ // A failed read rejects for Turbo exactly as its own would; this module needs no answer.
270
+ named.catch(() => {})
271
+ try {
272
+ Object.defineProperty(fetchResponse, "responseHTML", { configurable: true, value: named })
273
+ } catch {
274
+ // A response that refuses the swap keeps Turbo's own read, and the race this closes.
275
+ }
245
276
  })
246
277
 
247
278
  // In capture, so the hold is in place before any other listener takes Turbo's resume.
@@ -305,7 +336,7 @@ export function installPageTransitions(doc) {
305
336
  const left = leaveStyle(win, style)
306
337
  if (!transition) return
307
338
  if (!left) {
308
- transition.skipTransition()
339
+ skipOwnTransition(transition)
309
340
  return
310
341
  }
311
342
  markHeld(doc)
@@ -0,0 +1,93 @@
1
+ // studio/reload_visits: Turbo opens no view transition for a visit it will only reload.
2
+ //
3
+ // THE DEFECT. Smooth load (layouts/studio/_smooth_load) turns on Turbo's same-document view
4
+ // transitions. Turbo starts the transition BEFORE it reads the response's head: its render
5
+ // callback is what finds turbo-visit-control reload (turf-monster's /wallet and /account) or a
6
+ // changed data-turbo-track="reload" asset, and then navigates by a full load. That navigation
7
+ // can skip the transition while its `ready` promise is still pending. Turbo awaits only
8
+ // `finished` (turbo-rails 2.0.23, turbo.js ViewTransitioner#renderChange), so `ready` rejects
9
+ // with nobody listening: an unhandled "Transition was skipped" error on every such visit that
10
+ // loses the race (turf-monster CI run 42447610386).
11
+ //
12
+ // THE FIX, AT THE CAUSE. Turbo starts a transition only when both the current page and the new
13
+ // snapshot carry the view-transition meta (PageView#shouldTransitionTo). So when Turbo's own
14
+ // renderer says it will not render a response, this takes that meta out of the HTML Turbo
15
+ // parses. Turbo then swaps nothing in a transition and goes straight to its full load, which
16
+ // plays the page transition once (docs/PAGE_TRANSITIONS.md, "Full page loads"). Only a page
17
+ // Turbo was going to throw away is changed, and the page the full load brings is the server's
18
+ // own. No promise is marked handled, so a real failure (a duplicate view-transition-name, a
19
+ // render that throws) still surfaces.
20
+ //
21
+ // THE SEAM. turbo:before-fetch-response, the moment studio/loader also uses: Turbo awaits
22
+ // fetchResponse.responseHTML right after it, so a promise put there is what Turbo parses. The
23
+ // two compose in either order, since each reads the other's promise. A frame's response is left
24
+ // alone: a frame never transitions, and its reload is a new fetch.
25
+ //
26
+ // It imports nothing; test/javascript/reload_visits.test.mjs loads it as a data: module.
27
+
28
+ // The meta Turbo reads for a same-document transition: `view-transition` (same-origin), or
29
+ // the `turbo-view-transition` setting. Not `view-transition-*` names of anything else.
30
+ const TRANSITION_META = /<meta\b[^>]*\bname\s*=\s*["']?(?:turbo-)?view-transition(?![\w-])[^>]*>/gi
31
+ const VISIT_CONTROL_RELOAD = /<meta[^>]*(turbo-visit-control[^>]*reload|reload[^>]*turbo-visit-control)/i
32
+
33
+ // The head alone: Turbo's decision reads only the head, and the body is most of the bytes.
34
+ export function headOf(html) {
35
+ const end = html.search(/<\/head\s*>/i)
36
+ return end < 0 ? html : html.slice(0, end)
37
+ }
38
+
39
+ export function prefersTransition(html) {
40
+ TRANSITION_META.lastIndex = 0
41
+ return TRANSITION_META.test(headOf(html))
42
+ }
43
+
44
+ // Whether Turbo would render this HTML as the next page. Asked of Turbo's own PageRenderer, so
45
+ // the answer cannot drift from Turbo's (visit control, then the tracked assets). Without
46
+ // Turbo's classes, the visit-control meta alone, the case a host sets on purpose.
47
+ export function rendersAsPage(html, doc, turbo) {
48
+ const head = headOf(html)
49
+ if (turbo && turbo.PageRenderer && turbo.PageSnapshot) {
50
+ const current = turbo.PageSnapshot.fromElement(doc.documentElement)
51
+ const next = turbo.PageSnapshot.fromHTMLString(head)
52
+ return new turbo.PageRenderer(current, next, false).shouldRender
53
+ }
54
+ return !VISIT_CONTROL_RELOAD.test(head)
55
+ }
56
+
57
+ // The HTML Turbo should parse: unchanged, unless it carries the transition meta and Turbo will
58
+ // not render it, and then the same HTML with that meta out of its head.
59
+ export function withoutReloadTransition(html, doc, turbo) {
60
+ if (typeof html !== "string" || !prefersTransition(html)) return html
61
+ // A Turbo whose classes changed shape leaves the HTML as it came: the old behaviour, not a
62
+ // failed visit.
63
+ try {
64
+ if (rendersAsPage(html, doc, turbo)) return html
65
+ } catch {
66
+ return html
67
+ }
68
+ const head = headOf(html)
69
+ return head.replace(TRANSITION_META, "") + html.slice(head.length)
70
+ }
71
+
72
+ export function guardResponse(event, doc, turbo) {
73
+ if (event.target && event.target.tagName === "TURBO-FRAME") return false
74
+ const response = event.detail && event.detail.fetchResponse
75
+ if (!response || !response.isHTML) return false
76
+ const html = Promise.resolve(response.responseHTML).then((text) => withoutReloadTransition(text, doc, turbo))
77
+ Object.defineProperty(response, "responseHTML", { configurable: true, value: html })
78
+ return true
79
+ }
80
+
81
+ let installed = false
82
+
83
+ export function installReloadVisits(doc) {
84
+ if (installed || !doc || !doc.addEventListener) return false
85
+ installed = true
86
+ doc.addEventListener("turbo:before-fetch-response", (event) => {
87
+ const win = doc.defaultView
88
+ guardResponse(event, doc, win && win.Turbo)
89
+ })
90
+ return true
91
+ }
92
+
93
+ if (typeof document !== "undefined") installReloadVisits(document)
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Studio
4
+ # One third-party account a host app has connected over OAuth 2.0, for a
5
+ # provider the host declared with Studio.define_connection
6
+ # (Studio::Connections::Provider). docs/CONNECTIONS.md.
7
+ #
8
+ # One row per provider and account (account_key, unique within a provider).
9
+ # Connecting the same account again replaces its tokens (.store!). No token,
10
+ # and no part of one, is ever shown: every token column is encrypted, filtered
11
+ # from inspect, and read only by the provider's access_token.
12
+ #
13
+ # THE ROW DEPENDS ON THE APP'S ENCRYPTION KEYS: without them a connect refuses
14
+ # before it asks the provider for anything
15
+ # (Studio::Connections.encryption_ready?); with them lost or changed, a stored
16
+ # row is unreadable (#readable? is false), counts as not connected, and
17
+ # connecting again replaces it.
18
+ #
19
+ # ROTATION. #rotate! is called by the provider inside #with_lock, which
20
+ # reloads the row first: a racing caller waits, then spends the NEWEST
21
+ # refresh token, and the answered token is stored before the access token it
22
+ # came with is used.
23
+ class Connection < ApplicationRecord
24
+ self.table_name = "studio_connections"
25
+
26
+ encrypts :access_token, :refresh_token, :account_secret
27
+ self.filter_attributes += %i[access_token refresh_token account_secret account_key]
28
+
29
+ validates :provider, :account_key, :connected_at, presence: true
30
+ validates :account_key, uniqueness: { scope: :provider }
31
+ validate :holds_what_its_policy_needs
32
+
33
+ scope :for_provider, ->(key) { where(provider: key.to_s) }
34
+
35
+ class << self
36
+ def encryption_ready? = Studio::Connections.encryption_ready?
37
+
38
+ def newest_first = order(connected_at: :desc, id: :desc)
39
+
40
+ # Every connection of a provider whose tokens this server can read, newest first.
41
+ def readable(provider) = for_provider(provider).newest_first.select(&:readable?)
42
+
43
+ # Stores the account a connect reached. `grant` is the token endpoint's
44
+ # JSON ({} for a client-credentials consent). Raises InvalidAccount for an
45
+ # account that fails the provider's format, and RecordInvalid when the
46
+ # answer lacks what the provider's policy keeps; the message names the
47
+ # field, never a value.
48
+ def store!(provider, grant, account:, by:, label: nil, metadata: {}, now: Time.current)
49
+ provider = Studio::Connections.fetch(provider) unless provider.is_a?(Studio::Connections::Provider)
50
+ account = provider.normalize_account(account) or raise Studio::Connections::InvalidAccount, "not a #{provider.label} account"
51
+ key = provider.account_key_for(account)
52
+
53
+ transaction(requires_new: true) do
54
+ connection = find_or_initialize_by(provider: provider.key, account_key: key)
55
+ # A row whose tokens can no longer be read is replaced, not updated.
56
+ unless connection.new_record? || connection.readable?
57
+ where(id: connection.id).delete_all
58
+ connection = new(provider: provider.key, account_key: key)
59
+ end
60
+ keep_access = provider.refresh == :cached
61
+ connection.assign_attributes(
62
+ account_secret: provider.private_account ? account : nil,
63
+ label: label.to_s.strip.presence || provider.label,
64
+ access_token: keep_access ? grant["access_token"].to_s.presence : nil,
65
+ refresh_token: provider.refresh == :memory ? nil : grant["refresh_token"].to_s.presence,
66
+ access_expires_at: keep_access ? Studio::Connections::Provider.expiry(grant, "expires_in", now) : nil,
67
+ refresh_expires_at: Studio::Connections::Provider.expiry(grant, provider.refresh_expires_in_key, now),
68
+ metadata: metadata.to_h.deep_stringify_keys, connected_by: by.to_s.presence, connected_at: now,
69
+ last_refreshed_at: nil
70
+ )
71
+ connection.save!
72
+ connection
73
+ end
74
+ end
75
+ end
76
+
77
+ def provider_definition = Studio::Connections.fetch(provider)
78
+
79
+ # The account as the provider names it: the decrypted id for a private
80
+ # account, else the key itself.
81
+ def account_id = account_secret.presence || account_key
82
+
83
+ # An access token, by the provider's refresh policy. `stale:` is a token the
84
+ # API just refused with a 401 (the :cached policy refreshes it).
85
+ def fresh_access_token(stale: nil) = provider_definition.access_token(self, stale:)
86
+
87
+ # Can the stored tokens be decrypted with this app's keys?
88
+ def readable?
89
+ access_token
90
+ refresh_token
91
+ account_secret
92
+ true
93
+ rescue ActiveRecord::Encryption::Errors::Base
94
+ false
95
+ end
96
+
97
+ # Is the stored access token good for longer than the provider's margin? A
98
+ # token with no expiry is, until the provider refuses it.
99
+ def access_fresh?(now = Time.current)
100
+ return false if access_token.blank?
101
+
102
+ access_expires_at.nil? || access_expires_at > now + provider_definition.refresh_margin
103
+ end
104
+
105
+ # Stores what a refresh just answered. Called inside #with_lock by the
106
+ # provider, before the access token is used. A provider whose rotation is
107
+ # :required refuses an answer without a refresh token (storing nothing would
108
+ # lose the account); otherwise a blank one keeps the stored one.
109
+ def rotate!(grant, now: Time.current)
110
+ definition = provider_definition
111
+ answered = grant["refresh_token"].to_s.presence
112
+ if answered.nil? && definition.rotation == :required
113
+ raise Studio::Connections::Error, "#{definition.label} answered a refresh with no refresh token; connect again"
114
+ end
115
+
116
+ changes = { refresh_token: answered || refresh_token, last_refreshed_at: now,
117
+ refresh_expires_at: Studio::Connections::Provider.expiry(grant, definition.refresh_expires_in_key, now) || refresh_expires_at }
118
+ if definition.refresh == :cached
119
+ raise Studio::Connections::Error, "#{definition.label} answered a refresh with no access token" if grant["access_token"].blank?
120
+
121
+ changes.merge!(access_token: grant["access_token"], access_expires_at: Studio::Connections::Provider.expiry(grant, "expires_in", now))
122
+ end
123
+ update!(changes)
124
+ end
125
+
126
+ private
127
+
128
+ def holds_what_its_policy_needs
129
+ definition = Studio::Connections.defined?(provider) ? Studio::Connections.fetch(provider) : nil
130
+ return errors.add(:provider, "is not a defined connection provider") unless definition
131
+
132
+ errors.add(:refresh_token, :blank) if definition.refresh == :rotating && refresh_token.blank?
133
+ errors.add(:access_token, :blank) if definition.refresh == :cached && access_token.blank?
134
+ errors.add(:account_secret, :blank) if definition.private_account && account_secret.blank?
135
+ end
136
+ end
137
+ end