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) {
// HackSessionContext.getExternalUiView() apparently ignored any path on the URL. Whoops.
} else {
if (parsedUrl.path === "/") {
// The URL parser says path = "/" for both "http://foo" and "http://foo/". We want to be
// strict, though.
this.path = url.endsWith("/") ? "/" : "";
} else {
this.path = parsedUrl.path;
}
}
this.port = parsedUrl.port;
this.protocol = parsedUrl.protocol;
this.options = options || {};
} | 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,
});
return result.data;
}; | 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 = this.router.routerState.snapshot.url;
const _ = this.router.navigate(['/login'], {queryParams: {next: stateUrl}});
}
} else if (err.status >= 500) { | 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.config) {
const configFile = path.resolve(process.cwd(), parsedArgv.config);
applyConfigFile(configuration, configFile);
}
for (const key in parsedArgv) {
if (!parsedArgv.hasOwnProperty(key)) {
continue;
}
const configKey = key
.replace(/_/g, ".");
debug(`Found config value from cmd args '${key}' to '${configKey}'`);
setDeepProperty(configuration, configKey, parsedArgv[key]);
}
} | 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(data.message, { description, username });
}, | 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") || "";
document.body.appendChild(tooltip);
const parentCoords = target.getBoundingClientRect();
// Padded 10px to the left if there is space or centered otherwise
const left =
parentCoords.left +
Math.min((target.offsetWidth - tooltip.offsetWidth) / 2, 10);
const top =
parentCoords.top + (target.offsetHeight - tooltip.offsetHeight) / 2;
tooltip.style.left = `${left}px`;
tooltip.style.top = `${top + window.pageYOffset}px`;
return (): void => {
tooltip.remove();
if (isHidden) {
target.classList.add("hidden");
}
};
} | 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);
return;
}
const taskContext = new TaskContext(taskId, 'export');
try {
if (type === 'subtree' && (format === 'html' || format === 'markdown')) {
zipExportService.exportToZip(taskContext, branch, format, res);
}
else if (type === 'single') {
singleExportService.exportSingleNote(taskContext, branch, format, res);
}
else if (format === 'opml') {
opmlExportService.exportToOpml(taskContext, branch, version, res);
}
else {
return [404, "Unrecognized export format " + format];
}
}
catch (e) {
const message = "Export failed with following error: '" + e.message + "'. More details might be in the logs.";
taskContext.reportError(message);
log.error(message + e.stack);
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,
this.events,
this.options,
category !== 'recents'
).render()
);
}; | 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 NoSchemaError(endpoint)
}
const schema = this.getSchema(schemaData.data as any)
const tracingSupported =
(schemaData.extensions && Boolean(schemaData.extensions.tracing)) ||
false
const result: TracingSchemaTuple = {
schema,
tracingSupported,
}
this.sessionCache.set(this.hash(session), result)
resolve(result)
this.fetching = this.fetching.remove(hash)
const subscription = this.subscriptions.get(hash)
if (subscription) {
subscription(result.schema)
}
}, | CWE-79 | 1 |
const escapedHost = `${host.replace(/\./g, "​.")}`
// Some simple styling options
const backgroundColor = "#f9f9f9"
const textColor = "#444444"
const mainBackgroundColor = "#ffffff"
const buttonBackgroundColor = "#346df1"
const buttonBorderColor = "#346df1"
const buttonTextColor = "#ffffff"
return `
<body style="background: ${backgroundColor};">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center" style="padding: 10px 0px 20px 0px; font-size: 22px; font-family: Helvetica, Arial, sans-serif; color: ${textColor};">
<strong>${escapedHost}</strong>
</td>
</tr>
</table>
<table width="100%" border="0" cellspacing="20" cellpadding="0" style="background: ${mainBackgroundColor}; max-width: 600px; margin: auto; border-radius: 10px;">
<tr>
<td align="center" style="padding: 10px 0px 0px 0px; font-size: 18px; font-family: Helvetica, Arial, sans-serif; color: ${textColor};">
Sign in as <strong>${escapedEmail}</strong>
</td>
</tr>
<tr>
<td align="center" style="padding: 20px 0;">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center" style="border-radius: 5px;" bgcolor="${buttonBackgroundColor}"><a href="${url}" target="_blank" style="font-size: 18px; font-family: Helvetica, Arial, sans-serif; color: ${buttonTextColor}; text-decoration: none; border-radius: 5px; padding: 10px 20px; border: 1px solid ${buttonBorderColor}; display: inline-block; font-weight: bold;">Sign in</a></td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="center" style="padding: 0px 0px 10px 0px; font-size: 16px; line-height: 22px; font-family: Helvetica, Arial, sans-serif; color: ${textColor};">
If you did not request this email you can safely ignore it.
</td>
</tr>
</table>
</body>
`
} | 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 redirect the embedd*ing* window. [sso_redir_par_win]
sendToOtherIframes(['logoutClientSideOnly', ps]);
// Probaby not needed, since reload() below, but anyway:
patchTheStore({ setEditorOpen: false });
const sessWin: MainWin = getMainWin();
delete sessWin.typs.weakSessionId;
sessWin.theStore.me = 'TyMLOGDOUT' as any;
}
// Disconnect WebSocket so we won't receive data, for this user, after we've
// logged out: (we reload() below β but the service-worker might stay connected)
pubsub.disconnectWebSocket();
if (ps.goTo) {
if (eds.isInIframe) {
// Then we'll redirect the parent window instead. [sso_redir_par_win]
}
else {
location.assign(ps.goTo);
}
// If that for some reason won't do anything, then make sure we really forget
// all logged in state anyway:
setTimeout(function() {
logW(`location.assign(${ps.goTo}) had no effect? Reloading anyway...`);
location.reload();
}, 2000);
}
else {
// Quick fix that reloads the admin page (if one views it) so login dialog appears.
// But don't do in the goTo if branch β apparently location.reload()
// cancels location.assign(..) β even if done on the lines after (!).
location.reload();
}
} | 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].length > 0 &&
match[2].replace(
new RegExp(
':(' + { 'http:': 80, 'https:': 443 }[location.protocol] + ')?$'
),
''
) !== location.host
) {
return true;
}
return false;
} | 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.locale
});
},
data: {},
protocol: 'http',
get: function (propName) {
return { Host: 'you-need-to-set-baseUrl-in-app-js.com' }[propName];
},
query: {},
url: '/',
locale: self.apos.argv.locale || self.apos.modules['@apostrophecms/i18n'].defaultLocale,
mode: 'published',
aposNeverLoad: {},
aposStack: [],
__(key) {
self.apos.util.warnDevOnce('old-i18n-req-helper', stripIndent`
The req.__() and res.__() functions are deprecated and do not localize in A3.
Use req.t instead.
`);
return key;
}
};
addCloneMethod(req);
req.res.__ = req.__;
const { role, ..._properties } = options || {};
Object.assign(req, _properties);
self.apos.i18n.setPrefixUrls(req);
return req;
function addCloneMethod(req) {
req.clone = (properties = {}) => {
const _req = {
...req,
...properties
};
self.apos.i18n.setPrefixUrls(_req);
addCloneMethod(_req);
return _req;
};
}
}, | 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 β we might not yet have loaded
// the current user from the server; store.me might be stale.
const typs: PageSession = getMainWin().typs;
// This might not include part 3 (won't, if we're in an embedded comments
// iframe, and didn't login or resume via a popup win directly against the
// server so we could access cookie TyCoSid123, which includes part 3).
sid = typs.weakSessionId;
}
return sid || null;
} | 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(last, i) + (ch === '&' ? '&' : (ch === '"' ? '"' : '<'));
last = i + 1;
}
return escaped + str.substring(last);
} | 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 ( untracker.includes( a[key] ) ) a[key] = b[key]
else a[key] = delegate.call( this, a[key], b[key] )
} )
return a
} )
}
return assigner
}
Assigner.count = ( qty: number, delegate: ( arg: any, ...args: any[] ) => any ) => {
const assigner = ( ...receives: any[] ) => {
let group = receives.shift()
if ( untracker.includes( group ) ) throw new TypeError( `can't convert ${group} to object` )
let args = receives.splice( 0, qty - 1 )
while ( args.length ) {
const keys = []
for ( const arg of args )
for ( const key of Object.keys( arg ) )
if ( !keys.includes( key ) ) keys.push( key )
for ( const key of keys )
group[key] = delegate.call( this, group[key], ...args.map( arg => arg[key] ) )
args = receives.splice( 0, qty - 1 )
}
return group
}
return assigner
}
declare namespace Assigner {
export type BasicTypes = string | number | symbol | bigint | object | boolean | Function
export type Types = BasicTypes | Types[]
export type TypesWithExclude = BasicTypes | undefined | null | TypesWithExclude[]
}
export { Assigner } | 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 files.reduce((a, f) => a.concat(f), []);
} | 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(this));
}.bind(this) | 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 })
if (res.data.errors) {
throw res.data.errors
}
if (res.data.result === undefined) {
throw new Error("Empty response from server")
}
return res.data.result
} | 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 = new FormData()
formData.append('bannerfile', bannerfile)
this.bannerPopover?.close()
this.bannerChange.emit(formData)
if (this.previewImage) {
this.preview = this.sanitizer.bypassSecurityTrustResourceUrl(URL.createObjectURL(bannerfile))
}
} | 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.eventLog).to.eql([{ name: "_test", payload: "foo" }])
}) | 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(data);
}
return I18n.t(data.message, { description, username });
}, | 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(items) {
const discussion = this.attrs.discussion;
if (discussion.isSticky() && !this.attrs.params.q && !discussion.lastReadPostNumber()) {
const firstPost = discussion.firstPost();
if (firstPost) {
const excerpt = truncate(firstPost.contentPlain(), 175);
items.add('excerpt', m.trust(excerpt), -100);
}
}
});
} | 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, 0xb2, 0x95, 0x91, 0xfb, 0x5c, 0xda, 0xff, 0x63, 0x54, 0xc5, 0x91, 0xbf, 0x7a, 0x5a, 0xb5, 0x3d, 0xf, 0xf, 0x84, 0x41, 0x2d, 0xc3, 0x18, 0xf5, 0x74, 0xd7, 0xa9, 0x84, 0x70, 0xce}}
return a, nil
} | 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.length - 4, 0);
buf[4] = SIGN_REQUEST;
writeUInt32BE(buf, keylen, 5);
key.copy(buf, p);
writeUInt32BE(buf, datalen, p += keylen);
data.copy(buf, p += 4);
writeUInt32BE(buf, 0, p += datalen);
sock.write(buf);
} else {
/*
byte SSH2_AGENTC_REQUEST_IDENTITIES
*/
sock.write(Buffer.from([0, 0, 0, 1, REQUEST_IDENTITIES]));
}
} | 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
if (isLocalIP(this.ip)) {
address = this.ip;
}
const {port} = server.address();
const host = address.replace(/\./g, ',');
const portByte1 = port / 256 | 0;
const portByte2 = port % 256;
return this.reply(227, `PASV OK (${host},${portByte1},${portByte2})`);
})
.catch((err) => {
log.error(err);
return this.reply(425);
});
}, | 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 and when some pending transactions
// remains in the queue...
err = new Error(" Connection has been closed by client , but this transaction cannot be honored");
}
if (response && response instanceof ServiceFault) {
response.responseHeader.stringTable = [...(response.responseHeader.stringTable || [])];
err = new Error(" serviceResult = " + response.responseHeader.serviceResult.toString());
// " returned by server \n response:" + response.toString() + "\n request: " + request.toString());
(err as any).response = response;
((err as any).request = request), (response = undefined);
}
const theCallbackFunction = requestData.callback;
/* istanbul ignore next */
if (!theCallbackFunction) {
throw new Error("Internal error");
}
assert(requestData.msgType === "CLO" || (err && !response) || (!err && response));
// let set callback to undefined to prevent callback to be called again
requestData.callback = undefined;
theCallbackFunction(err || null, !err && response !== null ? response : undefined);
}
| 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, 0x79, 0x58, 0x26, 0xec, 0xaa, 0x9, 0x5a, 0x24, 0x6, 0x69, 0x2e, 0xe0, 0x3a, 0xb1, 0x53, 0xc4, 0x42, 0x72, 0x4d, 0xe0, 0x67, 0x6d, 0xae, 0x6c, 0x8f, 0xc4, 0x27, 0x27}}
return a, nil
} | 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(formatMessage(name, output) + msg);
}
} | 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 be an array or a false value
// It can happen that the value is no array if the key was repeated with traditional style like `list=1&list[]=2`
let prevValue = !currentParams[key] || typeof currentParams[key] === 'object' ? currentParams[key] : [currentParams[key]];
currentParams = currentParams[key] = prevValue || (isNaN(keys[j + 1]) ? {} : []);
} else {
currentParams = currentParams[key] = value;
}
}
} | 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;
state = 'creds';
sock.write(credsbuf);
}
} else if (state === 'creds') {
// if this is the first attempt, make sure to gather the valid
// uid and gid for our next attempt
if (!isRetrying)
inbuf.push(data);
if (bc === 12) {
sock.removeListener('connect', _onconnect);
sock.removeListener('data', _ondata);
sock.removeListener('close', _onclose);
if (isRetrying) {
addSockListeners();
sock.emit('connect');
} else {
isRetrying = true;
credsbuf = Buffer.concat(inbuf);
writeUInt32LE(credsbuf, process.pid, 0);
sock.destroy();
tryConnect();
}
}
}
} | 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 does not already exist
obj[part] = decouple(obj[part], options) || {};
// Recurse
pushVal(obj[part], pathParts.join("."), val, options);
} else if (part) {
// We have found the target array, push the value
obj[part] = decouple(obj[part], options) || [];
if (!(obj[part] instanceof Array)) {
throw("Cannot push to a path whose leaf node is not an array!");
}
obj[part].push(val);
} else {
// We have found the target array, push the value
obj = decouple(obj, options) || [];
if (!(obj instanceof Array)) {
throw("Cannot push to a path whose leaf node is not an array!");
}
obj.push(val);
}
return decouple(obj, options);
}; | 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(src);
propertiesMap.forEach((propStore) => {
const key = propStore.parent.schema.getAliasOf(propStore.propertyName) || propStore.propertyName;
keys = keys.filter((k) => k !== key);
let value = alterValue(propStore.schema, src[key], {...options, self: src});
next.type = propStore.computedType;
if (propStore.schema.hasGenerics) {
next.nestedGenerics = propStore.schema.nestedGenerics;
} else if (propStore.schema.isGeneric && options.nestedGenerics) {
const [genericTypes = [], ...nestedGenerics] = options.nestedGenerics;
const genericLabels = propStore.parent.schema.genericLabels || [];
next.type = genericTypes[genericLabels.indexOf(propStore.schema.genericType)] || Object;
next.nestedGenerics = nestedGenerics;
}
value = deserialize(value, {
...next,
collectionType: propStore.collectionType
});
if (value !== undefined) {
out[propStore.propertyName] = value;
}
});
if (additionalProperties) {
keys.forEach((key) => {
out[key] = src[key];
});
}
return out;
} | 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 "${await email}"`),
]);
await exec(`git tag -a ${JSON.stringify(tag)} -m "${await message}"`);
await exec(`git push origin ${JSON.stringify(`refs/tags/${tag}`)}`);
}; | 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);
} else if (nick.length === 0) {
return ctx.prompt('A nickname is required.\n' + PROMPT_NAME,
retryPrompt);
}
lowered = nick.toLowerCase();
for (var i = 0; i < users.length; ++i) {
if (users[i].name.toLowerCase() === lowered) {
return ctx.prompt('That nickname is already in use.\n' + PROMPT_NAME,
retryPrompt);
}
}
name = nick;
ctx.accept();
}); | 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)
.replace('%project%', timesheet.project.name)
.replace('%activity%', timesheet.activity.name);
htmlToInsert +=
`<li>` +
`<a href="${ this.attributes['href'].replace('000', timesheet.id) }" data-event="kimai.timesheetStart kimai.timesheetUpdate" class="api-link" data-method="PATCH" data-msg-error="timesheet.start.error" data-msg-success="timesheet.start.success">` +
`<i class="${ this.attributes['icon'] }"></i> ${ label }` +
`</a>` +
`</li>`;
}
this.itemList.innerHTML = htmlToInsert;
} | 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-remove>
${config.iconTagRemove}
</span>
`;
} | 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 embedded editor iframe that we just logged in,
// also include the session id, so Talkyard's script on the embedding page
// can remember it β because cookies and localstorage in an iframe typically
// get disabled by tracker blockers (they block 3rd party cookies).
const mainWin = getMainWin();
const typs: PageSession = mainWin.typs;
const weakSessionId = typs.weakSessionId;
const store: Store = ReactStore.allData();
const settings: SettingsVisibleClientSide = store.settings;
const rememberEmbSess =
settings.rememberEmbSess !== false &&
// If we got logged in automatically, then logout will be automatic too
// β could be surprising if we had to click buttons to log out,
// when we didn't need to do that, to log in.
typs.sessType !== SessionType.AutoTokenSiteCustomSso;
if (mainWin !== window) {
mainWin.theStore.me = _.cloneDeep(newMe);
}
sendToOtherIframes([
'justLoggedIn', { user: newMe, stuffForMe,
weakSessionId, pubSiteId: eds.pubSiteId, // [JLGDIN]
sessionType: null, rememberEmbSess }]);
}
setNewMe(newMe, stuffForMe);
if (afterwardsCallback) {
afterwardsCallback();
}
}); | 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,
comment_id: commentId,
author,
},
})
.then((res) => {
if (res.ok) {
return this.retrieveComments();
}
});
} | 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 === entry.userId)?.profile?.name : '']
if (getGlobalSetting('showCustomFieldsInDetails')) {
if (CustomFields.find({ classname: 'time_entry' }).count() > 0) {
for (const customfield of CustomFields.find({ classname: 'time_entry' }).fetch()) {
mapping.push(entry[customfield[customFieldType]])
}
}
if (CustomFields.find({ classname: 'project' }).count() > 0) {
for (const customfield of CustomFields.find({ classname: 'project' }).fetch()) {
mapping.push(project[customfield[customFieldType]])
}
}
}
if (getGlobalSetting('showCustomerInDetails')) {
mapping.push(project ? project.customer : '')
}
if (getGlobalSetting('useState')) {
mapping.push(entry.state)
}
mapping.push(Number(timeInUserUnit(entry.hours)))
mapping.push(entry._id)
return mapping
} | 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 === entry.userId)?.profile?.name : '']
if (getGlobalSetting('showCustomFieldsInDetails')) {
if (CustomFields.find({ classname: 'time_entry' }).count() > 0) {
for (const customfield of CustomFields.find({ classname: 'time_entry' }).fetch()) {
mapping.push(entry[customfield[customFieldType]])
}
}
if (CustomFields.find({ classname: 'project' }).count() > 0) {
for (const customfield of CustomFields.find({ classname: 'project' }).fetch()) {
mapping.push(project[customfield[customFieldType]])
}
}
}
if (getGlobalSetting('showCustomerInDetails')) {
mapping.push(project ? project.customer : '')
}
if (getGlobalSetting('useState')) {
mapping.push(entry.state)
}
mapping.push(Number(timeInUserUnit(entry.hours)))
mapping.push(entry._id)
return mapping
} | 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-tag-annotation', stdout);
}
});
} catch (error) {
core.setFailed(error.message);
}
} | 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.prop("checked", true).trigger('change');
// to show/hide OPML versions
this.$widget.find("input[name=export-subtree-format]:checked").trigger('change');
}
else if (defaultType === 'single') {
this.$singleType.prop("checked", true).trigger('change');
}
else {
throw new Error("Unrecognized type " + defaultType);
}
this.$widget.find(".opml-v2").prop("checked", true); // setting default
utils.openDialog(this.$widget);
const {noteId, parentNoteId} = treeService.getNoteIdAndParentIdFromNotePath(notePath);
this.branchId = await froca.getBranchId(parentNoteId, noteId);
const noteTitle = await treeService.getNoteTitle(noteId);
this.$noteTitle.html(noteTitle);
} | 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>
<div class="${ppfx}field ${ppfx}select">
<span id="${ppfx}input-holder">
<select id="${pfx}states" data-states></select>
</span>
<div class="${ppfx}sel-arrow">
<div class="${ppfx}d-s-arrow"></div>
</div>
</div>
</span>
</div>
</div>
<div id="${pfx}tags-field" class="${ppfx}field">
<div id="${pfx}tags-c" data-selectors></div>
<input id="${pfx}new" data-input/>
<span id="${pfx}add-tag" class="${pfx}tags-btn ${pfx}tags-btn__add" data-add>
${iconAdd}
</span>
<span class="${pfx}tags-btn ${pfx}tags-btn__sync" style="display: none" data-sync-style>
${iconSync}
</span>
</div>
<div class="${pfx}sels-info">
<div class="${pfx}label-sel">${labelInfo}:</div>
<div class="${pfx}sels" data-selected></div>
</div>`;
} | 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);
if (parsedArgv.config) {
const configFile = path.resolve(process.cwd(), parsedArgv.config);
applyConfigFile(configuration, configFile);
}
for (const key in parsedArgv) {
if (!parsedArgv.hasOwnProperty(key)) {
continue;
}
const configKey = key
.replace(/_/g, ".");
debug(`Found config value from cmd args '${key}' to '${configKey}'`);
setDeepProperty(configuration, configKey, parsedArgv[key]);
}
} | 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 === 0) {
return '';
}
return pairs.join('&');
} | 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(url);
} | 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, stdout, stderr) => {
if (error) return reject(error)
if (!stdout) return reject(new Error("can't probe file " + file))
let ffprobed: IFfprobe
try {
ffprobed = JSON.parse(stdout)
} catch (err) {
return reject(err)
}
for (let i = 0; i < ffprobed.streams.length; i++) {
if (ffprobed.streams[i].codec_type === 'video') ffprobed.video = ffprobed.streams[i] as IVideoStream
if (ffprobed.streams[i].codec_type === 'audio' && ffprobed.streams[i].channels)
ffprobed.audio = ffprobed.streams[i] as IAudioStream
}
resolve(ffprobed)
})
})
})
} | 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 -1 --format="%at" -- ${path}`);
return new Date(Number(ts) * 1000);
}; | CWE-78 | 6 |
): { destroy: () => void; update: (t: () => string) => void } { | CWE-79 | 1 |