Add dev CORS proxy and selectable Bitcoin price source

This commit is contained in:
raucao committed 2026-10-02 13:33:08 +02:00
1 parent 427d97da77
commit a57336351d
14 files changed
+591 -116

No files matched your search

+14
View File
@@ -24,6 +24,20 @@ You will need the following things properly installed on your computer.
- Visit your app at [http://localhost:4200](http://localhost:4200).
- Visit your tests at [http://localhost:4200/tests](http://localhost:4200/tests).
### Development CORS proxy
`pnpm start` also launches a small local CORS proxy (`cors-anywhere`) on
`http://localhost:8081/`, tied to the Vite dev server lifecycle. This lets
cross-origin requests (e.g. Discourse notifications, the Bitcoin ticker) work
when opening the app directly in a browser, without a third-party proxy.
- It is bound to `127.0.0.1` and only accepts requests from the app origin that
include the `X-Dashtab-Proxy` header, so it cannot be abused as an open proxy.
- Override the address/port with `DASHTAB_CORS_PROXY` (the base URL the client
uses) and `DASHTAB_CORS_PROXY_PORT` (the port the server binds).
- It is only active in development; production relies on the browser extension's
host permissions.
### Firefox dev extension
The `extension/` directory is a temporary MV3 shell that overrides the Firefox
@@ -3,29 +3,42 @@ import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { service } from '@ember/service';
import { on } from '@ember/modifier';
import SettingsSelect from './select.gjs';
import {
BITCOIN_DEFAULT_INTERVAL,
BITCOIN_DEFAULT_PROVIDER,
BITCOIN_INTERVAL_OPTIONS,
BITCOIN_PROVIDERS,
} from '../../../services/bitcoin';
export default class SettingsAddIntegrationBitcoin extends Component {
@service bitcoin;
@tracked interval = BITCOIN_DEFAULT_INTERVAL;
@tracked provider = BITCOIN_DEFAULT_PROVIDER;
get options() {
get intervalOptions() {
return BITCOIN_INTERVAL_OPTIONS;
}
get providerOptions() {
return BITCOIN_PROVIDERS.map(({ id, label }) => ({ value: id, label }));
}
@action
updateInterval(event) {
this.interval = Number(event.target.value);
updateInterval(value) {
this.interval = Number(value);
}
@action
updateProvider(value) {
this.provider = value;
}
@action
async handleSubmit(event) {
event.preventDefault();
await this.bitcoin.enable(this.interval);
await this.bitcoin.enable(this.interval, this.provider);
this.args.closeDialog();
}
@@ -42,74 +55,24 @@ export default class SettingsAddIntegrationBitcoin extends Component {
</div>
<form {{on "submit" this.handleSubmit}} class="mt-5">
<div>
<label
for="bitcoin-interval"
class="block text-sm/6 font-medium text-gray-900"
>Update interval</label>
<el-select
id="bitcoin-interval"
name="interval"
value="30000"
class="mt-2 block"
{{on "change" this.updateInterval}}
>
<button
type="button"
class="grid w-full cursor-default grid-cols-1 rounded-md bg-white py-1.5 pr-2 pl-3 text-left text-gray-900 outline-1 -outline-offset-1 outline-gray-300 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-indigo-600 sm:text-sm/6"
>
<el-selectedcontent
class="col-start-1 row-start-1 truncate pr-6"
>Every 30 seconds</el-selectedcontent>
<svg
viewBox="0 0 16 16"
fill="currentColor"
data-slot="icon"
aria-hidden="true"
class="col-start-1 row-start-1 size-5 self-center justify-self-end text-gray-500 sm:size-4"
>
<path
d="M5.22 10.22a.75.75 0 0 1 1.06 0L8 11.94l1.72-1.72a.75.75 0 1 1 1.06 1.06l-2.25 2.25a.75.75 0 0 1-1.06 0l-2.25-2.25a.75.75 0 0 1 0-1.06ZM10.78 5.78a.75.75 0 0 1-1.06 0L8 4.06 6.28 5.78a.75.75 0 0 1-1.06-1.06l2.25-2.25a.75.75 0 0 1 1.06 0l2.25 2.25a.75.75 0 0 1 0 1.06Z"
clip-rule="evenodd"
fill-rule="evenodd"
/>
</svg>
</button>
<div class="space-y-5">
<SettingsSelect
@id="bitcoin-provider"
@name="provider"
@label="Price source"
@options={{this.providerOptions}}
@value={{this.provider}}
@onChange={{this.updateProvider}}
/>
<el-options
anchor="bottom start"
popover
class="max-h-60 w-(--button-width) overflow-auto rounded-md bg-white py-1 text-base shadow-lg outline-1 outline-black/5 [--anchor-gap:--spacing(1)] data-leave:transition data-leave:transition-discrete data-leave:duration-100 data-leave:ease-in data-closed:data-leave:opacity-0 sm:text-sm"
>
{{#each this.options as |option|}}
<el-option
value={{option.value}}
class="group/option relative block cursor-default py-2 pr-9 pl-3 text-gray-900 select-none focus:bg-indigo-600 focus:text-white focus:outline-hidden"
>
<span
class="block truncate font-normal group-aria-selected/option:font-semibold"
>{{option.label}}</span>
<span
class="absolute inset-y-0 right-0 flex items-center pr-4 text-indigo-600 group-not-aria-selected/option:hidden group-focus/option:text-white in-[el-selectedcontent]:hidden"
>
<svg
viewBox="0 0 20 20"
fill="currentColor"
data-slot="icon"
aria-hidden="true"
class="size-5"
>
<path
d="M16.704 4.153a.75.75 0 0 1 .143 1.052l-8 10.5a.75.75 0 0 1-1.127.075l-4.5-4.5a.75.75 0 0 1 1.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 0 1 1.05-.143Z"
clip-rule="evenodd"
fill-rule="evenodd"
/>
</svg>
</span>
</el-option>
{{/each}}
</el-options>
</el-select>
<SettingsSelect
@id="bitcoin-interval"
@name="interval"
@label="Update interval"
@options={{this.intervalOptions}}
@value={{this.interval}}
@onChange={{this.updateInterval}}
/>
</div>
<div class="mt-5 sm:mt-6 flex gap-3">
@@ -0,0 +1,90 @@
import Component from '@glimmer/component';
import { action } from '@ember/object';
import { on } from '@ember/modifier';
import setAttribute from '../../../modifiers/set-attribute';
export default class SettingsAddIntegrationSelect extends Component {
get selectedLabel() {
const selected = this.args.options?.find(
(option) => String(option.value) === String(this.args.value)
);
return selected?.label ?? '';
}
@action
handleChange(event) {
this.args.onChange?.(event.target.value);
}
<template>
<div>
<label
for={{@id}}
class="block text-sm/6 font-medium text-gray-900"
>{{@label}}</label>
<el-select
id={{@id}}
name={{@name}}
class="mt-2 block"
{{setAttribute "value" @value}}
{{on "change" this.handleChange}}
>
<button
type="button"
class="grid w-full cursor-default grid-cols-1 rounded-md bg-white py-1.5 pr-2 pl-3 text-left text-gray-900 outline-1 -outline-offset-1 outline-gray-300 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-indigo-600 sm:text-sm/6"
>
<el-selectedcontent
class="col-start-1 row-start-1 truncate pr-6"
>{{this.selectedLabel}}</el-selectedcontent>
<svg
viewBox="0 0 16 16"
fill="currentColor"
data-slot="icon"
aria-hidden="true"
class="col-start-1 row-start-1 size-5 self-center justify-self-end text-gray-500 sm:size-4"
>
<path
d="M5.22 10.22a.75.75 0 0 1 1.06 0L8 11.94l1.72-1.72a.75.75 0 1 1 1.06 1.06l-2.25 2.25a.75.75 0 0 1-1.06 0l-2.25-2.25a.75.75 0 0 1 0-1.06ZM10.78 5.78a.75.75 0 0 1-1.06 0L8 4.06 6.28 5.78a.75.75 0 0 1-1.06-1.06l2.25-2.25a.75.75 0 0 1 1.06 0l2.25 2.25a.75.75 0 0 1 0 1.06Z"
clip-rule="evenodd"
fill-rule="evenodd"
/>
</svg>
</button>
<el-options
anchor="bottom start"
popover
class="max-h-60 w-(--button-width) overflow-auto rounded-md bg-white py-1 text-base shadow-lg outline-1 outline-black/5 [--anchor-gap:--spacing(1)] data-leave:transition data-leave:transition-discrete data-leave:duration-100 data-leave:ease-in data-closed:data-leave:opacity-0 sm:text-sm"
>
{{#each @options as |option|}}
<el-option
value={{option.value}}
class="group/option relative block cursor-default py-2 pr-9 pl-3 text-gray-900 select-none focus:bg-indigo-600 focus:text-white focus:outline-hidden"
>
<span
class="block truncate font-normal group-aria-selected/option:font-semibold"
>{{option.label}}</span>
<span
class="absolute inset-y-0 right-0 flex items-center pr-4 text-indigo-600 group-not-aria-selected/option:hidden group-focus/option:text-white in-[el-selectedcontent]:hidden"
>
<svg
viewBox="0 0 20 20"
fill="currentColor"
data-slot="icon"
aria-hidden="true"
class="size-5"
>
<path
d="M16.704 4.153a.75.75 0 0 1 .143 1.052l-8 10.5a.75.75 0 0 1-1.127.075l-4.5-4.5a.75.75 0 0 1 1.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 0 1 1.05-.143Z"
clip-rule="evenodd"
fill-rule="evenodd"
/>
</svg>
</span>
</el-option>
{{/each}}
</el-options>
</el-select>
</div>
</template>
}
+13
View File
@@ -0,0 +1,13 @@
import { modifier } from 'ember-modifier';
// Sets an attribute (rather than a same-named DOM property). Needed for custom
// elements like `<el-select>` whose `value` property setter runs synchronously
// and requires its children to already be present.
export default modifier((element, [name, value]) => {
if (value === undefined || value === null) {
element.removeAttribute(name);
return;
}
element.setAttribute(name, String(value));
});
+62 -12
View File
@@ -1,9 +1,6 @@
import Service, { service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
export const BITCOIN_TICKER_URL =
'https://cors.5apps.com/?uri=https://www.bitstamp.net/api/v2/ticker/btcusd/';
export const BITCOIN_DEFAULT_INTERVAL = 30000;
export const BITCOIN_INTERVAL_OPTIONS = [
@@ -12,11 +9,55 @@ export const BITCOIN_INTERVAL_OPTIONS = [
{ value: 300000, label: 'Every 5 minutes' },
];
export const BITCOIN_DEFAULT_PROVIDER = 'coingecko';
export const BITCOIN_PROVIDERS = [
{
id: 'coingecko',
label: 'CoinGecko',
url: 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_24hr_change=true',
parse(data) {
return {
price: Number.parseFloat(data.bitcoin.usd),
changePercent: Number.parseFloat(data.bitcoin.usd_24h_change),
};
},
},
{
id: 'binance',
label: 'Binance',
url: 'https://api.binance.com/api/v3/ticker/24hr?symbol=BTCUSDT',
parse(data) {
return {
price: Number.parseFloat(data.lastPrice),
changePercent: Number.parseFloat(data.priceChangePercent),
};
},
},
{
id: 'bitstamp',
label: 'Bitstamp',
url: 'https://cors.5apps.com/?uri=https://www.bitstamp.net/api/v2/ticker/btcusd/',
parse(data) {
return {
price: Number.parseFloat(data.last),
changePercent: Number.parseFloat(data.percent_change_24),
};
},
},
];
function providerFor(id) {
return BITCOIN_PROVIDERS.find((provider) => provider.id === id);
}
export default class BitcoinService extends Service {
@service storage;
@service http;
@tracked enabled = false;
@tracked interval = BITCOIN_DEFAULT_INTERVAL;
@tracked provider = BITCOIN_DEFAULT_PROVIDER;
@tracked price = null;
@tracked changePercent = null;
@tracked loading = false;
@@ -37,6 +78,8 @@ export default class BitcoinService extends Service {
if (integration?.status === 'active') {
this.enabled = true;
this.interval = integration.interval ?? BITCOIN_DEFAULT_INTERVAL;
// Records stored before providers existed used the Bitstamp source.
this.provider = integration.provider ?? 'bitstamp';
this.startPolling();
}
} catch (err) {
@@ -44,16 +87,21 @@ export default class BitcoinService extends Service {
}
}
async enable(interval = BITCOIN_DEFAULT_INTERVAL) {
async enable(
interval = BITCOIN_DEFAULT_INTERVAL,
provider = BITCOIN_DEFAULT_PROVIDER
) {
await this.ready;
this.interval = interval;
this.provider = provider;
this.enabled = true;
await this.storage.set('integrations', 'bitcoin', {
type: 'bitcoin',
status: 'active',
interval,
provider,
currency: 'usd',
createdAt: Date.now(),
});
@@ -66,18 +114,20 @@ export default class BitcoinService extends Service {
return;
}
const provider = providerFor(this.provider);
if (!provider) {
this.error = 'Unable to load the bitcoin price';
return;
}
this.fetching = true;
this.loading = true;
try {
const response = await fetch(BITCOIN_TICKER_URL);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const data = await response.json();
this.price = Number.parseFloat(data.last);
this.changePercent = Number.parseFloat(data.percent_change_24);
const data = await this.http.requestJson(provider.url);
const { price, changePercent } = provider.parse(data);
this.price = price;
this.changePercent = changePercent;
this.error = null;
} catch (err) {
console.error('Error fetching bitcoin price:', err);
+22 -1
View File
@@ -1,4 +1,7 @@
import Service from '@ember/service';
import config from 'dashtab/config/environment';
export const CORS_PROXY_HEADER = 'X-Dashtab-Proxy';
export class HttpError extends Error {
constructor(status) {
@@ -16,16 +19,34 @@ export class NetworkError extends Error {
}
}
// Rewrites an absolute http(s) URL to go through the local development CORS
// proxy. Relative URLs and URLs already pointing at the proxy are untouched.
export function proxiedUrl(url, base) {
if (!base || !/^https?:\/\//i.test(url) || url.startsWith(base)) {
return url;
}
return `${base}${url}`;
}
// Single seam for outbound requests. When Dashtab ships as a browser
// extension, this is the one place that needs to branch to service-worker
// messaging (e.g. chrome.runtime.sendMessage) so privileged cross-origin
// fetches can use the extension's host permissions instead of CORS.
export default class HttpService extends Service {
corsProxyBase = config.corsProxy ?? null;
async requestJson(url, options = {}) {
const target = proxiedUrl(url, this.corsProxyBase);
const headers = { ...(options.headers ?? {}) };
if (target !== url) {
headers[CORS_PROXY_HEADER] = '1';
}
let response;
try {
response = await fetch(url, options);
response = await fetch(target, { ...options, headers });
} catch (err) {
throw new NetworkError(err);
}
+4
View File
@@ -31,6 +31,10 @@ module.exports = function (environment) {
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
// Local development CORS proxy (started by the Vite dev server). Only set
// in development so tests and production requests go out directly.
ENV.corsProxy = process.env.DASHTAB_CORS_PROXY || 'http://localhost:8081/';
}
if (environment === 'test') {
+1
View File
@@ -55,6 +55,7 @@
"@tailwindplus/elements": "^1.0.22",
"babel-plugin-ember-template-compilation": "^4.0.0",
"concurrently": "^10.0.5",
"cors-anywhere": "^0.4.4",
"decorator-transforms": "^2.4.0",
"ember-auto-import": "^2.13.1",
"ember-cli": "~7.3.0",
+37 -10
View File
@@ -74,6 +74,9 @@ importers:
concurrently:
specifier: ^10.0.5
version: 10.0.5
cors-anywhere:
specifier: ^0.4.4
version: 0.4.4
decorator-transforms:
specifier: ^2.4.0
version: 2.4.0(@babel/core@7.29.7(supports-color@10.2.2))
@@ -2799,6 +2802,10 @@ packages:
core-util-is@1.0.3:
resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}
cors-anywhere@0.4.4:
resolution: {integrity: sha512-8OBFwnzMgR4mNrAeAyOLB2EruS2z7u02of2bOu7i9kKYlZG+niS7CTHLPgEXKWW2NAOJWRry9RRCaL9lJRjNqg==}
engines: {node: '>=0.10.0'}
cors@2.8.6:
resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==}
engines: {node: '>= 0.10'}
@@ -3422,6 +3429,9 @@ packages:
resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==}
engines: {node: '>= 0.6'}
eventemitter3@1.2.0:
resolution: {integrity: sha512-DOFqA1MF46fmZl2xtzXR3MPCRsXqgoFqdXcrCVYM3JNnfUeHTm/fh/v/iU7gBFpwkuBmoJPAm5GuhdDfSEJMJA==}
eventemitter3@4.0.7:
resolution: {integrity: sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==}
@@ -3950,6 +3960,10 @@ packages:
resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==}
engines: {node: '>= 14'}
http-proxy@1.11.1:
resolution: {integrity: sha512-qz7jZarkVG3G6GMq+4VRJPSN4NkIjL4VMTNhKGd8jc25BumeJjWWvnY3A7OkCGa8W1TTxbaK3dcE0ijFalITVA==}
engines: {node: '>=0.10.0'}
http-proxy@1.18.1:
resolution: {integrity: sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==}
engines: {node: '>=8.0.0'}
@@ -5324,6 +5338,9 @@ packages:
resolution: {integrity: sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==}
engines: {node: '>= 0.10'}
proxy-from-env@0.0.1:
resolution: {integrity: sha512-B9Hnta3CATuMS0q6kt5hEezOPM+V3dgaRewkFtFoaRQYTVNsHqUvFXmndH06z3QO1ZdDnRELv5vfY6zAj/gG7A==}
proxy-from-env@2.1.0:
resolution: {integrity: sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==}
engines: {node: '>=10'}
@@ -5468,6 +5485,9 @@ packages:
resolution: {integrity: sha512-L9jEkOi3ASd9PYit2cwRfyppc9NoABujTP8/5gFcbERmo5jUoAKovIC3fsF17pkTnGsrByysqX+Kxd2OTNI1ww==}
engines: {node: '>=0.10.5'}
requires-port@0.0.1:
resolution: {integrity: sha512-AzPDCliPoWDSvEVYRQmpzuPhGGEnPrQz9YiOEvn+UdB9ixBpw+4IOZWtwctmpzySLZTy7ynpn47V14H4yaowtA==}
requires-port@1.0.0:
resolution: {integrity: sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==}
@@ -6366,10 +6386,6 @@ packages:
resolution: {integrity: sha512-c9gP6tfJ8vK+eH84IF4+8r4Z/g2KhRc+XwLGl208tAIHR1mz0o7zy5Hkm+4XpACh8lNp9/EHqXHIQkw2nBbdYA==}
engines: {node: '>= 8'}
watchpack@2.4.4:
resolution: {integrity: sha512-c5EGNOiyxxV5qmTtAB7rbiXxi1ooX1pQKMLX/MIabJjRA0SJBQOjKF+KSVfHkr9U1cADPon0mRiVe/riyaiDUA==}
engines: {node: '>=10.13.0'}
watchpack@2.5.2:
resolution: {integrity: sha512-6i/00NBjP4yGPs+caKSyRfpTF/8Torsu0MOW3mMzIbhgISFder8i7xbqgHlLMwJrdiN8ndBV3UA1/AfzPSr+jg==}
engines: {node: '>=10.13.0'}
@@ -9517,6 +9533,11 @@ snapshots:
core-util-is@1.0.3: {}
cors-anywhere@0.4.4:
dependencies:
http-proxy: 1.11.1
proxy-from-env: 0.0.1
cors@2.8.6:
dependencies:
object-assign: 4.1.1
@@ -10483,6 +10504,8 @@ snapshots:
etag@1.8.1: {}
eventemitter3@1.2.0: {}
eventemitter3@4.0.7: {}
events-to-array@2.0.3: {}
@@ -11160,6 +11183,11 @@ snapshots:
transitivePeerDependencies:
- supports-color
http-proxy@1.11.1:
dependencies:
eventemitter3: 1.2.0
requires-port: 0.0.1
http-proxy@1.18.1(debug@4.4.3(supports-color@10.2.2)):
dependencies:
eventemitter3: 4.0.7
@@ -12471,6 +12499,8 @@ snapshots:
forwarded: 0.2.0
ipaddr.js: 1.9.1
proxy-from-env@0.0.1: {}
proxy-from-env@2.1.0: {}
pump@3.0.4:
@@ -12646,6 +12676,8 @@ snapshots:
requireindex@1.2.0: {}
requires-port@0.0.1: {}
requires-port@1.0.0: {}
reselect@4.1.8: {}
@@ -13763,11 +13795,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
watchpack@2.4.4:
dependencies:
glob-to-regexp: 0.4.1
graceful-fs: 4.2.11
watchpack@2.5.2:
dependencies:
graceful-fs: 4.2.11
@@ -13839,7 +13866,7 @@ snapshots:
schema-utils: 4.5.0
tapable: 2.3.3
terser-webpack-plugin: 5.3.14(uglify-js@3.19.3)(webpack@5.102.1(uglify-js@3.19.3))
watchpack: 2.4.4
watchpack: 2.5.2
webpack-sources: 3.3.3
transitivePeerDependencies:
- '@swc/core'
@@ -3,6 +3,13 @@ import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render, triggerEvent } from '@ember/test-helpers';
import Bitcoin from 'dashtab/components/settings/add-integration/bitcoin';
function changeSelect(selector, value) {
const select = document.querySelector(selector);
const event = new Event('change', { bubbles: true });
Object.defineProperty(event, 'target', { value: { value } });
select.dispatchEvent(event);
}
module(
'Integration | Component | settings/add-integration/bitcoin',
function (hooks) {
@@ -14,18 +21,25 @@ module(
await render(<template><Bitcoin @closeDialog={{noop}} /></template>);
assert.dom().containsText('Add Bitcoin Price Ticker');
assert.dom().containsText('Price source');
assert.dom().containsText('Update interval');
assert.dom('form').exists();
assert.dom('el-select').exists();
assert.dom('el-option').exists({ count: 3 });
assert.dom('el-select').exists({ count: 2 });
assert.dom('el-option').exists({ count: 6 });
assert.dom().containsText('CoinGecko');
assert.dom().containsText('Binance');
assert.dom().containsText('Bitstamp');
assert.dom().containsText('Every 30 seconds');
assert.dom().containsText('Every 60 seconds');
assert.dom().containsText('Every 5 minutes');
});
test('submitting enables the integration with the default interval and closes the dialog', async function (assert) {
test('submitting enables the integration with the default interval and provider', async function (assert) {
const calls = [];
const bitcoin = { enable: async (interval) => calls.push(interval) };
const bitcoin = {
enable: async (interval, provider) =>
calls.push({ interval, provider }),
};
this.owner.register('service:bitcoin', bitcoin, { instantiate: false });
let closed = false;
@@ -38,26 +52,42 @@ module(
);
await triggerEvent('form', 'submit');
assert.deepEqual(calls, [30000]);
assert.deepEqual(calls, [{ interval: 30000, provider: 'coingecko' }]);
assert.true(closed);
});
test('submitting uses the selected interval', async function (assert) {
const calls = [];
const bitcoin = { enable: async (interval) => calls.push(interval) };
const bitcoin = {
enable: async (interval, provider) =>
calls.push({ interval, provider }),
};
this.owner.register('service:bitcoin', bitcoin, { instantiate: false });
const noop = () => {};
await render(<template><Bitcoin @closeDialog={{noop}} /></template>);
const select = document.querySelector('el-select');
const event = new Event('change', { bubbles: true });
Object.defineProperty(event, 'target', { value: { value: '60000' } });
select.dispatchEvent(event);
changeSelect('#bitcoin-interval', '60000');
await triggerEvent('form', 'submit');
assert.deepEqual(calls, [60000]);
assert.deepEqual(calls, [{ interval: 60000, provider: 'coingecko' }]);
});
test('submitting uses the selected provider', async function (assert) {
const calls = [];
const bitcoin = {
enable: async (interval, provider) =>
calls.push({ interval, provider }),
};
this.owner.register('service:bitcoin', bitcoin, { instantiate: false });
const noop = () => {};
await render(<template><Bitcoin @closeDialog={{noop}} /></template>);
changeSelect('#bitcoin-provider', 'binance');
await triggerEvent('form', 'submit');
assert.deepEqual(calls, [{ interval: 30000, provider: 'binance' }]);
});
}
);
@@ -0,0 +1,65 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render } from '@ember/test-helpers';
import Select from 'dashtab/components/settings/add-integration/select';
module(
'Integration | Component | settings/add-integration/select',
function (hooks) {
setupRenderingTest(hooks);
test('it renders the label, options and selected label', async function (assert) {
this.set('options', [
{ value: 'a', label: 'Option A' },
{ value: 'b', label: 'Option B' },
]);
this.set('noop', () => {});
await render(
<template>
<Select
@id="test-select"
@label="Pick one"
@options={{this.options}}
@value="b"
@onChange={{this.noop}}
/>
</template>
);
assert.dom('label').hasText('Pick one');
assert.dom('el-select').exists();
assert.dom('el-option').exists({ count: 2 });
assert.dom('el-selectedcontent').hasText('Option B');
});
test('it calls onChange with the chosen value', async function (assert) {
this.set('options', [
{ value: 'a', label: 'Option A' },
{ value: 'b', label: 'Option B' },
]);
const calls = [];
this.set('onChange', (value) => calls.push(value));
await render(
<template>
<Select
@id="test-select"
@label="Pick one"
@options={{this.options}}
@value="a"
@onChange={{this.onChange}}
/>
</template>
);
const select = document.querySelector('el-select');
const event = new Event('change', { bubbles: true });
Object.defineProperty(event, 'target', { value: { value: 'b' } });
select.dispatchEvent(event);
assert.deepEqual(calls, ['b']);
});
}
);
+99 -9
View File
@@ -1,6 +1,10 @@
import { module, test } from 'qunit';
import { setupTest } from 'dashtab/tests/helpers';
import { BITCOIN_TICKER_URL } from 'dashtab/services/bitcoin';
import { BITCOIN_PROVIDERS } from 'dashtab/services/bitcoin';
const COINGECKO = BITCOIN_PROVIDERS.find(({ id }) => id === 'coingecko');
const BINANCE = BITCOIN_PROVIDERS.find(({ id }) => id === 'binance');
const BITSTAMP = BITCOIN_PROVIDERS.find(({ id }) => id === 'bitstamp');
module('Unit | Service | bitcoin', function (hooks) {
setupTest(hooks);
@@ -8,10 +12,13 @@ module('Unit | Service | bitcoin', function (hooks) {
let originalFetch;
let originalConsoleError;
hooks.beforeEach(function () {
hooks.beforeEach(async function () {
originalFetch = globalThis.fetch;
originalConsoleError = console.error;
console.error = () => {};
const storage = this.owner.lookup('service:storage');
await storage.remove('integrations', 'bitcoin');
});
hooks.afterEach(function () {
@@ -38,11 +45,30 @@ module('Unit | Service | bitcoin', function (hooks) {
assert.true(service.enabled);
assert.strictEqual(service.interval, 60000);
assert.strictEqual(service.provider, 'bitstamp');
assert.ok(service.intervalId);
service.stopPolling();
});
test('load restores the stored provider', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'bitcoin', {
type: 'bitcoin',
status: 'active',
interval: 60000,
provider: 'binance',
});
const service = this.owner.lookup('service:bitcoin');
service.fetchPrice = async () => {};
await service.ready;
assert.strictEqual(service.provider, 'binance');
service.stopPolling();
});
test('load stays disabled for a pending integration', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'bitcoin', {
@@ -58,34 +84,35 @@ module('Unit | Service | bitcoin', function (hooks) {
assert.strictEqual(service.intervalId, null);
});
test('enable persists an active integration and starts polling', async function (assert) {
test('enable persists an active integration with provider and starts polling', async function (assert) {
const service = this.owner.lookup('service:bitcoin');
service.fetchPrice = async () => {};
await service.enable(60000);
await service.enable(60000, 'binance');
const storage = this.owner.lookup('service:storage');
const integration = await storage.get('integrations', 'bitcoin');
assert.true(service.enabled);
assert.strictEqual(service.interval, 60000);
assert.strictEqual(service.provider, 'binance');
assert.strictEqual(integration.status, 'active');
assert.strictEqual(integration.type, 'bitcoin');
assert.strictEqual(integration.interval, 60000);
assert.strictEqual(integration.provider, 'binance');
assert.ok(service.intervalId);
service.stopPolling();
});
test('fetchPrice parses the ticker response', async function (assert) {
test('fetchPrice parses the CoinGecko response', async function (assert) {
let requestedUrl;
globalThis.fetch = async (url) => {
requestedUrl = url;
return {
ok: true,
json: async () => ({
last: '86246.18',
percent_change_24: '3.43',
bitcoin: { usd: 86246.18, usd_24h_change: 3.43 },
}),
};
};
@@ -94,13 +121,58 @@ module('Unit | Service | bitcoin', function (hooks) {
await service.ready;
await service.fetchPrice();
assert.strictEqual(requestedUrl, BITCOIN_TICKER_URL);
assert.strictEqual(requestedUrl, COINGECKO.url);
assert.strictEqual(service.price, 86246.18);
assert.strictEqual(service.changePercent, 3.43);
assert.strictEqual(service.error, null);
assert.false(service.loading);
});
test('fetchPrice parses the Binance response', async function (assert) {
let requestedUrl;
globalThis.fetch = async (url) => {
requestedUrl = url;
return {
ok: true,
json: async () => ({
lastPrice: '86246.18',
priceChangePercent: '3.43',
}),
};
};
const service = this.owner.lookup('service:bitcoin');
await service.ready;
service.provider = 'binance';
await service.fetchPrice();
assert.strictEqual(requestedUrl, BINANCE.url);
assert.strictEqual(service.price, 86246.18);
assert.strictEqual(service.changePercent, 3.43);
});
test('fetchPrice parses the Bitstamp response', async function (assert) {
let requestedUrl;
globalThis.fetch = async (url) => {
requestedUrl = url;
return {
ok: true,
json: async () => ({ last: '86246.18', percent_change_24: '3.43' }),
};
};
const service = this.owner.lookup('service:bitcoin');
await service.ready;
service.provider = 'bitstamp';
await service.fetchPrice();
assert.strictEqual(requestedUrl, BITSTAMP.url);
assert.strictEqual(service.price, 86246.18);
assert.strictEqual(service.changePercent, 3.43);
});
test('fetchPrice sets an error and keeps the last price on a failed response', async function (assert) {
globalThis.fetch = async () => ({
ok: false,
@@ -133,6 +205,24 @@ module('Unit | Service | bitcoin', function (hooks) {
assert.false(service.loading);
});
test('fetchPrice sets an error for an unknown provider', async function (assert) {
let calls = 0;
globalThis.fetch = async () => {
calls++;
return { ok: true, json: async () => ({}) };
};
const service = this.owner.lookup('service:bitcoin');
await service.ready;
service.provider = 'bogus';
await service.fetchPrice();
assert.strictEqual(service.error, 'Unable to load the bitcoin price');
assert.strictEqual(calls, 0);
assert.false(service.fetching);
});
test('fetchPrice ignores overlapping requests', async function (assert) {
let calls = 0;
let resolveFetch;
@@ -151,7 +241,7 @@ module('Unit | Service | bitcoin', function (hooks) {
resolveFetch({
ok: true,
json: async () => ({ last: '1', percent_change_24: '0' }),
json: async () => ({ bitcoin: { usd: 1, usd_24h_change: 0 } }),
});
await Promise.all([first, second]);
+75 -1
View File
@@ -1,6 +1,11 @@
import { module, test } from 'qunit';
import { setupTest } from 'dashtab/tests/helpers';
import { HttpError, NetworkError } from 'dashtab/services/http';
import {
CORS_PROXY_HEADER,
HttpError,
NetworkError,
proxiedUrl,
} from 'dashtab/services/http';
module('Unit | Service | http', function (hooks) {
setupTest(hooks);
@@ -66,4 +71,73 @@ module('Unit | Service | http', function (hooks) {
}
);
});
test('proxiedUrl prefixes absolute URLs with the proxy base', function (assert) {
const base = 'http://localhost:8081/';
assert.strictEqual(
proxiedUrl('https://forum.example.com/notifications.json', base),
'http://localhost:8081/https://forum.example.com/notifications.json'
);
assert.strictEqual(
proxiedUrl('http://example.com/data.json', base),
'http://localhost:8081/http://example.com/data.json'
);
});
test('proxiedUrl leaves relative, proxied and unconfigured URLs alone', function (assert) {
const base = 'http://localhost:8081/';
assert.strictEqual(proxiedUrl('/assets/app.js', base), '/assets/app.js');
assert.strictEqual(
proxiedUrl('http://localhost:8081/https://example.com', base),
'http://localhost:8081/https://example.com'
);
assert.strictEqual(
proxiedUrl('https://example.com/data.json', null),
'https://example.com/data.json'
);
});
test('requestJson routes through the proxy and adds the proxy header', async function (assert) {
let requestedUrl;
let requestedOptions;
globalThis.fetch = async (url, options) => {
requestedUrl = url;
requestedOptions = options;
return { ok: true, json: async () => ({}) };
};
const http = this.owner.lookup('service:http');
http.corsProxyBase = 'http://localhost:8081/';
await http.requestJson('https://forum.example.com/notifications.json', {
headers: { 'User-Api-Key': 'key' },
});
assert.strictEqual(
requestedUrl,
'http://localhost:8081/https://forum.example.com/notifications.json'
);
assert.strictEqual(requestedOptions.headers[CORS_PROXY_HEADER], '1');
assert.strictEqual(requestedOptions.headers['User-Api-Key'], 'key');
});
test('requestJson goes direct without a proxy base', async function (assert) {
let requestedUrl;
let requestedOptions;
globalThis.fetch = async (url, options) => {
requestedUrl = url;
requestedOptions = options;
return { ok: true, json: async () => ({}) };
};
const http = this.owner.lookup('service:http');
http.corsProxyBase = null;
await http.requestJson('https://example.com/data.json');
assert.strictEqual(requestedUrl, 'https://example.com/data.json');
assert.false(CORS_PROXY_HEADER in requestedOptions.headers);
});
});
+33
View File
@@ -2,12 +2,45 @@ import { defineConfig } from 'vite';
import { extensions, classicEmberSupport, ember } from '@embroider/vite';
import { babel } from '@rollup/plugin-babel';
import tailwindcss from '@tailwindcss/vite';
import corsAnywhere from 'cors-anywhere';
const CORS_PROXY_HOST = '127.0.0.1';
const CORS_PROXY_PORT = Number(process.env.DASHTAB_CORS_PROXY_PORT || 8081);
const CORS_PROXY_ORIGINS = ['http://localhost:4200', 'http://127.0.0.1:4200'];
// Local, dev-only CORS proxy so Discourse (and other cross-origin) requests
// work when opening http://localhost:4200 directly. Bound to loopback and
// restricted to the app origin plus a required header, so other pages cannot
// use it as an open/SSRF proxy.
function corsProxyPlugin() {
return {
name: 'dashtab-cors-proxy',
apply: 'serve',
configureServer(server) {
const proxy = corsAnywhere.createServer({
originWhitelist: CORS_PROXY_ORIGINS,
requireHeader: ['x-dashtab-proxy'],
removeHeaders: ['x-dashtab-proxy', 'cookie', 'cookie2'],
corsMaxAge: 600,
});
proxy.listen(CORS_PROXY_PORT, CORS_PROXY_HOST, () => {
server.config.logger.info(
` ➜ CORS proxy: http://${CORS_PROXY_HOST}:${CORS_PROXY_PORT}/`,
);
});
server.httpServer?.once('close', () => proxy.close());
},
};
}
export default defineConfig({
plugins: [
classicEmberSupport(),
ember(),
tailwindcss(),
corsProxyPlugin(),
// extra plugins here
babel({
babelHelpers: 'runtime',