Add Discourse reconnect/remove and harden auth callback
This commit is contained in:
1 parent
a57336351d
commit
44f4d78bfa
11 files changed
+736
-380
No files matched your search
@@ -3,6 +3,7 @@ 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;
|
||||
@@ -19,202 +20,20 @@ export default class SettingsAddIntegrationDiscourse extends Component {
|
||||
@action
|
||||
async handleSubmit(event) {
|
||||
event.preventDefault();
|
||||
|
||||
// Validate URL
|
||||
let url = this.discourseUrl.trim();
|
||||
if (!url) {
|
||||
this.error = 'Please enter a Discourse URL';
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure URL has protocol
|
||||
if (!url.startsWith('http://') && !url.startsWith('https://')) {
|
||||
url = 'https://' + url;
|
||||
}
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const urlObj = new URL(url);
|
||||
|
||||
// Check if there's already a pending integration for this URL
|
||||
const existingIntegration = await this.findPendingIntegration(
|
||||
urlObj.origin
|
||||
);
|
||||
|
||||
let clientId, nonce, publicKeyPem;
|
||||
|
||||
if (existingIntegration) {
|
||||
// Re-use existing pending integration
|
||||
console.log(
|
||||
'Re-using existing pending integration:',
|
||||
existingIntegration.data.clientId
|
||||
);
|
||||
clientId = existingIntegration.data.clientId;
|
||||
nonce = existingIntegration.data.nonce;
|
||||
|
||||
// Re-import the private key to get the public key
|
||||
const privateKeyData = Uint8Array.from(
|
||||
atob(existingIntegration.data.privateKey),
|
||||
(c) => c.charCodeAt(0)
|
||||
);
|
||||
const privateKey = await window.crypto.subtle.importKey(
|
||||
'pkcs8',
|
||||
privateKeyData,
|
||||
{
|
||||
name: 'RSA-OAEP',
|
||||
hash: 'SHA-1',
|
||||
},
|
||||
true,
|
||||
['decrypt']
|
||||
);
|
||||
|
||||
// Export as JWK to extract public key info, then re-export as SPKI
|
||||
const jwk = await window.crypto.subtle.exportKey('jwk', privateKey);
|
||||
const publicKey = await window.crypto.subtle.importKey(
|
||||
'jwk',
|
||||
{
|
||||
kty: jwk.kty,
|
||||
n: jwk.n,
|
||||
e: jwk.e,
|
||||
},
|
||||
{
|
||||
name: 'RSA-OAEP',
|
||||
hash: 'SHA-1',
|
||||
},
|
||||
true,
|
||||
['encrypt']
|
||||
);
|
||||
|
||||
publicKeyPem = await this.exportPublicKeyToPem(publicKey);
|
||||
} else {
|
||||
// Generate new RSA keypair and IDs
|
||||
const { publicKey, privateKey } = await this.generateKeyPair();
|
||||
clientId = crypto.randomUUID();
|
||||
nonce = crypto.randomUUID();
|
||||
|
||||
// Convert public key to PEM format for Discourse
|
||||
publicKeyPem = await this.exportPublicKeyToPem(publicKey);
|
||||
|
||||
// Use current origin for redirect - this needs to be whitelisted in Discourse
|
||||
const redirectUrl = window.location.origin + '/auth/discourse/callback';
|
||||
|
||||
// Store the pending integration with private key and nonce
|
||||
await this.storePendingIntegration(
|
||||
clientId,
|
||||
urlObj.origin,
|
||||
privateKey,
|
||||
nonce,
|
||||
redirectUrl
|
||||
);
|
||||
|
||||
console.log('Created new pending integration:', clientId);
|
||||
}
|
||||
|
||||
// Build the authorization URL
|
||||
const redirectUrl = window.location.origin + '/auth/discourse/callback';
|
||||
const authUrl = new URL('/user-api-key/new', urlObj);
|
||||
const params = new URLSearchParams({
|
||||
application_name: 'Dashtab',
|
||||
client_id: clientId,
|
||||
nonce: nonce,
|
||||
scopes: 'notifications,session_info',
|
||||
auth_redirect: redirectUrl,
|
||||
public_key: publicKeyPem,
|
||||
});
|
||||
|
||||
authUrl.search = params.toString();
|
||||
|
||||
console.log('Authorization URL:', authUrl.toString());
|
||||
console.log(
|
||||
'Redirect URL (must be whitelisted in Discourse):',
|
||||
redirectUrl
|
||||
);
|
||||
|
||||
// Redirect to Discourse authorization
|
||||
window.location.href = authUrl.toString();
|
||||
await startDiscourseAuthorization(this.discourseUrl, this.storage);
|
||||
} 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.';
|
||||
}
|
||||
}
|
||||
|
||||
async findPendingIntegration(discourseUrl) {
|
||||
try {
|
||||
const integrationKeys = await this.storage.keys('integrations');
|
||||
const discourseIntegrations = await Promise.all(
|
||||
integrationKeys
|
||||
.filter((key) => key.startsWith('discourse-'))
|
||||
.map(async (key) => {
|
||||
const data = await this.storage.get('integrations', key);
|
||||
return { key, data };
|
||||
})
|
||||
);
|
||||
|
||||
// Find a pending integration for this URL
|
||||
return discourseIntegrations.find(
|
||||
({ data }) =>
|
||||
data && data.status === 'pending' && data.url === discourseUrl
|
||||
);
|
||||
} catch (err) {
|
||||
console.error('Error finding pending integration:', err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async generateKeyPair() {
|
||||
// Use SHA-256 as specified by Discourse expert
|
||||
return await window.crypto.subtle.generateKey(
|
||||
{
|
||||
name: 'RSA-OAEP',
|
||||
modulusLength: 2048,
|
||||
publicExponent: new Uint8Array([1, 0, 1]),
|
||||
hash: 'SHA-256',
|
||||
},
|
||||
true,
|
||||
['encrypt', 'decrypt']
|
||||
);
|
||||
}
|
||||
|
||||
async exportPublicKeyToPem(publicKey) {
|
||||
const exported = await window.crypto.subtle.exportKey('spki', publicKey);
|
||||
const exportedAsBase64 = btoa(
|
||||
String.fromCharCode(...new Uint8Array(exported))
|
||||
);
|
||||
const pem = `-----BEGIN PUBLIC KEY-----\n${exportedAsBase64.match(/.{1,64}/g).join('\n')}\n-----END PUBLIC KEY-----`;
|
||||
return pem;
|
||||
}
|
||||
|
||||
async storePendingIntegration(
|
||||
clientId,
|
||||
discourseOrigin,
|
||||
privateKey,
|
||||
nonce,
|
||||
redirectUrl
|
||||
) {
|
||||
// Export private key for storage
|
||||
const exportedPrivateKey = await window.crypto.subtle.exportKey(
|
||||
'pkcs8',
|
||||
privateKey
|
||||
);
|
||||
const privateKeyBase64 = btoa(
|
||||
String.fromCharCode(...new Uint8Array(exportedPrivateKey))
|
||||
);
|
||||
|
||||
// Store pending integration state for when we return from auth
|
||||
const integrationKey = `discourse-${clientId}`;
|
||||
const integrationData = {
|
||||
type: 'discourse',
|
||||
status: 'pending',
|
||||
clientId,
|
||||
nonce,
|
||||
url: discourseOrigin,
|
||||
redirectUrl,
|
||||
privateKey: privateKeyBase64,
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
|
||||
await this.storage.set('integrations', integrationKey, integrationData);
|
||||
}
|
||||
|
||||
<template>
|
||||
<div class="p-6">
|
||||
<h3
|
||||
|
||||
@@ -1,107 +1,186 @@
|
||||
import { on } from '@ember/modifier';
|
||||
import Component from '@glimmer/component';
|
||||
import { action } from '@ember/object';
|
||||
import { fn } from '@ember/helper';
|
||||
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';
|
||||
|
||||
<template>
|
||||
<div class="block max-h-96 p-4 transform-gpu scroll-py-3 overflow-y-auto">
|
||||
<button
|
||||
type="button"
|
||||
{{on "click" (fn @switchComponent Discourse)}}
|
||||
class="group flex w-full rounded-xl p-3 cursor-pointer select-none focus:outline-hidden hover:bg-gray-100 aria-selected:bg-gray-100"
|
||||
>
|
||||
<div
|
||||
class="flex size-10 flex-none items-center justify-center rounded-lg bg-indigo-500"
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
data-slot="icon"
|
||||
class="size-6 text-white"
|
||||
>
|
||||
<path
|
||||
d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="ml-4 flex-auto text-left">
|
||||
export default class SettingsAddIntegrationList extends Component {
|
||||
@service notifications;
|
||||
@service storage;
|
||||
|
||||
get connected() {
|
||||
return this.notifications.sources.map((source) => ({
|
||||
...source,
|
||||
canReconnect: source.type === 'discourse',
|
||||
}));
|
||||
}
|
||||
|
||||
@action
|
||||
async reconnect(source) {
|
||||
try {
|
||||
await startDiscourseAuthorization(source.url, this.storage);
|
||||
} catch (err) {
|
||||
console.error('Error reconnecting Discourse integration:', err);
|
||||
}
|
||||
}
|
||||
|
||||
@action
|
||||
async remove(source) {
|
||||
await this.notifications.removeSource(source.id);
|
||||
}
|
||||
|
||||
<template>
|
||||
<div class="block max-h-96 p-4 transform-gpu scroll-py-3 overflow-y-auto">
|
||||
{{#if this.connected.length}}
|
||||
<p
|
||||
id="item-discourse-label"
|
||||
class="text-sm font-medium text-gray-700 group-aria-selected:text-gray-900"
|
||||
class="px-3 pb-1 text-xs font-semibold tracking-wide text-gray-500 uppercase"
|
||||
>
|
||||
Discourse
|
||||
Connected
|
||||
</p>
|
||||
<p class="text-sm text-gray-500 group-aria-selected:text-gray-700">
|
||||
Notifications from your discussion forums
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
{{on "click" (fn @switchComponent Bitcoin)}}
|
||||
class="group flex w-full rounded-xl p-3 cursor-pointer select-none focus:outline-hidden hover:bg-gray-100 aria-selected:bg-gray-100"
|
||||
>
|
||||
<div
|
||||
class="flex size-10 flex-none items-center justify-center rounded-lg bg-orange-500"
|
||||
{{#each this.connected as |source|}}
|
||||
<div
|
||||
class="flex items-center gap-3 rounded-xl p-3"
|
||||
data-connected={{source.id}}
|
||||
>
|
||||
<div class="flex-auto text-left">
|
||||
<p class="text-sm font-medium text-gray-700">{{source.label}}</p>
|
||||
{{#if source.error}}
|
||||
<p class="text-sm text-red-600">{{source.error}}</p>
|
||||
{{/if}}
|
||||
</div>
|
||||
{{#if source.canReconnect}}
|
||||
<button
|
||||
type="button"
|
||||
data-test-reconnect
|
||||
{{on "click" (fn this.reconnect source)}}
|
||||
class="rounded-md px-2.5 py-1.5 text-sm font-semibold text-gray-700 ring-1 ring-inset ring-gray-300 hover:bg-gray-50"
|
||||
>
|
||||
Reconnect
|
||||
</button>
|
||||
{{/if}}
|
||||
<button
|
||||
type="button"
|
||||
data-test-remove
|
||||
{{on "click" (fn this.remove source)}}
|
||||
class="rounded-md px-2.5 py-1.5 text-sm font-semibold text-red-600 ring-1 ring-inset ring-red-200 hover:bg-red-50"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
{{/each}}
|
||||
|
||||
<div class="my-2 border-t border-gray-200"></div>
|
||||
{{/if}}
|
||||
|
||||
<p
|
||||
class="px-3 pb-1 text-xs font-semibold tracking-wide text-gray-500 uppercase"
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
data-slot="icon"
|
||||
class="size-6 text-white"
|
||||
>
|
||||
<path
|
||||
d="M23.638 14.904c-1.602 6.43-8.113 10.34-14.542 8.736C2.67 22.05-1.244 15.525.362 9.105 1.962 2.67 8.475-1.243 14.9.358c6.43 1.605 10.342 8.115 8.738 14.546zm-6.35-4.613c.24-1.59-.974-2.45-2.64-3.03l.54-2.153-1.315-.328-.525 2.107c-.345-.087-.705-.167-1.064-.25l.526-2.127-1.32-.33-.54 2.165c-.285-.067-.565-.132-.84-.2l-.006-.02-1.815-.45-.35 1.407s.975.225.955.238c.535.136.63.486.615.766l-.862 3.454c-.04.1-.14.25-.365.195.01.014-.95-.237-.95-.237l-.656 1.51 1.72.43c.32.08.634.16.955.25l-.54 2.2 1.32.33.54-2.18c.36.1.71.19 1.05.28l-.53 2.16 1.31.33.54-2.2c2.28.43 3.99.26 4.71-1.8.58-1.65-.03-2.6-1.22-3.22.87-.2 1.53-.78 1.7-1.96z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="ml-4 flex-auto text-left">
|
||||
<p
|
||||
id="item-bitcoin-label"
|
||||
class="text-sm font-medium text-gray-700 group-aria-selected:text-gray-900"
|
||||
>
|
||||
Bitcoin Price Ticker
|
||||
</p>
|
||||
<p class="text-sm text-gray-500 group-aria-selected:text-gray-700">
|
||||
Live BTC price on your dashboard
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled
|
||||
class="group flex w-full cursor-default rounded-xl p-3 select-none focus:outline-hidden"
|
||||
>
|
||||
<div
|
||||
class="flex size-10 flex-none items-center justify-center rounded-lg bg-gray-300"
|
||||
Add integration
|
||||
</p>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
{{on "click" (fn @switchComponent Discourse)}}
|
||||
class="group flex w-full rounded-xl p-3 cursor-pointer select-none focus:outline-hidden hover:bg-gray-100 aria-selected:bg-gray-100"
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
data-slot="icon"
|
||||
class="size-6 text-white"
|
||||
<div
|
||||
class="flex size-10 flex-none items-center justify-center rounded-lg bg-indigo-500"
|
||||
>
|
||||
<path
|
||||
d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="ml-4 flex-auto text-left">
|
||||
<p id="item-gitea-label" class="text-sm font-medium text-gray-400">
|
||||
Gitea
|
||||
</p>
|
||||
<p class="text-sm text-gray-400">
|
||||
Notifications from your Git hosting servers
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
data-slot="icon"
|
||||
class="size-6 text-white"
|
||||
>
|
||||
<path
|
||||
d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="ml-4 flex-auto text-left">
|
||||
<p
|
||||
id="item-discourse-label"
|
||||
class="text-sm font-medium text-gray-700 group-aria-selected:text-gray-900"
|
||||
>
|
||||
Discourse
|
||||
</p>
|
||||
<p class="text-sm text-gray-500 group-aria-selected:text-gray-700">
|
||||
Notifications from your discussion forums
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
{{on "click" (fn @switchComponent Bitcoin)}}
|
||||
class="group flex w-full rounded-xl p-3 cursor-pointer select-none focus:outline-hidden hover:bg-gray-100 aria-selected:bg-gray-100"
|
||||
>
|
||||
<div
|
||||
class="flex size-10 flex-none items-center justify-center rounded-lg bg-orange-500"
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
data-slot="icon"
|
||||
class="size-6 text-white"
|
||||
>
|
||||
<path
|
||||
d="M23.638 14.904c-1.602 6.43-8.113 10.34-14.542 8.736C2.67 22.05-1.244 15.525.362 9.105 1.962 2.67 8.475-1.243 14.9.358c6.43 1.605 10.342 8.115 8.738 14.546zm-6.35-4.613c.24-1.59-.974-2.45-2.64-3.03l.54-2.153-1.315-.328-.525 2.107c-.345-.087-.705-.167-1.064-.25l.526-2.127-1.32-.33-.54 2.165c-.285-.067-.565-.132-.84-.2l-.006-.02-1.815-.45-.35 1.407s.975.225.955.238c.535.136.63.486.615.766l-.862 3.454c-.04.1-.14.25-.365.195.01.014-.95-.237-.95-.237l-.656 1.51 1.72.43c.32.08.634.16.955.25l-.54 2.2 1.32.33.54-2.18c.36.1.71.19 1.05.28l-.53 2.16 1.31.33.54-2.2c2.28.43 3.99.26 4.71-1.8.58-1.65-.03-2.6-1.22-3.22.87-.2 1.53-.78 1.7-1.96z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="ml-4 flex-auto text-left">
|
||||
<p
|
||||
id="item-bitcoin-label"
|
||||
class="text-sm font-medium text-gray-700 group-aria-selected:text-gray-900"
|
||||
>
|
||||
Bitcoin Price Ticker
|
||||
</p>
|
||||
<p class="text-sm text-gray-500 group-aria-selected:text-gray-700">
|
||||
Live BTC price on your dashboard
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
disabled
|
||||
class="group flex w-full cursor-default rounded-xl p-3 select-none focus:outline-hidden"
|
||||
>
|
||||
<div
|
||||
class="flex size-10 flex-none items-center justify-center rounded-lg bg-gray-300"
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
data-slot="icon"
|
||||
class="size-6 text-white"
|
||||
>
|
||||
<path
|
||||
d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div class="ml-4 flex-auto text-left">
|
||||
<p id="item-gitea-label" class="text-sm font-medium text-gray-400">
|
||||
Gitea
|
||||
</p>
|
||||
<p class="text-sm text-gray-400">
|
||||
Notifications from your Git hosting servers
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
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;
|
||||
@@ -14,98 +15,39 @@ export default class AuthDiscourseCallbackRoute extends Route {
|
||||
return { error: 'No payload received from Discourse' };
|
||||
}
|
||||
|
||||
try {
|
||||
// Find all pending discourse integrations
|
||||
const integrationKeys = await this.storage.keys('integrations');
|
||||
const pendingIntegrations = await Promise.all(
|
||||
integrationKeys
|
||||
.filter((key) => key.startsWith('discourse-'))
|
||||
.map(async (key) => {
|
||||
const data = await this.storage.get('integrations', key);
|
||||
return { key, data };
|
||||
})
|
||||
);
|
||||
const encryptedData = this.decodePayload(payload);
|
||||
if (!encryptedData) {
|
||||
return { error: 'Invalid payload format from Discourse' };
|
||||
}
|
||||
|
||||
const pendingIntegration = pendingIntegrations.find(
|
||||
try {
|
||||
const integrations = await this.discourseIntegrations();
|
||||
const pending = integrations.filter(
|
||||
({ data }) => data && data.status === 'pending'
|
||||
);
|
||||
|
||||
if (!pendingIntegration) {
|
||||
if (pending.length === 0) {
|
||||
return { error: 'No pending integration found' };
|
||||
}
|
||||
|
||||
// Import the stored private key using node-forge for PKCS#1 v1.5 support
|
||||
const privateKeyData = Uint8Array.from(
|
||||
atob(pendingIntegration.data.privateKey),
|
||||
(c) => c.charCodeAt(0)
|
||||
);
|
||||
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);
|
||||
});
|
||||
|
||||
// Convert to PEM format for node-forge
|
||||
const privateKeyDer = forge.util.createBuffer(privateKeyData);
|
||||
const privateKeyAsn1 = forge.asn1.fromDer(privateKeyDer);
|
||||
const privateKey = forge.pki.privateKeyFromAsn1(privateKeyAsn1);
|
||||
|
||||
// Decode the payload - it's BASE64URL encoded, not regular base64
|
||||
// First, remove any whitespace (newlines, spaces, etc)
|
||||
const cleanPayload = payload.replace(/\s/g, '');
|
||||
console.log('Original payload length:', payload.length);
|
||||
console.log('Cleaned payload length:', cleanPayload.length);
|
||||
|
||||
// Convert base64url to base64
|
||||
let base64 = cleanPayload.replace(/-/g, '+').replace(/_/g, '/');
|
||||
// Pad with = if needed
|
||||
while (base64.length % 4) {
|
||||
base64 += '=';
|
||||
}
|
||||
|
||||
let encryptedData;
|
||||
try {
|
||||
encryptedData = forge.util.decode64(base64);
|
||||
console.log(
|
||||
'Successfully decoded, encrypted data length:',
|
||||
encryptedData.length
|
||||
);
|
||||
} catch (err) {
|
||||
console.error('Failed to decode base64:', err);
|
||||
return { error: 'Invalid payload format from Discourse' };
|
||||
}
|
||||
|
||||
// Decrypt with PKCS#1 v1.5 padding (Discourse default)
|
||||
let decryptedData;
|
||||
try {
|
||||
console.log('Attempting decryption with PKCS#1 v1.5');
|
||||
// node-forge uses 'RSAES-PKCS1-V1_5' not 'RSA-PKCS1-V1_5'
|
||||
decryptedData = privateKey.decrypt(encryptedData, 'RSAES-PKCS1-V1_5');
|
||||
console.log('Decryption successful!');
|
||||
} catch (err) {
|
||||
console.error('PKCS#1 v1.5 decryption failed:', err);
|
||||
console.error('Payload length:', payload.length);
|
||||
console.error('Encrypted data length:', encryptedData.length);
|
||||
if (!match) {
|
||||
return {
|
||||
error:
|
||||
'Failed to decrypt response from Discourse. The key or encryption format may be incompatible.',
|
||||
};
|
||||
}
|
||||
|
||||
// Parse the decrypted data
|
||||
const apiData = JSON.parse(decryptedData);
|
||||
|
||||
// Update the integration with the API key
|
||||
await this.storage.set('integrations', pendingIntegration.key, {
|
||||
...pendingIntegration.data,
|
||||
status: 'active',
|
||||
apiKey: apiData.key,
|
||||
oneTimePassword: apiData.one_time_password,
|
||||
activatedAt: Date.now(),
|
||||
privateKey: undefined, // Remove private key after successful auth
|
||||
});
|
||||
await this.activate(match.candidate, match.apiData, integrations);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
integration: {
|
||||
...pendingIntegration.data,
|
||||
status: 'active',
|
||||
},
|
||||
integration: { ...match.candidate.data, status: 'active' },
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error processing Discourse callback:', error);
|
||||
@@ -113,7 +55,63 @@ export default class AuthDiscourseCallbackRoute extends Route {
|
||||
}
|
||||
}
|
||||
|
||||
afterModel() {
|
||||
// Don't auto-redirect anymore - let the user close the dialog
|
||||
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))
|
||||
);
|
||||
}
|
||||
}
|
||||
+15
-2
@@ -4,10 +4,12 @@ import config from 'dashtab/config/environment';
|
||||
export const CORS_PROXY_HEADER = 'X-Dashtab-Proxy';
|
||||
|
||||
export class HttpError extends Error {
|
||||
constructor(status) {
|
||||
constructor(status, errorType = null, body = null) {
|
||||
super(`Request failed with status ${status}`);
|
||||
this.name = 'HttpError';
|
||||
this.status = status;
|
||||
this.errorType = errorType;
|
||||
this.body = body;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,9 +54,20 @@ export default class HttpService extends Service {
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new HttpError(response.status);
|
||||
throw new HttpError(response.status, ...(await errorDetails(response)));
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
}
|
||||
|
||||
// Best-effort extraction of an API error body (e.g. Discourse's
|
||||
// `{"error_type":"invalid_access"}`) so callers can classify the failure.
|
||||
async function errorDetails(response) {
|
||||
try {
|
||||
const body = await response.json();
|
||||
return [body?.error_type ?? null, body];
|
||||
} catch {
|
||||
return [null, null];
|
||||
}
|
||||
}
|
||||
@@ -108,6 +108,7 @@ export default class NotificationsService extends Service {
|
||||
type: integration.type,
|
||||
groupId: this.groupIdForType(integration.type),
|
||||
label: labelForUrl(integration.url),
|
||||
url: integration.url,
|
||||
href: hrefForIntegration(integration),
|
||||
unreadCount: 0,
|
||||
status: 'loading',
|
||||
@@ -183,16 +184,25 @@ export default class NotificationsService extends Service {
|
||||
}
|
||||
|
||||
classifyError(err) {
|
||||
if (
|
||||
err instanceof HttpError &&
|
||||
(err.status === 401 || err.status === 403)
|
||||
) {
|
||||
return {
|
||||
errorType: 'unauthorized',
|
||||
error: 'Reconnect this forum',
|
||||
};
|
||||
}
|
||||
if (err instanceof HttpError) {
|
||||
if (err.errorType === 'not_logged_in') {
|
||||
return {
|
||||
errorType: 'unauthorized',
|
||||
error: 'No access token — reconnect this forum',
|
||||
};
|
||||
}
|
||||
if (err.errorType === 'invalid_access') {
|
||||
return {
|
||||
errorType: 'unauthorized',
|
||||
error: 'Access was rejected — reconnect this forum',
|
||||
};
|
||||
}
|
||||
if (err.status === 401 || err.status === 403) {
|
||||
return {
|
||||
errorType: 'unauthorized',
|
||||
error: 'Reconnect this forum',
|
||||
};
|
||||
}
|
||||
return {
|
||||
errorType: 'http',
|
||||
error: `Forum returned ${err.status}`,
|
||||
@@ -204,6 +214,20 @@ export default class NotificationsService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
// Re-reads integrations from storage and rebuilds the sources. Use after a
|
||||
// source is reconnected or removed so the new token is picked up without a
|
||||
// full page reload.
|
||||
async reload() {
|
||||
this.stopPolling();
|
||||
this.integrationBySourceId = new Map();
|
||||
await this.load();
|
||||
}
|
||||
|
||||
async removeSource(id) {
|
||||
await this.storage.remove('integrations', id);
|
||||
await this.reload();
|
||||
}
|
||||
|
||||
startPolling() {
|
||||
this.stopPolling();
|
||||
this.fetchAll();
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
// Discourse user-API-key authorization helpers, shared by the Add Integration
|
||||
// dialog and the "Reconnect" action.
|
||||
|
||||
export const DISCOURSE_AUTH_SCOPES = 'notifications,session_info';
|
||||
|
||||
export function normalizeDiscourseUrl(input) {
|
||||
let url = (input ?? '').trim();
|
||||
if (!url) {
|
||||
return null;
|
||||
}
|
||||
if (!url.startsWith('http://') && !url.startsWith('https://')) {
|
||||
url = 'https://' + url;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
// Selects the pending Discourse integration that the authorization payload
|
||||
// belongs to. `decrypt(candidate)` should return the decrypted payload object
|
||||
// for that candidate or throw if the candidate's key cannot decrypt it.
|
||||
//
|
||||
// Matching on the nonce (echoed back inside the encrypted payload) prevents a
|
||||
// key from being stored against the wrong forum when several authorizations
|
||||
// are pending at once.
|
||||
export function selectDecryptedIntegration(candidates, decrypt) {
|
||||
for (const candidate of candidates) {
|
||||
let apiData;
|
||||
|
||||
try {
|
||||
apiData = decrypt(candidate);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!apiData?.key) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
apiData.nonce &&
|
||||
candidate.data?.nonce &&
|
||||
apiData.nonce !== candidate.data.nonce
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return { candidate, apiData };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function generateKeyPair() {
|
||||
return window.crypto.subtle.generateKey(
|
||||
{
|
||||
name: 'RSA-OAEP',
|
||||
modulusLength: 2048,
|
||||
publicExponent: new Uint8Array([1, 0, 1]),
|
||||
hash: 'SHA-256',
|
||||
},
|
||||
true,
|
||||
['encrypt', 'decrypt']
|
||||
);
|
||||
}
|
||||
|
||||
async function exportPublicKeyToPem(publicKey) {
|
||||
const exported = await window.crypto.subtle.exportKey('spki', publicKey);
|
||||
const base64 = btoa(String.fromCharCode(...new Uint8Array(exported)));
|
||||
return `-----BEGIN PUBLIC KEY-----\n${base64.match(/.{1,64}/g).join('\n')}\n-----END PUBLIC KEY-----`;
|
||||
}
|
||||
|
||||
async function publicKeyPemFromPrivateKey(privateKeyBase64) {
|
||||
const privateKeyData = Uint8Array.from(atob(privateKeyBase64), (char) =>
|
||||
char.charCodeAt(0)
|
||||
);
|
||||
const privateKey = await window.crypto.subtle.importKey(
|
||||
'pkcs8',
|
||||
privateKeyData,
|
||||
{ name: 'RSA-OAEP', hash: 'SHA-1' },
|
||||
true,
|
||||
['decrypt']
|
||||
);
|
||||
|
||||
const jwk = await window.crypto.subtle.exportKey('jwk', privateKey);
|
||||
const publicKey = await window.crypto.subtle.importKey(
|
||||
'jwk',
|
||||
{ kty: jwk.kty, n: jwk.n, e: jwk.e },
|
||||
{ name: 'RSA-OAEP', hash: 'SHA-1' },
|
||||
true,
|
||||
['encrypt']
|
||||
);
|
||||
|
||||
return exportPublicKeyToPem(publicKey);
|
||||
}
|
||||
|
||||
async function findPendingIntegration(storage, origin) {
|
||||
const keys = await storage.keys('integrations');
|
||||
const records = await Promise.all(
|
||||
keys
|
||||
.filter((key) => key.startsWith('discourse-'))
|
||||
.map(async (key) => ({
|
||||
key,
|
||||
data: await storage.get('integrations', key),
|
||||
}))
|
||||
);
|
||||
|
||||
return records.find(
|
||||
({ data }) => data && data.status === 'pending' && data.url === origin
|
||||
);
|
||||
}
|
||||
|
||||
async function storePendingIntegration(
|
||||
storage,
|
||||
{ clientId, origin, privateKey, nonce, redirectUrl }
|
||||
) {
|
||||
const exportedPrivateKey = await window.crypto.subtle.exportKey(
|
||||
'pkcs8',
|
||||
privateKey
|
||||
);
|
||||
const privateKeyBase64 = btoa(
|
||||
String.fromCharCode(...new Uint8Array(exportedPrivateKey))
|
||||
);
|
||||
|
||||
await storage.set('integrations', `discourse-${clientId}`, {
|
||||
type: 'discourse',
|
||||
status: 'pending',
|
||||
clientId,
|
||||
nonce,
|
||||
url: origin,
|
||||
redirectUrl,
|
||||
privateKey: privateKeyBase64,
|
||||
createdAt: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
// 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) {
|
||||
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;
|
||||
let publicKeyPem;
|
||||
|
||||
const existing = await findPendingIntegration(storage, urlObj.origin);
|
||||
|
||||
if (existing) {
|
||||
clientId = existing.data.clientId;
|
||||
nonce = existing.data.nonce;
|
||||
publicKeyPem = await publicKeyPemFromPrivateKey(existing.data.privateKey);
|
||||
} else {
|
||||
const { publicKey, privateKey } = await generateKeyPair();
|
||||
clientId = crypto.randomUUID();
|
||||
nonce = crypto.randomUUID();
|
||||
publicKeyPem = await exportPublicKeyToPem(publicKey);
|
||||
|
||||
await storePendingIntegration(storage, {
|
||||
clientId,
|
||||
origin: urlObj.origin,
|
||||
privateKey,
|
||||
nonce,
|
||||
redirectUrl,
|
||||
});
|
||||
}
|
||||
|
||||
const authUrl = new URL('/user-api-key/new', urlObj);
|
||||
authUrl.search = new URLSearchParams({
|
||||
application_name: 'Dashtab',
|
||||
client_id: clientId,
|
||||
nonce,
|
||||
scopes: DISCOURSE_AUTH_SCOPES,
|
||||
auth_redirect: redirectUrl,
|
||||
public_key: publicKeyPem,
|
||||
}).toString();
|
||||
|
||||
window.location.href = authUrl.toString();
|
||||
}
|
||||
@@ -21,6 +21,7 @@ module(
|
||||
assert.dom().containsText('Add Discourse Integration');
|
||||
assert.dom().containsText('Enter your Discourse forum URL');
|
||||
assert.dom('form').exists();
|
||||
assert.dom('#discourse-url').hasNoValue();
|
||||
});
|
||||
}
|
||||
);
|
||||
@@ -1,18 +1,29 @@
|
||||
import { module, test } from 'qunit';
|
||||
import { setupRenderingTest } from 'dashtab/tests/helpers';
|
||||
import { render } from '@ember/test-helpers';
|
||||
import { render, click } from '@ember/test-helpers';
|
||||
import { tracked } from '@glimmer/tracking';
|
||||
import List from 'dashtab/components/settings/add-integration/list';
|
||||
|
||||
class FakeNotificationsService {
|
||||
@tracked sources = [];
|
||||
removed = [];
|
||||
|
||||
async removeSource(id) {
|
||||
this.removed.push(id);
|
||||
this.sources = this.sources.filter((source) => source.id !== id);
|
||||
}
|
||||
}
|
||||
|
||||
module(
|
||||
'Integration | Component | settings/add-integration/list',
|
||||
function (hooks) {
|
||||
setupRenderingTest(hooks);
|
||||
|
||||
test('it renders', async function (assert) {
|
||||
// Updating values is achieved using autotracking, just like in app code. For example:
|
||||
// class State { @tracked myProperty = 0; }; const state = new State();
|
||||
// and update using state.myProperty = 1; await rerender();
|
||||
// Handle any actions with function myAction(val) { ... };
|
||||
test('it renders the add options', async function (assert) {
|
||||
const notifications = new FakeNotificationsService();
|
||||
this.owner.register('service:notifications', notifications, {
|
||||
instantiate: false,
|
||||
});
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
@@ -25,5 +36,58 @@ module(
|
||||
assert.dom().containsText('Gitea');
|
||||
assert.dom().containsText('Notifications from your Git hosting servers');
|
||||
});
|
||||
|
||||
test('it lists connected integrations with reconnect and remove', async function (assert) {
|
||||
const notifications = new FakeNotificationsService();
|
||||
notifications.sources = [
|
||||
{
|
||||
id: 'discourse-abc',
|
||||
type: 'discourse',
|
||||
label: 'forum.example.com',
|
||||
url: 'https://forum.example.com',
|
||||
error: null,
|
||||
},
|
||||
];
|
||||
this.owner.register('service:notifications', notifications, {
|
||||
instantiate: false,
|
||||
});
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
await render(<template><List @switchComponent={{noop}} /></template>);
|
||||
|
||||
const row = '[data-connected="discourse-abc"]';
|
||||
assert.dom(row).exists();
|
||||
assert.dom(row).containsText('forum.example.com');
|
||||
assert.dom(`${row} [data-test-reconnect]`).exists();
|
||||
|
||||
await click(`${row} [data-test-remove]`);
|
||||
|
||||
assert.deepEqual(notifications.removed, ['discourse-abc']);
|
||||
});
|
||||
|
||||
test('it shows the error for a failing source', async function (assert) {
|
||||
const notifications = new FakeNotificationsService();
|
||||
notifications.sources = [
|
||||
{
|
||||
id: 'discourse-bad',
|
||||
type: 'discourse',
|
||||
label: 'bad.example.com',
|
||||
url: 'https://bad.example.com',
|
||||
error: 'Access was rejected — reconnect this forum',
|
||||
},
|
||||
];
|
||||
this.owner.register('service:notifications', notifications, {
|
||||
instantiate: false,
|
||||
});
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
await render(<template><List @switchComponent={{noop}} /></template>);
|
||||
|
||||
assert
|
||||
.dom('[data-connected="discourse-bad"]')
|
||||
.containsText('Access was rejected — reconnect this forum');
|
||||
});
|
||||
}
|
||||
);
|
||||
@@ -56,6 +56,29 @@ module('Unit | Service | http', function (hooks) {
|
||||
);
|
||||
});
|
||||
|
||||
test('it captures the API error type on a failed response', async function (assert) {
|
||||
globalThis.fetch = async () => ({
|
||||
ok: false,
|
||||
status: 403,
|
||||
json: async () => ({
|
||||
errors: ['You are not permitted to view the requested resource.'],
|
||||
error_type: 'invalid_access',
|
||||
}),
|
||||
});
|
||||
|
||||
const http = this.owner.lookup('service:http');
|
||||
|
||||
await assert.rejects(
|
||||
http.requestJson('https://example.com/data.json'),
|
||||
(err) => {
|
||||
assert.true(err instanceof HttpError);
|
||||
assert.strictEqual(err.status, 403);
|
||||
assert.strictEqual(err.errorType, 'invalid_access');
|
||||
return true;
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test('it throws NetworkError when the request cannot be made', async function (assert) {
|
||||
globalThis.fetch = async () => {
|
||||
throw new TypeError('Failed to fetch');
|
||||
|
||||
@@ -7,10 +7,13 @@ module('Unit | Service | notifications', 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.clear('integrations');
|
||||
});
|
||||
|
||||
hooks.afterEach(function () {
|
||||
@@ -190,6 +193,81 @@ module('Unit | Service | notifications', function (hooks) {
|
||||
assert.strictEqual(source.error, 'Reconnect this forum');
|
||||
});
|
||||
|
||||
test('fetchSource surfaces a rejected access token', async function (assert) {
|
||||
const storage = this.owner.lookup('service:storage');
|
||||
await storage.set('integrations', 'discourse-abc', {
|
||||
type: 'discourse',
|
||||
status: 'active',
|
||||
url: 'https://forum.example.com',
|
||||
apiKey: 'stale',
|
||||
});
|
||||
|
||||
const service = this.owner.lookup('service:notifications');
|
||||
service.fetchAll = async () => {};
|
||||
await service.ready;
|
||||
|
||||
globalThis.fetch = async () => ({
|
||||
ok: false,
|
||||
status: 403,
|
||||
json: async () => ({ error_type: 'invalid_access' }),
|
||||
});
|
||||
|
||||
await service.fetchSource(service.sources[0]);
|
||||
|
||||
const [source] = service.sources;
|
||||
assert.strictEqual(source.errorType, 'unauthorized');
|
||||
assert.strictEqual(
|
||||
source.error,
|
||||
'Access was rejected — reconnect this forum'
|
||||
);
|
||||
});
|
||||
|
||||
test('reload picks up newly added integrations', async function (assert) {
|
||||
const storage = this.owner.lookup('service:storage');
|
||||
const service = this.owner.lookup('service:notifications');
|
||||
service.fetchAll = async () => {};
|
||||
await service.ready;
|
||||
assert.strictEqual(service.sources.length, 0);
|
||||
|
||||
await storage.set('integrations', 'discourse-new', {
|
||||
type: 'discourse',
|
||||
status: 'active',
|
||||
url: 'https://new.example.com',
|
||||
apiKey: 'key',
|
||||
});
|
||||
await service.reload();
|
||||
|
||||
assert.strictEqual(service.sources.length, 1);
|
||||
assert.strictEqual(service.sources[0].id, 'discourse-new');
|
||||
|
||||
service.stopPolling();
|
||||
});
|
||||
|
||||
test('removeSource deletes the integration and reloads', async function (assert) {
|
||||
const storage = this.owner.lookup('service:storage');
|
||||
await storage.set('integrations', 'discourse-abc', {
|
||||
type: 'discourse',
|
||||
status: 'active',
|
||||
url: 'https://forum.example.com',
|
||||
apiKey: 'key',
|
||||
});
|
||||
|
||||
const service = this.owner.lookup('service:notifications');
|
||||
service.fetchAll = async () => {};
|
||||
await service.ready;
|
||||
assert.strictEqual(service.sources.length, 1);
|
||||
|
||||
await service.removeSource('discourse-abc');
|
||||
|
||||
assert.strictEqual(service.sources.length, 0);
|
||||
assert.strictEqual(
|
||||
await storage.get('integrations', 'discourse-abc'),
|
||||
null
|
||||
);
|
||||
|
||||
service.stopPolling();
|
||||
});
|
||||
|
||||
test('fetchSource flags other HTTP failures', async function (assert) {
|
||||
const storage = this.owner.lookup('service:storage');
|
||||
await storage.set('integrations', 'discourse-abc', {
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { module, test } from 'qunit';
|
||||
import {
|
||||
normalizeDiscourseUrl,
|
||||
selectDecryptedIntegration,
|
||||
startDiscourseAuthorization,
|
||||
} from 'dashtab/utils/discourse-auth';
|
||||
|
||||
module('Unit | Utility | discourse-auth', function () {
|
||||
test('normalizeDiscourseUrl adds a scheme and rejects empty input', function (assert) {
|
||||
assert.strictEqual(
|
||||
normalizeDiscourseUrl('forum.example.com'),
|
||||
'https://forum.example.com'
|
||||
);
|
||||
assert.strictEqual(
|
||||
normalizeDiscourseUrl('http://forum.example.com'),
|
||||
'http://forum.example.com'
|
||||
);
|
||||
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' } };
|
||||
|
||||
const decrypt = (candidate) => {
|
||||
if (candidate === first) {
|
||||
throw new Error('wrong key');
|
||||
}
|
||||
return { key: 'KEY', nonce: 'nonce-b' };
|
||||
};
|
||||
|
||||
const match = selectDecryptedIntegration([first, second], decrypt);
|
||||
|
||||
assert.strictEqual(match.candidate, second);
|
||||
assert.strictEqual(match.apiData.key, 'KEY');
|
||||
});
|
||||
|
||||
test('skips a candidate whose nonce does not match', function (assert) {
|
||||
const candidate = { key: 'discourse-a', data: { nonce: 'nonce-a' } };
|
||||
|
||||
const match = selectDecryptedIntegration([candidate], () => ({
|
||||
key: 'KEY',
|
||||
nonce: 'other',
|
||||
}));
|
||||
|
||||
assert.strictEqual(match, null);
|
||||
});
|
||||
|
||||
test('returns null when nothing decrypts', function (assert) {
|
||||
const candidate = { key: 'discourse-a', data: { nonce: 'nonce-a' } };
|
||||
|
||||
const match = selectDecryptedIntegration([candidate], () => {
|
||||
throw new Error('cannot decrypt');
|
||||
});
|
||||
|
||||
assert.strictEqual(match, null);
|
||||
});
|
||||
|
||||
test('accepts a payload without a nonce', function (assert) {
|
||||
const candidate = { key: 'discourse-a', data: { nonce: 'nonce-a' } };
|
||||
|
||||
const match = selectDecryptedIntegration([candidate], () => ({
|
||||
key: 'KEY',
|
||||
}));
|
||||
|
||||
assert.strictEqual(match.candidate, candidate);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user