Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
tilfin committed Apr 6, 2024
1 parent 35ba172 commit b19dd0d
Show file tree
Hide file tree
Showing 9 changed files with 87 additions and 35 deletions.
4 changes: 1 addition & 3 deletions src/js/handlers/remote_connect.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ export async function remoteCallback(uRL) {
refreshToken: resultToken.refresh_token,
};
await localRepo.set({ remoteConnectInfo });
const { profile } = await oauthClient.getUserConfig(resultToken.id_token);
return { profile };
return await oauthClient.getUserConfig(resultToken.id_token);
}

export async function getRemoteConnectInfo() {
Expand All @@ -58,7 +57,6 @@ export function deleteRemoteConnectInfo() {

export async function deleteRefreshTokenFromRemoteConnectInfo() {
const localRepo = StorageProvider.getLocalRepository();
localRepo.delete(['remoteConnectInfo']);
const { remoteConnectInfo } = await localRepo.get(['remoteConnectInfo']);
delete remoteConnectInfo.refreshToken;
await localRepo.set({ remoteConnectInfo });
Expand Down
16 changes: 5 additions & 11 deletions src/js/handlers/update_profiles.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { nowEpochSeconds } from "../lib/util.js";
import { DataProfilesSplitter } from "../lib/data_profiles_splitter.js";
import { writeProfileSetToTable, writeProfileItemsToTable, refreshDB } from "../lib/profile_db.js";
import { writeProfileItemsToTable, refreshDB } from "../lib/profile_db.js";
import { StorageProvider } from "../lib/storage_repository.js";
import { saveConfigIni } from "../lib/config_ini.js";
import { OAuthClient } from "../remote/oauth-client.js";
import { deleteRefreshTokenFromRemoteConnectInfo } from "./remote_connect.js";
import { reloadConfig } from "../lib/reload-config.js";

export async function updateProfilesTable() {
const syncRepo = StorageProvider.getSyncRepository();
Expand All @@ -14,15 +13,10 @@ export async function updateProfilesTable() {
const { profilesTableUpdated = 0, remoteConnectInfo = null } = await localRepo.get(['profilesTableUpdated', 'remoteConnectInfo']);

if (remoteConnectInfo) {
const oaClient = new OAuthClient(remoteConnectInfo.subdomain, remoteConnectInfo.clientId);
try {
const idToken = await oaClient.getIdTokenByRefresh(remoteConnectInfo.refreshToken);
const { profile } = await oaClient.getUserConfig(idToken);
await writeProfileSetToTable(profile);
console.log('Updated profile from Config Hub');
} catch {
await deleteRefreshTokenFromRemoteConnectInfo();
console.warn('Failed to profile from Config Hub, so the refresh token was deleted.');
await reloadConfig(remoteConnectInfo);
} catch (err) {
console.warn('Failed to get profile from Config Hub');
}
return;
}
Expand Down
6 changes: 4 additions & 2 deletions src/js/lib/profile_db.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,17 @@ export async function writeProfileSetToTable(profileSet) {
});

await dbManager.transaction('profiles', async dbTable => {
const { singles = [], complexes = [] } = profileSet;
let i = 0;
for (const profile of profileSet.singles) {

for (const profile of singles) {
await dbTable.insert({
profilePath: `[SINGLE];${formatNum(++i)}`,
...profile,
});
}

for (const baseProfile of profileSet.complexes) {
for (const baseProfile of complexes) {
const { targets, ...props } = baseProfile;
await dbTable.insert({
profilePath: `[COMPLEX];${formatNum(++i)}`,
Expand Down
21 changes: 21 additions & 0 deletions src/js/lib/reload-config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { OAuthClient, RefreshTokenError } from "../remote/oauth-client.js";
import { writeProfileSetToTable } from "./profile_db.js";
import { deleteRefreshTokenFromRemoteConnectInfo } from "../handlers/remote_connect.js";

export async function reloadConfig(remoteConnectInfo) {
const oaClient = new OAuthClient(remoteConnectInfo.subdomain, remoteConnectInfo.clientId);
try {
const idToken = await oaClient.getIdTokenByRefresh(remoteConnectInfo.refreshToken);
const { profile } = await oaClient.getUserConfig(idToken);
await writeProfileSetToTable(profile);
console.log('Updated profile from Config Hub');
return true;
} catch (err) {
if (err instanceof RefreshTokenError) {
await deleteRefreshTokenFromRemoteConnectInfo();
console.log('Refresh token is expired');
return false;
}
throw err;
}
}
32 changes: 17 additions & 15 deletions src/js/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { ColorPicker } from './lib/color_picker.js';
import { SessionMemory, StorageProvider } from './lib/storage_repository.js';
import { writeProfileSetToTable } from "./lib/profile_db.js";
import { remoteConnect, getRemoteConnectInfo, deleteRemoteConnectInfo } from './handlers/remote_connect.js';
import { OAuthClient } from './remote/oauth-client.js';
import { reloadConfig } from './lib/reload-config.js';

function elById(id) {
return document.getElementById(id);
Expand Down Expand Up @@ -36,18 +36,20 @@ window.onload = function() {
deleteRemoteConnectInfo();
}
elById('reloadConfigHubButton').onclick = function() {
getRemoteConnectInfo().then(({ subdomain, clientId, refreshToken }) => {
if (subdomain && clientId) {
const oaClient = new OAuthClient(subdomain, clientId);
oaClient.getIdTokenByRefresh(refreshToken).then(idToken => {
return oaClient.getUserConfig(idToken);
}).then(({ profile }) => {
return writeProfileSetToTable(profile);
}).then(() => {
updateMessage('remoteMsgSpan', "Successfully reloaded config from Hub!");
getRemoteConnectInfo().then(rci => {
if (rci && rci.subdomain && rci.clientId) {
reloadConfig(rci).then(result => {
if (result) {
updateMessage('remoteMsgSpan', "Successfully reloaded config from Hub!");
} else {
updateMessage('remoteMsgSpan', `Failed to reload because the connection expired.`, 'warn');
updateRemoteFieldsState('disconnected');
}
}).catch(e => {
updateMessage('remoteMsgSpan', `Failed to reload because ${e.message}`, 'warn');
});
} else {
updateMessage('remoteMsgSpan', `Failed to reload because the connection is broken.`, 'warn');
}
});
}
Expand Down Expand Up @@ -102,11 +104,11 @@ window.onload = function() {
syncStorageRepo.set({ signinEndpointInHere: this.checked });
}

getRemoteConnectInfo().then(({ subdomain, clientId, refreshToken }) => {
if (subdomain && clientId) {
elById('configHubDomain').value = subdomain;
elById('configHubClientId').value = clientId;
if (refreshToken) {
getRemoteConnectInfo().then(rci => {
if (rci && rci.subdomain && rci.clientId) {
elById('configHubDomain').value = rci.subdomain;
elById('configHubClientId').value = rci.clientId;
if (rci.refreshToken) {
updateRemoteFieldsState('connected');
} else {
updateRemoteFieldsState('disconnected');
Expand Down
14 changes: 11 additions & 3 deletions src/js/popup.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { CurrentContext } from './lib/current_context.js';
import { findTargetProfiles } from './lib/target_profiles.js';
import { SessionMemory, SyncStorageRepository } from './lib/storage_repository.js';
import { remoteCallback } from './handlers/remote_connect.js';
import { writeProfileSetToTable } from './lib/profile_db.js';

const sessionMemory = new SessionMemory(chrome || browser);

Expand All @@ -26,6 +27,12 @@ async function getCurrentTab() {
return tab;
}

async function moveTabToOption(tabId) {
const brw = chrome || browser;
const url = await brw.runtime.getURL('options.html');
await brw.tabs.update(tabId, { url });
}

async function executeAction(tabId, action, data) {
return (chrome || browser).tabs.sendMessage(tabId, { action, data });
}
Expand Down Expand Up @@ -95,15 +102,16 @@ function main() {
})
} else if (url.host.endsWith('.aesr.dev') && url.pathname.startsWith('/callback')) {
remoteCallback(url)
.then(() => {
.then(userCfg => {
const p = noMain.querySelector('p');
p.textContent = "Successfully connected to AESR Config Hub!";
noMain.style.display = 'block';
return writeProfileSetToTable(userCfg.profile);
})
.then(() => moveTabToOption(tab.id))
.catch(err => {
console.error(err);
const p = noMain.querySelector('p');
p.textContent = "Failed to connected to AESR Config Hub.";
p.textContent = `Failed to connect to AESR Config Hub because.\n${err.message}`;
noMain.style.display = 'block';
});
} else {
Expand Down
21 changes: 21 additions & 0 deletions src/js/remote/oauth-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ export class OAuthClient {

validateCallbackUrl(uRL) {
if (uRL.host === `api.${this.domain}` && uRL.pathname === '/callback') {
const error = uRL.searchParams.get('error');
if (error) {
let errmsg = error;
const errDesc = uRL.searchParams.get('error_description');
if (errDesc) errmsg += ': ' + errDesc;
throw new Error(errmsg);
}
const authCode = uRL.searchParams.get('code');
if (authCode) return authCode;
}
Expand All @@ -50,6 +57,9 @@ export class OAuthClient {
body: new URLSearchParams(params),
});
const result = await res.json();
if (!res.ok) {
throw new Error(result.error);
}
return result;
}

Expand All @@ -68,6 +78,12 @@ export class OAuthClient {
body: new URLSearchParams(params),
});
const result = await res.json();
if (!res.ok) {
if (result.error === 'invalid_grant') {
throw new RefreshTokenError('refresh token is invalid');
}
throw new Error(result.error);
}
return result.id_token;
}

Expand All @@ -79,6 +95,11 @@ export class OAuthClient {
},
})
const result = await res.json();
if (!res.ok) {
throw new Error(result.message);
}
return result;
}
}

export class RefreshTokenError extends Error {}
1 change: 1 addition & 0 deletions src/popup.html
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
margin: 12px 5px 5px 5px;
line-height: 1.66;
color: #666;
white-space: pre-wrap;
}
#supportComment p {
line-height: 1.25;
Expand Down
7 changes: 6 additions & 1 deletion src/updated.html
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,12 @@ <h3>'Sign-in endpoint in current region' setting (Experimental, Supporters only)

<hr style="margin:18px 0">

<h2>4.0.3 <span style="margin-left:0.75em; color:rgb(221, 63, 0)">New version!</span></h2>
<h2>5.0.0 <span style="margin-left:0.75em; color:rgb(221, 63, 0)">New version!</span></h2>
<ul>
<li>Add support for remote retrieval of user configurations through <a href="https://aesr.dev/" target="_blank"><b>AESR Config Hub</b></a>, facilitating dynamic configuration management.</li>
</ul>

<h2>4.0.3</h2>
<ul>
<li>Implement fallback for displaying the role list in Firefox private browsing mode</li>
</ul>
Expand Down

0 comments on commit b19dd0d

Please sign in to comment.