{"id":30799487,"url":"https://github.com/dwtechs/toker.js","last_synced_at":"2026-05-10T14:05:52.345Z","repository":{"id":313254767,"uuid":"1029595568","full_name":"DWTechs/Toker.js","owner":"DWTechs","description":"JWT management","archived":false,"fork":false,"pushed_at":"2025-09-04T19:53:37.000Z","size":164,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-09-04T21:33:31.475Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DWTechs.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-07-31T09:26:24.000Z","updated_at":"2025-09-04T19:53:40.000Z","dependencies_parsed_at":"2025-09-04T21:33:34.268Z","dependency_job_id":"4cf538a1-7650-427c-83ba-95fe0fcf0489","html_url":"https://github.com/DWTechs/Toker.js","commit_stats":null,"previous_names":["dwtechs/toker.js"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/DWTechs/Toker.js","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DWTechs%2FToker.js","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DWTechs%2FToker.js/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DWTechs%2FToker.js/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DWTechs%2FToker.js/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DWTechs","download_url":"https://codeload.github.com/DWTechs/Toker.js/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DWTechs%2FToker.js/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":273812862,"owners_count":25172890,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-05T02:00:09.113Z","response_time":402,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-09-05T19:50:34.172Z","updated_at":"2026-05-10T14:05:52.325Z","avatar_url":"https://github.com/DWTechs.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n[![License: MIT](https://img.shields.io/npm/l/@dwtechs/toker.svg?color=brightgreen)](https://opensource.org/licenses/MIT)\n[![npm version](https://badge.fury.io/js/%40dwtechs%2Ftoker.svg)](https://www.npmjs.com/package/@dwtechs/toker)\n[![last version release date](https://img.shields.io/github/release-date/DWTechs/Toker.js)](https://www.npmjs.com/package/@dwtechs/toker)\n![Jest:coverage](https://img.shields.io/badge/Jest:coverage-100%25-brightgreen.svg)\n\n- [Synopsis](#synopsis)\n- [Installation](#installation)\n- [Usage](#usage)\n- [API Reference](#api-reference)\n- [Error Handling](#error-handling)\n- [options](#options)\n- [Express.js](#expressjs)\n- [Support](#support)\n- [Contributors](#contributors)\n- [Stack](#stack)\n\n\n## Synopsis\n\n**[Toker.js](https://github.com/DWTechs/Toker.js)** is an open source JWT management library for Node.js to sign, verify and parse bearer safely.\n\n- 📦 Only 2 dependencies to check inputs variables and secure hash creation and comparison\n- 🪶 Very lightweight\n- 🧪 Thoroughly tested\n- 🚚 Shipped as ES2022 ECMAScript module\n- 📝 Written in Typescript\n\n## Installation\n\n```bash\n$ npm i @dwtechs/toker\n```\n\n\n## Usage\n\n\nExample of use with Express.js using ES2022 module format\n\n```javascript\n\nimport { sign, verify, parseBearer } from \"@dwtechs/toker\";\n\nconst { ACCESS_TOKEN_DURATION, REFRESH_TOKEN_DURATION, TOKEN_SECRET } = process.env;\n\n\nfunction decodeAccessToken(req, res, next){\n  let accessToken: string;\n  try {\n    accessToken = parseBearer(req.headers.authorization);\n  } catch (err: any) {\n    return next(err);\n  }\n  let decodedToken = null;\n  try {\n    decodedToken = verify(accessToken, [TOKEN_SECRET], true);\n  } catch (err: any) {\n    return next(err);\n  }\n  req.body.decodedAccessToken = decodedToken;\n  next();\n}\n\nfunction refreshToken(req, res, next) {\n  const iss = req.body.decodedAccessToken?.iss;\n  const newAccessToken = sign(iss, ACCESS_TOKEN_DURATION, \"access\", secrets);\n  const newRefreshToken = sign(iss, REFRESH_TOKEN_DURATION, \"refresh\", secrets);\n  try {\n    res.jwt = sign(req.userId, 3600, \"access\", [TOKEN_SECRET]);\n    next();\n  catch(err: any) {\n    next(err);\n  }\n}\n\nexport {\n  decodeAccessToken,\n  refreshToken,\n};\n\n```\n\n\n## API Reference\n\n\n### Types\n---\n\n```javascript\n\n// JWT\ntype Type = \"access\" | \"refresh\";\n\ntype Header = {\n  alg: string,\n  typ: string,\n  kid: number,\n};\n\ntype Payload = {\n  iss: number | string,\n  iat: number,\n  nbf: number,\n  exp: number,\n  typ: Type,\n}\n\n```\n\n### Methods\n---\n\n```javascript\n\n// JWT header default values\nconst header = {\n  alg: \"HS256\", // HMAC using SHA-256 hash algorithm\n  typ: \"JWT\",   // JSON Web Token\n  kid: number,  // Random key index, selected per call via crypto.randomInt()\n};\n\n/**\n * Signs a JWT (JSON Web Token) with the given parameters.\n *\n * @param {number|string} iss - The issuer of the token, which can be a string or a number.\n * @param {number} duration - The duration for which the token is valid, in seconds.\n * @param {Type} type - The type of the token, either \"access\" or \"refresh\".\n * @param {string[]} b64Keys - An array of base64 encoded secrets used for signing the token.\n * @returns {string} The signed JWT as a string.\n * @throws {InvalidIssuerError} Throws when `iss` is not a string or a number - HTTP 400\n * @throws {InvalidSecretsError} Throws when `b64Keys` is not an array or is empty - HTTP 500\n * @throws {InvalidDurationError} Throws when `duration` is not a positive number - HTTP 400\n * @throws {InvalidBase64Secret} Throws when the secret cannot be decoded from base64 - HTTP 500\n * \n * // Examples that throw specific errors:\n * sign(null, 3600, \"access\", secrets); // Throws InvalidIssuerError\n * sign(\"user123\", 3600, \"access\", []); // Throws InvalidSecretsError\n * sign(\"user123\", -1, \"access\", secrets); // Throws InvalidDurationError\n * sign(\"user123\", 3600, \"access\", [\"invalid-base64!\"]); // Throws InvalidBase64Secret\n * ```\n */\nfunction sign( iss: number | string, \n               duration: number, \n               type: Type,\n               b64Keys: string[]\n             ): string {}\n\n/**\n * Verifies a JWT token using the provided base64-encoded secrets.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string[]} b64Keys - An array of base64-encoded secrets used for verification.\n * @param {boolean} ignoreExpiration - Optional flag to ignore the expiration time of the token. Defaults to false.\n * @returns {Payload} The decoded payload of the JWT token.\n * @throws {InvalidTokenError} Throws when the token is malformed, has invalid structure, algorithm, or type - HTTP 401\n * @throws {InvalidSecretsError} Throws when b64Keys is not an array or is empty - HTTP 500\n * @throws {InactiveTokenError} Throws when the token cannot be used yet (nbf claim) - HTTP 401\n * @throws {ExpiredTokenError} Throws when the token has expired (exp claim) - HTTP 401\n * @throws {InvalidBase64Secret} Throws when the secret is not valid base64 encoded - HTTP 500\n * @throws {InvalidSignatureError} Throws when the token signature is invalid - HTTP 401\n * \n * // Examples that throw specific errors:\n * verify(\"invalid.token\", secrets); // Throws InvalidTokenError\n * verify(validToken, []); // Throws InvalidSecretsError\n * verify(expiredToken, secrets); // Throws ExpiredTokenError\n * verify(futureToken, secrets); // Throws InactiveTokenError\n * verify(tamperedToken, secrets); // Throws InvalidSignatureError\n * verify(validToken, [\"invalid-base64!\"]); // Throws InvalidBase64Secret\n * ```\n */\nfunction verify( token: string, \n                 b64Keys: string[],\n                 ignoreExpiration = false\n               ): Payload {}\n\n\n/**\n * Extracts the JWT token from an HTTP Authorization header with Bearer authentication scheme.\n * \n * This function validates that the authorization header follows the correct Bearer token format\n * (\"Bearer \u003ctoken\u003e\") and extracts the token portion for further processing.\n * \n * @param {string | undefined} authorization - The Authorization header value from an HTTP request\n * @returns {string} The extracted JWT token as a string\n * @throws {MissingAuthorizationError} Throws when the authorization parameter is undefined - HTTP 401\n * @throws {InvalidBearerFormatError} Throws when the format is invalid - HTTP 401\n * \n * @example\n * ```typescript\n * import { parseBearer, MissingAuthorizationError, InvalidBearerFormatError } from \"@dwtechs/toker\";\n * \n * // Valid Bearer tokens\n * const validHeader = \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\";\n * const token = parseBearer(validHeader);\n * // Returns: \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\"\n * \n * // Handles multiple spaces\n * const headerWithSpaces = \"Bearer    token123\";\n * const token2 = parseBearer(headerWithSpaces);\n * // Returns: \"token123\"\n * \n * // Examples that throw specific errors:\n * parseBearer(undefined); // Throws MissingAuthorizationError: \"Authorization header is missing\"\n * parseBearer(\"\"); // Throws InvalidBearerFormatError: \"Authorization header must be in the format 'Bearer \u003ctoken\u003e'\"\n * parseBearer(\"Basic dXNlcjpwYXNz\"); // Throws InvalidBearerFormatError\n * parseBearer(\"Bearer\"); // Throws InvalidBearerFormatError\n * parseBearer(\"Bearer \"); // Throws InvalidBearerFormatError\n * ```\n * \n */\nfunction parseBearer(authorization: string | undefined): string {}\n\n```\n\n## Error Handling\n\nToker uses a structured error system that helps you identify and handle specific error cases. All errors extend from a base `TokerError` class.\n\n\n### Common Properties\n\nAll error classes share these properties:\n\n- `message`: Human-readable error description\n- `code`: Human-readable error code (e.g., \"TOKEN_EXPIRED\")\n- `statusCode`: Suggested HTTP status code (e.g., 401)\n- `stack`: Error stack trace\n\n### Using Error Handling\n\n```typescript\nimport { sign, verify, parseBearer, ExpiredTokenError, InvalidSignatureError } from \"@dwtechs/toker\";\n\ntry {\n  // Attempt to verify a token\n  const payload = verify(token, secrets);\n  // Token is valid, proceed with the payload\n} catch (error) {\n  if (error instanceof ExpiredTokenError) {\n    // Handle expired token (e.g., prompt for reauthentication)\n    console.log('Your session has expired. Please log in again.');\n    console.log(`Status code: ${error.statusCode}`); // 401\n  } else if (error instanceof InvalidSignatureError) {\n    // Handle tampered token\n    console.log('Invalid token signature detected');\n    console.log(`Status code: ${error.statusCode}`); // 401\n  } else {\n    // Handle other verification errors\n    console.log(`Token verification failed: ${error.message}`);\n  }\n}\n```\n\n### Error Types and HTTP Status Codes\n\n| Error Class | Code | Status Code | Description |\n|-------------|------|-------------|-------------|\n| MissingAuthorizationError | MISSING_AUTHORIZATION | 401 | Authorization header is missing |\n| InvalidBearerFormatError | INVALID_BEARER_FORMAT | 401 | Authorization header must be in the format 'Bearer \u003ctoken\u003e' |\n| InvalidTokenError | INVALID_TOKEN | 401 | Invalid or malformed JWT token |\n| ExpiredTokenError | EXPIRED_TOKEN | 401 | JWT token has expired |\n| InactiveTokenError | INACTIVE_TOKEN | 401 | JWT token cannot be used yet (nbf claim) |\n| InvalidSignatureError | INVALID_SIGNATURE | 401 | JWT token signature is invalid |\n| InvalidIssuerError | INVALID_ISSUER | 400 | iss must be a string or a number |\n| InvalidSecretsError | INVALID_SECRETS | 500 | b64Keys must be an array |\n| InvalidDurationError | INVALID_DURATION | 400 | duration must be a positive number |\n| InvalidBase64Secret | INVALID_BASE64_SECRET | 500 | could not decode the base64 secret |\n\n## Express.js\n\nYou can use Toker directly as Express.js middlewares using [@dwtechs/toker-express library](https://www.npmjs.com/package/@dwtechs/toker-express).\nThis way you do not have to write express controllers yourself to use **Toker**.\n\n## Support\n\n| Environment | Version |\n| :---------- | :-----: |\n| Node.js     |  \u003e= 22  |\n\n## Contributors\n\n**Toker.js** is still in development and we would be glad to get all the help you can provide.\nTo contribute please read **[contributor.md](https://github.com/DWTechs/Toker.js/blob/main/contributor.md)** for detailed installation guide.\n\n## Stack\n\n| Purpose         |                    Choice                    |                             Motivation |\n| :-------------- | :------------------------------------------: | -------------------------------------------------------------: |\n| repository      |        [Github](https://github.com/)         |     hosting for software development version control using Git |\n| package manager |     [npm](https://www.npmjs.com/get-npm)     |                                default node.js package manager |\n| language        | [TypeScript](https://www.typescriptlang.org) | static type checking along with the latest ECMAScript features |\n| module bundler  |      [Rollup.js](https://rollupjs.org)       |                        advanced module bundler for ES2022 modules |\n| unit testing    |          [Jest](https://jestjs.io/)          |                  delightful testing with a focus on simplicity |\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdwtechs%2Ftoker.js","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdwtechs%2Ftoker.js","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdwtechs%2Ftoker.js/lists"}