GithubHelp home page GithubHelp logo

panva / paseto Goto Github PK

View Code? Open in Web Editor NEW
370.0 6.0 25.0 334 KB

PASETO (Platform-Agnostic SEcurity TOkens) for Node.js with no dependencies

License: MIT License

JavaScript 95.95% TypeScript 4.05%
paseto encrypt decrypt sign verify decode

paseto's Introduction

paseto

PASETO: Platform-Agnostic SEcurity TOkens for Node.js with no dependencies.

Implemented Protocol Versions

v1 v2 v3 v4
local
public

Support

If you or your business use paseto, please consider becoming a sponsor so I can continue maintaining it and adding new features carefree.

Documentation

Usage

Installing paseto

npm install paseto

Usage

const paseto = require('paseto')

// Generic (all versions) APIs
const { decode } = paseto

// PASETO Protocol Version v1 specific API
const { V1 } = paseto // { sign, verify, encrypt, decrypt, generateKey }

// PASETO Protocol Version v2 specific API
const { V2 } = paseto // { sign, verify, generateKey }

// PASETO Protocol Version v3 specific API
const { V3 } = paseto // { sign, verify, encrypt, decrypt, generateKey }

// PASETO Protocol Version v4 specific API
const { V4 } = paseto // { sign, verify, generateKey }

// errors utilized by paseto
const { errors } = paseto

Producing tokens

const { V4: { sign } } = paseto

(async () => {
  {
    const token = await sign({ sub: 'johndoe' }, privateKey)
    // v4.public.eyJzdWIiOiJqb2huZG9lIiwiaWF0IjoiMjAyMS0wOC0wM1QwNTozOTozNy42NzNaIn3AW3ri7P5HpdakJmZvhqssz7Wtzi2Rb3JafwKplLoCWuMkITYOo5KNNR5NMaeAR6ePZ3xWUcbO0R11YLb02awO
  }
})()

Consuming tokens

const { V4: { verify } } = paseto

(async () => {
  {
    const payload = await verify(token, publicKey)
    // { sub: 'johndoe', iat: '2019-07-01T15:22:47.982Z' }
  }
})()

FAQ

Supported Library Versions

Version Security Fixes 🔑 Other Bug Fixes 🐞 New Features ⭐ Node.js version supported
3.x.x >= 16.0.0
2.x.x ^12.19.0 || >=14.15.0
1.x.x >= 12.0.0

Semver?

Yes. Everything that's either exported in the TypeScript definitions file or documented is subject to Semantic Versioning 2.0.0. The rest is to be considered private API and is subject to change between any versions.

How do I use it outside of Node.js

It is only built for Node.js environment versions >=16.0.0

paseto's People

Contributors

dborysov avatar dependabot[bot] avatar krisgardiner avatar kschaefe avatar lhchavez avatar panva avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

paseto's Issues

Replacing libsodium-wrappers

Hi @panva!

only to let you know that i forked this lib to replace libsodium-wrappers for @StableLib modules, the reason is because i didn't want to add more libraries (and weight) to my stack. I know is very subjective, so only if you want i can do a pull request. Just let me know.

Thanks for your amazing work!

Not using ISO8601 Date Format

What happened?

JSON.stringify does not use a valid ISO8601 date format.

Version

3.1.2

Node.js Version

18

Code to reproduce

const paseto = require('paseto')
const { V3: { sign } } = paseto;

await sign({ 'a' : 'b' }, privateKey, {'expiresIn': '1 year'});

Required

  • I have searched the issues tracker and discussions for similar topics and couldn't find anything related.
  • I agree to follow this project's Code of Conduct

question: Nodejs Crypto vs libsodium

Hi!

Problem: lack of compatibility(?) between generated private keys via Nodejs Crypto module and various libsodium implementations.

It seems that Nodejs Crypto expects 48 bytes length keys whereas libsodium implementations provide 64 bytes length private keys. Of course due to that fact const token = await sign({ sub: 'johndoe' }, privateKey) fails.

Already stated a question on Nodejs nodejs/help#2543 help repo, but perhaps you could put more light on this problem, maybe I'm just missing something?

A low level example of the problem:

'use strict';

var sodium = require('sodium-native')
const paseto = require('paseto');
const { V2 } = paseto
const { V2: { sign } } = paseto
const crypto = require('crypto')
const { promisify } = require('util')
const generateKeyPair = promisify(crypto.generateKeyPair)
const {
  createPrivateKey,
  KeyObject
} = require('crypto');


let pk = Buffer.alloc(32);
let sk = Buffer.alloc(64);

// Create key pair with libsodium impl:
sodium.crypto_sign_keypair(pk, sk);

console.log(sk.length);

(async () => {
  const { privateKey } = await generateKeyPair('ed25519')
  const exp = privateKey.export({ type: 'pkcs8', format: 'der' });
  console.log(exp.length)

  // Try to instantiate Crypto private key from the one generated via libsodium:
  // Here it will fail with Error: error:0D07207B:asn1 encoding routines:ASN1_get_object:header too long
  createPrivateKey({ key: sk, format: 'der', type: 'pkcs8' }); 


})();

At paseto/lib/v1/sign.js

What happened?

I've got a bug

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'RSA_PKCS1_PSS_PADDING')
    at node_modules/paseto/lib/v1/sign.js (sign.js:3:28)
    at __require2 (chunk-CLUHM6AE.js?v=ffcba462:19:50)
    at node_modules/paseto/lib/v1/index.js (index.js:1:14)
    at __require2 (chunk-CLUHM6AE.js?v=ffcba462:19:50)
    at node_modules/paseto/lib/index.js (index.js:2:12)

Version

v3.1.2

Node.js Version

v16.0.4

Code to reproduce

Just a simple demo, I wonder if it's due to my local environment

Required

  • I have searched the issues tracker and discussions for similar topics and couldn't find anything related.
  • I agree to follow this project's Code of Conduct

stuck on key length error

const keyword = "..."

const key = crypto.createSecretKey(Buffer.from(keyword, "base64"));

key.byteLength // >= 32

V2.encrypt(payload, key);
// V2.local secret key must be 32 bytes long symmetric key

Always get this error even when the secret is long enough.

Node 14 bug - TypeError: Cannot read property 'subtle' of undefined (line 10 of crypto_worker.js)

What happened?

If the Node version is 14 (have not tested below 14), I get this error when importing V2 Paseto.

If I upgrade to Node 16 then this issue seems fixed, but some of my other packages don't support Node 16 yet, so this isn't ideal.

Version

v3.0.1

Node.js Version

v14.17.6

Code to reproduce

const { V2 } = require('paseto');

  • I have searched the issues tracker and discussions for similar topics and couldn't find anything related.
  • I agree to follow this project's Code of Conduct

bug: typescript types missing in install

Describe the bug
Typescript types aren't included in build on NPM

To Reproduce
npm install paseto or yarn add paseto

Expected behaviour
That typescript types be included in node_modules/paseto/types

Environment:

  • paseto version: [v1.0.2]

  • node version: [v12.10.0]

  • [N/A] the bug is happening on latest paseto version too.

  • [*] i have searched the issues tracker on github for similar issues and couldn't find anything related.

bug: Library breaks on lambda

Describe the bug

I tried the same code locally as I did on aws lambda, and the lambda container could not execute. I am using a custom runtime (node v12.13) from here (https://github.com/lambci/node-custom-lambda) as the only official lambda runtimes are v8 and v10 but I don't think that's the issue.

To Reproduce
Here's a sample lambda function to test the library in that I'm using

export const test: APIGatewayProxyHandler = async (_event, _context) => {
  let response = {statusCode:200, headers: {}, body: "{}"}
  //console.log(_event)
  let k2 = await V2.generateKey('public')
  let token = await V2.sign({'test': '12'}, k2)
  console.log("new token: ", token)
  let pub = crypto.createPublicKey(k2)
  let req = await V2.verify(token, pub)
  console.log("req: ", req);
  
  return response;
}

Expected behavior
When used locally this code creates and verifies a token

Environment:

  • node version: [e.g. v12.13.0]
  • using aws lambda

Bug:

events.js:187
throw er; // Unhandled 'error' event
^
Error: Cannot find module '/index.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:794:15)
at Function.Module._load (internal/modules/cjs/loader.js:687:27)
at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
at MessagePort.<anonymous> (internal/main/worker_thread.js:139:25)
at MessagePort.emit (events.js:210:5)
at MessagePort.onmessage (internal/worker/io.js:70:8)
Emitted 'error' event on Worker instance at:
at Worker.[kOnErrorMessage] (internal/worker.js:176:10)
at Worker.[kOnMessage] (internal/worker.js:186:37)
at MessagePort.<anonymous> (internal/worker.js:118:57)
at MessagePort.emit (events.js:210:5)
at MessagePort.EventEmitter.emit (domain.js:476:20)
at MessagePort.onmessage (internal/worker/io.js:70:8) {
code: 'MODULE_NOT_FOUND',
requireStack: []
}

Bug cannot read property 'subtle' of undefined

What happened?

When I try to implement paseto V4 in expressjs it gives me this error

C:\laragon\www\scirpt\node_modules\paseto\lib\help\crypto_worker.js:10
webcrypto: { subtle },
^

TypeError: Cannot read property 'subtle' of undefined
at Object. (C:\laragon\www\scirpt\node_modules\paseto\lib\help\crypto_worker.js:10:16)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object. (C:\laragon\www\scirpt\node_modules\paseto\lib\help\sign.js:1:18)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)

Version

v3.1.2

Node.js Version

v16.17.0

Code to reproduce

const paseto = require('paseto')
const { V4 } = paseto

Required

  • I have searched the issues tracker and discussions for similar topics and couldn't find anything related.
  • I agree to follow this project's Code of Conduct

question: How I create a secret key from a string?

Hi!

I try to encrypt a payload with V2, I want to encrypt with key 'example', how can make it work?

Always I give the error

TypeError: v2.local secret key must be 256 bytes long symmetric key

Thanks and nice work 😄

`{}` makes decryption results hard to use

What happened?

With TypeScript strict checking enabled (https://www.typescriptlang.org/tsconfig#strict), decrypt returns a type that causes compilation errors.

TS7053: Element implicitly has an 'any' type because expression of type '"usr"' can't be used to index type '{}'.
         Property 'usr' does not exist on type '{}'.

I would expect that indexed access would work and that the code should compile.

Changing the return from Promise<object> to Promise<Record<PropertyKey, unknown>> would allow indexed access.

Version

v3.1.1

Node.js Version

v16.13.0

Code to reproduce

paseto.V1.decrypt(token, Buffer.from(key)).then(
    (token) => {
        const uuid = token['usr'];
        // ... do stuff
    }
);

Required

  • I have searched the issues tracker and discussions for similar topics and couldn't find anything related.
  • I agree to follow this project's Code of Conduct

Generating a public paseto key should give the public key attached

Describe the bug
Playing around with the library, I discovered the V2.generateKey('public') won't return the public key from the keypair.
Unless there is a simple way to re-generate the public key from the private one in Node.js, which I didn't find a simple method for, it would be nice to get an object from the generateKey() function that contains both private and public, keeping it fool-proof from people signing with the public key, but reusable to verify the PASETOs

What do you think ?

To Reproduce
const key = await V2.generateKey('public')

Expected behaviour
Returns the keypair for ease of use, also
Environment:

  • paseto version: v2
  • node version: 14.2.0

Characters that Paseto uses to create tokens

Hi, so this is what a common paseto token looks like:
v2.local.rRfHP25HDj5Pda40FwdTsGcsEMoQAKM6ElH6OhCon6YzG1Pzmj1ZPAHORhPaxKQo0XLM5LPYgaevWGrkEy2Os3N68Xee_Me9A0LmbMlV6MNVt-UZMos7ETha

The characters used are:

  • Letters (upper and lower case)
  • Numbers
  • Special characters (-, _, .)

I was wondering if a token could contain a slash (/, \), maybe even other characters?
Thanks

TypeError: keyObject must be a KeyObject instance

What happened?

Tried to import existing key but type error occurs.

yarn run v1.22.10
$ ts-node index.ts
/Users/gohojeong/seia/tmp/a/node_modules/paseto/lib/v2/key.js:105
    throw new TypeError('keyObject must be a KeyObject instance')
          ^
TypeError: keyObject must be a KeyObject instance
    at _keyObjectToBytes (/Users/gohojeong/seia/tmp/a/node_modules/paseto/lib/v2/key.js:105:11)
    at Object.keyObjectToBytes (/Users/gohojeong/seia/tmp/a/node_modules/paseto/lib/v4/key.js:14:10)
    at loadKeyStore (/Users/gohojeong/seia/tmp/a/index.ts:11:24)
    at async main (/Users/gohojeong/seia/tmp/a/index.ts:26:3)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Version

^3.0.1

Node.js Version

v16.5.0 (arm64)

Code to reproduce

import type { KeyObject } from 'crypto'
import { V4 as paseto } from 'paseto'
import { promises as fs, existsSync } from 'fs'

const keyLocation = './key.cert'
let keyStore: KeyObject

const loadKeyStore = async () => {
  if (!existsSync(keyLocation)) {
    const key = await paseto.generateKey('public')
    const raw = paseto.keyObjectToBytes(keyStore).toString('hex')

    await fs.writeFile(keyLocation, raw, 'utf-8')

    keyStore = paseto.bytesToKeyObject(Buffer.from(raw, 'hex'))
  } else {
    const raw = await fs.readFile(keyLocation, 'utf-8')

    console.log(raw)

    keyStore = paseto.bytesToKeyObject(Buffer.from(raw, 'hex'))
  }
}

const main = async () => {
  await loadKeyStore()
}

main()

  • I have searched the issues tracker and discussions for similar topics and couldn't find anything related.
  • I agree to follow this project's Code of Conduct

Fails to verify with `complete: true` option if there is no footer.

What happened?

When trying to extract the footer information from a token that has no footer, the verify call returns a rejected promise.

Version

3.1.0

Node.js Version

v18.9.0

Code to reproduce

import { V4 } from 'paseto'

const key = await V4.generateKey('public', { format: 'paserk' })
const token = await V4.sign({}, key.secretKey)
// This next line fails
const payload = await V4.verify(token, key.publicKey, {
  complete: true
})

Required

  • I have searched the issues tracker and discussions for similar topics and couldn't find anything related.
  • I agree to follow this project's Code of Conduct

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.