@gloom-sh/terminal 0.19.5 → 0.19.6

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 (208) hide show
  1. package/package.json +1 -1
  2. package/patches/@opentui%2Fcore@0.3.2.patch +86 -25
  3. package/src/api-client/equity-screener.ts +23 -0
  4. package/src/app/pane-runtime/index.tsx +2 -0
  5. package/src/app/pane-runtime/plugin-bindings.ts +10 -1
  6. package/src/app.tsx +63 -16
  7. package/src/cli/commands/market.ts +149 -10
  8. package/src/cli/commands/search.ts +21 -3
  9. package/src/cli/commands/ticker.ts +74 -33
  10. package/src/cli/glossary.ts +3 -3
  11. package/src/cli/known-gaps.ts +8 -0
  12. package/src/cli/listing-arg.ts +12 -0
  13. package/src/cli/pane-functions/capabilities.ts +2 -0
  14. package/src/cli/pane-functions/catalog.ts +22 -4
  15. package/src/cli/pane-functions/function-help.ts +8 -5
  16. package/src/cli/pane-functions/headless.ts +4 -3
  17. package/src/cli/pane-functions/resolver.ts +75 -2
  18. package/src/cli/quote-answer.ts +9 -0
  19. package/src/cli/symbol-list.ts +54 -2
  20. package/src/cli/symbol-rows.ts +14 -2
  21. package/src/cli/ticker-resolution.ts +89 -20
  22. package/src/components/chart/composite/axis-overlays.tsx +60 -27
  23. package/src/components/chart/composite/composite-chart.tsx +118 -63
  24. package/src/components/chart/composite/cursor-source.ts +111 -0
  25. package/src/components/chart/composite/format.ts +168 -6
  26. package/src/components/chart/composite/legend.tsx +8 -4
  27. package/src/components/chart/composite/panel-labels.ts +20 -1
  28. package/src/components/chart/composite/panel-surface.tsx +201 -92
  29. package/src/components/chart/composite/price-axis-labels.tsx +92 -46
  30. package/src/components/chart/composite/price-series.ts +31 -8
  31. package/src/components/chart/composite/scene.ts +154 -59
  32. package/src/components/chart/composite/series-axis-tags.tsx +4 -2
  33. package/src/components/chart/composite/time-axis.ts +13 -5
  34. package/src/components/chart/composite/time-scale.ts +211 -56
  35. package/src/components/chart/composite/types.ts +11 -1
  36. package/src/components/chart/composite/use-composite-chart-keyboard.ts +32 -12
  37. package/src/components/chart/curve/curve-surface.tsx +5 -2
  38. package/src/components/chart/curve/model.ts +4 -1
  39. package/src/components/chart/native/use-bitmap-metrics.ts +81 -0
  40. package/src/components/chart/static/series.ts +3 -0
  41. package/src/components/command-bar/commands/collection-list.ts +81 -0
  42. package/src/components/command-bar/commands/direct/index.ts +6 -0
  43. package/src/components/command-bar/commands/registry.ts +8 -0
  44. package/src/components/command-bar/layout-items/current-layout.ts +22 -1
  45. package/src/components/command-bar/layout-items/focused-pane.ts +22 -1
  46. package/src/components/command-bar/pane-templates/items.ts +19 -3
  47. package/src/components/command-bar/pane-templates/workflow.ts +5 -0
  48. package/src/components/command-bar/routes/root/results.ts +23 -3
  49. package/src/components/command-bar/routes/root/selection.ts +4 -2
  50. package/src/components/command-bar/routes/root/shortcut-feedback.ts +1 -1
  51. package/src/components/command-bar/routes/root/shortcut-items.ts +3 -4
  52. package/src/components/command-bar/routes/root/shortcuts.ts +58 -14
  53. package/src/components/command-bar/routes/root/ticker-first.ts +32 -0
  54. package/src/components/command-bar/surface/environment.ts +2 -0
  55. package/src/components/command-bar/view-model.ts +7 -0
  56. package/src/components/command-bar/workflow/ops.ts +2 -1
  57. package/src/components/command-bar/workflow/tickers.ts +20 -0
  58. package/src/components/layout/shell/menu.ts +15 -1
  59. package/src/components/layout/shell/pane/actions.ts +4 -0
  60. package/src/components/layout/shell/ticker-link-menu.ts +12 -3
  61. package/src/components/layout/status-bar.tsx +20 -0
  62. package/src/components/onboarding/onboarding-keyboard.ts +5 -1
  63. package/src/components/onboarding/onboarding-wizard.tsx +15 -4
  64. package/src/components/onboarding/portfolio-step/positions-panel.tsx +8 -5
  65. package/src/components/onboarding/use-onboarding-progress.ts +20 -1
  66. package/src/components/price-sparkline/view.tsx +14 -6
  67. package/src/components/ticker/badge/index.tsx +8 -4
  68. package/src/components/ticker/badge/list.tsx +23 -7
  69. package/src/components/ui/column-grid.tsx +8 -2
  70. package/src/components/ui/data-table/opentui/model.ts +4 -1
  71. package/src/components/ui/tabs.tsx +5 -2
  72. package/src/core/state/app/layout.ts +18 -3
  73. package/src/core/state/app/state.ts +2 -0
  74. package/src/core/state/app/types.ts +5 -0
  75. package/src/data/config/layout.ts +3 -0
  76. package/src/data/config/store/normalize.ts +39 -4
  77. package/src/i18n/es.ts +10 -0
  78. package/src/i18n/ja.ts +10 -0
  79. package/src/i18n/ko.ts +10 -0
  80. package/src/i18n/zh-cn.ts +10 -0
  81. package/src/i18n/zh-tw.ts +10 -0
  82. package/src/layout/pane-manager/floating-placement.ts +7 -4
  83. package/src/layout/pane-manager/floating.ts +5 -2
  84. package/src/market-data/bond-funds.ts +19 -0
  85. package/src/market-data/futures-contract.ts +14 -3
  86. package/src/market-data/market/freshness.ts +18 -0
  87. package/src/market-data/market/status.ts +15 -2
  88. package/src/plugins/builtin/bond-calculator/headless.ts +2 -1
  89. package/src/plugins/builtin/bond-calculator/index.tsx +1 -1
  90. package/src/plugins/builtin/bond-calculator/model.ts +14 -5
  91. package/src/plugins/builtin/bond-calculator/pane.tsx +1 -1
  92. package/src/plugins/builtin/buildout/cells.tsx +25 -45
  93. package/src/plugins/builtin/buildout/detail/company.tsx +3 -3
  94. package/src/plugins/builtin/buildout/detail/index.tsx +1 -1
  95. package/src/plugins/builtin/buildout/detail/intel.tsx +4 -7
  96. package/src/plugins/builtin/buildout/detail/site.tsx +4 -4
  97. package/src/plugins/builtin/buildout/detail/ui.tsx +39 -38
  98. package/src/plugins/builtin/buildout/format.ts +23 -1
  99. package/src/plugins/builtin/buildout/model/types.ts +1 -0
  100. package/src/plugins/builtin/buildout/pane/index.tsx +2 -8
  101. package/src/plugins/builtin/buildout/table-model.ts +12 -4
  102. package/src/plugins/builtin/cds/headless.ts +1 -0
  103. package/src/plugins/builtin/cds/index.tsx +1 -1
  104. package/src/plugins/builtin/cloud/plugin.tsx +2 -0
  105. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +28 -3
  106. package/src/plugins/builtin/correlation/headless.ts +3 -2
  107. package/src/plugins/builtin/crypto-board/pane.tsx +5 -4
  108. package/src/plugins/builtin/debt-maturities/headless.ts +11 -2
  109. package/src/plugins/builtin/debt-maturities/model.ts +66 -0
  110. package/src/plugins/builtin/debt-maturities/pane.tsx +23 -4
  111. package/src/plugins/builtin/earnings-ripple/pane.tsx +1 -1
  112. package/src/plugins/builtin/econ/calendar-model.ts +28 -6
  113. package/src/plugins/builtin/equity-screener/client.ts +1 -1
  114. package/src/plugins/builtin/equity-screener/criterion-editor.tsx +4 -16
  115. package/src/plugins/builtin/equity-screener/headless.ts +4 -2
  116. package/src/plugins/builtin/equity-screener/ideas.ts +67 -3
  117. package/src/plugins/builtin/equity-screener/model.ts +180 -12
  118. package/src/plugins/builtin/equity-screener/pane.tsx +52 -12
  119. package/src/plugins/builtin/equity-screener/screen-check.ts +7 -4
  120. package/src/plugins/builtin/equity-screener/watchlist.ts +33 -0
  121. package/src/plugins/builtin/futures-curve/client.ts +19 -0
  122. package/src/plugins/builtin/futures-curve/headless.ts +52 -13
  123. package/src/plugins/builtin/futures-curve/index.tsx +1 -1
  124. package/src/plugins/builtin/futures-curve/model.ts +77 -6
  125. package/src/plugins/builtin/futures-curve/pane.tsx +19 -3
  126. package/src/plugins/builtin/macro-day/client.ts +41 -0
  127. package/src/plugins/builtin/macro-day/headless.ts +19 -9
  128. package/src/plugins/builtin/macro-day/model.ts +3 -1
  129. package/src/plugins/builtin/market-movers/index.tsx +4 -3
  130. package/src/plugins/builtin/mna/distress/headless.ts +1 -0
  131. package/src/plugins/builtin/perps/pane.tsx +3 -1
  132. package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +17 -0
  133. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +2 -1
  134. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +2 -1
  135. package/src/plugins/builtin/rate-path/headless.ts +24 -10
  136. package/src/plugins/builtin/research/event-model.ts +10 -3
  137. package/src/plugins/builtin/research/events-headless.ts +20 -2
  138. package/src/plugins/builtin/sec/fund-facts.ts +17 -1
  139. package/src/plugins/builtin/sec/index.tsx +1 -1
  140. package/src/plugins/builtin/shared/members-menu.tsx +103 -38
  141. package/src/plugins/builtin/short-interest/publications-model.ts +22 -1
  142. package/src/plugins/builtin/short-interest/publications-pane.tsx +13 -4
  143. package/src/plugins/builtin/short-interest/watch-model.ts +1 -1
  144. package/src/plugins/builtin/time-sales/pane.tsx +3 -2
  145. package/src/plugins/builtin/trace-bonds/client.ts +7 -4
  146. package/src/plugins/builtin/trace-bonds/index.tsx +1 -1
  147. package/src/plugins/builtin/volatility/client.ts +6 -1
  148. package/src/plugins/builtin/volatility/headless.ts +0 -1
  149. package/src/plugins/builtin/yield-curve/curves.ts +15 -0
  150. package/src/plugins/builtin/yield-curve/headless.ts +6 -1
  151. package/src/plugins/builtin/yield-curve/index.tsx +5 -8
  152. package/src/plugins/host-modules.ts +22 -3
  153. package/src/plugins/host-smoke.ts +6 -3
  154. package/src/portfolio/collection-name.ts +19 -0
  155. package/src/renderers/browser/http-proxy-transport.ts +78 -8
  156. package/src/renderers/cloudflare/http-proxy.ts +13 -2
  157. package/src/renderers/cloudflare/proxy-session.ts +47 -24
  158. package/src/renderers/cloudflare/worker.ts +15 -2
  159. package/src/renderers/desktop/geometry.ts +279 -0
  160. package/src/renderers/desktop/screen-setup.ts +246 -0
  161. package/src/renderers/desktop/sequential-window-host.ts +179 -0
  162. package/src/renderers/desktop/test-utils.ts +71 -0
  163. package/src/renderers/desktop/window-controller.ts +433 -0
  164. package/src/renderers/desktop/window-host.ts +70 -0
  165. package/src/renderers/desktop/window-layouts.ts +630 -0
  166. package/src/renderers/dom/data-frames.ts +15 -4
  167. package/src/renderers/electrobun/bun/application-menu/click.ts +1 -0
  168. package/src/renderers/electrobun/bun/application-menu/index.ts +4 -1
  169. package/src/renderers/electrobun/bun/desktop/backend-requests.ts +19 -8
  170. package/src/renderers/electrobun/bun/desktop/backend.ts +320 -19
  171. package/src/renderers/electrobun/bun/desktop/detached-windows.ts +83 -61
  172. package/src/renderers/electrobun/bun/desktop/host-requests.ts +4 -14
  173. package/src/renderers/electrobun/bun/desktop/initialization.ts +30 -11
  174. package/src/renderers/electrobun/bun/desktop/screen-setup-file.ts +55 -0
  175. package/src/renderers/electrobun/bun/desktop/state-broadcaster.ts +44 -8
  176. package/src/renderers/electrobun/bun/desktop/workspace/index.ts +298 -97
  177. package/src/renderers/electrobun/bun/desktop/workspace/requests.ts +44 -6
  178. package/src/renderers/electrobun/bun/index.ts +4 -97
  179. package/src/renderers/electrobun/bun/window/electrobun-window-host.ts +306 -0
  180. package/src/renderers/electrobun/bun/window/focus.ts +0 -25
  181. package/src/renderers/electrobun/bun/window/remembered-frame.ts +4 -82
  182. package/src/renderers/electrobun/shared/protocol.ts +44 -2
  183. package/src/renderers/electrobun/view/backend-rpc.ts +15 -0
  184. package/src/renderers/electrobun/view/desktop/window/bridge.ts +63 -3
  185. package/src/renderers/electrobun/view/main.tsx +13 -7
  186. package/src/series/fred-argument.ts +17 -0
  187. package/src/sources/provider-router/financial-routes.ts +7 -1
  188. package/src/state/app/context/index.tsx +16 -2
  189. package/src/state/desktop-windows.ts +63 -0
  190. package/src/sync/other-window-tabs.ts +62 -0
  191. package/src/tickers/company-name-listing.ts +23 -3
  192. package/src/tickers/listing-fate.ts +147 -1
  193. package/src/tickers/terminal-codes.ts +5 -0
  194. package/src/time-series/types.ts +6 -0
  195. package/src/types/config.ts +10 -1
  196. package/src/types/desktop-window.ts +71 -2
  197. package/src/types/financials.ts +4 -0
  198. package/src/types/headless.ts +19 -0
  199. package/src/types/plugin.ts +6 -0
  200. package/src/ui/index.tsx +14 -13
  201. package/src/ui/same-props.ts +58 -0
  202. package/src/utils/cli-output.ts +33 -4
  203. package/src/utils/format.ts +7 -2
  204. package/src/utils/futures-generic.ts +12 -0
  205. package/src/utils/http-proxy-upstream.ts +6 -2
  206. package/src/utils/plugin-proxy-hosts.json +0 -4
  207. package/src/utils/plugin-proxy-hosts.ts +22 -0
  208. package/src/utils/sec-filings.ts +7 -1
@@ -6,6 +6,70 @@ import {
6
6
  import type { HttpFetchTransport } from "../../utils/http-transport";
7
7
  import { HTTP_PROXY_PATH, isProxiedHost, PROXY_ALLOWED_HOSTS } from "../../utils/plugin-proxy-hosts";
8
8
 
9
+ /** Thrown when the worker refuses or cannot complete a proxied request. */
10
+ class ProxyRefusedError extends Error {
11
+ constructor(message: string, readonly status: number) {
12
+ super(message);
13
+ this.name = "ProxyRefusedError";
14
+ }
15
+ }
16
+
17
+ const UNREACHABLE = "The data source could not be reached. Check your connection and try again.";
18
+ const UNREADABLE = "The data source's answer could not be read. Try again shortly.";
19
+ /** Longer than any sentence the worker writes; anything past it is not one of them. */
20
+ const MAX_REFUSAL_LENGTH = 160;
21
+
22
+ /**
23
+ * The sentence a pane shows for a refusal. The worker answers with
24
+ * `{ error }` in plain words; anything else (an edge error page, a body cut
25
+ * short, a message that is not one short line) gets a sentence for its
26
+ * status, never the raw body.
27
+ */
28
+ async function refusalMessage(response: Response): Promise<string> {
29
+ const body = await response.json().catch(() => null) as { error?: unknown } | null;
30
+ const error = typeof body?.error === "string" ? body.error.trim() : "";
31
+ if (error && error.length <= MAX_REFUSAL_LENGTH && !/[{}<>\n]/.test(error)) return error;
32
+ if (response.status === 429) return "Too many requests right now. Try again in a minute.";
33
+ if (response.status >= 500) return "The data source could not be reached. Try again shortly.";
34
+ return "This request could not be completed.";
35
+ }
36
+
37
+ function isEnvelope(value: unknown): value is HttpProxyResponseEnvelope {
38
+ if (!value || typeof value !== "object") return false;
39
+ const { status, headers, body } = value as Partial<HttpProxyResponseEnvelope>;
40
+ return typeof status === "number" && !!headers && typeof headers === "object" && typeof body === "string";
41
+ }
42
+
43
+ /**
44
+ * A request that never got an answer fails with the browser's own words
45
+ * ("Failed to fetch", "Load failed"), which a pane would print as they are.
46
+ * It becomes a sentence instead, keeping the original as `cause` for code
47
+ * that classifies network failures. A caller's abort or timeout stays as it
48
+ * was, since callers check for those by name.
49
+ */
50
+ async function answered(request: () => Promise<Response>, signal: AbortSignal | null | undefined): Promise<Response> {
51
+ try {
52
+ return await request();
53
+ } catch (error) {
54
+ const name = (error as { name?: unknown } | null)?.name;
55
+ if (signal?.aborted || name === "AbortError" || name === "TimeoutError") throw error;
56
+ throw new Error(UNREACHABLE, { cause: error });
57
+ }
58
+ }
59
+
60
+ /**
61
+ * A browser owns `User-Agent`. Chrome drops one set by script, but Firefox
62
+ * sends it, which turns a simple cross-origin GET into a preflight that some
63
+ * of the hosts called directly do not allow. Every browser leaves it out.
64
+ */
65
+ function withoutUserAgent(init: RequestInit | undefined): RequestInit | undefined {
66
+ if (!init?.headers) return init;
67
+ const headers = new Headers(init.headers);
68
+ if (!headers.has("user-agent")) return init;
69
+ headers.delete("user-agent");
70
+ return { ...init, headers };
71
+ }
72
+
9
73
  function needsProxy(url: string, hosts: readonly string[]): boolean {
10
74
  try {
11
75
  const target = new URL(url, typeof location === "undefined" ? undefined : location.href);
@@ -36,20 +100,26 @@ export function createBrowserHttpProxyTransport(
36
100
  hosts: readonly string[] = PROXY_ALLOWED_HOSTS,
37
101
  ): HttpFetchTransport {
38
102
  return async function proxiedFetch(url: string, init?: RequestInit): Promise<Response> {
39
- if (!needsProxy(url, hosts)) return send(url, init);
103
+ if (!needsProxy(url, hosts)) return answered(() => send(url, withoutUserAgent(init)), init?.signal);
40
104
 
41
- const proxied = await send(HTTP_PROXY_PATH, {
105
+ const envelope = await toRequestEnvelope(url, init);
106
+ const proxied = await answered(() => send(HTTP_PROXY_PATH, {
42
107
  method: "POST",
43
108
  headers: { "content-type": "application/json" },
44
109
  credentials: "include",
45
110
  signal: init?.signal ?? null,
46
- body: JSON.stringify(await toRequestEnvelope(url, init)),
47
- });
111
+ body: JSON.stringify(envelope),
112
+ }), init?.signal);
48
113
 
49
- if (!proxied.ok) {
50
- const detail = await proxied.text().catch(() => "");
51
- throw new Error(`Plugin request was refused (${proxied.status}). ${detail}`.trim());
114
+ if (!proxied.ok) throw new ProxyRefusedError(await refusalMessage(proxied), proxied.status);
115
+ // A 200 that is not an envelope (an HTML page from a route that is not
116
+ // the worker's) would otherwise surface as a JSON SyntaxError quoting it.
117
+ const answer = await proxied.json().catch(() => null);
118
+ if (!isEnvelope(answer)) throw new ProxyRefusedError(UNREADABLE, proxied.status);
119
+ try {
120
+ return createProxyResponse(answer);
121
+ } catch {
122
+ throw new ProxyRefusedError(UNREADABLE, proxied.status);
52
123
  }
53
- return createProxyResponse(await proxied.json() as HttpProxyResponseEnvelope);
54
124
  };
55
125
  }
@@ -25,6 +25,13 @@ import { fetchCheckingRedirects, readBytesWithin, type ProxyUpstreamResult } fro
25
25
  import type { ProxySessionGate } from "./proxy-session";
26
26
 
27
27
  const PROXY_METHODS = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]);
28
+ /**
29
+ * What a caller without a confirmed session may send. The functions that work
30
+ * signed out only read (a POST carries a search, as FINRA's tape does), and
31
+ * the Origin check is no barrier to a script, so anonymous use stays a
32
+ * read-only proxy to the allowlisted hosts.
33
+ */
34
+ const ANONYMOUS_METHODS = new Set(["GET", "HEAD", "POST"]);
28
35
  const MAX_BODY_BYTES = 5 * 1024 * 1024;
29
36
  /** Plugin request bodies are small JSON; anything near this is not one. */
30
37
  const MAX_REQUEST_BYTES = 1024 * 1024;
@@ -74,13 +81,14 @@ function proxyError(message: string, status: number, headers: Record<string, str
74
81
  return Response.json({ error: message }, { status, headers: { "cache-control": "no-store", ...headers } });
75
82
  }
76
83
 
84
+ /** The pane shows `error` as is, so it says what happened in plain words. */
77
85
  function upstreamFailure(error: unknown): Response {
78
86
  const timedOut = error instanceof Error && error.name === "TimeoutError";
79
- return proxyError(timedOut ? "The upstream request timed out." : "The upstream request failed.", 504);
87
+ return proxyError(timedOut ? "The data source timed out. Try again shortly." : "The data source could not be reached. Try again shortly.", 504);
80
88
  }
81
89
 
82
90
  export interface HttpProxyOptions {
83
- /** Confirms the caller is signed in. One per isolate, so its cache is shared. */
91
+ /** Rate limits the caller, by user when signed in. One per isolate, so its cache is shared. */
84
92
  sessions: ProxySessionGate;
85
93
  /** Reaches the Gloomberb API for that check. */
86
94
  fetchApi: (request: Request) => Promise<Response>;
@@ -134,6 +142,9 @@ export async function handleHttpProxy(request: Request, options: HttpProxyOption
134
142
  if (!PROXY_METHODS.has(init.method)) {
135
143
  return proxyError("Method not allowed", 405);
136
144
  }
145
+ if (!admission.signedIn && !ANONYMOUS_METHODS.has(init.method)) {
146
+ return proxyError("Sign in to Gloom to send this request.", 401);
147
+ }
137
148
 
138
149
  const signal = AbortSignal.timeout(Math.min(init.timeoutMs ?? DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS));
139
150
  let result: ProxyUpstreamResult;
@@ -1,11 +1,15 @@
1
1
  /**
2
- * Who may use the plugin HTTP proxy: a signed-in Gloomberb session, confirmed
3
- * by the API rather than by the cookie merely being present.
2
+ * How much of the plugin HTTP proxy a caller gets. Everyone may use it, since
3
+ * the functions behind it show free public data that works signed out on the
4
+ * desktop too; what differs is the rate limit. A signed-in Gloomberb session,
5
+ * confirmed by the API rather than by the cookie merely being present, is
6
+ * counted per user. Everyone else, including a session the API rejects or
7
+ * cannot confirm right now, is counted per IP address against a smaller
8
+ * window, so a failed check never grants more than signing out would.
4
9
  *
5
10
  * Plugin panes fire requests in bursts, so a confirmed session is remembered
6
11
  * for a minute per isolate and concurrent requests share one check. A session
7
- * the API rejects is not remembered, so signing in again works at once. When
8
- * the API cannot answer, the proxy refuses rather than guessing.
12
+ * the API rejects is not remembered, so signing in again works at once.
9
13
  *
10
14
  * The cache is keyed by the exact cookies that were confirmed, but the rate
11
15
  * limit is keyed by the user the API named. The API reads only part of those
@@ -42,6 +46,12 @@ const SHARED_CHECK_GRACE_MS = 500;
42
46
  * stopping a script from turning one account into a free proxy.
43
47
  */
44
48
  const DEFAULT_REQUESTS_PER_WINDOW = 300;
49
+ /**
50
+ * Per IP address, per isolate, for callers without a confirmed session. A
51
+ * signed-out layout of the heaviest proxied panes (prediction markets, bond
52
+ * tape, Treasury, halts) stays well under this; a script does not.
53
+ */
54
+ const DEFAULT_ANONYMOUS_REQUESTS_PER_WINDOW = 240;
45
55
  const DEFAULT_WINDOW_MS = 60_000;
46
56
  /**
47
57
  * Confirmed cookie variants one user may hold in the cache at once. A user
@@ -69,7 +79,8 @@ interface RateWindow {
69
79
  }
70
80
 
71
81
  type ProxyAdmission =
72
- | { ok: true }
82
+ /** `signedIn` is true only for a session the API confirmed. */
83
+ | { ok: true; signedIn: boolean }
73
84
  | { ok: false; status: number; error: string; retryAfterSeconds?: number };
74
85
 
75
86
  export interface ProxySessionGate {
@@ -84,16 +95,26 @@ export interface ProxySessionGateOptions {
84
95
  maxEntries?: number;
85
96
  maxEntriesPerUser?: number;
86
97
  requestsPerWindow?: number;
98
+ anonymousRequestsPerWindow?: number;
87
99
  windowMs?: number;
88
100
  checkTimeoutMs?: number;
89
101
  }
90
102
 
91
- const SIGN_IN: ProxyAdmission = { ok: false, status: 401, error: "Sign in to use plugin requests." };
92
- const UNAVAILABLE: ProxyAdmission = {
93
- ok: false,
94
- status: 503,
95
- error: "Could not confirm your session right now. Try again shortly.",
96
- };
103
+ /**
104
+ * The window an anonymous caller is counted in. Cloudflare sets
105
+ * `cf-connecting-ip` on every request that reaches the worker. An IPv6 caller
106
+ * is counted by its /64, the block one subscriber is usually handed, so
107
+ * rotating through it does not open fresh windows.
108
+ */
109
+ function anonymousRateKey(request: Request): string {
110
+ const ip = request.headers.get("cf-connecting-ip")?.trim().toLowerCase() ?? "";
111
+ if (!ip.includes(":")) return `ip:${ip || "unknown"}`;
112
+ const [head = "", tail] = ip.split("::", 2);
113
+ const front = head ? head.split(":") : [];
114
+ const back = tail === undefined ? [] : tail ? tail.split(":") : [];
115
+ const groups = tail === undefined ? front : [...front, ...Array(Math.max(0, 8 - front.length - back.length)).fill("0"), ...back];
116
+ return `ip6:${groups.slice(0, 4).map((group) => group.replace(/^0+(?=.)/, "")).join(":")}`;
117
+ }
97
118
 
98
119
  /** The session cookies (and `dont_remember`) from a Cookie header, in order. */
99
120
  function forwardedCookies(header: string | null): string | null {
@@ -186,13 +207,18 @@ export function createProxySessionGate(options: ProxySessionGateOptions): ProxyS
186
207
  const maxEntries = options.maxEntries ?? DEFAULT_MAX_ENTRIES;
187
208
  const maxEntriesPerUser = Math.max(1, options.maxEntriesPerUser ?? DEFAULT_MAX_ENTRIES_PER_USER);
188
209
  const requestsPerWindow = options.requestsPerWindow ?? DEFAULT_REQUESTS_PER_WINDOW;
210
+ const anonymousRequestsPerWindow = options.anonymousRequestsPerWindow ?? DEFAULT_ANONYMOUS_REQUESTS_PER_WINDOW;
189
211
  const windowMs = options.windowMs ?? DEFAULT_WINDOW_MS;
190
212
  const checkTimeoutMs = options.checkTimeoutMs ?? DEFAULT_CHECK_TIMEOUT_MS;
191
213
  const sharedWaitMs = checkTimeoutMs + SHARED_CHECK_GRACE_MS;
192
214
  /** Cookie key to whose session it is and when that stops being trusted. */
193
215
  const confirmed = new Map<string, Confirmation>();
194
216
  const pending = new Map<string, PendingCheck>();
195
- /** Keyed by user id, not cookie, so every variant of a session shares one window. */
217
+ /**
218
+ * Keyed by user id, not cookie, so every variant of a session shares one
219
+ * window, or by address for anonymous callers. The prefixes keep the two
220
+ * apart.
221
+ */
196
222
  const windows = new Map<string, RateWindow>();
197
223
 
198
224
  /** Remembers `key` for `userId`, first dropping that user's oldest variants past the per-user cap. */
@@ -237,21 +263,21 @@ export function createProxySessionGate(options: ProxySessionGateOptions): ProxyS
237
263
  return verdict;
238
264
  }
239
265
 
240
- function withinRate(userId: string): ProxyAdmission {
266
+ function withinRate(windowKey: string, limit: number, signedIn: boolean): ProxyAdmission {
241
267
  const at = now();
242
- let window = windows.get(userId);
268
+ let window = windows.get(windowKey);
243
269
  if (!window || at - window.startedAt >= windowMs) {
244
- windows.delete(userId);
270
+ windows.delete(windowKey);
245
271
  makeRoom(windows, maxEntries, (entry) => at - entry.startedAt >= windowMs);
246
272
  window = { startedAt: at, count: 0 };
247
- windows.set(userId, window);
273
+ windows.set(windowKey, window);
248
274
  }
249
275
  window.count += 1;
250
- if (window.count <= requestsPerWindow) return { ok: true };
276
+ if (window.count <= limit) return { ok: true, signedIn };
251
277
  return {
252
278
  ok: false,
253
279
  status: 429,
254
- error: "Too many plugin requests. Try again in a minute.",
280
+ error: "Too many requests right now. Try again in a minute.",
255
281
  retryAfterSeconds: Math.max(1, Math.ceil((window.startedAt + windowMs - at) / 1_000)),
256
282
  };
257
283
  }
@@ -259,12 +285,9 @@ export function createProxySessionGate(options: ProxySessionGateOptions): ProxyS
259
285
  return {
260
286
  async admit(request, fetchApi) {
261
287
  const cookie = forwardedCookies(request.headers.get("cookie"));
262
- if (!cookie) return SIGN_IN;
263
- const key = await cacheKey(cookie);
264
- const verdict = await verdictFor(key, cookie, request, fetchApi);
265
- if (verdict === "invalid") return SIGN_IN;
266
- if (verdict === "unavailable") return UNAVAILABLE;
267
- return withinRate(verdict.userId);
288
+ const verdict = cookie ? await verdictFor(await cacheKey(cookie), cookie, request, fetchApi) : "invalid";
289
+ if (typeof verdict === "object") return withinRate(`user:${verdict.userId}`, requestsPerWindow, true);
290
+ return withinRate(anonymousRateKey(request), anonymousRequestsPerWindow, false);
268
291
  },
269
292
  };
270
293
  }
@@ -1,6 +1,6 @@
1
1
  import { handleHttpProxy } from "./http-proxy";
2
2
  import { createProxySessionGate } from "./proxy-session";
3
- import { HTTP_PROXY_PATH } from "../../utils/plugin-proxy-hosts";
3
+ import { HTTP_PROXY_PATH, WEB_DIRECT_HOSTS } from "../../utils/plugin-proxy-hosts";
4
4
 
5
5
  interface StaticAssetsBinding {
6
6
  fetch(request: Request): Promise<Response>;
@@ -70,8 +70,21 @@ type ApiFetch = (request: Request) => Promise<Response>;
70
70
  /** Module scope, so every request this isolate serves shares one session cache. */
71
71
  const proxySessions = createProxySessionGate({ sessionUrl: `${API_ORIGIN}/auth/get-session` });
72
72
 
73
+ /**
74
+ * What the page may fetch: itself (the API and the plugin proxy are both
75
+ * same-origin), the app's own hosts, and the plugin hosts the browser calls
76
+ * directly. Every other plugin host goes through the proxy.
77
+ */
78
+ const CONNECT_SRC = [
79
+ "'self'",
80
+ "https://api.github.com",
81
+ "https://plugins.gloom.sh",
82
+ "https://gloom.sh",
83
+ ...WEB_DIRECT_HOSTS.map((host) => `https://${host}`),
84
+ ].join(" ");
85
+
73
86
  export const SECURITY_HEADERS = {
74
- "content-security-policy": "default-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; media-src 'self' https:; connect-src 'self' https://api.github.com https://api.fiscaldata.treasury.gov https://plugins.gloom.sh https://gloom.sh; form-action 'self'; upgrade-insecure-requests",
87
+ "content-security-policy": `default-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; media-src 'self' https:; connect-src ${CONNECT_SRC}; form-action 'self'; upgrade-insecure-requests`,
75
88
  "cross-origin-opener-policy": "same-origin",
76
89
  "cross-origin-resource-policy": "same-origin",
77
90
  "permissions-policy": "camera=(), geolocation=(), microphone=(), payment=(), usb=()",
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Screens and window frames for the desktop app, in the coordinates the
3
+ * shell reports them in: one virtual desktop where every display has its
4
+ * place. Nothing here talks to a shell; the window host does (window-host.ts).
5
+ */
6
+
7
+ export interface Rect {
8
+ x: number;
9
+ y: number;
10
+ width: number;
11
+ height: number;
12
+ }
13
+
14
+ export interface DesktopDisplay {
15
+ /** The shell's id. It can change when a display is plugged in again, so placements never key on it. */
16
+ id: string;
17
+ bounds: Rect;
18
+ /** The bounds less the menu bar, Dock or task bar. */
19
+ workArea: Rect;
20
+ scaleFactor: number;
21
+ primary: boolean;
22
+ }
23
+
24
+ /** How much of a title bar has to sit on a screen for a window to count as reachable: enough to grab and drag. */
25
+ const REACHABLE_STRIP_HEIGHT = 24;
26
+ const REACHABLE_STRIP_WIDTH = 96;
27
+ /**
28
+ * How far past a screen's edge a frame may reach and still count as on it:
29
+ * shadows and the invisible resize borders Windows counts in a frame.
30
+ */
31
+ const EDGE_SLACK = 8;
32
+
33
+ function finite(value: number): number {
34
+ return Number.isFinite(value) ? Math.round(value) : 0;
35
+ }
36
+
37
+ export function sameRect(a: Rect | null | undefined, b: Rect | null | undefined): boolean {
38
+ if (!a || !b) return a === b;
39
+ return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
40
+ }
41
+
42
+ export function isUsableRect(rect: Rect | null | undefined): rect is Rect {
43
+ return !!rect
44
+ && [rect.x, rect.y, rect.width, rect.height].every((value) => typeof value === "number" && Number.isFinite(value))
45
+ && rect.width >= 1
46
+ && rect.height >= 1;
47
+ }
48
+
49
+ /** Displays the shell reported with a real size, primary first and then left to right, top to bottom. */
50
+ export function usableDisplays(displays: readonly DesktopDisplay[]): DesktopDisplay[] {
51
+ return displays
52
+ .filter((display) => isUsableRect(display.bounds) && isUsableRect(display.workArea))
53
+ .sort((a, b) => (
54
+ Number(b.primary) - Number(a.primary)
55
+ || a.bounds.x - b.bounds.x
56
+ || a.bounds.y - b.bounds.y
57
+ ));
58
+ }
59
+
60
+ /**
61
+ * One display, as placements remember it: where it sits, its size and its
62
+ * scale. A display unplugged and plugged back in the same place gets the
63
+ * same key, whatever id the shell gives it.
64
+ */
65
+ export function displayKey(display: DesktopDisplay): string {
66
+ const { x, y, width, height } = display.bounds;
67
+ const scale = Math.round((display.scaleFactor || 1) * 100) / 100;
68
+ return `${finite(x)},${finite(y)} ${finite(width)}x${finite(height)}@${scale}`;
69
+ }
70
+
71
+ /**
72
+ * The monitor arrangement a screen setup is saved under: every display's
73
+ * key, in a fixed order. Moving, adding or removing a display, or changing
74
+ * its resolution or scale, makes another arrangement.
75
+ */
76
+ export function arrangementKey(displays: readonly DesktopDisplay[]): string {
77
+ const keys = usableDisplays(displays).map(displayKey).sort();
78
+ return keys.length > 0 ? keys.join(" | ") : "none";
79
+ }
80
+
81
+ function overlapArea(a: Rect, b: Rect): number {
82
+ const width = Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x);
83
+ const height = Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y);
84
+ return width > 0 && height > 0 ? width * height : 0;
85
+ }
86
+
87
+ function clamp(value: number, min: number, max: number): number {
88
+ return Math.min(max, Math.max(min, value));
89
+ }
90
+
91
+ /** The display a frame is on: the one holding its centre, else the one it overlaps most. Null when it is on none. */
92
+ export function displayForFrame(frame: Rect, displays: readonly DesktopDisplay[]): DesktopDisplay | null {
93
+ const usable = usableDisplays(displays);
94
+ const centerX = frame.x + frame.width / 2;
95
+ const centerY = frame.y + frame.height / 2;
96
+ const containing = usable.find(({ bounds }) => (
97
+ centerX >= bounds.x && centerX < bounds.x + bounds.width
98
+ && centerY >= bounds.y && centerY < bounds.y + bounds.height
99
+ ));
100
+ if (containing) return containing;
101
+ let best: DesktopDisplay | null = null;
102
+ let bestArea = 0;
103
+ for (const display of usable) {
104
+ const area = overlapArea(frame, display.bounds);
105
+ if (area > bestArea) {
106
+ best = display;
107
+ bestArea = area;
108
+ }
109
+ }
110
+ return best;
111
+ }
112
+
113
+ /**
114
+ * Whether a person can reach the window to move it: a stretch of its title
115
+ * bar lies in some display's work area, not under the menu bar or off the
116
+ * edge of every screen.
117
+ */
118
+ export function isFrameReachable(frame: Rect, displays: readonly DesktopDisplay[]): boolean {
119
+ const titleBar: Rect = { x: frame.x, y: frame.y, width: frame.width, height: REACHABLE_STRIP_HEIGHT };
120
+ return usableDisplays(displays).some(({ workArea }) => {
121
+ const width = Math.min(titleBar.x + titleBar.width, workArea.x + workArea.width) - Math.max(titleBar.x, workArea.x);
122
+ const height = Math.min(titleBar.y + titleBar.height, workArea.y + workArea.height) - Math.max(titleBar.y, workArea.y);
123
+ return width >= Math.min(REACHABLE_STRIP_WIDTH, frame.width) && height >= Math.min(REACHABLE_STRIP_HEIGHT, frame.height);
124
+ });
125
+ }
126
+
127
+ /**
128
+ * Whether a window is on screen: all of it lies on the connected displays
129
+ * (across two of them counts), give or take its shadow, and its title bar
130
+ * sits in a work area where it can be grabbed.
131
+ */
132
+ export function isFrameVisible(frame: Rect, displays: readonly DesktopDisplay[]): boolean {
133
+ const usable = usableDisplays(displays);
134
+ const insetX = Math.min(EDGE_SLACK, Math.floor(frame.width / 4));
135
+ const insetY = Math.min(EDGE_SLACK, Math.floor(frame.height / 4));
136
+ const inner: Rect = {
137
+ x: frame.x + insetX,
138
+ y: frame.y + insetY,
139
+ width: frame.width - insetX * 2,
140
+ height: frame.height - insetY * 2,
141
+ };
142
+ // Mirrored displays share their bounds: count each place once.
143
+ const places = new Set<string>();
144
+ let covered = 0;
145
+ for (const { bounds } of usable) {
146
+ const place = `${bounds.x},${bounds.y},${bounds.width},${bounds.height}`;
147
+ if (places.has(place)) continue;
148
+ places.add(place);
149
+ covered += overlapArea(inner, bounds);
150
+ }
151
+ return covered >= inner.width * inner.height - 1 && isFrameReachable(frame, usable);
152
+ }
153
+
154
+ /** The display closest to a frame on none: the shortest way from its centre to a work area. */
155
+ function nearestDisplay(frame: Rect, displays: readonly DesktopDisplay[]): DesktopDisplay | null {
156
+ const centerX = frame.x + frame.width / 2;
157
+ const centerY = frame.y + frame.height / 2;
158
+ let best: DesktopDisplay | null = null;
159
+ let bestDistance = Infinity;
160
+ for (const display of displays) {
161
+ const area = display.workArea;
162
+ const dx = Math.max(area.x - centerX, 0, centerX - (area.x + area.width));
163
+ const dy = Math.max(area.y - centerY, 0, centerY - (area.y + area.height));
164
+ const distance = dx * dx + dy * dy;
165
+ if (distance < bestDistance) {
166
+ best = display;
167
+ bestDistance = distance;
168
+ }
169
+ }
170
+ return best;
171
+ }
172
+
173
+ /** A frame inside a work area, moved as little as it takes and shrunk to it when bigger. */
174
+ function fitFrameInArea(frame: Rect, area: Rect): Rect {
175
+ const width = Math.min(Math.round(frame.width), area.width);
176
+ const height = Math.min(Math.round(frame.height), area.height);
177
+ return {
178
+ x: clamp(Math.round(frame.x), area.x, area.x + area.width - width),
179
+ y: clamp(Math.round(frame.y), area.y, area.y + area.height - height),
180
+ width,
181
+ height,
182
+ };
183
+ }
184
+
185
+ /**
186
+ * Puts a window on a screen. One already on screen stays as it is. Any
187
+ * other moves onto the display it is mostly on, or the nearest one, by as
188
+ * little as it takes to lie in that display's work area, shrinking to it
189
+ * when it is bigger. Shells do not do this themselves: asked to open a
190
+ * window past a screen's edge, Electrobun leaves it there.
191
+ */
192
+ export function clampFrameToScreens(frame: Rect, displays: readonly DesktopDisplay[]): Rect {
193
+ const usable = usableDisplays(displays);
194
+ if (usable.length === 0 || isFrameVisible(frame, usable)) return frame;
195
+ const display = displayForFrame(frame, usable) ?? nearestDisplay(frame, usable) ?? usable[0]!;
196
+ return fitFrameInArea(frame, display.workArea);
197
+ }
198
+
199
+ /** A display as `displayKey` wrote it, for a placement saved under screens that are not all connected now. */
200
+ export function displayFromKey(key: string): DesktopDisplay | null {
201
+ const match = /^(-?\d+),(-?\d+) (\d+)x(\d+)@([\d.]+)$/.exec(key);
202
+ if (!match) return null;
203
+ const bounds = { x: Number(match[1]), y: Number(match[2]), width: Number(match[3]), height: Number(match[4]) };
204
+ if (!isUsableRect(bounds)) return null;
205
+ return { id: "", bounds, workArea: bounds, scaleFactor: Number(match[5]) || 1, primary: false };
206
+ }
207
+
208
+ /**
209
+ * The connected display a display that is gone became: the one at the same
210
+ * place (a new resolution keeps a screen's corner), else the one with its id.
211
+ */
212
+ function sameScreen(display: DesktopDisplay, displays: readonly DesktopDisplay[]): DesktopDisplay | null {
213
+ const { x, y } = display.bounds;
214
+ return displays.find(({ bounds }) => bounds.x === x && bounds.y === y)
215
+ ?? (display.id ? displays.find(({ id }) => id === display.id) : undefined)
216
+ ?? null;
217
+ }
218
+
219
+ /**
220
+ * Where a window that sat on `from` goes on the displays connected now,
221
+ * always on screen. Its display still there: where it was. The same screen
222
+ * at another resolution or place: the same place on it, in proportion.
223
+ * Its display gone: the same place in proportion on `fallback`. On no
224
+ * display at all: onto the nearest one.
225
+ */
226
+ export function relocateFrame(
227
+ frame: Rect,
228
+ from: DesktopDisplay | null,
229
+ displays: readonly DesktopDisplay[],
230
+ fallback: DesktopDisplay,
231
+ ): Rect {
232
+ const usable = usableDisplays(displays);
233
+ if (!from || usable.some((display) => displayKey(display) === displayKey(from))) {
234
+ return clampFrameToScreens(frame, usable);
235
+ }
236
+ const target = sameScreen(from, usable) ?? fallback;
237
+ return clampFrameToScreens(moveFrameToDisplay(frame, from, target), usable);
238
+ }
239
+
240
+ /**
241
+ * A window moving from one display to another keeps its place on the screen
242
+ * in proportion: a window on the right half of the old display lands on the
243
+ * right half of the new one, at the same size where it fits.
244
+ */
245
+ export function moveFrameToDisplay(frame: Rect, from: DesktopDisplay | null, to: DesktopDisplay): Rect {
246
+ const area = to.workArea;
247
+ const width = Math.min(frame.width, area.width);
248
+ const height = Math.min(frame.height, area.height);
249
+ if (!from) {
250
+ return {
251
+ x: area.x + Math.round((area.width - width) / 2),
252
+ y: area.y + Math.round((area.height - height) / 2),
253
+ width,
254
+ height,
255
+ };
256
+ }
257
+ const source = from.workArea;
258
+ const slackX = Math.max(0, source.width - frame.width);
259
+ const slackY = Math.max(0, source.height - frame.height);
260
+ const fractionX = slackX > 0 ? clamp((frame.x - source.x) / slackX, 0, 1) : 0.5;
261
+ const fractionY = slackY > 0 ? clamp((frame.y - source.y) / slackY, 0, 1) : 0;
262
+ return {
263
+ x: area.x + Math.round((area.width - width) * fractionX),
264
+ y: area.y + Math.round((area.height - height) * fractionY),
265
+ width,
266
+ height,
267
+ };
268
+ }
269
+
270
+ /** A frame `step` points down and to the right of `frame`, wrapped back to the work area's corner when it would leave it. */
271
+ export function cascadeFrame(frame: Rect, display: DesktopDisplay, step = 32): Rect {
272
+ const area = display.workArea;
273
+ const width = Math.min(frame.width, area.width);
274
+ const height = Math.min(frame.height, area.height);
275
+ const x = frame.x + step;
276
+ const y = frame.y + step;
277
+ const fits = x + width <= area.x + area.width && y + height <= area.y + area.height;
278
+ return fitFrameInArea(fits ? { x, y, width, height } : { x: area.x + step, y: area.y + step, width, height }, area);
279
+ }