code
stringlengths
12
2.05k
label_name
stringlengths
6
8
label
int64
0
95
commentSchema.statics.updateCommentsByPageId = function(comment, isMarkdown, commentId) { const Comment = this; return Comment.findOneAndUpdate( { _id: commentId }, { $set: { comment, isMarkdown } }, ); };
CWE-639
9
tooltipText: (c: FormatterContext, d: LineChartDatum) => string;
CWE-79
1
groupNames: groups.join(", "), }), "warning" ); } });
CWE-276
45
function localMessage(msg, source) { var output = source.output; output.add(formatMessage(msg, output)); }
CWE-78
6
resolve({root: require('os').homedir()}); } else reject('Bad username or password'); });
CWE-22
2
Object.keys(data).forEach((key) => { obj.add(ctx.next(data[key])); });
CWE-915
35
constructor(url, options, db, saveTemplate) { super(db, saveTemplate); if (!saveTemplate) { // enable backwards-compatibilty tweaks. this.fromHackSession = true; } const parsedUrl = Url.parse(url); this.host = parsedUrl.hostname; if (this.fromHackSession) { // HackSessionCo...
CWE-918
16
Languages.get = async function (language, namespace) { const data = await fs.promises.readFile(path.join(languagesPath, language, `${namespace}.json`), 'utf8'); const parsed = JSON.parse(data) || {}; const result = await plugins.hooks.fire('filter:languages.get', { language, namespace, data: parsed, }); retu...
CWE-22
2
tooltipText: (c: FormatterContext, d: BarChartDatum, e: string) => string;
CWE-79
1
return next.handle(req).pipe(catchError(err => { if (err.status === 401) { this.authenticationService.logout(); if (!req.url.includes('/v3/auth')) { // only reload the page if we aren't on the auth pages, this is so that we can display the auth errors. const stateUrl = thi...
CWE-613
7
export function applyCommandArgs(configuration: any, argv: string[]) { if (!argv || !argv.length) { return; } argv = argv.slice(2); const parsedArgv = yargs(argv); const argvKeys = Object.keys(parsedArgv); if (!argvKeys.length) { return; } debug("Appling command arguments:", parsedArgv); if (parsedArgv...
CWE-915
35
scroll_to_bottom_key: common.has_mac_keyboard() ? "Fn + <span class='tooltip_right_arrow'>→</span>" : "End", }), ); $(`.enter_sends_${user_settings.enter_sends}`).show(); common.adjust_mac_shortcuts(".enter_sends kbd"); }
CWE-79
1
const renderContent = (content: string | any) => { if (typeof content === 'string') { return renderHTML(content); } return content; };
CWE-79
1
return code.includes(hash); }); if (containsMentions) { // disable code highlighting if there is a mention in there // highlighting will be wrong anyway because this is not valid code return code; } return hljs.highlightAuto(code).value; }, });
CWE-79
1
function reduce(obj, str) { "use strict"; try { if ( typeof str !== "string") { return; } if ( typeof obj !== "object") { return; } return str.split('.').reduce(indexFalse, obj); } catch(ex) { console.error(ex); return; } ...
CWE-915
35
PageantSock.prototype.end = PageantSock.prototype.destroy = function() { this.buffer = null; if (this.proc) { this.proc.kill(); this.proc = undefined; } };
CWE-78
6
export function stringEncode(string: string) { let encodedString = ''; for (let i = 0; i < string.length; i++) { let charCodePointHex = string.charCodeAt(i).toString(16); encodedString += `\\u${charCodePointHex}`; } return encodedString; }
CWE-79
1
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name,
CWE-79
1
text(notificationName, data) { const username = formatUsername(data.display_username); let description; if (data.topic_title) { description = `<span data-topic-id="${this.attrs.topic_id}">${data.topic_title}</span>`; } else { description = this.description(data); } return I18n.t(...
CWE-79
1
function showTooltip(target: HTMLElement): () => void { const tooltip = document.createElement("div"); const isHidden = target.classList.contains("hidden"); if (isHidden) { target.classList.remove("hidden"); } tooltip.className = "keyboard-tooltip"; tooltip.innerHTML = target.getAttribute("data-key") ||...
CWE-79
1
function exportBranch(req, res) { const {branchId, type, format, version, taskId} = req.params; const branch = becca.getBranch(branchId); if (!branch) { const message = `Cannot export branch ${branchId} since it does not exist.`; log.error(message); res.status(500).send(message); ...
CWE-79
1
export function esc<T=unknown>(value: T): T|string; export function transform(input: string, options?: Options & { format?: 'esm' | 'cjs' }): string;
CWE-79
1
): void => { const name = createElement('h2', CLASS_CATEGORY_NAME); name.innerHTML = this.i18n.categories[category] || defaultI18n.categories[category]; this.emojis.appendChild(name); this.headers.push(name); this.emojis.appendChild( new EmojiContainer( emojis, true, ...
CWE-79
1
): { destroy: () => void; update: (t: () => string) => void } {
CWE-79
1
export function addEmailAddresses(userId: UserId, emailAddress: string, success: UserAcctRespHandler) { postJsonSuccess('/-/add-email-address', success, { userId, emailAddress }); }
CWE-613
7
next: schemaData => { if ( schemaData && ((schemaData.errors && schemaData.errors.length > 0) || !schemaData.data) ) { throw new Error(JSON.stringify(schemaData, null, 2)) } if (!schemaData) { throw new NoSche...
CWE-79
1
const escapedHost = `${host.replace(/\./g, "&#8203;.")}` // Some simple styling options const backgroundColor = "#f9f9f9" const textColor = "#444444" const mainBackgroundColor = "#ffffff" const buttonBackgroundColor = "#346df1" const buttonBorderColor = "#346df1" const buttonTextColor = "#ffffff" re...
CWE-79
1
async handler(ctx) { ctx.logStream.write(`Writing catalog-info.yaml`); const { entity } = ctx.input; await fs.writeFile( resolvePath(ctx.workspacePath, 'catalog-info.yaml'), yaml.stringify(entity), ); },
CWE-22
2
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name,
CWE-79
1
export function logoutClientSideOnly(ps: { goTo?: St, skipSend?: Bo } = {}) { Server.deleteTempSessId(); ReactDispatcher.handleViewAction({ actionType: actionTypes.Logout }); if (eds.isInEmbeddedCommentsIframe && !ps.skipSend) { // Tell the editor iframe that we've logged out. // And maybe we'll r...
CWE-613
7
export function loadEmailAddressesAndLoginMethods(userId: UserId, success: UserAcctRespHandler) { get(`/-/load-email-addrs-login-methods?userId=${userId}`, response => { success(response); }); }
CWE-613
7
text: text({ url, host }), html: html({ url, host, email }), }) }, options, } }
CWE-79
1
function isExternal(url) { let match = url.match( /^([^:/?#]+:)?(?:\/\/([^/?#]*))?([^?#]+)?(\?[^#]*)?(#.*)?/ ); if ( typeof match[1] === 'string' && match[1].length > 0 && match[1].toLowerCase() !== location.protocol ) { return true; } if ( typeof match[2] === 'string' && match[2...
CWE-79
1
...(options.role === 'anon' ? {} : { user: { title: 'System Task', role: options.role } }), res: {}, t(key, options = {}) { return self.apos.i18n.i18next.t(key, { ...options, lng: req.loca...
CWE-613
7
export function getCurSid12Maybe3(): St | N { // [ts_authn_modl] const store: Store = debiki2.ReactStore.allData(); const cookieName = debiki2.store_isFeatFlagOn(store, 'ffUseNewSid') ? 'TyCoSid123' : 'dwCoSid'; let sid = getSetCookie(cookieName); if (!sid) { // Cannot use store.me.mySidPart1 — w...
CWE-613
7
other_senders_count: Math.max(0, all_senders.length - MAX_AVATAR), other_sender_names, muted, topic_muted, participated: topic_data.participated, full_last_msg_date_time: full_datetime, }; }
CWE-79
1
export function escape(value: unknown, is_attr = false) { const str = String(value); const pattern = is_attr ? ATTR_REGEX : CONTENT_REGEX; pattern.lastIndex = 0; let escaped = ''; let last = 0; while (pattern.test(str)) { const i = pattern.lastIndex - 1; const ch = str[i]; escaped += str.substring...
CWE-79
1
const assigner = ( ...args: any[] ) => { console.log( { args } ) return args.reduce( ( a, b ) => { if ( untracker.includes( a ) ) throw new TypeError( `can't convert ${a} to object` ) if ( useuntrack && untracker.includes( b ) ) return a Object.keys( b ).forEach( key => { if ( untrac...
CWE-915
35
export function store_isFeatFlagOn(store: Store, featureFlag: St): Bo { return _.includes(store.siteFeatureFlags, featureFlag) || _.includes(store.serverFeatureFlags, featureFlag); }
CWE-613
7
const getValue = (target, prop) => { if (prop === 'Math') return Math; const { expressions, data } = target; if (!expressions.has(prop)) return data.get(prop); const expression = expressions.get(prop); return expression(); };
CWE-94
14
export async function recursiveReadDir(dir: string): Promise<string[]> { const subdirs = await readdir(dir); const files = await Promise.all( subdirs.map(async subdir => { const res = resolve(dir, subdir); return (await stat(res)).isDirectory() ? recursiveReadDir(res) : [res]; }), ); return ...
CWE-22
2
handler: function (grid, rowIndex) { let data = grid.getStore().getAt(rowIndex); pimcore.helpers.deleteConfirm(t('translation'), data.data.key, function () { grid.getStore().removeAt(rowIndex); }.bind...
CWE-79
1
async function apiCommand<T>(command: string, parameters: {} = {}): Promise<T> { const url = "/api" const method = "POST" const headers = { "Content-Type": "application/json" } const data: ApiRequest = { command, parameters } const res = await axios.request<CommandResult<T>>({ url, method, headers, data }) ...
CWE-306
79
PageantSock.prototype.connect = function() { this.emit('connect'); };
CWE-78
6
export default async function email( identifier: string, options: InternalOptions<"email"> ) { const { url, adapter, provider, logger, callbackUrl } = options // Generate token const token = (await provider.generateVerificationToken?.()) ??
CWE-79
1
getDownloadUrl(fileId, accessToken) { return `${Shopware.Context.api.apiPath}/_action/${this.getApiBasePath()}/` + `file/download?fileId=${fileId}&accessToken=${accessToken}`; }
CWE-639
9
onBannerChange (input: HTMLInputElement) { this.bannerfileInput = new ElementRef(input) const bannerfile = this.bannerfileInput.nativeElement.files[0] if (bannerfile.size > this.maxBannerSize) { this.notifier.error('Error', $localize`This image is too large.`) return } const formData...
CWE-79
1
{ host: serverB.getUrl(), clientAuthToken: serverB.authKey, enterprise: false }, ], }) garden.events.emit("_test", "foo") // Make sure events are flushed await streamer.close() expect(serverEventBusA.eventLog).to.eql([{ name: "_test", payload: "foo" }]) expect(serverEventBusB.ev...
CWE-306
79
provisionCallback: (user, renew, cb) => { cb(null, 'zzz'); } }); xoauth2.getToken(false, function(err, accessToken) { expect(err).to.not.exist; expect(accessToken).to.equal('zzz'); done(); }); });
CWE-88
3
text(notificationName, data) { const username = `<span>${formatUsername(data.display_username)}</span>`; let description; if (data.topic_title) { description = `<span data-topic-id="${this.attrs.topic_id}">${data.topic_title}</span>`; } else { description = this.description(d...
CWE-79
1
export default function addStickyControl() { extend(DiscussionListState.prototype, 'requestParams', function(params) { if (app.current.matches(IndexPage) || app.current.matches(DiscussionPage)) { params.include.push('firstPost'); } }); extend(DiscussionListItem.prototype, 'infoItems', function(item...
CWE-79
1
func cssGogsMinCssMap() (*asset, error) { bytes, err := cssGogsMinCssMapBytes() if err != nil { return nil, err } info := bindataFileInfo{name: "css/gogs.min.css.map", size: 22926, mode: os.FileMode(0644), modTime: time.Unix(1584214336, 0)} a := &asset{bytes: bytes, info: info, digest: [32]uint8{0x46, 0x89, 0xb...
CWE-281
93
function onconnect() { var buf; if (isSigning) { /* byte SSH2_AGENTC_SIGN_REQUEST string key_blob string data uint32 flags */ var p = 9; buf = Buffer.allocUnsafe(4 + 1 + 4 + keylen + 4 + datalen + 4); writeUInt32BE(buf, buf.le...
CWE-78
6
Object.keys(obj).forEach((propertyName: string) => { const propertyMetadata = ConverterService.getPropertyMetadata(properties, propertyName); return this.convertProperty(obj, instance, propertyName, propertyMetadata, options); });
CWE-915
35
handler: function ({log} = {}) { if (!this.server.options.pasv_url) { return this.reply(502); } this.connector = new PassiveConnector(this); return this.connector.setupServer() .then((server) => { let address = this.server.options.pasv_url; // Allow connecting from local i...
CWE-918
16
constructor ( private sanitizer: DomSanitizer, private serverService: ServerService, private notifier: Notifier ) { }
CWE-79
1
function process_request_callback(requestData: RequestData, err?: Error | null, response?: Response) { assert(typeof requestData.callback === "function"); const request = requestData.request; if (!response && !err && requestData.msgType !== "CLO") { // this case happens when CLO is called an...
CWE-770
37
module.exports = function(url, options) { return fetch(url, options); };
CWE-88
3
function reject(req, res, message) { log.info(`${req.method} ${req.path} rejected with 401 ${message}`); res.status(401).send(message); }
CWE-79
1
closeSocket() { if (this.dataSocket) { const socket = this.dataSocket; this.dataSocket.end(() => socket.destroy()); this.dataSocket = null; } }
CWE-918
16
func cssGogsMinCss() (*asset, error) { bytes, err := cssGogsMinCssBytes() if err != nil { return nil, err } info := bindataFileInfo{name: "css/gogs.min.css", size: 64378, mode: os.FileMode(0644), modTime: time.Unix(1584214336, 0)} a := &asset{bytes: bytes, info: info, digest: [32]uint8{0xd9, 0x49, 0xa9, 0x99, 0...
CWE-281
93
function userBroadcast(msg, source) { var sourceMsg = '> ' + msg; var name = '{cyan-fg}{bold}' + source.name + '{/}'; msg = ': ' + msg; for (var i = 0; i < users.length; ++i) { var user = users[i]; var output = user.output; if (source === user) output.add(sourceMsg); else output.add(...
CWE-78
6
function parseComplexParam(queryParams: Object, keys: Object, value: any): void { let currentParams = queryParams; let keysLastIndex = keys.length - 1; for (let j = 0; j <= keysLastIndex; j++) { let key = keys[j] === '' ? currentParams.length : keys[j]; if (j < keysLastIndex) { // The value has to b...
CWE-915
35
function g_sendError(channel: ServerSecureChannelLayer, message: Message, ResponseClass: any, statusCode: StatusCode): void { const response = new ResponseClass({ responseHeader: { serviceResult: statusCode } }); return channel.send_response("MSG", response, message); }
CWE-770
37
) => [number, number, string] | undefined;
CWE-79
1
constructor ( private sanitizer: DomSanitizer, private serverService: ServerService ) { this.bytesPipe = new BytesPipe() this.maxSizeText = $localize`max size` }
CWE-79
1
onUpdate: function(username, accessToken) { users[username] = accessToken; }
CWE-88
3
function _ondata(data) { bc += data.length; if (state === 'secret') { // the secret we sent is echoed back to us by cygwin, not sure of // the reason for that, but we ignore it nonetheless ... if (bc === 16) { bc = 0; ...
CWE-78
6
const pushVal = (obj, path, val, options = {}) => { if (obj === undefined || obj === null || path === undefined) { return obj; } // Clean the path path = clean(path); const pathParts = split(path); const part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it doe...
CWE-915
35
const {type, store = JsonEntityStore.from(type), ...next} = options; const propertiesMap = getPropertiesStores(store); let keys = Object.keys(src); const additionalProperties = propertiesMap.size ? !!store.schema.get("additionalProperties") || options.additionalProperties : true; const out: any = new type(sr...
CWE-915
35
module.exports = async function(tag) { if (!tag || ![ 'string', 'number' ].includes(typeof tag)) { throw new TypeError(`string was expected, instead got ${tag}`); } const { message, author, email } = this; await Promise.all([ exec(`git config user.name "${await author}"`), exec(`git config user.email "${awa...
CWE-78
6
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name, totalHours, }
CWE-79
1
function spliceOne(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) list[i] = list[k]; list.pop(); }
CWE-78
6
ctx.prompt(prompt, function retryPrompt(answers) { if (answers.length === 0) return ctx.reject(['keyboard-interactive']); nick = answers[0]; if (nick.length > MAX_NAME_LEN) { return ctx.prompt('That nickname is too long.\n' + PROMPT_NAME, retryPrompt); ...
CWE-78
6
setEntries(entries) { if (entries.length === 0) { this.emptyList(); return; } let htmlToInsert = ''; for (let timesheet of entries) { let label = this.attributes['template'] .replace('%customer%', timesheet.project.customer.name) ...
CWE-79
1
text += `${c.amount(value, a.currency)}<br>`; });
CWE-79
1
template() { const { pfx, model, config } = this; const label = model.get('label') || ''; return ` <span id="${pfx}checkbox" class="${pfx}tag-status" data-tag-status></span> <span id="${pfx}tag-label" data-tag-name>${label}</span> <span id="${pfx}close" class="${pfx}tag-close" data-tag-...
CWE-79
1
node.addEventListener("mouseenter", () => { const t = tooltip(); t.innerHTML = getter(); });
CWE-79
1
GraphQLPlayground.init(root, ${JSON.stringify( extendedOptions, null, 2, )}) })
CWE-79
1
export function loadFromGitSync(input: Input): string | never { try { return execSync(createCommand(input), { encoding: 'utf-8' }); } catch (error) { throw createLoadError(error); } }
CWE-78
6
Server.loadMyself((anyMe: Me | NU, stuffForMe?: StuffForMe) => { // @ifdef DEBUG // Might happen if there was no weakSessionId, and also, no cookie. dieIf(!anyMe, 'TyE4032SMH57'); // @endif const newMe = anyMe as Me; if (isInSomeEmbCommentsIframe()) { // Tell the embedded comments or emb...
CWE-613
7
putComment(comment, isMarkdown, commentId, author) { const { pageId, revisionId } = this.getPageContainer().state; return this.appContainer.apiPost('/comments.update', { commentForm: { comment, page_id: pageId, revision_id: revisionId, is_markdown: isMarkdown, co...
CWE-639
9
html: html({ url, host, email }), }) },
CWE-79
1
function detailedDataTableMapper(entry) { const project = Projects.findOne({ _id: entry.projectId }) const mapping = [project ? project.name : '', dayjs.utc(entry.date).format(getGlobalSetting('dateformat')), entry.task, projectUsers.findOne() ? projectUsers.findOne().users.find((elem) => elem._id === e...
CWE-79
1
function check_response(err: Error | null, response: any) { should.not.exist(err); //xx debugLog(response.toString()); response.responseHeader.serviceResult.should.eql(StatusCodes.BadInvalidArgument); }
CWE-770
37
function detailedDataTableMapper(entry) { const project = Projects.findOne({ _id: entry.projectId }) const mapping = [project ? project.name : '', dayjs.utc(entry.date).format(getGlobalSetting('dateformat')), entry.task, projectUsers.findOne() ? projectUsers.findOne().users.find((elem) => elem._id === e...
CWE-1236
12
function main() { try { let tag = process.env.GITHUB_REF; if (core.getInput('tag')) { tag = `refs/tags/${core.getInput('tag')}`; } exec(`git for-each-ref --format='%(contents)' ${tag}`, (err, stdout) => { if (err) { core.setFailed(err); } else { core.setOutput('git-t...
CWE-78
6
get(`/-/load-email-addrs-login-methods?userId=${userId}`, response => { success(response); });
CWE-613
7
async showExportDialogEvent({notePath, defaultType}) { // each opening of the dialog resets the taskId, so we don't associate it with previous exports anymore this.taskId = ''; this.$exportButton.removeAttr("disabled"); if (defaultType === 'subtree') { this.$subtreeType....
CWE-79
1
template({ labelInfo, labelHead, iconSync, iconAdd, pfx, ppfx }: any) { return ` <div id="${pfx}up" class="${pfx}header"> <div id="${pfx}label" class="${pfx}header-label">${labelHead}</div> <div id="${pfx}status-c" class="${pfx}header-status"> <span id="${pfx}input-c" data-states-c> ...
CWE-79
1
function applyCommandArgs(configuration, argv) { if (!argv || !argv.length) { return; } argv = argv.slice(2); const parsedArgv = yargs(argv); const argvKeys = Object.keys(parsedArgv); if (!argvKeys.length) { return; } debug("Appling command arguments:", parsedArgv); i...
CWE-915
35
export function buildQueryString(params: Object, traditional?: Boolean): string { let pairs = []; let keys = Object.keys(params || {}).sort(); for (let i = 0, len = keys.length; i < len; i++) { let key = keys[i]; pairs = pairs.concat(buildParam(key, params[key], traditional)); } if (pairs.length === ...
CWE-915
35
export default function isSafeRedirect(url: string): boolean { if (typeof url !== 'string') { throw new TypeError(`Invalid url: ${url}`); } // Prevent open redirects using the //foo.com format (double forward slash). if (/\/\//.test(url)) { return false; } return !/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(...
CWE-601
11
void addPathParam(String name, String value, boolean encoded) { if (relativeUrl == null) { // The relative URL is cleared when the first query parameter is set. throw new AssertionError(); } relativeUrl = relativeUrl.replace("{" + name + "}", canonicalizeForPath(value, encoded)); }
CWE-22
2
constructor(connection, {root, cwd} = {}) { this.connection = connection; this.cwd = nodePath.normalize(cwd ? nodePath.join(nodePath.sep, cwd) : nodePath.sep); this._root = nodePath.resolve(root || process.cwd()); }
CWE-22
2
var cleanUrl = function(url) { url = decodeURIComponent(url); while(url.indexOf('..').length > 0) { url = url.replace('..', ''); } return url; };
CWE-22
2
Object.keys(data).forEach((key) => { obj.set(key, ctx.next(data[key]) as T); });
CWE-915
35
export function ffprobe(file: string): Promise<IFfprobe> { return new Promise<IFfprobe>((resolve, reject) => { if (!file) throw new Error('no file provided') stat(file, (err, stats) => { if (err) throw err exec('ffprobe -v quiet -print_format json -show_format -show_streams ' + file, (error, std...
CWE-78
6
module.exports = async function(path) { if (!path || typeof path !== 'string') { throw new TypeError(`string was expected, instead got ${path}`); } const absolute = resolve(path); if (!(await exist(absolute))) { throw new Error(`Could not find file at path "${absolute}"`); } const ts = await exec(`git log ...
CWE-78
6
): { destroy: () => void; update: (t: () => string) => void } {
CWE-79
1