Compare commits

..
Author SHA1 Message Date
yu-i-i 377732a832 Add hotfixes 6.1.1 and 6.1.2 (adapted) 2026-03-15 03:39:16 +01:00
yu-i-i 362fc56949 Update README.md 2026-03-15 01:42:06 +01:00
yu-i-i 9d00984b97 Sandboxed compiles: add scripts to add/strip repo prefix from texlive images 2026-03-15 01:42:05 +01:00
yu-i-i 14d0300fc5 Add env variable to enable restoring project/file from history snapshot 2026-03-15 01:42:05 +01:00
yu-i-i fdb7578742 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-03-15 01:42:05 +01:00
yu-i-i c250e705b8 Git Bridge: Add git integration 2026-03-15 01:41:49 +01:00
yu-i-i eb53dd3b22 Sandboxed compiles: set imageName to default if undefined in project 2026-03-14 05:13:52 +01:00
yu-i-i 860b999ce2 Authentication: update passport-ldapauth to 3.0.1; fix minor issues 2026-03-14 05:13:52 +01:00
yu-i-i bb0804c6eb Linked URL: prevent SSRF via DNS rebinding; minor fixes 2026-03-14 05:13:51 +01:00
yu-i-i 7b407d2523 Template gallery: add template management authorization middleware
- Middleware to enforce template access rules
- Introduce template manager role
- Fix minor issues
2026-03-14 05:13:38 +01:00
yu-i-i 114911957e Admin tools: optimize user/project list performance
Add frontend pagination
Add search debouncing
Render modals conditionally
Remove unnecessary sorting
2026-03-13 21:04:13 +01:00
yu-i-i 0b8bcca8a0 Update README.md 2026-02-03 22:47:30 +01:00
yu-i-i e576fcb794 Sandboxed Compiles: pass imageName in Copy project 2026-02-03 20:47:33 +01:00
yu-i-i 9808a1d290 Admin tools: fix minor bugs 2026-02-03 20:04:16 +01:00
yu-i-i 523e5c3fcf Sandboxed compiles: add arm64 support to clsi seccomp profile 2026-02-02 18:26:21 +01:00
yu-i-i dad69464dd Sandboxed Compiles: support configurable texlive image root via env var 2026-02-02 18:26:21 +01:00
yu-i-i 00895bd201 Admin Tools: Fix EXTERNAL_AUTH is 'none' 2026-02-02 18:25:16 +01:00
yu-i-i 07b903b0b4 Admin Tools: Fix sorting 2026-02-02 18:25:16 +01:00
yu-i-i 73162171ee Template Gallery: migration to 6.1.0
enable menu for editor redisign
move frontend code to modules
2026-02-02 18:11:23 +01:00
yu-i-i 522704855f Symbol Palette: fix for 6.1.0 2026-01-29 15:54:54 +01:00
yu-i-i d22c71c7a6 Track changes: Fix import after upstream converted several files to ESM 2026-01-29 15:54:54 +01:00
yu-i-i d7378b42b7 Authentication: Fix import after upstream converted some files to ESM 2026-01-29 15:54:54 +01:00
yu-i-i 2d8a963e79 Admin Tools: Fix for 6.1.0 migraton 2026-01-29 15:54:54 +01:00
Guilhem Poy de6e491b06 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-01-29 15:54:54 +01:00
zhangziqian d4e11a1f80 Unlock overalltheme switching 2026-01-29 15:54:53 +01:00
yu-i-i 6f5acbd11b Admin Tools: Fix user name
fix user name is not updated

fix first_name/last_name is undefined
2026-01-29 15:54:53 +01:00
yu-i-i 103adeb820 Admin Tools: Manage users and Manage projects pages 2026-01-29 15:54:53 +01:00
yu-i-i b1db82ab0a Hotfix 5.5.6-ext-3.3 2026-01-29 15:54:53 +01:00
yu-i-i 5bc427623d Linked URL: add sanitize and normalize 2026-01-29 15:54:53 +01:00
yu-i-i f46927c3c3 README for extended CE 2026-01-29 15:54:52 +01:00
yu-i-i 22bee12e6b Add service for Linked URL feature 2026-01-29 15:54:52 +01:00
yu-i-i e3192dee6d Sandboxed compiles: adjust clsi-profile 2026-01-29 15:54:52 +01:00
yu-i-i 5c7e85fed1 Track changes: Fix import after upstream converted DocumentUpdaterHandler and CollaboratorsGetter to ESM 2026-01-29 15:54:52 +01:00
yu-i-i 7a0dc2364f Authentication: Fix import after upstream converted AuthenticationController to ESM 2026-01-29 15:54:52 +01:00
yu-i-i 4f8c0fb0a1 Template gallery: Fix import after upstream converted AuthenticationController, ProjectGetter, ProjectLocator and DocumentUpdaterHandler` to ESM 2026-01-29 15:54:52 +01:00
yu-i-i ed195212e0 Template gallery: Fix import after upstream converted CompileManager, ClsiManager and RateLimiterMiddleware to ESM 2026-01-29 15:54:52 +01:00
yu-i-i f6cfd0b71d Template gallery: Fix OLModal usage (see upstream commit 19b3834) 2026-01-29 15:54:52 +01:00
yu-i-i c35170ce61 Authentication: Fix import after upstream converted PermissionsManager, RateLimiterMiddleware, UserCreator and SAMLIdentityManager to ESM 2026-01-29 15:54:52 +01:00
yu-i-i 0c499ebc5b Track changes: Fix import after upstream converted ChatManager, UserInfoManager and UserInfoController to ESM 2026-01-29 15:54:51 +01:00
Rudy ERCEK c53c51a223 Add MAX_UPLOAD_SIZE environment variable 2026-01-29 15:54:51 +01:00
yu-i-i 370c6661f4 Fix style of Templates button in navbar 2026-01-29 15:54:51 +01:00
yu-i-i fea5749d0e Fix: comments thread does not necessarily belong to current document 2026-01-29 15:54:51 +01:00
yu-i-i 198bbb6fca Fix import after upstream converted AuthorizationMiddleware to ESM 2026-01-29 15:54:51 +01:00
yu-i-i 89b2b1910e Track changes: Use getProjectRanges introduced in the upstream 2026-01-29 15:54:51 +01:00
yu-i-i e3a976d2c2 Rename @node-saml/node-saml patch for v5.1.0 2026-01-29 15:54:51 +01:00
yu-i-i ab3660b121 Fix imports after upstream converted UserController and CaptchaMiddleware to ESM 2026-01-29 15:54:51 +01:00
yu-i-i 9bf4379f84 Fix import after upstream converted ErrorController to ESM 2026-01-29 15:54:51 +01:00
yu-i-i 05e929082a Bring back deleteFile removed upstream 2026-01-29 15:54:50 +01:00
yu-i-i 287653cfea Symbol palette: ui components were moved to shared folder 2026-01-29 15:54:50 +01:00
yu-i-i 3b3734756a Move Sympol Palette code to modules, closes #63 2026-01-29 15:54:50 +01:00
yu-i-i f41c73ee3d Template gallery: ui components were moved to shared folder 2026-01-29 15:54:50 +01:00
yu-i-i 4fd4e39199 passport-saml was updated to v5.1.0 2026-01-29 15:54:50 +01:00
yu-i-i b1609835a4 Fix: always include repository prefix in sandboxed compiles image name 2026-01-29 15:54:50 +01:00
yu-i-i 984a641a93 Fix template publishing to align with upstream project context changes 2026-01-29 15:54:50 +01:00
yu-i-i 0437f238de Remove LDAP admin check via group search in ldap-passport 2026-01-29 15:54:50 +01:00
yu-i-i eb94a0e3af toggleSymbolPalette now in useEditorPropertiesContext 2026-01-29 15:54:50 +01:00
yu-i-i 03206a00bf Set use-ai capability to false 2026-01-29 15:54:49 +01:00
yu-i-i 9cabcdee2e Track changes: convert to mjs 2026-01-29 15:54:49 +01:00
yu-i-i d668377045 Track changes: use getTrackedChangesUserIds introduced in the mainstream 2026-01-29 15:54:49 +01:00
yu-i-i 9088a32628 Remove OVERLEAF_OIDC_DISABLE_JIT_ACCOUNT_CREATION in favor of OVERLEAF_OIDC_ALLOWED_EMAIL_DOMAINS 2026-01-29 15:54:49 +01:00
Synésio Neto 19ac7b5e22 Introduce an environment variable to allow JIT OIDC users creation based on their email address domain. 2026-01-29 15:54:49 +01:00
yu-i-i b57053a3fb Introduce an environment variable to control user creation in OIDC authentication, closes #47 2026-01-29 15:54:49 +01:00
David Rotermund c5b3789630 I need the --network=host settings for building the container 2026-01-29 15:54:49 +01:00
yu-i-i 0e0b60ab72 Avoid DEP0174 by removing async from callback-based getGroupPolicyForUser 2026-01-29 15:54:49 +01:00
yu-i-i 3edaf8e4a8 Fix login page 2026-01-29 15:54:49 +01:00
yu-i-i 2ad1147cbc Symbol Palette: make close button visible 2026-01-29 15:54:48 +01:00
yu-i-i 4bdeb2987d Template Gallery: replace markdown-it with marked 2026-01-29 15:54:48 +01:00
yu-i-i 7194be158b 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-01-29 15:54:48 +01:00
yu-i-i 96e7bec2c4 Refactor Sandboxed Compiles 2026-01-29 15:54:48 +01:00
yu-i-i a06f584898 Symbol Palette: improve keyboard input experience 2026-01-29 15:54:48 +01:00
yu-i-i de34fbced5 Symbol Palette: get rid of @reach/tabs 2026-01-29 15:54:48 +01:00
yu-i-i c8d3965da8 Add 'poll' to clsi seccomp profile, fixes minted. Thanks, David. 2026-01-29 15:54:48 +01:00
yu-i-i b663e003bf Make Template Gallery optional; rename environment variables 2026-01-29 15:54:47 +01:00
yu-i-i 9443effae8 Add Template Gallery support 2026-01-29 15:54:47 +01:00
yu-i-i b4a15d0803 Track changes / comments: update backend to support frontend changes 2026-01-29 15:54:47 +01:00
yu-i-i 1d5e5f5950 Allow EXTERNAL_AUTH to be undefined, fixes #26 2026-01-29 15:54:47 +01:00
yu-i-i 2fbffeb206 Symbol palette: switch to 'OL' UI components and apply minor cosmetic changes 2026-01-29 15:54:47 +01:00
yu-i-i 194cf2d832 Make OVERLEAF_OIDC_USER_ID_FIELD support 'email' as a value 2026-01-29 15:54:47 +01:00
yu-i-i a8b4458a92 See upstream commit 42ee56e 2026-01-29 15:54:47 +01:00
yu-i-i 680d20ba5f Fix glitches in symbol palette after switching to Bootstrap 5 2026-01-29 15:54:46 +01:00
yu-i-i f4dae8b41c Whitelist /oidc/login endpoint, fixes #21 2026-01-29 15:54:46 +01:00
yu-i-i b7a07d2725 Add ENV variables to control SAML signature validation 2026-01-29 15:54:46 +01:00
yu-i-i cb6dcc78f8 Re-export doLogout (was removed from exports in commit b9fb636). 2026-01-29 15:54:46 +01:00
yu-i-i cbebcd99e2 Refactor authentication code; add OIDC support 2026-01-29 15:54:46 +01:00
yu-i-i 744c1dcbff Allow adding extra flags to LaTeX compiler through environment variable 2026-01-29 15:54:46 +01:00
yu-i-i c803ffd00a Enable LDAP and SAML authentication support 2026-01-29 15:54:46 +01:00
yu-i-i 34d7c15ddc Enable Symbol Palette 2026-01-29 15:54:45 +01:00
yu-i-i c2c27d3032 Allow selecting a TeX Live image for a project 2026-01-29 15:54:45 +01:00
Sam Van den Vonder 37a6c5286a Enable Sandboxed Compiles feature 2026-01-29 15:54:45 +01:00
yu-i-i ec1f16f716 Enable autocomplete of reference keys feature 2026-01-29 15:54:45 +01:00
yu-i-i 0d80609e2c Enable track changes and comments feature 2026-01-29 15:26:14 +01:00
yu-i-i 033ebdeab6 Redirect non-existing links to Overleaf page 2026-01-29 15:25:45 +01:00
3725 changed files with 173402 additions and 229434 deletions
+25
View File
@@ -0,0 +1,25 @@
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[Makefile]
indent_style = tab
[*.go]
indent_style = tab
[*.{pug,coffee}]
indent_style = tab
[*.{pug,patch}]
trim_trailing_whitespace = false
[Jenkinsfile]
insert_final_newline = false
max_line_length = off
+8 -11
View File
@@ -4,6 +4,7 @@ about: Report a bug
title: ''
labels: type:bug
assignees: ''
---
<!--
@@ -13,10 +14,11 @@ Note: This form should only be used to report bugs in the
-->
<!-- BUG REPORT TEMPLATE -->
## Steps to Reproduce
<!-- Describe the steps leading up to when / where you found the bug. -->
<!-- Screenshots may be helpful here. -->
@@ -25,28 +27,23 @@ Note: This form should only be used to report bugs in the
3.
## Expected Behaviour
<!-- What should have happened when you completed the steps above? -->
## Observed Behaviour
<!-- What actually happened when you completed the steps above? -->
<!-- Screenshots may be helpful here. -->
## Context
<!-- How has this issue affected you? What were you trying to accomplish? -->
## Technical Info
<!-- Provide any technical details that may be applicable (or N/A if not applicable). -->
- URL:
- Browser Name and version:
- Operating System and version (desktop or mobile):
- Signed in as:
- Project and/or file:
* URL:
* Browser Name and version:
* Operating System and version (desktop or mobile):
* Signed in as:
* Project and/or file:
## Analysis
<!--- Optionally, document investigation of / suggest a fix for the bug, e.g. 'comes from this line / commit' -->
+1 -2
View File
@@ -1,7 +1,6 @@
## Description
<!-- Goal of the pull request -->
## Related issues / Pull Requests
## Related issues / Pull Requests
<!-- Fixes #xyz, Contributes to #xyz, Related to #xyz-->
-58
View File
@@ -1,58 +0,0 @@
// Resolve ESM imports through Yarn PnP.
//
// Yarn ships .pnp.loader.mjs for use with module.register(), which runs hooks on a dedicated
// thread — a second V8 isolate costing 50-110MB in every node process, whether or not the
// loader does any work. registerHooks() runs synchronously in-thread instead, and PnP's own
// resolveRequest already applies "exports" conditions, so the hook is just a lookup.
import { registerHooks, isBuiltin, createRequire } from 'node:module'
import { pathToFileURL, fileURLToPath } from 'node:url'
import path from 'node:path'
const pnp = createRequire(import.meta.url)('pnpapi')
registerHooks({
resolve(specifier, context, nextResolve) {
// require() is patched by .pnp.cjs, and builtins never reach the filesystem.
if (context.conditions.includes('require') || isBuiltin(specifier)) {
return nextResolve(specifier, context)
}
// Only bare specifiers need PnP. The entrypoint arrives as a path, and mocha imports test
// files by file:// URL; both are already resolved.
let url
if (specifier.startsWith('file://')) {
url = specifier
} else if (!context.parentURL) {
url = pathToFileURL(specifier).href
} else {
// Tools installed outside the project — npm, corepack — bring their own node_modules.
// PnP does not own those paths and refuses to resolve from them.
const issuer = path.dirname(fileURLToPath(context.parentURL)) + '/'
if (!pnp.findPackageLocator(issuer)) {
return nextResolve(specifier, context)
}
try {
url = pathToFileURL(
pnp.resolveRequest(specifier, issuer, {
conditions: new Set(context.conditions),
})
).href
} catch (err) {
// PnP reports a missing module with the CommonJS code. require() returned above, so this is an ESM import and node's own resolver would raise the ESM code, which is what callers of an optional import catch.
if (err.code === 'MODULE_NOT_FOUND') err.code = 'ERR_MODULE_NOT_FOUND'
throw err
}
}
try {
// Keep the resolved path in the chain so loaders registered later can still mock it.
return nextResolve(url, context)
} catch (err) {
// Node cannot look inside PnP's zips, nor at its __virtual__ paths, so PnP's answer is
// final for those. Everything else — a genuinely missing file, an error raised by
// another loader — is a real failure.
if (url.includes('/__virtual__/') || url.includes('.zip/')) {
return { url, shortCircuit: true }
}
throw err
}
},
})
@@ -1,16 +0,0 @@
diff --git a/dist/index.mjs b/dist/index.mjs
index b781835b37a1262510bdd66d8d3b399a076e9d68..312c314186d85bb3bc2ab2620e99bca259ef7167 100644
--- a/dist/index.mjs
+++ b/dist/index.mjs
@@ -44,10 +44,9 @@ import { z as z2 } from "zod/v4";
// src/tool/types.ts
import { z } from "zod/v4";
-var LATEST_PROTOCOL_VERSION = "2025-11-25";
+var LATEST_PROTOCOL_VERSION = "2025-06-18";
var SUPPORTED_PROTOCOL_VERSIONS = [
LATEST_PROTOCOL_VERSION,
- "2025-06-18",
"2025-03-26",
"2024-11-05"
];
@@ -1,831 +0,0 @@
diff --git a/dist/index.cjs b/dist/index.cjs
index 39215ae..b44cb76 100644
--- a/dist/index.cjs
+++ b/dist/index.cjs
@@ -187,16 +187,23 @@ Helper function that returns a transaction spec which inserts a
completion's text in the main selection range, and any other
selection range that has the same text in front of it.
*/
-function insertCompletionText(state$1, text, from, to) {
+function insertCompletionText(state$1, text, from, to, extend) {
let { main } = state$1.selection, fromOff = from - main.from, toOff = to - main.from;
return Object.assign(Object.assign({}, state$1.changeByRange(range => {
if (range != main && from != to &&
state$1.sliceDoc(range.from + fromOff, range.from + toOff) != state$1.sliceDoc(from, to))
return { range };
- let lines = state$1.toText(text);
+ let change = {
+ from: range.from + fromOff,
+ to: to == main.from ? range.to : range.from + toOff,
+ insert: text instanceof state.Text ? text : state$1.toText(text),
+ };
+ if (extend) {
+ extend(state$1, change);
+ }
return {
- changes: { from: range.from + fromOff, to: to == main.from ? range.to : range.from + toOff, insert: lines },
- range: state.EditorSelection.cursor(range.from + fromOff + lines.length)
+ changes: change,
+ range: state.EditorSelection.cursor(change.from + change.insert.length)
};
})), { scrollIntoView: true, userEvent: "input.complete" });
}
@@ -389,7 +396,9 @@ const completionConfig = state.Facet.define({
filterStrict: false,
compareCompletions: (a, b) => a.label.localeCompare(b.label),
interactionDelay: 75,
- updateSyncTime: 100
+ updateSyncTime: 100,
+ // overleaf: default to at top which is default CM6 behaviour
+ unfilteredResultsAtEnd: false
}, {
defaultKeymap: (a, b) => a && b,
closeOnBlur: (a, b) => a && b,
@@ -744,6 +753,7 @@ function score(option) {
(option.type ? 1 : 0);
}
function sortOptions(active, state) {
+ var _a;
let options = [];
let sections = null;
let addOption = (option) => {
@@ -763,7 +773,8 @@ function sortOptions(active, state) {
let getMatch = a.result.getMatch;
if (a.result.filter === false) {
for (let option of a.result.options) {
- addOption(new Option(option, a.source, getMatch ? getMatch(option) : [], 1e9 - options.length));
+ let defaultScore = conf.unfilteredResultsAtEnd ? -1e9 : 1e9;
+ addOption(new Option(option, a.source, getMatch ? getMatch(option) : [], defaultScore - options.length));
}
}
else {
@@ -790,15 +801,42 @@ function sortOptions(active, state) {
}
}
let result = [], prev = null;
+ const priorityIndices = new Map();
let compare = conf.compareCompletions;
for (let opt of options.sort((a, b) => (b.score - a.score) || compare(a.completion, b.completion))) {
+ // overleaf: Deduplicate results with dedup options
+ // The goal is to keep only the highest priority option, in the
+ // highest scoring position.
+ const key = (_a = opt.completion.deduplicate) === null || _a === void 0 ? void 0 : _a.key;
+ if (key) {
+ // Handle merging specifically for deduplicated items item
+ const currentOptionIndex = priorityIndices.get(key);
+ if (currentOptionIndex === undefined) {
+ priorityIndices.set(key, result.length);
+ result.push(opt);
+ prev = opt.completion;
+ }
+ else {
+ if (result[currentOptionIndex].completion.deduplicate.priority < opt.completion.deduplicate.priority) {
+ result[currentOptionIndex] = opt;
+ if (currentOptionIndex === result.length - 1) {
+ prev = opt.completion;
+ }
+ }
+ }
+ continue;
+ }
+ // overleaf: end
let cur = opt.completion;
- if (!prev || prev.label != cur.label || prev.detail != cur.detail ||
- (prev.type != null && cur.type != null && prev.type != cur.type) ||
- prev.apply != cur.apply || prev.boost != cur.boost)
+ if (!prev || prev.label != cur.label)
+ result.push(opt);
+ // overleaf: we're already handling deduplication, so skip extra merges
+ else if (prev.deduplicate)
result.push(opt);
else if (score(opt.completion) > score(prev))
result[result.length - 1] = opt;
+ else if (opt.completion.info)
+ result[result.length - 1] = opt;
prev = opt.completion;
}
return result;
@@ -817,8 +855,9 @@ class CompletionDialog {
: new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected, this.disabled);
}
static build(active, state, id, prev, conf, didSetActive) {
- if (prev && !didSetActive && active.some(s => s.isPending))
- return prev.setDisabled();
+ // Overleaf: avoid setting the previous completion state to disabled while completion sources are pending
+ // if (prev && !didSetActive && active.some(s => s.isPending))
+ // return prev.setDisabled()
let options = sortOptions(active, state);
if (!options.length)
return prev && active.some(a => a.isPending) ? prev.setDisabled() : null;
@@ -1017,13 +1056,14 @@ const completionState = state.StateField.define({
view.EditorView.contentAttributes.from(f, state => state.attrs)
]
});
+const getCompletionTooltip = (state) => { var _a; return (_a = state.field(completionState, false)) === null || _a === void 0 ? void 0 : _a.tooltip; };
function applyCompletion(view, option) {
const apply = option.completion.apply || option.completion.label;
let result = view.state.field(completionState).active.find(a => a.source == option.source);
if (!(result instanceof ActiveResult))
return false;
if (typeof apply == "string")
- view.dispatch(Object.assign(Object.assign({}, insertCompletionText(view.state, apply, result.from, result.to)), { annotations: pickedCompletion.of(option.completion) }));
+ view.dispatch(Object.assign(Object.assign({}, insertCompletionText(view.state, apply, result.from, result.to, option.completion.extend)), { annotations: pickedCompletion.of(option.completion) }));
else
apply(view, option.completion, result.from, result.to);
return true;
@@ -1559,20 +1599,42 @@ interpreted as indicating a placeholder.
function snippet(template) {
let snippet = Snippet.parse(template);
return (editor, completion, from, to) => {
- let { text, ranges } = snippet.instantiate(editor.state, from);
- let { main } = editor.state.selection;
- let spec = {
- changes: { from, to: to == main.from ? main.to : to, insert: state.Text.of(text) },
- scrollIntoView: true,
- annotations: completion ? [pickedCompletion.of(completion), state.Transaction.userEvent.of("input.complete")] : undefined
- };
+ let { main } = editor.state.selection, fromOff = from - main.from, toOff = to - main.from;
+ let ranges = [];
+ let totalOffset = 0;
+ let spec = Object.assign(Object.assign({}, editor.state.changeByRange(range => {
+ if (range != main && from != to &&
+ editor.state.sliceDoc(range.from + fromOff, range.from + toOff) != editor.state.sliceDoc(from, to))
+ return { range };
+ let { text, ranges: fieldRanges } = snippet.instantiate(editor.state, range.from + fromOff);
+ let change = {
+ from: range.from + fromOff,
+ to: range.from + toOff,
+ insert: state.Text.of(text)
+ };
+ let originalTo = change.to;
+ let offset = change.insert.length + fromOff;
+ if (completion.extend) {
+ completion.extend(editor.state, change);
+ offset += originalTo - change.to;
+ }
+ for (const fieldRange of fieldRanges) {
+ ranges.push(new FieldRange(fieldRange.field, fieldRange.from + totalOffset, fieldRange.to + totalOffset));
+ }
+ totalOffset += offset;
+ return {
+ changes: change,
+ range: state.EditorSelection.cursor(change.from + change.insert.length)
+ };
+ })), { scrollIntoView: true, annotations: completion ? [pickedCompletion.of(completion), state.Transaction.userEvent.of("input.complete")] : undefined, effects: [] });
if (ranges.length)
spec.selection = fieldSelection(ranges, 0);
if (ranges.some(r => r.field > 0)) {
let active = new ActiveSnippet(ranges, 0);
- let effects = spec.effects = [setActive.of(active)];
- if (editor.state.field(snippetState, false) === undefined)
- effects.push(state.StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme]));
+ spec.effects.push(setActive.of(active));
+ if (editor.state.field(snippetState, false) === undefined) {
+ spec.effects.push(state.StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme]));
+ }
}
editor.dispatch(editor.state.update(spec));
};
@@ -1746,7 +1808,8 @@ const completeAnyWord = context => {
const defaults = {
brackets: ["(", "[", "{", "'", '"'],
before: ")]}:;>",
- stringPrefixes: []
+ stringPrefixes: [],
+ buildInsert: (state, range, open, close) => open + close,
};
const closeBracketEffect = state.StateEffect.define({
map(value, mapping) {
@@ -1854,8 +1917,8 @@ function insertBracket(state$1, bracket) {
for (let tok of tokens) {
let closed = closing(state.codePointAt(tok, 0));
if (bracket == tok)
- return closed == tok ? handleSame(state$1, tok, tokens.indexOf(tok + tok + tok) > -1, conf)
- : handleOpen(state$1, tok, closed, conf.before || defaults.before);
+ return closed == tok ? handleSame(state$1, tok, tokens.indexOf(tok + tok) > -1, tokens.indexOf(tok + tok + tok) > -1, conf)
+ : handleOpen(state$1, tok, closed, conf.before || defaults.before, conf);
if (bracket == closed && closedBracketAt(state$1, state$1.selection.main.from))
return handleClose(state$1, tok, closed);
}
@@ -1877,17 +1940,21 @@ function prevChar(doc, pos) {
let prev = doc.sliceString(pos - 2, pos);
return state.codePointSize(state.codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1);
}
-function handleOpen(state$1, open, close, closeBefore) {
+function handleOpen(state$1, open, close, closeBefore, config) {
+ let buildInsert = config.buildInsert || defaults.buildInsert;
let dont = null, changes = state$1.changeByRange(range => {
+ var _a;
if (!range.empty)
return { changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }],
effects: closeBracketEffect.of(range.to + open.length),
range: state.EditorSelection.range(range.anchor + open.length, range.head + open.length) };
let next = nextChar(state$1.doc, range.head);
- if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1)
- return { changes: { insert: open + close, from: range.head },
- effects: closeBracketEffect.of(range.head + open.length),
+ if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1) {
+ const insert = (_a = buildInsert(state$1, range, open, close)) !== null && _a !== void 0 ? _a : open + close;
+ return { changes: { insert, from: range.head },
+ effects: insert === open ? [] : closeBracketEffect.of(range.head + open.length),
range: state.EditorSelection.cursor(range.head + open.length) };
+ }
return { range: dont = range };
});
return dont ? null : state$1.update(changes, {
@@ -1909,18 +1976,36 @@ function handleClose(state$1, _open, close) {
}
// Handles cases where the open and close token are the same, and
// possibly triple quotes (as in `"""abc"""`-style quoting).
-function handleSame(state$1, token, allowTriple, config) {
+function handleSame(state$1, token, allowDouble, allowTriple, config) {
let stringPrefixes = config.stringPrefixes || defaults.stringPrefixes;
+ let buildInsert = config.buildInsert || defaults.buildInsert;
let dont = null, changes = state$1.changeByRange(range => {
+ var _a, _b, _c;
if (!range.empty)
return { changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }],
effects: closeBracketEffect.of(range.to + token.length),
range: state.EditorSelection.range(range.anchor + token.length, range.head + token.length) };
let pos = range.head, next = nextChar(state$1.doc, pos), start;
- if (next == token) {
+ if (allowTriple && state$1.sliceDoc(pos - 2 * token.length, pos) == token + token &&
+ (start = canStartStringAt(state$1, pos - 2 * token.length, stringPrefixes)) > -1 &&
+ nodeStart(state$1, start)) {
+ return { changes: { insert: token + token + token + token, from: pos },
+ effects: closeBracketEffect.of(pos + token.length),
+ range: state.EditorSelection.cursor(pos + token.length) };
+ }
+ else if (allowDouble && state$1.sliceDoc(pos - token.length, pos) == token &&
+ (start = canStartStringAt(state$1, pos - token.length, stringPrefixes)) > -1 &&
+ nodeStart(state$1, start)) {
+ let insert = (_a = buildInsert(state$1, range, token, token)) !== null && _a !== void 0 ? _a : token + token;
+ return { changes: { insert, from: pos },
+ effects: insert === token ? [] : closeBracketEffect.of(pos + token.length),
+ range: state.EditorSelection.cursor(pos + token.length) };
+ }
+ else if (next == token) {
if (nodeStart(state$1, pos)) {
- return { changes: { insert: token + token, from: pos },
- effects: closeBracketEffect.of(pos + token.length),
+ let insert = (_b = buildInsert(state$1, range, token, token)) !== null && _b !== void 0 ? _b : token + token;
+ return { changes: { insert, from: pos },
+ effects: insert === token ? [] : closeBracketEffect.of(pos + token.length),
range: state.EditorSelection.cursor(pos + token.length) };
}
else if (closedBracketAt(state$1, pos)) {
@@ -1930,18 +2015,13 @@ function handleSame(state$1, token, allowTriple, config) {
range: state.EditorSelection.cursor(pos + content.length) };
}
}
- else if (allowTriple && state$1.sliceDoc(pos - 2 * token.length, pos) == token + token &&
- (start = canStartStringAt(state$1, pos - 2 * token.length, stringPrefixes)) > -1 &&
- nodeStart(state$1, start)) {
- return { changes: { insert: token + token + token + token, from: pos },
- effects: closeBracketEffect.of(pos + token.length),
- range: state.EditorSelection.cursor(pos + token.length) };
- }
else if (state$1.charCategorizer(pos)(next) != state.CharCategory.Word) {
- if (canStartStringAt(state$1, pos, stringPrefixes) > -1 && !probablyInString(state$1, pos, token, stringPrefixes))
- return { changes: { insert: token + token, from: pos },
- effects: closeBracketEffect.of(pos + token.length),
+ if (canStartStringAt(state$1, pos, stringPrefixes) > -1 && !probablyInString(state$1, pos, token, stringPrefixes)) {
+ const insert = (_c = buildInsert(state$1, range, token, token)) !== null && _c !== void 0 ? _c : token + token;
+ return { changes: { insert, from: pos },
+ effects: insert === token ? [] : closeBracketEffect.of(pos + token.length),
range: state.EditorSelection.cursor(pos + token.length) };
+ }
}
return { range: dont = range };
});
@@ -2086,6 +2166,7 @@ exports.completionKeymap = completionKeymap;
exports.completionStatus = completionStatus;
exports.currentCompletions = currentCompletions;
exports.deleteBracketPair = deleteBracketPair;
+exports.getCompletionTooltip = getCompletionTooltip;
exports.hasNextSnippetField = hasNextSnippetField;
exports.hasPrevSnippetField = hasPrevSnippetField;
exports.ifIn = ifIn;
@@ -2093,8 +2174,10 @@ exports.ifNotIn = ifNotIn;
exports.insertBracket = insertBracket;
exports.insertCompletionText = insertCompletionText;
exports.moveCompletionSelection = moveCompletionSelection;
+exports.nextChar = nextChar;
exports.nextSnippetField = nextSnippetField;
exports.pickedCompletion = pickedCompletion;
+exports.prevChar = prevChar;
exports.prevSnippetField = prevSnippetField;
exports.selectedCompletion = selectedCompletion;
exports.selectedCompletionIndex = selectedCompletionIndex;
diff --git a/dist/index.d.cts b/dist/index.d.cts
index b57b8f6..fce47ab 100644
--- a/dist/index.d.cts
+++ b/dist/index.d.cts
@@ -1,6 +1,6 @@
import * as _codemirror_state from '@codemirror/state';
-import { EditorState, ChangeDesc, TransactionSpec, Transaction, StateCommand, Facet, Extension, StateEffect } from '@codemirror/state';
-import { EditorView, Rect, KeyBinding, Command } from '@codemirror/view';
+import { EditorState, Text, ChangeDesc, TransactionSpec, StateCommand, Transaction, Facet, SelectionRange, Extension, StateEffect } from '@codemirror/state';
+import { EditorView, Rect, KeyBinding, Tooltip, Command } from '@codemirror/view';
import * as _lezer_common from '@lezer/common';
/**
@@ -73,6 +73,19 @@ interface Completion {
a `{name}` object.
*/
section?: string | CompletionSection;
+ /**
+ Can be used to alter the change created when the completion is applied
+ */
+ extend?: ExtendCompletion;
+ /**
+ If multiple sources return the same result, use this field to specifiy a
+ deduplication key as well as a priority. For each unique key, only the
+ completion with the highest priority will be shown.
+ */
+ deduplicate?: {
+ key: string;
+ priority: number;
+ };
}
/**
The type returned from
@@ -306,12 +319,17 @@ This annotation is added to transactions that are produced by
picking a completion.
*/
declare const pickedCompletion: _codemirror_state.AnnotationType<Completion>;
+type ExtendCompletion = (state: EditorState, change: {
+ from: number;
+ to: number;
+ insert: string | Text;
+}) => void;
/**
Helper function that returns a transaction spec which inserts a
completion's text in the main selection range, and any other
selection range that has the same text in front of it.
*/
-declare function insertCompletionText(state: EditorState, text: string, from: number, to: number): TransactionSpec;
+declare function insertCompletionText(state: EditorState, text: string | Text, from: number, to: number, extend?: ExtendCompletion): TransactionSpec;
interface CompletionConfig {
/**
@@ -441,6 +459,10 @@ interface CompletionConfig {
milliseconds.
*/
updateSyncTime?: number;
+ /**
+ overleaf: Move unfiltered results after the filtered ones
+ */
+ unfilteredResultsAtEnd?: boolean;
}
/**
@@ -514,6 +536,8 @@ applies the snippet.
*/
declare function snippetCompletion(template: string, completion: Completion): Completion;
+declare const getCompletionTooltip: (state: EditorState) => Tooltip | undefined | null;
+
/**
Returns a command that moves the completion selection forward or
backward by the given amount.
@@ -562,6 +586,11 @@ interface CloseBracketConfig {
these prefixes before the opening quote.
*/
stringPrefixes?: string[];
+ /**
+ An optional callback for overriding the content that's inserted
+ based on surrounding characters
+ */
+ buildInsert?: (state: EditorState, range: SelectionRange, open: string, close: string) => string;
}
/**
Extension to enable bracket-closing behavior. When a closeable
@@ -593,6 +622,8 @@ to programmatically insert brackets—the
take care of running this for user input.)
*/
declare function insertBracket(state: EditorState, bracket: string): Transaction | null;
+declare function nextChar(doc: Text, pos: number): string;
+declare function prevChar(doc: Text, pos: number): string;
/**
Returns an extension that enables autocompletion.
@@ -636,4 +667,5 @@ the currently selected completion.
*/
declare function setSelectedCompletion(index: number): StateEffect<unknown>;
-export { type CloseBracketConfig, type Completion, CompletionContext, type CompletionInfo, type CompletionResult, type CompletionSection, type CompletionSource, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, hasNextSnippetField, hasPrevSnippetField, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextSnippetField, pickedCompletion, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };
+export { CompletionContext, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, getCompletionTooltip, hasNextSnippetField, hasPrevSnippetField, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextChar, nextSnippetField, pickedCompletion, prevChar, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };
+export type { CloseBracketConfig, Completion, CompletionInfo, CompletionResult, CompletionSection, CompletionSource };
diff --git a/dist/index.d.ts b/dist/index.d.ts
index b57b8f6..fce47ab 100644
--- a/dist/index.d.ts
+++ b/dist/index.d.ts
@@ -1,6 +1,6 @@
import * as _codemirror_state from '@codemirror/state';
-import { EditorState, ChangeDesc, TransactionSpec, Transaction, StateCommand, Facet, Extension, StateEffect } from '@codemirror/state';
-import { EditorView, Rect, KeyBinding, Command } from '@codemirror/view';
+import { EditorState, Text, ChangeDesc, TransactionSpec, StateCommand, Transaction, Facet, SelectionRange, Extension, StateEffect } from '@codemirror/state';
+import { EditorView, Rect, KeyBinding, Tooltip, Command } from '@codemirror/view';
import * as _lezer_common from '@lezer/common';
/**
@@ -73,6 +73,19 @@ interface Completion {
a `{name}` object.
*/
section?: string | CompletionSection;
+ /**
+ Can be used to alter the change created when the completion is applied
+ */
+ extend?: ExtendCompletion;
+ /**
+ If multiple sources return the same result, use this field to specifiy a
+ deduplication key as well as a priority. For each unique key, only the
+ completion with the highest priority will be shown.
+ */
+ deduplicate?: {
+ key: string;
+ priority: number;
+ };
}
/**
The type returned from
@@ -306,12 +319,17 @@ This annotation is added to transactions that are produced by
picking a completion.
*/
declare const pickedCompletion: _codemirror_state.AnnotationType<Completion>;
+type ExtendCompletion = (state: EditorState, change: {
+ from: number;
+ to: number;
+ insert: string | Text;
+}) => void;
/**
Helper function that returns a transaction spec which inserts a
completion's text in the main selection range, and any other
selection range that has the same text in front of it.
*/
-declare function insertCompletionText(state: EditorState, text: string, from: number, to: number): TransactionSpec;
+declare function insertCompletionText(state: EditorState, text: string | Text, from: number, to: number, extend?: ExtendCompletion): TransactionSpec;
interface CompletionConfig {
/**
@@ -441,6 +459,10 @@ interface CompletionConfig {
milliseconds.
*/
updateSyncTime?: number;
+ /**
+ overleaf: Move unfiltered results after the filtered ones
+ */
+ unfilteredResultsAtEnd?: boolean;
}
/**
@@ -514,6 +536,8 @@ applies the snippet.
*/
declare function snippetCompletion(template: string, completion: Completion): Completion;
+declare const getCompletionTooltip: (state: EditorState) => Tooltip | undefined | null;
+
/**
Returns a command that moves the completion selection forward or
backward by the given amount.
@@ -562,6 +586,11 @@ interface CloseBracketConfig {
these prefixes before the opening quote.
*/
stringPrefixes?: string[];
+ /**
+ An optional callback for overriding the content that's inserted
+ based on surrounding characters
+ */
+ buildInsert?: (state: EditorState, range: SelectionRange, open: string, close: string) => string;
}
/**
Extension to enable bracket-closing behavior. When a closeable
@@ -593,6 +622,8 @@ to programmatically insert brackets—the
take care of running this for user input.)
*/
declare function insertBracket(state: EditorState, bracket: string): Transaction | null;
+declare function nextChar(doc: Text, pos: number): string;
+declare function prevChar(doc: Text, pos: number): string;
/**
Returns an extension that enables autocompletion.
@@ -636,4 +667,5 @@ the currently selected completion.
*/
declare function setSelectedCompletion(index: number): StateEffect<unknown>;
-export { type CloseBracketConfig, type Completion, CompletionContext, type CompletionInfo, type CompletionResult, type CompletionSection, type CompletionSource, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, hasNextSnippetField, hasPrevSnippetField, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextSnippetField, pickedCompletion, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };
+export { CompletionContext, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, getCompletionTooltip, hasNextSnippetField, hasPrevSnippetField, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextChar, nextSnippetField, pickedCompletion, prevChar, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };
+export type { CloseBracketConfig, Completion, CompletionInfo, CompletionResult, CompletionSection, CompletionSource };
diff --git a/dist/index.js b/dist/index.js
index 4729223..9361a53 100644
--- a/dist/index.js
+++ b/dist/index.js
@@ -1,4 +1,4 @@
-import { Annotation, StateEffect, EditorSelection, codePointAt, codePointSize, fromCodePoint, Facet, combineConfig, StateField, Prec, Text, Transaction, MapMode, RangeValue, RangeSet, CharCategory } from '@codemirror/state';
+import { Annotation, StateEffect, Text, EditorSelection, codePointAt, codePointSize, fromCodePoint, Facet, combineConfig, StateField, Prec, Transaction, MapMode, RangeValue, RangeSet, CharCategory } from '@codemirror/state';
import { Direction, logException, showTooltip, EditorView, ViewPlugin, getTooltip, Decoration, WidgetType, keymap } from '@codemirror/view';
import { syntaxTree, indentUnit } from '@codemirror/language';
@@ -185,16 +185,23 @@ Helper function that returns a transaction spec which inserts a
completion's text in the main selection range, and any other
selection range that has the same text in front of it.
*/
-function insertCompletionText(state, text, from, to) {
+function insertCompletionText(state, text, from, to, extend) {
let { main } = state.selection, fromOff = from - main.from, toOff = to - main.from;
return Object.assign(Object.assign({}, state.changeByRange(range => {
if (range != main && from != to &&
state.sliceDoc(range.from + fromOff, range.from + toOff) != state.sliceDoc(from, to))
return { range };
- let lines = state.toText(text);
+ let change = {
+ from: range.from + fromOff,
+ to: to == main.from ? range.to : range.from + toOff,
+ insert: text instanceof Text ? text : state.toText(text),
+ };
+ if (extend) {
+ extend(state, change);
+ }
return {
- changes: { from: range.from + fromOff, to: to == main.from ? range.to : range.from + toOff, insert: lines },
- range: EditorSelection.cursor(range.from + fromOff + lines.length)
+ changes: change,
+ range: EditorSelection.cursor(change.from + change.insert.length)
};
})), { scrollIntoView: true, userEvent: "input.complete" });
}
@@ -387,7 +394,9 @@ const completionConfig = /*@__PURE__*/Facet.define({
filterStrict: false,
compareCompletions: (a, b) => a.label.localeCompare(b.label),
interactionDelay: 75,
- updateSyncTime: 100
+ updateSyncTime: 100,
+ // overleaf: default to at top which is default CM6 behaviour
+ unfilteredResultsAtEnd: false
}, {
defaultKeymap: (a, b) => a && b,
closeOnBlur: (a, b) => a && b,
@@ -742,6 +751,7 @@ function score(option) {
(option.type ? 1 : 0);
}
function sortOptions(active, state) {
+ var _a;
let options = [];
let sections = null;
let addOption = (option) => {
@@ -761,7 +771,8 @@ function sortOptions(active, state) {
let getMatch = a.result.getMatch;
if (a.result.filter === false) {
for (let option of a.result.options) {
- addOption(new Option(option, a.source, getMatch ? getMatch(option) : [], 1e9 - options.length));
+ let defaultScore = conf.unfilteredResultsAtEnd ? -1e9 : 1e9;
+ addOption(new Option(option, a.source, getMatch ? getMatch(option) : [], defaultScore - options.length));
}
}
else {
@@ -788,15 +799,42 @@ function sortOptions(active, state) {
}
}
let result = [], prev = null;
+ const priorityIndices = new Map();
let compare = conf.compareCompletions;
for (let opt of options.sort((a, b) => (b.score - a.score) || compare(a.completion, b.completion))) {
+ // overleaf: Deduplicate results with dedup options
+ // The goal is to keep only the highest priority option, in the
+ // highest scoring position.
+ const key = (_a = opt.completion.deduplicate) === null || _a === void 0 ? void 0 : _a.key;
+ if (key) {
+ // Handle merging specifically for deduplicated items item
+ const currentOptionIndex = priorityIndices.get(key);
+ if (currentOptionIndex === undefined) {
+ priorityIndices.set(key, result.length);
+ result.push(opt);
+ prev = opt.completion;
+ }
+ else {
+ if (result[currentOptionIndex].completion.deduplicate.priority < opt.completion.deduplicate.priority) {
+ result[currentOptionIndex] = opt;
+ if (currentOptionIndex === result.length - 1) {
+ prev = opt.completion;
+ }
+ }
+ }
+ continue;
+ }
+ // overleaf: end
let cur = opt.completion;
- if (!prev || prev.label != cur.label || prev.detail != cur.detail ||
- (prev.type != null && cur.type != null && prev.type != cur.type) ||
- prev.apply != cur.apply || prev.boost != cur.boost)
+ if (!prev || prev.label != cur.label)
+ result.push(opt);
+ // overleaf: we're already handling deduplication, so skip extra merges
+ else if (prev.deduplicate)
result.push(opt);
else if (score(opt.completion) > score(prev))
result[result.length - 1] = opt;
+ else if (opt.completion.info)
+ result[result.length - 1] = opt;
prev = opt.completion;
}
return result;
@@ -815,8 +853,9 @@ class CompletionDialog {
: new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected, this.disabled);
}
static build(active, state, id, prev, conf, didSetActive) {
- if (prev && !didSetActive && active.some(s => s.isPending))
- return prev.setDisabled();
+ // Overleaf: avoid setting the previous completion state to disabled while completion sources are pending
+ // if (prev && !didSetActive && active.some(s => s.isPending))
+ // return prev.setDisabled()
let options = sortOptions(active, state);
if (!options.length)
return prev && active.some(a => a.isPending) ? prev.setDisabled() : null;
@@ -1015,13 +1054,14 @@ const completionState = /*@__PURE__*/StateField.define({
EditorView.contentAttributes.from(f, state => state.attrs)
]
});
+const getCompletionTooltip = (state) => { var _a; return (_a = state.field(completionState, false)) === null || _a === void 0 ? void 0 : _a.tooltip; };
function applyCompletion(view, option) {
const apply = option.completion.apply || option.completion.label;
let result = view.state.field(completionState).active.find(a => a.source == option.source);
if (!(result instanceof ActiveResult))
return false;
if (typeof apply == "string")
- view.dispatch(Object.assign(Object.assign({}, insertCompletionText(view.state, apply, result.from, result.to)), { annotations: pickedCompletion.of(option.completion) }));
+ view.dispatch(Object.assign(Object.assign({}, insertCompletionText(view.state, apply, result.from, result.to, option.completion.extend)), { annotations: pickedCompletion.of(option.completion) }));
else
apply(view, option.completion, result.from, result.to);
return true;
@@ -1557,20 +1597,42 @@ interpreted as indicating a placeholder.
function snippet(template) {
let snippet = Snippet.parse(template);
return (editor, completion, from, to) => {
- let { text, ranges } = snippet.instantiate(editor.state, from);
- let { main } = editor.state.selection;
- let spec = {
- changes: { from, to: to == main.from ? main.to : to, insert: Text.of(text) },
- scrollIntoView: true,
- annotations: completion ? [pickedCompletion.of(completion), Transaction.userEvent.of("input.complete")] : undefined
- };
+ let { main } = editor.state.selection, fromOff = from - main.from, toOff = to - main.from;
+ let ranges = [];
+ let totalOffset = 0;
+ let spec = Object.assign(Object.assign({}, editor.state.changeByRange(range => {
+ if (range != main && from != to &&
+ editor.state.sliceDoc(range.from + fromOff, range.from + toOff) != editor.state.sliceDoc(from, to))
+ return { range };
+ let { text, ranges: fieldRanges } = snippet.instantiate(editor.state, range.from + fromOff);
+ let change = {
+ from: range.from + fromOff,
+ to: range.from + toOff,
+ insert: Text.of(text)
+ };
+ let originalTo = change.to;
+ let offset = change.insert.length + fromOff;
+ if (completion.extend) {
+ completion.extend(editor.state, change);
+ offset += originalTo - change.to;
+ }
+ for (const fieldRange of fieldRanges) {
+ ranges.push(new FieldRange(fieldRange.field, fieldRange.from + totalOffset, fieldRange.to + totalOffset));
+ }
+ totalOffset += offset;
+ return {
+ changes: change,
+ range: EditorSelection.cursor(change.from + change.insert.length)
+ };
+ })), { scrollIntoView: true, annotations: completion ? [pickedCompletion.of(completion), Transaction.userEvent.of("input.complete")] : undefined, effects: [] });
if (ranges.length)
spec.selection = fieldSelection(ranges, 0);
if (ranges.some(r => r.field > 0)) {
let active = new ActiveSnippet(ranges, 0);
- let effects = spec.effects = [setActive.of(active)];
- if (editor.state.field(snippetState, false) === undefined)
- effects.push(StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme]));
+ spec.effects.push(setActive.of(active));
+ if (editor.state.field(snippetState, false) === undefined) {
+ spec.effects.push(StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme]));
+ }
}
editor.dispatch(editor.state.update(spec));
};
@@ -1744,7 +1806,8 @@ const completeAnyWord = context => {
const defaults = {
brackets: ["(", "[", "{", "'", '"'],
before: ")]}:;>",
- stringPrefixes: []
+ stringPrefixes: [],
+ buildInsert: (state, range, open, close) => open + close,
};
const closeBracketEffect = /*@__PURE__*/StateEffect.define({
map(value, mapping) {
@@ -1852,8 +1915,8 @@ function insertBracket(state, bracket) {
for (let tok of tokens) {
let closed = closing(codePointAt(tok, 0));
if (bracket == tok)
- return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1, conf)
- : handleOpen(state, tok, closed, conf.before || defaults.before);
+ return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok) > -1, tokens.indexOf(tok + tok + tok) > -1, conf)
+ : handleOpen(state, tok, closed, conf.before || defaults.before, conf);
if (bracket == closed && closedBracketAt(state, state.selection.main.from))
return handleClose(state, tok, closed);
}
@@ -1875,17 +1938,21 @@ function prevChar(doc, pos) {
let prev = doc.sliceString(pos - 2, pos);
return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1);
}
-function handleOpen(state, open, close, closeBefore) {
+function handleOpen(state, open, close, closeBefore, config) {
+ let buildInsert = config.buildInsert || defaults.buildInsert;
let dont = null, changes = state.changeByRange(range => {
+ var _a;
if (!range.empty)
return { changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }],
effects: closeBracketEffect.of(range.to + open.length),
range: EditorSelection.range(range.anchor + open.length, range.head + open.length) };
let next = nextChar(state.doc, range.head);
- if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1)
- return { changes: { insert: open + close, from: range.head },
- effects: closeBracketEffect.of(range.head + open.length),
+ if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1) {
+ const insert = (_a = buildInsert(state, range, open, close)) !== null && _a !== void 0 ? _a : open + close;
+ return { changes: { insert, from: range.head },
+ effects: insert === open ? [] : closeBracketEffect.of(range.head + open.length),
range: EditorSelection.cursor(range.head + open.length) };
+ }
return { range: dont = range };
});
return dont ? null : state.update(changes, {
@@ -1907,18 +1974,36 @@ function handleClose(state, _open, close) {
}
// Handles cases where the open and close token are the same, and
// possibly triple quotes (as in `"""abc"""`-style quoting).
-function handleSame(state, token, allowTriple, config) {
+function handleSame(state, token, allowDouble, allowTriple, config) {
let stringPrefixes = config.stringPrefixes || defaults.stringPrefixes;
+ let buildInsert = config.buildInsert || defaults.buildInsert;
let dont = null, changes = state.changeByRange(range => {
+ var _a, _b, _c;
if (!range.empty)
return { changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }],
effects: closeBracketEffect.of(range.to + token.length),
range: EditorSelection.range(range.anchor + token.length, range.head + token.length) };
let pos = range.head, next = nextChar(state.doc, pos), start;
- if (next == token) {
+ if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token &&
+ (start = canStartStringAt(state, pos - 2 * token.length, stringPrefixes)) > -1 &&
+ nodeStart(state, start)) {
+ return { changes: { insert: token + token + token + token, from: pos },
+ effects: closeBracketEffect.of(pos + token.length),
+ range: EditorSelection.cursor(pos + token.length) };
+ }
+ else if (allowDouble && state.sliceDoc(pos - token.length, pos) == token &&
+ (start = canStartStringAt(state, pos - token.length, stringPrefixes)) > -1 &&
+ nodeStart(state, start)) {
+ let insert = (_a = buildInsert(state, range, token, token)) !== null && _a !== void 0 ? _a : token + token;
+ return { changes: { insert, from: pos },
+ effects: insert === token ? [] : closeBracketEffect.of(pos + token.length),
+ range: EditorSelection.cursor(pos + token.length) };
+ }
+ else if (next == token) {
if (nodeStart(state, pos)) {
- return { changes: { insert: token + token, from: pos },
- effects: closeBracketEffect.of(pos + token.length),
+ let insert = (_b = buildInsert(state, range, token, token)) !== null && _b !== void 0 ? _b : token + token;
+ return { changes: { insert, from: pos },
+ effects: insert === token ? [] : closeBracketEffect.of(pos + token.length),
range: EditorSelection.cursor(pos + token.length) };
}
else if (closedBracketAt(state, pos)) {
@@ -1928,18 +2013,13 @@ function handleSame(state, token, allowTriple, config) {
range: EditorSelection.cursor(pos + content.length) };
}
}
- else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token &&
- (start = canStartStringAt(state, pos - 2 * token.length, stringPrefixes)) > -1 &&
- nodeStart(state, start)) {
- return { changes: { insert: token + token + token + token, from: pos },
- effects: closeBracketEffect.of(pos + token.length),
- range: EditorSelection.cursor(pos + token.length) };
- }
else if (state.charCategorizer(pos)(next) != CharCategory.Word) {
- if (canStartStringAt(state, pos, stringPrefixes) > -1 && !probablyInString(state, pos, token, stringPrefixes))
- return { changes: { insert: token + token, from: pos },
- effects: closeBracketEffect.of(pos + token.length),
+ if (canStartStringAt(state, pos, stringPrefixes) > -1 && !probablyInString(state, pos, token, stringPrefixes)) {
+ const insert = (_c = buildInsert(state, range, token, token)) !== null && _c !== void 0 ? _c : token + token;
+ return { changes: { insert, from: pos },
+ effects: insert === token ? [] : closeBracketEffect.of(pos + token.length),
range: EditorSelection.cursor(pos + token.length) };
+ }
}
return { range: dont = range };
});
@@ -2071,4 +2151,4 @@ function setSelectedCompletion(index) {
return setSelectedEffect.of(index);
}
-export { CompletionContext, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, hasNextSnippetField, hasPrevSnippetField, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextSnippetField, pickedCompletion, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };
+export { CompletionContext, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, getCompletionTooltip, hasNextSnippetField, hasPrevSnippetField, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextChar, nextSnippetField, pickedCompletion, prevChar, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };
@@ -1,381 +0,0 @@
diff --git a/dist/index.cjs b/dist/index.cjs
index 46231ae..fb0f9aa 100644
--- a/dist/index.cjs
+++ b/dist/index.cjs
@@ -592,6 +592,7 @@ class SearchQuery {
this.valid = !!this.search && (!this.regexp || validRegExp(this.search));
this.unquoted = this.unquote(this.search);
this.wholeWord = !!config.wholeWord;
+ this.scope = config.scope;
}
/**
@internal
@@ -606,7 +607,7 @@ class SearchQuery {
eq(other) {
return this.search == other.search && this.replace == other.replace &&
this.caseSensitive == other.caseSensitive && this.regexp == other.regexp &&
- this.wholeWord == other.wholeWord;
+ this.wholeWord == other.wholeWord && this.scope == other.scope;
}
/**
@internal
@@ -631,7 +632,12 @@ class QueryType {
}
}
function stringCursor(spec, state, from, to) {
- return new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? undefined : x => x.toLowerCase(), spec.wholeWord ? stringWordTest(state.doc, state.charCategorizer(state.selection.main.head)) : undefined);
+ const test = spec.wholeWord ? stringWordTest(state.doc, state.charCategorizer(state.selection.main.head)) : undefined;
+ const testWithinScope = (from, to, buffer, bufferPos) => {
+ return (!test || test(from, to, buffer, bufferPos))
+ && (!spec.scope || spec.scope.some(range => from >= range.from && from <= range.to && to >= range.from && to <= range.to));
+ };
+ return new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? undefined : x => x.toLowerCase(), testWithinScope);
}
function stringWordTest(doc, categorizer) {
return (from, to, buf, bufPos) => {
@@ -695,9 +701,14 @@ class StringQuery extends QueryType {
}
}
function regexpCursor(spec, state, from, to) {
+ const test = spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : undefined;
+ const testWithinScope = (from, to, match) => {
+ return (!test || test(from, to, match))
+ && (!spec.scope || spec.scope.some(range => from >= range.from && from <= range.to && to >= range.from && to <= range.to));
+ };
return new RegExpCursor(state.doc, spec.search, {
ignoreCase: !spec.caseSensitive,
- test: spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : undefined
+ test: testWithinScope,
}, from, to);
}
function charBefore(str, index) {
@@ -737,10 +748,18 @@ class RegExpQuery extends QueryType {
this.prevMatchInRange(state, curTo, state.doc.length);
}
getReplacement(result) {
- return this.spec.unquote(this.spec.replace).replace(/\$([$&\d+])/g, (m, i) => i == "$" ? "$"
- : i == "&" ? result.match[0]
- : i != "0" && +i < result.match.length ? result.match[i]
- : m);
+ return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g, (m, i) => {
+ if (i == "&")
+ return result.match[0];
+ if (i == "$")
+ return "$";
+ for (let l = i.length; l > 0; l--) {
+ let n = +i.slice(0, l);
+ if (n > 0 && n < result.match.length)
+ return result.match[n] + i.slice(l);
+ }
+ return m;
+ });
}
matchAll(state, limit) {
let cursor = regexpCursor(this.spec, state, 0, state.doc.length), ranges = [];
@@ -1227,7 +1246,9 @@ const searchExtensions = [
exports.RegExpCursor = RegExpCursor;
exports.SearchCursor = SearchCursor;
exports.SearchQuery = SearchQuery;
+exports.StringQuery = StringQuery;
exports.closeSearchPanel = closeSearchPanel;
+exports.createSearchPanel = createSearchPanel;
exports.findNext = findNext;
exports.findPrevious = findPrevious;
exports.getSearchQuery = getSearchQuery;
@@ -1242,4 +1263,6 @@ exports.searchPanelOpen = searchPanelOpen;
exports.selectMatches = selectMatches;
exports.selectNextOccurrence = selectNextOccurrence;
exports.selectSelectionMatches = selectSelectionMatches;
+exports.selectWord = selectWord;
exports.setSearchQuery = setSearchQuery;
+exports.togglePanel = togglePanel;
diff --git a/dist/index.d.cts b/dist/index.d.cts
index 08f5696..663d192 100644
--- a/dist/index.d.cts
+++ b/dist/index.d.cts
@@ -1,6 +1,6 @@
import * as _codemirror_state from '@codemirror/state';
import { Text, Extension, StateCommand, EditorState, SelectionRange, StateEffect } from '@codemirror/state';
-import { Command, KeyBinding, EditorView, Panel } from '@codemirror/view';
+import { Command, EditorView, Panel, KeyBinding } from '@codemirror/view';
/**
A search cursor provides an iterator over text matches in a
@@ -161,6 +161,7 @@ the `"cm-selectionMatch"` class for the highlighting. When
itself will be highlighted with `"cm-selectionMatch-main"`.
*/
declare function highlightSelectionMatches(options?: HighlightOptions): Extension;
+declare const selectWord: StateCommand;
/**
Select next occurrence of the current selection. Expand selection
to the surrounding word when the selection is empty.
@@ -264,6 +265,13 @@ declare class SearchQuery {
*/
readonly wholeWord: boolean;
/**
+ When set, only include search matches within these ranges
+ */
+ readonly scope?: Readonly<{
+ from: number;
+ to: number;
+ }[]>;
+ /**
Create a query object.
*/
constructor(config: {
@@ -293,6 +301,13 @@ declare class SearchQuery {
Enable whole-word matching.
*/
wholeWord?: boolean;
+ /**
+ The ranges to match within
+ */
+ scope?: Readonly<{
+ from: number;
+ to: number;
+ }[]>;
});
/**
Compare this query to another query.
@@ -307,6 +322,34 @@ declare class SearchQuery {
to: number;
}>;
}
+type SearchResult = typeof SearchCursor.prototype.value;
+declare abstract class QueryType<Result extends SearchResult = SearchResult> {
+ readonly spec: SearchQuery;
+ constructor(spec: SearchQuery);
+ abstract nextMatch(state: EditorState, curFrom: number, curTo: number): Result | null;
+ abstract prevMatch(state: EditorState, curFrom: number, curTo: number): Result | null;
+ abstract getReplacement(result: Result): string;
+ abstract matchAll(state: EditorState, limit: number): readonly Result[] | null;
+ abstract highlight(state: EditorState, from: number, to: number, add: (from: number, to: number) => void): void;
+}
+declare class StringQuery extends QueryType<SearchResult> {
+ constructor(spec: SearchQuery);
+ nextMatch(state: EditorState, curFrom: number, curTo: number): {
+ from: number;
+ to: number;
+ } | null;
+ private prevMatchInRange;
+ prevMatch(state: EditorState, curFrom: number, curTo: number): {
+ from: number;
+ to: number;
+ } | null;
+ getReplacement(_result: SearchResult): string;
+ matchAll(state: EditorState, limit: number): {
+ from: number;
+ to: number;
+ }[] | null;
+ highlight(state: EditorState, from: number, to: number, add: (from: number, to: number) => void): void;
+}
/**
A state effect that updates the current search query. Note that
this only has an effect if the search state has been initialized
@@ -315,6 +358,7 @@ by running [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSea
once).
*/
declare const setSearchQuery: _codemirror_state.StateEffectType<SearchQuery>;
+declare const togglePanel: _codemirror_state.StateEffectType<boolean>;
/**
Get the current search query from an editor state.
*/
@@ -353,6 +397,7 @@ Replace all instances of the search query with the given
replacement.
*/
declare const replaceAll: Command;
+declare function createSearchPanel(view: EditorView): Panel;
/**
Make sure the search panel is open and focused.
*/
@@ -372,4 +417,4 @@ Default search-related key bindings.
*/
declare const searchKeymap: readonly KeyBinding[];
-export { RegExpCursor, SearchCursor, SearchQuery, closeSearchPanel, findNext, findPrevious, getSearchQuery, gotoLine, highlightSelectionMatches, openSearchPanel, replaceAll, replaceNext, search, searchKeymap, searchPanelOpen, selectMatches, selectNextOccurrence, selectSelectionMatches, setSearchQuery };
+export { RegExpCursor, SearchCursor, SearchQuery, StringQuery, closeSearchPanel, createSearchPanel, findNext, findPrevious, getSearchQuery, gotoLine, highlightSelectionMatches, openSearchPanel, replaceAll, replaceNext, search, searchKeymap, searchPanelOpen, selectMatches, selectNextOccurrence, selectSelectionMatches, selectWord, setSearchQuery, togglePanel };
diff --git a/dist/index.d.ts b/dist/index.d.ts
index 08f5696..663d192 100644
--- a/dist/index.d.ts
+++ b/dist/index.d.ts
@@ -1,6 +1,6 @@
import * as _codemirror_state from '@codemirror/state';
import { Text, Extension, StateCommand, EditorState, SelectionRange, StateEffect } from '@codemirror/state';
-import { Command, KeyBinding, EditorView, Panel } from '@codemirror/view';
+import { Command, EditorView, Panel, KeyBinding } from '@codemirror/view';
/**
A search cursor provides an iterator over text matches in a
@@ -161,6 +161,7 @@ the `"cm-selectionMatch"` class for the highlighting. When
itself will be highlighted with `"cm-selectionMatch-main"`.
*/
declare function highlightSelectionMatches(options?: HighlightOptions): Extension;
+declare const selectWord: StateCommand;
/**
Select next occurrence of the current selection. Expand selection
to the surrounding word when the selection is empty.
@@ -264,6 +265,13 @@ declare class SearchQuery {
*/
readonly wholeWord: boolean;
/**
+ When set, only include search matches within these ranges
+ */
+ readonly scope?: Readonly<{
+ from: number;
+ to: number;
+ }[]>;
+ /**
Create a query object.
*/
constructor(config: {
@@ -293,6 +301,13 @@ declare class SearchQuery {
Enable whole-word matching.
*/
wholeWord?: boolean;
+ /**
+ The ranges to match within
+ */
+ scope?: Readonly<{
+ from: number;
+ to: number;
+ }[]>;
});
/**
Compare this query to another query.
@@ -307,6 +322,34 @@ declare class SearchQuery {
to: number;
}>;
}
+type SearchResult = typeof SearchCursor.prototype.value;
+declare abstract class QueryType<Result extends SearchResult = SearchResult> {
+ readonly spec: SearchQuery;
+ constructor(spec: SearchQuery);
+ abstract nextMatch(state: EditorState, curFrom: number, curTo: number): Result | null;
+ abstract prevMatch(state: EditorState, curFrom: number, curTo: number): Result | null;
+ abstract getReplacement(result: Result): string;
+ abstract matchAll(state: EditorState, limit: number): readonly Result[] | null;
+ abstract highlight(state: EditorState, from: number, to: number, add: (from: number, to: number) => void): void;
+}
+declare class StringQuery extends QueryType<SearchResult> {
+ constructor(spec: SearchQuery);
+ nextMatch(state: EditorState, curFrom: number, curTo: number): {
+ from: number;
+ to: number;
+ } | null;
+ private prevMatchInRange;
+ prevMatch(state: EditorState, curFrom: number, curTo: number): {
+ from: number;
+ to: number;
+ } | null;
+ getReplacement(_result: SearchResult): string;
+ matchAll(state: EditorState, limit: number): {
+ from: number;
+ to: number;
+ }[] | null;
+ highlight(state: EditorState, from: number, to: number, add: (from: number, to: number) => void): void;
+}
/**
A state effect that updates the current search query. Note that
this only has an effect if the search state has been initialized
@@ -315,6 +358,7 @@ by running [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSea
once).
*/
declare const setSearchQuery: _codemirror_state.StateEffectType<SearchQuery>;
+declare const togglePanel: _codemirror_state.StateEffectType<boolean>;
/**
Get the current search query from an editor state.
*/
@@ -353,6 +397,7 @@ Replace all instances of the search query with the given
replacement.
*/
declare const replaceAll: Command;
+declare function createSearchPanel(view: EditorView): Panel;
/**
Make sure the search panel is open and focused.
*/
@@ -372,4 +417,4 @@ Default search-related key bindings.
*/
declare const searchKeymap: readonly KeyBinding[];
-export { RegExpCursor, SearchCursor, SearchQuery, closeSearchPanel, findNext, findPrevious, getSearchQuery, gotoLine, highlightSelectionMatches, openSearchPanel, replaceAll, replaceNext, search, searchKeymap, searchPanelOpen, selectMatches, selectNextOccurrence, selectSelectionMatches, setSearchQuery };
+export { RegExpCursor, SearchCursor, SearchQuery, StringQuery, closeSearchPanel, createSearchPanel, findNext, findPrevious, getSearchQuery, gotoLine, highlightSelectionMatches, openSearchPanel, replaceAll, replaceNext, search, searchKeymap, searchPanelOpen, selectMatches, selectNextOccurrence, selectSelectionMatches, selectWord, setSearchQuery, togglePanel };
diff --git a/dist/index.js b/dist/index.js
index 22172ef..08a9974 100644
--- a/dist/index.js
+++ b/dist/index.js
@@ -590,6 +590,7 @@ class SearchQuery {
this.valid = !!this.search && (!this.regexp || validRegExp(this.search));
this.unquoted = this.unquote(this.search);
this.wholeWord = !!config.wholeWord;
+ this.scope = config.scope;
}
/**
@internal
@@ -604,7 +605,7 @@ class SearchQuery {
eq(other) {
return this.search == other.search && this.replace == other.replace &&
this.caseSensitive == other.caseSensitive && this.regexp == other.regexp &&
- this.wholeWord == other.wholeWord;
+ this.wholeWord == other.wholeWord && this.scope == other.scope;
}
/**
@internal
@@ -629,7 +630,12 @@ class QueryType {
}
}
function stringCursor(spec, state, from, to) {
- return new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? undefined : x => x.toLowerCase(), spec.wholeWord ? stringWordTest(state.doc, state.charCategorizer(state.selection.main.head)) : undefined);
+ const test = spec.wholeWord ? stringWordTest(state.doc, state.charCategorizer(state.selection.main.head)) : undefined;
+ const testWithinScope = (from, to, buffer, bufferPos) => {
+ return (!test || test(from, to, buffer, bufferPos))
+ && (!spec.scope || spec.scope.some(range => from >= range.from && from <= range.to && to >= range.from && to <= range.to));
+ };
+ return new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? undefined : x => x.toLowerCase(), testWithinScope);
}
function stringWordTest(doc, categorizer) {
return (from, to, buf, bufPos) => {
@@ -693,9 +699,14 @@ class StringQuery extends QueryType {
}
}
function regexpCursor(spec, state, from, to) {
+ const test = spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : undefined;
+ const testWithinScope = (from, to, match) => {
+ return (!test || test(from, to, match))
+ && (!spec.scope || spec.scope.some(range => from >= range.from && from <= range.to && to >= range.from && to <= range.to));
+ };
return new RegExpCursor(state.doc, spec.search, {
ignoreCase: !spec.caseSensitive,
- test: spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : undefined
+ test: testWithinScope,
}, from, to);
}
function charBefore(str, index) {
@@ -735,10 +746,18 @@ class RegExpQuery extends QueryType {
this.prevMatchInRange(state, curTo, state.doc.length);
}
getReplacement(result) {
- return this.spec.unquote(this.spec.replace).replace(/\$([$&\d+])/g, (m, i) => i == "$" ? "$"
- : i == "&" ? result.match[0]
- : i != "0" && +i < result.match.length ? result.match[i]
- : m);
+ return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g, (m, i) => {
+ if (i == "&")
+ return result.match[0];
+ if (i == "$")
+ return "$";
+ for (let l = i.length; l > 0; l--) {
+ let n = +i.slice(0, l);
+ if (n > 0 && n < result.match.length)
+ return result.match[n] + i.slice(l);
+ }
+ return m;
+ });
}
matchAll(state, limit) {
let cursor = regexpCursor(this.spec, state, 0, state.doc.length), ranges = [];
@@ -1222,4 +1241,4 @@ const searchExtensions = [
baseTheme
];
-export { RegExpCursor, SearchCursor, SearchQuery, closeSearchPanel, findNext, findPrevious, getSearchQuery, gotoLine, highlightSelectionMatches, openSearchPanel, replaceAll, replaceNext, search, searchKeymap, searchPanelOpen, selectMatches, selectNextOccurrence, selectSelectionMatches, setSearchQuery };
+export { RegExpCursor, SearchCursor, SearchQuery, StringQuery, closeSearchPanel, createSearchPanel, findNext, findPrevious, getSearchQuery, gotoLine, highlightSelectionMatches, openSearchPanel, replaceAll, replaceNext, search, searchKeymap, searchPanelOpen, selectMatches, selectNextOccurrence, selectSelectionMatches, selectWord, setSearchQuery, togglePanel };
@@ -1,67 +0,0 @@
diff --git a/lib/request.js b/lib/request.js
index f42960ca2b94b784497392cfb85ef31e4e63a1ac..7feea2ed29873e519aee0ba5e1f5b36e09fe865d 100644
--- a/lib/request.js
+++ b/lib/request.js
@@ -6,6 +6,30 @@
const InvalidArgumentError = require('./errors/invalid-argument-error');
/* type-is: https://github.com/jshttp/type-is */
const typeis = require('type-is');
+// --- Overleaf patch: request-input lockdown compatibility ---
+// The constructor below destructures query/body directly off the raw
+// framework request object it's handed (see AuthenticationController.mjs's
+// `new Oauth2Server.Request(req)`), which is otherwise indistinguishable
+// from unvalidated application code reading raw request input under
+// Overleaf's request-input lockdown (see libraries/validation-tools and the
+// patched express in .yarn/patches/express-npm-*.patch). The lockdown
+// captures the original parsed values in symbol-keyed fields, registered in
+// the global symbol registry (the same ones @overleaf/validation-tools'
+// lockdown.js reads), and only turns the *public* req.query/req.body
+// properties into throwing accessors -- reading through these raw fields
+// instead sidesteps that, and is identical to plain req.query/req.body when
+// the lockdown isn't installed (i.e. for every consumer of this package
+// outside this monorepo).
+const __overleafLockdownInstalled = Symbol.for('overleaf.lockdown.installed');
+const __overleafLockdownRawQuery = Symbol.for('overleaf.lockdown.rawQuery');
+const __overleafLockdownRawBody = Symbol.for('overleaf.lockdown.rawBody');
+function __overleafRawQuery(req) {
+ return req[__overleafLockdownInstalled] ? req[__overleafLockdownRawQuery] : req.query;
+}
+function __overleafRawBody(req) {
+ return req[__overleafLockdownInstalled] ? req[__overleafLockdownRawBody] : req.body;
+}
+// --- end Overleaf patch ---
/**
* Wrapper for webserver's request.
@@ -29,7 +53,12 @@ class Request {
* @param otherOptions {...object} any other properties that should be assigned to the request by your webserver
* @throws {InvalidArgumentError} if one of headers, method or query are missing.
*/
- constructor({ headers, method, query, body, ...otherOptions } = {}) {
+ constructor(req = {}) {
+ const headers = req.headers;
+ const method = req.method;
+ const query = __overleafRawQuery(req);
+ const body = __overleafRawBody(req);
+
if (!headers) {
throw new InvalidArgumentError('Missing parameter: `headers`');
}
@@ -52,7 +81,16 @@ class Request {
this.headers[header.toLowerCase()] = value;
});
- // Store additional properties of the request object passed in
+ // Store additional properties of the request object passed in (mirrors
+ // the original `...otherOptions` rest destructuring, but built off
+ // Object.assign so query/body -- already handled above via the raw
+ // lockdown fields -- aren't read a second time through the throwing
+ // accessors).
+ const otherOptions = Object.assign({}, req);
+ delete otherOptions.headers;
+ delete otherOptions.method;
+ delete otherOptions.query;
+ delete otherOptions.body;
Object.entries(otherOptions)
.filter(([property]) => !this[property])
.forEach(([property, value]) => {
@@ -1,99 +0,0 @@
diff --git a/lib/strategy.js b/lib/strategy.js
index 4de162f7e92a20b1ccd4d34dd9bcc0916f4c8c43..c67bb4e0b0287d615eac4c01b84c83d2bac91446 100644
--- a/lib/strategy.js
+++ b/lib/strategy.js
@@ -5,6 +5,29 @@ const passport_strategy_1 = require("passport-strategy");
const assert_1 = require("assert");
const url = require("url");
const node_saml_1 = require("@node-saml/node-saml");
+// --- Overleaf patch: request-input lockdown compatibility ---
+// This library reads req.query/req.body directly to parse the SAML protocol
+// fields (SAMLResponse, SAMLRequest, RelayState) it's built around, which is
+// otherwise indistinguishable from unvalidated application code reading raw
+// request input under Overleaf's request-input lockdown (see
+// libraries/validation-tools and the patched express in
+// .yarn/patches/express-npm-*.patch). The lockdown captures the original
+// parsed values in symbol-keyed fields, registered in the global symbol
+// registry (the same ones @overleaf/validation-tools' lockdown.js reads), and
+// only turns the *public* req.query/req.body properties into throwing
+// accessors -- reading through these raw fields instead sidesteps that, and
+// is identical to plain req.query/req.body when the lockdown isn't installed
+// (i.e. for every consumer of this package outside this monorepo).
+const __overleafLockdownInstalled = Symbol.for("overleaf.lockdown.installed");
+const __overleafLockdownRawQuery = Symbol.for("overleaf.lockdown.rawQuery");
+const __overleafLockdownRawBody = Symbol.for("overleaf.lockdown.rawBody");
+function __overleafRawQuery(req) {
+ return req[__overleafLockdownInstalled] ? req[__overleafLockdownRawQuery] : req.query;
+}
+function __overleafRawBody(req) {
+ return req[__overleafLockdownInstalled] ? req[__overleafLockdownRawBody] : req.body;
+}
+// --- end Overleaf patch ---
class AbstractStrategy extends passport_strategy_1.Strategy {
constructor(options, signonVerify, logoutVerify) {
super();
@@ -52,7 +75,7 @@ class AbstractStrategy extends passport_strategy_1.Strategy {
catch (_c) {
userMatch = false;
}
- const RelayState = ((_a = req.query) === null || _a === void 0 ? void 0 : _a.RelayState) || ((_b = req.body) === null || _b === void 0 ? void 0 : _b.RelayState);
+ const RelayState = ((_a = __overleafRawQuery(req)) === null || _a === void 0 ? void 0 : _a.RelayState) || ((_b = __overleafRawBody(req)) === null || _b === void 0 ? void 0 : _b.RelayState);
if (this._saml == null) {
return this.error(new Error("Can't get logout response URL without a SAML provider defined."));
}
@@ -125,22 +148,22 @@ class AbstractStrategy extends passport_strategy_1.Strategy {
this.redirect(url);
}
};
- if (((_a = req.query) === null || _a === void 0 ? void 0 : _a.SAMLResponse) || ((_b = req.query) === null || _b === void 0 ? void 0 : _b.SAMLRequest)) {
+ if (((_a = __overleafRawQuery(req)) === null || _a === void 0 ? void 0 : _a.SAMLResponse) || ((_b = __overleafRawQuery(req)) === null || _b === void 0 ? void 0 : _b.SAMLRequest)) {
const originalQuery = (_c = url.parse(req.url).query) !== null && _c !== void 0 ? _c : "";
this._saml
- .validateRedirectAsync(req.query, originalQuery)
+ .validateRedirectAsync(__overleafRawQuery(req), originalQuery)
.then(validateCallback)
.catch((err) => this.error(err));
}
- else if ((_d = req.body) === null || _d === void 0 ? void 0 : _d.SAMLResponse) {
+ else if ((_d = __overleafRawBody(req)) === null || _d === void 0 ? void 0 : _d.SAMLResponse) {
this._saml
- .validatePostResponseAsync(req.body)
+ .validatePostResponseAsync(__overleafRawBody(req))
.then(validateCallback)
.catch((err) => this.error(err));
}
- else if ((_e = req.body) === null || _e === void 0 ? void 0 : _e.SAMLRequest) {
+ else if ((_e = __overleafRawBody(req)) === null || _e === void 0 ? void 0 : _e.SAMLRequest) {
this._saml
- .validatePostRequestAsync(req.body)
+ .validatePostRequestAsync(__overleafRawBody(req))
.then(validateCallback)
.catch((err) => this.error(err));
}
@@ -151,7 +174,7 @@ class AbstractStrategy extends passport_strategy_1.Strategy {
if (this._saml == null) {
throw new Error("Can't process login request without a SAML provider defined.");
}
- const RelayState = (req.query && req.query.RelayState) || (req.body && req.body.RelayState);
+ const RelayState = (__overleafRawQuery(req) && __overleafRawQuery(req).RelayState) || (__overleafRawBody(req) && __overleafRawBody(req).RelayState);
const host = req.headers && req.headers.host;
if (this._saml.options.authnRequestBinding === "HTTP-POST") {
const data = await this._saml.getAuthorizeFormAsync(RelayState, host);
@@ -172,7 +195,7 @@ class AbstractStrategy extends passport_strategy_1.Strategy {
throw new Error("Can't process logout request without a SAML provider defined.");
}
try {
- const RelayState = (req.query && req.query.RelayState) || (req.body && req.body.RelayState);
+ const RelayState = (__overleafRawQuery(req) && __overleafRawQuery(req).RelayState) || (__overleafRawBody(req) && __overleafRawBody(req).RelayState);
// Defaults to HTTP-Redirect
this.redirect(await this._saml.getLogoutUrlAsync(req.user, RelayState, options));
}
@@ -188,7 +211,7 @@ class AbstractStrategy extends passport_strategy_1.Strategy {
if (this._saml == null) {
throw new Error("Can't logout without a SAML provider defined.");
}
- const RelayState = (req.query && req.query.RelayState) || (req.body && req.body.RelayState);
+ const RelayState = (__overleafRawQuery(req) && __overleafRawQuery(req).RelayState) || (__overleafRawBody(req) && __overleafRawBody(req).RelayState);
this._saml
.getLogoutUrlAsync(req.user, RelayState, {})
.then((url) => callback(null, url))
@@ -1,132 +0,0 @@
diff --git a/lib/read.js b/lib/read.js
index fce6283f50961e68c2f576031ed5e3d4fdc39984..6131c31fb8ba8d413e0a3bf887ebd87f1c3a4007 100644
--- a/lib/read.js
+++ b/lib/read.js
@@ -18,7 +18,7 @@ var iconv = require('iconv-lite')
var onFinished = require('on-finished')
var unpipe = require('unpipe')
var zlib = require('zlib')
-
+var Stream = require('stream')
/**
* Module exports.
*/
@@ -166,25 +166,25 @@ function contentstream (req, debug, inflate) {
case 'deflate':
stream = zlib.createInflate()
debug('inflate body')
- req.pipe(stream)
+ // req.pipe(stream)
break
case 'gzip':
stream = zlib.createGunzip()
debug('gunzip body')
- req.pipe(stream)
+ // req.pipe(stream)
break
case 'identity':
stream = req
stream.length = length
- break
+ return req
default:
throw createError(415, 'unsupported content encoding "' + encoding + '"', {
encoding: encoding,
type: 'encoding.unsupported'
})
}
-
- return stream
+ var pass = new Stream.PassThrough(); Stream.pipeline(req, stream, pass, () => {})
+ return pass
}
/**
diff --git a/lib/types/json.js b/lib/types/json.js
index 59f3f7e28f2416cac957b5e35dc78839a5019e0d..f23e52eca828a726f12e915f8ea52698d3761d68 100644
--- a/lib/types/json.js
+++ b/lib/types/json.js
@@ -17,6 +17,8 @@ var contentType = require('content-type')
var createError = require('http-errors')
var debug = require('debug')('body-parser:json')
var read = require('../read')
+var LOCKDOWN_INSTALLED = Symbol.for('overleaf.lockdown.installed')
+var LOCKDOWN_RAW_BODY = Symbol.for('overleaf.lockdown.rawBody')
var typeis = require('type-is')
/**
@@ -105,7 +107,7 @@ function json (options) {
return
}
- req.body = req.body || {}
+ req.body = (req[LOCKDOWN_INSTALLED] ? req[LOCKDOWN_RAW_BODY] : req.body) || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
diff --git a/lib/types/raw.js b/lib/types/raw.js
index f5d1b67475405284e3dac312f92ade101571329f..251780a624b09340b8a821974565fa330f9792b7 100644
--- a/lib/types/raw.js
+++ b/lib/types/raw.js
@@ -13,6 +13,8 @@
var bytes = require('bytes')
var debug = require('debug')('body-parser:raw')
var read = require('../read')
+var LOCKDOWN_INSTALLED = Symbol.for('overleaf.lockdown.installed')
+var LOCKDOWN_RAW_BODY = Symbol.for('overleaf.lockdown.rawBody')
var typeis = require('type-is')
/**
@@ -59,7 +61,7 @@ function raw (options) {
return
}
- req.body = req.body || {}
+ req.body = (req[LOCKDOWN_INSTALLED] ? req[LOCKDOWN_RAW_BODY] : req.body) || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
diff --git a/lib/types/text.js b/lib/types/text.js
index 083a00908a6299a8ef72f477983359f5675f82ef..4ea3ee88191bf02ecedf6c975d20144d4d7f2f47 100644
--- a/lib/types/text.js
+++ b/lib/types/text.js
@@ -14,6 +14,8 @@ var bytes = require('bytes')
var contentType = require('content-type')
var debug = require('debug')('body-parser:text')
var read = require('../read')
+var LOCKDOWN_INSTALLED = Symbol.for('overleaf.lockdown.installed')
+var LOCKDOWN_RAW_BODY = Symbol.for('overleaf.lockdown.rawBody')
var typeis = require('type-is')
/**
@@ -61,7 +63,7 @@ function text (options) {
return
}
- req.body = req.body || {}
+ req.body = (req[LOCKDOWN_INSTALLED] ? req[LOCKDOWN_RAW_BODY] : req.body) || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
diff --git a/lib/types/urlencoded.js b/lib/types/urlencoded.js
index 832992c2c3e0324c9bcb612a01f2fe2fb3e19414..4da13852cd5a89c97d8d7be2b81ba8fd62551f9e 100644
--- a/lib/types/urlencoded.js
+++ b/lib/types/urlencoded.js
@@ -18,6 +18,8 @@ var createError = require('http-errors')
var debug = require('debug')('body-parser:urlencoded')
var deprecate = require('depd')('body-parser')
var read = require('../read')
+var LOCKDOWN_INSTALLED = Symbol.for('overleaf.lockdown.installed')
+var LOCKDOWN_RAW_BODY = Symbol.for('overleaf.lockdown.rawBody')
var typeis = require('type-is')
/**
@@ -83,7 +85,7 @@ function urlencoded (options) {
return
}
- req.body = req.body || {}
+ req.body = (req[LOCKDOWN_INSTALLED] ? req[LOCKDOWN_RAW_BODY] : req.body) || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
@@ -1,46 +0,0 @@
diff --git a/index.js b/index.js
index 367bdbafbc71b61daf3907913c3861d155140f07..b31ff2d98186ac29446718edfccc03a3562e796a 100644
--- a/index.js
+++ b/index.js
@@ -17,6 +17,30 @@ var Cookie = require('cookie')
var createError = require('http-errors')
var sign = require('cookie-signature').sign
var Tokens = require('csrf')
+// --- Overleaf patch: request-input lockdown compatibility ---
+// The default value getter reads req.body/req.query directly to find the
+// CSRF token submitted alongside a mutating request -- otherwise
+// indistinguishable from unvalidated application code reading raw request
+// input under Overleaf's request-input lockdown (see
+// libraries/validation-tools and the patched express in
+// .yarn/patches/express-npm-*.patch). The lockdown captures the original
+// parsed values in symbol-keyed fields, registered in the global symbol
+// registry (the same ones @overleaf/validation-tools' lockdown.js reads),
+// and only turns the *public* req.query/req.body properties into throwing
+// accessors -- reading through these raw fields instead sidesteps that, and
+// is identical to plain req.query/req.body when the lockdown isn't
+// installed (i.e. for every consumer of this package outside this
+// monorepo).
+var __overleafLockdownInstalled = Symbol.for('overleaf.lockdown.installed')
+var __overleafLockdownRawQuery = Symbol.for('overleaf.lockdown.rawQuery')
+var __overleafLockdownRawBody = Symbol.for('overleaf.lockdown.rawBody')
+function __overleafRawQuery (req) {
+ return req[__overleafLockdownInstalled] ? req[__overleafLockdownRawQuery] : req.query
+}
+function __overleafRawBody (req) {
+ return req[__overleafLockdownInstalled] ? req[__overleafLockdownRawBody] : req.body
+}
+// --- end Overleaf patch ---
/**
* Module exports.
@@ -128,8 +152,8 @@ function csurf (options) {
*/
function defaultValue (req) {
- return (req.body && req.body._csrf) ||
- (req.query && req.query._csrf) ||
+ return (__overleafRawBody(req) && __overleafRawBody(req)._csrf) ||
+ (__overleafRawQuery(req) && __overleafRawQuery(req)._csrf) ||
(req.headers['csrf-token']) ||
(req.headers['xsrf-token']) ||
(req.headers['x-csrf-token']) ||
File diff suppressed because one or more lines are too long
@@ -1,55 +0,0 @@
diff --git a/index.js b/index.js
index 49f181005f74cf11db3bd5b0ecf512520163ec71..d47ad4270883b90766152342c99495a07cb952e0 100644
--- a/index.js
+++ b/index.js
@@ -1,5 +1,29 @@
const parseCookie = require('cookie').parse;
const decodeCookie = require('cookie-parser').signedCookie;
+// --- Overleaf patch: request-input lockdown compatibility ---
+// This middleware is mounted globally, before any router split, and reads
+// req.query/req.body directly to look for a bearer token -- otherwise
+// indistinguishable from unvalidated application code reading raw request
+// input under Overleaf's request-input lockdown (see
+// libraries/validation-tools and the patched express in
+// .yarn/patches/express-npm-*.patch). The lockdown captures the original
+// parsed values in symbol-keyed fields, registered in the global symbol
+// registry (the same ones @overleaf/validation-tools' lockdown.js reads),
+// and only turns the *public* req.query/req.body properties into throwing
+// accessors -- reading through these raw fields instead sidesteps that, and
+// is identical to plain req.query/req.body when the lockdown isn't
+// installed (i.e. for every consumer of this package outside this
+// monorepo).
+const __overleafLockdownInstalled = Symbol.for('overleaf.lockdown.installed');
+const __overleafLockdownRawQuery = Symbol.for('overleaf.lockdown.rawQuery');
+const __overleafLockdownRawBody = Symbol.for('overleaf.lockdown.rawBody');
+function __overleafRawQuery(req) {
+ return req[__overleafLockdownInstalled] ? req[__overleafLockdownRawQuery] : req.query;
+}
+function __overleafRawBody(req) {
+ return req[__overleafLockdownInstalled] ? req[__overleafLockdownRawBody] : req.body;
+}
+// --- end Overleaf patch ---
const getCookie = (serialized_cookies, key) => parseCookie(serialized_cookies)[key] || false;
@@ -32,16 +56,16 @@ module.exports = opts => {
let error;
// query
- if (req.query && req.query[queryKey]) {
- token = req.query[queryKey];
+ if (__overleafRawQuery(req) && __overleafRawQuery(req)[queryKey]) {
+ token = __overleafRawQuery(req)[queryKey];
}
// body
- if (req.body && req.body[bodyKey]) {
+ if (__overleafRawBody(req) && __overleafRawBody(req)[bodyKey]) {
if (token) {
error = true;
}
- token = req.body[bodyKey];
+ token = __overleafRawBody(req)[bodyKey];
}
// headers
@@ -1,287 +0,0 @@
diff --git a/lib/lockdown.js b/lib/lockdown.js
new file mode 100644
index 0000000000000000000000000000000000000000..7acc55484421812ddb66edf015cdf0e1125b1cab
--- /dev/null
+++ b/lib/lockdown.js
@@ -0,0 +1,157 @@
+/*!
+ * Overleaf request-input lockdown.
+ *
+ * Captures parsed request input in symbol-keyed fields and, when
+ * REQ_LOCKDOWN_MODE is 'warn' or 'throw', turns the public req.body,
+ * req.query and req.params properties into lockdown accessors:
+ *
+ * - reads log a warning ('warn' mode) or throw ('throw' mode); request
+ * input must be read through parseReq() from @overleaf/validation-tools,
+ * which validates it against a zod schema, or through getRawReqInput()
+ * for allowlisted middleware
+ * - writes always work and are stored in the symbol-keyed fields, so body
+ * parsers and middleware that assign req.body keep functioning unchanged
+ *
+ * With REQ_LOCKDOWN_MODE unset (or 'off') nothing is installed and express
+ * behaves exactly like the unpatched package.
+ *
+ * The symbols are registered in the global symbol registry so that
+ * @overleaf/validation-tools can read the raw fields without importing
+ * express internals. Express' own internals (router param processing, the
+ * query middleware, res.jsonp) go through the helpers below instead of the
+ * public properties so that only application code trips the lockdown.
+ *
+ * Note: unlike the stock properties, the locked accessors are defined
+ * non-enumerable so that iterating/serializing a request (e.g. in logging)
+ * does not trip the lockdown.
+ */
+
+'use strict';
+
+var RAW_BODY = Symbol.for('overleaf.lockdown.rawBody');
+var RAW_QUERY = Symbol.for('overleaf.lockdown.rawQuery');
+var RAW_PARAMS = Symbol.for('overleaf.lockdown.rawParams');
+var INSTALLED = Symbol.for('overleaf.lockdown.installed');
+
+var VALID_MODES = ['off', 'warn', 'throw'];
+var cachedMode = null;
+
+function mode() {
+ if (cachedMode === null) {
+ var m = process.env.REQ_LOCKDOWN_MODE || 'off';
+ cachedMode = VALID_MODES.indexOf(m) === -1 ? 'off' : m;
+ }
+ return cachedMode;
+}
+
+/**
+ * Override the mode for tests. Pass null to re-read REQ_LOCKDOWN_MODE on the
+ * next access. Only affects requests that have not been handled yet.
+ */
+function setModeForTests(m) {
+ if (m === null) {
+ cachedMode = null;
+ } else {
+ cachedMode = VALID_MODES.indexOf(m) === -1 ? 'off' : m;
+ }
+}
+
+var warned = new Set();
+
+function report(req, field) {
+ var route = req.route && req.route.path;
+ var location =
+ (req.method || 'UNKNOWN') +
+ ' ' +
+ (route || req.originalUrl || req.url || 'unknown');
+ if (mode() === 'warn') {
+ var key = location + ' ' + field;
+ if (!warned.has(key)) {
+ warned.add(key);
+ var stack = new Error('trace').stack.split('\n').slice(2, 7).join('\n');
+ console.warn(
+ 'req-lockdown: raw request input read: req.' +
+ field +
+ ' at ' +
+ location +
+ '\n' +
+ stack
+ );
+ }
+ return;
+ }
+ var err = new Error(
+ 'raw request input is forbidden — use parseReq() (read req.' +
+ field +
+ ' at ' +
+ location +
+ ')'
+ );
+ err.code = 'ERR_RAW_REQ_INPUT';
+ throw err;
+}
+
+/**
+ * Install the lockdown accessors on a request. Idempotent, no-op in 'off'
+ * mode. Called from the router, the query middleware and expressInit so that
+ * every request is covered no matter how the app is assembled.
+ */
+function install(req) {
+ if (mode() === 'off') return;
+ if (req[INSTALLED]) return;
+ req[INSTALLED] = true;
+ lockField(req, 'body', RAW_BODY);
+ lockField(req, 'query', RAW_QUERY);
+ lockField(req, 'params', RAW_PARAMS);
+}
+
+function lockField(req, field, symbol) {
+ // preserve a value assigned before lockdown was installed
+ if (Object.prototype.hasOwnProperty.call(req, field)) {
+ req[symbol] = req[field];
+ delete req[field];
+ }
+ Object.defineProperty(req, field, {
+ configurable: true,
+ enumerable: false,
+ get: function () {
+ report(this, field);
+ return this[symbol]; // only reached in 'warn' mode
+ },
+ set: function (value) {
+ this[symbol] = value;
+ },
+ });
+}
+
+/**
+ * Effective params/query for express internals: the raw fields once lockdown
+ * is installed, the plain properties otherwise.
+ */
+function getParams(req) {
+ return req[INSTALLED] ? req[RAW_PARAMS] : req.params;
+}
+
+function getQuery(req) {
+ return req[INSTALLED] ? req[RAW_QUERY] : req.query;
+}
+
+/**
+ * Property key under which the router saves/restores params on the request.
+ */
+function paramsProp(req) {
+ return req[INSTALLED] ? RAW_PARAMS : 'params';
+}
+
+module.exports = {
+ RAW_BODY: RAW_BODY,
+ RAW_QUERY: RAW_QUERY,
+ RAW_PARAMS: RAW_PARAMS,
+ INSTALLED: INSTALLED,
+ mode: mode,
+ setModeForTests: setModeForTests,
+ install: install,
+ getParams: getParams,
+ getQuery: getQuery,
+ paramsProp: paramsProp,
+};
diff --git a/lib/middleware/init.js b/lib/middleware/init.js
index dfd042747bdb971d9760e9575241ddaa1b776cd8..162ec6da452bde5f5384d3d5bd79d5727742ed8f 100644
--- a/lib/middleware/init.js
+++ b/lib/middleware/init.js
@@ -14,6 +14,7 @@
*/
var setPrototypeOf = require('setprototypeof')
+var lockdown = require('../lockdown')
/**
* Initialization middleware, exposing the
@@ -27,6 +28,7 @@ var setPrototypeOf = require('setprototypeof')
exports.init = function(app){
return function expressInit(req, res, next){
+ lockdown.install(req);
if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express');
req.res = res;
res.req = req;
diff --git a/lib/middleware/query.js b/lib/middleware/query.js
index 7e9166947aff3be10f7ffec3771c92581ce211da..aad897b7ecd43477c1768e135ac06211a2424d36 100644
--- a/lib/middleware/query.js
+++ b/lib/middleware/query.js
@@ -15,6 +15,7 @@
var merge = require('utils-merge')
var parseUrl = require('parseurl');
var qs = require('qs');
+var lockdown = require('../lockdown');
/**
* @param {Object} options
@@ -37,7 +38,9 @@ module.exports = function query(options) {
}
return function query(req, res, next){
- if (!req.query) {
+ lockdown.install(req);
+
+ if (!lockdown.getQuery(req)) {
var val = parseUrl(req).query;
req.query = queryparse(val, opts);
}
diff --git a/lib/response.js b/lib/response.js
index 2b654f4c6629c821bbeaaeee970b199a420fd8b3..103df49d3d94abf017022cdcf4611e62cad84a74 100644
--- a/lib/response.js
+++ b/lib/response.js
@@ -29,6 +29,7 @@ var normalizeType = require('./utils').normalizeType;
var normalizeTypes = require('./utils').normalizeTypes;
var setCharset = require('./utils').setCharset;
var cookie = require('cookie');
+var lockdown = require('./lockdown');
var send = require('send');
var extname = path.extname;
var mime = send.mime;
@@ -312,7 +313,7 @@ res.jsonp = function jsonp(obj) {
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = stringify(val, replacer, spaces, escape)
- var callback = this.req.query[app.get('jsonp callback name')];
+ var callback = lockdown.getQuery(this.req)[app.get('jsonp callback name')];
// content-type
if (!this.get('Content-Type')) {
diff --git a/lib/router/index.js b/lib/router/index.js
index abb3a6f589e834c5e105f2a96907ed2eb6fc0185..66fef252003098bcc268ef2ebcef0d20b3cce62b 100644
--- a/lib/router/index.js
+++ b/lib/router/index.js
@@ -22,6 +22,7 @@ var deprecate = require('depd')('express');
var flatten = require('array-flatten');
var parseUrl = require('parseurl');
var setPrototypeOf = require('setprototypeof')
+var lockdown = require('../lockdown');
/**
* Module variables.
@@ -136,6 +137,8 @@ proto.param = function param(name, fn) {
proto.handle = function handle(req, res, out) {
var self = this;
+ lockdown.install(req);
+
debug('dispatching %s %s', req.method, req.url);
var idx = 0;
@@ -153,9 +156,9 @@ proto.handle = function handle(req, res, out) {
var stack = self.stack;
// manage inter-router variables
- var parentParams = req.params;
+ var parentParams = lockdown.getParams(req);
var parentUrl = req.baseUrl || '';
- var done = restore(out, req, 'baseUrl', 'next', 'params');
+ var done = restore(out, req, 'baseUrl', 'next', lockdown.paramsProp(req));
// setup next layer
req.next = next;
@@ -368,7 +371,7 @@ proto.process_params = function process_params(layer, called, req, res, done) {
paramIndex = 0;
key = keys[i++];
name = key.name;
- paramVal = req.params[name];
+ paramVal = lockdown.getParams(req)[name];
paramCallbacks = params[name];
paramCalled = called[name];
@@ -380,7 +383,7 @@ proto.process_params = function process_params(layer, called, req, res, done) {
if (paramCalled && (paramCalled.match === paramVal
|| (paramCalled.error && paramCalled.error !== 'route'))) {
// restore value
- req.params[name] = paramCalled.value;
+ lockdown.getParams(req)[name] = paramCalled.value;
// next param
return param(paramCalled.error);
@@ -400,7 +403,7 @@ proto.process_params = function process_params(layer, called, req, res, done) {
var fn = paramCallbacks[paramIndex++];
// store updated value
- paramCalled.value = req.params[key.name];
+ paramCalled.value = lockdown.getParams(req)[key.name];
if (err) {
// store error
@@ -1,34 +0,0 @@
diff --git a/lib/make-middleware.js b/lib/make-middleware.js
index 2c15f248d4f4d221bd9e2b2e1092b8d5c46d2bdd..859f55f56729f0a3874cfdac53722497cfc3c461 100644
--- a/lib/make-middleware.js
+++ b/lib/make-middleware.js
@@ -26,7 +26,10 @@ function makeMiddleware (setup) {
var preservePath = options.preservePath
var defParamCharset = options.defParamCharset
- req.body = Object.create(null)
+ // keep a local reference: with the Overleaf request-input lockdown
+ // installed, writing req.body is allowed but reading it warns/throws
+ var body = Object.create(null)
+ req.body = body
var busboy
var appender = null
@@ -157,7 +160,7 @@ function makeMiddleware (setup) {
if (fieldname.split('[').length - 1 > limits.fieldNestingDepth) return abortWithCode('LIMIT_FIELD_NESTING', fieldname)
}
- appendField(req.body, fieldname, value)
+ appendField(body, fieldname, value)
})
// handle files
@@ -174,7 +177,7 @@ function makeMiddleware (setup) {
if (fieldname == null) return abortWithCode('MISSING_FIELD_NAME')
// don't attach to the files object, if there is no file
- if (!filename) return fileStream.resume()
+ if (!filename) filename = 'undefined'
// Work around bug in Busboy (https://github.com/mscdex/busboy/issues/6)
if (limits && Object.prototype.hasOwnProperty.call(limits, 'fieldNameSize')) {
@@ -1,25 +0,0 @@
diff --git a/lib/strategy.js b/lib/strategy.js
index e54e92a86c8e3d40338ed8c6e57e8729393d85a3..cad017ef2027ad676782515a9803835138efa6b3 100644
--- a/lib/strategy.js
+++ b/lib/strategy.js
@@ -66,10 +66,18 @@ util.inherits(Strategy, passport.Strategy);
* @param {Object} req
* @api protected
*/
+var LOCKDOWN_INSTALLED = Symbol.for('overleaf.lockdown.installed');
+var LOCKDOWN_RAW_BODY = Symbol.for('overleaf.lockdown.rawBody');
+var LOCKDOWN_RAW_QUERY = Symbol.for('overleaf.lockdown.rawQuery');
+
Strategy.prototype.authenticate = function(req, options) {
options = options || {};
- var username = lookup(req.body, this._usernameField) || lookup(req.query, this._usernameField);
- var password = lookup(req.body, this._passwordField) || lookup(req.query, this._passwordField);
+ // with the Overleaf request-input lockdown installed, read the raw
+ // symbol-keyed fields; the public req.body/req.query accessors warn/throw
+ var body = req[LOCKDOWN_INSTALLED] ? req[LOCKDOWN_RAW_BODY] : req.body;
+ var query = req[LOCKDOWN_INSTALLED] ? req[LOCKDOWN_RAW_QUERY] : req.query;
+ var username = lookup(body, this._usernameField) || lookup(query, this._usernameField);
+ var password = lookup(body, this._passwordField) || lookup(query, this._passwordField);
if (!username || !password) {
return this.fail({ message: options.badRequestMessage || 'Missing credentials' }, 400);
@@ -1,85 +0,0 @@
diff --git a/lib/strategy.js b/lib/strategy.js
index b05aacce9a16fd32743a989b68f179bb35b20545..de1293a75c82452089eea37ab1031d4bbe42849c 100644
--- a/lib/strategy.js
+++ b/lib/strategy.js
@@ -14,6 +14,25 @@ var passport = require('passport-strategy')
, AuthorizationError = require('./errors/authorizationerror')
, TokenError = require('./errors/tokenerror')
, InternalOAuthError = require('./errors/internaloautherror');
+// --- Overleaf patch: request-input lockdown compatibility ---
+// This strategy reads req.query directly to parse the OAuth2 protocol
+// fields (error/error_description/error_uri, code, state) it's built
+// around, which is otherwise indistinguishable from unvalidated application
+// code reading raw request input under Overleaf's request-input lockdown
+// (see libraries/validation-tools and the patched express in
+// .yarn/patches/express-npm-*.patch). The lockdown captures the original
+// parsed values in symbol-keyed fields, registered in the global symbol
+// registry (the same ones @overleaf/validation-tools' lockdown.js reads),
+// and only turns the *public* req.query property into a throwing accessor
+// -- reading through this raw field instead sidesteps that, and is
+// identical to plain req.query when the lockdown isn't installed (i.e. for
+// every consumer of this package outside this monorepo).
+var __overleafLockdownInstalled = Symbol.for('overleaf.lockdown.installed');
+var __overleafLockdownRawQuery = Symbol.for('overleaf.lockdown.rawQuery');
+function __overleafRawQuery(req) {
+ return req[__overleafLockdownInstalled] ? req[__overleafLockdownRawQuery] : req.query;
+}
+// --- end Overleaf patch ---
/**
@@ -131,11 +150,11 @@ OAuth2Strategy.prototype.authenticate = function(req, options) {
options = options || {};
var self = this;
- if (req.query && req.query.error) {
- if (req.query.error == 'access_denied') {
- return this.fail({ message: req.query.error_description });
+ if (__overleafRawQuery(req) && __overleafRawQuery(req).error) {
+ if (__overleafRawQuery(req).error == 'access_denied') {
+ return this.fail({ message: __overleafRawQuery(req).error_description });
} else {
- return this.error(new AuthorizationError(req.query.error_description, req.query.error, req.query.error_uri));
+ return this.error(new AuthorizationError(__overleafRawQuery(req).error_description, __overleafRawQuery(req).error, __overleafRawQuery(req).error_uri));
}
}
@@ -156,14 +175,14 @@ OAuth2Strategy.prototype.authenticate = function(req, options) {
callbackURL: callbackURL
}
- if (req.query && req.query.code) {
+ if (__overleafRawQuery(req) && __overleafRawQuery(req).code) {
function loaded(err, ok, state) {
if (err) { return self.error(err); }
if (!ok) {
return self.fail(state, 403);
}
- var code = req.query.code;
+ var code = __overleafRawQuery(req).code;
var params = self.tokenParams(options);
params.grant_type = 'authorization_code';
@@ -213,7 +232,7 @@ OAuth2Strategy.prototype.authenticate = function(req, options) {
);
}
- var state = req.query.state;
+ var state = __overleafRawQuery(req).state;
try {
var arity = this._stateStore.verify.length;
if (arity == 4) {
diff --git a/lib/utils.js b/lib/utils.js
index 486f9e1..4584507 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -24,7 +24,7 @@ exports.originalURL = function(req, options) {
var trustProxy = options.proxy;
var proto = (req.headers['x-forwarded-proto'] || '').toLowerCase()
- , tls = req.connection.encrypted || (trustProxy && 'https' == proto.split(/\s*,\s*/)[0])
+ , tls = (req.connection && req.connection.encrypted) || (trustProxy && 'https' == proto.split(/\s*,\s*/)[0])
, host = (trustProxy && req.headers['x-forwarded-host']) || req.headers.host
, protocol = tls ? 'https' : 'http'
, path = req.url || '';
-14
View File
@@ -1,14 +0,0 @@
diff --git a/internal/legacy-cli.mjs b/internal/legacy-cli.mjs
index a76a536..f4d95ad 100644
--- a/internal/legacy-cli.mjs
+++ b/internal/legacy-cli.mjs
@@ -5832,6 +5832,9 @@ async function formatFiles(context) {
}
output = result.formatted;
} catch (error2) {
+ // invalidate cache on format error
+ formatResultsCache?.removeFormatResultsCache(filename);
+
const errorIsIgnored = handleError(
context,
fileNameToDisplay,
File diff suppressed because it is too large Load Diff
@@ -1,30 +0,0 @@
diff --git a/index.js b/index.js
index 2fae107d03b30aff9320d135ec79c049c51f298a..32ec707ddbf8937e3e130c3deac1060c308bf439 100644
--- a/index.js
+++ b/index.js
@@ -1,6 +1,6 @@
'use strict';
-const {PassThrough} = require('stream');
+const {PassThrough, pipeline} = require('stream');
const extend = require('extend');
let debug = () => {};
@@ -185,7 +185,7 @@ function retryRequest(requestOpts, opts, callback) {
.on('complete', (...params) => handleFinish(params))
.on('finish', (...params) => handleFinish(params));
- requestStream.pipe(delayStream);
+ pipeline(requestStream, delayStream, () => {});
} else {
activeRequest = opts.request(requestOpts, onResponse);
}
@@ -251,7 +251,7 @@ function retryRequest(requestOpts, opts, callback) {
// No more attempts need to be made, just continue on.
if (streamMode) {
retryStream.emit('response', response);
- delayStream.pipe(retryStream);
+ pipeline(delayStream, retryStream, () => {});
requestStream.on('error', err => {
retryStream.destroy(err);
});
@@ -1,30 +0,0 @@
diff --git a/index.js b/index.js
index 298a351097d70a7fb005b6961f4d58247e391d8f..6a809ace0349d40cb2b6732ad66fd8ad208698ca 100644
--- a/index.js
+++ b/index.js
@@ -1,6 +1,6 @@
'use strict';
-const {PassThrough} = require('stream');
+const {PassThrough, pipeline} = require('stream');
const extend = require('extend');
let debug = () => {};
@@ -185,7 +185,7 @@ function retryRequest(requestOpts, opts, callback) {
.on('complete', (...params) => handleFinish(params))
.on('finish', (...params) => handleFinish(params));
- requestStream.pipe(delayStream);
+ pipeline(requestStream, delayStream, () => {});
} else {
activeRequest = opts.request(requestOpts, onResponse);
}
@@ -251,7 +251,7 @@ function retryRequest(requestOpts, opts, callback) {
// No more attempts need to be made, just continue on.
if (streamMode) {
retryStream.emit('response', response);
- delayStream.pipe(retryStream);
+ pipeline(delayStream, retryStream, () => {});
requestStream.on('error', err => {
retryStream.destroy(err);
});
@@ -1,251 +0,0 @@
diff --git a/lib/logout.js b/lib/logout.js
index 77c417213851ffbe4a29f1b501027b8727931d8f..03d1bd8452ce80964f187f541ff47986931d3b73 100644
--- a/lib/logout.js
+++ b/lib/logout.js
@@ -10,6 +10,20 @@ var zlib = require('zlib');
var qs = require('querystring');
var xtend = require('xtend');
var constants = require('./constants');
+// --- Overleaf patch: request-input lockdown compatibility ---
+// See lib/samlp.js for the full rationale; the IdP-initiated and
+// SP-initiated logout flows read SAMLRequest/SAMLResponse/RelayState off
+// req.query/req.body directly, same as the login flow there.
+var __overleafLockdownInstalled = Symbol.for('overleaf.lockdown.installed');
+var __overleafLockdownRawQuery = Symbol.for('overleaf.lockdown.rawQuery');
+var __overleafLockdownRawBody = Symbol.for('overleaf.lockdown.rawBody');
+function __overleafRawQuery(req) {
+ return req[__overleafLockdownInstalled] ? req[__overleafLockdownRawQuery] : req.query;
+}
+function __overleafRawBody(req) {
+ return req[__overleafLockdownInstalled] ? req[__overleafLockdownRawBody] : req.body;
+}
+// --- end Overleaf patch ---
var BINDINGS = constants.BINDINGS;
var STATUS = constants.STATUS;
@@ -87,7 +101,7 @@ module.exports.logout = function (options) {
}
function validateSamlResponse(req, sessionParticipant, cb) {
- var SAMLResponse = req.query.SAMLResponse || req.body.SAMLResponse;
+ var SAMLResponse = __overleafRawQuery(req).SAMLResponse || __overleafRawBody(req).SAMLResponse;
function parseAndValidate(err, buffer) {
if (err) { return cb(err); }
@@ -141,7 +155,7 @@ module.exports.logout = function (options) {
cb(null, parsedResponse);
}
- if (req.body.SAMLResponse || !options.deflate) {
+ if (__overleafRawBody(req).SAMLResponse || !options.deflate) {
// HTTP-POST or HTTP-Redirect without deflate encoding
return parseAndValidate(null, new Buffer(SAMLResponse, 'base64'));
}
@@ -153,7 +167,7 @@ module.exports.logout = function (options) {
return function (req, res, next) {
try {
// SP Initated flow.
- if (req.query.SAMLRequest || req.body.SAMLRequest) {
+ if (__overleafRawQuery(req).SAMLRequest || __overleafRawBody(req).SAMLRequest) {
const opts = {
getCredentials: function getCredentials(issuer, sessionIndices, nameId, cb) {
options.sessionParticipants.get(issuer, sessionIndices, nameId, function (err, session) {
@@ -168,7 +182,7 @@ module.exports.logout = function (options) {
});
}
};
- parseIncomingLogoutRequest(req, req.query.SAMLRequest || req.body.SAMLRequest, opts, function (err, requestData) {
+ parseIncomingLogoutRequest(req, __overleafRawQuery(req).SAMLRequest || __overleafRawBody(req).SAMLRequest, opts, function (err, requestData) {
if (err) { return next(err); }
if (!requestData.issuer) {
@@ -185,7 +199,7 @@ module.exports.logout = function (options) {
id: requestData.id,
serviceProviderLogoutURL: (session|| {}).serviceProviderLogoutURL || options.destination
},
- relayState: req.query.RelayState || (req.body && req.body.RelayState)
+ relayState: __overleafRawQuery(req).RelayState || (__overleafRawBody(req) && __overleafRawBody(req).RelayState)
};
options.store.save(req, spData, function (err, transactionId) {
@@ -206,7 +220,7 @@ module.exports.logout = function (options) {
});
// Logout flow in progress, incoming SAMLResponse from SP. (Could be SP initiated or IdP initiated)
- } else if (req.query.SAMLResponse || req.body.SAMLResponse) {
+ } else if (__overleafRawQuery(req).SAMLResponse || __overleafRawBody(req).SAMLResponse) {
function process(state, transactionId) {
// LogoutResponse was OK, we remove the session participant from the IdP
options.sessionParticipants.remove(state.issuer, state.sessionIndex, state.nameId, function (err) {
@@ -218,7 +232,7 @@ module.exports.logout = function (options) {
}
// Verify that the state sent to the SP matches the one returned
- var h = req.query.RelayState || (req.body && req.body.RelayState);
+ var h = __overleafRawQuery(req).RelayState || (__overleafRawBody(req) && __overleafRawBody(req).RelayState);
options.store.load(req, h, {destroy: true}, function (err, state) {
if (err) { return next(err); }
if (!state) { return next(new Error('Invalid RelayState')); }
@@ -379,7 +393,7 @@ module.exports.sendLogoutError = function(options){
// Signature location
options.reference = constants.ELEMENTS.LOGOUT_RESPONSE.SIGNATURE_LOCATION_PATH;
- options.relayState = options.relayState || req.query.RelayState || (req.body || {}).RelayState;
+ options.relayState = options.relayState || __overleafRawQuery(req).RelayState || (__overleafRawBody(req) || {}).RelayState;
return prepareAndSendToken(req, res, 'LOGOUT_RESPONSE', logoutResponse, options, next);
};
diff --git a/lib/samlp.js b/lib/samlp.js
index 19a13328d60124417e9aa844c6d54745f7121166..08bef8456e1dcbadceb0460588bb78fff1e3f122 100644
--- a/lib/samlp.js
+++ b/lib/samlp.js
@@ -7,6 +7,30 @@ var templates = require('./templates');
var encoders = require('./encoders');
var PassportProfileMapper = require('./claims/PassportProfileMapper');
var constants = require('./constants');
+// --- Overleaf patch: request-input lockdown compatibility ---
+// This library reads req.query/req.body directly to parse the SAML protocol
+// fields (Signature, SigAlg, RelayState, SAMLRequest/SAMLResponse) it is
+// built around, which is otherwise indistinguishable from unvalidated
+// application code reading raw request input under Overleaf's
+// request-input lockdown (see libraries/validation-tools and the patched
+// express in .yarn/patches/express-npm-*.patch). The lockdown captures the
+// original parsed values in symbol-keyed fields, registered in the global
+// symbol registry (the same ones @overleaf/validation-tools' lockdown.js
+// reads), and only turns the *public* req.query/req.body properties into
+// throwing accessors -- reading through these raw fields instead sidesteps
+// that, and is identical to plain req.query/req.body when the lockdown
+// isn't installed (i.e. for every consumer of this package outside this
+// monorepo).
+var __overleafLockdownInstalled = Symbol.for('overleaf.lockdown.installed');
+var __overleafLockdownRawQuery = Symbol.for('overleaf.lockdown.rawQuery');
+var __overleafLockdownRawBody = Symbol.for('overleaf.lockdown.rawBody');
+function __overleafRawQuery(req) {
+ return req[__overleafLockdownInstalled] ? req[__overleafLockdownRawQuery] : req.query;
+}
+function __overleafRawBody(req) {
+ return req[__overleafLockdownInstalled] ? req[__overleafLockdownRawBody] : req.body;
+}
+// --- end Overleaf patch ---
function buildSamlResponse(options) {
var SAMLResponse = templates.samlresponse({
@@ -153,10 +177,10 @@ module.exports.auth = function (options) {
return function (req, res, next) {
var opts = xtend({}, options || {}); // clone options
- if (req.method === 'GET' && req.query.Signature) {
- opts.signature = req.query.Signature;
- opts.sigAlg = req.query.SigAlg;
- opts.relayState = opts.RelayState || req.query.RelayState;
+ if (req.method === 'GET' && __overleafRawQuery(req).Signature) {
+ opts.signature = __overleafRawQuery(req).Signature;
+ opts.sigAlg = __overleafRawQuery(req).SigAlg;
+ opts.relayState = opts.RelayState || __overleafRawQuery(req).RelayState;
}
function execute(postUrl, audience, req, res, next) {
@@ -178,14 +202,14 @@ module.exports.auth = function (options) {
res.send(templates.form({
type: 'SAMLResponse',
callback: postUrl,
- RelayState: opts.RelayState || (req.query || {}).RelayState || (req.body || {}).RelayState || '',
+ RelayState: opts.RelayState || (__overleafRawQuery(req) || {}).RelayState || (__overleafRawBody(req) || {}).RelayState || '',
token: response.toString('base64')
}));
}
});
}
- utils.parseSamlRequest(req, (req.query || {}).SAMLRequest || (req.body || {}).SAMLRequest, "AUTHN_REQUEST", opts, function (err, samlRequestDom) {
+ utils.parseSamlRequest(req, (__overleafRawQuery(req) || {}).SAMLRequest || (__overleafRawBody(req) || {}).SAMLRequest, "AUTHN_REQUEST", opts, function (err, samlRequestDom) {
if (err) return next(err);
var audience = opts.audience;
@@ -216,7 +240,7 @@ module.exports.parseRequest = function (req, options, callback) {
options = {};
}
- var samlRequest = (req.query || {}).SAMLRequest || (req.body || {}).SAMLRequest;
+ var samlRequest = (__overleafRawQuery(req) || {}).SAMLRequest || (__overleafRawBody(req) || {}).SAMLRequest;
if (!samlRequest)
return callback();
diff --git a/lib/utils.js b/lib/utils.js
index c091ac335be08b2bf55907b269e8e1ef79b686bb..23940db43725664367329341a713f2a1077ad071 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -6,6 +6,21 @@ const url = require('url');
const xtend = require('xtend');
const signers = require('./signers');
const constants = require('./constants');
+// --- Overleaf patch: request-input lockdown compatibility ---
+// See lib/samlp.js for the full rationale; this module validates SAML
+// signatures carried on req.query/req.body (Signature, SigAlg, RelayState,
+// SAMLRequest/SAMLResponse) for both the login (samlp.js) and logout
+// (logout.js) flows.
+const __overleafLockdownInstalled = Symbol.for('overleaf.lockdown.installed');
+const __overleafLockdownRawQuery = Symbol.for('overleaf.lockdown.rawQuery');
+const __overleafLockdownRawBody = Symbol.for('overleaf.lockdown.rawBody');
+function __overleafRawQuery(req) {
+ return req[__overleafLockdownInstalled] ? req[__overleafLockdownRawQuery] : req.query;
+}
+function __overleafRawBody(req) {
+ return req[__overleafLockdownInstalled] ? req[__overleafLockdownRawBody] : req.body;
+}
+// --- end Overleaf patch ---
const IdGenerator = require('auth0-id-generator');
const generator = new IdGenerator({len: 20, alphabet:"abcdef0123456789"});
@@ -20,7 +35,7 @@ module.exports.parseSamlRequest = function(req, samlRequest, type, options, call
const opts = {
signingCert: options.signingCert,
thumbprints: options.thumbprints,
- deflate: !!req.query.Signature,
+ deflate: !!__overleafRawQuery(req).Signature,
relayState: options.relayState
};
@@ -186,10 +201,10 @@ function validateSignature(req, element_type, xml, options) {
const type = constants.ELEMENTS[element_type].PROP;
const isRequestSigned = !options.deflate ?
- xpath.select(options.signaturePath || constants.ELEMENTS[element_type].SIGNATURE_VALIDATION_PATH, xml).length > 0 : !!req.query.Signature;
+ xpath.select(options.signaturePath || constants.ELEMENTS[element_type].SIGNATURE_VALIDATION_PATH, xml).length > 0 : !!__overleafRawQuery(req).Signature;
if (isRequestSigned) {
- if ((req.body && req.body[type]) || !options.deflate) {
+ if ((__overleafRawBody(req) && __overleafRawBody(req)[type]) || !options.deflate) {
// HTTP-POST or HTTP-Redirect without deflate encoding
const validationErrors = signers.validateXmlEmbeddedSignature(xml, options);
if (validationErrors && validationErrors.length > 0) {
@@ -199,9 +214,9 @@ function validateSignature(req, element_type, xml, options) {
else {
// HTTP-Redirect with deflate encoding
let signedContent = {};
- signedContent[type] = req.query[type];
- signedContent.RelayState = req.query.RelayState || options.relayState;
- signedContent.SigAlg = req.query.SigAlg;
+ signedContent[type] = __overleafRawQuery(req)[type];
+ signedContent.RelayState = __overleafRawQuery(req).RelayState || options.relayState;
+ signedContent.SigAlg = __overleafRawQuery(req).SigAlg;
if (!signedContent.RelayState && !options.relayState) {
delete signedContent.RelayState;
@@ -215,13 +230,13 @@ function validateSignature(req, element_type, xml, options) {
throw new Error('Invalid signature algorithm. Supported algorithms are http://www.w3.org/2001/04/xmldsig-more#rsa-sha1 and http://www.w3.org/2001/04/xmldsig-more#rsa-sha256');
}
- const valid = signers.isValidContentAndSignature(qs.stringify(signedContent), req.query.Signature, {
+ const valid = signers.isValidContentAndSignature(qs.stringify(signedContent), __overleafRawQuery(req).Signature, {
signingCert: options.signingCert,
- signatureAlgorithm: req.query.SigAlg
+ signatureAlgorithm: __overleafRawQuery(req).SigAlg
});
if (!valid) {
- throw new Error('Signature check errors: The signature provided (' + req.query.Signature + ') does not match the one calculated');
+ throw new Error('Signature check errors: The signature provided (' + __overleafRawQuery(req).Signature + ') does not match the one calculated');
}
}
} else if (options.signingCert) {
@@ -1,57 +0,0 @@
diff --git a/lib/sandboxed_module.js b/lib/sandboxed_module.js
index 1cd6743..4718b97 100644
--- a/lib/sandboxed_module.js
+++ b/lib/sandboxed_module.js
@@ -4,7 +4,7 @@ var Module = require('module');
var fs = require('fs');
var vm = require('vm');
var path = require('path');
-var builtinModules = require('./builtin_modules.json');
+var builtinModules = Module.builtinModules || require('./builtin_modules.json');
var parent = module.parent;
var globalOptions = {};
var registeredBuiltInSourceTransformers = ['coffee'];
@@ -157,12 +157,20 @@ SandboxedModule.prototype._createRecursiveRequireProxy = function() {
var cache = Object.create(null);
var required = this._getRequires();
for (var key in required) {
- var injectedFilename = requireLike(this.filename).resolve(key);
- cache[injectedFilename] = required[key];
+ // Under Yarn PnP, resolution from a transitive dependency's context may fail
+ // for packages not declared in that dependency's package.json. Silently skip
+ // cache pre-population on failure; the mock will still be injected via the
+ // inject map in requireInterceptor or resolved via RecursiveRequireProxy fallback.
+ try {
+ var injectedFilename = requireLike(this.filename).resolve(key);
+ cache[injectedFilename] = required[key];
+ } catch (e) {}
}
cache[this.filename] = this.exports;
var globals = this.globals;
+ // Store the top-level module's filename for PnP fallback resolution
+ var topLevelFilename = this.filename;
var options;
if(!this._options.sourceTransformersSingleOnly && this._options.sourceTransformers){
options = {
@@ -208,8 +216,18 @@ SandboxedModule.prototype._createRecursiveRequireProxy = function() {
if (request in cache) return cache[request];
return require(request);
}
- // cached modules
- var requestedFilename = requireLike(this.filename).resolve(request);
+ // Resolve the requested module filename.
+ // Under Yarn PnP, packages can only resolve their declared dependencies.
+ // When sandboxed-module loads a transitive dependency, the resolution context
+ // may not have access to all needed packages. Fall back to resolving from
+ // the top-level module's context (the module under test).
+ var requestedFilename;
+ try {
+ requestedFilename = requireLike(this.filename).resolve(request);
+ } catch (e) {
+ if (this.filename === topLevelFilename) throw e;
+ requestedFilename = requireLike(topLevelFilename).resolve(request);
+ }
if (requestedFilename in cache) return cache[requestedFilename];
var sandboxedModule = createInnerSandboxedModule(requestedFilename)
return sandboxedModule.exports;
-109
View File
@@ -1,109 +0,0 @@
approvedGitRepositories:
- "**"
enableGlobalCache: false
enableScripts: true
enableTelemetry: false
nodeLinker: pnp
npmMinimalAgeGate: 3d
packageExtensions:
"bootstrap@*":
dependencies:
"@popperjs/core": "*"
jquery: "^3"
"@overleaf/settings@*":
peerDependencies:
"@overleaf/logger": "*"
"mongodb@*":
peerDependencies:
aws4: "*"
"bunyan@*":
peerDependencies:
source-map-support: "*"
"mocha-multi-reporters@*":
peerDependencies:
mocha-junit-reporter: "*"
"mongodb-legacy@*":
peerDependencies:
mongodb: "*"
"knex@*":
dependencies:
pg-query-stream: "*"
"zod-validation-error@*":
peerDependencies:
zod: "*"
"@vitejs/plugin-react@*":
peerDependencies:
vite: "*"
"@babel/preset-env@*":
peerDependencies:
core-js: "*"
"express@^4.0.0":
dependencies:
pug: "*"
"@prettier/plugin-pug@*":
dependencies:
pug: "*"
pug-filters: "*"
pug-lexer: "*"
pug-linker: "*"
pug-load: "*"
pug-parser: "*"
pug-runtime: "*"
pug-strip-comments: "*"
pug-walk: "*"
"postcss-loader@*":
peerDependencies:
autoprefixer: "*"
tailwindcss: "*"
"@ai-sdk/gateway@*":
peerDependencies:
zod: "*"
"@ai-sdk/provider-utils@*":
peerDependencies:
zod: "*"
"ai@*":
peerDependencies:
zod: "*"
"@uppy/react@*":
peerDependencies:
"@uppy/status-bar": "*"
"inversify@*":
dependencies:
reflect-metadata: "*"
# Must match services/web's pinned mongoose version exactly (not a range):
# sinon-mongoose checks `instanceof mongoose.Model` against its own resolved
# copy, so any version drift from web's copy breaks that check silently.
"sinon-mongoose@*":
dependencies:
mongoose: "8.24.3"
"react-linkify@*":
peerDependencies:
react: "*"
"socket.io-client@*":
dependencies:
ws: "*"
"debug@*":
peerDependenciesMeta:
supports-color:
optional: true
pnpZipBackend: js
supportedArchitectures:
cpu:
- current
- arm64
- x64
libc:
- current
- glibc
os:
- current
- darwin
- linux
+8 -4
View File
@@ -1,9 +1,11 @@
# Contributing to Overleaf CE+
Contributing to Overleaf CE+
============================
Thank you for reading this! If you'd like to report a bug or join in the development
of Overleaf CE+, then here are some notes on how to do that.
## Reporting bugs and opening issues
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/yu-i-i/overleaf-cep).**
If there is then please add any more information that you have, or give it a 👍.
@@ -13,7 +15,8 @@ reproduce the bug, which situations it appears in, what you expected to happen,
If you can include a screenshot for front end issues that is very helpful.
## Pull Requests
Pull Requests
-------------
See [Overleaf wiki](https://github.com/overleaf/overleaf/wiki)
for how to manage the Overleaf development environment and for our developer guidelines.
@@ -24,6 +27,7 @@ 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/yu-i-i/overleaf-cep/issues).
## Security
Security
--------
Please see [Overleaf security policy](https://github.com/overleaf/overleaf/security/policy) if you would like to report a potential security vulnerability.
+28 -16
View File
@@ -5,21 +5,34 @@ 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 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).
LDAP authentication was inspired by:
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.
## Autocomplete of reference keys
Autocomplete of reference keys is based on:
https://github.com/lcpu-club/overleaf
The implementation largely follows the referenced code, except that a different `.bib` file parser is used.
## 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 missing parts were implemented based on:
https://github.com/ertuil/overleaf
The referenced code was fixed, optimized, and extended.
@@ -35,24 +48,23 @@ 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)
Git integration is based on:
## GitHub synchronization
https://github.com/ayaka-notes/overleaf-pro/tree/feat-git-bridge
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).
The backend was completely rewritten.\
The frontend uses the referenced code, which was optimized and improved.
## Sign Up page
## Original Features
The Sign Up page is based on [this code](https://github.com/ayaka-notes/overleaf-pro/tree/feat-public-registeration).
The following features are original work implemented in this project:
## Python script runner
- Template Gallery
- Advanced administrator tools for managing user accounts and projects
- SAML authentication
- OpenID Connect authentication
The Python script runner feature is the original Overleaf implementation, which
[was hidden behind a paywall](https://github.com/overleaf/overleaf/commit/b90a8500d5df763d1a9b00352928a79c7e247de7) in later releases.
# Acknowledgments
## Acknowledgments
Thanks to the users of the project for valuable feedback, suggestions,
and help in identifying and fixing bugs.
+6 -12
View File
@@ -14,7 +14,7 @@
<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 CE+
Figure 1: A screenshot of a project being edited in Overleaf Extended Community Edition.
</p>
## Community Edition
@@ -25,23 +25,17 @@
The present "extended" version of Overleaf CE includes:
- Template gallery
- Sandboxed compiles with TeX Live image selection
- Sign Up page
- LDAP authentication
- SAML authentication
- OpenID Connect authentication
- Real-time track changes and comments
- Autocomplete of reference keys
- 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
- Python script runner
- Logo tools
- Git integration
> [!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.
@@ -82,13 +76,13 @@ folder are added.
## Authors
[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). See also the authors of individual commits.
[yu-i-i](https://github.com/yu-i-i/overleaf-cep) — 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-2026.\
Copyright (c) @yu-i-i, @davrot, 2024-2026, for CE extensions.
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).
+3
View File
@@ -0,0 +1,3 @@
/compiles/*
!.gitkeep
.env
+91
View File
@@ -0,0 +1,91 @@
# Overleaf Community Edition, development environment
## Building and running
In this `develop` directory, build the services:
```shell
bin/build
```
> [!NOTE]
> If Docker is running out of RAM while building the services in parallel, create a `.env` file in this directory containing `COMPOSE_PARALLEL_LIMIT=1`.
Then start the services:
```shell
bin/up
```
Once the services are running, open <http://localhost/launchpad> to create the first admin account.
## TeX Live
Compiling a PDF requires building a TeX Live image to handle the compilation inside Docker:
```shell
docker build texlive -t texlive-full
```
> [!NOTE]
> To compile on a macOS host, you may need to override the path to the Docker socket by creating a `.env` file in this directory, containing
> `DOCKER_SOCKET_PATH=/var/run/docker.sock.raw`
## Development
To avoid running `bin/build && bin/up` after every code change, you can run Overleaf
Community Edition in _development mode_, where services will automatically update on code changes.
To do this, use the included `bin/dev` script:
```shell
bin/dev
```
This will start all services using `node --watch`, which will automatically monitor the code and restart the services as necessary.
To improve performance, you can start only a subset of the services in development mode by providing a space-separated list to the `bin/dev` script:
```shell
bin/dev [service1] [service2] ... [serviceN]
```
> [!NOTE]
> Starting the `web` service in _development mode_ will only update the `web`
> service when backend code changes. In order to automatically update frontend
> code as well, make sure to start the `webpack` service in _development mode_
> as well.
If no services are named, all services will start in development mode.
## Debugging
When run in _development mode_ most services expose a debugging port to which
you can attach a debugger such as
[the inspector in Chrome's Dev Tools](chrome://inspect/) or one integrated into
an IDE. The following table shows the port exposed on the **host machine** for
each service:
| Service | Port |
| ------------------ | ---- |
| `web` | 9229 |
| `clsi` | 9230 |
| `chat` | 9231 |
| `contacts` | 9232 |
| `docstore` | 9233 |
| `document-updater` | 9234 |
| `filestore` | 9235 |
| `notifications` | 9236 |
| `real-time` | 9237 |
| `references` | 9238 |
| `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
click _Configure..._ and add an entry `localhost:[service port]` for each of the
services you want to attach a debugger to.
After adding an entry, the service will show up as a _Remote Target_ that you
can inspect and debug.
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
docker compose build --pull "$@"
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
docker-compose -f docker-compose.yml -f docker-compose.dev.yml up --no-deps --detach "$@"
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
docker compose down "$@"
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
docker compose logs --follow --tail 10 --no-color "$@" \
| ggrep --line-buffered --invert-match "global.gc" \
| ggrep --line-buffered --invert-match "health.check" \
| ggrep --line-buffered --invert-match "slow event loop" \
| ggrep --line-buffered --invert-match "process.memoryUsage" \
| ggrep --line-buffered --only-matching "[{].*" \
| bunyan --output short
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
docker compose exec -it "$@" /bin/bash
Executable
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
docker compose up --detach "$@"
View File
+26
View File
@@ -0,0 +1,26 @@
CHAT_HOST=chat
CLSI_HOST=clsi
CONTACTS_HOST=contacts
DOCSTORE_HOST=docstore
DOCUMENT_UPDATER_HOST=document-updater
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
NOTIFICATIONS_HOST=notifications
PROJECT_HISTORY_HOST=project-history
QUEUES_REDIS_HOST=redis
DSMP_REDIS_HOST=redis
REALTIME_HOST=real-time
REDIS_HOST=redis
REFERENCES_HOST=references
SESSION_SECRET=foo
V1_HISTORY_HOST=history-v1
WEBPACK_HOST=webpack
WEB_API_PASSWORD=overleaf
WEB_API_USER=overleaf
WEB_HOST=web
+161
View File
@@ -0,0 +1,161 @@
services:
clsi:
command: ["node", "--watch", "app.js"]
environment:
- NODE_OPTIONS=--inspect=0.0.0.0:9229
ports:
- "127.0.0.1:9230:9229"
volumes:
- ../services/clsi/app:/overleaf/services/clsi/app
- ../services/clsi/app.js:/overleaf/services/clsi/app.js
- ../services/clsi/config:/overleaf/services/clsi/config
chat:
command: ["node", "--watch", "app.js"]
environment:
- NODE_OPTIONS=--inspect=0.0.0.0:9229
ports:
- "127.0.0.1:9231:9229"
volumes:
- ../services/chat/app:/overleaf/services/chat/app
- ../services/chat/app.js:/overleaf/services/chat/app.js
- ../services/chat/config:/overleaf/services/chat/config
contacts:
command: ["node", "--watch", "app.js"]
environment:
- NODE_OPTIONS=--inspect=0.0.0.0:9229
ports:
- "127.0.0.1:9232:9229"
volumes:
- ../services/contacts/app:/overleaf/services/contacts/app
- ../services/contacts/app.js:/overleaf/services/contacts/app.js
- ../services/contacts/config:/overleaf/services/contacts/config
docstore:
command: ["node", "--watch", "app.js"]
environment:
- NODE_OPTIONS=--inspect=0.0.0.0:9229
ports:
- "127.0.0.1:9233:9229"
volumes:
- ../services/docstore/app:/overleaf/services/docstore/app
- ../services/docstore/app.js:/overleaf/services/docstore/app.js
- ../services/docstore/config:/overleaf/services/docstore/config
document-updater:
command: ["node", "--watch", "app.js"]
environment:
- NODE_OPTIONS=--inspect=0.0.0.0:9229
ports:
- "127.0.0.1:9234:9229"
volumes:
- ../services/document-updater/app:/overleaf/services/document-updater/app
- ../services/document-updater/app.js:/overleaf/services/document-updater/app.js
- ../services/document-updater/config:/overleaf/services/document-updater/config
filestore:
command: ["node", "--watch", "app.js"]
environment:
- NODE_OPTIONS=--inspect=0.0.0.0:9229
ports:
- "127.0.0.1:9235:9229"
volumes:
- ../services/filestore/app:/overleaf/services/filestore/app
- ../services/filestore/app.js:/overleaf/services/filestore/app.js
- ../services/filestore/config:/overleaf/services/filestore/config
history-v1:
command: ["node", "--watch", "app.js"]
environment:
- NODE_OPTIONS=--inspect=0.0.0.0:9229
ports:
- "127.0.0.1:9239:9229"
volumes:
- ../services/history-v1/api:/overleaf/services/history-v1/api
- ../services/history-v1/app.js:/overleaf/services/history-v1/app.js
- ../services/history-v1/config:/overleaf/services/history-v1/config
- ../services/history-v1/storage:/overleaf/services/history-v1/storage
- ../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:
- NODE_OPTIONS=--inspect=0.0.0.0:9229
ports:
- "127.0.0.1:9236:9229"
volumes:
- ../services/notifications/app:/overleaf/services/notifications/app
- ../services/notifications/app.ts:/overleaf/services/notifications/app.ts
- ../services/notifications/config:/overleaf/services/notifications/config
project-history:
command: ["node", "--watch", "app.js"]
environment:
- NODE_OPTIONS=--inspect=0.0.0.0:9229
ports:
- "127.0.0.1:9240:9229"
volumes:
- ../services/project-history/app:/overleaf/services/project-history/app
- ../services/project-history/app.js:/overleaf/services/project-history/app.js
- ../services/project-history/config:/overleaf/services/project-history/config
real-time:
command: ["node", "--watch", "app.js"]
environment:
- NODE_OPTIONS=--inspect=0.0.0.0:9229
ports:
- "127.0.0.1:9237:9229"
volumes:
- ../services/real-time/app:/overleaf/services/real-time/app
- ../services/real-time/app.js:/overleaf/services/real-time/app.js
- ../services/real-time/config:/overleaf/services/real-time/config
references:
command: ["node", "--watch", "app.js"]
environment:
- NODE_OPTIONS=--inspect=0.0.0.0:9229
ports:
- "127.0.0.1:9238:9229"
volumes:
- ../services/references/app:/overleaf/services/references/app
- ../services/references/config:/overleaf/services/references/config
- ../services/references/app.js:/overleaf/services/references/app.js
web:
command: ["node", "--watch", "app.mjs", "--watch-locales"]
environment:
- NODE_OPTIONS=--inspect=0.0.0.0:9229
ports:
- "127.0.0.1:9229:9229"
volumes:
- ../services/web/app:/overleaf/services/web/app
- ../services/web/app.mjs:/overleaf/services/web/app.mjs
- ../services/web/config:/overleaf/services/web/config
- ../services/web/locales:/overleaf/services/web/locales
- ../services/web/modules:/overleaf/services/web/modules
- ../services/web/public:/overleaf/services/web/public
webpack:
volumes:
- ../services/web/app:/overleaf/services/web/app
- ../services/web/config:/overleaf/services/web/config
- ../services/web/frontend:/overleaf/services/web/frontend
- ../services/web/locales:/overleaf/services/web/locales
- ../services/web/modules:/overleaf/services/web/modules
- ../services/web/public:/overleaf/services/web/public
- ../services/web/transform:/overleaf/services/web/transform
- ../services/web/types:/overleaf/services/web/types
- ../services/web/webpack-plugins:/overleaf/services/web/webpack-plugins
+204
View File
@@ -0,0 +1,204 @@
volumes:
clsi-cache:
filestore-public-files:
filestore-template-files:
filestore-uploads:
filestore-user-files:
mongo-data:
redis-data:
sharelatex-data:
web-data:
history-v1-buckets:
services:
chat:
build:
context: ..
dockerfile: services/chat/Dockerfile
env_file:
- dev.env
clsi:
build:
context: ..
dockerfile: services/clsi/Dockerfile
env_file:
- dev.env
environment:
- TEXLIVE_IMAGE=texlive-full # docker build texlive -t texlive-full
- SANDBOXED_COMPILES=true
- SANDBOXED_COMPILES_HOST_DIR_COMPILES=${PWD}/compiles
- SANDBOXED_COMPILES_HOST_DIR_OUTPUT=${PWD}/output
user: root
volumes:
- ${PWD}/compiles:/overleaf/services/clsi/compiles
- ${PWD}/output:/overleaf/services/clsi/output
- ${DOCKER_SOCKET_PATH:-/var/run/docker.sock}:/var/run/docker.sock
- clsi-cache:/overleaf/services/clsi/cache
contacts:
build:
context: ..
dockerfile: services/contacts/Dockerfile
env_file:
- dev.env
docstore:
build:
context: ..
dockerfile: services/docstore/Dockerfile
env_file:
- dev.env
document-updater:
build:
context: ..
dockerfile: services/document-updater/Dockerfile
env_file:
- dev.env
filestore:
build:
context: ..
dockerfile: services/filestore/Dockerfile
env_file:
- dev.env
# environment:
# - ENABLE_CONVERSIONS=true
volumes:
- filestore-public-files:/overleaf/services/filestore/public_files
- filestore-template-files:/overleaf/services/filestore/template_files
- filestore-uploads:/overleaf/services/filestore/uploads
history-v1:
build:
context: ..
dockerfile: services/history-v1/Dockerfile
env_file:
- dev.env
environment:
OVERLEAF_EDITOR_ANALYTICS_BUCKET: "/buckets/analytics"
OVERLEAF_EDITOR_BLOBS_BUCKET: "/buckets/blobs"
OVERLEAF_EDITOR_CHUNKS_BUCKET: "/buckets/chunks"
OVERLEAF_EDITOR_PROJECT_BLOBS_BUCKET: "/buckets/project_blobs"
OVERLEAF_EDITOR_ZIPS_BUCKET: "/buckets/zips"
PERSISTOR_BACKEND: fs
volumes:
- history-v1-buckets:/buckets
linked-url-proxy:
build:
context: ..
dockerfile: services/linked-url-proxy/Dockerfile
env_file:
- dev.env
mongo:
image: mongo:6.0
command: --replSet overleaf
ports:
- "127.0.0.1:27017:27017" # for debugging
volumes:
- mongo-data:/data/db
- ../bin/shared/mongodb-init-replica-set.js:/docker-entrypoint-initdb.d/mongodb-init-replica-set.js
environment:
MONGO_INITDB_DATABASE: sharelatex
extra_hosts:
# Required when using the automatic database setup for initializing the
# replica set. This override is not needed when running the setup after
# starting up mongo.
- mongo:127.0.0.1
notifications:
build:
context: ..
dockerfile: services/notifications/Dockerfile
env_file:
- dev.env
project-history:
build:
context: ..
dockerfile: services/project-history/Dockerfile
env_file:
- dev.env
real-time:
build:
context: ..
dockerfile: services/real-time/Dockerfile
env_file:
- dev.env
redis:
image: redis:5
ports:
- "127.0.0.1:6379:6379" # for debugging
volumes:
- redis-data:/data
references:
build:
context: ..
dockerfile: services/references/Dockerfile
env_file:
- dev.env
web:
build:
context: ..
dockerfile: services/web/Dockerfile
target: dev
env_file:
- dev.env
environment:
- APP_NAME=Overleaf Community Edition
- ENABLED_LINKED_FILE_TYPES=project_file,project_output_file
- EMAIL_CONFIRMATION_DISABLED=true
- NODE_ENV=development
- OVERLEAF_ALLOW_PUBLIC_ACCESS=true
command: ["node", "app.mjs"]
volumes:
- sharelatex-data:/var/lib/overleaf
- web-data:/overleaf/services/web/data
depends_on:
- mongo
- redis
- chat
- clsi
- contacts
- docstore
- document-updater
- filestore
- history-v1
- linked-url-proxy
- notifications
- project-history
- real-time
- references
webpack:
build:
context: ..
dockerfile: services/web/Dockerfile
target: webpack
command: ["npx", "webpack", "serve", "--config", "webpack.config.dev-env.js"]
ports:
- "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
+8
View File
@@ -0,0 +1,8 @@
FROM debian:testing-slim
RUN apt-get update
RUN apt-cache depends texlive-full | grep "Depends: " | grep -v -- "-doc" | grep -v -- "-lang-" | sed 's/Depends: //' | xargs apt-get install -y --no-install-recommends
RUN apt-get install -y --no-install-recommends fontconfig inkscape pandoc python3-pygments
RUN useradd tex
USER tex
+28
View File
@@ -0,0 +1,28 @@
const { merge } = require('webpack-merge')
const base = require('./webpack.config.dev')
module.exports = merge(base, {
devServer: {
allowedHosts: 'auto',
devMiddleware: {
index: false,
},
proxy: [
{
context: '/socket.io/**',
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: 412 KiB

After

Width:  |  Height:  |  Size: 525 KiB

+21 -21
View File
@@ -1,23 +1,23 @@
version: "2.2"
version: '2.2'
services:
sharelatex:
ports:
- 30000:30000
- 30150:30150
- 30120:30120
- 30050:30050
- 30420:30420
- 30030:30030
- 30160:30160
- 30360:30360
- 30130:30130
- 30100:30100
- 30540:30540
- 30640:30640
- 40000:40000
sharelatex:
ports:
- 30000:30000
- 30150:30150
- 30120:30120
- 30050:30050
- 30420:30420
- 30030:30030
- 30160:30160
- 30360:30360
- 30130:30130
- 30100:30100
- 30540:30540
- 30640:30640
- 40000:40000
# Server Pro
- 30070:30070
- 30400:30400
environment:
DEBUG_NODE: "true"
# Server Pro
- 30070:30070
- 30400:30400
environment:
DEBUG_NODE: 'true'
+127 -130
View File
@@ -1,154 +1,151 @@
services:
sharelatex:
restart: always
# Server Pro users:
# image: quay.io/sharelatex/sharelatex-pro
image: sharelatex/sharelatex
container_name: sharelatex
depends_on:
mongo:
condition: service_healthy
redis:
condition: service_started
ports:
- 80:80
stop_grace_period: 60s
volumes:
- ~/sharelatex_data:/var/lib/overleaf
########################################################################
#### Server Pro: Uncomment the following line to mount the docker ####
#### socket, required for Sibling Containers to work ####
########################################################################
# - /var/run/docker.sock:/var/run/docker.sock
environment:
OVERLEAF_APP_NAME: Overleaf Community Edition
sharelatex:
restart: always
# Server Pro users:
# image: quay.io/sharelatex/sharelatex-pro
image: sharelatex/sharelatex
container_name: sharelatex
depends_on:
mongo:
condition: service_healthy
redis:
condition: service_started
ports:
- 80:80
stop_grace_period: 60s
volumes:
- ~/sharelatex_data:/var/lib/overleaf
########################################################################
#### Server Pro: Uncomment the following line to mount the docker ####
#### socket, required for Sibling Containers to work ####
########################################################################
# - /var/run/docker.sock:/var/run/docker.sock
environment:
OVERLEAF_MONGO_URL: mongodb://mongo/sharelatex
OVERLEAF_APP_NAME: Overleaf Community Edition
# Same property, unfortunately with different names in
# different locations
OVERLEAF_REDIS_HOST: redis
REDIS_HOST: redis
OVERLEAF_MONGO_URL: mongodb://mongo/sharelatex
# IMPORTANT: Required for invite token generation
# OVERLEAF_INVITE_TOKEN_SECRET: generate with `openssl rand -base64 32`
# Same property, unfortunately with different names in
# different locations
OVERLEAF_REDIS_HOST: redis
REDIS_HOST: redis
ENABLED_LINKED_FILE_TYPES: "project_file,project_output_file,zotero"
ENABLED_LINKED_FILE_TYPES: 'project_file,project_output_file'
# Enables Thumbnail generation using ImageMagick
ENABLE_CONVERSIONS: "true"
# Enables Thumbnail generation using ImageMagick
ENABLE_CONVERSIONS: 'true'
# Disables email confirmation requirement
EMAIL_CONFIRMATION_DISABLED: "true"
# Disables email confirmation requirement
EMAIL_CONFIRMATION_DISABLED: 'true'
## Set for SSL via nginx-proxy
#VIRTUAL_HOST: 103.112.212.22
## Set for SSL via nginx-proxy
#VIRTUAL_HOST: 103.112.212.22
# OVERLEAF_SITE_URL: http://overleaf.example.com
# OVERLEAF_NAV_TITLE: Overleaf Community Edition
# OVERLEAF_HEADER_IMAGE_URL: http://example.com/mylogo.png
# OVERLEAF_HEADER_IMAGE_URL_LIGHT: http://example.com/mylogo-light.png
# OVERLEAF_HEADER_IMAGE_URL_DARK: http://example.com/mylogo-dark.png
# OVERLEAF_ADMIN_EMAIL: support@it.com
# OVERLEAF_SITE_URL: http://overleaf.example.com
# OVERLEAF_NAV_TITLE: Overleaf Community Edition
# OVERLEAF_HEADER_IMAGE_URL: http://example.com/mylogo.png
# OVERLEAF_ADMIN_EMAIL: support@it.com
# OVERLEAF_LEFT_FOOTER: '[{"text": "Another page I want to link to can be found <a href=\"here\">here</a>"} ]'
# OVERLEAF_RIGHT_FOOTER: '[{"text": "Hello I am on the Right"} ]'
# OVERLEAF_LEFT_FOOTER: '[{"text": "Another page I want to link to can be found <a href=\"here\">here</a>"} ]'
# OVERLEAF_RIGHT_FOOTER: '[{"text": "Hello I am on the Right"} ]'
# OVERLEAF_EMAIL_FROM_ADDRESS: "hello@example.com"
# OVERLEAF_EMAIL_FROM_ADDRESS: "hello@example.com"
# OVERLEAF_EMAIL_AWS_SES_ACCESS_KEY_ID:
# OVERLEAF_EMAIL_AWS_SES_SECRET_KEY:
# OVERLEAF_EMAIL_AWS_SES_ACCESS_KEY_ID:
# OVERLEAF_EMAIL_AWS_SES_SECRET_KEY:
# OVERLEAF_EMAIL_SMTP_HOST: smtp.example.com
# OVERLEAF_EMAIL_SMTP_PORT: 587
# OVERLEAF_EMAIL_SMTP_SECURE: false
# OVERLEAF_EMAIL_SMTP_USER:
# OVERLEAF_EMAIL_SMTP_PASS:
# OVERLEAF_EMAIL_SMTP_TLS_REJECT_UNAUTH: true
# OVERLEAF_EMAIL_SMTP_IGNORE_TLS: false
# OVERLEAF_EMAIL_SMTP_NAME: '127.0.0.1'
# OVERLEAF_EMAIL_SMTP_LOGGER: true
# OVERLEAF_CUSTOM_EMAIL_FOOTER: "This system is run by department x"
# OVERLEAF_EMAIL_SMTP_HOST: smtp.example.com
# OVERLEAF_EMAIL_SMTP_PORT: 587
# OVERLEAF_EMAIL_SMTP_SECURE: false
# OVERLEAF_EMAIL_SMTP_USER:
# OVERLEAF_EMAIL_SMTP_PASS:
# OVERLEAF_EMAIL_SMTP_TLS_REJECT_UNAUTH: true
# OVERLEAF_EMAIL_SMTP_IGNORE_TLS: false
# OVERLEAF_EMAIL_SMTP_NAME: '127.0.0.1'
# OVERLEAF_EMAIL_SMTP_LOGGER: true
# OVERLEAF_CUSTOM_EMAIL_FOOTER: "This system is run by department x"
# ENABLE_CRON_RESOURCE_DELETION: true
# ENABLE_CRON_RESOURCE_DELETION: true
################
## Server Pro ##
################
################
## Server Pro ##
################
## The Community Edition is intended for use in environments where all users are trusted and is not appropriate for
## scenarios where isolation of users is required. Sandboxed Compiles are not available in the Community Edition,
## so the following environment variables must be commented out to avoid compile issues.
##
## Sandboxed Compiles: https://docs.overleaf.com/on-premises/configuration/overleaf-toolkit/server-pro-only-configuration/sandboxed-compiles
SANDBOXED_COMPILES: "true"
### Bind-mount source for /var/lib/overleaf/data/compiles inside the container.
SANDBOXED_COMPILES_HOST_DIR_COMPILES: "/home/user/sharelatex_data/data/compiles"
### Bind-mount source for /var/lib/overleaf/data/output inside the container.
SANDBOXED_COMPILES_HOST_DIR_OUTPUT: "/home/user/sharelatex_data/data/output"
### Backwards compatibility (before Server Pro 5.5)
DOCKER_RUNNER: "true"
SANDBOXED_COMPILES_SIBLING_CONTAINERS: "true"
## The Community Edition is intended for use in environments where all users are trusted and is not appropriate for
## scenarios where isolation of users is required. Sandboxed Compiles are not available in the Community Edition,
## so the following environment variables must be commented out to avoid compile issues.
##
## Sandboxed Compiles: https://docs.overleaf.com/on-premises/configuration/overleaf-toolkit/server-pro-only-configuration/sandboxed-compiles
SANDBOXED_COMPILES: 'true'
### Bind-mount source for /var/lib/overleaf/data/compiles inside the container.
SANDBOXED_COMPILES_HOST_DIR_COMPILES: '/home/user/sharelatex_data/data/compiles'
### Bind-mount source for /var/lib/overleaf/data/output inside the container.
SANDBOXED_COMPILES_HOST_DIR_OUTPUT: '/home/user/sharelatex_data/data/output'
### Backwards compatibility (before Server Pro 5.5)
DOCKER_RUNNER: 'true'
SANDBOXED_COMPILES_SIBLING_CONTAINERS: 'true'
## Works with test LDAP server shown at bottom of docker compose
# OVERLEAF_LDAP_URL: 'ldap://ldap:389'
# OVERLEAF_LDAP_SEARCH_BASE: 'ou=people,dc=planetexpress,dc=com'
# OVERLEAF_LDAP_SEARCH_FILTER: '(uid={{username}})'
# OVERLEAF_LDAP_BIND_DN: 'cn=admin,dc=planetexpress,dc=com'
# OVERLEAF_LDAP_BIND_CREDENTIALS: 'GoodNewsEveryone'
# OVERLEAF_LDAP_EMAIL_ATT: 'mail'
# OVERLEAF_LDAP_NAME_ATT: 'cn'
# OVERLEAF_LDAP_LAST_NAME_ATT: 'sn'
# OVERLEAF_LDAP_UPDATE_USER_DETAILS_ON_LOGIN: 'true'
## Works with test LDAP server shown at bottom of docker compose
# OVERLEAF_LDAP_URL: 'ldap://ldap:389'
# OVERLEAF_LDAP_SEARCH_BASE: 'ou=people,dc=planetexpress,dc=com'
# OVERLEAF_LDAP_SEARCH_FILTER: '(uid={{username}})'
# OVERLEAF_LDAP_BIND_DN: 'cn=admin,dc=planetexpress,dc=com'
# OVERLEAF_LDAP_BIND_CREDENTIALS: 'GoodNewsEveryone'
# OVERLEAF_LDAP_EMAIL_ATT: 'mail'
# OVERLEAF_LDAP_NAME_ATT: 'cn'
# OVERLEAF_LDAP_LAST_NAME_ATT: 'sn'
# OVERLEAF_LDAP_UPDATE_USER_DETAILS_ON_LOGIN: 'true'
# OVERLEAF_TEMPLATES_USER_ID: "578773160210479700917ee5"
# OVERLEAF_NEW_PROJECT_TEMPLATE_LINKS: '[ {"name":"All Templates","url":"/templates/all"}]'
# OVERLEAF_TEMPLATES_USER_ID: "578773160210479700917ee5"
# OVERLEAF_NEW_PROJECT_TEMPLATE_LINKS: '[ {"name":"All Templates","url":"/templates/all"}]'
# OVERLEAF_PROXY_LEARN: "true"
mongo:
restart: always
image: mongo:8.0
container_name: mongo
command: "--replSet overleaf"
volumes:
- ~/mongo_data:/data/db
- ./bin/shared/mongodb-init-replica-set.js:/docker-entrypoint-initdb.d/mongodb-init-replica-set.js
environment:
MONGO_INITDB_DATABASE: sharelatex
extra_hosts:
# Required when using the automatic database setup for initializing the replica set.
# This override is not needed when running the setup after starting up mongo.
- mongo:127.0.0.1
healthcheck:
test: echo 'db.stats().ok' | mongosh localhost:27017/test --quiet
interval: 10s
timeout: 10s
retries: 5
# OVERLEAF_PROXY_LEARN: "true"
redis:
restart: always
image: redis:6.2
container_name: redis
volumes:
- ~/redis_data:/data
mongo:
restart: always
image: mongo:6.0
container_name: mongo
command: '--replSet overleaf'
volumes:
- ~/mongo_data:/data/db
- ./bin/shared/mongodb-init-replica-set.js:/docker-entrypoint-initdb.d/mongodb-init-replica-set.js
environment:
MONGO_INITDB_DATABASE: sharelatex
extra_hosts:
# Required when using the automatic database setup for initializing the replica set.
# This override is not needed when running the setup after starting up mongo.
- mongo:127.0.0.1
healthcheck:
test: echo 'db.stats().ok' | mongosh localhost:27017/test --quiet
interval: 10s
timeout: 10s
retries: 5
# ldap:
# restart: always
# image: rroemhild/test-openldap
# container_name: ldap
redis:
restart: always
image: redis:6.2
container_name: redis
volumes:
- ~/redis_data:/data
# See https://github.com/jwilder/nginx-proxy for documentation on how to configure the nginx-proxy container,
# and https://github.com/overleaf/overleaf/wiki/HTTPS-reverse-proxy-using-Nginx for an example of some recommended
# settings. We recommend using a properly managed nginx instance outside of the Overleaf Server Pro setup,
# but the example here can be used if you'd prefer to run everything with docker-compose
# ldap:
# restart: always
# image: rroemhild/test-openldap
# container_name: ldap
# nginx-proxy:
# image: jwilder/nginx-proxy
# container_name: nginx-proxy
# ports:
# - "80:80"
# - "443:443"
# volumes:
# - /var/run/docker.sock:/tmp/docker.sock:ro
# - /home/overleaf/tmp:/etc/nginx/certs
# See https://github.com/jwilder/nginx-proxy for documentation on how to configure the nginx-proxy container,
# and https://github.com/overleaf/overleaf/wiki/HTTPS-reverse-proxy-using-Nginx for an example of some recommended
# settings. We recommend using a properly managed nginx instance outside of the Overleaf Server Pro setup,
# but the example here can be used if you'd prefer to run everything with docker-compose
# nginx-proxy:
# image: jwilder/nginx-proxy
# container_name: nginx-proxy
# ports:
# - "80:80"
# - "443:443"
# volumes:
# - /var/run/docker.sock:/tmp/docker.sock:ro
# - /home/overleaf/tmp:/etc/nginx/certs
@@ -1,7 +1,7 @@
let reporterOptions = {}
if (process.env.CI) {
reporterOptions = {
reporter: require.resolve('mocha-multi-reporters'),
reporter: '/overleaf/node_modules/mocha-multi-reporters',
'reporter-options': ['configFile=./test/mocha-multi-reporters.cjs'],
}
}
+1
View File
@@ -0,0 +1 @@
22.18.0
@@ -0,0 +1,9 @@
access-token-encryptor
--dependencies=None
--env-add=
--env-pass-through=
--esmock-loader=False
--is-library=True
--node-version=22.18.0
--pipeline-owner=🚉 Platform
--public-repo=False
+7 -11
View File
@@ -3,28 +3,24 @@
"version": "3.0.0",
"description": "",
"main": "index.js",
"exports": {
".": "./index.js",
"./*": "./*"
},
"scripts": {
"test": "yarn run lint && yarn run types:check && yarn run test:unit",
"lint": "eslint --cache --cache-location ../../.cache/eslint/ --ext .cjs,.js,.jsx,.mjs,.ts --max-warnings 0 .",
"lint:fix": "eslint --cache --cache-location ../../.cache/eslint/ --fix --ext .cjs,.js,.jsx,.mjs,.ts .",
"test:ci": "yarn run test:unit",
"test": "npm run lint && npm run format && npm run types:check && npm run test:unit",
"lint": "eslint --ext .cjs,.js,.jsx,.mjs,.ts --max-warnings 0 --format unix .",
"lint:fix": "eslint --fix --ext .cjs,.js,.jsx,.mjs,.ts .",
"format": "prettier --list-different $PWD/'**/*.{js,cjs,ts}'",
"format:fix": "prettier --write $PWD/'**/*.{js,cjs,ts}'",
"test:ci": "npm run test:unit",
"test:unit": "mocha --exit test/**/*.{js,cjs}",
"types:check": "tsc --noEmit"
},
"author": "",
"license": "AGPL-3.0-only",
"dependencies": {
"lodash": "^4.18.1"
"lodash": "^4.17.21"
},
"devDependencies": {
"@types/node": "^24.5.2",
"chai": "^4.3.6",
"chai-as-promised": "^7.1.1",
"eslint": "^10.4.0",
"mocha": "^11.1.0",
"mocha-junit-reporter": "^2.2.1",
"mocha-multi-reporters": "^1.5.1",
@@ -1,7 +1,7 @@
module.exports = {
reporterEnabled: 'spec, mocha-junit-reporter',
mochaJunitReporterReporterOptions: {
mochaFile: `reports/junit-mocha-${process.env.TEST_NAME_PATTERN}.xml`,
mochaFile: `reports/junit-mocha-${process.env.MOCHA_GREP}.xml`,
includePending: true,
jenkinsMode: true,
output: true,
@@ -1,4 +1,8 @@
{
"extends": "../../tsconfig.backend.json",
"include": ["**/*.js", "**/*.cjs", "**/*.ts"]
"include": [
"**/*.js",
"**/*.cjs",
"**/*.ts"
]
}
-76
View File
@@ -1,76 +0,0 @@
'use strict'
/**
* cypress-multi-reporters, loadable from inside Cypress.
*
* Cypress builds mocha reporters in its Electron process. That process resolves
* modules through PackherdModuleLoader and does not inherit NODE_OPTIONS, so
* Yarn PnP is not installed there and `require('cypress-multi-reporters')`
* fails with "Cannot find module".
*
* Installing PnP for the rest of that process is not an option either: Cypress
* asks packherd for its own bundled modules under ids like
* `packages/server/lib/browsers/`, which PnP reads as paths inside this
* workspace and then rejects ("it isn't declared in your dependencies"),
* breaking the browser launch.
*
* So install PnP, pull the reporters in through it, and hand resolution back to
* Cypress. Requires made by the modules that came in through PnP keep going
* through PnP, so anything they load later still resolves.
*
* Point Cypress at this package rather than at cypress-multi-reporters:
*
* reporter: require.resolve('@overleaf/cypress-pnp-reporter')
*/
const Module = require('node:module')
const path = require('node:path')
function loadReporters() {
const MultiReporters = require('cypress-multi-reporters')
// MultiReporters resolves the reporters named in reporterEnabled when a run
// starts, long after PnP is gone. It reads mocha's own registry before
// falling back to require(), so register mocha-junit-reporter there while it
// can still be found.
require('mocha').reporters[
'mocha-junit-reporter'
] = require('mocha-junit-reporter')
return MultiReporters
}
if (process.versions.pnp) {
module.exports = loadReporters()
} else {
const stockLoad = Module._load
const stockResolveFilename = Module._resolveFilename
const stockFindPath = Module._findPath
require(path.join(__dirname, '..', '..', '.pnp.cjs')).setup()
const pnpResolveFilename = Module._resolveFilename
const cachedBefore = new Set(Object.keys(Module._cache))
const loadedViaPnp = new Set()
try {
module.exports = loadReporters()
} finally {
for (const filename of Object.keys(Module._cache)) {
if (!cachedBefore.has(filename)) loadedViaPnp.add(filename)
}
// Leave the patched fs in place: the reporters live in zip archives, so
// anything they read lazily still has to go through it.
Module._load = stockLoad
Module._findPath = stockFindPath
Module._resolveFilename = function (request, parent, ...args) {
if (!parent || !loadedViaPnp.has(parent.filename)) {
return stockResolveFilename.call(this, request, parent, ...args)
}
const filename = pnpResolveFilename.call(this, request, parent, ...args)
loadedViaPnp.add(filename)
return filename
}
}
}
@@ -1,30 +0,0 @@
{
"name": "@overleaf/cypress-pnp-reporter",
"description": "cypress-multi-reporters, loadable from Cypress's Electron process, which has no Yarn PnP",
"main": "index.cjs",
"files": [
"index.cjs"
],
"author": "Overleaf (https://www.overleaf.com)",
"private": true,
"scripts": {
"lint": "eslint --cache --cache-location ../../.cache/eslint/ --ext .cjs,.js,.jsx,.mjs,.ts --max-warnings 0 .",
"lint:fix": "eslint --cache --cache-location ../../.cache/eslint/ --fix --ext .cjs,.js,.jsx,.mjs,.ts .",
"test": "yarn run lint && yarn run types:check && yarn run test:unit",
"test:ci": "yarn run test:unit",
"test:unit": "mocha --exit test/**/*.{js,cjs}",
"types:check": "tsc --noEmit"
},
"dependencies": {
"cypress-multi-reporters": "^2.0.5"
},
"devDependencies": {
"@types/node": "^24.5.2",
"chai": "^4.3.6",
"eslint": "^10.4.0",
"mocha": "^11.1.0",
"mocha-junit-reporter": "^2.2.1",
"mocha-multi-reporters": "^1.5.1",
"typescript": "^5.0.4"
}
}
@@ -1 +0,0 @@
// no setup yet
@@ -1,52 +0,0 @@
'use strict'
const { expect } = require('chai')
const Mocha = require('mocha')
const JUnitReporter = require('mocha-junit-reporter')
const MultiReporters = require('../../index.cjs')
function buildReporters(reporterEnabled) {
const runner = new Mocha.Runner(new Mocha.Suite(''))
const reporter = new MultiReporters(runner, {
reporterOptions: { reporterEnabled },
})
return reporter._reporters
}
describe('cypress-pnp-reporter', function () {
it('exports cypress-multi-reporters', function () {
expect(MultiReporters).to.equal(require('cypress-multi-reporters'))
})
it('registers mocha-junit-reporter on mocha', function () {
expect(Mocha.reporters['mocha-junit-reporter']).to.equal(JUnitReporter)
})
it('builds the reporters used across the Cypress suites', function () {
const reporters = buildReporters('spec, mocha-junit-reporter')
expect(reporters).to.have.length(2)
expect(reporters[0]).to.be.an.instanceOf(Mocha.reporters.spec)
expect(reporters[1]).to.be.an.instanceOf(JUnitReporter)
})
it('prefers the reporter registered on mocha over resolving it by name', function () {
// Cypress builds the reporters after the shim has handed module resolution
// back, so mocha's registry is the only place mocha-junit-reporter can
// still be found. Everything above this still passes if
// cypress-multi-reporters resolves it by name instead, so pin the lookup
// order with a reporter that is only reachable through the registry.
class Sentinel {}
const registered = Mocha.reporters['mocha-junit-reporter']
Mocha.reporters['mocha-junit-reporter'] = Sentinel
try {
expect(buildReporters('mocha-junit-reporter')[0]).to.be.an.instanceOf(
Sentinel
)
} finally {
Mocha.reporters['mocha-junit-reporter'] = registered
}
})
})
@@ -1,4 +0,0 @@
{
"extends": "../../tsconfig.backend.json",
"include": ["**/*.js", "**/*.cjs", "**/*.ts"]
}
@@ -1,160 +0,0 @@
// French typographic spacing rules for JSON string values.
// Per https://typographisme.net/post/Les-espaces-typographiques-et-le-web
// - NNBSP before ? ! ;
// - NBSP before :
// - NBSP inside guillemets (after «, before ») — keeps the
// guillemet attached to its content so it cannot be orphaned at a
// line break
// - NNBSP between digit groups (thousands separator)
// - NBSP between a number and a following word/unit (50 Mo, 5 jours)
// - NBSP before %
// - point médian "·" instead of parenthetical (e) for inclusive writing
const NBSP = ' '
const NNBSP = ' '
function autoFix(value) {
let v = value
// Normalize whitespace before ? ! ; to NNBSP
v = v.replace(/\s*([?!;])/g, `${NNBSP}$1`)
v = v.replace(/([^\s])([?!;])/g, `$1${NNBSP}$2`)
// Normalize whitespace before : (after a letter, not before /) to NBSP
v = v.replace(/(\p{L})\s*:(?!\/)/gu, `$1${NBSP}:`)
// NBSP after «
v = v.replace(/«\s*/g, `«${NBSP}`)
// NBSP before »
v = v.replace(/\s*»/g, `${NBSP}»`)
// NNBSP between digits (thousands separator)
v = v.replace(/(\d)\s+(\d)/g, `$1${NNBSP}$2`)
// NBSP between digit and following letter (number + unit/word)
v = v.replace(/(\d)\s+(\p{L})/gu, `$1${NBSP}$2`)
// NBSP before %
v = v.replace(/(\d)\s*%/g, `$1${NBSP}%`)
return v
}
function lint(value) {
const violations = []
for (const m of value.matchAll(/(.)([?!;])/g)) {
if (m[1] !== NNBSP) {
violations.push({
message: `expected NNBSP before "${m[2]}", got ${JSON.stringify(m[1])}`,
fixable: true,
})
}
}
for (const m of value.matchAll(/(\p{L})(\s*):(?!\/)/gu)) {
if (m[2] !== NBSP) {
violations.push({
message: `expected NBSP before ":" after letter ${JSON.stringify(m[1])}, got ${JSON.stringify(m[2])}`,
fixable: true,
})
}
}
for (const m of value.matchAll(/«(.)/g)) {
if (m[1] !== NBSP) {
violations.push({
message: `expected NBSP after "«", got ${JSON.stringify(m[1])}`,
fixable: true,
})
}
}
for (const m of value.matchAll(/(.)»/g)) {
if (m[1] !== NBSP) {
violations.push({
message: `expected NBSP before "»", got ${JSON.stringify(m[1])}`,
fixable: true,
})
}
}
for (const m of value.matchAll(/(\d)(\s)(\d)/g)) {
if (m[2] !== NNBSP) {
violations.push({
message: `expected NNBSP between digits "${m[1]}${m[3]}", got ${JSON.stringify(m[2])}`,
fixable: true,
})
}
}
for (const m of value.matchAll(/(\d)(\s)(\p{L})/gu)) {
if (m[2] !== NBSP) {
violations.push({
message: `expected NBSP between digit "${m[1]}" and "${m[3]}", got ${JSON.stringify(m[2])}`,
fixable: true,
})
}
}
for (const m of value.matchAll(/(\d)(\s*)%/g)) {
if (m[2] !== NBSP) {
violations.push({
message: `expected NBSP before "%" after "${m[1]}", got ${JSON.stringify(m[2])}`,
fixable: true,
})
}
}
if (value.includes('(e)')) {
violations.push({
message:
'expected point médian "·" instead of "(e)" for inclusive writing',
fixable: false, // suggestion-only
})
}
return violations
}
module.exports = {
meta: {
type: 'problem',
fixable: 'code',
hasSuggestions: true,
docs: {
description:
'Enforce French typographic spacing in JSON string values (NNBSP before ? ! ;, NBSP before : and inside « », etc.).',
},
schema: [],
},
create(context) {
return {
Member(node) {
if (node.value.type !== 'String') return
const original = node.value.value
const violations = lint(original)
if (violations.length === 0) return
const fixed = autoFix(original)
const replacement = JSON.stringify(fixed)
const inclusiveSuggestion = original.includes('(e)')
? JSON.stringify(original.replace(/\(e\)/g, '·e'))
: null
for (const v of violations) {
context.report({
node: node.value,
message: v.message,
...(v.fixable && fixed !== original
? {
fix(fixer) {
return fixer.replaceText(node.value, replacement)
},
}
: {}),
...(!v.fixable && inclusiveSuggestion
? {
suggest: [
{
desc: 'Replace "(e)" with "·e"',
fix(fixer) {
return fixer.replaceText(
node.value,
inclusiveSuggestion
)
},
},
],
}
: {}),
})
}
},
}
},
}
-17
View File
@@ -1,10 +1,4 @@
const pkg = require('./package.json')
module.exports = {
meta: {
name: pkg.name,
version: pkg.version,
},
rules: {
'no-unnecessary-trans': require('./no-unnecessary-trans'),
'prefer-kebab-url': require('./prefer-kebab-url'),
@@ -13,16 +7,5 @@ module.exports = {
'require-script-runner': require('./require-script-runner'),
'require-vi-doMock-valid-path': require('./require-vi-doMock-valid-path'),
'require-loading-label': require('./require-loading-label'),
'require-rel-for-docs-links': require('./require-rel-for-docs-links'),
'require-cio-snake-case-properties': require('./require-cio-snake-case-properties'),
'no-throw-in-callback': require('./no-throw-in-callback'),
'no-raw-req-access': require('./no-raw-req-access'),
'no-consecutive-spaces-in-locales': require('./no-consecutive-spaces-in-locales'),
'no-straight-apostrophes-in-locales': require('./no-straight-apostrophes-in-locales'),
'french-typography-in-locales': require('./french-typography-in-locales'),
'sorted-keys-in-locales': require('./sorted-keys-in-locales'),
'locale-variables-match-en': require('./locale-variables-match-en'),
'no-orphan-locale-keys': require('./no-orphan-locale-keys'),
'no-mocha-before': require('./no-mocha-before'),
},
}
@@ -1,93 +0,0 @@
// Ensure variable placeholders (`__name__`) in non-en locale values match
// those in the corresponding en.json key.
//
// Apply this rule to all non-en locale JSON files.
const fs = require('node:fs')
const Path = require('node:path')
// Placeholders always available in translations (injected by the i18n layer
// or globally defined as defaults).
const GLOBALS = new Set(['__appName__'])
// Keys whose translations are allowed to omit specific base placeholders.
const IGNORE_NESTING_FOR = {
over_x_templates_easy_getting_started: ['__templates__'],
all_packages_and_templates: ['__templatesLink__'],
}
function extractPlaceholders(str) {
return Array.from(str.matchAll(/__.*?__/g), m => m[0])
}
const enCache = new Map()
function loadEn(localesDir) {
if (enCache.has(localesDir)) return enCache.get(localesDir)
const path = Path.join(localesDir, 'en.json')
const data = JSON.parse(fs.readFileSync(path, 'utf8'))
enCache.set(localesDir, data)
return data
}
module.exports = {
meta: {
type: 'problem',
docs: {
description:
'Ensure variable placeholders in non-en locale values match the en.json base.',
},
schema: [],
messages: {
missing:
'Translation for key "{{key}}" is missing placeholder(s) {{placeholders}} present in en.json.',
extra:
'Translation for key "{{key}}" has placeholder(s) {{placeholders}} not present in en.json.',
},
},
create(context) {
const filename = context.filename
const localesDir = Path.dirname(filename)
if (Path.basename(filename) === 'en.json') return {}
let base
try {
base = loadEn(localesDir)
} catch {
return {}
}
return {
Member(node) {
if (node.value.type !== 'String') return
const key = node.name.value
if (!(key in base)) return // orphan key — covered by no-orphan-locale-keys
const basePlaceholders = extractPlaceholders(base[key])
const targetPlaceholders = extractPlaceholders(node.value.value)
const ignored = IGNORE_NESTING_FOR[key] || []
const missing = basePlaceholders.filter(
p => !targetPlaceholders.includes(p) && !ignored.includes(p)
)
const extra = targetPlaceholders.filter(
p => !basePlaceholders.includes(p) && !GLOBALS.has(p)
)
if (missing.length > 0) {
context.report({
node: node.value,
messageId: 'missing',
data: { key, placeholders: missing.join(', ') },
})
}
if (extra.length > 0) {
context.report({
node: node.value,
messageId: 'extra',
data: { key, placeholders: extra.join(', ') },
})
}
},
}
},
}
@@ -1,37 +0,0 @@
// Reject runs of two or more consecutive whitespace characters in JSON string
// values. Catches ASCII spaces, NBSP, NNBSP, tabs, and other Unicode whitespace.
const CONSECUTIVE_WHITESPACE = /\s{2,}/
module.exports = {
meta: {
type: 'problem',
fixable: 'code',
docs: {
description:
'Disallow runs of two or more consecutive whitespace characters in JSON string values (typically locale files).',
},
schema: [],
messages: {
consecutiveSpaces:
'Locale value contains a run of consecutive whitespace. Collapse to a single space.',
},
},
create(context) {
return {
Member(node) {
if (node.value.type !== 'String') return
const original = node.value.value
if (!CONSECUTIVE_WHITESPACE.test(original)) return
const fixed = original.replace(/\s{2,}/g, ' ')
context.report({
node: node.value,
messageId: 'consecutiveSpaces',
fix(fixer) {
return fixer.replaceText(node.value, JSON.stringify(fixed))
},
})
},
}
},
}
-112
View File
@@ -1,112 +0,0 @@
const Path = require('node:path')
/**
* Block bare mocha `before()` hooks in Cypress e2e suites.
*
* `before()` hooks run once per suite and do NOT re-run when a test retries,
* while `beforeEach`-based hooks (like `beforeWithReRunOnTestRetry`) do.
* Mixing the two also changes ordering: all `before()` hooks run ahead of
* every `beforeEach`, not in source order. This matters in the Server Pro
* e2e suite, where suites change the server config via `startWith()` while
* test setup runs in `beforeWithReRunOnTestRetry()`: when a later suite
* changes the config, both must re-run on retry and in registration order,
* otherwise a retried test runs against setup or config belonging to a
* different suite.
*
* The autofix rewrites `before(fn)` to `beforeWithReRunOnTestRetry(fn)` and
* adds the helper import when missing. Configure the helper location (repo
* root relative, no extension) via the `helperPath` option.
*/
module.exports = {
meta: {
type: 'suggestion',
docs: {
description:
'Disallow mocha before() hooks in favor of beforeWithReRunOnTestRetry()',
},
fixable: 'code',
schema: [
{
type: 'object',
properties: {
helperPath: { type: 'string' },
},
additionalProperties: false,
},
],
messages: {
noMochaBefore:
'before() hooks do not re-run when a test retries, so retried tests run against stale setup. Use beforeWithReRunOnTestRetry() instead.',
},
},
create(context) {
const helperPath = context.options[0]?.helperPath
let lastImport = null
let hasHelperImport = false
function helperImportSpecifier() {
const absolute = Path.resolve(context.cwd, helperPath)
let relative = Path.relative(
Path.dirname(Path.resolve(context.cwd, context.filename)),
absolute
)
relative = relative.split(Path.sep).join('/')
if (!relative.startsWith('.')) {
relative = `./${relative}`
}
return relative
}
return {
ImportDeclaration(node) {
lastImport = node
if (
node.specifiers.some(
specifier =>
specifier.type === 'ImportSpecifier' &&
specifier.imported.name === 'beforeWithReRunOnTestRetry'
)
) {
hasHelperImport = true
}
},
CallExpression(node) {
if (
node.callee.type !== 'Identifier' ||
node.callee.name !== 'before'
) {
return
}
// Only the global mocha hook; skip locally defined/imported `before`
const variable = context.sourceCode
.getScope(node)
.references.find(ref => ref.identifier === node.callee)?.resolved
if (variable && variable.defs.length > 0) {
return
}
const fixable = node.arguments.length === 1 && helperPath
context.report({
node: node.callee,
messageId: 'noMochaBefore',
fix: fixable
? fixer => {
const fixes = [
fixer.replaceText(node.callee, 'beforeWithReRunOnTestRetry'),
]
if (!hasHelperImport) {
const importText = `import { beforeWithReRunOnTestRetry } from '${helperImportSpecifier()}'`
fixes.push(
lastImport
? fixer.insertTextAfter(lastImport, `\n${importText}`)
: fixer.insertTextBeforeRange([0, 0], `${importText}\n`)
)
}
return fixes
}
: undefined,
})
},
}
},
}
@@ -1,69 +0,0 @@
// Detect translation keys in non-en locale files that don't exist in
// en.json (orphans).
const fs = require('node:fs')
const Path = require('node:path')
const enCache = new Map()
function loadEnKeys(localesDir) {
if (enCache.has(localesDir)) return enCache.get(localesDir)
const path = Path.join(localesDir, 'en.json')
const data = JSON.parse(fs.readFileSync(path, 'utf8'))
const keys = new Set(Object.keys(data))
enCache.set(localesDir, keys)
return keys
}
module.exports = {
meta: {
type: 'problem',
fixable: 'code',
docs: {
description:
'Detect translation keys in non-en locale files that are not present in en.json.',
},
schema: [],
messages: {
orphan:
'Translation key "{{key}}" is not present in en.json (orphan key).',
},
},
create(context) {
const filename = context.filename
const localesDir = Path.dirname(filename)
if (Path.basename(filename) === 'en.json') return {}
let enKeys
try {
enKeys = loadEnKeys(localesDir)
} catch {
return {}
}
return {
'Document > Object'(node) {
const orphans = node.members.filter(m => !enKeys.has(m.name.value))
if (orphans.length === 0) return
const text = context.sourceCode.text
const parsed = JSON.parse(text)
for (const member of orphans) {
delete parsed[member.name.value]
}
const sortedRemaining = Object.keys(parsed).sort()
const cleaned = JSON.stringify(parsed, sortedRemaining, 2) + '\n'
for (const member of orphans) {
context.report({
node: member,
messageId: 'orphan',
data: { key: member.name.value },
fix(fixer) {
return fixer.replaceTextRange([0, text.length], cleaned)
},
})
}
},
}
},
}
@@ -1,64 +0,0 @@
const RAW_FIELDS = new Set(['body', 'query', 'params'])
function isReqIdentifier(node) {
return node && node.type === 'Identifier' && node.name === 'req'
}
module.exports = {
meta: {
type: 'problem',
docs: {
description:
'Disallow reading raw request input (req.body/req.query/req.params); validate it with parseReq() instead',
},
messages: {
noRawReqAccess:
'Do not read req.{{field}} directly; validate request input with parseReq() from @overleaf/validation-tools. Allowlisted infrastructure middleware may use getRawReqInput().',
},
},
create(context) {
return {
MemberExpression(node) {
if (!isReqIdentifier(node.object)) return
const property = node.property
const field =
!node.computed && property.type === 'Identifier'
? property.name
: node.computed &&
property.type === 'Literal' &&
typeof property.value === 'string'
? property.value
: null
if (field === null || !RAW_FIELDS.has(field)) return
// writes stay allowed: body parsers and middleware assign req.body
const parent = node.parent
if (
parent.type === 'AssignmentExpression' &&
parent.left === node &&
parent.operator === '='
) {
return
}
context.report({ node, messageId: 'noRawReqAccess', data: { field } })
},
VariableDeclarator(node) {
if (!isReqIdentifier(node.init)) return
if (node.id.type !== 'ObjectPattern') return
for (const prop of node.id.properties) {
if (
prop.type === 'Property' &&
!prop.computed &&
prop.key.type === 'Identifier' &&
RAW_FIELDS.has(prop.key.name)
) {
context.report({
node: prop,
messageId: 'noRawReqAccess',
data: { field: prop.key.name },
})
}
}
},
}
},
}
@@ -1,36 +0,0 @@
// Reject straight apostrophes (') in JSON string values. Straight apostrophes
// in Angular templates can lead to XSS; use the right single quotation mark
// ’ (U+2019) instead. See https://github.com/overleaf/issues/issues/4478
module.exports = {
meta: {
type: 'problem',
fixable: 'code',
docs: {
description:
'Disallow straight apostrophes in JSON string values (typically locale files).',
},
schema: [],
messages: {
straightApostrophe:
"Locale value contains a straight apostrophe ('). Use the right single quotation mark ’ (U+2019) instead.",
},
},
create(context) {
return {
Member(node) {
if (node.value.type !== 'String') return
const original = node.value.value
if (!original.includes("'")) return
const fixed = original.replace(/'/g, '’')
context.report({
node: node.value,
messageId: 'straightApostrophe',
fix(fixer) {
return fixer.replaceText(node.value, JSON.stringify(fixed))
},
})
},
}
},
}
@@ -1,52 +0,0 @@
const CALLBACK_PARAM_NAMES = new Set(['cb', 'callback', 'done', 'next'])
function isCallbackParam(param) {
return (
param && param.type === 'Identifier' && CALLBACK_PARAM_NAMES.has(param.name)
)
}
module.exports = {
meta: {
type: 'error',
docs: {
description: 'Disallow throw statements inside callback-based functions',
},
messages: {
noThrowInCallback:
'Pass the error to the callback instead of throwing in callback-based code.',
},
},
create(context) {
// Stack tracks whether each enclosing function is a callback-style function.
// A callback-style function is non-async and has a last param named cb/callback/done/next.
const stack = []
function enterFunction(node) {
const params = node.params
const isCallback =
!node.async &&
params.length > 0 &&
isCallbackParam(params[params.length - 1])
stack.push(isCallback)
}
function exitFunction() {
stack.pop()
}
return {
FunctionDeclaration: enterFunction,
'FunctionDeclaration:exit': exitFunction,
FunctionExpression: enterFunction,
'FunctionExpression:exit': exitFunction,
ArrowFunctionExpression: enterFunction,
'ArrowFunctionExpression:exit': exitFunction,
ThrowStatement(node) {
if (stack[stack.length - 1]) {
context.report({ node, messageId: 'noThrowInCallback' })
}
},
}
},
}
+4 -13
View File
@@ -5,22 +5,13 @@
"license": "AGPL-3.0-only",
"main": "index.js",
"dependencies": {
"lodash": "^4.18.1"
"eslint": "^8.51.0",
"lodash": "^4.17.21"
},
"devDependencies": {
"@eslint/json": "^2.0.0",
"@types/node": "^24.5.2",
"@typescript-eslint/parser": "^8.59.4",
"eslint": "^10.4.0",
"typescript": "^5.0.4",
"vitest": "4.1.5"
"@typescript-eslint/parser": "^8.50.0"
},
"scripts": {
"test": "yarn run lint && yarn run types:check && yarn run test:unit",
"lint": "eslint --cache --cache-location ../../.cache/eslint/ --ext .cjs,.js,.jsx,.mjs,.ts --max-warnings 0 .",
"lint:fix": "eslint --cache --cache-location ../../.cache/eslint/ --fix --ext .cjs,.js,.jsx,.mjs,.ts .",
"test:ci": "yarn run test:unit",
"test:unit": "vitest --config vitest.config.ts",
"types:check": "tsc --noEmit"
"test": "node rules.test.js"
}
}
@@ -49,7 +49,6 @@ const ignoreWords = {
camel: new Set([
'addWorkflowScope',
'aiErrorAssistant',
'aiFeatureUsage',
'beginAuth',
'brandVariationId',
'closeEditor',
@@ -71,7 +70,6 @@ const ignoreWords = {
'resendManagedUserInvite',
'salesContactForm',
'showSupport',
'uniExternalCollaboration',
]),
other: new Set([
'Project',
+4 -2
View File
@@ -29,7 +29,7 @@ const getSuggestion = routePath => {
if (routePath instanceof RegExp) {
const words = removeTextBetweenBrackets(routePath.source).match(/[\w-]+/g)
if (!words) return null
if (!words) return routePath
let newSource = routePath.source
for (const word of words) {
@@ -42,7 +42,9 @@ const getSuggestion = routePath => {
}
const kebabed = new RegExp(newSource, routePath.flags)
return kebabed.source === routePath.source ? null : kebabed.toString()
return kebabed.source.toString() === routePath.source.toString()
? null
: kebabed
}
}
@@ -1,111 +0,0 @@
'use strict'
const SNAKE_CASE_RE = /^[a-z][a-z0-9]*(_[a-z0-9]+)*$/
function isSnakeCase(name) {
return SNAKE_CASE_RE.test(name)
}
function getStaticKeyName(property) {
if (property.computed) return null
if (property.key.type === 'Identifier') return property.key.name
if (property.key.type === 'Literal' && typeof property.key.value === 'string')
return property.key.value
return null
}
/**
* Check if a node is a call to CustomerIoHandler.updateUserAttributes()
* and return the attributes argument (2nd argument)
*/
function getUpdateUserAttributesArg(node) {
if (
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'Identifier' &&
node.callee.object.name === 'CustomerIoHandler' &&
node.callee.property.name === 'updateUserAttributes' &&
node.arguments[1]?.type === 'ObjectExpression'
) {
return node.arguments[1]
}
return null
}
/**
* Check if a node is a call to Modules[.promises].hooks.fire('setUserProperties', ...)
* and return the attributes argument (3rd argument)
*/
function getSetUserPropertiesArg(node) {
const callee = node.callee
if (callee.type !== 'MemberExpression' || callee.property.name !== 'fire') {
return null
}
// Check first argument is 'setUserProperties'
if (
!node.arguments[0] ||
node.arguments[0].type !== 'Literal' ||
node.arguments[0].value !== 'setUserProperties'
) {
return null
}
// Match: Modules.hooks.fire or Modules.promises.hooks.fire
const obj = callee.object
if (obj.type === 'MemberExpression' && obj.property.name === 'hooks') {
const parent = obj.object
// Modules.hooks
if (parent.type === 'Identifier' && parent.name === 'Modules') {
if (node.arguments[2]?.type === 'ObjectExpression') {
return node.arguments[2]
}
}
// Modules.promises.hooks
if (
parent.type === 'MemberExpression' &&
parent.property.name === 'promises' &&
parent.object.type === 'Identifier' &&
parent.object.name === 'Modules'
) {
if (node.arguments[2]?.type === 'ObjectExpression') {
return node.arguments[2]
}
}
}
return null
}
module.exports = {
meta: {
type: 'problem',
docs: {
description:
'Enforce snake_case for Customer.io user property attribute names',
},
},
create(context) {
return {
CallExpression(node) {
const attrsNode =
getUpdateUserAttributesArg(node) || getSetUserPropertiesArg(node)
if (!attrsNode) return
for (const property of attrsNode.properties) {
if (property.type === 'SpreadElement') continue
const keyName = getStaticKeyName(property)
if (keyName === null) continue // skip computed/dynamic keys
if (!isSnakeCase(keyName)) {
context.report({
node: property.key,
message: `Customer.io attribute '{{name}}' must be in snake_case.`,
data: { name: keyName },
})
}
}
},
}
},
}
@@ -1,87 +0,0 @@
const DOCS_HOST = 'docs.overleaf.com'
const REQUIRED_REL_TOKENS = ['noopener', 'noreferrer']
// Elements that forward href/target/rel straight onto a rendered <a>.
const LINK_ELEMENT_NAMES = ['a', 'OLButton']
function getStringLiteralValue(node) {
if (!node) return undefined
if (node.type === 'Literal' && typeof node.value === 'string') {
return node.value
}
if (
node.type === 'JSXExpressionContainer' &&
node.expression.type === 'Literal' &&
typeof node.expression.value === 'string'
) {
return node.expression.value
}
return undefined
}
module.exports = {
meta: {
type: 'problem',
fixable: 'code',
docs: {
description:
'Require rel="noopener noreferrer" on links to docs.overleaf.com that open in a new tab, to prevent reverse-tabnabbing',
},
schema: [],
},
create(context) {
const selector = `JSXOpeningElement[name.name=/^(${LINK_ELEMENT_NAMES.join('|')})$/]`
return {
[selector](node) {
const attributes = new Map(
node.attributes
.filter(attr => attr.type === 'JSXAttribute')
.map(attr => [attr.name.name, attr])
)
const hrefAttr = attributes.get('href')
const href = getStringLiteralValue(hrefAttr?.value)
if (!href || !href.includes(DOCS_HOST)) {
return
}
const targetAttr = attributes.get('target')
const target = getStringLiteralValue(targetAttr?.value)
if (!target || target.toLowerCase() !== '_blank') {
return
}
const relAttr = attributes.get('rel')
const rel = getStringLiteralValue(relAttr?.value) || ''
const relTokens = rel.toLowerCase().split(/\s+/).filter(Boolean)
const missingTokens = REQUIRED_REL_TOKENS.filter(
token => !relTokens.includes(token)
)
if (missingTokens.length === 0) {
return
}
context.report({
node: relAttr || node,
message:
'Links to docs.overleaf.com with target="_blank" must have rel="noopener noreferrer" to prevent reverse-tabnabbing.',
fix(fixer) {
const newRel = Array.from(
new Set([...relTokens, ...REQUIRED_REL_TOKENS])
).join(' ')
if (relAttr) {
if (!relAttr.value) {
return fixer.replaceText(relAttr, `rel="${newRel}"`)
}
return fixer.replaceText(relAttr.value, `"${newRel}"`)
}
return fixer.insertTextAfter(targetAttr, ` rel="${newRel}"`)
},
})
},
}
},
}
@@ -22,7 +22,7 @@ module.exports = {
},
},
create(context) {
const currentFilePath = context.filename
const currentFilePath = context.getFilename()
// ESLint can sometimes pass <text> or <input> for snippets not in a file
if (currentFilePath === '<text>' || currentFilePath === '<input>') {
return {}
@@ -81,10 +81,9 @@ module.exports = {
typeof firstArg.value !== 'string'
) {
if (firstArg.type === 'Identifier') {
const scope = context.sourceCode.getScope(node)
const variable = scope.variables.find(
v => v.name === firstArg.name
)
const variable = context
.getScope()
.variables.find(v => v.name === firstArg.name)
if (
variable &&
variable.defs.length > 0 &&
+168
View File
@@ -0,0 +1,168 @@
const { RuleTester } = require('eslint')
const preferKebabUrl = require('./prefer-kebab-url')
const noUnnecessaryTrans = require('./no-unnecessary-trans')
const shouldUnescapeTrans = require('./should-unescape-trans')
const noGeneratedEditorThemes = require('./no-generated-editor-themes')
const viDoMockValidPath = require('./require-vi-doMock-valid-path')
const ruleTester = new RuleTester({
parser: require.resolve('@typescript-eslint/parser'),
parserOptions: {
ecmaVersion: 'latest',
ecmaFeatures: { jsx: true },
},
})
ruleTester.run('prefer-kebab-url', preferKebabUrl, {
valid: [
{ code: `app.get('/foo-bar')` },
{ code: `app.get('/foo-bar/:id')` },
{ code: `router.post('/foo-bar')` },
{ code: `router.get('/foo-bar/:id/:name/:age')` },
{ code: `webRouter.get('/foo-bar/:user_id/(ProjectName)/get-info')` },
{ code: `webApp.post('/foo-bar/:user_id/(ProjectName)/get-info')` },
{
code: `router.get(/^\\/download\\/project\\/([^/]*)\\/output\\/output\\.pdf$/)`,
},
{
code: `webRouter.get(/^\\/project\\/([^/]*)\\/user\\/([0-9a-f]+)\\/build\\/([0-9a-f-]+)\\/output\\/(.*)$/)`,
},
],
invalid: [
{
code: `app.get('/fooBar')`,
errors: [{ message: 'Route path should be in kebab-case.' }],
},
{
code: `app.get('/fooBar/:id')`,
errors: [{ message: 'Route path should be in kebab-case.' }],
},
{
code: `webRouter.get('/foo_bar/:id/FooBar/:name/fooBar')`,
errors: [{ message: 'Route path should be in kebab-case.' }],
},
{
code: `router.get(/^\\/downLoad\\/pro-ject\\/([^/]*)\\/OutPut\\/out-put\\.pdf$/)`,
errors: [{ message: 'Route path should be in kebab-case.' }],
},
],
})
ruleTester.run('no-unnecessary-trans', noUnnecessaryTrans, {
valid: [
{ code: `<Trans i18nKey="test" components={{ strong: <strong/> }}/>` },
],
invalid: [
{
code: `<Trans i18nKey="test" values={{ test: 'foo '}}/>`,
errors: [{ message: `Use t('…') when there are no components` }],
},
{
code: `<Trans i18nKey="test" />`,
errors: [{ message: `Use t('…') when there are no components` }],
output: `{t('test')}`,
},
],
})
ruleTester.run('should-unescape-trans', shouldUnescapeTrans, {
valid: [
{
code: `<Trans i18nKey="test" components={{ strong: <strong/> }}/>`,
},
{
code: `<Trans i18nKey="test" values={{ foo: 'bar' }} components={{ strong: <strong/> }} shouldUnescape tOptions={{ interpolation: { escapeValue: true } }}/>`,
},
],
invalid: [
{
code: `<Trans i18nKey="test" values={{ foo: 'bar' }} components={{ strong: <strong/> }} />`,
errors: [{ message: 'Trans with values must have shouldUnescape' }],
output: `<Trans i18nKey="test" values={{ foo: 'bar' }}\nshouldUnescape components={{ strong: <strong/> }} />`,
},
{
code: `<Trans i18nKey="test" values={{ foo: 'bar' }} components={{ strong: <strong/> }} shouldUnescape />`,
errors: [
{
message:
'Trans with shouldUnescape must have tOptions.interpolation.escapeValue',
},
],
output: `<Trans i18nKey="test" values={{ foo: 'bar' }} components={{ strong: <strong/> }} shouldUnescape\ntOptions={{ interpolation: { escapeValue: true } }} />`,
},
],
})
const noGeneratedEditorThemesError =
'EditorView.theme and EditorView.baseTheme each add CSS to the page for every instance of the theme. Store the theme in a variable and reuse it instead.'
ruleTester.run('no-generated-editor-themes', noGeneratedEditorThemes, {
valid: [
{
code: `EditorView.theme({ '.cm-editor': { color: 'black' } })`,
},
{
code: `const theme = EditorView.theme({ '.cm-editor': { color: 'black' } })`,
},
],
invalid: [
{
code: `function createTheme() { return EditorView.theme({ '.cm-editor': { color: 'black' } }) }`,
errors: [
{
message: noGeneratedEditorThemesError,
},
],
},
{
code: `() => EditorView.theme({ '.cm-editor': { color: 'black' } })`,
errors: [
{
message: noGeneratedEditorThemesError,
},
],
},
{
code: `class Foo { createTheme() { return EditorView.theme({ '.cm-editor': { color: 'black' } }) } }`,
errors: [
{
message: noGeneratedEditorThemesError,
},
],
},
],
})
ruleTester.run('domock-require-valid-path', viDoMockValidPath, {
valid: [
{
code: 'vi.doMock("./require-vi-doMock-valid-path.js")',
filename: __filename,
},
{
code: 'const filename = "./require-vi-doMock-valid-path.js"; vi.doMock(filename);',
filename: __filename,
},
],
invalid: [
{
code: "vi.doMock('./require-vi-doMock-valid-path2')",
filename: __filename,
errors: [
{
message:
'The path "./require-vi-doMock-valid-path2" in vi.doMock() cannot be resolved relative to the current file.',
},
],
},
{
code: 'const filename = "./require-vi-doMock-valid-path2.js"; vi.doMock(filename);',
filename: __filename,
errors: [
{
message:
'The first argument of vi.doMock() must be (or resolve to) a string literal representing a path.',
},
],
},
],
})
@@ -1,43 +0,0 @@
// Enforce alphabetically sorted top-level keys in JSON files.
module.exports = {
meta: {
type: 'problem',
fixable: 'code',
docs: {
description:
'Require top-level keys to be sorted alphabetically in JSON files (typically locale files).',
},
schema: [],
messages: {
unsorted:
'Top-level keys are not sorted alphabetically. Key "{{key}}" should come before "{{predecessor}}".',
},
},
create(context) {
return {
'Document > Object'(node) {
const members = node.members
for (let i = 1; i < members.length; i++) {
const prev = members[i - 1].name.value
const curr = members[i].name.value
if (curr < prev) {
const text = context.sourceCode.text
const parsed = JSON.parse(text)
const sortedKeys = Object.keys(parsed).sort()
const sorted = JSON.stringify(parsed, sortedKeys, 2) + '\n'
context.report({
node: members[i],
messageId: 'unsorted',
data: { key: curr, predecessor: prev },
fix(fixer) {
return fixer.replaceTextRange([0, text.length], sorted)
},
})
return // one violation per file is enough; the fix re-sorts everything
}
}
},
}
},
}
-9
View File
@@ -1,9 +0,0 @@
import { afterAll, describe, it } from 'vitest'
import { RuleTester } from 'eslint'
// ESLint's RuleTester discovers the test framework via these hooks. The repo's
// vitest configs deliberately avoid `globals: true`, so wire them explicitly.
RuleTester.afterAll = afterAll
RuleTester.describe = describe
RuleTester.it = it
RuleTester.itOnly = it.only
@@ -1,687 +0,0 @@
import { fileURLToPath } from 'node:url'
import { RuleTester } from 'eslint'
import tsParser from '@typescript-eslint/parser'
import json from '@eslint/json'
import noThrowInCallback from '../../no-throw-in-callback.js'
import noRawReqAccess from '../../no-raw-req-access.js'
import preferKebabUrl from '../../prefer-kebab-url.js'
import noUnnecessaryTrans from '../../no-unnecessary-trans.js'
import shouldUnescapeTrans from '../../should-unescape-trans.js'
import noGeneratedEditorThemes from '../../no-generated-editor-themes.js'
import viDoMockValidPath from '../../require-vi-doMock-valid-path.js'
import requireCioSnakeCaseProperties from '../../require-cio-snake-case-properties.js'
import requireRelForDocsLinks from '../../require-rel-for-docs-links.js'
import noConsecutiveSpacesInLocales from '../../no-consecutive-spaces-in-locales.js'
import noStraightApostrophesInLocales from '../../no-straight-apostrophes-in-locales.js'
import frenchTypographyInLocales from '../../french-typography-in-locales.js'
import sortedKeysInLocales from '../../sorted-keys-in-locales.js'
import noMochaBefore from '../../no-mocha-before.js'
const __filename = fileURLToPath(import.meta.url)
const ruleTester = new RuleTester({
languageOptions: {
parser: tsParser,
ecmaVersion: 'latest',
parserOptions: { ecmaFeatures: { jsx: true } },
},
})
const jsonRuleTester = new RuleTester({
plugins: { json },
language: 'json/json',
})
ruleTester.run('prefer-kebab-url', preferKebabUrl, {
valid: [
{ code: `app.get('/foo-bar')` },
{ code: `app.get('/foo-bar/:id')` },
{ code: `router.post('/foo-bar')` },
{ code: `router.get('/foo-bar/:id/:name/:age')` },
{ code: `webRouter.get('/foo-bar/:user_id/(ProjectName)/get-info')` },
{ code: `webApp.post('/foo-bar/:user_id/(ProjectName)/get-info')` },
{
code: `router.get(/^\\/download\\/project\\/([^/]*)\\/output\\/output\\.pdf$/)`,
},
{
code: `webRouter.get(/^\\/project\\/([^/]*)\\/user\\/([0-9a-f]+)\\/build\\/([0-9a-f-]+)\\/output\\/(.*)$/)`,
},
],
invalid: [
{
code: `app.get('/fooBar')`,
errors: [
{ message: 'Route path should be in kebab-case.', suggestions: 1 },
],
},
{
code: `app.get('/fooBar/:id')`,
errors: [
{ message: 'Route path should be in kebab-case.', suggestions: 1 },
],
},
{
code: `webRouter.get('/foo_bar/:id/FooBar/:name/fooBar')`,
errors: [
{ message: 'Route path should be in kebab-case.', suggestions: 1 },
],
},
{
code: `router.get(/^\\/downLoad\\/pro-ject\\/([^/]*)\\/OutPut\\/out-put\\.pdf$/)`,
errors: [
{
message: 'Route path should be in kebab-case.',
suggestions: [
{
desc: 'Change to kebab-case: /^\\/down-load\\/pro-ject\\/([^/]*)\\/out-put\\/out-put\\.pdf$/',
output: `router.get(/^\\/down-load\\/pro-ject\\/([^/]*)\\/out-put\\/out-put\\.pdf$/)`,
},
],
},
],
},
],
})
ruleTester.run('no-unnecessary-trans', noUnnecessaryTrans, {
valid: [
{ code: `<Trans i18nKey="test" components={{ strong: <strong/> }}/>` },
],
invalid: [
{
code: `<Trans i18nKey="test" values={{ test: 'foo '}}/>`,
errors: [{ message: `Use t('…') when there are no components` }],
},
{
code: `<Trans i18nKey="test" />`,
errors: [{ message: `Use t('…') when there are no components` }],
output: `{t('test')}`,
},
],
})
ruleTester.run('should-unescape-trans', shouldUnescapeTrans, {
valid: [
{
code: `<Trans i18nKey="test" components={{ strong: <strong/> }}/>`,
},
{
code: `<Trans i18nKey="test" values={{ foo: 'bar' }} components={{ strong: <strong/> }} shouldUnescape tOptions={{ interpolation: { escapeValue: true } }}/>`,
},
],
invalid: [
{
code: `<Trans i18nKey="test" values={{ foo: 'bar' }} components={{ strong: <strong/> }} />`,
errors: [{ message: 'Trans with values must have shouldUnescape' }],
output: `<Trans i18nKey="test" values={{ foo: 'bar' }}\nshouldUnescape components={{ strong: <strong/> }} />`,
},
{
code: `<Trans i18nKey="test" values={{ foo: 'bar' }} components={{ strong: <strong/> }} shouldUnescape />`,
errors: [
{
message:
'Trans with shouldUnescape must have tOptions.interpolation.escapeValue',
},
],
output: `<Trans i18nKey="test" values={{ foo: 'bar' }} components={{ strong: <strong/> }} shouldUnescape\ntOptions={{ interpolation: { escapeValue: true } }} />`,
},
],
})
const noGeneratedEditorThemesError =
'EditorView.theme and EditorView.baseTheme each add CSS to the page for every instance of the theme. Store the theme in a variable and reuse it instead.'
ruleTester.run('no-generated-editor-themes', noGeneratedEditorThemes, {
valid: [
{
code: `EditorView.theme({ '.cm-editor': { color: 'black' } })`,
},
{
code: `const theme = EditorView.theme({ '.cm-editor': { color: 'black' } })`,
},
],
invalid: [
{
code: `function createTheme() { return EditorView.theme({ '.cm-editor': { color: 'black' } }) }`,
errors: [
{
message: noGeneratedEditorThemesError,
},
],
},
{
code: `() => EditorView.theme({ '.cm-editor': { color: 'black' } })`,
errors: [
{
message: noGeneratedEditorThemesError,
},
],
},
{
code: `class Foo { createTheme() { return EditorView.theme({ '.cm-editor': { color: 'black' } }) } }`,
errors: [
{
message: noGeneratedEditorThemesError,
},
],
},
],
})
ruleTester.run('domock-require-valid-path', viDoMockValidPath, {
valid: [
{
code: 'vi.doMock("../../require-vi-doMock-valid-path.js")',
filename: __filename,
},
{
code: 'const filename = "../../require-vi-doMock-valid-path.js"; vi.doMock(filename);',
filename: __filename,
},
],
invalid: [
{
code: "vi.doMock('../../require-vi-doMock-valid-path2')",
filename: __filename,
errors: [
{
message:
'The path "../../require-vi-doMock-valid-path2" in vi.doMock() cannot be resolved relative to the current file.',
suggestions: [],
},
],
},
{
code: 'const filename = "../../require-vi-doMock-valid-path2.js"; vi.doMock(filename);',
filename: __filename,
errors: [
{
message:
'The first argument of vi.doMock() must be (or resolve to) a string literal representing a path.',
suggestions: [],
},
],
},
],
})
ruleTester.run(
'require-cio-snake-case-properties',
requireCioSnakeCaseProperties,
{
valid: [
// updateUserAttributes with snake_case keys
{
code: `CustomerIoHandler.updateUserAttributes(userId, { plan_type: 'free', group_size: 10 })`,
},
// Modules.promises.hooks.fire with snake_case keys
{
code: `Modules.promises.hooks.fire('setUserProperties', userId, { plan_type: 'free', last_active: 123 })`,
},
// Modules.hooks.fire with snake_case keys
{
code: `Modules.hooks.fire('setUserProperties', userId, { plan_type: 'free' })`,
},
// Single-word keys are valid snake_case
{
code: `CustomerIoHandler.updateUserAttributes(userId, { email: 'a@b.com', role: 'admin' })`,
},
// Computed/dynamic keys are skipped
{
code: `CustomerIoHandler.updateUserAttributes(userId, { [dynamicKey]: true })`,
},
// Spread elements are skipped
{
code: `CustomerIoHandler.updateUserAttributes(userId, { ...existingAttrs })`,
},
// Unrelated function calls are not checked
{
code: `SomeOtherHandler.updateUserAttributes(userId, { camelCase: true })`,
},
// fire() with a different event name is not checked
{
code: `Modules.promises.hooks.fire('someOtherEvent', userId, { camelCase: true })`,
},
],
invalid: [
// camelCase key in updateUserAttributes
{
code: `CustomerIoHandler.updateUserAttributes(userId, { planType: 'free' })`,
errors: [
{
message: `Customer.io attribute 'planType' must be in snake_case.`,
},
],
},
// kebab-case string key
{
code: `CustomerIoHandler.updateUserAttributes(userId, { 'plan-type': 'free' })`,
errors: [
{
message: `Customer.io attribute 'plan-type' must be in snake_case.`,
},
],
},
// PascalCase key
{
code: `CustomerIoHandler.updateUserAttributes(userId, { PlanType: 'free' })`,
errors: [
{
message: `Customer.io attribute 'PlanType' must be in snake_case.`,
},
],
},
// camelCase in Modules.promises.hooks.fire
{
code: `Modules.promises.hooks.fire('setUserProperties', userId, { planType: 'free' })`,
errors: [
{
message: `Customer.io attribute 'planType' must be in snake_case.`,
},
],
},
// camelCase in Modules.hooks.fire
{
code: `Modules.hooks.fire('setUserProperties', userId, { planType: 'free' })`,
errors: [
{
message: `Customer.io attribute 'planType' must be in snake_case.`,
},
],
},
// Multiple invalid keys report multiple errors
{
code: `CustomerIoHandler.updateUserAttributes(userId, { planType: 'free', groupSize: 10, plan_term: 'annual' })`,
errors: [
{
message: `Customer.io attribute 'planType' must be in snake_case.`,
},
{
message: `Customer.io attribute 'groupSize' must be in snake_case.`,
},
],
},
],
}
)
const noThrowInCallbackMessage =
'Pass the error to the callback instead of throwing in callback-based code.'
ruleTester.run('no-throw-in-callback', noThrowInCallback, {
valid: [
// Calling the callback with an error is fine
{ code: `function foo(cb) { cb(new Error()) }` },
// async functions may throw (they return a rejected promise)
{ code: `async function foo(cb) { throw new Error() }` },
// Last param not a callback name — not a callback-style function
{ code: `function foo(data) { throw new Error() }` },
// No params at all
{ code: `function foo() { throw new Error() }` },
// throw inside a nested non-callback function is fine
{ code: `function foo(cb) { [1].map(function() { throw new Error() }) }` },
// throw inside a nested async arrow is fine
{ code: `function foo(cb) { [1].map(async () => { throw new Error() }) }` },
],
invalid: [
{
code: `function foo(cb) { throw new Error() }`,
errors: [{ message: noThrowInCallbackMessage }],
},
{
code: `function foo(callback) { throw new Error() }`,
errors: [{ message: noThrowInCallbackMessage }],
},
{
code: `function foo(done) { throw new Error() }`,
errors: [{ message: noThrowInCallbackMessage }],
},
{
code: `function foo(next) { throw new Error() }`,
errors: [{ message: noThrowInCallbackMessage }],
},
{
code: `function foo(data, cb) { throw new Error() }`,
errors: [{ message: noThrowInCallbackMessage }],
},
{
code: `const foo = (cb) => { throw new Error() }`,
errors: [{ message: noThrowInCallbackMessage }],
},
// throw in a nested callback-style function inside another callback function
{
code: `function foo(cb) { bar(function(done) { throw new Error() }) }`,
errors: [{ message: noThrowInCallbackMessage }],
},
],
})
ruleTester.run('no-raw-req-access', noRawReqAccess, {
valid: [
// validated access goes through parseReq
{ code: `const { params, body } = parseReq(req, schema)` },
// allowlisted middleware reads raw input explicitly
{ code: `const { query } = getRawReqInput(req)` },
// writes stay allowed: body parsers and middleware assign req.body
{ code: `req.body = {}` },
{ code: `req.query = parsed` },
// other request fields are not locked
{ code: `const ua = req.headers['user-agent']` },
{ code: `const s = req.session` },
// other objects with the same field names are fine
{ code: `const b = options.body` },
{ code: `const { body } = response` },
],
invalid: [
{
code: `const id = req.params.project_id`,
errors: [{ messageId: 'noRawReqAccess', data: { field: 'params' } }],
},
{
code: `if (req.query.force) { doIt() }`,
errors: [{ messageId: 'noRawReqAccess', data: { field: 'query' } }],
},
{
code: `send(req.body)`,
errors: [{ messageId: 'noRawReqAccess', data: { field: 'body' } }],
},
// computed string access
{
code: `const b = req['body']`,
errors: [{ messageId: 'noRawReqAccess', data: { field: 'body' } }],
},
// destructuring reads
{
code: `const { body } = req`,
errors: [{ messageId: 'noRawReqAccess', data: { field: 'body' } }],
},
{
code: `const { params, query } = req`,
errors: [
{ messageId: 'noRawReqAccess', data: { field: 'params' } },
{ messageId: 'noRawReqAccess', data: { field: 'query' } },
],
},
// compound assignment reads before writing
{
code: `req.body ||= {}`,
errors: [{ messageId: 'noRawReqAccess', data: { field: 'body' } }],
},
// optional chaining
{
code: `const q = req?.query`,
errors: [{ messageId: 'noRawReqAccess', data: { field: 'query' } }],
},
],
})
ruleTester.run('require-rel-for-docs-links', requireRelForDocsLinks, {
valid: [
{
code: `<a href="https://docs.overleaf.com/foo" target="_blank" rel="noopener noreferrer">x</a>`,
},
{
code: `<a href="https://docs.overleaf.com/foo" target="_blank" rel="noreferrer noopener">x</a>`,
},
{ code: `<a href="/learn/foo" target="_blank">x</a>` },
{ code: `<a href="https://docs.overleaf.com/foo">x</a>` },
{ code: `<a href="https://docs.overleaf.com/foo" target="_self">x</a>` },
{
code: `<OLButton href="https://docs.overleaf.com/foo" target="_blank" rel="noopener noreferrer">x</OLButton>`,
},
{ code: `<OLButton href="https://docs.overleaf.com/foo">x</OLButton>` },
],
invalid: [
{
code: `<a href="https://docs.overleaf.com/foo" target="_blank">x</a>`,
errors: [
{
message:
'Links to docs.overleaf.com with target="_blank" must have rel="noopener noreferrer" to prevent reverse-tabnabbing.',
},
],
output: `<a href="https://docs.overleaf.com/foo" target="_blank" rel="noopener noreferrer">x</a>`,
},
{
code: `<a href="https://docs.overleaf.com/foo" target="_BLANK">x</a>`,
errors: [
{
message:
'Links to docs.overleaf.com with target="_blank" must have rel="noopener noreferrer" to prevent reverse-tabnabbing.',
},
],
output: `<a href="https://docs.overleaf.com/foo" target="_BLANK" rel="noopener noreferrer">x</a>`,
},
{
code: `<a href="https://docs.overleaf.com/foo" target="_blank" rel="noopener">x</a>`,
errors: [
{
message:
'Links to docs.overleaf.com with target="_blank" must have rel="noopener noreferrer" to prevent reverse-tabnabbing.',
},
],
output: `<a href="https://docs.overleaf.com/foo" target="_blank" rel="noopener noreferrer">x</a>`,
},
{
code: `<a href="https://docs.overleaf.com/foo" target="_blank" rel="noreferrer">x</a>`,
errors: [
{
message:
'Links to docs.overleaf.com with target="_blank" must have rel="noopener noreferrer" to prevent reverse-tabnabbing.',
},
],
output: `<a href="https://docs.overleaf.com/foo" target="_blank" rel="noreferrer noopener">x</a>`,
},
{
code: `<OLButton href="https://docs.overleaf.com/foo" target="_blank">x</OLButton>`,
errors: [
{
message:
'Links to docs.overleaf.com with target="_blank" must have rel="noopener noreferrer" to prevent reverse-tabnabbing.',
},
],
output: `<OLButton href="https://docs.overleaf.com/foo" target="_blank" rel="noopener noreferrer">x</OLButton>`,
},
{
// Boolean attribute (no value) - relAttr.value is null, must not crash the fixer.
code: `<a href="https://docs.overleaf.com/foo" target="_blank" rel />`,
errors: [
{
message:
'Links to docs.overleaf.com with target="_blank" must have rel="noopener noreferrer" to prevent reverse-tabnabbing.',
},
],
output: `<a href="https://docs.overleaf.com/foo" target="_blank" rel="noopener noreferrer" />`,
},
],
})
jsonRuleTester.run(
'no-consecutive-spaces-in-locales',
noConsecutiveSpacesInLocales,
{
valid: [
{ code: '{ "key": "one space" }' },
{ code: '{ "key": "no whitespace" }' },
],
invalid: [
{
code: '{ "key": "two spaces" }',
errors: [{ messageId: 'consecutiveSpaces' }],
output: '{ "key": "two spaces" }',
},
{
code: '{ "key": "three spaces" }',
errors: [{ messageId: 'consecutiveSpaces' }],
output: '{ "key": "three spaces" }',
},
{
// \t then space → two consecutive whitespace chars
code: '{ "key": "tab\\t and" }',
errors: [{ messageId: 'consecutiveSpaces' }],
output: '{ "key": "tab and" }',
},
],
}
)
jsonRuleTester.run(
'no-straight-apostrophes-in-locales',
noStraightApostrophesInLocales,
{
valid: [
{ code: '{ "key": "no apostrophe" }' },
{ code: '{ "key": "it’s curly" }' },
],
invalid: [
{
code: `{ "key": "it's straight" }`,
errors: [{ messageId: 'straightApostrophe' }],
output: '{ "key": "it’s straight" }',
},
],
}
)
jsonRuleTester.run('sorted-keys-in-locales', sortedKeysInLocales, {
valid: [
{ code: '{\n "a": "1",\n "b": "2"\n}\n' },
{ code: '{}' },
{ code: '{ "only": "one" }' },
],
invalid: [
{
code: '{\n "b": "2",\n "a": "1"\n}\n',
errors: [{ messageId: 'unsorted' }],
output: '{\n "a": "1",\n "b": "2"\n}\n',
},
],
})
jsonRuleTester.run('french-typography-in-locales', frenchTypographyInLocales, {
valid: [
{ code: '{ "key": "Bonjour ?" }' },
{ code: '{ "key": "Liste :" }' },
{ code: '{ "key": "« contenu »" }' },
{ code: '{ "key": "abc 123" }' },
{ code: '{ "key": "10 %" }' },
],
invalid: [
{
code: '{ "key": "Bonjour?" }',
errors: 1,
output: '{ "key": "Bonjour ?" }',
},
{
code: '{ "key": "Bonjour ?" }',
errors: 1,
output: '{ "key": "Bonjour ?" }',
},
{
code: '{ "key": "Liste:" }',
errors: 1,
output: '{ "key": "Liste :" }',
},
{
code: '{ "key": "«contenu»" }',
errors: 2,
output: '{ "key": "« contenu »" }',
},
{
code: '{ "key": "10%" }',
errors: 1,
output: '{ "key": "10 %" }',
},
{
code: '{ "key": "sûr(e)" }',
errors: [
{
message:
'expected point médian "·" instead of "(e)" for inclusive writing',
suggestions: [
{
desc: 'Replace "(e)" with "·e"',
output: '{ "key": "sûr·e" }',
},
],
},
],
},
],
})
const noMochaBeforeOptions = [
{ helperPath: 'server-ce/test/helpers/beforeWithReRunOnTestRetry' },
]
ruleTester.run('no-mocha-before', noMochaBefore, {
valid: [
{
code: `beforeEach(function () { setup() })`,
options: noMochaBeforeOptions,
},
{
code: `import { beforeWithReRunOnTestRetry } from './helpers/beforeWithReRunOnTestRetry'
beforeWithReRunOnTestRetry(function () { setup() })`,
options: noMochaBeforeOptions,
},
{
// locally defined `before` is not the mocha hook
code: `function before(fn) { fn() }
before(function () { setup() })`,
options: noMochaBeforeOptions,
},
],
invalid: [
{
// rename + import added after the last existing import
filename: 'server-ce/test/foo.spec.ts',
code: `import { login } from './helpers/login'
before(async function () { this.timeout(1000) })`,
options: noMochaBeforeOptions,
errors: 1,
output: `import { login } from './helpers/login'
import { beforeWithReRunOnTestRetry } from './helpers/beforeWithReRunOnTestRetry'
beforeWithReRunOnTestRetry(async function () { this.timeout(1000) })`,
},
{
// no imports yet: import inserted at the top
filename: 'server-ce/test/foo.spec.ts',
code: `before(function () { setup() })`,
options: noMochaBeforeOptions,
errors: 1,
output: `import { beforeWithReRunOnTestRetry } from './helpers/beforeWithReRunOnTestRetry'
beforeWithReRunOnTestRetry(function () { setup() })`,
},
{
// helper already imported: rename only
filename: 'server-ce/test/foo.spec.ts',
code: `import { beforeWithReRunOnTestRetry } from './helpers/beforeWithReRunOnTestRetry'
before(function () { setup() })`,
options: noMochaBeforeOptions,
errors: 1,
output: `import { beforeWithReRunOnTestRetry } from './helpers/beforeWithReRunOnTestRetry'
beforeWithReRunOnTestRetry(function () { setup() })`,
},
{
// file inside helpers/: relative path has no directory prefix
filename: 'server-ce/test/helpers/config.ts',
code: `before(function () { setup() })`,
options: noMochaBeforeOptions,
errors: 1,
output: `import { beforeWithReRunOnTestRetry } from './beforeWithReRunOnTestRetry'
beforeWithReRunOnTestRetry(function () { setup() })`,
},
{
// two-argument mocha form: report without autofix
filename: 'server-ce/test/foo.spec.ts',
code: `before('named hook', function () { setup() })`,
options: noMochaBeforeOptions,
errors: 1,
},
{
// no helperPath configured: report without autofix
filename: 'server-ce/test/foo.spec.ts',
code: `before(function () { setup() })`,
errors: 1,
},
],
})
+3 -1
View File
@@ -1,4 +1,6 @@
{
"extends": "../../tsconfig.backend.json",
"include": ["**/*.js", "**/*.cjs", "**/*.ts"]
"include": [
"**/*.js",
]
}
-25
View File
@@ -1,25 +0,0 @@
import { defineConfig, ViteUserConfig } from 'vitest/config'
let reporterOptions: ViteUserConfig['test'] = {}
if (process.env.CI) {
reporterOptions = {
reporters: [
'default',
[
'junit',
{
classnameTemplate: `Unit tests.{filename}`,
},
],
],
outputFile: 'reports/junit-vitest-unit.xml',
}
}
export default defineConfig({
test: {
include: ['test/unit/**/*.test.{js,ts}'],
setupFiles: ['./test/setup.js'],
isolate: false,
...reporterOptions,
},
})
@@ -1,7 +1,7 @@
let reporterOptions = {}
if (process.env.CI) {
reporterOptions = {
reporter: require.resolve('mocha-multi-reporters'),
reporter: '/overleaf/node_modules/mocha-multi-reporters',
'reporter-options': ['configFile=./test/mocha-multi-reporters.cjs'],
}
}
+1
View File
@@ -0,0 +1 @@
22.18.0
+9
View File
@@ -0,0 +1,9 @@
fetch-utils
--dependencies=None
--env-add=
--env-pass-through=
--esmock-loader=False
--is-library=True
--node-version=22.18.0
--pipeline-owner=🚉 Platform
--public-repo=False
+326
View File
@@ -0,0 +1,326 @@
const _ = require('lodash')
const { Readable } = require('node:stream')
const OError = require('@overleaf/o-error')
const fetch = require('node-fetch')
const http = require('node:http')
const https = require('node:https')
/**
* @import { Response } from 'node-fetch'
*/
/**
* Make a request and return the parsed JSON response.
*
* @param {string | URL} url - request URL
* @param {any} [opts] - fetch options
* @return {Promise<any>} the parsed JSON response
* @throws {RequestFailedError} if the response has a failure status code
*/
async function fetchJson(url, opts = {}) {
const { json } = await fetchJsonWithResponse(url, opts)
return json
}
async function fetchJsonWithResponse(url, opts = {}) {
const { fetchOpts, detachSignal } = parseOpts(opts)
fetchOpts.headers = fetchOpts.headers ?? {}
fetchOpts.headers.Accept = fetchOpts.headers.Accept ?? 'application/json'
const response = await performRequest(url, fetchOpts, detachSignal)
if (!response.ok) {
const body = await maybeGetResponseBody(response)
throw new RequestFailedError(url, opts, response, body)
}
const json = await response.json()
return { json, response }
}
/**
* Make a request and return a stream.
*
* If the response body is destroyed, the request is aborted.
*
* @param {string | URL} url - request URL
* @param {any} [opts] - fetch options
* @return {Promise<Readable>}
* @throws {RequestFailedError} if the response has a failure status code
*/
async function fetchStream(url, opts = {}) {
const { stream } = await fetchStreamWithResponse(url, opts)
return stream
}
async function fetchStreamWithResponse(url, opts = {}) {
const { fetchOpts, abortController, detachSignal } = parseOpts(opts)
const response = await performRequest(url, fetchOpts, detachSignal)
if (!response.ok) {
const body = await maybeGetResponseBody(response)
throw new RequestFailedError(url, opts, response, body)
}
abortOnDestroyedResponse(abortController, response)
const stream = response.body
return { stream, response }
}
/**
* Make a request and discard the response.
*
* @param {string | URL} url - request URL
* @param {any} [opts] - fetch options
* @return {Promise<Response>}
* @throws {RequestFailedError} if the response has a failure status code
*/
async function fetchNothing(url, opts = {}) {
const { fetchOpts, detachSignal } = parseOpts(opts)
const response = await performRequest(url, fetchOpts, detachSignal)
if (!response.ok) {
const body = await maybeGetResponseBody(response)
throw new RequestFailedError(url, opts, response, body)
}
await discardResponseBody(response)
return response
}
/**
* Make a request and extract the redirect from the response.
*
* @param {string | URL} url - request URL
* @param {any} [opts] - fetch options
* @return {Promise<string>}
* @throws {RequestFailedError} if the response has a non redirect status code or missing Location header
*/
async function fetchRedirect(url, opts = {}) {
const { location } = await fetchRedirectWithResponse(url, opts)
return location
}
/**
* Make a request and extract the redirect from the response.
*
* @param {string | URL} url - request URL
* @param {object} opts - fetch options
* @return {Promise<{location: string, response: Response}>}
* @throws {RequestFailedError} if the response has a non redirect status code or missing Location header
*/
async function fetchRedirectWithResponse(url, opts = {}) {
const { fetchOpts, detachSignal } = parseOpts(opts)
fetchOpts.redirect = 'manual'
const response = await performRequest(url, fetchOpts, detachSignal)
if (response.status < 300 || response.status >= 400) {
const body = await maybeGetResponseBody(response)
throw new RequestFailedError(url, opts, response, body)
}
const location = response.headers.get('Location')
if (!location) {
const body = await maybeGetResponseBody(response)
throw new RequestFailedError(url, opts, response, body).withCause(
new OError('missing Location response header on 3xx response', {
headers: Object.fromEntries(response.headers.entries()),
})
)
}
await discardResponseBody(response)
return { location, response }
}
/**
* Make a request and return a string.
*
* @param {string | URL} url - request URL
* @param {any} [opts] - fetch options
* @return {Promise<string>}
* @throws {RequestFailedError} if the response has a failure status code
*/
async function fetchString(url, opts = {}) {
const { body } = await fetchStringWithResponse(url, opts)
return body
}
async function fetchStringWithResponse(url, opts = {}) {
const { fetchOpts, detachSignal } = parseOpts(opts)
const response = await performRequest(url, fetchOpts, detachSignal)
if (!response.ok) {
const body = await maybeGetResponseBody(response)
throw new RequestFailedError(url, opts, response, body)
}
const body = await response.text()
return { body, response }
}
class RequestFailedError extends OError {
constructor(url, opts, response, body) {
super('request failed', {
url,
method: opts.method ?? 'GET',
status: response.status,
})
this.response = response
if (body != null) {
this.body = body
}
}
}
function parseOpts(opts) {
const fetchOpts = _.omit(opts, ['json', 'signal', 'basicAuth'])
if (opts.json) {
setupJsonBody(fetchOpts, opts.json)
}
if (opts.basicAuth) {
setupBasicAuth(fetchOpts, opts.basicAuth)
}
const abortController = new AbortController()
fetchOpts.signal = abortController.signal
let detachSignal = () => {}
if (opts.signal) {
detachSignal = abortOnSignal(abortController, opts.signal)
}
if (opts.body instanceof Readable) {
abortOnDestroyedRequest(abortController, fetchOpts.body)
}
return { fetchOpts, abortController, detachSignal }
}
function setupJsonBody(fetchOpts, json) {
fetchOpts.body = JSON.stringify(json)
fetchOpts.headers = fetchOpts.headers ?? {}
fetchOpts.headers['Content-Type'] = 'application/json'
}
function setupBasicAuth(fetchOpts, basicAuth) {
fetchOpts.headers = fetchOpts.headers ?? {}
fetchOpts.headers.Authorization =
'Basic ' +
Buffer.from(`${basicAuth.user}:${basicAuth.password}`).toString('base64')
}
function abortOnSignal(abortController, signal) {
const listener = () => {
abortController.abort(signal.reason)
}
if (signal.aborted) {
abortController.abort(signal.reason)
}
signal.addEventListener('abort', listener)
return () => {
signal.removeEventListener('abort', listener)
}
}
function abortOnDestroyedRequest(abortController, stream) {
stream.on('close', () => {
if (!stream.readableEnded) {
abortController.abort()
}
})
}
function abortOnDestroyedResponse(abortController, response) {
response.body.on('close', () => {
if (!response.bodyUsed) {
abortController.abort()
}
})
}
async function performRequest(url, fetchOpts, detachSignal) {
let response
try {
response = await fetch(url, fetchOpts)
} catch (err) {
detachSignal()
if (fetchOpts.body instanceof Readable) {
fetchOpts.body.destroy()
}
throw OError.tag(err, err.message, {
url,
method: fetchOpts.method ?? 'GET',
})
}
response.body.on('close', detachSignal)
if (fetchOpts.body instanceof Readable) {
response.body.on('close', () => {
if (!fetchOpts.body.readableEnded) {
fetchOpts.body.destroy()
}
})
}
return response
}
async function discardResponseBody(response) {
// eslint-disable-next-line no-unused-vars
for await (const chunk of response.body) {
// discard the body
}
}
/**
* @param {Response} response
*/
async function maybeGetResponseBody(response) {
try {
return await response.text()
} catch (err) {
return null
}
}
// Define custom http and https agents with support for connect timeouts
class ConnectTimeoutError extends OError {
constructor(options) {
super('connect timeout', options)
}
}
function withTimeout(createConnection, options, callback) {
if (options.connectTimeout) {
// Wrap createConnection in a timeout
const timer = setTimeout(() => {
socket.destroy(new ConnectTimeoutError(options))
}, options.connectTimeout)
const socket = createConnection(options, (err, stream) => {
clearTimeout(timer)
callback(err, stream)
})
return socket
} else {
// Fallback to default createConnection
return createConnection(options, callback)
}
}
class CustomHttpAgent extends http.Agent {
createConnection(options, callback) {
return withTimeout(super.createConnection.bind(this), options, callback)
}
}
class CustomHttpsAgent extends https.Agent {
createConnection(options, callback) {
return withTimeout(super.createConnection.bind(this), options, callback)
}
}
module.exports = {
fetchJson,
fetchJsonWithResponse,
fetchStream,
fetchStreamWithResponse,
fetchNothing,
fetchRedirect,
fetchRedirectWithResponse,
fetchString,
fetchStringWithResponse,
RequestFailedError,
ConnectTimeoutError,
CustomHttpAgent,
CustomHttpsAgent,
}
-490
View File
@@ -1,490 +0,0 @@
import { Readable, Duplex } from 'node:stream'
import OError from '@overleaf/o-error'
import fetch, { Headers } from 'node-fetch'
import type { RequestInit, Response } from 'node-fetch'
import http from 'node:http'
import https from 'node:https'
import net from 'node:net'
import tls from 'node:tls'
let logger: { warn: (...args: any[]) => void } | undefined
type BasicAuthOptions = {
user: string
password: string
}
type FetchRequestOptions = RequestInit & {
json?: unknown
basicAuth?: BasicAuthOptions
}
type FetchHeaders = NonNullable<RequestInit['headers']>
type ParsedFetchOptions = Omit<
FetchRequestOptions,
'json' | 'signal' | 'basicAuth' | 'headers'
> & {
headers: Headers
signal?: AbortSignal
}
function setLogger(loggerInstance: { warn: (...args: any[]) => void }) {
logger = loggerInstance
}
/**
* Make a request and return the parsed JSON response.
*
* @throws {RequestFailedError} if the response has a failure status code
*/
async function fetchJson(url: string | URL, opts: FetchRequestOptions = {}) {
const { json } = await fetchJsonWithResponse(url, opts)
return json
}
async function fetchJsonWithResponse(
url: string | URL,
opts: FetchRequestOptions = {}
) {
const { fetchOpts, detachSignal } = parseOpts(opts, url)
if (!fetchOpts.headers.has('Accept')) {
fetchOpts.headers.set('Accept', 'application/json')
}
const response = await performRequest(url, fetchOpts, detachSignal)
if (!response.ok) {
const body = await maybeGetResponseBody(response)
throw new RequestFailedError(url, opts, response, body)
}
const json = await response.json()
return { json, response }
}
/**
* Make a request and return a stream.
*
* If the response body is destroyed, the request is aborted.
*
* @throws {RequestFailedError} if the response has a failure status code
*/
async function fetchStream(url: string | URL, opts: FetchRequestOptions = {}) {
const { stream } = await fetchStreamWithResponse(url, opts)
return stream
}
async function fetchStreamWithResponse(
url: string | URL,
opts: FetchRequestOptions = {}
) {
const { fetchOpts, abortController, detachSignal } = parseOpts(opts, url)
const response = await performRequest(url, fetchOpts, detachSignal)
if (!response.ok) {
const body = await maybeGetResponseBody(response)
throw new RequestFailedError(url, opts, response, body)
}
abortOnDestroyedResponse(abortController, response)
const stream = response.body
return { stream, response }
}
/**
* Make a request and discard the response.
*
* @throws {RequestFailedError} if the response has a failure status code
*/
async function fetchNothing(url: string | URL, opts: FetchRequestOptions = {}) {
const { fetchOpts, detachSignal } = parseOpts(opts, url)
const response = await performRequest(url, fetchOpts, detachSignal)
if (!response.ok) {
const body = await maybeGetResponseBody(response)
throw new RequestFailedError(url, opts, response, body)
}
await discardResponseBody(response)
return response
}
/**
* Make a request and extract the redirect from the response.
*
* @throws {RequestFailedError} if the response has a non redirect status code or missing Location header
*/
async function fetchRedirect(
url: string | URL,
opts: FetchRequestOptions = {}
) {
const { location } = await fetchRedirectWithResponse(url, opts)
return location
}
/**
* Make a request and extract the redirect from the response.
*
* @throws {RequestFailedError} if the response has a non redirect status code or missing Location header
*/
async function fetchRedirectWithResponse(
url: string | URL,
opts: FetchRequestOptions = {}
) {
const { fetchOpts, detachSignal } = parseOpts(opts, url)
fetchOpts.redirect = 'manual'
const response = await performRequest(url, fetchOpts, detachSignal)
if (response.status < 300 || response.status >= 400) {
const body = await maybeGetResponseBody(response)
throw new RequestFailedError(url, opts, response, body)
}
const location = response.headers.get('Location')
if (!location) {
const body = await maybeGetResponseBody(response)
throw new RequestFailedError(url, opts, response, body).withCause(
new OError('missing Location response header on 3xx response', {
headers: Object.fromEntries(response.headers.entries()),
})
)
}
await discardResponseBody(response)
return { location, response }
}
/**
* Make a request and return a string.
*
* @throws {RequestFailedError} if the response has a failure status code
*/
async function fetchString(url: string | URL, opts: FetchRequestOptions = {}) {
const { body } = await fetchStringWithResponse(url, opts)
return body
}
async function fetchStringWithResponse(
url: string | URL,
opts: FetchRequestOptions = {}
) {
const { fetchOpts, detachSignal } = parseOpts(opts, url)
const response = await performRequest(url, fetchOpts, detachSignal)
if (!response.ok) {
const body = await maybeGetResponseBody(response)
throw new RequestFailedError(url, opts, response, body)
}
const body = await response.text()
return { body, response }
}
class RequestFailedError extends OError {
response: Response
body?: string
constructor(
url: string | URL,
opts: Pick<FetchRequestOptions, 'method'>,
response: Response,
body: string | null
) {
super('request failed', {
url,
method: opts.method ?? 'GET',
status: response.status,
...([400, 409, 413, 422].includes(response.status) ? { body } : {}),
})
this.response = response
if (body != null) {
this.body = body
}
}
}
function setupDefaultAgent(fetchOpts: ParsedFetchOptions) {
// Provide a function to get the agent for each request as there may be
// multiple requests with different protocols due to redirects.
fetchOpts.agent = (url: URL) =>
url.protocol === 'https:' ? httpsAgent : httpAgent
}
/**
* Normalise the headers option into a Headers instance, which is what
* node-fetch builds from it anyway.
*
* Headers with an unset value are dropped: header values are stringified, so
* they would otherwise be sent as the literal string `undefined`.
*/
function parseHeaders(headers: FetchHeaders): Headers {
// A Headers instance can't hold unset values. Pass it through rather than
// iterate it, which would collapse repeated headers into a single
// comma-separated value.
if (headers instanceof Headers) {
return headers
}
// Not in the TS type, but node-fetch accepts any iterable of entries, such as
// a Map or a global Headers instance. Those expose no own enumerable
// properties, so they have to be iterated rather than passed to
// Object.entries().
const entries: Iterable<[string, unknown]> =
Symbol.iterator in headers
? (headers as Iterable<[string, unknown]>)
: Object.entries(headers)
const parsedHeaders = new Headers()
for (const [name, value] of entries) {
if (value != null) {
parsedHeaders.append(name, String(value))
}
}
return parsedHeaders
}
function parseOpts(opts: FetchRequestOptions, url: string | URL) {
const { json, signal, basicAuth, headers, ...rawFetchOpts } = opts
const fetchOpts: ParsedFetchOptions = {
...rawFetchOpts,
headers: parseHeaders(headers ?? {}),
}
if (json) {
setupJsonBody(fetchOpts, json)
}
if (basicAuth) {
setupBasicAuth(fetchOpts, basicAuth)
}
if (!fetchOpts.agent) {
setupDefaultAgent(fetchOpts)
}
const abortController = new AbortController()
fetchOpts.signal = abortController.signal
let detachSignal: () => void
if (signal) {
detachSignal = abortOnSignal(abortController, signal)
} else {
let overTimeoutStart: bigint | undefined
const stack = new Error().stack
const timeout = setTimeout(() => {
overTimeoutStart = process.hrtime.bigint()
}, 120000)
detachSignal = () => {
clearTimeout(timeout)
if (overTimeoutStart && logger) {
logger.warn(
{
url,
method: fetchOpts.method ?? 'GET',
overTimeoutMs:
Number(process.hrtime.bigint() - overTimeoutStart) / 1e6,
stack,
},
'Fetch request did not complete within 120 seconds'
)
}
}
}
if (fetchOpts.body instanceof Readable) {
abortOnDestroyedRequest(abortController, fetchOpts.body)
}
return { fetchOpts, abortController, detachSignal }
}
function setupJsonBody(fetchOpts: ParsedFetchOptions, json: unknown) {
fetchOpts.body = JSON.stringify(json)
fetchOpts.headers.set('Content-Type', 'application/json')
}
function setupBasicAuth(
fetchOpts: ParsedFetchOptions,
basicAuth: BasicAuthOptions
) {
fetchOpts.headers.set(
'Authorization',
'Basic ' +
Buffer.from(`${basicAuth.user}:${basicAuth.password}`).toString('base64')
)
}
function abortOnSignal(abortController: AbortController, signal: AbortSignal) {
const listener = () => {
abortController.abort(signal.reason)
}
if (signal.aborted) {
abortController.abort(signal.reason)
}
signal.addEventListener('abort', listener)
return () => {
signal.removeEventListener('abort', listener)
}
}
function abortOnDestroyedRequest(
abortController: AbortController,
stream: Readable
) {
stream.on('close', () => {
if (!stream.readableEnded) {
abortController.abort()
}
})
}
function abortOnDestroyedResponse(
abortController: AbortController,
response: Response
) {
response.body.on('close', () => {
if (!response.bodyUsed) {
abortController.abort()
}
})
}
async function performRequest(
url: string | URL,
fetchOpts: ParsedFetchOptions,
detachSignal: () => void
) {
let response
try {
response = await fetch(url, fetchOpts)
} catch (err: any) {
detachSignal()
if (fetchOpts.body instanceof Readable) {
fetchOpts.body.destroy()
}
throw OError.tag(err, err.message, {
url,
method: fetchOpts.method ?? 'GET',
})
}
response.body.on('close', detachSignal)
if (fetchOpts.body instanceof Readable) {
const requestBodyStream = fetchOpts.body
response.body.on('close', () => {
if (!requestBodyStream.readableEnded) {
requestBodyStream.destroy()
}
})
}
return response
}
async function discardResponseBody(response: Response) {
// eslint-disable-next-line no-unused-vars
for await (const chunk of response.body) {
// discard the body
}
}
async function maybeGetResponseBody(response: Response) {
try {
return await response.text()
} catch (err) {
return null
}
}
// Define custom http and https agents with support for connect timeouts
class ConnectTimeoutError extends OError {
constructor(options: any) {
super('connect timeout', options)
}
}
function tryToCreateConnection(
createConnection: (options: any) => Duplex,
options: any,
callback: (err: any, socket: any) => void
) {
let socket: Duplex
try {
socket = createConnection(options)
} catch (err) {
callback(err, null)
return
}
const timer = setTimeout(() => {
socket.destroy(new ConnectTimeoutError(options))
}, options.connectTimeout)
const onConnect = () => {
clearTimeout(timer)
socket.off('error', onError)
callback(null, socket)
}
const onError = (err: any) => {
clearTimeout(timer)
socket.off('connect', onConnect)
callback(err, null)
}
socket.once('connect', onConnect)
socket.once('error', onError)
}
function withTimeout(
createConnection: (options: any) => Duplex,
options: any,
callback: (err: any, socket: any) => void
) {
const attempt = (remainingAttempts: number) => {
remainingAttempts--
tryToCreateConnection(createConnection, options, (err, socket) => {
if (err && remainingAttempts > 0) {
setTimeout(() => {
attempt(remainingAttempts)
}, options.connectRetryInterval ?? 100)
return
}
callback(err, socket)
})
}
attempt(3)
}
class CustomHttpAgent extends http.Agent {
constructor(options: any) {
if (!(options.connectTimeout > 0)) {
throw new Error(
'CustomHttpAgent must be called with positive connectTimeout'
)
}
super(options)
}
createConnection(options: any, callback: any) {
withTimeout(net.createConnection, options, callback)
return undefined
}
}
class CustomHttpsAgent extends https.Agent {
constructor(options: any) {
if (!(options.connectTimeout > 0)) {
throw new Error(
'CustomHttpsAgent must be called with positive connectTimeout'
)
}
super(options)
}
createConnection(options: any, callback: any) {
withTimeout(tls.connect, options, callback)
return undefined
}
}
const MAX_CONNECT_TIME = 1000
const httpAgent = new CustomHttpAgent({ connectTimeout: MAX_CONNECT_TIME })
const httpsAgent = new CustomHttpsAgent({ connectTimeout: MAX_CONNECT_TIME })
export {
fetchJson,
fetchJsonWithResponse,
fetchStream,
fetchStreamWithResponse,
fetchNothing,
fetchRedirect,
fetchRedirectWithResponse,
fetchString,
fetchStringWithResponse,
RequestFailedError,
ConnectTimeoutError,
CustomHttpAgent,
CustomHttpsAgent,
setLogger,
}
+17 -21
View File
@@ -2,38 +2,34 @@
"name": "@overleaf/fetch-utils",
"version": "0.1.0",
"description": "utilities for node-fetch",
"main": "index.ts",
"exports": {
"import": "./index.ts",
"require": "./index.ts",
"default": "./index.ts"
},
"type": "module",
"main": "index.js",
"scripts": {
"test": "yarn run lint && yarn run types:check && yarn run test:unit",
"lint": "eslint --cache --cache-location ../../.cache/eslint/ --ext .cjs,.js,.jsx,.mjs,.ts --max-warnings 0 .",
"lint:fix": "eslint --cache --cache-location ../../.cache/eslint/ --fix --ext .cjs,.js,.jsx,.mjs,.ts .",
"test:ci": "yarn run test:unit",
"test:unit": "vitest --config vitest.config.ts",
"test": "npm run lint && npm run format && npm run types:check && npm run test:unit",
"lint": "eslint --ext .cjs,.js,.jsx,.mjs,.ts --max-warnings 0 --format unix .",
"lint:fix": "eslint --fix --ext .cjs,.js,.jsx,.mjs,.ts .",
"format": "prettier --list-different $PWD/'**/*.{js,cjs,ts}'",
"format:fix": "prettier --write $PWD/'**/*.{js,cjs,ts}'",
"test:ci": "npm run test:unit",
"test:unit": "mocha --exit test/**/*.{js,cjs}",
"types:check": "tsc --noEmit"
},
"author": "Overleaf (https://www.overleaf.com)",
"license": "AGPL-3.0-only",
"devDependencies": {
"@types/lodash": "^4.17.24",
"@types/node": "^24.5.2",
"@types/node-fetch": "^2.6.13",
"body-parser": "1.20.4",
"chai": "^4.3.6",
"chai-as-promised": "^7.1.1",
"eslint": "^10.4.0",
"express": "4.22.1",
"selfsigned": "^5.5.0",
"typescript": "^5.0.4",
"vitest": "4.1.5"
"mocha": "^11.1.0",
"mocha-junit-reporter": "^2.2.1",
"mocha-multi-reporters": "^1.5.1",
"typescript": "^5.0.4"
},
"dependencies": {
"@overleaf/o-error": "workspace:*",
"lodash": "^4.18.1",
"node-fetch": "^2.7.0"
"@overleaf/o-error": "*",
"lodash": "^4.17.21",
"node-fetch": "^2.7.0",
"selfsigned": "^2.4.1"
}
}
@@ -1,7 +1,7 @@
module.exports = {
reporterEnabled: 'spec, mocha-junit-reporter',
mochaJunitReporterReporterOptions: {
mochaFile: `reports/junit-mocha-${process.env.TEST_NAME_PATTERN}.xml`,
mochaFile: `reports/junit-mocha-${process.env.MOCHA_GREP}.xml`,
includePending: true,
jenkinsMode: true,
output: true,
+2 -2
View File
@@ -1,4 +1,4 @@
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
chai.use(chaiAsPromised)
@@ -1,652 +0,0 @@
import { expect } from 'chai'
import dns from 'node:dns'
import http from 'node:http'
import { once } from 'node:events'
import events from 'node:events'
import fs from 'node:fs'
import { pipeline } from 'node:stream/promises'
import { Readable } from 'node:stream'
import { describe, beforeAll, beforeEach, afterAll, it } from 'vitest'
import { AbortError, FetchError, Headers } from 'node-fetch'
import selfsigned from 'selfsigned'
import { TestServer } from './helpers/TestServer.js'
import {
fetchJson,
fetchStream,
fetchNothing,
fetchRedirect,
fetchString,
RequestFailedError,
CustomHttpAgent,
CustomHttpsAgent,
} from '../../index.ts'
const HTTP_PORT = 30001
const HTTPS_PORT = 30002
const url = pathname => `http://example.com:${HTTP_PORT}${pathname}`
const httpsUrl = pathname => `https://example.com:${HTTPS_PORT}${pathname}`
const _originalLookup = dns.lookup
// Custom DNS resolver function
dns.lookup = (hostname, options, callback) => {
if (hostname === 'example.com') {
// If the hostname is our test case, return the ip address for the test server
if (options?.all) {
callback(null, [{ address: '127.0.0.1', family: 4 }])
} else {
callback(null, '127.0.0.1', 4)
}
} else {
// Otherwise, use the default lookup
_originalLookup(hostname, options, callback)
}
}
describe('fetch-utils', function () {
let server
let PUBLIC_CERT
beforeAll(async function () {
server = new TestServer()
const attrs = [{ name: 'commonName', value: 'example.com' }]
const pems = await selfsigned.generate(attrs, { days: 365, keySize: 2048 })
const PRIVATE_KEY = pems.private
PUBLIC_CERT = pems.cert
await server.start(HTTP_PORT, HTTPS_PORT, {
key: PRIVATE_KEY,
cert: PUBLIC_CERT,
})
})
beforeEach(function () {
server.lastReq = undefined
})
afterAll(async function () {
await server.stop()
})
describe('fetchJson', function () {
it('parses a JSON response', async function () {
const json = await fetchJson(url('/json/hello'))
expect(json).to.deep.equal({ msg: 'hello' })
})
it('parses JSON in the request', async function () {
const json = await fetchJson(url('/json/add'), {
method: 'POST',
json: { a: 2, b: 3 },
})
expect(json).to.deep.equal({ sum: 5 })
})
it('accepts stringified JSON as body', async function () {
const json = await fetchJson(url('/json/add'), {
method: 'POST',
body: JSON.stringify({ a: 2, b: 3 }),
headers: { 'Content-Type': 'application/json' },
})
expect(json).to.deep.equal({ sum: 5 })
})
it('throws a FetchError when the payload is not JSON', async function () {
await expect(fetchJson(url('/hello'))).to.be.rejectedWith(FetchError)
})
it('aborts the request if JSON parsing fails', async function () {
await expect(fetchJson(url('/large'))).to.be.rejectedWith(FetchError)
await expectRequestAborted(server.lastReq)
})
it('handles errors when the payload is JSON', async function () {
await expect(fetchJson(url('/json/500'))).to.be.rejectedWith(
RequestFailedError
)
await expectRequestAborted(server.lastReq)
})
it('handles errors when the payload is not JSON', async function () {
await expect(fetchJson(url('/500'))).to.be.rejectedWith(
RequestFailedError
)
await expectRequestAborted(server.lastReq)
})
it('supports abort signals', async function () {
await expect(
abortOnceReceived(signal => fetchJson(url('/hang'), { signal }), server)
).to.be.rejectedWith(AbortError)
await expectRequestAborted(server.lastReq)
})
it('supports basic auth', async function () {
const json = await fetchJson(url('/json/basic-auth'), {
basicAuth: { user: 'user', password: 'pass' },
})
expect(json).to.deep.equal({ key: 'verysecret' })
})
it('sets an Authorization header for basic auth', async function () {
await fetchJson(url('/json/basic-auth'), {
basicAuth: { user: 'user', password: 'pass' },
})
expect(server.lastReq.headers.authorization).to.equal(
'Basic ' + Buffer.from('user:pass').toString('base64')
)
})
it("destroys the request body if it doesn't get consumed", async function () {
const stream = Readable.from(infiniteIterator())
await fetchJson(url('/json/ignore-request'), {
method: 'POST',
body: stream,
})
expect(stream.destroyed).to.be.true
})
describe('headers', function () {
it('sets an Accept header of application/json by default', async function () {
await fetchJson(url('/json/hello'))
expect(server.lastReq.headers.accept).to.equal('application/json')
})
it('passes provided headers', async function () {
await fetchJson(url('/json/hello'), {
headers: { 'x-some-value': 'value' },
})
expect(server.lastReq.headers['x-some-value']).to.equal('value')
})
it('respects an explicitly provided Accept header', async function () {
await fetchJson(url('/json/hello'), {
headers: { Accept: 'application/vnd.api+json' },
})
expect(server.lastReq.headers.accept).to.equal(
'application/vnd.api+json'
)
})
it('sets the default Accept header when headers are provided as a Headers instance', async function () {
await fetchJson(url('/json/hello'), {
headers: new Headers({ 'X-Foo': 'bar' }),
})
expect(server.lastReq.headers.accept).to.equal('application/json')
expect(server.lastReq.headers['x-foo']).to.equal('bar')
})
it('sets the default Accept header when headers are provided as an array of tuples', async function () {
await fetchJson(url('/json/hello'), {
headers: [['X-Foo', 'bar']],
})
expect(server.lastReq.headers.accept).to.equal('application/json')
expect(server.lastReq.headers['x-foo']).to.equal('bar')
})
it('treats an unset Accept header as absent and applies the default', async function () {
await fetchJson(url('/json/hello'), {
headers: { Accept: undefined },
})
expect(server.lastReq.headers.accept).to.equal('application/json')
})
it('omits headers with unset values rather than sending "undefined"', async function () {
await fetchJson(url('/json/hello'), {
headers: { 'x-some-value': undefined, 'x-other-value': null },
})
expect(server.lastReq.headers).to.not.have.property('x-some-value')
expect(server.lastReq.headers).to.not.have.property('x-other-value')
})
it('omits headers with unset values provided as an array of tuples', async function () {
await fetchJson(url('/json/hello'), {
headers: [
['X-Foo', 'bar'],
['X-Unset', undefined],
],
})
expect(server.lastReq.headers['x-foo']).to.equal('bar')
expect(server.lastReq.headers).to.not.have.property('x-unset')
})
it('omits headers with unset values provided as a Map', async function () {
await fetchJson(url('/json/hello'), {
headers: new Map([
['X-Foo', 'bar'],
['X-Unset', undefined],
]),
})
expect(server.lastReq.headers['x-foo']).to.equal('bar')
expect(server.lastReq.headers).to.not.have.property('x-unset')
})
it('keeps headers provided as a global Headers instance', async function () {
// Not an instance of node-fetch's Headers: it exposes no own
// enumerable properties to iterate over.
await fetchJson(url('/json/hello'), {
headers: new globalThis.Headers({ 'X-Foo': 'bar' }),
})
expect(server.lastReq.headers['x-foo']).to.equal('bar')
})
it('sets a Content-Type header of application/json when sending a JSON body', async function () {
await fetchJson(url('/json/add'), {
method: 'POST',
json: { a: 2, b: 3 },
})
expect(server.lastReq.headers['content-type']).to.equal(
'application/json'
)
})
})
})
describe('fetchStream', function () {
it('returns a stream', async function () {
const stream = await fetchStream(url('/large'))
const text = await streamToString(stream)
expect(text).to.equal(server.largePayload)
})
it('aborts the request when the stream is destroyed', async function () {
const stream = await fetchStream(url('/large'))
stream.destroy()
await expectRequestAborted(server.lastReq)
})
it('aborts the request when the request body is destroyed before transfer', async function () {
const stream = Readable.from(infiniteIterator())
const promise = fetchStream(url('/hang'), {
method: 'POST',
body: stream,
})
stream.destroy()
await expect(promise).to.be.rejectedWith(AbortError)
await wait(80)
expect(server.lastReq).to.be.undefined
})
it('aborts the request when the request body is destroyed during transfer', async function () {
const stream = Readable.from(infiniteIterator())
// Note: this test won't work on `/hang`
const promise = fetchStream(url('/sink'), {
method: 'POST',
body: stream,
})
await once(server.events, 'request-received')
stream.destroy()
await expect(promise).to.be.rejectedWith(AbortError)
await expectRequestAborted(server.lastReq)
})
it('handles errors', async function () {
await expect(fetchStream(url('/500'))).to.be.rejectedWith(
RequestFailedError
)
await expectRequestAborted(server.lastReq)
})
it('supports abort signals', async function () {
await expect(
abortOnceReceived(
signal => fetchStream(url('/hang'), { signal }),
server
)
).to.be.rejectedWith(AbortError)
await expectRequestAborted(server.lastReq)
})
it('destroys the request body when an error occurs', async function () {
const stream = Readable.from(infiniteIterator())
await expect(
abortOnceReceived(
signal =>
fetchStream(url('/hang'), {
method: 'POST',
body: stream,
signal,
}),
server
)
).to.be.rejectedWith(AbortError)
expect(stream.destroyed).to.be.true
})
it('detaches from signal on success', async function () {
const signal = AbortSignal.timeout(10_000)
for (let i = 0; i < 20; i++) {
const s = await fetchStream(url('/hello'), { signal })
expect(events.getEventListeners(signal, 'abort')).to.have.length(1)
await pipeline(s, fs.createWriteStream('/dev/null'))
expect(events.getEventListeners(signal, 'abort')).to.have.length(0)
}
})
it('detaches from signal on error', async function () {
const signal = AbortSignal.timeout(10_000)
for (let i = 0; i < 20; i++) {
try {
await fetchStream(url('/500'), { signal })
} catch (err) {
if (err instanceof RequestFailedError && err.response.status === 500)
continue
throw err
} finally {
expect(events.getEventListeners(signal, 'abort')).to.have.length(0)
}
}
})
})
describe('fetchNothing', function () {
it('closes the connection', async function () {
await fetchNothing(url('/large'))
await expectRequestAborted(server.lastReq)
})
it('aborts the request when the request body is destroyed before transfer', async function () {
const stream = Readable.from(infiniteIterator())
const promise = fetchNothing(url('/hang'), {
method: 'POST',
body: stream,
})
stream.destroy()
await expect(promise).to.be.rejectedWith(AbortError)
expect(server.lastReq).to.be.undefined
})
it('aborts the request when the request body is destroyed during transfer', async function () {
const stream = Readable.from(infiniteIterator())
// Note: this test won't work on `/hang`
const promise = fetchNothing(url('/sink'), {
method: 'POST',
body: stream,
})
await once(server.events, 'request-received')
stream.destroy()
await expect(promise).to.be.rejectedWith(AbortError)
await wait(80)
await expectRequestAborted(server.lastReq)
})
it("doesn't abort the request if the request body ends normally", async function () {
const stream = Readable.from('hello there')
await fetchNothing(url('/sink'), { method: 'POST', body: stream })
})
it('handles errors', async function () {
await expect(fetchNothing(url('/500'))).to.be.rejectedWith(
RequestFailedError
)
await expectRequestAborted(server.lastReq)
})
it('supports abort signals', async function () {
await expect(
abortOnceReceived(
signal => fetchNothing(url('/hang'), { signal }),
server
)
).to.be.rejectedWith(AbortError)
await expectRequestAborted(server.lastReq)
})
it('destroys the request body when an error occurs', async function () {
const stream = Readable.from(infiniteIterator())
await expect(
abortOnceReceived(
signal =>
fetchNothing(url('/hang'), {
method: 'POST',
body: stream,
signal,
}),
server
)
).to.be.rejectedWith(AbortError)
expect(stream.destroyed).to.be.true
})
})
describe('RequestFailedError', function () {
it('includes the response body in OError.info for a 400', async function () {
const err = await getRejection(fetchNothing(url('/400')))
expect(err.info).to.have.property('body', 'boom-400')
})
it('includes the response body in OError.info for a 409', async function () {
const err = await getRejection(fetchNothing(url('/409')))
expect(err.info).to.have.property('body', 'boom-409')
})
it('includes the response body in OError.info for a 413', async function () {
const err = await getRejection(fetchNothing(url('/413')))
expect(err.info).to.have.property('body', 'boom-413')
})
it('includes the response body in OError.info for a 422', async function () {
const err = await getRejection(fetchNothing(url('/422')))
expect(err.info).to.have.property('body', 'boom-422')
})
it('omits the response body from OError.info for a 500', async function () {
const err = await getRejection(fetchNothing(url('/500')))
expect(err.body).to.equal('Internal Server Error')
expect(err.info).to.not.have.property('body')
})
})
describe('fetchString', function () {
it('returns a string', async function () {
const body = await fetchString(url('/hello'))
expect(body).to.equal('hello')
})
it('handles errors', async function () {
await expect(fetchString(url('/500'))).to.be.rejectedWith(
RequestFailedError
)
await expectRequestAborted(server.lastReq)
})
})
describe('fetchRedirect', function () {
it('returns the immediate redirect', async function () {
const body = await fetchRedirect(url('/redirect/1'))
expect(body).to.equal(url('/redirect/2'))
})
it('rejects status 200', async function () {
await expect(fetchRedirect(url('/hello'))).to.be.rejectedWith(
RequestFailedError
)
await expectRequestAborted(server.lastReq)
})
it('rejects empty redirect', async function () {
await expect(fetchRedirect(url('/redirect/empty-location')))
.to.be.rejectedWith(RequestFailedError)
.and.eventually.have.property('cause')
.and.to.have.property('message')
.to.equal('missing Location response header on 3xx response')
await expectRequestAborted(server.lastReq)
})
it('handles errors', async function () {
await expect(fetchRedirect(url('/500'))).to.be.rejectedWith(
RequestFailedError
)
await expectRequestAborted(server.lastReq)
})
})
describe('CustomHttpAgent', function () {
it('makes an http request successfully', async function () {
const agent = new CustomHttpAgent({ connectTimeout: 100 })
const body = await fetchString(url('/hello'), { agent })
expect(body).to.equal('hello')
})
it('times out when accessing a non-routable address', async function () {
const agent = new CustomHttpAgent({ connectTimeout: 10 })
await expect(fetchString('http://10.255.255.255/', { agent }))
.to.be.rejectedWith(FetchError)
.and.eventually.have.property('message')
.and.to.equal(
'request to http://10.255.255.255/ failed, reason: connect timeout'
)
})
it('retries after a delay', { timeout: 5_000 }, async function () {
// The test should finish after 1.5s.
// t 0ms: first connect fails with ECONNREFUSED
// t 500ms: listen on port
// t1000ms: retry to connect again, works
// t1500ms: respond to request
const agent = new CustomHttpAgent({
connectTimeout: 100,
connectRetryInterval: 1_000,
})
const server = http.createServer((req, res) => {
setTimeout(() => {
res.write('hello')
res.end()
server.close()
}, 500)
})
// Grab a dynamic port, then close again so that the first connect
// attempt is refused before the server starts listening for real.
await once(server.listen(0), 'listening')
const { port } = server.address()
await new Promise(resolve => server.close(resolve))
const t0 = performance.now()
setTimeout(() => {
server.listen(port)
}, 500)
const body = await fetchString(`http://127.0.0.1:${port}`, { agent })
expect(body).to.equal('hello')
const t1 = performance.now()
expect(t1 - t0).to.be.at.least(1_500)
})
it('does not open a stray connection when the socket errors after connect', async function () {
const agent = new CustomHttpAgent({
connectTimeout: 100,
connectRetryInterval: 10,
})
const connections = []
const server = http.createServer(req => {
// Reset the established connection before responding. Doing this in
// the request handler guarantees the client finished the connect
// phase, so the ECONNRESET arrives after 'connect' has fired.
req.socket.resetAndDestroy()
})
server.on('connection', socket => connections.push(socket))
await once(server.listen(0), 'listening')
const { port } = server.address()
try {
await expect(
fetchString(`http://127.0.0.1:${port}/`, { agent })
).to.be.rejectedWith(FetchError)
// Leave time for a buggy connect retry to open a stray connection.
await wait(200)
expect(connections).to.have.length(1)
} finally {
for (const socket of connections) socket.destroy()
server.close()
}
})
})
describe('CustomHttpsAgent', function () {
it('makes an https request successfully', async function () {
const agent = new CustomHttpsAgent({
connectTimeout: 100,
ca: PUBLIC_CERT,
})
const body = await fetchString(httpsUrl('/hello'), { agent })
expect(body).to.equal('hello')
})
it('rejects an untrusted server', async function () {
const agent = new CustomHttpsAgent({
connectTimeout: 100,
})
await expect(fetchString(httpsUrl('/hello'), { agent }))
.to.be.rejectedWith(FetchError)
.and.eventually.have.property('code')
.and.to.equal('DEPTH_ZERO_SELF_SIGNED_CERT')
})
it('times out when accessing a non-routable address', async function () {
const agent = new CustomHttpsAgent({ connectTimeout: 10 })
await expect(fetchString('https://10.255.255.255/', { agent }))
.to.be.rejectedWith(FetchError)
.and.eventually.have.property('message')
.and.to.equal(
'request to https://10.255.255.255/ failed, reason: connect timeout'
)
})
})
})
async function streamToString(stream) {
let s = ''
for await (const chunk of stream) {
s += chunk
}
return s
}
async function* infiniteIterator() {
let i = 1
while (true) {
yield `chunk ${i++}\n`
}
}
/**
* @param {(signal: AbortSignal) => Promise<any>} func
* @param {TestServer} server
*/
async function abortOnceReceived(func, server) {
const controller = new AbortController()
const promise = func(controller.signal)
expect(events.getEventListeners(controller.signal, 'abort')).to.have.length(1)
await once(server.events, 'request-received')
controller.abort()
try {
return await promise
} finally {
expect(events.getEventListeners(controller.signal, 'abort')).to.have.length(
0
)
}
}
async function expectRequestAborted(req) {
if (!req.destroyed) {
try {
await once(req, 'close')
} catch (err) {
// `once` throws if req emits an 'error' event.
// We ignore `Error: aborted` when the request is aborted.
if (err.message !== 'aborted') {
throw err
}
}
}
expect(req.destroyed).to.be.true
}
const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
async function getRejection(promise) {
try {
await promise
} catch (err) {
return err
}
expect.fail('expected promise to reject')
}
@@ -0,0 +1,449 @@
const { expect } = require('chai')
const fs = require('node:fs')
const events = require('node:events')
const { FetchError, AbortError } = require('node-fetch')
const { Readable } = require('node:stream')
const { pipeline } = require('node:stream/promises')
const { once } = require('node:events')
const { TestServer } = require('./helpers/TestServer')
const selfsigned = require('selfsigned')
const {
fetchJson,
fetchStream,
fetchNothing,
fetchRedirect,
fetchString,
RequestFailedError,
CustomHttpAgent,
CustomHttpsAgent,
} = require('../..')
const HTTP_PORT = 30001
const HTTPS_PORT = 30002
const attrs = [{ name: 'commonName', value: 'example.com' }]
const pems = selfsigned.generate(attrs, { days: 365 })
const PRIVATE_KEY = pems.private
const PUBLIC_CERT = pems.cert
const dns = require('node:dns')
const _originalLookup = dns.lookup
// Custom DNS resolver function
dns.lookup = (hostname, options, callback) => {
if (hostname === 'example.com') {
// If the hostname is our test case, return the ip address for the test server
if (options?.all) {
callback(null, [{ address: '127.0.0.1', family: 4 }])
} else {
callback(null, '127.0.0.1', 4)
}
} else {
// Otherwise, use the default lookup
_originalLookup(hostname, options, callback)
}
}
describe('fetch-utils', function () {
before(async function () {
this.server = new TestServer()
await this.server.start(HTTP_PORT, HTTPS_PORT, {
key: PRIVATE_KEY,
cert: PUBLIC_CERT,
})
this.url = path => `http://example.com:${HTTP_PORT}${path}`
this.httpsUrl = path => `https://example.com:${HTTPS_PORT}${path}`
})
beforeEach(function () {
this.server.lastReq = undefined
})
after(async function () {
await this.server.stop()
})
describe('fetchJson', function () {
it('parses a JSON response', async function () {
const json = await fetchJson(this.url('/json/hello'))
expect(json).to.deep.equal({ msg: 'hello' })
})
it('parses JSON in the request', async function () {
const json = await fetchJson(this.url('/json/add'), {
method: 'POST',
json: { a: 2, b: 3 },
})
expect(json).to.deep.equal({ sum: 5 })
})
it('accepts stringified JSON as body', async function () {
const json = await fetchJson(this.url('/json/add'), {
method: 'POST',
body: JSON.stringify({ a: 2, b: 3 }),
headers: { 'Content-Type': 'application/json' },
})
expect(json).to.deep.equal({ sum: 5 })
})
it('throws a FetchError when the payload is not JSON', async function () {
await expect(fetchJson(this.url('/hello'))).to.be.rejectedWith(FetchError)
})
it('aborts the request if JSON parsing fails', async function () {
await expect(fetchJson(this.url('/large'))).to.be.rejectedWith(FetchError)
await expectRequestAborted(this.server.lastReq)
})
it('handles errors when the payload is JSON', async function () {
await expect(fetchJson(this.url('/json/500'))).to.be.rejectedWith(
RequestFailedError
)
await expectRequestAborted(this.server.lastReq)
})
it('handles errors when the payload is not JSON', async function () {
await expect(fetchJson(this.url('/500'))).to.be.rejectedWith(
RequestFailedError
)
await expectRequestAborted(this.server.lastReq)
})
it('supports abort signals', async function () {
await expect(
abortOnceReceived(
signal => fetchJson(this.url('/hang'), { signal }),
this.server
)
).to.be.rejectedWith(AbortError)
await expectRequestAborted(this.server.lastReq)
})
it('supports basic auth', async function () {
const json = await fetchJson(this.url('/json/basic-auth'), {
basicAuth: { user: 'user', password: 'pass' },
})
expect(json).to.deep.equal({ key: 'verysecret' })
})
it("destroys the request body if it doesn't get consumed", async function () {
const stream = Readable.from(infiniteIterator())
await fetchJson(this.url('/json/ignore-request'), {
method: 'POST',
body: stream,
})
expect(stream.destroyed).to.be.true
})
})
describe('fetchStream', function () {
it('returns a stream', async function () {
const stream = await fetchStream(this.url('/large'))
const text = await streamToString(stream)
expect(text).to.equal(this.server.largePayload)
})
it('aborts the request when the stream is destroyed', async function () {
const stream = await fetchStream(this.url('/large'))
stream.destroy()
await expectRequestAborted(this.server.lastReq)
})
it('aborts the request when the request body is destroyed before transfer', async function () {
const stream = Readable.from(infiniteIterator())
const promise = fetchStream(this.url('/hang'), {
method: 'POST',
body: stream,
})
stream.destroy()
await expect(promise).to.be.rejectedWith(AbortError)
await wait(80)
expect(this.server.lastReq).to.be.undefined
})
it('aborts the request when the request body is destroyed during transfer', async function () {
const stream = Readable.from(infiniteIterator())
// Note: this test won't work on `/hang`
const promise = fetchStream(this.url('/sink'), {
method: 'POST',
body: stream,
})
await once(this.server.events, 'request-received')
stream.destroy()
await expect(promise).to.be.rejectedWith(AbortError)
await expectRequestAborted(this.server.lastReq)
})
it('handles errors', async function () {
await expect(fetchStream(this.url('/500'))).to.be.rejectedWith(
RequestFailedError
)
await expectRequestAborted(this.server.lastReq)
})
it('supports abort signals', async function () {
await expect(
abortOnceReceived(
signal => fetchStream(this.url('/hang'), { signal }),
this.server
)
).to.be.rejectedWith(AbortError)
await expectRequestAborted(this.server.lastReq)
})
it('destroys the request body when an error occurs', async function () {
const stream = Readable.from(infiniteIterator())
await expect(
abortOnceReceived(
signal =>
fetchStream(this.url('/hang'), {
method: 'POST',
body: stream,
signal,
}),
this.server
)
).to.be.rejectedWith(AbortError)
expect(stream.destroyed).to.be.true
})
it('detaches from signal on success', async function () {
const signal = AbortSignal.timeout(10_000)
for (let i = 0; i < 20; i++) {
const s = await fetchStream(this.url('/hello'), { signal })
expect(events.getEventListeners(signal, 'abort')).to.have.length(1)
await pipeline(s, fs.createWriteStream('/dev/null'))
expect(events.getEventListeners(signal, 'abort')).to.have.length(0)
}
})
it('detaches from signal on error', async function () {
const signal = AbortSignal.timeout(10_000)
for (let i = 0; i < 20; i++) {
try {
await fetchStream(this.url('/500'), { signal })
} catch (err) {
if (err instanceof RequestFailedError && err.response.status === 500)
continue
throw err
} finally {
expect(events.getEventListeners(signal, 'abort')).to.have.length(0)
}
}
})
})
describe('fetchNothing', function () {
it('closes the connection', async function () {
await fetchNothing(this.url('/large'))
await expectRequestAborted(this.server.lastReq)
})
it('aborts the request when the request body is destroyed before transfer', async function () {
const stream = Readable.from(infiniteIterator())
const promise = fetchNothing(this.url('/hang'), {
method: 'POST',
body: stream,
})
stream.destroy()
await expect(promise).to.be.rejectedWith(AbortError)
expect(this.server.lastReq).to.be.undefined
})
it('aborts the request when the request body is destroyed during transfer', async function () {
const stream = Readable.from(infiniteIterator())
// Note: this test won't work on `/hang`
const promise = fetchNothing(this.url('/sink'), {
method: 'POST',
body: stream,
})
await once(this.server.events, 'request-received')
stream.destroy()
await expect(promise).to.be.rejectedWith(AbortError)
await wait(80)
await expectRequestAborted(this.server.lastReq)
})
it("doesn't abort the request if the request body ends normally", async function () {
const stream = Readable.from('hello there')
await fetchNothing(this.url('/sink'), { method: 'POST', body: stream })
})
it('handles errors', async function () {
await expect(fetchNothing(this.url('/500'))).to.be.rejectedWith(
RequestFailedError
)
await expectRequestAborted(this.server.lastReq)
})
it('supports abort signals', async function () {
await expect(
abortOnceReceived(
signal => fetchNothing(this.url('/hang'), { signal }),
this.server
)
).to.be.rejectedWith(AbortError)
await expectRequestAborted(this.server.lastReq)
})
it('destroys the request body when an error occurs', async function () {
const stream = Readable.from(infiniteIterator())
await expect(
abortOnceReceived(
signal =>
fetchNothing(this.url('/hang'), {
method: 'POST',
body: stream,
signal,
}),
this.server
)
).to.be.rejectedWith(AbortError)
expect(stream.destroyed).to.be.true
})
})
describe('fetchString', function () {
it('returns a string', async function () {
const body = await fetchString(this.url('/hello'))
expect(body).to.equal('hello')
})
it('handles errors', async function () {
await expect(fetchString(this.url('/500'))).to.be.rejectedWith(
RequestFailedError
)
await expectRequestAborted(this.server.lastReq)
})
})
describe('fetchRedirect', function () {
it('returns the immediate redirect', async function () {
const body = await fetchRedirect(this.url('/redirect/1'))
expect(body).to.equal(this.url('/redirect/2'))
})
it('rejects status 200', async function () {
await expect(fetchRedirect(this.url('/hello'))).to.be.rejectedWith(
RequestFailedError
)
await expectRequestAborted(this.server.lastReq)
})
it('rejects empty redirect', async function () {
await expect(fetchRedirect(this.url('/redirect/empty-location')))
.to.be.rejectedWith(RequestFailedError)
.and.eventually.have.property('cause')
.and.to.have.property('message')
.to.equal('missing Location response header on 3xx response')
await expectRequestAborted(this.server.lastReq)
})
it('handles errors', async function () {
await expect(fetchRedirect(this.url('/500'))).to.be.rejectedWith(
RequestFailedError
)
await expectRequestAborted(this.server.lastReq)
})
})
describe('CustomHttpAgent', function () {
it('makes an http request successfully', async function () {
const agent = new CustomHttpAgent({ connectTimeout: 100 })
const body = await fetchString(this.url('/hello'), { agent })
expect(body).to.equal('hello')
})
it('times out when accessing a non-routable address', async function () {
const agent = new CustomHttpAgent({ connectTimeout: 10 })
await expect(fetchString('http://10.255.255.255/', { agent }))
.to.be.rejectedWith(FetchError)
.and.eventually.have.property('message')
.and.to.equal(
'request to http://10.255.255.255/ failed, reason: connect timeout'
)
})
})
describe('CustomHttpsAgent', function () {
it('makes an https request successfully', async function () {
const agent = new CustomHttpsAgent({
connectTimeout: 100,
ca: PUBLIC_CERT,
})
const body = await fetchString(this.httpsUrl('/hello'), { agent })
expect(body).to.equal('hello')
})
it('rejects an untrusted server', async function () {
const agent = new CustomHttpsAgent({
connectTimeout: 100,
})
await expect(fetchString(this.httpsUrl('/hello'), { agent }))
.to.be.rejectedWith(FetchError)
.and.eventually.have.property('code')
.and.to.equal('DEPTH_ZERO_SELF_SIGNED_CERT')
})
it('times out when accessing a non-routable address', async function () {
const agent = new CustomHttpsAgent({ connectTimeout: 10 })
await expect(fetchString('https://10.255.255.255/', { agent }))
.to.be.rejectedWith(FetchError)
.and.eventually.have.property('message')
.and.to.equal(
'request to https://10.255.255.255/ failed, reason: connect timeout'
)
})
})
})
async function streamToString(stream) {
let s = ''
for await (const chunk of stream) {
s += chunk
}
return s
}
async function* infiniteIterator() {
let i = 1
while (true) {
yield `chunk ${i++}\n`
}
}
/**
* @param {(signal: AbortSignal) => Promise<any>} func
* @param {TestServer} server
*/
async function abortOnceReceived(func, server) {
const controller = new AbortController()
const promise = func(controller.signal)
expect(events.getEventListeners(controller.signal, 'abort')).to.have.length(1)
await once(server.events, 'request-received')
controller.abort()
try {
return await promise
} finally {
expect(events.getEventListeners(controller.signal, 'abort')).to.have.length(
0
)
}
}
async function expectRequestAborted(req) {
if (!req.destroyed) {
try {
await once(req, 'close')
} catch (err) {
// `once` throws if req emits an 'error' event.
// We ignore `Error: aborted` when the request is aborted.
if (err.message !== 'aborted') {
throw err
}
}
}
expect(req.destroyed).to.be.true
}
const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
@@ -1,15 +1,16 @@
import express from 'express'
import { EventEmitter } from 'node:events'
import http from 'node:http'
import https from 'node:https'
import { promisify } from 'node:util'
const express = require('express')
const bodyParser = require('body-parser')
const { EventEmitter } = require('node:events')
const http = require('node:http')
const https = require('node:https')
const { promisify } = require('node:util')
class TestServer {
constructor() {
this.app = express()
this.events = new EventEmitter()
this.app.use(express.json())
this.app.use(bodyParser.json())
this.app.use((req, res, next) => {
this.events.emit('request-received')
this.lastReq = req
@@ -39,22 +40,6 @@ class TestServer {
res.sendStatus(500)
})
this.app.get('/400', (req, res) => {
res.status(400).send('boom-400')
})
this.app.get('/409', (req, res) => {
res.status(409).send('boom-409')
})
this.app.get('/413', (req, res) => {
res.status(413).send('boom-413')
})
this.app.get('/422', (req, res) => {
res.status(422).send('boom-422')
})
this.app.post('/sink', (req, res) => {
req.on('data', () => {})
req.on('end', () => {
@@ -134,21 +119,12 @@ class TestServer {
}
stop() {
const promises = []
if (this.server) {
const stopHttp = promisify(this.server.close).bind(this.server)
this.server.closeAllConnections()
promises.push(stopHttp())
}
if (this.https_server) {
const stopHttps = promisify(this.https_server.close).bind(
this.https_server
)
this.https_server.closeAllConnections()
promises.push(stopHttps())
}
return Promise.all(promises)
const stopHttp = promisify(this.server.close).bind(this.server)
const stopHttps = promisify(this.https_server.close).bind(this.https_server)
this.server.closeAllConnections()
this.https_server.closeAllConnections()
return Promise.all([stopHttp(), stopHttps()])
}
}
export { TestServer }
module.exports = { TestServer }
+5 -4
View File
@@ -1,7 +1,8 @@
{
"extends": "../../tsconfig.backend.json",
"compilerOptions": {
"noImplicitAny": true
},
"include": ["**/*.js", "**/*.cjs", "**/*.ts"]
"include": [
"**/*.js",
"**/*.cjs",
"**/*.ts"
]
}
-25
View File
@@ -1,25 +0,0 @@
import { defineConfig, ViteUserConfig } from 'vitest/config'
let reporterOptions: ViteUserConfig['test'] = {}
if (process.env.CI) {
reporterOptions = {
reporters: [
'default',
[
'junit',
{
classnameTemplate: `Unit tests.{filename}`,
},
],
],
outputFile: 'reports/junit-vitest-unit.xml',
}
}
export default defineConfig({
test: {
include: ['test/unit/**/*.test.{js,ts}'],
setupFiles: ['./test/setup.js'],
isolate: false,
...reporterOptions,
},
})
+1 -1
View File
@@ -1,7 +1,7 @@
let reporterOptions = {}
if (process.env.CI) {
reporterOptions = {
reporter: require.resolve('mocha-multi-reporters'),
reporter: '/overleaf/node_modules/mocha-multi-reporters',
'reporter-options': ['configFile=./test/mocha-multi-reporters.cjs'],
}
}
+1
View File
@@ -0,0 +1 @@
22.18.0
+3 -2
View File
@@ -1,9 +1,10 @@
## v3.1.1
- Handle malformed requests in the req serializer
* Handle malformed requests in the req serializer
## v3.0.0
- Improve logging in Google Cloud Platform. Set environment variable `GCP_LOGGING=true` to enable.
* Improve logging in Google Cloud Platform. Set environment variable `GCP_LOGGING=true` to enable.
This version of the metrics module only works with versions of the `@overleaf/metrics` module greater than v4.0.0
+9
View File
@@ -0,0 +1,9 @@
logger
--dependencies=None
--env-add=
--env-pass-through=
--esmock-loader=False
--is-library=True
--node-version=22.18.0
--pipeline-owner=🚉 Platform
--public-repo=False
-47
View File
@@ -1,5 +1,4 @@
const Stream = require('node:stream')
const { setTimeout } = require('node:timers/promises')
const bunyan = require('bunyan')
const GCPManager = require('./gcp-manager')
const Serializers = require('./serializers')
@@ -7,23 +6,8 @@ const {
FileLogLevelChecker,
GCEMetadataLogLevelChecker,
} = require('./log-level-checker')
const { setLogger } = require('@overleaf/fetch-utils')
const {
setLogger: setValidationToolsLogger,
} = require('@overleaf/validation-tools')
// Delay (ms) before exiting to allow final logs to be flushed.
const EXIT_DELAY = 500
const LoggingManager = {
/**
* The serializers registered by addSerializer, kept here rather than only on
* the logger so that they survive a later initialize() call. A module that
* registers one as it is imported would otherwise lose it, since a service
* initializes its logger after its imports have run.
*/
customSerializers: {},
/**
* @param {string} name - The name of the logger
*/
@@ -42,35 +26,14 @@ const LoggingManager = {
error: Serializers.err,
req: Serializers.req,
res: Serializers.res,
...this.customSerializers,
},
streams: options.streams ?? [this._getOutputStreamConfig()],
})
this._setupRingBuffer()
this._setupLogLevelChecker()
setLogger(this)
setValidationToolsLogger(this)
return this
},
/**
* Register a serializer, which decides what gets recorded for a named log
* field, e.g. `logger.error({ dropboxResponseError: err }, '...')`. Callers
* add their own on top of the ones initialize() sets up, and keep them across
* a later initialize(), so registering one as a module is imported works.
*
* A serializer takes whatever was logged under that field, so it receives an
* unknown and narrows it itself, and returns the value to record in its
* place, which is only ever JSON encoded.
*
* @param {string} name - the log field the serializer applies to
* @param {(value: unknown) => unknown} serializer
*/
addSerializer(name, serializer) {
this.customSerializers[name] = serializer
this.logger.serializers[name] = serializer
},
/**
* @param {Record<string, any>|string} attributes - Attributes to log (nice serialization for err, req, res)
* @param {string} [message] - Optional message
@@ -131,16 +94,6 @@ const LoggingManager = {
this.logger.fatal(attributes, message)
},
/**
* Exit after a delay to ensure that log messages are flushed
* @param {number} code
*/
async exit(code) {
await setTimeout(EXIT_DELAY)
process.exit(code)
},
_getOutputStreamConfig() {
switch (process.env.LOGGING_FORMAT) {
case 'gke': {
+9 -14
View File
@@ -7,31 +7,26 @@
"url": "https://github.com/overleaf/overleaf"
},
"main": "index.js",
"exports": {
".": "./index.js",
"./*": "./*"
},
"license": "AGPL-3.0-only",
"version": "3.1.1",
"scripts": {
"test": "yarn run lint && yarn run types:check && yarn run test:unit",
"lint": "eslint --cache --cache-location ../../.cache/eslint/ --ext .cjs,.js,.jsx,.mjs,.ts --max-warnings 0 .",
"lint:fix": "eslint --cache --cache-location ../../.cache/eslint/ --fix --ext .cjs,.js,.jsx,.mjs,.ts .",
"test:ci": "yarn run test:unit",
"test": "npm run lint && npm run format && npm run types:check && npm run test:unit",
"format": "prettier --list-different $PWD/'**/*.{js,cjs,ts}'",
"format:fix": "prettier --write $PWD/'**/*.{js,cjs,ts}'",
"lint": "eslint --ext .cjs,.js,.jsx,.mjs,.ts --max-warnings 0 --format unix .",
"lint:fix": "eslint --fix --ext .cjs,.js,.jsx,.mjs,.ts .",
"test:ci": "npm run test:unit",
"test:unit": "mocha --exit test/**/*.{js,cjs}",
"types:check": "tsc --noEmit"
},
"dependencies": {
"@google-cloud/logging-bunyan": "^5.1.0",
"@overleaf/fetch-utils": "workspace:*",
"@overleaf/o-error": "workspace:*",
"@overleaf/validation-tools": "workspace:*",
"@overleaf/fetch-utils": "*",
"@overleaf/o-error": "*",
"bunyan": "^1.8.14"
},
"devDependencies": {
"@types/node": "^24.5.2",
"chai": "^4.3.6",
"eslint": "^10.4.0",
"mocha": "^11.1.0",
"mocha-junit-reporter": "^2.2.1",
"mocha-multi-reporters": "^1.5.1",
@@ -41,6 +36,6 @@
"typescript": "^5.0.4"
},
"peerDependencies": {
"@overleaf/metrics": "workspace:*"
"@overleaf/metrics": "*"
}
}
+6 -15
View File
@@ -1,5 +1,4 @@
const OError = require('@overleaf/o-error')
const { getRawReqInput } = require('@overleaf/validation-tools')
function errSerializer(err) {
if (!err) {
@@ -37,14 +36,11 @@ function reqSerializer(req) {
'content-length': headers['content-length'],
},
}
// raw access justified: case 2 (final error-handler logging) — this
// serializer must not throw while extracting log context, and bunyan
// silently drops the whole `req` field (with a stderr warning) if it did
const { params } = getRawReqInput(req)
if (params) {
const projectId = params.projectId || params.project_id || params.Project_id
const userId = params.userId || params.user_id
const docId = params.docId || params.doc_id
if (req.params) {
const projectId =
req.params.projectId || req.params.project_id || req.params.Project_id
const userId = req.params.userId || req.params.user_id
const docId = req.params.docId || req.params.doc_id
if (projectId) {
entry.projectId = projectId
}
@@ -84,9 +80,4 @@ function getRemoteIp(req) {
return null
}
module.exports = {
err: errSerializer,
error: errSerializer,
req: reqSerializer,
res: resSerializer,
}
module.exports = { err: errSerializer, req: reqSerializer, res: resSerializer }
+1 -1
View File
@@ -11,7 +11,7 @@ function testLogRecorder() {
if (name in entry) entry[name] = fn(entry[name])
}
currentTest.consoleErrors = (currentTest.consoleErrors || []).concat(
JSON.stringify(entry, bunyan.safeCycles())
JSON.stringify(info, bunyan.safeCycles())
)
}
}
@@ -1,7 +1,7 @@
module.exports = {
reporterEnabled: 'spec, mocha-junit-reporter',
mochaJunitReporterReporterOptions: {
mochaFile: `reports/junit-mocha-${process.env.TEST_NAME_PATTERN}.xml`,
mochaFile: `reports/junit-mocha-${process.env.MOCHA_GREP}.xml`,
includePending: true,
jenkinsMode: true,
output: true,
-5
View File
@@ -7,11 +7,6 @@ chai.should()
chai.use(sinonChai)
SandboxedModule.configure({
requires: {
// pulls in mongodb (via zod ObjectId helpers), which does not compile in
// the sandbox (missing TextEncoder)
'@overleaf/validation-tools': require('@overleaf/validation-tools'),
},
globals: { Buffer, JSON, console, process },
sourceTransformers: {
removeNodePrefix: function (source) {
@@ -17,7 +17,6 @@ describe('LoggingManager', function () {
info: sinon.stub(),
level: sinon.stub(),
warn: sinon.stub(),
serializers: {},
}
this.Bunyan = {
createLogger: sinon.stub().returns(this.bunyanLogger),
@@ -44,17 +43,9 @@ describe('LoggingManager', function () {
.stub()
.returns(this.GCEMetadataLogLevelChecker),
}
this.fetchUtils = {
setLogger: sinon.stub(),
}
this.validationTools = {
setLogger: sinon.stub(),
}
this.LoggingManager = SandboxedModule.require(MODULE_PATH, {
requires: {
bunyan: this.Bunyan,
'@overleaf/fetch-utils': this.fetchUtils,
'@overleaf/validation-tools': this.validationTools,
'./log-level-checker': this.LogLevelChecker,
},
})
@@ -127,37 +118,6 @@ describe('LoggingManager', function () {
})
})
describe('addSerializer', function () {
beforeEach(function () {
this.serializer = sinon.stub()
})
it('registers the serializer on the current logger', function () {
this.LoggingManager.addSerializer('custom', this.serializer)
expect(this.bunyanLogger.serializers.custom).to.equal(this.serializer)
})
it('keeps the serializer through a later initialize', function () {
// A module registering a serializer as it is imported does so before the
// service initializes its own logger, which replaces the bunyan instance.
this.LoggingManager.addSerializer('custom', this.serializer)
this.Bunyan.createLogger.reset()
this.LoggingManager.initialize(this.loggerName)
expect(
this.Bunyan.createLogger.firstCall.args[0].serializers.custom
).to.equal(this.serializer)
})
it('keeps the serializers initialize sets up', function () {
this.LoggingManager.addSerializer('custom', this.serializer)
this.Bunyan.createLogger.reset()
this.LoggingManager.initialize(this.loggerName)
expect(
this.Bunyan.createLogger.firstCall.args[0].serializers
).to.include.keys('err', 'error', 'req', 'res')
})
})
describe('bunyan logging', function () {
beforeEach(function () {
this.logArgs = [{ foo: 'bar' }, 'foo', 'bar']

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