mcanoglu/cwe-class-group huggingface dataset:
constructor() {
        super();

        this.name = this.constructor.name + counter;
        counter += 1;

        this._timerId = null;
        this._timeout = 30000; // 30 seconds timeout
        this._socket = null;
        this.headerSize = 8;
        this.protocolVersion = 0;

        this._disconnecting = false;
        this._pendingBuffer = undefined;

        this.bytesWritten = 0;
        this.bytesRead = 0;

        this._theCallback = undefined;
        this.chunkWrittenCount = 0;
        this.chunkReadCount = 0;

        this._onSocketClosedHasBeenCalled = false;
        this._onSocketEndedHasBeenCalled = false;
        TCP_transport.registry.register(this);
    }

// Vulnerability class: CWE-400
private onWebSocket(req, socket, websocket) {
    websocket.on("error", onUpgradeError);

    if (
      transports[req._query.transport] !== undefined &&
      !transports[req._query.transport].prototype.handlesUpgrades
    ) {
      debug("transport doesnt handle upgraded requests");
      websocket.close();
      return;
    }

    // get client id
    const id = req._query.sid;

    // keep a reference to the ws.Socket
    req.websocket = websocket;

    if (id) {
      const client = this.clients[id];
      if (!client) {
        debug("upgrade attempt for closed client");
        websocket.close();
      } else if (client.upgrading) {
        debug("transport has already been trying to upgrade");
        websocket.close();
      } else if (client.upgraded) {
        debug("transport had already been upgraded");
        websocket.close();
      } else {
        debug("upgrading existing transport");

        // transport error handling takes over
        websocket.removeListener("error", onUpgradeError);

        const transport = this.createTransport(req._query.transport, req);
        if (req._query && req._query.b64) {
          transport.supportsBinary = false;
        } else {
          transport.supportsBinary = true;
        }
        transport.perMessageDeflate = this.opts.perMessageDeflate;
        client.maybeUpgrade(transport);
      }
    } else {
      // transport error handling takes over
      websocket.removeListener("error", onUpgradeError);

      const closeConnection = (errorCode, errorContext) =>
        abortUpgrade(socket, errorCode, errorContext);
      this.handshake(req._query.transport, req, closeConnection);
    }

    function onUpgradeError() {
      debug("websocket error before upgrade");
      // websocket.close() not needed
    }
  }

// Vulnerability class: CWE-754
private _buildData(data: Buffer) {
        if (data && this._stack.length === 0) {
            return data;
        }
        if (!data && this._stack.length === 1) {
            data = this._stack[0];
            this._stack.length = 0; // empty stack array
            return data;
        }
        this._stack.push(data);
        data = Buffer.concat(this._stack);
        this._stack.length = 0;
        return data;
    }

// Vulnerability class: CWE-400
const uploader = multer({ dest: path.join(__dirname, '.upload'), limits: { fileSize: 1024 ** 3 }, ...options.multer }).any()

  app.get(`${basePath}/`, [
    hooks0.onRequest,
    ctrlHooks0.onRequest,
    createValidateHandler(req => [
      Object.keys(req.query).length ? validateOrReject(Object.assign(new Validators.Query(), req.query), validatorOptions) : null
    ]),
    asyncMethodToHandler(controller0.get)
  ])

  app.post(`${basePath}/`, [
    hooks0.onRequest,
    ctrlHooks0.onRequest,
    uploader,
    formatMulterData([]),
    createValidateHandler(req => [
      validateOrReject(Object.assign(new Validators.Query(), req.query), validatorOptions),
      validateOrReject(Object.assign(new Validators.Body(), req.body), validatorOptions)
    ]),
    methodToHandler(controller0.post)
  ])

  app.get(`${basePath}/empty/noEmpty`, [
    hooks0.onRequest,
    methodToHandler(controller1.get)
  ])

  app.post(`${basePath}/multiForm`, [
    hooks0.onRequest,
    uploader,
    formatMulterData([['empty', false], ['vals', false], ['files', false]]),
    createValidateHandler(req => [
      validateOrReject(Object.assign(new Validators.MultiForm(), req.body), validatorOptions)
    ]),
    methodToHandler(controller2.post)
  ])

  app.get(`${basePath}/texts`, [
    hooks0.onRequest,
    methodToHandler(controller3.get)
  ])

  app.put(`${basePath}/texts`, [
    hooks0.onRequest,
    methodToHandler(controller3.put)
  ])

  app.put(`${basePath}/texts/sample`, [
    hooks0.onRequest,
    parseJSONBoby,
    methodToHandler(controller4.put)
  ])

  app.get(`${basePath}/users`, [
    hooks0.onRequest,
    hooks1.onRequest,
    ...ctrlHooks1.preHandler,
    asyncMethodToHandler(controller5.get)
  ])

  app.post(`${basePath}/users`, [
    hooks0.onRequest,
    hooks1.onRequest,
    parseJSONBoby,
    createValidateHandler(req => [
      validateOrReject(Object.assign(new Validators.UserInfo(), req.body), validatorOptions)
    ]),
    ...ctrlHooks1.preHandler,
    methodToHandler(controller5.post)
  ])

  return app
}

// Vulnerability class: CWE-20
WebContents.prototype.sendToFrame = function (frameId, channel, ...args) {
  if (typeof channel !== 'string') {
    throw new Error('Missing required channel argument');
  } else if (typeof frameId !== 'number') {
    throw new Error('Missing required frameId argument');
  }

  return this._sendToFrame(false /* internal */, frameId, channel, args);
};

// Vulnerability class: CWE-668
) => {
  if (!info || !info.sessionToken) {
    throw new Parse.Error(
      Parse.Error.INVALID_SESSION_TOKEN,
      'Invalid session token'
    );
  }
  const sessionToken = info.sessionToken;
  const selectedFields = getFieldNames(queryInfo)
    .filter(field => field.startsWith(keysPrefix))
    .map(field => field.replace(keysPrefix, ''));

  const keysAndInclude = extractKeysAndInclude(selectedFields);
  const { keys } = keysAndInclude;
  let { include } = keysAndInclude;

  if (validatedToken && !keys && !include) {
    return {
      sessionToken,
    };
  } else if (keys && !include) {
    include = 'user';
  }

  const options = {};
  if (keys) {
    options.keys = keys
      .split(',')
      .map(key => `user.${key}`)
      .join(',');
  }
  if (include) {
    options.include = include
      .split(',')
      .map(included => `user.${included}`)
      .join(',');
  }

  const response = await rest.find(
    config,
    Auth.master(config),
    '_Session',
    { sessionToken },
    options,
    info.clientVersion,
    info.context,
  );
  if (
    !response.results ||
    response.results.length == 0 ||
    !response.results[0].user
  ) {
    throw new Parse.Error(
      Parse.Error.INVALID_SESSION_TOKEN,
      'Invalid session token'
    );
  } else {
    const user = response.results[0].user;
    return {
      sessionToken,
      user,
    };
  }
};

// Vulnerability class: CWE-863
let getNftParentId = async (tokenIdHex: string) => {
            let txnhex = (await asyncSlpValidator.getRawTransactions([tokenIdHex]))[0];
            let tx = Primatives.Transaction.parseFromBuffer(Buffer.from(txnhex, 'hex'));
            let nftBurnTxnHex = (await asyncSlpValidator.getRawTransactions([tx.inputs[0].previousTxHash]))[0];
            let nftBurnTxn = Primatives.Transaction.parseFromBuffer(Buffer.from(nftBurnTxnHex, 'hex'));
            let slp = new Slp(this.BITBOX);
            let nftBurnSlp = slp.parseSlpOutputScript(Buffer.from(nftBurnTxn.outputs[0].scriptPubKey));
            if (nftBurnSlp.transactionType === SlpTransactionType.GENESIS) {
                return tx.inputs[0].previousTxHash;
            }
            else {
                return nftBurnSlp.tokenIdHex;
            }
        }

// Vulnerability class: CWE-20
private _renew_security_token() {
        doDebug && debugLog("ClientSecureChannelLayer#_renew_security_token");

        // istanbul ignore next
        if (!this.isValid()) {
            // this may happen if the communication has been closed by the client or the sever
            warningLog("Invalid socket => Communication has been lost, cannot renew token");
            return;
        }

        const isInitial = false;
        this._open_secure_channel_request(isInitial, (err?: Error | null) => {
            /* istanbul ignore else */
            if (!err) {
                doDebug && debugLog(" token renewed");
                /**
                 * notify the observers that the security has been renewed
                 * @event security_token_renewed
                 */
                this.emit("security_token_renewed");
            } else {
                if (doDebug) {
                    debugLog("ClientSecureChannelLayer: Warning: securityToken hasn't been renewed -> err ", err);
                }
                // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX CHECK ME !!!
                this.closeWithError(new Error("Restarting because Request has timed out during OpenSecureChannel"), () => {
                    /* */
                });
            }
        });
    }

// Vulnerability class: CWE-400
etsyApiFetch(endpoint, options) {
     this._assumeField('endpoint', endpoint);
     return new Promise((resolve, reject) => {
         const getQueryString = queryString.stringify(this.getOptions(options));
         fetch(`${this.apiUrl}${endpoint}?${getQueryString}`)
           .then(response => EtsyClient._response(response, resolve, reject))
           .catch(reject);
     });
  }

// Vulnerability class: CWE-200
async function waitSessionCountChange(currentSessionCountMonitoredItem) {

    return await new Promise((resolve,reject) => {
        const timer = setTimeout(() => {
            reject(new Error("Never received ", currentSessionCountMonitoredItem.toString()));
        }, 5000);

        currentSessionCountMonitoredItem.once("changed", function (dataValue) {
            clearTimeout(timer);
            const new_currentSessionCount = dataValue.value.value;
            debugLog("new currentSessionCount=", dataValue.toString());
            resolve(new_currentSessionCount);
        });
    });
}

// Vulnerability class: CWE-400
getScriptOperations(script: Buffer) {
        let ops: PushDataOperation[] = [];
        try {
            let n = 0;
            let dlen: number;
            while (n < script.length) {
                let op: PushDataOperation = { opcode: script[n], data: null }
                n += 1;
                if(op.opcode <= this.BITBOX.Script.opcodes.OP_PUSHDATA4) {
                    if(op.opcode < this.BITBOX.Script.opcodes.OP_PUSHDATA1)
                        dlen = op.opcode;
                    else if(op.opcode === this.BITBOX.Script.opcodes.OP_PUSHDATA1) {
                        dlen = script[n];
                        n += 1;
                    }
                    else if(op.opcode === this.BITBOX.Script.opcodes.OP_PUSHDATA2) {
                        dlen = script.slice(n, n + 2).readUIntLE(0,2);
                        n += 2;
                    }
                    else {
                        dlen = script.slice(n, n + 4).readUIntLE(0,4);
                        n += 4;
                    }
                    if((n + dlen) > script.length) {
                        throw Error('IndexError');
                    }
                    if(dlen > 0)
                        op.data = script.slice(n, n + dlen);
                    n += dlen
                }
                ops.push(op);
            }
        } catch(e) {
            //console.log(e);
            throw Error('truncated script')
        }
        return ops;
    }

// Vulnerability class: CWE-20
buildRawNFT1GenesisTx(config: configBuildRawNFT1GenesisTx, type = 0x01) {
        let config2: configBuildRawGenesisTx = {
            slpGenesisOpReturn: config.slpNFT1GenesisOpReturn,
            mintReceiverAddress: config.mintReceiverAddress,
            mintReceiverSatoshis: config.mintReceiverSatoshis,
            batonReceiverAddress: null,
            bchChangeReceiverAddress: config.bchChangeReceiverAddress,
            input_utxos: config.input_utxos,
            allowed_token_burning: [ config.parentTokenIdHex ]
        }

        return this.buildRawGenesisTx(config2);
    }

// Vulnerability class: CWE-20
userPassword: bcrypt.hashSync(req.body.userPassword, 10),
        isAdmin: isAdmin
    };

    // check for existing user
    db.users.findOne({'userEmail': req.body.userEmail}, (err, user) => {
        if(user){
            // user already exists with that email address
            console.error(colors.red('Failed to insert user, possibly already exists: ' + err));
            req.session.message = 'A user with that email address already exists';
            req.session.messageType = 'danger';
            res.redirect('/admin/user/new');
            return;
        }
        // email is ok to be used.
        db.users.insert(doc, (err, doc) => {
            // show the view
            if(err){
                if(doc){
                    console.error(colors.red('Failed to insert user: ' + err));
                    req.session.message = 'User exists';
                    req.session.messageType = 'danger';
                    res.redirect('/admin/user/edit/' + doc._id);
                    return;
                }
                console.error(colors.red('Failed to insert user: ' + err));
                req.session.message = 'New user creation failed';
                req.session.messageType = 'danger';
                res.redirect('/admin/user/new');
                return;
            }
            req.session.message = 'User account inserted';
            req.session.messageType = 'success';

            // if from setup we add user to session and redirect to login.
            // Otherwise we show users screen
            if(urlParts.path === '/admin/setup'){
                req.session.user = req.body.userEmail;
                res.redirect('/admin/login');
                return;
            }
            res.redirect('/admin/users');
        });
    });
});

// Vulnerability class: CWE-732
calculateGenesisCost(genesisOpReturnLength: number, inputUtxoSize: number, batonAddress: string|null, bchChangeAddress?: string, feeRate = 1) {
        return this.calculateMintOrGenesisCost(genesisOpReturnLength, inputUtxoSize, batonAddress, bchChangeAddress, feeRate);
    }

// Vulnerability class: CWE-20
export function cloneTask(repo: string | undefined, directory: string | undefined, customArgs: string[]): StringTask<string> {
   const commands = ['clone', ...customArgs];
   if (typeof repo === 'string') {
      commands.push(repo);
   }
   if (typeof directory === 'string') {
      commands.push(directory);
   }

   return straightThroughStringTask(commands);
}

// Vulnerability class: CWE-77
export function exportVariable(name: string, val: any): void {
  const convertedVal = toCommandValue(val)
  process.env[name] = convertedVal

  const filePath = process.env['GITHUB_ENV'] || ''
  if (filePath) {
    const delimiter = '_GitHubActionsFileCommandDelimeter_'
    const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`
    issueFileCommand('ENV', commandValue)
  } else {
    issueCommand('set-env', {name}, convertedVal)
  }
}

// Vulnerability class: CWE-74
resetPassword(req) {
    const config = req.config;

    if (!config) {
      this.invalidRequest();
    }

    if (!config.publicServerURL) {
      return this.missingPublicServerURL();
    }

    const { username, token, new_password } = req.body;

    if ((!username || !token || !new_password) && req.xhr === false) {
      return this.invalidLink(req);
    }

    if (!username) {
      throw new Parse.Error(Parse.Error.USERNAME_MISSING, 'Missing username');
    }

    if (!token) {
      throw new Parse.Error(Parse.Error.OTHER_CAUSE, 'Missing token');
    }

    if (!new_password) {
      throw new Parse.Error(Parse.Error.PASSWORD_MISSING, 'Missing password');
    }

    return config.userController
      .updatePassword(username, token, new_password)
      .then(
        () => {
          return Promise.resolve({
            success: true,
          });
        },
        err => {
          return Promise.resolve({
            success: false,
            err,
          });
        }
      )
      .then(result => {
        const params = qs.stringify({
          username: username,
          token: token,
          id: config.applicationId,
          error: result.err,
          app: config.appName,
        });

        if (req.xhr) {
          if (result.success) {
            return Promise.resolve({
              status: 200,
              response: 'Password successfully reset',
            });
          }
          if (result.err) {
            throw new Parse.Error(Parse.Error.OTHER_CAUSE, `${result.err}`);
          }
        }

        const encodedUsername = encodeURIComponent(username);
        const location = result.success
          ? `${config.passwordResetSuccessURL}?username=${encodedUsername}`
          : `${config.choosePasswordURL}?${params}`;

        return Promise.resolve({
          status: 302,
          location,
        });
      });
  }

// Vulnerability class: CWE-863
this.transport.init(socket, (err?: Error) => {
            if (err) {
                callback(err);
            } else {
                this._rememberClientAddressAndPort();

                this.messageChunker.maxMessageSize = this.transport.maxMessageSize;

                // bind low level TCP transport to messageBuilder
                this.transport.on("message", (messageChunk: Buffer) => {
                    assert(this.messageBuilder);
                    this.messageBuilder.feed(messageChunk);
                });
                debugLog("ServerSecureChannelLayer : Transport layer has been initialized");
                debugLog("... now waiting for OpenSecureChannelRequest...");

                ServerSecureChannelLayer.registry.register(this);

                this._wait_for_open_secure_channel_request(callback, this.timeout);
            }
        });

// Vulnerability class: CWE-400
constructor() {
        super();
        this._aborted = 0;
        this._helloReceived = false;
        this.receiveBufferSize = 0;
        this.sendBufferSize = 0;
        this.maxMessageSize = 0;
        this.maxChunkCount = 0;
        this.protocolVersion = 0;
    }

// Vulnerability class: CWE-400
verifyEmail(req) {
    const { token, username } = req.query;
    const appId = req.params.appId;
    const config = Config.get(appId);

    if (!config) {
      this.invalidRequest();
    }

    if (!config.publicServerURL) {
      return this.missingPublicServerURL();
    }

    if (!token || !username) {
      return this.invalidLink(req);
    }

    const userController = config.userController;
    return userController.verifyEmail(username, token).then(
      () => {
        const params = qs.stringify({ username });
        return Promise.resolve({
          status: 302,
          location: `${config.verifyEmailSuccessURL}?${params}`,
        });
      },
      () => {
        return this.invalidVerificationLink(req);
      }
    );
  }

// Vulnerability class: CWE-863
'X-Parse-Session-Token': user1.getSessionToken(),
                    },
                  },
                });

                let foundGraphQLClassReadPreference = false;
                let foundUserClassReadPreference = false;
                databaseAdapter.database.serverConfig.cursor.calls
                  .all()
                  .forEach((call) => {
                    if (
                      call.args[0].ns.collection.indexOf('GraphQLClass') >= 0
                    ) {
                      foundGraphQLClassReadPreference = true;
                      expect(call.args[0].options.readPreference.mode).toBe(
                        ReadPreference.PRIMARY
                      );
                    } else if (
                      call.args[0].ns.collection.indexOf('_User') >= 0
                    ) {
                      foundUserClassReadPreference = true;
                      expect(call.args[0].options.readPreference.mode).toBe(
                        ReadPreference.PRIMARY
                      );
                    }
                  });

                expect(foundGraphQLClassReadPreference).toBe(true);
                expect(foundUserClassReadPreference).toBe(true);
              } catch (e) {
                handleError(e);
              }
            });

// Vulnerability class: CWE-863
session: session.fromPartition('about-window'),
        spellcheck: false,
        webviewTag: false,
      },
      width: WINDOW_SIZE.WIDTH,
    });
    aboutWindow.setMenuBarVisibility(false);

    // Prevent any kind of navigation
    // will-navigate is broken with sandboxed env, intercepting requests instead
    // see https://github.com/electron/electron/issues/8841
    aboutWindow.webContents.session.webRequest.onBeforeRequest(async ({url}, callback) => {
      // Only allow those URLs to be opened within the window
      if (ABOUT_WINDOW_ALLOWLIST.includes(url)) {
        return callback({cancel: false});
      }

      // Open HTTPS links in browser instead
      if (url.startsWith('https://')) {
        await shell.openExternal(url);
      } else {
        logger.info(`Attempt to open URL "${url}" in window prevented.`);
        callback({redirectURL: ABOUT_HTML});
      }
    });

    // Locales
    ipcMain.on(EVENT_TYPE.ABOUT.LOCALE_VALUES, (event, labels: locale.i18nLanguageIdentifier[]) => {
      if (aboutWindow) {
        const isExpected = event.sender.id === aboutWindow.webContents.id;
        if (isExpected) {
          const resultLabels: Record<string, string> = {};
          labels.forEach(label => (resultLabels[label] = locale.getText(label)));
          event.sender.send(EVENT_TYPE.ABOUT.LOCALE_RENDER, resultLabels);
        }
      }
    });

    // Close window via escape
    aboutWindow.webContents.on('before-input-event', (_event, input) => {
      if (input.type === 'keyDown' && input.key === 'Escape') {
        if (aboutWindow) {
          aboutWindow.close();
        }
      }
    });

    aboutWindow.on('closed', () => (aboutWindow = undefined));

    await aboutWindow.loadURL(ABOUT_HTML);

    if (aboutWindow) {
      aboutWindow.webContents.send(EVENT_TYPE.ABOUT.LOADED, {
        copyright: config.copyright,
        electronVersion: config.version,
        productName: config.name,
        webappVersion,
      });
    }
  }

  aboutWindow.show();
};

// Vulnerability class: CWE-20
from: globalDb.getServerTitle() + " <" + returnAddress + ">",
        subject: "Testing your Sandstorm's SMTP setting",
        text: "Success! Your outgoing SMTP is working.",
        smtpConfig: restConfig,
      });
    } catch (e) {
      // Attempt to give more accurate error messages for a variety of known failure modes,
      // and the actual exception data in the event a user hits a new failure mode.
      if (e.syscall === "getaddrinfo") {
        if (e.code === "EIO" || e.code === "ENOTFOUND") {
          throw new Meteor.Error("getaddrinfo " + e.code, "Couldn't resolve \"" + smtpConfig.hostname + "\" - check for typos or broken DNS.");
        }
      } else if (e.syscall === "connect") {
        if (e.code === "ECONNREFUSED") {
          throw new Meteor.Error("connect ECONNREFUSED", "Server at " + smtpConfig.hostname + ":" + smtpConfig.port + " refused connection.  Check your settings, firewall rules, and that your mail server is up.");
        }
      } else if (e.name === "AuthError") {
        throw new Meteor.Error("auth error", "Authentication failed.  Check your credentials.  Message from " +
                smtpConfig.hostname + ": " + e.data);
      }

      throw new Meteor.Error("other-email-sending-error", "Error while trying to send test email: " + JSON.stringify(e));
    }
  },

// Vulnerability class: CWE-287
requestResetPassword(req) {
    const config = req.config;

    if (!config) {
      this.invalidRequest();
    }

    if (!config.publicServerURL) {
      return this.missingPublicServerURL();
    }

    const { username, token } = req.query;

    if (!username || !token) {
      return this.invalidLink(req);
    }

    return config.userController.checkResetTokenValidity(username, token).then(
      () => {
        const params = qs.stringify({
          token,
          id: config.applicationId,
          username,
          app: config.appName,
        });
        return Promise.resolve({
          status: 302,
          location: `${config.choosePasswordURL}?${params}`,
        });
      },
      () => {
        return this.invalidLink(req);
      }
    );
  }

// Vulnerability class: CWE-863
WebContents.prototype._sendToFrameInternal = function (frameId, channel, ...args) {
  if (typeof channel !== 'string') {
    throw new Error('Missing required channel argument');
  } else if (typeof frameId !== 'number') {
    throw new Error('Missing required frameId argument');
  }

  return this._sendToFrame(true /* internal */, frameId, channel, args);
};

// Vulnerability class: CWE-668
async function logPlatform(logger: Logger): Promise<void> {
	const os = require('os');
    let platform = os.platform();
    logger.log(`OS is ${platform}`);
	if (platform === 'darwin' || platform === 'win32') {
		return;
	}

    const osInfo = require('linux-os-info');
    const result = await osInfo();
    const dist = result.id;
    logger.log(`dist: ${dist}`);
}

// Vulnerability class: CWE-863
constructor(options: PacketAssemblerOptions) {
        super();
        this._stack = [];
        this.expectedLength = 0;
        this.currentLength = 0;
        this.readMessageFunc = options.readMessageFunc;
        this.minimumSizeInBytes = options.minimumSizeInBytes || 8;
        assert(typeof this.readMessageFunc === "function", "packet assembler requires a readMessageFunc");
    }

// Vulnerability class: CWE-400
private _on_receive_message_chunk(messageChunk: Buffer) {
        /* istanbul ignore next */
        if (doDebug1) {
            const _stream = new BinaryStream(messageChunk);
            const messageHeader = readMessageHeader(_stream);
            debugLog("CLIENT RECEIVED " + chalk.yellow(JSON.stringify(messageHeader) + ""));
            debugLog("\n" + hexDump(messageChunk));
            debugLog(messageHeaderToString(messageChunk));
        }
        this.messageBuilder.feed(messageChunk);
    }

// Vulnerability class: CWE-400