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

Add share link feature #150

Merged
merged 2 commits into from
May 16, 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
16 changes: 16 additions & 0 deletions packages/collaboration-extension/schema/shared-link.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"title": "Shared link",
"description": "Shared link settings",
"jupyter.lab.toolbars": {
"TopBar": [
{
"name": "@jupyter/collaboration:shared-link",
"command": "collaboration:shared-link",
"rank": 99
}
]
},
"properties": {},
"additionalProperties": false,
"type": "object"
}
2 changes: 2 additions & 0 deletions packages/collaboration-extension/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
rtcPanelPlugin,
userEditorCursors
} from './collaboration';
import { sharedLink } from './sharedlink';

/**
* Export the plugins as default.
Expand All @@ -35,6 +36,7 @@ const plugins: JupyterFrontEndPlugin<any>[] = [
menuBarPlugin,
rtcGlobalAwarenessPlugin,
rtcPanelPlugin,
sharedLink,
userEditorCursors
];

Expand Down
56 changes: 56 additions & 0 deletions packages/collaboration-extension/src/sharedlink.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

import {
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import { Clipboard, ICommandPalette } from '@jupyterlab/apputils';
import { ITranslator, nullTranslator } from '@jupyterlab/translation';
import { shareIcon } from '@jupyterlab/ui-components';

import { showSharedLinkDialog } from '@jupyter/collaboration';

/**
* The command IDs used by the plugin.
*/
namespace CommandIDs {
export const share = 'collaboration:shared-link';
}

/**
* Plugin to share the URL of the running Jupyter Server
*/
export const sharedLink: JupyterFrontEndPlugin<void> = {
id: '@jupyter/collaboration-extension:shared-link',
autoStart: true,
optional: [ICommandPalette, ITranslator],
activate: async (
app: JupyterFrontEnd,
palette: ICommandPalette | null,
translator: ITranslator | null
) => {
const { commands } = app;
const trans = (translator ?? nullTranslator).load('collaboration');

commands.addCommand(CommandIDs.share, {
label: trans.__('Generate a Shared Link'),
icon: shareIcon,
execute: async () => {
const result = await showSharedLinkDialog({
translator
});
if (result.button.accept && result.value) {
Clipboard.copyToSystem(result.value);
}
}
});

if (palette) {
palette.addItem({
command: CommandIDs.share,
category: trans.__('Server')
});
}
}
};
3 changes: 2 additions & 1 deletion packages/collaboration/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
*/

export * from './tokens';
export * from './collaboratorspanel';
export * from './cursors';
export * from './menu';
export * from './sharedlink';
export * from './userinfopanel';
export * from './collaboratorspanel';
197 changes: 197 additions & 0 deletions packages/collaboration/src/sharedlink.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

import { Dialog, showDialog } from '@jupyterlab/apputils';

import { PageConfig, URLExt } from '@jupyterlab/coreutils';

import {
ITranslator,
TranslationBundle,
nullTranslator
} from '@jupyterlab/translation';

import { Widget } from '@lumino/widgets';

import { Message } from '@lumino/messaging';

/**
* Shared link dialog options
*/
export interface ISharedLinkDialogOptions {
/**
* Translation object.
*/
translator?: ITranslator | null;
}

/**
* Show the shared link dialog
*
* @param options Shared link dialog options
* @returns Dialog result
*/
export async function showSharedLinkDialog({
translator
}: ISharedLinkDialogOptions): Promise<Dialog.IResult<string>> {
const trans = (translator ?? nullTranslator).load('collaboration');

const token = PageConfig.getToken();
const url = new URL(
URLExt.normalize(
PageConfig.getUrl({
workspace: PageConfig.defaultWorkspace
})
)
);

return showDialog({
title: trans.__('Share Jupyter Server Link'),
body: new SharedLinkBody(
url.toString(),
token,
PageConfig.getOption('hubUser') !== '',
trans
),
buttons: [
Dialog.cancelButton(),
Dialog.okButton({
label: trans.__('Copy Link'),
caption: trans.__('Copy the link to the Jupyter Server')
})
]
});
}

class SharedLinkBody extends Widget implements Dialog.IBodyWidget {
private _tokenCheckbox: HTMLInputElement | null = null;
private _warning: HTMLDivElement;

constructor(
private _url: string,
private _token: string,
private _behindHub: boolean,
private _trans: TranslationBundle
) {
super();
this._warning = document.createElement('div');
this.populateBody(this.node);
this.addClass('jp-shared-link-body');
}

/**
* Returns the input value.
*/
getValue(): string {
const withToken = this._tokenCheckbox?.checked === true;

if (withToken) {
const url_ = new URL(this._url);
url_.searchParams.set('token', this._token);
return url_.toString();
} else {
return this._url;
}
}

protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
this._tokenCheckbox?.addEventListener('change', this.onTokenChange);
}

protected onBeforeDetach(msg: Message): void {
this._tokenCheckbox?.removeEventListener('change', this.onTokenChange);
super.onBeforeDetach(msg);
}

private updateContent(withToken: boolean): void {
this._warning.innerHTML = '';
const urlInput =
this.node.querySelector<HTMLInputElement>('input[readonly]');
if (withToken) {
if (urlInput) {
const url_ = new URL(this._url);
url_.searchParams.set('token', this._token.slice(0, 5));
urlInput.value = url_.toString() + '…';
}
this._warning.appendChild(document.createElement('h3')).textContent =
this._trans.__('Security warning!');
this._warning.insertAdjacentText(
'beforeend',
this._trans.__(
'Anyone with this link has full access to your notebook server, including all your files!'
)
);
this._warning.insertAdjacentHTML('beforeend', '<br>');
this._warning.insertAdjacentText(
'beforeend',
this._trans.__('Please be careful who you share it with.')
);
this._warning.insertAdjacentHTML('beforeend', '<br>');
if (this._behindHub) {
this._warning.insertAdjacentText(
'beforeend', // You can restart the server to revoke the token in a JupyterHub
this._trans.__('They will be able to access this server AS YOU.')
);
this._warning.insertAdjacentHTML('beforeend', '<br>');
this._warning.insertAdjacentText(
'beforeend',
this._trans.__(
'To revoke access, go to File -> Hub Control Panel, and restart your server.'
)
);
} else {
this._warning.insertAdjacentText(
'beforeend',
// Elsewhere, you *must* shut down your server - no way to revoke it
this._trans.__(
'Currently, there is no way to revoke access other than shutting down your server.'
)
);
}
} else {
if (urlInput) {
urlInput.value = this._url;
}
if (this._behindHub) {
this._warning.insertAdjacentText(
'beforeend',
this._trans.__(
'Only users with `access:servers` permissions for this server will be able to use this link.'
)
);
} else {
this._warning.insertAdjacentText(
'beforeend',
this._trans.__(
'Only authenticated users will be able to use this link.'
)
);
}
}
}

private onTokenChange = (e: Event) => {
const target = e.target as HTMLInputElement;
this.updateContent(target?.checked);
};

private populateBody(dialogBody: HTMLElement): void {
dialogBody.insertAdjacentHTML(
'afterbegin',
`<input readonly value="${this._url}">`
);

if (this._token) {
const label = dialogBody.appendChild(document.createElement('label'));
label.insertAdjacentHTML('beforeend', '<input type="checkbox">');
this._tokenCheckbox = label.firstChild as HTMLInputElement;
label.insertAdjacentText(
'beforeend',
this._trans.__('Include token in URL')
);
dialogBody.insertAdjacentElement('beforeend', this._warning);
this.updateContent(false);
}
}
}
43 changes: 0 additions & 43 deletions packages/collaboration/src/utils.ts

This file was deleted.

4 changes: 4 additions & 0 deletions packages/collaboration/style/base.css
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@

@import url('./menu.css');
@import url('./sidepanel.css');

.jp-shared-link-body {
user-select: none;
}
29 changes: 21 additions & 8 deletions packages/docprovider/src/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,24 +39,37 @@ export async function requestDocSession(
type: string,
path: string
): Promise<ISessionModel> {
const { makeSettings, makeRequest, ResponseError } = ServerConnection;

const settings = makeSettings();
const settings = ServerConnection.makeSettings();
const url = URLExt.join(
settings.baseUrl,
DOC_SESSION_URL,
encodeURIComponent(path)
);
const data = {
const body = {
method: 'PUT',
body: JSON.stringify({ format, type })
};

const response = await makeRequest(url, data, settings);
let response: Response;
try {
response = await ServerConnection.makeRequest(url, body, settings);
} catch (error) {
throw new ServerConnection.NetworkError(error as Error);
}

let data: any = await response.text();

if (data.length > 0) {
try {
data = JSON.parse(data);
} catch (error) {
console.log('Not a JSON response body.', response);
}
}

if (response.status !== 200 && response.status !== 201) {
throw new ResponseError(response);
if (!response.ok) {
throw new ServerConnection.ResponseError(response, data.message || data);
}

return response.json();
return data;
}
1 change: 0 additions & 1 deletion tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

Loading