2022-10-13 13:13:01 +00:00
|
|
|
import {ApiError} from 'app/common/ApiError';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {delay} from 'app/common/delay';
|
|
|
|
import {DocCreationInfo} from 'app/common/DocListAPI';
|
2023-06-06 17:08:50 +00:00
|
|
|
import {encodeUrl, getSlugIfNeeded, GristDeploymentType, GristDeploymentTypes,
|
|
|
|
GristLoadConfig, IGristUrlState, isOrgInPathOnly, parseSubdomain,
|
|
|
|
sanitizePathTail} from 'app/common/gristUrls';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {getOrgUrlInfo} from 'app/common/gristUrls';
|
2023-09-06 18:35:46 +00:00
|
|
|
import {safeJsonParse} from 'app/common/gutil';
|
2023-07-04 21:21:34 +00:00
|
|
|
import {InstallProperties} from 'app/common/InstallAPI';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {UserProfile} from 'app/common/LoginSessionAPI';
|
|
|
|
import {tbind} from 'app/common/tbind';
|
|
|
|
import * as version from 'app/common/version';
|
2023-03-21 13:32:34 +00:00
|
|
|
import {ApiServer, getOrgFromRequest} from 'app/gen-server/ApiServer';
|
2021-03-18 22:40:02 +00:00
|
|
|
import {Document} from "app/gen-server/entity/Document";
|
|
|
|
import {Organization} from "app/gen-server/entity/Organization";
|
|
|
|
import {Workspace} from 'app/gen-server/entity/Workspace';
|
2022-05-11 19:05:35 +00:00
|
|
|
import {Activations} from 'app/gen-server/lib/Activations';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {DocApiForwarder} from 'app/gen-server/lib/DocApiForwarder';
|
|
|
|
import {getDocWorkerMap} from 'app/gen-server/lib/DocWorkerMap';
|
|
|
|
import {HomeDBManager} from 'app/gen-server/lib/HomeDBManager';
|
|
|
|
import {Housekeeper} from 'app/gen-server/lib/Housekeeper';
|
|
|
|
import {Usage} from 'app/gen-server/lib/Usage';
|
2022-07-19 15:39:49 +00:00
|
|
|
import {AccessTokens, IAccessTokens} from 'app/server/lib/AccessTokens';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {attachAppEndpoint} from 'app/server/lib/AppEndpoint';
|
2022-06-03 14:54:49 +00:00
|
|
|
import {appSettings} from 'app/server/lib/AppSettings';
|
2023-09-06 18:35:46 +00:00
|
|
|
import {addRequestUser, getTransitiveHeaders, getUser, getUserId, isAnonymousUser,
|
2023-03-21 13:32:34 +00:00
|
|
|
isSingleUserMode, redirectToLoginUnconditionally} from 'app/server/lib/Authorizer';
|
2021-10-01 14:24:23 +00:00
|
|
|
import {redirectToLogin, RequestWithLogin, signInStatusMiddleware} from 'app/server/lib/Authorizer';
|
2021-11-24 14:50:44 +00:00
|
|
|
import {forceSessionChange} from 'app/server/lib/BrowserSession';
|
2022-06-04 04:12:30 +00:00
|
|
|
import {Comm} from 'app/server/lib/Comm';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {create} from 'app/server/lib/create';
|
2021-10-01 14:24:23 +00:00
|
|
|
import {addDiscourseConnectEndpoints} from 'app/server/lib/DiscourseConnect';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {addDocApiRoutes} from 'app/server/lib/DocApi';
|
|
|
|
import {DocManager} from 'app/server/lib/DocManager';
|
|
|
|
import {DocStorageManager} from 'app/server/lib/DocStorageManager';
|
|
|
|
import {DocWorker} from 'app/server/lib/DocWorker';
|
|
|
|
import {DocWorkerInfo, IDocWorkerMap} from 'app/server/lib/DocWorkerMap';
|
2022-01-07 18:11:52 +00:00
|
|
|
import {expressWrap, jsonErrorHandler, secureJsonErrorHandler} from 'app/server/lib/expressWrap';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {Hosts, RequestWithOrg} from 'app/server/lib/extractOrg';
|
2021-10-01 14:24:23 +00:00
|
|
|
import {addGoogleAuthEndpoint} from "app/server/lib/GoogleAuth";
|
2023-02-13 20:52:17 +00:00
|
|
|
import {DocTemplate, GristLoginMiddleware, GristLoginSystem, GristServer,
|
|
|
|
RequestWithGrist} from 'app/server/lib/GristServer';
|
(core) support GRIST_WORKER_GROUP to place worker into an exclusive group
Summary:
In an emergency, we may want to serve certain documents with "old" workers as we fix problems. This diff adds some support for that.
* Creates duplicate task definitions and services for staging and production doc workers (called grist-docs-staging2 and grist-docs-prod2), pulling from distinct docker tags (staging2 and prod2). The services are set to have zero workers until we need them.
* These new workers are started with a new env variable `GRIST_WORKER_GROUP` set to `secondary`.
* The `GRIST_WORKER_GROUP` variable, if set, makes the worker available to documents in the named group, and only that group.
* An unauthenticated `/assign` endpoint is added to documents which, when POSTed to, checks that the doc is served by a worker in the desired group for that doc (as set manually in redis), and if not frees the doc up for reassignment. This makes it possible to move individual docs between workers without redeployments.
The bash scripts added are a record of how the task definitions + services were created. The services could just have been copied manually, but the task definitions will need to be updated whenever the definitions for the main doc workers are updated, so it is worth scripting that.
For example, if a certain document were to fail on a new deployment of Grist, but rolling back the full deployment wasn't practical:
* Set prod2 tag in docker to desired codebase for that document
* Set desired_count for grist-docs-prod2 service to non-zero
* Set doc-<docid>-group for that doc in redis to secondary
* Hit /api/docs/<docid>/assign to move the doc to grist-docs-prod2
(If the document needs to be reverted to a previous snapshot, that currently would need doing manually - could be made simpler, but not in scope of this diff).
Test Plan: added tests
Reviewers: dsagal
Reviewed By: dsagal
Differential Revision: https://phab.getgrist.com/D2649
2020-11-02 19:24:46 +00:00
|
|
|
import {initGristSessions, SessionStore} from 'app/server/lib/gristSessions';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {HostedStorageManager} from 'app/server/lib/HostedStorageManager';
|
|
|
|
import {IBilling} from 'app/server/lib/IBilling';
|
|
|
|
import {IDocStorageManager} from 'app/server/lib/IDocStorageManager';
|
|
|
|
import {INotifier} from 'app/server/lib/INotifier';
|
2022-07-04 14:14:55 +00:00
|
|
|
import log from 'app/server/lib/log';
|
2022-03-07 16:40:46 +00:00
|
|
|
import {getLoginSystem} from 'app/server/lib/logins';
|
2021-01-12 15:48:40 +00:00
|
|
|
import {IPermitStore} from 'app/server/lib/Permit';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {getAppPathTo, getAppRoot, getUnpackedAppRoot} from 'app/server/lib/places';
|
|
|
|
import {addPluginEndpoints, limitToPlugins} from 'app/server/lib/PluginEndpoint';
|
|
|
|
import {PluginManager} from 'app/server/lib/PluginManager';
|
(core) For exporting XLSX, do it memory-efficiently in a worker thread.
Summary:
- Excel exports were awfully memory-inefficient, causing occasional docWorker
crashes. The fix is to use the "streaming writer" option of ExcelJS
https://github.com/exceljs/exceljs#streaming-xlsx-writercontents. (Empirically
on one example, max memory went down from 3G to 100M)
- It's also CPU intensive and synchronous, and can block node for tens of
seconds. The fix is to use a worker-thread. This diff uses "piscina" library
for a pool of threads.
- Additionally, adds ProcessMonitor that logs memory and cpu usage,
particularly when those change significantly.
- Also introduces request cancellation, so that a long download cancelled by
the user will cancel the work being done in the worker thread.
Test Plan:
Updated previous export tests; memory and CPU performance tested
manually by watching output of ProcessMonitor.
Difference visible in these log excerpts:
Before (total time to serve request 22 sec):
```
Telemetry processMonitor heapUsedMB=2187, heapTotalMB=2234, cpuAverage=1.13, intervalMs=17911
Telemetry processMonitor heapUsedMB=2188, heapTotalMB=2234, cpuAverage=0.66, intervalMs=5005
Telemetry processMonitor heapUsedMB=2188, heapTotalMB=2234, cpuAverage=0, intervalMs=5005
Telemetry processMonitor heapUsedMB=71, heapTotalMB=75, cpuAverage=0.13, intervalMs=5002
```
After (total time to server request 18 sec):
```
Telemetry processMonitor heapUsedMB=109, heapTotalMB=144, cpuAverage=0.5, intervalMs=5001
Telemetry processMonitor heapUsedMB=109, heapTotalMB=144, cpuAverage=1.39, intervalMs=5002
Telemetry processMonitor heapUsedMB=94, heapTotalMB=131, cpuAverage=1.13, intervalMs=5000
Telemetry processMonitor heapUsedMB=94, heapTotalMB=131, cpuAverage=1.35, intervalMs=5001
```
Note in "Before" that heapTotalMB goes up to 2GB in the first case, and "intervalMs" of 17 seconds indicates that node was unresponsive for that long. In the second case, heapTotalMB stays low, and the main thread remains responsive the whole time.
Reviewers: jarek
Reviewed By: jarek
Differential Revision: https://phab.getgrist.com/D3906
2023-06-01 13:09:50 +00:00
|
|
|
import * as ProcessMonitor from 'app/server/lib/ProcessMonitor';
|
2023-07-04 21:21:34 +00:00
|
|
|
import {adaptServerUrl, getOrgUrl, getOriginUrl, getScope, isDefaultUser, optStringParam,
|
|
|
|
RequestWithGristInfo, sendOkReply, stringParam, TEST_HTTPS_OFFSET,
|
|
|
|
trustOrigin} from 'app/server/lib/requestUtils';
|
2021-07-21 08:46:03 +00:00
|
|
|
import {ISendAppPageOptions, makeGristConfig, makeMessagePage, makeSendAppPage} from 'app/server/lib/sendAppPage';
|
(core) Speed up and upgrade build.
Summary:
- Upgrades to build-related packages:
- Upgrade typescript, related libraries and typings.
- Upgrade webpack, eslint; add tsc-watch, node-dev, eslint_d.
- Build organization changes:
- Build webpack from original typescript, transpiling only; with errors still
reported by a background tsc watching process.
- Typescript-related changes:
- Reduce imports of AWS dependencies (very noticeable speedup)
- Avoid auto-loading global @types
- Client code is now built with isolatedModules flag (for safe transpilation)
- Use allowJs to avoid copying JS files manually.
- Linting changes
- Enhance Arcanist ESLintLinter to run before/after commands, and set up to use eslint_d
- Update eslint config, and include .eslintignore to avoid linting generated files.
- Include a bunch of eslint-prompted and eslint-generated fixes
- Add no-unused-expression rule to eslint, and fix a few warnings about it
- Other items:
- Refactor cssInput to avoid circular dependency
- Remove a bit of unused code, libraries, dependencies
Test Plan: No behavior changes, all existing tests pass. There are 30 tests fewer reported because `test_gpath.py` was removed (it's been unused for years)
Reviewers: paulfitz
Reviewed By: paulfitz
Subscribers: paulfitz
Differential Revision: https://phab.getgrist.com/D3498
2022-06-27 20:09:41 +00:00
|
|
|
import {getDatabaseUrl, listenPromise} from 'app/server/lib/serverUtils';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {Sessions} from 'app/server/lib/Sessions';
|
|
|
|
import * as shutdown from 'app/server/lib/shutdown';
|
|
|
|
import {TagChecker} from 'app/server/lib/TagChecker';
|
2023-07-04 21:21:34 +00:00
|
|
|
import {getTelemetryPrefs, ITelemetry} from 'app/server/lib/Telemetry';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {startTestingHooks} from 'app/server/lib/TestingHooks';
|
(core) move more tests to grist-core
Summary:
* Tie build and run-time docker base images to a consistent version (buster)
* Extend the test login system activated by GRIST_TEST_LOGIN to ease porting tests that currently rely on cognito (many)
* Make org resets work in absence of billing endpoints
* When in-memory session caches are used, add missing invalidation steps
* Pass org information through sign-ups/sign-ins more carefully
* For CORS, explicitly trust GRIST_HOST origin when set
* Move some fixtures and tests to core, focussing on tests that cover existing failures or are in the set of tests run on deployments
* Retain regular `test` target to run the test suite directly, without docker
* Add a `test:smoke` target to run a single simple test without `GRIST_TEST_LOGIN` activated
* Add a `test:docker` target to run the tests against a grist-core docker image - since tests rely on certain fixture teams/docs, added `TEST_SUPPORT_API_KEY` and `TEST_ADD_SAMPLES` flags to ease porting
The tests ported were `nbrowser` tests: `ActionLog.ts` (the first test I tend to port to anything, out of habit), `Fork.ts` (exercises a lot of doc creation paths), `HomeIntro.ts` (a lot of DocMenu exercise), and `DuplicateDocument.ts` (covers a feature known to be failing prior to this diff, the CORS tweak resolves it).
Test Plan: Manually tested via `buildtools/build_core.sh`. In follow up, I want to add running the `test:docker` target in grist-core's workflows. In jenkins, only the smoke test is run. There'd be an argument for running all tests, but they include particularly slow tests, and are duplicates of tests already run (in different configuration admittedly), so I'd like to try first just using them in grist-core to gate updates to any packaged version of Grist (the docker image currently).
Reviewers: alexmojaki
Reviewed By: alexmojaki
Subscribers: alexmojaki
Differential Revision: https://phab.getgrist.com/D3176
2021-12-10 22:42:54 +00:00
|
|
|
import {getTestLoginSystem} from 'app/server/lib/TestLogin';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {addUploadRoute} from 'app/server/lib/uploads';
|
2021-11-26 10:43:55 +00:00
|
|
|
import {buildWidgetRepository, IWidgetRepository} from 'app/server/lib/WidgetRepository';
|
2023-01-24 13:13:18 +00:00
|
|
|
import {setupLocale} from 'app/server/localization';
|
2020-07-21 13:20:51 +00:00
|
|
|
import axios from 'axios';
|
|
|
|
import * as bodyParser from 'body-parser';
|
2023-09-06 18:35:46 +00:00
|
|
|
import * as cookie from 'cookie';
|
2022-07-04 14:14:55 +00:00
|
|
|
import express from 'express';
|
2020-07-21 13:20:51 +00:00
|
|
|
import * as fse from 'fs-extra';
|
|
|
|
import * as http from 'http';
|
|
|
|
import * as https from 'https';
|
2022-09-29 08:01:37 +00:00
|
|
|
import {i18n} from 'i18next';
|
|
|
|
import i18Middleware from "i18next-http-middleware";
|
2020-10-15 21:51:30 +00:00
|
|
|
import mapValues = require('lodash/mapValues');
|
2022-07-04 14:14:55 +00:00
|
|
|
import morganLogger from 'morgan';
|
2020-07-21 13:20:51 +00:00
|
|
|
import {AddressInfo} from 'net';
|
2020-10-15 21:51:30 +00:00
|
|
|
import fetch from 'node-fetch';
|
2020-07-21 13:20:51 +00:00
|
|
|
import * as path from 'path';
|
|
|
|
import * as serveStatic from "serve-static";
|
|
|
|
|
|
|
|
// Health checks are a little noisy in the logs, so we don't show them all.
|
|
|
|
// We show the first N health checks:
|
|
|
|
const HEALTH_CHECK_LOG_SHOW_FIRST_N = 10;
|
|
|
|
// And we show every Nth health check:
|
|
|
|
const HEALTH_CHECK_LOG_SHOW_EVERY_N = 100;
|
|
|
|
|
2022-01-19 22:16:16 +00:00
|
|
|
// DocID of Grist doc to collect the Welcome questionnaire responses, such
|
|
|
|
// as "GristNewUserInfo".
|
|
|
|
const DOC_ID_NEW_USER_INFO = process.env.DOC_ID_NEW_USER_INFO;
|
2020-10-15 21:51:30 +00:00
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
export interface FlexServerOptions {
|
|
|
|
dataDir?: string;
|
|
|
|
|
|
|
|
// Base domain for org hostnames, starting with ".". Defaults to the base domain of APP_HOME_URL.
|
|
|
|
baseDomain?: string;
|
2020-07-22 15:43:24 +00:00
|
|
|
// Base URL for plugins, if permitted. Defaults to APP_UNTRUSTED_URL.
|
|
|
|
pluginUrl?: string;
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
2022-05-18 10:25:14 +00:00
|
|
|
const noop: express.RequestHandler = (req, res, next) => next();
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
export class FlexServer implements GristServer {
|
|
|
|
public readonly create = create;
|
|
|
|
public tagChecker: TagChecker;
|
|
|
|
public app: express.Express;
|
|
|
|
public deps: Set<string> = new Set();
|
|
|
|
public appRoot: string;
|
|
|
|
public host: string;
|
|
|
|
public tag: string;
|
|
|
|
public info = new Array<[string, any]>();
|
|
|
|
public usage: Usage;
|
|
|
|
public housekeeper: Housekeeper;
|
|
|
|
public server: http.Server;
|
|
|
|
public httpsServer?: https.Server;
|
2022-05-17 22:25:36 +00:00
|
|
|
public settings?: Readonly<Record<string, unknown>>;
|
2020-07-21 13:20:51 +00:00
|
|
|
public worker: DocWorkerInfo;
|
|
|
|
public electronServerMethods: ElectronServerMethods;
|
|
|
|
public readonly docsRoot: string;
|
2022-09-29 08:01:37 +00:00
|
|
|
public readonly i18Instance: i18n;
|
2023-06-06 17:08:50 +00:00
|
|
|
private _activations: Activations;
|
2021-08-17 15:22:30 +00:00
|
|
|
private _comm: Comm;
|
2023-06-06 17:08:50 +00:00
|
|
|
private _deploymentType: GristDeploymentType;
|
2021-08-17 15:22:30 +00:00
|
|
|
private _dbManager: HomeDBManager;
|
2020-07-21 13:20:51 +00:00
|
|
|
private _defaultBaseDomain: string|undefined;
|
2020-07-22 15:43:24 +00:00
|
|
|
private _pluginUrl: string|undefined;
|
2020-07-21 13:20:51 +00:00
|
|
|
private _billing: IBilling;
|
|
|
|
private _instanceRoot: string;
|
|
|
|
private _docManager: DocManager;
|
|
|
|
private _docWorker: DocWorker;
|
|
|
|
private _hosts: Hosts;
|
|
|
|
private _pluginManager: PluginManager;
|
2021-08-16 15:11:17 +00:00
|
|
|
private _sessions: Sessions;
|
(core) support GRIST_WORKER_GROUP to place worker into an exclusive group
Summary:
In an emergency, we may want to serve certain documents with "old" workers as we fix problems. This diff adds some support for that.
* Creates duplicate task definitions and services for staging and production doc workers (called grist-docs-staging2 and grist-docs-prod2), pulling from distinct docker tags (staging2 and prod2). The services are set to have zero workers until we need them.
* These new workers are started with a new env variable `GRIST_WORKER_GROUP` set to `secondary`.
* The `GRIST_WORKER_GROUP` variable, if set, makes the worker available to documents in the named group, and only that group.
* An unauthenticated `/assign` endpoint is added to documents which, when POSTed to, checks that the doc is served by a worker in the desired group for that doc (as set manually in redis), and if not frees the doc up for reassignment. This makes it possible to move individual docs between workers without redeployments.
The bash scripts added are a record of how the task definitions + services were created. The services could just have been copied manually, but the task definitions will need to be updated whenever the definitions for the main doc workers are updated, so it is worth scripting that.
For example, if a certain document were to fail on a new deployment of Grist, but rolling back the full deployment wasn't practical:
* Set prod2 tag in docker to desired codebase for that document
* Set desired_count for grist-docs-prod2 service to non-zero
* Set doc-<docid>-group for that doc in redis to secondary
* Hit /api/docs/<docid>/assign to move the doc to grist-docs-prod2
(If the document needs to be reverted to a previous snapshot, that currently would need doing manually - could be made simpler, but not in scope of this diff).
Test Plan: added tests
Reviewers: dsagal
Reviewed By: dsagal
Differential Revision: https://phab.getgrist.com/D2649
2020-11-02 19:24:46 +00:00
|
|
|
private _sessionStore: SessionStore;
|
2020-07-21 13:20:51 +00:00
|
|
|
private _storageManager: IDocStorageManager;
|
2023-06-06 17:08:50 +00:00
|
|
|
private _telemetry: ITelemetry;
|
(core) For exporting XLSX, do it memory-efficiently in a worker thread.
Summary:
- Excel exports were awfully memory-inefficient, causing occasional docWorker
crashes. The fix is to use the "streaming writer" option of ExcelJS
https://github.com/exceljs/exceljs#streaming-xlsx-writercontents. (Empirically
on one example, max memory went down from 3G to 100M)
- It's also CPU intensive and synchronous, and can block node for tens of
seconds. The fix is to use a worker-thread. This diff uses "piscina" library
for a pool of threads.
- Additionally, adds ProcessMonitor that logs memory and cpu usage,
particularly when those change significantly.
- Also introduces request cancellation, so that a long download cancelled by
the user will cancel the work being done in the worker thread.
Test Plan:
Updated previous export tests; memory and CPU performance tested
manually by watching output of ProcessMonitor.
Difference visible in these log excerpts:
Before (total time to serve request 22 sec):
```
Telemetry processMonitor heapUsedMB=2187, heapTotalMB=2234, cpuAverage=1.13, intervalMs=17911
Telemetry processMonitor heapUsedMB=2188, heapTotalMB=2234, cpuAverage=0.66, intervalMs=5005
Telemetry processMonitor heapUsedMB=2188, heapTotalMB=2234, cpuAverage=0, intervalMs=5005
Telemetry processMonitor heapUsedMB=71, heapTotalMB=75, cpuAverage=0.13, intervalMs=5002
```
After (total time to server request 18 sec):
```
Telemetry processMonitor heapUsedMB=109, heapTotalMB=144, cpuAverage=0.5, intervalMs=5001
Telemetry processMonitor heapUsedMB=109, heapTotalMB=144, cpuAverage=1.39, intervalMs=5002
Telemetry processMonitor heapUsedMB=94, heapTotalMB=131, cpuAverage=1.13, intervalMs=5000
Telemetry processMonitor heapUsedMB=94, heapTotalMB=131, cpuAverage=1.35, intervalMs=5001
```
Note in "Before" that heapTotalMB goes up to 2GB in the first case, and "intervalMs" of 17 seconds indicates that node was unresponsive for that long. In the second case, heapTotalMB stays low, and the main thread remains responsive the whole time.
Reviewers: jarek
Reviewed By: jarek
Differential Revision: https://phab.getgrist.com/D3906
2023-06-01 13:09:50 +00:00
|
|
|
private _processMonitorStop?: () => void; // Callback to stop the ProcessMonitor
|
2020-07-21 13:20:51 +00:00
|
|
|
private _docWorkerMap: IDocWorkerMap;
|
2021-11-26 10:43:55 +00:00
|
|
|
private _widgetRepository: IWidgetRepository;
|
2022-02-24 00:27:16 +00:00
|
|
|
private _notifier: INotifier;
|
2022-07-19 15:39:49 +00:00
|
|
|
private _accessTokens: IAccessTokens;
|
2021-08-16 15:11:17 +00:00
|
|
|
private _internalPermitStore: IPermitStore; // store for permits that stay within our servers
|
|
|
|
private _externalPermitStore: IPermitStore; // store for permits that pass through outside servers
|
2020-07-21 13:20:51 +00:00
|
|
|
private _disabled: boolean = false;
|
2022-06-03 14:54:49 +00:00
|
|
|
private _disableExternalStorage: boolean = false;
|
2020-07-21 13:20:51 +00:00
|
|
|
private _healthy: boolean = true; // becomes false if a serious error has occurred and
|
|
|
|
// server cannot do its work.
|
|
|
|
private _healthCheckCounter: number = 0;
|
|
|
|
private _hasTestingHooks: boolean = false;
|
|
|
|
private _loginMiddleware: GristLoginMiddleware;
|
|
|
|
private _userIdMiddleware: express.RequestHandler;
|
|
|
|
private _trustOriginsMiddleware: express.RequestHandler;
|
|
|
|
private _docPermissionsMiddleware: express.RequestHandler;
|
|
|
|
// This middleware redirects to signin/signup for anon, except on merged org or for
|
|
|
|
// a team site that allows anon access.
|
|
|
|
private _redirectToLoginWithExceptionsMiddleware: express.RequestHandler;
|
|
|
|
// This unconditionally redirects to signin/signup for anon, for pages where anon access
|
|
|
|
// is never desired.
|
|
|
|
private _redirectToLoginWithoutExceptionsMiddleware: express.RequestHandler;
|
2020-08-19 20:25:42 +00:00
|
|
|
// This can be called to do a redirect to signin/signup in a nuanced situation.
|
|
|
|
private _redirectToLoginUnconditionally: express.RequestHandler | null;
|
2020-07-21 13:20:51 +00:00
|
|
|
private _redirectToOrgMiddleware: express.RequestHandler;
|
|
|
|
private _redirectToHostMiddleware: express.RequestHandler;
|
2021-08-16 15:11:17 +00:00
|
|
|
private _getLoginRedirectUrl: (req: express.Request, target: URL) => Promise<string>;
|
|
|
|
private _getSignUpRedirectUrl: (req: express.Request, target: URL) => Promise<string>;
|
|
|
|
private _getLogoutRedirectUrl: (req: express.Request, nextUrl: URL) => Promise<string>;
|
2020-07-21 13:20:51 +00:00
|
|
|
private _sendAppPage: (req: express.Request, resp: express.Response, options: ISendAppPageOptions) => Promise<void>;
|
2023-02-13 20:52:17 +00:00
|
|
|
private _getLoginSystem?: () => Promise<GristLoginSystem>;
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
constructor(public port: number, public name: string = 'flexServer',
|
2021-04-26 21:54:09 +00:00
|
|
|
public readonly options: FlexServerOptions = {}) {
|
2020-07-21 13:20:51 +00:00
|
|
|
this.app = express();
|
|
|
|
this.app.set('port', port);
|
|
|
|
this.appRoot = getAppRoot();
|
|
|
|
this.host = process.env.GRIST_HOST || "localhost";
|
|
|
|
log.info(`== Grist version is ${version.version} (commit ${version.gitcommit})`);
|
|
|
|
this.info.push(['appRoot', this.appRoot]);
|
2022-09-29 08:01:37 +00:00
|
|
|
// Initialize locales files.
|
|
|
|
this.i18Instance = setupLocale(this.appRoot);
|
|
|
|
if (Array.isArray(this.i18Instance.options.preload)) {
|
|
|
|
this.info.push(['i18:locale', this.i18Instance.options.preload.join(",")]);
|
|
|
|
}
|
|
|
|
if (Array.isArray(this.i18Instance.options.ns)) {
|
|
|
|
this.info.push(['i18:namespace', this.i18Instance.options.ns.join(",")]);
|
|
|
|
}
|
|
|
|
// Add language detection middleware.
|
|
|
|
this.app.use(i18Middleware.handle(this.i18Instance));
|
2020-07-21 13:20:51 +00:00
|
|
|
// This directory hold Grist documents.
|
2022-03-07 14:27:43 +00:00
|
|
|
let docsRoot = path.resolve((this.options && this.options.dataDir) ||
|
2021-06-02 19:07:13 +00:00
|
|
|
process.env.GRIST_DATA_DIR ||
|
|
|
|
getAppPathTo(this.appRoot, 'samples'));
|
2022-03-07 14:27:43 +00:00
|
|
|
// In testing, it can be useful to separate out document roots used
|
|
|
|
// by distinct FlexServers.
|
|
|
|
if (process.env.GRIST_TEST_ADD_PORT_TO_DOCS_ROOT === 'true') {
|
|
|
|
docsRoot = path.resolve(docsRoot, String(port));
|
|
|
|
}
|
2021-06-02 19:07:13 +00:00
|
|
|
// Create directory if it doesn't exist.
|
|
|
|
// TODO: track down all dependencies on 'samples' existing in tests and
|
|
|
|
// in dev environment, and remove them. Then it would probably be best
|
|
|
|
// to simply fail if the docs root directory does not exist.
|
|
|
|
fse.mkdirpSync(docsRoot);
|
|
|
|
this.docsRoot = fse.realpathSync(docsRoot);
|
2020-07-21 13:20:51 +00:00
|
|
|
this.info.push(['docsRoot', this.docsRoot]);
|
|
|
|
|
2023-06-06 17:08:50 +00:00
|
|
|
this._deploymentType = this.create.deploymentType();
|
|
|
|
if (process.env.GRIST_TEST_SERVER_DEPLOYMENT_TYPE) {
|
|
|
|
this._deploymentType = GristDeploymentTypes.check(process.env.GRIST_TEST_SERVER_DEPLOYMENT_TYPE);
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
const homeUrl = process.env.APP_HOME_URL;
|
2022-06-15 14:29:29 +00:00
|
|
|
// The "base domain" is only a thing if orgs are encoded as a subdomain.
|
|
|
|
if (process.env.GRIST_ORG_IN_PATH === 'true' || process.env.GRIST_SINGLE_ORG) {
|
|
|
|
this._defaultBaseDomain = options.baseDomain || (homeUrl && new URL(homeUrl).hostname);
|
|
|
|
} else {
|
|
|
|
this._defaultBaseDomain = options.baseDomain || (homeUrl && parseSubdomain(new URL(homeUrl).hostname).base);
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
this.info.push(['defaultBaseDomain', this._defaultBaseDomain]);
|
2020-07-22 15:43:24 +00:00
|
|
|
this._pluginUrl = options.pluginUrl || process.env.APP_UNTRUSTED_URL;
|
|
|
|
this.info.push(['pluginUrl', this._pluginUrl]);
|
2020-07-21 13:20:51 +00:00
|
|
|
|
2022-07-25 20:11:11 +00:00
|
|
|
// The electron build is not supported at this time, but this stub
|
|
|
|
// implementation of electronServerMethods is present to allow kicking
|
|
|
|
// its tires.
|
|
|
|
let userConfig: any = {
|
|
|
|
recentItems: [],
|
|
|
|
};
|
|
|
|
this.electronServerMethods = {
|
|
|
|
async importDoc() { throw new Error('not implemented'); },
|
|
|
|
onDocOpen(cb) {
|
|
|
|
// currently only a stub.
|
|
|
|
cb('');
|
|
|
|
},
|
|
|
|
async getUserConfig() {
|
|
|
|
return userConfig;
|
|
|
|
},
|
|
|
|
async updateUserConfig(obj: any) {
|
|
|
|
userConfig = obj;
|
|
|
|
},
|
|
|
|
onBackupMade() {
|
|
|
|
log.info('backup skipped');
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
this.app.use((req, res, next) => {
|
|
|
|
(req as RequestWithGrist).gristServer = this;
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-02-13 20:52:17 +00:00
|
|
|
// Allow overridding the login system.
|
|
|
|
public setLoginSystem(loginSystem: () => Promise<GristLoginSystem>) {
|
|
|
|
this._getLoginSystem = loginSystem;
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
public getHost(): string {
|
|
|
|
return `${this.host}:${this.getOwnPort()}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get a url for this server, based on the protocol it speaks (http), the host it
|
|
|
|
// runs on, and the port it listens on. The url the client uses to communicate with
|
|
|
|
// the server may be different if there are intermediaries (such as a load-balancer
|
|
|
|
// terminating TLS).
|
|
|
|
public getOwnUrl(): string {
|
|
|
|
const port = this.getOwnPort();
|
|
|
|
return `http://${this.host}:${port}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get a url for the home server api. Called without knowledge of a specific
|
|
|
|
* request, so will default to a generic url. Use of this method can render
|
|
|
|
* code incompatible with custom base domains (currently, sendgrid notifications
|
|
|
|
* via Notifier are incompatible for this reason).
|
|
|
|
*/
|
|
|
|
public getDefaultHomeUrl(): string {
|
|
|
|
const homeUrl = process.env.APP_HOME_URL || (this._has('api') && this.getOwnUrl());
|
|
|
|
if (!homeUrl) { throw new Error("need APP_HOME_URL"); }
|
|
|
|
return homeUrl;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get a url for the home server api, adapting it to match the base domain in the
|
|
|
|
* requested url. This adaptation is important for cookie-based authentication.
|
|
|
|
*
|
|
|
|
* If relPath is given, returns that path relative to homeUrl. If omitted, note that
|
|
|
|
* getHomeUrl() will still return a URL ending in "/".
|
|
|
|
*/
|
|
|
|
public getHomeUrl(req: express.Request, relPath: string = ''): string {
|
|
|
|
// Get the default home url.
|
|
|
|
const homeUrl = new URL(relPath, this.getDefaultHomeUrl());
|
|
|
|
adaptServerUrl(homeUrl, req as RequestWithOrg);
|
|
|
|
return homeUrl.href;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get a home url that is appropriate for the given document. For now, this
|
|
|
|
* returns a default that works for all documents. That could change in future,
|
|
|
|
* specifically with custom domains (perhaps we might limit which docs can be accessed
|
|
|
|
* based on domain).
|
|
|
|
*/
|
|
|
|
public async getHomeUrlByDocId(docId: string, relPath: string = ''): Promise<string> {
|
|
|
|
return new URL(relPath, this.getDefaultHomeUrl()).href;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get the port number the server listens on. This may be different from the port
|
|
|
|
// number the client expects when communicating with the server if there are intermediaries.
|
|
|
|
public getOwnPort(): number {
|
|
|
|
// Get the port from the server in case it was started with port 0.
|
|
|
|
return this.server ? (this.server.address() as AddressInfo).port : this.port;
|
|
|
|
}
|
|
|
|
|
2022-02-11 06:03:30 +00:00
|
|
|
/**
|
|
|
|
* Get a url to an org that should be accessible by all signed-in users. For now, this
|
|
|
|
* returns the base URL of the personal org (typically docs[-s]).
|
|
|
|
*/
|
|
|
|
public getMergedOrgUrl(req: RequestWithLogin, pathname: string = '/'): string {
|
|
|
|
return this._getOrgRedirectUrl(req, this._dbManager.mergedOrgDomain(), pathname);
|
|
|
|
}
|
|
|
|
|
2021-01-12 15:48:40 +00:00
|
|
|
public getPermitStore(): IPermitStore {
|
2021-08-16 15:11:17 +00:00
|
|
|
if (!this._internalPermitStore) { throw new Error('no permit store available'); }
|
|
|
|
return this._internalPermitStore;
|
|
|
|
}
|
|
|
|
|
|
|
|
public getExternalPermitStore(): IPermitStore {
|
|
|
|
if (!this._externalPermitStore) { throw new Error('no permit store available'); }
|
|
|
|
return this._externalPermitStore;
|
|
|
|
}
|
|
|
|
|
|
|
|
public getSessions(): Sessions {
|
|
|
|
if (!this._sessions) { throw new Error('no sessions available'); }
|
|
|
|
return this._sessions;
|
2021-01-12 15:48:40 +00:00
|
|
|
}
|
|
|
|
|
2021-08-17 15:22:30 +00:00
|
|
|
public getComm(): Comm {
|
|
|
|
if (!this._comm) { throw new Error('no Comm available'); }
|
|
|
|
return this._comm;
|
|
|
|
}
|
|
|
|
|
2023-06-06 17:08:50 +00:00
|
|
|
public getDeploymentType(): GristDeploymentType {
|
|
|
|
return this._deploymentType;
|
|
|
|
}
|
|
|
|
|
2021-08-17 15:22:30 +00:00
|
|
|
public getHosts(): Hosts {
|
|
|
|
if (!this._hosts) { throw new Error('no hosts available'); }
|
|
|
|
return this._hosts;
|
|
|
|
}
|
|
|
|
|
2023-06-06 17:08:50 +00:00
|
|
|
public getActivations(): Activations {
|
|
|
|
if (!this._activations) { throw new Error('no activations available'); }
|
|
|
|
return this._activations;
|
|
|
|
}
|
|
|
|
|
2021-08-17 15:22:30 +00:00
|
|
|
public getHomeDBManager(): HomeDBManager {
|
|
|
|
if (!this._dbManager) { throw new Error('no home db available'); }
|
|
|
|
return this._dbManager;
|
|
|
|
}
|
|
|
|
|
2021-09-13 21:29:35 +00:00
|
|
|
public getStorageManager(): IDocStorageManager {
|
|
|
|
if (!this._storageManager) { throw new Error('no storage manager available'); }
|
|
|
|
return this._storageManager;
|
|
|
|
}
|
|
|
|
|
2023-06-06 17:08:50 +00:00
|
|
|
public getTelemetry(): ITelemetry {
|
|
|
|
if (!this._telemetry) { throw new Error('no telemetry available'); }
|
|
|
|
return this._telemetry;
|
2023-04-06 15:10:29 +00:00
|
|
|
}
|
|
|
|
|
2021-11-26 10:43:55 +00:00
|
|
|
public getWidgetRepository(): IWidgetRepository {
|
|
|
|
if (!this._widgetRepository) { throw new Error('no widget repository available'); }
|
|
|
|
return this._widgetRepository;
|
|
|
|
}
|
|
|
|
|
2022-02-24 00:27:16 +00:00
|
|
|
public getNotifier(): INotifier {
|
|
|
|
if (!this._notifier) { throw new Error('no notifier available'); }
|
|
|
|
return this._notifier;
|
|
|
|
}
|
|
|
|
|
2022-07-19 15:39:49 +00:00
|
|
|
public getAccessTokens() {
|
|
|
|
if (this._accessTokens) { return this._accessTokens; }
|
|
|
|
this.addDocWorkerMap();
|
|
|
|
const cli = this._docWorkerMap.getRedisClient();
|
|
|
|
this._accessTokens = new AccessTokens(cli);
|
|
|
|
return this._accessTokens;
|
|
|
|
}
|
|
|
|
|
2022-03-07 16:40:46 +00:00
|
|
|
public sendAppPage(req: express.Request, resp: express.Response, options: ISendAppPageOptions): Promise<void> {
|
|
|
|
if (!this._sendAppPage) { throw new Error('no _sendAppPage method available'); }
|
|
|
|
return this._sendAppPage(req, resp, options);
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
public addLogging() {
|
|
|
|
if (this._check('logging')) { return; }
|
2020-10-28 17:37:36 +00:00
|
|
|
if (process.env.GRIST_LOG_SKIP_HTTP) { return; }
|
2020-07-21 13:20:51 +00:00
|
|
|
// Add a timestamp token that matches exactly the formatting of non-morgan logs.
|
|
|
|
morganLogger.token('logTime', (req: Request) => log.timestamp());
|
2022-04-01 21:31:24 +00:00
|
|
|
// Add an optional gristInfo token that can replace the url, if the url is sensitive.
|
2020-07-21 13:20:51 +00:00
|
|
|
morganLogger.token('gristInfo', (req: RequestWithGristInfo) =>
|
|
|
|
req.gristInfo || req.originalUrl || req.url);
|
|
|
|
morganLogger.token('host', (req: express.Request) => req.get('host'));
|
|
|
|
const msg = ':logTime :host :method :gristInfo :status :response-time ms - :res[content-length]';
|
|
|
|
// In hosted Grist, render json so logs retain more organization.
|
|
|
|
function outputJson(tokens: any, req: any, res: any) {
|
|
|
|
return JSON.stringify({
|
|
|
|
timestamp: tokens.logTime(req, res),
|
|
|
|
method: tokens.method(req, res),
|
|
|
|
path: tokens.gristInfo(req, res),
|
|
|
|
status: tokens.status(req, res),
|
|
|
|
timeMs: parseFloat(tokens['response-time'](req, res)) || undefined,
|
|
|
|
contentLength: parseInt(tokens.res(req, res, 'content-length'), 10) || undefined,
|
2022-07-14 06:01:08 +00:00
|
|
|
host: tokens.host(req, res),
|
|
|
|
altSessionId: req.altSessionId,
|
2020-07-21 13:20:51 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
this.app.use(morganLogger(process.env.GRIST_HOSTED_VERSION ? outputJson : msg, {
|
|
|
|
skip: this._shouldSkipRequestLogging.bind(this)
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
|
|
|
public addHealthCheck() {
|
|
|
|
if (this._check('health')) { return; }
|
|
|
|
// Health check endpoint. if called with /hooks, testing hooks are required in order to be
|
|
|
|
// considered healthy. Testing hooks are used only in server started for tests, and
|
|
|
|
// /status/hooks allows the tests to wait for them to be ready.
|
|
|
|
this.app.get('/status(/hooks)?', (req, res) => {
|
|
|
|
if (this._healthy && (this._hasTestingHooks || !req.url.endsWith('/hooks'))) {
|
|
|
|
this._healthCheckCounter++;
|
|
|
|
res.status(200).send(`Grist ${this.name} is alive.`);
|
|
|
|
} else {
|
|
|
|
this._healthCheckCounter = 0; // reset counter if we ever go internally unhealthy.
|
|
|
|
res.status(500).send(`Grist ${this.name} is unhealthy.`);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
public testAddRouter() {
|
|
|
|
if (this._check('router')) { return; }
|
|
|
|
this.app.get('/test/router', (req, res) => {
|
2023-09-05 18:27:35 +00:00
|
|
|
const act = optStringParam(req.query.act, 'act') || 'none';
|
2021-11-29 20:12:45 +00:00
|
|
|
const port = stringParam(req.query.port, 'port'); // port is trusted in mock; in prod it is not.
|
2020-07-21 13:20:51 +00:00
|
|
|
if (act === 'add' || act === 'remove') {
|
|
|
|
const host = `localhost:${port}`;
|
|
|
|
return res.status(200).json({
|
|
|
|
act,
|
|
|
|
host,
|
|
|
|
url: `http://${host}`,
|
|
|
|
message: 'ok',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return res.status(500).json({error: 'unrecognized action'});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
public addCleanup() {
|
|
|
|
if (this._check('cleanup')) { return; }
|
|
|
|
// Set up signal handlers. Note that nodemon sends SIGUSR2 to restart node.
|
|
|
|
shutdown.cleanupOnSignals('SIGINT', 'SIGTERM', 'SIGHUP', 'SIGUSR2');
|
|
|
|
}
|
|
|
|
|
|
|
|
public addTagChecker() {
|
|
|
|
if (this._check('tag', '!org')) { return; }
|
|
|
|
// Handle requests that start with /v/TAG/ and set .tag property on them.
|
|
|
|
this.tag = version.gitcommit;
|
|
|
|
this.info.push(['tag', this.tag]);
|
|
|
|
this.tagChecker = new TagChecker(this.tag);
|
|
|
|
this.app.use(this.tagChecker.inspectTag);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* To allow routing to doc workers via the path, doc workers remove any
|
|
|
|
* path prefix of the form /dw/...../ if present. The prefix is not checked,
|
|
|
|
* just removed unconditionally.
|
|
|
|
* TODO: determine what the prefix should be, and check it, to catch bugs.
|
|
|
|
*/
|
|
|
|
public stripDocWorkerIdPathPrefixIfPresent() {
|
|
|
|
if (this._check('strip_dw', '!tag', '!org')) { return; }
|
|
|
|
this.app.use((req, resp, next) => {
|
|
|
|
const match = req.url.match(/^\/dw\/([-a-zA-Z0-9]+)([/?].*)?$/);
|
|
|
|
if (match) { req.url = sanitizePathTail(match[2]); }
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
public addOrg() {
|
|
|
|
if (this._check('org', 'homedb', 'hosts')) { return; }
|
|
|
|
this.app.use(this._hosts.extractOrg);
|
|
|
|
}
|
|
|
|
|
|
|
|
public setDirectory() {
|
|
|
|
if (this._check('dir')) { return; }
|
|
|
|
process.chdir(getUnpackedAppRoot(this.appRoot));
|
|
|
|
}
|
|
|
|
|
|
|
|
public get instanceRoot() {
|
|
|
|
if (!this._instanceRoot) {
|
|
|
|
this._instanceRoot = path.resolve(process.env.GRIST_INST_DIR || this.appRoot);
|
|
|
|
this.info.push(['instanceRoot', this._instanceRoot]);
|
|
|
|
}
|
|
|
|
return this._instanceRoot;
|
|
|
|
}
|
|
|
|
|
|
|
|
public addStaticAndBowerDirectories() {
|
|
|
|
if (this._check('static_and_bower', 'dir')) { return; }
|
|
|
|
this.addTagChecker();
|
|
|
|
// Allow static files to be requested from any origin.
|
|
|
|
const options: serveStatic.ServeStaticOptions = {
|
|
|
|
setHeaders: (res, filepath, stat) => {
|
2020-10-28 17:37:36 +00:00
|
|
|
res.setHeader("Access-Control-Allow-Origin", "*");
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
// Grist has static help files, which may be useful for standalone app,
|
|
|
|
// but for hosted grist the latest help is at support.getgrist.com. Redirect
|
|
|
|
// to this page for the benefit of crawlers which currently rank the static help
|
|
|
|
// page link highly for historic reasons.
|
|
|
|
this.app.use(/^\/help\//, expressWrap(async (req, res) => {
|
|
|
|
res.redirect('https://support.getgrist.com');
|
|
|
|
}));
|
2023-02-13 20:52:17 +00:00
|
|
|
// If there is a directory called "static_ext", serve material from there
|
|
|
|
// as well. This isn't used in grist-core but is handy for extensions such
|
|
|
|
// as an Electron app.
|
|
|
|
const staticExtDir = getAppPathTo(this.appRoot, 'static') + '_ext';
|
|
|
|
const staticExtApp = fse.existsSync(staticExtDir) ?
|
|
|
|
express.static(staticExtDir, options) : null;
|
2020-07-21 13:20:51 +00:00
|
|
|
const staticApp = express.static(getAppPathTo(this.appRoot, 'static'), options);
|
|
|
|
const bowerApp = express.static(getAppPathTo(this.appRoot, 'bower_components'), options);
|
2022-09-29 08:01:37 +00:00
|
|
|
if (process.env.GRIST_LOCALES_DIR) {
|
|
|
|
const locales = express.static(process.env.GRIST_LOCALES_DIR, options);
|
|
|
|
this.app.use("/locales", this.tagChecker.withTag(locales));
|
|
|
|
}
|
2023-02-13 20:52:17 +00:00
|
|
|
if (staticExtApp) { this.app.use(this.tagChecker.withTag(staticExtApp)); }
|
2020-07-21 13:20:51 +00:00
|
|
|
this.app.use(this.tagChecker.withTag(staticApp));
|
|
|
|
this.app.use(this.tagChecker.withTag(bowerApp));
|
|
|
|
}
|
|
|
|
|
|
|
|
// Some tests rely on testFOO.html files being served.
|
|
|
|
public addAssetsForTests() {
|
|
|
|
if (this._check('testAssets', 'dir')) { return; }
|
|
|
|
// Serve test[a-z]*.html for test purposes.
|
|
|
|
this.app.use(/^\/(test[a-z]*.html)$/i, expressWrap(async (req, res) =>
|
|
|
|
res.sendFile(req.params[0], {root: getAppPathTo(this.appRoot, 'static')})));
|
|
|
|
}
|
|
|
|
|
|
|
|
// Plugin operation relies currently on grist-plugin-api.js being available,
|
|
|
|
// and with Grist's static assets to be also available on the untrusted
|
|
|
|
// host. The assets should be available without version tags.
|
|
|
|
public async addAssetsForPlugins() {
|
|
|
|
if (this._check('pluginUntaggedAssets', 'dir')) { return; }
|
|
|
|
this.app.use(/^\/(grist-plugin-api.js)$/, expressWrap(async (req, res) =>
|
|
|
|
res.sendFile(req.params[0], {root: getAppPathTo(this.appRoot, 'static')})));
|
|
|
|
// Plugins get access to static resources without a tag
|
|
|
|
this.app.use(limitToPlugins(express.static(getAppPathTo(this.appRoot, 'static'))));
|
|
|
|
this.app.use(limitToPlugins(express.static(getAppPathTo(this.appRoot, 'bower_components'))));
|
2022-03-07 12:58:06 +00:00
|
|
|
// Serve custom-widget.html message for anyone.
|
|
|
|
this.app.use(/^\/(custom-widget.html)$/, expressWrap(async (req, res) =>
|
|
|
|
res.sendFile(req.params[0], {root: getAppPathTo(this.appRoot, 'static')})));
|
2020-07-21 13:20:51 +00:00
|
|
|
this.addOrg();
|
|
|
|
addPluginEndpoints(this, await this._addPluginManager());
|
|
|
|
}
|
|
|
|
|
|
|
|
// Prepare cache for managing org-to-host relationship.
|
|
|
|
public addHosts() {
|
|
|
|
if (this._check('hosts', 'homedb')) { return; }
|
2021-08-17 15:22:30 +00:00
|
|
|
this._hosts = new Hosts(this._defaultBaseDomain, this._dbManager, this._pluginUrl);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public async initHomeDBManager() {
|
|
|
|
if (this._check('homedb')) { return; }
|
2021-08-17 15:22:30 +00:00
|
|
|
this._dbManager = new HomeDBManager();
|
|
|
|
this._dbManager.setPrefix(process.env.GRIST_ID_PREFIX || "");
|
|
|
|
await this._dbManager.connect();
|
|
|
|
await this._dbManager.initializeSpecialIds();
|
2020-07-21 13:20:51 +00:00
|
|
|
// Report which database we are using, without sensitive credentials.
|
2021-08-17 15:22:30 +00:00
|
|
|
this.info.push(['database', getDatabaseUrl(this._dbManager.connection.options, false)]);
|
2022-05-11 19:05:35 +00:00
|
|
|
// If the installation appears to be new, give it an id and a creation date.
|
2023-06-06 17:08:50 +00:00
|
|
|
this._activations = new Activations(this._dbManager);
|
|
|
|
await this._activations.current();
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public addDocWorkerMap() {
|
|
|
|
if (this._check('map')) { return; }
|
|
|
|
this._docWorkerMap = getDocWorkerMap();
|
2021-08-16 15:11:17 +00:00
|
|
|
this._internalPermitStore = this._docWorkerMap.getPermitStore('internal');
|
|
|
|
this._externalPermitStore = this._docWorkerMap.getPermitStore('external');
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Set up the main express middleware used. For a single user setup, without logins,
|
|
|
|
// all this middleware is currently a no-op.
|
|
|
|
public addAccessMiddleware() {
|
2022-06-15 14:29:29 +00:00
|
|
|
if (this._check('middleware', 'map', 'config', isSingleUserMode() ? null : 'hosts')) { return; }
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
if (!isSingleUserMode()) {
|
2022-06-15 14:29:29 +00:00
|
|
|
const skipSession = appSettings.section('login').flag('skipSession').readBool({
|
|
|
|
envVar: 'GRIST_IGNORE_SESSION',
|
|
|
|
});
|
2020-07-21 13:20:51 +00:00
|
|
|
// Middleware to redirect landing pages to preferred host
|
|
|
|
this._redirectToHostMiddleware = this._hosts.redirectHost;
|
|
|
|
// Middleware to add the userId to the express request object.
|
2022-06-15 14:29:29 +00:00
|
|
|
this._userIdMiddleware = expressWrap(addRequestUser.bind(
|
|
|
|
null, this._dbManager, this._internalPermitStore,
|
|
|
|
{
|
|
|
|
getProfile: this._loginMiddleware.getProfile?.bind(this._loginMiddleware),
|
|
|
|
// Set this to false to stop Grist using a cookie for authentication purposes.
|
|
|
|
skipSession,
|
2022-07-19 15:39:49 +00:00
|
|
|
gristServer: this,
|
2022-06-15 14:29:29 +00:00
|
|
|
}
|
|
|
|
));
|
2020-07-21 13:20:51 +00:00
|
|
|
this._trustOriginsMiddleware = expressWrap(trustOriginHandler);
|
|
|
|
// middleware to authorize doc access to the app. Note that this requires the userId
|
|
|
|
// to be set on the request by _userIdMiddleware.
|
|
|
|
this._docPermissionsMiddleware = expressWrap((...args) => this._docWorker.assertDocAccess(...args));
|
|
|
|
this._redirectToLoginWithExceptionsMiddleware = redirectToLogin(true,
|
|
|
|
this._getLoginRedirectUrl,
|
|
|
|
this._getSignUpRedirectUrl,
|
2021-08-17 15:22:30 +00:00
|
|
|
this._dbManager);
|
2020-07-21 13:20:51 +00:00
|
|
|
this._redirectToLoginWithoutExceptionsMiddleware = redirectToLogin(false,
|
|
|
|
this._getLoginRedirectUrl,
|
|
|
|
this._getSignUpRedirectUrl,
|
2021-08-17 15:22:30 +00:00
|
|
|
this._dbManager);
|
2020-08-19 20:25:42 +00:00
|
|
|
this._redirectToLoginUnconditionally = redirectToLoginUnconditionally(this._getLoginRedirectUrl,
|
|
|
|
this._getSignUpRedirectUrl);
|
2020-07-21 13:20:51 +00:00
|
|
|
this._redirectToOrgMiddleware = tbind(this._redirectToOrg, this);
|
|
|
|
} else {
|
|
|
|
this._userIdMiddleware = noop;
|
|
|
|
this._trustOriginsMiddleware = noop;
|
2022-05-18 10:25:14 +00:00
|
|
|
// For standalone single-user Grist, documents are stored on-disk
|
|
|
|
// with their filename equal to the document title, no document
|
|
|
|
// aliases are possible, and there is no access control.
|
|
|
|
// The _docPermissionsMiddleware is a no-op.
|
|
|
|
// TODO We might no longer have any tests for isSingleUserMode, or modes of operation.
|
|
|
|
this._docPermissionsMiddleware = noop;
|
2020-07-21 13:20:51 +00:00
|
|
|
this._redirectToLoginWithExceptionsMiddleware = noop;
|
|
|
|
this._redirectToLoginWithoutExceptionsMiddleware = noop;
|
2020-08-19 20:25:42 +00:00
|
|
|
this._redirectToLoginUnconditionally = null; // there is no way to log in.
|
2020-07-21 13:20:51 +00:00
|
|
|
this._redirectToOrgMiddleware = noop;
|
|
|
|
this._redirectToHostMiddleware = noop;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Add middleware common to all API endpoints (including forwarding ones).
|
|
|
|
*/
|
|
|
|
public addApiMiddleware() {
|
|
|
|
if (this._check('api-mw', 'middleware')) { return; }
|
|
|
|
// API endpoints need req.userId and need to support requests from different subdomains.
|
|
|
|
this.app.use("/api", this._userIdMiddleware);
|
|
|
|
this.app.use("/api", this._trustOriginsMiddleware);
|
|
|
|
this.app.use("/api", noCaching);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Add error-handling middleware common to all API endpoints.
|
|
|
|
*/
|
|
|
|
public addApiErrorHandlers() {
|
|
|
|
if (this._check('api-error', 'api-mw')) { return; }
|
|
|
|
|
|
|
|
// add a final not-found handler for api
|
|
|
|
this.app.use("/api", (req, res) => {
|
|
|
|
res.status(404).send({error: `not found: ${req.originalUrl}`});
|
|
|
|
});
|
|
|
|
|
|
|
|
// Add a final error handler for /api endpoints that reports errors as JSON.
|
2022-01-07 18:11:52 +00:00
|
|
|
this.app.use('/api/auth', secureJsonErrorHandler);
|
2020-07-21 13:20:51 +00:00
|
|
|
this.app.use('/api', jsonErrorHandler);
|
|
|
|
}
|
|
|
|
|
|
|
|
public addHomeApi() {
|
|
|
|
if (this._check('api', 'homedb', 'json', 'api-mw')) { return; }
|
|
|
|
|
|
|
|
// ApiServer's constructor adds endpoints to the app.
|
|
|
|
// tslint:disable-next-line:no-unused-expression
|
2021-11-26 10:43:55 +00:00
|
|
|
new ApiServer(this.app, this._dbManager, this._widgetRepository = buildWidgetRepository());
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public addBillingApi() {
|
|
|
|
if (this._check('billing-api', 'homedb', 'json', 'api-mw')) { return; }
|
|
|
|
this._getBilling();
|
2022-08-22 19:46:25 +00:00
|
|
|
this._billing.addEndpoints(this.app);
|
2020-07-21 13:20:51 +00:00
|
|
|
this._billing.addEventHandlers();
|
|
|
|
}
|
|
|
|
|
2022-05-11 19:05:35 +00:00
|
|
|
public async addBillingMiddleware() {
|
|
|
|
if (this._check('activation', 'homedb')) { return; }
|
|
|
|
this._getBilling();
|
|
|
|
await this._billing.addMiddleware?.(this.app);
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
/**
|
|
|
|
* Add a /api/log endpoint that simply outputs client errors to our
|
|
|
|
* logs. This is a minimal placeholder for a special-purpose
|
|
|
|
* service for dealing with client errors.
|
|
|
|
*/
|
|
|
|
public addLogEndpoint() {
|
|
|
|
if (this._check('log-endpoint', 'json', 'api-mw')) { return; }
|
2023-04-06 15:10:29 +00:00
|
|
|
|
|
|
|
this.app.post('/api/log', async (req, resp) => {
|
2020-07-21 13:20:51 +00:00
|
|
|
const mreq = req as RequestWithLogin;
|
|
|
|
log.rawWarn('client error', {
|
|
|
|
event: req.body.event,
|
2022-04-11 13:52:34 +00:00
|
|
|
docId: req.body.docId,
|
2020-07-21 13:20:51 +00:00
|
|
|
page: req.body.page,
|
|
|
|
browser: req.body.browser,
|
|
|
|
org: mreq.org,
|
|
|
|
email: mreq.user && mreq.user.loginEmail,
|
|
|
|
userId: mreq.userId,
|
2022-04-08 18:00:43 +00:00
|
|
|
altSessionId: mreq.altSessionId,
|
2020-07-21 13:20:51 +00:00
|
|
|
});
|
|
|
|
return resp.status(200).send();
|
2023-04-06 15:10:29 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-07-04 21:21:34 +00:00
|
|
|
public async addTelemetry() {
|
2023-06-06 17:08:50 +00:00
|
|
|
if (this._check('telemetry', 'homedb', 'json', 'api-mw')) { return; }
|
2023-04-06 15:10:29 +00:00
|
|
|
|
2023-06-06 17:08:50 +00:00
|
|
|
this._telemetry = this.create.Telemetry(this._dbManager, this);
|
|
|
|
this._telemetry.addEndpoints(this.app);
|
2023-07-04 21:21:34 +00:00
|
|
|
this._telemetry.addPages(this.app, [
|
|
|
|
this._redirectToHostMiddleware,
|
|
|
|
this._userIdMiddleware,
|
|
|
|
this._redirectToLoginWithoutExceptionsMiddleware,
|
|
|
|
]);
|
|
|
|
await this._telemetry.start();
|
2023-04-06 15:10:29 +00:00
|
|
|
|
(core) For exporting XLSX, do it memory-efficiently in a worker thread.
Summary:
- Excel exports were awfully memory-inefficient, causing occasional docWorker
crashes. The fix is to use the "streaming writer" option of ExcelJS
https://github.com/exceljs/exceljs#streaming-xlsx-writercontents. (Empirically
on one example, max memory went down from 3G to 100M)
- It's also CPU intensive and synchronous, and can block node for tens of
seconds. The fix is to use a worker-thread. This diff uses "piscina" library
for a pool of threads.
- Additionally, adds ProcessMonitor that logs memory and cpu usage,
particularly when those change significantly.
- Also introduces request cancellation, so that a long download cancelled by
the user will cancel the work being done in the worker thread.
Test Plan:
Updated previous export tests; memory and CPU performance tested
manually by watching output of ProcessMonitor.
Difference visible in these log excerpts:
Before (total time to serve request 22 sec):
```
Telemetry processMonitor heapUsedMB=2187, heapTotalMB=2234, cpuAverage=1.13, intervalMs=17911
Telemetry processMonitor heapUsedMB=2188, heapTotalMB=2234, cpuAverage=0.66, intervalMs=5005
Telemetry processMonitor heapUsedMB=2188, heapTotalMB=2234, cpuAverage=0, intervalMs=5005
Telemetry processMonitor heapUsedMB=71, heapTotalMB=75, cpuAverage=0.13, intervalMs=5002
```
After (total time to server request 18 sec):
```
Telemetry processMonitor heapUsedMB=109, heapTotalMB=144, cpuAverage=0.5, intervalMs=5001
Telemetry processMonitor heapUsedMB=109, heapTotalMB=144, cpuAverage=1.39, intervalMs=5002
Telemetry processMonitor heapUsedMB=94, heapTotalMB=131, cpuAverage=1.13, intervalMs=5000
Telemetry processMonitor heapUsedMB=94, heapTotalMB=131, cpuAverage=1.35, intervalMs=5001
```
Note in "Before" that heapTotalMB goes up to 2GB in the first case, and "intervalMs" of 17 seconds indicates that node was unresponsive for that long. In the second case, heapTotalMB stays low, and the main thread remains responsive the whole time.
Reviewers: jarek
Reviewed By: jarek
Differential Revision: https://phab.getgrist.com/D3906
2023-06-01 13:09:50 +00:00
|
|
|
// Start up a monitor for memory and cpu usage.
|
2023-06-06 17:08:50 +00:00
|
|
|
this._processMonitorStop = ProcessMonitor.start(this._telemetry);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public async close() {
|
(core) For exporting XLSX, do it memory-efficiently in a worker thread.
Summary:
- Excel exports were awfully memory-inefficient, causing occasional docWorker
crashes. The fix is to use the "streaming writer" option of ExcelJS
https://github.com/exceljs/exceljs#streaming-xlsx-writercontents. (Empirically
on one example, max memory went down from 3G to 100M)
- It's also CPU intensive and synchronous, and can block node for tens of
seconds. The fix is to use a worker-thread. This diff uses "piscina" library
for a pool of threads.
- Additionally, adds ProcessMonitor that logs memory and cpu usage,
particularly when those change significantly.
- Also introduces request cancellation, so that a long download cancelled by
the user will cancel the work being done in the worker thread.
Test Plan:
Updated previous export tests; memory and CPU performance tested
manually by watching output of ProcessMonitor.
Difference visible in these log excerpts:
Before (total time to serve request 22 sec):
```
Telemetry processMonitor heapUsedMB=2187, heapTotalMB=2234, cpuAverage=1.13, intervalMs=17911
Telemetry processMonitor heapUsedMB=2188, heapTotalMB=2234, cpuAverage=0.66, intervalMs=5005
Telemetry processMonitor heapUsedMB=2188, heapTotalMB=2234, cpuAverage=0, intervalMs=5005
Telemetry processMonitor heapUsedMB=71, heapTotalMB=75, cpuAverage=0.13, intervalMs=5002
```
After (total time to server request 18 sec):
```
Telemetry processMonitor heapUsedMB=109, heapTotalMB=144, cpuAverage=0.5, intervalMs=5001
Telemetry processMonitor heapUsedMB=109, heapTotalMB=144, cpuAverage=1.39, intervalMs=5002
Telemetry processMonitor heapUsedMB=94, heapTotalMB=131, cpuAverage=1.13, intervalMs=5000
Telemetry processMonitor heapUsedMB=94, heapTotalMB=131, cpuAverage=1.35, intervalMs=5001
```
Note in "Before" that heapTotalMB goes up to 2GB in the first case, and "intervalMs" of 17 seconds indicates that node was unresponsive for that long. In the second case, heapTotalMB stays low, and the main thread remains responsive the whole time.
Reviewers: jarek
Reviewed By: jarek
Differential Revision: https://phab.getgrist.com/D3906
2023-06-01 13:09:50 +00:00
|
|
|
this._processMonitorStop?.();
|
2021-05-12 15:04:37 +00:00
|
|
|
if (this.usage) { await this.usage.close(); }
|
2020-07-21 13:20:51 +00:00
|
|
|
if (this._hosts) { this._hosts.close(); }
|
2021-08-17 15:22:30 +00:00
|
|
|
if (this._dbManager) {
|
|
|
|
this._dbManager.removeAllListeners();
|
|
|
|
this._dbManager.flushDocAuthCache();
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
if (this.server) { this.server.close(); }
|
|
|
|
if (this.httpsServer) { this.httpsServer.close(); }
|
|
|
|
if (this.housekeeper) { await this.housekeeper.stop(); }
|
|
|
|
await this._shutdown();
|
2022-07-19 15:39:49 +00:00
|
|
|
if (this._accessTokens) { await this._accessTokens.close(); }
|
(core) support GRIST_WORKER_GROUP to place worker into an exclusive group
Summary:
In an emergency, we may want to serve certain documents with "old" workers as we fix problems. This diff adds some support for that.
* Creates duplicate task definitions and services for staging and production doc workers (called grist-docs-staging2 and grist-docs-prod2), pulling from distinct docker tags (staging2 and prod2). The services are set to have zero workers until we need them.
* These new workers are started with a new env variable `GRIST_WORKER_GROUP` set to `secondary`.
* The `GRIST_WORKER_GROUP` variable, if set, makes the worker available to documents in the named group, and only that group.
* An unauthenticated `/assign` endpoint is added to documents which, when POSTed to, checks that the doc is served by a worker in the desired group for that doc (as set manually in redis), and if not frees the doc up for reassignment. This makes it possible to move individual docs between workers without redeployments.
The bash scripts added are a record of how the task definitions + services were created. The services could just have been copied manually, but the task definitions will need to be updated whenever the definitions for the main doc workers are updated, so it is worth scripting that.
For example, if a certain document were to fail on a new deployment of Grist, but rolling back the full deployment wasn't practical:
* Set prod2 tag in docker to desired codebase for that document
* Set desired_count for grist-docs-prod2 service to non-zero
* Set doc-<docid>-group for that doc in redis to secondary
* Hit /api/docs/<docid>/assign to move the doc to grist-docs-prod2
(If the document needs to be reverted to a previous snapshot, that currently would need doing manually - could be made simpler, but not in scope of this diff).
Test Plan: added tests
Reviewers: dsagal
Reviewed By: dsagal
Differential Revision: https://phab.getgrist.com/D2649
2020-11-02 19:24:46 +00:00
|
|
|
// Do this after _shutdown, since DocWorkerMap is used during shutdown.
|
2020-07-21 13:20:51 +00:00
|
|
|
if (this._docWorkerMap) { await this._docWorkerMap.close(); }
|
(core) support GRIST_WORKER_GROUP to place worker into an exclusive group
Summary:
In an emergency, we may want to serve certain documents with "old" workers as we fix problems. This diff adds some support for that.
* Creates duplicate task definitions and services for staging and production doc workers (called grist-docs-staging2 and grist-docs-prod2), pulling from distinct docker tags (staging2 and prod2). The services are set to have zero workers until we need them.
* These new workers are started with a new env variable `GRIST_WORKER_GROUP` set to `secondary`.
* The `GRIST_WORKER_GROUP` variable, if set, makes the worker available to documents in the named group, and only that group.
* An unauthenticated `/assign` endpoint is added to documents which, when POSTed to, checks that the doc is served by a worker in the desired group for that doc (as set manually in redis), and if not frees the doc up for reassignment. This makes it possible to move individual docs between workers without redeployments.
The bash scripts added are a record of how the task definitions + services were created. The services could just have been copied manually, but the task definitions will need to be updated whenever the definitions for the main doc workers are updated, so it is worth scripting that.
For example, if a certain document were to fail on a new deployment of Grist, but rolling back the full deployment wasn't practical:
* Set prod2 tag in docker to desired codebase for that document
* Set desired_count for grist-docs-prod2 service to non-zero
* Set doc-<docid>-group for that doc in redis to secondary
* Hit /api/docs/<docid>/assign to move the doc to grist-docs-prod2
(If the document needs to be reverted to a previous snapshot, that currently would need doing manually - could be made simpler, but not in scope of this diff).
Test Plan: added tests
Reviewers: dsagal
Reviewed By: dsagal
Differential Revision: https://phab.getgrist.com/D2649
2020-11-02 19:24:46 +00:00
|
|
|
if (this._sessionStore) { await this._sessionStore.close(); }
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public addDocApiForwarder() {
|
|
|
|
if (this._check('doc_api_forwarder', '!json', 'homedb', 'api-mw', 'map')) { return; }
|
2022-07-19 15:39:49 +00:00
|
|
|
const docApiForwarder = new DocApiForwarder(this._docWorkerMap, this._dbManager, this);
|
2020-07-21 13:20:51 +00:00
|
|
|
docApiForwarder.addEndpoints(this.app);
|
|
|
|
}
|
|
|
|
|
|
|
|
public addJsonSupport() {
|
|
|
|
if (this._check('json')) { return; }
|
|
|
|
this.app.use(bodyParser.json({limit: '1mb'})); // Increase from the default 100kb
|
|
|
|
}
|
|
|
|
|
|
|
|
public addSessions() {
|
|
|
|
if (this._check('sessions', 'config')) { return; }
|
|
|
|
this.addTagChecker();
|
|
|
|
this.addOrg();
|
|
|
|
|
|
|
|
// Create the sessionStore and related objects.
|
2023-02-13 20:52:17 +00:00
|
|
|
const {sessions, sessionMiddleware, sessionStore} = initGristSessions(getUnpackedAppRoot(this.instanceRoot), this);
|
2020-07-21 13:20:51 +00:00
|
|
|
this.app.use(sessionMiddleware);
|
2021-10-01 14:24:23 +00:00
|
|
|
this.app.use(signInStatusMiddleware);
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
// Create an endpoint for making cookies during testing.
|
|
|
|
this.app.get('/test/session', async (req, res) => {
|
2021-11-24 14:50:44 +00:00
|
|
|
const mreq = req as RequestWithLogin;
|
|
|
|
forceSessionChange(mreq.session);
|
2020-07-21 13:20:51 +00:00
|
|
|
res.status(200).send(`Grist ${this.name} is alive and is interested in you.`);
|
|
|
|
});
|
|
|
|
|
2021-08-16 15:11:17 +00:00
|
|
|
this._sessions = sessions;
|
(core) support GRIST_WORKER_GROUP to place worker into an exclusive group
Summary:
In an emergency, we may want to serve certain documents with "old" workers as we fix problems. This diff adds some support for that.
* Creates duplicate task definitions and services for staging and production doc workers (called grist-docs-staging2 and grist-docs-prod2), pulling from distinct docker tags (staging2 and prod2). The services are set to have zero workers until we need them.
* These new workers are started with a new env variable `GRIST_WORKER_GROUP` set to `secondary`.
* The `GRIST_WORKER_GROUP` variable, if set, makes the worker available to documents in the named group, and only that group.
* An unauthenticated `/assign` endpoint is added to documents which, when POSTed to, checks that the doc is served by a worker in the desired group for that doc (as set manually in redis), and if not frees the doc up for reassignment. This makes it possible to move individual docs between workers without redeployments.
The bash scripts added are a record of how the task definitions + services were created. The services could just have been copied manually, but the task definitions will need to be updated whenever the definitions for the main doc workers are updated, so it is worth scripting that.
For example, if a certain document were to fail on a new deployment of Grist, but rolling back the full deployment wasn't practical:
* Set prod2 tag in docker to desired codebase for that document
* Set desired_count for grist-docs-prod2 service to non-zero
* Set doc-<docid>-group for that doc in redis to secondary
* Hit /api/docs/<docid>/assign to move the doc to grist-docs-prod2
(If the document needs to be reverted to a previous snapshot, that currently would need doing manually - could be made simpler, but not in scope of this diff).
Test Plan: added tests
Reviewers: dsagal
Reviewed By: dsagal
Differential Revision: https://phab.getgrist.com/D2649
2020-11-02 19:24:46 +00:00
|
|
|
this._sessionStore = sessionStore;
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Close connections and stop accepting new connections. Remove server from any lists
|
|
|
|
// it may be in.
|
|
|
|
public async stopListening(mode: 'crash'|'clean' = 'clean') {
|
|
|
|
if (!this._disabled) {
|
|
|
|
if (mode === 'clean') {
|
|
|
|
await this._shutdown();
|
|
|
|
this._disabled = true;
|
|
|
|
} else {
|
|
|
|
this._disabled = true;
|
2021-08-17 15:22:30 +00:00
|
|
|
if (this._comm) {
|
|
|
|
this._comm.setServerActivation(false);
|
|
|
|
this._comm.destroyAllClients();
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
this.server.close();
|
|
|
|
if (this.httpsServer) { this.httpsServer.close(); }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public async createWorkerUrl(): Promise<{url: string, host: string}> {
|
|
|
|
if (!process.env.GRIST_ROUTER_URL) {
|
|
|
|
throw new Error('No service available to create worker url');
|
|
|
|
}
|
|
|
|
const w = await axios.get(process.env.GRIST_ROUTER_URL,
|
|
|
|
{params: {act: 'add', port: this.getOwnPort()}});
|
|
|
|
log.info(`DocWorker registered itself via ${process.env.GRIST_ROUTER_URL} as ${w.data.url}`);
|
|
|
|
const statusUrl = `${w.data.url}/status`;
|
|
|
|
// We now wait for the worker to be available from the url that clients will
|
|
|
|
// use to connect to it. This may take some time. The main delay is the
|
|
|
|
// new target group and load balancer rule taking effect - typically 10-20 seconds.
|
|
|
|
// If we don't wait, the worker will end up registered for work and clients
|
|
|
|
// could end up trying to reach it to open documents - but the url they have
|
|
|
|
// won't work.
|
|
|
|
for (let tries = 0; tries < 600; tries++) {
|
|
|
|
await delay(1000);
|
|
|
|
try {
|
|
|
|
await axios.get(statusUrl);
|
|
|
|
return w.data;
|
|
|
|
} catch (err) {
|
2022-06-08 17:54:00 +00:00
|
|
|
log.debug(`While waiting for ${statusUrl} got error ${(err as Error).message}`);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
throw new Error(`Cannot connect to ${statusUrl}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Accept new connections again. Add server to any lists it needs to be in to get work.
|
|
|
|
public async restartListening() {
|
|
|
|
if (!this._docWorkerMap) { throw new Error('expected to have DocWorkerMap'); }
|
|
|
|
await this.stopListening('clean');
|
|
|
|
if (this._disabled) {
|
|
|
|
if (this._storageManager) {
|
|
|
|
this._storageManager.testReopenStorage();
|
|
|
|
}
|
2021-08-17 15:22:30 +00:00
|
|
|
this._comm.setServerActivation(true);
|
2020-07-21 13:20:51 +00:00
|
|
|
if (this.worker) {
|
|
|
|
await this._startServers(this.server, this.httpsServer, this.name, this.port, false);
|
|
|
|
await this._addSelfAsWorker(this._docWorkerMap);
|
|
|
|
}
|
|
|
|
this._disabled = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-05 15:12:46 +00:00
|
|
|
public async addLandingPages() {
|
2020-07-21 13:20:51 +00:00
|
|
|
// TODO: check if isSingleUserMode() path can be removed from this method
|
|
|
|
if (this._check('landing', 'map', isSingleUserMode() ? null : 'homedb')) { return; }
|
|
|
|
this.addSessions();
|
|
|
|
|
|
|
|
// Initialize _sendAppPage helper.
|
|
|
|
this._sendAppPage = makeSendAppPage({
|
2023-06-06 17:08:50 +00:00
|
|
|
server: this,
|
2020-07-21 13:20:51 +00:00
|
|
|
staticDir: getAppPathTo(this.appRoot, 'static'),
|
|
|
|
tag: this.tag,
|
|
|
|
testLogin: allowTestLogin(),
|
|
|
|
baseDomain: this._defaultBaseDomain,
|
|
|
|
});
|
|
|
|
|
2022-06-15 14:29:29 +00:00
|
|
|
const isForced = appSettings.section('login').flag('forced').readBool({
|
|
|
|
envVar: 'GRIST_FORCE_LOGIN',
|
|
|
|
});
|
|
|
|
const forcedLoginMiddleware = isForced ? this._redirectToLoginWithoutExceptionsMiddleware : noop;
|
2022-05-18 10:25:14 +00:00
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
const welcomeNewUser: express.RequestHandler = isSingleUserMode() ?
|
|
|
|
(req, res, next) => next() :
|
|
|
|
expressWrap(async (req, res, next) => {
|
|
|
|
const mreq = req as RequestWithLogin;
|
|
|
|
const user = getUser(req);
|
|
|
|
if (user && user.isFirstTimeUser) {
|
|
|
|
log.debug(`welcoming user: ${user.name}`);
|
2022-06-06 17:42:51 +00:00
|
|
|
// Reset isFirstTimeUser flag.
|
2022-02-22 03:09:18 +00:00
|
|
|
await this._dbManager.updateUser(user.id, {isFirstTimeUser: false});
|
|
|
|
|
2022-03-11 20:35:29 +00:00
|
|
|
// This is a good time to set some other flags, for showing a popup with welcome question(s)
|
|
|
|
// to this new user and recording their sign-up with Google Tag Manager. These flags are also
|
|
|
|
// scoped to the user, but isFirstTimeUser has a dedicated DB field because it predates userPrefs.
|
|
|
|
// Note that the updateOrg() method handles all levels of prefs (for user, user+org, or org).
|
|
|
|
await this._dbManager.updateOrg(getScope(req), 0, {userPrefs: {
|
|
|
|
showNewUserQuestions: true,
|
2023-03-14 16:00:38 +00:00
|
|
|
recordSignUpEvent: true
|
2022-03-11 20:35:29 +00:00
|
|
|
}});
|
2022-02-22 03:09:18 +00:00
|
|
|
|
2023-06-15 00:03:17 +00:00
|
|
|
// Give a chance to the login system to react to the first visit after signup.
|
|
|
|
this._loginMiddleware.onFirstVisit?.(req);
|
|
|
|
|
2023-09-06 18:35:46 +00:00
|
|
|
// If we need to copy an unsaved document or template as part of sign-up, do so now
|
|
|
|
// and redirect to it.
|
|
|
|
const docId = await this._maybeCopyDocToHomeWorkspace(mreq, res);
|
|
|
|
if (docId) {
|
|
|
|
return res.redirect(this.getMergedOrgUrl(mreq, `/doc/${docId}`));
|
|
|
|
}
|
|
|
|
|
2022-06-06 17:42:51 +00:00
|
|
|
const domain = mreq.org ?? null;
|
|
|
|
if (!process.env.GRIST_SINGLE_ORG && this._dbManager.isMergedOrg(domain)) {
|
|
|
|
// We're logging in for the first time on the merged org; if the user has
|
|
|
|
// access to other team sites, forward the user to a page that lists all
|
|
|
|
// the teams they have access to.
|
|
|
|
const result = await this._dbManager.getMergedOrgs(user.id, user.id, domain);
|
|
|
|
const orgs = this._dbManager.unwrapQueryResult(result);
|
|
|
|
if (orgs.length > 1 && mreq.path === '/') {
|
|
|
|
// Only forward if the request is for the home page.
|
|
|
|
return res.redirect(this.getMergedOrgUrl(mreq, '/welcome/teams'));
|
|
|
|
}
|
2022-04-04 21:50:40 +00:00
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
2021-06-24 23:32:37 +00:00
|
|
|
if (mreq.org && mreq.org.startsWith('o-')) {
|
|
|
|
// We are on a team site without a custom subdomain.
|
2022-06-08 17:54:00 +00:00
|
|
|
const orgInfo = this._dbManager.unwrapQueryResult(await this._dbManager.getOrg({userId: user.id}, mreq.org));
|
|
|
|
|
2021-06-24 23:32:37 +00:00
|
|
|
// If the user is a billing manager for the org, and the org
|
|
|
|
// is supposed to have a custom subdomain, forward the user
|
|
|
|
// to a page to set it.
|
|
|
|
|
|
|
|
// TODO: this is more or less a hack for AppSumo signup flow,
|
|
|
|
// and could be removed if/when signup flow is revamped.
|
|
|
|
|
|
|
|
// If "welcomeNewUser" is ever added to billing pages, we'd need
|
|
|
|
// to avoid a redirect loop.
|
|
|
|
|
|
|
|
if (orgInfo.billingAccount.isManager && orgInfo.billingAccount.product.features.vanityDomain) {
|
2022-06-08 17:54:00 +00:00
|
|
|
const prefix = isOrgInPathOnly(req.hostname) ? `/o/${mreq.org}` : '';
|
|
|
|
return res.redirect(`${prefix}/billing/payment?billingTask=signUpLite`);
|
2021-06-24 23:32:37 +00:00
|
|
|
}
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
next();
|
|
|
|
});
|
|
|
|
|
|
|
|
attachAppEndpoint({
|
|
|
|
app: this.app,
|
|
|
|
middleware: [
|
|
|
|
this._redirectToHostMiddleware,
|
|
|
|
this._userIdMiddleware,
|
2022-05-18 10:25:14 +00:00
|
|
|
forcedLoginMiddleware,
|
2020-07-21 13:20:51 +00:00
|
|
|
this._redirectToLoginWithExceptionsMiddleware,
|
|
|
|
this._redirectToOrgMiddleware,
|
|
|
|
welcomeNewUser
|
|
|
|
],
|
2020-08-19 20:25:42 +00:00
|
|
|
docMiddleware: [
|
|
|
|
// Same as middleware, except without login redirect middleware.
|
|
|
|
this._redirectToHostMiddleware,
|
|
|
|
this._userIdMiddleware,
|
2022-05-18 10:25:14 +00:00
|
|
|
forcedLoginMiddleware,
|
2020-08-19 20:25:42 +00:00
|
|
|
this._redirectToOrgMiddleware,
|
|
|
|
welcomeNewUser
|
|
|
|
],
|
|
|
|
forceLogin: this._redirectToLoginUnconditionally,
|
2020-07-21 13:20:51 +00:00
|
|
|
docWorkerMap: isSingleUserMode() ? null : this._docWorkerMap,
|
|
|
|
sendAppPage: this._sendAppPage,
|
2021-08-17 15:22:30 +00:00
|
|
|
dbManager: this._dbManager,
|
(core) make Grist easier to run with a single server
Summary:
This makes many small changes so that Grist is less fussy to run as a single instance behind a reverse proxy. Some users had difficulty with the self-connections Grist would make, due to internal network setup, and since these are unnecessary in any case in this scenario, they are now optimized away. Likewise some users had difficulties related to doc worker urls, which are now also optimized away. With these changes, users should be able to get a lot further on first try, at least far enough to open and edit documents.
The `GRIST_SINGLE_ORG` setting was proving a bit confusing, since it appeared to only work when set to `docs`. This diff
adds a check for whether the specified org exists, and if not, it creates it. This still depends on having a user email to make as the owner of the team, so there could be remaining difficulties there.
Test Plan: tested manually with nginx
Reviewers: jarek
Reviewed By: jarek
Differential Revision: https://phab.getgrist.com/D3299
2022-03-02 19:07:26 +00:00
|
|
|
plugins : (await this._addPluginManager()).getPlugins(),
|
|
|
|
gristServer: this,
|
2020-07-21 13:20:51 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-05-17 22:25:36 +00:00
|
|
|
/**
|
|
|
|
* Load user config file from standard location (if present).
|
|
|
|
*
|
|
|
|
* Note that the user config file doesn't do anything today, but may be useful in
|
|
|
|
* the future for configuring things that don't fit well into environment variables.
|
|
|
|
*
|
|
|
|
* TODO: Revisit this, and update `GristServer.settings` type to match the expected shape
|
|
|
|
* of config.json. (ts-interface-checker could be useful here for runtime validation.)
|
|
|
|
*/
|
|
|
|
public async loadConfig() {
|
2020-07-21 13:20:51 +00:00
|
|
|
if (this._check('config')) { return; }
|
2022-05-17 22:25:36 +00:00
|
|
|
const settingsPath = path.join(this.instanceRoot, 'config.json');
|
|
|
|
if (await fse.pathExists(settingsPath)) {
|
|
|
|
log.info(`Loading config from ${settingsPath}`);
|
|
|
|
this.settings = JSON.parse(await fse.readFile(settingsPath, 'utf8'));
|
2020-07-21 13:20:51 +00:00
|
|
|
} else {
|
2022-05-17 22:25:36 +00:00
|
|
|
log.info(`Loading empty config because ${settingsPath} missing`);
|
|
|
|
this.settings = {};
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: We could include a third mock provider of login/logout URLs for better tests. Or we
|
|
|
|
// could create a mock SAML identity provider for testing this using the SAML flow.
|
2023-02-13 20:52:17 +00:00
|
|
|
const loginSystem = await (process.env.GRIST_TEST_LOGIN ? getTestLoginSystem() :
|
|
|
|
(this._getLoginSystem?.() || getLoginSystem()));
|
2021-09-29 15:39:56 +00:00
|
|
|
this._loginMiddleware = await loginSystem.getMiddleware(this);
|
2020-07-21 13:20:51 +00:00
|
|
|
this._getLoginRedirectUrl = tbind(this._loginMiddleware.getLoginRedirectUrl, this._loginMiddleware);
|
|
|
|
this._getSignUpRedirectUrl = tbind(this._loginMiddleware.getSignUpRedirectUrl, this._loginMiddleware);
|
|
|
|
this._getLogoutRedirectUrl = tbind(this._loginMiddleware.getLogoutRedirectUrl, this._loginMiddleware);
|
2023-02-13 20:52:17 +00:00
|
|
|
const wildcardMiddleware = this._loginMiddleware.getWildcardMiddleware?.();
|
|
|
|
if (wildcardMiddleware?.length) {
|
|
|
|
this.app.use(wildcardMiddleware);
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public addComm() {
|
2022-06-15 14:29:29 +00:00
|
|
|
if (this._check('comm', 'start', 'homedb', 'config')) { return; }
|
2021-08-17 15:22:30 +00:00
|
|
|
this._comm = new Comm(this.server, {
|
2020-07-21 13:20:51 +00:00
|
|
|
settings: this.settings,
|
2021-08-16 15:11:17 +00:00
|
|
|
sessions: this._sessions,
|
2020-07-21 13:20:51 +00:00
|
|
|
hosts: this._hosts,
|
2022-06-15 14:29:29 +00:00
|
|
|
loginMiddleware: this._loginMiddleware,
|
2020-07-21 13:20:51 +00:00
|
|
|
httpsServer: this.httpsServer,
|
2022-09-29 08:01:37 +00:00
|
|
|
i18Instance: this.i18Instance
|
2020-07-21 13:20:51 +00:00
|
|
|
});
|
|
|
|
}
|
2021-07-13 07:29:38 +00:00
|
|
|
/**
|
|
|
|
* Add endpoint that servers a javascript file with various api keys that
|
|
|
|
* are used by the client libraries.
|
|
|
|
*/
|
|
|
|
public addClientSecrets() {
|
|
|
|
if (this._check('clientSecret')) { return; }
|
|
|
|
this.app.get('/client-secret.js', expressWrap(async (req, res) => {
|
|
|
|
const config = this.getGristConfig();
|
|
|
|
// Currently we are exposing only Google keys.
|
|
|
|
// Those keys are eventually visible by the client, but should be usable
|
|
|
|
// only from Grist's domains.
|
|
|
|
const secrets = {
|
2021-08-03 10:34:05 +00:00
|
|
|
googleClientId: config.googleClientId,
|
2021-07-13 07:29:38 +00:00
|
|
|
};
|
|
|
|
res.set('Content-Type', 'application/javascript');
|
|
|
|
res.status(200);
|
|
|
|
res.send(`
|
|
|
|
window.gristClientSecret = ${JSON.stringify(secrets)}
|
|
|
|
`);
|
|
|
|
}));
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
|
2021-08-17 15:22:30 +00:00
|
|
|
public async addLoginRoutes() {
|
(core) move more tests to grist-core
Summary:
* Tie build and run-time docker base images to a consistent version (buster)
* Extend the test login system activated by GRIST_TEST_LOGIN to ease porting tests that currently rely on cognito (many)
* Make org resets work in absence of billing endpoints
* When in-memory session caches are used, add missing invalidation steps
* Pass org information through sign-ups/sign-ins more carefully
* For CORS, explicitly trust GRIST_HOST origin when set
* Move some fixtures and tests to core, focussing on tests that cover existing failures or are in the set of tests run on deployments
* Retain regular `test` target to run the test suite directly, without docker
* Add a `test:smoke` target to run a single simple test without `GRIST_TEST_LOGIN` activated
* Add a `test:docker` target to run the tests against a grist-core docker image - since tests rely on certain fixture teams/docs, added `TEST_SUPPORT_API_KEY` and `TEST_ADD_SAMPLES` flags to ease porting
The tests ported were `nbrowser` tests: `ActionLog.ts` (the first test I tend to port to anything, out of habit), `Fork.ts` (exercises a lot of doc creation paths), `HomeIntro.ts` (a lot of DocMenu exercise), and `DuplicateDocument.ts` (covers a feature known to be failing prior to this diff, the CORS tweak resolves it).
Test Plan: Manually tested via `buildtools/build_core.sh`. In follow up, I want to add running the `test:docker` target in grist-core's workflows. In jenkins, only the smoke test is run. There'd be an argument for running all tests, but they include particularly slow tests, and are duplicates of tests already run (in different configuration admittedly), so I'd like to try first just using them in grist-core to gate updates to any packaged version of Grist (the docker image currently).
Reviewers: alexmojaki
Reviewed By: alexmojaki
Subscribers: alexmojaki
Differential Revision: https://phab.getgrist.com/D3176
2021-12-10 22:42:54 +00:00
|
|
|
if (this._check('login', 'org', 'sessions', 'homedb', 'hosts')) { return; }
|
2020-07-21 13:20:51 +00:00
|
|
|
// TODO: We do NOT want Comm here at all, it's only being used for handling sessions, which
|
|
|
|
// should be factored out of it.
|
|
|
|
this.addComm();
|
|
|
|
|
2022-04-01 21:31:24 +00:00
|
|
|
const signinMiddleware = this._loginMiddleware.getLoginOrSignUpMiddleware ?
|
2022-03-07 16:40:46 +00:00
|
|
|
this._loginMiddleware.getLoginOrSignUpMiddleware() :
|
|
|
|
[];
|
2023-03-21 13:32:34 +00:00
|
|
|
this.app.get('/login', ...signinMiddleware, expressWrap(this._redirectToLoginOrSignup.bind(this, {
|
|
|
|
signUp: false,
|
|
|
|
})));
|
|
|
|
this.app.get('/signup', ...signinMiddleware, expressWrap(this._redirectToLoginOrSignup.bind(this, {
|
|
|
|
signUp: true,
|
|
|
|
})));
|
|
|
|
this.app.get('/signin', ...signinMiddleware, expressWrap(this._redirectToLoginOrSignup.bind(this, {})));
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
if (allowTestLogin()) {
|
|
|
|
// This is an endpoint for the dev environment that lets you log in as anyone.
|
|
|
|
// For a standard dev environment, it will be accessible at localhost:8080/test/login
|
|
|
|
// and localhost:8080/o/<org>/test/login. Only available when GRIST_TEST_LOGIN is set.
|
|
|
|
// Handy when without network connectivity to reach Cognito.
|
|
|
|
|
|
|
|
log.warn("Adding a /test/login endpoint because GRIST_TEST_LOGIN is set. " +
|
|
|
|
"Users will be able to login as anyone.");
|
|
|
|
|
|
|
|
this.app.get('/test/login', expressWrap(async (req, res) => {
|
|
|
|
log.warn("Serving unauthenticated /test/login endpoint, made available because GRIST_TEST_LOGIN is set.");
|
|
|
|
|
(core) move more tests to grist-core
Summary:
* Tie build and run-time docker base images to a consistent version (buster)
* Extend the test login system activated by GRIST_TEST_LOGIN to ease porting tests that currently rely on cognito (many)
* Make org resets work in absence of billing endpoints
* When in-memory session caches are used, add missing invalidation steps
* Pass org information through sign-ups/sign-ins more carefully
* For CORS, explicitly trust GRIST_HOST origin when set
* Move some fixtures and tests to core, focussing on tests that cover existing failures or are in the set of tests run on deployments
* Retain regular `test` target to run the test suite directly, without docker
* Add a `test:smoke` target to run a single simple test without `GRIST_TEST_LOGIN` activated
* Add a `test:docker` target to run the tests against a grist-core docker image - since tests rely on certain fixture teams/docs, added `TEST_SUPPORT_API_KEY` and `TEST_ADD_SAMPLES` flags to ease porting
The tests ported were `nbrowser` tests: `ActionLog.ts` (the first test I tend to port to anything, out of habit), `Fork.ts` (exercises a lot of doc creation paths), `HomeIntro.ts` (a lot of DocMenu exercise), and `DuplicateDocument.ts` (covers a feature known to be failing prior to this diff, the CORS tweak resolves it).
Test Plan: Manually tested via `buildtools/build_core.sh`. In follow up, I want to add running the `test:docker` target in grist-core's workflows. In jenkins, only the smoke test is run. There'd be an argument for running all tests, but they include particularly slow tests, and are duplicates of tests already run (in different configuration admittedly), so I'd like to try first just using them in grist-core to gate updates to any packaged version of Grist (the docker image currently).
Reviewers: alexmojaki
Reviewed By: alexmojaki
Subscribers: alexmojaki
Differential Revision: https://phab.getgrist.com/D3176
2021-12-10 22:42:54 +00:00
|
|
|
// Query parameter is called "username" for compatibility with Cognito.
|
2023-09-05 18:27:35 +00:00
|
|
|
const email = optStringParam(req.query.username, 'username');
|
(core) move more tests to grist-core
Summary:
* Tie build and run-time docker base images to a consistent version (buster)
* Extend the test login system activated by GRIST_TEST_LOGIN to ease porting tests that currently rely on cognito (many)
* Make org resets work in absence of billing endpoints
* When in-memory session caches are used, add missing invalidation steps
* Pass org information through sign-ups/sign-ins more carefully
* For CORS, explicitly trust GRIST_HOST origin when set
* Move some fixtures and tests to core, focussing on tests that cover existing failures or are in the set of tests run on deployments
* Retain regular `test` target to run the test suite directly, without docker
* Add a `test:smoke` target to run a single simple test without `GRIST_TEST_LOGIN` activated
* Add a `test:docker` target to run the tests against a grist-core docker image - since tests rely on certain fixture teams/docs, added `TEST_SUPPORT_API_KEY` and `TEST_ADD_SAMPLES` flags to ease porting
The tests ported were `nbrowser` tests: `ActionLog.ts` (the first test I tend to port to anything, out of habit), `Fork.ts` (exercises a lot of doc creation paths), `HomeIntro.ts` (a lot of DocMenu exercise), and `DuplicateDocument.ts` (covers a feature known to be failing prior to this diff, the CORS tweak resolves it).
Test Plan: Manually tested via `buildtools/build_core.sh`. In follow up, I want to add running the `test:docker` target in grist-core's workflows. In jenkins, only the smoke test is run. There'd be an argument for running all tests, but they include particularly slow tests, and are duplicates of tests already run (in different configuration admittedly), so I'd like to try first just using them in grist-core to gate updates to any packaged version of Grist (the docker image currently).
Reviewers: alexmojaki
Reviewed By: alexmojaki
Subscribers: alexmojaki
Differential Revision: https://phab.getgrist.com/D3176
2021-12-10 22:42:54 +00:00
|
|
|
if (email) {
|
2023-09-05 18:27:35 +00:00
|
|
|
const redirect = optStringParam(req.query.next, 'next');
|
(core) move more tests to grist-core
Summary:
* Tie build and run-time docker base images to a consistent version (buster)
* Extend the test login system activated by GRIST_TEST_LOGIN to ease porting tests that currently rely on cognito (many)
* Make org resets work in absence of billing endpoints
* When in-memory session caches are used, add missing invalidation steps
* Pass org information through sign-ups/sign-ins more carefully
* For CORS, explicitly trust GRIST_HOST origin when set
* Move some fixtures and tests to core, focussing on tests that cover existing failures or are in the set of tests run on deployments
* Retain regular `test` target to run the test suite directly, without docker
* Add a `test:smoke` target to run a single simple test without `GRIST_TEST_LOGIN` activated
* Add a `test:docker` target to run the tests against a grist-core docker image - since tests rely on certain fixture teams/docs, added `TEST_SUPPORT_API_KEY` and `TEST_ADD_SAMPLES` flags to ease porting
The tests ported were `nbrowser` tests: `ActionLog.ts` (the first test I tend to port to anything, out of habit), `Fork.ts` (exercises a lot of doc creation paths), `HomeIntro.ts` (a lot of DocMenu exercise), and `DuplicateDocument.ts` (covers a feature known to be failing prior to this diff, the CORS tweak resolves it).
Test Plan: Manually tested via `buildtools/build_core.sh`. In follow up, I want to add running the `test:docker` target in grist-core's workflows. In jenkins, only the smoke test is run. There'd be an argument for running all tests, but they include particularly slow tests, and are duplicates of tests already run (in different configuration admittedly), so I'd like to try first just using them in grist-core to gate updates to any packaged version of Grist (the docker image currently).
Reviewers: alexmojaki
Reviewed By: alexmojaki
Subscribers: alexmojaki
Differential Revision: https://phab.getgrist.com/D3176
2021-12-10 22:42:54 +00:00
|
|
|
const profile: UserProfile = {
|
|
|
|
email,
|
2023-09-05 18:27:35 +00:00
|
|
|
name: optStringParam(req.query.name, 'name') || email,
|
(core) move more tests to grist-core
Summary:
* Tie build and run-time docker base images to a consistent version (buster)
* Extend the test login system activated by GRIST_TEST_LOGIN to ease porting tests that currently rely on cognito (many)
* Make org resets work in absence of billing endpoints
* When in-memory session caches are used, add missing invalidation steps
* Pass org information through sign-ups/sign-ins more carefully
* For CORS, explicitly trust GRIST_HOST origin when set
* Move some fixtures and tests to core, focussing on tests that cover existing failures or are in the set of tests run on deployments
* Retain regular `test` target to run the test suite directly, without docker
* Add a `test:smoke` target to run a single simple test without `GRIST_TEST_LOGIN` activated
* Add a `test:docker` target to run the tests against a grist-core docker image - since tests rely on certain fixture teams/docs, added `TEST_SUPPORT_API_KEY` and `TEST_ADD_SAMPLES` flags to ease porting
The tests ported were `nbrowser` tests: `ActionLog.ts` (the first test I tend to port to anything, out of habit), `Fork.ts` (exercises a lot of doc creation paths), `HomeIntro.ts` (a lot of DocMenu exercise), and `DuplicateDocument.ts` (covers a feature known to be failing prior to this diff, the CORS tweak resolves it).
Test Plan: Manually tested via `buildtools/build_core.sh`. In follow up, I want to add running the `test:docker` target in grist-core's workflows. In jenkins, only the smoke test is run. There'd be an argument for running all tests, but they include particularly slow tests, and are duplicates of tests already run (in different configuration admittedly), so I'd like to try first just using them in grist-core to gate updates to any packaged version of Grist (the docker image currently).
Reviewers: alexmojaki
Reviewed By: alexmojaki
Subscribers: alexmojaki
Differential Revision: https://phab.getgrist.com/D3176
2021-12-10 22:42:54 +00:00
|
|
|
};
|
|
|
|
const url = new URL(redirect || getOrgUrl(req));
|
|
|
|
// Make sure we update session for org we'll be redirecting to.
|
|
|
|
const {org} = await this._hosts.getOrgInfoFromParts(url.hostname, url.pathname);
|
|
|
|
const scopedSession = this._sessions.getOrCreateSessionFromRequest(req, { org });
|
|
|
|
await scopedSession.updateUserProfile(req, profile);
|
|
|
|
this._sessions.clearCacheIfNeeded({email, org});
|
|
|
|
if (redirect) { return res.redirect(redirect); }
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
res.send(`<!doctype html>
|
|
|
|
<html><body>
|
(core) move more tests to grist-core
Summary:
* Tie build and run-time docker base images to a consistent version (buster)
* Extend the test login system activated by GRIST_TEST_LOGIN to ease porting tests that currently rely on cognito (many)
* Make org resets work in absence of billing endpoints
* When in-memory session caches are used, add missing invalidation steps
* Pass org information through sign-ups/sign-ins more carefully
* For CORS, explicitly trust GRIST_HOST origin when set
* Move some fixtures and tests to core, focussing on tests that cover existing failures or are in the set of tests run on deployments
* Retain regular `test` target to run the test suite directly, without docker
* Add a `test:smoke` target to run a single simple test without `GRIST_TEST_LOGIN` activated
* Add a `test:docker` target to run the tests against a grist-core docker image - since tests rely on certain fixture teams/docs, added `TEST_SUPPORT_API_KEY` and `TEST_ADD_SAMPLES` flags to ease porting
The tests ported were `nbrowser` tests: `ActionLog.ts` (the first test I tend to port to anything, out of habit), `Fork.ts` (exercises a lot of doc creation paths), `HomeIntro.ts` (a lot of DocMenu exercise), and `DuplicateDocument.ts` (covers a feature known to be failing prior to this diff, the CORS tweak resolves it).
Test Plan: Manually tested via `buildtools/build_core.sh`. In follow up, I want to add running the `test:docker` target in grist-core's workflows. In jenkins, only the smoke test is run. There'd be an argument for running all tests, but they include particularly slow tests, and are duplicates of tests already run (in different configuration admittedly), so I'd like to try first just using them in grist-core to gate updates to any packaged version of Grist (the docker image currently).
Reviewers: alexmojaki
Reviewed By: alexmojaki
Subscribers: alexmojaki
Differential Revision: https://phab.getgrist.com/D3176
2021-12-10 22:42:54 +00:00
|
|
|
<div class="modal-content-desktop">
|
2022-02-28 19:43:51 +00:00
|
|
|
<h1>A Very Credulous Login Page</h1>
|
(core) move more tests to grist-core
Summary:
* Tie build and run-time docker base images to a consistent version (buster)
* Extend the test login system activated by GRIST_TEST_LOGIN to ease porting tests that currently rely on cognito (many)
* Make org resets work in absence of billing endpoints
* When in-memory session caches are used, add missing invalidation steps
* Pass org information through sign-ups/sign-ins more carefully
* For CORS, explicitly trust GRIST_HOST origin when set
* Move some fixtures and tests to core, focussing on tests that cover existing failures or are in the set of tests run on deployments
* Retain regular `test` target to run the test suite directly, without docker
* Add a `test:smoke` target to run a single simple test without `GRIST_TEST_LOGIN` activated
* Add a `test:docker` target to run the tests against a grist-core docker image - since tests rely on certain fixture teams/docs, added `TEST_SUPPORT_API_KEY` and `TEST_ADD_SAMPLES` flags to ease porting
The tests ported were `nbrowser` tests: `ActionLog.ts` (the first test I tend to port to anything, out of habit), `Fork.ts` (exercises a lot of doc creation paths), `HomeIntro.ts` (a lot of DocMenu exercise), and `DuplicateDocument.ts` (covers a feature known to be failing prior to this diff, the CORS tweak resolves it).
Test Plan: Manually tested via `buildtools/build_core.sh`. In follow up, I want to add running the `test:docker` target in grist-core's workflows. In jenkins, only the smoke test is run. There'd be an argument for running all tests, but they include particularly slow tests, and are duplicates of tests already run (in different configuration admittedly), so I'd like to try first just using them in grist-core to gate updates to any packaged version of Grist (the docker image currently).
Reviewers: alexmojaki
Reviewed By: alexmojaki
Subscribers: alexmojaki
Differential Revision: https://phab.getgrist.com/D3176
2021-12-10 22:42:54 +00:00
|
|
|
<p>
|
|
|
|
A minimal login screen to facilitate testing.
|
|
|
|
I'll believe anything you tell me.
|
|
|
|
</p>
|
|
|
|
<form>
|
|
|
|
<div>Email <input type=text name=username placeholder=email /></div>
|
|
|
|
<div>Name <input type=text name=name placeholder=name /></div>
|
|
|
|
<div>Dummy password <input type=text name=password placeholder=unused ></div>
|
|
|
|
<input type=hidden name=next value="${req.query.next || ''}">
|
|
|
|
<div><input type=submit name=signInSubmitButton value=login></div>
|
|
|
|
</form>
|
|
|
|
</div>
|
2020-07-21 13:20:51 +00:00
|
|
|
</body></html>
|
|
|
|
`);
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
2022-04-01 21:31:24 +00:00
|
|
|
const logoutMiddleware = this._loginMiddleware.getLogoutMiddleware ?
|
|
|
|
this._loginMiddleware.getLogoutMiddleware() :
|
|
|
|
[];
|
|
|
|
this.app.get('/logout', ...logoutMiddleware, expressWrap(async (req, resp) => {
|
|
|
|
const scopedSession = this._sessions.getOrCreateSessionFromRequest(req);
|
|
|
|
const signedOutUrl = new URL(getOrgUrl(req) + 'signed-out');
|
|
|
|
const redirectUrl = await this._getLogoutRedirectUrl(req, signedOutUrl);
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
// Clear session so that user needs to log in again at the next request.
|
|
|
|
// SAML logout in theory uses userSession, so clear it AFTER we compute the URL.
|
|
|
|
// Express-session will save these changes.
|
2022-04-01 21:31:24 +00:00
|
|
|
const expressSession = (req as RequestWithLogin).session;
|
2020-07-21 13:20:51 +00:00
|
|
|
if (expressSession) { expressSession.users = []; expressSession.orgToUser = {}; }
|
2021-10-01 14:24:23 +00:00
|
|
|
await scopedSession.clearScopedSession(req);
|
(core) move more tests to grist-core
Summary:
* Tie build and run-time docker base images to a consistent version (buster)
* Extend the test login system activated by GRIST_TEST_LOGIN to ease porting tests that currently rely on cognito (many)
* Make org resets work in absence of billing endpoints
* When in-memory session caches are used, add missing invalidation steps
* Pass org information through sign-ups/sign-ins more carefully
* For CORS, explicitly trust GRIST_HOST origin when set
* Move some fixtures and tests to core, focussing on tests that cover existing failures or are in the set of tests run on deployments
* Retain regular `test` target to run the test suite directly, without docker
* Add a `test:smoke` target to run a single simple test without `GRIST_TEST_LOGIN` activated
* Add a `test:docker` target to run the tests against a grist-core docker image - since tests rely on certain fixture teams/docs, added `TEST_SUPPORT_API_KEY` and `TEST_ADD_SAMPLES` flags to ease porting
The tests ported were `nbrowser` tests: `ActionLog.ts` (the first test I tend to port to anything, out of habit), `Fork.ts` (exercises a lot of doc creation paths), `HomeIntro.ts` (a lot of DocMenu exercise), and `DuplicateDocument.ts` (covers a feature known to be failing prior to this diff, the CORS tweak resolves it).
Test Plan: Manually tested via `buildtools/build_core.sh`. In follow up, I want to add running the `test:docker` target in grist-core's workflows. In jenkins, only the smoke test is run. There'd be an argument for running all tests, but they include particularly slow tests, and are duplicates of tests already run (in different configuration admittedly), so I'd like to try first just using them in grist-core to gate updates to any packaged version of Grist (the docker image currently).
Reviewers: alexmojaki
Reviewed By: alexmojaki
Subscribers: alexmojaki
Differential Revision: https://phab.getgrist.com/D3176
2021-12-10 22:42:54 +00:00
|
|
|
// TODO: limit cache clearing to specific user.
|
|
|
|
this._sessions.clearCacheIfNeeded();
|
2020-07-21 13:20:51 +00:00
|
|
|
resp.redirect(redirectUrl);
|
|
|
|
}));
|
|
|
|
|
2022-04-01 21:31:24 +00:00
|
|
|
// Add a static "signed-out" page. This is where logout typically lands (e.g. after redirecting
|
|
|
|
// through SAML).
|
2020-07-21 13:20:51 +00:00
|
|
|
this.app.get('/signed-out', expressWrap((req, resp) =>
|
|
|
|
this._sendAppPage(req, resp, {path: 'error.html', status: 200, config: {errPage: 'signed-out'}})));
|
|
|
|
|
2021-08-17 15:22:30 +00:00
|
|
|
const comment = await this._loginMiddleware.addEndpoints(this.app);
|
2020-07-21 13:20:51 +00:00
|
|
|
this.info.push(['loginMiddlewareComment', comment]);
|
2021-10-01 14:24:23 +00:00
|
|
|
|
|
|
|
addDiscourseConnectEndpoints(this.app, {
|
|
|
|
userIdMiddleware: this._userIdMiddleware,
|
|
|
|
redirectToLogin: this._redirectToLoginWithoutExceptionsMiddleware,
|
|
|
|
});
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public async addTestingHooks(workerServers?: FlexServer[]) {
|
|
|
|
if (process.env.GRIST_TESTING_SOCKET) {
|
2021-08-17 15:22:30 +00:00
|
|
|
await startTestingHooks(process.env.GRIST_TESTING_SOCKET, this.port, this._comm, this,
|
2020-07-21 13:20:51 +00:00
|
|
|
workerServers || []);
|
|
|
|
this._hasTestingHooks = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns a Map from docId to number of connected clients for each doc.
|
|
|
|
public async getDocClientCounts(): Promise<Map<string, number>> {
|
|
|
|
return this._docManager ? this._docManager.getDocClientCounts() : new Map();
|
|
|
|
}
|
|
|
|
|
|
|
|
// allow the document manager to be specified externally, for convenience in testing.
|
|
|
|
public testSetDocManager(docManager: DocManager) {
|
|
|
|
this._docManager = docManager;
|
|
|
|
}
|
|
|
|
|
2020-09-29 22:16:29 +00:00
|
|
|
// Add document-related endpoints and related support.
|
|
|
|
public async addDoc() {
|
2023-04-06 15:10:29 +00:00
|
|
|
this._check('doc', 'start', 'tag', 'json', isSingleUserMode() ?
|
2023-06-06 17:08:50 +00:00
|
|
|
null : 'homedb', 'api-mw', 'map', 'telemetry');
|
2020-07-21 13:20:51 +00:00
|
|
|
// add handlers for cleanup, if we are in charge of the doc manager.
|
|
|
|
if (!this._docManager) { this.addCleanup(); }
|
|
|
|
await this.loadConfig();
|
|
|
|
this.addComm();
|
|
|
|
|
2023-07-10 16:49:56 +00:00
|
|
|
await this.create.configure?.();
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
if (!isSingleUserMode()) {
|
2022-06-03 14:54:49 +00:00
|
|
|
const externalStorage = appSettings.section('externalStorage');
|
|
|
|
const haveExternalStorage = Object.values(externalStorage.nested)
|
|
|
|
.some(storage => storage.flag('active').getAsBool());
|
|
|
|
const disabled = externalStorage.flag('disable')
|
|
|
|
.read({ envVar: 'GRIST_DISABLE_S3' }).getAsBool();
|
|
|
|
if (disabled || !haveExternalStorage) {
|
|
|
|
this._disableExternalStorage = true;
|
|
|
|
externalStorage.flag('active').set(false);
|
2020-10-30 16:53:23 +00:00
|
|
|
}
|
2023-07-13 06:44:46 +00:00
|
|
|
await this.create.checkBackend?.();
|
2020-07-21 13:20:51 +00:00
|
|
|
const workers = this._docWorkerMap;
|
|
|
|
const docWorkerId = await this._addSelfAsWorker(workers);
|
|
|
|
|
2022-06-03 14:54:49 +00:00
|
|
|
const storageManager = new HostedStorageManager(this.docsRoot, docWorkerId, this._disableExternalStorage, workers,
|
2021-08-17 15:22:30 +00:00
|
|
|
this._dbManager, this.create);
|
2020-07-21 13:20:51 +00:00
|
|
|
this._storageManager = storageManager;
|
|
|
|
} else {
|
|
|
|
const samples = getAppPathTo(this.appRoot, 'public_samples');
|
2021-08-17 15:22:30 +00:00
|
|
|
const storageManager = new DocStorageManager(this.docsRoot, samples, this._comm, this);
|
2020-07-21 13:20:51 +00:00
|
|
|
this._storageManager = storageManager;
|
|
|
|
}
|
|
|
|
|
|
|
|
const pluginManager = await this._addPluginManager();
|
|
|
|
this._docManager = this._docManager || new DocManager(this._storageManager, pluginManager,
|
2021-08-17 15:22:30 +00:00
|
|
|
this._dbManager, this);
|
2020-07-21 13:20:51 +00:00
|
|
|
const docManager = this._docManager;
|
|
|
|
|
|
|
|
shutdown.addCleanupHandler(null, this._shutdown.bind(this), 25000, 'FlexServer._shutdown');
|
|
|
|
|
2021-07-01 15:15:43 +00:00
|
|
|
if (!isSingleUserMode()) {
|
2021-08-17 15:22:30 +00:00
|
|
|
this._comm.registerMethods({
|
2020-07-21 13:20:51 +00:00
|
|
|
openDoc: docManager.openDoc.bind(docManager),
|
|
|
|
});
|
|
|
|
this._serveDocPage();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Attach docWorker endpoints and Comm methods.
|
2022-07-19 15:39:49 +00:00
|
|
|
const docWorker = new DocWorker(this._dbManager, {comm: this._comm, gristServer: this});
|
2020-07-21 13:20:51 +00:00
|
|
|
this._docWorker = docWorker;
|
|
|
|
|
|
|
|
// Register the websocket comm functions associated with the docworker.
|
|
|
|
docWorker.registerCommCore();
|
|
|
|
docWorker.registerCommPlugin();
|
|
|
|
|
|
|
|
// Doc-specific endpoints require authorization; collect the relevant middleware in one list.
|
|
|
|
const docAccessMiddleware = [
|
|
|
|
this._userIdMiddleware,
|
|
|
|
this._docPermissionsMiddleware,
|
|
|
|
this.tagChecker.requireTag
|
|
|
|
];
|
|
|
|
|
2021-05-23 17:43:11 +00:00
|
|
|
this._addSupportPaths(docAccessMiddleware);
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
if (!isSingleUserMode()) {
|
2021-08-17 15:22:30 +00:00
|
|
|
addDocApiRoutes(this.app, docWorker, this._docWorkerMap, docManager, this._dbManager, this);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-03 14:54:49 +00:00
|
|
|
public disableExternalStorage() {
|
2020-07-21 13:20:51 +00:00
|
|
|
if (this.deps.has('doc')) {
|
2022-06-03 14:54:49 +00:00
|
|
|
throw new Error('disableExternalStorage called too late');
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
2022-06-03 14:54:49 +00:00
|
|
|
this._disableExternalStorage = true;
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
2022-01-07 18:11:52 +00:00
|
|
|
public addAccountPage() {
|
|
|
|
const middleware = [
|
|
|
|
this._redirectToHostMiddleware,
|
|
|
|
this._userIdMiddleware,
|
|
|
|
this._redirectToLoginWithoutExceptionsMiddleware
|
|
|
|
];
|
|
|
|
|
|
|
|
this.app.get('/account', ...middleware, expressWrap(async (req, resp) => {
|
2023-07-04 21:21:34 +00:00
|
|
|
return this._sendAppPage(req, resp, {path: 'app.html', status: 200, config: {}});
|
2022-01-07 18:11:52 +00:00
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
public addBillingPages() {
|
|
|
|
const middleware = [
|
|
|
|
this._redirectToHostMiddleware,
|
|
|
|
this._userIdMiddleware,
|
|
|
|
this._redirectToLoginWithoutExceptionsMiddleware
|
|
|
|
];
|
|
|
|
|
2022-08-22 19:46:25 +00:00
|
|
|
this._getBilling();
|
|
|
|
this._billing.addPages(this.app, middleware);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Add billing webhooks. Strip signatures sign the raw body of the message, so
|
|
|
|
* we need to get these webhooks in before the bodyParser is added to parse json.
|
|
|
|
*/
|
|
|
|
public addEarlyWebhooks() {
|
|
|
|
if (this._check('webhooks', 'homedb')) { return; }
|
|
|
|
if (this.deps.has('json')) {
|
|
|
|
throw new Error('addEarlyWebhooks called too late');
|
|
|
|
}
|
|
|
|
this._getBilling();
|
|
|
|
this._billing.addWebhooks(this.app);
|
|
|
|
}
|
|
|
|
|
|
|
|
public addWelcomePaths() {
|
|
|
|
const middleware = [
|
|
|
|
this._redirectToHostMiddleware,
|
|
|
|
this._userIdMiddleware,
|
|
|
|
this._redirectToLoginWithoutExceptionsMiddleware,
|
|
|
|
];
|
|
|
|
|
2022-02-24 05:50:26 +00:00
|
|
|
// These are some special-purpose welcome pages, with no middleware.
|
|
|
|
this.app.get(/\/welcome\/(signup|verify|teams|select-account)/, expressWrap(async (req, resp, next) => {
|
2022-03-11 20:35:29 +00:00
|
|
|
return this._sendAppPage(req, resp, {path: 'app.html', status: 200, config: {}, googleTagManager: 'anon'});
|
2021-06-25 14:00:01 +00:00
|
|
|
}));
|
|
|
|
|
2023-03-21 13:32:34 +00:00
|
|
|
/**
|
|
|
|
* A nuanced redirecting endpoint. For example, on docs.getgrist.com it does:
|
|
|
|
* 1) If logged in and no team site -> https://docs.getgrist.com/
|
|
|
|
* 2) If logged in and has team sites -> https://docs.getgrist.com/welcome/teams
|
|
|
|
* 3) If logged out but has a cookie -> /login, then 1 or 2
|
|
|
|
* 4) If entirely unknown -> /signup
|
|
|
|
*/
|
|
|
|
this.app.get('/welcome/start', [
|
|
|
|
this._redirectToHostMiddleware,
|
|
|
|
this._userIdMiddleware,
|
|
|
|
], expressWrap(async (req, resp, next) => {
|
|
|
|
if (isAnonymousUser(req)) {
|
|
|
|
return this._redirectToLoginOrSignup({
|
|
|
|
nextUrl: new URL(getOrgUrl(req, '/welcome/start')),
|
|
|
|
}, req, resp);
|
|
|
|
}
|
2023-05-01 18:24:23 +00:00
|
|
|
|
|
|
|
await this._redirectToHomeOrWelcomePage(req as RequestWithLogin, resp);
|
|
|
|
}));
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Like /welcome/start, but doesn't redirect anonymous users to sign in.
|
|
|
|
*
|
|
|
|
* Used by the client when the last site the user visited is unknown, and
|
|
|
|
* a suitable site is needed for the home page.
|
|
|
|
*
|
|
|
|
* For example, on templates.getgrist.com it does:
|
|
|
|
* 1) If logged in and no team site -> https://docs.getgrist.com/
|
|
|
|
* 2) If logged in and has team sites -> https://docs.getgrist.com/welcome/teams
|
|
|
|
* 3) If logged out -> https://docs.getgrist.com/
|
|
|
|
*/
|
|
|
|
this.app.get('/welcome/home', [
|
|
|
|
this._redirectToHostMiddleware,
|
|
|
|
this._userIdMiddleware,
|
|
|
|
], expressWrap(async (req, resp) => {
|
|
|
|
const mreq = req as RequestWithLogin;
|
|
|
|
if (isAnonymousUser(req)) {
|
|
|
|
return resp.redirect(this.getMergedOrgUrl(mreq));
|
|
|
|
}
|
|
|
|
|
|
|
|
await this._redirectToHomeOrWelcomePage(mreq, resp, {redirectToMergedOrg: true});
|
2023-03-21 13:32:34 +00:00
|
|
|
}));
|
|
|
|
|
2022-02-24 05:50:26 +00:00
|
|
|
this.app.post('/welcome/info', ...middleware, expressWrap(async (req, resp, next) => {
|
2020-07-21 13:20:51 +00:00
|
|
|
const userId = getUserId(req);
|
2022-02-24 05:50:26 +00:00
|
|
|
const user = getUser(req);
|
|
|
|
const row = {...req.body, UserID: userId, Name: user.name, Email: user.loginEmail};
|
|
|
|
this._recordNewUserInfo(row)
|
|
|
|
.catch(e => {
|
|
|
|
// If we failed to record, at least log the data, so we could potentially recover it.
|
|
|
|
log.rawWarn(`Failed to record new user info: ${e.message}`, {newUserQuestions: row});
|
|
|
|
});
|
2020-07-21 13:20:51 +00:00
|
|
|
|
2022-02-24 05:50:26 +00:00
|
|
|
resp.status(200).send();
|
2022-08-03 10:48:01 +00:00
|
|
|
}), jsonErrorHandler); // Add a final error handler that reports errors as JSON.
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public finalize() {
|
|
|
|
this.addApiErrorHandlers();
|
|
|
|
|
|
|
|
// add a final non-found handler for other content.
|
|
|
|
this.app.use("/", expressWrap((req, resp) => {
|
|
|
|
if (this._sendAppPage) {
|
|
|
|
return this._sendAppPage(req, resp, {path: 'error.html', status: 404, config: {errPage: 'not-found'}});
|
|
|
|
} else {
|
|
|
|
return resp.status(404).json({error: 'not found'});
|
|
|
|
}
|
|
|
|
}));
|
|
|
|
|
|
|
|
// add a final error handler
|
|
|
|
this.app.use(async (err: any, req: express.Request, resp: express.Response, next: express.NextFunction) => {
|
|
|
|
// Delegate to default error handler when headers have already been sent, as express advises
|
|
|
|
// at https://expressjs.com/en/guide/error-handling.html#the-default-error-handler.
|
|
|
|
// Also delegates if no _sendAppPage method has been configured.
|
|
|
|
if (resp.headersSent || !this._sendAppPage) { return next(err); }
|
|
|
|
try {
|
|
|
|
const errPage = (
|
|
|
|
err.status === 403 ? 'access-denied' :
|
|
|
|
err.status === 404 ? 'not-found' :
|
|
|
|
'other-error'
|
|
|
|
);
|
|
|
|
const config = {errPage, errMessage: err.message || err};
|
|
|
|
await this._sendAppPage(req, resp, {path: 'error.html', status: err.status || 400, config});
|
2021-05-23 17:43:11 +00:00
|
|
|
} catch (error) {
|
|
|
|
return next(error);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
public summary() {
|
|
|
|
for (const [label, value] of this.info) {
|
|
|
|
log.info("== %s: %s", label, value);
|
|
|
|
}
|
2022-06-03 14:54:49 +00:00
|
|
|
for (const item of appSettings.describeAll()) {
|
|
|
|
const txt =
|
|
|
|
((item.value !== undefined) ? String(item.value) : '-') +
|
|
|
|
(item.foundInEnvVar ? ` [${item.foundInEnvVar}]` : '') +
|
|
|
|
(item.usedDefault ? ' [default]' : '') +
|
|
|
|
((item.wouldFindInEnvVar && !item.foundInEnvVar) ? ` [${item.wouldFindInEnvVar}]` : '');
|
|
|
|
log.info("== %s: %s", item.name, txt);
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
2023-05-23 16:51:58 +00:00
|
|
|
public checkOptionCombinations() {
|
|
|
|
// Check for some bad combinations we should warn about.
|
|
|
|
const allowedWebhookDomains = appSettings.section('integrations').flag('allowedWebhookDomains').readString({
|
|
|
|
envVar: 'ALLOWED_WEBHOOK_DOMAINS',
|
|
|
|
});
|
|
|
|
const proxy = appSettings.section('integrations').flag('proxy').readString({
|
|
|
|
envVar: 'GRIST_HTTPS_PROXY',
|
|
|
|
});
|
|
|
|
// If all webhook targets are accepted, and no proxy is defined, issue
|
|
|
|
// a warning. This warning can be removed by explicitly setting the proxy
|
|
|
|
// to the empty string.
|
|
|
|
if (allowedWebhookDomains === '*' && proxy === undefined) {
|
|
|
|
log.warn("Setting an ALLOWED_WEBHOOK_DOMAINS wildcard without a GRIST_HTTPS_PROXY exposes your internal network");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
public async start() {
|
|
|
|
if (this._check('start')) { return; }
|
|
|
|
|
|
|
|
const servers = this._createServers();
|
|
|
|
this.server = servers.server;
|
|
|
|
this.httpsServer = servers.httpsServer;
|
|
|
|
await this._startServers(this.server, this.httpsServer, this.name, this.port, true);
|
|
|
|
}
|
|
|
|
|
|
|
|
public addNotifier() {
|
|
|
|
if (this._check('notifier', 'start', 'homedb')) { return; }
|
|
|
|
// TODO: make Notifier aware of base domains, rather than sending emails with default
|
|
|
|
// base domain.
|
|
|
|
// Most notifications are ultimately triggered by requests with a base domain in them,
|
|
|
|
// and all that is needed is a refactor to pass that info along. But there is also the
|
|
|
|
// case of notification(s) from stripe. May need to associate a preferred base domain
|
|
|
|
// with org/user and persist that?
|
2022-02-24 00:27:16 +00:00
|
|
|
this._notifier = this.create.Notifier(this._dbManager, this);
|
2021-03-18 22:40:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public getGristConfig(): GristLoadConfig {
|
2023-06-06 17:08:50 +00:00
|
|
|
return makeGristConfig({
|
|
|
|
homeUrl: this.getDefaultHomeUrl(),
|
|
|
|
extra: {},
|
|
|
|
baseDomain: this._defaultBaseDomain,
|
|
|
|
});
|
2021-03-18 22:40:02 +00:00
|
|
|
}
|
|
|
|
|
2021-06-17 20:48:46 +00:00
|
|
|
/**
|
|
|
|
* Get a url for a team site.
|
|
|
|
*/
|
|
|
|
public async getOrgUrl(orgKey: string|number): Promise<string> {
|
2022-06-08 17:54:00 +00:00
|
|
|
const org = await this.getOrg(orgKey);
|
|
|
|
return this.getResourceUrl(org);
|
|
|
|
}
|
|
|
|
|
|
|
|
public async getOrg(orgKey: string|number) {
|
2021-08-17 15:22:30 +00:00
|
|
|
if (!this._dbManager) { throw new Error('database missing'); }
|
|
|
|
const org = await this._dbManager.getOrg({
|
|
|
|
userId: this._dbManager.getPreviewerUserId(),
|
2021-06-17 20:48:46 +00:00
|
|
|
showAll: true
|
|
|
|
}, orgKey);
|
2022-06-08 17:54:00 +00:00
|
|
|
return this._dbManager.unwrapQueryResult(org);
|
2021-06-17 20:48:46 +00:00
|
|
|
}
|
|
|
|
|
2021-03-18 22:40:02 +00:00
|
|
|
/**
|
|
|
|
* Get a url for an organization, workspace, or document.
|
|
|
|
*/
|
2022-07-19 15:39:49 +00:00
|
|
|
public async getResourceUrl(resource: Organization|Workspace|Document,
|
|
|
|
purpose?: 'api'|'html'): Promise<string> {
|
2021-08-17 15:22:30 +00:00
|
|
|
if (!this._dbManager) { throw new Error('database missing'); }
|
2021-03-18 22:40:02 +00:00
|
|
|
const gristConfig = this.getGristConfig();
|
|
|
|
const state: IGristUrlState = {};
|
|
|
|
let org: Organization;
|
|
|
|
if (resource instanceof Organization) {
|
|
|
|
org = resource;
|
|
|
|
} else if (resource instanceof Workspace) {
|
|
|
|
org = resource.org;
|
|
|
|
state.ws = resource.id;
|
|
|
|
} else {
|
|
|
|
org = resource.workspace.org;
|
2021-05-27 20:08:18 +00:00
|
|
|
state.doc = resource.urlId || resource.id;
|
2021-03-18 22:40:02 +00:00
|
|
|
state.slug = getSlugIfNeeded(resource);
|
|
|
|
}
|
2021-08-17 15:22:30 +00:00
|
|
|
state.org = this._dbManager.normalizeOrgDomain(org.id, org.domain, org.ownerId);
|
2021-03-18 22:40:02 +00:00
|
|
|
if (!gristConfig.homeUrl) { throw new Error('Computing a resource URL requires a home URL'); }
|
2022-07-19 15:39:49 +00:00
|
|
|
return encodeUrl(gristConfig, state, new URL(gristConfig.homeUrl),
|
|
|
|
{ api: purpose === 'api' });
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public addUsage() {
|
|
|
|
if (this._check('usage', 'start', 'homedb')) { return; }
|
2021-08-17 15:22:30 +00:00
|
|
|
this.usage = new Usage(this._dbManager);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public async addHousekeeper() {
|
2021-01-05 14:35:14 +00:00
|
|
|
if (this._check('housekeeper', 'start', 'homedb', 'map', 'json', 'api-mw')) { return; }
|
2020-07-21 13:20:51 +00:00
|
|
|
const store = this._docWorkerMap;
|
2021-08-17 15:22:30 +00:00
|
|
|
this.housekeeper = new Housekeeper(this._dbManager, this, this._internalPermitStore, store);
|
2021-01-05 14:35:14 +00:00
|
|
|
this.housekeeper.addEndpoints(this.app);
|
2020-07-21 13:20:51 +00:00
|
|
|
await this.housekeeper.start();
|
|
|
|
}
|
|
|
|
|
|
|
|
public async startCopy(name2: string, port2: number) {
|
|
|
|
const servers = this._createServers();
|
|
|
|
await this._startServers(servers.server, servers.httpsServer, name2, port2, true);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Close all documents currently held open.
|
|
|
|
*/
|
|
|
|
public async closeDocs(): Promise<void> {
|
|
|
|
if (this._docManager) {
|
|
|
|
return this._docManager.shutdownAll();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-21 08:46:03 +00:00
|
|
|
public addGoogleAuthEndpoint() {
|
|
|
|
if (this._check('google-auth')) { return; }
|
2021-07-21 16:38:57 +00:00
|
|
|
const messagePage = makeMessagePage(getAppPathTo(this.appRoot, 'static'));
|
2021-07-21 08:46:03 +00:00
|
|
|
addGoogleAuthEndpoint(this.app, messagePage);
|
|
|
|
}
|
|
|
|
|
2023-07-04 21:21:34 +00:00
|
|
|
public addInstallEndpoints() {
|
|
|
|
if (this._check('install')) { return; }
|
|
|
|
|
|
|
|
const isManager = expressWrap(
|
|
|
|
(req: express.Request, _res: express.Response, next: express.NextFunction) => {
|
|
|
|
if (!isDefaultUser(req)) { throw new ApiError('Access denied', 403); }
|
|
|
|
|
|
|
|
next();
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
this.app.get('/api/install/prefs', expressWrap(async (_req, resp) => {
|
|
|
|
const activation = await this._activations.current();
|
|
|
|
|
|
|
|
return sendOkReply(null, resp, {
|
|
|
|
telemetry: await getTelemetryPrefs(this._dbManager, activation),
|
|
|
|
});
|
|
|
|
}));
|
|
|
|
|
|
|
|
this.app.patch('/api/install/prefs', isManager, expressWrap(async (req, resp) => {
|
|
|
|
const props = {prefs: req.body};
|
|
|
|
const activation = await this._activations.current();
|
|
|
|
activation.checkProperties(props);
|
|
|
|
activation.updateFromProperties(props);
|
|
|
|
await activation.save();
|
|
|
|
|
|
|
|
if ((props as Partial<InstallProperties>).prefs?.telemetry) {
|
|
|
|
// Make sure the Telemetry singleton picks up the changes to telemetry preferences.
|
|
|
|
// TODO: if there are multiple home server instances, notify them all of changes to
|
|
|
|
// preferences (via Redis Pub/Sub).
|
|
|
|
await this._telemetry.fetchTelemetryPrefs();
|
|
|
|
}
|
|
|
|
|
|
|
|
return resp.status(200).send();
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
(core) make Grist easier to run with a single server
Summary:
This makes many small changes so that Grist is less fussy to run as a single instance behind a reverse proxy. Some users had difficulty with the self-connections Grist would make, due to internal network setup, and since these are unnecessary in any case in this scenario, they are now optimized away. Likewise some users had difficulties related to doc worker urls, which are now also optimized away. With these changes, users should be able to get a lot further on first try, at least far enough to open and edit documents.
The `GRIST_SINGLE_ORG` setting was proving a bit confusing, since it appeared to only work when set to `docs`. This diff
adds a check for whether the specified org exists, and if not, it creates it. This still depends on having a user email to make as the owner of the team, so there could be remaining difficulties there.
Test Plan: tested manually with nginx
Reviewers: jarek
Reviewed By: jarek
Differential Revision: https://phab.getgrist.com/D3299
2022-03-02 19:07:26 +00:00
|
|
|
// Get the HTML template sent for document pages.
|
|
|
|
public async getDocTemplate(): Promise<DocTemplate> {
|
|
|
|
const page = await fse.readFile(path.join(getAppPathTo(this.appRoot, 'static'),
|
|
|
|
'app.html'), 'utf8');
|
|
|
|
return {
|
|
|
|
page,
|
|
|
|
tag: this.tag
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
public getTag(): string {
|
|
|
|
return this.tag;
|
|
|
|
}
|
|
|
|
|
2022-03-07 14:27:43 +00:00
|
|
|
/**
|
|
|
|
* Make sure external storage of all docs is up to date.
|
|
|
|
*/
|
|
|
|
public async testFlushDocs() {
|
|
|
|
const assignments = await this._docWorkerMap.getAssignments(this.worker.id);
|
|
|
|
for (const assignment of assignments) {
|
|
|
|
await this._storageManager.flushDoc(assignment);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-21 13:20:51 +00:00
|
|
|
// Adds endpoints that support imports and exports.
|
2021-05-23 17:43:11 +00:00
|
|
|
private _addSupportPaths(docAccessMiddleware: express.RequestHandler[]) {
|
2020-07-21 13:20:51 +00:00
|
|
|
if (!this._docWorker) { throw new Error("need DocWorker"); }
|
|
|
|
|
|
|
|
const basicMiddleware = [this._userIdMiddleware, this.tagChecker.requireTag];
|
|
|
|
|
|
|
|
// Add the handling for the /upload route. Most uploads are meant for a DocWorker: they are put
|
|
|
|
// in temporary files, and the DocWorker needs to be on the same machine to have access to them.
|
|
|
|
// This doesn't check for doc access permissions because the request isn't tied to a document.
|
2020-10-08 13:28:39 +00:00
|
|
|
addUploadRoute(this, this.app, this._trustOriginsMiddleware, ...basicMiddleware);
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
this.app.get('/attachment', ...docAccessMiddleware,
|
|
|
|
expressWrap(async (req, res) => this._docWorker.getAttachment(req, res)));
|
|
|
|
}
|
|
|
|
|
|
|
|
private _check(part: string, ...precedents: Array<string|null>) {
|
|
|
|
if (this.deps.has(part)) { return true; }
|
|
|
|
for (const precedent of precedents) {
|
|
|
|
if (!precedent) { continue; }
|
|
|
|
if (precedent[0] === '!') {
|
|
|
|
const antecedent = precedent.slice(1);
|
|
|
|
if (this._has(antecedent)) {
|
|
|
|
throw new Error(`${part} is needed before ${antecedent}`);
|
|
|
|
}
|
|
|
|
} else if (!this._has(precedent)) {
|
|
|
|
throw new Error(`${precedent} is needed before ${part}`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
this.deps.add(part);
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
private _has(part: string) {
|
|
|
|
return this.deps.has(part);
|
|
|
|
}
|
|
|
|
|
|
|
|
private async _addSelfAsWorker(workers: IDocWorkerMap): Promise<string> {
|
|
|
|
try {
|
|
|
|
this._healthy = true;
|
|
|
|
// Check if this is the first time calling this method. In production,
|
|
|
|
// it always will be. In testing, we may disconnect and reconnect the
|
|
|
|
// worker. We only need to determine docWorkerId and this.worker once.
|
|
|
|
if (!this.worker) {
|
|
|
|
|
|
|
|
if (process.env.GRIST_ROUTER_URL) {
|
|
|
|
// register ourselves with the load balancer first.
|
|
|
|
const w = await this.createWorkerUrl();
|
|
|
|
const url = `${w.url}/v/${this.tag}/`;
|
|
|
|
// TODO: we could compute a distinct internal url here.
|
|
|
|
this.worker = {
|
|
|
|
id: w.host,
|
|
|
|
publicUrl: url,
|
|
|
|
internalUrl: url,
|
|
|
|
};
|
|
|
|
} else {
|
|
|
|
const url = (process.env.APP_DOC_URL || this.getOwnUrl()) + `/v/${this.tag}/`;
|
|
|
|
this.worker = {
|
|
|
|
// The worker id should be unique to this worker.
|
|
|
|
id: process.env.GRIST_DOC_WORKER_ID || `testDocWorkerId_${this.port}`,
|
|
|
|
publicUrl: url,
|
|
|
|
internalUrl: process.env.APP_DOC_INTERNAL_URL || url,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
this.info.push(['docWorkerId', this.worker.id]);
|
|
|
|
|
(core) support GRIST_WORKER_GROUP to place worker into an exclusive group
Summary:
In an emergency, we may want to serve certain documents with "old" workers as we fix problems. This diff adds some support for that.
* Creates duplicate task definitions and services for staging and production doc workers (called grist-docs-staging2 and grist-docs-prod2), pulling from distinct docker tags (staging2 and prod2). The services are set to have zero workers until we need them.
* These new workers are started with a new env variable `GRIST_WORKER_GROUP` set to `secondary`.
* The `GRIST_WORKER_GROUP` variable, if set, makes the worker available to documents in the named group, and only that group.
* An unauthenticated `/assign` endpoint is added to documents which, when POSTed to, checks that the doc is served by a worker in the desired group for that doc (as set manually in redis), and if not frees the doc up for reassignment. This makes it possible to move individual docs between workers without redeployments.
The bash scripts added are a record of how the task definitions + services were created. The services could just have been copied manually, but the task definitions will need to be updated whenever the definitions for the main doc workers are updated, so it is worth scripting that.
For example, if a certain document were to fail on a new deployment of Grist, but rolling back the full deployment wasn't practical:
* Set prod2 tag in docker to desired codebase for that document
* Set desired_count for grist-docs-prod2 service to non-zero
* Set doc-<docid>-group for that doc in redis to secondary
* Hit /api/docs/<docid>/assign to move the doc to grist-docs-prod2
(If the document needs to be reverted to a previous snapshot, that currently would need doing manually - could be made simpler, but not in scope of this diff).
Test Plan: added tests
Reviewers: dsagal
Reviewed By: dsagal
Differential Revision: https://phab.getgrist.com/D2649
2020-11-02 19:24:46 +00:00
|
|
|
if (process.env.GRIST_WORKER_GROUP) {
|
|
|
|
this.worker.group = process.env.GRIST_WORKER_GROUP;
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
} else {
|
|
|
|
if (process.env.GRIST_ROUTER_URL) {
|
|
|
|
await this.createWorkerUrl();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
await workers.addWorker(this.worker);
|
|
|
|
await workers.setWorkerAvailability(this.worker.id, true);
|
|
|
|
} catch (err) {
|
|
|
|
this._healthy = false;
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
return this.worker.id;
|
|
|
|
}
|
|
|
|
|
|
|
|
private async _removeSelfAsWorker(workers: IDocWorkerMap, docWorkerId: string) {
|
|
|
|
this._healthy = false;
|
|
|
|
await workers.removeWorker(docWorkerId);
|
|
|
|
if (process.env.GRIST_ROUTER_URL) {
|
|
|
|
await axios.get(process.env.GRIST_ROUTER_URL,
|
|
|
|
{params: {act: 'remove', port: this.getOwnPort()}});
|
|
|
|
log.info(`DocWorker unregistered itself via ${process.env.GRIST_ROUTER_URL}`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Called when server is shutting down. Save any state that needs saving, and
|
|
|
|
// disentangle ourselves from outside world.
|
|
|
|
private async _shutdown(): Promise<void> {
|
|
|
|
if (!this.worker) { return; }
|
|
|
|
if (!this._storageManager) { return; }
|
|
|
|
if (!this._docWorkerMap) { return; } // but this should never happen.
|
|
|
|
|
|
|
|
const workers = this._docWorkerMap;
|
|
|
|
|
|
|
|
// Pick up the pace on saving documents.
|
|
|
|
this._storageManager.prepareToCloseStorage();
|
|
|
|
|
|
|
|
// We urgently want to disable any new assignments.
|
|
|
|
await workers.setWorkerAvailability(this.worker.id, false);
|
|
|
|
|
|
|
|
// Enumerate the documents we are responsible for.
|
|
|
|
let assignments = await workers.getAssignments(this.worker.id);
|
|
|
|
let retries: number = 0;
|
|
|
|
while (assignments.length > 0 && retries < 3) {
|
|
|
|
await Promise.all(assignments.map(async assignment => {
|
|
|
|
log.info("FlexServer shutdown assignment", assignment);
|
|
|
|
try {
|
|
|
|
// Start sending the doc to S3 if needed.
|
|
|
|
const flushOp = this._storageManager.closeDocument(assignment);
|
|
|
|
|
|
|
|
// Get access to the clients of this document. This has the side
|
|
|
|
// effect of waiting for the ActiveDoc to finish initialization.
|
|
|
|
// This could include loading it from S3, an operation we could
|
|
|
|
// potentially abort as an optimization.
|
|
|
|
// TODO: abort any s3 loading as an optimization.
|
|
|
|
const docPromise = this._docManager.getActiveDoc(assignment);
|
|
|
|
const doc = docPromise && await docPromise;
|
|
|
|
|
|
|
|
await flushOp;
|
|
|
|
// At this instant, S3 and local document should be the same.
|
|
|
|
|
|
|
|
// We'd now like to make sure (synchronously) that:
|
|
|
|
// - we never output anything new to S3 about this document.
|
|
|
|
// - we never output anything new to user about this document.
|
|
|
|
// There could be asynchronous operations going on related to
|
|
|
|
// these documents, but if we can make sure that their effects
|
|
|
|
// do not reach the outside world then we can ignore them.
|
|
|
|
if (doc) {
|
|
|
|
doc.docClients.interruptAllClients();
|
|
|
|
doc.setMuted();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Release this document for other workers to pick up.
|
|
|
|
// There is a small window of time here in which a client
|
|
|
|
// could reconnect to us. The muted ActiveDoc will result
|
|
|
|
// in them being dropped again.
|
|
|
|
await workers.releaseAssignment(this.worker.id, assignment);
|
|
|
|
} catch (err) {
|
|
|
|
log.info("problem dealing with assignment", assignment, err);
|
|
|
|
}
|
|
|
|
}));
|
|
|
|
// Check for any assignments that slipped through at the last minute.
|
|
|
|
assignments = await workers.getAssignments(this.worker.id);
|
|
|
|
retries++;
|
|
|
|
}
|
|
|
|
if (assignments.length > 0) {
|
|
|
|
log.error("FlexServer shutdown failed to release assignments:", assignments);
|
|
|
|
}
|
|
|
|
|
|
|
|
await this._removeSelfAsWorker(workers, this.worker.id);
|
|
|
|
try {
|
|
|
|
await this._docManager.shutdownAll();
|
|
|
|
} catch (err) {
|
|
|
|
log.error("FlexServer shutdown problem", err);
|
|
|
|
}
|
2021-08-17 15:22:30 +00:00
|
|
|
if (this._comm) {
|
|
|
|
this._comm.destroyAllClients();
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
log.info("FlexServer shutdown is complete");
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Middleware that redirects a request with a userId but without an org to an org-specific URL,
|
|
|
|
* after looking up the first org for this userId in DB.
|
|
|
|
*/
|
|
|
|
private async _redirectToOrg(req: express.Request, resp: express.Response, next: express.NextFunction) {
|
|
|
|
const mreq = req as RequestWithLogin;
|
2021-08-17 15:22:30 +00:00
|
|
|
if (mreq.org || !mreq.userId) { return next(); }
|
|
|
|
|
|
|
|
// Redirect anonymous users to the merged org.
|
|
|
|
if (!mreq.userIsAuthorized) {
|
2022-02-11 06:03:30 +00:00
|
|
|
const redirectUrl = this.getMergedOrgUrl(mreq);
|
2021-08-17 15:22:30 +00:00
|
|
|
log.debug(`Redirecting anonymous user to: ${redirectUrl}`);
|
|
|
|
return resp.redirect(redirectUrl);
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
|
|
|
|
// We have a userId, but the request is for an unknown org. Redirect to an org that's
|
|
|
|
// available to the user. This matters in dev, and in prod when visiting a generic URL, which
|
|
|
|
// will here redirect to e.g. the user's personal org.
|
2021-08-17 15:22:30 +00:00
|
|
|
const result = await this._dbManager.getMergedOrgs(mreq.userId, mreq.userId, null);
|
2020-07-21 13:20:51 +00:00
|
|
|
const orgs = (result.status === 200) ? result.data : null;
|
|
|
|
const subdomain = orgs && orgs.length > 0 ? orgs[0].domain : null;
|
|
|
|
const redirectUrl = subdomain && this._getOrgRedirectUrl(mreq, subdomain);
|
|
|
|
if (redirectUrl) {
|
|
|
|
log.debug(`Redirecting userId ${mreq.userId} to: ${redirectUrl}`);
|
|
|
|
return resp.redirect(redirectUrl);
|
|
|
|
}
|
|
|
|
next();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Given a Request and a desired subdomain, returns a URL for a similar request that specifies that
|
|
|
|
* subdomain either in the hostname or in the path. Optionally passing pathname overrides url's
|
|
|
|
* path.
|
|
|
|
*/
|
|
|
|
private _getOrgRedirectUrl(req: RequestWithLogin, subdomain: string, pathname: string = req.originalUrl): string {
|
2022-04-05 15:48:15 +00:00
|
|
|
const config = this.getGristConfig();
|
|
|
|
const {hostname, orgInPath} = getOrgUrlInfo(subdomain, req.get('host')!, config);
|
2022-04-27 16:07:08 +00:00
|
|
|
const redirectUrl = new URL(pathname, getOriginUrl(req));
|
2020-07-21 13:20:51 +00:00
|
|
|
if (hostname) {
|
|
|
|
redirectUrl.hostname = hostname;
|
|
|
|
}
|
|
|
|
if (orgInPath) {
|
|
|
|
redirectUrl.pathname = `/o/${orgInPath}` + redirectUrl.pathname;
|
|
|
|
}
|
|
|
|
return redirectUrl.href;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Create and initialize the plugin manager
|
|
|
|
private async _addPluginManager() {
|
|
|
|
if (this._pluginManager) { return this._pluginManager; }
|
|
|
|
// Only used as {userRoot}/plugins as a place for plugins in addition to {appRoot}/plugins
|
|
|
|
const userRoot = path.resolve(process.env.GRIST_USER_ROOT || getAppPathTo(this.appRoot, '.grist'));
|
|
|
|
this.info.push(['userRoot', userRoot]);
|
|
|
|
|
|
|
|
const pluginManager = new PluginManager(this.appRoot, userRoot);
|
|
|
|
// `initialize()` is asynchronous and reads plugins manifests; if PluginManager is used before it
|
|
|
|
// finishes, it will act as if there are no plugins.
|
|
|
|
// ^ I think this comment was here to justify calling initialize without waiting for
|
|
|
|
// the result. I'm just going to wait, for determinism.
|
|
|
|
await pluginManager.initialize();
|
|
|
|
this._pluginManager = pluginManager;
|
|
|
|
return pluginManager;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Serve the static app.html proxied for a document.
|
|
|
|
private _serveDocPage() {
|
|
|
|
// Serve the static app.html file.
|
|
|
|
// TODO: We should be the ones to fill in the base href here to ensure that the browser fetches
|
|
|
|
// the correct version of static files for this app.html.
|
|
|
|
this.app.get('/:docId/app.html', this._userIdMiddleware, expressWrap(async (req, res) => {
|
(core) make Grist easier to run with a single server
Summary:
This makes many small changes so that Grist is less fussy to run as a single instance behind a reverse proxy. Some users had difficulty with the self-connections Grist would make, due to internal network setup, and since these are unnecessary in any case in this scenario, they are now optimized away. Likewise some users had difficulties related to doc worker urls, which are now also optimized away. With these changes, users should be able to get a lot further on first try, at least far enough to open and edit documents.
The `GRIST_SINGLE_ORG` setting was proving a bit confusing, since it appeared to only work when set to `docs`. This diff
adds a check for whether the specified org exists, and if not, it creates it. This still depends on having a user email to make as the owner of the team, so there could be remaining difficulties there.
Test Plan: tested manually with nginx
Reviewers: jarek
Reviewed By: jarek
Differential Revision: https://phab.getgrist.com/D3299
2022-03-02 19:07:26 +00:00
|
|
|
res.json(await this.getDocTemplate());
|
2020-07-21 13:20:51 +00:00
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
|
|
|
private _getBilling(): IBilling {
|
|
|
|
if (!this._billing) {
|
2021-08-17 15:22:30 +00:00
|
|
|
if (!this._dbManager) { throw new Error("need dbManager"); }
|
|
|
|
this._billing = this.create.Billing(this._dbManager, this);
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
return this._billing;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check whether logger should skip a line. Careful, req and res are morgan-specific
|
|
|
|
// types, not Express.
|
|
|
|
private _shouldSkipRequestLogging(req: {url: string}, res: {statusCode: number}) {
|
|
|
|
if (req.url === '/status' && [200, 304].includes(res.statusCode) &&
|
|
|
|
this._healthCheckCounter > HEALTH_CHECK_LOG_SHOW_FIRST_N &&
|
|
|
|
this._healthCheckCounter % HEALTH_CHECK_LOG_SHOW_EVERY_N !== 1) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
private _createServers() {
|
|
|
|
// Start the app.
|
|
|
|
const server = configServer(http.createServer(this.app));
|
|
|
|
let httpsServer;
|
|
|
|
if (TEST_HTTPS_OFFSET) {
|
|
|
|
const certFile = process.env.GRIST_TEST_SSL_CERT;
|
|
|
|
const privateKeyFile = process.env.GRIST_TEST_SSL_KEY;
|
|
|
|
if (!certFile) { throw new Error('Set GRIST_TEST_SSL_CERT to location of certificate file'); }
|
|
|
|
if (!privateKeyFile) { throw new Error('Set GRIST_TEST_SSL_KEY to location of private key file'); }
|
|
|
|
log.debug(`https support: reading cert from ${certFile}`);
|
|
|
|
log.debug(`https support: reading private key from ${privateKeyFile}`);
|
|
|
|
httpsServer = configServer(https.createServer({
|
|
|
|
key: fse.readFileSync(privateKeyFile, 'utf8'),
|
|
|
|
cert: fse.readFileSync(certFile, 'utf8'),
|
|
|
|
}, this.app));
|
|
|
|
}
|
|
|
|
return {server, httpsServer};
|
|
|
|
}
|
|
|
|
|
|
|
|
private async _startServers(server: http.Server, httpsServer: https.Server|undefined,
|
|
|
|
name: string, port: number, verbose: boolean) {
|
(core) Speed up and upgrade build.
Summary:
- Upgrades to build-related packages:
- Upgrade typescript, related libraries and typings.
- Upgrade webpack, eslint; add tsc-watch, node-dev, eslint_d.
- Build organization changes:
- Build webpack from original typescript, transpiling only; with errors still
reported by a background tsc watching process.
- Typescript-related changes:
- Reduce imports of AWS dependencies (very noticeable speedup)
- Avoid auto-loading global @types
- Client code is now built with isolatedModules flag (for safe transpilation)
- Use allowJs to avoid copying JS files manually.
- Linting changes
- Enhance Arcanist ESLintLinter to run before/after commands, and set up to use eslint_d
- Update eslint config, and include .eslintignore to avoid linting generated files.
- Include a bunch of eslint-prompted and eslint-generated fixes
- Add no-unused-expression rule to eslint, and fix a few warnings about it
- Other items:
- Refactor cssInput to avoid circular dependency
- Remove a bit of unused code, libraries, dependencies
Test Plan: No behavior changes, all existing tests pass. There are 30 tests fewer reported because `test_gpath.py` was removed (it's been unused for years)
Reviewers: paulfitz
Reviewed By: paulfitz
Subscribers: paulfitz
Differential Revision: https://phab.getgrist.com/D3498
2022-06-27 20:09:41 +00:00
|
|
|
await listenPromise(server.listen(port, this.host));
|
2020-07-21 13:20:51 +00:00
|
|
|
if (verbose) { log.info(`${name} available at ${this.host}:${port}`); }
|
|
|
|
if (TEST_HTTPS_OFFSET && httpsServer) {
|
|
|
|
const httpsPort = port + TEST_HTTPS_OFFSET;
|
(core) Speed up and upgrade build.
Summary:
- Upgrades to build-related packages:
- Upgrade typescript, related libraries and typings.
- Upgrade webpack, eslint; add tsc-watch, node-dev, eslint_d.
- Build organization changes:
- Build webpack from original typescript, transpiling only; with errors still
reported by a background tsc watching process.
- Typescript-related changes:
- Reduce imports of AWS dependencies (very noticeable speedup)
- Avoid auto-loading global @types
- Client code is now built with isolatedModules flag (for safe transpilation)
- Use allowJs to avoid copying JS files manually.
- Linting changes
- Enhance Arcanist ESLintLinter to run before/after commands, and set up to use eslint_d
- Update eslint config, and include .eslintignore to avoid linting generated files.
- Include a bunch of eslint-prompted and eslint-generated fixes
- Add no-unused-expression rule to eslint, and fix a few warnings about it
- Other items:
- Refactor cssInput to avoid circular dependency
- Remove a bit of unused code, libraries, dependencies
Test Plan: No behavior changes, all existing tests pass. There are 30 tests fewer reported because `test_gpath.py` was removed (it's been unused for years)
Reviewers: paulfitz
Reviewed By: paulfitz
Subscribers: paulfitz
Differential Revision: https://phab.getgrist.com/D3498
2022-06-27 20:09:41 +00:00
|
|
|
await listenPromise(httpsServer.listen(httpsPort, this.host));
|
2020-07-21 13:20:51 +00:00
|
|
|
if (verbose) { log.info(`${name} available at https://${this.host}:${httpsPort}`); }
|
|
|
|
}
|
|
|
|
}
|
2021-10-31 06:08:24 +00:00
|
|
|
|
|
|
|
private async _recordNewUserInfo(row: object) {
|
|
|
|
const urlId = DOC_ID_NEW_USER_INFO;
|
2022-01-19 22:16:16 +00:00
|
|
|
// If nowhere to record data, return immediately.
|
|
|
|
if (!urlId) { return; }
|
2021-10-31 06:08:24 +00:00
|
|
|
let body: string|undefined;
|
|
|
|
let permitKey: string|undefined;
|
|
|
|
try {
|
|
|
|
body = JSON.stringify(mapValues(row, value => [value]));
|
|
|
|
|
|
|
|
// Take an extra step to translate the special urlId to a docId. This is helpful to
|
|
|
|
// allow the same urlId to be used in production and in test. We need the docId for the
|
|
|
|
// specialPermit below, which we need to be able to write to this doc.
|
|
|
|
//
|
|
|
|
// TODO With proper forms support, we could give an origin-based permission to submit a
|
|
|
|
// form to this doc, and do it from the client directly.
|
|
|
|
const previewerUserId = this._dbManager.getPreviewerUserId();
|
|
|
|
const docAuth = await this._dbManager.getDocAuthCached({urlId, userId: previewerUserId});
|
|
|
|
const docId = docAuth.docId;
|
|
|
|
if (!docId) {
|
|
|
|
throw new Error(`Can't resolve ${urlId}: ${docAuth.error}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
permitKey = await this._internalPermitStore.setPermit({docId});
|
|
|
|
const res = await fetch(await this.getHomeUrlByDocId(docId, `/api/docs/${docId}/tables/Responses/data`), {
|
|
|
|
method: 'POST',
|
|
|
|
headers: {'Permit': permitKey, 'Content-Type': 'application/json'},
|
|
|
|
body,
|
|
|
|
});
|
|
|
|
if (res.status !== 200) {
|
|
|
|
throw new Error(`API call failed with ${res.status}`);
|
|
|
|
}
|
|
|
|
} finally {
|
|
|
|
if (permitKey) {
|
|
|
|
await this._internalPermitStore.removePermit(permitKey);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-21 13:32:34 +00:00
|
|
|
/**
|
|
|
|
* If signUp is true, redirect to signUp.
|
|
|
|
* If signUp is false, redirect to login.
|
|
|
|
* If signUp is not set, redirect to signUp if no cookie found, else login.
|
|
|
|
*
|
|
|
|
* If nextUrl is not supplied, it will be constructed from a path in
|
|
|
|
* the "next" query parameter.
|
|
|
|
*/
|
|
|
|
private async _redirectToLoginOrSignup(
|
|
|
|
options: {
|
|
|
|
signUp?: boolean, nextUrl?: URL,
|
|
|
|
},
|
|
|
|
req: express.Request, resp: express.Response,
|
|
|
|
) {
|
|
|
|
let {nextUrl, signUp} = options;
|
|
|
|
|
|
|
|
const mreq = req as RequestWithLogin;
|
|
|
|
|
|
|
|
// This will ensure that express-session will set our cookie if it hasn't already -
|
|
|
|
// we'll need it when we redirect back.
|
|
|
|
forceSessionChange(mreq.session);
|
|
|
|
// Redirect to the requested URL after successful login.
|
|
|
|
if (!nextUrl) {
|
2023-09-05 18:27:35 +00:00
|
|
|
const nextPath = optStringParam(req.query.next, 'next');
|
2023-03-21 13:32:34 +00:00
|
|
|
nextUrl = new URL(getOrgUrl(req, nextPath));
|
|
|
|
}
|
|
|
|
if (signUp === undefined) {
|
|
|
|
// Like redirectToLogin in Authorizer, redirect to sign up if it doesn't look like the
|
|
|
|
// user has ever logged in on this browser.
|
|
|
|
signUp = (mreq.session.users === undefined);
|
|
|
|
}
|
|
|
|
const getRedirectUrl = signUp ? this._getSignUpRedirectUrl : this._getLoginRedirectUrl;
|
|
|
|
resp.redirect(await getRedirectUrl(req, nextUrl));
|
|
|
|
}
|
2023-05-01 18:24:23 +00:00
|
|
|
|
|
|
|
private async _redirectToHomeOrWelcomePage(
|
|
|
|
mreq: RequestWithLogin,
|
|
|
|
resp: express.Response,
|
|
|
|
options: {redirectToMergedOrg?: boolean} = {}
|
|
|
|
) {
|
|
|
|
const {redirectToMergedOrg} = options;
|
|
|
|
const userId = getUserId(mreq);
|
|
|
|
const domain = getOrgFromRequest(mreq);
|
|
|
|
const orgs = this._dbManager.unwrapQueryResult(
|
|
|
|
await this._dbManager.getOrgs(userId, domain, {
|
|
|
|
ignoreEveryoneShares: true,
|
|
|
|
})
|
|
|
|
);
|
|
|
|
if (orgs.length > 1) {
|
|
|
|
resp.redirect(getOrgUrl(mreq, '/welcome/teams'));
|
|
|
|
} else {
|
|
|
|
resp.redirect(redirectToMergedOrg ? this.getMergedOrgUrl(mreq) : getOrgUrl(mreq));
|
|
|
|
}
|
|
|
|
}
|
2023-09-06 18:35:46 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* If a valid cookie was set during sign-up to copy a document to the
|
|
|
|
* user's Home workspace, copy it and return the id of the new document.
|
|
|
|
*
|
|
|
|
* If a valid cookie wasn't set or copying failed, return `null`.
|
|
|
|
*/
|
|
|
|
private async _maybeCopyDocToHomeWorkspace(
|
|
|
|
req: RequestWithLogin,
|
|
|
|
resp: express.Response
|
|
|
|
): Promise<string|null> {
|
|
|
|
const cookies = cookie.parse(req.headers.cookie || '');
|
|
|
|
if (!cookies) { return null; }
|
|
|
|
|
|
|
|
const stateCookie = cookies['gr_signup_state'];
|
|
|
|
if (!stateCookie) { return null; }
|
|
|
|
|
|
|
|
const state = safeJsonParse(stateCookie, {});
|
|
|
|
const {srcDocId} = state;
|
|
|
|
if (!srcDocId) { return null; }
|
|
|
|
|
|
|
|
let newDocId: string | null = null;
|
|
|
|
try {
|
|
|
|
newDocId = await this._copyDocToHomeWorkspace(req, srcDocId);
|
|
|
|
} catch (e) {
|
|
|
|
log.error(`FlexServer failed to copy doc ${srcDocId} to Home workspace`, e);
|
|
|
|
} finally {
|
|
|
|
resp.clearCookie('gr_signup_state');
|
|
|
|
}
|
|
|
|
return newDocId;
|
|
|
|
}
|
|
|
|
|
|
|
|
private async _copyDocToHomeWorkspace(
|
|
|
|
req: express.Request,
|
|
|
|
docId: string,
|
|
|
|
): Promise<string> {
|
|
|
|
const userId = getUserId(req);
|
|
|
|
const doc = await this._dbManager.getDoc({userId, urlId: docId});
|
|
|
|
if (!doc) { throw new Error(`Doc ${docId} not found`); }
|
|
|
|
|
|
|
|
const workspacesQueryResult = await this._dbManager.getOrgWorkspaces(getScope(req), 0);
|
|
|
|
const workspaces = this._dbManager.unwrapQueryResult(workspacesQueryResult);
|
|
|
|
const workspace = workspaces.find(w => w.name === 'Home');
|
|
|
|
if (!workspace) { throw new Error('Home workspace not found'); }
|
|
|
|
|
|
|
|
const copyDocUrl = this.getHomeUrl(req, '/api/docs');
|
|
|
|
const response = await fetch(copyDocUrl, {
|
|
|
|
headers: {
|
|
|
|
...getTransitiveHeaders(req),
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
},
|
|
|
|
method: 'POST',
|
|
|
|
body: JSON.stringify({
|
|
|
|
sourceDocumentId: doc.id,
|
|
|
|
workspaceId: workspace.id,
|
|
|
|
documentName: doc.name,
|
|
|
|
}),
|
|
|
|
});
|
|
|
|
return await response.json();
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns the passed-in server, with some options adjusted. Specifically, removes the default
|
|
|
|
* socket timeout.
|
|
|
|
*/
|
|
|
|
function configServer<T extends https.Server|http.Server>(server: T): T {
|
|
|
|
// Remove the socket timeout, which causes node to close socket for long-running requests
|
|
|
|
// (like imports), triggering browser retry. (The default is 2 min; removed starting node v13.)
|
|
|
|
// See also https://nodejs.org/docs/latest-v10.x/api/http.html#http_server_settimeout_msecs_callback.)
|
|
|
|
server.setTimeout(0);
|
|
|
|
|
|
|
|
// The server's keepAlive timeout should be longer than the load-balancer's. Otherwise LB will
|
|
|
|
// produce occasional 502 errors when it sends a request to node just as node closes a
|
|
|
|
// connection. See https://adamcrowder.net/posts/node-express-api-and-aws-alb-502/.
|
|
|
|
const lbTimeoutSec = 300;
|
|
|
|
|
|
|
|
// Ensure all inactive connections are terminated by the ALB, by setting this a few seconds
|
|
|
|
// higher than the ALB idle timeout
|
|
|
|
server.keepAliveTimeout = (lbTimeoutSec + 5) * 1000;
|
|
|
|
|
|
|
|
// Ensure the headersTimeout is set higher than the keepAliveTimeout due to this nodejs
|
|
|
|
// regression bug: https://github.com/nodejs/node/issues/27363
|
|
|
|
server.headersTimeout = (lbTimeoutSec + 6) * 1000;
|
|
|
|
|
|
|
|
log.info("Server timeouts: keepAliveTimeout %s headersTimeout %s",
|
|
|
|
server.keepAliveTimeout, server.headersTimeout);
|
|
|
|
|
|
|
|
return server;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns true if environment is configured to allow unauthenticated test logins.
|
|
|
|
function allowTestLogin() {
|
|
|
|
return Boolean(process.env.GRIST_TEST_LOGIN);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check OPTIONS requests for allowed origins, and return heads to allow the browser to proceed
|
|
|
|
// with a POST (or other method) request.
|
|
|
|
function trustOriginHandler(req: express.Request, res: express.Response, next: express.NextFunction) {
|
2022-11-03 10:15:42 +00:00
|
|
|
res.header("Access-Control-Allow-Methods", "GET, PATCH, PUT, POST, DELETE, OPTIONS");
|
2020-07-21 13:20:51 +00:00
|
|
|
if (trustOrigin(req, res)) {
|
|
|
|
res.header("Access-Control-Allow-Credentials", "true");
|
2020-10-08 13:28:39 +00:00
|
|
|
res.header("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Requested-With");
|
|
|
|
} else {
|
2022-11-03 10:15:42 +00:00
|
|
|
// Any origin is allowed, but if it isn't trusted, then we don't allow credentials,
|
|
|
|
// i.e. no Cookie or Authorization header.
|
|
|
|
res.header("Access-Control-Allow-Origin", "*");
|
|
|
|
res.header("Access-Control-Allow-Headers", "Content-Type, X-Requested-With");
|
|
|
|
if (req.get("Cookie") || req.get("Authorization")) {
|
|
|
|
// In practice we don't expect to actually reach this point,
|
|
|
|
// as the browser should not include credentials in preflight (OPTIONS) requests,
|
|
|
|
// and should block real requests with credentials based on the preflight response.
|
|
|
|
// But having this means not having to rely on our understanding of browsers and CORS too much.
|
|
|
|
throw new ApiError("Credentials not supported for cross-origin requests", 403);
|
|
|
|
}
|
2020-07-21 13:20:51 +00:00
|
|
|
}
|
|
|
|
if ('OPTIONS' === req.method) {
|
|
|
|
res.sendStatus(200);
|
|
|
|
} else {
|
|
|
|
next();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set Cache-Control header to "no-cache"
|
|
|
|
function noCaching(req: express.Request, res: express.Response, next: express.NextFunction) {
|
|
|
|
res.header("Cache-Control", "no-cache");
|
|
|
|
next();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Methods that Electron app relies on.
|
|
|
|
export interface ElectronServerMethods {
|
|
|
|
importDoc(filepath: string): Promise<DocCreationInfo>;
|
2022-07-25 20:11:11 +00:00
|
|
|
onDocOpen(cb: (filePath: string) => void): void;
|
2020-07-21 13:20:51 +00:00
|
|
|
getUserConfig(): Promise<any>;
|
|
|
|
updateUserConfig(obj: any): Promise<void>;
|
|
|
|
onBackupMade(cb: () => void): void;
|
|
|
|
}
|