WIP Add Discourse integration

This commit is contained in:
raucao committed 2025-11-05 11:45:00 +01:00
1 parent f1c6d684d0
commit 2d71d49884
7 files changed
+448 -11

No files matched your search

@@ -1,14 +1,238 @@
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { service } from '@ember/service';
import { on } from '@ember/modifier';
export default class SettingsAddIntegrationDiscourse extends Component {
@service storage;
@tracked discourseUrl = '';
@tracked error = null;
@action
updateUrl(event) {
this.discourseUrl = event.target.value;
this.error = null;
}
@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;
}
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();
} catch (err) {
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 id="dialog-title" class="text-base font-semibold leading-6 text-gray-900">Add Discourse Integration</h3>
<div class="mt-2">
<p class="text-sm text-gray-500">
Configure your Discourse forum integration here.
Enter your Discourse forum URL to connect and receive notifications.
</p>
</div>
<form {{on "submit" this.handleSubmit}} class="mt-5">
<div>
<label for="discourse-url" class="block text-sm font-medium leading-6 text-gray-900">
Discourse URL
</label>
<div class="mt-2">
<input
type="text"
id="discourse-url"
value={{this.discourseUrl}}
{{on "input" this.updateUrl}}
placeholder="forum.example.com"
class="block w-full rounded-md border-0 px-3 py-2 text-sm text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600"
/>
</div>
{{#if this.error}}
<p class="mt-2 text-sm text-red-600">{{this.error}}</p>
{{/if}}
</div>
<div class="mt-5 sm:mt-6 flex gap-3">
<button
type="submit"
class="inline-flex w-full justify-center rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Continue
</button>
<button
type="button"
{{on "click" @closeDialog}}
class="inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50"
>
Cancel
</button>
</div>
</form>
</div>
</template>
}
@@ -0,0 +1,61 @@
import Component from '@glimmer/component';
import { action } from '@ember/object';
import { service } from '@ember/service';
export default class IntegrationResultDialog extends Component {
@service router;
get isSuccess() {
return this.args.result?.success;
}
get isError() {
return this.args.result?.error;
}
@action
goBack() {
this.router.transitionTo('index');
}
<template>
<div>
<div class="mx-auto flex size-12 items-center justify-center rounded-full {{if this.isSuccess 'bg-green-100' 'bg-red-100'}}">
{{#if this.isSuccess}}
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" data-slot="icon" aria-hidden="true" class="size-6 text-green-600">
<path d="m4.5 12.75 6 6 9-13.5" stroke-linecap="round" stroke-linejoin="round" />
</svg>
{{else}}
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" data-slot="icon" aria-hidden="true" class="size-6 text-red-600">
<path d="M6 18L18 6M6 6l12 12" stroke-linecap="round" stroke-linejoin="round" />
</svg>
{{/if}}
</div>
<div class="mt-3 text-center sm:mt-5">
<h3 id="dialog-title" class="text-base font-semibold text-gray-900">
{{if this.isSuccess "Integration Successful!" "Integration Failed"}}
</h3>
<div class="mt-2">
<p class="text-sm text-gray-500">
{{#if this.isSuccess}}
Your Discourse forum has been connected successfully. You can now receive notifications from your forum.
{{else}}
{{@result.error}}
{{/if}}
</p>
</div>
</div>
</div>
<div class="mt-5 sm:mt-6">
<button
type="button"
command="close"
commandfor="integration-result-dialog"
onclick={{this.goBack}}
class="inline-flex w-full justify-center rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-xs hover:bg-indigo-500 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Go back to dashboard
</button>
</div>
</template>
}
+7 -1
View File
@@ -6,4 +6,10 @@ export default class Router extends EmberRouter {
rootURL = config.rootURL;
}
Router.map(function () {});
Router.map(function () {
this.route('auth', function() {
this.route('discourse', function() {
this.route('callback');
});
});
});
+113
View File
@@ -0,0 +1,113 @@
import Route from '@ember/routing/route';
import { service } from '@ember/service';
import forge from 'node-forge';
export default class AuthDiscourseCallbackRoute extends Route {
@service storage;
@service router;
async model(params) {
const urlParams = new URLSearchParams(window.location.search);
const payload = urlParams.get('payload');
if (!payload) {
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 pendingIntegration = pendingIntegrations.find(
({ data }) => data && data.status === 'pending'
);
if (!pendingIntegration) {
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)
);
// 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);
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
});
return {
success: true,
integration: {
...pendingIntegration.data,
status: 'active'
}
};
} catch (error) {
console.error('Error processing Discourse callback:', error);
return { error: error.message };
}
}
afterModel(model) {
// Don't auto-redirect anymore - let the user close the dialog
}
}
+26
View File
@@ -0,0 +1,26 @@
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((element) => {
// 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>
+4 -5
View File
@@ -80,7 +80,9 @@
"tailwindcss": "^4.1.16",
"testem": "^3.16.0",
"tracked-built-ins": "^4.0.0",
"vite": "^7.1.9"
"vite": "^7.1.9",
"localforage": "^1.10.0",
"node-forge": "^1.3.1"
},
"engines": {
"node": ">= 20"
@@ -88,8 +90,5 @@
"ember": {
"edition": "octane"
},
"packageManager": "pnpm@9.15.4+sha512.b2dc20e2fc72b3e18848459b37359a32064663e5627a51e4c74b2c29dd8e8e0491483c3abb40789cfd578bf362fb6ba8261b05f0387d76792ed6e23ea3b1b6a0",
"dependencies": {
"localforage": "^1.10.0"
}
"packageManager": "pnpm@9.15.4+sha512.b2dc20e2fc72b3e18848459b37359a32064663e5627a51e4c74b2c29dd8e8e0491483c3abb40789cfd578bf362fb6ba8261b05f0387d76792ed6e23ea3b1b6a0"
}
+12 -4
View File
@@ -7,10 +7,6 @@ settings:
importers:
.:
dependencies:
localforage:
specifier: ^1.10.0
version: 1.10.0
devDependencies:
'@babel/core':
specifier: ^7.28.4
@@ -132,6 +128,12 @@ importers:
globals:
specifier: ^16.4.0
version: 16.4.0
localforage:
specifier: ^1.10.0
version: 1.10.0
node-forge:
specifier: ^1.3.1
version: 1.3.1
postcss:
specifier: ^8.5.6
version: 8.5.6
@@ -4507,6 +4509,10 @@ packages:
no-case@3.0.4:
resolution: {integrity: sha512-fgAN3jGAh+RoxUGZHTSOLJIqUc2wmoBwGR4tbpNAKmmovFoWq0OdRkb0VkldReO2a2iBT/OEulG9XSUc10r3zg==}
node-forge@1.3.1:
resolution: {integrity: sha512-dPEtOeMvF9VMcYV/1Wb8CPoVAXtp6MKMlcbAt4ddqmGqUJ6fQZFXkNZNkNlfevtNkGtaSoXf/vNNNSvgrdXwtA==}
engines: {node: '>= 6.13.0'}
node-int64@0.4.0:
resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==}
@@ -11414,6 +11420,8 @@ snapshots:
lower-case: 2.0.2
tslib: 2.8.1
node-forge@1.3.1: {}
node-int64@0.4.0: {}
node-notifier@10.0.1: