Skip to content

Instantly share code, notes, and snippets.

@sidorares
Created June 22, 2020 04:14
Show Gist options
  • Save sidorares/48532379b176610ee213935c8895b222 to your computer and use it in GitHub Desktop.
Save sidorares/48532379b176610ee213935c8895b222 to your computer and use it in GitHub Desktop.
const mysql = require('mysql2');
const server = mysql.createServer();
server.listen(3307);
let connectionId = 0;
server.on('connection', conn => {
connectionId++;
console.log(`New connection ${connectionId}`);
let acceptSalt = null;
let acceptAuthToken = null;
const remote = mysql.createConnection({
authPlugins: {
mysql_native_password: () => {
return pluginData => {
acceptSalt(pluginData);
return new Promise(accept => (acceptAuthToken = accept));
};
}
}
});
remote.serverConnId = connectionId;
conn.serverHandshake({
protocolVersion: 10,
serverVersion: 'mysql proxy',
connectionId,
statusFlags: 2,
characterSet: 8,
capabilityFlags: 16777183, // all flags but no compression
getSalt: () => new Promise(accept => (acceptSalt = accept)),
authCallback: ({ user, database, authToken }) => {
remote.config.user = user;
remote.config.database = database;
acceptAuthToken(authToken);
// might worth moving this to remote.on('connected') and add error handler
conn.writeOk();
conn.sequenceId = 0;
}
});
conn.on('query', sql => {
conn.sequenceId = 1;
console.log(`${remote.serverConnId} proxying query: ${sql}`);
remote.query(sql, function(err, rows, columns) {
if (err) {
console.log(err);
// TODO: proxy back error response
return;
}
if (Array.isArray(rows)) {
conn.writeTextResult(rows, columns);
conn.sequenceId = 0;
} else {
// response to an 'insert', 'update' or 'delete'
const result = rows;
conn.writeOk(result);
conn.sequenceId = 0;
}
});
});
conn.on('error', err => {
remote.end();
});
conn.on('quit', () => {
console.log('Client closed connection');
remote.end();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment