code
stringlengths 14
2.05k
| label
int64 0
1
| programming_language
stringclasses 7
values | cwe_id
stringlengths 6
14
| cwe_name
stringlengths 5
98
⌀ | description
stringlengths 36
379
⌀ | url
stringlengths 36
48
⌀ | label_name
stringclasses 2
values |
---|---|---|---|---|---|---|---|
{ preValidation: authenticator.authenticate(strategyName, { authInfo: false }) },
async (request, reply) => {
await request.logout()
void reply.send('logged out')
}
)
} | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
return this.success({ namespace, id: String(counter++) })
}
this.fail()
} | 1 | TypeScript | CWE-352 | Cross-Site Request Forgery (CSRF) | The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. | https://cwe.mitre.org/data/definitions/352.html | safe |
export function deepMerge<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S> {
if (!sources.length)
return target as any
const source = sources.shift()
if (source === undefined)
return target as any
if (isMergableObject(target) && isMergableObject(source)) {
objectKeys(source).forEach((key) => {
if (key === '__proto__' || key === 'constructor' || key === 'prototype')
return
// @ts-expect-error
if (isMergableObject(source[key])) {
// @ts-expect-error
if (!target[key])
// @ts-expect-error
target[key] = {}
// @ts-expect-error
deepMerge(target[key], source[key])
}
else {
// @ts-expect-error
target[key] = source[key]
}
})
}
return deepMerge(target, ...sources)
} | 1 | TypeScript | CWE-1321 | Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution') | The product receives input from an upstream component that specifies attributes that are to be initialized or updated in an object, but it does not properly control modifications of attributes of the object prototype. | https://cwe.mitre.org/data/definitions/1321.html | safe |
expect(html).toContain(`Topic: ${escapeHtml(topic)}`);
}); | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
constructor(username: string, password: string, allowCrossOriginAuthentication?: boolean) {
this.username = username;
this.password = password;
this.allowCrossOriginAuthentication = allowCrossOriginAuthentication;
} | 1 | TypeScript | CWE-522 | Insufficiently Protected Credentials | The product transmits or stores authentication credentials, but it uses an insecure method that is susceptible to unauthorized interception and/or retrieval. | https://cwe.mitre.org/data/definitions/522.html | safe |
constructor(token: string, allowCrossOriginAuthentication?: boolean) {
this.token = token;
this.allowCrossOriginAuthentication = allowCrossOriginAuthentication;
} | 1 | TypeScript | CWE-522 | Insufficiently Protected Credentials | The product transmits or stores authentication credentials, but it uses an insecure method that is susceptible to unauthorized interception and/or retrieval. | https://cwe.mitre.org/data/definitions/522.html | safe |
constructor(token: string, allowCrossOriginAuthentication?: boolean) {
this.token = token;
this.allowCrossOriginAuthentication = allowCrossOriginAuthentication;
} | 1 | TypeScript | CWE-522 | Insufficiently Protected Credentials | The product transmits or stores authentication credentials, but it uses an insecure method that is susceptible to unauthorized interception and/or retrieval. | https://cwe.mitre.org/data/definitions/522.html | safe |
function resolveMetadataRecord(owner: object, context: Context, useMetaFromContext: boolean): MetadataRecord
{
// If registry is not to be used, it means that context.metadata is available
if (useMetaFromContext) {
return context.metadata as MetadataRecord;
}
// Obtain record from registry, or create new empty object.
let metadata: MetadataRecord = registry.get(owner) ?? Object.create(null);
// In case that the owner has Symbol.metadata defined (e.g. from base class),
// then merge it current metadata. This ensures that inheritance works as
// intended, whilst a base class still keeping its original metadata.
if (Reflect.has(owner, METADATA)) {
// @ts-expect-error: Owner has Symbol.metadata!
metadata = Object.assign(metadata, owner[METADATA]);
}
return metadata;
} | 1 | TypeScript | CWE-1321 | Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution') | The product receives input from an upstream component that specifies attributes that are to be initialized or updated in an object, but it does not properly control modifications of attributes of the object prototype. | https://cwe.mitre.org/data/definitions/1321.html | safe |
public handleUpgrade(
req: IncomingMessage,
socket: Duplex,
upgradeHead: Buffer
) {
this.prepare(req);
const res = new WebSocketResponse(req, socket);
const callback = (errorCode, errorContext) => {
if (errorCode !== undefined) {
this.emit("connection_error", {
req,
code: errorCode,
message: Server.errorMessages[errorCode],
context: errorContext,
});
abortUpgrade(socket, errorCode, errorContext);
return;
}
const head = Buffer.from(upgradeHead);
upgradeHead = null;
// some middlewares (like express-session) wait for the writeHead() call to flush their headers
// see https://github.com/expressjs/session/blob/1010fadc2f071ddf2add94235d72224cf65159c6/index.js#L220-L244
res.writeHead();
// delegate to ws
this.ws.handleUpgrade(req, socket, head, (websocket) => {
this.onWebSocket(req, socket, websocket);
});
};
this._applyMiddlewares(req, res as unknown as ServerResponse, (err) => {
if (err) {
callback(Server.errors.BAD_REQUEST, { name: "MIDDLEWARE_FAILURE" });
} else {
this.verify(req, true, callback);
}
});
} | 1 | TypeScript | CWE-248 | Uncaught Exception | An exception is thrown from a function, but it is not caught. | https://cwe.mitre.org/data/definitions/248.html | safe |
const callback = (errorCode, errorContext) => {
if (errorCode !== undefined) {
this.emit("connection_error", {
req,
code: errorCode,
message: Server.errorMessages[errorCode],
context: errorContext,
});
abortUpgrade(socket, errorCode, errorContext);
return;
}
const head = Buffer.from(upgradeHead);
upgradeHead = null;
// some middlewares (like express-session) wait for the writeHead() call to flush their headers
// see https://github.com/expressjs/session/blob/1010fadc2f071ddf2add94235d72224cf65159c6/index.js#L220-L244
res.writeHead();
// delegate to ws
this.ws.handleUpgrade(req, socket, head, (websocket) => {
this.onWebSocket(req, socket, websocket);
});
}; | 1 | TypeScript | CWE-248 | Uncaught Exception | An exception is thrown from a function, but it is not caught. | https://cwe.mitre.org/data/definitions/248.html | safe |
const callback = async (errorCode, errorContext) => {
if (errorCode !== undefined) {
this.emit("connection_error", {
req,
code: errorCode,
message: Server.errorMessages[errorCode],
context: errorContext,
});
this.abortRequest(res, errorCode, errorContext);
return;
}
const id = req._query.sid;
let transport;
if (id) {
const client = this.clients[id];
if (!client) {
debug("upgrade attempt for closed client");
res.close();
} else if (client.upgrading) {
debug("transport has already been trying to upgrade");
res.close();
} else if (client.upgraded) {
debug("transport had already been upgraded");
res.close();
} else {
debug("upgrading existing transport");
transport = this.createTransport(req._query.transport, req);
client.maybeUpgrade(transport);
}
} else {
transport = await this.handshake(
req._query.transport,
req,
(errorCode, errorContext) =>
this.abortRequest(res, errorCode, errorContext)
);
if (!transport) {
return;
}
}
// calling writeStatus() triggers the flushing of any header added in a middleware
req.res.writeStatus("101 Switching Protocols");
res.upgrade(
{
transport,
},
req.getHeader("sec-websocket-key"),
req.getHeader("sec-websocket-protocol"),
req.getHeader("sec-websocket-extensions"),
context
);
}; | 1 | TypeScript | CWE-248 | Uncaught Exception | An exception is thrown from a function, but it is not caught. | https://cwe.mitre.org/data/definitions/248.html | safe |
const rejectPrivateFieldsTransformer = input => mapQuery(input, function (value, key) {
const lowerCaseKey = key.toLowerCase();
if (lowerCaseKey.startsWith('password') || lowerCaseKey.startsWith('email')) {
return;
}
return {
[key]: value
};
}); | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
query(frame) {
const options = {
...frame.options,
mongoTransformer: rejectPrivateFieldsTransformer
};
return models.Author.findPage(options);
} | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
const rejectPrivateFieldsTransformer = input => mapQuery(input, function (value, key) {
let lowerCaseKey = key.toLowerCase();
if (lowerCaseKey.startsWith('authors.password') || lowerCaseKey.startsWith('authors.email')) {
return;
}
return {
[key]: value
};
}); | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
query(frame) {
const options = {
...frame.options,
mongoTransformer: rejectPrivateFieldsTransformer
};
return models.Post.findPage(options);
} | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
const rejectPrivateFieldsTransformer = input => mapQuery(input, function (value, key) {
const lowerCaseKey = key.toLowerCase();
if (lowerCaseKey.startsWith('authors.password') || lowerCaseKey.startsWith('authors.email')) {
return;
}
return {
[key]: value
};
}); | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
query(frame) {
const options = {
...frame.options,
mongoTransformer: rejectPrivateFieldsTransformer
};
return models.Post.findPage(options);
} | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
async setup (props, { attrs }) {
const query = parseQuery(parseURL(url).search)
const urlProps = query.props ? JSON.parse(query.props as string) : {}
const path = resolve(query.path as string)
if (!path.startsWith(devRootDir)) {
throw new Error(`[nuxt] Cannot access path outside of project root directory: \`${path}\`.`)
}
const comp = await import(/* @vite-ignore */ query.path as string).then(r => r.default)
return () => [
h('div', 'Component Test Wrapper for ' + query.path),
h('div', { id: 'nuxt-component-root' }, [
h(comp, { ...attrs, ...props, ...urlProps })
])
]
} | 1 | TypeScript | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. | https://cwe.mitre.org/data/definitions/94.html | safe |
`export const devRootDir = ${ctx.nuxt.options.dev ? JSON.stringify(ctx.nuxt.options.rootDir) : 'null'}`
].join('\n\n')
} | 1 | TypeScript | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. | https://cwe.mitre.org/data/definitions/94.html | safe |
export const replaceUnicodeChar = (inputString: string): string => {
let unicodeChar = "\u202E";
return inputString.split(unicodeChar).join("<�202e>");
}; | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
return function viteServeStaticMiddleware(req, res, next) {
// only serve the file if it's not an html request or ends with `/`
// so that html requests can fallthrough to our html middleware for
// special processing
// also skip internal requests `/@fs/ /@vite-client` etc...
const cleanedUrl = cleanUrl(req.url!)
if (
cleanedUrl[cleanedUrl.length - 1] === '/' ||
path.extname(cleanedUrl) === '.html' ||
isInternalRequest(req.url!)
) {
return next()
}
const url = new URL(req.url!.replace(/^\/+/, '/'), 'http://example.com')
const pathname = decodeURIComponent(url.pathname)
// apply aliases to static requests as well
let redirectedPathname: string | undefined
for (const { find, replacement } of server.config.resolve.alias) {
const matches =
typeof find === 'string'
? pathname.startsWith(find)
: find.test(pathname)
if (matches) {
redirectedPathname = pathname.replace(find, replacement)
break
}
}
if (redirectedPathname) {
// dir is pre-normalized to posix style
if (redirectedPathname.startsWith(dir)) {
redirectedPathname = redirectedPathname.slice(dir.length)
}
}
const resolvedPathname = redirectedPathname || pathname
let fileUrl = path.resolve(dir, removeLeadingSlash(resolvedPathname))
if (
resolvedPathname[resolvedPathname.length - 1] === '/' &&
fileUrl[fileUrl.length - 1] !== '/'
) {
fileUrl = fileUrl + '/'
}
if (!ensureServingAccess(fileUrl, server, res, next)) {
return
}
if (redirectedPathname) {
url.pathname = encodeURIComponent(redirectedPathname)
req.url = url.href.slice(url.origin.length)
}
serve(req, res, next)
} | 1 | TypeScript | CWE-706 | Use of Incorrectly-Resolved Name or Reference | The product uses a name or reference to access a resource, but the name/reference resolves to a resource that is outside of the intended control sphere. | https://cwe.mitre.org/data/definitions/706.html | safe |
return function viteServeRawFsMiddleware(req, res, next) {
const url = new URL(req.url!.replace(/^\/+/, '/'), 'http://example.com')
// In some cases (e.g. linked monorepos) files outside of root will
// reference assets that are also out of served root. In such cases
// the paths are rewritten to `/@fs/` prefixed paths and must be served by
// searching based from fs root.
if (url.pathname.startsWith(FS_PREFIX)) {
const pathname = decodeURIComponent(url.pathname)
// restrict files outside of `fs.allow`
if (
!ensureServingAccess(
slash(path.resolve(fsPathFromId(pathname))),
server,
res,
next,
)
) {
return
}
let newPathname = pathname.slice(FS_PREFIX.length)
if (isWindows) newPathname = newPathname.replace(/^[A-Z]:/i, '')
url.pathname = encodeURIComponent(newPathname)
req.url = url.href.slice(url.origin.length)
serveFromRoot(req, res, next)
} else {
next()
}
} | 1 | TypeScript | CWE-706 | Use of Incorrectly-Resolved Name or Reference | The product uses a name or reference to access a resource, but the name/reference resolves to a resource that is outside of the intended control sphere. | https://cwe.mitre.org/data/definitions/706.html | safe |
export function serveRawFsMiddleware(
server: ViteDevServer,
): Connect.NextHandleFunction {
const serveFromRoot = sirv(
'/',
sirvOptions({ headers: server.config.server.headers }),
)
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
return function viteServeRawFsMiddleware(req, res, next) {
const url = new URL(req.url!.replace(/^\/+/, '/'), 'http://example.com')
// In some cases (e.g. linked monorepos) files outside of root will
// reference assets that are also out of served root. In such cases
// the paths are rewritten to `/@fs/` prefixed paths and must be served by
// searching based from fs root.
if (url.pathname.startsWith(FS_PREFIX)) {
const pathname = decodeURIComponent(url.pathname)
// restrict files outside of `fs.allow`
if (
!ensureServingAccess(
slash(path.resolve(fsPathFromId(pathname))),
server,
res,
next,
)
) {
return
}
let newPathname = pathname.slice(FS_PREFIX.length)
if (isWindows) newPathname = newPathname.replace(/^[A-Z]:/i, '')
url.pathname = encodeURIComponent(newPathname)
req.url = url.href.slice(url.origin.length)
serveFromRoot(req, res, next)
} else {
next()
}
}
} | 1 | TypeScript | CWE-706 | Use of Incorrectly-Resolved Name or Reference | The product uses a name or reference to access a resource, but the name/reference resolves to a resource that is outside of the intended control sphere. | https://cwe.mitre.org/data/definitions/706.html | safe |
getModel: jest.fn(() => {
return { kind: 'singleType' };
}),
}; | 1 | TypeScript | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
getModel: jest.fn(() => {
return { kind: 'singleType' };
}), | 1 | TypeScript | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. | https://cwe.mitre.org/data/definitions/200.html | safe |
): string | null => {
if (!url) return null;
let parsedUrl: URL | null = null;
try {
parsedUrl = new URL(url);
} catch (error) {
return permitInvalid ? url : null;
}
if (
allowedSchemes &&
!allowedSchemes.includes(parsedUrl.protocol.slice(0, -1))
) {
return null;
}
return parsedUrl.href;
}; | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
target: el.getAttribute('target') || '_blank',
};
}
return undefined;
}, | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
export const submitFloatingLink = <V extends Value>(editor: PlateEditor<V>) => {
if (!editor.selection) return;
const { forceSubmit } = getPluginOptions<LinkPlugin, V>(editor, ELEMENT_LINK);
const url = floatingLinkSelectors.url();
if (!forceSubmit && !validateUrl(editor, url)) return;
const text = floatingLinkSelectors.text();
const target = floatingLinkSelectors.newTab() ? undefined : '_self';
floatingLinkActions.hide();
upsertLink(editor, {
url,
text,
target,
skipValidation: true,
});
setTimeout(() => {
focusEditor(editor, editor.selection!);
}, 0);
return true;
}; | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
plugins: [createLinkPlugin()],
});
describe('when url is valid', () => {
const link: TLinkElement = {
...baseLink,
url: 'https://example.com/',
target: '_self',
};
it('should return href and target', () => {
expect(getLinkAttributes(editor, link)).toEqual({
href: 'https://example.com/',
target: '_self',
});
});
});
describe('when url is invalid', () => {
const link: TLinkElement = {
...baseLink,
// eslint-disable-next-line no-script-url
url: 'javascript://example.com/',
target: '_self',
};
it('href should be undefined', () => {
expect(getLinkAttributes(editor, link)).toEqual({
href: undefined,
target: '_self',
});
});
});
describe('when target is not set', () => {
const link: TLinkElement = {
...baseLink,
url: 'https://example.com/',
};
it('target should be undefiend', () => {
expect(getLinkAttributes(editor, link)).toEqual({
href: 'https://example.com/',
target: undefined,
});
});
});
}); | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
) => {
const { allowedSchemes } = getPluginOptions<LinkPlugin, V>(
editor,
ELEMENT_LINK
);
const href = sanitizeUrl(link.url, { allowedSchemes }) || undefined;
const { target } = link;
return { href, target };
}; | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
): boolean => {
const { allowedSchemes, isUrl } = getPluginOptions<LinkPlugin, V>(
editor,
ELEMENT_LINK
);
if (isUrl && !isUrl(url)) return false;
if (
!sanitizeUrl(url, {
allowedSchemes,
permitInvalid: true,
})
)
return false;
return true;
}; | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
t.notFound = () => {
d.ok();
}; | 1 | TypeScript | CWE-284 | Improper Access Control | The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor. | https://cwe.mitre.org/data/definitions/284.html | safe |
export function escape(arg, options = {}) {
const helpers = getPlatformHelpers();
const { flagProtection, interpolation, shellName } = parseOptions(
{ env: process.env, options },
helpers,
);
const argAsString = checkedToString(arg);
const escape = helpers.getEscapeFunction(shellName, { interpolation });
const escapedArg = escape(argAsString);
if (flagProtection) {
const flagProtect = helpers.getFlagProtectionFunction(shellName);
return flagProtect(escapedArg);
} else {
return escapedArg;
}
} | 1 | TypeScript | CWE-150 | Improper Neutralization of Escape, Meta, or Control Sequences | The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as escape, meta, or control character sequences when they are sent to a downstream component. | https://cwe.mitre.org/data/definitions/150.html | safe |
export function quote(arg, options = {}) {
const helpers = getPlatformHelpers();
const { flagProtection, shellName } = parseOptions(
{ env: process.env, options },
helpers,
);
const argAsString = checkedToString(arg);
const [escape, quote] = helpers.getQuoteFunction(shellName);
const escapedArg = escape(argAsString);
if (flagProtection) {
const flagProtect = helpers.getFlagProtectionFunction(shellName);
return quote(flagProtect(escapedArg));
} else {
return quote(escapedArg);
}
} | 1 | TypeScript | CWE-150 | Improper Neutralization of Escape, Meta, or Control Sequences | The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as escape, meta, or control character sequences when they are sent to a downstream component. | https://cwe.mitre.org/data/definitions/150.html | safe |
export function resolveExecutable(
{ env, executable },
{ exists, readlink, which },
) {
try {
executable = which(executable, { path: env.PATH || env.Path });
} catch (_) {
// For backwards compatibility return the executable even if its location
// cannot be obtained
return executable;
}
if (!exists(executable)) {
// For backwards compatibility return the executable even if there exists no
// file at the specified path
return executable;
}
try {
executable = readlink(executable);
} catch (_) {
// An error will be thrown if the executable is not a (sym)link, this is not
// a problem so the error is ignored
}
return executable;
} | 1 | TypeScript | CWE-150 | Improper Neutralization of Escape, Meta, or Control Sequences | The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as escape, meta, or control character sequences when they are sent to a downstream component. | https://cwe.mitre.org/data/definitions/150.html | safe |
export function parseOptions(
{ env, options: { flagProtection, interpolation, shell } },
{ getDefaultShell, getShellName },
) {
flagProtection = flagProtection ? true : false;
interpolation = interpolation ? true : false;
shell = isString(shell) ? shell : getDefaultShell({ env });
const shellName = getShellName({ env, shell }, { resolveExecutable });
return { flagProtection, interpolation, shellName };
} | 1 | TypeScript | CWE-150 | Improper Neutralization of Escape, Meta, or Control Sequences | The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as escape, meta, or control character sequences when they are sent to a downstream component. | https://cwe.mitre.org/data/definitions/150.html | safe |
export function getShellName({ env, shell }, { resolveExecutable }) {
shell = resolveExecutable(
{ env, executable: shell },
{ exists: fs.existsSync, readlink: fs.readlinkSync, which: which.sync },
);
const shellName = path.basename(shell);
if (getEscapeFunction(shellName, {}) === undefined) {
return binBash;
}
return shellName;
} | 1 | TypeScript | CWE-150 | Improper Neutralization of Escape, Meta, or Control Sequences | The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as escape, meta, or control character sequences when they are sent to a downstream component. | https://cwe.mitre.org/data/definitions/150.html | safe |
export function getTestArgs() {
return ["harmless", ...injectionStrings];
} | 1 | TypeScript | CWE-150 | Improper Neutralization of Escape, Meta, or Control Sequences | The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as escape, meta, or control character sequences when they are sent to a downstream component. | https://cwe.mitre.org/data/definitions/150.html | safe |
export function getTestShells() {
const systemShells = constants.isWindows
? constants.shellsWindows
: constants.shellsUnix;
return [false, true, ...systemShells];
} | 1 | TypeScript | CWE-150 | Improper Neutralization of Escape, Meta, or Control Sequences | The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as escape, meta, or control character sequences when they are sent to a downstream component. | https://cwe.mitre.org/data/definitions/150.html | safe |
export function getTestFn(shell) {
try {
if (!isCI && typeof shell === "string") {
which.sync(shell, { path: process.env.PATH || process.env.Path });
}
return test;
} catch (_) {
return test.skip;
}
} | 1 | TypeScript | CWE-150 | Improper Neutralization of Escape, Meta, or Control Sequences | The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as escape, meta, or control character sequences when they are sent to a downstream component. | https://cwe.mitre.org/data/definitions/150.html | safe |
function getPlatformFixtures() {
if (constants.isWindows) {
return fixturesWindows;
} else {
return fixturesUnix;
}
} | 1 | TypeScript | CWE-150 | Improper Neutralization of Escape, Meta, or Control Sequences | The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as escape, meta, or control character sequences when they are sent to a downstream component. | https://cwe.mitre.org/data/definitions/150.html | safe |
quote: Object.values(fixtures.quote[shellName]).flat(),
};
} | 1 | TypeScript | CWE-150 | Improper Neutralization of Escape, Meta, or Control Sequences | The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as escape, meta, or control character sequences when they are sent to a downstream component. | https://cwe.mitre.org/data/definitions/150.html | safe |
handler: function (grid, rowIndex) {
let data = grid.getStore().getAt(rowIndex);
pimcore.helpers.deleteConfirm(t('translation').toLowerCase(), Ext.util.Format.htmlEncode(data.data.key), function () {
grid.getStore().removeAt(rowIndex);
}.bind(this));
}.bind(this) | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
const htmlPath = `${basePath}/${filename(mdFilePath)}.html`;
if (mdFilename !== 'sanitize_15.md') continue;
const mdToHtmlOptions: any = {
bodyOnly: true,
};
if (mdFilename === 'checkbox_alternative.md') {
mdToHtmlOptions.plugins = {
checkbox: {
checkboxRenderingType: 2,
},
};
}
const markdown = await shim.fsDriver().readFile(mdFilePath);
let expectedHtml = await shim.fsDriver().readFile(htmlPath);
const result = await mdToHtml.render(markdown, null, mdToHtmlOptions);
let actualHtml = result.html;
expectedHtml = expectedHtml.replace(/\r?\n/g, '\n');
actualHtml = actualHtml.replace(/\r?\n/g, '\n');
if (actualHtml !== expectedHtml) {
const msg: string[] = [
'',
`Error converting file: ${mdFilename}`,
'--------------------------------- Got:',
actualHtml,
'--------------------------------- Raw:',
actualHtml.split('\n'),
'--------------------------------- Expected:',
expectedHtml.split('\n'),
'--------------------------------------------',
'',
];
// eslint-disable-next-line no-console
console.info(msg.join('\n'));
expect(false).toBe(true);
// return;
} else {
expect(true).toBe(true);
}
}
})); | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
() => {} | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
async updatePlanId(userId: number, planId: number) {
const user = await User.findByPk(userId)
if (!user) throw Errors.USER_NOT_FOUND
if (userId === 6 && planId === 6 && config.officialInstance) {
throw Errors.HANDLED_BY_PAYMENT_PROVIDER
}
await User.update(
{
planId
},
{
where: {
id: userId
}
}
)
return true
} | 1 | TypeScript | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
const canBypassCORS = () => !!get(BYPASS_CORS_KEY); | 1 | TypeScript | CWE-863 | Incorrect Authorization | The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | safe |
cancel: !url.href.startsWith(rootFileURL)
});
} else if (url.origin === 'https://extensions.turbowarp.org') {
// Rewrite extensions.turbowarp.org to the offline cache.
callback({
redirectURL: `tw-extensions://${url.pathname}`
});
} else {
// This should never happen.
callback({});
}
}); | 1 | TypeScript | CWE-863 | Incorrect Authorization | The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | safe |
...(details.responseHeaders || {}),
'access-control-allow-origin': '*'
}
});
} else {
const corsHeaders = details.responseHeaders?.['access-control-allow-origin'] || [];
const corsHeader = corsHeaders.join(',');
callback({
cancel: corsHeader !== '*'
});
}
return;
}
}
callback({});
}); | 1 | TypeScript | CWE-863 | Incorrect Authorization | The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | safe |
): Promise<{ mnemonicPhrase: string; error: string }> => {
let response = { mnemonicPhrase: "", error: "" };
try {
response = await sendMessageToBackground({
password,
type: SERVICE_TYPES.SHOW_BACKUP_PHRASE,
});
} catch (e) {
console.error(e);
}
return response;
}; | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
mnemonicPhrase: mnemonicPhraseSelector(sessionStore.getState()),
}; | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
async function getStreamingFile(req, res) {
try {
validateSessionId(req.params.folder);
validateFilename(req.params.file);
const filePath = path.join(gladys.config.tempFolder, req.params.folder, req.params.file);
const filestream = fs.createReadStream(filePath);
filestream.on('error', (err) => {
res.status(404).end();
});
filestream.pipe(res);
} catch (e) {
if (e instanceof Error400) {
throw e;
}
logger.warn(e);
throw new Error404('FILE_NOT_FOUND');
}
} | 1 | TypeScript | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. | https://cwe.mitre.org/data/definitions/22.html | safe |
release: getBridgeVersion(),
serverName: config.bridge.domain,
includeLocalVariables: true,
});
log.info("Sentry reporting enabled");
}
if (config.generic?.allowJsTransformationFunctions) {
await GenericHookConnection.initialiseQuickJS();
}
const botUsersManager = new BotUsersManager(config, appservice);
const bridgeApp = new Bridge(config, listener, appservice, storage, botUsersManager);
process.once("SIGTERM", () => {
log.error("Got SIGTERM");
listener.stop();
bridgeApp.stop();
// Don't care to await this, as the process is about to end
storage.disconnect?.();
}); | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
const codeEvalResult = ctx.evalCode(`function f(data) {${validatedConfig.transformationFunction}}`, undefined, { compileOnly: true }); | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
public async onStateUpdate(stateEv: MatrixEvent<unknown>) {
const validatedConfig = GenericHookConnection.validateState(stateEv.content as Record<string, unknown>);
if (validatedConfig.transformationFunction) {
const ctx = GenericHookConnection.quickModule!.newContext();
const codeEvalResult = ctx.evalCode(`function f(data) {${validatedConfig.transformationFunction}}`, undefined, { compileOnly: true });
if (codeEvalResult.error) {
const errorString = JSON.stringify(ctx.dump(codeEvalResult.error), null, 2);
codeEvalResult.error.dispose();
ctx.dispose();
const errorPrefix = "Could not compile transformation function:";
await this.intent.sendEvent(this.roomId, {
msgtype: "m.text",
body: errorPrefix + "\n\n```json\n\n" + errorString + "\n\n```",
formatted_body: `<p>${errorPrefix}</p><p><pre><code class=\\"language-json\\">${errorString}</code></pre></p>`,
format: "org.matrix.custom.html",
});
} else {
codeEvalResult.value.dispose();
ctx.dispose();
this.transformationFunction = validatedConfig.transformationFunction;
}
} else {
this.transformationFunction = undefined;
}
this.state = validatedConfig;
} | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
public static async initialiseQuickJS() {
GenericHookConnection.quickModule = await newQuickJSWASMModule();
} | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
constructor(
roomId: string,
private state: GenericHookConnectionState,
public readonly hookId: string,
stateKey: string,
private readonly messageClient: MessageSenderClient,
private readonly config: BridgeConfigGenericWebhooks,
private readonly as: Appservice,
private readonly intent: Intent,
) {
super(roomId, stateKey, GenericHookConnection.CanonicalEventType);
if (state.transformationFunction && GenericHookConnection.quickModule) {
this.transformationFunction = state.transformationFunction;
}
} | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
static async provisionConnection(roomId: string, userId: string, data: Record<string, unknown> = {}, {as, intent, config, messageClient}: ProvisionConnectionOpts) {
if (!config.generic) {
throw Error('Generic Webhooks are not configured');
}
const hookId = randomUUID();
const validState = GenericHookConnection.validateState(data);
await GenericHookConnection.ensureRoomAccountData(roomId, intent, hookId, validState.name);
await intent.underlyingClient.sendStateEvent(roomId, this.CanonicalEventType, validState.name, validState);
const connection = new GenericHookConnection(roomId, validState, hookId, validState.name, messageClient, config.generic, as, intent);
return {
connection,
stateEventContent: validState,
}
} | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
decryptTopicPage(data) {
if (!data.currentRouteName?.startsWith("topic.")) {
return;
}
if (
!this.container ||
this.container.isDestroyed ||
this.container.isDestroying
) {
return;
}
const topicController = this.container.lookup("controller:topic");
const topic = topicController.get("model");
const topicId = topic.id;
if (topic?.encrypted_title) {
document.querySelector(".private_message").classList.add("encrypted");
}
getTopicTitle(topicId).then((topicTitle) => {
// Update fancy title stored in model
topicController.model.set("fancy_title", escapeExpression(topicTitle));
// Update document title
const documentTitle = this.container.lookup("service:document-title");
documentTitle.setTitle(
documentTitle
.getTitle()
.replace(topicController.model.title, topicTitle)
);
});
}, | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
const parseContent = (id, source, children, parse) => {
let result;
let setInnerHTML = false;
if (!children || children.length === 0 || children instanceof Function) {
const template = source.querySelector(`template#${id}`);
const templateHTML = template.innerHTML ?? "";
if (parse) {
const parsed = parseHTML(templateHTML);
const childResult = children instanceof Function ? children(parsed) : false;
result = childResult || parsed;
} else {
const childResult = children instanceof Function ? children(template) : false;
if (childResult) {
result = childResult;
} else {
result = templateHTML;
setInnerHTML = true;
}
}
} else {
result = children;
}
return { children: result, setInnerHTML };
}; | 1 | TypeScript | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
function inbox(ctx: Router.RouterContext) {
// 署名の検証
// referenced: https://github.com/mei23/misskey/pull/4749
let signature: httpSignature.IParsedSignature;
try {
// ヘッダーの検証はライブラリに投げる
signature = httpSignature.parseRequest(ctx.req, { "headers": ["(request-target)", "digest", "host", "date"] });
} catch (e) {
logger.warn("inbox: signature parse error");
ctx.status = 401;
return;
}
// Digestヘッダーの検証
const digest = ctx.req.headers.digest;
if (typeof digest !== "string") {
//logger.warn("Invalid digest (not string)")
ctx.status = 401;
return;
}
const match = digest.match(/^([0-9A-Za-z-]+)=(.+)$/);
if (match == null) {
logger.warn("Invalid digest (match == null)")
ctx.status = 401;
return;
}
const digestAlgo = match[1];
const digestExpected = match[2];
if (digestAlgo.toUpperCase() !== "SHA-256") {
// アルゴリズムをサポートしていない
logger.warn("digestAlgo is not supported")
ctx.status = 401;
return;
}
const digestActual = crypto.createHash("sha256").update(ctx.request.rawBody).digest("base64")
if (digestExpected !== digestActual) {
// 不正なダイジェスト
logger.warn("Invalid digest (digestExpected !== digestActual)")
ctx.status = 401;
return;
}
if (!signature.params.headers.includes("host") || ctx.headers.host !== config.host) {
// Host not specified or not match.
logger.warn("Invalid host header")
ctx.status = 400;
return;
}
const activity = ctx.request.body as IActivity;
processInbox(activity, signature);
ctx.status = 202;
} | 1 | TypeScript | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
function isActivityPubReq(ctx: Router.RouterContext) {
ctx.response.vary("Accept");
const accepted = ctx.accepts("html", ACTIVITY_JSON, LD_JSON);
return typeof accepted === "string" && !accepted.match(/html/);
} | 1 | TypeScript | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
visibility: In(["public" as const, "home" as const]),
localOnly: false,
});
if (note == null) {
ctx.status = 404;
return;
}
// リモートだったらリダイレクト
if (note.userHost != null) {
if (note.uri == null || isSelfHost(note.userHost)) {
ctx.status = 500;
return;
}
ctx.redirect(note.uri);
return;
}
ctx.body = renderActivity(await renderNote(note, false));
ctx.set("Cache-Control", "public, max-age=180");
setResponseType(ctx);
}); | 1 | TypeScript | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
detectJSON: () => true,
}); | 1 | TypeScript | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
host: IsNull(),
});
if (user == null) {
ctx.status = 404;
return;
}
const keypair = await getUserKeypair(user.id);
if (Users.isLocalUser(user)) {
ctx.body = renderActivity(renderKey(user, keypair));
ctx.set("Cache-Control", "public, max-age=180");
setResponseType(ctx);
} else {
ctx.status = 400;
}
}); | 1 | TypeScript | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
detectJSON: () => true,
});
try {
await koaBodyParser(ctx, next);
}
catch {
ctx.status = 400;
return;
}
} | 1 | TypeScript | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
async function userInfo(ctx: Router.RouterContext, user: User | null) {
if (user == null) {
ctx.status = 404;
return;
}
ctx.body = renderActivity(await renderPerson(user as ILocalUser));
ctx.set("Cache-Control", "public, max-age=180");
setResponseType(ctx);
} | 1 | TypeScript | CWE-20 | Improper Input Validation | The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly. | https://cwe.mitre.org/data/definitions/20.html | safe |
export function serializeObject(o: any): string {
return Buffer.from(JSON.stringify(o)).toString("base64")
} | 1 | TypeScript | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
export function serializeObject(o: any): string {
return Buffer.from(JSON.stringify(o)).toString("base64")
} | 1 | TypeScript | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. | https://cwe.mitre.org/data/definitions/94.html | safe |
export function deserializeObject(s: string) {
return JSON.parse(Buffer.from(s, "base64").toString())
} | 1 | TypeScript | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
export function deserializeObject(s: string) {
return JSON.parse(Buffer.from(s, "base64").toString())
} | 1 | TypeScript | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. | https://cwe.mitre.org/data/definitions/94.html | safe |
module.exports.shake256 = (data, len) => {
if (!data) {
return "";
}
return crypto.createHash("shake256", { outputLength: len })
.update(data)
.digest("hex");
}; | 1 | TypeScript | CWE-384 | Session Fixation | Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions. | https://cwe.mitre.org/data/definitions/384.html | safe |
allowRequest: (req, callback) => {
let isOriginValid = true;
const bypass = isDev || process.env.UPTIME_KUMA_WS_ORIGIN_CHECK === "bypass";
if (!bypass) {
let host = req.headers.host;
// If this is set, it means the request is from the browser
let origin = req.headers.origin;
// If this is from the browser, check if the origin is allowed
if (origin) {
try {
let originURL = new URL(origin);
if (host !== originURL.host) {
isOriginValid = false;
log.error("auth", `Origin (${origin}) does not match host (${host}), IP: ${req.socket.remoteAddress}`);
}
} catch (e) {
// Invalid origin url, probably not from browser
isOriginValid = false;
log.error("auth", `Invalid origin url (${origin}), IP: ${req.socket.remoteAddress}`);
}
} else {
log.info("auth", `Origin is not set, IP: ${req.socket.remoteAddress}`);
}
} else {
log.debug("auth", "Origin check is bypassed");
}
callback(null, isOriginValid);
}
});
} | 1 | TypeScript | CWE-346 | Origin Validation Error | The product does not properly verify that the source of data or communication is valid. | https://cwe.mitre.org/data/definitions/346.html | safe |
allowRequest: (req, callback) => {
let isOriginValid = true;
const bypass = isDev || process.env.UPTIME_KUMA_WS_ORIGIN_CHECK === "bypass";
if (!bypass) {
let host = req.headers.host;
// If this is set, it means the request is from the browser
let origin = req.headers.origin;
// If this is from the browser, check if the origin is allowed
if (origin) {
try {
let originURL = new URL(origin);
if (host !== originURL.host) {
isOriginValid = false;
log.error("auth", `Origin (${origin}) does not match host (${host}), IP: ${req.socket.remoteAddress}`);
}
} catch (e) {
// Invalid origin url, probably not from browser
isOriginValid = false;
log.error("auth", `Invalid origin url (${origin}), IP: ${req.socket.remoteAddress}`);
}
} else {
log.info("auth", `Origin is not set, IP: ${req.socket.remoteAddress}`);
}
} else {
log.debug("auth", "Origin check is bypassed");
}
callback(null, isOriginValid);
} | 1 | TypeScript | CWE-346 | Origin Validation Error | The product does not properly verify that the source of data or communication is valid. | https://cwe.mitre.org/data/definitions/346.html | safe |
const main = async () => {
console.log("Connecting the database");
Database.init(args);
await Database.connect(false, false, true);
try {
// No need to actually reset the password for testing, just make sure no connection problem. It is ok for now.
if (!process.env.TEST_BACKEND) {
const user = await R.findOne("user");
if (! user) {
throw new Error("user not found, have you installed?");
}
console.log("Found user: " + user.username);
while (true) {
let password = await question("New Password: ");
let confirmPassword = await question("Confirm New Password: ");
if (password === confirmPassword) {
await User.resetPassword(user.id, password);
// Reset all sessions by reset jwt secret
await initJWTSecret();
// Disconnect all other socket clients of the user
await disconnectAllSocketClients(user.username, password);
break;
} else {
console.log("Passwords do not match, please try again.");
}
}
console.log("Password reset successfully.");
}
} catch (e) {
console.error("Error: " + e.message);
}
await Database.close();
rl.close();
console.log("Finished.");
}; | 1 | TypeScript | CWE-384 | Session Fixation | Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions. | https://cwe.mitre.org/data/definitions/384.html | safe |
function disconnectAllSocketClients(username, password) {
return new Promise((resolve) => {
console.log("Connecting to " + localWebSocketURL + " to disconnect all other socket clients");
// Disconnect all socket connections
const socket = io(localWebSocketURL, {
transports: [ "websocket" ],
reconnection: false,
timeout: 5000,
});
socket.on("connect", () => {
socket.emit("login", {
username,
password,
}, (res) => {
if (res.ok) {
console.log("Logged in.");
socket.emit("disconnectOtherSocketClients");
} else {
console.warn("Login failed.");
console.warn("Please restart the server to disconnect all sessions.");
}
socket.close();
});
});
socket.on("connect_error", function () {
// The localWebSocketURL is not guaranteed to be working for some complicated Uptime Kuma setup
// Ask the user to restart the server manually
console.warn("Failed to connect to " + localWebSocketURL);
console.warn("Please restart the server to disconnect all sessions manually.");
resolve();
});
socket.on("disconnect", () => {
resolve();
});
});
} | 1 | TypeScript | CWE-384 | Session Fixation | Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions. | https://cwe.mitre.org/data/definitions/384.html | safe |
disconnectAllSocketClients(userID, currentSocketID = undefined) {
for (const socket of this.io.sockets.sockets.values()) {
if (socket.userID === userID && socket.id !== currentSocketID) {
try {
socket.emit("refresh");
socket.disconnect();
} catch (e) {
}
}
}
} | 1 | TypeScript | CWE-384 | Session Fixation | Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions. | https://cwe.mitre.org/data/definitions/384.html | safe |
static getInstance() {
if (UptimeKumaServer.instance == null) {
UptimeKumaServer.instance = new UptimeKumaServer();
}
return UptimeKumaServer.instance;
} | 1 | TypeScript | CWE-384 | Session Fixation | Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions. | https://cwe.mitre.org/data/definitions/384.html | safe |
.then(({ response }) => {
if (response === 0) {
this.doOpenLink(parsedUrl, details)
}
}) | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
message: lang.get("couldNotOpenLink_msg", { "{link}": details.url }),
type: "error",
})
}) | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
constructor(cfg) {
super();
/**
* Configuration options.
*
* The default `hasher` and `interations` is different from CryptoJs to enhance security:
* https://github.com/entronad/crypto-es/security/advisories/GHSA-mpj8-q39x-wq5h
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hasher to use. Default: SHA256
* @property {number} iterations The number of iterations to perform. Default: 250000
*/
this.cfg = Object.assign(
new Base(),
{
keySize: 128 / 32,
hasher: SHA256Algo,
iterations: 250000,
},
cfg,
);
} | 1 | TypeScript | CWE-327 | Use of a Broken or Risky Cryptographic Algorithm | The product uses a broken or risky cryptographic algorithm or protocol. | https://cwe.mitre.org/data/definitions/327.html | safe |
export const loadEnableCustomFilters = (store: Store<AppState, AnyAction>): void => {
const { settings, enableCustomFilters } = store.getState();
store.dispatch({
type: ActionType.UPDATE_ENABLE_CUSTOM_FILTERS,
value: enableCustomFilters ?? settings.enable_custom_filters ?? enableCustomFilters,
});
}; | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
export const enableCustomFilters = (state = false, action: AppActionTypes): boolean => {
switch (action.type) {
case ActionType.INIT_PARAMS:
return toBool(getHiddenValue('enable_custom_filters'));
case ActionType.UPDATE_ENABLE_CUSTOM_FILTERS:
return action.value;
case ActionType.LOAD_PREVIEW:
return false;
default:
return state;
}
}; | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
export const selectBaseEnableCustomFilters = (state: AppState): boolean => state.enableCustomFilters; | 1 | TypeScript | NVD-CWE-noinfo | null | null | null | safe |
export const enableWebUploads = (state = false, action: AppActionTypes): boolean => {
switch (action.type) {
case ActionType.INIT_PARAMS:
return toBool(getHiddenValue('enable_web_uploads'));
case ActionType.LOAD_PREVIEW:
return false;
default:
return state;
}
}; | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
export const selectEnableWebUploads = (state: AppState): boolean => state.enableWebUploads; | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
export async function trackedFetch(url: RequestInfo, init?: RequestInit): Promise<Response> {
const request = new Request(url, init)
return await runInSpan(
{
op: 'fetch',
description: `${request.method} ${request.url}`,
},
async () => {
if (isProdEnv() && !process.env.NODE_ENV?.includes('functional-tests')) {
await raiseIfUserProvidedUrlUnsafe(request.url)
}
return await fetch(url, init)
}
)
} | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
person_created_at: DateTime.fromISO(now).toUTC(),
} as any)
expect(fetch).toHaveBeenCalledWith('https://example.com/', {
body: JSON.stringify(
{
hook: {
id: 'id',
event: 'foo',
target: 'https://example.com/',
},
data: {
event: 'foo',
teamId: hook.team_id,
person: {
uuid: uuid,
properties: { foo: 'bar' },
created_at: now,
},
},
},
undefined,
4
),
headers: { 'Content-Type': 'application/json' },
method: 'POST',
timeout: 20000,
})
})
test('private IP hook forbidden in prod', async () => {
process.env.NODE_ENV = 'production'
await expect(
hookCommander.postRestHook({ ...hook, target: 'http://127.0.0.1' }, { event: 'foo' } as any)
).rejects.toThrow(new FetchError('Internal hostname', 'posthog-host-guard'))
})
}) | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
person_created_at: DateTime.fromISO(now).toUTC(),
} as any)
expect(fetch).toHaveBeenCalledWith('https://example.com/', {
body: JSON.stringify(
{
hook: {
id: 'id',
event: 'foo',
target: 'https://example.com/',
},
data: {
event: 'foo',
teamId: hook.team_id,
person: {
uuid: uuid,
properties: { foo: 'bar' },
created_at: now,
},
},
},
undefined,
4
),
headers: { 'Content-Type': 'application/json' },
method: 'POST',
timeout: 20000,
})
})
test('private IP hook forbidden in prod', async () => {
process.env.NODE_ENV = 'production'
await expect(
hookCommander.postRestHook({ ...hook, target: 'http://127.0.0.1' }, { event: 'foo' } as any)
).rejects.toThrow(new FetchError('Internal hostname', 'posthog-host-guard'))
})
})
}) | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
const protectRoute = (query, info) => {
const savePopulate = protectPopulate(query, info);
query.populate = savePopulate.populate || savePopulate.on;
query.fields = savePopulate.fields;
query.filters = protectFilters(query.filters, info);
return query;
}; | 1 | TypeScript | CWE-863 | Incorrect Authorization | The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. | https://cwe.mitre.org/data/definitions/863.html | safe |
function validateTLD(tld: string) {
return Boolean(tld.match(/^[a-zA-Z]{2,63}$/));
} | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
export function generateRequestUrl(options: Partial<Omit<TranslateOptions, 'raw'>> = {}): string {
const translateOptions = { ...defaultTranslateOptions, ...options };
if (!validateTLD(translateOptions.tld)) {
throw new Error("Invalid TLD: Must be 2-63 letters only")
}
const queryParams = {
rpcids: translateOptions.rpcids,
'source-path': '/',
hl: translateOptions.hl,
'soc-app': '1',
'soc-platform': '1',
'soc-device': '1',
rt: 'c'
};
const searchParams = new URLSearchParams(queryParams);
return `https://translate.google.${translateOptions.tld}/_/TranslateWebserverUi/data/batchexecute?${searchParams}`;
} | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
'Content-Length': Buffer.byteLength(body)
}
}, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
resolve(normaliseResponse(data))
});
}).on('error', reject);
req.write(body);
req.end();
}) | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
export function createRequestBody(text: string, translateOptions: Pick<TranslateOptions, "to" | "from" | "rpcids">) {
const encodedData = encodeURIComponent(`[[["${translateOptions.rpcids}","[[\\"${text}\\",\\"${translateOptions.from}\\",\\"${translateOptions.to}\\",true],[1]]",null,"generic"]]]`);
return `f.req=${encodedData}&`;
} | 1 | TypeScript | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
markClaimed: async function (inviteId = null, user) {
const invite = await this.get(`id = ${escape(inviteId)}`);
if (!invite) return { success: false, error: "Invite does not exist." };
if (invite.status !== "pending")
return { success: false, error: "Invite is not in pending status." };
const db = await this.db();
const { success, message } = await db
.run(`UPDATE ${this.tablename} SET status=?,claimedBy=? WHERE id=?`, [
"claimed",
user.id,
inviteId,
])
.then(() => {
return { success: true, message: null };
})
.catch((error) => {
return { success: false, message: error.message };
});
db.close();
if (!success) {
console.error(message);
return { success: false, error: message };
}
return { success: true, error: null };
}, | 1 | TypeScript | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
markClaimed: async function (inviteId = null, user) {
const invite = await this.get(`id = ${escape(inviteId)}`);
if (!invite) return { success: false, error: "Invite does not exist." };
if (invite.status !== "pending")
return { success: false, error: "Invite is not in pending status." };
const db = await this.db();
const { success, message } = await db
.run(`UPDATE ${this.tablename} SET status=?,claimedBy=? WHERE id=?`, [
"claimed",
user.id,
inviteId,
])
.then(() => {
return { success: true, message: null };
})
.catch((error) => {
return { success: false, message: error.message };
});
db.close();
if (!success) {
console.error(message);
return { success: false, error: message };
}
return { success: true, error: null };
}, | 1 | TypeScript | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
deactivate: async function (inviteId = null) {
const invite = await this.get(`id = ${escape(inviteId)}`);
if (!invite) return { success: false, error: "Invite does not exist." };
if (invite.status !== "pending")
return { success: false, error: "Invite is not in pending status." };
const db = await this.db();
const { success, message } = await db
.run(`UPDATE ${this.tablename} SET status=? WHERE id=?`, [
"disabled",
inviteId,
])
.then(() => {
return { success: true, message: null };
})
.catch((error) => {
return { success: false, message: error.message };
});
db.close();
if (!success) {
console.error(message);
return { success: false, error: message };
}
return { success: true, error: null };
}, | 1 | TypeScript | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
deactivate: async function (inviteId = null) {
const invite = await this.get(`id = ${escape(inviteId)}`);
if (!invite) return { success: false, error: "Invite does not exist." };
if (invite.status !== "pending")
return { success: false, error: "Invite is not in pending status." };
const db = await this.db();
const { success, message } = await db
.run(`UPDATE ${this.tablename} SET status=? WHERE id=?`, [
"disabled",
inviteId,
])
.then(() => {
return { success: true, message: null };
})
.catch((error) => {
return { success: false, message: error.message };
});
db.close();
if (!success) {
console.error(message);
return { success: false, error: message };
}
return { success: true, error: null };
}, | 1 | TypeScript | CWE-89 | Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/89.html | safe |
RENDERER_INLINE.paragraph = (text) => {
return text;
}; | 0 | TypeScript | CWE-167 | Improper Handling of Additional Special Element | The product receives input from an upstream component, but it does not handle or incorrectly handles when an additional unexpected special element is provided. | https://cwe.mitre.org/data/definitions/167.html | vulnerable |
public ngOnChanges() {
let html = '';
const markdown = this.markdown;
if (!markdown) {
html = markdown;
} else if (this.optional && markdown.indexOf('!') !== 0) {
html = markdown;
} else if (this.markdown) {
const renderer = this.inline ? RENDERER_INLINE : RENDERER_DEFAULT;
html = marked(this.markdown, { renderer });
}
if (!this.html && (!html || html === this.markdown || html.indexOf('<') < 0)) {
this.renderer.setProperty(this.element.nativeElement, 'textContent', html);
} else {
this.renderer.setProperty(this.element.nativeElement, 'innerHTML', html);
}
} | 0 | TypeScript | CWE-167 | Improper Handling of Additional Special Element | The product receives input from an upstream component, but it does not handle or incorrectly handles when an additional unexpected special element is provided. | https://cwe.mitre.org/data/definitions/167.html | vulnerable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.