code
stringlengths 12
2.05k
| label_name
stringlengths 6
8
| label
int64 0
95
|
---|---|---|
PageantSock.prototype.write = function(buf) {
if (this.buffer === null)
this.buffer = buf;
else {
this.buffer = Buffer.concat([this.buffer, buf],
this.buffer.length + buf.length);
}
// Wait for at least all length bytes
if (this.buffer.length < 4)
return;
var len = readUInt32BE(this.buffer, 0);
// Make sure we have a full message before querying pageant
if ((this.buffer.length - 4) < len)
return;
buf = this.buffer.slice(0, 4 + len);
if (this.buffer.length > (4 + len))
this.buffer = this.buffer.slice(4 + len);
else
this.buffer = null;
var self = this;
var proc;
var hadError = false;
proc = this.proc = cp.spawn(EXEPATH, [ buf.length ]);
proc.stdout.on('data', function(data) {
self.emit('data', data);
});
proc.once('error', function(err) {
if (!hadError) {
hadError = true;
self.emit('error', err);
}
});
proc.once('close', function(code) {
self.proc = undefined;
if (ERROR[code] && !hadError) {
hadError = true;
self.emit('error', ERROR[code]);
}
self.emit('close', hadError);
});
proc.stdin.end(buf);
}; | CWE-78 | 6 |
this.serversUpdatedListener = ({ servers }) => {
// Update status log line with new `garden dashboard` server, if any
for (const { host, command } of servers) {
if (command === "dashboard") {
this.showUrl(host)
return
}
}
// No active explicit dashboard processes, show own URL instead
this.showUrl(this.getUrl())
} | CWE-306 | 79 |
export function setDeepProperty(obj: any, propertyPath: string, value: any): void {
const a = splitPath(propertyPath);
const n = a.length;
for (let i = 0; i < n - 1; i++) {
const k = a[i];
if (!(k in obj)) {
obj[k] = {};
}
obj = obj[k];
}
obj[a[n - 1]] = value;
return;
} | CWE-915 | 35 |
constructor(
private readonly ptarmiganService: PtarmiganService,
private readonly bitcoinService: BitcoinService,
private readonly cacheService: CacheService,
private readonly invoicesGateway: InvoicesGateway
) {
} | CWE-295 | 52 |
}) => Awaitable<void>
/**
* By default, we are generating a random verification token.
* You can make it predictable or modify it as you like with this method.
* @example
* ```js
* Providers.Email({
* async generateVerificationToken() {
* return "ABC123"
* }
* })
* ```
* [Documentation](https://next-auth.js.org/providers/email#customising-the-verification-token)
*/
generateVerificationToken?: () => Awaitable<string> | CWE-79 | 1 |
[req.locale]: self.getBrowserBundles(req.locale)
};
if (req.locale !== self.defaultLocale) {
i18n[self.defaultLocale] = self.getBrowserBundles(self.defaultLocale);
}
const result = {
i18n,
locale: req.locale,
defaultLocale: self.defaultLocale,
locales: self.locales,
debug: self.debug,
show: self.show,
action: self.action,
crossDomainClipboard: req.session.aposCrossDomainClipboard
};
if (req.session.aposCrossDomainClipboard) {
req.session.aposCrossDomainClipboard = null;
}
return result;
}, | CWE-613 | 7 |
text: () => string
): { destroy: () => void; update: (t: () => string) => void } { | CWE-79 | 1 |
servers: servers.map((p) => ({ command: p.command!, host: p.serverHost! })),
}) | CWE-306 | 79 |
function formatMessage(msg, output) {
var output = output;
output.parseTags = true;
msg = output._parseTags(msg);
output.parseTags = false;
return msg;
} | CWE-78 | 6 |
export declare function applyCommandArgs(configuration: any, argv: string[]): void;
export declare function setDeepProperty(obj: any, propertyPath: string, value: any): void; | CWE-915 | 35 |
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 |
export function render_markdown_timestamp(time: number | Date): {
text: string;
tooltip_content: string;
} {
const hourformat = user_settings.twenty_four_hour_time ? "HH:mm" : "h:mm a";
const timestring = format(time, "E, MMM d yyyy, " + hourformat);
const tz_offset_str = get_tz_with_UTC_offset(time);
const tooltip_html_content = render_markdown_time_tooltip({tz_offset_str});
return {
text: timestring,
tooltip_content: tooltip_html_content,
};
} | CWE-79 | 1 |
declare function getSetCookie(cookieName: string, value?: string, options?: any): string;
// backw compat, later, do once per file instead (don't want a global 'r').
//
// ReactDOMFactories looks like:
//
// var ReactDOMFactories = {
// a: createDOMFactory('a'),
// abbr: ...
//
// function createDOMFactory(type) {
// var factory = React.createElement.bind(null, type);
// factory.type = type; // makes: `<Foo />.type === Foo` work
// return factory;
// };
//
// and React.createElement(type: keyof ReactHTML, props, ...children) returns:
// DetailedReactHTMLElement<P, T>
//
const r: { [elmName: string]: (props?: any, ...children) => RElm } = ReactDOMFactories; | CWE-613 | 7 |
export function escape<T>(input: T): T extends SafeValue ? T['value'] : T {
return typeof input === 'string'
? string.escapeHTML(input)
: input instanceof SafeValue
? input.value
: input
} | CWE-843 | 43 |
export const initAuth0: InitAuth0 = (params) => {
const { baseConfig, nextConfig } = getConfig(params);
// Init base layer (with base config)
const getClient = clientFactory(baseConfig, { name: 'nextjs-auth0', version });
const transientStore = new TransientStore(baseConfig);
const cookieStore = new CookieStore(baseConfig);
const sessionCache = new SessionCache(baseConfig, cookieStore);
const baseHandleLogin = baseLoginHandler(baseConfig, getClient, transientStore);
const baseHandleLogout = baseLogoutHandler(baseConfig, getClient, sessionCache);
const baseHandleCallback = baseCallbackHandler(baseConfig, getClient, sessionCache, transientStore);
// Init Next layer (with next config)
const getSession = sessionFactory(sessionCache);
const getAccessToken = accessTokenFactory(nextConfig, getClient, sessionCache);
const withApiAuthRequired = withApiAuthRequiredFactory(sessionCache);
const withPageAuthRequired = withPageAuthRequiredFactory(nextConfig.routes.login, getSession);
const handleLogin = loginHandler(baseHandleLogin, nextConfig);
const handleLogout = logoutHandler(baseHandleLogout);
const handleCallback = callbackHandler(baseHandleCallback, nextConfig);
const handleProfile = profileHandler(getClient, getAccessToken, sessionCache);
const handleAuth = handlerFactory({ handleLogin, handleLogout, handleCallback, handleProfile });
return {
getSession,
getAccessToken,
withApiAuthRequired,
withPageAuthRequired,
handleLogin,
handleLogout,
handleCallback,
handleProfile,
handleAuth
};
}; | CWE-601 | 11 |
api.update = async function(req, res) {
const { commentForm } = req.body;
const pageId = commentForm.page_id;
const comment = commentForm.comment;
const isMarkdown = commentForm.is_markdown;
const commentId = commentForm.comment_id;
const author = commentForm.author;
if (comment === '') {
return res.json(ApiResponse.error('Comment text is required'));
}
if (commentId == null) {
return res.json(ApiResponse.error('\'comment_id\' is undefined'));
}
if (author !== req.user.username) {
return res.json(ApiResponse.error('Only the author can edit'));
}
// check whether accessible
const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
if (!isAccessible) {
return res.json(ApiResponse.error('Current user is not accessible to this page.'));
}
let updatedComment;
try {
updatedComment = await Comment.updateCommentsByPageId(comment, isMarkdown, commentId);
}
catch (err) {
logger.error(err);
return res.json(ApiResponse.error(err));
}
res.json(ApiResponse.success({ comment: updatedComment }));
// process notification if needed
}; | CWE-639 | 9 |
const createCommand = ({ ref, path }: Input) => {
return `git show ${ref}:${path}`;
}; | CWE-78 | 6 |
async convert(input, options) {
this[_validate]();
options = this[_parseOptions](options);
const output = await this[_convert](input, options);
return output;
} | CWE-94 | 14 |
export function orderLinks<T extends NameAndType>(links: T[]) {
const [provided, unknown] = partition<T>(links, isProvided);
return [
...sortBy(provided, link => PROVIDED_TYPES.indexOf(link.type)),
...sortBy(unknown, link => link.name!.toLowerCase())
];
} | CWE-79 | 1 |
render() {}, | CWE-79 | 1 |
parse(cookieStr) {
let cookie = {};
(cookieStr || '')
.toString()
.split(';')
.forEach(cookiePart => {
let valueParts = cookiePart.split('=');
let key = valueParts
.shift()
.trim()
.toLowerCase();
let value = valueParts.join('=').trim();
let domain;
if (!key) {
// skip empty parts
return;
}
switch (key) {
case 'expires':
value = new Date(value);
// ignore date if can not parse it
if (value.toString() !== 'Invalid Date') {
cookie.expires = value;
}
break;
case 'path':
cookie.path = value;
break;
case 'domain':
domain = value.toLowerCase();
if (domain.length && domain.charAt(0) !== '.') {
domain = '.' + domain; // ensure preceeding dot for user set domains
}
cookie.domain = domain;
break;
case 'max-age':
cookie.expires = new Date(Date.now() + (Number(value) || 0) * 1000);
break;
case 'secure':
cookie.secure = true;
break;
case 'httponly':
cookie.httponly = true;
break;
default:
if (!cookie.name) {
cookie.name = key;
cookie.value = value;
}
}
});
return cookie;
} | CWE-88 | 3 |
return `1 ${base} = ${c.amount(d.value, quote)}<em>${day(d.date)}</em>`;
},
});
} | CWE-79 | 1 |
export function setupCleanupOnExit(cssPath: string) {
if (!hasSetupCleanupOnExit){
process.on('SIGINT', () => {
console.log('Exiting, running CSS cleanup');
exec(`rm -r ${cssPath}`, function(error) {
if (error) {
console.error(error);
process.exit(1);
}
console.log('Deleted CSS files');
});
});
hasSetupCleanupOnExit = true;
}
} | CWE-78 | 6 |
getDownloadUrl(file) {
return this.importExport.getDownloadUrl(file.id, file.accessToken);
}, | CWE-639 | 9 |
const getCdnMarkup = ({ version, cdnUrl = '//cdn.jsdelivr.net/npm', faviconUrl }) => `
<link rel="stylesheet" href="${cdnUrl}/graphql-playground-react${ | CWE-79 | 1 |
export function escapeCommentText(value: string): string {
return value.replace(END_COMMENT, END_COMMENT_ESCAPED);
} | CWE-79 | 1 |
function checkCredentials(req, res, next) {
if (!sqlInit.isDbInitialized()) {
res.status(400).send('Database is not initialized yet.');
return;
}
if (!passwordService.isPasswordSet()) {
res.status(400).send('Password has not been set yet. Please set a password and repeat the action');
return;
}
const header = req.headers['trilium-cred'] || '';
const auth = new Buffer.from(header, 'base64').toString();
const [username, password] = auth.split(/:/);
// username is ignored
if (!passwordEncryptionService.verifyPassword(password)) {
res.status(401).send('Incorrect password');
}
else {
next();
}
} | CWE-79 | 1 |
message: new MockBuilder(
{
from: '[email protected]',
to: '[email protected]'
},
'message\r\nline 2'
)
},
function(err, data) {
expect(err).to.not.exist;
expect(data.messageId).to.equal('<test>');
expect(output).to.equal('message\nline 2');
client._spawn.restore();
done();
}
);
}); | CWE-88 | 3 |
function get(target, path) {
"use strict";
try {
return reduce(target, path);
} catch(ex) {
console.error(ex);
return;
}
} | CWE-915 | 35 |
export default function handleLoginFactory(handler: BaseHandleLogin, nextConfig: NextConfig): HandleLogin {
return async (req, res, options = {}): Promise<void> => {
try {
assertReqRes(req, res);
if (req.query.returnTo) {
const returnTo = Array.isArray(req.query.returnTo) ? req.query.returnTo[0] : req.query.returnTo;
if (!isSafeRedirect(returnTo)) {
throw new Error('Invalid value provided for returnTo, must be a relative url');
}
options = { ...options, returnTo };
}
if (nextConfig.organization) {
options = {
...options,
authorizationParams: { organization: nextConfig.organization, ...options.authorizationParams }
};
}
return await handler(req, res, options);
} catch (e) {
throw new HandlerError(e);
}
};
} | CWE-601 | 11 |
formatMessage() {
if (this.isATweet) {
const withUserName = this.message.replace(
TWITTER_USERNAME_REGEX,
TWITTER_USERNAME_REPLACEMENT
);
const withHash = withUserName.replace(
TWITTER_HASH_REGEX,
TWITTER_HASH_REPLACEMENT
);
const markedDownOutput = marked(withHash);
return markedDownOutput;
}
return marked(this.message, { breaks: true, gfm: true });
} | CWE-79 | 1 |
export function cleanObject(obj: any): any {
return Object.entries(obj).reduce(
(obj, [key, value]) =>
value === undefined
? obj
: {
...obj,
[key]: value
},
{}
);
} | CWE-915 | 35 |
export declare function setDeepProperty(obj: any, propertyPath: string, value: any): void;
export declare function getDeepProperty(obj: any, propertyPath: string): any; | CWE-915 | 35 |
userId: projectUsers.findOne().users.find((elem) => elem._id === entry._id.userId)?.profile?.name,
totalHours,
} | CWE-1236 | 12 |
function escapeShellArg(arg) {
return arg.replace(/'/g, `'\\''`);
} | CWE-88 | 3 |
function lazyLoadCustomEmoji(element: HTMLElement): void {
const img = createElement('img', CLASS_CUSTOM_EMOJI) as HTMLImageElement;
if (element.dataset.emoji) {
img.src = element.dataset.emoji;
element.innerText = '';
element.appendChild(img);
}
} | CWE-79 | 1 |
clip: Object.assign({ x: 0, y: 0 }, dimensions)
}, provider.getScreenshotOptions(options)));
return output;
} | CWE-94 | 14 |
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 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.