npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

web-token

v1.1.4

Published

Fast and safe token generator for web and any app

Downloads

298

Readme

web-token

  • Generate safe tokens for web and networks Fast & memory wise alternative for "jws" & "jwt" & "json web token"

  • Hash passwords before storing them on the database, best alternative to Bcrypt.

Sign tokens

Use it to sign cookies, authorizations, ...

Sign key

import { sign } from 'web-token';

const signedKey: Buffer= sign(
	/** Data to sign */
	data:	string | NodeJS.ArrayBufferView,
	/** Secret key */
	secret:	string | Buffer,
	/** @optional token expiration date as timestamp */
	expires: number = -1
	/** @Optional Hash algorithm */
	algorithm: HashAlgorithm = "sha256"
);

// Convert to string using any encoding
const encodedSignedKey= signedKey.toString('base64url');

Supported encoding by "::toString" are:

  • ascii
  • utf8
  • utf-8
  • utf16le
  • ucs2
  • ucs-2
  • base64
  • base64url
  • latin1
  • binary
  • hex'

Examples:

import { sign } from "web-token";

// Sign text
var signedData = sign("My-vulnerable-id", "my-secret-key");

// Sign object
var signedObj = sign(
	JSON.stringify({ id: "xxxx", expires: "2070-01-01" }),
	"my-secret-key"
);

// Sign Buffer
var signedObj = sign(Buffer.from("myData", "my-encoding"), "Secret-key");

Verify signature

import { verify } from "web-token";

{
	isValid:	boolean,
	expires:	number,
	data:		Buffer
}= verify(
	/** Signed data */
	data: string | Buffer,
	/** Secret key */
	secret: string | Buffer,
	/** @Optional hash algorithm */
	hashAlgorithm: HashAlgorithm = "sha512"
);

Examples

1- Sign & verify simple text:

import { sign, verify } from "web-token";
const SECRET_KEY = "my-secret-key";
const TextToEncode = "My-vulnerable-id";

//* SIGN DATA ----------------------
var signedDataAsText = sign(
	TextToEncode,
	SECRET_KEY,
	55541455485 // Expiration date
).toString("base64url");

//* VERIFY & DECODE ----------------
var info = verify(Buffer.from(signedDataAsText, "base64url"), SECRET_KEY);
if (info.isValid === false) throw new Error("Invalid token");
else if (info.expires < Date.now()) throw new Error("Expired token");

/**
 * @Assert TextToEncode === originalData
 */
const originalData = info.data.toString();

2- Sign & Verify Object as JSON:

import { sign, verify } from "web-token";
const SECRET_KEY = "my-secret-key";
// Object to encode
const ObjectToEncode = { id: 1, firstName: "khalid", lastName: "RAFIK" };

//* SIGN DATA ----------------------
var signedDataAsText = sign(
	JSON.stringify(ObjectToEncode),
	SECRET_KEY,
	55541455485 // Expiration date
).toString("base64url");

//* VERIFY & DECODE ----------------
var info = verify(Buffer.from(signedDataAsText, "base64url"), SECRET_KEY);
if (info.isValid === false) throw new Error("Invalid token");
else if (info.expires < Date.now()) throw new Error("Expired token");

/**
 * @Assert ObjectToEncode equals originalData
 */
const originalData = JSON.parse(info.data.toString());

Hash password

Create Hash

For security reasons: NEVER store your user passwords plain in your database . Store password hashes instead.

import { hash } from "web-token";

var passwordHash= hash(
	data: string | Buffer,
	secret: string | Buffer,
	hashAlgorithm: HashAlgorithm = "sha512"
);

// Example: Generate password hash & convert it to Hexadecimal
var hs= hash('pass', 'secretKey').toString('hex');

_ NOTE: Better to store password hash when ever possible as buffer instead of string. This will enhance performance and reduce required space _

Compare passwords

// Password sent by client form
const userPassword= ...
// Password stored in the database
const dbUserPassword= ...

// If password is stored as string, convert it to Buffer first
// Use the same encoding as when you converted it to string (most cases hex or base64)
// We recommend to store passwords as buffers when possible to preserve space and performance.
const buffPassword= Buffer.from(dbUserPassword, 'hex');

// Hash requested password
var reqPassword= hash(userPassword, 'Your secret');

// And than compare theme
// Buffer::compare will return "0" if equals, 1 or -1 otherwise
var areEquals= reqPassword.compare(buffPassword) === 0;

Author

khalid RAFIK Senior full Stack Web, Mobile, Data & Security Engineer [email protected]