2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* DocWorker collects the methods and endpoints that relate to a single Grist document.
|
|
|
|
* In hosted environment, this comprises the functionality of the DocWorker instance type.
|
|
|
|
*/
|
2022-11-15 14:37:48 +00:00
|
|
|
import {isAffirmative} from 'app/common/gutil';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {HomeDBManager} from 'app/gen-server/lib/HomeDBManager';
|
|
|
|
import {ActionHistoryImpl} from 'app/server/lib/ActionHistoryImpl';
|
2022-03-24 10:59:47 +00:00
|
|
|
import {assertAccess, getOrSetDocAuth, RequestWithLogin} from 'app/server/lib/Authorizer';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {Client} from 'app/server/lib/Client';
|
2022-06-04 04:12:30 +00:00
|
|
|
import {Comm} from 'app/server/lib/Comm';
|
2021-04-28 18:53:18 +00:00
|
|
|
import {DocSession, docSessionFromRequest} from 'app/server/lib/DocSession';
|
|
|
|
import {filterDocumentInPlace} from 'app/server/lib/filterUtils';
|
2022-07-19 15:39:49 +00:00
|
|
|
import {GristServer} from 'app/server/lib/GristServer';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {IDocStorageManager} from 'app/server/lib/IDocStorageManager';
|
2022-07-04 14:14:55 +00:00
|
|
|
import log from 'app/server/lib/log';
|
2022-03-24 10:59:47 +00:00
|
|
|
import {getDocId, integerParam, optStringParam, stringParam} from 'app/server/lib/requestUtils';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {OpenMode, quoteIdent, SQLiteDB} from 'app/server/lib/SQLiteDB';
|
2022-07-04 14:14:55 +00:00
|
|
|
import contentDisposition from 'content-disposition';
|
2020-07-21 13:20:51 +00:00
|
|
|
import * as express from 'express';
|
|
|
|
import * as fse from 'fs-extra';
|
|
|
|
import * as mimeTypes from 'mime-types';
|
|
|
|
import * as path from 'path';
|
|
|
|
|
|
|
|
export interface AttachOptions {
|
|
|
|
comm: Comm; // Comm object for methods called via websocket
|
2022-07-19 15:39:49 +00:00
|
|
|
gristServer: GristServer;
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export class DocWorker {
|
|
|
|
private _comm: Comm;
|
2022-07-19 15:39:49 +00:00
|
|
|
private _gristServer: GristServer;
|
|
|
|
constructor(private _dbManager: HomeDBManager, options: AttachOptions) {
|
|
|
|
this._comm = options.comm;
|
|
|
|
this._gristServer = options.gristServer;
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public async getAttachment(req: express.Request, res: express.Response): Promise<void> {
|
|
|
|
try {
|
2021-11-29 20:12:45 +00:00
|
|
|
const docSession = this._getDocSession(stringParam(req.query.clientId, 'clientId'),
|
|
|
|
integerParam(req.query.docFD, 'docFD'));
|
2020-09-02 18:17:17 +00:00
|
|
|
const activeDoc = docSession.activeDoc;
|
2022-07-06 22:36:09 +00:00
|
|
|
const colId = stringParam(req.query.colId, 'colId');
|
|
|
|
const tableId = stringParam(req.query.tableId, 'tableId');
|
|
|
|
const rowId = integerParam(req.query.rowId, 'rowId');
|
|
|
|
const cell = {colId, tableId, rowId};
|
2022-11-15 14:37:48 +00:00
|
|
|
const maybeNew = isAffirmative(req.query.maybeNew);
|
2022-07-06 22:36:09 +00:00
|
|
|
const attId = integerParam(req.query.attId, 'attId');
|
|
|
|
const attRecord = activeDoc.getAttachmentMetadata(attId);
|
|
|
|
const ext = path.extname(attRecord.fileIdent);
|
2020-07-21 13:20:51 +00:00
|
|
|
const type = mimeTypes.lookup(ext);
|
|
|
|
|
|
|
|
let inline = Boolean(req.query.inline);
|
|
|
|
// Serving up user-uploaded HTML files inline is an open door to XSS attacks.
|
|
|
|
if (type === "text/html") { inline = false; }
|
|
|
|
|
|
|
|
// Construct a content-disposition header of the form 'inline|attachment; filename="NAME"'
|
|
|
|
const contentDispType = inline ? "inline" : "attachment";
|
2021-11-29 20:12:45 +00:00
|
|
|
const contentDispHeader = contentDisposition(stringParam(req.query.name, 'name'), {type: contentDispType});
|
2022-11-15 14:37:48 +00:00
|
|
|
const data = await activeDoc.getAttachmentData(docSession, attRecord, {cell, maybeNew});
|
2020-07-21 13:20:51 +00:00
|
|
|
res.status(200)
|
|
|
|
.type(ext)
|
|
|
|
.set('Content-Disposition', contentDispHeader)
|
|
|
|
.set('Cache-Control', 'private, max-age=3600')
|
|
|
|
.send(data);
|
|
|
|
} catch (err) {
|
|
|
|
res.status(404).send({error: err.toString()});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public async downloadDoc(req: express.Request, res: express.Response,
|
|
|
|
storageManager: IDocStorageManager): Promise<void> {
|
|
|
|
const mreq = req as RequestWithLogin;
|
2022-03-24 10:59:47 +00:00
|
|
|
const docId = getDocId(mreq);
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
// Query DB for doc metadata to get the doc title.
|
2022-03-24 10:59:47 +00:00
|
|
|
const doc = await this._dbManager.getDoc(req);
|
2020-07-21 13:20:51 +00:00
|
|
|
const docTitle = doc.name;
|
|
|
|
|
|
|
|
// Get a copy of document for downloading.
|
|
|
|
const tmpPath = await storageManager.getCopy(docId);
|
2023-08-18 10:54:03 +00:00
|
|
|
if (isAffirmative(req.query.template)) {
|
2020-07-21 13:20:51 +00:00
|
|
|
await removeData(tmpPath);
|
2023-08-18 10:54:03 +00:00
|
|
|
await removeHistory(tmpPath);
|
|
|
|
} else if (isAffirmative(req.query.nohistory)) {
|
|
|
|
await removeHistory(tmpPath);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
2023-08-18 10:54:03 +00:00
|
|
|
|
2021-04-28 18:53:18 +00:00
|
|
|
await filterDocumentInPlace(docSessionFromRequest(mreq), tmpPath);
|
2020-07-21 13:20:51 +00:00
|
|
|
// NOTE: We may want to reconsider the mimeType used for Grist files.
|
|
|
|
return res.type('application/x-sqlite3')
|
2023-09-05 18:27:35 +00:00
|
|
|
.download(
|
|
|
|
tmpPath,
|
|
|
|
(optStringParam(req.query.title, 'title') || docTitle || 'document') + ".grist",
|
|
|
|
async (err: any) => {
|
|
|
|
if (err) {
|
|
|
|
if (err.message && /Request aborted/.test(err.message)) {
|
|
|
|
log.warn(`Download request aborted for doc ${docId}`, err);
|
|
|
|
} else {
|
|
|
|
log.error(`Download failure for doc ${docId}`, err);
|
|
|
|
}
|
2022-05-18 21:06:38 +00:00
|
|
|
}
|
2023-09-05 18:27:35 +00:00
|
|
|
await fse.unlink(tmpPath);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
2023-09-05 18:27:35 +00:00
|
|
|
);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Register main methods related to documents.
|
|
|
|
public registerCommCore(): void {
|
|
|
|
const comm = this._comm;
|
|
|
|
comm.registerMethods({
|
|
|
|
closeDoc: activeDocMethod.bind(null, null, 'closeDoc'),
|
|
|
|
fetchTable: activeDocMethod.bind(null, 'viewers', 'fetchTable'),
|
|
|
|
fetchTableSchema: activeDocMethod.bind(null, 'viewers', 'fetchTableSchema'),
|
|
|
|
useQuerySet: activeDocMethod.bind(null, 'viewers', 'useQuerySet'),
|
|
|
|
disposeQuerySet: activeDocMethod.bind(null, 'viewers', 'disposeQuerySet'),
|
|
|
|
applyUserActions: activeDocMethod.bind(null, 'editors', 'applyUserActions'),
|
|
|
|
applyUserActionsById: activeDocMethod.bind(null, 'editors', 'applyUserActionsById'),
|
|
|
|
findColFromValues: activeDocMethod.bind(null, 'viewers', 'findColFromValues'),
|
|
|
|
getFormulaError: activeDocMethod.bind(null, 'viewers', 'getFormulaError'),
|
|
|
|
importFiles: activeDocMethod.bind(null, 'editors', 'importFiles'),
|
|
|
|
finishImportFiles: activeDocMethod.bind(null, 'editors', 'finishImportFiles'),
|
|
|
|
cancelImportFiles: activeDocMethod.bind(null, 'editors', 'cancelImportFiles'),
|
2021-10-08 06:32:59 +00:00
|
|
|
generateImportDiff: activeDocMethod.bind(null, 'editors', 'generateImportDiff'),
|
2020-07-21 13:20:51 +00:00
|
|
|
addAttachments: activeDocMethod.bind(null, 'editors', 'addAttachments'),
|
|
|
|
removeInstanceFromDoc: activeDocMethod.bind(null, 'editors', 'removeInstanceFromDoc'),
|
|
|
|
startBundleUserActions: activeDocMethod.bind(null, 'editors', 'startBundleUserActions'),
|
|
|
|
stopBundleUserActions: activeDocMethod.bind(null, 'editors', 'stopBundleUserActions'),
|
|
|
|
autocomplete: activeDocMethod.bind(null, 'viewers', 'autocomplete'),
|
|
|
|
fetchURL: activeDocMethod.bind(null, 'viewers', 'fetchURL'),
|
|
|
|
getActionSummaries: activeDocMethod.bind(null, 'viewers', 'getActionSummaries'),
|
|
|
|
reloadDoc: activeDocMethod.bind(null, 'editors', 'reloadDoc'),
|
|
|
|
fork: activeDocMethod.bind(null, 'viewers', 'fork'),
|
2020-12-15 04:19:38 +00:00
|
|
|
checkAclFormula: activeDocMethod.bind(null, 'viewers', 'checkAclFormula'),
|
2021-01-14 16:10:42 +00:00
|
|
|
getAclResources: activeDocMethod.bind(null, 'viewers', 'getAclResources'),
|
2021-10-01 13:45:27 +00:00
|
|
|
waitForInitialization: activeDocMethod.bind(null, 'viewers', 'waitForInitialization'),
|
2021-10-08 14:56:33 +00:00
|
|
|
getUsersForViewAs: activeDocMethod.bind(null, 'viewers', 'getUsersForViewAs'),
|
2022-07-19 15:39:49 +00:00
|
|
|
getAccessToken: activeDocMethod.bind(null, 'viewers', 'getAccessToken'),
|
2020-07-21 13:20:51 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// Register methods related to plugins.
|
|
|
|
public registerCommPlugin(): void {
|
|
|
|
this._comm.registerMethods({
|
|
|
|
forwardPluginRpc: activeDocMethod.bind(null, 'editors', 'forwardPluginRpc'),
|
|
|
|
// TODO: consider not providing reloadPlugins on hosted grist, since it affects the
|
|
|
|
// plugin manager shared across docs on a given doc worker, and seems useful only in
|
|
|
|
// standalone case.
|
|
|
|
reloadPlugins: activeDocMethod.bind(null, 'editors', 'reloadPlugins'),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// Checks that document is accessible, and adds docAuth information to request.
|
|
|
|
// Otherwise issues a 403 access denied.
|
|
|
|
// (This is used for endpoints like /download, /gen-csv, /attachment.)
|
|
|
|
public async assertDocAccess(
|
|
|
|
req: express.Request,
|
|
|
|
res: express.Response,
|
|
|
|
next: express.NextFunction
|
|
|
|
) {
|
|
|
|
const mreq = req as RequestWithLogin;
|
|
|
|
let urlId: string|undefined;
|
|
|
|
try {
|
2023-09-05 18:27:35 +00:00
|
|
|
if (optStringParam(req.query.clientId, 'clientId')) {
|
2021-11-29 20:12:45 +00:00
|
|
|
const activeDoc = this._getDocSession(stringParam(req.query.clientId, 'clientId'),
|
|
|
|
integerParam(req.query.docFD, 'docFD')).activeDoc;
|
2020-07-21 13:20:51 +00:00
|
|
|
// TODO: The docId should be stored in the ActiveDoc class. Currently docName is
|
|
|
|
// used instead, which will coincide with the docId for hosted grist but not for
|
|
|
|
// standalone grist.
|
|
|
|
urlId = activeDoc.docName;
|
|
|
|
} else {
|
|
|
|
// Otherwise, if being used without a client, expect the doc query parameter to
|
|
|
|
// be the docId.
|
2021-11-29 20:12:45 +00:00
|
|
|
urlId = stringParam(req.query.doc, 'doc');
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
if (!urlId) { return res.status(403).send({error: 'missing document id'}); }
|
|
|
|
|
2022-07-19 15:39:49 +00:00
|
|
|
const docAuth = await getOrSetDocAuth(mreq, this._dbManager, this._gristServer, urlId);
|
2020-07-21 13:20:51 +00:00
|
|
|
assertAccess('viewers', docAuth);
|
|
|
|
next();
|
|
|
|
} catch (err) {
|
|
|
|
log.info(`DocWorker can't access document ${urlId} with userId ${mreq.userId}: ${err}`);
|
|
|
|
res.status(err.status || 404).send({error: err.toString()});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-02 18:17:17 +00:00
|
|
|
private _getDocSession(clientId: string, docFD: number): DocSession {
|
2020-07-21 13:20:51 +00:00
|
|
|
const client = this._comm.getClient(clientId);
|
2020-09-02 18:17:17 +00:00
|
|
|
return client.getDocSession(docFD);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Translates calls from the browser client into calls of the form
|
|
|
|
* `activeDoc.method(docSession, ...args)`.
|
|
|
|
*/
|
|
|
|
async function activeDocMethod(role: 'viewers'|'editors'|null, methodName: string, client: Client,
|
|
|
|
docFD: number, ...args: any[]): Promise<any> {
|
|
|
|
const docSession = client.getDocSession(docFD);
|
|
|
|
const activeDoc = docSession.activeDoc;
|
|
|
|
if (role) { await docSession.authorizer.assertAccess(role); }
|
|
|
|
// Include a basic log record for each ActiveDoc method call.
|
2020-09-02 18:17:17 +00:00
|
|
|
log.rawDebug('activeDocMethod', activeDoc.getLogMeta(docSession, methodName));
|
2020-07-21 13:20:51 +00:00
|
|
|
return (activeDoc as any)[methodName](docSession, ...args);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-08-18 10:54:03 +00:00
|
|
|
* Remove rows from all user tables.
|
2020-07-21 13:20:51 +00:00
|
|
|
*/
|
|
|
|
async function removeData(filename: string) {
|
|
|
|
const db = await SQLiteDB.openDBRaw(filename, OpenMode.OPEN_EXISTING);
|
|
|
|
const tableIds = (await db.all("SELECT name FROM sqlite_master WHERE type='table'"))
|
|
|
|
.map(row => row.name as string)
|
|
|
|
.filter(name => !name.startsWith('_grist'));
|
|
|
|
for (const tableId of tableIds) {
|
|
|
|
await db.run(`DELETE FROM ${quoteIdent(tableId)}`);
|
|
|
|
}
|
2023-08-18 10:54:03 +00:00
|
|
|
await db.close();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Wipe as much history as we can.
|
|
|
|
*/
|
|
|
|
async function removeHistory(filename: string) {
|
|
|
|
const db = await SQLiteDB.openDBRaw(filename, OpenMode.OPEN_EXISTING);
|
2020-07-21 13:20:51 +00:00
|
|
|
const history = new ActionHistoryImpl(db);
|
|
|
|
await history.deleteActions(1);
|
|
|
|
await db.close();
|
|
|
|
}
|