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
function sendPrivateMessage() { let pMsg = checkMsg(msgerPrivateMsgInput.value.trim()); if (!pMsg) { msgerPrivateMsgInput.value = ''; isChatPasteTxt = false; return; } let toPeerName = msgerPrivateBtn.value; emitMsg(myPeerName, toPeerName, pMsg, true, peerId); appendMessage(myPeerName, rightChatAvatar, 'right', pMsg + '<hr>Private message to ' + toPeerName, true); msgerPrivateMsgInput.value = ''; msgerCP.style.display = 'none'; }
0
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
vulnerable
fastify.register(FastifyCsrfProtection, { getUserInfo(req) { return req.session.get('username') }})
0
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
vulnerable
function addDummyBuildTarget(config: any = buildConfig) { architectHost.addTarget( { project: 'dummy', target: 'build' }, '@angular-devkit/architect:true', config ); }
0
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
vulnerable
async function runNgsscbuild(options: Schema & JsonObject) { // A "run" can have multiple outputs, and contains progress information. const run = await architect.scheduleBuilder( 'angular-server-side-configuration:ngsscbuild', options, { logger } ); // The "result" member (of type BuilderOutput) is the next output. const output = await run.result; // Stop the builder from running. This stops Architect from keeping // the builder-associated states in memory, since builders keep waiting // to be scheduled. await run.stop(); return output; }
0
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
vulnerable
export async function detectVariables(context: BuilderContext): Promise<NgsscContext> { const detector = new VariableDetector(context.logger); const typeScriptFiles = findTypeScriptFiles(context.workspaceRoot); let ngsscContext: NgsscContext | null = null; for (const file of typeScriptFiles) { const fileContent = await readFileAsync(file, 'utf8'); const innerNgsscContext = detector.detect(fileContent); if (!innerNgsscContext.variables.length) { continue; } else if (!ngsscContext) { ngsscContext = innerNgsscContext; continue; } if (ngsscContext.variant !== innerNgsscContext.variant) { context.logger.info( `ngssc: Detected conflicting variants (${ngsscContext.variant} and ${innerNgsscContext.variant}) being used` ); } ngsscContext.variables.push( ...innerNgsscContext.variables.filter((v) => !ngsscContext!.variables.includes(v)) ); } if (!ngsscContext) { return { variant: 'process', variables: [] }; } context.logger.info( `ngssc: Detected variant '${ngsscContext.variant}' with variables ` + `'${ngsscContext.variables.join(', ')}'` ); return ngsscContext; }
0
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
vulnerable
export async function detectVariablesAndBuildNgsscJson( options: NgsscBuildSchema, browserOptions: BrowserBuilderOptions, context: BuilderContext, multiple: boolean = false ) { const ngsscContext = await detectVariables(context); const outputPath = join(context.workspaceRoot, browserOptions.outputPath); const ngssc = buildNgssc(ngsscContext, options, browserOptions, multiple); await writeFileAsync(join(outputPath, 'ngssc.json'), JSON.stringify(ngssc, null, 2), 'utf8'); }
0
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
vulnerable
function findTypeScriptFiles(root: string): string[] { const directory = root.replace(/\\/g, '/'); return readdirSync(directory) .map((f) => `${directory}/${f}`) .map((f) => { const stat = lstatSync(f); if (stat.isDirectory()) { return findTypeScriptFiles(f); } else if (stat.isFile() && f.endsWith('.ts') && !f.endsWith('.spec.ts')) { return [f]; } else { return []; } }) .reduce((current, next) => current.concat(next), []); }
0
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
vulnerable
export function is_form_content_type(request) { return is_content_type(request, 'application/x-www-form-urlencoded', 'multipart/form-data'); }
0
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
vulnerable
constructor(options: AuthenticatorOptions = {}) { this.key = options.key || 'passport' this.userProperty = options.userProperty || 'user' this.use(new SessionStrategy(this.deserializeUser.bind(this))) this.sessionManager = new SecureSessionManager({ key: this.key }, this.serializeUser.bind(this)) }
0
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
vulnerable
constructor(options: SerializeFunction | { key?: string }, serializeUser?: SerializeFunction) { if (typeof options === 'function') { this.serializeUser = options this.key = 'passport' } else if (typeof serializeUser === 'function') { this.serializeUser = serializeUser this.key = (options && typeof options === 'object' && typeof options.key === 'string' && options.key) || 'passport' } else { throw new Error('SecureSessionManager#constructor must have a valid serializeUser-function passed as a parameter') } }
0
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
vulnerable
) => { const { fastifyPassport, server } = getRegisteredTestServer(sessionOptions) fastifyPassport.use(name, strategy) return { fastifyPassport, server } }
0
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
vulnerable
export const getRegisteredTestServer = (sessionOptions: SessionOptions = null) => { const fastifyPassport = new Authenticator() fastifyPassport.registerUserSerializer(async (user) => JSON.stringify(user)) fastifyPassport.registerUserDeserializer(async (serialized: string) => JSON.parse(serialized)) const server = getTestServer(sessionOptions) void server.register(fastifyPassport.initialize()) void server.register(fastifyPassport.secureSession()) return { fastifyPassport, server } }
0
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
vulnerable
export const getTestServer = (sessionOptions: SessionOptions = null) => { const server = fastify() loadSessionPlugins(server, sessionOptions) server.setErrorHandler((error, request, reply) => { console.error(error) void reply.status(500) void reply.send(error) }) return server }
0
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
vulnerable
preValidation: authenticator.authenticate(strategyName, { successRedirect: `/${namespace}`, authInfo: false, }), }, () => { return } ) instance.post( `/logout-${namespace}`, { preValidation: authenticator.authenticate(strategyName, { authInfo: false }) }, async (request, reply) => { await request.logout() void reply.send('logged out') } ) }) } })
0
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
vulnerable
return this.success({ namespace, id: String(counter++) }) } this.fail() }
0
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
vulnerable
constructor(username: string, password: string) { this.username = username; this.password = password; }
0
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
vulnerable
constructor(token: string) { this.token = token; }
0
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
vulnerable
constructor(token: string) { this.token = token; }
0
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
vulnerable
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) ?? {}; // 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; }
0
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
vulnerable
public handleUpgrade( req: IncomingMessage, socket: Duplex, upgradeHead: Buffer ) { this.prepare(req); const res = new WebSocketResponse(req, socket); const callback = (errorCode, errorContext) => { if (errorCode) { 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); } }); }
0
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
vulnerable
const callback = (errorCode, errorContext) => { if (errorCode) { 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); }); };
0
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
vulnerable
const callback = async (errorCode, errorContext) => { if (errorCode) { 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 ); };
0
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
vulnerable
query(frame) { return models.Author.findPage(frame.options); }
0
TypeScript
NVD-CWE-noinfo
null
null
null
vulnerable
query(frame) { return models.Post.findPage(frame.options); }
0
TypeScript
NVD-CWE-noinfo
null
null
null
vulnerable
query(frame) { return models.Post.findPage(frame.options); }
0
TypeScript
NVD-CWE-noinfo
null
null
null
vulnerable
`export const devPagesDir = ${ctx.nuxt.options.dev ? JSON.stringify(ctx.nuxt.options.dir.pages) : 'null'}` ].join('\n\n') }
0
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
vulnerable
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!, '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) }
0
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
vulnerable
return function viteServeRawFsMiddleware(req, res, next) { const url = new URL(req.url!, '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() } }
0
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
vulnerable
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!, '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() } } }
0
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
vulnerable
getModel() { return { privateAttributes: [], attributes: { title: { type: 'text', private: false, }, }, primaryKey: 'id', options: {}, }; },
0
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
vulnerable
getModel: jest.fn(() => { return { kind: 'singleType', privateAttributes: [] }; }), };
0
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
vulnerable
getModel: jest.fn(() => { return { kind: 'singleType', privateAttributes: [] }; }),
0
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
vulnerable
global.strapi = { config: createConfig() }; Object.assign(model, { privateAttributes: getPrivateAttributes(model) }); expect(isPrivateAttribute(model, 'foo')).toBeTruthy(); expect(isPrivateAttribute(model, 'bar')).toBeFalsy(); expect(isPrivateAttribute(model, 'foobar')).toBeTruthy(); expect(strapi.config.get).toHaveBeenCalledWith('api.responses.privateAttributes', []); }); });
0
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
vulnerable
Object.assign(model, { privateAttributes: getPrivateAttributes(model) }); expect(isPrivateAttribute(model, 'foo')).toBeTruthy(); expect(isPrivateAttribute(model, 'bar')).toBeFalsy(); expect(isPrivateAttribute(model, 'foobar')).toBeFalsy(); expect(strapi.config.get).toHaveBeenCalledWith('api.responses.privateAttributes', []); });
0
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
vulnerable
export const submitFloatingLink = <V extends Value>(editor: PlateEditor<V>) => { if (!editor.selection) return; const { isUrl, forceSubmit } = getPluginOptions<LinkPlugin, V>( editor, ELEMENT_LINK ); const url = floatingLinkSelectors.url(); const isValid = isUrl?.(url) || forceSubmit;
0
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
vulnerable
isUrl?: (url: string) => boolean;
0
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
vulnerable
match: { type: getPluginType(editor, ELEMENT_LINK) }, }); // anchor and focus in link -> insert text if (insertTextInLink && linkAbove) { // we don't want to insert marks in links editor.insertText(url); return true; } if (!isUrl?.(url)) return;
0
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
vulnerable
export function escape(arg, options = {}) { const helpers = getPlatformHelpers(); const { flagProtection, interpolation, shellName } = parseOptions( { options, process }, 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; } }
0
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
vulnerable
export function quote(arg, options = {}) { const helpers = getPlatformHelpers(); const { flagProtection, shellName } = parseOptions( { options, process }, 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); } }
0
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
vulnerable
export function resolveExecutable({ executable }, { exists, readlink, which }) { try { executable = which(executable); } 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; }
0
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
vulnerable
export function parseOptions( { options: { flagProtection, interpolation, shell }, process: { env } }, { getDefaultShell, getShellName }, ) { flagProtection = flagProtection ? true : false; interpolation = interpolation ? true : false; shell = isString(shell) ? shell : getDefaultShell({ env }); const shellName = getShellName({ shell }, { resolveExecutable }); return { flagProtection, interpolation, shellName }; }
0
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
vulnerable
export function getShellName({ shell }, { resolveExecutable }) { shell = resolveExecutable( { executable: shell }, { exists: fs.existsSync, readlink: fs.readlinkSync, which: which.sync }, ); const shellName = path.basename(shell); if (getEscapeFunction(shellName, {}) === undefined) { return binBash; } return shellName; }
0
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
vulnerable
function getPlatformFixtures() { if (common.isWindows) { return fixturesWindows; } else { return fixturesUnix; } }
0
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
vulnerable
export function* platformShells() { if (common.isWindows) { yield* common.shellsWindows; } else { yield* common.shellsUnix; } }
0
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
vulnerable
quote: Object.values(fixtures.quote[shell]).flat(), }; }
0
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
vulnerable
handler: function (grid, rowIndex) { let data = grid.getStore().getAt(rowIndex); pimcore.helpers.deleteConfirm(t('translation'), Ext.util.Format.htmlEncode(data.data.key), function () { grid.getStore().removeAt(rowIndex); }.bind(this)); }.bind(this)
0
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
vulnerable
const htmlPath = `${basePath}/${filename(mdFilePath)}.html`; // if (mdFilename !== 'sanitize_9.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); } } }));
0
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
vulnerable
async updatePlanId(userId: number, planId: number) { const user = await User.findByPk(userId) if (!user) throw Errors.USER_NOT_FOUND if (userId === 6 && planId === 6) { throw Errors.HANDLED_BY_PAYMENT_PROVIDER } await User.update( { planId }, { where: { id: userId } } ) return true }
0
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
vulnerable
): Promise<{ error: string }> => { let response = { error: "" }; try { response = await sendMessageToBackground({ password, type: SERVICE_TYPES.SHOW_BACKUP_PHRASE, }); } catch (e) { console.error(e); } return response; };
0
TypeScript
NVD-CWE-noinfo
null
null
null
vulnerable
mnemonicPhrase: mnemonicPhraseSelector(sessionStore.getState()), });
0
TypeScript
NVD-CWE-noinfo
null
null
null
vulnerable
keyID: (await localStore.getItem(KEY_ID)) || "", password, }); return {}; } catch (e) {
0
TypeScript
NVD-CWE-noinfo
null
null
null
vulnerable
public async onStateUpdate(stateEv: MatrixEvent<unknown>) { const validatedConfig = GenericHookConnection.validateState(stateEv.content as Record<string, unknown>, this.config.allowJsTransformationFunctions || false); if (validatedConfig.transformationFunction) { try { this.transformationFunction = new Script(validatedConfig.transformationFunction); } catch (ex) { await this.messageClient.sendMatrixText(this.roomId, 'Could not compile transformation function:' + ex, "m.text", this.intent.userId); } } else { this.transformationFunction = undefined; } this.state = validatedConfig; }
0
TypeScript
NVD-CWE-noinfo
null
null
null
vulnerable
public async provisionerUpdateConfig(userId: string, config: Record<string, unknown>) { // Apply previous state to the current config, as provisioners might not return "unknown" keys. config = { ...this.state, ...config }; const validatedConfig = GenericHookConnection.validateState(config, this.config.allowJsTransformationFunctions || false); await this.intent.underlyingClient.sendStateEvent(this.roomId, GenericHookConnection.CanonicalEventType, this.stateKey, { ...validatedConfig, hookId: this.hookId } ); this.state = validatedConfig; }
0
TypeScript
NVD-CWE-noinfo
null
null
null
vulnerable
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 && config.allowJsTransformationFunctions) { this.transformationFunction = new Script(state.transformationFunction); } }
0
TypeScript
NVD-CWE-noinfo
null
null
null
vulnerable
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, config.generic.allowJsTransformationFunctions || false); 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, } }
0
TypeScript
NVD-CWE-noinfo
null
null
null
vulnerable
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", topicTitle); // Update document title const documentTitle = this.container.lookup("service:document-title"); documentTitle.setTitle( documentTitle .getTitle() .replace(topicController.model.title, topicTitle) ); }); },
0
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
vulnerable
function inbox(ctx: Router.RouterContext) { let signature; try { signature = httpSignature.parseRequest(ctx.req, { 'headers': [] }); } catch (e) { ctx.status = 401; return; } processInbox(ctx.request.body, signature); ctx.status = 202; }
0
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
vulnerable
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/); }
0
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
vulnerable
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); });
0
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
vulnerable
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; } });
0
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
vulnerable
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); }
0
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
vulnerable
export function serializeObject(o: any): string { return Buffer.from(Cryo.stringify(o)).toString("base64") }
0
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
vulnerable
export function serializeObject(o: any): string { return Buffer.from(Cryo.stringify(o)).toString("base64") }
0
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
vulnerable
export function deserializeObject(s: string) { return Cryo.parse(Buffer.from(s, "base64")) }
0
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
vulnerable
export function deserializeObject(s: string) { return Cryo.parse(Buffer.from(s, "base64")) }
0
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
vulnerable
cert: fs.readFileSync(sslCert), passphrase: sslKeyPassphrase, }, this.app); } else { log.info("server", "Server Type: HTTP"); this.httpServer = http.createServer(this.app); } try { this.indexHTML = fs.readFileSync("./dist/index.html").toString(); } catch (e) { // "dist/index.html" is not necessary for development if (process.env.NODE_ENV !== "development") { log.error("server", "Error: Cannot find 'dist/index.html', did you install correctly?"); process.exit(1); } } // Set Monitor Types UptimeKumaServer.monitorTypeList["real-browser"] = new RealBrowserMonitorType(); UptimeKumaServer.monitorTypeList["tailscale-ping"] = new TailscalePing(); this.io = new Server(this.httpServer); }
0
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
vulnerable
static getInstance(args) { if (UptimeKumaServer.instance == null) { UptimeKumaServer.instance = new UptimeKumaServer(args); } return UptimeKumaServer.instance; }
0
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
vulnerable
message: lang.get("couldNotOpenLink_msg", { "{link}": details.url }), type: "error", }) })
0
TypeScript
NVD-CWE-noinfo
null
null
null
vulnerable
constructor(cfg) { super(); /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hasher to use. Default: SHA1 * @property {number} iterations The number of iterations to perform. Default: 1 */ this.cfg = Object.assign( new Base(), { keySize: 128 / 32, hasher: SHA1Algo, iterations: 1, }, cfg, ); }
0
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
vulnerable
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 () => await fetch(url, init) ) }
0
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
vulnerable
export async function safeTrackedFetch(url: RequestInfo, init?: RequestInit): Promise<Response> { const request = new Request(url, init) return await runInSpan( { op: 'fetch', description: `${request.method} ${request.url}`, }, async () => { await raiseIfUserProvidedUrlUnsafe(request.url) return await fetch(url, init) } ) }
0
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
vulnerable
...(isTestEnv() ? { 'test-utils/write-to-file': writeToFile, } : {}), '@google-cloud/bigquery': bigquery, '@google-cloud/pubsub': pubsub, '@google-cloud/storage': gcs, '@posthog/plugin-contrib': contrib, '@posthog/plugin-scaffold': scaffold, 'aws-sdk': AWS, ethers: ethers, 'generic-pool': genericPool, 'node-fetch': isCloud() && (!hub.fetchHostnameGuardTeams || hub.fetchHostnameGuardTeams.has(teamId)) ? safeTrackedFetch : trackedFetch, 'snowflake-sdk': snowflake, crypto: crypto, jsonwebtoken: jsonwebtoken, faker: faker, pg: pg, stream: { PassThrough }, url: url, zlib: zlib, }
0
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
vulnerable
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 allowed on self-hosted', async () => { await hookCommander.postRestHook({ ...hook, target: 'http://127.0.0.1' }, { event: 'foo' } as any) expect(fetch).toHaveBeenCalledWith('http://127.0.0.1', expect.anything()) }) test('private IP hook forbidden on Cloud', async () => { jest.mocked(isCloud).mockReturnValue(true) await expect( hookCommander.postRestHook({ ...hook, target: 'http://127.0.0.1' }, { event: 'foo' } as any) ).rejects.toThrow(new FetchError('Internal hostname', 'posthog-host-guard')) }) })
0
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
vulnerable
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 allowed on self-hosted', async () => { await hookCommander.postRestHook({ ...hook, target: 'http://127.0.0.1' }, { event: 'foo' } as any) expect(fetch).toHaveBeenCalledWith('http://127.0.0.1', expect.anything()) }) test('private IP hook forbidden on Cloud', async () => { jest.mocked(isCloud).mockReturnValue(true) await expect( hookCommander.postRestHook({ ...hook, target: 'http://127.0.0.1' }, { event: 'foo' } as any) ).rejects.toThrow(new FetchError('Internal hostname', 'posthog-host-guard')) }) }) })
0
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
vulnerable
const protectRoute = (query, info) => { const savePopulate = protectPopulate(query, info); query.populate = savePopulate.populate; query.fields = savePopulate.fields; query.filters = protectFilters(query.filters, info); return query; };
0
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
vulnerable
'Content-Length': Buffer.byteLength(body) } }, (resp) => { let data = ''; resp.on('data', (chunk) => { data += chunk; }); resp.on('end', () => { resolve(normaliseResponse(data)) }); }).on('error', (err) => { reject(err) }) req.write(body); req.end(); })
0
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
vulnerable
markClaimed: async function (inviteId = null, user) { const invite = await this.get(`id = ${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 }; },
0
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
vulnerable
markClaimed: async function (inviteId = null, user) { const invite = await this.get(`id = ${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 }; },
0
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
vulnerable
deactivate: async function (inviteId = null) { const invite = await this.get(`id = ${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 }; },
0
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
vulnerable
deactivate: async function (inviteId = null) { const invite = await this.get(`id = ${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 }; },
0
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
vulnerable
update: async function (userId, updates = {}) { const user = await this.get(`id = ${userId}`); if (!user) return { success: false, error: "User does not exist." }; const { username, password, role, suspended = 0 } = updates; const toUpdate = { suspended }; if (user.username !== username && username?.length > 0) { const usedUsername = !!(await this.get(`username = '${username}'`)); if (usedUsername) return { success: false, error: `${username} is already in use.` }; toUpdate.username = username; } if (!!password) { const bcrypt = require("bcrypt"); toUpdate.password = bcrypt.hashSync(password, 10); } if (user.role !== role && ["admin", "default"].includes(role)) { // If was existing admin and that has been changed // make sure at least one admin exists if (user.role === "admin") { const validAdminCount = (await this.count(`role = 'admin'`)) > 1; if (!validAdminCount) return { success: false, error: `There would be no admins if this action was completed. There must be at least one admin.`, }; } toUpdate.role = role; } if (Object.keys(toUpdate).length !== 0) { const values = Object.values(toUpdate); const template = `UPDATE ${this.tablename} SET ${Object.keys( toUpdate ).map((key) => { return `${key}=?`; })} WHERE id = ?`; const db = await this.db(); const { success, message } = await db .run(template, [...values, userId]) .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 }; },
0
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
vulnerable
update: async function (userId, updates = {}) { const user = await this.get(`id = ${userId}`); if (!user) return { success: false, error: "User does not exist." }; const { username, password, role, suspended = 0 } = updates; const toUpdate = { suspended }; if (user.username !== username && username?.length > 0) { const usedUsername = !!(await this.get(`username = '${username}'`)); if (usedUsername) return { success: false, error: `${username} is already in use.` }; toUpdate.username = username; } if (!!password) { const bcrypt = require("bcrypt"); toUpdate.password = bcrypt.hashSync(password, 10); } if (user.role !== role && ["admin", "default"].includes(role)) { // If was existing admin and that has been changed // make sure at least one admin exists if (user.role === "admin") { const validAdminCount = (await this.count(`role = 'admin'`)) > 1; if (!validAdminCount) return { success: false, error: `There would be no admins if this action was completed. There must be at least one admin.`, }; } toUpdate.role = role; } if (Object.keys(toUpdate).length !== 0) { const values = Object.values(toUpdate); const template = `UPDATE ${this.tablename} SET ${Object.keys( toUpdate ).map((key) => { return `${key}=?`; })} WHERE id = ?`; const db = await this.db(); const { success, message } = await db .run(template, [...values, userId]) .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 }; },
0
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
vulnerable
new: async function (name = null, creatorId = null) { if (!name) return { result: null, message: "name cannot be null" }; var slug = slugify(name, { lower: true }); const existingBySlug = await this.get(`slug = '${slug}'`); if (existingBySlug !== null) { const slugSeed = Math.floor(10000000 + Math.random() * 90000000); slug = slugify(`${name}-${slugSeed}`, { lower: true }); } const db = await this.db(); const { id, success, message } = await db .run(`INSERT INTO ${this.tablename} (name, slug) VALUES (?, ?)`, [ name, slug, ]) .then((res) => { return { id: res.lastID, success: true, message: null }; }) .catch((error) => { return { id: null, success: false, message: error.message }; }); if (!success) { db.close(); return { workspace: null, message }; } const workspace = await db.get( `SELECT * FROM ${this.tablename} WHERE id = ${id}` ); db.close(); // If created with a user then we need to create the relationship as well. // If creating with an admin User it wont change anything because admins can // view all workspaces anyway. if (!!creatorId) await WorkspaceUser.create(creatorId, workspace.id); return { workspace, message: null }; },
0
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
vulnerable
new: async function (name = null, creatorId = null) { if (!name) return { result: null, message: "name cannot be null" }; var slug = slugify(name, { lower: true }); const existingBySlug = await this.get(`slug = '${slug}'`); if (existingBySlug !== null) { const slugSeed = Math.floor(10000000 + Math.random() * 90000000); slug = slugify(`${name}-${slugSeed}`, { lower: true }); } const db = await this.db(); const { id, success, message } = await db .run(`INSERT INTO ${this.tablename} (name, slug) VALUES (?, ?)`, [ name, slug, ]) .then((res) => { return { id: res.lastID, success: true, message: null }; }) .catch((error) => { return { id: null, success: false, message: error.message }; }); if (!success) { db.close(); return { workspace: null, message }; } const workspace = await db.get( `SELECT * FROM ${this.tablename} WHERE id = ${id}` ); db.close(); // If created with a user then we need to create the relationship as well. // If creating with an admin User it wont change anything because admins can // view all workspaces anyway. if (!!creatorId) await WorkspaceUser.create(creatorId, workspace.id); return { workspace, message: null }; },
0
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
vulnerable
async function validApiKey(request, response, next) { const multiUserMode = await SystemSettings.isMultiUserMode(); response.locals.multiUserMode = multiUserMode; const auth = request.header("Authorization"); const bearerKey = auth ? auth.split(" ")[1] : null; if (!bearerKey) { response.status(403).json({ error: "No valid api key found.", }); return; } const apiKey = await ApiKey.get(`secret = '${bearerKey}'`); if (!apiKey) { response.status(403).json({ error: "No valid api key found.", }); return; } next(); }
0
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
vulnerable
async function validApiKey(request, response, next) { const multiUserMode = await SystemSettings.isMultiUserMode(); response.locals.multiUserMode = multiUserMode; const auth = request.header("Authorization"); const bearerKey = auth ? auth.split(" ")[1] : null; if (!bearerKey) { response.status(403).json({ error: "No valid api key found.", }); return; } const apiKey = await ApiKey.get(`secret = '${bearerKey}'`); if (!apiKey) { response.status(403).json({ error: "No valid api key found.", }); return; } next(); }
0
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
vulnerable
constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) { this.children = children || {} this.methods = [] this.name = '' if (method && handler) { const m: Record<string, HandlerSet<T>> = {} m[method] = { handler, params: {}, possibleKeys: [], score: 0, name: this.name } this.methods = [m] } this.patterns = [] }
0
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
vulnerable
constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) { this.children = children || {} this.methods = [] this.name = '' if (method && handler) { const m: Record<string, HandlerSet<T>> = {} m[method] = { handler, params: {}, possibleKeys: [], score: 0, name: this.name } this.methods = [m] } this.patterns = [] }
0
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
vulnerable
export const canCreateToken = (userScopes: string[], tokenScopes: string[]) => { return tokenScopes.every((scope) => userScopes.includes(scope)) }
0
TypeScript
CWE-1220
Insufficient Granularity of Access Control
The product implements access controls via a policy or other feature with the intention to disable or restrict accesses (reads and/or writes) to assets in a system from untrusted agents. However, implemented access controls lack required granularity, which renders the control policy too broad because it allows accesses from unauthorized agents to the security-sensitive assets.
https://cwe.mitre.org/data/definitions/1220.html
vulnerable
exports.handler = async ({ arguments: args }) => { if (!args) return respondWithError("Internal error while trying to execute lease task.", "Event arguments missing."); if (!args.action) return respondWithError("Internal error while trying to execute lease task.", "Parameter 'action' missing."); let params; if (args.paramJson) { try { params = JSON.parse(args.paramJson); } catch (e) { return respondWithError("'paramJson' contains malformed JSON string."); } } try { switch (args.action) { case "getAwsLoginUrlForEvent": return getAwsLoginUrlForEvent(params); case "getAwsLoginUrlForLease": return getAwsLoginUrlForLease(params); default: throw new Error("unknown API action '" + args.action + "'"); } } catch (error) { return respondWithError("Internal error while trying to execute login task.", error); } };
0
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
vulnerable
exports.handler = async ({ arguments: args }) => { if (!args) return respondWithError("Internal error while trying to execute lease task.", "Event arguments missing."); if (!args.action) return respondWithError("Internal error while trying to execute lease task.", "Parameter 'action' missing."); let params; if (args.paramJson) { try { params = JSON.parse(args.paramJson); } catch (e) { return respondWithError("'paramJson' contains malformed JSON string."); } } try { switch (args.action) { case "getAwsLoginUrlForEvent": return getAwsLoginUrlForEvent(params); case "getAwsLoginUrlForLease": return getAwsLoginUrlForLease(params); default: throw new Error("unknown API action '" + args.action + "'"); } } catch (error) { return respondWithError("Internal error while trying to execute login task.", error); } };
0
TypeScript
CWE-269
Improper Privilege Management
The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
vulnerable
const AuthContainer = ({ children }) => { const dispatch = useDispatch(); const config = useSelector((state) => state.config) const { user, authStatus } = useAuthenticator((context) => [context.user, context.authStatus]); useEffect(() => { applyMode(Mode[config.DISPLAY_THEME]) applyDensity(Density[config.DISPLAY_TEXT_MODE]) },[config]) useEffect(() => { if (authStatus === "authenticated") { dispatch(setCurrentUser(user)); dispatch(fetchConfig()); } }, [dispatch, user, authStatus]); return children; };
0
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
vulnerable
const AuthContainer = ({ children }) => { const dispatch = useDispatch(); const config = useSelector((state) => state.config) const { user, authStatus } = useAuthenticator((context) => [context.user, context.authStatus]); useEffect(() => { applyMode(Mode[config.DISPLAY_THEME]) applyDensity(Density[config.DISPLAY_TEXT_MODE]) },[config]) useEffect(() => { if (authStatus === "authenticated") { dispatch(setCurrentUser(user)); dispatch(fetchConfig()); } }, [dispatch, user, authStatus]); return children; };
0
TypeScript
CWE-269
Improper Privilege Management
The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
vulnerable
const clearEvent = () => { dispatch({ type: "event/dismiss" }); dispatch({ type: "notification/dismiss" }); setInputError({}); setValueChangedOnce(true); };
0
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
vulnerable
const clearEvent = () => { dispatch({ type: "event/dismiss" }); dispatch({ type: "notification/dismiss" }); setInputError({}); setValueChangedOnce(true); };
0
TypeScript
CWE-269
Improper Privilege Management
The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
vulnerable
const submit = () => { dispatch({ type: "notification/dismiss" }); if (!validateInputs(value)) { return; } dispatch(fetchEndUserEvent(value)); };
0
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
vulnerable
const submit = () => { dispatch({ type: "notification/dismiss" }); if (!validateInputs(value)) { return; } dispatch(fetchEndUserEvent(value)); };
0
TypeScript
CWE-269
Improper Privilege Management
The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
vulnerable
user: User.email, expiresOn: moment .unix(Event.item.eventOn) .add(Event.item.eventDays, "days") .add(Event.item.eventHours, "hours") .unix(), maxAccounts: Event.item.maxAccounts, eventId: Event.item.id }) ) } disabled={NotificationItem.visible} > Open AWS Console </Button> <AwsLoginModal /> </> )} <Alert type={NotificationItem.type} header={NotificationItem.header} onDismiss={() => dispatch({ type: "notification/dismiss" })} visible={NotificationItem.visible} dismissAriaLabel="Close error" dismissible > {NotificationItem.content} </Alert> </SpaceBetween> </Container>
0
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
vulnerable
user: User.email, expiresOn: moment .unix(Event.item.eventOn) .add(Event.item.eventDays, "days") .add(Event.item.eventHours, "hours") .unix(), maxAccounts: Event.item.maxAccounts, eventId: Event.item.id }) ) } disabled={NotificationItem.visible} > Open AWS Console </Button> <AwsLoginModal /> </> )} <Alert type={NotificationItem.type} header={NotificationItem.header} onDismiss={() => dispatch({ type: "notification/dismiss" })} visible={NotificationItem.visible} dismissAriaLabel="Close error" dismissible > {NotificationItem.content} </Alert> </SpaceBetween> </Container>
0
TypeScript
CWE-269
Improper Privilege Management
The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
vulnerable
const updateFormValue = (update) => { setValue((prev) => { let newValue = { ...prev, ...update }; validateInputs(newValue, true); let user = newValue.user.replace(/[^a-zA-Z0-9]/g, Config.EVENT_EMAIL_SUBST); if (newValue.eventId !== "") newValue.principalId = newValue.eventId + Config.EVENT_PRINCIPAL_SEPARATOR + user; else newValue.principalId = user; return newValue; }); };
0
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
vulnerable