![Namecheap Takes Down Polyfill.io Service Following Supply Chain Attack](https://cdn.sanity.io/images/cgdhsj6q/production/6af25114feaaac7179b18127c83327568ff592d1-1024x1024.webp?w=800&fit=max&auto=format)
Security News
Namecheap Takes Down Polyfill.io Service Following Supply Chain Attack
Polyfill.io has been serving malware for months via its CDN, after the project's open source maintainer sold the service to a company based in China.
spdy
Advanced tools
Package description
The spdy npm package is designed to support the SPDY and HTTP/2 protocols in Node.js. It provides server and client functionality, allowing developers to create SPDY/HTTP2 servers and clients with ease. This package is particularly useful for improving web application performance by leveraging the advanced features of these protocols, such as multiplexing, server push, and header compression.
Creating an SPDY/HTTP2 server
This code sample demonstrates how to create a simple SPDY/HTTP2 server using the spdy package along with Express. It sets up a server that listens on port 3000 and serves a simple message over SPDY/HTTP2.
const spdy = require('spdy');
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.end('Hello over SPDY/HTTP2');
});
const options = {
key: fs.readFileSync('<path-to-key>'),
cert: fs.readFileSync('<path-to-cert>')
};
spdy.createServer(options, app).listen(3000, () => {
console.log('Server is running on https://localhost:3000');
});
Creating an SPDY/HTTP2 client
This code sample shows how to create an SPDY/HTTP2 client that connects to a server. It demonstrates making a request to the server and handling the response, including reading response headers and data.
const spdy = require('spdy');
const http2 = require('http2');
const client = spdy.connect('https://localhost:3000', (err, socket) => {
if (err) {
throw new Error('Connection failed');
}
const req = http2.request({
':path': '/'
});
req.on('response', (headers) => {
console.log('Response headers:', headers);
});
req.setEncoding('utf8');
req.on('data', (chunk) => console.log(chunk));
req.end();
});
The http2 package is a core module in Node.js that provides an implementation of the HTTP/2 protocol. It offers similar functionalities to spdy, such as creating servers and clients that can communicate over HTTP/2. However, spdy provides additional support for the SPDY protocol, which is not covered by the http2 module.
node-http2 is an npm package that also implements the HTTP/2 protocol. It provides an API for creating HTTP/2 servers and clients. Compared to spdy, node-http2 focuses solely on HTTP/2 without support for SPDY. spdy might offer a more comprehensive solution for developers looking to support both protocols.
Readme
With this module you can create SPDY servers in node.js with natural http module interface and fallback to regular https (for browsers that don't support SPDY yet).
Server:
var spdy = require('spdy'),
fs = require('fs');
var options = {
key: fs.readFileSync(__dirname + '/keys/spdy-key.pem'),
cert: fs.readFileSync(__dirname + '/keys/spdy-cert.pem'),
ca: fs.readFileSync(__dirname + '/keys/spdy-ca.pem'),
// **optional** SPDY-specific options
windowSize: 1024 * 1024, // Server's window size
// **optional** if true - server will send 3.1 frames on 3.0 *plain* spdy
autoSpdy31: false
};
var server = spdy.createServer(options, function(req, res) {
res.writeHead(200);
res.end('hello world!');
});
server.listen(443);
Client:
var spdy = require('spdy');
var http = require('http');
var agent = spdy.createAgent({
host: 'www.google.com',
port: 443,
// Optional SPDY options
spdy: {
plain: false or true,
ssl: false or true,
version: 3 // Force SPDY version
}
});
http.get({
host: 'www.google.com',
agent: agent
}, function(response) {
console.log('yikes');
// Here it goes like with any other node.js HTTP request
// ...
// And once we're done - we may close TCP connection to server
// NOTE: All non-closed requests will die!
agent.close();
}).end();
And by popular demand - usage with express:
var spdy = require('spdy'),
express = require('express'),
fs = require('fs');
var options = { /* the same as above */ };
var app = express();
app.use(/* your favorite middleware */);
var server = spdy.createServer(options, app);
server.listen(443);
API is compatible with http
and https
module, but you can use another
function as base class for SPDYServer.
spdy.createServer(
[base class constructor, i.e. https.Server],
{ /* keys and options */ }, // <- the only one required argument
[request listener]
).listen([port], [host], [callback]);
Request listener will receive two arguments: request
and response
. They're
both instances of http
's IncomingMessage
and OutgoingMessage
. But three
custom properties are added to both of them: streamID
, isSpdy
,
spdyVersion
. The first one indicates on which spdy stream are sitting request
and response. Second is always true and can be checked to ensure that incoming
request wasn't received by HTTPS fallback and last one is a number representing
used SPDY protocol version (2 or 3 for now).
It is possible to initiate 'push' streams to send content to clients before the client requests it.
spdy.createServer(options, function(req, res) {
var headers = { 'content-type': 'application/javascript' };
var stream = res.push('/main.js', headers);
stream.on('acknowledge', function() {
});
stream.on('error', function() {
});
stream.end('alert("hello from push stream!");');
res.end('<script src="/main.js"></script>');
}).listen(443);
Push is accomplished via the push()
method invoked on the current response
object (this works for express.js response objects as well). The format of the
push()
method is:
.push('full or relative url', { ... headers ... }, optional priority, callback)
You can use either full ( http://host/path
) or relative ( /path
) urls with
.push()
. headers
are the same as for regular response object. callback
will receive two arguments: err
(if any error is happened) and stream
(stream object have API compatible with a
net.Socket ).
Client usage:
var agent = spdy.createAgent({ /* ... */ });
agent.on('push', function(stream) {
stream.on('error', function(err) {
// Handle error
});
// Read data from stream
// ...
// stream.associated points to associated client-initiated stream
});
NOTE: You're responsible for the stream
object once given it in .push()
callback. Hence ignoring error
events on it might result in uncaught
exceptions and crash your program.
Server usage:
function (req, res) {
// Send trailing headers to client
res.addTrailers({ header1: 'value1', header2: 'value2' });
// On client's trailing headers
req.on('trailers', function(headers) {
// ...
});
}
Client usage:
var req = http.request({ agent: spdyAgent, /* ... */ }).function (res) {
// On server's trailing headers
res.on('trailers', function(headers) {
// ...
});
});
req.write('stuff');
req.addTrailers({ /* ... */ });
req.end();
All options supported by
tls are working
with node-spdy. In addition, maxStreams
options is available. it allows you
controlling maximum concurrent streams
protocol option (if client will start more streams than that limit, RST_STREAM
will be sent for each additional stream).
Additional options:
plain
- if defined, server will ignore NPN and ALPN data and choose whether
to use spdy or plain http by looking at first data packet.ssl
- if false
and options.plain
is true
, http.Server
will be used
as a base
class for created server.maxChunk
- if set and non-falsy, limits number of bytes sent in one DATA
chunk. Setting it to non-zero value is recommended if you care about
interleaving of outgoing data from multiple different streams.
(defaults to 8192)This software is licensed under the MIT License.
Copyright Fedor Indutny, 2014.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
FAQs
Implementation of the SPDY protocol on node.js.
The npm package spdy receives a total of 9,037,691 weekly downloads. As such, spdy popularity was classified as popular.
We found that spdy demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Polyfill.io has been serving malware for months via its CDN, after the project's open source maintainer sold the service to a company based in China.
Security News
OpenSSF is warning open source maintainers to stay vigilant against reputation farming on GitHub, where users artificially inflate their status by manipulating interactions on closed issues and PRs.
Security News
A JavaScript library maintainer is under fire after merging a controversial PR to support legacy versions of Node.js.