Support extension auth via launchWebAuthFlow and package app as extension page
This commit is contained in:
1 parent
df5808b144
commit
5643de9915
30 files changed
+595
-216
No files matched your search
@@ -2,6 +2,7 @@
|
||||
/dist/
|
||||
/declarations/
|
||||
/tmp/
|
||||
/extension/build/
|
||||
|
||||
# dependencies
|
||||
/node_modules/
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
# compiled output
|
||||
/dist/
|
||||
/extension/build/
|
||||
|
||||
# misc
|
||||
/coverage/
|
||||
|
||||
@@ -3,3 +3,4 @@
|
||||
|
||||
# compiled output
|
||||
/dist/
|
||||
/extension/build/
|
||||
@@ -38,22 +38,27 @@ when opening the app directly in a browser, without a third-party proxy.
|
||||
- It is only active in development; production relies on the browser extension's
|
||||
host permissions.
|
||||
|
||||
### Firefox dev extension
|
||||
### Browser extension
|
||||
|
||||
The `extension/` directory is a temporary MV3 shell that overrides the Firefox
|
||||
new-tab page with an iframe pointing at the dev server.
|
||||
The built app is packaged as an MV3 extension that serves the dashboard directly
|
||||
as the new-tab page (no iframe), so it behaves the same in development and
|
||||
production: requests go out with the extension's host permissions and
|
||||
authorizations use the browser's `identity.launchWebAuthFlow`.
|
||||
|
||||
- `pnpm ext:dev` starts the dev server and launches Firefox via `web-ext`
|
||||
(dedicated temporary profile; auto-reloads the add-on on changes). The new tab
|
||||
renders the dashboard with HMR.
|
||||
- Or run `pnpm start`, then load the extension manually:
|
||||
`about:debugging#/runtime/this-firefox` → **Load Temporary Add-on…** → select
|
||||
`extension/manifest.json`. Temporary add-ons are removed when Firefox closes.
|
||||
- `pnpm ext:lint` validates the extension manifest.
|
||||
- `pnpm ext:build:firefox` / `pnpm ext:build:chrome` build the app into
|
||||
`extension/build/` with the matching `extension/manifest.<browser>.json`.
|
||||
- `pnpm ext:dev` rebuilds on change and launches Firefox via `web-ext`
|
||||
(dedicated temporary profile). Changes reload the add-on rather than using HMR.
|
||||
- `pnpm ext:serve` runs `web-ext` against an existing `extension/build/`.
|
||||
- Load manually: `about:debugging#/runtime/this-firefox` → **Load Temporary
|
||||
Add-on…** → select `extension/build/manifest.json` (Firefox), or
|
||||
`chrome://extensions` → **Load unpacked** → `extension/build/` (Chrome).
|
||||
- `pnpm ext:lint` validates the packaged extension.
|
||||
|
||||
Because the iframe is a `localhost` document, requests are still subject to CORS
|
||||
and the extension's host permissions are not exercised. See the Discourse
|
||||
integration notes for the follow-up on privileged cross-origin requests.
|
||||
The extension IDs are pinned (`key` in the Chrome manifest, `browser_specific_settings.gecko.id`
|
||||
in the Firefox manifest) so the OAuth redirect URL is stable. See
|
||||
[`doc/extension_auth.md`](doc/extension_auth.md) for the redirect URLs forum
|
||||
admins must allowlist.
|
||||
|
||||
### Code Generators
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { discourseProvider } from './providers/discourse';
|
||||
|
||||
// Registry of authorization providers keyed by integration type. Adding a new
|
||||
// provider is a matter of implementing `prepare`/`complete` and registering it
|
||||
// here; the transport (web redirect vs. extension web-auth flow) is handled
|
||||
// separately by the authorization service.
|
||||
export const providers = {
|
||||
discourse: discourseProvider,
|
||||
};
|
||||
|
||||
export function providerFor(type) {
|
||||
return providers[type] ?? null;
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
// Discourse user-API-key authorization helpers, shared by the Add Integration
|
||||
// dialog and the "Reconnect" action.
|
||||
import forge from 'node-forge';
|
||||
|
||||
// Discourse user-api-key authorization. This is not OAuth2: the client sends a
|
||||
// public key, the user approves on the forum, and Discourse redirects back with
|
||||
// an RSA-encrypted payload.
|
||||
|
||||
export const DISCOURSE_AUTH_SCOPES = 'notifications,session_info';
|
||||
|
||||
@@ -132,16 +135,77 @@ async function storePendingIntegration(
|
||||
});
|
||||
}
|
||||
|
||||
// Generates/reuses a pending integration for the forum and redirects the browser
|
||||
// to Discourse's authorization page. Throws for an empty or invalid URL.
|
||||
export async function startDiscourseAuthorization(inputUrl, storage) {
|
||||
async function discourseIntegrations(storage) {
|
||||
const keys = await storage.keys('integrations');
|
||||
const integrations = await Promise.all(
|
||||
keys
|
||||
.filter((key) => key.startsWith('discourse-'))
|
||||
.map(async (key) => ({
|
||||
key,
|
||||
data: await storage.get('integrations', key),
|
||||
}))
|
||||
);
|
||||
return integrations.filter(({ data }) => Boolean(data));
|
||||
}
|
||||
|
||||
function decodePayload(payload) {
|
||||
const clean = payload.replace(/\s/g, '');
|
||||
let base64 = clean.replace(/-/g, '+').replace(/_/g, '/');
|
||||
while (base64.length % 4) {
|
||||
base64 += '=';
|
||||
}
|
||||
|
||||
try {
|
||||
return forge.util.decode64(base64);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function importPrivateKey(privateKeyBase64) {
|
||||
const bytes = Uint8Array.from(atob(privateKeyBase64), (char) =>
|
||||
char.charCodeAt(0)
|
||||
);
|
||||
const der = forge.util.createBuffer(bytes);
|
||||
const asn1 = forge.asn1.fromDer(der);
|
||||
return forge.pki.privateKeyFromAsn1(asn1);
|
||||
}
|
||||
|
||||
async function activate(candidate, apiData, integrations, storage) {
|
||||
const active = {
|
||||
...candidate.data,
|
||||
status: 'active',
|
||||
apiKey: apiData.key,
|
||||
oneTimePassword: apiData.one_time_password,
|
||||
activatedAt: Date.now(),
|
||||
};
|
||||
delete active.privateKey;
|
||||
|
||||
await storage.set('integrations', candidate.key, active);
|
||||
|
||||
// Drop superseded records for the same forum: leftover pending records or a
|
||||
// previous active record replaced by a reconnect.
|
||||
await Promise.all(
|
||||
integrations
|
||||
.filter(
|
||||
({ key, data }) =>
|
||||
key !== candidate.key && data?.url === candidate.data.url
|
||||
)
|
||||
.map(({ key }) => storage.remove('integrations', key))
|
||||
);
|
||||
|
||||
return active;
|
||||
}
|
||||
|
||||
// Generates/reuses a pending integration for the forum and returns the URL the
|
||||
// user must visit to authorize Dashtab.
|
||||
async function prepare({ inputUrl, redirectUri, storage }) {
|
||||
const url = normalizeDiscourseUrl(inputUrl);
|
||||
if (!url) {
|
||||
throw new Error('Please enter a Discourse URL');
|
||||
}
|
||||
|
||||
const urlObj = new URL(url);
|
||||
const redirectUrl = window.location.origin + '/auth/discourse/callback';
|
||||
|
||||
let clientId;
|
||||
let nonce;
|
||||
@@ -164,7 +228,7 @@ export async function startDiscourseAuthorization(inputUrl, storage) {
|
||||
origin: urlObj.origin,
|
||||
privateKey,
|
||||
nonce,
|
||||
redirectUrl,
|
||||
redirectUrl: redirectUri,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -174,9 +238,53 @@ export async function startDiscourseAuthorization(inputUrl, storage) {
|
||||
client_id: clientId,
|
||||
nonce,
|
||||
scopes: DISCOURSE_AUTH_SCOPES,
|
||||
auth_redirect: redirectUrl,
|
||||
auth_redirect: redirectUri,
|
||||
public_key: publicKeyPem,
|
||||
}).toString();
|
||||
|
||||
window.location.href = authUrl.toString();
|
||||
return authUrl.toString();
|
||||
}
|
||||
|
||||
// Decrypts the payload returned by Discourse and stores the activated
|
||||
// integration. `resultUrl` is the full redirect URL containing `?payload=`.
|
||||
async function complete({ resultUrl, storage }) {
|
||||
const payload = new URL(resultUrl).searchParams.get('payload');
|
||||
if (!payload) {
|
||||
throw new Error('No payload received from Discourse');
|
||||
}
|
||||
|
||||
const encryptedData = decodePayload(payload);
|
||||
if (!encryptedData) {
|
||||
throw new Error('Invalid payload format from Discourse');
|
||||
}
|
||||
|
||||
const integrations = await discourseIntegrations(storage);
|
||||
const pending = integrations.filter(
|
||||
({ data }) => data && data.status === 'pending'
|
||||
);
|
||||
|
||||
if (pending.length === 0) {
|
||||
throw new Error('No pending integration found');
|
||||
}
|
||||
|
||||
const match = selectDecryptedIntegration(pending, (candidate) => {
|
||||
const privateKey = importPrivateKey(candidate.data.privateKey);
|
||||
const decrypted = privateKey.decrypt(encryptedData, 'RSAES-PKCS1-V1_5');
|
||||
return JSON.parse(decrypted);
|
||||
});
|
||||
|
||||
if (!match) {
|
||||
throw new Error(
|
||||
'Failed to decrypt response from Discourse. The key or encryption format may be incompatible.'
|
||||
);
|
||||
}
|
||||
|
||||
return activate(match.candidate, match.apiData, integrations, storage);
|
||||
}
|
||||
|
||||
export const discourseProvider = {
|
||||
id: 'discourse',
|
||||
webCallbackPath: '/auth/discourse/callback',
|
||||
prepare,
|
||||
complete,
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
import { getIdentityApi } from '../utils/extension';
|
||||
|
||||
// Chooses how an authorization request is carried out. In a browser extension
|
||||
// the browser provides `identity.launchWebAuthFlow`, which intercepts the
|
||||
// provider redirect to a `*.chromiumapp.org` / `*.extensions.allizom.org` URL.
|
||||
// Everywhere else we fall back to a full-page redirect handled by a callback
|
||||
// route.
|
||||
export function selectTransport(identity = getIdentityApi()) {
|
||||
if (identity) {
|
||||
return {
|
||||
kind: 'extension',
|
||||
redirectUri: (providerId) => identity.getRedirectURL(providerId),
|
||||
async launch(url) {
|
||||
return identity.launchWebAuthFlow({ url, interactive: true });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'web',
|
||||
redirect(url) {
|
||||
window.location.href = url;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import Component from '@glimmer/component';
|
||||
import { service } from '@ember/service';
|
||||
import { modifier } from 'ember-modifier';
|
||||
import ModalDialog from './modal-dialog.gjs';
|
||||
import IntegrationResult from './settings/add-integration/result.gjs';
|
||||
|
||||
const autoOpenDialog = modifier(() => {
|
||||
setTimeout(() => {
|
||||
const dialog = document.getElementById('integration-result-dialog');
|
||||
if (dialog && !dialog.open) {
|
||||
dialog.showModal();
|
||||
}
|
||||
}, 100);
|
||||
});
|
||||
|
||||
export default class IntegrationResultModalComponent extends Component {
|
||||
@service integrationResult;
|
||||
|
||||
get result() {
|
||||
return this.integrationResult.result;
|
||||
}
|
||||
|
||||
<template>
|
||||
{{#if this.result}}
|
||||
<div {{autoOpenDialog}}>
|
||||
<ModalDialog @id="integration-result-dialog" @maxWidth="sm">
|
||||
<div class="px-4 pt-5 pb-4 sm:p-6">
|
||||
<IntegrationResult @result={{this.result}} />
|
||||
</div>
|
||||
</ModalDialog>
|
||||
</div>
|
||||
{{/if}}
|
||||
</template>
|
||||
}
|
||||
@@ -3,10 +3,11 @@ import { tracked } from '@glimmer/tracking';
|
||||
import { action } from '@ember/object';
|
||||
import { service } from '@ember/service';
|
||||
import { on } from '@ember/modifier';
|
||||
import { startDiscourseAuthorization } from '../../../utils/discourse-auth';
|
||||
|
||||
export default class SettingsAddIntegrationDiscourse extends Component {
|
||||
@service storage;
|
||||
@service authorization;
|
||||
@service integrationResult;
|
||||
@service sites;
|
||||
|
||||
@tracked discourseUrl = '';
|
||||
@tracked error = null;
|
||||
@@ -23,14 +24,28 @@ export default class SettingsAddIntegrationDiscourse extends Component {
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
await startDiscourseAuthorization(this.discourseUrl, this.storage);
|
||||
const { transport, integration } = await this.authorization.start(
|
||||
'discourse',
|
||||
this.discourseUrl
|
||||
);
|
||||
|
||||
// In a browser extension the flow completes in place; a web app navigates
|
||||
// away to the forum and returns through the callback route instead.
|
||||
if (transport === 'extension') {
|
||||
await this.sites.reload();
|
||||
this.integrationResult.show({ success: true, integration });
|
||||
this.args.closeDialog?.();
|
||||
}
|
||||
} catch (err) {
|
||||
if (err?.message === 'Please enter a Discourse URL') {
|
||||
this.error = 'Please enter a Discourse URL';
|
||||
return;
|
||||
}
|
||||
console.error('Error setting up Discourse integration:', err);
|
||||
this.error = 'Invalid URL. Please enter a valid Discourse forum URL.';
|
||||
this.error =
|
||||
err instanceof TypeError
|
||||
? 'Invalid URL. Please enter a valid Discourse forum URL.'
|
||||
: (err?.message ?? 'Unable to connect to the forum');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,12 +5,12 @@ import { on } from '@ember/modifier';
|
||||
import { service } from '@ember/service';
|
||||
import Discourse from './discourse.gjs';
|
||||
import Bitcoin from './bitcoin.gjs';
|
||||
import { startDiscourseAuthorization } from '../../../utils/discourse-auth';
|
||||
|
||||
export default class SettingsAddIntegrationList extends Component {
|
||||
@service authorization;
|
||||
@service integrationResult;
|
||||
@service sites;
|
||||
@service notifications;
|
||||
@service storage;
|
||||
|
||||
get connected() {
|
||||
return this.sites.all.map((site) => ({
|
||||
@@ -23,7 +23,15 @@ export default class SettingsAddIntegrationList extends Component {
|
||||
@action
|
||||
async reconnect(source) {
|
||||
try {
|
||||
await startDiscourseAuthorization(source.url, this.storage);
|
||||
const { transport, integration } = await this.authorization.start(
|
||||
'discourse',
|
||||
source.url
|
||||
);
|
||||
|
||||
if (transport === 'extension') {
|
||||
await this.sites.reload();
|
||||
this.integrationResult.show({ success: true, integration });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error reconnecting Discourse integration:', err);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { action } from '@ember/object';
|
||||
import { service } from '@ember/service';
|
||||
|
||||
export default class IntegrationResultDialog extends Component {
|
||||
@service router;
|
||||
@service integrationResult;
|
||||
|
||||
get isSuccess() {
|
||||
return this.args.result?.success;
|
||||
@@ -15,7 +15,7 @@ export default class IntegrationResultDialog extends Component {
|
||||
|
||||
@action
|
||||
goBack() {
|
||||
this.router.transitionTo('index');
|
||||
this.integrationResult.dismiss();
|
||||
}
|
||||
|
||||
<template>
|
||||
|
||||
+4
-1
@@ -1,8 +1,11 @@
|
||||
import EmberRouter from '@embroider/router';
|
||||
import config from 'dashtab/config/environment';
|
||||
import { canUseExtensionAuth } from './utils/extension';
|
||||
|
||||
export default class Router extends EmberRouter {
|
||||
location = config.locationType;
|
||||
// Extension pages are served as `index.html`, which history mode would try to
|
||||
// read as a route, so skip URL syncing there.
|
||||
location = canUseExtensionAuth() ? 'none' : config.locationType;
|
||||
rootURL = config.rootURL;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,117 +1,25 @@
|
||||
import Route from '@ember/routing/route';
|
||||
import { service } from '@ember/service';
|
||||
import forge from 'node-forge';
|
||||
import { selectDecryptedIntegration } from '../../../utils/discourse-auth';
|
||||
|
||||
export default class AuthDiscourseCallbackRoute extends Route {
|
||||
@service storage;
|
||||
@service authorization;
|
||||
@service integrationResult;
|
||||
@service router;
|
||||
|
||||
async model() {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const payload = urlParams.get('payload');
|
||||
|
||||
if (!payload) {
|
||||
return { error: 'No payload received from Discourse' };
|
||||
}
|
||||
|
||||
const encryptedData = this.decodePayload(payload);
|
||||
if (!encryptedData) {
|
||||
return { error: 'Invalid payload format from Discourse' };
|
||||
}
|
||||
|
||||
try {
|
||||
const integrations = await this.discourseIntegrations();
|
||||
const pending = integrations.filter(
|
||||
({ data }) => data && data.status === 'pending'
|
||||
const integration = await this.authorization.completeWebCallback(
|
||||
'discourse',
|
||||
window.location.href
|
||||
);
|
||||
|
||||
if (pending.length === 0) {
|
||||
return { error: 'No pending integration found' };
|
||||
}
|
||||
|
||||
const match = selectDecryptedIntegration(pending, (candidate) => {
|
||||
const privateKey = this.importPrivateKey(candidate.data.privateKey);
|
||||
const decrypted = privateKey.decrypt(encryptedData, 'RSAES-PKCS1-V1_5');
|
||||
return JSON.parse(decrypted);
|
||||
});
|
||||
|
||||
if (!match) {
|
||||
return {
|
||||
error:
|
||||
'Failed to decrypt response from Discourse. The key or encryption format may be incompatible.',
|
||||
};
|
||||
}
|
||||
|
||||
await this.activate(match.candidate, match.apiData, integrations);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
integration: { ...match.candidate.data, status: 'active' },
|
||||
};
|
||||
this.integrationResult.show({ success: true, integration });
|
||||
} catch (error) {
|
||||
console.error('Error processing Discourse callback:', error);
|
||||
return { error: error.message };
|
||||
this.integrationResult.show({ error: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
async discourseIntegrations() {
|
||||
const integrationKeys = await this.storage.keys('integrations');
|
||||
const integrations = await Promise.all(
|
||||
integrationKeys
|
||||
.filter((key) => key.startsWith('discourse-'))
|
||||
.map(async (key) => ({
|
||||
key,
|
||||
data: await this.storage.get('integrations', key),
|
||||
}))
|
||||
);
|
||||
return integrations.filter(({ data }) => Boolean(data));
|
||||
}
|
||||
|
||||
decodePayload(payload) {
|
||||
const clean = payload.replace(/\s/g, '');
|
||||
let base64 = clean.replace(/-/g, '+').replace(/_/g, '/');
|
||||
while (base64.length % 4) {
|
||||
base64 += '=';
|
||||
}
|
||||
|
||||
try {
|
||||
return forge.util.decode64(base64);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
importPrivateKey(privateKeyBase64) {
|
||||
const bytes = Uint8Array.from(atob(privateKeyBase64), (char) =>
|
||||
char.charCodeAt(0)
|
||||
);
|
||||
const der = forge.util.createBuffer(bytes);
|
||||
const asn1 = forge.asn1.fromDer(der);
|
||||
return forge.pki.privateKeyFromAsn1(asn1);
|
||||
}
|
||||
|
||||
async activate(candidate, apiData, integrations) {
|
||||
const active = {
|
||||
...candidate.data,
|
||||
status: 'active',
|
||||
apiKey: apiData.key,
|
||||
oneTimePassword: apiData.one_time_password,
|
||||
activatedAt: Date.now(),
|
||||
};
|
||||
delete active.privateKey;
|
||||
|
||||
await this.storage.set('integrations', candidate.key, active);
|
||||
|
||||
// Drop superseded records for the same forum: leftover pending records or a
|
||||
// previous active record replaced by a reconnect.
|
||||
await Promise.all(
|
||||
integrations
|
||||
.filter(
|
||||
({ key, data }) =>
|
||||
key !== candidate.key && data?.url === candidate.data.url
|
||||
)
|
||||
.map(({ key }) => this.storage.remove('integrations', key))
|
||||
);
|
||||
afterModel() {
|
||||
return this.router.replaceWith('index');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import Service, { service } from '@ember/service';
|
||||
import { providerFor } from '../auth/providers';
|
||||
import { selectTransport } from '../auth/transport';
|
||||
import { getIdentityApi } from '../utils/extension';
|
||||
|
||||
// Orchestrates an integration authorization, delegating to a provider for the
|
||||
// protocol specifics and to a transport for how the user's browser gets there.
|
||||
export default class AuthorizationService extends Service {
|
||||
@service storage;
|
||||
|
||||
async start(type, inputUrl, identity = getIdentityApi()) {
|
||||
const provider = providerFor(type);
|
||||
if (!provider) {
|
||||
throw new Error(`Unsupported integration type: ${type}`);
|
||||
}
|
||||
|
||||
const transport = selectTransport(identity);
|
||||
const redirectUri =
|
||||
transport.kind === 'extension'
|
||||
? transport.redirectUri(provider.id)
|
||||
: `${window.location.origin}${provider.webCallbackPath}`;
|
||||
|
||||
const requestUrl = await provider.prepare({
|
||||
inputUrl,
|
||||
redirectUri,
|
||||
storage: this.storage,
|
||||
});
|
||||
|
||||
if (transport.kind === 'extension') {
|
||||
const resultUrl = await transport.launch(requestUrl);
|
||||
if (!resultUrl) {
|
||||
throw new Error('Authorization was cancelled');
|
||||
}
|
||||
const integration = await provider.complete({
|
||||
resultUrl,
|
||||
storage: this.storage,
|
||||
});
|
||||
return { transport: transport.kind, integration };
|
||||
}
|
||||
|
||||
transport.redirect(requestUrl);
|
||||
return { transport: transport.kind };
|
||||
}
|
||||
|
||||
async completeWebCallback(type, resultUrl) {
|
||||
const provider = providerFor(type);
|
||||
if (!provider) {
|
||||
throw new Error(`Unsupported integration type: ${type}`);
|
||||
}
|
||||
return provider.complete({ resultUrl, storage: this.storage });
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import Service from '@ember/service';
|
||||
import config from 'dashtab/config/environment';
|
||||
import { canUseExtensionAuth } from '../utils/extension';
|
||||
|
||||
export const CORS_PROXY_HEADER = 'X-Dashtab-Proxy';
|
||||
|
||||
@@ -30,12 +31,13 @@ export function proxiedUrl(url, base) {
|
||||
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.
|
||||
// Single seam for outbound requests. As an extension page the app fetches
|
||||
// cross-origin directly using the extension's host permissions; elsewhere the
|
||||
// development CORS proxy stands in for them.
|
||||
export default class HttpService extends Service {
|
||||
corsProxyBase = config.corsProxy ?? null;
|
||||
// In an extension the development CORS proxy (tied to the localhost origin)
|
||||
// must not be used; host permissions take over.
|
||||
corsProxyBase = canUseExtensionAuth() ? null : (config.corsProxy ?? null);
|
||||
|
||||
async request(url, options = {}) {
|
||||
const target = proxiedUrl(url, this.corsProxyBase);
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import Service from '@ember/service';
|
||||
import { tracked } from '@glimmer/tracking';
|
||||
|
||||
// Holds the outcome of the most recent integration authorization so it can be
|
||||
// shown as a modal on top of the dashboard, both after an in-place extension
|
||||
// flow and after the web redirect round-trip.
|
||||
export default class IntegrationResultService extends Service {
|
||||
@tracked result = null;
|
||||
|
||||
show(result) {
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
dismiss() {
|
||||
this.result = null;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { pageTitle } from 'ember-page-title';
|
||||
import IntegrationResultModal from '../components/integration-result-modal.gjs';
|
||||
|
||||
<template>
|
||||
{{pageTitle "Dashtab"}}
|
||||
@@ -9,4 +10,6 @@ import { pageTitle } from 'ember-page-title';
|
||||
>
|
||||
{{outlet}}
|
||||
</div>
|
||||
|
||||
<IntegrationResultModal />
|
||||
</template>
|
||||
@@ -1,26 +0,0 @@
|
||||
import { pageTitle } from 'ember-page-title';
|
||||
import ModalDialog from '../../../components/modal-dialog.gjs';
|
||||
import IntegrationResult from '../../../components/settings/add-integration/result.gjs';
|
||||
import { modifier } from 'ember-modifier';
|
||||
|
||||
const autoOpenDialog = modifier(() => {
|
||||
// Auto-open the dialog when the template is rendered
|
||||
setTimeout(() => {
|
||||
const dialog = document.getElementById('integration-result-dialog');
|
||||
if (dialog && !dialog.open) {
|
||||
dialog.showModal();
|
||||
}
|
||||
}, 100);
|
||||
});
|
||||
|
||||
<template>
|
||||
{{pageTitle "Discourse Authorization"}}
|
||||
|
||||
<div {{autoOpenDialog}}>
|
||||
<ModalDialog @id="integration-result-dialog" @maxWidth="sm">
|
||||
<div class="px-4 pt-5 pb-4 sm:p-6">
|
||||
<IntegrationResult @result={{@model}} />
|
||||
</div>
|
||||
</ModalDialog>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,22 @@
|
||||
// Runtime detection for browser-extension contexts.
|
||||
//
|
||||
// On ordinary web pages `window.chrome` exists but does not expose the identity
|
||||
// API, so we feature-check the function we actually need rather than trusting
|
||||
// the presence of a `chrome`/`browser` global.
|
||||
|
||||
export function getIdentityApi(api = globalThis.browser ?? globalThis.chrome) {
|
||||
const identity = api?.identity;
|
||||
|
||||
if (
|
||||
typeof identity?.launchWebAuthFlow === 'function' &&
|
||||
typeof identity?.getRedirectURL === 'function'
|
||||
) {
|
||||
return identity;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function canUseExtensionAuth() {
|
||||
return Boolean(getIdentityApi());
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
# Integration authorization: web vs. extension
|
||||
|
||||
Dashtab connects to integrations through a small authorization layer
|
||||
(`app/auth/`):
|
||||
|
||||
- **Providers** (`app/auth/providers/*`) implement the protocol for an
|
||||
integration type. Discourse uses its user-api-key flow (RSA public key in,
|
||||
encrypted payload out) rather than OAuth2; other providers can be added
|
||||
without touching the transport.
|
||||
- **Transport** (`app/auth/transport.js`) decides how the browser gets to the
|
||||
provider:
|
||||
- **Web app** → full-page redirect to `${origin}${provider.webCallbackPath}`
|
||||
(e.g. `/auth/discourse/callback`).
|
||||
- **Browser extension** → `identity.getRedirectURL(providerId)` plus
|
||||
`identity.launchWebAuthFlow`, which opens a browser-managed auth window and
|
||||
intercepts the redirect to a browser-owned domain.
|
||||
|
||||
The choice is made at runtime by feature-detecting the identity API, so the same
|
||||
build works as a normal site and as an extension.
|
||||
|
||||
## Forum configuration
|
||||
|
||||
Discourse only accepts a redirect that matches the
|
||||
`allowed_user_api_auth_redirects` site setting. Its default is
|
||||
`https://api.discourse.org/api/auth_redirect|discourse://auth_redirect`, so an
|
||||
admin must add the redirects Dashtab uses:
|
||||
|
||||
- **Web app** — the deployed origin plus callback path, e.g.
|
||||
`https://dashtab.example.com/auth/discourse/callback`.
|
||||
- **Chrome / Chromium extension** — `https://<extension-id>.chromiumapp.org/discourse`,
|
||||
or the wildcard `https://*.chromiumapp.org/*`.
|
||||
- **Firefox extension** — `https://<host>.extensions.allizom.org/discourse`
|
||||
(the host is derived from the add-on id), or the wildcard
|
||||
`https://*.extensions.allizom.org/*`.
|
||||
|
||||
`allowed_user_api_auth_redirects` supports `*` wildcards in the scheme, host,
|
||||
path and query, so the wildcard entries are the least brittle option for a
|
||||
publicly distributed extension. The exact redirect URL is whatever
|
||||
`browser.identity.getRedirectURL('discourse')` returns; it is stable because the
|
||||
extension ids are pinned (`extension/manifest.chrome.json` `key` and
|
||||
`extension/manifest.firefox.json` `browser_specific_settings.gecko.id`).
|
||||
|
||||
## Security note
|
||||
|
||||
Allowing `https://*.chromiumapp.org/*` makes it possible for _any_ installed
|
||||
extension to run the authorization flow. That does not leak keys: Discourse
|
||||
encrypts the generated user API key to the public key supplied by the requesting
|
||||
client, so only the client holding the matching private key can decrypt it. The
|
||||
user still has to explicitly approve each request on the forum.
|
||||
+7
-1
@@ -37,7 +37,13 @@ export default [
|
||||
* https://eslint.org/docs/latest/use/configure/ignore
|
||||
*/
|
||||
{
|
||||
ignores: ['dist/', 'node_modules/', 'coverage/', '!**/.*'],
|
||||
ignores: [
|
||||
'dist/',
|
||||
'node_modules/',
|
||||
'coverage/',
|
||||
'extension/build/',
|
||||
'!**/.*',
|
||||
],
|
||||
},
|
||||
/**
|
||||
* https://eslint.org/docs/latest/use/configure/configuration-files#configuring-linter-options
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "Dashtab (dev)",
|
||||
"version": "0.0.0",
|
||||
"description": "Dashtab new-tab dashboard — development shell.",
|
||||
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqUOWNvCBFYXD+6LOT+Qm/rK3A/5QGsWDKDFn5WDG2TcX0CIPlDOcrJoCk0oxjFDrVlEYvp3QvITCBZTWTkq36sR9olqConwVUSnvXd14+WgzEI7dAlazv/KeLrBGBmdpETbXzoRt3WpKMDzEGWORk+DvO+SQ7JwT1T7HkwSohG1i9BUwsouOPHhjX6Lq4eNpBXQZUTdHoliiC1j2TThnIkKKcK3xcEw/dfnPz5F28A/B+KmbIIYcrWXq/Wc6a98fdTpQyN8IFCSIARTH6aYcPWQExBYDoGcU48dFORHp/PGC1p9w7KNXr0VHf8Mup4bya2MaxnacGXu71qHwvOxt3wIDAQAB",
|
||||
"permissions": ["identity"],
|
||||
"host_permissions": ["https://*/*"],
|
||||
"chrome_url_overrides": {
|
||||
"newtab": "index.html"
|
||||
}
|
||||
}
|
||||
@@ -5,14 +5,16 @@
|
||||
"description": "Dashtab new-tab dashboard — development shell.",
|
||||
"browser_specific_settings": {
|
||||
"gecko": {
|
||||
"id": "dashtab-dev@local",
|
||||
"id": "dashtab@dashtab.app",
|
||||
"strict_min_version": "142.0",
|
||||
"data_collection_permissions": {
|
||||
"required": ["none"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"permissions": ["identity"],
|
||||
"host_permissions": ["https://*/*"],
|
||||
"chrome_url_overrides": {
|
||||
"newtab": "newtab.html"
|
||||
"newtab": "index.html"
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Dashtab</title>
|
||||
<style>
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
iframe {
|
||||
display: block;
|
||||
border: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<iframe src="http://localhost:4200/" title="Dashtab"></iframe>
|
||||
</body>
|
||||
</html>
|
||||
+6
-3
@@ -12,9 +12,12 @@
|
||||
},
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
"ext:dev": "concurrently -k \"pnpm start\" \"wait-on tcp:4200 && pnpm ext:serve\"",
|
||||
"ext:lint": "web-ext lint --source-dir=extension",
|
||||
"ext:serve": "web-ext run --source-dir=extension --start-url about:newtab",
|
||||
"ext:build": "DASHTAB_EXT=1 DASHTAB_EXT_TARGET=firefox vite build --mode development",
|
||||
"ext:build:chrome": "DASHTAB_EXT=1 DASHTAB_EXT_TARGET=chrome vite build --mode development",
|
||||
"ext:build:firefox": "DASHTAB_EXT=1 DASHTAB_EXT_TARGET=firefox vite build --mode development",
|
||||
"ext:dev": "concurrently -k \"DASHTAB_EXT=1 DASHTAB_EXT_TARGET=firefox vite build --mode development --watch\" \"wait-on extension/build/manifest.json && pnpm ext:serve\"",
|
||||
"ext:lint": "web-ext lint --source-dir=extension/build",
|
||||
"ext:serve": "web-ext run --source-dir=extension/build --start-url about:newtab",
|
||||
"format": "prettier . --cache --write",
|
||||
"lint": "concurrently \"pnpm:lint:*(!fix)\" --names \"lint:\" --prefixColors auto",
|
||||
"lint:css": "stylelint \"**/*.css\"",
|
||||
|
||||
+11
-10
@@ -2,10 +2,10 @@ import { module, test } from 'qunit';
|
||||
import {
|
||||
normalizeDiscourseUrl,
|
||||
selectDecryptedIntegration,
|
||||
startDiscourseAuthorization,
|
||||
} from 'dashtab/utils/discourse-auth';
|
||||
discourseProvider,
|
||||
} from 'dashtab/auth/providers/discourse';
|
||||
|
||||
module('Unit | Utility | discourse-auth', function () {
|
||||
module('Unit | Auth | providers | discourse', function () {
|
||||
test('normalizeDiscourseUrl adds a scheme and rejects empty input', function (assert) {
|
||||
assert.strictEqual(
|
||||
normalizeDiscourseUrl('forum.example.com'),
|
||||
@@ -18,13 +18,6 @@ module('Unit | Utility | discourse-auth', function () {
|
||||
assert.strictEqual(normalizeDiscourseUrl(' '), null);
|
||||
});
|
||||
|
||||
test('startDiscourseAuthorization rejects an empty url', async function (assert) {
|
||||
await assert.rejects(
|
||||
startDiscourseAuthorization('', {}),
|
||||
/Please enter a Discourse URL/
|
||||
);
|
||||
});
|
||||
|
||||
test('selects the candidate whose payload nonce matches', function (assert) {
|
||||
const first = { key: 'discourse-a', data: { nonce: 'nonce-a' } };
|
||||
const second = { key: 'discourse-b', data: { nonce: 'nonce-b' } };
|
||||
@@ -72,4 +65,12 @@ module('Unit | Utility | discourse-auth', function () {
|
||||
|
||||
assert.strictEqual(match.candidate, candidate);
|
||||
});
|
||||
|
||||
test('exposes its id and web callback path', function (assert) {
|
||||
assert.strictEqual(discourseProvider.id, 'discourse');
|
||||
assert.strictEqual(
|
||||
discourseProvider.webCallbackPath,
|
||||
'/auth/discourse/callback'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { module, test } from 'qunit';
|
||||
import { selectTransport } from 'dashtab/auth/transport';
|
||||
|
||||
module('Unit | Auth | transport', function () {
|
||||
test('selects the web transport without an identity API', function (assert) {
|
||||
const transport = selectTransport(null);
|
||||
|
||||
assert.strictEqual(transport.kind, 'web');
|
||||
assert.strictEqual(typeof transport.redirect, 'function');
|
||||
});
|
||||
|
||||
test('selects the extension transport and launches the web auth flow', async function (assert) {
|
||||
const calls = [];
|
||||
const identity = {
|
||||
getRedirectURL: (path) => `https://abc.chromiumapp.org/${path}`,
|
||||
launchWebAuthFlow: async (details) => {
|
||||
calls.push(details);
|
||||
return 'https://abc.chromiumapp.org/discourse?payload=x';
|
||||
},
|
||||
};
|
||||
|
||||
const transport = selectTransport(identity);
|
||||
|
||||
assert.strictEqual(transport.kind, 'extension');
|
||||
assert.strictEqual(
|
||||
transport.redirectUri('discourse'),
|
||||
'https://abc.chromiumapp.org/discourse'
|
||||
);
|
||||
|
||||
const result = await transport.launch('https://forum.example.com/new');
|
||||
assert.strictEqual(
|
||||
result,
|
||||
'https://abc.chromiumapp.org/discourse?payload=x'
|
||||
);
|
||||
assert.deepEqual(calls, [
|
||||
{ url: 'https://forum.example.com/new', interactive: true },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { module, test } from 'qunit';
|
||||
import { setupTest } from 'dashtab/tests/helpers';
|
||||
|
||||
module('Unit | Service | authorization', function (hooks) {
|
||||
setupTest(hooks);
|
||||
|
||||
test('it exists', function (assert) {
|
||||
const service = this.owner.lookup('service:authorization');
|
||||
assert.ok(service);
|
||||
});
|
||||
|
||||
test('rejects an unsupported integration type', async function (assert) {
|
||||
const service = this.owner.lookup('service:authorization');
|
||||
|
||||
await assert.rejects(
|
||||
service.start('unknown', 'https://example.com'),
|
||||
/Unsupported integration type/
|
||||
);
|
||||
await assert.rejects(
|
||||
service.completeWebCallback('unknown', 'https://example.com'),
|
||||
/Unsupported integration type/
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import { module, test } from 'qunit';
|
||||
import { getIdentityApi, canUseExtensionAuth } from 'dashtab/utils/extension';
|
||||
|
||||
module('Unit | Utility | extension', function () {
|
||||
test('returns null without an identity API', function (assert) {
|
||||
assert.strictEqual(getIdentityApi(null), null);
|
||||
assert.strictEqual(getIdentityApi({}), null);
|
||||
});
|
||||
|
||||
test('returns the identity API when both functions exist', function (assert) {
|
||||
const identity = { launchWebAuthFlow() {}, getRedirectURL() {} };
|
||||
|
||||
assert.strictEqual(getIdentityApi({ identity }), identity);
|
||||
});
|
||||
|
||||
test('ignores a partial identity API', function (assert) {
|
||||
assert.strictEqual(
|
||||
getIdentityApi({ identity: { launchWebAuthFlow() {} } }),
|
||||
null
|
||||
);
|
||||
assert.strictEqual(
|
||||
getIdentityApi({ identity: { getRedirectURL() {} } }),
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
test('canUseExtensionAuth is false without an identity API', function (assert) {
|
||||
// Test runs in a normal page context, where `chrome` (if present) has no
|
||||
// identity API.
|
||||
assert.false(canUseExtensionAuth());
|
||||
});
|
||||
});
|
||||
+55
-12
@@ -3,6 +3,8 @@ import { extensions, classicEmberSupport, ember } from '@embroider/vite';
|
||||
import { babel } from '@rollup/plugin-babel';
|
||||
import tailwindcss from '@tailwindcss/vite';
|
||||
import corsAnywhere from 'cors-anywhere';
|
||||
import { copyFileSync, mkdirSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const CORS_PROXY_HOST = '127.0.0.1';
|
||||
const CORS_PROXY_PORT = Number(process.env.DASHTAB_CORS_PROXY_PORT || 8081);
|
||||
@@ -35,16 +37,57 @@ function corsProxyPlugin() {
|
||||
};
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
classicEmberSupport(),
|
||||
ember(),
|
||||
tailwindcss(),
|
||||
corsProxyPlugin(),
|
||||
// extra plugins here
|
||||
babel({
|
||||
babelHelpers: 'runtime',
|
||||
extensions,
|
||||
}),
|
||||
],
|
||||
// Emits the target browser's manifest into the extension build output so the
|
||||
// packaged app can be loaded as an unpacked extension or linted with web-ext.
|
||||
function extensionManifestPlugin(target) {
|
||||
return {
|
||||
name: 'dashtab-extension-manifest',
|
||||
apply: 'build',
|
||||
closeBundle() {
|
||||
const buildDir = fileURLToPath(
|
||||
new URL('./extension/build', import.meta.url),
|
||||
);
|
||||
mkdirSync(buildDir, { recursive: true });
|
||||
copyFileSync(
|
||||
fileURLToPath(
|
||||
new URL(`./extension/manifest.${target}.json`, import.meta.url),
|
||||
),
|
||||
fileURLToPath(
|
||||
new URL('./extension/build/manifest.json', import.meta.url),
|
||||
),
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default defineConfig(() => {
|
||||
const isExtension = Boolean(process.env.DASHTAB_EXT);
|
||||
const target = process.env.DASHTAB_EXT_TARGET ?? 'firefox';
|
||||
|
||||
return {
|
||||
// Extension pages load from the extension root, so assets must resolve
|
||||
// relative to index.html rather than the site root.
|
||||
base: isExtension ? './' : '/',
|
||||
build: isExtension
|
||||
? {
|
||||
outDir: 'extension/build',
|
||||
emptyOutDir: true,
|
||||
target: 'es2022',
|
||||
// MV3 forbids inline scripts; opting out of the polyfill keeps the
|
||||
// generated index.html free of them.
|
||||
modulePreload: { polyfill: false },
|
||||
}
|
||||
: {},
|
||||
plugins: [
|
||||
classicEmberSupport(),
|
||||
ember(),
|
||||
tailwindcss(),
|
||||
corsProxyPlugin(),
|
||||
isExtension && extensionManifestPlugin(target),
|
||||
babel({
|
||||
babelHelpers: 'runtime',
|
||||
extensions,
|
||||
}),
|
||||
].filter(Boolean),
|
||||
};
|
||||
});
|
||||
Reference in new issue
Block a user