npm package: @jnode/auth
Description: Simple authorization package for Node.js.
Author: JustApple
Latest version: 1.0.0

# `@jnode/auth`

Simple authorization package for Node.js.

## Installation

```
npm i @jnode/auth
```

## Quick start

### Import

```js
const { AuthService } = require('@jnode/auth');
const crypto = require('crypto');
```

### Basic usage

```js
// Generate a pair of keys for demonstration
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
});

// Initialize the service
const auth = new AuthService(publicKey, privateKey);

// Sign a token
const token = auth.signToken({ alg: 'RSA-SHA256' }, { userId: 123, role: 'admin' });

// Example token output:
// ABR7ImFsZyI6IlJTQS1TSEEyNTYifQAdeyJ1c2VySWQiOjEyMywicm9sZSI6ImFkbWluIn1JG1YPNJNfZ2jA29DcqiU_HojNAC34mz0ueYYOZ45nbHg86Q_Q7RULHsQfMp1tn0AdeGC9gStX1QK-fCB7Qgt3kF85qCtlDcYywDrjwmg19H0XnWeD27fXCOmmcM-rLjkVe61WDEb8rktmtlMJAUtivDYJr8RxyI2kQF-ZddlrgukjzRtua2_FmWmohb5MeahhfQ6xmlM1HRbYSMlUBaGjSxx_Q4s3wNrpMNDWiDM0adA1iHH5h00VRo2t5iepytOY3YunEW3_UXKcqr9PZ8KV-ikW2mXXp45Xw39U96dkeD3M9dR3vexL8yBc8kNDeT6a8YpHb63HW8s6LUlV_jzB

// Verify a token
try {
  const decoded = auth.verifyToken(token);
  console.log('Decoded:', decoded);
  /* 
  Output: 
  { 
    header: { alg: 'RSA-SHA256' }, 
    payload: { userId: 123, role: 'admin' } 
  }
  */
} catch (err) {
  console.error('Verification failed:', err.message);
}
```

## How it works?

`@jnode/auth` provides a lightweight and binary-safe alternative to JWT, focusing on a straightforward token format encoded in `base64url`.

The token structure is as follows:

1. **Header Length**: 2 bytes (UInt16BE)
2. **Header JSON**: n bytes
3. **Payload Length**: 2 bytes (UInt16BE)
4. **Payload JSON**: n bytes
5. **Signature**: RSA-SHA256 signature of the preceding segments (bytes 1 through 4).

This format ensures that the token is self-contained and tamper-proof while being extremely efficient to parse without complex regex or split operations.

------

# Reference

## Class: `auth.AuthService`

The main class to handle signing and verification of tokens.

### `new auth.AuthService(publicKey, privateKey)`

- `publicKey` [\<string\>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type) | [\<Buffer\>](https://nodejs.org/docs/latest/api/buffer.html#class-buffer) | [\<KeyObject\>](https://nodejs.org/docs/latest/api/crypto.html#class-keyobject) The public key used for verification.
- `privateKey` [\<string\>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type) | [\<Buffer\>](https://nodejs.org/docs/latest/api/buffer.html#class-buffer) | [\<KeyObject\>](https://nodejs.org/docs/latest/api/crypto.html#class-keyobject) The private key used for signing.

### Static method: `AuthService.signToken(header, payload, privateKey)`

- `header` [\<Object\>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [\<Buffer\>](https://nodejs.org/docs/latest/api/buffer.html#class-buffer) Token header data. **Default:** `{}`.
- `payload` [\<Object\>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [\<Buffer\>](https://nodejs.org/docs/latest/api/buffer.html#class-buffer) Token payload data. **Default:** `{}`.
- `privateKey` [\<string\>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type) | [\<Buffer\>](https://nodejs.org/docs/latest/api/buffer.html#class-buffer) | [\<KeyObject\>](https://nodejs.org/docs/latest/api/crypto.html#class-keyobject)
- Returns: [\<string\>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type) A `base64url` encoded token.

Signs the provided header and payload using the RSA-SHA256 algorithm.

### Static method: `AuthService.verifyToken(token, publicKey)`

- `token` [\<string\>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type) | [\<Buffer\>](https://nodejs.org/docs/latest/api/buffer.html#class-buffer) The token to verify.
- `publicKey` [\<string\>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type) | [\<Buffer\>](https://nodejs.org/docs/latest/api/buffer.html#class-buffer) | [\<KeyObject\>](https://nodejs.org/docs/latest/api/crypto.html#class-keyobject)
- Returns: [\<Object\>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object containing `{ header, payload }`.

Parses and verifies the token. Throws an `Error` if the signature is invalid or `TypeError` if keys are missing.

### `service.signToken(header, payload)`

- `header` [\<Object\>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [\<Buffer\>](https://nodejs.org/docs/latest/api/buffer.html#class-buffer)
- `payload` [\<Object\>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [\<Buffer\>](https://nodejs.org/docs/latest/api/buffer.html#class-buffer)
- Returns: [\<string\>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type)

Instance method that uses the `privateKey` provided in the constructor to sign a token.

### `service.verifyToken(token)`

- `token` [\<string\>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type) | [\<Buffer\>](https://nodejs.org/docs/latest/api/buffer.html#class-buffer)
- Returns: [\<Object\>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)

Instance method that uses the `publicKey` provided in the constructor to verify a token.