Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cookie issue fix again #1835

Merged
merged 2 commits into from
Jun 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 31 additions & 15 deletions app/src/os/lib/shipHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,21 @@ export async function getCookie({
throw new Error(`Bad response from server: ${response.status}`);
}
cookie = response.headers.get('set-cookie');
const ship = cookie?.split('; ')[0].split('=')[0].replace('urbauth-', '');
const path = cookie?.split('; ')[1].split('=')[1];
// const maxAge = cookie?.split('; ')[2].split('=')[1];
const value = cookie?.split('=')[1].split('; ')[0];

// const expiresAt = parseInt(maxAge ?? '0') * 1000;

await session.defaultSession.cookies.remove(serverUrl, `urbauth-${ship}`);
await session.defaultSession.cookies.set({
url: serverUrl,
name: `urbauth-${ship}`,
value,
path: path,
});

return cookie;
} catch (e) {
log.error(`Error getting cookie for ${serverUrl}`, e);
Expand All @@ -46,25 +61,26 @@ export async function getCookie({

export async function setSessionCookie(credentials: Credentials) {
const path = credentials.cookie?.split('; ')[1].split('=')[1];
const maxAge = credentials.cookie?.split('; ')[2].split('=')[1];
// const maxAge = credentials.cookie?.split('; ')[2].split('=')[1];
const value = credentials.cookie?.split('=')[1].split('; ')[0];

try {
// remove current cookie
await session
.fromPartition(`persist:webview-${credentials.ship}`)
.cookies.remove(`${credentials.url}`, `urbauth-${credentials.ship}`);
await session.defaultSession.cookies.remove(
`${credentials.url}`,
`urbauth-${credentials.ship}`
);

// set new cookie
return await session
.fromPartition(`persist:webview-${credentials.ship}`)
.cookies.set({
url: `${credentials.url}`,
name: `urbauth-${credentials.ship}`,
value,
expirationDate: new Date(
Date.now() + parseInt(maxAge ?? '0') * 1000
).getTime(),
path: path,
});
return await session.defaultSession.cookies.set({
url: `${credentials.url}`,
name: `urbauth-${credentials.ship}`,
value,
// expirationDate: new Date(
// Date.now() + parseInt(maxAge ?? '0') * 1000
// ).getTime(),
path: path,
});
} catch (e) {
log.error('setSessionCookie error:', e);
}
Expand Down
15 changes: 9 additions & 6 deletions app/src/os/realm.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ export class RealmService extends AbstractService<RealmUpdateTypes> {
app.on(
'web-contents-created',
async (_: Event, webContents: WebContents) => {
webContents.on('will-redirect', (_: Event, url: string) => {
webContents.on('will-redirect', (e: Event, url: string) => {
e.preventDefault();
this.onWillRedirect(url, webContents);
});
}
Expand All @@ -50,6 +51,7 @@ export class RealmService extends AbstractService<RealmUpdateTypes> {
const windows = BrowserWindow.getAllWindows();
windows.forEach(({ webContents }) => {
webContents.on('did-attach-webview', (event, webviewWebContents) => {
log.info("realm.service.ts: 'did-attach-webview' event fired");
this.onWebViewAttached(event, webviewWebContents);
});
});
Expand Down Expand Up @@ -132,6 +134,7 @@ export class RealmService extends AbstractService<RealmUpdateTypes> {
log.error('realm.service.ts:', 'No credentials found');
return false;
}

const cookie = await getCookie({
serverUrl: credentials.url,
serverCode: credentials.code,
Expand Down Expand Up @@ -343,21 +346,21 @@ export class RealmService extends AbstractService<RealmUpdateTypes> {
return;
}

await setSessionCookie({ ...credentials, cookie });
// await setSessionCookie({ ...credentials, cookie });

this.services?.ship?.updateCookie(cookie);
log.info('realm.service.ts', 'reloading after cookie refresh');
webContents.reload();
// webContents.loadURL(url, {
// extraHeaders: `Cookie: ${cookie}`,
// });
}
} catch (e) {
console.error(e);
}
}

async onWebViewAttached(_: any, webContents: WebContents) {
webContents.on('will-redirect', (_, url) => {
this.onWillRedirect(url, webContents);
});

webContents.on('dom-ready', () => {
// TODO wire up libs here
});
Expand Down
16 changes: 8 additions & 8 deletions app/src/os/services/api/api-connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ export class APIConnection {
private constructor(session: ConduitSession) {
this.conduitInstance = new Conduit(session.ship);
this.handleConnectionStatus(this.conduitInstance);
// this.conduitInstance
// .init(session.url, session.code, session.cookie ?? '')
// // .then(() => {
// // log.info('Conduit initialized');
// // })
// .catch((e) => {
// log.error('Conduit initialization failed', e);
// });
this.conduitInstance
.init(session.url, session.code, session.cookie ?? '')
// .then(() => {
// log.info('Conduit initialized');
// })
.catch((e) => {
log.error('Conduit initialization failed', e);
});

app.on('quit', () => {
this.closeChannel();
Expand Down
23 changes: 14 additions & 9 deletions app/src/os/services/api/conduit.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { session } from 'electron';
import log from 'electron-log';
import { deSig, preSig } from '@urbit/aura';
import EventEmitter, { setMaxListeners } from 'events';
import EventSource from 'eventsource';

import { getCookie } from '../../lib/shipHelpers';
import { getCookie, setSessionCookie } from '../../lib/shipHelpers';
import {
Action,
ConduitState,
Expand Down Expand Up @@ -700,13 +699,19 @@ export class Conduit extends EventEmitter {
});
if (cookie) {
this.cookie = cookie;
await session
.fromPartition(`persist:default-${this.ship}`)
.cookies.set({
url: `${this.url}`,
name: `urbauth-${this.ship}`,
value: cookie?.split('=')[1].split('; ')[0],
});
await setSessionCookie({
ship: preSig(this.ship),
url: this.url,
code: this.code,
cookie: this.cookie,
});
// await session
// .fromPartition(`persist:default-${this.ship}`)
// .cookies.set({
// url: `${this.url}`,
// name: `urbauth-${this.ship}`,
// value: cookie?.split('=')[1].split('; ')[0],
// });
this.updateStatus(ConduitState.Refreshed, {
url: this.url,
ship: preSig(this.ship),
Expand Down
43 changes: 20 additions & 23 deletions app/src/os/services/auth/onboarding.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -539,30 +539,27 @@ export class OnboardingService extends AbstractService<OnboardingUpdateTypes> {
const { serverUrl, serverCode, serverId } = (this.credentials ||
creds) as OnboardingCredentials;
const cookie = await this.getCookie({ serverId, serverUrl, serverCode });
// return new Promise(async (resolve, reject) => {
// after 10 seconds, give up
setTimeout(() => {
throw new Error(
'conduit took too long to open (is the url supposed to be https instead of http?)'
);
}, 10000);

const conduit = APIConnection.getInstance({
url: serverUrl,
code: serverCode,
ship: serverId,
cookie,
}).conduit;
conduit
.on('connected', () => {
// resolve(null);
return new Promise((resolve, reject) => {
// after 10 seconds, give up
setTimeout(() => {
reject(
'conduit took too long to open (is the url supposed to be https instead of http?)'
);
}, 10000);
APIConnection.getInstance({
url: serverUrl,
code: serverCode,
ship: serverId,
cookie,
})
.on('error', (err: any) => {
log.error('onboarding.service.ts:', 'Conduit error', err);
// reject(err);
});
console.log('_openConduit: init');
return conduit.init(serverUrl, serverCode, cookie);
.conduit.on('connected', () => {
resolve(null);
})
.on('error', (err: any) => {
log.error('onboarding.service.ts:', 'Conduit error', err);
reject(err);
});
});
}

private _createShipDB(
Expand Down
60 changes: 26 additions & 34 deletions app/src/os/services/ship/ship.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,44 +92,36 @@ export class ShipService extends AbstractService<any> {
}

async _openConduit(credentials: any) {
// return new Promise(async (resolve) => {
console.log('_openConduit');
const conduit = APIConnection.getInstance({
...credentials,
ship: this.patp,
}).conduit;
console.log('_openConduit: events');
conduit
.on('connected', () => {
// resolve(null);
return new Promise((resolve, reject) => {
console.log('_openConduit');
APIConnection.getInstance({
...credentials,
ship: this.patp,
})
.on('failed', () => {
// log.info('ship.service.ts:', 'Conduit failed');
try {
.conduit.on('connected', () => {
resolve(null);
})
.on('failed', () => {
log.info('ship.service.ts:', 'Conduit failed');
this.shipDB?.setCredentials(credentials.url, credentials.code, null);
this.authService?._setLockfile({ ...credentials, cookie: null });
APIConnection.getInstance().closeChannel();
} catch (e) {
log.error(e);
}
// resolve(null);
})
.on('refreshed', (session: ConduitSession) => {
// log.info('ship.service.ts:', 'Conduit refreshed', session);
this.shipDB?.setCredentials(session.url, session.code, session.cookie);
// resolve(null);
})
.on('error', (err: any) => {
log.error('ship.service.ts:', 'Conduit error', err);
// reject(err);
});
console.log('_openConduit: init');
await conduit.init(
credentials.url,
credentials.code,
credentials.cookie || ''
);
// });
resolve(null);
})
.on('refreshed', (session: ConduitSession) => {
// log.info('ship.service.ts:', 'Conduit refreshed', session);
this.shipDB?.setCredentials(
session.url,
session.code,
session.cookie
);
resolve(null);
})
.on('error', (err: any) => {
log.error('ship.service.ts:', 'Conduit error', err);
reject(err);
});
});
}

private _registerServices() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ const AppViewPresenter = ({ isResizing, isDragging, appWindow }: Props) => {
id={`${appWindow.appId}-urbit-webview`}
appId={appWindow.appId}
useragent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:101.0) Gecko/20100101 Firefox/101.0"
partition={`persist:webview-${loggedInAccount?.serverId}`}
// partition={`persist:webview-${loggedInAccount?.serverId}`}
webpreferences="sandbox=false, nativeWindowOpen=yes"
// @ts-ignore
allowpopups="true"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ const DevViewPresenter = ({ appWindow, isResizing }: Props) => {
src={appWindow.href?.site}
webpreferences="sandbox=false"
useragent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:101.0) Gecko/20100101 Firefox/101.0"
partition={`persist:webview-${loggedInAccount?.serverId}`}
// partition={`persist:webview-${loggedInAccount?.serverId}`}
isLocked={isResizing || loading.isOn}
style={{
width: 'inherit',
Expand Down
4 changes: 2 additions & 2 deletions hosting-holium-com/src/pages/account/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ const HostingPresenter = () => {
if (
isUploadedIdentity &&
ships.length === 1 &&
!selectedShip.payment_status
selectedShip.ship_type !== 'planet'
) {
OnboardingStorage.set({
productType: 'byop-p',
Expand All @@ -71,7 +71,7 @@ const HostingPresenter = () => {
const shipToSelect = ships.find((teShip) => teShip.patp === ship);
if (
shipToSelect?.product_type === 'byop-p' &&
!shipToSelect?.payment_status
shipToSelect.ship_type !== 'planet'
) {
OnboardingStorage.set({
productType: 'byop-p',
Expand Down
2 changes: 1 addition & 1 deletion hosting-holium-com/src/pages/upload-id.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export default function UploadId() {
if (
ships.length === 1 &&
ships[0].product_type === 'byop-p' &&
!ships[0].payment_status
ships[0].ship_type !== 'planet'
) {
OnboardingStorage.set({
productType: 'byop-p',
Expand Down
2 changes: 1 addition & 1 deletion shared/src/onboarding/components/AccountDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export const AccountDialog = ({
if (
ship &&
ship.product_type === 'byop-p' &&
!ship.payment_status
ship.ship_type !== 'planet'
) {
return {
value: patp,
Expand Down