Compare commits

...
Author SHA1 Message Date
yu-i-i c7579e3e74 Update README.md for 6.2.0 2026-07-17 17:08:43 +02:00
yu-i-i fa93cbab49 Add syscalls to seccomp profile, fixes #194 2026-07-17 01:54:20 +02:00
yu-i-i f3075e1a0c Admin tools: improve Active Projects UI
- do not show the project owner, email and connections number columns
 - add mailto: all active users of a project when clicking the project title
 - fix error handling
2026-07-17 01:54:20 +02:00
yu-i-i 661bbf1de1 Fix: hide Git Bridge, GitHub Sync and Zotero UI elements when the corresponding feature is disabled 2026-07-17 01:54:20 +02:00
yu-i-i 341ddc2106 Reference picker: improve usability
- show tags for nonexistent references
- click a badge to find the corresponding reference
2026-07-17 01:54:20 +02:00
yu-i-i 77cae80c16 Add variables to enable experimental features: pandoc conversion and editor tabs 2026-07-17 01:54:19 +02:00
yu-i-i c8baf113d4 Registration page: the initial commit 2026-07-17 01:54:13 +02:00
yu-i-i 82d8e2fde3 Git bridge, Template gallery: remove integration with the old editor code 2026-07-17 01:54:13 +02:00
yu-i-i d0735d5d8a Admin tools: handle bad SMTP configuration error on account creation 2026-07-17 01:54:13 +02:00
yu-i-i 3828f4c51c Admin tools: remove themed pages env var; style admin header
- themed pages now is enabled by default upstream
  - make the header background red on admin manage urers/projects pages
  - fix minor bug
2026-07-17 01:53:53 +02:00
yu-i-i 1e35481223 Github Sync: enhance token handling and post-sync indexing
- support file-based token cipher
  - reindex references after sync
  - fix typo and clean up code
2026-07-16 17:34:49 +02:00
yu-i-i 5d3441e08f Zotero: improve integration and reference import
- use OAuth instead of tokens
  - add an integration card
  - improve error handling
  - add BibLaTeX format support
  - fix indexing of linked .bib files on creation
2026-07-16 17:34:16 +02:00
yu-i-i a55f2a497f Linked URL: adapt for yarn; bump node to 24.14.1 2026-07-08 16:27:40 +02:00
David Rotermund 5e465336ba Fix admin socket metadata handling and footer HTML rendering in admin-tools 2026-07-07 14:42:59 +02:00
Pierpaolo Vittorini f13a251381 Admin tools, Authentication: Fix: set analyticsId when creating a new user 2026-07-07 14:42:59 +02:00
yu-i-i 1e0e9473d2 Zotero: allow collaborators to refresh files imported from Zotero; show importer's name in the header 2026-07-07 14:42:59 +02:00
yu-i-i 9a1d84887a Admin tools: move styles to modules directory; fix form for dark theme 2026-07-07 14:42:59 +02:00
yu-i-i 6c4ba6ff5e Github Sync: initial commit 2026-07-07 14:42:59 +02:00
yu-i-i dc99fbc810 Template Gallery: fix for 6.2.0 2026-07-07 14:42:59 +02:00
yu-i-i ccecdc3fb5 Git integration: use named export for settings page widget
remove stray console.log
2026-07-07 14:42:59 +02:00
Synésio Neto d4e0184b5e Fix a greyed out create file button after the Zotero Integration was merged. 2026-07-07 14:42:59 +02:00
yu-i-i 92fd2b0997 Sandboxed compiles: cwd argument was added to CommandRunner
see upstream commit ce6f9b8
2026-07-07 14:42:59 +02:00
yu-i-i ff9872d8bf Patches handled by yarn 2026-07-07 14:42:58 +02:00
yu-i-i 8bf99c7e29 Revert "[clsi] remove locking from docker actions (#32373)"
This reverts commit d66a856baa.
2026-07-07 14:42:58 +02:00
yu-i-i df7a4fa9ff Reference picker: normal search instead of fuzzy; overleafying modal 2026-07-07 14:42:58 +02:00
David Rotermund ea73e68f56 Reference picker 2026-07-07 14:42:58 +02:00
yu-i-i 2d4a923bfc Authentication: fix ldap searchAttributes for passport-ldapauth 3.0.1 2026-07-07 14:42:58 +02:00
David Rotermund 7ae7736a8c Zotero Integration (#164) 2026-07-07 14:42:58 +02:00
David Rotermund b1cf1f3c4b Logo Tools (#158)
* Logo Tools

* Moved to /tools/logo; Checks dependencies first and stops if they are not there; Added information about 3_remove_branding_from_projectpage.sh in README ; reordered the commands of 1_convert.sh to avoid the logo-horizontal.png problem
2026-07-07 14:42:58 +02:00
yu-i-i 7e7db051e5 Git Bridge: fix incorrect token creation date display 2026-07-07 14:42:58 +02:00
David Rotermund 820f3a1e2d Admin tools: introduce Activ Projects tab on the Manage Site page
- code moved to modules/admin-tools (yu-i-i)
2026-07-07 14:42:58 +02:00
yu-i-i b569fad605 Git Bridge: route PAT validation endpoint to correct router 2026-07-07 14:42:58 +02:00
yu-i-i 0829a07998 Sandboxed compiles: avoid destroying containers of recently accessed projects
see upstream commit a9c4138
  here is an appropriate DockerRunner.mjs patch
2026-07-07 14:42:58 +02:00
yu-i-i ec4ad68791 Admin tools: themed dashboard 2026-07-07 14:42:57 +02:00
Tao Chen 623f78905b Git Bridge: support git-bridge configuration via env in nginx
- generate overleaf.conf dynamically
- support GIT_BRIDGE_HOST and GIT_BRIDGE_PORT
- configure client_max_body_size for /git using GIT_BRIDGE_REPOSTORE_MAX_FILE_SIZE
2026-07-07 14:42:57 +02:00
yu-i-i 031d83a605 Linked URL: bump node to 24.13.0 2026-07-07 14:42:57 +02:00
yu-i-i bbb212bdf6 Git Bridge: integrations-panel code was moved 2026-07-07 14:42:57 +02:00
yu-i-i 0567c8927e Authentication: fix uid ldap login after email parsing was added to rate limiter 2026-07-07 14:42:57 +02:00
yu-i-i 4ef5f28282 Sandboxed compiles: convert DockerRunner to ESM 2026-07-07 14:42:57 +02:00
yu-i-i 32ee988a26 Update README.md 2026-07-07 14:42:57 +02:00
yu-i-i 9374c22bb6 Sandboxed compiles: add scripts to add/strip repo prefix from texlive images 2026-07-07 14:42:57 +02:00
yu-i-i a47638c120 Add env variable to enable restoring project/file from history snapshot 2026-07-07 14:42:57 +02:00
yu-i-i a7349c0c7e Admin tools: minor improvements
- enable Projects button in navbar for admin projects page
- enable copy of user ID in user info modal
- add null check in UserListController (thanks @moschlar)
2026-07-07 14:42:57 +02:00
yu-i-i 83f2ec5f1c Git Bridge: Add git integration 2026-07-07 14:42:57 +02:00
yu-i-i 5c68279105 Sandboxed compiles: set imageName to default if undefined in project 2026-07-07 14:42:56 +02:00
yu-i-i e226d1b179 Authentication: update passport-ldapauth to 3.0.1; fix minor issues 2026-07-07 14:42:56 +02:00
yu-i-i e59d381d60 Linked URL: prevent SSRF via DNS rebinding; minor fixes 2026-07-07 14:42:56 +02:00
yu-i-i b6e33c120d Template gallery: add template management authorization middleware
- Middleware to enforce template access rules
- Introduce template manager role
- Fix minor issues
2026-07-07 14:42:56 +02:00
yu-i-i 9472d977b0 Admin tools: optimize user/project list performance
Add frontend pagination
Add search debouncing
Render modals conditionally
Remove unnecessary sorting
2026-07-07 14:42:56 +02:00
yu-i-i 5673353770 Update README.md 2026-07-07 14:42:56 +02:00
yu-i-i 942bd4b7f8 Sandboxed Compiles: pass imageName in Copy project 2026-07-07 14:42:56 +02:00
yu-i-i 5db0f4fece Admin tools: fix minor bugs 2026-07-07 14:42:56 +02:00
yu-i-i 9db3d2cda3 Sandboxed compiles: add arm64 support to clsi seccomp profile 2026-07-07 14:42:56 +02:00
yu-i-i d871ce961a Sandboxed Compiles: support configurable texlive image root via env var 2026-07-07 14:42:56 +02:00
yu-i-i 0f8e6979e2 Admin Tools: Fix EXTERNAL_AUTH is 'none' 2026-07-07 14:42:55 +02:00
yu-i-i c3814a9062 Admin Tools: Fix sorting 2026-07-07 14:42:55 +02:00
yu-i-i de346104a1 Template Gallery: migration to 6.1.0
enable menu for editor redisign
move frontend code to modules
2026-07-07 14:42:55 +02:00
yu-i-i 4499088928 Symbol Palette: fix for 6.1.0 2026-07-07 14:42:55 +02:00
yu-i-i 8a3ff69f3e Track changes: Fix import after upstream converted several files to ESM 2026-07-07 14:42:55 +02:00
yu-i-i 76623f85eb Authentication: Fix import after upstream converted some files to ESM 2026-07-07 14:42:55 +02:00
yu-i-i 1348946421 Admin Tools: Fix for 6.1.0 migraton 2026-07-07 14:42:55 +02:00
Guilhem Poy 1f9d03c389 Add support for EMAIL_SMTP_PASS_FILE
Small feature to provide the email password from a file rather than directly from the env variable OVERLEAF_EMAIL_SMTP_PASS. Useful when used in conjunction with Docker Compose secrets.
2026-07-07 14:42:55 +02:00
yu-i-i 51a9ce881c Admin Tools: Fix user name
fix user name is not updated

fix first_name/last_name is undefined
2026-07-07 14:42:55 +02:00
yu-i-i 59a140fe30 Admin Tools: Manage users and Manage projects pages 2026-07-07 14:42:55 +02:00
yu-i-i 13fb6cd418 Hotfix 5.5.6-ext-3.3 2026-07-07 14:42:54 +02:00
yu-i-i 343a7de538 Linked URL: add sanitize and normalize 2026-07-07 14:42:54 +02:00
yu-i-i 0b2b709638 README for extended CE 2026-07-07 14:42:54 +02:00
yu-i-i b4896abdea Add service for Linked URL feature 2026-07-07 14:42:54 +02:00
yu-i-i b72a9f9e42 Sandboxed compiles: adjust clsi-profile 2026-07-07 14:42:54 +02:00
yu-i-i 164f160243 Track changes: Fix import after upstream converted DocumentUpdaterHandler and CollaboratorsGetter to ESM 2026-07-07 14:42:54 +02:00
yu-i-i 6a4647ee60 Authentication: Fix import after upstream converted AuthenticationController to ESM 2026-07-07 14:42:54 +02:00
yu-i-i 4a9e22c487 Template gallery: Fix import after upstream converted AuthenticationController, ProjectGetter, ProjectLocator and DocumentUpdaterHandler` to ESM 2026-07-07 14:42:54 +02:00
yu-i-i b062f92ce9 Template gallery: Fix import after upstream converted CompileManager, ClsiManager and RateLimiterMiddleware to ESM 2026-07-07 14:42:54 +02:00
yu-i-i 6c97b44b5b Template gallery: Fix OLModal usage (see upstream commit 19b3834) 2026-07-07 14:42:53 +02:00
yu-i-i cb2a4739ff Authentication: Fix import after upstream converted PermissionsManager, RateLimiterMiddleware, UserCreator and SAMLIdentityManager to ESM 2026-07-07 14:42:53 +02:00
yu-i-i 9755e7f500 Track changes: Fix import after upstream converted ChatManager, UserInfoManager and UserInfoController to ESM 2026-07-07 14:42:53 +02:00
Rudy ERCEK 6dec15bb6f Add MAX_UPLOAD_SIZE environment variable 2026-07-07 14:42:53 +02:00
yu-i-i 4e77cc0471 Fix style of Templates button in navbar 2026-07-07 14:42:53 +02:00
yu-i-i 60c66ad1d5 Fix: comments thread does not necessarily belong to current document 2026-07-07 14:42:53 +02:00
yu-i-i c9f570f108 Fix import after upstream converted AuthorizationMiddleware to ESM 2026-07-07 14:42:53 +02:00
yu-i-i 4d5be374cd Track changes: Use getProjectRanges introduced in the upstream 2026-07-07 14:42:53 +02:00
yu-i-i 9880977b34 Rename @node-saml/node-saml patch for v5.1.0 2026-07-07 14:42:53 +02:00
yu-i-i f76afc3aba Fix imports after upstream converted UserController and CaptchaMiddleware to ESM 2026-07-07 14:42:53 +02:00
yu-i-i 1e53bff130 Fix import after upstream converted ErrorController to ESM 2026-07-07 14:42:53 +02:00
yu-i-i 6becc486fa Bring back deleteFile removed upstream 2026-07-07 14:42:53 +02:00
yu-i-i 8f5267cde9 Symbol palette: ui components were moved to shared folder 2026-07-07 14:42:52 +02:00
yu-i-i 4e42c6d232 Move Sympol Palette code to modules, closes #63 2026-07-07 14:42:52 +02:00
yu-i-i f502d4e4b5 Template gallery: ui components were moved to shared folder 2026-07-07 14:42:52 +02:00
yu-i-i e965b4f0f0 passport-saml was updated to v5.1.0 2026-07-07 14:42:52 +02:00
yu-i-i 5f8118ee61 Fix: always include repository prefix in sandboxed compiles image name 2026-07-07 14:42:52 +02:00
yu-i-i effbd8ed6b Fix template publishing to align with upstream project context changes 2026-07-07 14:42:52 +02:00
yu-i-i 02c474afbb Remove LDAP admin check via group search in ldap-passport 2026-07-07 14:42:52 +02:00
yu-i-i 73b49a0dfe toggleSymbolPalette now in useEditorPropertiesContext 2026-07-07 14:42:52 +02:00
yu-i-i 65af49b820 Set use-ai capability to false 2026-07-07 14:42:52 +02:00
yu-i-i 3a1e4f13ed Track changes: convert to mjs 2026-07-07 14:42:52 +02:00
yu-i-i 4671f26904 Track changes: use getTrackedChangesUserIds introduced in the mainstream 2026-07-07 14:42:52 +02:00
yu-i-i 23fb6e3ebb Remove OVERLEAF_OIDC_DISABLE_JIT_ACCOUNT_CREATION in favor of OVERLEAF_OIDC_ALLOWED_EMAIL_DOMAINS 2026-07-07 14:42:52 +02:00
Synésio Neto a2416a499c Introduce an environment variable to allow JIT OIDC users creation based on their email address domain. 2026-07-07 14:42:52 +02:00
yu-i-i ff04f9a073 Introduce an environment variable to control user creation in OIDC authentication, closes #47 2026-07-07 14:42:51 +02:00
David Rotermund e534b32953 I need the --network=host settings for building the container 2026-07-07 14:42:51 +02:00
yu-i-i da1567cc51 Avoid DEP0174 by removing async from callback-based getGroupPolicyForUser 2026-07-07 14:42:51 +02:00
yu-i-i f59d616422 Fix login page 2026-07-07 14:42:51 +02:00
yu-i-i e094fb59df Symbol Palette: make close button visible 2026-07-07 14:42:51 +02:00
yu-i-i efc0289497 Template Gallery: replace markdown-it with marked 2026-07-07 14:42:51 +02:00
yu-i-i bcb5af48ae Refactor Template Gallery; resolves #38 and #39
- Replace free-text license input with a select box
- Improve visual presentation of modals and enhance keyboard interaction
2026-07-07 14:42:51 +02:00
yu-i-i e6db566a9c Refactor Sandboxed Compiles 2026-07-07 14:42:51 +02:00
yu-i-i c7350d5877 Symbol Palette: improve keyboard input experience 2026-07-07 14:42:51 +02:00
yu-i-i 3f6acabf26 Symbol Palette: get rid of @reach/tabs 2026-07-07 14:42:51 +02:00
yu-i-i dc78d3f028 Add 'poll' to clsi seccomp profile, fixes minted. Thanks, David. 2026-07-07 14:42:51 +02:00
yu-i-i 6b3472e3a8 Make Template Gallery optional; rename environment variables 2026-07-07 14:42:51 +02:00
yu-i-i 8dc220fdc5 Add Template Gallery support 2026-07-07 14:42:50 +02:00
yu-i-i ffe7d44174 Track changes / comments: update backend to support frontend changes 2026-07-07 14:42:50 +02:00
yu-i-i 5b9c6985d4 Allow EXTERNAL_AUTH to be undefined, fixes #26 2026-07-07 14:42:50 +02:00
yu-i-i 6e4e540c5a Symbol palette: switch to 'OL' UI components and apply minor cosmetic changes 2026-07-07 14:42:50 +02:00
yu-i-i 837519b08d Make OVERLEAF_OIDC_USER_ID_FIELD support 'email' as a value 2026-07-07 14:42:50 +02:00
yu-i-i 9bc7fcf77a See upstream commit 42ee56e 2026-07-07 14:42:50 +02:00
yu-i-i dbd14d5e86 Fix glitches in symbol palette after switching to Bootstrap 5 2026-07-07 14:42:50 +02:00
yu-i-i 36719cbf3a Whitelist /oidc/login endpoint, fixes #21 2026-07-07 14:42:50 +02:00
yu-i-i 899d4cd66f Add ENV variables to control SAML signature validation 2026-07-07 14:42:50 +02:00
yu-i-i 3bd8b49ae1 Re-export doLogout (was removed from exports in commit b9fb636). 2026-07-07 14:42:50 +02:00
yu-i-i cfeed73e52 Refactor authentication code; add OIDC support 2026-07-07 14:42:49 +02:00
yu-i-i 81d51d1498 Allow adding extra flags to LaTeX compiler through environment variable 2026-07-07 14:42:49 +02:00
yu-i-i bbd5300f66 Enable LDAP and SAML authentication support 2026-07-07 14:42:49 +02:00
yu-i-i 8dea2fab50 Enable Symbol Palette 2026-07-07 14:42:49 +02:00
yu-i-i a66d4389bf Allow selecting a TeX Live image for a project 2026-07-07 14:42:49 +02:00
Sam Van den Vonder 9aee49e3b8 Enable Sandboxed Compiles feature 2026-07-07 14:42:49 +02:00
yu-i-i 636231490e Enable track changes and comments feature 2026-07-07 02:49:07 +02:00
yu-i-i 0d0450b7ca Redirect non-existing links to Overleaf page 2026-07-07 02:49:06 +02:00
425 changed files with 30991 additions and 235 deletions
+2 -6
View File
@@ -8,12 +8,8 @@ assignees: ''
<!--
Note: If you are using www.overleaf.com and have a problem,
or if you would like to request a new feature please contact
the support team at support@overleaf.com
This form should only be used to report bugs in the
Community Edition release of Overleaf.
Note: This form should only be used to report bugs in the
Extended CE release of Overleaf.
-->
-4
View File
@@ -5,7 +5,3 @@
## Related issues / Pull Requests
<!-- Fixes #xyz, Contributes to #xyz, Related to #xyz-->
## Contributor Agreement
- [ ] I confirm I have signed the [Contributor License Agreement](https://github.com/overleaf/overleaf/blob/main/CONTRIBUTING.md#contributor-license-agreement)
@@ -0,0 +1,23 @@
diff --git a/lib/saml.js b/lib/saml.js
index 64180fdd7fe6302bf8da7d1ca65c01bb1ea5e2c1..7015c3b73603f624c15195a0a38c2fbf750a4c60 100644
--- a/lib/saml.js
+++ b/lib/saml.js
@@ -327,7 +327,8 @@ class SAML {
const requestOrResponse = request || response;
(0, utility_1.assertRequired)(requestOrResponse, "either request or response is required");
let buffer;
- if (this.options.skipRequestCompression) {
+ // logout requestOrResponse must be compressed anyway
+ if (this.options.skipRequestCompression && operation !== "logout") {
buffer = Buffer.from(requestOrResponse, "utf8");
}
else {
@@ -510,7 +511,7 @@ class SAML {
try {
xml = Buffer.from(container.SAMLResponse, "base64").toString("utf8");
doc = await (0, xml_1.parseDomFromString)(xml);
- const inResponseToNodes = xml_1.xpath.selectAttributes(doc, "/*[local-name()='Response']/@InResponseTo");
+ const inResponseToNodes = xml_1.xpath.selectAttributes(doc, "/*[local-name()='Response' or local-name()='LogoutResponse']/@InResponseTo");
if (inResponseToNodes) {
inResponseTo = inResponseToNodes.length ? inResponseToNodes[0].nodeValue : null;
await this.validateInResponseTo(inResponseTo);
@@ -0,0 +1,73 @@
diff --git a/lib/ldapauth.js b/lib/ldapauth.js
index 88398ed31afee34c8958ad5e7a53653e1b5f6f82..0334177af8a65c7c5f9de7570924ab0f359e3f38 100644
--- a/lib/ldapauth.js
+++ b/lib/ldapauth.js
@@ -87,6 +87,7 @@ function LdapAuth(opts) {
this.opts.bindProperty || (this.opts.bindProperty = 'dn');
this.opts.groupSearchScope || (this.opts.groupSearchScope = 'sub');
this.opts.groupDnProperty || (this.opts.groupDnProperty = 'dn');
+ this.opts.tlsStarted = false;
EventEmitter.call(this);
@@ -126,21 +127,7 @@ function LdapAuth(opts) {
this._userClient.on('error', this._handleError.bind(this));
var self = this;
- if (this.opts.starttls) {
- // When starttls is enabled, this callback supplants the 'connect' callback
- this._adminClient.starttls(this.opts.tlsOptions, this._adminClient.controls, function (err) {
- if (err) {
- self._handleError(err);
- } else {
- self._onConnectAdmin();
- }
- });
- this._userClient.starttls(this.opts.tlsOptions, this._userClient.controls, function (err) {
- if (err) {
- self._handleError(err);
- }
- });
- } else if (opts.reconnect) {
+ if (opts.reconnect && !this.opts.starttls) {
this.once('_installReconnectListener', function () {
self.log && self.log.trace('install reconnect listener');
self._adminClient.on('connect', function () {
@@ -401,6 +388,37 @@ LdapAuth.prototype._findGroups = function (user, callback) {
*/
LdapAuth.prototype.authenticate = function (username, password, callback) {
var self = this;
+ if (this.opts.starttls && !this.opts.tlsStarted) {
+ // When starttls is enabled, this callback supplants the 'connect' callback
+ this._adminClient.starttls(this.opts.tlsOptions, this._adminClient.controls, function (err) {
+ if (err) {
+ self._handleError(err);
+ } else {
+ self._onConnectAdmin(function(){self._handleAuthenticate(username, password, callback);});
+ }
+ });
+ this._userClient.starttls(this.opts.tlsOptions, this._userClient.controls, function (err) {
+ if (err) {
+ self._handleError(err);
+ }
+ });
+ } else {
+ self._handleAuthenticate(username, password, callback);
+ }
+};
+
+/**
+ * Authenticate given credentials against LDAP server
+ *
+ * @private
+ * @param {string} username - The username to authenticate
+ * @param {string} password - The password to verify
+ * @param {resultCallback} callback - Result handling callback
+ * @returns {undefined}
+ */
+LdapAuth.prototype._handleAuthenticate = function (username, password, callback) {
+ this.opts.tlsStarted = true;
+ var self = this;
if (typeof password === 'undefined' || password === null || password === '') {
return callback(new Error('no password given'));
+6 -15
View File
@@ -1,38 +1,29 @@
# Contributing to Overleaf
# Contributing to Overleaf CE+
Thank you for reading this! If you'd like to report a bug or join in the development
of Overleaf, then here are some notes on how to do that.
of Overleaf CE+, then here are some notes on how to do that.
## Reporting bugs and opening issues
If you'd like to report a bug or open an issue, please **[check if there is an existing issue](https://github.com/overleaf/overleaf/issues).**
If you'd like to report a bug or open an issue, please **[check if there is an existing issue](https://github.com/yu-i-i/overleaf-cep).**
If there is then please add any more information that you have, or give it a 👍.
When submitting an issue please describe the issue as clearly as possible, including how to
reproduce the bug, which situations it appears in, what you expected to happen, and what actually happens.
If you can include a screenshot for front end issues that is very helpful.
**Note**: If you are using [www.overleaf.com](www.overleaf.com) and have a problem, or if you would like to request a new feature, please contact the Support team at support@overleaf.com. Raise an issue here only to report bugs in the Community Edition release of Overleaf.
## Pull Requests
See [our wiki](https://github.com/overleaf/overleaf/wiki)
See [Overleaf wiki](https://github.com/overleaf/overleaf/wiki)
for how to manage the Overleaf development environment and for our developer guidelines.
We love pull requests, so be bold with them! Don't be afraid of going ahead
and changing something, or adding a new feature. We're very happy to work with you
to get your changes merged into Overleaf.
If you're looking for something to work on, have a look at the [open issues](https://github.com/overleaf/overleaf/issues).
If you're looking for something to work on, have a look at the [open issues](https://github.com/yu-i-i/overleaf-cep/issues).
## Security
Please see [our security policy](https://github.com/overleaf/overleaf/security/policy) if you would like to report a potential security vulnerability.
## Contributor License Agreement
Before we can accept any contributions of code, we need you to agree to our
[Contributor License Agreement](https://docs.google.com/forms/d/e/1FAIpQLSef79XH3mb7yIiMzZw-yALEegS-wyFetvjTiNBfZvf_IHD2KA/viewform?usp=sf_link).
This is to ensure that you own the copyright of your contribution, and that you
agree to give us a license to use it in both the open source version, and the version
of Overleaf running at www.overleaf.com, which may have additional changes.
Please see [Overleaf security policy](https://github.com/overleaf/overleaf/security/policy) if you would like to report a potential security vulnerability.
+53
View File
@@ -0,0 +1,53 @@
# CREDITS
This project includes ideas and adapted code from several open-source projects.\
In most cases the original code has been modified, optimized, or extended.
## Symbol palette
The symbol palette feature is based on the
[original Overleaf implementation](https://github.com/overleaf/web/tree/master/frontend/js/features/symbol-palette)
The original code was slightly improved, particularly in the parts related to keyboard input.
## LDAP authentication
LDAP authentication was inspired by [this project](https://github.com/smhaller/ldap-overleaf-sl).
The project provided the idea and part of the implementation for adding LDAP users to the user's contacts.
## Real-time track changes and comments
The Track Changes and Comments feature exists largely in the original Overleaf codebase.\
The missing parts were implemented based on [this code](https://github.com/ertuil/overleaf).
The referenced code was fixed, optimized, and extended.
## Sandboxed compiles
The Sandboxed Compiles feature was until recently largely present in the original Overleaf codebase.\
The missing parts were implemented in this project.
## Import file from external URL
The "From External URL" feature exists in the original Overleaf code.\
The missing proxy component was implemented in this project.
## Git integration
The Git integration feature includes parts of the frontend code
from [here](https://github.com/ayaka-notes/overleaf-pro/tree/feat-git-bridge)
## GitHub synchronization
The GitHub synchronization feature includes parts of the frontend code and the OAuth2 backend implementation
from [here](https://github.com/ayaka-notes/overleaf-pro/commit/06a30fe9a0ed75e5ab40b50a8a4e94f43161cf71).
## Sign Up page
The Sign Up page is based on [this code](https://github.com/ayaka-notes/overleaf-pro/tree/feat-public-registeration).
# Acknowledgments
Thanks to the users of the project for valuable feedback, suggestions,
and help in identifying and fixing bugs.
+44 -31
View File
@@ -6,52 +6,65 @@
<h4 align="center">An open-source online real-time collaborative LaTeX editor.</h4>
<p align="center">
<a href="https://github.com/overleaf/overleaf/wiki">Wiki</a> •
<a href="https://github.com/yu-i-i/overleaf-cep/wiki">Wiki</a> •
<a href="https://www.overleaf.com/for/enterprises">Server Pro</a> •
<a href="#contributing">Contributing</a> •
<a href="https://mailchi.mp/overleaf.com/community-edition-and-server-pro">Mailing List</a> •
<a href="#authors">Authors</a> •
<a href="#license">License</a>
</p>
<img src="doc/screenshot.png" alt="A screenshot of a project being edited in Overleaf Community Edition">
<img src="doc/screenshot.png" alt="A screenshot of a project being edited in Overleaf Extended Community Edition">
<p align="center">
Figure 1: A screenshot of a project being edited in Overleaf Community Edition.
Figure 1: A screenshot of a project being edited in Overleaf Extended Community Edition.
</p>
## Community Edition
[Overleaf](https://www.overleaf.com) is an open-source online real-time collaborative LaTeX editor. We run a hosted version at [www.overleaf.com](https://www.overleaf.com), but you can also run your own local version, and contribute to the development of Overleaf.
[Overleaf](https://www.overleaf.com) is an open-source online real-time collaborative LaTeX editor. Overleaf runs a hosted version at [www.overleaf.com](https://www.overleaf.com), but you can also run your own local version, and contribute to the development of Overleaf.
## Extended Community Edition (CE+)
The present "extended" version of Overleaf CE includes:
- Sandboxed compiles with TeX Live image selection
- Sign Up page
- LDAP authentication
- SAML authentication
- OpenID Connect authentication
- Real-time track changes and comments
- Symbol palette
- Template gallery
- Import file from external URL
- Git integration
- GitHub synchronization
- Zotero integration
- Reference Search and Pick Tool
- Document Import (`.docx`, `.md`) and Export (`.docx`, `.md`, `.html`)
- Advanced administrator tools for managing user accounts and projects
- Logo tools
> [!CAUTION]
> Overleaf Community Edition is intended for use in environments where **all** users are trusted. Community Edition is **not** appropriate for scenarios where isolation of users is required due to Sandbox Compiles not being available. When not using Sandboxed Compiles, users have full read and write access to the `sharelatex` container resources (filesystem, network, environment variables) when running LaTeX compiles.
> Overleaf Community Edition is intended for use in environments where **all** users are trusted. Community Edition is **not** appropriate for scenarios where isolation of users is required due to Sandbox Compiles not being available. When not using Sandboxed Compiles, users have full read and write access to the `sharelatex` container resources (filesystem, network, environment variables) when running LaTeX compiles.
Therefore, in any environment where not all users can be fully trusted, it is strongly recommended to enable the Sandboxed Compiles feature available in the Extended Community Edition.
For more information on Sandbox Compiles check out our [documentation](https://docs.overleaf.com/on-premises/configuration/overleaf-toolkit/server-pro-only-configuration/sandboxed-compiles).
For more information on Sandbox Compiles check out Overleaf [documentation](https://docs.overleaf.com/on-premises/configuration/overleaf-toolkit/server-pro-only-configuration/sandboxed-compiles).
## Enterprise
If you want help installing and maintaining Overleaf in your lab or workplace, we offer an officially supported version called [Overleaf Server Pro](https://www.overleaf.com/for/enterprises). It also includes more features for security (SSO with LDAP or SAML), administration and collaboration (e.g. tracked changes). [Find out more!](https://www.overleaf.com/for/enterprises)
## Keeping up to date
Sign up to the [mailing list](https://mailchi.mp/overleaf.com/community-edition-and-server-pro) to get updates on Overleaf releases and development.
If you want help installing and maintaining Overleaf in your lab or workplace, Overleaf offers an officially supported version called [Overleaf Server Pro](https://www.overleaf.com/for/enterprises).
## Installation
We have detailed installation instructions in the [Overleaf Toolkit](https://github.com/overleaf/toolkit/).
## Upgrading
If you are upgrading from a previous version of Overleaf, please see the [Release Notes section on the Wiki](https://github.com/overleaf/overleaf/wiki#release-notes) for all of the versions between your current version and the version you are upgrading to.
Detailed installation instructions can be found in the [Overleaf Toolkit](https://github.com/overleaf/toolkit/).
Configuration details and release history for the Extended Community Edition can be found on the [Extended CE Wiki Page](https://github.com/yu-i-i/overleaf-cep/wiki).
## Overleaf Docker Image
This repo contains two dockerfiles, [`Dockerfile-base`](server-ce/Dockerfile-base), which builds the
`sharelatex/sharelatex-base` image, and [`Dockerfile`](server-ce/Dockerfile) which builds the
`sharelatex/sharelatex` (or "community") image.
`sharelatex/sharelatex-base:ext-ce` image, and [`Dockerfile`](server-ce/Dockerfile) which builds the
`sharelatex/sharelatex:ext-ce` image.
The Base image generally contains the basic dependencies like `wget`, plus `texlive`.
We split this out because it's a pretty heavy set of
This is split out because it's a pretty heavy set of
dependencies, and it's nice to not have to rebuild all of that every time.
The `sharelatex/sharelatex` image extends the base image and adds the actual Overleaf code
@@ -59,22 +72,22 @@ and services.
Use `make build-base` and `make build-community` from `server-ce/` to build these images.
We use the [Phusion base-image](https://github.com/phusion/baseimage-docker)
(which is extended by our `base` image) to provide us with a VM-like container
The [Phusion base-image](https://github.com/phusion/baseimage-docker)
(which is extended by the `base` image) provides a VM-like container
in which to run the Overleaf services. Baseimage uses the `runit` service
manager to manage services, and we add our init-scripts from the `server-ce/runit`
folder.
## Contributing
Please see the [CONTRIBUTING](CONTRIBUTING.md) file for information on contributing to the development of Overleaf.
manager to manage services, and init scripts from the `server-ce/runit`
folder are added.
## Authors
[The Overleaf Team](https://www.overleaf.com/about)
[The Overleaf Team](https://www.overleaf.com/about)\
[yu-i-i](https://github.com/yu-i-i), [davrot](https://github.com/davrot) — CE extensions; references to adapted code are listed in [`CREDITS`](CREDITS.md)
## License
The code in this repository is released under the GNU AFFERO GENERAL PUBLIC LICENSE, version 3. A copy can be found in the [`LICENSE`](LICENSE) file.
Copyright (c) Overleaf, 2014-2025.
Copyright (c) Overleaf, 2014-2026.\
Copyright (c) @yu-i-i, 2024-2026, for CE extensions.
Portions of the code are derived from other open-source projects; see [`CREDITS`](CREDITS.md).
+1
View File
@@ -66,6 +66,7 @@ each service:
| `real-time` | 9237 |
| `history-v1` | 9239 |
| `project-history` | 9240 |
| `linked-url-proxy` | 9241 |
To attach to a service using Chrome's _remote debugging_, go to
<chrome://inspect/> and make sure _Discover network targets_ is checked. Next
+1
View File
@@ -7,6 +7,7 @@ FILESTORE_HOST=filestore
GRACEFUL_SHUTDOWN_DELAY_SECONDS=0
HISTORY_V1_HOST=history-v1
HISTORY_REDIS_HOST=redis
LINKED_URL_PROXY_HOST=linked-url-proxy
LISTEN_ADDRESS=0.0.0.0
MONGO_HOST=mongo
MONGO_URL=mongodb://mongo/sharelatex?directConnection=true
+11
View File
@@ -68,6 +68,17 @@ services:
- ../services/history-v1/knexfile.js:/overleaf/services/history-v1/knexfile.js
- ../services/history-v1/migrations:/overleaf/services/history-v1/migrations
linked-url-proxy:
command: ["node", "--watch", "app.mjs"]
environment:
- NODE_OPTIONS=--inspect=0.0.0.0:9229
ports:
- "127.0.0.1:9241:9229"
volumes:
- ../services/linked-url-proxy/app:/overleaf/services/linked-url-proxy/app
- ../services/linked-url-proxy/config:/overleaf/services/linked-url-proxy/config
- ../services/linked-url-proxy/app.mjs:/overleaf/services/linked-url-proxy/app.mjs
notifications:
command: ["node", "--watch", "app.ts"]
environment:
+24 -1
View File
@@ -88,6 +88,13 @@ services:
volumes:
- history-v1-buckets:/buckets
linked-url-proxy:
build:
context: ..
dockerfile: services/linked-url-proxy/Dockerfile
env_file:
- dev.env
mongo:
image: mongo:8
command: --replSet overleaf
@@ -141,7 +148,7 @@ services:
- dev.env
environment:
- APP_NAME=Overleaf Community Edition
- ENABLED_LINKED_FILE_TYPES=project_file,project_output_file
- ENABLED_LINKED_FILE_TYPES=project_file,project_output_file,zotero
- EMAIL_CONFIRMATION_DISABLED=true
- NODE_ENV=development
- OVERLEAF_ALLOW_PUBLIC_ACCESS=true
@@ -158,6 +165,7 @@ services:
- document-updater
- filestore
- history-v1
- linked-url-proxy
- notifications
- project-history
- real-time
@@ -173,3 +181,18 @@ services:
- "127.0.0.1:80:3808"
volumes:
- ./webpack.config.dev-env.js:/overleaf/services/web/webpack.config.dev-env.js
git-bridge:
image: quay.io/sharelatex/git-bridge:latest
expose:
- "8000"
ports:
- "8000:8000"
environment:
GIT_BRIDGE_API_BASE_URL: "http://web:3000/api/v0"
GIT_BRIDGE_OAUTH2_SERVER: "http://web:3000"
GIT_BRIDGE_POSTBACK_BASE_URL: "http://git-bridge:8000"
GIT_BRIDGE_ROOT_DIR: "/data/git-bridge"
LOG_LEVEL: "DEBUG"
volumes:
- ./data/git-bridge:/data/git-bridge
+5
View File
@@ -14,6 +14,11 @@ module.exports = merge(base, {
target: 'http://real-time:3026',
ws: true,
},
{
context: '/git/**',
target: 'http://git-bridge:8000',
pathRewrite: { '^/git': '' }
},
{
context: ['!**/*.js', '!**/*.css', '!**/*.json'],
target: 'http://web:3000',
Binary file not shown.

Before

Width:  |  Height:  |  Size: 271 KiB

After

Width:  |  Height:  |  Size: 525 KiB

+1 -1
View File
@@ -33,7 +33,7 @@ services:
# IMPORTANT: Required for invite token generation
# OVERLEAF_INVITE_TOKEN_SECRET: generate with `openssl rand -base64 32`
ENABLED_LINKED_FILE_TYPES: "project_file,project_output_file"
ENABLED_LINKED_FILE_TYPES: "project_file,project_output_file,zotero"
# Enables Thumbnail generation using ImageMagick
ENABLE_CONVERSIONS: "true"
+3
View File
@@ -178,6 +178,8 @@
"fast-xml-builder": "1.1.7",
"fast-xml-parser": "5.7.3",
"ip-address": "10.1.1",
"ldapauth-fork@npm:^5.0.1": "patch:ldapauth-fork@npm%3A5.0.5#~/.yarn/patches/ldapauth-fork-npm-5.0.5-c8b86f5231.patch",
"@node-saml/node-saml@npm:^5.1.0": "patch:@node-saml/node-saml@npm%3A5.1.0#~/.yarn/patches/@node-saml-node-saml-npm-5.1.0-f4eb6913cc.patch",
"systeminformation": "5.31.6"
},
"scripts": {
@@ -212,6 +214,7 @@
"services/history-v1",
"services/idp",
"services/latexqc",
"services/linked-url-proxy",
"services/notifications",
"services/project-history",
"services/real-time",
+4 -2
View File
@@ -49,7 +49,7 @@ ADD server-ce/config/env.sh /etc/overleaf/env.sh
# Configure nginx
# ---------------
ADD server-ce/nginx/nginx.conf.template /etc/nginx/templates/nginx.conf.template
ADD server-ce/nginx/overleaf.conf /etc/nginx/sites-enabled/overleaf.conf
ADD server-ce/nginx/overleaf.conf.template /etc/nginx/templates/overleaf.conf.template
ADD server-ce/nginx/clsi-nginx.conf /etc/nginx/sites-enabled/clsi-nginx.conf
@@ -121,7 +121,9 @@ ENV GRACEFUL_SHUTDOWN_DELAY_SECONDS=1
ENV NODE_ENV="production"
ENV LOG_LEVEL="info"
ENV GIT_BRIDGE_HOST=git-bridge
ENV GIT_BRIDGE_PORT=8000
ENV GIT_BRIDGE_REPOSTORE_MAX_FILE_SIZE=52428800
EXPOSE 80
ENTRYPOINT ["/sbin/my_init"]
+2
View File
@@ -37,6 +37,7 @@ build-base:
--cache-from $(OVERLEAF_BASE_BRANCH) \
--tag $(OVERLEAF_BASE_TAG) \
--tag $(OVERLEAF_BASE_BRANCH) \
--network=host \
$(MONOREPO_ROOT)
@@ -52,6 +53,7 @@ build-community:
--file Dockerfile \
--tag $(OVERLEAF_TAG) \
--tag $(OVERLEAF_BRANCH) \
--network=host \
$(MONOREPO_ROOT)
push:
+1
View File
@@ -5,6 +5,7 @@ export DOCUMENT_UPDATER_HOST=127.0.0.1
export DOCUPDATER_HOST=127.0.0.1
export FILESTORE_HOST=127.0.0.1
export HISTORY_V1_HOST=127.0.0.1
export LINKED_URL_PROXY_HOST=127.0.0.1
export NOTIFICATIONS_HOST=127.0.0.1
export PROJECT_HISTORY_HOST=127.0.0.1
export REALTIME_HOST=127.0.0.1
+12 -1
View File
@@ -193,6 +193,8 @@ const settings = {
maintenanceMessage: process.env.OVERLEAF_MAINTENANCE_MESSAGE,
maintenanceMessageHTML: process.env.OVERLEAF_MAINTENANCE_MESSAGE_HTML,
enableRegiserPage: process.env.OVERLEAF_ENABLE_REGISTER_PAGE === 'true',
// The name this is used to describe your Overleaf Community Edition Installation
appName: process.env.OVERLEAF_APP_NAME || 'Overleaf Community Edition',
@@ -393,7 +395,16 @@ if (process.env.OVERLEAF_EMAIL_FROM_ADDRESS != null) {
}
if (
process.env.OVERLEAF_EMAIL_SMTP_USER != null ||
process.env.OVERLEAF_EMAIL_SMTP_USER != null &&
process.env.OVERLEAF_EMAIL_SMTP_PASS_FILE != null
) {
settings.email.parameters.auth = {
user: process.env.OVERLEAF_EMAIL_SMTP_USER,
pass: require("fs").readFileSync(process.env.OVERLEAF_EMAIL_SMTP_PASS_FILE, "utf8")
}
}
else if (
process.env.OVERLEAF_EMAIL_SMTP_USER != null &&
process.env.OVERLEAF_EMAIL_SMTP_PASS != null
) {
settings.email.parameters.auth = {
+13
View File
@@ -0,0 +1,13 @@
diff --git a/services/web/modules/authentication/saml/app/src/SAMLModuleManager.mjs b/services/web/modules/authentication/saml/app/src/SAMLModuleManager.mjs
index 29e9ae52cd..335ace8209 100644
--- a/services/web/modules/authentication/saml/app/src/SAMLModuleManager.mjs
+++ b/services/web/modules/authentication/saml/app/src/SAMLModuleManager.mjs
@@ -26,7 +26,7 @@ const SAMLModuleManager = {
callbackUrl: `${Settings.siteUrl.replace(/\/+$/, '')}/saml/login/callback`,
issuer: process.env.OVERLEAF_SAML_ISSUER,
audience: process.env.OVERLEAF_SAML_AUDIENCE,
- cert: readFilesContentFromEnv(process.env.OVERLEAF_SAML_IDP_CERT),
+ idpCert: readFilesContentFromEnv(process.env.OVERLEAF_SAML_IDP_CERT),
privateKey: readFilesContentFromEnv(process.env.OVERLEAF_SAML_PRIVATE_KEY),
decryptionPvk: readFilesContentFromEnv(process.env.OVERLEAF_SAML_DECRYPTION_PVK),
signatureAlgorithm: process.env.OVERLEAF_SAML_SIGNATURE_ALGORITHM,
+20
View File
@@ -0,0 +1,20 @@
FROM overleafcep/sharelatex:5.5.6-ext-v3.2
# add normalize and sanitize to linked-url-proxy
COPY *.patch* .
RUN bash -ec 'for p in *.patch; do echo "=== Applying $p ==="; patch -p1 < "$p" && rm $p; done' \
&& npm install als-normalize-urlpath@2.3.0 \
&& rm -f ./package.json.orig \
./services/history-v1/storage/scripts/back_fill_file_hash.mjs.orig \
./services/history-v1/test/acceptance/js/storage/back_fill_file_hash.test.mjs.orig \
./services/linked-url-proxy/app/js/LinkedUrlProxyController.mjs.orig \
./services/web/config/settings.defaults.js.orig \
./services/web/frontend/js/features/source-editor/components/toolbar/toolbar-items.tsx.orig \
./services/web/test/frontend/features/share-project-modal/components/share-project-modal.test.jsx.orig \
./services/web/package.json.orig \
./services/filestore/app.js.orig \
./package-lock.json.orig \
./package-lock.json.diff \
/etc/my_init.d/100_make_overleaf_data_dirs.sh.orig \
/etc/overleaf/settings.js.orig
@@ -0,0 +1,256 @@
diff --git a/package.json b/package.json
index 64fbd258ed..7cc3c7f9b3 100644
--- a/package.json
+++ b/package.json
@@ -66,6 +66,7 @@
"services/history-v1",
"services/idp",
"services/latexqc",
+ "services/linked-url-proxy",
"services/notifications",
"services/project-history",
"services/real-time",
diff --git a/services/linked-url-proxy/Dockerfile b/services/linked-url-proxy/Dockerfile
index 677006182c..7f2053f614 100644
--- a/services/linked-url-proxy/Dockerfile
+++ b/services/linked-url-proxy/Dockerfile
@@ -2,7 +2,7 @@
# Instead run bin/update_build_scripts from
# https://github.com/overleaf/internal/
-FROM node:20.18.2 AS base
+FROM node:22.18.0 AS base
WORKDIR /overleaf/services/linked-url-proxy
@@ -13,16 +13,20 @@ RUN mkdir /home/node/.config && chown node:node /home/node/.config
FROM base AS app
COPY package.json package-lock.json /overleaf/
+COPY libraries/fetch-utils/package.json /overleaf/libraries/fetch-utils/package.json
COPY libraries/logger/package.json /overleaf/libraries/logger/package.json
COPY libraries/metrics/package.json /overleaf/libraries/metrics/package.json
+COPY libraries/o-error/package.json /overleaf/libraries/o-error/package.json
COPY libraries/settings/package.json /overleaf/libraries/settings/package.json
COPY services/linked-url-proxy/package.json /overleaf/services/linked-url-proxy/package.json
COPY patches/ /overleaf/patches/
RUN cd /overleaf && npm ci --quiet
+COPY libraries/fetch-utils/ /overleaf/libraries/fetch-utils/
COPY libraries/logger/ /overleaf/libraries/logger/
COPY libraries/metrics/ /overleaf/libraries/metrics/
+COPY libraries/o-error/ /overleaf/libraries/o-error/
COPY libraries/settings/ /overleaf/libraries/settings/
COPY services/linked-url-proxy/ /overleaf/services/linked-url-proxy/
diff --git a/services/linked-url-proxy/app/js/LinkedUrlProxyController.mjs b/services/linked-url-proxy/app/js/LinkedUrlProxyController.mjs
index 1269eede0d..ea82f65d16 100644
--- a/services/linked-url-proxy/app/js/LinkedUrlProxyController.mjs
+++ b/services/linked-url-proxy/app/js/LinkedUrlProxyController.mjs
@@ -1,4 +1,6 @@
import dns from 'dns/promises'
+import { sanitizeUrl } from 'strict-url-sanitise'
+import normalizeUrlPath from 'als-normalize-urlpath'
import ipaddr from 'ipaddr.js'
import { URL } from 'node:url'
import { Transform } from 'node:stream'
@@ -18,15 +20,7 @@ function isBlockedIp(ipStr, targetUrl) {
}
const range = addr.range()
- if ([
- 'loopback',
- 'private',
- 'linkLocal',
- 'multicast',
- 'reserved',
- 'broadcast',
- 'unspecified'
- ].includes(range)) {
+ if (!['unicast'].includes(addr.range())) {
return true
}
@@ -44,7 +38,7 @@ function isBlockedIp(ipStr, targetUrl) {
return false
}
-async function validateSourceUrl(hostname, targetUrl) {
+async function checkUrlAccess(hostname, targetUrl) {
const records = await dns.lookup(hostname, { all: true }).catch(() => [])
if (!records.length) {
const err = new Error(`DNS lookup failed for ${hostname}`)
@@ -62,22 +56,40 @@ async function validateSourceUrl(hostname, targetUrl) {
}
}
-async function fetchValidated(urlStr, redirectCount = 0) {
+async function validateAndFetch(rawUrl, redirectCount = 0) {
if (redirectCount > Settings.maxRedirects) {
const err = new Error('Too many redirects')
err.info = { status: 421 }
throw err
}
- const url = new URL(urlStr)
+ const sanitizedUrl = sanitizeUrl(rawUrl)
+ if (!sanitizedUrl) {
+ const err = new Error(`Invalid or unsafe URL: ${rawUrl}`)
+ err.info = { status: 400 }
+ throw err
+ }
+
+ const url = new URL(sanitizedUrl)
+
if (!['http:', 'https:'].includes(url.protocol)) {
const err = new Error(`${url.protocol} protocol is not allowed`)
err.info = { status: 400 }
throw err
}
- // Validate DNS and blocked IPs
- await validateSourceUrl(url.hostname, urlStr)
+ const normalizedPath = normalizeUrlPath(url.pathname).pathname
+
+ if (!normalizedPath) {
+ const err = new Error(`Invalid or unsafe URL path: ${url.pathname}`)
+ err.info = { status: 400 }
+ throw err
+ }
+
+ const normalizedUrl = url.toString()
+
+ // check DNS and allowed resources
+ await checkUrlAccess(url.hostname, normalizedUrl)
const opts = {
redirect: 'manual',
@@ -86,7 +98,7 @@ async function fetchValidated(urlStr, redirectCount = 0) {
}
try {
- const { stream, response } = await fetchStreamWithResponse(urlStr, opts)
+ const { stream, response } = await fetchStreamWithResponse(normalizedUrl, opts)
const contentLengthHeader = response.headers.get('content-length')
if (contentLengthHeader) {
@@ -112,8 +124,8 @@ async function fetchValidated(urlStr, redirectCount = 0) {
if (status >= 300 && status < 400) {
const location = err.response.headers.get('Location')
if (location) {
- const nextUrl = new URL(location, url).toString()
- return fetchValidated(nextUrl, redirectCount + 1)
+ const nextUrl = new URL(location, normalizedUrl).toString()
+ return validateAndFetch(nextUrl, redirectCount + 1)
} else {
const e = new Error('Redirect response missing Location header')
e.info = { status: 421 }
@@ -141,14 +153,14 @@ async function proxy(req, res) {
return
}
- const { stream: upstreamStream, response, headers } = await fetchValidated(targetUrl)
+ const { stream: upstreamStream, response, headers } = await validateAndFetch(targetUrl)
res.statusCode = response.status || 200
res.setHeader('Content-Type', headers['content-type'] || 'application/octet-stream')
res.setHeader('Cache-Control', 'no-store')
function onError(err) {
- logger.warn({ err, url: req.url }, 'linked-url-proxy request failed')
+ logger.info({ err, url: req.url }, 'linked-url-proxy request failed')
try { upstreamStream.destroy() } catch (_) {}
if (!res.headersSent) {
let body = `Error: ${err?.message ?? String(err)}`
@@ -163,11 +175,9 @@ async function proxy(req, res) {
upstreamStream.pipe(res)
} catch (err) {
- logger.warn({ err, url: req.url }, 'linked-url-proxy request failed')
-
- let status = err.info.status
+ const status = err.info?.status || 500
+ logger.info({ linkedUrl: err.message, status, url: req.url }, 'linked-url-proxy request failed')
let body = `Error: ${err.message || String(err)}`
-
try {
res.writeHead(status, { 'Content-Type': 'text/plain' })
res.end(body)
diff --git a/services/linked-url-proxy/package.json b/services/linked-url-proxy/package.json
index 845551c8ef..8081a80822 100644
--- a/services/linked-url-proxy/package.json
+++ b/services/linked-url-proxy/package.json
@@ -2,18 +2,24 @@
"name": "@overleaf/linked-url-proxy",
"description": "An API for providing linked url proxy",
"private": true,
- "type": "module",
"main": "app.mjs",
"scripts": {
- "start": "node app.mjs"
+ "start": "node app.mjs",
+ "nodemon": "node --watch app.mjs"
},
- "version": "0.1.0",
+ "version": "0.1.1",
"dependencies": {
"@overleaf/settings": "*",
"@overleaf/logger": "*",
"@overleaf/metrics": "*",
"async": "^3.2.5",
- "express": "^4.21.2"
- "ipaddr.js": "^1.9.1"
+ "express": "^4.21.2",
+ "ipaddr.js": "^1.9.1",
+ "als-normalize-urlpath": "^2.3.0",
+ "strict-url-sanitise": "^0.0.1"
+ },
+ "devDependencies": {
+ "als-normalize-urlpath": "^2.3.0",
+ "strict-url-sanitise": "^0.0.1"
}
}
diff --git a/services/linked-url-proxy/tsconfig.json b/services/linked-url-proxy/tsconfig.json
index c018d6e682..0639496cc8 100644
--- a/services/linked-url-proxy/tsconfig.json
+++ b/services/linked-url-proxy/tsconfig.json
@@ -1,7 +1,7 @@
{
"extends": "../../tsconfig.backend.json",
"include": [
- "app.js",
+ "app.mjs",
"app.ts",
"app/js/**/*",
"benchmarks/**/*",
diff --git a/services/web/package.json b/services/web/package.json
index 21da1188a2..c2c4fcfaba 100644
--- a/services/web/package.json
+++ b/services/web/package.json
@@ -69,6 +69,7 @@
"last 1 year",
"safari > 14"
],
+
"dependencies": {
"@contentful/rich-text-html-renderer": "^16.0.2",
"@contentful/rich-text-types": "^16.0.2",
@@ -92,6 +93,7 @@
"@xmldom/xmldom": "^0.7.13",
"accepts": "^1.3.7",
"ajv": "^8.12.0",
+ "als-normalize-urlpath": "^2.3.0",
"archiver": "^5.3.0",
"async": "^3.2.5",
"base-x": "^4.0.1",
@@ -166,7 +168,8 @@
"request": "^2.88.2",
"requestretry": "^7.1.0",
"sanitize-html": "^2.8.1",
- "stripe": "^18.1.0",
+ "strict-url-sanitise": "^0.0.1",
+ "stripe": "^18.4.0",
"tough-cookie": "^4.0.0",
"tsscmp": "^1.0.6",
"uid-safe": "^2.1.5",
@@ -16,11 +16,18 @@ fi
nginx_template_file="${nginx_templates_dir}/nginx.conf.template"
nginx_config_file="${nginx_dir}/nginx.conf"
overleaf_template_file="${nginx_templates_dir}/overleaf.conf.template"
overleaf_config_file="${nginx_dir}/sites-enabled/overleaf.conf"
if [ -f "${nginx_template_file}" ]; then
export NGINX_KEEPALIVE_TIMEOUT="${NGINX_KEEPALIVE_TIMEOUT:-65}"
export NGINX_WORKER_CONNECTIONS="${NGINX_WORKER_CONNECTIONS:-768}"
export NGINX_WORKER_PROCESSES="${NGINX_WORKER_PROCESSES:-4}"
export MAX_UPLOAD_SIZE="${MAX_UPLOAD_SIZE:-50}"
export GIT_BRIDGE_HOST="${GIT_BRIDGE_HOST:-git-bridge}"
export GIT_BRIDGE_PORT="${GIT_BRIDGE_PORT:-8000}"
export GIT_BRIDGE_REPOSTORE_MAX_FILE_SIZE="${GIT_BRIDGE_REPOSTORE_MAX_FILE_SIZE:-52428800}"
echo "Nginx: generating config file from template"
# Note the single-quotes, they are important.
@@ -31,10 +38,20 @@ if [ -f "${nginx_template_file}" ]; then
${NGINX_KEEPALIVE_TIMEOUT}
${NGINX_WORKER_CONNECTIONS}
${NGINX_WORKER_PROCESSES}
${MAX_UPLOAD_SIZE}
' \
< "${nginx_template_file}" \
> "${nginx_config_file}"
# Config git-bridge in nginx
envsubst '
${GIT_BRIDGE_HOST}
${GIT_BRIDGE_PORT}
${GIT_BRIDGE_REPOSTORE_MAX_FILE_SIZE}
' \
< "${overleaf_template_file}" \
> "${overleaf_config_file}"
echo "Checking Nginx config"
nginx -t
+2 -2
View File
@@ -34,8 +34,8 @@ server {
root /var/lib/overleaf/data/output/$1-$2/generated-files/$3/;
}
# handle output files for anonymous users
location ~ ^/project/([0-9a-f]+)/build/([0-9a-f-]+)/output/(.+)$ {
rewrite ^/project/([0-9a-f]+)/build/([0-9a-f-]+)/output/(.+)$ /$3 break;
location ~ ^/project/([0-9a-f-]+)/build/([0-9a-f-]+)/output/(.+)$ {
rewrite ^/project/([0-9a-f-]+)/build/([0-9a-f-]+)/output/(.+)$ /$3 break;
root /var/lib/overleaf/data/output/$1/generated-files/$2/;
}
+1 -1
View File
@@ -46,7 +46,7 @@ http {
gzip_disable "msie6";
gzip_proxied any; # allow upstream server to compress.
client_max_body_size 50m;
client_max_body_size ${MAX_UPLOAD_SIZE}m;
# gzip_vary on;
# gzip_proxied any;
@@ -21,6 +21,23 @@ server {
proxy_send_timeout 10m;
}
location ^~ /git/ {
resolver_timeout 2s;
resolver 127.0.0.11 valid=10s;
set $git_upstream http://${GIT_BRIDGE_HOST}:${GIT_BRIDGE_PORT};
rewrite ^/git/(.*)$ /$1 break;
client_max_body_size ${GIT_BRIDGE_REPOSTORE_MAX_FILE_SIZE};
proxy_pass $git_upstream;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 10m;
proxy_send_timeout 10m;
}
location /socket.io {
proxy_pass http://127.0.0.1:3026;
proxy_http_version 1.1;
+12
View File
@@ -0,0 +1,12 @@
#!/bin/bash
NODE_PARAMS=""
if [ "$DEBUG_NODE" == "true" ]; then
echo "running debug - linked-url-proxy"
NODE_PARAMS="--inspect=0.0.0.0:30660"
fi
source /etc/overleaf/env.sh
export LISTEN_ADDRESS=127.0.0.1
exec /sbin/setuser www-data /usr/bin/node $NODE_PARAMS /overleaf/services/linked-url-proxy/app.mjs >> /var/log/overleaf/linked-url-proxy.log 2>&1
+3
View File
@@ -29,6 +29,9 @@ module.exports = [
{
name: 'history-v1',
},
{
name: 'linked-url-proxy',
},
]
if (require.main === module) {
+1 -1
View File
@@ -19,7 +19,7 @@ services:
OVERLEAF_EMAIL_SMTP_HOST: "mailtrap"
OVERLEAF_EMAIL_SMTP_PORT: "25"
OVERLEAF_EMAIL_SMTP_IGNORE_TLS: "true"
ENABLED_LINKED_FILE_TYPES: "project_file,project_output_file"
ENABLED_LINKED_FILE_TYPES: "project_file,project_output_file,zotero"
ENABLE_CONVERSIONS: "true"
EMAIL_CONFIRMATION_DISABLED: "true"
OVERLEAF_INVITE_TOKEN_SECRET: "invite-token-secret"
+1 -1
View File
@@ -29,7 +29,7 @@ The CLSI can be configured through the following environment variables:
- `PROCESS_LIFE_SPAN_LIMIT_MS` - Process life span limit in milliseconds
- `SMOKE_TEST` - Whether to run smoke tests
- `TEXLIVE_IMAGE` - The TeX Live Docker image to use for sibling containers, e.g. `us-east1-docker.pkg.dev/overleaf-ops/ol-docker/texlive-full:2025.1`
- `TEX_LIVE_IMAGE_NAME_OVERRIDE` - The name of the registry for the Docker image e.g. `us-east1-docker.pkg.dev/overleaf-ops/ol-docker`
- `TEX_LIVE_DOCKER_IMAGE_ROOT` - The name of the registry for the Docker image e.g. `us-east1-docker.pkg.dev/overleaf-ops/ol-docker`
- `TEXLIVE_IMAGE_USER` - When using sibling containers, the user to run as in the TeX Live image. Defaults to `tex`
- `TEXLIVE_OPENOUT_ANY` - Sets the `openout_any` environment variable for TeX Live (see the `\openout` primitive [documentation](http://tug.org/texinfohtml/web2c.html#tex-invocation))
+1 -1
View File
@@ -10,7 +10,7 @@ import logger from '@overleaf/logger'
let commandRunnerPath
if ((Settings.clsi != null ? Settings.clsi.dockerRunner : undefined) === true) {
commandRunnerPath = './DockerRunner.js'
commandRunnerPath = './DockerRunner.mjs'
} else {
commandRunnerPath = './LocalCommandRunner.js'
}
+110
View File
@@ -0,0 +1,110 @@
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import logger from '@overleaf/logger'
let LockManager
const LockState = {} // locks for docker container operations, by container name
export default LockManager = {
MAX_LOCK_HOLD_TIME: 15000, // how long we can keep a lock
MAX_LOCK_WAIT_TIME: 10000, // how long we wait for a lock
LOCK_TEST_INTERVAL: 1000, // retry time
tryLock(key, callback) {
let lockValue
if (callback == null) {
callback = function () {}
}
const existingLock = LockState[key]
if (existingLock != null) {
// the lock is already taken, check how old it is
const lockAge = Date.now() - existingLock.created
if (lockAge < LockManager.MAX_LOCK_HOLD_TIME) {
return callback(null, false) // we didn't get the lock, bail out
} else {
logger.error(
{ key, lock: existingLock, age: lockAge },
'taking old lock by force'
)
}
}
// take the lock
LockState[key] = lockValue = { created: Date.now() }
return callback(null, true, lockValue)
},
getLock(key, callback) {
let attempt
if (callback == null) {
callback = function () {}
}
const startTime = Date.now()
return (attempt = () =>
LockManager.tryLock(key, function (error, gotLock, lockValue) {
if (error != null) {
return callback(error)
}
if (gotLock) {
return callback(null, lockValue)
} else if (Date.now() - startTime > LockManager.MAX_LOCK_WAIT_TIME) {
const e = new Error('Lock timeout')
e.key = key
return callback(e)
} else {
return setTimeout(attempt, LockManager.LOCK_TEST_INTERVAL)
}
}))()
},
releaseLock(key, lockValue, callback) {
if (callback == null) {
callback = function () {}
}
const existingLock = LockState[key]
if (existingLock === lockValue) {
// lockValue is an object, so we can test by reference
delete LockState[key] // our lock, so we can free it
return callback()
} else if (existingLock != null) {
// lock exists but doesn't match ours
logger.error(
{ key, lock: existingLock },
'tried to release lock taken by force'
)
return callback()
} else {
logger.error(
{ key, lock: existingLock },
'tried to release lock that has gone'
)
return callback()
}
},
runWithLock(key, runner, callback) {
if (callback == null) {
callback = function () {}
}
return LockManager.getLock(key, function (error, lockValue) {
if (error != null) {
return callback(error)
}
return runner((error1, ...args) =>
LockManager.releaseLock(key, lockValue, function (error2) {
error = error1 || error2
if (error != null) {
return callback(error)
}
return callback(null, ...Array.from(args))
})
)
})
},
}
+630
View File
@@ -0,0 +1,630 @@
import { promisify } from 'node:util'
import Settings from '@overleaf/settings'
import logger from '@overleaf/logger'
import Docker from 'dockerode'
import crypto from 'node:crypto'
import async from 'async'
import LockManager from './DockerLockManager.js'
import Path from 'node:path'
import _ from 'lodash'
import { getLastProjectAccessTime } from './LastProjectAccess.js'
const dockerode = new Docker()
const ONE_HOUR_IN_MS = 60 * 60 * 1000
logger.debug('using docker runner')
let containerMonitorTimeout
let containerMonitorInterval
const DockerRunner = {
run(
projectId,
command,
directory,
image,
timeout,
environment,
compileGroup,
cwd,
callback
) {
command = command.map(arg =>
arg.toString().replace('$COMPILE_DIR', '/compile')
)
if (image == null) {
image = Settings.clsi.docker.image
}
if (
Settings.clsi.docker.allowedImages &&
!Settings.clsi.docker.allowedImages.includes(image)
) {
return callback(new Error('image not allowed'))
}
if (Settings.texliveImageNameOveride != null) {
const img = Path.basename(image)
image = `${Settings.texliveImageNameOveride}/${img}`
}
if (compileGroup === 'synctex-output') {
// In: directory = '/overleaf/services/clsi/output/projectId-userId/generated-files/buildId'
// directory.split('/').slice(-3) === 'projectId-userId/generated-files/buildId'
// sandboxedCompilesHostDirOutput = '/host/output'
// Out: directory = '/host/output/projectId-userId/generated-files/buildId'
directory = Path.join(
Settings.path.sandboxedCompilesHostDirOutput,
...directory.split('/').slice(-3)
)
} else {
// In: directory = '/overleaf/services/clsi/compiles/projectId-userId'
// Path.basename(directory) === 'projectId-userId'
// sandboxedCompilesHostDirCompiles = '/host/compiles'
// Out: directory = '/host/compiles/projectId-userId'
directory = Path.join(
Settings.path.sandboxedCompilesHostDirCompiles,
Path.basename(directory)
)
}
const volumes = { [directory]: '/compile' }
if (
compileGroup === 'synctex' ||
compileGroup === 'synctex-output' ||
compileGroup === 'wordcount'
) {
volumes[directory] += ':ro'
}
const options = DockerRunner._getContainerOptions(
command,
image,
volumes,
timeout,
environment,
compileGroup,
cwd
)
const fingerprint = DockerRunner._fingerprintContainer(options)
const name = `project-${projectId}-${fingerprint}`
options.name = name
// logOptions = _.clone(options)
// logOptions?.HostConfig?.SecurityOpt = "secomp used, removed in logging"
logger.debug({ projectId }, 'running docker container')
DockerRunner._runAndWaitForContainer(
options,
volumes,
timeout,
(error, output) => {
if (error && error.statusCode === 500) {
logger.debug(
{ err: error, projectId },
'error running container so destroying and retrying'
)
DockerRunner.destroyContainer(name, null, true, error => {
if (error != null) {
return callback(error)
}
DockerRunner._runAndWaitForContainer(
options,
volumes,
timeout,
callback
)
})
} else {
callback(error, output)
}
}
)
// pass back the container name to allow it to be killed
return name
},
kill(containerId, callback) {
logger.debug({ containerId }, 'sending kill signal to container')
const container = dockerode.getContainer(containerId)
container.kill(error => {
if (
error != null &&
error.message != null &&
error.message.match(/Cannot kill container .* is not running/)
) {
logger.warn(
{ err: error, containerId },
'container not running, continuing'
)
error = null
}
if (error != null) {
logger.error({ err: error, containerId }, 'error killing container')
callback(error)
} else {
callback()
}
})
},
_runAndWaitForContainer(options, volumes, timeout, _callback) {
const callback = _.once(_callback)
const { name } = options
let streamEnded = false
let containerReturned = false
let output = {}
function callbackIfFinished() {
if (streamEnded && containerReturned) {
callback(null, output)
}
}
function attachStreamHandler(error, _output) {
if (error != null) {
return callback(error)
}
output = _output
streamEnded = true
callbackIfFinished()
}
DockerRunner.startContainer(
options,
volumes,
attachStreamHandler,
(error, containerId) => {
if (error != null) {
return callback(error)
}
DockerRunner.waitForContainer(
name,
timeout,
options,
(error, exitCode) => {
if (error != null) {
return callback(error)
}
if (exitCode === 137) {
// exit status from kill -9
const err = new Error('terminated')
err.terminated = true
return callback(err)
}
if (exitCode === 1) {
// exit status from chktex
const err = new Error('exited')
err.code = exitCode
return callback(err)
}
output.exitCode = exitCode
containerReturned = true
logger.debug(
// The seccomp policy is very large. Avoid logging it. _.omit deep clones.
{ exitCode, options: _.omit(options, 'HostConfig.SecurityOpt') },
'docker container has exited'
)
callbackIfFinished()
}
)
}
)
},
_getContainerOptions(
command,
image,
volumes,
timeout,
environment,
compileGroup,
cwd
) {
const timeoutInSeconds = timeout / 1000
for (const hostVol in volumes) {
const dockerVol = volumes[hostVol]
if (volumes[hostVol].slice(-3).indexOf(':r') === -1) {
volumes[hostVol] = `${dockerVol}:rw`
}
}
// merge settings and environment parameter
const env = {}
for (const src of [Settings.clsi.docker.env, environment || {}]) {
for (const key in src) {
const value = src[key]
env[key] = value
}
}
// set the path based on the image year
const match = image.match(/:([0-9]+)\.[0-9]+|:TL([0-9]+)/)
// the rolling build does not follow our <year>.<version>.<patch> convention
const year = match ? match[1] || match[2] : 'rolling'
env.PATH = `/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/texlive/${year}/bin/x86_64-linux/`
const options = {
Cmd: command,
Image: image,
WorkingDir: cwd
? Path.posix.join('/compile', cwd)
: '/compile',
NetworkDisabled: true,
Memory: 1024 * 1024 * 1024 * 1024, // 1 Gb
User: Settings.clsi.docker.user,
Env: Object.entries(env).map(([key, value]) => `${key}=${value}`),
HostConfig: {
Binds: Object.entries(volumes).map(
([hostVol, dockerVol]) => `${hostVol}:${dockerVol}`
),
LogConfig: { Type: 'none', Config: {} },
Ulimits: [
{
Name: 'cpu',
Soft: timeoutInSeconds + 5,
Hard: timeoutInSeconds + 10,
},
],
CapDrop: ['ALL'],
SecurityOpt: ['no-new-privileges'],
},
}
if (Settings.clsi.docker.seccomp_profile != null) {
options.HostConfig.SecurityOpt.push(
`seccomp=${Settings.clsi.docker.seccomp_profile}`
)
}
if (Settings.clsi.docker.apparmor_profile != null) {
options.HostConfig.SecurityOpt.push(
`apparmor=${Settings.clsi.docker.apparmor_profile}`
)
}
if (Settings.clsi.docker.runtime) {
options.HostConfig.Runtime = Settings.clsi.docker.runtime
}
if (Settings.clsi.docker.Readonly) {
options.HostConfig.ReadonlyRootfs = true
options.HostConfig.Tmpfs = { '/tmp': 'rw,noexec,nosuid,size=65536k' }
options.Volumes['/home/tex'] = {}
}
// Allow per-compile group overriding of individual settings
if (
Settings.clsi.docker.compileGroupConfig &&
Settings.clsi.docker.compileGroupConfig[compileGroup]
) {
const override = Settings.clsi.docker.compileGroupConfig[compileGroup]
for (const key in override) {
_.set(options, key, override[key])
}
}
return options
},
_fingerprintContainer(containerOptions) {
// Yay, Hashing!
const json = JSON.stringify(containerOptions)
return crypto.createHash('md5').update(json).digest('hex')
},
startContainer(options, volumes, attachStreamHandler, callback) {
LockManager.runWithLock(
options.name,
releaseLock =>
DockerRunner._startContainer(
options,
volumes,
attachStreamHandler,
releaseLock
),
callback
)
},
// Check that volumes exist and are directories
_startContainer(options, volumes, attachStreamHandler, callback) {
callback = _.once(callback)
const { name } = options
logger.debug({ containerName: name }, 'starting container')
const container = dockerode.getContainer(name)
function createAndStartContainer() {
dockerode.createContainer(options, (error, container) => {
if (error != null) {
return callback(error)
}
startExistingContainer()
})
}
function startExistingContainer() {
DockerRunner.attachToContainer(
options.name,
attachStreamHandler,
error => {
if (error != null) {
return callback(error)
}
container.start(error => {
if (error != null && error.statusCode !== 304) {
callback(error)
} else {
// already running
callback()
}
})
}
)
}
container.inspect((error, stats) => {
if (error != null && error.statusCode === 404) {
createAndStartContainer()
} else if (error != null) {
logger.err(
{ containerName: name, error },
'unable to inspect container to start'
)
callback(error)
} else {
startExistingContainer()
}
})
},
attachToContainer(containerId, attachStreamHandler, attachStartCallback) {
const container = dockerode.getContainer(containerId)
container.attach({ stdout: 1, stderr: 1, stream: 1 }, (error, stream) => {
if (error != null) {
logger.error(
{ err: error, containerId },
'error attaching to container'
)
return attachStartCallback(error)
} else {
attachStartCallback()
}
logger.debug({ containerId }, 'attached to container')
const MAX_OUTPUT = 1024 * 1024 * 2 // limit output to 2MB
function createStringOutputStream(name) {
return {
data: '',
overflowed: false,
write(data) {
if (this.overflowed) {
return
}
if (this.data.length < MAX_OUTPUT) {
this.data += data
} else {
logger.info(
{
containerId,
length: this.data.length,
maxLen: MAX_OUTPUT,
},
`${name} exceeds max size`
)
this.data += `(...truncated at ${MAX_OUTPUT} chars...)`
this.overflowed = true
}
},
// kill container if too much output
// docker.containers.kill(containerId, () ->)
}
}
const stdout = createStringOutputStream('stdout')
const stderr = createStringOutputStream('stderr')
container.modem.demuxStream(stream, stdout, stderr)
stream.on('error', err =>
logger.error(
{ err, containerId },
'error reading from container stream'
)
)
stream.on('end', () =>
attachStreamHandler(null, { stdout: stdout.data, stderr: stderr.data })
)
})
},
waitForContainer(containerId, timeout, options, _callback) {
const callback = _.once(_callback)
const container = dockerode.getContainer(containerId)
let timedOut = false
const timeoutId = setTimeout(() => {
timedOut = true
logger.debug({ containerId }, 'timeout reached, killing container')
container.kill(err => {
logger.warn({ err, containerId }, 'failed to kill container')
})
}, timeout)
logger.debug({ containerId }, 'waiting for docker container')
container.wait((error, res) => {
if (error?.statusCode === 404 && options.HostConfig.AutoRemove) {
logger.debug(
{ containerId },
'auto-destroy container destroyed before starting to wait'
)
clearTimeout(timeoutId)
return callback(null, 0)
}
if (error != null) {
clearTimeout(timeoutId)
logger.warn({ err: error, containerId }, 'error waiting for container')
return callback(error)
}
if (timedOut) {
logger.debug({ containerId }, 'docker container timed out')
error = new Error('container timed out')
error.timedout = true
callback(error)
} else {
clearTimeout(timeoutId)
logger.debug(
{ containerId, exitCode: res.StatusCode },
'docker container returned'
)
callback(null, res.StatusCode)
}
})
},
destroyContainer(containerName, containerId, shouldForce, callback) {
// We want the containerName for the lock and, ideally, the
// containerId to delete. There is a bug in the docker.io module
// where if you delete by name and there is an error, it throws an
// async exception, but if you delete by id it just does a normal
// error callback. We fall back to deleting by name if no id is
// supplied.
LockManager.runWithLock(
containerName,
releaseLock =>
DockerRunner._destroyContainer(
containerId || containerName,
shouldForce,
releaseLock
),
callback
)
},
_destroyContainer(containerId, shouldForce, callback) {
logger.debug({ containerId }, 'destroying docker container')
const container = dockerode.getContainer(containerId)
container.remove({ force: shouldForce === true, v: true }, error => {
if (error != null && error.statusCode === 404) {
logger.warn(
{ err: error, containerId },
'container not found, continuing'
)
error = null
}
if (error != null) {
logger.error({ err: error, containerId }, 'error destroying container')
} else {
logger.debug({ containerId }, 'destroyed container')
}
callback(error)
})
},
// handle expiry of docker containers
MAX_CONTAINER_AGE: Settings.clsi.docker.maxContainerAge || ONE_HOUR_IN_MS,
examineOldContainer(container, callback) {
const name = container.Name || (container.Names && container.Names[0])
const created = container.Created * 1000 // creation time is returned in seconds
const now = Date.now()
const age = now - created
const maxAge = DockerRunner.MAX_CONTAINER_AGE
const ttl = maxAge - age
logger.debug(
{ containerName: name, created, now, age, maxAge, ttl },
'checking whether to destroy container'
)
return { name, id: container.Id, ttl }
},
destroyOldContainers(callback) {
dockerode.listContainers({ all: true }, (error, containers) => {
if (error != null) {
return callback(error)
}
const jobs = []
for (const container of containers) {
const { name, id, ttl } = DockerRunner.examineOldContainer(container)
if (name.slice(0, 9) === '/project-' && ttl <= 0) {
// extract projectId: /project-<projectId>-...
const match = name.match(/^\/project-([a-f0-9]{24})-/)
const projectId = match && match[1]
if (projectId != null) {
const lastAccess = getLastProjectAccessTime(projectId)
// if last access time is missing, lastAccess === 0, container will be destroyed
// provided that MAX_CONTAINER_AGE is less that 56 years, but anyway, let's check it
if (lastAccess && lastAccess > Date.now() - DockerRunner.MAX_CONTAINER_AGE) {
continue
}
}
// strip the / prefix
// the LockManager uses the plain container name
const plainName = name.slice(1)
jobs.push(cb =>
DockerRunner.destroyContainer(plainName, id, false, () => cb())
)
}
}
// Ignore errors because some containers get stuck but
// will be destroyed next time
async.series(jobs, callback)
})
},
startContainerMonitor() {
logger.debug(
{ maxAge: DockerRunner.MAX_CONTAINER_AGE },
'starting container expiry'
)
// guarantee only one monitor is running
DockerRunner.stopContainerMonitor()
// randomise the start time
const randomDelay = Math.floor(Math.random() * 5 * 60 * 1000)
containerMonitorTimeout = setTimeout(() => {
containerMonitorInterval = setInterval(
() =>
DockerRunner.destroyOldContainers(err => {
if (err) {
logger.error({ err }, 'failed to destroy old containers')
}
}),
ONE_HOUR_IN_MS
)
}, randomDelay)
},
stopContainerMonitor() {
if (containerMonitorTimeout) {
clearTimeout(containerMonitorTimeout)
containerMonitorTimeout = undefined
}
if (containerMonitorInterval) {
clearInterval(containerMonitorInterval)
containerMonitorInterval = undefined
}
},
canRunSyncTeXInOutputDir() {
return Boolean(Settings.path.sandboxedCompilesHostDirOutput)
},
}
DockerRunner.startContainerMonitor()
DockerRunner.promises = {
run: promisify(DockerRunner.run),
kill: promisify(DockerRunner.kill),
}
export default DockerRunner
+1 -1
View File
@@ -1,7 +1,7 @@
clsi
--data-dirs=cache,compiles,output
--dependencies=
--env-add=DOWNLOAD_HOST=http://clsi-nginx:8080,ALLOWED_COMPILE_GROUPS=clsi-perf simple-latex-file,ENABLE_PDF_CACHING=true,PDF_CACHING_ENABLE_WORKER_POOL=true,ALLOWED_IMAGES=quay.io/sharelatex/texlive-full:2017.1 quay.io/sharelatex/texlive-full:2025.1 quay.io/sharelatex/pandoc:3.9 quay.io/sharelatex/pdftocairo:24.02,TEXLIVE_IMAGE=quay.io/sharelatex/texlive-full:2025.1,TEX_LIVE_IMAGE_NAME_OVERRIDE=us-east1-docker.pkg.dev/overleaf-ops/ol-docker,TEXLIVE_IMAGE_USER=tex,SANDBOXED_COMPILES=true,SANDBOXED_COMPILES_HOST_DIR_COMPILES=$PWD/compiles,SANDBOXED_COMPILES_HOST_DIR_OUTPUT=$PWD/output,ENABLE_PANDOC_CONVERSIONS=true,ENABLE_PDF_CONVERSIONS=true
--env-add=DOWNLOAD_HOST=http://clsi-nginx:8080,ALLOWED_COMPILE_GROUPS=clsi-perf simple-latex-file,ENABLE_PDF_CACHING=true,PDF_CACHING_ENABLE_WORKER_POOL=true,ALLOWED_IMAGES=quay.io/sharelatex/texlive-full:2017.1 quay.io/sharelatex/texlive-full:2025.1 quay.io/sharelatex/pandoc:3.9 quay.io/sharelatex/pdftocairo:24.02,TEXLIVE_IMAGE=quay.io/sharelatex/texlive-full:2025.1,TEX_LIVE_DOCKER_IMAGE_ROOT=us-east1-docker.pkg.dev/overleaf-ops/ol-docker,TEXLIVE_IMAGE_USER=tex,SANDBOXED_COMPILES=true,SANDBOXED_COMPILES_HOST_DIR_COMPILES=$PWD/compiles,SANDBOXED_COMPILES_HOST_DIR_OUTPUT=$PWD/output,ENABLE_PANDOC_CONVERSIONS=true,ENABLE_PDF_CONVERSIONS=true
--env-pass-through=
--esmock-loader=False
--node-version=24.14.1
+4 -4
View File
@@ -92,7 +92,7 @@ module.exports = {
parallelFileDownloads:
parseInt(process.env.FILESTORE_PARALLEL_FILE_DOWNLOADS, 10) || 1,
filestoreDomainOveride: process.env.FILESTORE_DOMAIN_OVERRIDE,
texliveImageNameOveride: process.env.TEX_LIVE_IMAGE_NAME_OVERRIDE,
texliveImageNameOveride: process.env.TEX_LIVE_DOCKER_IMAGE_ROOT,
texliveOpenoutAny: process.env.TEXLIVE_OPENOUT_ANY,
texliveMaxPrintLine: process.env.TEXLIVE_MAX_PRINT_LINE,
enablePdfCaching: process.env.ENABLE_PDF_CACHING === 'true',
@@ -124,7 +124,7 @@ if (process.env.ALLOWED_COMPILE_GROUPS) {
if ((process.env.DOCKER_RUNNER || process.env.SANDBOXED_COMPILES) === 'true') {
if (
!fs.existsSync(Path.join(__dirname, '..', 'app', 'js', 'DockerRunner.js'))
!fs.existsSync(Path.join(__dirname, '..', 'app', 'js', 'DockerRunner.mjs'))
) {
console.error(
'Sandboxed compiles are only available with Overleaf Server Pro. Compare Server Pro with Community Edition here: https://docs.overleaf.com/on-premises/welcome/server-pro-vs.-community-edition'
@@ -139,13 +139,13 @@ if ((process.env.DOCKER_RUNNER || process.env.SANDBOXED_COMPILES) === 'true') {
image:
process.env.TEXLIVE_IMAGE ||
process.env.TEX_LIVE_DOCKER_IMAGE ||
'quay.io/sharelatex/texlive-full:2017.1',
process.env.ALL_TEX_LIVE_DOCKER_IMAGES.split(',')[0].trim(),
env: {
HOME: '/tmp',
CLSI: 1,
},
socketPath: '/var/run/docker.sock',
user: process.env.TEXLIVE_IMAGE_USER || 'tex',
user: process.env.TEXLIVE_IMAGE_USER || 'www-data',
},
optimiseInDocker: true,
expireProjectAfterIdleMs: 24 * 60 * 60 * 1000,
+1 -1
View File
@@ -32,7 +32,7 @@ services:
PDF_CACHING_ENABLE_WORKER_POOL: true
ALLOWED_IMAGES: quay.io/sharelatex/texlive-full:2017.1 quay.io/sharelatex/texlive-full:2025.1 quay.io/sharelatex/pandoc:3.9 quay.io/sharelatex/pdftocairo:24.02
TEXLIVE_IMAGE: quay.io/sharelatex/texlive-full:2025.1
TEX_LIVE_IMAGE_NAME_OVERRIDE: us-east1-docker.pkg.dev/overleaf-ops/ol-docker
TEX_LIVE_DOCKER_IMAGE_ROOT: us-east1-docker.pkg.dev/overleaf-ops/ol-docker
TEXLIVE_IMAGE_USER: tex
SANDBOXED_COMPILES: true
SANDBOXED_COMPILES_HOST_DIR_COMPILES: $PWD/compiles
+1 -1
View File
@@ -55,7 +55,7 @@ services:
PDF_CACHING_ENABLE_WORKER_POOL: true
ALLOWED_IMAGES: quay.io/sharelatex/texlive-full:2017.1 quay.io/sharelatex/texlive-full:2025.1 quay.io/sharelatex/pandoc:3.9 quay.io/sharelatex/pdftocairo:24.02
TEXLIVE_IMAGE: quay.io/sharelatex/texlive-full:2025.1
TEX_LIVE_IMAGE_NAME_OVERRIDE: us-east1-docker.pkg.dev/overleaf-ops/ol-docker
TEX_LIVE_DOCKER_IMAGE_ROOT: us-east1-docker.pkg.dev/overleaf-ops/ol-docker
TEXLIVE_IMAGE_USER: tex
SANDBOXED_COMPILES: true
SANDBOXED_COMPILES_HOST_DIR_COMPILES: $PWD/compiles
+909
View File
@@ -0,0 +1,909 @@
{
"defaultAction": "SCMP_ACT_ERRNO",
"architectures": [
"SCMP_ARCH_X86_64",
"SCMP_ARCH_X86",
"SCMP_ARCH_X32",
"SCMP_ARCH_AARCH64",
"SCMP_ARCH_ARM"
],
"syscalls": [
{
"name": "getrandom",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "access",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "arch_prctl",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "brk",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "chdir",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "chmod",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "clock_getres",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "clock_gettime",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "clock_nanosleep",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "clone",
"action": "SCMP_ACT_ALLOW",
"args": [
{
"index": 0,
"value": 2080505856,
"valueTwo": 0,
"op": "SCMP_CMP_MASKED_EQ"
}
]
},
{
"name": "clone3",
"action": "SCMP_ACT_ERRNO",
"errnoRet": 38
},
{
"name": "close",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "copy_file_range",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "creat",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "dup",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "dup2",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "dup3",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "execve",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "execveat",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "exit",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "exit_group",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "faccessat",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fadvise64",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fadvise64_64",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fallocate",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fchdir",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fchmod",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fchmodat",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fcntl",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fcntl64",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fdatasync",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fork",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fstat",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fstat64",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fstatat64",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fstatfs",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fstatfs64",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fsync",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "ftruncate",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "ftruncate64",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "futex",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "futimesat",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getcpu",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getcwd",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getdents",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getdents64",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getegid",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getegid32",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "geteuid",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "geteuid32",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getgid",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getgid32",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getgroups",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getgroups32",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getpgid",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getpgrp",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getpid",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getppid",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getpriority",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getresgid",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getresgid32",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getresuid",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getresuid32",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getrlimit",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "get_robust_list",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getrusage",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getsid",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "gettid",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getuid",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "getuid32",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "ioctl",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "kill",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "_llseek",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "lseek",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "lstat",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "lstat64",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "madvise",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "mkdir",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "mkdirat",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "mmap",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "mmap2",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "mprotect",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "mremap",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "munmap",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "newfstatat",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "open",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "openat",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "openat2",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "pause",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "pipe",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "pipe2",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "prctl",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "pread64",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "preadv",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "prlimit64",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "pwrite64",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "pwritev",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "read",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "readlink",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "readlinkat",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "readv",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "rename",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "renameat",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "renameat2",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "restart_syscall",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "rmdir",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "rt_sigaction",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "rt_sigpending",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "rt_sigprocmask",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "rt_sigqueueinfo",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "rt_sigreturn",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "rt_sigsuspend",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "rt_sigtimedwait",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "rt_tgsigqueueinfo",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "sched_getaffinity",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "sched_getparam",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "sched_get_priority_max",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "sched_get_priority_min",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "sched_getscheduler",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "sched_rr_get_interval",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "sched_yield",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "sendfile",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "sendfile64",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "setgroups",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "setgroups32",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "set_robust_list",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "set_tid_address",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "sigaltstack",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "stat",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "statx",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "stat64",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "statfs",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "statfs64",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "sync",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "sync_file_range",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "syncfs",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "sysinfo",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "tgkill",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "timer_create",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "timer_delete",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "timer_getoverrun",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "timer_gettime",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "timer_settime",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "times",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "tkill",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "truncate",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "truncate64",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "umask",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "uname",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "unlink",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "unlinkat",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "utime",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "utimensat",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "utimes",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "vfork",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "vhangup",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "wait4",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "waitid",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "write",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "writev",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "pread",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "setgid",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "setuid",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "capget",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "capset",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "fchown",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "gettimeofday",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "epoll_wait",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "epoll_pwait",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "epoll_pwait2",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "poll",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "ppoll",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "epoll_create",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "epoll_create1",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "epoll_ctl",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "timerfd_create",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "timerfd_settime",
"action": "SCMP_ACT_ALLOW",
"args": []
},
{
"name": "eventfd2",
"action": "SCMP_ACT_ALLOW",
"args": []
}
]
}
@@ -0,0 +1,259 @@
import { vi, describe, beforeEach, it } from 'vitest'
import sinon from 'sinon'
import path from 'node:path'
const modulePath = path.join(
import.meta.dirname,
'../../../app/js/DockerLockManager'
)
describe('DockerLockManager', function () {
beforeEach(async function (ctx) {
vi.doMock('@overleaf/settings', () => ({
default: (ctx.Settings = { clsi: { docker: {} } }),
}))
return (ctx.LockManager = (await import(modulePath)).default)
})
return describe('runWithLock', function () {
describe('with a single lock', function () {
beforeEach(async function (ctx) {
await new Promise((resolve, reject) => {
ctx.callback = sinon.stub()
return ctx.LockManager.runWithLock(
'lock-one',
releaseLock =>
setTimeout(() => releaseLock(null, 'hello', 'world'), 100),
(err, ...args) => {
ctx.callback(err, ...Array.from(args))
return resolve()
}
)
})
})
return it('should call the callback', function (ctx) {
return ctx.callback
.calledWith(null, 'hello', 'world')
.should.equal(true)
})
})
describe('with two locks', function () {
beforeEach(async function (ctx) {
await new Promise((resolve, reject) => {
ctx.callback1 = sinon.stub()
ctx.callback2 = sinon.stub()
ctx.LockManager.runWithLock(
'lock-one',
releaseLock =>
setTimeout(() => releaseLock(null, 'hello', 'world', 'one'), 100),
(err, ...args) => {
return ctx.callback1(err, ...Array.from(args))
}
)
return ctx.LockManager.runWithLock(
'lock-two',
releaseLock =>
setTimeout(() => releaseLock(null, 'hello', 'world', 'two'), 200),
(err, ...args) => {
ctx.callback2(err, ...Array.from(args))
return resolve()
}
)
})
})
it('should call the first callback', function (ctx) {
return ctx.callback1
.calledWith(null, 'hello', 'world', 'one')
.should.equal(true)
})
return it('should call the second callback', function (ctx) {
return ctx.callback2
.calledWith(null, 'hello', 'world', 'two')
.should.equal(true)
})
})
return describe('with lock contention', function () {
describe('where the first lock is released quickly', function () {
beforeEach(async function (ctx) {
await new Promise((resolve, reject) => {
ctx.LockManager.MAX_LOCK_WAIT_TIME = 1000
ctx.LockManager.LOCK_TEST_INTERVAL = 100
ctx.callback1 = sinon.stub()
ctx.callback2 = sinon.stub()
ctx.LockManager.runWithLock(
'lock',
releaseLock =>
setTimeout(
() => releaseLock(null, 'hello', 'world', 'one'),
100
),
(err, ...args) => {
return ctx.callback1(err, ...Array.from(args))
}
)
return ctx.LockManager.runWithLock(
'lock',
releaseLock =>
setTimeout(
() => releaseLock(null, 'hello', 'world', 'two'),
200
),
(err, ...args) => {
ctx.callback2(err, ...Array.from(args))
return resolve()
}
)
})
})
it('should call the first callback', function (ctx) {
return ctx.callback1
.calledWith(null, 'hello', 'world', 'one')
.should.equal(true)
})
return it('should call the second callback', function (ctx) {
return ctx.callback2
.calledWith(null, 'hello', 'world', 'two')
.should.equal(true)
})
})
describe('where the first lock is held longer than the waiting time', function () {
beforeEach(async function (ctx) {
await new Promise((resolve, reject) => {
let doneTwo
ctx.LockManager.MAX_LOCK_HOLD_TIME = 10000
ctx.LockManager.MAX_LOCK_WAIT_TIME = 1000
ctx.LockManager.LOCK_TEST_INTERVAL = 100
ctx.callback1 = sinon.stub()
ctx.callback2 = sinon.stub()
let doneOne = (doneTwo = false)
const finish = function (key) {
if (key === 1) {
doneOne = true
}
if (key === 2) {
doneTwo = true
}
if (doneOne && doneTwo) {
return resolve()
}
}
ctx.LockManager.runWithLock(
'lock',
releaseLock =>
setTimeout(
() => releaseLock(null, 'hello', 'world', 'one'),
1100
),
(err, ...args) => {
ctx.callback1(err, ...Array.from(args))
return finish(1)
}
)
return ctx.LockManager.runWithLock(
'lock',
releaseLock =>
setTimeout(
() => releaseLock(null, 'hello', 'world', 'two'),
100
),
(err, ...args) => {
ctx.callback2(err, ...Array.from(args))
return finish(2)
}
)
})
})
it('should call the first callback', function (ctx) {
return ctx.callback1
.calledWith(null, 'hello', 'world', 'one')
.should.equal(true)
})
return it('should call the second callback with an error', function (ctx) {
const error = sinon.match.instanceOf(Error)
return ctx.callback2.calledWith(error).should.equal(true)
})
})
return describe('where the first lock is held longer than the max holding time', function () {
beforeEach(async function (ctx) {
await new Promise((resolve, reject) => {
let doneTwo
ctx.LockManager.MAX_LOCK_HOLD_TIME = 1000
ctx.LockManager.MAX_LOCK_WAIT_TIME = 2000
ctx.LockManager.LOCK_TEST_INTERVAL = 100
ctx.callback1 = sinon.stub()
ctx.callback2 = sinon.stub()
let doneOne = (doneTwo = false)
const finish = function (key) {
if (key === 1) {
doneOne = true
}
if (key === 2) {
doneTwo = true
}
if (doneOne && doneTwo) {
return resolve()
}
}
ctx.LockManager.runWithLock(
'lock',
releaseLock =>
setTimeout(
() => releaseLock(null, 'hello', 'world', 'one'),
1500
),
(err, ...args) => {
ctx.callback1(err, ...Array.from(args))
return finish(1)
}
)
return ctx.LockManager.runWithLock(
'lock',
releaseLock =>
setTimeout(
() => releaseLock(null, 'hello', 'world', 'two'),
100
),
(err, ...args) => {
ctx.callback2(err, ...Array.from(args))
return finish(2)
}
)
})
})
it('should call the first callback', function (ctx) {
return ctx.callback1
.calledWith(null, 'hello', 'world', 'one')
.should.equal(true)
})
return it('should call the second callback', function (ctx) {
return ctx.callback2
.calledWith(null, 'hello', 'world', 'two')
.should.equal(true)
})
})
})
})
})
@@ -5,7 +5,7 @@ import Path from 'node:path'
const modulePath = Path.join(
import.meta.dirname,
'../../../app/js/DockerRunner'
'../../../app/js/DockerRunner.mjs'
)
describe('DockerRunner', () => {
+5
View File
@@ -66,6 +66,11 @@ if (settings.filestore.stores.template_files) {
keyBuilder.templateFileKeyMiddleware,
fileController.insertFile
)
app.delete(
'/template/:template_id/v/:version/:format',
keyBuilder.templateFileKeyMiddleware,
fileController.deleteFile
)
}
app.get(
@@ -10,6 +10,7 @@ export default {
getFile,
getFileHead,
insertFile,
deleteFile,
}
function getFile(req, res, next) {
@@ -93,6 +94,22 @@ function getFile(req, res, next) {
})
}
function deleteFile(req, res, next) {
metrics.inc('deleteFile')
const { key, bucket } = req
req.requestLogger.addFields({ key, bucket })
req.requestLogger.setMessage('deleting file')
FileHandler.deleteFile(bucket, key, function (err) {
if (err) {
next(err)
} else {
res.sendStatus(204)
}
})
}
function getFileHead(req, res, next) {
const { key, bucket } = req
+1 -1
View File
@@ -6,7 +6,7 @@ import Errors from './Errors.js'
const { ConversionError } = Errors
const APPROVED_FORMATS = ['png']
const APPROVED_FORMATS = ['png', 'jpg']
const FOURTY_SECONDS = 40 * 1000
const KILL_SIGNAL = 'SIGTERM'
+24 -1
View File
@@ -13,6 +13,7 @@ const { ConversionError, InvalidParametersError } = Errors
const FileHandler = {
insertFile: callbackify(insertFile),
deleteFile: callbackify(deleteFile),
getFile: callbackify(getFile),
getRedirectUrl: callbackify(getRedirectUrl),
getFileSize: callbackify(getFileSize),
@@ -20,6 +21,7 @@ const FileHandler = {
getFile,
getRedirectUrl,
insertFile,
deleteFile,
getFileSize,
},
}
@@ -46,6 +48,25 @@ async function insertFile(bucket, key, stream) {
await PersistorManager.sendStream(bucket, key, stream)
}
async function deleteFile(bucket, key) {
const convertedKey = KeyBuilder.getConvertedFolderKey(key)
if (!convertedKey.match(/^[0-9a-f]{24}\/([0-9a-f]{24}|v\/[0-9]+\/[a-z]+)/i)) {
throw new InvalidParametersError('key does not match validation regex', {
bucket,
key,
convertedKey,
})
}
const jobs = [PersistorManager.deleteObject(bucket, key)]
if (
Settings.enableConversions &&
bucket === Settings.filestore.stores.template_files
) {
jobs.push(PersistorManager.deleteDirectory(bucket, convertedKey))
}
await Promise.all(jobs)
}
async function getFile(bucket, key, opts) {
opts = opts || {}
if (!opts.format && !opts.style) {
@@ -111,7 +132,9 @@ async function _getConvertedFileAndCache(bucket, key, convertedKey, opts) {
let convertedFsPath
try {
convertedFsPath = await _convertFile(bucket, key, opts)
await ImageOptimiser.promises.compressPng(convertedFsPath)
if (convertedFsPath.toLowerCase().endsWith(".png")) {
await ImageOptimiser.promises.compressPng(convertedFsPath)
}
await PersistorManager.sendFile(bucket, convertedKey, convertedFsPath)
} catch (err) {
LocalFileWriter.deleteFile(convertedFsPath, () => {})
+1
View File
@@ -0,0 +1 @@
24.14.1
+41
View File
@@ -0,0 +1,41 @@
# This file was auto-generated, do not edit it directly.
# Instead run bin/update_build_scripts from
# https://github.com/overleaf/internal/
FROM node:24.14.1 AS base
ENV PATH="/overleaf/node_modules/.bin:$PATH"
ENV COREPACK_HOME=/opt/corepack
RUN corepack enable && corepack install -g yarn@4.14.1
ENV COREPACK_ENABLE_NETWORK=0
WORKDIR /overleaf/services/linked-url-proxy
# Google Cloud Storage needs a writable $HOME/.config for resumable uploads
# (see https://googleapis.dev/nodejs/storage/latest/File.html#createWriteStream)
RUN mkdir /home/node/.config && chown node:node /home/node/.config
FROM base AS app
COPY package.json yarn.lock .yarnrc.yml /overleaf/
COPY libraries/fetch-utils/package.json /overleaf/libraries/fetch-utils/package.json
COPY libraries/logger/package.json /overleaf/libraries/logger/package.json
COPY libraries/metrics/package.json /overleaf/libraries/metrics/package.json
COPY libraries/o-error/package.json /overleaf/libraries/o-error/package.json
COPY libraries/settings/package.json /overleaf/libraries/settings/package.json
COPY services/linked-url-proxy/package.json /overleaf/services/linked-url-proxy/package.json
COPY .yarn/patches/ /overleaf/.yarn/patches/
RUN cd /overleaf && yarn workspaces focus @overleaf/linked-url-proxy overleaf
COPY libraries/fetch-utils/ /overleaf/libraries/fetch-utils/
COPY libraries/logger/ /overleaf/libraries/logger/
COPY libraries/metrics/ /overleaf/libraries/metrics/
COPY libraries/o-error/ /overleaf/libraries/o-error/
COPY libraries/settings/ /overleaf/libraries/settings/
COPY services/linked-url-proxy/ /overleaf/services/linked-url-proxy/
FROM app
USER node
CMD ["node", "--expose-gc", "app.mjs"]
+662
View File
@@ -0,0 +1,662 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.
+174
View File
@@ -0,0 +1,174 @@
# This file was auto-generated, do not edit it directly.
# Instead run bin/update_build_scripts from
# https://github.com/overleaf/internal/
BUILD_NUMBER ?= local
BRANCH_NAME ?= $(shell git rev-parse --abbrev-ref HEAD)
PROJECT_NAME = linked-url-proxy
BUILD_DIR_NAME = $(shell pwd | xargs basename | tr -cd '[a-zA-Z0-9_.\-]')
HERE=$(shell pwd)
export MONOREPO ?= $(shell cd ../../ && pwd)
IMAGE_CI ?= ci/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER)
IMAGE_REPO ?= us-east1-docker.pkg.dev/overleaf-ops/ol-docker/$(PROJECT_NAME)
IMAGE_REPO_FINAL ?= $(IMAGE_REPO):$(BRANCH_NAME)-$(BUILD_NUMBER)
IMAGE_CACHE ?= $(IMAGE_REPO):cache-$(shell cat \
$(MONOREPO)/package.json \
$(MONOREPO)/package-lock.json \
$(MONOREPO)/libraries/fetch-utils/package.json \
$(MONOREPO)/libraries/logger/package.json \
$(MONOREPO)/libraries/metrics/package.json \
$(MONOREPO)/libraries/o-error/package.json \
$(MONOREPO)/libraries/overleaf-editor-core/package.json \
$(MONOREPO)/libraries/promise-utils/package.json \
$(MONOREPO)/libraries/settings/package.json \
$(MONOREPO)/libraries/stream-utils/package.json \
$(MONOREPO)/services/linked-url-proxy/package.json \
$(MONOREPO)/patches/* \
| sha256sum | cut -d '-' -f1)
DOCKER_COMPOSE_FLAGS ?= -f docker-compose.yml
DOCKER_COMPOSE := BUILD_NUMBER=$(BUILD_NUMBER) \
BRANCH_NAME=$(BRANCH_NAME) \
PROJECT_NAME=$(PROJECT_NAME) \
MOCHA_GREP=${MOCHA_GREP} \
docker compose ${DOCKER_COMPOSE_FLAGS}
COMPOSE_PROJECT_NAME_TEST_ACCEPTANCE ?= test_acceptance_$(BUILD_DIR_NAME)
DOCKER_COMPOSE_TEST_ACCEPTANCE = \
COMPOSE_PROJECT_NAME=$(COMPOSE_PROJECT_NAME_TEST_ACCEPTANCE) $(DOCKER_COMPOSE)
COMPOSE_PROJECT_NAME_TEST_UNIT ?= test_unit_$(BUILD_DIR_NAME)
DOCKER_COMPOSE_TEST_UNIT = \
COMPOSE_PROJECT_NAME=$(COMPOSE_PROJECT_NAME_TEST_UNIT) $(DOCKER_COMPOSE)
clean:
-docker rmi $(IMAGE_CI)
-docker rmi $(IMAGE_REPO_FINAL)
-$(DOCKER_COMPOSE_TEST_UNIT) down --remove-orphans --rmi local --timeout 0 --volumes
-$(DOCKER_COMPOSE_TEST_ACCEPTANCE) down --remove-orphans --rmi local --timeout 0 --volumes
-rm -rf reports/
# Run the linting commands in the scope of the monorepo.
# Eslint and prettier (plus some configs) are on the root.
RUN_LINTING = docker run --rm -v $(MONOREPO):$(MONOREPO) -w $(HERE) node:24.14.1 npm run --silent
RUN_LINTING_CI = docker run --rm --volume $(MONOREPO)/.editorconfig:/overleaf/.editorconfig --volume $(MONOREPO)/.eslintignore:/overleaf/.eslintignore --volume $(MONOREPO)/.eslintrc:/overleaf/.eslintrc --volume $(MONOREPO)/.prettierignore:/overleaf/.prettierignore --volume $(MONOREPO)/.prettierrc:/overleaf/.prettierrc --volume $(MONOREPO)/tsconfig.backend.json:/overleaf/tsconfig.backend.json --volume $(MONOREPO)/services/linked-url-proxy/reports:/overleaf/services/linked-url-proxy/reports $(IMAGE_CI) npm run --silent
# Same but from the top of the monorepo
RUN_LINTING_MONOREPO = docker run --rm -v $(MONOREPO):$(MONOREPO) -w $(MONOREPO) node:24.14.1 npm run --silent
SHELLCHECK_OPTS = \
--shell=bash \
--external-sources
SHELLCHECK_COLOR := $(if $(CI),--color=never,--color)
SHELLCHECK_FILES := { git ls-files "*.sh" -z; git grep -Plz "\A\#\!.*bash"; } | sort -zu
shellcheck:
@$(SHELLCHECK_FILES) | xargs -0 -r docker run --rm -v $(HERE):/mnt -w /mnt \
koalaman/shellcheck:stable $(SHELLCHECK_OPTS) $(SHELLCHECK_COLOR)
shellcheck_fix:
@$(SHELLCHECK_FILES) | while IFS= read -r -d '' file; do \
diff=$$(docker run --rm -v $(HERE):/mnt -w /mnt koalaman/shellcheck:stable $(SHELLCHECK_OPTS) --format=diff "$$file" 2>/dev/null); \
if [ -n "$$diff" ] && ! echo "$$diff" | patch -p1 >/dev/null 2>&1; then echo "\033[31m$$file\033[0m"; \
elif [ -n "$$diff" ]; then echo "$$file"; \
else echo "\033[2m$$file\033[0m"; fi \
done
format:
$(RUN_LINTING) format
format_ci:
$(RUN_LINTING_CI) format
format_fix:
$(RUN_LINTING) format:fix
lint:
$(RUN_LINTING) lint
lint_ci:
-$(RUN_LINTING_CI) lint -- --format json --output-file reports/eslint.json
sed -i 's_"filePath":"/overleaf_"filePath":"$(MONOREPO)_g' reports/eslint.json
lint_fix:
$(RUN_LINTING) lint:fix
typecheck:
$(RUN_LINTING) types:check
typecheck_ci:
$(RUN_LINTING_CI) types:check
test: format lint typecheck shellcheck test_unit test_acceptance
test_unit:
ifneq (,$(wildcard test/unit))
$(DOCKER_COMPOSE_TEST_UNIT) run --rm test_unit
endif
test_clean: test_unit_clean
test_unit_clean:
ifneq (,$(wildcard test/unit))
$(DOCKER_COMPOSE_TEST_UNIT) down -v -t 0
endif
test_acceptance: test_acceptance_clean test_acceptance_pre_run test_acceptance_run
$(MAKE) test_acceptance_clean
test_acceptance_debug: test_acceptance_clean test_acceptance_pre_run test_acceptance_run_debug
$(MAKE) test_acceptance_clean
test_acceptance_run:
ifneq (,$(wildcard test/acceptance))
$(DOCKER_COMPOSE_TEST_ACCEPTANCE) run --rm test_acceptance
endif
test_acceptance_run_debug:
ifneq (,$(wildcard test/acceptance))
$(DOCKER_COMPOSE_TEST_ACCEPTANCE) run -p 127.0.0.9:19999:19999 --rm test_acceptance npm run test:acceptance -- --inspect=0.0.0.0:19999 --inspect-brk
endif
test_clean: test_acceptance_clean
test_acceptance_clean:
$(DOCKER_COMPOSE_TEST_ACCEPTANCE) down -v -t 0
test_acceptance_pre_run:
ifneq (,$(wildcard test/acceptance/js/scripts/pre-run))
$(DOCKER_COMPOSE_TEST_ACCEPTANCE) run --rm test_acceptance test/acceptance/js/scripts/pre-run
endif
benchmarks:
$(DOCKER_COMPOSE_TEST_ACCEPTANCE) run --rm test_acceptance npm run benchmarks
build:
docker build \
--pull \
--build-arg BUILDKIT_INLINE_CACHE=1 \
--tag $(IMAGE_CI) \
--tag $(IMAGE_CACHE) \
--tag $(IMAGE_REPO_FINAL) \
--cache-from $(IMAGE_CACHE) \
--file Dockerfile \
../..
tar:
$(DOCKER_COMPOSE) up tar
push:
docker push $(IMAGE_REPO_FINAL)
push_branch:
docker push $(IMAGE_CACHE)
.PHONY: clean \
format format_fix \
lint lint_fix \
build_types typecheck \
lint_ci format_ci typecheck_ci \
shellcheck shellcheck_fix \
test test_clean test_unit test_unit_clean \
test_acceptance test_acceptance_debug test_acceptance_pre_run \
test_acceptance_run test_acceptance_run_debug test_acceptance_clean \
benchmarks \
build tar publish \
+10
View File
@@ -0,0 +1,10 @@
overleaf/linked-url-proxy
===============
An API for providing linked url proxy
License
=======
The code in this repository is released under the GNU AFFERO GENERAL PUBLIC LICENSE, version 3.
Copyright (c) yu-i-i (https://github.com/yu-i-i/overleaf-cep), 2025.
+39
View File
@@ -0,0 +1,39 @@
import '@overleaf/metrics/initialize.js'
import express from 'express'
import Settings from '@overleaf/settings'
import logger from '@overleaf/logger'
import Metrics from '@overleaf/metrics'
import LinkedUrlProxyController from './app/js/LinkedUrlProxyController.mjs'
Metrics.open_sockets.monitor(true)
Metrics.memory.monitor(logger)
Metrics.leaked_sockets.monitor(logger)
const app = express()
Metrics.injectMetricsRoute(app)
app.use(Metrics.http.monitor(logger))
app.get('/', LinkedUrlProxyController.proxy)
app.get('/status', (req, res) => res.send({ status: 'linked-url-proxy is up' }))
const host = Settings.internal.linkedUrlProxy.host
const port = Settings.internal.linkedUrlProxy.port
logger.debug('Listening at', { host, port })
const server = app.listen(port, host, function (error) {
if (error) {
throw error
}
logger.info({ host, port }, 'linked-url-proxy HTTP server starting up')
})
process.on('SIGTERM', () => {
server.close(() => {
logger.info({ host, port }, 'linked-url-proxy HTTP server closed')
Metrics.close()
})
})
@@ -0,0 +1,201 @@
import dns from 'dns/promises'
import { sanitizeUrl } from 'strict-url-sanitise'
import normalizeUrlPath from 'als-normalize-urlpath'
import ipaddr from 'ipaddr.js'
import { URL } from 'node:url'
import { Transform } from 'node:stream'
import logger from '@overleaf/logger'
import Settings from '@overleaf/settings'
import { fetchStreamWithResponse, RequestFailedError } from '@overleaf/fetch-utils'
import { Agent } from 'undici'
function isAllowedResource(targetUrl) {
if (!Settings.allowedResources) return false
return Settings.allowedResources.test(targetUrl)
}
function isBlockedIp(ipStr, targetUrl) {
const addr = ipaddr.parse(ipStr)
if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {
return isBlockedIp(addr.toIPv4Address().toString(), targetUrl)
}
const range = addr.range()
if (!['unicast'].includes(addr.range())) {
return true
}
for (const blocked of Settings.blockedNetworks) {
try {
const net = ipaddr.parseCIDR(blocked)
if (addr.match(net)) return true
} catch (e) {
logger.error({ blocked, error: e }, 'Invalid blockedNetworks entry')
const err = new Error(`Invalid blockedNetworks entry: ${blocked}`)
err.info = { status: 500 }
throw err
}
}
return false
}
async function checkUrlAccess(hostname, targetUrl) {
const records = await dns.lookup(hostname, { all: true }).catch(() => [])
if (!records.length) {
const err = new Error(`DNS lookup failed for ${hostname}`)
err.info = { status: 421 }
throw err
}
// Permit explicitly allowed resources without checking blocked IPs
if (isAllowedResource(targetUrl)) return records[0].address
for (const { address } of records) {
if (isBlockedIp(address, targetUrl)) {
const err = new Error(`Blocked IP address: ${address}`)
err.info = { status: 403 }
throw err
}
}
return records[0].address
}
async function validateAndFetch(rawUrl, redirectCount = 0) {
if (redirectCount > Settings.maxRedirects) {
const err = new Error('Too many redirects')
err.info = { status: 421 }
throw err
}
const sanitizedUrl = sanitizeUrl(rawUrl)
if (!sanitizedUrl) {
const err = new Error(`Invalid or unsafe URL: ${rawUrl}`)
err.info = { status: 400 }
throw err
}
const url = new URL(sanitizedUrl)
if (!['http:', 'https:'].includes(url.protocol)) {
const err = new Error(`${url.protocol} protocol is not allowed`)
err.info = { status: 400 }
throw err
}
const normalizedPath = normalizeUrlPath(url.pathname).pathname
if (!normalizedPath) {
const err = new Error(`Invalid or unsafe URL path: ${url.pathname}`)
err.info = { status: 400 }
throw err
}
const normalizedUrl = url.toString()
// check DNS and allowed resources
const validatedIp = await checkUrlAccess(url.hostname, normalizedUrl)
// pin fetch to validated IP to prevent DNS rebinding
const agent = new Agent({
connect: {
lookup(hostname, opts, cb) {
cb(null, validatedIp, 4)
}
}
})
const opts = {
redirect: 'manual',
timeout: Settings.fetchTimeoutMs,
headers: Settings.userAgentHeader,
}
try {
const { stream, response } = await fetchStreamWithResponse(normalizedUrl, { ...opts, dispatcher: agent })
const contentLengthHeader = response.headers.get('content-length')
if (contentLengthHeader) {
const n = parseInt(contentLengthHeader, 10)
if (!Number.isNaN(n) && n > Settings.maxUploadSize) {
const err = new Error('file too large')
err.info = { status: 413 }
try { stream.destroy() } catch (_) {}
throw err
}
}
return {
stream,
response,
headers: Object.fromEntries(response.headers.entries()),
}
} catch (err) {
if (err instanceof RequestFailedError) {
const status = err.info.status
// Handle redirects
if (status >= 300 && status < 400) {
const location = err.response.headers.get('Location')
if (location) {
const nextUrl = new URL(location, normalizedUrl).toString()
return validateAndFetch(nextUrl, redirectCount + 1)
} else {
const e = new Error('Redirect response missing Location header')
e.info = { status: 421 }
throw e
}
}
throw err
}
if (!err?.info?.status) {
if(err.type === "request-timeout") {
err.info = { status: 408 }
} else err.info = { status: 422 }
}
throw err
}
}
async function proxy(req, res) {
try {
const u = new URL(req.url, `http://${req.headers.host}`)
const targetUrl = u.searchParams.get('url')
if (!targetUrl) {
res.writeHead(400, { 'Content-Type': 'text/plain' })
res.end('Missing ?url parameter')
return
}
const { stream: upstreamStream, response, headers } = await validateAndFetch(targetUrl)
res.statusCode = response.status || 200
res.setHeader('Content-Type', headers['content-type'] || 'application/octet-stream')
res.setHeader('Cache-Control', 'no-store')
function onError(err) {
logger.info({ err, url: req.url }, 'linked-url-proxy request failed')
try { upstreamStream.destroy() } catch (_) {}
if (!res.headersSent) {
let body = `Error: ${err?.message ?? String(err)}`
res.writeHead(err?.info?.status || 503, { 'Content-Type': 'text/plain' })
res.end(body)
} else {
try { res.destroy() } catch (_) {}
}
}
upstreamStream.on('error', onError)
upstreamStream.pipe(res)
} catch (err) {
const status = err.info?.status || 500
logger.info({ linkedUrl: err.message, status, url: req.url }, 'linked-url-proxy request failed')
let body = `Error: ${err.message || String(err)}`
try {
res.writeHead(status, { 'Content-Type': 'text/plain' })
res.end(body)
} catch {
try { res.end() } catch {}
}
}
}
export default { proxy }
@@ -0,0 +1,6 @@
linked-url-proxy
--env-add=
--env-pass-through=
--esmock-loader=False
--node-version=24.14.1
--public-repo=False
@@ -0,0 +1,27 @@
const blockedNetworks = (process.env.OVERLEAF_LINKED_URL_BLOCKED_NETWORKS || '')
.split(/[,\s]+/)
.filter(Boolean)
.map(cidr => cidr.trim())
const allowedResources = process.env.OVERLEAF_LINKED_URL_ALLOWED_RESOURCES
? new RegExp(process.env.OVERLEAF_LINKED_URL_ALLOWED_RESOURCES)
: null
module.exports = {
maxRedirects: 5,
fetchTimeoutMs: 30000,
blockedNetworks,
allowedResources,
userAgentHeader: {
'User-Agent': 'Overleaf Extended CE - LinkedURLProxy (https://github.com/yu-i-i/overleaf-cep)'
},
maxUploadSize: process.env.MAX_UPLOAD_SIZE
? parseInt(process.env.MAX_UPLOAD_SIZE, 10) * 1024 * 1024
: 50 * 1024 * 1024, // 50 MB
internal: {
linkedUrlProxy: {
port: 3066,
host: process.env.LINKED_URL_PROXY_HOST || '127.0.0.1',
},
},
}
@@ -0,0 +1,32 @@
# This file was auto-generated, do not edit it directly.
# Instead run bin/update_build_scripts from
# https://github.com/overleaf/internal/
services:
test_unit:
image: ci/$PROJECT_NAME:$BRANCH_NAME-$BUILD_NUMBER
user: node
command: npm run test:unit:_run
environment:
NODE_ENV: test
NODE_OPTIONS: "--unhandled-rejections=strict"
test_acceptance:
build: .
image: ci/$PROJECT_NAME:$BRANCH_NAME-$BUILD_NUMBER
environment:
ELASTIC_SEARCH_DSN: es:9200
POSTGRES_HOST: postgres
MOCHA_GREP: ${MOCHA_GREP}
NODE_ENV: test
NODE_OPTIONS: "--unhandled-rejections=strict"
user: node
command: npm run test:acceptance
tar:
build: .
image: ci/$PROJECT_NAME:$BRANCH_NAME-$BUILD_NUMBER
volumes:
- ./:/tmp/build/
command: tar -czf /tmp/build/build.tar.gz --exclude=build.tar.gz --exclude-vcs .
user: root
@@ -0,0 +1,36 @@
# This file was auto-generated, do not edit it directly.
# Instead run bin/update_build_scripts from
# https://github.com/overleaf/internal/
services:
test_unit:
image: node:24.14.1
volumes:
- .:/overleaf/services/linked-url-proxy
- ../../node_modules:/overleaf/node_modules
- ../../libraries:/overleaf/libraries
working_dir: /overleaf/services/linked-url-proxy
environment:
MOCHA_GREP: ${MOCHA_GREP}
LOG_LEVEL: ${LOG_LEVEL:-}
NODE_ENV: test
NODE_OPTIONS: "--unhandled-rejections=strict"
command: npm run --silent test:unit
user: node
test_acceptance:
image: node:24.14.1
volumes:
- .:/overleaf/services/linked-url-proxy
- ../../node_modules:/overleaf/node_modules
- ../../libraries:/overleaf/libraries
working_dir: /overleaf/services/linked-url-proxy
environment:
ELASTIC_SEARCH_DSN: es:9200
POSTGRES_HOST: postgres
MOCHA_GREP: ${MOCHA_GREP}
LOG_LEVEL: ${LOG_LEVEL:-}
NODE_ENV: test
NODE_OPTIONS: "--unhandled-rejections=strict"
user: node
command: npm run --silent test:acceptance
+22
View File
@@ -0,0 +1,22 @@
{
"name": "@overleaf/linked-url-proxy",
"description": "An API for providing linked url proxy",
"private": true,
"main": "app.mjs",
"scripts": {
"start": "node app.mjs",
"nodemon": "node --watch app.mjs"
},
"version": "0.1.1",
"dependencies": {
"@overleaf/settings": "workspace:*",
"@overleaf/logger": "workspace:*",
"@overleaf/metrics": "workspace:*",
"async": "^3.2.5",
"express": "^4.22.1",
"ipaddr.js": "^2.1.0",
"als-normalize-urlpath": "^2.3.0",
"strict-url-sanitise": "^0.0.1",
"undici": "^7.22.0"
}
}
+13
View File
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.backend.json",
"include": [
"app.mjs",
"app.ts",
"app/js/**/*",
"benchmarks/**/*",
"config/**/*",
"scripts/**/*",
"test/**/*",
"types"
]
}
@@ -110,6 +110,7 @@ const AuthenticationController = {
alphaProgram: user.alphaProgram || undefined, // only store if set
betaProgram: user.betaProgram || undefined, // only store if set
labsProgram: user.labsProgram || undefined, // only store if set
externalAuth: user.externalAuth || false,
}
if (user.isAdmin) {
lightUser.isAdmin = true
@@ -157,6 +157,7 @@ const transferOwnershipSchema = z.object({
}),
body: z.object({
user_id: zz.objectId(),
skipEmails: z.boolean().optional(),
}),
})
@@ -173,6 +174,7 @@ async function transferOwnership(req, res, next) {
allowTransferToNonCollaborators: hasAdminAccess(sessionUser),
sessionUserId: new ObjectId(sessionUser._id),
ipAddress: req.ip,
skipEmails: body.skipEmails
}
)
res.sendStatus(204)
@@ -11,6 +11,7 @@ import EmailHelper from '../Helpers/EmailHelper.mjs'
import EditorRealTimeController from '../Editor/EditorRealTimeController.mjs'
import AnalyticsManager from '../Analytics/AnalyticsManager.mjs'
import SessionManager from '../Authentication/SessionManager.mjs'
import Features from '../../infrastructure/Features.mjs'
import { RateLimiter } from '../../infrastructure/RateLimiter.mjs'
import { z, zz, parseReq } from '../../infrastructure/Validation.mjs'
import { expressify } from '@overleaf/promise-utils'
@@ -334,7 +335,11 @@ async function viewInvite(req, res) {
user_first_name: owner.first_name,
}
AuthenticationController.setRedirectInSession(req)
return res.redirect('/register')
if (Features.hasFeature('registration-page')) {
return res.redirect('/register')
} else {
return res.redirect('/login')
}
}
// cleanup if set for register page
@@ -374,7 +379,11 @@ async function viewSharingLink(req, res) {
const currentUser = SessionManager.getSessionUser(req.session)
if (!currentUser) {
AuthenticationController.setRedirectInSession(req)
return res.redirect('/register')
if (Features.hasFeature('registration-page')) {
return res.redirect('/register')
} else {
return res.redirect('/login')
}
}
// cleanup if set for register page
@@ -1066,7 +1066,7 @@ async function _getContentFromMongo(projectId) {
function _finaliseRequest(projectId, options, project, docs, files) {
const resources = []
let flags
let flags = []
let rootResourcePath = options.rootResourcePath
let rootResourcePathOverride = null
let hasMainFile = false
@@ -1135,6 +1135,10 @@ function _finaliseRequest(projectId, options, project, docs, files) {
flags = ['-file-line-error']
}
if (process.env.TEX_COMPILER_EXTRA_FLAGS) {
flags.push(...process.env.TEX_COMPILER_EXTRA_FLAGS.split(/\s+/).filter(Boolean))
}
return {
compile: {
options: {
@@ -76,6 +76,7 @@ function getClient() {
}
async function sendEmail(options, emailType) {
console.log("EMAIL_SETTINGS = ", EMAIL_SETTINGS)
try {
const canContinue = await checkCanSendEmail(options)
metrics.inc('email_status', {
@@ -189,7 +189,29 @@ export default LinkedFilesController = {
refreshLinkedFile: expressify(refreshLinkedFile),
handleError(error, req, res, next) {
if (error instanceof AccessDeniedError) {
if (
error instanceof AccessDeniedError &&
error.message === 'Zotero account not linked'
) {
res.status(400)
plainTextResponse(
res,
res.locals.translate(
'zotero_reference_loading_error_not_linked'
)
)
} else if (
error instanceof AccessDeniedError &&
error.message === 'Zotero access denied'
) {
res.status(403)
plainTextResponse(
res,
res.locals.translate(
'zotero_reference_loading_error_forbidden'
)
)
} else if (error instanceof AccessDeniedError) {
res.status(403)
plainTextResponse(
res,
@@ -231,8 +253,7 @@ export default LinkedFilesController = {
} else {
plainTextResponse(
res,
`Your URL could not be reached (${
error.info?.status || error.cause?.info?.status
`Your URL could not be reached (${error.info?.status || error.cause?.info?.status
} status code). Please check it and try again.`
)
}
@@ -72,6 +72,7 @@ async function getUserForPasswordResetToken(token) {
'overleaf.id': 1,
email: 1,
must_reconfirm: 1,
hashedPassword: 1,
})
await assertUserPermissions(user, ['change-password'])
@@ -563,6 +563,7 @@ const _ProjectController = {
brandVariationId: 1,
overleaf: 1,
tokens: 1,
imageName: 1,
}),
userIsMemberOfGroupSubscription: sessionUser
? (async () =>
@@ -648,6 +649,8 @@ const _ProjectController = {
)
const imageNames = await ProjectHelper.getAllowedImagesForUser(user)
if (!project.imageName) await EditorController.promises.setImageName(projectId, Settings.currentImageName)
const privilegeLevel =
await AuthorizationManager.promises.getPrivilegeLevelForProject(
userId,
@@ -775,7 +778,7 @@ const _ProjectController = {
}
const isAdminOrTemplateOwner =
hasAdminAccess(user) || Settings.templates?.user_id === userId
hasAdminAccess(user) || Settings.templates?.nonAdminCanManage || Settings.templates?.user_id === userId
const showTemplatesServerPro =
Features.hasFeature('templates-server-pro') && isAdminOrTemplateOwner
@@ -79,7 +79,7 @@ async function unmarkAsDeletedByExternalSource(projectId) {
).exec()
}
async function deleteUsersProjects(userId) {
async function deleteUsersProjects(userId, options = {}) {
const projects = await Project.find({ owner_ref: userId }).exec()
logger.info(
{ userId, projectCount: projects.length },
@@ -87,6 +87,7 @@ async function deleteUsersProjects(userId) {
)
await promiseMapWithLimit(5, projects, project =>
deleteProject(project._id, {
...options,
deletedReason: DeletedProjectReasons.ACCOUNT_DELETION,
})
)
@@ -235,6 +236,7 @@ async function deleteProject(projectId, options = {}) {
})
}
const deleterData = {
deletedAt: new Date(),
deleterId:
@@ -277,6 +279,7 @@ async function deleteProject(projectId, options = {}) {
{ projectId, userId: project.owner_ref },
'successfully deleted project'
)
return { deletedAt: deleterData.deletedAt, deleterId: deleterData.deleterId }
} catch (err) {
logger.warn({ err }, 'problem deleting project')
throw err
@@ -306,7 +309,7 @@ async function undeleteProject(projectId, options = {}) {
// if we're undeleting, we want the document to show up
restored.name = await ProjectDetailsHandler.promises.generateUniqueName(
deletedProject.deleterData.deletedProjectOwnerId,
restored.name + ' (Restored)'
restored.name + (options.suffix ?? ' (Restored)')
)
restored.archived = undefined
@@ -330,6 +333,7 @@ async function undeleteProject(projectId, options = {}) {
await db.projects.insertOne(restored)
await DeletedProject.deleteOne({ _id: deletedProject._id }).exec()
return restored
}
async function expireDeletedProject(projectId) {
@@ -117,6 +117,7 @@ async function duplicate(
)
attributes.overleaf = { history: { id: newHistoryId } }
}
attributes.imageName = originalProject.imageName
// Now create the new project, cleaning it up on failure if necessary
const newProject = await ProjectCreationHandler.promises.createBlankProject(
@@ -3,7 +3,7 @@ import Path from 'node:path'
let ProjectEditorHandler
export default ProjectEditorHandler = {
trackChangesAvailable: false,
trackChangesAvailable: true,
buildProjectModelView(
project,
@@ -26,7 +26,7 @@ export default ProjectEditorHandler = {
deletedByExternalDataSource: project.deletedByExternalDataSource || false,
imageName:
project.imageName != null
? Path.basename(project.imageName)
? project.imageName
: undefined,
}
@@ -39,14 +39,13 @@ const ProjectOptionsHandler = {
if (!imageName || !Array.isArray(settings.allowedImageNames)) {
return undefined
}
imageName = imageName.toLowerCase()
const isAllowed = settings.allowedImageNames.find(
allowed => imageName === allowed.imageName
)
if (!isAllowed) {
throw new OError('invalid imageName', { imageName })
}
return settings.imageRoot + '/' + imageName
return imageName
},
async setImageName(projectId, imageName) {
@@ -23,15 +23,15 @@ const AdminController = {
let url
const openSockets = {}
for (url in http.globalAgent.sockets) {
openSockets[`http://${url}`] = http.globalAgent.sockets[url].map(
socket => socket._httpMessage.path
)
openSockets[`http://${url}`] = http.globalAgent.sockets[url].map(socket => {
return socket._httpMessage?.path || '(unknown request)'
})
}
for (url in https.globalAgent.sockets) {
openSockets[`https://${url}`] = https.globalAgent.sockets[url].map(
socket => socket._httpMessage.path
)
openSockets[`https://${url}`] = https.globalAgent.sockets[url].map(socket => {
return socket._httpMessage?.path || '(unknown request)'
})
}
const systemMessages =
@@ -7,21 +7,22 @@ import { expressify } from '@overleaf/promise-utils'
const TemplatesController = {
async getV1Template(req, res) {
const templateVersionId = req.params.Template_version_id
const templateId = req.query.id
if (!/^[0-9]+$/.test(templateVersionId) || !/^[0-9]+$/.test(templateId)) {
logger.err(
{ templateVersionId, templateId },
'invalid template id or version'
)
return res.sendStatus(400)
}
const templateId = req.params.Template_version_id
const templateVersionId = req.query.version
// if (!/^[0-9]+$/.test(templateVersionId) || !/^[0-9]+$/.test(templateId)) {
// logger.err(
// { templateVersionId, templateId },
// 'invalid template id or version'
// )
// return res.sendStatus(400)
// }
const data = {
templateVersionId,
templateId,
name: req.query.templateName,
compiler: ProjectHelper.compilerFromV1Engine(req.query.latexEngine),
imageName: req.query.texImage,
name: req.query.name,
compiler: req.query.compiler,
language: req.query.language,
imageName: req.query.imageName,
mainFile: req.query.mainFile,
brandVariationId: req.query.brandVariationId,
}
@@ -36,6 +37,7 @@ const TemplatesController = {
async createProjectFromV1Template(req, res) {
const userId = SessionManager.getLoggedInUserId(req.session)
const project = await TemplatesManager.promises.createProjectFromV1Template(
req.body.brandVariationId,
req.body.compiler,
@@ -44,7 +46,8 @@ const TemplatesController = {
req.body.templateName,
req.body.templateVersionId,
userId,
req.body.imageName
req.body.imageName,
req.body.language
)
delete req.session.templateData
if (!project) {
@@ -20,6 +20,7 @@ import OError from '@overleaf/o-error'
const { promises: ProjectRootDocManager } = ProjectRootDocManagerModule
const { promises: ProjectOptionsHandler } = ProjectOptionsHandlerModule
const TIMEOUT = 30000 // 30 sec
const TemplatesManager = {
async createProjectFromV1Template(
@@ -30,33 +31,33 @@ const TemplatesManager = {
templateName,
templateVersionId,
userId,
imageName
imageName,
spellCheckLanguage
) {
compiler = ProjectOptionsHandler.normalizeCompiler(
compiler || settings.defaultLatexCompiler
)
imageName = ProjectOptionsHandler.normalizeImageName(
imageName || 'wl_texlive:2018.1'
)
try {
imageName = ProjectOptionsHandler.normalizeImageName(imageName)
} catch {
logger.warn( { templateId, imageName }, 'cannot use the image required by the template, using the default image')
imageName = null
}
const zipUrl = `${settings.apis.v1.url}/api/v1/overleaf/templates/${templateVersionId}`
const zipUrl = `${settings.apis.filestore.url}/template/${templateId}/v/${templateVersionId}/zip`
const zipReq = await fetchStreamWithResponse(zipUrl, {
basicAuth: {
user: settings.apis.v1.user,
password: settings.apis.v1.pass,
},
signal: AbortSignal.timeout(settings.apis.v1.timeout),
signal: AbortSignal.timeout(TIMEOUT),
})
const projectName = ProjectDetailsHandler.fixProjectName(templateName)
const dumpPath = `${settings.path.dumpFolder}/${crypto.randomUUID()}_templates-manager`
const writeStream = fs.createWriteStream(dumpPath)
try {
const attributes = {
fromV1TemplateId: templateId,
fromV1TemplateVersionId: templateVersionId,
compiler,
imageName,
spellCheckLanguage
}
if (brandVariationId) attributes.brandVariationId = brandVariationId
@@ -577,4 +577,5 @@ export default {
expireDeletedUsersAfterDuration: expressify(expireDeletedUsersAfterDuration),
ensureAffiliationMiddleware: expressify(ensureAffiliationMiddleware),
ensureAffiliation,
doLogout,
}
@@ -63,7 +63,7 @@ async function deleteUser(userId, options) {
logger.info({ userId }, 'creating deleted user record')
await _createDeletedUser(user, options)
logger.info({ userId }, 'deleting user projects')
await ProjectDeleter.promises.deleteUsersProjects(user._id)
await ProjectDeleter.promises.deleteUsersProjects(user._id, options)
if (options.skipEmail) {
logger.info({ userId }, 'skipping sending deletion email to user')
} else {
@@ -52,10 +52,8 @@ async function settingsPage(req, res) {
const reconfirmedViaSAML = _.get(req.session, ['saml', 'reconfirmed'])
delete req.session.saml
let shouldAllowEditingDetails = true
if (Settings.ldap && Settings.ldap.updateUserDetailsOnLogin) {
shouldAllowEditingDetails = false
}
if (Settings.saml && Settings.saml.updateUserDetailsOnLogin) {
const externalAuth = req.user.externalAuth
if (externalAuth && Settings[externalAuth].updateUserDetailsOnLogin) {
shouldAllowEditingDetails = false
}
const oauthProviders = Settings.oauthProviders || {}
@@ -15,10 +15,12 @@ import OError from '@overleaf/o-error'
const UserRegistrationHandler = {
_registrationRequestIsValid(body) {
const invalidEmail = AuthenticationManager.validateEmail(body.email || '')
if (invalidEmail) throw new OError('InvalidEmailError')
const invalidPassword = AuthenticationManager.validatePassword(
body.password || '',
body.email
)
if (invalidPassword) throw new OError('InvalidPasswordError')
return !(invalidEmail || invalidPassword)
},
@@ -116,9 +116,9 @@ export default async function (webRouter, privateApiRouter, publicApiRouter) {
webRouter.use(function (req, res, next) {
req.externalAuthenticationSystemUsed =
Features.externalAuthenticationSystemUsed
() => !!req?.user?.externalAuth
res.locals.externalAuthenticationSystemUsed =
Features.externalAuthenticationSystemUsed
() => !!req?.user?.externalAuth
req.hasFeature = res.locals.hasFeature = Features.hasFeature
next()
})
@@ -413,10 +413,12 @@ export default async function (webRouter, privateApiRouter, publicApiRouter) {
labsEnabled: Settings.labs && Settings.labs.enable,
wikiEnabled: Settings.overleaf != null || Settings.proxyLearn,
templatesEnabled:
Settings.overleaf != null || Settings.templates?.user_id != null,
Settings.overleaf != null || Boolean(Settings.templates),
cioWriteKey: Settings.analytics?.cio?.writeKey,
cioSiteId: Settings.analytics?.cio?.siteId,
linkedInInsightsPartnerId: Settings.analytics?.linkedIn?.partnerId,
githubSyncEnabled: !!Settings.githubSync?.clientID && !!Settings.githubSync?.clientSecret,
zoteroEnabled: !!Settings.zotero?.clientKey && !!Settings.zotero?.clientSecret,
enablePandocConversions: Settings.enablePandocConversions,
mixpanelLabsToken:
Settings.labs?.enable && Settings.analytics?.mixpanel?.labsToken,
@@ -34,6 +34,7 @@ const Features = {
return (
(Boolean(Settings.ldap) && Boolean(Settings.ldap.enable)) ||
(Boolean(Settings.saml) && Boolean(Settings.saml.enable)) ||
(Boolean(Settings.oidc) && Boolean(Settings.oidc.enable)) ||
Boolean(Settings.overleaf)
)
},
@@ -51,10 +52,7 @@ const Features = {
case 'homepage':
return Boolean(Settings.enableHomepage)
case 'registration-page':
return (
!Features.externalAuthenticationSystemUsed() ||
Boolean(Settings.overleaf)
)
return Boolean(Settings.enableRegistrationPage)
case 'registration':
return Boolean(Settings.overleaf)
case 'chat':
@@ -68,7 +66,7 @@ const Features = {
case 'oauth':
return Boolean(Settings.oauth)
case 'templates-server-pro':
return Boolean(Settings.templates?.user_id)
return Boolean(Settings.templates)
case 'affiliations':
case 'analytics':
return Boolean(_.get(Settings, ['apis', 'v1', 'url']))
@@ -83,6 +83,7 @@ export const db = {
systemmessages: internalDb.collection('systemmessages'),
tags: internalDb.collection('tags'),
teamInvites: internalDb.collection('teamInvites'),
templates: internalDb.collection('templates'),
tokens: internalDb.collection('tokens'),
userAuditLogEntries: internalDb.collection('userAuditLogEntries'),
users: internalDb.collection('users'),
+8
View File
@@ -236,6 +236,8 @@ async function initialize(webRouter, privateApiRouter, publicApiRouter) {
CaptchaMiddleware.canSkipCaptcha
)
await Modules.applyRouter(webRouter, privateApiRouter, publicApiRouter)
webRouter.get('/login', UserPagesController.loginPage)
AuthenticationController.addEndpointToLoginWhitelist('/login')
@@ -281,6 +283,8 @@ async function initialize(webRouter, privateApiRouter, publicApiRouter) {
'/read-only/one-time-login'
)
await Modules.applyRouter(webRouter, privateApiRouter, publicApiRouter)
webRouter.get('/logout', UserPagesController.logout)
webRouter.post('/logout', UserController.logout)
@@ -1271,6 +1275,10 @@ async function initialize(webRouter, privateApiRouter, publicApiRouter) {
)
}
webRouter.get(['/learn*', '/blog*', '/latex*', '/for/*', '/contact*'], (req, res) => {
res.redirect(301, `https://www.overleaf.com${req.originalUrl}`)
})
webRouter.get('/unsupported-browser', renderUnsupportedBrowserPage)
webRouter.get('*', ErrorController.notFound)
+5
View File
@@ -14,6 +14,7 @@ block content
.nav-tabs-container
ul.nav.nav-tabs.align-left(role='tablist')
+bookmarkable-tabset-header('system-messages', 'System Messages', true)
+bookmarkable-tabset-header('active-projects', 'Active Projects')
+bookmarkable-tabset-header('open-sockets', 'Open Sockets')
+bookmarkable-tabset-header('open-close-editor', 'Open/Close Editor')
if hasFeature('saas')
@@ -42,6 +43,10 @@ block content
input(name='_csrf' type='hidden' value=csrfToken)
button.btn.btn-danger(type='submit') Clear all messages
.tab-pane(role='tabpanel' id='active-projects')
.row-spaced
include ../../../modules/admin-tools/app/views/active-projects.pug
.tab-pane(role='tabpanel' id='open-sockets')
.row-spaced
ul
@@ -66,7 +66,7 @@ nav.navbar.navbar-default.navbar-main.navbar-expand-lg(
+dropdown-menu-link-item(href='/admin') Manage Site
+dropdown-menu-link-item(href='/admin/user') Manage Users
if canDisplayProjectUrlLookup
+dropdown-menu-link-item(href='/admin/project') Project URL Lookup
+dropdown-menu-link-item(href='/admin/project') Manage Projects
if canDisplayAdminRedirect
+dropdown-menu-link-item(href=settings.adminUrl) Switch to Admin
if canDisplaySplitTestMenu
@@ -151,6 +151,18 @@ nav.navbar.navbar-default.navbar-main.navbar-expand-lg(
// logged out
if !getSessionUser()
// templates link
if settings.templates
+nav-item
+nav-link(
href="/templates"
event-tracking="menu-click"
event-tracking-action="clicked"
event-tracking-trigger="click"
event-tracking-mb="true"
event-segmentation={ page: currentUrl, item: 'templates', location: 'top-menu' }
) #{translate('templates')}
// register link
if hasFeature('registration-page')
+nav-item.primary
@@ -29,8 +29,10 @@ block content
input(type="hidden" name="templateVersionId" value=templateVersionId)
input(type="hidden" name="templateName" value=name)
input(type="hidden" name="compiler" value=compiler)
input(type="hidden" name="imageName" value=imageName)
if imageName
input(type="hidden" name="imageName" value=imageName)
input(type="hidden" name="mainFile" value=mainFile)
input(type="hidden" name="language" value=language)
if brandVariationId
input(type="hidden" name="brandVariationId" value=brandVariationId)
input(hidden type="submit")
+20 -1
View File
@@ -26,8 +26,9 @@ block content
label(for='email') #{translate("email")}
input#email.form-control(
name='email'
type='email'
type=(settings.ldap && settings.ldap.enable) ? 'text' : 'email'
required
placeholder=(settings.ldap && settings.ldap.enable) ? settings.ldap.placeholder : 'email@example.com'
autofocus='true'
autocomplete='username'
)
@@ -47,3 +48,21 @@ block content
if login_support_text
hr
p.text-center !{login_support_text}
if settings.saml && settings.saml.enable
.actions(style='margin-top: 30px;')
a.button.btn-secondary.btn(
href='/saml/login',
style="width: 100%;"
data-ol-disabled-inflight
)
span(data-ol-inflight="idle") #{settings.saml.identityServiceName}
span(hidden data-ol-inflight="pending") #{translate("logging_in")}…
if settings.oidc && settings.oidc.enable
.actions(style='margin-top: 30px;')
a.button.btn-secondary.btn(
href='/oidc/login',
style="width: 100%;"
data-ol-disabled-inflight
)
span(data-ol-inflight="idle") #{settings.oidc.identityServiceName}
span(hidden data-ol-inflight="pending") #{translate("logging_in")}…
@@ -50,7 +50,7 @@ block content
+notification({ariaLive: 'assertive', type: 'error', className: 'mb-3', content: translate(error)})
div(data-ol-custom-form-message='no-password-allowed-due-to-sso' hidden)
+notification({ariaLive: 'polite', type: 'error', className: 'mb-3', content: translate('you_cant_reset_password_due_to_sso', {}, [{name: 'a', attrs: {href: '/sso-login'}}])})
+notification({ariaLive: 'polite', type: 'error', className: 'mb-3', content: translate('you_cant_reset_password_due_to_ldap_or_sso')})
input(name='_csrf' type='hidden' value=csrfToken)
.form-group.mb-3
label.form-label(for='email') #{translate("email")}
+157 -19
View File
@@ -271,6 +271,9 @@ module.exports = {
realTime: {
url: `http://${process.env.REALTIME_HOST || '127.0.0.1'}:3026`,
},
linkedUrlProxy: {
url: `http://${process.env.LINKED_URL_PROXY_HOST || '127.0.0.1'}:3066`,
},
notifications: {
url: `http://${process.env.NOTIFICATIONS_HOST || '127.0.0.1'}:3042`,
},
@@ -379,7 +382,9 @@ module.exports = {
process.env.PROJECT_UPLOAD_TIMEOUT || '120000',
10
),
maxUploadSize: 50 * 1024 * 1024, // 50 MB
maxUploadSize: process.env.MAX_UPLOAD_SIZE
? parseInt(process.env.MAX_UPLOAD_SIZE, 10) * 1024 * 1024
: 50 * 1024 * 1024, // 50 MB
multerOptions: {
preservePath: process.env.MULTER_PRESERVE_PATH,
},
@@ -1020,14 +1025,39 @@ module.exports = {
//
// Restart webpack after making changes.
//
createFileModes: [],
createFileModes: [
Path.resolve(
__dirname,
'../modules/zotero/frontend/js/components/zotero-create-file'
),
],
devToolbar: [],
gitBridge: [],
publishModal: [],
tprFileViewInfo: [],
tprFileViewRefreshError: [],
tprFileViewRefreshButton: [],
tprFileViewNotOriginalImporter: [],
tprFileViewInfo: [
Path.resolve(
__dirname,
'../modules/zotero/frontend/js/components/tpr-file-view-info'
),
],
tprFileViewRefreshError: [
Path.resolve(
__dirname,
'../modules/zotero/frontend/js/components/tpr-file-view-refresh-error'
),
],
tprFileViewRefreshButton: [
Path.resolve(
__dirname,
'../modules/zotero/frontend/js/components/tpr-file-view-refresh-button'
),
],
tprFileViewNotOriginalImporter: [
Path.resolve(
__dirname,
'../modules/zotero/frontend/js/components/tpr-file-view-not-original-importer'
),
],
contactUsModal: [],
sourceEditorExtensions: [],
sourceEditorVisualExtensions: [],
@@ -1038,25 +1068,66 @@ module.exports = {
pdfPreviewPromotions: [],
diagnosticActions: [],
sourceEditorCompletionSources: [],
sourceEditorSymbolPalette: [],
sourceEditorSymbolPalette: [
Path.resolve(
__dirname,
'../modules/symbol-palette/frontend/components/symbol-palette'
),
],
sourceEditorToolbarStartButtons: [],
sourceEditorToolbarButtonGroups: [],
sourceEditorToolbarComponents: [],
sourceEditorToolbarEndButtons: [],
rootContextProviders: [],
mainEditorLayoutModals: [],
mainEditorLayoutModals: [
Path.resolve(
__dirname,
'../modules/reference-picker/frontend/components/reference-picker-controller.tsx'
),
],
mainEditorLayoutPanels: [],
pythonRunner: [],
langFeedbackLinkingWidgets: [],
labsExperiments: [],
integrationLinkingWidgets: [],
referenceLinkingWidgets: [],
importProjectFromGithubModalWrapper: [],
importProjectFromGithubMenu: [],
integrationLinkingWidgets: [
Path.resolve(
__dirname,
'../modules/github-sync/frontend/js/components/github-sync-widget.tsx'
),
],
referenceLinkingWidgets: [
Path.resolve(
__dirname,
'../modules/zotero/frontend/js/components/zotero-widget'
),
],
importProjectFromGithubModalWrapper: [
Path.resolve(
__dirname,
'../modules/github-sync/frontend/js/components/import-from-github-modal-wrapper.tsx'
),
],
importProjectFromGithubMenu: [
Path.resolve(
__dirname,
'../modules/github-sync/frontend/js/components/import-from-github-menu.tsx'
),
],
editorLeftMenuSync: [],
editorLeftMenuManageTemplate: [],
menubarExtraComponents: [],
menubarExtraComponents: [
Path.resolve(
__dirname,
'../modules/template-gallery/frontend/js/features/template/components/menubar-manage-template'
),
],
insertMenuSections: [],
oauth2Server: [],
oauth2Server: [
Path.resolve(
__dirname,
'../modules/git-bridge/frontend/js/widget/components/git-integration-widget.tsx'
)
],
managedGroupSubscriptionEnrollmentNotification: [],
managedGroupEnrollmentInvite: [],
ssoCertificateInfo: [],
@@ -1067,7 +1138,12 @@ module.exports = {
rollingBuildsUpdatedAlert: [],
offlineModeToolbarButtons: [],
settingsEntries: [],
autoCompleteExtensions: [],
autoCompleteExtensions: [
Path.resolve(
__dirname,
'../modules/reference-picker/frontend/extensions/reference-picker-keybinding.ts'
),
],
sectionTitleGenerators: [],
toastGenerators: [
Path.resolve(
@@ -1093,12 +1169,31 @@ module.exports = {
'../modules/full-project-search/frontend/js/components/full-project-search.tsx'
),
],
integrationPanelComponents: [],
integrationPanelComponents: [
Path.resolve(
__dirname,
'../modules/github-sync/frontend/js/components/github-integration-card.tsx'
),
Path.resolve(
__dirname,
'../modules/git-bridge/frontend/js/card/components/git-integration-card.tsx'
),
Path.resolve(
__dirname,
'../modules/zotero/frontend/js/components/zotero-integration-card.tsx'
),
],
referenceSearchSetting: [],
settingsModalEditorTabSections: [],
settingsModalSpellcheckSections: [],
editorFloatingMenuActions: [],
errorLogsComponents: [],
referenceIndices: [],
referenceIndices: [
Path.resolve(
__dirname,
'../modules/reference-picker/frontend/reference-index/advanced-reference-index.ts'
),
],
railEntries: [],
railPopovers: [],
railActions: [],
@@ -1109,7 +1204,19 @@ module.exports = {
'history-v1',
'launchpad',
'server-ce-scripts',
'user-activate',
'sandboxed-compiles',
'symbol-palette',
'reference-picker',
'track-changes',
'authentication/ldap',
'authentication/saml',
'authentication/oidc',
'admin-tools', // import after authentication
'registration-page', // import after authentication
'template-gallery',
'git-bridge',
'github-sync',
'zotero',
],
viewIncludes: {},
@@ -1123,7 +1230,6 @@ module.exports = {
'app/views/project/ide-react': [`img-src 'self' data: blob:`],
},
},
unsupportedBrowsers: {
ie: '<=11',
safari: '<15',
@@ -1138,6 +1244,38 @@ module.exports = {
},
enablePandocConversions: process.env.ENABLE_PANDOC_CONVERSIONS === 'true',
oauthProviders: {
...(process.env.EXTERNAL_AUTH && process.env.EXTERNAL_AUTH.includes('oidc') && {
[process.env.OVERLEAF_OIDC_PROVIDER_ID || 'oidc']: {
name: process.env.OVERLEAF_OIDC_PROVIDER_NAME || 'OIDC Provider',
descriptionKey: process.env.OVERLEAF_OIDC_PROVIDER_DESCRIPTION,
descriptionOptions: { link: process.env.OVERLEAF_OIDC_PROVIDER_INFO_LINK },
hideWhenNotLinked: process.env.OVERLEAF_OIDC_PROVIDER_HIDE_NOT_LINKED ?
process.env.OVERLEAF_OIDC_PROVIDER_HIDE_NOT_LINKED.toLowerCase() === 'true' : undefined,
linkPath: '/oidc/login',
},
}),
},
splitTestOverrides: {
...(process.env.ENABLE_EDITOR_TABS?.toLowerCase() === 'true' ? {
'editor-tabs': 'enabled',
} : {}),
...(process.env.ENABLE_PANDOC_CONVERSIONS === 'true' ? {
'import-docx': 'enabled',
'import-markdown': 'enabled',
'export-docx': 'enabled',
'export-html': 'enabled',
'export-markdown': 'enabled',
} : {}),
...(process.env.OVERLEAF_HISTORY_RESTORE?.toLowerCase() === 'true' ? {
'history-ranges-support': 'enabled',
'revert-file': 'enabled',
'revert-project': 'enabled',
} : {}),
},
}
module.exports.mergeWith = function (overrides) {
@@ -24,17 +24,28 @@
"a_new_reference_was_added_to_file_from_provider": "",
"a_new_version_of_the_rolling_texlive_build_released": "",
"about_to_archive_projects": "",
"about_to_delete_accounts": "",
"about_to_delete_cert": "",
"about_to_delete_projects": "",
"about_to_delete_tag": "",
"about_to_delete_template": "",
"about_to_delete_the_following_project": "",
"about_to_delete_the_following_projects": "",
"about_to_delete_user_preamble": "",
"about_to_enable_managed_users": "",
"about_to_leave_project": "",
"about_to_leave_projects": "",
"about_to_permanently_delete_accounts": "",
"about_to_permanently_delete_projects": "",
"about_to_remove_user_preamble": "",
"about_to_resend_activation_email": "",
"about_to_restore_accounts": "",
"about_to_restore_projects": "",
"about_to_resume_accounts": "",
"about_to_set_admin_accounts": "",
"about_to_suspend_accounts": "",
"about_to_trash_projects": "",
"about_to_unset_admin_accounts": "",
"abstract": "",
"accept_all_cookies": "",
"accept_and_continue": "",
@@ -59,6 +70,7 @@
"account_has_been_link_to_institution_account": "",
"account_has_past_due_invoice_change_plan_warning": "",
"account_help": "",
"account_information": "",
"account_managed_by_group_administrator": "",
"account_managed_by_group_teamname": "",
"account_not_linked_to_dropbox": "",
@@ -66,6 +78,7 @@
"acct_linked_to_institution_acct_2": "",
"action_needed": "",
"actions": "",
"activation_link": "",
"active": "",
"add": "",
"add_a_recovery_email_address": "",
@@ -150,6 +163,8 @@
"all_project_activity_description": "",
"all_projects": "",
"all_projects_will_be_transferred_immediately": "",
"all_templates": "",
"all_users": "",
"all_these_experiments_are_available_exclusively": "",
"allocate_license": "",
"allows_to_search_by_author_title_etc_possible_to_pull_results_directly_from_your_reference_manager_if_connected": "",
@@ -182,6 +197,8 @@
"are_you_still_at": "",
"are_you_sure_you_want_to_cancel_add_on": "",
"as_email": "",
"ask_proj_owner_to_add_you_as_github_collaborator": "",
"ask_proj_owner_to_export_to_github": "",
"ask_proj_owner_to_unlink_from_current_github": "",
"ask_proj_owner_to_upgrade_for_full_history": "",
"ask_repo_owner_to_reconnect": "",
@@ -189,6 +206,7 @@
"at_most_x_libraries_can_be_selected": "",
"attach_image_or_pdf": "",
"audit_logs": "",
"author": "",
"auto_close_brackets": "",
"auto_compile": "",
"auto_complete": "",
@@ -207,6 +225,7 @@
"back_to_my_projects": "",
"back_to_pdf": "",
"back_to_subscription": "",
"back_to_user_list": "",
"back_to_your_projects": "",
"basic_compile_time": "",
"before_you_use_error_assistant": "",
@@ -263,6 +282,8 @@
"card_must_be_authenticated_by_3dsecure": "",
"card_payment": "",
"careers": "",
"categories": "",
"category": "",
"category_arrows": "",
"category_greek": "",
"category_misc": "",
@@ -382,6 +403,7 @@
"contacting_the_sales_team": "",
"continue": "",
"continue_github_merge": "",
"continue_github_merge": "",
"continue_to": "",
"continue_using_free_features": "",
"continue_with_free_plan": "",
@@ -430,6 +452,7 @@
"cut": "",
"dark_mode_pdf_preview": "",
"dark_themes": "",
"date": "",
"date_and_owner": "",
"date_and_time": "",
"dealing_with_errors": "",
@@ -438,6 +461,7 @@
"delete_account": "",
"delete_account_confirmation_label": "",
"delete_account_warning_message_3": "",
"delete_accounts": "",
"delete_acct_no_existing_pw": "",
"delete_and_leave": "",
"delete_and_leave_projects": "",
@@ -459,6 +483,7 @@
"delete_sso_config": "",
"delete_table": "",
"delete_tag": "",
"delete_template": "",
"delete_token": "",
"delete_user": "",
"delete_your_account": "",
@@ -467,6 +492,7 @@
"deleted_by_id": "",
"deleted_by_ip": "",
"deleted_by_on": "",
"deleted_projects": "",
"deleted_user": "",
"deleting": "",
"demonstrating_git_integration": "",
@@ -581,6 +607,7 @@
"edit_sso_configuration": "",
"edit_tag": "",
"edit_tag_name": "",
"edit_template": "",
"edit_your_custom_dictionary": "",
"edited": "",
"editing": "",
@@ -701,6 +728,7 @@
"files_cannot_include_invalid_characters": "",
"files_selected": "",
"filter_projects": "",
"filter_users": "",
"find": "",
"find_and_check_citations": "",
"find_out_how_to_get_the_most_out_of_your_new_subscription": "",
@@ -821,6 +849,9 @@
"github_timeout_error": "",
"github_too_many_files_error": "",
"github_validation_check": "",
"github_validation_check_auth": "",
"github_validation_name_exists": "",
"github_validation_name_invalid": "",
"github_workflow_authorize": "",
"github_workflow_files_delete_github_repo": "",
"github_workflow_files_error": "",
@@ -961,8 +992,10 @@
"imported_from_papers_at_date": "",
"imported_from_the_output_of_another_project_at_date": "",
"imported_from_zotero_at_date": "",
"imported_from_zotero_at_date_by": "",
"importing": "",
"importing_and_merging_changes_in_github": "",
"inactive_projects": "",
"in_order_to_match_institutional_metadata_2": "",
"in_order_to_match_institutional_metadata_associated": "",
"inactive": "",
@@ -1090,6 +1123,7 @@
"last_name": "",
"last_resort_trouble_shooting_guide": "",
"last_suggested_fix": "",
"last_updated": "",
"last_updated_date_by_x": "",
"last_used": "",
"last_verification_attempt": "",
@@ -1098,6 +1132,8 @@
"latam_discount_modal_title": "",
"latex_places_figures_according_to_a_special_algorithm": "",
"latex_places_tables_according_to_a_special_algorithm": "",
"latex_templates": "",
"latex_templates_for_journal_articles": "",
"layout_options": "",
"learn_more": "",
"learn_more_about": "",
@@ -1280,12 +1316,14 @@
"need_to_add_new_primary_before_remove": "",
"need_to_leave": "",
"neither_agree_nor_disagree": "",
"never": "",
"new": "",
"new_compile_domain_notice": "",
"new_compiles_in_this_project_will_automatically_use_the_newest_version": "",
"new_file": "",
"new_folder": "",
"new_name": "",
"new_owner": "",
"new_password": "",
"new_project": "",
"new_reference": "",
@@ -1334,7 +1372,9 @@
"no_search_results": "",
"no_selection_select_file": "",
"no_symbols_found": "",
"no_templates_found": "",
"no_thanks_cancel_now": "",
"no_users": "",
"non_blinking_cursor": "",
"normal": "",
"normally_x_price_per_month": "",
@@ -1346,6 +1386,7 @@
"notification_personal_and_group_subscriptions": "",
"notification_project_invite_accepted_message": "",
"notification_project_invite_message": "",
"notify_users_about_account_deletion": "",
"number_of_users": "",
"numbered_list": "",
"oauth_orcid_description": "",
@@ -1370,6 +1411,7 @@
"only_project_owner_can_link_github": "",
"open_action_menu": "",
"open_advanced_reference_search": "",
"open_as_template": "",
"open_each_file_in_its_own_tab": "",
"open_file": "",
"open_files_in_tabs": "",
@@ -1382,6 +1424,7 @@
"optional": "",
"or": "",
"or_enable_clipboard_access_in_your_browser_settings": "",
"organization": "",
"organization_name": "",
"organize_tags": "",
"other": "",
@@ -1399,12 +1442,15 @@
"overleaf_labs": "",
"overleaf_learning_center": "",
"overleaf_logo": "",
"overleaf_template_gallery": "",
"overleafs_functionality_meets_my_needs": "",
"overview": "",
"overwrite": "",
"overwriting_the_original_folder": "",
"owned_by_x": "",
"owned_projects": "",
"owner": "",
"ownership_of_projects_will_be_transferred": "",
"page_current": "",
"page_x_of_n": "",
"pagination_navigation": "",
@@ -1461,9 +1507,11 @@
"pending_subscription_message": "",
"per_license": "",
"per_month": "",
"per_month_x_annually": "",
"per_page": "",
"per_year": "",
"percent_is_the_percentage_of_the_line_width": "",
"permanently_delete_accounts": "",
"permanently_delete_projects": "",
"permanently_disables_the_preview": "",
"personal_library": "",
"pick_up_where_you_left_off": "",
@@ -1473,6 +1521,7 @@
"please_ask_the_project_owner_to_upgrade_to_track_changes": "",
"please_change_primary_to_remove": "",
"please_compile_pdf_before_download": "",
"please_compile_pdf_before_publish_as_template": "",
"please_confirm_primary_email_or_edit": "",
"please_confirm_secondary_email_or_edit": "",
"please_confirm_your_email_before_making_it_default": "",
@@ -1509,8 +1558,10 @@
"presentation_mode": "",
"press_shift_space_for_suggestions": "",
"press_space_to_open_the_ai_assistant": "",
"prev": "",
"preview": "",
"preview_editor_tabs": "",
"previous": "",
"previous_page": "",
"previous_suggestion": "",
"price": "",
@@ -1537,6 +1588,7 @@
"project_actions": "",
"project_approaching_file_limit": "",
"project_categories_tags": "",
"problem_checking_connection_with_provider": "",
"project_figure_modal": "",
"project_files_history": "",
"project_flagged_too_many_compiles": "",
@@ -1578,6 +1630,7 @@
"publisher_account": "",
"publishing": "",
"pull_github_changes_into_sharelatex": "",
"purge": "",
"push_sharelatex_changes_to_github": "",
"push_to_github_pull_to_overleaf": "",
"quoted_text": "",
@@ -1624,10 +1677,13 @@
"reference_managers": "",
"reference_search": "",
"reference_search_setting": "",
"reference_search_results": "",
"reference_search_settings": "",
"reference_search_style": "",
"reference_sync": "",
"references_from_these_libraries_will_be_included_in_your_reference_search_results": "",
"references_picker_empty_hint": "",
"references_picker_title": "",
"refresh": "",
"refresh_page_after_linking_dropbox": "",
"refresh_page_after_starting_free_trial": "",
@@ -1682,6 +1738,7 @@
"repository_visibility": "",
"republish": "",
"resend": "",
"resend_activation_email": "",
"resend_confirmation_code": "",
"resend_group_invite": "",
"resend_invite": "",
@@ -1694,6 +1751,8 @@
"resolve_comment_error_title": "",
"resolved_comments": "",
"restore": "",
"restore_accounts": "",
"restore_projects": "",
"restore_file": "",
"restore_file_confirmation_message": "",
"restore_file_confirmation_title": "",
@@ -1703,6 +1762,8 @@
"restore_project_to_this_version": "",
"restore_this_version": "",
"restoring": "",
"resume": "",
"resume_account": "",
"resync_completed": "",
"resync_message": "",
"resync_project_history": "",
@@ -1797,6 +1858,7 @@
"select_all": "",
"select_all_entries": "",
"select_all_projects": "",
"select_all_users": "",
"select_an_output_file": "",
"select_an_output_file_figure_modal": "",
"select_bib_file": "",
@@ -1813,6 +1875,7 @@
"select_image_from_project_files": "",
"select_project": "",
"select_projects": "",
"select_users": "",
"select_size": "",
"select_tag": "",
"select_tax_id_type": "",
@@ -1825,6 +1888,7 @@
"send": "",
"send_confirmation_code": "",
"send_message": "",
"send_notification_emails_to_users": "",
"send_request": "",
"sending": "",
"sentence_completion": "",
@@ -1837,6 +1901,8 @@
"session_expired_redirecting_to_login": "",
"sessions": "",
"set_as_main_document": "",
"set_admin": "",
"set_admin_account": "",
"set_color": "",
"set_column_width": "",
"set_up_single_sign_on": "",
@@ -1876,6 +1942,7 @@
"showing_x_results_plural": "",
"sidebar": "",
"sign_up": "",
"signed_up": "",
"simple_search_mode": "",
"single_sign_on_sso": "",
"size": "",
@@ -2011,6 +2078,9 @@
"sure_you_want_to_change_plan": "",
"sure_you_want_to_delete": "",
"sure_you_want_to_leave_group": "",
"suspend": "",
"suspend_account": "",
"switch_between_dark_and_light_mode": "",
"switch_compile_mode_for_faster_draft_compilation": "",
"switch_to_editor": "",
"switch_to_pdf": "",
@@ -2045,6 +2115,7 @@
"tell_the_project_owner_and_ask_them_to_upgrade": "",
"template": "",
"template_description": "",
"template_gallery": "",
"template_title_taken_from_project_title": "",
"templates": "",
"temporarily_hides_the_preview": "",
@@ -2100,6 +2171,7 @@
"they_will_retain_ownership_of_projects_currently_owned_by_them_and_collaborators_will_become_read_only": "",
"they_will_retain_their_existing_account_on_the_free_plan": "",
"they_wont_be_able_to_log_in_with_sso_they_will_need_to_set_password": "",
"this_action_can_be_undone_within_limited_period": "",
"this_action_cannot_be_reversed": "",
"this_action_cannot_be_undone": "",
"this_action_will_also_disable_domain_capture": "",
@@ -2223,6 +2295,7 @@
"track_changes": "",
"tracked_change_added": "",
"tracked_change_deleted": "",
"transfer_all_projects_to": "",
"transfer_management_of_your_account": "",
"transfer_management_of_your_account_to_x": "",
"transfer_management_resolve_following_issues": "",
@@ -2234,6 +2307,7 @@
"trashed": "",
"trashed_projects": "",
"trashing_projects_wont_affect_collaborators": "",
"trashing_projects_wont_affect_user_collaborators": "",
"trial_last_day": "",
"trial_remaining_days": "",
"tried_to_log_in_with_email": "",
@@ -2241,6 +2315,7 @@
"try_again": "",
"try_for_free": "",
"try_now": "",
"try_recompile_project": "",
"try_recompile_project_or_troubleshoot": "",
"try_relinking_provider": "",
"try_to_compile_despite_errors": "",
@@ -2297,6 +2372,8 @@
"unpausing": "",
"unpublish": "",
"unpublishing": "",
"unset_admin": "",
"unset_admin_account": "",
"unsubscribe": "",
"until_then_you_can_still": "",
"untrash": "",
@@ -2343,6 +2420,17 @@
"used_latex_response_occasionally": "",
"used_latex_response_often": "",
"used_when_referring_to_the_figure_elsewhere_in_the_document": "",
"user_activity": "",
"user_categories": "",
"user_category_admin": "",
"user_category_all": "",
"user_category_deleted": "",
"user_category_inactive": "",
"user_category_ldap": "",
"user_category_local": "",
"user_category_oidc": "",
"user_category_saml": "",
"user_category_suspended": "",
"user_deletion_error": "",
"user_deletion_password_reset_tip": "",
"user_email_attribute": "",
@@ -2352,6 +2440,7 @@
"user_management": "",
"user_personal_access_tokens": "",
"user_sessions": "",
"users_list": "",
"using_latex": "",
"using_premium_features": "",
"using_the_overleaf_editor": "",
@@ -2398,6 +2487,7 @@
"view_options": "",
"view_payment_portal": "",
"view_payment_portal_disclaimer": "",
"view_pdf": "",
"view_your_invoices": "",
"viewer": "",
"viewing": "",
@@ -2492,6 +2582,7 @@
"you_can_select_or_invite_collaborator": "",
"you_can_select_or_invite_collaborator_plural": "",
"you_can_still_use_your_premium_features": "",
"you_cant_add_or_change_password_due_to_ldap_or_sso": "",
"you_cant_add_or_change_password_due_to_sso": "",
"you_cant_join_this_group_subscription": "",
"you_currently_have_x_linked_with_your_overleaf_account": "",
@@ -2579,6 +2670,7 @@
"zoom_out": "",
"zoom_to": "",
"zotero": "",
"zotero_account_linked_successfully": "",
"zotero_dynamic_sync_description": "",
"zotero_groups_loading_error": "",
"zotero_groups_relink": "",
@@ -2587,6 +2679,7 @@
"zotero_reference_loading_error": "",
"zotero_reference_loading_error_expired": "",
"zotero_reference_loading_error_forbidden": "",
"zotero_reference_loading_error_not_linked": "",
"zotero_sync_description": "",
"zotero_upgrade_prompt_content": "",
"zotero_upgrade_prompt_title": ""
@@ -5,6 +5,7 @@
export default /** @type {const} */ ([
'account_balance',
'add_moderator',
'arrow_back_ios_new',
'arrow_circle_up',
'auto_delete',
@@ -28,6 +29,7 @@ export default /** @type {const} */ ([
'domain',
'edit',
'edit_square',
'edit',
'error',
'experiment',
'find_replace',
@@ -39,7 +41,7 @@ export default /** @type {const} */ ([
'help',
'image',
'info',
'info',
'info_i',
'integration_instructions',
'lightbulb',
'lightbulb_2',
@@ -53,12 +55,16 @@ export default /** @type {const} */ ([
'notifications',
'open_in_new',
'password',
'pause_circle',
'person',
'person_edit',
'picture_as_pdf',
'play_circle',
'push_pin',
'rate_review',
'remove_moderator',
'report',
'restore_from_trash',
'search',
'settings',
'shuffle',
@@ -13,11 +13,16 @@ import { FullSizeLoadingSpinner } from '@/shared/components/loading-spinner'
import getMeta from '@/utils/meta'
import OLNotification from '@/shared/components/ol/ol-notification'
const createFileModeModules = importOverleafModules('createFileModes') as {
const allCreateFileModeModules = importOverleafModules('createFileModes') as {
import: { CreateFilePane: ElementType; CreateFileMode: ElementType }
path: string
}[]
const createFileModeModules = allCreateFileModeModules.filter(
({ path }) =>
(getMeta('ol-ExposedSettings').zoteroEnabled || !path.includes('zotero-create-file'))
)
const FileTreeUploadDoc = lazy(() => import('./modes/file-tree-upload-doc'))
export default function FileTreeModalCreateFileBody() {
@@ -487,7 +487,13 @@ export const FileTreeActionableProvider: FC<React.PropsWithChildren> = ({
const finishCreatingLinkedFile = useCallback(
(entity: Omit<NewLinkedFileEntity, 'endpoint'>) => {
return finishCreatingDocOrFile({ ...entity, endpoint: 'linked_file' })
const shouldReindexReferences = /\.bib$/.test(entity.name)
return finishCreatingDocOrFile({ ...entity, endpoint: 'linked_file' }).
then(() => {
if (shouldReindexReferences) {
indexAllReferences(true)
}
})
},
[finishCreatingDocOrFile]
)
@@ -15,6 +15,14 @@ export type LinkedFileData = {
source_project_id: string
source_output_file_path: string
}
zotero: {
provider: 'zotero'
zoteroGroupId?: string
importedAt: Date | string
importedByUserId: string
importedByName: string
bibFormat: 'bibtex' | 'biblatex'
}
}
export type BinaryFile<T extends keyof LinkedFileData = keyof LinkedFileData> =
@@ -71,7 +71,7 @@ export const RailLayout = () => {
const { features } = useProjectContext()
const { isRestrictedTokenMember } = useEditorContext()
const gitBridgeEnabled = getMeta('ol-gitBridgeEnabled')
const { isOverleaf } = getMeta('ol-ExposedSettings')
const { isOverleaf, githubSyncEnabled, zoteroEnabled } = getMeta('ol-ExposedSettings')
const { view, setLeftMenuShown, focusMode } = useLayoutContext()
@@ -119,7 +119,7 @@ export const RailLayout = () => {
icon: 'integration_instructions',
title: t('integrations'),
component: <IntegrationsPanel />,
hide: !isOverleaf && !gitBridgeEnabled,
hide: !isOverleaf && !gitBridgeEnabled && !githubSyncEnabled && !zoteroEnabled,
},
{
key: 'review-panel',
@@ -148,6 +148,8 @@ export const RailLayout = () => {
isRestrictedTokenMember,
isOverleaf,
gitBridgeEnabled,
githubSyncEnabled,
zoteroEnabled,
]
)
@@ -235,7 +235,7 @@ export const EditorManagerProvider: FC<React.PropsWithChildren> = ({
}
if (
update.meta.type === 'external' &&
update.meta.source === 'git-bridge'
(update.meta.source === 'git-bridge' || update.meta.source === 'github')
) {
return
}
@@ -2,11 +2,19 @@ import { ElementType } from 'react'
import importOverleafModules from '../../../macros/import-overleaf-module.macro'
import { useTranslation } from 'react-i18next'
import RailPanelHeader from '@/features/ide-react/components/rail/rail-panel-header'
import getMeta from '../../utils/meta'
const integrationPanelComponents = importOverleafModules(
const allIntegrationPanelComponents = importOverleafModules(
'integrationPanelComponents'
) as { import: { default: ElementType }; path: string }[]
const integrationPanelComponents = allIntegrationPanelComponents.filter(
({ path }) =>
(getMeta('ol-gitBridgeEnabled') || !path.includes('git-bridge')) &&
(getMeta('ol-ExposedSettings').githubSyncEnabled || !path.includes('github-sync')) &&
(getMeta('ol-ExposedSettings').zoteroEnabled || !path.includes('zotero'))
)
export default function IntegrationsPanel() {
const { t } = useTranslation()
@@ -58,7 +58,7 @@ function NewProjectButton({
align,
}: NewProjectButtonProps) {
const { t } = useTranslation()
const { templateLinks } = getMeta('ol-ExposedSettings')
const { templateLinks, githubSyncEnabled } = getMeta('ol-ExposedSettings')
const [modal, setModal] =
useState<Nullable<NewProjectButtonModalVariant>>(null)
const portalTemplates = getMeta('ol-portalTemplates') || []
@@ -166,7 +166,7 @@ function NewProjectButton({
[sendProjectListMB, sendTrackingEvent]
)
const [importProjectFromGithubMenu] = importOverleafModules(
const [importProjectFromGithubMenu] = !githubSyncEnabled ? [] : importOverleafModules(
'importProjectFromGithubMenu'
)
@@ -68,7 +68,7 @@ function WelcomeMessageCreateNewProjectDropdown({
useFeatureFlag('import-markdown') &&
getMeta('ol-ExposedSettings').enablePandocConversions
const { isOverleaf } = getMeta('ol-ExposedSettings')
const { isOverleaf, githubSyncEnabled } = getMeta('ol-ExposedSettings')
const handleDropdownItemClick = useCallback(
(
@@ -170,7 +170,7 @@ function WelcomeMessageCreateNewProjectDropdown({
</DropdownItem>
</li>
)}
{isOverleaf && (
{(isOverleaf || githubSyncEnabled) && (
<li role="none">
<DropdownItem
as="button"
@@ -44,7 +44,7 @@ export const ReviewPanelComment = memo<{
const handleResolveComment = useCallback(async () => {
setProcessing(true)
try {
await resolveThread(comment.op.t)
await resolveThread(comment.op.t, docId)
} catch (err) {
debugConsole.error(err)
showGenericMessageModal(
@@ -54,7 +54,7 @@ export const ReviewPanelComment = memo<{
} finally {
setProcessing(false)
}
}, [comment.op.t, resolveThread, showGenericMessageModal, t])
}, [comment.op.t, docId, resolveThread, showGenericMessageModal, t])
const handleEditMessage = useCallback(
async (commentId: CommentId, content: string) => {
@@ -110,7 +110,7 @@ export const ReviewPanelComment = memo<{
async (commentId: ThreadId) => {
setProcessing(true)
try {
await deleteThread(commentId)
await deleteThread(commentId, docId)
} catch (err) {
debugConsole.error(err)
showGenericMessageModal(
@@ -121,7 +121,7 @@ export const ReviewPanelComment = memo<{
setProcessing(false)
}
},
[deleteThread, showGenericMessageModal, t]
[deleteThread, docId, showGenericMessageModal, t]
)
const handleSubmitReply = useCallback(
@@ -17,7 +17,8 @@ export const ReviewPanelResolvedThread: FC<{
id: ThreadId
comment: Change<CommentOperation>
docName: string
}> = ({ id, comment, docName }) => {
docId: string
}> = ({ id, comment, docName, docId }) => {
const { t } = useTranslation()
const { reopenThread, deleteThread } = useThreadsActionsContext()
const [processing, setProcessing] = useState(false)
@@ -33,7 +34,7 @@ export const ReviewPanelResolvedThread: FC<{
const handleReopenThread = useCallback(async () => {
setProcessing(true)
try {
await reopenThread(id)
await reopenThread(id, docId)
} catch (err) {
debugConsole.error(err)
showGenericMessageModal(
@@ -43,12 +44,12 @@ export const ReviewPanelResolvedThread: FC<{
} finally {
setProcessing(false)
}
}, [id, reopenThread, showGenericMessageModal, t])
}, [id, docId, reopenThread, showGenericMessageModal, t])
const handleDeleteThread = useCallback(async () => {
setProcessing(true)
try {
await deleteThread(id)
await deleteThread(id, docId)
} catch (err) {
debugConsole.error(err)
showGenericMessageModal(
@@ -58,7 +59,7 @@ export const ReviewPanelResolvedThread: FC<{
} finally {
setProcessing(false)
}
}, [id, deleteThread, showGenericMessageModal, t])
}, [id, docId, deleteThread, showGenericMessageModal, t])
return (
<div
@@ -18,7 +18,7 @@ export const ReviewPanelResolvedThreadsMenu: FC = () => {
const { projectRanges, loading } = useProjectRanges()
const docNameForThread = useMemo(() => {
const docNameForThread = new Map<string, string>()
const docNameForThread = new Map<string, { docId: string; docName: string }>()
const otMigrationStage = getMeta('ol-otMigrationStage')
for (const [docId, ranges] of projectRanges?.entries() ?? []) {
@@ -28,7 +28,7 @@ export const ReviewPanelResolvedThreadsMenu: FC = () => {
if (docName !== undefined) {
for (const comment of ranges.comments) {
const threadId = comment.op.t
docNameForThread.set(threadId, docName)
docNameForThread.set(threadId, { docId, docName })
}
}
}
@@ -112,7 +112,8 @@ export const ReviewPanelResolvedThreadsMenu: FC = () => {
key={thread.id}
id={thread.id as ThreadId}
comment={comment}
docName={docNameForThread.get(thread.id) ?? t('unknown')}
docName={docNameForThread.get(thread.id)?.docName ?? t('unknown')}
docId={docNameForThread.get(thread.id)?.docId}
/>
)
})}

Some files were not shown because too many files have changed in this diff Show More