pax_global_header00006660000000000000000000000064143704305660014522gustar00rootroot0000000000000052 comment=a4610ca887f8aefb2b5f919238717004b49921a1 jose-4.11.4/000077500000000000000000000000001437043056600125515ustar00rootroot00000000000000jose-4.11.4/.electron_flags.sh000077500000000000000000000005341437043056600161570ustar00rootroot00000000000000electron -i <<< 'process.exit(parseInt(process.versions.node, 10))' &> /dev/null NODE_VERSION=$? export NODE_OPTIONS='--no-warnings' if [[ $NODE_VERSION -eq 18 ]]; then export NODE_OPTIONS+=' --experimental-global-webcrypto' elif [[ $NODE_VERSION -eq 16 ]]; then export NODE_OPTIONS+=' --experimental-global-webcrypto --experimental-fetch' fi jose-4.11.4/.github/000077500000000000000000000000001437043056600141115ustar00rootroot00000000000000jose-4.11.4/.github/ISSUE_TEMPLATE/000077500000000000000000000000001437043056600162745ustar00rootroot00000000000000jose-4.11.4/.github/ISSUE_TEMPLATE/bug-report.yml000066400000000000000000000036601437043056600211120ustar00rootroot00000000000000name: 🐞Bug report description: There's a bug I want to report labels: triage body: - type: markdown attributes: value: | Thanks for taking the time to fill out this bug report. Do not use this form to ask questions or make suggestions, use the [appropriate](https://github.com/panva/jose/issues/new/choose) Discussions Topic for those. - type: textarea attributes: label: What happened? description: A clear and concise description of what the bug is and what you expected to happen instead. validations: required: true - type: input attributes: label: Version description: What exact version of the library do you use? placeholder: e.g. v3.14.0 validations: required: true - type: dropdown attributes: label: Runtime description: What javascript runtime are you seeing the problem on? options: - Browser - Cloudflare Workers - Deno - Electron - Node.js - Other (I will specify below) validations: required: true - type: input attributes: label: Runtime Details description: More information about the runtime (e.g. node version, browser vendor and version, electron version, operating system) validations: required: true - type: textarea attributes: label: Code to reproduce description: Please copy and paste code to reproduce the issue. This will be automatically formatted into javascript code, so no need for backticks. render: js validations: required: true - type: checkboxes attributes: label: Required options: - label: I have searched the issues tracker and discussions for similar topics and couldn't find anything related. required: true - label: I agree to follow this project's [Code of Conduct](https://github.com/panva/jose/blob/main/CODE_OF_CONDUCT.md) required: true jose-4.11.4/.github/ISSUE_TEMPLATE/config.yml000066400000000000000000000012421437043056600202630ustar00rootroot00000000000000blank_issues_enabled: false contact_links: - name: ❓ Question url: https://github.com/panva/jose/discussions/new?category=q-a about: Have a question about using jose? Head over to the discussions "Q&A" Category - name: 💡 Feature proposal url: https://github.com/panva/jose/discussions/new?category=ideas about: Have a proposal for a new feature? Head over to the discussions "Ideas" Category - name: Support the project url: https://github.com/sponsors/panva about: Are you asking your nth question? Relying on jose for critical operations? Consider supporting the project so that it may continue being maintained. jose-4.11.4/.github/dependabot.yml000066400000000000000000000011151437043056600167370ustar00rootroot00000000000000# To get started with Dependabot version updates, you'll need to specify which # package ecosystems to update and where the package manifests are located. # Please see the documentation for all configuration options: # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates version: 2 updates: - package-ecosystem: "npm" # See documentation for possible values directory: "/" # Location of package manifests schedule: interval: "weekly" versioning-strategy: "increase" allow: - dependency-name: "edge-runtime" jose-4.11.4/.github/workflows/000077500000000000000000000000001437043056600161465ustar00rootroot00000000000000jose-4.11.4/.github/workflows/browserstack.yml000066400000000000000000000101041437043056600213760ustar00rootroot00000000000000name: Browserstack on: push: branches: [main] tags: ['v[0-9]+.[0-9]+.[0-9]+'] pull_request: branches: [main] pull_request_target: types: [labeled] branches: [main] schedule: - cron: '11 11 * * 1' workflow_dispatch: jobs: unlabel: if: ${{ github.event_name == 'pull_request_target' && github.event.label.name == 'trigger-browserstack' }} runs-on: ubuntu-latest steps: - run: gh pr edit $PR --repo $REPO --remove-label "trigger-browserstack" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} PR: ${{ github.event.number }} REPO: ${{ github.event.repository.full_name }} cert: if: ${{ !startsWith(github.event_name, 'pull_request') || (github.event_name == 'pull_request_target' && github.event.label.name == 'trigger-browserstack') }} runs-on: ubuntu-latest outputs: cache-key: ${{ steps.cache-key.outputs.value }} steps: - name: Environment Information run: npx envinfo - id: cache-key run: echo "value=letsencrypt-$(date +"%Y%m")" >> $GITHUB_OUTPUT - name: Cache letsencrypt uses: actions/cache@v3 id: cert with: path: letsencrypt key: ${{ steps.cache-key.outputs.value }} - name: Get test certificate if: ${{ steps.cert.outputs.cache-hit != 'true' }} run: | sudo snap install core sudo snap refresh core sudo snap install --classic certbot sudo snap set certbot trust-plugin-with-root=ok sudo snap install certbot-dns-route53 certbot certonly -n -m 'panva.ip@gmail.com' \ --agree-tos \ --dns-route53 \ --config-dir 'letsencrypt/config' \ --work-dir 'letsencrypt/work' \ --logs-dir 'letsencrypt/logs' \ -d jose.panva.me env: AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} browserstack: needs: - cert if: ${{ !startsWith(github.event_name, 'pull_request') || (github.event_name == 'pull_request_target' && github.event.label.name == 'trigger-browserstack') }} runs-on: ubuntu-latest strategy: fail-fast: false matrix: browser: - browserstack:android - browserstack:ios - browserstack:safari steps: - name: Environment Information run: npx envinfo - name: Checkout uses: actions/checkout@v3 - name: Cache letsencrypt id: cert uses: actions/cache@v3 with: path: letsencrypt key: ${{ needs.cert.outputs.cache-key }} - name: Abort if cert isn't cached if: ${{ steps.cert.outputs.cache-hit != 'true' }} uses: actions/github-script@v6 with: script: core.setFailed('cert cache hit failed') - name: Setup node uses: actions/setup-node@v3 with: node-version: lts/hydrogen # 18 cache: 'npm' check-latest: true - run: npm clean-install - run: npm install --global testcafe@2 testcafe-browser-provider-browserstack@1 - run: npm run build:browser - name: BrowserStack Env Setup uses: browserstack/github-actions/setup-env@00ce173eae311a7838f80682a5fad5144c4219ad with: username: ${{ secrets.BROWSERSTACK_USERNAME }} access-key: ${{ secrets.BROWSERSTACK_ACCESS_KEY }} build-name: 'BUILD_INFO' project-name: 'REPO_NAME' - name: Start BrowserStackLocal Tunnel uses: browserstack/github-actions/setup-local@00ce173eae311a7838f80682a5fad5144c4219ad with: local-testing: 'start' local-logging-level: 'all-logs' local-identifier: 'random' - name: Run Test Suite run: npm run tap:browsers env: BROWSER: ${{ matrix.browser }} - name: Stop BrowserStackLocal if: ${{ always() }} uses: browserstack/github-actions/setup-local@00ce173eae311a7838f80682a5fad5144c4219ad with: local-testing: 'stop' jose-4.11.4/.github/workflows/codeql.yml000066400000000000000000000053321437043056600201430ustar00rootroot00000000000000# For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. # # ******** NOTE ******** # We have attempted to detect the languages in your repository. Please check # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # name: "CodeQL" on: push: branches: [ "main" ] pull_request: # The branches below must be a subset of the branches above branches: [ "main" ] schedule: - cron: '11 11 * * 1' jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [ 'javascript' ] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support steps: - name: Checkout repository uses: actions/checkout@v3 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v2 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs # queries: security-extended,security-and-quality # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@v2 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun # If the Autobuild fails above, remove it and uncomment the following three lines. # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. # - run: | # echo "Run, Build Application using script" # ./location_of_script_within_repo/buildscript.sh - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 with: category: "/language:${{matrix.language}}" jose-4.11.4/.github/workflows/lock.yml000066400000000000000000000006011437043056600176160ustar00rootroot00000000000000name: "Lock threads" on: schedule: - cron: '11 11 * * 1' jobs: lock: continue-on-error: true runs-on: ubuntu-latest steps: - uses: dessant/lock-threads@c1b35ae # v4.0.0 with: github-token: ${{ github.token }} issue-inactive-days: "90" issue-lock-reason: "" pr-inactive-days: "90" pr-lock-reason: "" jose-4.11.4/.github/workflows/publish.yml000066400000000000000000000034711437043056600203440ustar00rootroot00000000000000name: NPM Publish on: release: types: [published] jobs: publish: runs-on: ubuntu-latest continue-on-error: true strategy: fail-fast: false matrix: prepare-script: - browser - node-cjs - node-esm - universal steps: - name: Environment Information run: npx envinfo - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0 - name: Setup node uses: actions/setup-node@v3 with: node-version: lts/hydrogen # 18 check-latest: true registry-url: https://registry.npmjs.org always-auth: true - name: Load cached dist uses: actions/cache@v3 id: dist with: path: dist key: dist-${{ hashFiles('src/**/*.ts', 'tsconfig/*.json', '.github/workflows/*.yml', 'package-lock.json') }} - name: Abort if dist isn't cached if: ${{ steps.dist.outputs.cache-hit != 'true' }} uses: actions/github-script@v6 with: script: core.setFailed('dist cache hit failed') - name: Prepare distribution run: node tools/publish-${{ matrix.prepare-script }} - run: npm publish env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} push: needs: - publish runs-on: ubuntu-latest steps: - name: Environment Information run: npx envinfo - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0 - run: git push origin $GITHUB_SHA:v4.x - run: git rm -r dist/**/* - run: | git config --local user.email "panva.ip@gmail.com" git config --local user.name "Filip Skokan" git commit -m "chore: cleanup after publish" - run: git push origin HEAD:main jose-4.11.4/.github/workflows/test.yml000066400000000000000000000216671437043056600176640ustar00rootroot00000000000000name: Test on: push: branches: [main] tags: ['v[0-9]+.[0-9]+.[0-9]+'] pull_request: branches: [main] schedule: - cron: '11 11 * * 1' workflow_dispatch: jobs: build: runs-on: ubuntu-latest outputs: cache-key: ${{ steps.cache-key.outputs.value }} steps: - name: Environment Information run: npx envinfo - name: Checkout uses: actions/checkout@v3 - name: Setup node uses: actions/setup-node@v3 with: node-version: lts/hydrogen # 18 cache: 'npm' check-latest: true - run: npm clean-install - id: cache-key run: echo "value=dist-${{ hashFiles('src/**/*.ts', 'tsconfig/*.json', '.github/workflows/*.yml', 'package-lock.json') }}" >> $GITHUB_OUTPUT - name: Cache dist uses: actions/cache@v3 id: dist with: path: dist key: ${{ steps.cache-key.outputs.value }} - name: Build run: npm run build-all if: ${{ steps.dist.outputs.cache-hit != 'true' }} - uses: actions/upload-artifact@v3 with: name: dist path: dist - run: git reset HEAD --hard node: needs: - build continue-on-error: ${{ !startsWith(matrix.node-version, 'lts') }} strategy: fail-fast: false matrix: node-version: - lts/erbium # 12 - lts/fermium # 14 - lts/gallium # 16 - lts/hydrogen # 18 - current runs-on: ubuntu-latest steps: - name: Environment Information run: npx envinfo - name: Checkout uses: actions/checkout@v3 - name: Setup node id: node uses: actions/setup-node@v3 with: node-version: ${{ matrix.node-version }} cache: 'npm' check-latest: true - run: npm install --global npm@8 if: ${{ startsWith(steps.node.outputs.node-version, 'v12') || startsWith(steps.node.outputs.node-version, 'v14') }} - run: npm clean-install - name: Load cached dist uses: actions/cache@v3 id: dist with: path: dist key: ${{ needs.build.outputs.cache-key }} - name: Abort if dist isn't cached if: ${{ steps.dist.outputs.cache-hit != 'true' }} uses: actions/github-script@v6 with: script: core.setFailed('dist cache hit failed') - name: Test (TAP) run: npm run tap:node if: ${{ !startsWith(steps.node.outputs.node-version, 'v12') }} - run: | find test -type f -name '*.mjs' -print0 | xargs -0 sed -i -e "s/await import(/require(/g" npm install --save-dev ava@4 if: ${{ startsWith(steps.node.outputs.node-version, 'v12') }} - name: Test (AVA) run: npm run test deno: needs: - build runs-on: ubuntu-latest steps: - name: Environment Information run: npx envinfo - name: Checkout uses: actions/checkout@v3 - uses: denoland/setup-deno@v1 with: deno-version: v1.x - name: Load cached dist uses: actions/cache@v3 id: dist with: path: dist key: ${{ needs.build.outputs.cache-key }} - name: Abort if dist isn't cached if: ${{ steps.dist.outputs.cache-hit != 'true' }} uses: actions/github-script@v6 with: script: core.setFailed('dist cache hit failed') - name: Test Deno Definitions run: deno check dist/deno/index.ts - name: Setup node uses: actions/setup-node@v3 with: node-version: lts/hydrogen # 18 cache: 'npm' check-latest: true - run: npm clean-install - name: Test Deno run: npm run tap:deno bun: needs: - build runs-on: ubuntu-latest continue-on-error: true steps: - name: Environment Information run: npx envinfo - name: Checkout uses: actions/checkout@v3 - run: curl https://bun.sh/install | bash - name: Load cached dist uses: actions/cache@v3 id: dist with: path: dist key: ${{ needs.build.outputs.cache-key }} - name: Abort if dist isn't cached if: ${{ steps.dist.outputs.cache-hit != 'true' }} uses: actions/github-script@v6 with: script: core.setFailed('dist cache hit failed') - name: Setup node uses: actions/setup-node@v3 with: node-version: lts/hydrogen # 18 cache: 'npm' check-latest: true - run: npm clean-install - name: Test Bun run: npm run tap:bun workers: needs: - build runs-on: ubuntu-latest steps: - name: Environment Information run: npx envinfo - name: Checkout uses: actions/checkout@v3 - name: Setup node uses: actions/setup-node@v3 with: node-version: lts/hydrogen # 18 cache: 'npm' check-latest: true - run: npm clean-install - run: npm install --global workerd - name: Load cached dist uses: actions/cache@v3 id: dist with: path: dist key: ${{ needs.build.outputs.cache-key }} - name: Abort if dist isn't cached if: ${{ steps.dist.outputs.cache-hit != 'true' }} uses: actions/github-script@v6 with: script: core.setFailed('dist cache hit failed') - name: Run Test Suite run: npm run tap:workers edge-runtime: needs: - build runs-on: ubuntu-latest steps: - name: Environment Information run: npx envinfo - name: Checkout uses: actions/checkout@v3 - name: Setup node uses: actions/setup-node@v3 with: node-version: lts/hydrogen # 18 cache: 'npm' check-latest: true - run: npm clean-install - name: Load cached dist uses: actions/cache@v3 id: dist with: path: dist key: ${{ needs.build.outputs.cache-key }} - name: Abort if dist isn't cached if: ${{ steps.dist.outputs.cache-hit != 'true' }} uses: actions/github-script@v6 with: script: core.setFailed('dist cache hit failed') - name: Run Test Suite run: npm run tap:edge-runtime browsers: needs: - build runs-on: ubuntu-latest strategy: fail-fast: false matrix: browser: - chrome:headless - firefox:headless - edge:headless steps: - name: Environment Information run: npx envinfo - name: Checkout uses: actions/checkout@v3 - name: Setup node uses: actions/setup-node@v3 with: node-version: lts/hydrogen # 18 cache: 'npm' check-latest: true - run: npm clean-install - run: npm install --global testcafe@2 - name: Load cached dist uses: actions/cache@v3 id: dist with: path: dist key: ${{ needs.build.outputs.cache-key }} - name: Abort if dist isn't cached if: ${{ steps.dist.outputs.cache-hit != 'true' }} uses: actions/github-script@v6 with: script: core.setFailed('dist cache hit failed') - name: Run Test Suite run: npm run tap:browsers env: BROWSER: ${{ matrix.browser }} electron: needs: - build runs-on: macos-latest steps: - name: Environment Information run: npx envinfo - name: Checkout uses: actions/checkout@v3 - name: Setup node uses: actions/setup-node@v3 with: node-version: lts/hydrogen # 18 cache: 'npm' check-latest: true - run: npm clean-install - name: Load cached dist uses: actions/cache@v3 id: dist with: path: dist key: ${{ needs.build.outputs.cache-key }} - name: Abort if dist isn't cached if: ${{ steps.dist.outputs.cache-hit != 'true' }} uses: actions/github-script@v6 with: script: core.setFailed('dist cache hit failed') - name: Install Electron run: npm install --global electron - name: Run Test Suite run: npm run tap:electron prepare-release: needs: - browsers - bun - deno - edge-runtime - electron - node - workers runs-on: ubuntu-latest if: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags') && github.repository == 'panva/jose' }} steps: - name: Environment Information run: npx envinfo - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 2 - name: Setup node uses: actions/setup-node@v3 with: node-version: lts/hydrogen # 18 cache: 'npm' check-latest: true - run: node tools/release-notes env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} jose-4.11.4/.gitignore000066400000000000000000000037231437043056600145460ustar00rootroot00000000000000# crypto runtime copies src/runtime/*.ts !src/runtime/*.d.ts # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* # Diagnostic reports (https://nodejs.org/api/report.html) report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage *.lcov # nyc test coverage .nyc_output # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directory and lockfiles node_modules/ jspm_packages/ yarn.lock npm-shrinkwrap.json # Snowpack dependency directory (https://snowpack.dev/) web_modules/ # TypeScript cache *.tsbuildinfo # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Microbundle cache .rpt2_cache/ .rts2_cache_cjs/ .rts2_cache_es/ .rts2_cache_umd/ # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variables file .env .env.test # parcel-bundler cache (https://parceljs.org/) .cache .parcel-cache # Next.js build output .next out # Nuxt.js build / generate output .nuxt dist dist-browser-tests # Gatsby files .cache/ # Comment in the public line in if your project uses Gatsby and not Next.js # https://nextjs.org/blog/next-9-1#public-directory-support # public # vuepress build output .vuepress/dist # Serverless directories .serverless/ # FuseBox cache .fusebox/ # DynamoDB Local files .dynamodb/ # TernJS port file .tern-port # Stores VSCode versions used for testing VSCode extensions .vscode-test # yarn v2 .yarn/cache .yarn/unplugged .yarn/build-state.yml .yarn/install-state.gz .pnp.* .npmrc tap/*.js tap/run-*.mjs *.bak *.bun tap/.workers.capnp jose-4.11.4/.mdn_links.cjs000066400000000000000000000004001437043056600153000ustar00rootroot00000000000000const doms = new Set([ 'URL', ]) module.exports.load = function load(app) { app.renderer.addUnknownSymbolResolver('typescript', (name) => { if (doms.has(name)) { return `https://developer.mozilla.org/en-US/docs/Web/API/${name}` } }) } jose-4.11.4/.node_flags.sh000077500000000000000000000005241437043056600152700ustar00rootroot00000000000000node -e 'process.exit(parseInt(process.versions.node, 10))' &> /dev/null NODE_VERSION=$? export NODE_OPTIONS='--no-warnings' if [[ $NODE_VERSION -eq 18 ]]; then export NODE_OPTIONS+=' --experimental-global-webcrypto' elif [[ $NODE_VERSION -eq 16 ]]; then export NODE_OPTIONS+=' --experimental-global-webcrypto --experimental-fetch' fi jose-4.11.4/.prettierignore000066400000000000000000000000501437043056600156070ustar00rootroot00000000000000# Ignore artifacts: build dist coverage jose-4.11.4/.prettierrc.json000066400000000000000000000003701437043056600157050ustar00rootroot00000000000000{ "trailingComma": "all", "singleQuote": true, "printWidth": 100, "semi": false, "plugins": ["prettier-plugin-jsdoc"], "tsdoc": true, "jsdocSeparateReturnsFromParam": true, "jsdocSeparateTagGroups": true, "jsdocPrintWidth": 100 } jose-4.11.4/.versionrc.json000066400000000000000000000013531437043056600155360ustar00rootroot00000000000000{ "commit-all": true, "scripts": { "prerelease": "npm run-script build-all", "postbump": "node ./tools/postbump.js", "postchangelog": "sed -i '' -e 's/### \\[/## [/g' CHANGELOG.md" }, "types": [ { "type": "feat", "section": "Features" }, { "type": "fix", "section": "Fixes" }, { "type": "chore", "hidden": true }, { "type": "docs", "hidden": true }, { "type": "style", "hidden": true }, { "type": "refactor", "section": "Refactor", "hidden": false }, { "type": "perf", "section": "Performance", "hidden": false }, { "type": "test", "hidden": true } ] } jose-4.11.4/CHANGELOG.md000066400000000000000000001637271437043056600144020ustar00rootroot00000000000000# Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ## [4.11.4](https://github.com/panva/jose/compare/v4.11.3...v4.11.4) (2023-02-07) ### Fixes * **build:** ignore deno files in npm publishes ([b3d6a11](https://github.com/panva/jose/commit/b3d6a11bf0803c37e1e9d0368ccec1f1264eef74)) ## [4.11.3](https://github.com/panva/jose/compare/v4.11.2...v4.11.3) (2023-02-07) ### Fixes * **CF Workers:** improve miniflare compat with different Node.js versions, get ready for future non-proprietary support ([3406b9f](https://github.com/panva/jose/commit/3406b9f73b1884b5db9c60675a68fe85794d48e0)), closes [#446](https://github.com/panva/jose/issues/446) [#495](https://github.com/panva/jose/issues/495) [#497](https://github.com/panva/jose/issues/497) ## [4.11.2](https://github.com/panva/jose/compare/v4.11.1...v4.11.2) (2023-01-01) ### Refactor * **node:** dry node version checks ([aff2f7c](https://github.com/panva/jose/commit/aff2f7c00f28b599ee72dd9f0a36c3783f1e195f)) ## [4.11.1](https://github.com/panva/jose/compare/v4.11.0...v4.11.1) (2022-11-22) ## [4.11.0](https://github.com/panva/jose/compare/v4.10.4...v4.11.0) (2022-11-08) ### Features * add bun as a supported runtime ([3a63631](https://github.com/panva/jose/commit/3a636318914866decd934d455d7c3789d304992c)) ### Fixes * respect JWK ext for symmetric keys ([20557fc](https://github.com/panva/jose/commit/20557fccf1ce0ebd7dd5d18cc33aa64d6f7b35ba)) ## [4.10.4](https://github.com/panva/jose/compare/v4.10.3...v4.10.4) (2022-10-28) ### Fixes * typo in importPKSC8 error message ([#468](https://github.com/panva/jose/issues/468)) ([746bc64](https://github.com/panva/jose/commit/746bc64675636f2a09a6745e71cba8a2bdf3718f)) * workaround for invalid use checks on CF Workers and Deno ([e4d04eb](https://github.com/panva/jose/commit/e4d04eb65f72041784d948eaa8432e4b64193729)) ## [4.10.3](https://github.com/panva/jose/compare/v4.10.2...v4.10.3) (2022-10-20) ## [4.10.2](https://github.com/panva/jose/compare/v4.10.1...v4.10.2) (2022-10-20) ## [4.10.1](https://github.com/panva/jose/compare/v4.10.0...v4.10.1) (2022-10-20) ## [4.10.0](https://github.com/panva/jose/compare/v4.9.3...v4.10.0) (2022-09-27) ### Features * Curve25519, and Curve448 support for WebCryptoAPI runtimes ([fea359a](https://github.com/panva/jose/commit/fea359a2055aa1b65170999a7f8e1bb23a3a1cb5)) ### Fixes * **importX509:** handle length encodings better ([47d0d77](https://github.com/panva/jose/commit/47d0d777a1ac90ff2ed0368fdab536db3d17aa8c)), closes [#459](https://github.com/panva/jose/issues/459) ## [4.9.3](https://github.com/panva/jose/compare/v4.9.2...v4.9.3) (2022-09-15) ### Refactor * update CEK length validation error message ([81a92a9](https://github.com/panva/jose/commit/81a92a9a9803022b82ea67577bde3fc0da3ecc6f)) * update key input validation error messages ([2eac34a](https://github.com/panva/jose/commit/2eac34aa8f02c800a5f0b944e03fbe681c962b9c)) * update keylike description for WinterCG ([6741679](https://github.com/panva/jose/commit/6741679936acf78f00c6effd559b4698cc92f123)) ## [4.9.2](https://github.com/panva/jose/compare/v4.9.1...v4.9.2) (2022-09-01) ### Fixes * limit default PBES2 alg's computational expense ([03d6d01](https://github.com/panva/jose/commit/03d6d013bf6e070e85adfe5731f526978e3e8e4d)) ## [4.9.1](https://github.com/panva/jose/compare/v4.9.0...v4.9.1) (2022-08-29) ### Fixes * **deno:** add a Deno package entrypoint ([9f3c459](https://github.com/panva/jose/commit/9f3c459e30b71eec54163d500edb59f5c72bf7c9)) ## [4.9.0](https://github.com/panva/jose/compare/v4.8.3...v4.9.0) (2022-08-17) ### Features * add support for RFC 9278 - JWK Thumbprint URI ([d06ce65](https://github.com/panva/jose/commit/d06ce654666c5f584716f39843534118407c14e0)) ### Refactor * consume some base64url decode errors ([#436](https://github.com/panva/jose/issues/436)) ([caaf2c3](https://github.com/panva/jose/commit/caaf2c38dc51209d7adc493029f416c61759b1b1)) * unify JOSENotSupported throw on key export ([fe5d093](https://github.com/panva/jose/commit/fe5d093bf74b812ecd3ee92d40dd02619e88e06c)) ## [4.8.3](https://github.com/panva/jose/compare/v4.8.1...v4.8.3) (2022-06-29) ## [4.8.1](https://github.com/panva/jose/compare/v4.8.0...v4.8.1) (2022-05-02) ### Fixes * **typescript:** add types export for nodenext module resolution ([#406](https://github.com/panva/jose/issues/406)) ([5a6d8f0](https://github.com/panva/jose/commit/5a6d8f0a2a3283bd1e832f1e71906d70f74c1262)) ## [4.8.0](https://github.com/panva/jose/compare/v4.7.0...v4.8.0) (2022-04-26) ### Features * add "worker" export in package.json ([#400](https://github.com/panva/jose/issues/400)) ([c58c80a](https://github.com/panva/jose/commit/c58c80ae98b7a55b3b95e72438040983ae9a23de)) * optional headers options for createRemoteJWKSet ([#397](https://github.com/panva/jose/issues/397)) ([b4612f5](https://github.com/panva/jose/commit/b4612f5d256b773ab7a1144ac839bdf0f8ccff53)) ## [4.7.0](https://github.com/panva/jose/compare/v4.6.2...v4.7.0) (2022-04-21) ### Features * add createRemoteJWKSet cacheMaxAge option ([5017d95](https://github.com/panva/jose/commit/5017d95764b3aca551631c1a2fbe7cc40cbb6055)), closes [#394](https://github.com/panva/jose/issues/394) ## [4.6.2](https://github.com/panva/jose/compare/v4.6.1...v4.6.2) (2022-04-19) ### Fixes * dont check JWT iat is in the past unless maxTokenAge is used ([96d85c7](https://github.com/panva/jose/commit/96d85c70033d2249de41ed07d97ed6843c15eb2a)) ## [4.6.1](https://github.com/panva/jose/compare/v4.6.0...v4.6.1) (2022-04-11) ## [4.6.0](https://github.com/panva/jose/compare/v4.5.3...v4.6.0) (2022-03-06) ### Features * mark APIs and parameters that can lead to footguns as deprecated ([0ddbcc6](https://github.com/panva/jose/commit/0ddbcc6725ecb2d68efdaf0951cec4db31cc9b16)) * **types:** include JSDoc in the types ([74187a9](https://github.com/panva/jose/commit/74187a9aa97cac70c42035949dd847177025af7c)) ## [4.5.3](https://github.com/panva/jose/compare/v4.5.2...v4.5.3) (2022-03-05) ### Fixes * **web api runtime:** rely on default fetch init values ([df6d966](https://github.com/panva/jose/commit/df6d96651d4ddeeb4a9b05bd2d778bd58528dad2)) ## [4.5.2](https://github.com/panva/jose/compare/v4.5.1...v4.5.2) (2022-03-04) ### Fixes * decrypting empty ciphertext compact JWEs ([#374](https://github.com/panva/jose/issues/374)) ([95fe597](https://github.com/panva/jose/commit/95fe59791dab9b31203f7a4ec5f4b44633d9b74f)) ## [4.5.1](https://github.com/panva/jose/compare/v4.5.0...v4.5.1) (2022-02-22) ### Fixes * **typescript:** allow synchronous get key functions ([7c99153](https://github.com/panva/jose/commit/7c99153a9e8ae45a35de7eff45fcf6e60e1b088b)) ## [4.5.0](https://github.com/panva/jose/compare/v4.4.0...v4.5.0) (2022-02-07) ### Features * add jose.decodeJwt utility ([3d2a2b8](https://github.com/panva/jose/commit/3d2a2b8eee18c9b60debbfae284b2bc3d2947dd2)) ### Fixes * concurrent fetch await in cloudflare ([e44cd18](https://github.com/panva/jose/commit/e44cd18ea4cf8af173f874ca3a847fc315eee592)), closes [#355](https://github.com/panva/jose/issues/355) ## [4.4.0](https://github.com/panva/jose/compare/v4.3.9...v4.4.0) (2022-01-24) ### Features * add createLocalJWKSet, resolver to verify using a local JWKSet ([bd7bf37](https://github.com/panva/jose/commit/bd7bf3789c146d765bbee2db0c93ba035020b24c)) ## [4.3.9](https://github.com/panva/jose/compare/v4.3.8...v4.3.9) (2022-01-22) ### Fixes * only add y to the epk header parameter when EC keys are used ([dd6775e](https://github.com/panva/jose/commit/dd6775eed00b60c14b7038ddec85c8bb3cf05781)), closes [#348](https://github.com/panva/jose/issues/348) ## [4.3.8](https://github.com/panva/jose/compare/v4.3.7...v4.3.8) (2022-01-09) ## [4.3.7](https://github.com/panva/jose/compare/v4.3.6...v4.3.7) (2021-11-18) ### Fixes * **typescript:** b64: true is fine to use in JWT, its useless, but allowed ([#324](https://github.com/panva/jose/issues/324)) ([ee401c9](https://github.com/panva/jose/commit/ee401c9e0f23f10ff5c0484798cb0cb3e9074b84)) ## [4.3.6](https://github.com/panva/jose/compare/v4.3.5...v4.3.6) (2021-11-16) ### Fixes * **electron:** rsa-pss keys are never supported ([188c1f7](https://github.com/panva/jose/commit/188c1f709002302da99105cfc8fc6863a95761d9)) ## [4.3.5](https://github.com/panva/jose/compare/v4.3.4...v4.3.5) (2021-11-12) ### Fixes * **typescript:** b64 header regression ([#324](https://github.com/panva/jose/issues/324)) ([9da0a7f](https://github.com/panva/jose/commit/9da0a7f49cf763314748eb01303320ce5af69762)) ## [4.3.4](https://github.com/panva/jose/compare/v4.3.3...v4.3.4) (2021-11-12) ### Fixes * Compact JWS verification handles a zero-length payload string ([7c70e7b](https://github.com/panva/jose/commit/7c70e7b9700886dfad8e7555b909da8e079c88da)) ## [4.3.3](https://github.com/panva/jose/compare/v4.3.2...v4.3.3) (2021-11-11) ### Fixes * **typescript:** apply updated compact and jwt headers to compact/jwt verify and decrypt results ([0c1946c](https://github.com/panva/jose/commit/0c1946c3e2a95e082b9a9095bf035756d8f17730)) ## [4.3.2](https://github.com/panva/jose/compare/v4.3.0...v4.3.2) (2021-11-11) ### Fixes * createRemoteJWKSet handles all JWS syntaxes ([aaba8f3](https://github.com/panva/jose/commit/aaba8f3000b76b41733567367b9000348a839c17)) * **typescript:** Compact JWS Header Parameters has alg and enc as required ([0fa87af](https://github.com/panva/jose/commit/0fa87af64b8e9f0f0cb68264f4dc22cc985acf91)) * **typescript:** Compact JWS Header Parameters has alg as required ([c7fabd0](https://github.com/panva/jose/commit/c7fabd0f012513f3c9161b0f59befae1d7430e16)) * **typescript:** Signed JWT Header Parameters has alg as required and b64 as never ([79cbd82](https://github.com/panva/jose/commit/79cbd82d3dd36f9ef87e4d306d77d9694a1c5836)) ## [4.3.0](https://github.com/panva/jose/compare/v4.2.1...v4.3.0) (2021-11-11) ### Features * add GeneralSign signature and GeneralEncrypt recipient builder chaining ([cfc93f5](https://github.com/panva/jose/commit/cfc93f5daf4729a189ef5caabae4a9ec9ad45378)) ## [4.2.1](https://github.com/panva/jose/compare/v4.2.0...v4.2.1) (2021-11-09) ### Fixes * **node:** dont mention CryptoKey in versions without webcrypto ([401cabf](https://github.com/panva/jose/commit/401cabf97419768cea1d685dc73d933fa38d6c26)) ## [4.2.0](https://github.com/panva/jose/compare/v4.1.5...v4.2.0) (2021-11-08) ### Features * General JWE Encryption ([94eca81](https://github.com/panva/jose/commit/94eca816872527074d2a591a983ee6c5d64da30c)) ## [4.1.5](https://github.com/panva/jose/compare/v4.1.4...v4.1.5) (2021-11-05) ### Fixes * importX509 certificate values that do not include a version number ([51a18b6](https://github.com/panva/jose/commit/51a18b675a771ed573047398f79cd6f70d8f9fec)), closes [#308](https://github.com/panva/jose/issues/308) ## [4.1.4](https://github.com/panva/jose/compare/v4.1.3...v4.1.4) (2021-11-01) ### Fixes * allow shorter HMAC secrets ([57126f1](https://github.com/panva/jose/commit/57126f1806493a2782647610c2a6b5d20ea3e516)) ## [4.1.3](https://github.com/panva/jose/compare/v4.1.2...v4.1.3) (2021-11-01) ### Fixes * **edge-functions:** don't use globalThis ([3952030](https://github.com/panva/jose/commit/39520302d078da2273b5a24f8254f6c221195c63)) ## [4.1.2](https://github.com/panva/jose/compare/v4.1.1...v4.1.2) (2021-10-25) ### Fixes * **build:** ensure cjs/esm specific packages have the right main entry ([2f4526a](https://github.com/panva/jose/commit/2f4526a22b9bd62727bdd825e326ef79695c8ea3)) ## [4.1.1](https://github.com/panva/jose/compare/v4.1.0...v4.1.1) (2021-10-21) ### Fixes * **typescript:** work around potentially missing global URL from DOM lib ([7ed731c](https://github.com/panva/jose/commit/7ed731c567db6e64f0fbd618efe7e48d812af0c6)), closes [#295](https://github.com/panva/jose/issues/295) ## [4.1.0](https://github.com/panva/jose/compare/v4.0.4...v4.1.0) (2021-10-18) ### Features * **web:** publish umd and bundle files to cdnjs.com ([3b3100a](https://github.com/panva/jose/commit/3b3100a8f115db5fb7c56482a0c5cf4814e0f838)) ## [4.0.4](https://github.com/panva/jose/compare/v4.0.3...v4.0.4) (2021-10-17) ### Fixes * **web:** check Uint8Array CEK lengths, refactor for better tree-shaking ([e8299f2](https://github.com/panva/jose/commit/e8299f246b1dbf1665d8f1ed141b9bde34684293)) ## [4.0.3](https://github.com/panva/jose/compare/v4.0.2...v4.0.3) (2021-10-16) ### Fixes * **web:** checking cryptokey applicability early ([89dc2aa](https://github.com/panva/jose/commit/89dc2aab99d831e922ba865eccfb29b8229ed767)) ## [4.0.2](https://github.com/panva/jose/compare/v4.0.1...v4.0.2) (2021-10-15) ### Fixes * **typescript:** export ProduceJWT ([#285](https://github.com/panva/jose/issues/285)) ([2b8738e](https://github.com/panva/jose/commit/2b8738e38a4286c9a1411e3aef3159f61427317c)) ## [4.0.1](https://github.com/panva/jose/compare/v4.0.0...v4.0.1) (2021-10-14) ### Fixes * **typescript:** re-export all types from index.d.ts ([d68f104](https://github.com/panva/jose/commit/d68f104d5895f639812b3317696a4616c3e5fb59)) ## [4.0.0](https://github.com/panva/jose/compare/v3.20.3...v4.0.0) (2021-10-14) ### ⚠ BREAKING CHANGES * All module named exports have moved from subpaths to just "jose". For example, `import { jwtVerify } from 'jose/jwt/verify'` is now just `import { jwtVerify } from 'jose'`. * All submodule default exports and named have been removed in favour of just "jose" named exports. * **typescript:** remove repeated type re-exports * The undocumented `jose/util/random` was removed. * The `jose/jwk/thumbprint` named export is renamed to `calculateJwkThumbprint`, now `import { calculateJwkThumbprint } from 'jose'` * The deprecated `jose/jwk/parse` module was removed, use `import { importJWK } from 'jose'` instead. * The deprecated `jose/jwk/from_key_like` module was removed, use `import { exportJWK } from 'jose'` instead. ### Refactor * redo exports to support broader tooling ([dd2cf9e](https://github.com/panva/jose/commit/dd2cf9ed2d89488de6dc4536f721887ffc9bb34f)) * remove util/random ([914e47f](https://github.com/panva/jose/commit/914e47fc9b6c207fd7e3469b1c3fac40f7a81031)) * removed the deprecated jwk/from_key_like module ([ec1d0e7](https://github.com/panva/jose/commit/ec1d0e72fe39ec2bccc28e46b5bce2dc17711134)) * removed the deprecated jwk/parse module ([8d3cc3b](https://github.com/panva/jose/commit/8d3cc3bb46e7e87e6511859dce58a651811ca551)) * rename calculateThumprint to calculateJwkThumbprint ([5afb713](https://github.com/panva/jose/commit/5afb713fbb99e6c884bb3b1c68ae2cf490e54595)) * **typescript:** remove repeated type re-exports ([3e137d2](https://github.com/panva/jose/commit/3e137d2427035d18397825074c2ee1e5db97515b)) ## [3.20.3](https://github.com/panva/jose/compare/v3.20.2...v3.20.3) (2021-10-14) ### Fixes * remove clutter when tree shaking browser dist ([73ba370](https://github.com/panva/jose/commit/73ba3708d45e32215c76f17d9982b0f4e20b7f08)) * **typescript:** JWTExpired error TS2417 ([373e0e4](https://github.com/panva/jose/commit/373e0e4b22fb48cefcf14385a19c5ea6a57a849e)) ## [3.20.2](https://github.com/panva/jose/compare/v3.20.1...v3.20.2) (2021-10-13) ### Fixes * allow tree-shaking of errors ([0824301](https://github.com/panva/jose/commit/08243010d922c36d22002e35299ec5710654c695)) ## [3.20.1](https://github.com/panva/jose/compare/v3.20.0...v3.20.1) (2021-10-06) ### Fixes * **typescript:** PEM import functions always resolve a KeyLike, never a Uint8Array ([8ef3a8e](https://github.com/panva/jose/commit/8ef3a8ebb78b592e664102cb593542ae6259d72a)) ## [3.20.0](https://github.com/panva/jose/compare/v3.19.0...v3.20.0) (2021-10-06) ### Features * improve key input type errors, remove dependency on @types/node ([a13eb04](https://github.com/panva/jose/commit/a13eb045d86d96e56f7a250cdc808f8c5aa0e62a)) ### Fixes * proper createRemoteJWKSet timeoutDuration handling ([efa1619](https://github.com/panva/jose/commit/efa16195173f9f66b21d4f41039caaad0ccfa92a)), closes [#277](https://github.com/panva/jose/issues/277) ## [3.19.0](https://github.com/panva/jose/compare/v3.18.0...v3.19.0) (2021-09-26) ### Features * return resolved key when verify and decrypt resolve functions are used ([49fb62c](https://github.com/panva/jose/commit/49fb62cb96cd9afc854f5102313f16e27c0eb2b4)) ## [3.18.0](https://github.com/panva/jose/compare/v3.17.0...v3.18.0) (2021-09-22) ### Features * add X.509/SPKI/PKCS8 key import and SPKI/PKCS8 export functions ([a2af0f4](https://github.com/panva/jose/commit/a2af0f45fe47b3d73178ab00c18e49fccd2b1432)) ## [3.17.0](https://github.com/panva/jose/compare/v3.16.1...v3.17.0) (2021-09-10) ### Features * **cloudflare workers:** add support for EdDSA using Ed25519 ([0967369](https://github.com/panva/jose/commit/09673694027ffc4961c211c12e0b7eb2ac9966f3)) ## [3.16.1](https://github.com/panva/jose/compare/v3.16.0...v3.16.1) (2021-09-08) ### Fixes * guard Sign payloads and Encrypt plaintext argument types ([10a18f2](https://github.com/panva/jose/commit/10a18f28a0f845e91579afab3573730c9b1ae478)) ## [3.16.0](https://github.com/panva/jose/compare/v3.15.5...v3.16.0) (2021-09-07) ### Features * **node:** support rsa-pss keys in Node.js >= 16.9.0 for sign/verify ([0b112cf](https://github.com/panva/jose/commit/0b112cf63ed2a859806531853c37486485740f9c)) ## [3.15.5](https://github.com/panva/jose/compare/v3.15.4...v3.15.5) (2021-09-02) ### Fixes * omit some fetch options when running in Cloudflare Workers env ([ced065a](https://github.com/panva/jose/commit/ced065aa9754c625ea88a598025962503e078ae9)), closes [#255](https://github.com/panva/jose/issues/255) ## [3.15.4](https://github.com/panva/jose/compare/v3.15.3...v3.15.4) (2021-08-20) ### Fixes * **deno:** ignore incomplete webcrypto api type errors ([c5f2262](https://github.com/panva/jose/commit/c5f226290ead93b7f43f664fc05c5fec90f38be8)) * **typescript:** generateKeyPair never returns Uint8Array ([73adc01](https://github.com/panva/jose/commit/73adc014ad9827067637153a97f230bfdd72cb9b)) ## [3.15.3](https://github.com/panva/jose/compare/v3.15.2...v3.15.3) (2021-08-20) ### Fixes * **typescript:** GeneralJWSInput and GeneralJWS omit ([bc0b42f](https://github.com/panva/jose/commit/bc0b42f0f58e802721910ac1bc4d62eb704910ff)) ## [3.15.2](https://github.com/panva/jose/compare/v3.15.1...v3.15.2) (2021-08-20) ## [3.15.1](https://github.com/panva/jose/compare/v3.15.0...v3.15.1) (2021-08-20) ### Fixes * **typescript:** remove file extensions from types/**/*.d.ts files ([0c432e5](https://github.com/panva/jose/commit/0c432e554e7b1f0382efefe44c0053a446c9dcc4)), closes [#222](https://github.com/panva/jose/issues/222) ## [3.15.0](https://github.com/panva/jose/compare/v3.14.4...v3.15.0) (2021-08-20) ### Features * experimental Deno build & publish ([5c7d265](https://github.com/panva/jose/commit/5c7d2656b6e5659a19c6cb3c4fed73e724fe2f6e)) ### Fixes * **typescript:** allow sign results to be passed to verify ([59aa96d](https://github.com/panva/jose/commit/59aa96d28dd259d9d8b03fcf37b5a703c5e36874)) ## [3.14.4](https://github.com/panva/jose/compare/v3.14.3...v3.14.4) (2021-08-16) ### Fixes * throw JWEInvalid when jwe protected header is invalid ([991d435](https://github.com/panva/jose/commit/991d4350d0357ebad17080644c24bccec844c3b9)) * throw JWSInvalid when jws protected header is invalid ([#244](https://github.com/panva/jose/issues/244)) ([1fc79aa](https://github.com/panva/jose/commit/1fc79aa8315fa25e28f63f1c5534d0630fc781dc)) ## [3.14.3](https://github.com/panva/jose/compare/v3.14.2...v3.14.3) (2021-07-21) ### Fixes * **docs:** update doc links again ([26c4361](https://github.com/panva/jose/commit/26c4361c007e3bc7e6ee60b65f9535cecf447fe6)) ## [3.14.2](https://github.com/panva/jose/compare/v3.14.1...v3.14.2) (2021-07-21) ### Fixes * **docs:** update doc links ([86f9134](https://github.com/panva/jose/commit/86f9134248a1746904f4c9f79ee404007ab68858)) ## [3.14.1](https://github.com/panva/jose/compare/v3.14.0...v3.14.1) (2021-07-21) ### Fixes * **typescript:** export generate key pair result interface ([2b5cc28](https://github.com/panva/jose/commit/2b5cc28684bd9cd09de2f774d7326bffe61fe6ea)) ## [3.14.0](https://github.com/panva/jose/compare/v3.13.0...v3.14.0) (2021-07-02) ### Features * add verbose key type error messages ([df56b94](https://github.com/panva/jose/commit/df56b942c64dfdbb14cb860a403742f25ec60b49)) ### Fixes * **typescript:** remove file extensions from .d.ts files ([e091f0f](https://github.com/panva/jose/commit/e091f0f24537541e350e803bd1e657348f428da2)), closes [#222](https://github.com/panva/jose/issues/222) * AES Key Wrap input type check ([b83821b](https://github.com/panva/jose/commit/b83821b2bf99fe2051d4d4d89fe4ff18a8559722)) * guard SignJWT.prototype.sign() from missing protected header ([4103719](https://github.com/panva/jose/commit/4103719c24d1811306acf7d5290ef15c5afddcfb)), closes [#221](https://github.com/panva/jose/issues/221) * **typescript:** add "jku" header to JoseHeaderParameters ([#220](https://github.com/panva/jose/issues/220)) ([72a72db](https://github.com/panva/jose/commit/72a72db7723e06994066d6ad154073387c5bc17c)) ## [3.13.0](https://github.com/panva/jose/compare/v3.12.3...v3.13.0) (2021-06-22) ### Features * **typescript:** export consume module interface types ([#213](https://github.com/panva/jose/issues/213)) ([13fa3d8](https://github.com/panva/jose/commit/13fa3d8ae089b21dace0ea22782451ca77941600)) ## [3.12.3](https://github.com/panva/jose/compare/v3.12.2...v3.12.3) (2021-06-02) ### Fixes * **browser:** remove the use of a node std-lib in decodeProtectedHeader ([d9d4a5f](https://github.com/panva/jose/commit/d9d4a5f2e88ca5172ff753a503bfbdb50522d094)), closes [#206](https://github.com/panva/jose/issues/206) ## [3.12.2](https://github.com/panva/jose/compare/v3.12.1...v3.12.2) (2021-05-19) ### Performance * **node:** use util.types.is* helpers when available ([d36311d](https://github.com/panva/jose/commit/d36311d5162b3500728937bf25bd2c756f8a33d6)) ## [3.12.1](https://github.com/panva/jose/compare/v3.12.0...v3.12.1) (2021-05-14) ### Fixes * **browser:** avoid global-conflicting variable name fetch ([#199](https://github.com/panva/jose/issues/199)) ([b2c6273](https://github.com/panva/jose/commit/b2c6273eccad5e34cbe0219c521c6453ba71e6c4)) ## [3.12.0](https://github.com/panva/jose/compare/v3.11.6...v3.12.0) (2021-05-12) ### Features * **webcrypto:** allow generate* modules extractable: false override ([afae428](https://github.com/panva/jose/commit/afae428f39eb920297ef474878d4266172d9a015)) ## [3.11.6](https://github.com/panva/jose/compare/v3.11.5...v3.11.6) (2021-04-30) ### Fixes * swallow promisified crypto.verify errors ([d512ede](https://github.com/panva/jose/commit/d512ede0730155051707d60ae8c69ba0492d858f)) ## [3.11.5](https://github.com/panva/jose/compare/v3.11.4...v3.11.5) (2021-04-13) ### Fixes * isObject helper in different vm contexts or jest re-assigned globals ([7819df7](https://github.com/panva/jose/commit/7819df73ebf6391377ef3e7623948d8329ac47f5)), closes [#178](https://github.com/panva/jose/issues/178) ## [3.11.4](https://github.com/panva/jose/compare/v3.11.3...v3.11.4) (2021-04-09) ### Fixes * defer AES CBC w/ HMAC decryption after tag verification passes ([579485c](https://github.com/panva/jose/commit/579485cb806e9989643e32a66752d3235cd43f09)) ## [3.11.3](https://github.com/panva/jose/compare/v3.11.2...v3.11.3) (2021-04-01) ### Fixes * **node:** check CryptoKey algorithm & usage before exporting KeyObject ([dab4b2f](https://github.com/panva/jose/commit/dab4b2f03efc5772773e66fdb757db5571deee4d)) ## [3.11.2](https://github.com/panva/jose/compare/v3.11.1...v3.11.2) (2021-03-30) ### Fixes * assert KeyLike input types, change "any" types to "unknown" ([edb83a8](https://github.com/panva/jose/commit/edb83a846a880d316d77ace485641330dd0debb6)) ## [3.11.1](https://github.com/panva/jose/compare/v3.11.0...v3.11.1) (2021-03-26) ### Fixes * **node:** crypto.verify callback invocation with a private keyobject ([d3d4acd](https://github.com/panva/jose/commit/d3d4acd8be612850999309ef7de86c549d5de9c0)) ## [3.11.0](https://github.com/panva/jose/compare/v3.10.0...v3.11.0) (2021-03-24) ### Features * export error codes as static properties ([89d8003](https://github.com/panva/jose/commit/89d80038755be21228a3455a8feca396e76fbcf5)), closes [#170](https://github.com/panva/jose/issues/170) ## [3.10.0](https://github.com/panva/jose/compare/v3.9.0...v3.10.0) (2021-03-18) ### Features * **node:** use libuv threadpool to sign in node >= 15.12.0 ([cf5074e](https://github.com/panva/jose/commit/cf5074e7e1333728f7632ee6785cc52ef32711bf)) * **node:** use libuv threadpool to verify in node >= 15.12.0 ([ae9a7f4](https://github.com/panva/jose/commit/ae9a7f4186da9675820dc2e77786b9ee3f7dd0d0)) * **node:** use native JWK export in node >= 15.9.0 ([7f3cc44](https://github.com/panva/jose/commit/7f3cc44bd0508bf15c061500738473eeafdc32d1)) * **node:** use native JWK import in node >= 15.12.0 ([f0c2a64](https://github.com/panva/jose/commit/f0c2a6472844c43a92a79ed90b51cc5133a2e22e)) ## [3.9.0](https://github.com/panva/jose/compare/v3.8.0...v3.9.0) (2021-03-15) ### Features * add named exports for all modules ([5cba6b0](https://github.com/panva/jose/commit/5cba6b0fdddd24c2e48623d8aaf48640b3279a43)) ## [3.8.0](https://github.com/panva/jose/compare/v3.7.1...v3.8.0) (2021-03-12) ### Features * publish alternative Node.js and Browser specific distributions ([7856dad](https://github.com/panva/jose/commit/7856dad1031845bfc3cadfdbe609d0f0154f19ce)) ## [3.7.1](https://github.com/panva/jose/compare/v3.7.0...v3.7.1) (2021-03-11) ### Fixes * swallow invalid signature encoding errors ([e0adf49](https://github.com/panva/jose/commit/e0adf49e5789f9fc23afb1e2bd3e330e34b46b78)) ## [3.7.0](https://github.com/panva/jose/compare/v3.6.2...v3.7.0) (2021-03-02) ### Features * electron >=12.0.0 is now supported (and tested on ci) ([8fffd3e](https://github.com/panva/jose/commit/8fffd3e2e1ec0c5f3517a779b42974a4c1beae27)) ### Fixes * **electron:** only call (de)cipher.setAAD() when aad is not empty ([a5a6c4d](https://github.com/panva/jose/commit/a5a6c4dc9f459b88de5f243cf1d4ea620def8d98)) * **electron:** properly ASN.1 encode [0x00] when converting RSA JWKs ([433f020](https://github.com/panva/jose/commit/433f020246a9131f63705a3e1aa99492dac50947)) ## [3.6.2](https://github.com/panva/jose/compare/v3.6.1...v3.6.2) (2021-02-16) ### Fixes * **typescript:** update maxTokenAge type and examples ([2c358e0](https://github.com/panva/jose/commit/2c358e0ea550f19896ccf43724ee8224aa04a664)) ## [3.6.1](https://github.com/panva/jose/compare/v3.6.0...v3.6.1) (2021-02-10) ### Fixes * node runtime json fetch handles connection errors properly ([fc584b2](https://github.com/panva/jose/commit/fc584b2efd9a6e7bf2ac83c6fb0ddf96fb0ca6a5)) ## [3.6.0](https://github.com/panva/jose/compare/v3.5.4...v3.6.0) (2021-02-04) ### Features * allow CryptoKey instances in a regular non-webcrypto node runtime ([e8d41a9](https://github.com/panva/jose/commit/e8d41a933582495c9a9b02d6ec38b46bef8795e1)) ## [3.5.4](https://github.com/panva/jose/compare/v3.5.3...v3.5.4) (2021-01-26) ### Fixes * export package.json ([8c29107](https://github.com/panva/jose/commit/8c29107aea26a54869d8adadceaf0bbf70fb18cd)), closes [#157](https://github.com/panva/jose/issues/157) ## [3.5.3](https://github.com/panva/jose/compare/v3.5.2...v3.5.3) (2021-01-20) ### Fixes * workaround downstream dependency issues messing with http ([2e58005](https://github.com/panva/jose/commit/2e5800535ab72ab35f3abfaab7493163d8b0494e)), closes [#154](https://github.com/panva/jose/issues/154) ## [3.5.2](https://github.com/panva/jose/compare/v3.5.1...v3.5.2) (2021-01-18) ### Performance * use 'base64url' encoding when available in Node.js runtime ([808f06c](https://github.com/panva/jose/commit/808f06cd08b10cf53343afb35802cc6e5b95ea20)) * use KeyObject.prototype asymmetricKeyDetails when available ([ad88ee2](https://github.com/panva/jose/commit/ad88ee2cd5bcaee3c3e5ec79735c8172ae2725be)) ## [3.5.1](https://github.com/panva/jose/compare/v3.5.0...v3.5.1) (2021-01-10) ### Fixes * workaround for RangeError in browser runtime base64url ([ed32b0d](https://github.com/panva/jose/commit/ed32b0d46ee570e405e0d88b43aecd8ef6fea129)) ## [3.5.0](https://github.com/panva/jose/compare/v3.4.0...v3.5.0) (2020-12-17) ### Features * added JWE General JSON Serialization decryption ([16dea9e](https://github.com/panva/jose/commit/16dea9ec7d6179471f794a3463bba0c6e77295ff)) ## [3.4.0](https://github.com/panva/jose/compare/v3.3.2...v3.4.0) (2020-12-16) ### Features * added JWS General JSON Serialization signing ([6fb862c](https://github.com/panva/jose/commit/6fb862cf12d34b7dc5077d1872ad29eeac27d21e)), closes [#129](https://github.com/panva/jose/issues/129) * added JWS General JSON Serialization verification ([55b7781](https://github.com/panva/jose/commit/55b77810d03a1f7e38e13bec384dece08b74b206)), closes [#129](https://github.com/panva/jose/issues/129) * added utility function for decoding token's protected header ([fa29d68](https://github.com/panva/jose/commit/fa29d68cfdf0922c7e4dac24eb50161d1eab28d4)) ## [3.3.2](https://github.com/panva/jose/compare/v3.3.1...v3.3.2) (2020-12-14) ### Fixes * **typescript:** ref dom lib via triple-slash to fix some compile issues ([175f273](https://github.com/panva/jose/commit/175f273819785c29b9ad822dcb5d70073523f504)), closes [#126](https://github.com/panva/jose/issues/126) ## [3.3.1](https://github.com/panva/jose/compare/v3.3.0...v3.3.1) (2020-12-06) ### Fixes * botched v3.3.0 release ([1c3e116](https://github.com/panva/jose/commit/1c3e116976c997f205b917405f010b568d1bd3b9)) ## [3.3.0](https://github.com/panva/jose/compare/v3.2.0...v3.3.0) (2020-12-06) ### Features * support recognizing proprietary `crit` header parameters ([5163116](https://github.com/panva/jose/commit/5163116ca1c091871ed0c601c9fbc1dbe94599cd)), closes [#123](https://github.com/panva/jose/issues/123) ### Fixes * reject JWTs with b64: false ([691b44a](https://github.com/panva/jose/commit/691b44ad4717c82a06539facfedff48fa0e9c6a9)) ## [3.2.0](https://github.com/panva/jose/compare/v3.1.3...v3.2.0) (2020-12-02) ### Features * allow specifying modulusLength when generating RSA Key Pairs ([5f7a0e9](https://github.com/panva/jose/commit/5f7a0e9055256bce4786a53711bcf14cf59fa8f1)), closes [#121](https://github.com/panva/jose/issues/121) ## [3.1.3](https://github.com/panva/jose/compare/v3.1.2...v3.1.3) (2020-11-26) ### Fixes * **typescript:** refactored how types are published ([2937363](https://github.com/panva/jose/commit/29373633bc540ff1e7bfe8fb3e5c5b391e79c2d9)), closes [#119](https://github.com/panva/jose/issues/119) ## [3.1.2](https://github.com/panva/jose/compare/v3.1.1...v3.1.2) (2020-11-24) ### Fixes * handle globalThis undefined in legacy browsers ([b83c59b](https://github.com/panva/jose/commit/b83c59bb43ad14ac932cd0c662f7dfc2c4c62753)) ## [3.1.1](https://github.com/panva/jose/compare/v3.1.0...v3.1.1) (2020-11-24) ### Fixes * global detection in a browser worker runtime ([56ff8fa](https://github.com/panva/jose/commit/56ff8fa65aa045411c6c6a67d80b67c1099576a0)) ## [3.1.0](https://github.com/panva/jose/compare/v3.0.2...v3.1.0) (2020-11-22) ### Features * added "KeyLike to JWK" module ([7a8418e](https://github.com/panva/jose/commit/7a8418eadd68b645fb7edf78873a35980ea8e41d)), closes [#109](https://github.com/panva/jose/issues/109) * allow compact verify/decrypt tokens to be uint8array encoded ([e39c3db](https://github.com/panva/jose/commit/e39c3dba75e5ae70697e6a4f93096c492a265c07)) * allow http.Agent and https.Agent passed in remote JWK Set ([38494a8](https://github.com/panva/jose/commit/38494a88828a8df2015efa78ca29c1a6317a3a50)) ## [3.0.2](https://github.com/panva/jose/compare/v3.0.1...v3.0.2) (2020-11-15) ### Fixes * **build:** publish esm submodules ([7b6364f](https://github.com/panva/jose/commit/7b6364f26f7654368c9e33af58043ee40e77ec77)), closes [#104](https://github.com/panva/jose/issues/104) ## [3.0.1](https://github.com/panva/jose/compare/v3.0.0...v3.0.1) (2020-11-15) ### Fixes * **typescript:** fix compiling by adding .d.ts files for runtime modules ([d9cb573](https://github.com/panva/jose/commit/d9cb5734d779df26c3e717a9f4f23d18b856dc5f)) ## [3.0.0](https://github.com/panva/jose/compare/v2.0.3...v3.0.0) (2020-11-14) ### ⚠ BREAKING CHANGES * Revised, Promise-based API * No dependencies * Browser support (using [Web Cryptography API](https://www.w3.org/TR/WebCryptoAPI/)) * Support for verification using a remote JWKS endpoint ### Features * Revised API, No dependencies, Browser Support, Promises ([357fe0b](https://github.com/panva/jose/commit/357fe0b964903e8c84ab49f0f27ddf0447d44c84)) ## [2.0.3](https://github.com/panva/jose/compare/v2.0.2...v2.0.3) (2020-10-29) ### Fixes * allow stubbing of the JWT.decode function ([6c3b92f](https://github.com/panva/jose/commit/6c3b92f4394a5d7092d7336922eda61e311e6f8c)) ## [2.0.2](https://github.com/panva/jose/compare/v2.0.1...v2.0.2) (2020-09-14) ### Fixes * **esm:** include esm files in the published package ([1956746](https://github.com/panva/jose/commit/1956746df6542c00bc33af750f93394805b5d603)) ## [2.0.1](https://github.com/panva/jose/compare/v2.0.0...v2.0.1) (2020-09-10) ### Fixes * allow plugins such as jose-chacha to work in newer node runtime ([30f1dc2](https://github.com/panva/jose/commit/30f1dc2c41e5554d322167b84b610a99bf5e69c5)) ## [2.0.0](https://github.com/panva/jose/compare/v1.28.0...v2.0.0) (2020-09-08) ### ⚠ BREAKING CHANGES * the `JWE.decrypt` option `algorithms` was removed and replaced with contentEncryptionAlgorithms (handles `enc` allowlist) and keyManagementAlgorithms (handles `alg` allowlist) * the `JWT.verify` profile option was removed, use e.g. `JWT.IdToken.verify` instead. * removed the `maxAuthAge` `JWT.verify` option, this option is now only present at the specific JWT profile APIs where the `auth_time` property applies. * removed the `nonce` `JWT.verify` option, this option is now only present at the specific JWT profile APIs where the `nonce` property applies. * the `acr`, `amr`, `nonce` and `azp` claim value types will only be checked when verifying a specific JWT profile using its dedicated API. * using the draft implementing APIs will emit a one-time warning per process using `process.emitWarning` * `JWT.sign` function options no longer accept a `nonce` property. To create a JWT with a `nonce` just pass the value to the payload. * due to added ESM module support Node.js version with ESM implementation bugs are no longer supported, this only affects early v13.x versions. The resulting Node.js semver range is `>=10.13.0 < 13 || >=13.7.0` * deprecated method `JWK.importKey` was removed * deprecated method `JWKS.KeyStore.fromJWKS` was removed * the use of unregistered curve name P-256K for secp256k1 was removed * jose.JWE.Encrypt constructor aad and unprotectedHeader arguments swapped places * jose.JWE.encrypt.flattened header (unprotectedHeader) and aad arguments swapped places * jose.JWE.encrypt.general header (unprotectedHeader) and aad arguments swapped places * JWS.verify returned payloads are now always buffers * JWS.verify options `encoding` and `parse` were removed ### Features * added support for ESM (ECMAScript modules) ([1aa9035](https://github.com/panva/jose/commit/1aa9035552bbcb34b95e092d0f082cc6d94465ab)) * decrypt allowlists for both key management and content encryption ([30e5c46](https://github.com/panva/jose/commit/30e5c46ecf00a498e65a551ced88bc897531c2a4)) ### Fixes * **typescript:** allow Buffer when verifying detached signature ([cadbd04](https://github.com/panva/jose/commit/cadbd047ca953d6d8171439f2efd7bb98a5d8e73)) * **typescript:** properly type all decode/verify/decrypt fn options ([4c23bd6](https://github.com/panva/jose/commit/4c23bd65fe6fa634726a5eb73c6d590f7348a97e)) ### Refactor * encrypt APIs unprotectedHeader and aad arguments swapped ([70bd4ae](https://github.com/panva/jose/commit/70bd4ae6b2e6ba94bbe0b3dc1a17b2990af3a18b)) * move JWT profile specifics outside of generic JWT ([fd69d7f](https://github.com/panva/jose/commit/fd69d7f5093d0b3a231d7d79aa3bca3a8a64464c)) * removed `nonce` option from `JWT.sign` ([c4267cc](https://github.com/panva/jose/commit/c4267cc655bc2721d846c98f8a40640d1a12e9ad)) * removed deprecated methods and utilities ([6c35c51](https://github.com/panva/jose/commit/6c35c519c9181f8246b36ad02572adb609d6de1d)) * removed payload parsing from JWS.verify ([ba5c897](https://github.com/panva/jose/commit/ba5c89791915a2a3cd56b3dab1f3328778152d33)) ## [1.28.0](https://github.com/panva/jose/compare/v1.27.3...v1.28.0) (2020-08-10) ### Features * support for validating issuer from a list of values ([#91](https://github.com/panva/jose/issues/91)) ([ce6836a](https://github.com/panva/jose/commit/ce6836af88c9e73c29560233f15ed1760c7dcc13)) ## [1.27.3](https://github.com/panva/jose/compare/v1.27.2...v1.27.3) (2020-08-04) ### Fixes * do not mutate unencoded payload when signing for multiple parties ([1695423](https://github.com/panva/jose/commit/169542363f884e4028db9f80086d631e626eb469)), closes [#89](https://github.com/panva/jose/issues/89) * ensure "b64" is the same for all recipients edge cases ([d56ec9f](https://github.com/panva/jose/commit/d56ec9f5ddc2612e5ff21fe35d45a56e7153e0e4)) ## [1.27.2](https://github.com/panva/jose/compare/v1.27.1...v1.27.2) (2020-07-01) ### Fixes * handle private EC keys without public component ([#86](https://github.com/panva/jose/issues/86)) ([e8ad389](https://github.com/panva/jose/commit/e8ad38993e29747098f7fd1594dde4ce893ba802)), closes [#85](https://github.com/panva/jose/issues/85) ## [1.27.1](https://github.com/panva/jose/compare/v1.27.0...v1.27.1) (2020-06-01) ### Fixes * allow any JSON numeric value for timestamp values ([7ba4922](https://github.com/panva/jose/commit/7ba492237aaf788914166c134d50fb046041efa0)) ## [1.27.0](https://github.com/panva/jose/compare/v1.26.1...v1.27.0) (2020-05-05) ### Features * add opt-in objects to verify using embedded JWS Header public keys ([7c1cab1](https://github.com/panva/jose/commit/7c1cab196edc409ec6cc4741bdf7e06c5aaf5dab)) ## [1.26.1](https://github.com/panva/jose/compare/v1.26.0...v1.26.1) (2020-04-27) ### Fixes * **typescript:** types of key generate functions without overloads ([7e60722](https://github.com/panva/jose/commit/7e60722ae7054f8acf833e015c22679d56fbc0ca)), closes [#80](https://github.com/panva/jose/issues/80) * "typ" content-type validation, case insensitive and handled prefix ([0691586](https://github.com/panva/jose/commit/06915861b32c0ae252dcc84791050bc3716ce102)) ## [1.26.0](https://github.com/panva/jose/compare/v1.25.2...v1.26.0) (2020-04-16) ### Features * update JWT Profile for OAuth 2.0 Access Tokens to latest draft ([8c0a8a9](https://github.com/panva/jose/commit/8c0a8a950e4503cb7a756589e307286fe1116b05)) ### BREAKING CHANGES * `at+JWT` JWT draft profile - in the draft's Section 2.2 the claims `iat` and `jti` are now REQUIRED (was RECOMMENDED). ## [1.25.2](https://github.com/panva/jose/compare/v1.25.1...v1.25.2) (2020-04-15) ### Fixes * **build:** don't publish junk files ([6e98c1a](https://github.com/panva/jose/commit/6e98c1a5f994224b9412fc47c4065b468c89fe2c)) ## [1.25.1](https://github.com/panva/jose/compare/v1.25.0...v1.25.1) (2020-04-15) ### Fixes * use native openssl AES Key Wrap 🤦 ([dcf8d75](https://github.com/panva/jose/commit/dcf8d75a8aca4f05fe04df64fdd2ba50bbc75bc9)) ## [1.25.0](https://github.com/panva/jose/compare/v1.24.1...v1.25.0) (2020-03-11) ### Features * update JWT Profile for OAuth 2.0 Access Tokens to latest draft ([bc77a15](https://github.com/panva/jose/commit/bc77a15fab10f8a29561ef667a923b2f074fa9b3)) ## [1.24.1](https://github.com/panva/jose/compare/v1.24.0...v1.24.1) (2020-03-05) ### Fixes * allow importing simpler passphrases as `oct` keys ([f86bda3](https://github.com/panva/jose/commit/f86bda3bb709f29e4264fb8de45242f518128744)) ## [1.24.0](https://github.com/panva/jose/compare/v1.23.0...v1.24.0) (2020-02-25) ### Features * add JWT.verify "typ" option for checking JWT Type Header parameter ([fc08426](https://github.com/panva/jose/commit/fc08426466233709b442ba21232768ddeeb94e56)) ## [1.23.0](https://github.com/panva/jose/compare/v1.22.2...v1.23.0) (2020-02-18) ### Fixes * **typescript:** add optional JWK.Key props and make them readonly ([b92079c](https://github.com/panva/jose/commit/b92079cb64216b8ea91082adc07ac03972dbbb0e)), closes [#67](https://github.com/panva/jose/issues/67) ### Features * add ECDH-ES with X25519 and X448 OKP keys ([38369ea](https://github.com/panva/jose/commit/38369ea3d72812abe7ecebd6dc7da164b0a2e29d)) * add RSA-OAEP-384 and RSA-OAEP-512 JWE Key Management Algorithms ([7477f08](https://github.com/panva/jose/commit/7477f0831b38765a9a916b35b1d40aaf11f0e6b8)) ## [1.22.2](https://github.com/panva/jose/compare/v1.22.1...v1.22.2) (2020-02-06) ### Performance Improvements * various codepaths refactored ([3e3d7dd](https://github.com/panva/jose/commit/3e3d7dd38168159e188e54c48a9f83e3a02a8fe1)) ## [1.22.1](https://github.com/panva/jose/compare/v1.22.0...v1.22.1) (2020-02-03) ### Fixes * actually remove the base64url proper encoding check ([eae01b5](https://github.com/panva/jose/commit/eae01b57ab9f33e8c621ffcd2a77d513a51d22b2)) ## [1.22.0](https://github.com/panva/jose/compare/v1.21.1...v1.22.0) (2020-01-29) ### Features * keystore filtering by JWK Key thumbprint ([a9f6f71](https://github.com/panva/jose/commit/a9f6f7135005d6231d6f42d95c02414139a89d17)) ### Performance Improvements * base64url decode, JWT.verify, JWK.Key instance re-use ([470b4c7](https://github.com/panva/jose/commit/470b4c73154e1fcf8b92726d521940e5e11c9d94)) ## [1.21.1](https://github.com/panva/jose/compare/v1.21.0...v1.21.1) (2020-01-25) ### Fixes * contactKDF iteration count fixed for key sizes larger than 256 bits ([70ff222](https://github.com/panva/jose/commit/70ff22227ad303e57228dc8351688531499a833a)) ## [1.21.0](https://github.com/panva/jose/compare/v1.20.0...v1.21.0) (2020-01-23) ### Fixes * **typescript:** don't expose non existant classes, fix decode key ([0f8bf88](https://github.com/panva/jose/commit/0f8bf886da1b5d02cd0d968d0ec02a58673df258)) ### Features * add opt-in support for Unsecured JWS algorithm "none" ([3a6d17f](https://github.com/panva/jose/commit/3a6d17fdd18d8bbd074c07c2dd08f0406c16a8f1)) ## [1.20.0](https://github.com/panva/jose/compare/v1.19.0...v1.20.0) (2020-01-16) ### Features * add JWTExpired error and JWTClaimInvalid claim and reason props ([a0c0c7a](https://github.com/panva/jose/commit/a0c0c7ad70f42d9b23b3e71de43599a8ac6fe1ff)), closes [#62](https://github.com/panva/jose/issues/62) ## [1.19.0](https://github.com/panva/jose/compare/v1.18.2...v1.19.0) (2020-01-13) ### Features * exposed shorthands for JWT verification profiles ([b1864e3](https://github.com/panva/jose/commit/b1864e319d1a7a42eadfa0c4b0145952e7814726)) ## [1.18.2](https://github.com/panva/jose/compare/v1.18.1...v1.18.2) (2020-01-08) ### Fixes * ensure asn1.js version to remove Buffer deprecation notice ([13b1106](https://github.com/panva/jose/commit/13b1106048fdeae00b09d54f05245dded85b14a7)) * expose JOSENotSupported key import errors on unsupported runtimes ([bc81e5d](https://github.com/panva/jose/commit/bc81e5dec2987f6ce6dc3fa5daa23dfe620c0a34)) * typo in JOSENotSupported error when x509 certs are not supported ([bb58c9c](https://github.com/panva/jose/commit/bb58c9ce52e807ca4cfad6bcbf1ab96b91778b1f)) ## [1.18.1](https://github.com/panva/jose/compare/v1.18.0...v1.18.1) (2020-01-01) ### Fixes * force iat past check when maxTokenAge option is used + JWT refactor ([828ad5a](https://github.com/panva/jose/commit/828ad5a33dc0cc0049923b69f43f97463295456e)) ## [1.18.0](https://github.com/panva/jose/compare/v1.17.2...v1.18.0) (2019-12-31) ### Features * add JWT validation profiles for Access Tokens and Logout Tokens ([7bb5c95](https://github.com/panva/jose/commit/7bb5c953a9c6d9bd915e8ebc0608bc0649427745)) ## [1.17.2](https://github.com/panva/jose/compare/v1.17.1...v1.17.2) (2019-12-17) ### Fixes * skip validating iat is in the past when exp is present ([0ed5025](https://github.com/panva/jose/commit/0ed5025de30a754de95ae2587ce0f4573909b006)) ## [1.17.1](https://github.com/panva/jose/compare/v1.17.0...v1.17.1) (2019-12-10) ### Fixes * properly fail to import unsupported openssh keys ([bee5744](https://github.com/panva/jose/commit/bee574457f29597ccab09d51ac61b85dd7a7146a)) ## [1.17.0](https://github.com/panva/jose/compare/v1.16.2...v1.17.0) (2019-12-10) ### Features * importing a certificate populates x5c and x5t thumbprints ([25a7a71](https://github.com/panva/jose/commit/25a7a71915c4f7514536cec9e7e162d0ad3b670c)), closes [#59](https://github.com/panva/jose/issues/59) ## [1.16.2](https://github.com/panva/jose/compare/v1.16.1...v1.16.2) (2019-12-05) ### Fixes * handle Unencoded Payload (b64:false) with arbitrary buffer payloads ([daabedc](https://github.com/panva/jose/commit/daabedc776617f4fde427b3a5e79d8c176293132)), closes [#57](https://github.com/panva/jose/issues/57) ## [1.16.1](https://github.com/panva/jose/compare/v1.16.0...v1.16.1) (2019-12-05) ### Fixes * allow PBES2 for the correct JWK `use` values ([f0d7194](https://github.com/panva/jose/commit/f0d719416ec9ca041ea88b8a983b5d899a6aa107)) ## [1.16.0](https://github.com/panva/jose/compare/v1.15.1...v1.16.0) (2019-12-04) ### Features * two official jose plugins/extensions for those living on the edge ([5b27c97](https://github.com/panva/jose/commit/5b27c97ac8836ffa9f3880e009c8db5afbfbaa2c)), closes [#56](https://github.com/panva/jose/issues/56) ## [1.15.1](https://github.com/panva/jose/compare/v1.15.0...v1.15.1) (2019-11-30) ### Fixes * **typescript:** export Key Input types ([0277fcd](https://github.com/panva/jose/commit/0277fcd1896af497e79190212b0719f7e62366c1)) ## [1.15.0](https://github.com/panva/jose/compare/v1.14.0...v1.15.0) (2019-11-27) ### Fixes * default JWT.sign `kid` option value is false for HMAC signatures ([ce77388](https://github.com/panva/jose/commit/ce7738825403f8cdb8f99cb51c096baf0dfa3af7)) ### Features * allow JWK.asKey inputs for sign/verify/encrypt/decrypt operations ([5e1009a](https://github.com/panva/jose/commit/5e1009a63e4bc829009cc46d6295c00f8431024c)) ## [1.14.0](https://github.com/panva/jose/compare/v1.13.0...v1.14.0) (2019-11-26) ### Features * allow JWKS.KeyStore .all and .get to filter for key curves ([ea60338](https://github.com/panva/jose/commit/ea60338ca6f58f2626992a38da76812477ce4540)) ## [1.13.0](https://github.com/panva/jose/compare/v1.12.1...v1.13.0) (2019-11-23) ### Features * return the CEK from JWE.decrypt operation with { complete: true } ([c3eb845](https://github.com/panva/jose/commit/c3eb8450b98b2f5ecc127d69afe85a7ae2cc5aaa)) ## [1.12.1](https://github.com/panva/jose/compare/v1.12.0...v1.12.1) (2019-11-14) ## [1.12.0](https://github.com/panva/jose/compare/v1.11.0...v1.12.0) (2019-11-05) ### Features * add JWS.verify encoding and parsing options ([6bb66d4](https://github.com/panva/jose/commit/6bb66d4f0b4c96f2da8ac5f14fda6bc4f53f2994)) ## [1.11.0](https://github.com/panva/jose/compare/v1.10.2...v1.11.0) (2019-11-03) ### Features * expose crypto.KeyObject instances in supported runtimes ([8ea9683](https://github.com/panva/jose/commit/8ea968312e97ed0f992fab909a20e7993159ec45)) ## [1.10.2](https://github.com/panva/jose/compare/v1.10.1...v1.10.2) (2019-10-29) ### Fixes * only use secp256k1 keys for signing/verification ([9588223](https://github.com/panva/jose/commit/95882232d6d409a321b6a8c168f5b78ebbdabf95)) ## [1.10.1](https://github.com/panva/jose/compare/v1.10.0...v1.10.1) (2019-10-04) ### Fixes * throw proper error when runtime doesn't support OKP ([0a16efb](https://github.com/panva/jose/commit/0a16efb)), closes [#48](https://github.com/panva/jose/issues/48) ## [1.10.0](https://github.com/panva/jose/compare/v1.9.2...v1.10.0) (2019-10-01) ### Features * rename package ([26f4cf2](https://github.com/panva/jose/commit/26f4cf2)) ## [1.9.2](https://github.com/panva/jose/compare/v1.9.1...v1.9.2) (2019-09-16) ### Fixes * keystore.toJWKS(true) does not throw on public keys ([81abdfa](https://github.com/panva/jose/commit/81abdfa)), closes [#42](https://github.com/panva/jose/issues/42) ## [1.9.1](https://github.com/panva/jose/compare/v1.9.0...v1.9.1) (2019-09-10) ## [1.9.0](https://github.com/panva/jose/compare/v1.8.0...v1.9.0) (2019-08-24) ### Features * allow JWKS.asKeyStore to swallow errors ([78398d3](https://github.com/panva/jose/commit/78398d3)) ## [1.8.0](https://github.com/panva/jose/compare/v1.7.0...v1.8.0) (2019-08-22) ### Features * added Node.js lts/dubnium support for runtime supported features ([67a8601](https://github.com/panva/jose/commit/67a8601)) ## [1.7.0](https://github.com/panva/jose/compare/v1.6.1...v1.7.0) (2019-08-20) ### Features * add RSA-OAEP-256 support (when a node version supports it) ([28d7cf8](https://github.com/panva/jose/commit/28d7cf8)), closes [#29](https://github.com/panva/jose/issues/29) ## [1.6.1](https://github.com/panva/jose/compare/v1.6.0...v1.6.1) (2019-07-29) ### Fixes * properly pad calculated RSA primes ([dd121ce](https://github.com/panva/jose/commit/dd121ce)) ## [1.6.0](https://github.com/panva/jose/compare/v1.5.2...v1.6.0) (2019-07-27) ### Fixes * use the correct ECPrivateKey version when importing EC JWK ([24acd20](https://github.com/panva/jose/commit/24acd20)) ### Features * electron v6.x support ([e7ad82c](https://github.com/panva/jose/commit/e7ad82c)) ## [1.5.2](https://github.com/panva/jose/compare/v1.5.1...v1.5.2) (2019-07-27) ### Fixes * importing x5c in electron requires the input split ([181fd09](https://github.com/panva/jose/commit/181fd09)) ## [1.5.1](https://github.com/panva/jose/compare/v1.5.0...v1.5.1) (2019-07-27) ### Fixes * correctly pad integers when importing RSA JWK ([1dc7f35](https://github.com/panva/jose/commit/1dc7f35)) ## [1.5.0](https://github.com/panva/jose/compare/v1.4.1...v1.5.0) (2019-07-23) ### Features * validate JWTs according to a JWT profile - ID Token ([6c98b61](https://github.com/panva/jose/commit/6c98b61)) ## [1.4.1](https://github.com/panva/jose/compare/v1.4.0...v1.4.1) (2019-07-14) ### Fixes * honour the JWT.sign `jti` option ([36c9ce2](https://github.com/panva/jose/commit/36c9ce2)), closes [#33](https://github.com/panva/jose/issues/33) ## [1.4.0](https://github.com/panva/jose/compare/v1.3.0...v1.4.0) (2019-07-08) ### Features * add secp256k1 EC Key curve and ES256K ([211d7af](https://github.com/panva/jose/commit/211d7af)) ## [1.3.0](https://github.com/panva/jose/compare/v1.0.2...c51dc28) (2019-06-21) ### Features * compute private RSA key p, q, dp, dq, qi when omitted ([6e3d6fd](https://github.com/panva/jose/commit/6e3d6fd)), closes [#26](https://github.com/panva/jose/issues/26) * add support for JWK x5c, x5t and x5t#S256 ([9d46c48](https://github.com/panva/jose/commit/9d46c48)) * instances of JWKS.KeyStore are now iterable (e.g. for ... of) ([2eae293](https://github.com/panva/jose/commit/2eae293)) ### Fixes * limit calculation of missing RSA private components ([5b53cb0](https://github.com/panva/jose/commit/5b53cb0)) * reject rsa keys without all factors and exponents with a specific message ([b0ff436](https://github.com/panva/jose/commit/b0ff436)) ### Deprecations - this deprecates the use of `JWK.importKey` in favor of `JWK.asKey` - this deprecates the use of `JWKS.KeyStore.fromJWKS` in favor of `JWKS.asKeyStore` Both `JWK.importKey` and `JWKS.KeyStore.fromJWKS` could have resulted in the process getting blocked when large bitsize RSA private keys were missing their components and could also result in an endless calculation loop when the private key's private exponent was outright invalid or tampered with. The new methods still allow to import private RSA keys with these optimization key parameters missing but it is disabled by default and one should choose to enable it when working with keys from trusted sources It is recommended not to use `jose` versions with this feature in its original on-by-default form - v1.1.0 and v1.2.0 ## [1.0.2](https://github.com/panva/jose/compare/v1.0.1...v1.0.2) (2019-05-13) ### Fixes * add missing keystore.toJWKS() .d.ts definition ([c7a8606](https://github.com/panva/jose/commit/c7a8606)), closes [#25](https://github.com/panva/jose/issues/25) ## [1.0.1](https://github.com/panva/jose/compare/v1.0.0...v1.0.1) (2019-04-27) ### Fixes * oct key ts "k" type fix ([0750d2c](https://github.com/panva/jose/commit/0750d2c)) ## [1.0.0](https://github.com/panva/jose/compare/v0.12.0...v1.0.0) (2019-04-23) ### Fixes * fail to import invalid PEM formatted strings and buffers ([857dc2b](https://github.com/panva/jose/commit/857dc2b)) ### Features * add JWK key_ops support, fix .algorithms() op returns ([23b874c](https://github.com/panva/jose/commit/23b874c)) * add key.toPEM() export function with optional encryption ([1159b0d](https://github.com/panva/jose/commit/1159b0d)) * add OKP Key and EdDSA sign/verify support ([2dbd3ed](https://github.com/panva/jose/commit/2dbd3ed)), closes [#12](https://github.com/panva/jose/issues/12) ### BREAKING CHANGES * key.algorithms(op) un+wrapKey was split into correct wrapKey/unwrapKey/deriveKey returns * keystore.all and keystore.get `operation` option was removed, `key_ops: string[]` supersedes it * Node.js minimal version is now v12.0.0 due to its added EdDSA support (crypto.sign, crypto.verify and eddsa key objects) ## [0.12.0](https://github.com/panva/jose/compare/v0.11.5...v0.12.0) (2019-04-07) ### Reverts * add EC P-256K JWK and ES256K sign/verify support ([e21fea1](https://github.com/panva/jose/commit/e21fea1)) ### BREAKING CHANGES * removing ES256K alg and EC P-256K crv support until the IETF WG decides on what the final names will be. ## [0.11.5](https://github.com/panva/jose/compare/v0.11.4...v0.11.5) (2019-04-04) ### Features * add key.secret and key.type for completeness ([2dd7053](https://github.com/panva/jose/commit/2dd7053)) * add key.thumbprint always returning the JWK Thumbprint (RFC7638) ([65db7e0](https://github.com/panva/jose/commit/65db7e0)) ## [0.11.4](https://github.com/panva/jose/compare/v0.11.3...v0.11.4) (2019-03-28) ### Fixes * properly restrict EC curves in generate(Sync) ([764b863](https://github.com/panva/jose/commit/764b863)) * remove unintended exposure of private material via enumerables ([946d9df](https://github.com/panva/jose/commit/946d9df)) ## [0.11.3](https://github.com/panva/jose/compare/v0.11.2...v0.11.3) (2019-03-27) ### Fixes * throw on unsupported EC curves ([cfa4222](https://github.com/panva/jose/commit/cfa4222)) ### Features * add EC P-256K JWK and ES256K sign/verify support ([2e33e1c](https://github.com/panva/jose/commit/2e33e1c)) ## [0.11.2](https://github.com/panva/jose/compare/v0.11.1...v0.11.2) (2019-03-19) ### Fixes * internal symbol method is now really a symbol ([925d47c](https://github.com/panva/jose/commit/925d47c)) * key.toJWK() fixed on windows ([57f1692](https://github.com/panva/jose/commit/57f1692)), closes [#17](https://github.com/panva/jose/issues/17) ## [0.11.1](https://github.com/panva/jose/compare/v0.11.0...v0.11.1) (2019-03-17) ### Fixes * restrict RS key algorithms by the key's bit size ([9af295b](https://github.com/panva/jose/commit/9af295b)) ## [0.11.0](https://github.com/panva/jose/compare/v0.10.0...v0.11.0) (2019-03-16) ### Fixes * all JWA defined RSA operations require key of 2048 or more ([cc70c5d](https://github.com/panva/jose/commit/cc70c5d)) * use correct salt length for RSASSA-PSS ([e936d54](https://github.com/panva/jose/commit/e936d54)) ### BREAKING CHANGES * all [JWA](https://www.rfc-editor.org/rfc/rfc7518) defined RSA based operations require key size of 2048 bits or more. ## [0.10.0](https://github.com/panva/jose/compare/v0.9.2...v0.10.0) (2019-03-12) ### Fixes * do not list "dir" under wrap/unwrapKey operations ([17b37d3](https://github.com/panva/jose/commit/17b37d3)) ### Features * keystore .all and .get operation option ([d349ba9](https://github.com/panva/jose/commit/d349ba9)) ### BREAKING CHANGES * "dir" is no longer returned as wrap/unwrapKey key operation ## [0.9.2](https://github.com/panva/jose/compare/v0.9.1...v0.9.2) (2019-03-05) ### Fixes * "dir" is only available on keys with correct lengths ([6854860](https://github.com/panva/jose/commit/6854860)) * do not 'in' operator when importing keys as string ([be3f4e4](https://github.com/panva/jose/commit/be3f4e4)) ## [0.9.1](https://github.com/panva/jose/compare/v0.9.0...v0.9.1) (2019-03-02) ### Fixes * only import RSA, EC and oct successfully ([e5e02fc](https://github.com/panva/jose/commit/e5e02fc)) # 0.9.0 (2019-03-02) Initial release ### Implemented Features - JSON Web Signature (JWS) - [RFC7515][spec-jws] - JSON Web Encryption (JWE) - [RFC7516][spec-jwe] - JSON Web Key (JWK) - [RFC7517][spec-jwk] - JSON Web Algorithms (JWA) - [RFC7518][spec-jwa] - JSON Web Token (JWT) - [RFC7519][spec-jwt] - JSON Web Key (JWK) Thumbprint - [RFC7638][spec-thumbprint] - JWS Unencoded Payload Option - [RFC7797][spec-b64] | JWK Key Types | Supported || | -- | -- | -- | | RSA | ✓ | RSA | | Elliptic Curve | ✓ | EC | | Octet sequence | ✓ | oct | | Serialization | JWS Sign | JWS Verify | JWE Encrypt | JWE Decrypt | | -- | -- | -- | -- | -- | | Compact | ✓ | ✓ | ✓ | ✓ | | General JSON | ✓ | ✓ | ✓ | ✓ | | Flattened JSON | ✓ | ✓ | ✓ | ✓ | | JWS Algorithms | Supported || | -- | -- | -- | | RSASSA-PKCS1-v1_5 | ✓ | RS256, RS384, RS512 | | RSASSA-PSS | ✓ | PS256, PS384, PS512 | | ECDSA | ✓ | ES256, ES384, ES512 | | HMAC with SHA-2 | ✓ | HS256, HS384, HS512 | | JWE Key Management Algorithms | Supported || | -- | -- | -- | | AES | ✓ | A128KW, A192KW, A256KW | | AES GCM | ✓ | A128GCMKW, A192GCMKW, A256GCMKW | | Direct Key Agreement | ✓ | dir | | RSAES OAEP | ✓* | RSA-OAEP (*RSA-OAEP-256 is not supported due to its lack of support in Node.js) | | RSAES-PKCS1-v1_5 | ✓ | RSA1_5 | | PBES2 | ✓ | PBES2-HS256+A128KW, PBES2-HS384+A192KW, PBES2-HS512+A256KW | | ECDH-ES | ✓ | ECDH-ES, ECDH-ES+A128KW, ECDH-ES+A192KW, ECDH-ES+A256KW | | JWE Content Encryption Algorithms | Supported || | -- | -- | -- | | AES GCM | ✓ | A128GCM, A192GCM, A256GCM | | AES_CBC_HMAC_SHA2 | ✓ | A128CBC-HS256, A192CBC-HS384, A256CBC-HS512 | [spec-b64]: https://www.rfc-editor.org/rfc/rfc7797 [spec-jwa]: https://www.rfc-editor.org/rfc/rfc7518 [spec-jwe]: https://www.rfc-editor.org/rfc/rfc7516 [spec-jwk]: https://www.rfc-editor.org/rfc/rfc7517 [spec-jws]: https://www.rfc-editor.org/rfc/rfc7515 [spec-jwt]: https://www.rfc-editor.org/rfc/rfc7519 [spec-thumbprint]: https://www.rfc-editor.org/rfc/rfc7638 jose-4.11.4/CODE_OF_CONDUCT.md000066400000000000000000000125561437043056600153610ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at panva.ip@gmail.com. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations jose-4.11.4/CONTRIBUTING.md000066400000000000000000000016621437043056600150070ustar00rootroot00000000000000# Contributing to jose Please note we have a [code of conduct][coc], please follow it in all your interactions with the project. When contributing to this project, please first discuss the change you wish to make via a discussion, email, or any other appropriate method with the owners of this project before proposing a change via a Pull Request. The project promotes and follows current best practices in regards to the specifications it implements. A contribution that tries to implement something non-standard will most likely be dismissed. ## Rules of the discussions Remember to be very clear and transparent when discussing any issue in the discussions boards. We ask that you keep the language to English and keep on track with the issue at hand. Lastly, please be respectful of our fellow contributors and keep an exemplary level of professionalism at all times. [coc]: https://github.com/panva/jose/blob/main/CODE_OF_CONDUCT.md jose-4.11.4/LICENSE.md000066400000000000000000000020671437043056600141620ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2018 Filip Skokan 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. jose-4.11.4/README.md000066400000000000000000000145431437043056600140370ustar00rootroot00000000000000# jose > "JSON Web Almost Everything" - JWA, JWS, JWE, JWT, JWK, JWKS for Node.js, Browser, Cloudflare Workers, Deno, Bun, and other Web-interoperable runtimes. ## Implemented specs & features The following specifications are implemented by `jose` - JSON Web Signature (JWS) - [RFC7515][spec-jws] - JSON Web Encryption (JWE) - [RFC7516][spec-jwe] - JSON Web Key (JWK) - [RFC7517][spec-jwk] - JSON Web Algorithms (JWA) - [RFC7518][spec-jwa] - JSON Web Token (JWT) - [RFC7519][spec-jwt] - JSON Web Key Thumbprint - [RFC7638][spec-thumbprint] - JSON Web Key Thumbprint URI - [RFC9278][spec-thumbprint-uri] - JWS Unencoded Payload Option - [RFC7797][spec-b64] - CFRG Elliptic Curve ECDH and Signatures - [RFC8037][spec-okp] - secp256k1 EC Key curve support - [JOSE Registrations for WebAuthn Algorithms][spec-secp256k1] The test suite utilizes examples defined in [RFC7520][spec-cookbook] to confirm its JOSE implementation is correct. ## [💗 Help the project](https://github.com/sponsors/panva) ## Dependencies: 0 ## Documentation **`example`** ESM import ```js import * as jose from 'jose' ``` **`example`** CJS require ```js const jose = require('jose') ``` **`example`** Deno import ```js import * as jose from 'https://deno.land/x/jose@v4.11.4/index.ts' ``` - JSON Web Tokens (JWT) - [Signing](docs/classes/jwt_sign.SignJWT.md#readme) - [Verification & JWT Claims Set Validation](docs/functions/jwt_verify.jwtVerify.md#readme) - Encrypted JSON Web Tokens - [Encryption](docs/classes/jwt_encrypt.EncryptJWT.md#readme) - [Decryption & JWT Claims Set Validation](docs/functions/jwt_decrypt.jwtDecrypt.md#readme) - Key Import - [JWK Import](docs/functions/key_import.importJWK.md#readme) - [Public Key Import (SPKI)](docs/functions/key_import.importSPKI.md#readme) - [Public Key Import (X.509 Certificate)](docs/functions/key_import.importX509.md#readme) - [Private Key Import (PKCS #8)](docs/functions/key_import.importPKCS8.md#readme) - JSON Web Encryption (JWE) - Encryption - [Compact](docs/classes/jwe_compact_encrypt.CompactEncrypt.md#readme), [Flattened](docs/classes/jwe_flattened_encrypt.FlattenedEncrypt.md#readme), [General](docs/classes/jwe_general_encrypt.GeneralEncrypt.md#readme) - Decryption - [Compact](docs/functions/jwe_compact_decrypt.compactDecrypt.md#readme), [Flattened](docs/functions/jwe_flattened_decrypt.flattenedDecrypt.md#readme), [General](docs/functions/jwe_general_decrypt.generalDecrypt.md#readme) - JSON Web Signature (JWS) - Signing - [Compact](docs/classes/jws_compact_sign.CompactSign.md#readme), [Flattened](docs/classes/jws_flattened_sign.FlattenedSign.md#readme), [General](docs/classes/jws_general_sign.GeneralSign.md#readme) - Verification - [Compact](docs/functions/jws_compact_verify.compactVerify.md#readme), [Flattened](docs/functions/jws_flattened_verify.flattenedVerify.md#readme), [General](docs/functions/jws_general_verify.generalVerify.md#readme) - JSON Web Key (JWK) - [Calculating JWK Thumbprint](docs/functions/jwk_thumbprint.calculateJwkThumbprint.md#readme) - [Calculating JWK Thumbprint URI](docs/functions/jwk_thumbprint.calculateJwkThumbprintUri.md#readme) - [Verification using a JWK Embedded in a JWS Header](docs/functions/jwk_embedded.EmbeddedJWK.md#readme) - JSON Web Key Set (JWKS) - [Verify using a local JWKSet](docs/functions/jwks_local.createLocalJWKSet.md#readme) - [Verify using a remote JWKSet](docs/functions/jwks_remote.createRemoteJWKSet.md#readme) - Key Pair or Secret Generation - [Asymmetric Key Pair Generation](docs/functions/key_generate_key_pair.generateKeyPair.md#readme) - [Symmetric Secret Generation](docs/functions/key_generate_secret.generateSecret.md#readme) - Key Export - [JWK Export](docs/functions/key_export.exportJWK.md#readme) - [Private Key Export](docs/functions/key_export.exportPKCS8.md#readme) - [Public Key Export](docs/functions/key_export.exportSPKI.md#readme) - Utilities - [Decoding Token's Protected Header](docs/functions/util_decode_protected_header.decodeProtectedHeader.md#readme) - [Decoding JWT Claims Set](docs/functions/util_decode_jwt.decodeJwt.md#readme) - [Unsecured JWT](docs/classes/jwt_unsecured.UnsecuredJWT.md#readme) - [JOSE Errors](docs/modules/util_errors.md#readme) ## Supported Runtimes The supported JavaScript runtimes include ones that support the utilized Web API globals and standard built-in objects or are Node.js These are _(this is not an exhaustive list)_: - [Bun](https://github.com/panva/jose/issues/471) - [Browsers](https://github.com/panva/jose/issues/263) - [Cloudflare Workers](https://github.com/panva/jose/issues/265) - [Deno](https://github.com/panva/jose/issues/266) - [Electron](https://github.com/panva/jose/issues/264) - [Node.js](https://github.com/panva/jose/issues/262) - [Vercel's Edge Runtime](https://github.com/panva/jose/issues/301) ## FAQ #### Supported Versions | Version | Security Fixes 🔑 | Other Bug Fixes 🐞 | New Features ⭐ | | ------- | --------- | -------- | -------- | | [v4.x](https://github.com/panva/jose/tree/v4.x) | ✅ | ✅ | ✅ | | [v3.x](https://github.com/panva/jose/tree/v3.x), [v2.x](https://github.com/panva/jose/tree/v2.x), [v1.x](https://github.com/panva/jose/tree/v1.x) | ✅ | ❌ | ❌ | #### Uint8Array?! - Whenever `Uint8Array` is a valid input, so is [`Buffer`](https://nodejs.org/api/buffer.html#buffer_buffer) since buffers are instances of Uint8Array. - Whenever `Uint8Array` is returned and you want a `Buffer` instead, use `Buffer.from(uint8array)`. #### Bundle Size, Package Size, Tree Shaking Yes the bundle size is on the larger side, that is because each module is actually published multiple times so that it can remain truly without dependencies and be universal / isomorphic. Nevertheless, since each module can be required independently and is fully tree-shakeable, the install size should not be a cause for concern. [spec-b64]: https://www.rfc-editor.org/rfc/rfc7797 [spec-cookbook]: https://www.rfc-editor.org/rfc/rfc7520 [spec-jwa]: https://www.rfc-editor.org/rfc/rfc7518 [spec-jwe]: https://www.rfc-editor.org/rfc/rfc7516 [spec-jwk]: https://www.rfc-editor.org/rfc/rfc7517 [spec-jws]: https://www.rfc-editor.org/rfc/rfc7515 [spec-jwt]: https://www.rfc-editor.org/rfc/rfc7519 [spec-okp]: https://www.rfc-editor.org/rfc/rfc8037 [spec-secp256k1]: https://www.rfc-editor.org/rfc/rfc8812 [spec-thumbprint]: https://www.rfc-editor.org/rfc/rfc7638 [spec-thumbprint-uri]: https://www.rfc-editor.org/rfc/rfc9278 jose-4.11.4/ava.config.cjs000066400000000000000000000005031437043056600152630ustar00rootroot00000000000000const files = [ "./test/**/*.test.mjs" ] const environmentVariables = {} if ('CITGM' in process.env) { files.push("!**/remote.test.mjs") } if ('electron' in process.versions) { files.push("!**/rsa-pss.test.mjs") } module.exports = { require: [ "./test/.require.mjs" ], files, environmentVariables, }; jose-4.11.4/cookbook/000077500000000000000000000000001437043056600143575ustar00rootroot00000000000000jose-4.11.4/cookbook/jwe.mjs000066400000000000000000001336601437043056600156700ustar00rootroot00000000000000export default [ { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-5.1 - Key Encryption using RSA v1.5 and AES-HMAC-SHA2', webcrypto: false, reproducible: false, input: { plaintext: 'You can trust us to stick with you through thick and thin–to the bitter end. And you can trust us to keep any secret of yours–closer than you keep it yourself. But you cannot trust us to let you face trouble alone, and go off without a word. We are your friends, Frodo.', key: { kty: 'RSA', ext: false, kid: 'frodo.baggins@hobbiton.example', use: 'enc', n: 'maxhbsmBtdQ3CNrKvprUE6n9lYcregDMLYNeTAWcLj8NnPU9XIYegTHVHQjxKDSHP2l-F5jS7sppG1wgdAqZyhnWvXhYNvcM7RfgKxqNx_xAHx6f3yy7s-M9PSNCwPC2lh6UAkR4I00EhV9lrypM9Pi4lBUop9t5fS9W5UNwaAllhrd-osQGPjIeI1deHTwx-ZTHu3C60Pu_LJIl6hKn9wbwaUmA4cR5Bd2pgbaY7ASgsjCUbtYJaNIHSoHXprUdJZKUMAzV0WOKPfA6OPI4oypBadjvMZ4ZAj3BnXaSYsEZhaueTXvZB4eZOAjIyh2e_VOIKVMsnDrJYAVotGlvMQ', e: 'AQAB', d: 'Kn9tgoHfiTVi8uPu5b9TnwyHwG5dK6RE0uFdlpCGnJN7ZEi963R7wybQ1PLAHmpIbNTztfrheoAniRV1NCIqXaW_qS461xiDTp4ntEPnqcKsyO5jMAji7-CL8vhpYYowNFvIesgMoVaPRYMYT9TW63hNM0aWs7USZ_hLg6Oe1mY0vHTI3FucjSM86Nff4oIENt43r2fspgEPGRrdE6fpLc9Oaq-qeP1GFULimrRdndm-P8q8kvN3KHlNAtEgrQAgTTgz80S-3VD0FgWfgnb1PNmiuPUxO8OpI9KDIfu_acc6fg14nsNaJqXe6RESvhGPH2afjHqSy_Fd2vpzj85bQQ', p: '2DwQmZ43FoTnQ8IkUj3BmKRf5Eh2mizZA5xEJ2MinUE3sdTYKSLtaEoekX9vbBZuWxHdVhM6UnKCJ_2iNk8Z0ayLYHL0_G21aXf9-unynEpUsH7HHTklLpYAzOOx1ZgVljoxAdWNn3hiEFrjZLZGS7lOH-a3QQlDDQoJOJ2VFmU', q: 'te8LY4-W7IyaqH1ExujjMqkTAlTeRbv0VLQnfLY2xINnrWdwiQ93_VF099aP1ESeLja2nw-6iKIe-qT7mtCPozKfVtUYfz5HrJ_XY2kfexJINb9lhZHMv5p1skZpeIS-GPHCC6gRlKo1q-idn_qxyusfWv7WAxlSVfQfk8d6Et0', dp: 'UfYKcL_or492vVc0PzwLSplbg4L3-Z5wL48mwiswbpzOyIgd2xHTHQmjJpFAIZ8q-zf9RmgJXkDrFs9rkdxPtAsL1WYdeCT5c125Fkdg317JVRDo1inX7x2Kdh8ERCreW8_4zXItuTl_KiXZNU5lvMQjWbIw2eTx1lpsflo0rYU', dq: 'iEgcO-QfpepdH8FWd7mUFyrXdnOkXJBCogChY6YKuIHGc_p8Le9MbpFKESzEaLlN1Ehf3B6oGBl5Iz_ayUlZj2IoQZ82znoUrpa9fVYNot87ACfzIG7q9Mv7RiPAderZi03tkVXAdaBau_9vs5rS-7HMtxkVrxSUvJY14TkXlHE', qi: 'kC-lzZOqoFaZCr5l0tOVtREKoVqaAYhQiqIRGL-MzS4sCmRkxm5vZlXYx6RtE1n_AagjqajlkjieGlxTTThHD8Iga6foGBMaAr5uR1hGQpSc7Gl7CF1DZkBJMTQN6EshYzZfxW08mIO8M6Rzuh0beL6fG9mkDcIyPrBXx2bQ_mM', }, alg: 'RSA1_5', enc: 'A128CBC-HS256', }, generated: { cek: '3qyTVhIWt5juqZUCpfRqpvauwB956MEJL2Rt-8qXKSo', iv: 'bbd5sTkYwhAIqfHsx8DayA', }, encrypting_key: {}, encrypting_content: { protected: { alg: 'RSA1_5', kid: 'frodo.baggins@hobbiton.example', enc: 'A128CBC-HS256', }, }, output: { compact: 'eyJhbGciOiJSU0ExXzUiLCJraWQiOiJmcm9kby5iYWdnaW5zQGhvYmJpdG9uLmV4YW1wbGUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.laLxI0j-nLH-_BgLOXMozKxmy9gffy2gTdvqzfTihJBuuzxg0V7yk1WClnQePFvG2K-pvSlWc9BRIazDrn50RcRai__3TDON395H3c62tIouJJ4XaRvYHFjZTZ2GXfz8YAImcc91Tfk0WXC2F5Xbb71ClQ1DDH151tlpH77f2ff7xiSxh9oSewYrcGTSLUeeCt36r1Kt3OSj7EyBQXoZlN7IxbyhMAfgIe7Mv1rOTOI5I8NQqeXXW8VlzNmoxaGMny3YnGir5Wf6Qt2nBq4qDaPdnaAuuGUGEecelIO1wx1BpyIfgvfjOhMBs9M8XL223Fg47xlGsMXdfuY-4jaqVw.bbd5sTkYwhAIqfHsx8DayA.0fys_TY_na7f8dwSfXLiYdHaA2DxUjD67ieF7fcVbIR62JhJvGZ4_FNVSiGc_raa0HnLQ6s1P2sv3Xzl1p1l_o5wR_RsSzrS8Z-wnI3Jvo0mkpEEnlDmZvDu_k8OWzJv7eZVEqiWKdyVzFhPpiyQU28GLOpRc2VbVbK4dQKPdNTjPPEmRqcaGeTWZVyeSUvf5k59yJZxRuSvWFf6KrNtmRdZ8R4mDOjHSrM_s8uwIFcqt4r5GX8TKaI0zT5CbL5Qlw3sRc7u_hg0yKVOiRytEAEs3vZkcfLkP6nbXdC_PkMdNS-ohP78T2O6_7uInMGhFeX4ctHG7VelHGiT93JfWDEQi5_V9UN1rhXNrYu-0fVMkZAKX3VWi7lzA6BP430m.kvKuFBXHe5mQr4lqgobAUg', json: { recipients: [ { encrypted_key: 'laLxI0j-nLH-_BgLOXMozKxmy9gffy2gTdvqzfTihJBuuzxg0V7yk1WClnQePFvG2K-pvSlWc9BRIazDrn50RcRai__3TDON395H3c62tIouJJ4XaRvYHFjZTZ2GXfz8YAImcc91Tfk0WXC2F5Xbb71ClQ1DDH151tlpH77f2ff7xiSxh9oSewYrcGTSLUeeCt36r1Kt3OSj7EyBQXoZlN7IxbyhMAfgIe7Mv1rOTOI5I8NQqeXXW8VlzNmoxaGMny3YnGir5Wf6Qt2nBq4qDaPdnaAuuGUGEecelIO1wx1BpyIfgvfjOhMBs9M8XL223Fg47xlGsMXdfuY-4jaqVw', }, ], protected: 'eyJhbGciOiJSU0ExXzUiLCJraWQiOiJmcm9kby5iYWdnaW5zQGhvYmJpdG9uLmV4YW1wbGUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0', iv: 'bbd5sTkYwhAIqfHsx8DayA', ciphertext: '0fys_TY_na7f8dwSfXLiYdHaA2DxUjD67ieF7fcVbIR62JhJvGZ4_FNVSiGc_raa0HnLQ6s1P2sv3Xzl1p1l_o5wR_RsSzrS8Z-wnI3Jvo0mkpEEnlDmZvDu_k8OWzJv7eZVEqiWKdyVzFhPpiyQU28GLOpRc2VbVbK4dQKPdNTjPPEmRqcaGeTWZVyeSUvf5k59yJZxRuSvWFf6KrNtmRdZ8R4mDOjHSrM_s8uwIFcqt4r5GX8TKaI0zT5CbL5Qlw3sRc7u_hg0yKVOiRytEAEs3vZkcfLkP6nbXdC_PkMdNS-ohP78T2O6_7uInMGhFeX4ctHG7VelHGiT93JfWDEQi5_V9UN1rhXNrYu-0fVMkZAKX3VWi7lzA6BP430m', tag: 'kvKuFBXHe5mQr4lqgobAUg', }, json_flat: { protected: 'eyJhbGciOiJSU0ExXzUiLCJraWQiOiJmcm9kby5iYWdnaW5zQGhvYmJpdG9uLmV4YW1wbGUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0', encrypted_key: 'laLxI0j-nLH-_BgLOXMozKxmy9gffy2gTdvqzfTihJBuuzxg0V7yk1WClnQePFvG2K-pvSlWc9BRIazDrn50RcRai__3TDON395H3c62tIouJJ4XaRvYHFjZTZ2GXfz8YAImcc91Tfk0WXC2F5Xbb71ClQ1DDH151tlpH77f2ff7xiSxh9oSewYrcGTSLUeeCt36r1Kt3OSj7EyBQXoZlN7IxbyhMAfgIe7Mv1rOTOI5I8NQqeXXW8VlzNmoxaGMny3YnGir5Wf6Qt2nBq4qDaPdnaAuuGUGEecelIO1wx1BpyIfgvfjOhMBs9M8XL223Fg47xlGsMXdfuY-4jaqVw', iv: 'bbd5sTkYwhAIqfHsx8DayA', ciphertext: '0fys_TY_na7f8dwSfXLiYdHaA2DxUjD67ieF7fcVbIR62JhJvGZ4_FNVSiGc_raa0HnLQ6s1P2sv3Xzl1p1l_o5wR_RsSzrS8Z-wnI3Jvo0mkpEEnlDmZvDu_k8OWzJv7eZVEqiWKdyVzFhPpiyQU28GLOpRc2VbVbK4dQKPdNTjPPEmRqcaGeTWZVyeSUvf5k59yJZxRuSvWFf6KrNtmRdZ8R4mDOjHSrM_s8uwIFcqt4r5GX8TKaI0zT5CbL5Qlw3sRc7u_hg0yKVOiRytEAEs3vZkcfLkP6nbXdC_PkMdNS-ohP78T2O6_7uInMGhFeX4ctHG7VelHGiT93JfWDEQi5_V9UN1rhXNrYu-0fVMkZAKX3VWi7lzA6BP430m', tag: 'kvKuFBXHe5mQr4lqgobAUg', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-5.2 - Key Encryption using RSA-OAEP with AES-GCM', input: { plaintext: 'You can trust us to stick with you through thick and thin–to the bitter end. And you can trust us to keep any secret of yours–closer than you keep it yourself. But you cannot trust us to let you face trouble alone, and go off without a word. We are your friends, Frodo.', key: { kty: 'RSA', ext: false, kid: 'samwise.gamgee@hobbiton.example', use: 'enc', n: 'wbdxI55VaanZXPY29Lg5hdmv2XhvqAhoxUkanfzf2-5zVUxa6prHRrI4pP1AhoqJRlZfYtWWd5mmHRG2pAHIlh0ySJ9wi0BioZBl1XP2e-C-FyXJGcTy0HdKQWlrfhTm42EW7Vv04r4gfao6uxjLGwfpGrZLarohiWCPnkNrg71S2CuNZSQBIPGjXfkmIy2tl_VWgGnL22GplyXj5YlBLdxXp3XeStsqo571utNfoUTU8E4qdzJ3U1DItoVkPGsMwlmmnJiwA7sXRItBCivR4M5qnZtdw-7v4WuR4779ubDuJ5nalMv2S66-RPcnFAzWSKxtBDnFJJDGIUe7Tzizjg1nms0Xq_yPub_UOlWn0ec85FCft1hACpWG8schrOBeNqHBODFskYpUc2LC5JA2TaPF2dA67dg1TTsC_FupfQ2kNGcE1LgprxKHcVWYQb86B-HozjHZcqtauBzFNV5tbTuB-TpkcvJfNcFLlH3b8mb-H_ox35FjqBSAjLKyoeqfKTpVjvXhd09knwgJf6VKq6UC418_TOljMVfFTWXUxlnfhOOnzW6HSSzD1c9WrCuVzsUMv54szidQ9wf1cYWf3g5qFDxDQKis99gcDaiCAwM3yEBIzuNeeCa5dartHDb1xEB_HcHSeYbghbMjGfasvKn0aZRsnTyC0xhWBlsolZE', e: 'AQAB', alg: 'RSA-OAEP', d: 'n7fzJc3_WG59VEOBTkayzuSMM780OJQuZjN_KbH8lOZG25ZoA7T4Bxcc0xQn5oZE5uSCIwg91oCt0JvxPcpmqzaJZg1nirjcWZ-oBtVk7gCAWq-B3qhfF3izlbkosrzjHajIcY33HBhsy4_WerrXg4MDNE4HYojy68TcxT2LYQRxUOCf5TtJXvM8olexlSGtVnQnDRutxEUCwiewfmmrfveEogLx9EA-KMgAjTiISXxqIXQhWUQX1G7v_mV_Hr2YuImYcNcHkRvp9E7ook0876DhkO8v4UOZLwA1OlUX98mkoqwc58A_Y2lBYbVx1_s5lpPsEqbbH-nqIjh1fL0gdNfihLxnclWtW7pCztLnImZAyeCWAG7ZIfv-Rn9fLIv9jZ6r7r-MSH9sqbuziHN2grGjD_jfRluMHa0l84fFKl6bcqN1JWxPVhzNZo01yDF-1LiQnqUYSepPf6X3a2SOdkqBRiquE6EvLuSYIDpJq3jDIsgoL8Mo1LoomgiJxUwL_GWEOGu28gplyzm-9Q0U0nyhEf1uhSR8aJAQWAiFImWH5W_IQT9I7-yrindr_2fWQ_i1UgMsGzA7aOGzZfPljRy6z-tY_KuBG00-28S_aWvjyUc-Alp8AUyKjBZ-7CWH32fGWK48j1t-zomrwjL_mnhsPbGs0c9WsWgRzI-K8gE', p: '7_2v3OQZzlPFcHyYfLABQ3XP85Es4hCdwCkbDeltaUXgVy9l9etKghvM4hRkOvbb01kYVuLFmxIkCDtpi-zLCYAdXKrAK3PtSbtzld_XZ9nlsYa_QZWpXB_IrtFjVfdKUdMz94pHUhFGFj7nr6NNxfpiHSHWFE1zD_AC3mY46J961Y2LRnreVwAGNw53p07Db8yD_92pDa97vqcZOdgtybH9q6uma-RFNhO1AoiJhYZj69hjmMRXx-x56HO9cnXNbmzNSCFCKnQmn4GQLmRj9sfbZRqL94bbtE4_e0Zrpo8RNo8vxRLqQNwIy85fc6BRgBJomt8QdQvIgPgWCv5HoQ', q: 'zqOHk1P6WN_rHuM7ZF1cXH0x6RuOHq67WuHiSknqQeefGBA9PWs6ZyKQCO-O6mKXtcgE8_Q_hA2kMRcKOcvHil1hqMCNSXlflM7WPRPZu2qCDcqssd_uMbP-DqYthH_EzwL9KnYoH7JQFxxmcv5An8oXUtTwk4knKjkIYGRuUwfQTus0w1NfjFAyxOOiAQ37ussIcE6C6ZSsM3n41UlbJ7TCqewzVJaPJN5cxjySPZPD3Vp01a9YgAD6a3IIaKJdIxJS1ImnfPevSJQBE79-EXe2kSwVgOzvt-gsmM29QQ8veHy4uAqca5dZzMs7hkkHtw1z0jHV90epQJJlXXnH8Q', dp: '19oDkBh1AXelMIxQFm2zZTqUhAzCIr4xNIGEPNoDt1jK83_FJA-xnx5kA7-1erdHdms_Ef67HsONNv5A60JaR7w8LHnDiBGnjdaUmmuO8XAxQJ_ia5mxjxNjS6E2yD44USo2JmHvzeeNczq25elqbTPLhUpGo1IZuG72FZQ5gTjXoTXC2-xtCDEUZfaUNh4IeAipfLugbpe0JAFlFfrTDAMUFpC3iXjxqzbEanflwPvj6V9iDSgjj8SozSM0dLtxvu0LIeIQAeEgT_yXcrKGmpKdSO08kLBx8VUjkbv_3Pn20Gyu2YEuwpFlM_H1NikuxJNKFGmnAq9LcnwwT0jvoQ', dq: 'S6p59KrlmzGzaQYQM3o0XfHCGvfqHLYjCO557HYQf72O9kLMCfd_1VBEqeD-1jjwELKDjck8kOBl5UvohK1oDfSP1DleAy-cnmL29DqWmhgwM1ip0CCNmkmsmDSlqkUXDi6sAaZuntyukyflI-qSQ3C_BafPyFaKrt1fgdyEwYa08pESKwwWisy7KnmoUvaJ3SaHmohFS78TJ25cfc10wZ9hQNOrIChZlkiOdFCtxDqdmCqNacnhgE3bZQjGp3n83ODSz9zwJcSUvODlXBPc2AycH6Ci5yjbxt4Ppox_5pjm6xnQkiPgj01GpsUssMmBN7iHVsrE7N2iznBNCeOUIQ', qi: 'FZhClBMywVVjnuUud-05qd5CYU0dK79akAgy9oX6RX6I3IIIPckCciRrokxglZn-omAY5CnCe4KdrnjFOT5YUZE7G_Pg44XgCXaarLQf4hl80oPEf6-jJ5Iy6wPRx7G2e8qLxnh9cOdf-kRqgOS3F48Ucvw3ma5V6KGMwQqWFeV31XtZ8l5cVI-I3NzBS7qltpUVgz2Ju021eyc7IlqgzR98qKONl27DuEES0aK0WE97jnsyO27Yp88Wa2RiBrEocM89QZI1seJiGDizHRUP4UZxw9zsXww46wy0P6f9grnYp7t8LkyDDk8eoI4KX6SNMNVcyVS9IWjlq8EzqZEKIA', }, alg: 'RSA-OAEP', enc: 'A256GCM', }, generated: { cek: 'mYMfsggkTAm0TbvtlFh2hyoXnbEzJQjMxmgLN3d8xXA', iv: '-nBoKLH0YkLZPSI9', }, encrypting_key: {}, encrypting_content: { protected: { alg: 'RSA-OAEP', kid: 'samwise.gamgee@hobbiton.example', enc: 'A256GCM', }, }, output: { compact: 'eyJhbGciOiJSU0EtT0FFUCIsImtpZCI6InNhbXdpc2UuZ2FtZ2VlQGhvYmJpdG9uLmV4YW1wbGUiLCJlbmMiOiJBMjU2R0NNIn0.rT99rwrBTbTI7IJM8fU3Eli7226HEB7IchCxNuh7lCiud48LxeolRdtFF4nzQibeYOl5S_PJsAXZwSXtDePz9hk-BbtsTBqC2UsPOdwjC9NhNupNNu9uHIVftDyucvI6hvALeZ6OGnhNV4v1zx2k7O1D89mAzfw-_kT3tkuorpDU-CpBENfIHX1Q58-Aad3FzMuo3Fn9buEP2yXakLXYa15BUXQsupM4A1GD4_H4Bd7V3u9h8Gkg8BpxKdUV9ScfJQTcYm6eJEBz3aSwIaK4T3-dwWpuBOhROQXBosJzS1asnuHtVMt2pKIIfux5BC6huIvmY7kzV7W7aIUrpYm_3H4zYvyMeq5pGqFmW2k8zpO878TRlZx7pZfPYDSXZyS0CfKKkMozT_qiCwZTSz4duYnt8hS4Z9sGthXn9uDqd6wycMagnQfOTs_lycTWmY-aqWVDKhjYNRf03NiwRtb5BE-tOdFwCASQj3uuAgPGrO2AWBe38UjQb0lvXn1SpyvYZ3WFc7WOJYaTa7A8DRn6MC6T-xDmMuxC0G7S2rscw5lQQU06MvZTlFOt0UvfuKBa03cxA_nIBIhLMjY2kOTxQMmpDPTr6Cbo8aKaOnx6ASE5Jx9paBpnNmOOKH35j_QlrQhDWUN6A2Gg8iFayJ69xDEdHAVCGRzN3woEI2ozDRs.-nBoKLH0YkLZPSI9.o4k2cnGN8rSSw3IDo1YuySkqeS_t2m1GXklSgqBdpACm6UJuJowOHC5ytjqYgRL-I-soPlwqMUf4UgRWWeaOGNw6vGW-xyM01lTYxrXfVzIIaRdhYtEMRBvBWbEwP7ua1DRfvaOjgZv6Ifa3brcAM64d8p5lhhNcizPersuhw5f-pGYzseva-TUaL8iWnctc-sSwy7SQmRkfhDjwbz0fz6kFovEgj64X1I5s7E6GLp5fnbYGLa1QUiML7Cc2GxgvI7zqWo0YIEc7aCflLG1-8BboVWFdZKLK9vNoycrYHumwzKluLWEbSVmaPpOslY2n525DxDfWaVFUfKQxMF56vn4B9QMpWAbnypNimbM8zVOw.UCGiqJxhBI3IFVdPalHHvA', json: { recipients: [ { encrypted_key: 'rT99rwrBTbTI7IJM8fU3Eli7226HEB7IchCxNuh7lCiud48LxeolRdtFF4nzQibeYOl5S_PJsAXZwSXtDePz9hk-BbtsTBqC2UsPOdwjC9NhNupNNu9uHIVftDyucvI6hvALeZ6OGnhNV4v1zx2k7O1D89mAzfw-_kT3tkuorpDU-CpBENfIHX1Q58-Aad3FzMuo3Fn9buEP2yXakLXYa15BUXQsupM4A1GD4_H4Bd7V3u9h8Gkg8BpxKdUV9ScfJQTcYm6eJEBz3aSwIaK4T3-dwWpuBOhROQXBosJzS1asnuHtVMt2pKIIfux5BC6huIvmY7kzV7W7aIUrpYm_3H4zYvyMeq5pGqFmW2k8zpO878TRlZx7pZfPYDSXZyS0CfKKkMozT_qiCwZTSz4duYnt8hS4Z9sGthXn9uDqd6wycMagnQfOTs_lycTWmY-aqWVDKhjYNRf03NiwRtb5BE-tOdFwCASQj3uuAgPGrO2AWBe38UjQb0lvXn1SpyvYZ3WFc7WOJYaTa7A8DRn6MC6T-xDmMuxC0G7S2rscw5lQQU06MvZTlFOt0UvfuKBa03cxA_nIBIhLMjY2kOTxQMmpDPTr6Cbo8aKaOnx6ASE5Jx9paBpnNmOOKH35j_QlrQhDWUN6A2Gg8iFayJ69xDEdHAVCGRzN3woEI2ozDRs', }, ], protected: 'eyJhbGciOiJSU0EtT0FFUCIsImtpZCI6InNhbXdpc2UuZ2FtZ2VlQGhvYmJpdG9uLmV4YW1wbGUiLCJlbmMiOiJBMjU2R0NNIn0', iv: '-nBoKLH0YkLZPSI9', ciphertext: 'o4k2cnGN8rSSw3IDo1YuySkqeS_t2m1GXklSgqBdpACm6UJuJowOHC5ytjqYgRL-I-soPlwqMUf4UgRWWeaOGNw6vGW-xyM01lTYxrXfVzIIaRdhYtEMRBvBWbEwP7ua1DRfvaOjgZv6Ifa3brcAM64d8p5lhhNcizPersuhw5f-pGYzseva-TUaL8iWnctc-sSwy7SQmRkfhDjwbz0fz6kFovEgj64X1I5s7E6GLp5fnbYGLa1QUiML7Cc2GxgvI7zqWo0YIEc7aCflLG1-8BboVWFdZKLK9vNoycrYHumwzKluLWEbSVmaPpOslY2n525DxDfWaVFUfKQxMF56vn4B9QMpWAbnypNimbM8zVOw', tag: 'UCGiqJxhBI3IFVdPalHHvA', }, json_flat: { protected: 'eyJhbGciOiJSU0EtT0FFUCIsImtpZCI6InNhbXdpc2UuZ2FtZ2VlQGhvYmJpdG9uLmV4YW1wbGUiLCJlbmMiOiJBMjU2R0NNIn0', encrypted_key: 'rT99rwrBTbTI7IJM8fU3Eli7226HEB7IchCxNuh7lCiud48LxeolRdtFF4nzQibeYOl5S_PJsAXZwSXtDePz9hk-BbtsTBqC2UsPOdwjC9NhNupNNu9uHIVftDyucvI6hvALeZ6OGnhNV4v1zx2k7O1D89mAzfw-_kT3tkuorpDU-CpBENfIHX1Q58-Aad3FzMuo3Fn9buEP2yXakLXYa15BUXQsupM4A1GD4_H4Bd7V3u9h8Gkg8BpxKdUV9ScfJQTcYm6eJEBz3aSwIaK4T3-dwWpuBOhROQXBosJzS1asnuHtVMt2pKIIfux5BC6huIvmY7kzV7W7aIUrpYm_3H4zYvyMeq5pGqFmW2k8zpO878TRlZx7pZfPYDSXZyS0CfKKkMozT_qiCwZTSz4duYnt8hS4Z9sGthXn9uDqd6wycMagnQfOTs_lycTWmY-aqWVDKhjYNRf03NiwRtb5BE-tOdFwCASQj3uuAgPGrO2AWBe38UjQb0lvXn1SpyvYZ3WFc7WOJYaTa7A8DRn6MC6T-xDmMuxC0G7S2rscw5lQQU06MvZTlFOt0UvfuKBa03cxA_nIBIhLMjY2kOTxQMmpDPTr6Cbo8aKaOnx6ASE5Jx9paBpnNmOOKH35j_QlrQhDWUN6A2Gg8iFayJ69xDEdHAVCGRzN3woEI2ozDRs', iv: '-nBoKLH0YkLZPSI9', ciphertext: 'o4k2cnGN8rSSw3IDo1YuySkqeS_t2m1GXklSgqBdpACm6UJuJowOHC5ytjqYgRL-I-soPlwqMUf4UgRWWeaOGNw6vGW-xyM01lTYxrXfVzIIaRdhYtEMRBvBWbEwP7ua1DRfvaOjgZv6Ifa3brcAM64d8p5lhhNcizPersuhw5f-pGYzseva-TUaL8iWnctc-sSwy7SQmRkfhDjwbz0fz6kFovEgj64X1I5s7E6GLp5fnbYGLa1QUiML7Cc2GxgvI7zqWo0YIEc7aCflLG1-8BboVWFdZKLK9vNoycrYHumwzKluLWEbSVmaPpOslY2n525DxDfWaVFUfKQxMF56vn4B9QMpWAbnypNimbM8zVOw', tag: 'UCGiqJxhBI3IFVdPalHHvA', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-5.3 - Key Wrap using PBES2-AES-KeyWrap with AES-CBC-HMAC-SHA2', electron: false, reproducible: true, input: { plaintext: '{"keys":[{"kty":"oct","kid":"77c7e2b8-6e13-45cf-8672-617b5b45243a","use":"enc","alg":"A128GCM","k":"XctOhJAkA-pD9Lh7ZgW_2A"},{"kty":"oct","kid":"81b20965-8332-43d9-a468-82160ad91ac8","use":"enc","alg":"A128KW","k":"GZy6sIZ6wl9NJOKB-jnmVQ"},{"kty":"oct","kid":"18ec08e1-bfa9-4d95-b205-2b4dd1d4321d","use":"enc","alg":"A256GCMKW","k":"qC57l_uxcm7Nm3K-ct4GFjx8tM1U8CZ0NLBvdQstiS8"}]}', pwd: 'entrap_o–peter_long–credit_tun', alg: 'PBES2-HS512+A256KW', enc: 'A128CBC-HS256', }, generated: { cek: 'uwsjJXaBK407Qaf0_zpcpmr1Cs0CC50hIUEyGNEt3m0', iv: 'VBiCzVHNoLiR3F4V82uoTQ', }, encrypting_key: { salt: '8Q1SzinasR3xchYz6ZZcHA', iteration_count: 8192, }, encrypting_content: { protected: { alg: 'PBES2-HS512+A256KW', p2s: '8Q1SzinasR3xchYz6ZZcHA', p2c: 8192, cty: 'jwk-set+json', enc: 'A128CBC-HS256', }, }, output: { compact: 'eyJhbGciOiJQQkVTMi1IUzUxMitBMjU2S1ciLCJwMnMiOiI4UTFTemluYXNSM3hjaFl6NlpaY0hBIiwicDJjIjo4MTkyLCJjdHkiOiJqd2stc2V0K2pzb24iLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.d3qNhUWfqheyPp4H8sjOWsDYajoej4c5Je6rlUtFPWdgtURtmeDV1g.VBiCzVHNoLiR3F4V82uoTQ.23i-Tb1AV4n0WKVSSgcQrdg6GRqsUKxjruHXYsTHAJLZ2nsnGIX86vMXqIi6IRsfywCRFzLxEcZBRnTvG3nhzPk0GDD7FMyXhUHpDjEYCNA_XOmzg8yZR9oyjo6lTF6si4q9FZ2EhzgFQCLO_6h5EVg3vR75_hkBsnuoqoM3dwejXBtIodN84PeqMb6asmas_dpSsz7H10fC5ni9xIz424givB1YLldF6exVmL93R3fOoOJbmk2GBQZL_SEGllv2cQsBgeprARsaQ7Bq99tT80coH8ItBjgV08AtzXFFsx9qKvC982KLKdPQMTlVJKkqtV4Ru5LEVpBZXBnZrtViSOgyg6AiuwaS-rCrcD_ePOGSuxvgtrokAKYPqmXUeRdjFJwafkYEkiuDCV9vWGAi1DH2xTafhJwcmywIyzi4BqRpmdn_N-zl5tuJYyuvKhjKv6ihbsV_k1hJGPGAxJ6wUpmwC4PTQ2izEm0TuSE8oMKdTw8V3kobXZ77ulMwDs4p.0HlwodAhOCILG5SQ2LQ9dg', json: { recipients: [ { encrypted_key: 'd3qNhUWfqheyPp4H8sjOWsDYajoej4c5Je6rlUtFPWdgtURtmeDV1g', }, ], protected: 'eyJhbGciOiJQQkVTMi1IUzUxMitBMjU2S1ciLCJwMnMiOiI4UTFTemluYXNSM3hjaFl6NlpaY0hBIiwicDJjIjo4MTkyLCJjdHkiOiJqd2stc2V0K2pzb24iLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0', iv: 'VBiCzVHNoLiR3F4V82uoTQ', ciphertext: '23i-Tb1AV4n0WKVSSgcQrdg6GRqsUKxjruHXYsTHAJLZ2nsnGIX86vMXqIi6IRsfywCRFzLxEcZBRnTvG3nhzPk0GDD7FMyXhUHpDjEYCNA_XOmzg8yZR9oyjo6lTF6si4q9FZ2EhzgFQCLO_6h5EVg3vR75_hkBsnuoqoM3dwejXBtIodN84PeqMb6asmas_dpSsz7H10fC5ni9xIz424givB1YLldF6exVmL93R3fOoOJbmk2GBQZL_SEGllv2cQsBgeprARsaQ7Bq99tT80coH8ItBjgV08AtzXFFsx9qKvC982KLKdPQMTlVJKkqtV4Ru5LEVpBZXBnZrtViSOgyg6AiuwaS-rCrcD_ePOGSuxvgtrokAKYPqmXUeRdjFJwafkYEkiuDCV9vWGAi1DH2xTafhJwcmywIyzi4BqRpmdn_N-zl5tuJYyuvKhjKv6ihbsV_k1hJGPGAxJ6wUpmwC4PTQ2izEm0TuSE8oMKdTw8V3kobXZ77ulMwDs4p', tag: '0HlwodAhOCILG5SQ2LQ9dg', }, json_flat: { protected: 'eyJhbGciOiJQQkVTMi1IUzUxMitBMjU2S1ciLCJwMnMiOiI4UTFTemluYXNSM3hjaFl6NlpaY0hBIiwicDJjIjo4MTkyLCJjdHkiOiJqd2stc2V0K2pzb24iLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0', encrypted_key: 'd3qNhUWfqheyPp4H8sjOWsDYajoej4c5Je6rlUtFPWdgtURtmeDV1g', iv: 'VBiCzVHNoLiR3F4V82uoTQ', ciphertext: '23i-Tb1AV4n0WKVSSgcQrdg6GRqsUKxjruHXYsTHAJLZ2nsnGIX86vMXqIi6IRsfywCRFzLxEcZBRnTvG3nhzPk0GDD7FMyXhUHpDjEYCNA_XOmzg8yZR9oyjo6lTF6si4q9FZ2EhzgFQCLO_6h5EVg3vR75_hkBsnuoqoM3dwejXBtIodN84PeqMb6asmas_dpSsz7H10fC5ni9xIz424givB1YLldF6exVmL93R3fOoOJbmk2GBQZL_SEGllv2cQsBgeprARsaQ7Bq99tT80coH8ItBjgV08AtzXFFsx9qKvC982KLKdPQMTlVJKkqtV4Ru5LEVpBZXBnZrtViSOgyg6AiuwaS-rCrcD_ePOGSuxvgtrokAKYPqmXUeRdjFJwafkYEkiuDCV9vWGAi1DH2xTafhJwcmywIyzi4BqRpmdn_N-zl5tuJYyuvKhjKv6ihbsV_k1hJGPGAxJ6wUpmwC4PTQ2izEm0TuSE8oMKdTw8V3kobXZ77ulMwDs4p', tag: '0HlwodAhOCILG5SQ2LQ9dg', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-5.4 - Key Agreement with Key Wrapping using ECDH-ES and AES-KeyWrap with AES-GCM', electron: false, input: { plaintext: 'You can trust us to stick with you through thick and thin–to the bitter end. And you can trust us to keep any secret of yours–closer than you keep it yourself. But you cannot trust us to let you face trouble alone, and go off without a word. We are your friends, Frodo.', key: { kty: 'EC', ext: false, kid: 'peregrin.took@tuckborough.example', use: 'enc', crv: 'P-384', x: 'YU4rRUzdmVqmRtWOs2OpDE_T5fsNIodcG8G5FWPrTPMyxpzsSOGaQLpe2FpxBmu2', y: 'A8-yxCHxkfBz3hKZfI1jUYMjUhsEveZ9THuwFjH2sCNdtksRJU7D5-SkgaFL1ETP', d: 'iTx2pk7wW-GqJkHcEkFQb2EFyYcO7RugmaW3mRrQVAOUiPommT0IdnYK2xDlZh-j', }, alg: 'ECDH-ES+A128KW', enc: 'A128GCM', }, generated: { cek: 'Nou2ueKlP70ZXDbq9UrRwg', iv: 'mH-G2zVqgztUtnW_', }, encrypting_key: { epk: { kty: 'EC', crv: 'P-384', x: 'uBo4kHPw6kbjx5l0xowrd_oYzBmaz-GKFZu4xAFFkbYiWgutEK6iuEDsQ6wNdNg3', y: 'sp3p5SGhZVC2faXumI-e9JU2Mo8KpoYrFDr5yPNVtW4PgEwZOyQTA-JdaY8tb7E0', d: 'D5H4Y_5PSKZvhfVFbcCYJOtcGZygRgfZkpsBr59Icmmhe9sW6nkZ8WfwhinUfWJg', }, }, encrypting_content: { protected: { alg: 'ECDH-ES+A128KW', kid: 'peregrin.took@tuckborough.example', epk: { kty: 'EC', crv: 'P-384', x: 'uBo4kHPw6kbjx5l0xowrd_oYzBmaz-GKFZu4xAFFkbYiWgutEK6iuEDsQ6wNdNg3', y: 'sp3p5SGhZVC2faXumI-e9JU2Mo8KpoYrFDr5yPNVtW4PgEwZOyQTA-JdaY8tb7E0', }, enc: 'A128GCM', }, }, output: { compact: 'eyJhbGciOiJFQ0RILUVTK0ExMjhLVyIsImtpZCI6InBlcmVncmluLnRvb2tAdHVja2Jvcm91Z2guZXhhbXBsZSIsImVwayI6eyJrdHkiOiJFQyIsImNydiI6IlAtMzg0IiwieCI6InVCbzRrSFB3Nmtiang1bDB4b3dyZF9vWXpCbWF6LUdLRlp1NHhBRkZrYllpV2d1dEVLNml1RURzUTZ3TmROZzMiLCJ5Ijoic3AzcDVTR2haVkMyZmFYdW1JLWU5SlUyTW84S3BvWXJGRHI1eVBOVnRXNFBnRXdaT3lRVEEtSmRhWTh0YjdFMCJ9LCJlbmMiOiJBMTI4R0NNIn0.0DJjBXri_kBcC46IkU5_Jk9BqaQeHdv2.mH-G2zVqgztUtnW_.tkZuOO9h95OgHJmkkrfLBisku8rGf6nzVxhRM3sVOhXgz5NJ76oID7lpnAi_cPWJRCjSpAaUZ5dOR3Spy7QuEkmKx8-3RCMhSYMzsXaEwDdXta9Mn5B7cCBoJKB0IgEnj_qfo1hIi-uEkUpOZ8aLTZGHfpl05jMwbKkTe2yK3mjF6SBAsgicQDVCkcY9BLluzx1RmC3ORXaM0JaHPB93YcdSDGgpgBWMVrNU1ErkjcMqMoT_wtCex3w03XdLkjXIuEr2hWgeP-nkUZTPU9EoGSPj6fAS-bSz87RCPrxZdj_iVyC6QWcqAu07WNhjzJEPc4jVntRJ6K53NgPQ5p99l3Z408OUqj4ioYezbS6vTPlQ.WuGzxmcreYjpHGJoa17EBg', json: { recipients: [ { encrypted_key: '0DJjBXri_kBcC46IkU5_Jk9BqaQeHdv2', }, ], protected: 'eyJhbGciOiJFQ0RILUVTK0ExMjhLVyIsImtpZCI6InBlcmVncmluLnRvb2tAdHVja2Jvcm91Z2guZXhhbXBsZSIsImVwayI6eyJrdHkiOiJFQyIsImNydiI6IlAtMzg0IiwieCI6InVCbzRrSFB3Nmtiang1bDB4b3dyZF9vWXpCbWF6LUdLRlp1NHhBRkZrYllpV2d1dEVLNml1RURzUTZ3TmROZzMiLCJ5Ijoic3AzcDVTR2haVkMyZmFYdW1JLWU5SlUyTW84S3BvWXJGRHI1eVBOVnRXNFBnRXdaT3lRVEEtSmRhWTh0YjdFMCJ9LCJlbmMiOiJBMTI4R0NNIn0', iv: 'mH-G2zVqgztUtnW_', ciphertext: 'tkZuOO9h95OgHJmkkrfLBisku8rGf6nzVxhRM3sVOhXgz5NJ76oID7lpnAi_cPWJRCjSpAaUZ5dOR3Spy7QuEkmKx8-3RCMhSYMzsXaEwDdXta9Mn5B7cCBoJKB0IgEnj_qfo1hIi-uEkUpOZ8aLTZGHfpl05jMwbKkTe2yK3mjF6SBAsgicQDVCkcY9BLluzx1RmC3ORXaM0JaHPB93YcdSDGgpgBWMVrNU1ErkjcMqMoT_wtCex3w03XdLkjXIuEr2hWgeP-nkUZTPU9EoGSPj6fAS-bSz87RCPrxZdj_iVyC6QWcqAu07WNhjzJEPc4jVntRJ6K53NgPQ5p99l3Z408OUqj4ioYezbS6vTPlQ', tag: 'WuGzxmcreYjpHGJoa17EBg', }, json_flat: { protected: 'eyJhbGciOiJFQ0RILUVTK0ExMjhLVyIsImtpZCI6InBlcmVncmluLnRvb2tAdHVja2Jvcm91Z2guZXhhbXBsZSIsImVwayI6eyJrdHkiOiJFQyIsImNydiI6IlAtMzg0IiwieCI6InVCbzRrSFB3Nmtiang1bDB4b3dyZF9vWXpCbWF6LUdLRlp1NHhBRkZrYllpV2d1dEVLNml1RURzUTZ3TmROZzMiLCJ5Ijoic3AzcDVTR2haVkMyZmFYdW1JLWU5SlUyTW84S3BvWXJGRHI1eVBOVnRXNFBnRXdaT3lRVEEtSmRhWTh0YjdFMCJ9LCJlbmMiOiJBMTI4R0NNIn0', encrypted_key: '0DJjBXri_kBcC46IkU5_Jk9BqaQeHdv2', iv: 'mH-G2zVqgztUtnW_', ciphertext: 'tkZuOO9h95OgHJmkkrfLBisku8rGf6nzVxhRM3sVOhXgz5NJ76oID7lpnAi_cPWJRCjSpAaUZ5dOR3Spy7QuEkmKx8-3RCMhSYMzsXaEwDdXta9Mn5B7cCBoJKB0IgEnj_qfo1hIi-uEkUpOZ8aLTZGHfpl05jMwbKkTe2yK3mjF6SBAsgicQDVCkcY9BLluzx1RmC3ORXaM0JaHPB93YcdSDGgpgBWMVrNU1ErkjcMqMoT_wtCex3w03XdLkjXIuEr2hWgeP-nkUZTPU9EoGSPj6fAS-bSz87RCPrxZdj_iVyC6QWcqAu07WNhjzJEPc4jVntRJ6K53NgPQ5p99l3Z408OUqj4ioYezbS6vTPlQ', tag: 'WuGzxmcreYjpHGJoa17EBg', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-5.5 - Key Agreement using ECDH-ES with AES-CBC-HMAC-SHA2', input: { plaintext: 'You can trust us to stick with you through thick and thin–to the bitter end. And you can trust us to keep any secret of yours–closer than you keep it yourself. But you cannot trust us to let you face trouble alone, and go off without a word. We are your friends, Frodo.', key: { kty: 'EC', ext: false, kid: 'meriadoc.brandybuck@buckland.example', use: 'enc', crv: 'P-256', x: 'Ze2loSV3wrroKUN_4zhwGhCqo3Xhu1td4QjeQ5wIVR0', y: 'HlLtdXARY_f55A3fnzQbPcm6hgr34Mp8p-nuzQCE0Zw', d: 'r_kHyZ-a06rmxM3yESK84r1otSg-aQcVStkRhA-iCM8', }, alg: 'ECDH-ES', enc: 'A128CBC-HS256', }, generated: { iv: 'yc9N8v5sYyv3iGQT926IUg', }, encrypting_key: { epk: { kty: 'EC', crv: 'P-256', x: 'mPUKT_bAWGHIhg0TpjjqVsP1rXWQu_vwVOHHtNkdYoA', y: '8BQAsImGeAS46fyWw5MhYfGTT0IjBpFw2SS34Dv4Irs', d: 'AtH35vJsQ9SGjYfOsjUxYXQKrPH3FjZHmEtSKoSN8cM', }, cek: 'hzHdlfQIAEehb8Hrd_mFRhKsKLEzPfshfXs9l6areCc', }, encrypting_content: { protected: { alg: 'ECDH-ES', kid: 'meriadoc.brandybuck@buckland.example', epk: { kty: 'EC', crv: 'P-256', x: 'mPUKT_bAWGHIhg0TpjjqVsP1rXWQu_vwVOHHtNkdYoA', y: '8BQAsImGeAS46fyWw5MhYfGTT0IjBpFw2SS34Dv4Irs', }, enc: 'A128CBC-HS256', }, }, output: { compact: 'eyJhbGciOiJFQ0RILUVTIiwia2lkIjoibWVyaWFkb2MuYnJhbmR5YnVja0BidWNrbGFuZC5leGFtcGxlIiwiZXBrIjp7Imt0eSI6IkVDIiwiY3J2IjoiUC0yNTYiLCJ4IjoibVBVS1RfYkFXR0hJaGcwVHBqanFWc1AxclhXUXVfdndWT0hIdE5rZFlvQSIsInkiOiI4QlFBc0ltR2VBUzQ2ZnlXdzVNaFlmR1RUMElqQnBGdzJTUzM0RHY0SXJzIn0sImVuYyI6IkExMjhDQkMtSFMyNTYifQ..yc9N8v5sYyv3iGQT926IUg.BoDlwPnTypYq-ivjmQvAYJLb5Q6l-F3LIgQomlz87yW4OPKbWE1zSTEFjDfhU9IPIOSA9Bml4m7iDFwA-1ZXvHteLDtw4R1XRGMEsDIqAYtskTTmzmzNa-_q4F_evAPUmwlO-ZG45Mnq4uhM1fm_D9rBtWolqZSF3xGNNkpOMQKF1Cl8i8wjzRli7-IXgyirlKQsbhhqRzkv8IcY6aHl24j03C-AR2le1r7URUhArM79BY8soZU0lzwI-sD5PZ3l4NDCCei9XkoIAfsXJWmySPoeRb2Ni5UZL4mYpvKDiwmyzGd65KqVw7MsFfI_K767G9C9Azp73gKZD0DyUn1mn0WW5LmyX_yJ-3AROq8p1WZBfG-ZyJ6195_JGG2m9Csg.WCCkNa-x4BeB9hIDIfFuhg', json: { protected: 'eyJhbGciOiJFQ0RILUVTIiwia2lkIjoibWVyaWFkb2MuYnJhbmR5YnVja0BidWNrbGFuZC5leGFtcGxlIiwiZXBrIjp7Imt0eSI6IkVDIiwiY3J2IjoiUC0yNTYiLCJ4IjoibVBVS1RfYkFXR0hJaGcwVHBqanFWc1AxclhXUXVfdndWT0hIdE5rZFlvQSIsInkiOiI4QlFBc0ltR2VBUzQ2ZnlXdzVNaFlmR1RUMElqQnBGdzJTUzM0RHY0SXJzIn0sImVuYyI6IkExMjhDQkMtSFMyNTYifQ', iv: 'yc9N8v5sYyv3iGQT926IUg', ciphertext: 'BoDlwPnTypYq-ivjmQvAYJLb5Q6l-F3LIgQomlz87yW4OPKbWE1zSTEFjDfhU9IPIOSA9Bml4m7iDFwA-1ZXvHteLDtw4R1XRGMEsDIqAYtskTTmzmzNa-_q4F_evAPUmwlO-ZG45Mnq4uhM1fm_D9rBtWolqZSF3xGNNkpOMQKF1Cl8i8wjzRli7-IXgyirlKQsbhhqRzkv8IcY6aHl24j03C-AR2le1r7URUhArM79BY8soZU0lzwI-sD5PZ3l4NDCCei9XkoIAfsXJWmySPoeRb2Ni5UZL4mYpvKDiwmyzGd65KqVw7MsFfI_K767G9C9Azp73gKZD0DyUn1mn0WW5LmyX_yJ-3AROq8p1WZBfG-ZyJ6195_JGG2m9Csg', tag: 'WCCkNa-x4BeB9hIDIfFuhg', }, json_flat: { protected: 'eyJhbGciOiJFQ0RILUVTIiwia2lkIjoibWVyaWFkb2MuYnJhbmR5YnVja0BidWNrbGFuZC5leGFtcGxlIiwiZXBrIjp7Imt0eSI6IkVDIiwiY3J2IjoiUC0yNTYiLCJ4IjoibVBVS1RfYkFXR0hJaGcwVHBqanFWc1AxclhXUXVfdndWT0hIdE5rZFlvQSIsInkiOiI4QlFBc0ltR2VBUzQ2ZnlXdzVNaFlmR1RUMElqQnBGdzJTUzM0RHY0SXJzIn0sImVuYyI6IkExMjhDQkMtSFMyNTYifQ', iv: 'yc9N8v5sYyv3iGQT926IUg', ciphertext: 'BoDlwPnTypYq-ivjmQvAYJLb5Q6l-F3LIgQomlz87yW4OPKbWE1zSTEFjDfhU9IPIOSA9Bml4m7iDFwA-1ZXvHteLDtw4R1XRGMEsDIqAYtskTTmzmzNa-_q4F_evAPUmwlO-ZG45Mnq4uhM1fm_D9rBtWolqZSF3xGNNkpOMQKF1Cl8i8wjzRli7-IXgyirlKQsbhhqRzkv8IcY6aHl24j03C-AR2le1r7URUhArM79BY8soZU0lzwI-sD5PZ3l4NDCCei9XkoIAfsXJWmySPoeRb2Ni5UZL4mYpvKDiwmyzGd65KqVw7MsFfI_K767G9C9Azp73gKZD0DyUn1mn0WW5LmyX_yJ-3AROq8p1WZBfG-ZyJ6195_JGG2m9Csg', tag: 'WCCkNa-x4BeB9hIDIfFuhg', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-5.6 - Direction Encryption using AES-GCM', reproducible: true, input: { plaintext: 'You can trust us to stick with you through thick and thin–to the bitter end. And you can trust us to keep any secret of yours–closer than you keep it yourself. But you cannot trust us to let you face trouble alone, and go off without a word. We are your friends, Frodo.', key: { kty: 'oct', ext: false, kid: '77c7e2b8-6e13-45cf-8672-617b5b45243a', use: 'enc', alg: 'A128GCM', k: 'XctOhJAkA-pD9Lh7ZgW_2A', }, alg: 'dir', enc: 'A128GCM', }, generated: { iv: 'refa467QzzKx6QAB', }, encrypting_content: { protected: { alg: 'dir', kid: '77c7e2b8-6e13-45cf-8672-617b5b45243a', enc: 'A128GCM', }, }, output: { compact: 'eyJhbGciOiJkaXIiLCJraWQiOiI3N2M3ZTJiOC02ZTEzLTQ1Y2YtODY3Mi02MTdiNWI0NTI0M2EiLCJlbmMiOiJBMTI4R0NNIn0..refa467QzzKx6QAB.JW_i_f52hww_ELQPGaYyeAB6HYGcR559l9TYnSovc23XJoBcW29rHP8yZOZG7YhLpT1bjFuvZPjQS-m0IFtVcXkZXdH_lr_FrdYt9HRUYkshtrMmIUAyGmUnd9zMDB2n0cRDIHAzFVeJUDxkUwVAE7_YGRPdcqMyiBoCO-FBdE-Nceb4h3-FtBP-c_BIwCPTjb9o0SbdcdREEMJMyZBH8ySWMVi1gPD9yxi-aQpGbSv_F9N4IZAxscj5g-NJsUPbjk29-s7LJAGb15wEBtXphVCgyy53CoIKLHHeJHXex45Uz9aKZSRSInZI-wjsY0yu3cT4_aQ3i1o-tiE-F8Ios61EKgyIQ4CWao8PFMj8TTnp.vbb32Xvllea2OtmHAdccRQ', json: { protected: 'eyJhbGciOiJkaXIiLCJraWQiOiI3N2M3ZTJiOC02ZTEzLTQ1Y2YtODY3Mi02MTdiNWI0NTI0M2EiLCJlbmMiOiJBMTI4R0NNIn0', iv: 'refa467QzzKx6QAB', ciphertext: 'JW_i_f52hww_ELQPGaYyeAB6HYGcR559l9TYnSovc23XJoBcW29rHP8yZOZG7YhLpT1bjFuvZPjQS-m0IFtVcXkZXdH_lr_FrdYt9HRUYkshtrMmIUAyGmUnd9zMDB2n0cRDIHAzFVeJUDxkUwVAE7_YGRPdcqMyiBoCO-FBdE-Nceb4h3-FtBP-c_BIwCPTjb9o0SbdcdREEMJMyZBH8ySWMVi1gPD9yxi-aQpGbSv_F9N4IZAxscj5g-NJsUPbjk29-s7LJAGb15wEBtXphVCgyy53CoIKLHHeJHXex45Uz9aKZSRSInZI-wjsY0yu3cT4_aQ3i1o-tiE-F8Ios61EKgyIQ4CWao8PFMj8TTnp', tag: 'vbb32Xvllea2OtmHAdccRQ', }, json_flat: { protected: 'eyJhbGciOiJkaXIiLCJraWQiOiI3N2M3ZTJiOC02ZTEzLTQ1Y2YtODY3Mi02MTdiNWI0NTI0M2EiLCJlbmMiOiJBMTI4R0NNIn0', iv: 'refa467QzzKx6QAB', ciphertext: 'JW_i_f52hww_ELQPGaYyeAB6HYGcR559l9TYnSovc23XJoBcW29rHP8yZOZG7YhLpT1bjFuvZPjQS-m0IFtVcXkZXdH_lr_FrdYt9HRUYkshtrMmIUAyGmUnd9zMDB2n0cRDIHAzFVeJUDxkUwVAE7_YGRPdcqMyiBoCO-FBdE-Nceb4h3-FtBP-c_BIwCPTjb9o0SbdcdREEMJMyZBH8ySWMVi1gPD9yxi-aQpGbSv_F9N4IZAxscj5g-NJsUPbjk29-s7LJAGb15wEBtXphVCgyy53CoIKLHHeJHXex45Uz9aKZSRSInZI-wjsY0yu3cT4_aQ3i1o-tiE-F8Ios61EKgyIQ4CWao8PFMj8TTnp', tag: 'vbb32Xvllea2OtmHAdccRQ', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-5.6 - Key Wrap using AES-GCM KeyWrap with AES-CBC-HMAC-SHA2', reproducible: true, input: { plaintext: 'You can trust us to stick with you through thick and thin–to the bitter end. And you can trust us to keep any secret of yours–closer than you keep it yourself. But you cannot trust us to let you face trouble alone, and go off without a word. We are your friends, Frodo.', key: { kty: 'oct', ext: false, kid: '18ec08e1-bfa9-4d95-b205-2b4dd1d4321d', use: 'enc', alg: 'A256GCMKW', k: 'qC57l_uxcm7Nm3K-ct4GFjx8tM1U8CZ0NLBvdQstiS8', }, alg: 'A256GCMKW', enc: 'A128CBC-HS256', }, generated: { cek: 'UWxARpat23nL9ReIj4WG3D1ee9I4r-Mv5QLuFXdy_rE', iv: 'gz6NjyEFNm_vm8Gj6FwoFQ', }, encrypting_key: { iv: 'KkYT0GX_2jHlfqN_', tag: 'kfPduVQ3T3H6vnewt--ksw', }, encrypting_content: { protected: { alg: 'A256GCMKW', kid: '18ec08e1-bfa9-4d95-b205-2b4dd1d4321d', tag: 'kfPduVQ3T3H6vnewt--ksw', iv: 'KkYT0GX_2jHlfqN_', enc: 'A128CBC-HS256', }, }, output: { compact: 'eyJhbGciOiJBMjU2R0NNS1ciLCJraWQiOiIxOGVjMDhlMS1iZmE5LTRkOTUtYjIwNS0yYjRkZDFkNDMyMWQiLCJ0YWciOiJrZlBkdVZRM1QzSDZ2bmV3dC0ta3N3IiwiaXYiOiJLa1lUMEdYXzJqSGxmcU5fIiwiZW5jIjoiQTEyOENCQy1IUzI1NiJ9.lJf3HbOApxMEBkCMOoTnnABxs_CvTWUmZQ2ElLvYNok.gz6NjyEFNm_vm8Gj6FwoFQ.Jf5p9-ZhJlJy_IQ_byKFmI0Ro7w7G1QiaZpI8OaiVgD8EqoDZHyFKFBupS8iaEeVIgMqWmsuJKuoVgzR3YfzoMd3GxEm3VxNhzWyWtZKX0gxKdy6HgLvqoGNbZCzLjqcpDiF8q2_62EVAbr2uSc2oaxFmFuIQHLcqAHxy51449xkjZ7ewzZaGV3eFqhpco8o4DijXaG5_7kp3h2cajRfDgymuxUbWgLqaeNQaJtvJmSMFuEOSAzw9Hdeb6yhdTynCRmu-kqtO5Dec4lT2OMZKpnxc_F1_4yDJFcqb5CiDSmA-psB2k0JtjxAj4UPI61oONK7zzFIu4gBfjJCndsZfdvG7h8wGjV98QhrKEnR7xKZ3KCr0_qR1B-gxpNk3xWU.DKW7jrb4WaRSNfbXVPlT5g', json: { recipients: [ { encrypted_key: 'lJf3HbOApxMEBkCMOoTnnABxs_CvTWUmZQ2ElLvYNok', }, ], protected: 'eyJhbGciOiJBMjU2R0NNS1ciLCJraWQiOiIxOGVjMDhlMS1iZmE5LTRkOTUtYjIwNS0yYjRkZDFkNDMyMWQiLCJ0YWciOiJrZlBkdVZRM1QzSDZ2bmV3dC0ta3N3IiwiaXYiOiJLa1lUMEdYXzJqSGxmcU5fIiwiZW5jIjoiQTEyOENCQy1IUzI1NiJ9', iv: 'gz6NjyEFNm_vm8Gj6FwoFQ', ciphertext: 'Jf5p9-ZhJlJy_IQ_byKFmI0Ro7w7G1QiaZpI8OaiVgD8EqoDZHyFKFBupS8iaEeVIgMqWmsuJKuoVgzR3YfzoMd3GxEm3VxNhzWyWtZKX0gxKdy6HgLvqoGNbZCzLjqcpDiF8q2_62EVAbr2uSc2oaxFmFuIQHLcqAHxy51449xkjZ7ewzZaGV3eFqhpco8o4DijXaG5_7kp3h2cajRfDgymuxUbWgLqaeNQaJtvJmSMFuEOSAzw9Hdeb6yhdTynCRmu-kqtO5Dec4lT2OMZKpnxc_F1_4yDJFcqb5CiDSmA-psB2k0JtjxAj4UPI61oONK7zzFIu4gBfjJCndsZfdvG7h8wGjV98QhrKEnR7xKZ3KCr0_qR1B-gxpNk3xWU', tag: 'DKW7jrb4WaRSNfbXVPlT5g', }, json_flat: { protected: 'eyJhbGciOiJBMjU2R0NNS1ciLCJraWQiOiIxOGVjMDhlMS1iZmE5LTRkOTUtYjIwNS0yYjRkZDFkNDMyMWQiLCJ0YWciOiJrZlBkdVZRM1QzSDZ2bmV3dC0ta3N3IiwiaXYiOiJLa1lUMEdYXzJqSGxmcU5fIiwiZW5jIjoiQTEyOENCQy1IUzI1NiJ9', encrypted_key: 'lJf3HbOApxMEBkCMOoTnnABxs_CvTWUmZQ2ElLvYNok', iv: 'gz6NjyEFNm_vm8Gj6FwoFQ', ciphertext: 'Jf5p9-ZhJlJy_IQ_byKFmI0Ro7w7G1QiaZpI8OaiVgD8EqoDZHyFKFBupS8iaEeVIgMqWmsuJKuoVgzR3YfzoMd3GxEm3VxNhzWyWtZKX0gxKdy6HgLvqoGNbZCzLjqcpDiF8q2_62EVAbr2uSc2oaxFmFuIQHLcqAHxy51449xkjZ7ewzZaGV3eFqhpco8o4DijXaG5_7kp3h2cajRfDgymuxUbWgLqaeNQaJtvJmSMFuEOSAzw9Hdeb6yhdTynCRmu-kqtO5Dec4lT2OMZKpnxc_F1_4yDJFcqb5CiDSmA-psB2k0JtjxAj4UPI61oONK7zzFIu4gBfjJCndsZfdvG7h8wGjV98QhrKEnR7xKZ3KCr0_qR1B-gxpNk3xWU', tag: 'DKW7jrb4WaRSNfbXVPlT5g', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-5.8 - Key Wrap using AES-KeyWrap with AES-GCM', electron: false, reproducible: true, input: { plaintext: 'You can trust us to stick with you through thick and thin–to the bitter end. And you can trust us to keep any secret of yours–closer than you keep it yourself. But you cannot trust us to let you face trouble alone, and go off without a word. We are your friends, Frodo.', key: { kty: 'oct', ext: false, kid: '81b20965-8332-43d9-a468-82160ad91ac8', use: 'enc', alg: 'A128KW', k: 'GZy6sIZ6wl9NJOKB-jnmVQ', }, alg: 'A128KW', enc: 'A128GCM', }, generated: { cek: 'aY5_Ghmk9KxWPBLu_glx1w', iv: 'Qx0pmsDa8KnJc9Jo', }, encrypting_key: {}, encrypting_content: { protected: { alg: 'A128KW', kid: '81b20965-8332-43d9-a468-82160ad91ac8', enc: 'A128GCM', }, }, output: { compact: 'eyJhbGciOiJBMTI4S1ciLCJraWQiOiI4MWIyMDk2NS04MzMyLTQzZDktYTQ2OC04MjE2MGFkOTFhYzgiLCJlbmMiOiJBMTI4R0NNIn0.CBI6oDw8MydIx1IBntf_lQcw2MmJKIQx.Qx0pmsDa8KnJc9Jo.AwliP-KmWgsZ37BvzCefNen6VTbRK3QMA4TkvRkH0tP1bTdhtFJgJxeVmJkLD61A1hnWGetdg11c9ADsnWgL56NyxwSYjU1ZEHcGkd3EkU0vjHi9gTlb90qSYFfeF0LwkcTtjbYKCsiNJQkcIp1yeM03OmuiYSoYJVSpf7ej6zaYcMv3WwdxDFl8REwOhNImk2Xld2JXq6BR53TSFkyT7PwVLuq-1GwtGHlQeg7gDT6xW0JqHDPn_H-puQsmthc9Zg0ojmJfqqFvETUxLAF-KjcBTS5dNy6egwkYtOt8EIHK-oEsKYtZRaa8Z7MOZ7UGxGIMvEmxrGCPeJa14slv2-gaqK0kEThkaSqdYw0FkQZF.ER7MWJZ1FBI_NKvn7Zb1Lw', json: { recipients: [ { encrypted_key: 'CBI6oDw8MydIx1IBntf_lQcw2MmJKIQx', }, ], protected: 'eyJhbGciOiJBMTI4S1ciLCJraWQiOiI4MWIyMDk2NS04MzMyLTQzZDktYTQ2OC04MjE2MGFkOTFhYzgiLCJlbmMiOiJBMTI4R0NNIn0', iv: 'Qx0pmsDa8KnJc9Jo', ciphertext: 'AwliP-KmWgsZ37BvzCefNen6VTbRK3QMA4TkvRkH0tP1bTdhtFJgJxeVmJkLD61A1hnWGetdg11c9ADsnWgL56NyxwSYjU1ZEHcGkd3EkU0vjHi9gTlb90qSYFfeF0LwkcTtjbYKCsiNJQkcIp1yeM03OmuiYSoYJVSpf7ej6zaYcMv3WwdxDFl8REwOhNImk2Xld2JXq6BR53TSFkyT7PwVLuq-1GwtGHlQeg7gDT6xW0JqHDPn_H-puQsmthc9Zg0ojmJfqqFvETUxLAF-KjcBTS5dNy6egwkYtOt8EIHK-oEsKYtZRaa8Z7MOZ7UGxGIMvEmxrGCPeJa14slv2-gaqK0kEThkaSqdYw0FkQZF', tag: 'ER7MWJZ1FBI_NKvn7Zb1Lw', }, json_flat: { protected: 'eyJhbGciOiJBMTI4S1ciLCJraWQiOiI4MWIyMDk2NS04MzMyLTQzZDktYTQ2OC04MjE2MGFkOTFhYzgiLCJlbmMiOiJBMTI4R0NNIn0', encrypted_key: 'CBI6oDw8MydIx1IBntf_lQcw2MmJKIQx', iv: 'Qx0pmsDa8KnJc9Jo', ciphertext: 'AwliP-KmWgsZ37BvzCefNen6VTbRK3QMA4TkvRkH0tP1bTdhtFJgJxeVmJkLD61A1hnWGetdg11c9ADsnWgL56NyxwSYjU1ZEHcGkd3EkU0vjHi9gTlb90qSYFfeF0LwkcTtjbYKCsiNJQkcIp1yeM03OmuiYSoYJVSpf7ej6zaYcMv3WwdxDFl8REwOhNImk2Xld2JXq6BR53TSFkyT7PwVLuq-1GwtGHlQeg7gDT6xW0JqHDPn_H-puQsmthc9Zg0ojmJfqqFvETUxLAF-KjcBTS5dNy6egwkYtOt8EIHK-oEsKYtZRaa8Z7MOZ7UGxGIMvEmxrGCPeJa14slv2-gaqK0kEThkaSqdYw0FkQZF', tag: 'ER7MWJZ1FBI_NKvn7Zb1Lw', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-5.9 - Compressed Content', webapi: false, electron: false, reproducible: true, input: { plaintext: 'You can trust us to stick with you through thick and thin–to the bitter end. And you can trust us to keep any secret of yours–closer than you keep it yourself. But you cannot trust us to let you face trouble alone, and go off without a word. We are your friends, Frodo.', key: { kty: 'oct', ext: false, kid: '81b20965-8332-43d9-a468-82160ad91ac8', use: 'enc', alg: 'A128KW', k: 'GZy6sIZ6wl9NJOKB-jnmVQ', }, alg: 'A128KW', enc: 'A128GCM', zip: 'DEF', }, generated: { plaintext_c: 'bY_BDcIwDEVX-QNU3QEOrIA4pqlDokYxchxVvbEDGzIJbioOSJwc-f___HPjBu8KVFpVtAplVE1-wZo0YjNZo3C7R5v72pV5f5X382VWjYQpqZKAyjziZOr2B7kQPSy6oZIXUnDYbVKN4jNXi2u0yB7t1qSHTjmMODf9QgvrDzfTIQXnyQRuUya4zIWG3vTOdir0v7BRHFYWq3k1k1A_gSDJqtcBF-GZxw8', cek: 'hC-MpLZSuwWv8sexS6ydfw', iv: 'p9pUq6XHY0jfEZIl', }, encrypting_key: {}, encrypting_content: { protected: { alg: 'A128KW', kid: '81b20965-8332-43d9-a468-82160ad91ac8', enc: 'A128GCM', zip: 'DEF', }, }, output: { compact: 'eyJhbGciOiJBMTI4S1ciLCJraWQiOiI4MWIyMDk2NS04MzMyLTQzZDktYTQ2OC04MjE2MGFkOTFhYzgiLCJlbmMiOiJBMTI4R0NNIiwiemlwIjoiREVGIn0.5vUT2WOtQxKWcekM_IzVQwkGgzlFDwPi.p9pUq6XHY0jfEZIl.HbDtOsdai1oYziSx25KEeTxmwnh8L8jKMFNc1k3zmMI6VB8hry57tDZ61jXyezSPt0fdLVfe6Jf5y5-JaCap_JQBcb5opbmT60uWGml8blyiMQmOn9J--XhhlYg0m-BHaqfDO5iTOWxPxFMUedx7WCy8mxgDHj0aBMG6152PsM-w5E_o2B3jDbrYBKhpYA7qi3AyijnCJ7BP9rr3U8kxExCpG3mK420TjOw.VILuUwuIxaLVmh5X-T7kmA', json: { recipients: [ { encrypted_key: '5vUT2WOtQxKWcekM_IzVQwkGgzlFDwPi', }, ], protected: 'eyJhbGciOiJBMTI4S1ciLCJraWQiOiI4MWIyMDk2NS04MzMyLTQzZDktYTQ2OC04MjE2MGFkOTFhYzgiLCJlbmMiOiJBMTI4R0NNIiwiemlwIjoiREVGIn0', iv: 'p9pUq6XHY0jfEZIl', ciphertext: 'HbDtOsdai1oYziSx25KEeTxmwnh8L8jKMFNc1k3zmMI6VB8hry57tDZ61jXyezSPt0fdLVfe6Jf5y5-JaCap_JQBcb5opbmT60uWGml8blyiMQmOn9J--XhhlYg0m-BHaqfDO5iTOWxPxFMUedx7WCy8mxgDHj0aBMG6152PsM-w5E_o2B3jDbrYBKhpYA7qi3AyijnCJ7BP9rr3U8kxExCpG3mK420TjOw', tag: 'VILuUwuIxaLVmh5X-T7kmA', }, json_flat: { protected: 'eyJhbGciOiJBMTI4S1ciLCJraWQiOiI4MWIyMDk2NS04MzMyLTQzZDktYTQ2OC04MjE2MGFkOTFhYzgiLCJlbmMiOiJBMTI4R0NNIiwiemlwIjoiREVGIn0', encrypted_key: '5vUT2WOtQxKWcekM_IzVQwkGgzlFDwPi', iv: 'p9pUq6XHY0jfEZIl', ciphertext: 'HbDtOsdai1oYziSx25KEeTxmwnh8L8jKMFNc1k3zmMI6VB8hry57tDZ61jXyezSPt0fdLVfe6Jf5y5-JaCap_JQBcb5opbmT60uWGml8blyiMQmOn9J--XhhlYg0m-BHaqfDO5iTOWxPxFMUedx7WCy8mxgDHj0aBMG6152PsM-w5E_o2B3jDbrYBKhpYA7qi3AyijnCJ7BP9rr3U8kxExCpG3mK420TjOw', tag: 'VILuUwuIxaLVmh5X-T7kmA', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-5.10 - Including Additional Authenticated Data', electron: false, reproducible: true, input: { plaintext: 'You can trust us to stick with you through thick and thin–to the bitter end. And you can trust us to keep any secret of yours–closer than you keep it yourself. But you cannot trust us to let you face trouble alone, and go off without a word. We are your friends, Frodo.', key: { kty: 'oct', ext: false, kid: '81b20965-8332-43d9-a468-82160ad91ac8', use: 'enc', alg: 'A128KW', k: 'GZy6sIZ6wl9NJOKB-jnmVQ', }, alg: 'A128KW', enc: 'A128GCM', aad: '["vcard",[["version",{},"text","4.0"],["fn",{},"text","Meriadoc Brandybuck"],["n",{},"text",["Brandybuck","Meriadoc","Mr.",""]],["bday",{},"text","TA 2982"],["gender",{},"text","M"]]]', }, generated: { cek: '75m1ALsYv10pZTKPWrsqdg', iv: 'veCx9ece2orS7c_N', aad_b64u: 'WyJ2Y2FyZCIsW1sidmVyc2lvbiIse30sInRleHQiLCI0LjAiXSxbImZuIix7fSwidGV4dCIsIk1lcmlhZG9jIEJyYW5keWJ1Y2siXSxbIm4iLHt9LCJ0ZXh0IixbIkJyYW5keWJ1Y2siLCJNZXJpYWRvYyIsIk1yLiIsIiJdXSxbImJkYXkiLHt9LCJ0ZXh0IiwiVEEgMjk4MiJdLFsiZ2VuZGVyIix7fSwidGV4dCIsIk0iXV1d', }, encrypting_key: {}, encrypting_content: { protected: { alg: 'A128KW', kid: '81b20965-8332-43d9-a468-82160ad91ac8', enc: 'A128GCM', }, }, output: { json: { recipients: [ { encrypted_key: '4YiiQ_ZzH76TaIkJmYfRFgOV9MIpnx4X', }, ], protected: 'eyJhbGciOiJBMTI4S1ciLCJraWQiOiI4MWIyMDk2NS04MzMyLTQzZDktYTQ2OC04MjE2MGFkOTFhYzgiLCJlbmMiOiJBMTI4R0NNIn0', iv: 'veCx9ece2orS7c_N', aad: 'WyJ2Y2FyZCIsW1sidmVyc2lvbiIse30sInRleHQiLCI0LjAiXSxbImZuIix7fSwidGV4dCIsIk1lcmlhZG9jIEJyYW5keWJ1Y2siXSxbIm4iLHt9LCJ0ZXh0IixbIkJyYW5keWJ1Y2siLCJNZXJpYWRvYyIsIk1yLiIsIiJdXSxbImJkYXkiLHt9LCJ0ZXh0IiwiVEEgMjk4MiJdLFsiZ2VuZGVyIix7fSwidGV4dCIsIk0iXV1d', ciphertext: 'Z_3cbr0k3bVM6N3oSNmHz7Lyf3iPppGf3Pj17wNZqteJ0Ui8p74SchQP8xygM1oFRWCNzeIa6s6BcEtp8qEFiqTUEyiNkOWDNoF14T_4NFqF-p2Mx8zkbKxI7oPK8KNarFbyxIDvICNqBLba-v3uzXBdB89fzOI-Lv4PjOFAQGHrgv1rjXAmKbgkft9cB4WeyZw8MldbBhc-V_KWZslrsLNygon_JJWd_ek6LQn5NRehvApqf9ZrxB4aq3FXBxOxCys35PhCdaggy2kfUfl2OkwKnWUbgXVD1C6HxLIlqHhCwXDG59weHrRDQeHyMRoBljoV3X_bUTJDnKBFOod7nLz-cj48JMx3SnCZTpbQAkFV', tag: 'vOaH_Rajnpy_3hOtqvZHRA', }, json_flat: { protected: 'eyJhbGciOiJBMTI4S1ciLCJraWQiOiI4MWIyMDk2NS04MzMyLTQzZDktYTQ2OC04MjE2MGFkOTFhYzgiLCJlbmMiOiJBMTI4R0NNIn0', encrypted_key: '4YiiQ_ZzH76TaIkJmYfRFgOV9MIpnx4X', aad: 'WyJ2Y2FyZCIsW1sidmVyc2lvbiIse30sInRleHQiLCI0LjAiXSxbImZuIix7fSwidGV4dCIsIk1lcmlhZG9jIEJyYW5keWJ1Y2siXSxbIm4iLHt9LCJ0ZXh0IixbIkJyYW5keWJ1Y2siLCJNZXJpYWRvYyIsIk1yLiIsIiJdXSxbImJkYXkiLHt9LCJ0ZXh0IiwiVEEgMjk4MiJdLFsiZ2VuZGVyIix7fSwidGV4dCIsIk0iXV1d', iv: 'veCx9ece2orS7c_N', ciphertext: 'Z_3cbr0k3bVM6N3oSNmHz7Lyf3iPppGf3Pj17wNZqteJ0Ui8p74SchQP8xygM1oFRWCNzeIa6s6BcEtp8qEFiqTUEyiNkOWDNoF14T_4NFqF-p2Mx8zkbKxI7oPK8KNarFbyxIDvICNqBLba-v3uzXBdB89fzOI-Lv4PjOFAQGHrgv1rjXAmKbgkft9cB4WeyZw8MldbBhc-V_KWZslrsLNygon_JJWd_ek6LQn5NRehvApqf9ZrxB4aq3FXBxOxCys35PhCdaggy2kfUfl2OkwKnWUbgXVD1C6HxLIlqHhCwXDG59weHrRDQeHyMRoBljoV3X_bUTJDnKBFOod7nLz-cj48JMx3SnCZTpbQAkFV', tag: 'vOaH_Rajnpy_3hOtqvZHRA', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-5.11 - Protecting Specific Header Fields', electron: false, reproducible: true, input: { plaintext: 'You can trust us to stick with you through thick and thin–to the bitter end. And you can trust us to keep any secret of yours–closer than you keep it yourself. But you cannot trust us to let you face trouble alone, and go off without a word. We are your friends, Frodo.', key: { kty: 'oct', ext: false, kid: '81b20965-8332-43d9-a468-82160ad91ac8', use: 'enc', alg: 'A128KW', k: 'GZy6sIZ6wl9NJOKB-jnmVQ', }, alg: 'A128KW', enc: 'A128GCM', }, generated: { cek: 'WDgEptBmQs9ouUvArz6x6g', iv: 'WgEJsDS9bkoXQ3nR', }, encrypting_key: {}, encrypting_content: { protected: { enc: 'A128GCM', }, unprotected: { alg: 'A128KW', kid: '81b20965-8332-43d9-a468-82160ad91ac8', }, }, output: { json: { recipients: [ { encrypted_key: 'jJIcM9J-hbx3wnqhf5FlkEYos0sHsF0H', }, ], unprotected: { alg: 'A128KW', kid: '81b20965-8332-43d9-a468-82160ad91ac8', }, protected: 'eyJlbmMiOiJBMTI4R0NNIn0', iv: 'WgEJsDS9bkoXQ3nR', ciphertext: 'lIbCyRmRJxnB2yLQOTqjCDKV3H30ossOw3uD9DPsqLL2DM3swKkjOwQyZtWsFLYMj5YeLht_StAn21tHmQJuuNt64T8D4t6C7kC9OCCJ1IHAolUv4MyOt80MoPb8fZYbNKqplzYJgIL58g8N2v46OgyG637d6uuKPwhAnTGm_zWhqc_srOvgiLkzyFXPq1hBAURbc3-8BqeRb48iR1-_5g5UjWVD3lgiLCN_P7AW8mIiFvUNXBPJK3nOWL4teUPS8yHLbWeL83olU4UAgL48x-8dDkH23JykibVSQju-f7e-1xreHWXzWLHs1NqBbre0dEwK3HX_xM0LjUz77Krppgegoutpf5qaKg3l-_xMINmf', tag: 'fNYLqpUe84KD45lvDiaBAQ', }, json_flat: { protected: 'eyJlbmMiOiJBMTI4R0NNIn0', unprotected: { alg: 'A128KW', kid: '81b20965-8332-43d9-a468-82160ad91ac8', }, encrypted_key: 'jJIcM9J-hbx3wnqhf5FlkEYos0sHsF0H', iv: 'WgEJsDS9bkoXQ3nR', ciphertext: 'lIbCyRmRJxnB2yLQOTqjCDKV3H30ossOw3uD9DPsqLL2DM3swKkjOwQyZtWsFLYMj5YeLht_StAn21tHmQJuuNt64T8D4t6C7kC9OCCJ1IHAolUv4MyOt80MoPb8fZYbNKqplzYJgIL58g8N2v46OgyG637d6uuKPwhAnTGm_zWhqc_srOvgiLkzyFXPq1hBAURbc3-8BqeRb48iR1-_5g5UjWVD3lgiLCN_P7AW8mIiFvUNXBPJK3nOWL4teUPS8yHLbWeL83olU4UAgL48x-8dDkH23JykibVSQju-f7e-1xreHWXzWLHs1NqBbre0dEwK3HX_xM0LjUz77Krppgegoutpf5qaKg3l-_xMINmf', tag: 'fNYLqpUe84KD45lvDiaBAQ', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-5.12 - Protecting Content Only', electron: false, reproducible: true, input: { plaintext: 'You can trust us to stick with you through thick and thin–to the bitter end. And you can trust us to keep any secret of yours–closer than you keep it yourself. But you cannot trust us to let you face trouble alone, and go off without a word. We are your friends, Frodo.', key: { kty: 'oct', ext: false, kid: '81b20965-8332-43d9-a468-82160ad91ac8', use: 'enc', alg: 'A128KW', k: 'GZy6sIZ6wl9NJOKB-jnmVQ', }, alg: 'A128KW', enc: 'A128GCM', }, generated: { cek: 'KBooAFl30QPV3vkcZlXnzQ', iv: 'YihBoVOGsR1l7jCD', }, encrypting_key: {}, encrypting_content: { unprotected: { alg: 'A128KW', kid: '81b20965-8332-43d9-a468-82160ad91ac8', enc: 'A128GCM', }, }, output: { json: { recipients: [ { encrypted_key: '244YHfO_W7RMpQW81UjQrZcq5LSyqiPv', }, ], unprotected: { alg: 'A128KW', kid: '81b20965-8332-43d9-a468-82160ad91ac8', enc: 'A128GCM', }, iv: 'YihBoVOGsR1l7jCD', ciphertext: 'qtPIMMaOBRgASL10dNQhOa7Gqrk7Eal1vwht7R4TT1uq-arsVCPaIeFwQfzrSS6oEUWbBtxEasE0vC6r7sphyVziMCVJEuRJyoAHFSP3eqQPb4Ic1SDSqyXjw_L3svybhHYUGyQuTmUQEDjgjJfBOifwHIsDsRPeBz1NomqeifVPq5GTCWFo5k_MNIQURR2Wj0AHC2k7JZfu2iWjUHLF8ExFZLZ4nlmsvJu_mvifMYiikfNfsZAudISOa6O73yPZtL04k_1FI7WDfrb2w7OqKLWDXzlpcxohPVOLQwpA3mFNRKdY-bQz4Z4KX9lfz1cne31N4-8BKmojpw-OdQjKdLOGkC445Fb_K1tlDQXw2sBF', tag: 'e2m0Vm7JvjK2VpCKXS-kyg', }, json_flat: { unprotected: { alg: 'A128KW', kid: '81b20965-8332-43d9-a468-82160ad91ac8', enc: 'A128GCM', }, encrypted_key: '244YHfO_W7RMpQW81UjQrZcq5LSyqiPv', iv: 'YihBoVOGsR1l7jCD', ciphertext: 'qtPIMMaOBRgASL10dNQhOa7Gqrk7Eal1vwht7R4TT1uq-arsVCPaIeFwQfzrSS6oEUWbBtxEasE0vC6r7sphyVziMCVJEuRJyoAHFSP3eqQPb4Ic1SDSqyXjw_L3svybhHYUGyQuTmUQEDjgjJfBOifwHIsDsRPeBz1NomqeifVPq5GTCWFo5k_MNIQURR2Wj0AHC2k7JZfu2iWjUHLF8ExFZLZ4nlmsvJu_mvifMYiikfNfsZAudISOa6O73yPZtL04k_1FI7WDfrb2w7OqKLWDXzlpcxohPVOLQwpA3mFNRKdY-bQz4Z4KX9lfz1cne31N4-8BKmojpw-OdQjKdLOGkC445Fb_K1tlDQXw2sBF', tag: 'e2m0Vm7JvjK2VpCKXS-kyg', }, }, }, ] jose-4.11.4/cookbook/jws.mjs000066400000000000000000000460161437043056600157040ustar00rootroot00000000000000export default [ { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-4.1 - RSA v1.5 Signature', reproducible: true, input: { payload: "It’s a dangerous business, Frodo, going out your door. You step onto the road, and if you don't keep your feet, there’s no knowing where you might be swept off to.", key: { kty: 'RSA', ext: false, kid: 'bilbo.baggins@hobbiton.example', use: 'sig', n: 'n4EPtAOCc9AlkeQHPzHStgAbgs7bTZLwUBZdR8_KuKPEHLd4rHVTeT-O-XV2jRojdNhxJWTDvNd7nqQ0VEiZQHz_AJmSCpMaJMRBSFKrKb2wqVwGU_NsYOYL-QtiWN2lbzcEe6XC0dApr5ydQLrHqkHHig3RBordaZ6Aj-oBHqFEHYpPe7Tpe-OfVfHd1E6cS6M1FZcD1NNLYD5lFHpPI9bTwJlsde3uhGqC0ZCuEHg8lhzwOHrtIQbS0FVbb9k3-tVTU4fg_3L_vniUFAKwuCLqKnS2BYwdq_mzSnbLY7h_qixoR7jig3__kRhuaxwUkRz5iaiQkqgc5gHdrNP5zw', e: 'AQAB', d: 'bWUC9B-EFRIo8kpGfh0ZuyGPvMNKvYWNtB_ikiH9k20eT-O1q_I78eiZkpXxXQ0UTEs2LsNRS-8uJbvQ-A1irkwMSMkK1J3XTGgdrhCku9gRldY7sNA_AKZGh-Q661_42rINLRCe8W-nZ34ui_qOfkLnK9QWDDqpaIsA-bMwWWSDFu2MUBYwkHTMEzLYGqOe04noqeq1hExBTHBOBdkMXiuFhUq1BU6l-DqEiWxqg82sXt2h-LMnT3046AOYJoRioz75tSUQfGCshWTBnP5uDjd18kKhyv07lhfSJdrPdM5Plyl21hsFf4L_mHCuoFau7gdsPfHPxxjVOcOpBrQzwQ', p: '3Slxg_DwTXJcb6095RoXygQCAZ5RnAvZlno1yhHtnUex_fp7AZ_9nRaO7HX_-SFfGQeutao2TDjDAWU4Vupk8rw9JR0AzZ0N2fvuIAmr_WCsmGpeNqQnev1T7IyEsnh8UMt-n5CafhkikzhEsrmndH6LxOrvRJlsPp6Zv8bUq0k', q: 'uKE2dh-cTf6ERF4k4e_jy78GfPYUIaUyoSSJuBzp3Cubk3OCqs6grT8bR_cu0Dm1MZwWmtdqDyI95HrUeq3MP15vMMON8lHTeZu2lmKvwqW7anV5UzhM1iZ7z4yMkuUwFWoBvyY898EXvRD-hdqRxHlSqAZ192zB3pVFJ0s7pFc', dp: 'B8PVvXkvJrj2L-GYQ7v3y9r6Kw5g9SahXBwsWUzp19TVlgI-YV85q1NIb1rxQtD-IsXXR3-TanevuRPRt5OBOdiMGQp8pbt26gljYfKU_E9xn-RULHz0-ed9E9gXLKD4VGngpz-PfQ_q29pk5xWHoJp009Qf1HvChixRX59ehik', dq: 'CLDmDGduhylc9o7r84rEUVn7pzQ6PF83Y-iBZx5NT-TpnOZKF1pErAMVeKzFEl41DlHHqqBLSM0W1sOFbwTxYWZDm6sI6og5iTbwQGIC3gnJKbi_7k_vJgGHwHxgPaX2PnvP-zyEkDERuf-ry4c_Z11Cq9AqC2yeL6kdKT1cYF8', qi: '3PiqvXQN0zwMeE-sBvZgi289XP9XCQF3VWqPzMKnIgQp7_Tugo6-NZBKCQsMf3HaEGBjTVJs_jcK8-TRXvaKe-7ZMaQj8VfBdYkssbu0NKDDhjJ-GtiseaDVWt7dcH0cfwxgFUHpQh7FoCrjFJ6h6ZEpMF6xmujs4qMpPz8aaI4', }, alg: 'RS256', }, signing: { protected: { alg: 'RS256', kid: 'bilbo.baggins@hobbiton.example', }, }, output: { compact: 'eyJhbGciOiJSUzI1NiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhbXBsZSJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4.MRjdkly7_-oTPTS3AXP41iQIGKa80A0ZmTuV5MEaHoxnW2e5CZ5NlKtainoFmKZopdHM1O2U4mwzJdQx996ivp83xuglII7PNDi84wnB-BDkoBwA78185hX-Es4JIwmDLJK3lfWRa-XtL0RnltuYv746iYTh_qHRD68BNt1uSNCrUCTJDt5aAE6x8wW1Kt9eRo4QPocSadnHXFxnt8Is9UzpERV0ePPQdLuW3IS_de3xyIrDaLGdjluPxUAhb6L2aXic1U12podGU0KLUQSE_oI-ZnmKJ3F4uOZDnd6QZWJushZ41Axf_fcIe8u9ipH84ogoree7vjbU5y18kDquDg', json: { payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4', signatures: [ { protected: 'eyJhbGciOiJSUzI1NiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhbXBsZSJ9', signature: 'MRjdkly7_-oTPTS3AXP41iQIGKa80A0ZmTuV5MEaHoxnW2e5CZ5NlKtainoFmKZopdHM1O2U4mwzJdQx996ivp83xuglII7PNDi84wnB-BDkoBwA78185hX-Es4JIwmDLJK3lfWRa-XtL0RnltuYv746iYTh_qHRD68BNt1uSNCrUCTJDt5aAE6x8wW1Kt9eRo4QPocSadnHXFxnt8Is9UzpERV0ePPQdLuW3IS_de3xyIrDaLGdjluPxUAhb6L2aXic1U12podGU0KLUQSE_oI-ZnmKJ3F4uOZDnd6QZWJushZ41Axf_fcIe8u9ipH84ogoree7vjbU5y18kDquDg', }, ], }, json_flat: { payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4', protected: 'eyJhbGciOiJSUzI1NiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhbXBsZSJ9', signature: 'MRjdkly7_-oTPTS3AXP41iQIGKa80A0ZmTuV5MEaHoxnW2e5CZ5NlKtainoFmKZopdHM1O2U4mwzJdQx996ivp83xuglII7PNDi84wnB-BDkoBwA78185hX-Es4JIwmDLJK3lfWRa-XtL0RnltuYv746iYTh_qHRD68BNt1uSNCrUCTJDt5aAE6x8wW1Kt9eRo4QPocSadnHXFxnt8Is9UzpERV0ePPQdLuW3IS_de3xyIrDaLGdjluPxUAhb6L2aXic1U12podGU0KLUQSE_oI-ZnmKJ3F4uOZDnd6QZWJushZ41Axf_fcIe8u9ipH84ogoree7vjbU5y18kDquDg', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc8037#appendix-A.4 - Ed25519 Signing', reproducible: true, input: { payload: 'Example of Ed25519 signing', key: { kty: 'OKP', ext: false, crv: 'Ed25519', d: 'nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A', x: '11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo', }, alg: 'EdDSA', }, signing: { protected: { alg: 'EdDSA', }, }, output: { compact: 'eyJhbGciOiJFZERTQSJ9.RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc.hgyY0il_MGCjP0JzlnLWG1PPOt7-09PGcvMg3AIbQR6dWbhijcNR4ki4iylGjg5BhVsPt9g7sVvpAr_MuM0KAg', json: { payload: 'RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc', signatures: [ { protected: 'eyJhbGciOiJFZERTQSJ9', signature: 'hgyY0il_MGCjP0JzlnLWG1PPOt7-09PGcvMg3AIbQR6dWbhijcNR4ki4iylGjg5BhVsPt9g7sVvpAr_MuM0KAg', }, ], }, json_flat: { payload: 'RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc', protected: 'eyJhbGciOiJFZERTQSJ9', signature: 'hgyY0il_MGCjP0JzlnLWG1PPOt7-09PGcvMg3AIbQR6dWbhijcNR4ki4iylGjg5BhVsPt9g7sVvpAr_MuM0KAg', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-4.2 - RSA-PSS Signature', input: { payload: "It’s a dangerous business, Frodo, going out your door. You step onto the road, and if you don't keep your feet, there’s no knowing where you might be swept off to.", key: { kty: 'RSA', ext: false, kid: 'bilbo.baggins@hobbiton.example', use: 'sig', n: 'n4EPtAOCc9AlkeQHPzHStgAbgs7bTZLwUBZdR8_KuKPEHLd4rHVTeT-O-XV2jRojdNhxJWTDvNd7nqQ0VEiZQHz_AJmSCpMaJMRBSFKrKb2wqVwGU_NsYOYL-QtiWN2lbzcEe6XC0dApr5ydQLrHqkHHig3RBordaZ6Aj-oBHqFEHYpPe7Tpe-OfVfHd1E6cS6M1FZcD1NNLYD5lFHpPI9bTwJlsde3uhGqC0ZCuEHg8lhzwOHrtIQbS0FVbb9k3-tVTU4fg_3L_vniUFAKwuCLqKnS2BYwdq_mzSnbLY7h_qixoR7jig3__kRhuaxwUkRz5iaiQkqgc5gHdrNP5zw', e: 'AQAB', d: 'bWUC9B-EFRIo8kpGfh0ZuyGPvMNKvYWNtB_ikiH9k20eT-O1q_I78eiZkpXxXQ0UTEs2LsNRS-8uJbvQ-A1irkwMSMkK1J3XTGgdrhCku9gRldY7sNA_AKZGh-Q661_42rINLRCe8W-nZ34ui_qOfkLnK9QWDDqpaIsA-bMwWWSDFu2MUBYwkHTMEzLYGqOe04noqeq1hExBTHBOBdkMXiuFhUq1BU6l-DqEiWxqg82sXt2h-LMnT3046AOYJoRioz75tSUQfGCshWTBnP5uDjd18kKhyv07lhfSJdrPdM5Plyl21hsFf4L_mHCuoFau7gdsPfHPxxjVOcOpBrQzwQ', p: '3Slxg_DwTXJcb6095RoXygQCAZ5RnAvZlno1yhHtnUex_fp7AZ_9nRaO7HX_-SFfGQeutao2TDjDAWU4Vupk8rw9JR0AzZ0N2fvuIAmr_WCsmGpeNqQnev1T7IyEsnh8UMt-n5CafhkikzhEsrmndH6LxOrvRJlsPp6Zv8bUq0k', q: 'uKE2dh-cTf6ERF4k4e_jy78GfPYUIaUyoSSJuBzp3Cubk3OCqs6grT8bR_cu0Dm1MZwWmtdqDyI95HrUeq3MP15vMMON8lHTeZu2lmKvwqW7anV5UzhM1iZ7z4yMkuUwFWoBvyY898EXvRD-hdqRxHlSqAZ192zB3pVFJ0s7pFc', dp: 'B8PVvXkvJrj2L-GYQ7v3y9r6Kw5g9SahXBwsWUzp19TVlgI-YV85q1NIb1rxQtD-IsXXR3-TanevuRPRt5OBOdiMGQp8pbt26gljYfKU_E9xn-RULHz0-ed9E9gXLKD4VGngpz-PfQ_q29pk5xWHoJp009Qf1HvChixRX59ehik', dq: 'CLDmDGduhylc9o7r84rEUVn7pzQ6PF83Y-iBZx5NT-TpnOZKF1pErAMVeKzFEl41DlHHqqBLSM0W1sOFbwTxYWZDm6sI6og5iTbwQGIC3gnJKbi_7k_vJgGHwHxgPaX2PnvP-zyEkDERuf-ry4c_Z11Cq9AqC2yeL6kdKT1cYF8', qi: '3PiqvXQN0zwMeE-sBvZgi289XP9XCQF3VWqPzMKnIgQp7_Tugo6-NZBKCQsMf3HaEGBjTVJs_jcK8-TRXvaKe-7ZMaQj8VfBdYkssbu0NKDDhjJ-GtiseaDVWt7dcH0cfwxgFUHpQh7FoCrjFJ6h6ZEpMF6xmujs4qMpPz8aaI4', }, alg: 'PS384', }, signing: { protected: { alg: 'PS384', kid: 'bilbo.baggins@hobbiton.example', }, }, output: { compact: 'eyJhbGciOiJQUzM4NCIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhbXBsZSJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4.cu22eBqkYDKgIlTpzDXGvaFfz6WGoz7fUDcfT0kkOy42miAh2qyBzk1xEsnk2IpN6-tPid6VrklHkqsGqDqHCdP6O8TTB5dDDItllVo6_1OLPpcbUrhiUSMxbbXUvdvWXzg-UD8biiReQFlfz28zGWVsdiNAUf8ZnyPEgVFn442ZdNqiVJRmBqrYRXe8P_ijQ7p8Vdz0TTrxUeT3lm8d9shnr2lfJT8ImUjvAA2Xez2Mlp8cBE5awDzT0qI0n6uiP1aCN_2_jLAeQTlqRHtfa64QQSUmFAAjVKPbByi7xho0uTOcbH510a6GYmJUAfmWjwZ6oD4ifKo8DYM-X72Eaw', json: { payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4', signatures: [ { protected: 'eyJhbGciOiJQUzM4NCIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhbXBsZSJ9', signature: 'cu22eBqkYDKgIlTpzDXGvaFfz6WGoz7fUDcfT0kkOy42miAh2qyBzk1xEsnk2IpN6-tPid6VrklHkqsGqDqHCdP6O8TTB5dDDItllVo6_1OLPpcbUrhiUSMxbbXUvdvWXzg-UD8biiReQFlfz28zGWVsdiNAUf8ZnyPEgVFn442ZdNqiVJRmBqrYRXe8P_ijQ7p8Vdz0TTrxUeT3lm8d9shnr2lfJT8ImUjvAA2Xez2Mlp8cBE5awDzT0qI0n6uiP1aCN_2_jLAeQTlqRHtfa64QQSUmFAAjVKPbByi7xho0uTOcbH510a6GYmJUAfmWjwZ6oD4ifKo8DYM-X72Eaw', }, ], }, json_flat: { payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4', protected: 'eyJhbGciOiJQUzM4NCIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhbXBsZSJ9', signature: 'cu22eBqkYDKgIlTpzDXGvaFfz6WGoz7fUDcfT0kkOy42miAh2qyBzk1xEsnk2IpN6-tPid6VrklHkqsGqDqHCdP6O8TTB5dDDItllVo6_1OLPpcbUrhiUSMxbbXUvdvWXzg-UD8biiReQFlfz28zGWVsdiNAUf8ZnyPEgVFn442ZdNqiVJRmBqrYRXe8P_ijQ7p8Vdz0TTrxUeT3lm8d9shnr2lfJT8ImUjvAA2Xez2Mlp8cBE5awDzT0qI0n6uiP1aCN_2_jLAeQTlqRHtfa64QQSUmFAAjVKPbByi7xho0uTOcbH510a6GYmJUAfmWjwZ6oD4ifKo8DYM-X72Eaw', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-4.3 - ECDSA Signature', input: { payload: "It’s a dangerous business, Frodo, going out your door. You step onto the road, and if you don't keep your feet, there’s no knowing where you might be swept off to.", key: { kty: 'EC', ext: false, kid: 'bilbo.baggins@hobbiton.example', use: 'sig', crv: 'P-521', x: 'AHKZLLOsCOzz5cY97ewNUajB957y-C-U88c3v13nmGZx6sYl_oJXu9A5RkTKqjqvjyekWF-7ytDyRXYgCF5cj0Kt', y: 'AdymlHvOiLxXkEhayXQnNCvDX4h9htZaCJN34kfmC6pV5OhQHiraVySsUdaQkAgDPrwQrJmbnX9cwlGfP-HqHZR1', d: 'AAhRON2r9cqXX1hg-RoI6R1tX5p2rUAYdmpHZoC1XNM56KtscrX6zbKipQrCW9CGZH3T4ubpnoTKLDYJ_fF3_rJt', }, alg: 'ES512', }, signing: { protected: { alg: 'ES512', kid: 'bilbo.baggins@hobbiton.example', }, }, output: { compact: 'eyJhbGciOiJFUzUxMiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhbXBsZSJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4.AE_R_YZCChjn4791jSQCrdPZCNYqHXCTZH0-JZGYNlaAjP2kqaluUIIUnC9qvbu9Plon7KRTzoNEuT4Va2cmL1eJAQy3mtPBu_u_sDDyYjnAMDxXPn7XrT0lw-kvAD890jl8e2puQens_IEKBpHABlsbEPX6sFY8OcGDqoRuBomu9xQ2', json: { payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4', signatures: [ { protected: 'eyJhbGciOiJFUzUxMiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhbXBsZSJ9', signature: 'AE_R_YZCChjn4791jSQCrdPZCNYqHXCTZH0-JZGYNlaAjP2kqaluUIIUnC9qvbu9Plon7KRTzoNEuT4Va2cmL1eJAQy3mtPBu_u_sDDyYjnAMDxXPn7XrT0lw-kvAD890jl8e2puQens_IEKBpHABlsbEPX6sFY8OcGDqoRuBomu9xQ2', }, ], }, json_flat: { payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4', protected: 'eyJhbGciOiJFUzUxMiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhbXBsZSJ9', signature: 'AE_R_YZCChjn4791jSQCrdPZCNYqHXCTZH0-JZGYNlaAjP2kqaluUIIUnC9qvbu9Plon7KRTzoNEuT4Va2cmL1eJAQy3mtPBu_u_sDDyYjnAMDxXPn7XrT0lw-kvAD890jl8e2puQens_IEKBpHABlsbEPX6sFY8OcGDqoRuBomu9xQ2', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-4.4 - HMAC-SHA2 Integrity Protection', reproducible: true, input: { payload: "It’s a dangerous business, Frodo, going out your door. You step onto the road, and if you don't keep your feet, there’s no knowing where you might be swept off to.", key: { kty: 'oct', ext: false, kid: '018c0ae5-4d9b-471b-bfd6-eef314bc7037', use: 'sig', alg: 'HS256', k: 'hJtXIZ2uSN5kbQfbtTNWbpdmhkV8FJG-Onbc6mxCcYg', }, alg: 'HS256', }, signing: { protected: { alg: 'HS256', kid: '018c0ae5-4d9b-471b-bfd6-eef314bc7037', }, }, output: { compact: 'eyJhbGciOiJIUzI1NiIsImtpZCI6IjAxOGMwYWU1LTRkOWItNDcxYi1iZmQ2LWVlZjMxNGJjNzAzNyJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4.s0h6KThzkfBBBkLspW1h84VsJZFTsPPqMDA7g1Md7p0', json: { payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4', signatures: [ { protected: 'eyJhbGciOiJIUzI1NiIsImtpZCI6IjAxOGMwYWU1LTRkOWItNDcxYi1iZmQ2LWVlZjMxNGJjNzAzNyJ9', signature: 's0h6KThzkfBBBkLspW1h84VsJZFTsPPqMDA7g1Md7p0', }, ], }, json_flat: { payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4', protected: 'eyJhbGciOiJIUzI1NiIsImtpZCI6IjAxOGMwYWU1LTRkOWItNDcxYi1iZmQ2LWVlZjMxNGJjNzAzNyJ9', signature: 's0h6KThzkfBBBkLspW1h84VsJZFTsPPqMDA7g1Md7p0', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-4.6 - Protecting Specific Header Fields', reproducible: true, input: { payload: "It’s a dangerous business, Frodo, going out your door. You step onto the road, and if you don't keep your feet, there’s no knowing where you might be swept off to.", key: { kty: 'oct', ext: false, kid: '018c0ae5-4d9b-471b-bfd6-eef314bc7037', use: 'sig', alg: 'HS256', k: 'hJtXIZ2uSN5kbQfbtTNWbpdmhkV8FJG-Onbc6mxCcYg', }, alg: 'HS256', }, signing: { protected: { alg: 'HS256', }, unprotected: { kid: '018c0ae5-4d9b-471b-bfd6-eef314bc7037', }, }, output: { json: { payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4', signatures: [ { protected: 'eyJhbGciOiJIUzI1NiJ9', header: { kid: '018c0ae5-4d9b-471b-bfd6-eef314bc7037', }, signature: 'bWUSVaxorn7bEF1djytBd0kHv70Ly5pvbomzMWSOr20', }, ], }, json_flat: { payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4', protected: 'eyJhbGciOiJIUzI1NiJ9', header: { kid: '018c0ae5-4d9b-471b-bfd6-eef314bc7037', }, signature: 'bWUSVaxorn7bEF1djytBd0kHv70Ly5pvbomzMWSOr20', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7520#section-4.7 - Protecting Content Only', reproducible: true, input: { payload: "It’s a dangerous business, Frodo, going out your door. You step onto the road, and if you don't keep your feet, there’s no knowing where you might be swept off to.", key: { kty: 'oct', ext: false, kid: '018c0ae5-4d9b-471b-bfd6-eef314bc7037', use: 'sig', alg: 'HS256', k: 'hJtXIZ2uSN5kbQfbtTNWbpdmhkV8FJG-Onbc6mxCcYg', }, alg: 'HS256', }, signing: { unprotected: { alg: 'HS256', kid: '018c0ae5-4d9b-471b-bfd6-eef314bc7037', }, }, output: { json: { payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4', signatures: [ { header: { alg: 'HS256', kid: '018c0ae5-4d9b-471b-bfd6-eef314bc7037', }, signature: 'xuLifqLGiblpv9zBpuZczWhNj1gARaLV3UxvxhJxZuk', }, ], }, json_flat: { payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4', header: { alg: 'HS256', kid: '018c0ae5-4d9b-471b-bfd6-eef314bc7037', }, signature: 'xuLifqLGiblpv9zBpuZczWhNj1gARaLV3UxvxhJxZuk', }, }, }, { title: 'https://www.rfc-editor.org/rfc/rfc7797#section-4.1 - { "b64": false } JSON only', reproducible: true, input: { payload: '$.02', key: { kty: 'oct', ext: false, alg: 'HS256', k: 'AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow', }, alg: 'HS256', }, signing: { protected: { alg: 'HS256', b64: false, crit: ['b64'], }, }, output: { json: { payload: '$.02', signatures: [ { protected: 'eyJhbGciOiJIUzI1NiIsImI2NCI6ZmFsc2UsImNyaXQiOlsiYjY0Il19', signature: 'A5dxf2s96_n5FLueVuW1Z_vh161FwXZC4YLPff6dmDY', }, ], }, json_flat: { payload: '$.02', protected: 'eyJhbGciOiJIUzI1NiIsImI2NCI6ZmFsc2UsImNyaXQiOlsiYjY0Il19', signature: 'A5dxf2s96_n5FLueVuW1Z_vh161FwXZC4YLPff6dmDY', }, }, }, ] jose-4.11.4/dist/000077500000000000000000000000001437043056600135145ustar00rootroot00000000000000jose-4.11.4/dist/browser/000077500000000000000000000000001437043056600151775ustar00rootroot00000000000000jose-4.11.4/dist/browser/index.bundle.js000066400000000000000000003371531437043056600201300ustar00rootroot00000000000000var __defProp = Object.defineProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; // dist/browser/runtime/webcrypto.js var webcrypto_default = crypto; var isCryptoKey = (key) => key instanceof CryptoKey; // dist/browser/runtime/digest.js var digest = async (algorithm, data) => { const subtleDigest = `SHA-${algorithm.slice(-3)}`; return new Uint8Array(await webcrypto_default.subtle.digest(subtleDigest, data)); }; var digest_default = digest; // dist/browser/lib/buffer_utils.js var encoder = new TextEncoder(); var decoder = new TextDecoder(); var MAX_INT32 = 2 ** 32; function concat(...buffers) { const size = buffers.reduce((acc, { length }) => acc + length, 0); const buf = new Uint8Array(size); let i = 0; buffers.forEach((buffer) => { buf.set(buffer, i); i += buffer.length; }); return buf; } function p2s(alg, p2sInput) { return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput); } function writeUInt32BE(buf, value, offset) { if (value < 0 || value >= MAX_INT32) { throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); } buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset); } function uint64be(value) { const high = Math.floor(value / MAX_INT32); const low = value % MAX_INT32; const buf = new Uint8Array(8); writeUInt32BE(buf, high, 0); writeUInt32BE(buf, low, 4); return buf; } function uint32be(value) { const buf = new Uint8Array(4); writeUInt32BE(buf, value); return buf; } function lengthAndInput(input) { return concat(uint32be(input.length), input); } async function concatKdf(secret, bits, value) { const iterations = Math.ceil((bits >> 3) / 32); const res = new Uint8Array(iterations * 32); for (let iter = 0; iter < iterations; iter++) { const buf = new Uint8Array(4 + secret.length + value.length); buf.set(uint32be(iter + 1)); buf.set(secret, 4); buf.set(value, 4 + secret.length); res.set(await digest_default("sha256", buf), iter * 32); } return res.slice(0, bits >> 3); } // dist/browser/runtime/base64url.js var encodeBase64 = (input) => { let unencoded = input; if (typeof unencoded === "string") { unencoded = encoder.encode(unencoded); } const CHUNK_SIZE = 32768; const arr = []; for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) { arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE))); } return btoa(arr.join("")); }; var encode = (input) => { return encodeBase64(input).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); }; var decodeBase64 = (encoded) => { const binary = atob(encoded); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) { bytes[i] = binary.charCodeAt(i); } return bytes; }; var decode = (input) => { let encoded = input; if (encoded instanceof Uint8Array) { encoded = decoder.decode(encoded); } encoded = encoded.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""); try { return decodeBase64(encoded); } catch (_a) { throw new TypeError("The input to be decoded is not correctly encoded."); } }; // dist/browser/util/errors.js var errors_exports = {}; __export(errors_exports, { JOSEAlgNotAllowed: () => JOSEAlgNotAllowed, JOSEError: () => JOSEError, JOSENotSupported: () => JOSENotSupported, JWEDecryptionFailed: () => JWEDecryptionFailed, JWEInvalid: () => JWEInvalid, JWKInvalid: () => JWKInvalid, JWKSInvalid: () => JWKSInvalid, JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys, JWKSNoMatchingKey: () => JWKSNoMatchingKey, JWKSTimeout: () => JWKSTimeout, JWSInvalid: () => JWSInvalid, JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed, JWTClaimValidationFailed: () => JWTClaimValidationFailed, JWTExpired: () => JWTExpired, JWTInvalid: () => JWTInvalid }); var JOSEError = class extends Error { static get code() { return "ERR_JOSE_GENERIC"; } constructor(message2) { var _a; super(message2); this.code = "ERR_JOSE_GENERIC"; this.name = this.constructor.name; (_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, this, this.constructor); } }; var JWTClaimValidationFailed = class extends JOSEError { static get code() { return "ERR_JWT_CLAIM_VALIDATION_FAILED"; } constructor(message2, claim = "unspecified", reason = "unspecified") { super(message2); this.code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; this.claim = claim; this.reason = reason; } }; var JWTExpired = class extends JOSEError { static get code() { return "ERR_JWT_EXPIRED"; } constructor(message2, claim = "unspecified", reason = "unspecified") { super(message2); this.code = "ERR_JWT_EXPIRED"; this.claim = claim; this.reason = reason; } }; var JOSEAlgNotAllowed = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JOSE_ALG_NOT_ALLOWED"; } static get code() { return "ERR_JOSE_ALG_NOT_ALLOWED"; } }; var JOSENotSupported = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JOSE_NOT_SUPPORTED"; } static get code() { return "ERR_JOSE_NOT_SUPPORTED"; } }; var JWEDecryptionFailed = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWE_DECRYPTION_FAILED"; this.message = "decryption operation failed"; } static get code() { return "ERR_JWE_DECRYPTION_FAILED"; } }; var JWEInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWE_INVALID"; } static get code() { return "ERR_JWE_INVALID"; } }; var JWSInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWS_INVALID"; } static get code() { return "ERR_JWS_INVALID"; } }; var JWTInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWT_INVALID"; } static get code() { return "ERR_JWT_INVALID"; } }; var JWKInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWK_INVALID"; } static get code() { return "ERR_JWK_INVALID"; } }; var JWKSInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWKS_INVALID"; } static get code() { return "ERR_JWKS_INVALID"; } }; var JWKSNoMatchingKey = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWKS_NO_MATCHING_KEY"; this.message = "no applicable key found in the JSON Web Key Set"; } static get code() { return "ERR_JWKS_NO_MATCHING_KEY"; } }; var JWKSMultipleMatchingKeys = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; this.message = "multiple matching keys found in the JSON Web Key Set"; } static get code() { return "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; } }; var JWKSTimeout = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWKS_TIMEOUT"; this.message = "request timed out"; } static get code() { return "ERR_JWKS_TIMEOUT"; } }; var JWSSignatureVerificationFailed = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; this.message = "signature verification failed"; } static get code() { return "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; } }; // dist/browser/runtime/random.js var random_default = webcrypto_default.getRandomValues.bind(webcrypto_default); // dist/browser/lib/iv.js function bitLength(alg) { switch (alg) { case "A128GCM": case "A128GCMKW": case "A192GCM": case "A192GCMKW": case "A256GCM": case "A256GCMKW": return 96; case "A128CBC-HS256": case "A192CBC-HS384": case "A256CBC-HS512": return 128; default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); } } var iv_default = (alg) => random_default(new Uint8Array(bitLength(alg) >> 3)); // dist/browser/lib/check_iv_length.js var checkIvLength = (enc, iv) => { if (iv.length << 3 !== bitLength(enc)) { throw new JWEInvalid("Invalid Initialization Vector length"); } }; var check_iv_length_default = checkIvLength; // dist/browser/runtime/check_cek_length.js var checkCekLength = (cek, expected) => { const actual = cek.byteLength << 3; if (actual !== expected) { throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); } }; var check_cek_length_default = checkCekLength; // dist/browser/runtime/timing_safe_equal.js var timingSafeEqual = (a, b) => { if (!(a instanceof Uint8Array)) { throw new TypeError("First argument must be a buffer"); } if (!(b instanceof Uint8Array)) { throw new TypeError("Second argument must be a buffer"); } if (a.length !== b.length) { throw new TypeError("Input buffers must have the same length"); } const len = a.length; let out = 0; let i = -1; while (++i < len) { out |= a[i] ^ b[i]; } return out === 0; }; var timing_safe_equal_default = timingSafeEqual; // dist/browser/runtime/env.js function isCloudflareWorkers() { return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel"; } // dist/browser/lib/crypto_key.js function unusable(name, prop = "algorithm.name") { return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); } function isAlgorithm(algorithm, name) { return algorithm.name === name; } function getHashLength(hash) { return parseInt(hash.name.slice(4), 10); } function getNamedCurve(alg) { switch (alg) { case "ES256": return "P-256"; case "ES384": return "P-384"; case "ES512": return "P-521"; default: throw new Error("unreachable"); } } function checkUsage(key, usages) { if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { let msg = "CryptoKey does not support this operation, its usages must include "; if (usages.length > 2) { const last = usages.pop(); msg += `one of ${usages.join(", ")}, or ${last}.`; } else if (usages.length === 2) { msg += `one of ${usages[0]} or ${usages[1]}.`; } else { msg += `${usages[0]}.`; } throw new TypeError(msg); } } function checkSigCryptoKey(key, alg, ...usages) { switch (alg) { case "HS256": case "HS384": case "HS512": { if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC"); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); break; } case "RS256": case "RS384": case "RS512": { if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5"); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); break; } case "PS256": case "PS384": case "PS512": { if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS"); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); break; } case "EdDSA": { if (key.algorithm.name !== "Ed25519" && key.algorithm.name !== "Ed448") { if (isCloudflareWorkers()) { if (isAlgorithm(key.algorithm, "NODE-ED25519")) break; throw unusable("Ed25519, Ed448, or NODE-ED25519"); } throw unusable("Ed25519 or Ed448"); } break; } case "ES256": case "ES384": case "ES512": { if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA"); const expected = getNamedCurve(alg); const actual = key.algorithm.namedCurve; if (actual !== expected) throw unusable(expected, "algorithm.namedCurve"); break; } default: throw new TypeError("CryptoKey does not support this operation"); } checkUsage(key, usages); } function checkEncCryptoKey(key, alg, ...usages) { switch (alg) { case "A128GCM": case "A192GCM": case "A256GCM": { if (!isAlgorithm(key.algorithm, "AES-GCM")) throw unusable("AES-GCM"); const expected = parseInt(alg.slice(1, 4), 10); const actual = key.algorithm.length; if (actual !== expected) throw unusable(expected, "algorithm.length"); break; } case "A128KW": case "A192KW": case "A256KW": { if (!isAlgorithm(key.algorithm, "AES-KW")) throw unusable("AES-KW"); const expected = parseInt(alg.slice(1, 4), 10); const actual = key.algorithm.length; if (actual !== expected) throw unusable(expected, "algorithm.length"); break; } case "ECDH": { switch (key.algorithm.name) { case "ECDH": case "X25519": case "X448": break; default: throw unusable("ECDH, X25519, or X448"); } break; } case "PBES2-HS256+A128KW": case "PBES2-HS384+A192KW": case "PBES2-HS512+A256KW": if (!isAlgorithm(key.algorithm, "PBKDF2")) throw unusable("PBKDF2"); break; case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": { if (!isAlgorithm(key.algorithm, "RSA-OAEP")) throw unusable("RSA-OAEP"); const expected = parseInt(alg.slice(9), 10) || 1; const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); break; } default: throw new TypeError("CryptoKey does not support this operation"); } checkUsage(key, usages); } // dist/browser/lib/invalid_key_input.js function message(msg, actual, ...types2) { if (types2.length > 2) { const last = types2.pop(); msg += `one of type ${types2.join(", ")}, or ${last}.`; } else if (types2.length === 2) { msg += `one of type ${types2[0]} or ${types2[1]}.`; } else { msg += `of type ${types2[0]}.`; } if (actual == null) { msg += ` Received ${actual}`; } else if (typeof actual === "function" && actual.name) { msg += ` Received function ${actual.name}`; } else if (typeof actual === "object" && actual != null) { if (actual.constructor && actual.constructor.name) { msg += ` Received an instance of ${actual.constructor.name}`; } } return msg; } var invalid_key_input_default = (actual, ...types2) => { return message("Key must be ", actual, ...types2); }; function withAlg(alg, actual, ...types2) { return message(`Key for the ${alg} algorithm must be `, actual, ...types2); } // dist/browser/runtime/is_key_like.js var is_key_like_default = (key) => { return isCryptoKey(key); }; var types = ["CryptoKey"]; // dist/browser/runtime/decrypt.js async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) { if (!(cek instanceof Uint8Array)) { throw new TypeError(invalid_key_input_default(cek, "Uint8Array")); } const keySize = parseInt(enc.slice(1, 4), 10); const encKey = await webcrypto_default.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["decrypt"]); const macKey = await webcrypto_default.subtle.importKey("raw", cek.subarray(0, keySize >> 3), { hash: `SHA-${keySize << 1}`, name: "HMAC" }, false, ["sign"]); const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); const expectedTag = new Uint8Array((await webcrypto_default.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)); let macCheckPassed; try { macCheckPassed = timing_safe_equal_default(tag, expectedTag); } catch (_a) { } if (!macCheckPassed) { throw new JWEDecryptionFailed(); } let plaintext; try { plaintext = new Uint8Array(await webcrypto_default.subtle.decrypt({ iv, name: "AES-CBC" }, encKey, ciphertext)); } catch (_b) { } if (!plaintext) { throw new JWEDecryptionFailed(); } return plaintext; } async function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) { let encKey; if (cek instanceof Uint8Array) { encKey = await webcrypto_default.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]); } else { checkEncCryptoKey(cek, enc, "decrypt"); encKey = cek; } try { return new Uint8Array(await webcrypto_default.subtle.decrypt({ additionalData: aad, iv, name: "AES-GCM", tagLength: 128 }, encKey, concat(ciphertext, tag))); } catch (_a) { throw new JWEDecryptionFailed(); } } var decrypt = async (enc, cek, ciphertext, iv, tag, aad) => { if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { throw new TypeError(invalid_key_input_default(cek, ...types, "Uint8Array")); } check_iv_length_default(enc, iv); switch (enc) { case "A128CBC-HS256": case "A192CBC-HS384": case "A256CBC-HS512": if (cek instanceof Uint8Array) check_cek_length_default(cek, parseInt(enc.slice(-3), 10)); return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad); case "A128GCM": case "A192GCM": case "A256GCM": if (cek instanceof Uint8Array) check_cek_length_default(cek, parseInt(enc.slice(1, 4), 10)); return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad); default: throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm"); } }; var decrypt_default = decrypt; // dist/browser/runtime/zlib.js var inflate = async () => { throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.'); }; var deflate = async () => { throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.'); }; // dist/browser/lib/is_disjoint.js var isDisjoint = (...headers) => { const sources = headers.filter(Boolean); if (sources.length === 0 || sources.length === 1) { return true; } let acc; for (const header of sources) { const parameters = Object.keys(header); if (!acc || acc.size === 0) { acc = new Set(parameters); continue; } for (const parameter of parameters) { if (acc.has(parameter)) { return false; } acc.add(parameter); } } return true; }; var is_disjoint_default = isDisjoint; // dist/browser/lib/is_object.js function isObjectLike(value) { return typeof value === "object" && value !== null; } function isObject(input) { if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") { return false; } if (Object.getPrototypeOf(input) === null) { return true; } let proto = input; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(input) === proto; } // dist/browser/runtime/bogus.js var bogusWebCrypto = [ { hash: "SHA-256", name: "HMAC" }, true, ["sign"] ]; var bogus_default = bogusWebCrypto; // dist/browser/runtime/aeskw.js function checkKeySize(key, alg) { if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) { throw new TypeError(`Invalid key size for alg: ${alg}`); } } function getCryptoKey(key, alg, usage) { if (isCryptoKey(key)) { checkEncCryptoKey(key, alg, usage); return key; } if (key instanceof Uint8Array) { return webcrypto_default.subtle.importKey("raw", key, "AES-KW", true, [usage]); } throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array")); } var wrap = async (alg, key, cek) => { const cryptoKey = await getCryptoKey(key, alg, "wrapKey"); checkKeySize(cryptoKey, alg); const cryptoKeyCek = await webcrypto_default.subtle.importKey("raw", cek, ...bogus_default); return new Uint8Array(await webcrypto_default.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW")); }; var unwrap = async (alg, key, encryptedKey) => { const cryptoKey = await getCryptoKey(key, alg, "unwrapKey"); checkKeySize(cryptoKey, alg); const cryptoKeyCek = await webcrypto_default.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", ...bogus_default); return new Uint8Array(await webcrypto_default.subtle.exportKey("raw", cryptoKeyCek)); }; // dist/browser/runtime/ecdhes.js async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) { if (!isCryptoKey(publicKey)) { throw new TypeError(invalid_key_input_default(publicKey, ...types)); } checkEncCryptoKey(publicKey, "ECDH"); if (!isCryptoKey(privateKey)) { throw new TypeError(invalid_key_input_default(privateKey, ...types)); } checkEncCryptoKey(privateKey, "ECDH", "deriveBits"); const value = concat(lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength)); let length; if (publicKey.algorithm.name === "X25519") { length = 256; } else if (publicKey.algorithm.name === "X448") { length = 448; } else { length = Math.ceil(parseInt(publicKey.algorithm.namedCurve.substr(-3), 10) / 8) << 3; } const sharedSecret = new Uint8Array(await webcrypto_default.subtle.deriveBits({ name: publicKey.algorithm.name, public: publicKey }, privateKey, length)); return concatKdf(sharedSecret, keyLength, value); } async function generateEpk(key) { if (!isCryptoKey(key)) { throw new TypeError(invalid_key_input_default(key, ...types)); } return webcrypto_default.subtle.generateKey(key.algorithm, true, ["deriveBits"]); } function ecdhAllowed(key) { if (!isCryptoKey(key)) { throw new TypeError(invalid_key_input_default(key, ...types)); } return ["P-256", "P-384", "P-521"].includes(key.algorithm.namedCurve) || key.algorithm.name === "X25519" || key.algorithm.name === "X448"; } // dist/browser/lib/check_p2s.js function checkP2s(p2s2) { if (!(p2s2 instanceof Uint8Array) || p2s2.length < 8) { throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets"); } } // dist/browser/runtime/pbes2kw.js function getCryptoKey2(key, alg) { if (key instanceof Uint8Array) { return webcrypto_default.subtle.importKey("raw", key, "PBKDF2", false, ["deriveBits"]); } if (isCryptoKey(key)) { checkEncCryptoKey(key, alg, "deriveBits", "deriveKey"); return key; } throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array")); } async function deriveKey2(p2s2, alg, p2c, key) { checkP2s(p2s2); const salt = p2s(alg, p2s2); const keylen = parseInt(alg.slice(13, 16), 10); const subtleAlg = { hash: `SHA-${alg.slice(8, 11)}`, iterations: p2c, name: "PBKDF2", salt }; const wrapAlg = { length: keylen, name: "AES-KW" }; const cryptoKey = await getCryptoKey2(key, alg); if (cryptoKey.usages.includes("deriveBits")) { return new Uint8Array(await webcrypto_default.subtle.deriveBits(subtleAlg, cryptoKey, keylen)); } if (cryptoKey.usages.includes("deriveKey")) { return webcrypto_default.subtle.deriveKey(subtleAlg, cryptoKey, wrapAlg, false, ["wrapKey", "unwrapKey"]); } throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"'); } var encrypt = async (alg, key, cek, p2c = 2048, p2s2 = random_default(new Uint8Array(16))) => { const derived = await deriveKey2(p2s2, alg, p2c, key); const encryptedKey = await wrap(alg.slice(-6), derived, cek); return { encryptedKey, p2c, p2s: encode(p2s2) }; }; var decrypt2 = async (alg, key, encryptedKey, p2c, p2s2) => { const derived = await deriveKey2(p2s2, alg, p2c, key); return unwrap(alg.slice(-6), derived, encryptedKey); }; // dist/browser/runtime/subtle_rsaes.js function subtleRsaEs(alg) { switch (alg) { case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": return "RSA-OAEP"; default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } } // dist/browser/runtime/check_key_length.js var check_key_length_default = (alg, key) => { if (alg.startsWith("RS") || alg.startsWith("PS")) { const { modulusLength } = key.algorithm; if (typeof modulusLength !== "number" || modulusLength < 2048) { throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); } } }; // dist/browser/runtime/rsaes.js var encrypt2 = async (alg, key, cek) => { if (!isCryptoKey(key)) { throw new TypeError(invalid_key_input_default(key, ...types)); } checkEncCryptoKey(key, alg, "encrypt", "wrapKey"); check_key_length_default(alg, key); if (key.usages.includes("encrypt")) { return new Uint8Array(await webcrypto_default.subtle.encrypt(subtleRsaEs(alg), key, cek)); } if (key.usages.includes("wrapKey")) { const cryptoKeyCek = await webcrypto_default.subtle.importKey("raw", cek, ...bogus_default); return new Uint8Array(await webcrypto_default.subtle.wrapKey("raw", cryptoKeyCek, key, subtleRsaEs(alg))); } throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation'); }; var decrypt3 = async (alg, key, encryptedKey) => { if (!isCryptoKey(key)) { throw new TypeError(invalid_key_input_default(key, ...types)); } checkEncCryptoKey(key, alg, "decrypt", "unwrapKey"); check_key_length_default(alg, key); if (key.usages.includes("decrypt")) { return new Uint8Array(await webcrypto_default.subtle.decrypt(subtleRsaEs(alg), key, encryptedKey)); } if (key.usages.includes("unwrapKey")) { const cryptoKeyCek = await webcrypto_default.subtle.unwrapKey("raw", encryptedKey, key, subtleRsaEs(alg), ...bogus_default); return new Uint8Array(await webcrypto_default.subtle.exportKey("raw", cryptoKeyCek)); } throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation'); }; // dist/browser/lib/cek.js function bitLength2(alg) { switch (alg) { case "A128GCM": return 128; case "A192GCM": return 192; case "A256GCM": case "A128CBC-HS256": return 256; case "A192CBC-HS384": return 384; case "A256CBC-HS512": return 512; default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); } } var cek_default = (alg) => random_default(new Uint8Array(bitLength2(alg) >> 3)); // dist/browser/lib/format_pem.js var format_pem_default = (b64, descriptor) => { const newlined = (b64.match(/.{1,64}/g) || []).join("\n"); return `-----BEGIN ${descriptor}----- ${newlined} -----END ${descriptor}-----`; }; // dist/browser/runtime/asn1.js var genericExport = async (keyType, keyFormat, key) => { if (!isCryptoKey(key)) { throw new TypeError(invalid_key_input_default(key, ...types)); } if (!key.extractable) { throw new TypeError("CryptoKey is not extractable"); } if (key.type !== keyType) { throw new TypeError(`key is not a ${keyType} key`); } return format_pem_default(encodeBase64(new Uint8Array(await webcrypto_default.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`); }; var toSPKI = (key) => { return genericExport("public", "spki", key); }; var toPKCS8 = (key) => { return genericExport("private", "pkcs8", key); }; var findOid = (keyData, oid, from = 0) => { if (from === 0) { oid.unshift(oid.length); oid.unshift(6); } let i = keyData.indexOf(oid[0], from); if (i === -1) return false; const sub = keyData.subarray(i, i + oid.length); if (sub.length !== oid.length) return false; return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1); }; var getNamedCurve2 = (keyData) => { switch (true) { case findOid(keyData, [42, 134, 72, 206, 61, 3, 1, 7]): return "P-256"; case findOid(keyData, [43, 129, 4, 0, 34]): return "P-384"; case findOid(keyData, [43, 129, 4, 0, 35]): return "P-521"; case findOid(keyData, [43, 101, 110]): return "X25519"; case findOid(keyData, [43, 101, 111]): return "X448"; case findOid(keyData, [43, 101, 112]): return "Ed25519"; case findOid(keyData, [43, 101, 113]): return "Ed448"; default: throw new JOSENotSupported("Invalid or unsupported EC Key Curve or OKP Key Sub Type"); } }; var genericImport = async (replace, keyFormat, pem, alg, options) => { var _a, _b; let algorithm; let keyUsages; const keyData = new Uint8Array(atob(pem.replace(replace, "")).split("").map((c) => c.charCodeAt(0))); const isPublic = keyFormat === "spki"; switch (alg) { case "PS256": case "PS384": case "PS512": algorithm = { name: "RSA-PSS", hash: `SHA-${alg.slice(-3)}` }; keyUsages = isPublic ? ["verify"] : ["sign"]; break; case "RS256": case "RS384": case "RS512": algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${alg.slice(-3)}` }; keyUsages = isPublic ? ["verify"] : ["sign"]; break; case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": algorithm = { name: "RSA-OAEP", hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}` }; keyUsages = isPublic ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"]; break; case "ES256": algorithm = { name: "ECDSA", namedCurve: "P-256" }; keyUsages = isPublic ? ["verify"] : ["sign"]; break; case "ES384": algorithm = { name: "ECDSA", namedCurve: "P-384" }; keyUsages = isPublic ? ["verify"] : ["sign"]; break; case "ES512": algorithm = { name: "ECDSA", namedCurve: "P-521" }; keyUsages = isPublic ? ["verify"] : ["sign"]; break; case "ECDH-ES": case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": { const namedCurve = getNamedCurve2(keyData); algorithm = namedCurve.startsWith("P-") ? { name: "ECDH", namedCurve } : { name: namedCurve }; keyUsages = isPublic ? [] : ["deriveBits"]; break; } case "EdDSA": algorithm = { name: getNamedCurve2(keyData) }; keyUsages = isPublic ? ["verify"] : ["sign"]; break; default: throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value'); } try { return await webcrypto_default.subtle.importKey(keyFormat, keyData, algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages); } catch (err) { if (algorithm.name === "Ed25519" && (err === null || err === void 0 ? void 0 : err.name) === "NotSupportedError" && isCloudflareWorkers()) { algorithm = { name: "NODE-ED25519", namedCurve: "NODE-ED25519" }; return await webcrypto_default.subtle.importKey(keyFormat, keyData, algorithm, (_b = options === null || options === void 0 ? void 0 : options.extractable) !== null && _b !== void 0 ? _b : false, keyUsages); } throw err; } }; var fromPKCS8 = (pem, alg, options) => { return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, "pkcs8", pem, alg, options); }; var fromSPKI = (pem, alg, options) => { return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, "spki", pem, alg, options); }; // dist/browser/runtime/jwk_to_key.js function subtleMapping(jwk) { let algorithm; let keyUsages; switch (jwk.kty) { case "oct": { switch (jwk.alg) { case "HS256": case "HS384": case "HS512": algorithm = { name: "HMAC", hash: `SHA-${jwk.alg.slice(-3)}` }; keyUsages = ["sign", "verify"]; break; case "A128CBC-HS256": case "A192CBC-HS384": case "A256CBC-HS512": throw new JOSENotSupported(`${jwk.alg} keys cannot be imported as CryptoKey instances`); case "A128GCM": case "A192GCM": case "A256GCM": case "A128GCMKW": case "A192GCMKW": case "A256GCMKW": algorithm = { name: "AES-GCM" }; keyUsages = ["encrypt", "decrypt"]; break; case "A128KW": case "A192KW": case "A256KW": algorithm = { name: "AES-KW" }; keyUsages = ["wrapKey", "unwrapKey"]; break; case "PBES2-HS256+A128KW": case "PBES2-HS384+A192KW": case "PBES2-HS512+A256KW": algorithm = { name: "PBKDF2" }; keyUsages = ["deriveBits"]; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } case "RSA": { switch (jwk.alg) { case "PS256": case "PS384": case "PS512": algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "RS256": case "RS384": case "RS512": algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": algorithm = { name: "RSA-OAEP", hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}` }; keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"]; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } case "EC": { switch (jwk.alg) { case "ES256": algorithm = { name: "ECDSA", namedCurve: "P-256" }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "ES384": algorithm = { name: "ECDSA", namedCurve: "P-384" }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "ES512": algorithm = { name: "ECDSA", namedCurve: "P-521" }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "ECDH-ES": case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": algorithm = { name: "ECDH", namedCurve: jwk.crv }; keyUsages = jwk.d ? ["deriveBits"] : []; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } case "OKP": { switch (jwk.alg) { case "EdDSA": algorithm = { name: jwk.crv }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "ECDH-ES": case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": algorithm = { name: jwk.crv }; keyUsages = jwk.d ? ["deriveBits"] : []; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } default: throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); } return { algorithm, keyUsages }; } var parse = async (jwk) => { var _a, _b; const { algorithm, keyUsages } = subtleMapping(jwk); const rest = [ algorithm, (_a = jwk.ext) !== null && _a !== void 0 ? _a : false, (_b = jwk.key_ops) !== null && _b !== void 0 ? _b : keyUsages ]; if (algorithm.name === "PBKDF2") { return webcrypto_default.subtle.importKey("raw", decode(jwk.k), ...rest); } const keyData = { ...jwk }; delete keyData.alg; delete keyData.use; try { return await webcrypto_default.subtle.importKey("jwk", keyData, ...rest); } catch (err) { if (algorithm.name === "Ed25519" && (err === null || err === void 0 ? void 0 : err.name) === "NotSupportedError" && isCloudflareWorkers()) { rest[0] = { name: "NODE-ED25519", namedCurve: "NODE-ED25519" }; return await webcrypto_default.subtle.importKey("jwk", keyData, ...rest); } throw err; } }; var jwk_to_key_default = parse; // dist/browser/key/import.js function getElement(seq) { let result = []; let next = 0; while (next < seq.length) { let nextPart = parseElement(seq.subarray(next)); result.push(nextPart); next += nextPart.byteLength; } return result; } function parseElement(bytes) { let position = 0; let tag = bytes[0] & 31; position++; if (tag === 31) { tag = 0; while (bytes[position] >= 128) { tag = tag * 128 + bytes[position] - 128; position++; } tag = tag * 128 + bytes[position] - 128; position++; } let length = 0; if (bytes[position] < 128) { length = bytes[position]; position++; } else if (length === 128) { length = 0; while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) { if (length > bytes.byteLength) { throw new TypeError("invalid indefinite form length"); } length++; } const byteLength2 = position + length + 2; return { byteLength: byteLength2, contents: bytes.subarray(position, position + length), raw: bytes.subarray(0, byteLength2) }; } else { let numberOfDigits = bytes[position] & 127; position++; length = 0; for (let i = 0; i < numberOfDigits; i++) { length = length * 256 + bytes[position]; position++; } } const byteLength = position + length; return { byteLength, contents: bytes.subarray(position, byteLength), raw: bytes.subarray(0, byteLength) }; } function spkiFromX509(buf) { const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents); return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 160 ? 6 : 5].raw); } function getSPKI(x509) { const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, ""); const raw = decodeBase64(pem); return format_pem_default(spkiFromX509(raw), "PUBLIC KEY"); } async function importSPKI(spki, alg, options) { if (typeof spki !== "string" || spki.indexOf("-----BEGIN PUBLIC KEY-----") !== 0) { throw new TypeError('"spki" must be SPKI formatted string'); } return fromSPKI(spki, alg, options); } async function importX509(x509, alg, options) { if (typeof x509 !== "string" || x509.indexOf("-----BEGIN CERTIFICATE-----") !== 0) { throw new TypeError('"x509" must be X.509 formatted string'); } let spki; try { spki = getSPKI(x509); } catch (cause) { throw new TypeError("failed to parse the X.509 certificate", { cause }); } return fromSPKI(spki, alg, options); } async function importPKCS8(pkcs8, alg, options) { if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) { throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); } return fromPKCS8(pkcs8, alg, options); } async function importJWK(jwk, alg, octAsKeyObject) { var _a; if (!isObject(jwk)) { throw new TypeError("JWK must be an object"); } alg || (alg = jwk.alg); if (typeof alg !== "string" || !alg) { throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); } switch (jwk.kty) { case "oct": if (typeof jwk.k !== "string" || !jwk.k) { throw new TypeError('missing "k" (Key Value) Parameter value'); } octAsKeyObject !== null && octAsKeyObject !== void 0 ? octAsKeyObject : octAsKeyObject = jwk.ext !== true; if (octAsKeyObject) { return jwk_to_key_default({ ...jwk, alg, ext: (_a = jwk.ext) !== null && _a !== void 0 ? _a : false }); } return decode(jwk.k); case "RSA": if (jwk.oth !== void 0) { throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); } case "EC": case "OKP": return jwk_to_key_default({ ...jwk, alg }); default: throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); } } // dist/browser/lib/check_key_type.js var symmetricTypeCheck = (alg, key) => { if (key instanceof Uint8Array) return; if (!is_key_like_default(key)) { throw new TypeError(withAlg(alg, key, ...types, "Uint8Array")); } if (key.type !== "secret") { throw new TypeError(`${types.join(" or ")} instances for symmetric algorithms must be of type "secret"`); } }; var asymmetricTypeCheck = (alg, key, usage) => { if (!is_key_like_default(key)) { throw new TypeError(withAlg(alg, key, ...types)); } if (key.type === "secret") { throw new TypeError(`${types.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`); } if (usage === "sign" && key.type === "public") { throw new TypeError(`${types.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`); } if (usage === "decrypt" && key.type === "public") { throw new TypeError(`${types.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`); } if (key.algorithm && usage === "verify" && key.type === "private") { throw new TypeError(`${types.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`); } if (key.algorithm && usage === "encrypt" && key.type === "private") { throw new TypeError(`${types.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`); } }; var checkKeyType = (alg, key, usage) => { const symmetric = alg.startsWith("HS") || alg === "dir" || alg.startsWith("PBES2") || /^A\d{3}(?:GCM)?KW$/.test(alg); if (symmetric) { symmetricTypeCheck(alg, key); } else { asymmetricTypeCheck(alg, key, usage); } }; var check_key_type_default = checkKeyType; // dist/browser/runtime/encrypt.js async function cbcEncrypt(enc, plaintext, cek, iv, aad) { if (!(cek instanceof Uint8Array)) { throw new TypeError(invalid_key_input_default(cek, "Uint8Array")); } const keySize = parseInt(enc.slice(1, 4), 10); const encKey = await webcrypto_default.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["encrypt"]); const macKey = await webcrypto_default.subtle.importKey("raw", cek.subarray(0, keySize >> 3), { hash: `SHA-${keySize << 1}`, name: "HMAC" }, false, ["sign"]); const ciphertext = new Uint8Array(await webcrypto_default.subtle.encrypt({ iv, name: "AES-CBC" }, encKey, plaintext)); const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); const tag = new Uint8Array((await webcrypto_default.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)); return { ciphertext, tag }; } async function gcmEncrypt(enc, plaintext, cek, iv, aad) { let encKey; if (cek instanceof Uint8Array) { encKey = await webcrypto_default.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]); } else { checkEncCryptoKey(cek, enc, "encrypt"); encKey = cek; } const encrypted = new Uint8Array(await webcrypto_default.subtle.encrypt({ additionalData: aad, iv, name: "AES-GCM", tagLength: 128 }, encKey, plaintext)); const tag = encrypted.slice(-16); const ciphertext = encrypted.slice(0, -16); return { ciphertext, tag }; } var encrypt3 = async (enc, plaintext, cek, iv, aad) => { if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { throw new TypeError(invalid_key_input_default(cek, ...types, "Uint8Array")); } check_iv_length_default(enc, iv); switch (enc) { case "A128CBC-HS256": case "A192CBC-HS384": case "A256CBC-HS512": if (cek instanceof Uint8Array) check_cek_length_default(cek, parseInt(enc.slice(-3), 10)); return cbcEncrypt(enc, plaintext, cek, iv, aad); case "A128GCM": case "A192GCM": case "A256GCM": if (cek instanceof Uint8Array) check_cek_length_default(cek, parseInt(enc.slice(1, 4), 10)); return gcmEncrypt(enc, plaintext, cek, iv, aad); default: throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm"); } }; var encrypt_default = encrypt3; // dist/browser/lib/aesgcmkw.js async function wrap2(alg, key, cek, iv) { const jweAlgorithm = alg.slice(0, 7); iv || (iv = iv_default(jweAlgorithm)); const { ciphertext: encryptedKey, tag } = await encrypt_default(jweAlgorithm, cek, key, iv, new Uint8Array(0)); return { encryptedKey, iv: encode(iv), tag: encode(tag) }; } async function unwrap2(alg, key, encryptedKey, iv, tag) { const jweAlgorithm = alg.slice(0, 7); return decrypt_default(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0)); } // dist/browser/lib/decrypt_key_management.js async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { check_key_type_default(alg, key, "decrypt"); switch (alg) { case "dir": { if (encryptedKey !== void 0) throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); return key; } case "ECDH-ES": if (encryptedKey !== void 0) throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": { if (!isObject(joseHeader.epk)) throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); if (!ecdhAllowed(key)) throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); const epk = await importJWK(joseHeader.epk, alg); let partyUInfo; let partyVInfo; if (joseHeader.apu !== void 0) { if (typeof joseHeader.apu !== "string") throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); partyUInfo = decode(joseHeader.apu); } if (joseHeader.apv !== void 0) { if (typeof joseHeader.apv !== "string") throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); partyVInfo = decode(joseHeader.apv); } const sharedSecret = await deriveKey(epk, key, alg === "ECDH-ES" ? joseHeader.enc : alg, alg === "ECDH-ES" ? bitLength2(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); if (alg === "ECDH-ES") return sharedSecret; if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing"); return unwrap(alg.slice(-6), sharedSecret, encryptedKey); } case "RSA1_5": case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": { if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing"); return decrypt3(alg, key, encryptedKey); } case "PBES2-HS256+A128KW": case "PBES2-HS384+A192KW": case "PBES2-HS512+A256KW": { if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing"); if (typeof joseHeader.p2c !== "number") throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); const p2cLimit = (options === null || options === void 0 ? void 0 : options.maxPBES2Count) || 1e4; if (joseHeader.p2c > p2cLimit) throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); if (typeof joseHeader.p2s !== "string") throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); return decrypt2(alg, key, encryptedKey, joseHeader.p2c, decode(joseHeader.p2s)); } case "A128KW": case "A192KW": case "A256KW": { if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing"); return unwrap(alg, key, encryptedKey); } case "A128GCMKW": case "A192GCMKW": case "A256GCMKW": { if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing"); if (typeof joseHeader.iv !== "string") throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); if (typeof joseHeader.tag !== "string") throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); const iv = decode(joseHeader.iv); const tag = decode(joseHeader.tag); return unwrap2(alg, key, encryptedKey, iv, tag); } default: { throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); } } } var decrypt_key_management_default = decryptKeyManagement; // dist/browser/lib/validate_crit.js function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { if (joseHeader.crit !== void 0 && protectedHeader.crit === void 0) { throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); } if (!protectedHeader || protectedHeader.crit === void 0) { return /* @__PURE__ */ new Set(); } if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) { throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); } let recognized; if (recognizedOption !== void 0) { recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); } else { recognized = recognizedDefault; } for (const parameter of protectedHeader.crit) { if (!recognized.has(parameter)) { throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); } if (joseHeader[parameter] === void 0) { throw new Err(`Extension Header Parameter "${parameter}" is missing`); } else if (recognized.get(parameter) && protectedHeader[parameter] === void 0) { throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); } } return new Set(protectedHeader.crit); } var validate_crit_default = validateCrit; // dist/browser/lib/validate_algorithms.js var validateAlgorithms = (option, algorithms) => { if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) { throw new TypeError(`"${option}" option must be an array of strings`); } if (!algorithms) { return void 0; } return new Set(algorithms); }; var validate_algorithms_default = validateAlgorithms; // dist/browser/jwe/flattened/decrypt.js async function flattenedDecrypt(jwe, key, options) { var _a; if (!isObject(jwe)) { throw new JWEInvalid("Flattened JWE must be an object"); } if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) { throw new JWEInvalid("JOSE Header missing"); } if (typeof jwe.iv !== "string") { throw new JWEInvalid("JWE Initialization Vector missing or incorrect type"); } if (typeof jwe.ciphertext !== "string") { throw new JWEInvalid("JWE Ciphertext missing or incorrect type"); } if (typeof jwe.tag !== "string") { throw new JWEInvalid("JWE Authentication Tag missing or incorrect type"); } if (jwe.protected !== void 0 && typeof jwe.protected !== "string") { throw new JWEInvalid("JWE Protected Header incorrect type"); } if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") { throw new JWEInvalid("JWE Encrypted Key incorrect type"); } if (jwe.aad !== void 0 && typeof jwe.aad !== "string") { throw new JWEInvalid("JWE AAD incorrect type"); } if (jwe.header !== void 0 && !isObject(jwe.header)) { throw new JWEInvalid("JWE Shared Unprotected Header incorrect type"); } if (jwe.unprotected !== void 0 && !isObject(jwe.unprotected)) { throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type"); } let parsedProt; if (jwe.protected) { try { const protectedHeader2 = decode(jwe.protected); parsedProt = JSON.parse(decoder.decode(protectedHeader2)); } catch (_b) { throw new JWEInvalid("JWE Protected Header is invalid"); } } if (!is_disjoint_default(parsedProt, jwe.header, jwe.unprotected)) { throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint"); } const joseHeader = { ...parsedProt, ...jwe.header, ...jwe.unprotected }; validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader); if (joseHeader.zip !== void 0) { if (!parsedProt || !parsedProt.zip) { throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); } if (joseHeader.zip !== "DEF") { throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value'); } } const { alg, enc } = joseHeader; if (typeof alg !== "string" || !alg) { throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header"); } if (typeof enc !== "string" || !enc) { throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header"); } const keyManagementAlgorithms = options && validate_algorithms_default("keyManagementAlgorithms", options.keyManagementAlgorithms); const contentEncryptionAlgorithms = options && validate_algorithms_default("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms); if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) { throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed'); } if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed'); } let encryptedKey; if (jwe.encrypted_key !== void 0) { encryptedKey = decode(jwe.encrypted_key); } let resolvedKey = false; if (typeof key === "function") { key = await key(parsedProt, jwe); resolvedKey = true; } let cek; try { cek = await decrypt_key_management_default(alg, key, encryptedKey, joseHeader, options); } catch (err) { if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { throw err; } cek = cek_default(enc); } const iv = decode(jwe.iv); const tag = decode(jwe.tag); const protectedHeader = encoder.encode((_a = jwe.protected) !== null && _a !== void 0 ? _a : ""); let additionalData; if (jwe.aad !== void 0) { additionalData = concat(protectedHeader, encoder.encode("."), encoder.encode(jwe.aad)); } else { additionalData = protectedHeader; } let plaintext = await decrypt_default(enc, cek, decode(jwe.ciphertext), iv, tag, additionalData); if (joseHeader.zip === "DEF") { plaintext = await ((options === null || options === void 0 ? void 0 : options.inflateRaw) || inflate)(plaintext); } const result = { plaintext }; if (jwe.protected !== void 0) { result.protectedHeader = parsedProt; } if (jwe.aad !== void 0) { result.additionalAuthenticatedData = decode(jwe.aad); } if (jwe.unprotected !== void 0) { result.sharedUnprotectedHeader = jwe.unprotected; } if (jwe.header !== void 0) { result.unprotectedHeader = jwe.header; } if (resolvedKey) { return { ...result, key }; } return result; } // dist/browser/jwe/compact/decrypt.js async function compactDecrypt(jwe, key, options) { if (jwe instanceof Uint8Array) { jwe = decoder.decode(jwe); } if (typeof jwe !== "string") { throw new JWEInvalid("Compact JWE must be a string or Uint8Array"); } const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length } = jwe.split("."); if (length !== 5) { throw new JWEInvalid("Invalid Compact JWE"); } const decrypted = await flattenedDecrypt({ ciphertext, iv: iv || void 0, protected: protectedHeader || void 0, tag: tag || void 0, encrypted_key: encryptedKey || void 0 }, key, options); const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; if (typeof key === "function") { return { ...result, key: decrypted.key }; } return result; } // dist/browser/jwe/general/decrypt.js async function generalDecrypt(jwe, key, options) { if (!isObject(jwe)) { throw new JWEInvalid("General JWE must be an object"); } if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) { throw new JWEInvalid("JWE Recipients missing or incorrect type"); } if (!jwe.recipients.length) { throw new JWEInvalid("JWE Recipients has no members"); } for (const recipient of jwe.recipients) { try { return await flattenedDecrypt({ aad: jwe.aad, ciphertext: jwe.ciphertext, encrypted_key: recipient.encrypted_key, header: recipient.header, iv: jwe.iv, protected: jwe.protected, tag: jwe.tag, unprotected: jwe.unprotected }, key, options); } catch (_a) { } } throw new JWEDecryptionFailed(); } // dist/browser/runtime/key_to_jwk.js var keyToJWK = async (key) => { if (key instanceof Uint8Array) { return { kty: "oct", k: encode(key) }; } if (!isCryptoKey(key)) { throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array")); } if (!key.extractable) { throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK"); } const { ext, key_ops, alg, use, ...jwk } = await webcrypto_default.subtle.exportKey("jwk", key); return jwk; }; var key_to_jwk_default = keyToJWK; // dist/browser/key/export.js async function exportSPKI(key) { return toSPKI(key); } async function exportPKCS8(key) { return toPKCS8(key); } async function exportJWK(key) { return key_to_jwk_default(key); } // dist/browser/lib/encrypt_key_management.js async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { let encryptedKey; let parameters; let cek; check_key_type_default(alg, key, "encrypt"); switch (alg) { case "dir": { cek = key; break; } case "ECDH-ES": case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": { if (!ecdhAllowed(key)) { throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); } const { apu, apv } = providedParameters; let { epk: ephemeralKey } = providedParameters; ephemeralKey || (ephemeralKey = (await generateEpk(key)).privateKey); const { x, y, crv, kty } = await exportJWK(ephemeralKey); const sharedSecret = await deriveKey(key, ephemeralKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? bitLength2(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); parameters = { epk: { x, crv, kty } }; if (kty === "EC") parameters.epk.y = y; if (apu) parameters.apu = encode(apu); if (apv) parameters.apv = encode(apv); if (alg === "ECDH-ES") { cek = sharedSecret; break; } cek = providedCek || cek_default(enc); const kwAlg = alg.slice(-6); encryptedKey = await wrap(kwAlg, sharedSecret, cek); break; } case "RSA1_5": case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": { cek = providedCek || cek_default(enc); encryptedKey = await encrypt2(alg, key, cek); break; } case "PBES2-HS256+A128KW": case "PBES2-HS384+A192KW": case "PBES2-HS512+A256KW": { cek = providedCek || cek_default(enc); const { p2c, p2s: p2s2 } = providedParameters; ({ encryptedKey, ...parameters } = await encrypt(alg, key, cek, p2c, p2s2)); break; } case "A128KW": case "A192KW": case "A256KW": { cek = providedCek || cek_default(enc); encryptedKey = await wrap(alg, key, cek); break; } case "A128GCMKW": case "A192GCMKW": case "A256GCMKW": { cek = providedCek || cek_default(enc); const { iv } = providedParameters; ({ encryptedKey, ...parameters } = await wrap2(alg, key, cek, iv)); break; } default: { throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); } } return { cek, encryptedKey, parameters }; } var encrypt_key_management_default = encryptKeyManagement; // dist/browser/jwe/flattened/encrypt.js var unprotected = Symbol(); var FlattenedEncrypt = class { constructor(plaintext) { if (!(plaintext instanceof Uint8Array)) { throw new TypeError("plaintext must be an instance of Uint8Array"); } this._plaintext = plaintext; } setKeyManagementParameters(parameters) { if (this._keyManagementParameters) { throw new TypeError("setKeyManagementParameters can only be called once"); } this._keyManagementParameters = parameters; return this; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError("setProtectedHeader can only be called once"); } this._protectedHeader = protectedHeader; return this; } setSharedUnprotectedHeader(sharedUnprotectedHeader) { if (this._sharedUnprotectedHeader) { throw new TypeError("setSharedUnprotectedHeader can only be called once"); } this._sharedUnprotectedHeader = sharedUnprotectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError("setUnprotectedHeader can only be called once"); } this._unprotectedHeader = unprotectedHeader; return this; } setAdditionalAuthenticatedData(aad) { this._aad = aad; return this; } setContentEncryptionKey(cek) { if (this._cek) { throw new TypeError("setContentEncryptionKey can only be called once"); } this._cek = cek; return this; } setInitializationVector(iv) { if (this._iv) { throw new TypeError("setInitializationVector can only be called once"); } this._iv = iv; return this; } async encrypt(key, options) { if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()"); } if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) { throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...this._sharedUnprotectedHeader }; validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader); if (joseHeader.zip !== void 0) { if (!this._protectedHeader || !this._protectedHeader.zip) { throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); } if (joseHeader.zip !== "DEF") { throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value'); } } const { alg, enc } = joseHeader; if (typeof alg !== "string" || !alg) { throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); } if (typeof enc !== "string" || !enc) { throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); } let encryptedKey; if (alg === "dir") { if (this._cek) { throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption"); } } else if (alg === "ECDH-ES") { if (this._cek) { throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement"); } } let cek; { let parameters; ({ cek, encryptedKey, parameters } = await encrypt_key_management_default(alg, enc, key, this._cek, this._keyManagementParameters)); if (parameters) { if (options && unprotected in options) { if (!this._unprotectedHeader) { this.setUnprotectedHeader(parameters); } else { this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters }; } } else { if (!this._protectedHeader) { this.setProtectedHeader(parameters); } else { this._protectedHeader = { ...this._protectedHeader, ...parameters }; } } } } this._iv || (this._iv = iv_default(enc)); let additionalData; let protectedHeader; let aadMember; if (this._protectedHeader) { protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader))); } else { protectedHeader = encoder.encode(""); } if (this._aad) { aadMember = encode(this._aad); additionalData = concat(protectedHeader, encoder.encode("."), encoder.encode(aadMember)); } else { additionalData = protectedHeader; } let ciphertext; let tag; if (joseHeader.zip === "DEF") { const deflated = await ((options === null || options === void 0 ? void 0 : options.deflateRaw) || deflate)(this._plaintext); ({ ciphertext, tag } = await encrypt_default(enc, deflated, cek, this._iv, additionalData)); } else { ; ({ ciphertext, tag } = await encrypt_default(enc, this._plaintext, cek, this._iv, additionalData)); } const jwe = { ciphertext: encode(ciphertext), iv: encode(this._iv), tag: encode(tag) }; if (encryptedKey) { jwe.encrypted_key = encode(encryptedKey); } if (aadMember) { jwe.aad = aadMember; } if (this._protectedHeader) { jwe.protected = decoder.decode(protectedHeader); } if (this._sharedUnprotectedHeader) { jwe.unprotected = this._sharedUnprotectedHeader; } if (this._unprotectedHeader) { jwe.header = this._unprotectedHeader; } return jwe; } }; // dist/browser/jwe/general/encrypt.js var IndividualRecipient = class { constructor(enc, key, options) { this.parent = enc; this.key = key; this.options = options; } setUnprotectedHeader(unprotectedHeader) { if (this.unprotectedHeader) { throw new TypeError("setUnprotectedHeader can only be called once"); } this.unprotectedHeader = unprotectedHeader; return this; } addRecipient(...args) { return this.parent.addRecipient(...args); } encrypt(...args) { return this.parent.encrypt(...args); } done() { return this.parent; } }; var GeneralEncrypt = class { constructor(plaintext) { this._recipients = []; this._plaintext = plaintext; } addRecipient(key, options) { const recipient = new IndividualRecipient(this, key, { crit: options === null || options === void 0 ? void 0 : options.crit }); this._recipients.push(recipient); return recipient; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError("setProtectedHeader can only be called once"); } this._protectedHeader = protectedHeader; return this; } setSharedUnprotectedHeader(sharedUnprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError("setSharedUnprotectedHeader can only be called once"); } this._unprotectedHeader = sharedUnprotectedHeader; return this; } setAdditionalAuthenticatedData(aad) { this._aad = aad; return this; } async encrypt(options) { var _a, _b, _c; if (!this._recipients.length) { throw new JWEInvalid("at least one recipient must be added"); } options = { deflateRaw: options === null || options === void 0 ? void 0 : options.deflateRaw }; if (this._recipients.length === 1) { const [recipient] = this._recipients; const flattened = await new FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).encrypt(recipient.key, { ...recipient.options, ...options }); let jwe2 = { ciphertext: flattened.ciphertext, iv: flattened.iv, recipients: [{}], tag: flattened.tag }; if (flattened.aad) jwe2.aad = flattened.aad; if (flattened.protected) jwe2.protected = flattened.protected; if (flattened.unprotected) jwe2.unprotected = flattened.unprotected; if (flattened.encrypted_key) jwe2.recipients[0].encrypted_key = flattened.encrypted_key; if (flattened.header) jwe2.recipients[0].header = flattened.header; return jwe2; } let enc; for (let i = 0; i < this._recipients.length; i++) { const recipient = this._recipients[i]; if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) { throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...recipient.unprotectedHeader }; const { alg } = joseHeader; if (typeof alg !== "string" || !alg) { throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); } if (alg === "dir" || alg === "ECDH-ES") { throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); } if (typeof joseHeader.enc !== "string" || !joseHeader.enc) { throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); } if (!enc) { enc = joseHeader.enc; } else if (enc !== joseHeader.enc) { throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); } validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), recipient.options.crit, this._protectedHeader, joseHeader); if (joseHeader.zip !== void 0) { if (!this._protectedHeader || !this._protectedHeader.zip) { throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); } } } const cek = cek_default(enc); let jwe = { ciphertext: "", iv: "", recipients: [], tag: "" }; for (let i = 0; i < this._recipients.length; i++) { const recipient = this._recipients[i]; const target = {}; jwe.recipients.push(target); const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...recipient.unprotectedHeader }; const p2c = joseHeader.alg.startsWith("PBES2") ? 2048 + i : void 0; if (i === 0) { const flattened = await new FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(cek).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).setKeyManagementParameters({ p2c }).encrypt(recipient.key, { ...recipient.options, ...options, [unprotected]: true }); jwe.ciphertext = flattened.ciphertext; jwe.iv = flattened.iv; jwe.tag = flattened.tag; if (flattened.aad) jwe.aad = flattened.aad; if (flattened.protected) jwe.protected = flattened.protected; if (flattened.unprotected) jwe.unprotected = flattened.unprotected; target.encrypted_key = flattened.encrypted_key; if (flattened.header) target.header = flattened.header; continue; } const { encryptedKey, parameters } = await encrypt_key_management_default(((_a = recipient.unprotectedHeader) === null || _a === void 0 ? void 0 : _a.alg) || ((_b = this._protectedHeader) === null || _b === void 0 ? void 0 : _b.alg) || ((_c = this._unprotectedHeader) === null || _c === void 0 ? void 0 : _c.alg), enc, recipient.key, cek, { p2c }); target.encrypted_key = encode(encryptedKey); if (recipient.unprotectedHeader || parameters) target.header = { ...recipient.unprotectedHeader, ...parameters }; } return jwe; } }; // dist/browser/runtime/subtle_dsa.js function subtleDsa(alg, algorithm) { const hash = `SHA-${alg.slice(-3)}`; switch (alg) { case "HS256": case "HS384": case "HS512": return { hash, name: "HMAC" }; case "PS256": case "PS384": case "PS512": return { hash, name: "RSA-PSS", saltLength: alg.slice(-3) >> 3 }; case "RS256": case "RS384": case "RS512": return { hash, name: "RSASSA-PKCS1-v1_5" }; case "ES256": case "ES384": case "ES512": return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve }; case "EdDSA": if (isCloudflareWorkers() && algorithm.name === "NODE-ED25519") { return { name: "NODE-ED25519", namedCurve: "NODE-ED25519" }; } return { name: algorithm.name }; default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } } // dist/browser/runtime/get_sign_verify_key.js function getCryptoKey3(alg, key, usage) { if (isCryptoKey(key)) { checkSigCryptoKey(key, alg, usage); return key; } if (key instanceof Uint8Array) { if (!alg.startsWith("HS")) { throw new TypeError(invalid_key_input_default(key, ...types)); } return webcrypto_default.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]); } throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array")); } // dist/browser/runtime/verify.js var verify = async (alg, key, signature, data) => { const cryptoKey = await getCryptoKey3(alg, key, "verify"); check_key_length_default(alg, cryptoKey); const algorithm = subtleDsa(alg, cryptoKey.algorithm); try { return await webcrypto_default.subtle.verify(algorithm, cryptoKey, signature, data); } catch (_a) { return false; } }; var verify_default = verify; // dist/browser/jws/flattened/verify.js async function flattenedVerify(jws, key, options) { var _a; if (!isObject(jws)) { throw new JWSInvalid("Flattened JWS must be an object"); } if (jws.protected === void 0 && jws.header === void 0) { throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); } if (jws.protected !== void 0 && typeof jws.protected !== "string") { throw new JWSInvalid("JWS Protected Header incorrect type"); } if (jws.payload === void 0) { throw new JWSInvalid("JWS Payload missing"); } if (typeof jws.signature !== "string") { throw new JWSInvalid("JWS Signature missing or incorrect type"); } if (jws.header !== void 0 && !isObject(jws.header)) { throw new JWSInvalid("JWS Unprotected Header incorrect type"); } let parsedProt = {}; if (jws.protected) { try { const protectedHeader = decode(jws.protected); parsedProt = JSON.parse(decoder.decode(protectedHeader)); } catch (_b) { throw new JWSInvalid("JWS Protected Header is invalid"); } } if (!is_disjoint_default(parsedProt, jws.header)) { throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); } const joseHeader = { ...parsedProt, ...jws.header }; const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader); let b64 = true; if (extensions.has("b64")) { b64 = parsedProt.b64; if (typeof b64 !== "boolean") { throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); } } const { alg } = joseHeader; if (typeof alg !== "string" || !alg) { throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); } const algorithms = options && validate_algorithms_default("algorithms", options.algorithms); if (algorithms && !algorithms.has(alg)) { throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed'); } if (b64) { if (typeof jws.payload !== "string") { throw new JWSInvalid("JWS Payload must be a string"); } } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) { throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance"); } let resolvedKey = false; if (typeof key === "function") { key = await key(parsedProt, jws); resolvedKey = true; } check_key_type_default(alg, key, "verify"); const data = concat(encoder.encode((_a = jws.protected) !== null && _a !== void 0 ? _a : ""), encoder.encode("."), typeof jws.payload === "string" ? encoder.encode(jws.payload) : jws.payload); const signature = decode(jws.signature); const verified = await verify_default(alg, key, signature, data); if (!verified) { throw new JWSSignatureVerificationFailed(); } let payload; if (b64) { payload = decode(jws.payload); } else if (typeof jws.payload === "string") { payload = encoder.encode(jws.payload); } else { payload = jws.payload; } const result = { payload }; if (jws.protected !== void 0) { result.protectedHeader = parsedProt; } if (jws.header !== void 0) { result.unprotectedHeader = jws.header; } if (resolvedKey) { return { ...result, key }; } return result; } // dist/browser/jws/compact/verify.js async function compactVerify(jws, key, options) { if (jws instanceof Uint8Array) { jws = decoder.decode(jws); } if (typeof jws !== "string") { throw new JWSInvalid("Compact JWS must be a string or Uint8Array"); } const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split("."); if (length !== 3) { throw new JWSInvalid("Invalid Compact JWS"); } const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options); const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; if (typeof key === "function") { return { ...result, key: verified.key }; } return result; } // dist/browser/jws/general/verify.js async function generalVerify(jws, key, options) { if (!isObject(jws)) { throw new JWSInvalid("General JWS must be an object"); } if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) { throw new JWSInvalid("JWS Signatures missing or incorrect type"); } for (const signature of jws.signatures) { try { return await flattenedVerify({ header: signature.header, payload: jws.payload, protected: signature.protected, signature: signature.signature }, key, options); } catch (_a) { } } throw new JWSSignatureVerificationFailed(); } // dist/browser/lib/epoch.js var epoch_default = (date) => Math.floor(date.getTime() / 1e3); // dist/browser/lib/secs.js var minute = 60; var hour = minute * 60; var day = hour * 24; var week = day * 7; var year = day * 365.25; var REGEX = /^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i; var secs_default = (str) => { const matched = REGEX.exec(str); if (!matched) { throw new TypeError("Invalid time period format"); } const value = parseFloat(matched[1]); const unit = matched[2].toLowerCase(); switch (unit) { case "sec": case "secs": case "second": case "seconds": case "s": return Math.round(value); case "minute": case "minutes": case "min": case "mins": case "m": return Math.round(value * minute); case "hour": case "hours": case "hr": case "hrs": case "h": return Math.round(value * hour); case "day": case "days": case "d": return Math.round(value * day); case "week": case "weeks": case "w": return Math.round(value * week); default: return Math.round(value * year); } }; // dist/browser/lib/jwt_claims_set.js var normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, ""); var checkAudiencePresence = (audPayload, audOption) => { if (typeof audPayload === "string") { return audOption.includes(audPayload); } if (Array.isArray(audPayload)) { return audOption.some(Set.prototype.has.bind(new Set(audPayload))); } return false; }; var jwt_claims_set_default = (protectedHeader, encodedPayload, options = {}) => { const { typ } = options; if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', "typ", "check_failed"); } let payload; try { payload = JSON.parse(decoder.decode(encodedPayload)); } catch (_a) { } if (!isObject(payload)) { throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); } const { issuer } = options; if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { throw new JWTClaimValidationFailed('unexpected "iss" claim value', "iss", "check_failed"); } const { subject } = options; if (subject && payload.sub !== subject) { throw new JWTClaimValidationFailed('unexpected "sub" claim value', "sub", "check_failed"); } const { audience } = options; if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) { throw new JWTClaimValidationFailed('unexpected "aud" claim value', "aud", "check_failed"); } let tolerance; switch (typeof options.clockTolerance) { case "string": tolerance = secs_default(options.clockTolerance); break; case "number": tolerance = options.clockTolerance; break; case "undefined": tolerance = 0; break; default: throw new TypeError("Invalid clockTolerance option type"); } const { currentDate } = options; const now = epoch_default(currentDate || /* @__PURE__ */ new Date()); if ((payload.iat !== void 0 || options.maxTokenAge) && typeof payload.iat !== "number") { throw new JWTClaimValidationFailed('"iat" claim must be a number', "iat", "invalid"); } if (payload.nbf !== void 0) { if (typeof payload.nbf !== "number") { throw new JWTClaimValidationFailed('"nbf" claim must be a number', "nbf", "invalid"); } if (payload.nbf > now + tolerance) { throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', "nbf", "check_failed"); } } if (payload.exp !== void 0) { if (typeof payload.exp !== "number") { throw new JWTClaimValidationFailed('"exp" claim must be a number', "exp", "invalid"); } if (payload.exp <= now - tolerance) { throw new JWTExpired('"exp" claim timestamp check failed', "exp", "check_failed"); } } if (options.maxTokenAge) { const age = now - payload.iat; const max = typeof options.maxTokenAge === "number" ? options.maxTokenAge : secs_default(options.maxTokenAge); if (age - tolerance > max) { throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', "iat", "check_failed"); } if (age < 0 - tolerance) { throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', "iat", "check_failed"); } } return payload; }; // dist/browser/jwt/verify.js async function jwtVerify(jwt, key, options) { var _a; const verified = await compactVerify(jwt, key, options); if (((_a = verified.protectedHeader.crit) === null || _a === void 0 ? void 0 : _a.includes("b64")) && verified.protectedHeader.b64 === false) { throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); } const payload = jwt_claims_set_default(verified.protectedHeader, verified.payload, options); const result = { payload, protectedHeader: verified.protectedHeader }; if (typeof key === "function") { return { ...result, key: verified.key }; } return result; } // dist/browser/jwt/decrypt.js async function jwtDecrypt(jwt, key, options) { const decrypted = await compactDecrypt(jwt, key, options); const payload = jwt_claims_set_default(decrypted.protectedHeader, decrypted.plaintext, options); const { protectedHeader } = decrypted; if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload.iss) { throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', "iss", "mismatch"); } if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload.sub) { throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', "sub", "mismatch"); } if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', "aud", "mismatch"); } const result = { payload, protectedHeader }; if (typeof key === "function") { return { ...result, key: decrypted.key }; } return result; } // dist/browser/jwe/compact/encrypt.js var CompactEncrypt = class { constructor(plaintext) { this._flattened = new FlattenedEncrypt(plaintext); } setContentEncryptionKey(cek) { this._flattened.setContentEncryptionKey(cek); return this; } setInitializationVector(iv) { this._flattened.setInitializationVector(iv); return this; } setProtectedHeader(protectedHeader) { this._flattened.setProtectedHeader(protectedHeader); return this; } setKeyManagementParameters(parameters) { this._flattened.setKeyManagementParameters(parameters); return this; } async encrypt(key, options) { const jwe = await this._flattened.encrypt(key, options); return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join("."); } }; // dist/browser/runtime/sign.js var sign = async (alg, key, data) => { const cryptoKey = await getCryptoKey3(alg, key, "sign"); check_key_length_default(alg, cryptoKey); const signature = await webcrypto_default.subtle.sign(subtleDsa(alg, cryptoKey.algorithm), cryptoKey, data); return new Uint8Array(signature); }; var sign_default = sign; // dist/browser/jws/flattened/sign.js var FlattenedSign = class { constructor(payload) { if (!(payload instanceof Uint8Array)) { throw new TypeError("payload must be an instance of Uint8Array"); } this._payload = payload; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError("setProtectedHeader can only be called once"); } this._protectedHeader = protectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError("setUnprotectedHeader can only be called once"); } this._unprotectedHeader = unprotectedHeader; return this; } async sign(key, options) { if (!this._protectedHeader && !this._unprotectedHeader) { throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()"); } if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader)) { throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader }; const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader); let b64 = true; if (extensions.has("b64")) { b64 = this._protectedHeader.b64; if (typeof b64 !== "boolean") { throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); } } const { alg } = joseHeader; if (typeof alg !== "string" || !alg) { throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); } check_key_type_default(alg, key, "sign"); let payload = this._payload; if (b64) { payload = encoder.encode(encode(payload)); } let protectedHeader; if (this._protectedHeader) { protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader))); } else { protectedHeader = encoder.encode(""); } const data = concat(protectedHeader, encoder.encode("."), payload); const signature = await sign_default(alg, key, data); const jws = { signature: encode(signature), payload: "" }; if (b64) { jws.payload = decoder.decode(payload); } if (this._unprotectedHeader) { jws.header = this._unprotectedHeader; } if (this._protectedHeader) { jws.protected = decoder.decode(protectedHeader); } return jws; } }; // dist/browser/jws/compact/sign.js var CompactSign = class { constructor(payload) { this._flattened = new FlattenedSign(payload); } setProtectedHeader(protectedHeader) { this._flattened.setProtectedHeader(protectedHeader); return this; } async sign(key, options) { const jws = await this._flattened.sign(key, options); if (jws.payload === void 0) { throw new TypeError("use the flattened module for creating JWS with b64: false"); } return `${jws.protected}.${jws.payload}.${jws.signature}`; } }; // dist/browser/jws/general/sign.js var IndividualSignature = class { constructor(sig, key, options) { this.parent = sig; this.key = key; this.options = options; } setProtectedHeader(protectedHeader) { if (this.protectedHeader) { throw new TypeError("setProtectedHeader can only be called once"); } this.protectedHeader = protectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this.unprotectedHeader) { throw new TypeError("setUnprotectedHeader can only be called once"); } this.unprotectedHeader = unprotectedHeader; return this; } addSignature(...args) { return this.parent.addSignature(...args); } sign(...args) { return this.parent.sign(...args); } done() { return this.parent; } }; var GeneralSign = class { constructor(payload) { this._signatures = []; this._payload = payload; } addSignature(key, options) { const signature = new IndividualSignature(this, key, options); this._signatures.push(signature); return signature; } async sign() { if (!this._signatures.length) { throw new JWSInvalid("at least one signature must be added"); } const jws = { signatures: [], payload: "" }; for (let i = 0; i < this._signatures.length; i++) { const signature = this._signatures[i]; const flattened = new FlattenedSign(this._payload); flattened.setProtectedHeader(signature.protectedHeader); flattened.setUnprotectedHeader(signature.unprotectedHeader); const { payload, ...rest } = await flattened.sign(signature.key, signature.options); if (i === 0) { jws.payload = payload; } else if (jws.payload !== payload) { throw new JWSInvalid("inconsistent use of JWS Unencoded Payload Option (RFC7797)"); } jws.signatures.push(rest); } return jws; } }; // dist/browser/jwt/produce.js var ProduceJWT = class { constructor(payload) { if (!isObject(payload)) { throw new TypeError("JWT Claims Set MUST be an object"); } this._payload = payload; } setIssuer(issuer) { this._payload = { ...this._payload, iss: issuer }; return this; } setSubject(subject) { this._payload = { ...this._payload, sub: subject }; return this; } setAudience(audience) { this._payload = { ...this._payload, aud: audience }; return this; } setJti(jwtId) { this._payload = { ...this._payload, jti: jwtId }; return this; } setNotBefore(input) { if (typeof input === "number") { this._payload = { ...this._payload, nbf: input }; } else { this._payload = { ...this._payload, nbf: epoch_default(/* @__PURE__ */ new Date()) + secs_default(input) }; } return this; } setExpirationTime(input) { if (typeof input === "number") { this._payload = { ...this._payload, exp: input }; } else { this._payload = { ...this._payload, exp: epoch_default(/* @__PURE__ */ new Date()) + secs_default(input) }; } return this; } setIssuedAt(input) { if (typeof input === "undefined") { this._payload = { ...this._payload, iat: epoch_default(/* @__PURE__ */ new Date()) }; } else { this._payload = { ...this._payload, iat: input }; } return this; } }; // dist/browser/jwt/sign.js var SignJWT = class extends ProduceJWT { setProtectedHeader(protectedHeader) { this._protectedHeader = protectedHeader; return this; } async sign(key, options) { var _a; const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload))); sig.setProtectedHeader(this._protectedHeader); if (Array.isArray((_a = this._protectedHeader) === null || _a === void 0 ? void 0 : _a.crit) && this._protectedHeader.crit.includes("b64") && this._protectedHeader.b64 === false) { throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); } return sig.sign(key, options); } }; // dist/browser/jwt/encrypt.js var EncryptJWT = class extends ProduceJWT { setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError("setProtectedHeader can only be called once"); } this._protectedHeader = protectedHeader; return this; } setKeyManagementParameters(parameters) { if (this._keyManagementParameters) { throw new TypeError("setKeyManagementParameters can only be called once"); } this._keyManagementParameters = parameters; return this; } setContentEncryptionKey(cek) { if (this._cek) { throw new TypeError("setContentEncryptionKey can only be called once"); } this._cek = cek; return this; } setInitializationVector(iv) { if (this._iv) { throw new TypeError("setInitializationVector can only be called once"); } this._iv = iv; return this; } replicateIssuerAsHeader() { this._replicateIssuerAsHeader = true; return this; } replicateSubjectAsHeader() { this._replicateSubjectAsHeader = true; return this; } replicateAudienceAsHeader() { this._replicateAudienceAsHeader = true; return this; } async encrypt(key, options) { const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload))); if (this._replicateIssuerAsHeader) { this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss }; } if (this._replicateSubjectAsHeader) { this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub }; } if (this._replicateAudienceAsHeader) { this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud }; } enc.setProtectedHeader(this._protectedHeader); if (this._iv) { enc.setInitializationVector(this._iv); } if (this._cek) { enc.setContentEncryptionKey(this._cek); } if (this._keyManagementParameters) { enc.setKeyManagementParameters(this._keyManagementParameters); } return enc.encrypt(key, options); } }; // dist/browser/jwk/thumbprint.js var check = (value, description) => { if (typeof value !== "string" || !value) { throw new JWKInvalid(`${description} missing or invalid`); } }; async function calculateJwkThumbprint(jwk, digestAlgorithm) { if (!isObject(jwk)) { throw new TypeError("JWK must be an object"); } digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : digestAlgorithm = "sha256"; if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") { throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); } let components; switch (jwk.kty) { case "EC": check(jwk.crv, '"crv" (Curve) Parameter'); check(jwk.x, '"x" (X Coordinate) Parameter'); check(jwk.y, '"y" (Y Coordinate) Parameter'); components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; break; case "OKP": check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); check(jwk.x, '"x" (Public Key) Parameter'); components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; break; case "RSA": check(jwk.e, '"e" (Exponent) Parameter'); check(jwk.n, '"n" (Modulus) Parameter'); components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; break; case "oct": check(jwk.k, '"k" (Key Value) Parameter'); components = { k: jwk.k, kty: jwk.kty }; break; default: throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); } const data = encoder.encode(JSON.stringify(components)); return encode(await digest_default(digestAlgorithm, data)); } async function calculateJwkThumbprintUri(jwk, digestAlgorithm) { digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : digestAlgorithm = "sha256"; const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm); return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; } // dist/browser/jwk/embedded.js async function EmbeddedJWK(protectedHeader, token) { const joseHeader = { ...protectedHeader, ...token.header }; if (!isObject(joseHeader.jwk)) { throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); } const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg, true); if (key instanceof Uint8Array || key.type !== "public") { throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); } return key; } // dist/browser/jwks/local.js function getKtyFromAlg(alg) { switch (typeof alg === "string" && alg.slice(0, 2)) { case "RS": case "PS": return "RSA"; case "ES": return "EC"; case "Ed": return "OKP"; default: throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); } } function isJWKSLike(jwks) { return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike); } function isJWKLike(key) { return isObject(key); } function clone(obj) { if (typeof structuredClone === "function") { return structuredClone(obj); } return JSON.parse(JSON.stringify(obj)); } var LocalJWKSet = class { constructor(jwks) { this._cached = /* @__PURE__ */ new WeakMap(); if (!isJWKSLike(jwks)) { throw new JWKSInvalid("JSON Web Key Set malformed"); } this._jwks = clone(jwks); } async getKey(protectedHeader, token) { const { alg, kid } = { ...protectedHeader, ...token.header }; const kty = getKtyFromAlg(alg); const candidates = this._jwks.keys.filter((jwk2) => { let candidate = kty === jwk2.kty; if (candidate && typeof kid === "string") { candidate = kid === jwk2.kid; } if (candidate && typeof jwk2.alg === "string") { candidate = alg === jwk2.alg; } if (candidate && typeof jwk2.use === "string") { candidate = jwk2.use === "sig"; } if (candidate && Array.isArray(jwk2.key_ops)) { candidate = jwk2.key_ops.includes("verify"); } if (candidate && alg === "EdDSA") { candidate = jwk2.crv === "Ed25519" || jwk2.crv === "Ed448"; } if (candidate) { switch (alg) { case "ES256": candidate = jwk2.crv === "P-256"; break; case "ES256K": candidate = jwk2.crv === "secp256k1"; break; case "ES384": candidate = jwk2.crv === "P-384"; break; case "ES512": candidate = jwk2.crv === "P-521"; break; } } return candidate; }); const { 0: jwk, length } = candidates; if (length === 0) { throw new JWKSNoMatchingKey(); } else if (length !== 1) { throw new JWKSMultipleMatchingKeys(); } const cached = this._cached.get(jwk) || this._cached.set(jwk, {}).get(jwk); if (cached[alg] === void 0) { const keyObject = await importJWK({ ...jwk, ext: true }, alg); if (keyObject instanceof Uint8Array || keyObject.type !== "public") { throw new JWKSInvalid("JSON Web Key Set members must be public keys"); } cached[alg] = keyObject; } return cached[alg]; } }; function createLocalJWKSet(jwks) { return LocalJWKSet.prototype.getKey.bind(new LocalJWKSet(jwks)); } // dist/browser/runtime/fetch_jwks.js var fetchJwks = async (url, timeout, options) => { let controller; let id; let timedOut = false; if (typeof AbortController === "function") { controller = new AbortController(); id = setTimeout(() => { timedOut = true; controller.abort(); }, timeout); } const response = await fetch(url.href, { signal: controller ? controller.signal : void 0, redirect: "manual", headers: options.headers }).catch((err) => { if (timedOut) throw new JWKSTimeout(); throw err; }); if (id !== void 0) clearTimeout(id); if (response.status !== 200) { throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response"); } try { return await response.json(); } catch (_a) { throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON"); } }; var fetch_jwks_default = fetchJwks; // dist/browser/jwks/remote.js var RemoteJWKSet = class extends LocalJWKSet { constructor(url, options) { super({ keys: [] }); this._jwks = void 0; if (!(url instanceof URL)) { throw new TypeError("url must be an instance of URL"); } this._url = new URL(url.href); this._options = { agent: options === null || options === void 0 ? void 0 : options.agent, headers: options === null || options === void 0 ? void 0 : options.headers }; this._timeoutDuration = typeof (options === null || options === void 0 ? void 0 : options.timeoutDuration) === "number" ? options === null || options === void 0 ? void 0 : options.timeoutDuration : 5e3; this._cooldownDuration = typeof (options === null || options === void 0 ? void 0 : options.cooldownDuration) === "number" ? options === null || options === void 0 ? void 0 : options.cooldownDuration : 3e4; this._cacheMaxAge = typeof (options === null || options === void 0 ? void 0 : options.cacheMaxAge) === "number" ? options === null || options === void 0 ? void 0 : options.cacheMaxAge : 6e5; } coolingDown() { return typeof this._jwksTimestamp === "number" ? Date.now() < this._jwksTimestamp + this._cooldownDuration : false; } fresh() { return typeof this._jwksTimestamp === "number" ? Date.now() < this._jwksTimestamp + this._cacheMaxAge : false; } async getKey(protectedHeader, token) { if (!this._jwks || !this.fresh()) { await this.reload(); } try { return await super.getKey(protectedHeader, token); } catch (err) { if (err instanceof JWKSNoMatchingKey) { if (this.coolingDown() === false) { await this.reload(); return super.getKey(protectedHeader, token); } } throw err; } } async reload() { if (this._pendingFetch && isCloudflareWorkers()) { return new Promise((resolve) => { const isDone = () => { if (this._pendingFetch === void 0) { resolve(); } else { setTimeout(isDone, 5); } }; isDone(); }); } if (!this._pendingFetch) { this._pendingFetch = fetch_jwks_default(this._url, this._timeoutDuration, this._options).then((json) => { if (!isJWKSLike(json)) { throw new JWKSInvalid("JSON Web Key Set malformed"); } this._jwks = { keys: json.keys }; this._jwksTimestamp = Date.now(); this._pendingFetch = void 0; }).catch((err) => { this._pendingFetch = void 0; throw err; }); } await this._pendingFetch; } }; function createRemoteJWKSet(url, options) { return RemoteJWKSet.prototype.getKey.bind(new RemoteJWKSet(url, options)); } // dist/browser/jwt/unsecured.js var UnsecuredJWT = class extends ProduceJWT { encode() { const header = encode(JSON.stringify({ alg: "none" })); const payload = encode(JSON.stringify(this._payload)); return `${header}.${payload}.`; } static decode(jwt, options) { if (typeof jwt !== "string") { throw new JWTInvalid("Unsecured JWT must be a string"); } const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split("."); if (length !== 3 || signature !== "") { throw new JWTInvalid("Invalid Unsecured JWT"); } let header; try { header = JSON.parse(decoder.decode(decode(encodedHeader))); if (header.alg !== "none") throw new Error(); } catch (_a) { throw new JWTInvalid("Invalid Unsecured JWT"); } const payload = jwt_claims_set_default(header, decode(encodedPayload), options); return { payload, header }; } }; // dist/browser/util/base64url.js var base64url_exports2 = {}; __export(base64url_exports2, { decode: () => decode2, encode: () => encode2 }); var encode2 = encode; var decode2 = decode; // dist/browser/util/decode_protected_header.js function decodeProtectedHeader(token) { let protectedB64u; if (typeof token === "string") { const parts = token.split("."); if (parts.length === 3 || parts.length === 5) { ; [protectedB64u] = parts; } } else if (typeof token === "object" && token) { if ("protected" in token) { protectedB64u = token.protected; } else { throw new TypeError("Token does not contain a Protected Header"); } } try { if (typeof protectedB64u !== "string" || !protectedB64u) { throw new Error(); } const result = JSON.parse(decoder.decode(decode2(protectedB64u))); if (!isObject(result)) { throw new Error(); } return result; } catch (_a) { throw new TypeError("Invalid Token or Protected Header formatting"); } } // dist/browser/util/decode_jwt.js function decodeJwt(jwt) { if (typeof jwt !== "string") throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string"); const { 1: payload, length } = jwt.split("."); if (length === 5) throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded"); if (length !== 3) throw new JWTInvalid("Invalid JWT"); if (!payload) throw new JWTInvalid("JWTs must contain a payload"); let decoded; try { decoded = decode2(payload); } catch (_a) { throw new JWTInvalid("Failed to parse the base64url encoded payload"); } let result; try { result = JSON.parse(decoder.decode(decoded)); } catch (_b) { throw new JWTInvalid("Failed to parse the decoded payload as JSON"); } if (!isObject(result)) throw new JWTInvalid("Invalid JWT Claims Set"); return result; } // dist/browser/runtime/generate.js async function generateSecret(alg, options) { var _a; let length; let algorithm; let keyUsages; switch (alg) { case "HS256": case "HS384": case "HS512": length = parseInt(alg.slice(-3), 10); algorithm = { name: "HMAC", hash: `SHA-${length}`, length }; keyUsages = ["sign", "verify"]; break; case "A128CBC-HS256": case "A192CBC-HS384": case "A256CBC-HS512": length = parseInt(alg.slice(-3), 10); return random_default(new Uint8Array(length >> 3)); case "A128KW": case "A192KW": case "A256KW": length = parseInt(alg.slice(1, 4), 10); algorithm = { name: "AES-KW", length }; keyUsages = ["wrapKey", "unwrapKey"]; break; case "A128GCMKW": case "A192GCMKW": case "A256GCMKW": case "A128GCM": case "A192GCM": case "A256GCM": length = parseInt(alg.slice(1, 4), 10); algorithm = { name: "AES-GCM", length }; keyUsages = ["encrypt", "decrypt"]; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } return webcrypto_default.subtle.generateKey(algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages); } function getModulusLengthOption(options) { var _a; const modulusLength = (_a = options === null || options === void 0 ? void 0 : options.modulusLength) !== null && _a !== void 0 ? _a : 2048; if (typeof modulusLength !== "number" || modulusLength < 2048) { throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used"); } return modulusLength; } async function generateKeyPair(alg, options) { var _a, _b, _c, _d; let algorithm; let keyUsages; switch (alg) { case "PS256": case "PS384": case "PS512": algorithm = { name: "RSA-PSS", hash: `SHA-${alg.slice(-3)}`, publicExponent: new Uint8Array([1, 0, 1]), modulusLength: getModulusLengthOption(options) }; keyUsages = ["sign", "verify"]; break; case "RS256": case "RS384": case "RS512": algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${alg.slice(-3)}`, publicExponent: new Uint8Array([1, 0, 1]), modulusLength: getModulusLengthOption(options) }; keyUsages = ["sign", "verify"]; break; case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": algorithm = { name: "RSA-OAEP", hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`, publicExponent: new Uint8Array([1, 0, 1]), modulusLength: getModulusLengthOption(options) }; keyUsages = ["decrypt", "unwrapKey", "encrypt", "wrapKey"]; break; case "ES256": algorithm = { name: "ECDSA", namedCurve: "P-256" }; keyUsages = ["sign", "verify"]; break; case "ES384": algorithm = { name: "ECDSA", namedCurve: "P-384" }; keyUsages = ["sign", "verify"]; break; case "ES512": algorithm = { name: "ECDSA", namedCurve: "P-521" }; keyUsages = ["sign", "verify"]; break; case "EdDSA": keyUsages = ["sign", "verify"]; const crv = (_a = options === null || options === void 0 ? void 0 : options.crv) !== null && _a !== void 0 ? _a : "Ed25519"; switch (crv) { case "Ed25519": case "Ed448": algorithm = { name: crv }; break; default: throw new JOSENotSupported("Invalid or unsupported crv option provided"); } break; case "ECDH-ES": case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": { keyUsages = ["deriveKey", "deriveBits"]; const crv2 = (_b = options === null || options === void 0 ? void 0 : options.crv) !== null && _b !== void 0 ? _b : "P-256"; switch (crv2) { case "P-256": case "P-384": case "P-521": { algorithm = { name: "ECDH", namedCurve: crv2 }; break; } case "X25519": case "X448": algorithm = { name: crv2 }; break; default: throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448"); } break; } default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } try { return await webcrypto_default.subtle.generateKey(algorithm, (_c = options === null || options === void 0 ? void 0 : options.extractable) !== null && _c !== void 0 ? _c : false, keyUsages); } catch (err) { if (algorithm.name === "Ed25519" && (err === null || err === void 0 ? void 0 : err.name) === "NotSupportedError" && isCloudflareWorkers()) { algorithm = { name: "NODE-ED25519", namedCurve: "NODE-ED25519" }; return await webcrypto_default.subtle.generateKey(algorithm, (_d = options === null || options === void 0 ? void 0 : options.extractable) !== null && _d !== void 0 ? _d : false, keyUsages); } throw err; } } // dist/browser/key/generate_key_pair.js async function generateKeyPair2(alg, options) { return generateKeyPair(alg, options); } // dist/browser/key/generate_secret.js async function generateSecret2(alg, options) { return generateSecret(alg, options); } export { CompactEncrypt, CompactSign, EmbeddedJWK, EncryptJWT, FlattenedEncrypt, FlattenedSign, GeneralEncrypt, GeneralSign, SignJWT, UnsecuredJWT, base64url_exports2 as base64url, calculateJwkThumbprint, calculateJwkThumbprintUri, compactDecrypt, compactVerify, createLocalJWKSet, createRemoteJWKSet, decodeJwt, decodeProtectedHeader, errors_exports as errors, exportJWK, exportPKCS8, exportSPKI, flattenedDecrypt, flattenedVerify, generalDecrypt, generalVerify, generateKeyPair2 as generateKeyPair, generateSecret2 as generateSecret, importJWK, importPKCS8, importSPKI, importX509, jwtDecrypt, jwtVerify }; jose-4.11.4/dist/browser/index.bundle.min.js000066400000000000000000001751531437043056600207120ustar00rootroot00000000000000var Xt=Object.defineProperty;var ct=(e,t)=>{for(var r in t)Xt(e,r,{get:t[r],enumerable:!0})};var f=crypto,b=e=>e instanceof CryptoKey;var Yt=async(e,t)=>{let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await f.subtle.digest(r,t))},xe=Yt;var E=new TextEncoder,v=new TextDecoder,He=2**32;function W(...e){let t=e.reduce((o,{length:a})=>o+a,0),r=new Uint8Array(t),n=0;return e.forEach(o=>{r.set(o,n),n+=o.length}),r}function dt(e,t){return W(E.encode(e),new Uint8Array([0]),t)}function Be(e,t,r){if(t<0||t>=He)throw new RangeError(`value must be >= 0 and <= ${He-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function Ce(e){let t=Math.floor(e/He),r=e%He,n=new Uint8Array(8);return Be(n,t,0),Be(n,r,4),n}function Pe(e){let t=new Uint8Array(4);return Be(t,e),t}function We(e){return W(Pe(e.length),e)}async function pt(e,t,r){let n=Math.ceil((t>>3)/32),o=new Uint8Array(n*32);for(let a=0;a>3)}var pe=e=>{let t=e;typeof t=="string"&&(t=E.encode(t));let r=32768,n=[];for(let o=0;ope(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),Le=e=>{let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n{let t=e;t instanceof Uint8Array&&(t=v.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return Le(t)}catch(r){throw new TypeError("The input to be decoded is not correctly encoded.")}};var ft={};ct(ft,{JOSEAlgNotAllowed:()=>B,JOSEError:()=>C,JOSENotSupported:()=>m,JWEDecryptionFailed:()=>M,JWEInvalid:()=>u,JWKInvalid:()=>ue,JWKSInvalid:()=>L,JWKSMultipleMatchingKeys:()=>fe,JWKSNoMatchingKey:()=>q,JWKSTimeout:()=>le,JWSInvalid:()=>h,JWSSignatureVerificationFailed:()=>Z,JWTClaimValidationFailed:()=>J,JWTExpired:()=>re,JWTInvalid:()=>x});var C=class extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(t){var r;super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}},J=class extends C{static get code(){return"ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(t,r="unspecified",n="unspecified"){super(t),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n}},re=class extends C{static get code(){return"ERR_JWT_EXPIRED"}constructor(t,r="unspecified",n="unspecified"){super(t),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n}},B=class extends C{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}},m=class extends C{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}},M=class extends C{constructor(){super(...arguments),this.code="ERR_JWE_DECRYPTION_FAILED",this.message="decryption operation failed"}static get code(){return"ERR_JWE_DECRYPTION_FAILED"}},u=class extends C{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}static get code(){return"ERR_JWE_INVALID"}},h=class extends C{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},x=class extends C{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}},ue=class extends C{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}static get code(){return"ERR_JWK_INVALID"}},L=class extends C{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}static get code(){return"ERR_JWKS_INVALID"}},q=class extends C{constructor(){super(...arguments),this.code="ERR_JWKS_NO_MATCHING_KEY",this.message="no applicable key found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_NO_MATCHING_KEY"}},fe=class extends C{constructor(){super(...arguments),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",this.message="multiple matching keys found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}},le=class extends C{constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out"}static get code(){return"ERR_JWKS_TIMEOUT"}},Z=class extends C{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}};var $=f.getRandomValues.bind(f);function $e(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new m(`Unsupported JWE Algorithm: ${e}`)}}var Je=e=>$(new Uint8Array($e(e)>>3));var qt=(e,t)=>{if(t.length<<3!==$e(e))throw new u("Invalid Initialization Vector length")},Te=qt;var Zt=(e,t)=>{let r=e.byteLength<<3;if(r!==t)throw new u(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)},ne=Zt;var Qt=(e,t)=>{if(!(e instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");if(e.length!==t.length)throw new TypeError("Input buffers must have the same length");let r=e.length,n=0,o=-1;for(;++oe.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function ht(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!N(e.algorithm,"HMAC"))throw P("HMAC");let n=parseInt(t.slice(2),10);if(Ie(e.algorithm.hash)!==n)throw P(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!N(e.algorithm,"RSASSA-PKCS1-v1_5"))throw P("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(Ie(e.algorithm.hash)!==n)throw P(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!N(e.algorithm,"RSA-PSS"))throw P("RSA-PSS");let n=parseInt(t.slice(2),10);if(Ie(e.algorithm.hash)!==n)throw P(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448"){if(D()){if(N(e.algorithm,"NODE-ED25519"))break;throw P("Ed25519, Ed448, or NODE-ED25519")}throw P("Ed25519 or Ed448")}break}case"ES256":case"ES384":case"ES512":{if(!N(e.algorithm,"ECDSA"))throw P("ECDSA");let n=jt(t);if(e.algorithm.namedCurve!==n)throw P(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}mt(e,r)}function I(e,t,...r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!N(e.algorithm,"AES-GCM"))throw P("AES-GCM");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw P(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!N(e.algorithm,"AES-KW"))throw P("AES-KW");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw P(n,"algorithm.length");break}case"ECDH":{switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw P("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!N(e.algorithm,"PBKDF2"))throw P("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!N(e.algorithm,"RSA-OAEP"))throw P("RSA-OAEP");let n=parseInt(t.slice(9),10)||1;if(Ie(e.algorithm.hash)!==n)throw P(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}mt(e,r)}function yt(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var A=(e,...t)=>yt("Key must be ",e,...t);function Ge(e,t,...r){return yt(`Key for the ${e} algorithm must be `,t,...r)}var Ve=e=>b(e),y=["CryptoKey"];async function er(e,t,r,n,o,a){if(!(t instanceof Uint8Array))throw new TypeError(A(t,"Uint8Array"));let i=parseInt(e.slice(1,4),10),s=await f.subtle.importKey("raw",t.subarray(i>>3),"AES-CBC",!1,["decrypt"]),c=await f.subtle.importKey("raw",t.subarray(0,i>>3),{hash:`SHA-${i<<1}`,name:"HMAC"},!1,["sign"]),p=W(a,n,r,Ce(a.length<<3)),d=new Uint8Array((await f.subtle.sign("HMAC",c,p)).slice(0,i>>3)),l;try{l=lt(o,d)}catch(T){}if(!l)throw new M;let H;try{H=new Uint8Array(await f.subtle.decrypt({iv:n,name:"AES-CBC"},s,r))}catch(T){}if(!H)throw new M;return H}async function tr(e,t,r,n,o,a){let i;t instanceof Uint8Array?i=await f.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(I(t,e,"decrypt"),i=t);try{return new Uint8Array(await f.subtle.decrypt({additionalData:a,iv:n,name:"AES-GCM",tagLength:128},i,W(r,o)))}catch(s){throw new M}}var rr=async(e,t,r,n,o,a)=>{if(!b(t)&&!(t instanceof Uint8Array))throw new TypeError(A(t,...y,"Uint8Array"));switch(Te(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&ne(t,parseInt(e.slice(-3),10)),er(e,t,r,n,o,a);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&ne(t,parseInt(e.slice(1,4),10)),tr(e,t,r,n,o,a);default:throw new m("Unsupported JWE Content Encryption Algorithm")}},De=rr;var wt=async()=>{throw new m('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.')},Et=async()=>{throw new m('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.')};var nr=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let a of o){if(r.has(a))return!1;r.add(a)}}return!0},R=nr;function or(e){return typeof e=="object"&&e!==null}function w(e){if(!or(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var ar=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]],oe=ar;function gt(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function St(e,t,r){if(b(e))return I(e,t,r),e;if(e instanceof Uint8Array)return f.subtle.importKey("raw",e,"AES-KW",!0,[r]);throw new TypeError(A(e,...y,"Uint8Array"))}var me=async(e,t,r)=>{let n=await St(t,e,"wrapKey");gt(n,e);let o=await f.subtle.importKey("raw",r,...oe);return new Uint8Array(await f.subtle.wrapKey("raw",o,n,"AES-KW"))},he=async(e,t,r)=>{let n=await St(t,e,"unwrapKey");gt(n,e);let o=await f.subtle.unwrapKey("raw",r,n,"AES-KW",...oe);return new Uint8Array(await f.subtle.exportKey("raw",o))};async function Re(e,t,r,n,o=new Uint8Array(0),a=new Uint8Array(0)){if(!b(e))throw new TypeError(A(e,...y));if(I(e,"ECDH"),!b(t))throw new TypeError(A(t,...y));I(t,"ECDH","deriveBits");let i=W(We(E.encode(r)),We(o),We(a),Pe(n)),s;e.algorithm.name==="X25519"?s=256:e.algorithm.name==="X448"?s=448:s=Math.ceil(parseInt(e.algorithm.namedCurve.substr(-3),10)/8)<<3;let c=new Uint8Array(await f.subtle.deriveBits({name:e.algorithm.name,public:e},t,s));return pt(c,n,i)}async function At(e){if(!b(e))throw new TypeError(A(e,...y));return f.subtle.generateKey(e.algorithm,!0,["deriveBits"])}function Oe(e){if(!b(e))throw new TypeError(A(e,...y));return["P-256","P-384","P-521"].includes(e.algorithm.namedCurve)||e.algorithm.name==="X25519"||e.algorithm.name==="X448"}function Fe(e){if(!(e instanceof Uint8Array)||e.length<8)throw new u("PBES2 Salt Input must be 8 or more octets")}function ir(e,t){if(e instanceof Uint8Array)return f.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);if(b(e))return I(e,t,"deriveBits","deriveKey"),e;throw new TypeError(A(e,...y,"Uint8Array"))}async function _t(e,t,r,n){Fe(e);let o=dt(t,e),a=parseInt(t.slice(13,16),10),i={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:o},s={length:a,name:"AES-KW"},c=await ir(n,t);if(c.usages.includes("deriveBits"))return new Uint8Array(await f.subtle.deriveBits(i,c,a));if(c.usages.includes("deriveKey"))return f.subtle.deriveKey(i,c,s,!1,["wrapKey","unwrapKey"]);throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}var vt=async(e,t,r,n=2048,o=$(new Uint8Array(16)))=>{let a=await _t(o,e,n,t);return{encryptedKey:await me(e.slice(-6),a,r),p2c:n,p2s:g(o)}},Kt=async(e,t,r,n,o)=>{let a=await _t(o,e,n,t);return he(e.slice(-6),a,r)};function ae(e){switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Q=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};var xt=async(e,t,r)=>{if(!b(t))throw new TypeError(A(t,...y));if(I(t,e,"encrypt","wrapKey"),Q(e,t),t.usages.includes("encrypt"))return new Uint8Array(await f.subtle.encrypt(ae(e),t,r));if(t.usages.includes("wrapKey")){let n=await f.subtle.importKey("raw",r,...oe);return new Uint8Array(await f.subtle.wrapKey("raw",n,t,ae(e)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},Ht=async(e,t,r)=>{if(!b(t))throw new TypeError(A(t,...y));if(I(t,e,"decrypt","unwrapKey"),Q(e,t),t.usages.includes("decrypt"))return new Uint8Array(await f.subtle.decrypt(ae(e),t,r));if(t.usages.includes("unwrapKey")){let n=await f.subtle.unwrapKey("raw",r,t,ae(e),...oe);return new Uint8Array(await f.subtle.exportKey("raw",n))}throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')};function ye(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new m(`Unsupported JWE Algorithm: ${e}`)}}var O=e=>$(new Uint8Array(ye(e)>>3));var Ue=(e,t)=>{let r=(e.match(/.{1,64}/g)||[]).join(` `);return`-----BEGIN ${t}----- ${r} -----END ${t}-----`};var Pt=async(e,t,r)=>{if(!b(r))throw new TypeError(A(r,...y));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return Ue(pe(new Uint8Array(await f.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},Wt=e=>Pt("public","spki",e),Jt=e=>Pt("private","pkcs8",e),G=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return!1;let o=e.subarray(n,n+t.length);return o.length!==t.length?!1:o.every((a,i)=>a===t[i])||G(e,t,n+1)},Ct=e=>{switch(!0){case G(e,[42,134,72,206,61,3,1,7]):return"P-256";case G(e,[43,129,4,0,34]):return"P-384";case G(e,[43,129,4,0,35]):return"P-521";case G(e,[43,101,110]):return"X25519";case G(e,[43,101,111]):return"X448";case G(e,[43,101,112]):return"Ed25519";case G(e,[43,101,113]):return"Ed448";default:throw new m("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Tt=async(e,t,r,n,o)=>{var a,i;let s,c,p=new Uint8Array(atob(r.replace(e,"")).split("").map(l=>l.charCodeAt(0))),d=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":s={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},c=d?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":s={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},c=d?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},c=d?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":s={name:"ECDSA",namedCurve:"P-256"},c=d?["verify"]:["sign"];break;case"ES384":s={name:"ECDSA",namedCurve:"P-384"},c=d?["verify"]:["sign"];break;case"ES512":s={name:"ECDSA",namedCurve:"P-521"},c=d?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let l=Ct(p);s=l.startsWith("P-")?{name:"ECDH",namedCurve:l}:{name:l},c=d?[]:["deriveBits"];break}case"EdDSA":s={name:Ct(p)},c=d?["verify"]:["sign"];break;default:throw new m('Invalid or unsupported "alg" (Algorithm) value')}try{return await f.subtle.importKey(t,p,s,(a=o==null?void 0:o.extractable)!==null&&a!==void 0?a:!1,c)}catch(l){if(s.name==="Ed25519"&&(l==null?void 0:l.name)==="NotSupportedError"&&D())return s={name:"NODE-ED25519",namedCurve:"NODE-ED25519"},await f.subtle.importKey(t,p,s,(i=o==null?void 0:o.extractable)!==null&&i!==void 0?i:!1,c);throw l}},It=(e,t,r)=>Tt(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),ze=(e,t,r)=>Tt(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);function sr(e){let t,r;switch(e.kty){case"oct":{switch(e.alg){case"HS256":case"HS384":case"HS512":t={name:"HMAC",hash:`SHA-${e.alg.slice(-3)}`},r=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":throw new m(`${e.alg} keys cannot be imported as CryptoKey instances`);case"A128GCM":case"A192GCM":case"A256GCM":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":t={name:"AES-GCM"},r=["encrypt","decrypt"];break;case"A128KW":case"A192KW":case"A256KW":t={name:"AES-KW"},r=["wrapKey","unwrapKey"];break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":t={name:"PBKDF2"},r=["deriveBits"];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new m('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}var cr=async e=>{var t,r;let{algorithm:n,keyUsages:o}=sr(e),a=[n,(t=e.ext)!==null&&t!==void 0?t:!1,(r=e.key_ops)!==null&&r!==void 0?r:o];if(n.name==="PBKDF2")return f.subtle.importKey("raw",S(e.k),...a);let i={...e};delete i.alg,delete i.use;try{return await f.subtle.importKey("jwk",i,...a)}catch(s){if(n.name==="Ed25519"&&(s==null?void 0:s.name)==="NotSupportedError"&&D())return a[0]={name:"NODE-ED25519",namedCurve:"NODE-ED25519"},await f.subtle.importKey("jwk",i,...a);throw s}},Xe=cr;function Dt(e){let t=[],r=0;for(;r=128;)r=r*128+e[t]-128,t++;r=r*128+e[t]-128,t++}let n=0;if(e[t]<128)n=e[t],t++;else if(n===128){for(n=0;e[t+n]!==0||e[t+n+1]!==0;){if(n>e.byteLength)throw new TypeError("invalid indefinite form length");n++}let a=t+n+2;return{byteLength:a,contents:e.subarray(t,t+n),raw:e.subarray(0,a)}}else{let a=e[t]&127;t++,n=0;for(let i=0;i{if(!(t instanceof Uint8Array)){if(!Ve(t))throw new TypeError(Ge(e,t,...y,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${y.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},hr=(e,t,r)=>{if(!Ve(t))throw new TypeError(Ge(e,t,...y));if(t.type==="secret")throw new TypeError(`${y.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${y.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${y.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${y.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${y.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},yr=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?mr(e,t):hr(e,t,r)},V=yr;async function wr(e,t,r,n,o){if(!(r instanceof Uint8Array))throw new TypeError(A(r,"Uint8Array"));let a=parseInt(e.slice(1,4),10),i=await f.subtle.importKey("raw",r.subarray(a>>3),"AES-CBC",!1,["encrypt"]),s=await f.subtle.importKey("raw",r.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),c=new Uint8Array(await f.subtle.encrypt({iv:n,name:"AES-CBC"},i,t)),p=W(o,n,c,Ce(o.length<<3)),d=new Uint8Array((await f.subtle.sign("HMAC",s,p)).slice(0,a>>3));return{ciphertext:c,tag:d}}async function Er(e,t,r,n,o){let a;r instanceof Uint8Array?a=await f.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(I(r,e,"encrypt"),a=r);let i=new Uint8Array(await f.subtle.encrypt({additionalData:o,iv:n,name:"AES-GCM",tagLength:128},a,t)),s=i.slice(-16);return{ciphertext:i.slice(0,-16),tag:s}}var gr=async(e,t,r,n,o)=>{if(!b(r)&&!(r instanceof Uint8Array))throw new TypeError(A(r,...y,"Uint8Array"));switch(Te(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&ne(r,parseInt(e.slice(-3),10)),wr(e,t,r,n,o);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&ne(r,parseInt(e.slice(1,4),10)),Er(e,t,r,n,o);default:throw new m("Unsupported JWE Content Encryption Algorithm")}},we=gr;async function Ot(e,t,r,n){let o=e.slice(0,7);n||(n=Je(o));let{ciphertext:a,tag:i}=await we(o,r,t,n,new Uint8Array(0));return{encryptedKey:a,iv:g(n),tag:g(i)}}async function Ut(e,t,r,n,o){let a=e.slice(0,7);return De(a,t,r,n,o,new Uint8Array(0))}async function Sr(e,t,r,n,o){switch(V(e,t,"decrypt"),e){case"dir":{if(r!==void 0)throw new u("Encountered unexpected JWE Encrypted Key");return t}case"ECDH-ES":if(r!==void 0)throw new u("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!w(n.epk))throw new u('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!Oe(t))throw new m("ECDH with the provided key is not allowed or not supported by your javascript runtime");let a=await j(n.epk,e),i,s;if(n.apu!==void 0){if(typeof n.apu!="string")throw new u('JOSE Header "apu" (Agreement PartyUInfo) invalid');i=S(n.apu)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new u('JOSE Header "apv" (Agreement PartyVInfo) invalid');s=S(n.apv)}let c=await Re(a,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?ye(n.enc):parseInt(e.slice(-5,-2),10),i,s);if(e==="ECDH-ES")return c;if(r===void 0)throw new u("JWE Encrypted Key missing");return he(e.slice(-6),c,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(r===void 0)throw new u("JWE Encrypted Key missing");return Ht(e,t,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new u("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new u('JOSE Header "p2c" (PBES2 Count) missing or invalid');let a=(o==null?void 0:o.maxPBES2Count)||1e4;if(n.p2c>a)throw new u('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new u('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return Kt(e,t,r,n.p2c,S(n.p2s))}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new u("JWE Encrypted Key missing");return he(e,t,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new u("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new u('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new u('JOSE Header "tag" (Authentication Tag) missing or invalid');let a=S(n.iv),i=S(n.tag);return Ut(e,t,r,a,i)}default:throw new m('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var Mt=Sr;function Ar(e,t,r,n,o){if(o.crit!==void 0&&n.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let i of n.crit){if(!a.has(i))throw new m(`Extension Header Parameter "${i}" is not recognized`);if(o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(a.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var U=Ar;var br=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)},Ee=br;async function ge(e,t,r){var n;if(!w(e))throw new u("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new u("JOSE Header missing");if(typeof e.iv!="string")throw new u("JWE Initialization Vector missing or incorrect type");if(typeof e.ciphertext!="string")throw new u("JWE Ciphertext missing or incorrect type");if(typeof e.tag!="string")throw new u("JWE Authentication Tag missing or incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new u("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new u("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new u("JWE AAD incorrect type");if(e.header!==void 0&&!w(e.header))throw new u("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!w(e.unprotected))throw new u("JWE Per-Recipient Unprotected Header incorrect type");let o;if(e.protected)try{let Y=S(e.protected);o=JSON.parse(v.decode(Y))}catch(Y){throw new u("JWE Protected Header is invalid")}if(!R(o,e.header,e.unprotected))throw new u("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let a={...o,...e.header,...e.unprotected};if(U(u,new Map,r==null?void 0:r.crit,o,a),a.zip!==void 0){if(!o||!o.zip)throw new u('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(a.zip!=="DEF")throw new m('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:i,enc:s}=a;if(typeof i!="string"||!i)throw new u("missing JWE Algorithm (alg) in JWE Header");if(typeof s!="string"||!s)throw new u("missing JWE Encryption Algorithm (enc) in JWE Header");let c=r&&Ee("keyManagementAlgorithms",r.keyManagementAlgorithms),p=r&&Ee("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(c&&!c.has(i))throw new B('"alg" (Algorithm) Header Parameter not allowed');if(p&&!p.has(s))throw new B('"enc" (Encryption Algorithm) Header Parameter not allowed');let d;e.encrypted_key!==void 0&&(d=S(e.encrypted_key));let l=!1;typeof t=="function"&&(t=await t(o,e),l=!0);let H;try{H=await Mt(i,t,d,a,r)}catch(Y){if(Y instanceof TypeError||Y instanceof u||Y instanceof m)throw Y;H=O(s)}let T=S(e.iv),K=S(e.tag),_=E.encode((n=e.protected)!==null&&n!==void 0?n:""),k;e.aad!==void 0?k=W(_,E.encode("."),E.encode(e.aad)):k=_;let ke=await De(s,H,S(e.ciphertext),T,K,k);a.zip==="DEF"&&(ke=await((r==null?void 0:r.inflateRaw)||wt)(ke));let te={plaintext:ke};return e.protected!==void 0&&(te.protectedHeader=o),e.aad!==void 0&&(te.additionalAuthenticatedData=S(e.aad)),e.unprotected!==void 0&&(te.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(te.unprotectedHeader=e.header),l?{...te,key:t}:te}async function Ye(e,t,r){if(e instanceof Uint8Array&&(e=v.decode(e)),typeof e!="string")throw new u("Compact JWE must be a string or Uint8Array");let{0:n,1:o,2:a,3:i,4:s,length:c}=e.split(".");if(c!==5)throw new u("Invalid Compact JWE");let p=await ge({ciphertext:i,iv:a||void 0,protected:n||void 0,tag:s||void 0,encrypted_key:o||void 0},t,r),d={plaintext:p.plaintext,protectedHeader:p.protectedHeader};return typeof t=="function"?{...d,key:p.key}:d}async function _r(e,t,r){if(!w(e))throw new u("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(w))throw new u("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new u("JWE Recipients has no members");for(let n of e.recipients)try{return await ge({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch(o){}throw new M}var vr=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:g(e)};if(!b(e))throw new TypeError(A(e,...y,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:o,...a}=await f.subtle.exportKey("jwk",e);return a},Nt=vr;async function Kr(e){return Wt(e)}async function xr(e){return Jt(e)}async function qe(e){return Nt(e)}async function Hr(e,t,r,n,o={}){let a,i,s;switch(V(e,r,"encrypt"),e){case"dir":{s=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Oe(r))throw new m("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:c,apv:p}=o,{epk:d}=o;d||(d=(await At(r)).privateKey);let{x:l,y:H,crv:T,kty:K}=await qe(d),_=await Re(r,d,e==="ECDH-ES"?t:e,e==="ECDH-ES"?ye(t):parseInt(e.slice(-5,-2),10),c,p);if(i={epk:{x:l,crv:T,kty:K}},K==="EC"&&(i.epk.y=H),c&&(i.apu=g(c)),p&&(i.apv=g(p)),e==="ECDH-ES"){s=_;break}s=n||O(t);let k=e.slice(-6);a=await me(k,_,s);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{s=n||O(t),a=await xt(e,r,s);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=n||O(t);let{p2c:c,p2s:p}=o;({encryptedKey:a,...i}=await vt(e,r,s,c,p));break}case"A128KW":case"A192KW":case"A256KW":{s=n||O(t),a=await me(e,r,s);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=n||O(t);let{iv:c}=o;({encryptedKey:a,...i}=await Ot(e,r,s,c));break}default:throw new m('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:s,encryptedKey:a,parameters:i}}var Me=Hr;var Ze=Symbol(),F=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=t}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}async encrypt(t,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new u("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!R(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new u("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(U(u,new Map,r==null?void 0:r.crit,this._protectedHeader,n),n.zip!==void 0){if(!this._protectedHeader||!this._protectedHeader.zip)throw new u('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(n.zip!=="DEF")throw new m('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:o,enc:a}=n;if(typeof o!="string"||!o)throw new u('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof a!="string"||!a)throw new u('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let i;if(o==="dir"){if(this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption")}else if(o==="ECDH-ES"&&this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");let s;{let K;({cek:s,encryptedKey:i,parameters:K}=await Me(o,a,t,this._cek,this._keyManagementParameters)),K&&(r&&Ze in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...K}:this.setUnprotectedHeader(K):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...K}:this.setProtectedHeader(K))}this._iv||(this._iv=Je(a));let c,p,d;this._protectedHeader?p=E.encode(g(JSON.stringify(this._protectedHeader))):p=E.encode(""),this._aad?(d=g(this._aad),c=W(p,E.encode("."),E.encode(d))):c=p;let l,H;if(n.zip==="DEF"){let K=await((r==null?void 0:r.deflateRaw)||Et)(this._plaintext);({ciphertext:l,tag:H}=await we(a,K,s,this._iv,c))}else({ciphertext:l,tag:H}=await we(a,this._plaintext,s,this._iv,c));let T={ciphertext:g(l),iv:g(this._iv),tag:g(H)};return i&&(T.encrypted_key=g(i)),d&&(T.aad=d),this._protectedHeader&&(T.protected=v.decode(p)),this._sharedUnprotectedHeader&&(T.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(T.header=this._unprotectedHeader),T}};var Qe=class{constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addRecipient(...t){return this.parent.addRecipient(...t)}encrypt(...t){return this.parent.encrypt(...t)}done(){return this.parent}},je=class{constructor(t){this._recipients=[],this._plaintext=t}addRecipient(t,r){let n=new Qe(this,t,{crit:r==null?void 0:r.crit});return this._recipients.push(n),n}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}async encrypt(t){var r,n,o;if(!this._recipients.length)throw new u("at least one recipient must be added");if(t={deflateRaw:t==null?void 0:t.deflateRaw},this._recipients.length===1){let[c]=this._recipients,p=await new F(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(c.unprotectedHeader).encrypt(c.key,{...c.options,...t}),d={ciphertext:p.ciphertext,iv:p.iv,recipients:[{}],tag:p.tag};return p.aad&&(d.aad=p.aad),p.protected&&(d.protected=p.protected),p.unprotected&&(d.unprotected=p.unprotected),p.encrypted_key&&(d.recipients[0].encrypted_key=p.encrypted_key),p.header&&(d.recipients[0].header=p.header),d}let a;for(let c=0;c>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return D()&&t.name==="NODE-ED25519"?{name:"NODE-ED25519",namedCurve:"NODE-ED25519"}:{name:t.name};default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function Ae(e,t,r){if(b(t))return ht(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(A(t,...y));return f.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(A(t,...y,"Uint8Array"))}var Cr=async(e,t,r,n)=>{let o=await Ae(e,t,"verify");Q(e,o);let a=Se(e,o.algorithm);try{return await f.subtle.verify(a,o,r,n)}catch(i){return!1}},kt=Cr;async function be(e,t,r){var n;if(!w(e))throw new h("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new h('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new h("JWS Protected Header incorrect type");if(e.payload===void 0)throw new h("JWS Payload missing");if(typeof e.signature!="string")throw new h("JWS Signature missing or incorrect type");if(e.header!==void 0&&!w(e.header))throw new h("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{let k=S(e.protected);o=JSON.parse(v.decode(k))}catch(k){throw new h("JWS Protected Header is invalid")}if(!R(o,e.header))throw new h("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let a={...o,...e.header},i=U(h,new Map([["b64",!0]]),r==null?void 0:r.crit,o,a),s=!0;if(i.has("b64")&&(s=o.b64,typeof s!="boolean"))throw new h('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:c}=a;if(typeof c!="string"||!c)throw new h('JWS "alg" (Algorithm) Header Parameter missing or invalid');let p=r&&Ee("algorithms",r.algorithms);if(p&&!p.has(c))throw new B('"alg" (Algorithm) Header Parameter not allowed');if(s){if(typeof e.payload!="string")throw new h("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new h("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof t=="function"&&(t=await t(o,e),d=!0),V(c,t,"verify");let l=W(E.encode((n=e.protected)!==null&&n!==void 0?n:""),E.encode("."),typeof e.payload=="string"?E.encode(e.payload):e.payload),H=S(e.signature);if(!await kt(c,t,H,l))throw new Z;let K;s?K=S(e.payload):typeof e.payload=="string"?K=E.encode(e.payload):K=e.payload;let _={payload:K};return e.protected!==void 0&&(_.protectedHeader=o),e.header!==void 0&&(_.unprotectedHeader=e.header),d?{..._,key:t}:_}async function et(e,t,r){if(e instanceof Uint8Array&&(e=v.decode(e)),typeof e!="string")throw new h("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:a,length:i}=e.split(".");if(i!==3)throw new h("Invalid Compact JWS");let s=await be({payload:o,protected:n,signature:a},t,r),c={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t=="function"?{...c,key:s.key}:c}async function Pr(e,t,r){if(!w(e))throw new h("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(w))throw new h("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await be({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch(o){}throw new Z}var ie=e=>Math.floor(e.getTime()/1e3);var Wr=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,se=e=>{let t=Wr.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}};var Bt=e=>e.toLowerCase().replace(/^application\//,""),Jr=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,ce=(e,t,r={})=>{let{typ:n}=r;if(n&&(typeof e.typ!="string"||Bt(e.typ)!==Bt(n)))throw new J('unexpected "typ" JWT header value',"typ","check_failed");let o;try{o=JSON.parse(v.decode(t))}catch(l){}if(!w(o))throw new x("JWT Claims Set must be a top-level JSON object");let{issuer:a}=r;if(a&&!(Array.isArray(a)?a:[a]).includes(o.iss))throw new J('unexpected "iss" claim value',"iss","check_failed");let{subject:i}=r;if(i&&o.sub!==i)throw new J('unexpected "sub" claim value',"sub","check_failed");let{audience:s}=r;if(s&&!Jr(o.aud,typeof s=="string"?[s]:s))throw new J('unexpected "aud" claim value',"aud","check_failed");let c;switch(typeof r.clockTolerance){case"string":c=se(r.clockTolerance);break;case"number":c=r.clockTolerance;break;case"undefined":c=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=r,d=ie(p||new Date);if((o.iat!==void 0||r.maxTokenAge)&&typeof o.iat!="number")throw new J('"iat" claim must be a number',"iat","invalid");if(o.nbf!==void 0){if(typeof o.nbf!="number")throw new J('"nbf" claim must be a number',"nbf","invalid");if(o.nbf>d+c)throw new J('"nbf" claim timestamp check failed',"nbf","check_failed")}if(o.exp!==void 0){if(typeof o.exp!="number")throw new J('"exp" claim must be a number',"exp","invalid");if(o.exp<=d-c)throw new re('"exp" claim timestamp check failed',"exp","check_failed")}if(r.maxTokenAge){let l=d-o.iat,H=typeof r.maxTokenAge=="number"?r.maxTokenAge:se(r.maxTokenAge);if(l-c>H)throw new re('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(l<0-c)throw new J('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return o};async function Tr(e,t,r){var n;let o=await et(e,t,r);if(!((n=o.protectedHeader.crit)===null||n===void 0)&&n.includes("b64")&&o.protectedHeader.b64===!1)throw new x("JWTs MUST NOT use unencoded payload");let i={payload:ce(o.protectedHeader,o.payload,r),protectedHeader:o.protectedHeader};return typeof t=="function"?{...i,key:o.key}:i}async function Ir(e,t,r){let n=await Ye(e,t,r),o=ce(n.protectedHeader,n.plaintext,r),{protectedHeader:a}=n;if(a.iss!==void 0&&a.iss!==o.iss)throw new J('replicated "iss" claim header parameter mismatch',"iss","mismatch");if(a.sub!==void 0&&a.sub!==o.sub)throw new J('replicated "sub" claim header parameter mismatch',"sub","mismatch");if(a.aud!==void 0&&JSON.stringify(a.aud)!==JSON.stringify(o.aud))throw new J('replicated "aud" claim header parameter mismatch',"aud","mismatch");let i={payload:o,protectedHeader:a};return typeof t=="function"?{...i,key:n.key}:i}var _e=class{constructor(t){this._flattened=new F(t)}setContentEncryptionKey(t){return this._flattened.setContentEncryptionKey(t),this}setInitializationVector(t){return this._flattened.setInitializationVector(t),this}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}setKeyManagementParameters(t){return this._flattened.setKeyManagementParameters(t),this}async encrypt(t,r){let n=await this._flattened.encrypt(t,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}};var Dr=async(e,t,r)=>{let n=await Ae(e,t,"sign");Q(e,n);let o=await f.subtle.sign(Se(e,n.algorithm),n,r);return new Uint8Array(o)},Lt=Dr;var ee=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new h("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!R(this._protectedHeader,this._unprotectedHeader))throw new h("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},o=U(h,new Map([["b64",!0]]),r==null?void 0:r.crit,this._protectedHeader,n),a=!0;if(o.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new h('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new h('JWS "alg" (Algorithm) Header Parameter missing or invalid');V(i,t,"sign");let s=this._payload;a&&(s=E.encode(g(s)));let c;this._protectedHeader?c=E.encode(g(JSON.stringify(this._protectedHeader))):c=E.encode("");let p=W(c,E.encode("."),s),d=await Lt(i,t,p),l={signature:g(d),payload:""};return a&&(l.payload=v.decode(s)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=v.decode(c)),l}};var ve=class{constructor(t){this._flattened=new ee(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};var tt=class{constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setProtectedHeader(t){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=t,this}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addSignature(...t){return this.parent.addSignature(...t)}sign(...t){return this.parent.sign(...t)}done(){return this.parent}},rt=class{constructor(t){this._signatures=[],this._payload=t}addSignature(t,r){let n=new tt(this,t,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new h("at least one signature must be added");let t={signatures:[],payload:""};for(let r=0;r{if(typeof e!="string"||!e)throw new ue(`${t} missing or invalid`)};async function $t(e,t){if(!w(e))throw new TypeError("JWK must be an object");if(t!=null||(t="sha256"),t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":X(e.crv,'"crv" (Curve) Parameter'),X(e.x,'"x" (X Coordinate) Parameter'),X(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":X(e.crv,'"crv" (Subtype of Key Pair) Parameter'),X(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":X(e.e,'"e" (Exponent) Parameter'),X(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":X(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new m('"kty" (Key Type) Parameter missing or unsupported')}let n=E.encode(JSON.stringify(r));return g(await xe(t,n))}async function Rr(e,t){t!=null||(t="sha256");let r=await $t(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}async function Or(e,t){let r={...e,...t.header};if(!w(r.jwk))throw new h('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await j({...r.jwk,ext:!0},r.alg,!0);if(n instanceof Uint8Array||n.type!=="public")throw new h('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}function Ur(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new m('Unsupported "alg" value for a JSON Web Key Set')}}function at(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(Mr)}function Mr(e){return w(e)}function Nr(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}var de=class{constructor(t){if(this._cached=new WeakMap,!at(t))throw new L("JSON Web Key Set malformed");this._jwks=Nr(t)}async getKey(t,r){let{alg:n,kid:o}={...t,...r.header},a=Ur(n),i=this._jwks.keys.filter(d=>{let l=a===d.kty;if(l&&typeof o=="string"&&(l=o===d.kid),l&&typeof d.alg=="string"&&(l=n===d.alg),l&&typeof d.use=="string"&&(l=d.use==="sig"),l&&Array.isArray(d.key_ops)&&(l=d.key_ops.includes("verify")),l&&n==="EdDSA"&&(l=d.crv==="Ed25519"||d.crv==="Ed448"),l)switch(n){case"ES256":l=d.crv==="P-256";break;case"ES256K":l=d.crv==="secp256k1";break;case"ES384":l=d.crv==="P-384";break;case"ES512":l=d.crv==="P-521";break}return l}),{0:s,length:c}=i;if(c===0)throw new q;if(c!==1)throw new fe;let p=this._cached.get(s)||this._cached.set(s,{}).get(s);if(p[n]===void 0){let d=await j({...s,ext:!0},n);if(d instanceof Uint8Array||d.type!=="public")throw new L("JSON Web Key Set members must be public keys");p[n]=d}return p[n]}};function kr(e){return de.prototype.getKey.bind(new de(e))}var Br=async(e,t,r)=>{let n,o,a=!1;typeof AbortController=="function"&&(n=new AbortController,o=setTimeout(()=>{a=!0,n.abort()},t));let i=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(s=>{throw a?new le:s});if(o!==void 0&&clearTimeout(o),i.status!==200)throw new C("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch(s){throw new C("Failed to parse the JSON Web Key Set HTTP response as JSON")}},Gt=Br;var Ne=class extends de{constructor(t,r){if(super({keys:[]}),this._jwks=void 0,!(t instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(t.href),this._options={agent:r==null?void 0:r.agent,headers:r==null?void 0:r.headers},this._timeoutDuration=typeof(r==null?void 0:r.timeoutDuration)=="number"?r==null?void 0:r.timeoutDuration:5e3,this._cooldownDuration=typeof(r==null?void 0:r.cooldownDuration)=="number"?r==null?void 0:r.cooldownDuration:3e4,this._cacheMaxAge=typeof(r==null?void 0:r.cacheMaxAge)=="number"?r==null?void 0:r.cacheMaxAge:6e5}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now(){let r=()=>{this._pendingFetch===void 0?t():setTimeout(r,5)};r()});this._pendingFetch||(this._pendingFetch=Gt(this._url,this._timeoutDuration,this._options).then(t=>{if(!at(t))throw new L("JSON Web Key Set malformed");this._jwks={keys:t.keys},this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(t=>{throw this._pendingFetch=void 0,t})),await this._pendingFetch}};function Lr(e,t){return Ne.prototype.getKey.bind(new Ne(e,t))}var it=class extends z{encode(){let t=g(JSON.stringify({alg:"none"})),r=g(JSON.stringify(this._payload));return`${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new x("Unsecured JWT must be a string");let{0:n,1:o,2:a,length:i}=t.split(".");if(i!==3||a!=="")throw new x("Invalid Unsecured JWT");let s;try{if(s=JSON.parse(v.decode(S(n))),s.alg!=="none")throw new Error}catch(p){throw new x("Invalid Unsecured JWT")}return{payload:ce(s,S(o),r),header:s}}};var Vt={};ct(Vt,{decode:()=>Ke,encode:()=>$r});var $r=g,Ke=S;function Gr(e){let t;if(typeof e=="string"){let r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let r=JSON.parse(v.decode(Ke(t)));if(!w(r))throw new Error;return r}catch(r){throw new TypeError("Invalid Token or Protected Header formatting")}}function Vr(e){if(typeof e!="string")throw new x("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new x("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new x("Invalid JWT");if(!t)throw new x("JWTs must contain a payload");let n;try{n=Ke(t)}catch(a){throw new x("Failed to parse the base64url encoded payload")}let o;try{o=JSON.parse(v.decode(n))}catch(a){throw new x("Failed to parse the decoded payload as JSON")}if(!w(o))throw new x("Invalid JWT Claims Set");return o}async function Ft(e,t){var r;let n,o,a;switch(e){case"HS256":case"HS384":case"HS512":n=parseInt(e.slice(-3),10),o={name:"HMAC",hash:`SHA-${n}`,length:n},a=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return n=parseInt(e.slice(-3),10),$(new Uint8Array(n>>3));case"A128KW":case"A192KW":case"A256KW":n=parseInt(e.slice(1,4),10),o={name:"AES-KW",length:n},a=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":n=parseInt(e.slice(1,4),10),o={name:"AES-GCM",length:n},a=["encrypt","decrypt"];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return f.subtle.generateKey(o,(r=t==null?void 0:t.extractable)!==null&&r!==void 0?r:!1,a)}function st(e){var t;let r=(t=e==null?void 0:e.modulusLength)!==null&&t!==void 0?t:2048;if(typeof r!="number"||r<2048)throw new m("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return r}async function zt(e,t){var r,n,o,a;let i,s;switch(e){case"PS256":case"PS384":case"PS512":i={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:st(t)},s=["sign","verify"];break;case"RS256":case"RS384":case"RS512":i={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:st(t)},s=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":i={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:st(t)},s=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":i={name:"ECDSA",namedCurve:"P-256"},s=["sign","verify"];break;case"ES384":i={name:"ECDSA",namedCurve:"P-384"},s=["sign","verify"];break;case"ES512":i={name:"ECDSA",namedCurve:"P-521"},s=["sign","verify"];break;case"EdDSA":s=["sign","verify"];let c=(r=t==null?void 0:t.crv)!==null&&r!==void 0?r:"Ed25519";switch(c){case"Ed25519":case"Ed448":i={name:c};break;default:throw new m("Invalid or unsupported crv option provided")}break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{s=["deriveKey","deriveBits"];let p=(n=t==null?void 0:t.crv)!==null&&n!==void 0?n:"P-256";switch(p){case"P-256":case"P-384":case"P-521":{i={name:"ECDH",namedCurve:p};break}case"X25519":case"X448":i={name:p};break;default:throw new m("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}try{return await f.subtle.generateKey(i,(o=t==null?void 0:t.extractable)!==null&&o!==void 0?o:!1,s)}catch(c){if(i.name==="Ed25519"&&(c==null?void 0:c.name)==="NotSupportedError"&&D())return i={name:"NODE-ED25519",namedCurve:"NODE-ED25519"},await f.subtle.generateKey(i,(a=t==null?void 0:t.extractable)!==null&&a!==void 0?a:!1,s);throw c}}async function Fr(e,t){return zt(e,t)}async function zr(e,t){return Ft(e,t)}export{_e as CompactEncrypt,ve as CompactSign,Or as EmbeddedJWK,ot as EncryptJWT,F as FlattenedEncrypt,ee as FlattenedSign,je as GeneralEncrypt,rt as GeneralSign,nt as SignJWT,it as UnsecuredJWT,Vt as base64url,$t as calculateJwkThumbprint,Rr as calculateJwkThumbprintUri,Ye as compactDecrypt,et as compactVerify,kr as createLocalJWKSet,Lr as createRemoteJWKSet,Vr as decodeJwt,Gr as decodeProtectedHeader,ft as errors,qe as exportJWK,xr as exportPKCS8,Kr as exportSPKI,ge as flattenedDecrypt,be as flattenedVerify,_r as generalDecrypt,Pr as generalVerify,Fr as generateKeyPair,zr as generateSecret,j as importJWK,lr as importPKCS8,ur as importSPKI,fr as importX509,Ir as jwtDecrypt,Tr as jwtVerify}; jose-4.11.4/dist/browser/index.js000066400000000000000000000033151437043056600166460ustar00rootroot00000000000000export { compactDecrypt } from './jwe/compact/decrypt.js'; export { flattenedDecrypt } from './jwe/flattened/decrypt.js'; export { generalDecrypt } from './jwe/general/decrypt.js'; export { GeneralEncrypt } from './jwe/general/encrypt.js'; export { compactVerify } from './jws/compact/verify.js'; export { flattenedVerify } from './jws/flattened/verify.js'; export { generalVerify } from './jws/general/verify.js'; export { jwtVerify } from './jwt/verify.js'; export { jwtDecrypt } from './jwt/decrypt.js'; export { CompactEncrypt } from './jwe/compact/encrypt.js'; export { FlattenedEncrypt } from './jwe/flattened/encrypt.js'; export { CompactSign } from './jws/compact/sign.js'; export { FlattenedSign } from './jws/flattened/sign.js'; export { GeneralSign } from './jws/general/sign.js'; export { SignJWT } from './jwt/sign.js'; export { EncryptJWT } from './jwt/encrypt.js'; export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.js'; export { EmbeddedJWK } from './jwk/embedded.js'; export { createLocalJWKSet } from './jwks/local.js'; export { createRemoteJWKSet } from './jwks/remote.js'; export { UnsecuredJWT } from './jwt/unsecured.js'; export { exportPKCS8, exportSPKI, exportJWK } from './key/export.js'; export { importSPKI, importPKCS8, importX509, importJWK } from './key/import.js'; export { decodeProtectedHeader } from './util/decode_protected_header.js'; export { decodeJwt } from './util/decode_jwt.js'; import * as errors_1 from './util/errors.js'; export { errors_1 as errors }; export { generateKeyPair } from './key/generate_key_pair.js'; export { generateSecret } from './key/generate_secret.js'; import * as base64url_1 from './util/base64url.js'; export { base64url_1 as base64url }; jose-4.11.4/dist/browser/index.umd.js000066400000000000000000003557701437043056600174510ustar00rootroot00000000000000(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jose = {})); })(this, (function (exports) { 'use strict'; var __defProp = Object.defineProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; // dist/browser/runtime/webcrypto.js var webcrypto_default = crypto; var isCryptoKey = (key) => key instanceof CryptoKey; // dist/browser/runtime/digest.js var digest = async (algorithm, data) => { const subtleDigest = `SHA-${algorithm.slice(-3)}`; return new Uint8Array(await webcrypto_default.subtle.digest(subtleDigest, data)); }; var digest_default = digest; // dist/browser/lib/buffer_utils.js var encoder = new TextEncoder(); var decoder = new TextDecoder(); var MAX_INT32 = 2 ** 32; function concat(...buffers) { const size = buffers.reduce((acc, { length }) => acc + length, 0); const buf = new Uint8Array(size); let i = 0; buffers.forEach((buffer) => { buf.set(buffer, i); i += buffer.length; }); return buf; } function p2s(alg, p2sInput) { return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput); } function writeUInt32BE(buf, value, offset) { if (value < 0 || value >= MAX_INT32) { throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); } buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset); } function uint64be(value) { const high = Math.floor(value / MAX_INT32); const low = value % MAX_INT32; const buf = new Uint8Array(8); writeUInt32BE(buf, high, 0); writeUInt32BE(buf, low, 4); return buf; } function uint32be(value) { const buf = new Uint8Array(4); writeUInt32BE(buf, value); return buf; } function lengthAndInput(input) { return concat(uint32be(input.length), input); } async function concatKdf(secret, bits, value) { const iterations = Math.ceil((bits >> 3) / 32); const res = new Uint8Array(iterations * 32); for (let iter = 0; iter < iterations; iter++) { const buf = new Uint8Array(4 + secret.length + value.length); buf.set(uint32be(iter + 1)); buf.set(secret, 4); buf.set(value, 4 + secret.length); res.set(await digest_default("sha256", buf), iter * 32); } return res.slice(0, bits >> 3); } // dist/browser/runtime/base64url.js var encodeBase64 = (input) => { let unencoded = input; if (typeof unencoded === "string") { unencoded = encoder.encode(unencoded); } const CHUNK_SIZE = 32768; const arr = []; for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) { arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE))); } return btoa(arr.join("")); }; var encode = (input) => { return encodeBase64(input).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); }; var decodeBase64 = (encoded) => { const binary = atob(encoded); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) { bytes[i] = binary.charCodeAt(i); } return bytes; }; var decode = (input) => { let encoded = input; if (encoded instanceof Uint8Array) { encoded = decoder.decode(encoded); } encoded = encoded.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""); try { return decodeBase64(encoded); } catch (_a) { throw new TypeError("The input to be decoded is not correctly encoded."); } }; // dist/browser/util/errors.js var errors_exports = {}; __export(errors_exports, { JOSEAlgNotAllowed: () => JOSEAlgNotAllowed, JOSEError: () => JOSEError, JOSENotSupported: () => JOSENotSupported, JWEDecryptionFailed: () => JWEDecryptionFailed, JWEInvalid: () => JWEInvalid, JWKInvalid: () => JWKInvalid, JWKSInvalid: () => JWKSInvalid, JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys, JWKSNoMatchingKey: () => JWKSNoMatchingKey, JWKSTimeout: () => JWKSTimeout, JWSInvalid: () => JWSInvalid, JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed, JWTClaimValidationFailed: () => JWTClaimValidationFailed, JWTExpired: () => JWTExpired, JWTInvalid: () => JWTInvalid }); var JOSEError = class extends Error { static get code() { return "ERR_JOSE_GENERIC"; } constructor(message2) { var _a; super(message2); this.code = "ERR_JOSE_GENERIC"; this.name = this.constructor.name; (_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, this, this.constructor); } }; var JWTClaimValidationFailed = class extends JOSEError { static get code() { return "ERR_JWT_CLAIM_VALIDATION_FAILED"; } constructor(message2, claim = "unspecified", reason = "unspecified") { super(message2); this.code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; this.claim = claim; this.reason = reason; } }; var JWTExpired = class extends JOSEError { static get code() { return "ERR_JWT_EXPIRED"; } constructor(message2, claim = "unspecified", reason = "unspecified") { super(message2); this.code = "ERR_JWT_EXPIRED"; this.claim = claim; this.reason = reason; } }; var JOSEAlgNotAllowed = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JOSE_ALG_NOT_ALLOWED"; } static get code() { return "ERR_JOSE_ALG_NOT_ALLOWED"; } }; var JOSENotSupported = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JOSE_NOT_SUPPORTED"; } static get code() { return "ERR_JOSE_NOT_SUPPORTED"; } }; var JWEDecryptionFailed = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWE_DECRYPTION_FAILED"; this.message = "decryption operation failed"; } static get code() { return "ERR_JWE_DECRYPTION_FAILED"; } }; var JWEInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWE_INVALID"; } static get code() { return "ERR_JWE_INVALID"; } }; var JWSInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWS_INVALID"; } static get code() { return "ERR_JWS_INVALID"; } }; var JWTInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWT_INVALID"; } static get code() { return "ERR_JWT_INVALID"; } }; var JWKInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWK_INVALID"; } static get code() { return "ERR_JWK_INVALID"; } }; var JWKSInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWKS_INVALID"; } static get code() { return "ERR_JWKS_INVALID"; } }; var JWKSNoMatchingKey = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWKS_NO_MATCHING_KEY"; this.message = "no applicable key found in the JSON Web Key Set"; } static get code() { return "ERR_JWKS_NO_MATCHING_KEY"; } }; var JWKSMultipleMatchingKeys = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; this.message = "multiple matching keys found in the JSON Web Key Set"; } static get code() { return "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; } }; var JWKSTimeout = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWKS_TIMEOUT"; this.message = "request timed out"; } static get code() { return "ERR_JWKS_TIMEOUT"; } }; var JWSSignatureVerificationFailed = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; this.message = "signature verification failed"; } static get code() { return "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; } }; // dist/browser/runtime/random.js var random_default = webcrypto_default.getRandomValues.bind(webcrypto_default); // dist/browser/lib/iv.js function bitLength(alg) { switch (alg) { case "A128GCM": case "A128GCMKW": case "A192GCM": case "A192GCMKW": case "A256GCM": case "A256GCMKW": return 96; case "A128CBC-HS256": case "A192CBC-HS384": case "A256CBC-HS512": return 128; default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); } } var iv_default = (alg) => random_default(new Uint8Array(bitLength(alg) >> 3)); // dist/browser/lib/check_iv_length.js var checkIvLength = (enc, iv) => { if (iv.length << 3 !== bitLength(enc)) { throw new JWEInvalid("Invalid Initialization Vector length"); } }; var check_iv_length_default = checkIvLength; // dist/browser/runtime/check_cek_length.js var checkCekLength = (cek, expected) => { const actual = cek.byteLength << 3; if (actual !== expected) { throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); } }; var check_cek_length_default = checkCekLength; // dist/browser/runtime/timing_safe_equal.js var timingSafeEqual = (a, b) => { if (!(a instanceof Uint8Array)) { throw new TypeError("First argument must be a buffer"); } if (!(b instanceof Uint8Array)) { throw new TypeError("Second argument must be a buffer"); } if (a.length !== b.length) { throw new TypeError("Input buffers must have the same length"); } const len = a.length; let out = 0; let i = -1; while (++i < len) { out |= a[i] ^ b[i]; } return out === 0; }; var timing_safe_equal_default = timingSafeEqual; // dist/browser/runtime/env.js function isCloudflareWorkers() { return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel"; } // dist/browser/lib/crypto_key.js function unusable(name, prop = "algorithm.name") { return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); } function isAlgorithm(algorithm, name) { return algorithm.name === name; } function getHashLength(hash) { return parseInt(hash.name.slice(4), 10); } function getNamedCurve(alg) { switch (alg) { case "ES256": return "P-256"; case "ES384": return "P-384"; case "ES512": return "P-521"; default: throw new Error("unreachable"); } } function checkUsage(key, usages) { if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { let msg = "CryptoKey does not support this operation, its usages must include "; if (usages.length > 2) { const last = usages.pop(); msg += `one of ${usages.join(", ")}, or ${last}.`; } else if (usages.length === 2) { msg += `one of ${usages[0]} or ${usages[1]}.`; } else { msg += `${usages[0]}.`; } throw new TypeError(msg); } } function checkSigCryptoKey(key, alg, ...usages) { switch (alg) { case "HS256": case "HS384": case "HS512": { if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC"); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); break; } case "RS256": case "RS384": case "RS512": { if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5"); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); break; } case "PS256": case "PS384": case "PS512": { if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS"); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); break; } case "EdDSA": { if (key.algorithm.name !== "Ed25519" && key.algorithm.name !== "Ed448") { if (isCloudflareWorkers()) { if (isAlgorithm(key.algorithm, "NODE-ED25519")) break; throw unusable("Ed25519, Ed448, or NODE-ED25519"); } throw unusable("Ed25519 or Ed448"); } break; } case "ES256": case "ES384": case "ES512": { if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA"); const expected = getNamedCurve(alg); const actual = key.algorithm.namedCurve; if (actual !== expected) throw unusable(expected, "algorithm.namedCurve"); break; } default: throw new TypeError("CryptoKey does not support this operation"); } checkUsage(key, usages); } function checkEncCryptoKey(key, alg, ...usages) { switch (alg) { case "A128GCM": case "A192GCM": case "A256GCM": { if (!isAlgorithm(key.algorithm, "AES-GCM")) throw unusable("AES-GCM"); const expected = parseInt(alg.slice(1, 4), 10); const actual = key.algorithm.length; if (actual !== expected) throw unusable(expected, "algorithm.length"); break; } case "A128KW": case "A192KW": case "A256KW": { if (!isAlgorithm(key.algorithm, "AES-KW")) throw unusable("AES-KW"); const expected = parseInt(alg.slice(1, 4), 10); const actual = key.algorithm.length; if (actual !== expected) throw unusable(expected, "algorithm.length"); break; } case "ECDH": { switch (key.algorithm.name) { case "ECDH": case "X25519": case "X448": break; default: throw unusable("ECDH, X25519, or X448"); } break; } case "PBES2-HS256+A128KW": case "PBES2-HS384+A192KW": case "PBES2-HS512+A256KW": if (!isAlgorithm(key.algorithm, "PBKDF2")) throw unusable("PBKDF2"); break; case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": { if (!isAlgorithm(key.algorithm, "RSA-OAEP")) throw unusable("RSA-OAEP"); const expected = parseInt(alg.slice(9), 10) || 1; const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); break; } default: throw new TypeError("CryptoKey does not support this operation"); } checkUsage(key, usages); } // dist/browser/lib/invalid_key_input.js function message(msg, actual, ...types2) { if (types2.length > 2) { const last = types2.pop(); msg += `one of type ${types2.join(", ")}, or ${last}.`; } else if (types2.length === 2) { msg += `one of type ${types2[0]} or ${types2[1]}.`; } else { msg += `of type ${types2[0]}.`; } if (actual == null) { msg += ` Received ${actual}`; } else if (typeof actual === "function" && actual.name) { msg += ` Received function ${actual.name}`; } else if (typeof actual === "object" && actual != null) { if (actual.constructor && actual.constructor.name) { msg += ` Received an instance of ${actual.constructor.name}`; } } return msg; } var invalid_key_input_default = (actual, ...types2) => { return message("Key must be ", actual, ...types2); }; function withAlg(alg, actual, ...types2) { return message(`Key for the ${alg} algorithm must be `, actual, ...types2); } // dist/browser/runtime/is_key_like.js var is_key_like_default = (key) => { return isCryptoKey(key); }; var types = ["CryptoKey"]; // dist/browser/runtime/decrypt.js async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) { if (!(cek instanceof Uint8Array)) { throw new TypeError(invalid_key_input_default(cek, "Uint8Array")); } const keySize = parseInt(enc.slice(1, 4), 10); const encKey = await webcrypto_default.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["decrypt"]); const macKey = await webcrypto_default.subtle.importKey("raw", cek.subarray(0, keySize >> 3), { hash: `SHA-${keySize << 1}`, name: "HMAC" }, false, ["sign"]); const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); const expectedTag = new Uint8Array((await webcrypto_default.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)); let macCheckPassed; try { macCheckPassed = timing_safe_equal_default(tag, expectedTag); } catch (_a) { } if (!macCheckPassed) { throw new JWEDecryptionFailed(); } let plaintext; try { plaintext = new Uint8Array(await webcrypto_default.subtle.decrypt({ iv, name: "AES-CBC" }, encKey, ciphertext)); } catch (_b) { } if (!plaintext) { throw new JWEDecryptionFailed(); } return plaintext; } async function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) { let encKey; if (cek instanceof Uint8Array) { encKey = await webcrypto_default.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]); } else { checkEncCryptoKey(cek, enc, "decrypt"); encKey = cek; } try { return new Uint8Array(await webcrypto_default.subtle.decrypt({ additionalData: aad, iv, name: "AES-GCM", tagLength: 128 }, encKey, concat(ciphertext, tag))); } catch (_a) { throw new JWEDecryptionFailed(); } } var decrypt = async (enc, cek, ciphertext, iv, tag, aad) => { if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { throw new TypeError(invalid_key_input_default(cek, ...types, "Uint8Array")); } check_iv_length_default(enc, iv); switch (enc) { case "A128CBC-HS256": case "A192CBC-HS384": case "A256CBC-HS512": if (cek instanceof Uint8Array) check_cek_length_default(cek, parseInt(enc.slice(-3), 10)); return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad); case "A128GCM": case "A192GCM": case "A256GCM": if (cek instanceof Uint8Array) check_cek_length_default(cek, parseInt(enc.slice(1, 4), 10)); return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad); default: throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm"); } }; var decrypt_default = decrypt; // dist/browser/runtime/zlib.js var inflate = async () => { throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.'); }; var deflate = async () => { throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.'); }; // dist/browser/lib/is_disjoint.js var isDisjoint = (...headers) => { const sources = headers.filter(Boolean); if (sources.length === 0 || sources.length === 1) { return true; } let acc; for (const header of sources) { const parameters = Object.keys(header); if (!acc || acc.size === 0) { acc = new Set(parameters); continue; } for (const parameter of parameters) { if (acc.has(parameter)) { return false; } acc.add(parameter); } } return true; }; var is_disjoint_default = isDisjoint; // dist/browser/lib/is_object.js function isObjectLike(value) { return typeof value === "object" && value !== null; } function isObject(input) { if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") { return false; } if (Object.getPrototypeOf(input) === null) { return true; } let proto = input; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(input) === proto; } // dist/browser/runtime/bogus.js var bogusWebCrypto = [ { hash: "SHA-256", name: "HMAC" }, true, ["sign"] ]; var bogus_default = bogusWebCrypto; // dist/browser/runtime/aeskw.js function checkKeySize(key, alg) { if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) { throw new TypeError(`Invalid key size for alg: ${alg}`); } } function getCryptoKey(key, alg, usage) { if (isCryptoKey(key)) { checkEncCryptoKey(key, alg, usage); return key; } if (key instanceof Uint8Array) { return webcrypto_default.subtle.importKey("raw", key, "AES-KW", true, [usage]); } throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array")); } var wrap = async (alg, key, cek) => { const cryptoKey = await getCryptoKey(key, alg, "wrapKey"); checkKeySize(cryptoKey, alg); const cryptoKeyCek = await webcrypto_default.subtle.importKey("raw", cek, ...bogus_default); return new Uint8Array(await webcrypto_default.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW")); }; var unwrap = async (alg, key, encryptedKey) => { const cryptoKey = await getCryptoKey(key, alg, "unwrapKey"); checkKeySize(cryptoKey, alg); const cryptoKeyCek = await webcrypto_default.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", ...bogus_default); return new Uint8Array(await webcrypto_default.subtle.exportKey("raw", cryptoKeyCek)); }; // dist/browser/runtime/ecdhes.js async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) { if (!isCryptoKey(publicKey)) { throw new TypeError(invalid_key_input_default(publicKey, ...types)); } checkEncCryptoKey(publicKey, "ECDH"); if (!isCryptoKey(privateKey)) { throw new TypeError(invalid_key_input_default(privateKey, ...types)); } checkEncCryptoKey(privateKey, "ECDH", "deriveBits"); const value = concat(lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength)); let length; if (publicKey.algorithm.name === "X25519") { length = 256; } else if (publicKey.algorithm.name === "X448") { length = 448; } else { length = Math.ceil(parseInt(publicKey.algorithm.namedCurve.substr(-3), 10) / 8) << 3; } const sharedSecret = new Uint8Array(await webcrypto_default.subtle.deriveBits({ name: publicKey.algorithm.name, public: publicKey }, privateKey, length)); return concatKdf(sharedSecret, keyLength, value); } async function generateEpk(key) { if (!isCryptoKey(key)) { throw new TypeError(invalid_key_input_default(key, ...types)); } return webcrypto_default.subtle.generateKey(key.algorithm, true, ["deriveBits"]); } function ecdhAllowed(key) { if (!isCryptoKey(key)) { throw new TypeError(invalid_key_input_default(key, ...types)); } return ["P-256", "P-384", "P-521"].includes(key.algorithm.namedCurve) || key.algorithm.name === "X25519" || key.algorithm.name === "X448"; } // dist/browser/lib/check_p2s.js function checkP2s(p2s2) { if (!(p2s2 instanceof Uint8Array) || p2s2.length < 8) { throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets"); } } // dist/browser/runtime/pbes2kw.js function getCryptoKey2(key, alg) { if (key instanceof Uint8Array) { return webcrypto_default.subtle.importKey("raw", key, "PBKDF2", false, ["deriveBits"]); } if (isCryptoKey(key)) { checkEncCryptoKey(key, alg, "deriveBits", "deriveKey"); return key; } throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array")); } async function deriveKey2(p2s2, alg, p2c, key) { checkP2s(p2s2); const salt = p2s(alg, p2s2); const keylen = parseInt(alg.slice(13, 16), 10); const subtleAlg = { hash: `SHA-${alg.slice(8, 11)}`, iterations: p2c, name: "PBKDF2", salt }; const wrapAlg = { length: keylen, name: "AES-KW" }; const cryptoKey = await getCryptoKey2(key, alg); if (cryptoKey.usages.includes("deriveBits")) { return new Uint8Array(await webcrypto_default.subtle.deriveBits(subtleAlg, cryptoKey, keylen)); } if (cryptoKey.usages.includes("deriveKey")) { return webcrypto_default.subtle.deriveKey(subtleAlg, cryptoKey, wrapAlg, false, ["wrapKey", "unwrapKey"]); } throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"'); } var encrypt = async (alg, key, cek, p2c = 2048, p2s2 = random_default(new Uint8Array(16))) => { const derived = await deriveKey2(p2s2, alg, p2c, key); const encryptedKey = await wrap(alg.slice(-6), derived, cek); return { encryptedKey, p2c, p2s: encode(p2s2) }; }; var decrypt2 = async (alg, key, encryptedKey, p2c, p2s2) => { const derived = await deriveKey2(p2s2, alg, p2c, key); return unwrap(alg.slice(-6), derived, encryptedKey); }; // dist/browser/runtime/subtle_rsaes.js function subtleRsaEs(alg) { switch (alg) { case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": return "RSA-OAEP"; default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } } // dist/browser/runtime/check_key_length.js var check_key_length_default = (alg, key) => { if (alg.startsWith("RS") || alg.startsWith("PS")) { const { modulusLength } = key.algorithm; if (typeof modulusLength !== "number" || modulusLength < 2048) { throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); } } }; // dist/browser/runtime/rsaes.js var encrypt2 = async (alg, key, cek) => { if (!isCryptoKey(key)) { throw new TypeError(invalid_key_input_default(key, ...types)); } checkEncCryptoKey(key, alg, "encrypt", "wrapKey"); check_key_length_default(alg, key); if (key.usages.includes("encrypt")) { return new Uint8Array(await webcrypto_default.subtle.encrypt(subtleRsaEs(alg), key, cek)); } if (key.usages.includes("wrapKey")) { const cryptoKeyCek = await webcrypto_default.subtle.importKey("raw", cek, ...bogus_default); return new Uint8Array(await webcrypto_default.subtle.wrapKey("raw", cryptoKeyCek, key, subtleRsaEs(alg))); } throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation'); }; var decrypt3 = async (alg, key, encryptedKey) => { if (!isCryptoKey(key)) { throw new TypeError(invalid_key_input_default(key, ...types)); } checkEncCryptoKey(key, alg, "decrypt", "unwrapKey"); check_key_length_default(alg, key); if (key.usages.includes("decrypt")) { return new Uint8Array(await webcrypto_default.subtle.decrypt(subtleRsaEs(alg), key, encryptedKey)); } if (key.usages.includes("unwrapKey")) { const cryptoKeyCek = await webcrypto_default.subtle.unwrapKey("raw", encryptedKey, key, subtleRsaEs(alg), ...bogus_default); return new Uint8Array(await webcrypto_default.subtle.exportKey("raw", cryptoKeyCek)); } throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation'); }; // dist/browser/lib/cek.js function bitLength2(alg) { switch (alg) { case "A128GCM": return 128; case "A192GCM": return 192; case "A256GCM": case "A128CBC-HS256": return 256; case "A192CBC-HS384": return 384; case "A256CBC-HS512": return 512; default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); } } var cek_default = (alg) => random_default(new Uint8Array(bitLength2(alg) >> 3)); // dist/browser/lib/format_pem.js var format_pem_default = (b64, descriptor) => { const newlined = (b64.match(/.{1,64}/g) || []).join("\n"); return `-----BEGIN ${descriptor}----- ${newlined} -----END ${descriptor}-----`; }; // dist/browser/runtime/asn1.js var genericExport = async (keyType, keyFormat, key) => { if (!isCryptoKey(key)) { throw new TypeError(invalid_key_input_default(key, ...types)); } if (!key.extractable) { throw new TypeError("CryptoKey is not extractable"); } if (key.type !== keyType) { throw new TypeError(`key is not a ${keyType} key`); } return format_pem_default(encodeBase64(new Uint8Array(await webcrypto_default.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`); }; var toSPKI = (key) => { return genericExport("public", "spki", key); }; var toPKCS8 = (key) => { return genericExport("private", "pkcs8", key); }; var findOid = (keyData, oid, from = 0) => { if (from === 0) { oid.unshift(oid.length); oid.unshift(6); } let i = keyData.indexOf(oid[0], from); if (i === -1) return false; const sub = keyData.subarray(i, i + oid.length); if (sub.length !== oid.length) return false; return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1); }; var getNamedCurve2 = (keyData) => { switch (true) { case findOid(keyData, [42, 134, 72, 206, 61, 3, 1, 7]): return "P-256"; case findOid(keyData, [43, 129, 4, 0, 34]): return "P-384"; case findOid(keyData, [43, 129, 4, 0, 35]): return "P-521"; case findOid(keyData, [43, 101, 110]): return "X25519"; case findOid(keyData, [43, 101, 111]): return "X448"; case findOid(keyData, [43, 101, 112]): return "Ed25519"; case findOid(keyData, [43, 101, 113]): return "Ed448"; default: throw new JOSENotSupported("Invalid or unsupported EC Key Curve or OKP Key Sub Type"); } }; var genericImport = async (replace, keyFormat, pem, alg, options) => { var _a, _b; let algorithm; let keyUsages; const keyData = new Uint8Array(atob(pem.replace(replace, "")).split("").map((c) => c.charCodeAt(0))); const isPublic = keyFormat === "spki"; switch (alg) { case "PS256": case "PS384": case "PS512": algorithm = { name: "RSA-PSS", hash: `SHA-${alg.slice(-3)}` }; keyUsages = isPublic ? ["verify"] : ["sign"]; break; case "RS256": case "RS384": case "RS512": algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${alg.slice(-3)}` }; keyUsages = isPublic ? ["verify"] : ["sign"]; break; case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": algorithm = { name: "RSA-OAEP", hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}` }; keyUsages = isPublic ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"]; break; case "ES256": algorithm = { name: "ECDSA", namedCurve: "P-256" }; keyUsages = isPublic ? ["verify"] : ["sign"]; break; case "ES384": algorithm = { name: "ECDSA", namedCurve: "P-384" }; keyUsages = isPublic ? ["verify"] : ["sign"]; break; case "ES512": algorithm = { name: "ECDSA", namedCurve: "P-521" }; keyUsages = isPublic ? ["verify"] : ["sign"]; break; case "ECDH-ES": case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": { const namedCurve = getNamedCurve2(keyData); algorithm = namedCurve.startsWith("P-") ? { name: "ECDH", namedCurve } : { name: namedCurve }; keyUsages = isPublic ? [] : ["deriveBits"]; break; } case "EdDSA": algorithm = { name: getNamedCurve2(keyData) }; keyUsages = isPublic ? ["verify"] : ["sign"]; break; default: throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value'); } try { return await webcrypto_default.subtle.importKey(keyFormat, keyData, algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages); } catch (err) { if (algorithm.name === "Ed25519" && (err === null || err === void 0 ? void 0 : err.name) === "NotSupportedError" && isCloudflareWorkers()) { algorithm = { name: "NODE-ED25519", namedCurve: "NODE-ED25519" }; return await webcrypto_default.subtle.importKey(keyFormat, keyData, algorithm, (_b = options === null || options === void 0 ? void 0 : options.extractable) !== null && _b !== void 0 ? _b : false, keyUsages); } throw err; } }; var fromPKCS8 = (pem, alg, options) => { return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, "pkcs8", pem, alg, options); }; var fromSPKI = (pem, alg, options) => { return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, "spki", pem, alg, options); }; // dist/browser/runtime/jwk_to_key.js function subtleMapping(jwk) { let algorithm; let keyUsages; switch (jwk.kty) { case "oct": { switch (jwk.alg) { case "HS256": case "HS384": case "HS512": algorithm = { name: "HMAC", hash: `SHA-${jwk.alg.slice(-3)}` }; keyUsages = ["sign", "verify"]; break; case "A128CBC-HS256": case "A192CBC-HS384": case "A256CBC-HS512": throw new JOSENotSupported(`${jwk.alg} keys cannot be imported as CryptoKey instances`); case "A128GCM": case "A192GCM": case "A256GCM": case "A128GCMKW": case "A192GCMKW": case "A256GCMKW": algorithm = { name: "AES-GCM" }; keyUsages = ["encrypt", "decrypt"]; break; case "A128KW": case "A192KW": case "A256KW": algorithm = { name: "AES-KW" }; keyUsages = ["wrapKey", "unwrapKey"]; break; case "PBES2-HS256+A128KW": case "PBES2-HS384+A192KW": case "PBES2-HS512+A256KW": algorithm = { name: "PBKDF2" }; keyUsages = ["deriveBits"]; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } case "RSA": { switch (jwk.alg) { case "PS256": case "PS384": case "PS512": algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "RS256": case "RS384": case "RS512": algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": algorithm = { name: "RSA-OAEP", hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}` }; keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"]; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } case "EC": { switch (jwk.alg) { case "ES256": algorithm = { name: "ECDSA", namedCurve: "P-256" }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "ES384": algorithm = { name: "ECDSA", namedCurve: "P-384" }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "ES512": algorithm = { name: "ECDSA", namedCurve: "P-521" }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "ECDH-ES": case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": algorithm = { name: "ECDH", namedCurve: jwk.crv }; keyUsages = jwk.d ? ["deriveBits"] : []; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } case "OKP": { switch (jwk.alg) { case "EdDSA": algorithm = { name: jwk.crv }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "ECDH-ES": case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": algorithm = { name: jwk.crv }; keyUsages = jwk.d ? ["deriveBits"] : []; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } default: throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); } return { algorithm, keyUsages }; } var parse = async (jwk) => { var _a, _b; const { algorithm, keyUsages } = subtleMapping(jwk); const rest = [ algorithm, (_a = jwk.ext) !== null && _a !== void 0 ? _a : false, (_b = jwk.key_ops) !== null && _b !== void 0 ? _b : keyUsages ]; if (algorithm.name === "PBKDF2") { return webcrypto_default.subtle.importKey("raw", decode(jwk.k), ...rest); } const keyData = { ...jwk }; delete keyData.alg; delete keyData.use; try { return await webcrypto_default.subtle.importKey("jwk", keyData, ...rest); } catch (err) { if (algorithm.name === "Ed25519" && (err === null || err === void 0 ? void 0 : err.name) === "NotSupportedError" && isCloudflareWorkers()) { rest[0] = { name: "NODE-ED25519", namedCurve: "NODE-ED25519" }; return await webcrypto_default.subtle.importKey("jwk", keyData, ...rest); } throw err; } }; var jwk_to_key_default = parse; // dist/browser/key/import.js function getElement(seq) { let result = []; let next = 0; while (next < seq.length) { let nextPart = parseElement(seq.subarray(next)); result.push(nextPart); next += nextPart.byteLength; } return result; } function parseElement(bytes) { let position = 0; let tag = bytes[0] & 31; position++; if (tag === 31) { tag = 0; while (bytes[position] >= 128) { tag = tag * 128 + bytes[position] - 128; position++; } tag = tag * 128 + bytes[position] - 128; position++; } let length = 0; if (bytes[position] < 128) { length = bytes[position]; position++; } else if (length === 128) { length = 0; while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) { if (length > bytes.byteLength) { throw new TypeError("invalid indefinite form length"); } length++; } const byteLength2 = position + length + 2; return { byteLength: byteLength2, contents: bytes.subarray(position, position + length), raw: bytes.subarray(0, byteLength2) }; } else { let numberOfDigits = bytes[position] & 127; position++; length = 0; for (let i = 0; i < numberOfDigits; i++) { length = length * 256 + bytes[position]; position++; } } const byteLength = position + length; return { byteLength, contents: bytes.subarray(position, byteLength), raw: bytes.subarray(0, byteLength) }; } function spkiFromX509(buf) { const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents); return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 160 ? 6 : 5].raw); } function getSPKI(x509) { const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, ""); const raw = decodeBase64(pem); return format_pem_default(spkiFromX509(raw), "PUBLIC KEY"); } async function importSPKI(spki, alg, options) { if (typeof spki !== "string" || spki.indexOf("-----BEGIN PUBLIC KEY-----") !== 0) { throw new TypeError('"spki" must be SPKI formatted string'); } return fromSPKI(spki, alg, options); } async function importX509(x509, alg, options) { if (typeof x509 !== "string" || x509.indexOf("-----BEGIN CERTIFICATE-----") !== 0) { throw new TypeError('"x509" must be X.509 formatted string'); } let spki; try { spki = getSPKI(x509); } catch (cause) { throw new TypeError("failed to parse the X.509 certificate", { cause }); } return fromSPKI(spki, alg, options); } async function importPKCS8(pkcs8, alg, options) { if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) { throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); } return fromPKCS8(pkcs8, alg, options); } async function importJWK(jwk, alg, octAsKeyObject) { var _a; if (!isObject(jwk)) { throw new TypeError("JWK must be an object"); } alg || (alg = jwk.alg); if (typeof alg !== "string" || !alg) { throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); } switch (jwk.kty) { case "oct": if (typeof jwk.k !== "string" || !jwk.k) { throw new TypeError('missing "k" (Key Value) Parameter value'); } octAsKeyObject !== null && octAsKeyObject !== void 0 ? octAsKeyObject : octAsKeyObject = jwk.ext !== true; if (octAsKeyObject) { return jwk_to_key_default({ ...jwk, alg, ext: (_a = jwk.ext) !== null && _a !== void 0 ? _a : false }); } return decode(jwk.k); case "RSA": if (jwk.oth !== void 0) { throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); } case "EC": case "OKP": return jwk_to_key_default({ ...jwk, alg }); default: throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); } } // dist/browser/lib/check_key_type.js var symmetricTypeCheck = (alg, key) => { if (key instanceof Uint8Array) return; if (!is_key_like_default(key)) { throw new TypeError(withAlg(alg, key, ...types, "Uint8Array")); } if (key.type !== "secret") { throw new TypeError(`${types.join(" or ")} instances for symmetric algorithms must be of type "secret"`); } }; var asymmetricTypeCheck = (alg, key, usage) => { if (!is_key_like_default(key)) { throw new TypeError(withAlg(alg, key, ...types)); } if (key.type === "secret") { throw new TypeError(`${types.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`); } if (usage === "sign" && key.type === "public") { throw new TypeError(`${types.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`); } if (usage === "decrypt" && key.type === "public") { throw new TypeError(`${types.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`); } if (key.algorithm && usage === "verify" && key.type === "private") { throw new TypeError(`${types.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`); } if (key.algorithm && usage === "encrypt" && key.type === "private") { throw new TypeError(`${types.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`); } }; var checkKeyType = (alg, key, usage) => { const symmetric = alg.startsWith("HS") || alg === "dir" || alg.startsWith("PBES2") || /^A\d{3}(?:GCM)?KW$/.test(alg); if (symmetric) { symmetricTypeCheck(alg, key); } else { asymmetricTypeCheck(alg, key, usage); } }; var check_key_type_default = checkKeyType; // dist/browser/runtime/encrypt.js async function cbcEncrypt(enc, plaintext, cek, iv, aad) { if (!(cek instanceof Uint8Array)) { throw new TypeError(invalid_key_input_default(cek, "Uint8Array")); } const keySize = parseInt(enc.slice(1, 4), 10); const encKey = await webcrypto_default.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["encrypt"]); const macKey = await webcrypto_default.subtle.importKey("raw", cek.subarray(0, keySize >> 3), { hash: `SHA-${keySize << 1}`, name: "HMAC" }, false, ["sign"]); const ciphertext = new Uint8Array(await webcrypto_default.subtle.encrypt({ iv, name: "AES-CBC" }, encKey, plaintext)); const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); const tag = new Uint8Array((await webcrypto_default.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)); return { ciphertext, tag }; } async function gcmEncrypt(enc, plaintext, cek, iv, aad) { let encKey; if (cek instanceof Uint8Array) { encKey = await webcrypto_default.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]); } else { checkEncCryptoKey(cek, enc, "encrypt"); encKey = cek; } const encrypted = new Uint8Array(await webcrypto_default.subtle.encrypt({ additionalData: aad, iv, name: "AES-GCM", tagLength: 128 }, encKey, plaintext)); const tag = encrypted.slice(-16); const ciphertext = encrypted.slice(0, -16); return { ciphertext, tag }; } var encrypt3 = async (enc, plaintext, cek, iv, aad) => { if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { throw new TypeError(invalid_key_input_default(cek, ...types, "Uint8Array")); } check_iv_length_default(enc, iv); switch (enc) { case "A128CBC-HS256": case "A192CBC-HS384": case "A256CBC-HS512": if (cek instanceof Uint8Array) check_cek_length_default(cek, parseInt(enc.slice(-3), 10)); return cbcEncrypt(enc, plaintext, cek, iv, aad); case "A128GCM": case "A192GCM": case "A256GCM": if (cek instanceof Uint8Array) check_cek_length_default(cek, parseInt(enc.slice(1, 4), 10)); return gcmEncrypt(enc, plaintext, cek, iv, aad); default: throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm"); } }; var encrypt_default = encrypt3; // dist/browser/lib/aesgcmkw.js async function wrap2(alg, key, cek, iv) { const jweAlgorithm = alg.slice(0, 7); iv || (iv = iv_default(jweAlgorithm)); const { ciphertext: encryptedKey, tag } = await encrypt_default(jweAlgorithm, cek, key, iv, new Uint8Array(0)); return { encryptedKey, iv: encode(iv), tag: encode(tag) }; } async function unwrap2(alg, key, encryptedKey, iv, tag) { const jweAlgorithm = alg.slice(0, 7); return decrypt_default(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0)); } // dist/browser/lib/decrypt_key_management.js async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { check_key_type_default(alg, key, "decrypt"); switch (alg) { case "dir": { if (encryptedKey !== void 0) throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); return key; } case "ECDH-ES": if (encryptedKey !== void 0) throw new JWEInvalid("Encountered unexpected JWE Encrypted Key"); case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": { if (!isObject(joseHeader.epk)) throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); if (!ecdhAllowed(key)) throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); const epk = await importJWK(joseHeader.epk, alg); let partyUInfo; let partyVInfo; if (joseHeader.apu !== void 0) { if (typeof joseHeader.apu !== "string") throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); partyUInfo = decode(joseHeader.apu); } if (joseHeader.apv !== void 0) { if (typeof joseHeader.apv !== "string") throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); partyVInfo = decode(joseHeader.apv); } const sharedSecret = await deriveKey(epk, key, alg === "ECDH-ES" ? joseHeader.enc : alg, alg === "ECDH-ES" ? bitLength2(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); if (alg === "ECDH-ES") return sharedSecret; if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing"); return unwrap(alg.slice(-6), sharedSecret, encryptedKey); } case "RSA1_5": case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": { if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing"); return decrypt3(alg, key, encryptedKey); } case "PBES2-HS256+A128KW": case "PBES2-HS384+A192KW": case "PBES2-HS512+A256KW": { if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing"); if (typeof joseHeader.p2c !== "number") throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); const p2cLimit = (options === null || options === void 0 ? void 0 : options.maxPBES2Count) || 1e4; if (joseHeader.p2c > p2cLimit) throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); if (typeof joseHeader.p2s !== "string") throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); return decrypt2(alg, key, encryptedKey, joseHeader.p2c, decode(joseHeader.p2s)); } case "A128KW": case "A192KW": case "A256KW": { if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing"); return unwrap(alg, key, encryptedKey); } case "A128GCMKW": case "A192GCMKW": case "A256GCMKW": { if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing"); if (typeof joseHeader.iv !== "string") throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); if (typeof joseHeader.tag !== "string") throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); const iv = decode(joseHeader.iv); const tag = decode(joseHeader.tag); return unwrap2(alg, key, encryptedKey, iv, tag); } default: { throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); } } } var decrypt_key_management_default = decryptKeyManagement; // dist/browser/lib/validate_crit.js function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { if (joseHeader.crit !== void 0 && protectedHeader.crit === void 0) { throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); } if (!protectedHeader || protectedHeader.crit === void 0) { return /* @__PURE__ */ new Set(); } if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) { throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); } let recognized; if (recognizedOption !== void 0) { recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); } else { recognized = recognizedDefault; } for (const parameter of protectedHeader.crit) { if (!recognized.has(parameter)) { throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); } if (joseHeader[parameter] === void 0) { throw new Err(`Extension Header Parameter "${parameter}" is missing`); } else if (recognized.get(parameter) && protectedHeader[parameter] === void 0) { throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); } } return new Set(protectedHeader.crit); } var validate_crit_default = validateCrit; // dist/browser/lib/validate_algorithms.js var validateAlgorithms = (option, algorithms) => { if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) { throw new TypeError(`"${option}" option must be an array of strings`); } if (!algorithms) { return void 0; } return new Set(algorithms); }; var validate_algorithms_default = validateAlgorithms; // dist/browser/jwe/flattened/decrypt.js async function flattenedDecrypt(jwe, key, options) { var _a; if (!isObject(jwe)) { throw new JWEInvalid("Flattened JWE must be an object"); } if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) { throw new JWEInvalid("JOSE Header missing"); } if (typeof jwe.iv !== "string") { throw new JWEInvalid("JWE Initialization Vector missing or incorrect type"); } if (typeof jwe.ciphertext !== "string") { throw new JWEInvalid("JWE Ciphertext missing or incorrect type"); } if (typeof jwe.tag !== "string") { throw new JWEInvalid("JWE Authentication Tag missing or incorrect type"); } if (jwe.protected !== void 0 && typeof jwe.protected !== "string") { throw new JWEInvalid("JWE Protected Header incorrect type"); } if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") { throw new JWEInvalid("JWE Encrypted Key incorrect type"); } if (jwe.aad !== void 0 && typeof jwe.aad !== "string") { throw new JWEInvalid("JWE AAD incorrect type"); } if (jwe.header !== void 0 && !isObject(jwe.header)) { throw new JWEInvalid("JWE Shared Unprotected Header incorrect type"); } if (jwe.unprotected !== void 0 && !isObject(jwe.unprotected)) { throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type"); } let parsedProt; if (jwe.protected) { try { const protectedHeader2 = decode(jwe.protected); parsedProt = JSON.parse(decoder.decode(protectedHeader2)); } catch (_b) { throw new JWEInvalid("JWE Protected Header is invalid"); } } if (!is_disjoint_default(parsedProt, jwe.header, jwe.unprotected)) { throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint"); } const joseHeader = { ...parsedProt, ...jwe.header, ...jwe.unprotected }; validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader); if (joseHeader.zip !== void 0) { if (!parsedProt || !parsedProt.zip) { throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); } if (joseHeader.zip !== "DEF") { throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value'); } } const { alg, enc } = joseHeader; if (typeof alg !== "string" || !alg) { throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header"); } if (typeof enc !== "string" || !enc) { throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header"); } const keyManagementAlgorithms = options && validate_algorithms_default("keyManagementAlgorithms", options.keyManagementAlgorithms); const contentEncryptionAlgorithms = options && validate_algorithms_default("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms); if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) { throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed'); } if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed'); } let encryptedKey; if (jwe.encrypted_key !== void 0) { encryptedKey = decode(jwe.encrypted_key); } let resolvedKey = false; if (typeof key === "function") { key = await key(parsedProt, jwe); resolvedKey = true; } let cek; try { cek = await decrypt_key_management_default(alg, key, encryptedKey, joseHeader, options); } catch (err) { if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { throw err; } cek = cek_default(enc); } const iv = decode(jwe.iv); const tag = decode(jwe.tag); const protectedHeader = encoder.encode((_a = jwe.protected) !== null && _a !== void 0 ? _a : ""); let additionalData; if (jwe.aad !== void 0) { additionalData = concat(protectedHeader, encoder.encode("."), encoder.encode(jwe.aad)); } else { additionalData = protectedHeader; } let plaintext = await decrypt_default(enc, cek, decode(jwe.ciphertext), iv, tag, additionalData); if (joseHeader.zip === "DEF") { plaintext = await ((options === null || options === void 0 ? void 0 : options.inflateRaw) || inflate)(plaintext); } const result = { plaintext }; if (jwe.protected !== void 0) { result.protectedHeader = parsedProt; } if (jwe.aad !== void 0) { result.additionalAuthenticatedData = decode(jwe.aad); } if (jwe.unprotected !== void 0) { result.sharedUnprotectedHeader = jwe.unprotected; } if (jwe.header !== void 0) { result.unprotectedHeader = jwe.header; } if (resolvedKey) { return { ...result, key }; } return result; } // dist/browser/jwe/compact/decrypt.js async function compactDecrypt(jwe, key, options) { if (jwe instanceof Uint8Array) { jwe = decoder.decode(jwe); } if (typeof jwe !== "string") { throw new JWEInvalid("Compact JWE must be a string or Uint8Array"); } const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length } = jwe.split("."); if (length !== 5) { throw new JWEInvalid("Invalid Compact JWE"); } const decrypted = await flattenedDecrypt({ ciphertext, iv: iv || void 0, protected: protectedHeader || void 0, tag: tag || void 0, encrypted_key: encryptedKey || void 0 }, key, options); const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; if (typeof key === "function") { return { ...result, key: decrypted.key }; } return result; } // dist/browser/jwe/general/decrypt.js async function generalDecrypt(jwe, key, options) { if (!isObject(jwe)) { throw new JWEInvalid("General JWE must be an object"); } if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) { throw new JWEInvalid("JWE Recipients missing or incorrect type"); } if (!jwe.recipients.length) { throw new JWEInvalid("JWE Recipients has no members"); } for (const recipient of jwe.recipients) { try { return await flattenedDecrypt({ aad: jwe.aad, ciphertext: jwe.ciphertext, encrypted_key: recipient.encrypted_key, header: recipient.header, iv: jwe.iv, protected: jwe.protected, tag: jwe.tag, unprotected: jwe.unprotected }, key, options); } catch (_a) { } } throw new JWEDecryptionFailed(); } // dist/browser/runtime/key_to_jwk.js var keyToJWK = async (key) => { if (key instanceof Uint8Array) { return { kty: "oct", k: encode(key) }; } if (!isCryptoKey(key)) { throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array")); } if (!key.extractable) { throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK"); } const { ext, key_ops, alg, use, ...jwk } = await webcrypto_default.subtle.exportKey("jwk", key); return jwk; }; var key_to_jwk_default = keyToJWK; // dist/browser/key/export.js async function exportSPKI(key) { return toSPKI(key); } async function exportPKCS8(key) { return toPKCS8(key); } async function exportJWK(key) { return key_to_jwk_default(key); } // dist/browser/lib/encrypt_key_management.js async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { let encryptedKey; let parameters; let cek; check_key_type_default(alg, key, "encrypt"); switch (alg) { case "dir": { cek = key; break; } case "ECDH-ES": case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": { if (!ecdhAllowed(key)) { throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime"); } const { apu, apv } = providedParameters; let { epk: ephemeralKey } = providedParameters; ephemeralKey || (ephemeralKey = (await generateEpk(key)).privateKey); const { x, y, crv, kty } = await exportJWK(ephemeralKey); const sharedSecret = await deriveKey(key, ephemeralKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? bitLength2(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); parameters = { epk: { x, crv, kty } }; if (kty === "EC") parameters.epk.y = y; if (apu) parameters.apu = encode(apu); if (apv) parameters.apv = encode(apv); if (alg === "ECDH-ES") { cek = sharedSecret; break; } cek = providedCek || cek_default(enc); const kwAlg = alg.slice(-6); encryptedKey = await wrap(kwAlg, sharedSecret, cek); break; } case "RSA1_5": case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": { cek = providedCek || cek_default(enc); encryptedKey = await encrypt2(alg, key, cek); break; } case "PBES2-HS256+A128KW": case "PBES2-HS384+A192KW": case "PBES2-HS512+A256KW": { cek = providedCek || cek_default(enc); const { p2c, p2s: p2s2 } = providedParameters; ({ encryptedKey, ...parameters } = await encrypt(alg, key, cek, p2c, p2s2)); break; } case "A128KW": case "A192KW": case "A256KW": { cek = providedCek || cek_default(enc); encryptedKey = await wrap(alg, key, cek); break; } case "A128GCMKW": case "A192GCMKW": case "A256GCMKW": { cek = providedCek || cek_default(enc); const { iv } = providedParameters; ({ encryptedKey, ...parameters } = await wrap2(alg, key, cek, iv)); break; } default: { throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); } } return { cek, encryptedKey, parameters }; } var encrypt_key_management_default = encryptKeyManagement; // dist/browser/jwe/flattened/encrypt.js var unprotected = Symbol(); var FlattenedEncrypt = class { constructor(plaintext) { if (!(plaintext instanceof Uint8Array)) { throw new TypeError("plaintext must be an instance of Uint8Array"); } this._plaintext = plaintext; } setKeyManagementParameters(parameters) { if (this._keyManagementParameters) { throw new TypeError("setKeyManagementParameters can only be called once"); } this._keyManagementParameters = parameters; return this; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError("setProtectedHeader can only be called once"); } this._protectedHeader = protectedHeader; return this; } setSharedUnprotectedHeader(sharedUnprotectedHeader) { if (this._sharedUnprotectedHeader) { throw new TypeError("setSharedUnprotectedHeader can only be called once"); } this._sharedUnprotectedHeader = sharedUnprotectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError("setUnprotectedHeader can only be called once"); } this._unprotectedHeader = unprotectedHeader; return this; } setAdditionalAuthenticatedData(aad) { this._aad = aad; return this; } setContentEncryptionKey(cek) { if (this._cek) { throw new TypeError("setContentEncryptionKey can only be called once"); } this._cek = cek; return this; } setInitializationVector(iv) { if (this._iv) { throw new TypeError("setInitializationVector can only be called once"); } this._iv = iv; return this; } async encrypt(key, options) { if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()"); } if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) { throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...this._sharedUnprotectedHeader }; validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader); if (joseHeader.zip !== void 0) { if (!this._protectedHeader || !this._protectedHeader.zip) { throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); } if (joseHeader.zip !== "DEF") { throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value'); } } const { alg, enc } = joseHeader; if (typeof alg !== "string" || !alg) { throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); } if (typeof enc !== "string" || !enc) { throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); } let encryptedKey; if (alg === "dir") { if (this._cek) { throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption"); } } else if (alg === "ECDH-ES") { if (this._cek) { throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement"); } } let cek; { let parameters; ({ cek, encryptedKey, parameters } = await encrypt_key_management_default(alg, enc, key, this._cek, this._keyManagementParameters)); if (parameters) { if (options && unprotected in options) { if (!this._unprotectedHeader) { this.setUnprotectedHeader(parameters); } else { this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters }; } } else { if (!this._protectedHeader) { this.setProtectedHeader(parameters); } else { this._protectedHeader = { ...this._protectedHeader, ...parameters }; } } } } this._iv || (this._iv = iv_default(enc)); let additionalData; let protectedHeader; let aadMember; if (this._protectedHeader) { protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader))); } else { protectedHeader = encoder.encode(""); } if (this._aad) { aadMember = encode(this._aad); additionalData = concat(protectedHeader, encoder.encode("."), encoder.encode(aadMember)); } else { additionalData = protectedHeader; } let ciphertext; let tag; if (joseHeader.zip === "DEF") { const deflated = await ((options === null || options === void 0 ? void 0 : options.deflateRaw) || deflate)(this._plaintext); ({ ciphertext, tag } = await encrypt_default(enc, deflated, cek, this._iv, additionalData)); } else { ({ ciphertext, tag } = await encrypt_default(enc, this._plaintext, cek, this._iv, additionalData)); } const jwe = { ciphertext: encode(ciphertext), iv: encode(this._iv), tag: encode(tag) }; if (encryptedKey) { jwe.encrypted_key = encode(encryptedKey); } if (aadMember) { jwe.aad = aadMember; } if (this._protectedHeader) { jwe.protected = decoder.decode(protectedHeader); } if (this._sharedUnprotectedHeader) { jwe.unprotected = this._sharedUnprotectedHeader; } if (this._unprotectedHeader) { jwe.header = this._unprotectedHeader; } return jwe; } }; // dist/browser/jwe/general/encrypt.js var IndividualRecipient = class { constructor(enc, key, options) { this.parent = enc; this.key = key; this.options = options; } setUnprotectedHeader(unprotectedHeader) { if (this.unprotectedHeader) { throw new TypeError("setUnprotectedHeader can only be called once"); } this.unprotectedHeader = unprotectedHeader; return this; } addRecipient(...args) { return this.parent.addRecipient(...args); } encrypt(...args) { return this.parent.encrypt(...args); } done() { return this.parent; } }; var GeneralEncrypt = class { constructor(plaintext) { this._recipients = []; this._plaintext = plaintext; } addRecipient(key, options) { const recipient = new IndividualRecipient(this, key, { crit: options === null || options === void 0 ? void 0 : options.crit }); this._recipients.push(recipient); return recipient; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError("setProtectedHeader can only be called once"); } this._protectedHeader = protectedHeader; return this; } setSharedUnprotectedHeader(sharedUnprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError("setSharedUnprotectedHeader can only be called once"); } this._unprotectedHeader = sharedUnprotectedHeader; return this; } setAdditionalAuthenticatedData(aad) { this._aad = aad; return this; } async encrypt(options) { var _a, _b, _c; if (!this._recipients.length) { throw new JWEInvalid("at least one recipient must be added"); } options = { deflateRaw: options === null || options === void 0 ? void 0 : options.deflateRaw }; if (this._recipients.length === 1) { const [recipient] = this._recipients; const flattened = await new FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).encrypt(recipient.key, { ...recipient.options, ...options }); let jwe2 = { ciphertext: flattened.ciphertext, iv: flattened.iv, recipients: [{}], tag: flattened.tag }; if (flattened.aad) jwe2.aad = flattened.aad; if (flattened.protected) jwe2.protected = flattened.protected; if (flattened.unprotected) jwe2.unprotected = flattened.unprotected; if (flattened.encrypted_key) jwe2.recipients[0].encrypted_key = flattened.encrypted_key; if (flattened.header) jwe2.recipients[0].header = flattened.header; return jwe2; } let enc; for (let i = 0; i < this._recipients.length; i++) { const recipient = this._recipients[i]; if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) { throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint"); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...recipient.unprotectedHeader }; const { alg } = joseHeader; if (typeof alg !== "string" || !alg) { throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); } if (alg === "dir" || alg === "ECDH-ES") { throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); } if (typeof joseHeader.enc !== "string" || !joseHeader.enc) { throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); } if (!enc) { enc = joseHeader.enc; } else if (enc !== joseHeader.enc) { throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); } validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), recipient.options.crit, this._protectedHeader, joseHeader); if (joseHeader.zip !== void 0) { if (!this._protectedHeader || !this._protectedHeader.zip) { throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); } } } const cek = cek_default(enc); let jwe = { ciphertext: "", iv: "", recipients: [], tag: "" }; for (let i = 0; i < this._recipients.length; i++) { const recipient = this._recipients[i]; const target = {}; jwe.recipients.push(target); const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...recipient.unprotectedHeader }; const p2c = joseHeader.alg.startsWith("PBES2") ? 2048 + i : void 0; if (i === 0) { const flattened = await new FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(cek).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).setKeyManagementParameters({ p2c }).encrypt(recipient.key, { ...recipient.options, ...options, [unprotected]: true }); jwe.ciphertext = flattened.ciphertext; jwe.iv = flattened.iv; jwe.tag = flattened.tag; if (flattened.aad) jwe.aad = flattened.aad; if (flattened.protected) jwe.protected = flattened.protected; if (flattened.unprotected) jwe.unprotected = flattened.unprotected; target.encrypted_key = flattened.encrypted_key; if (flattened.header) target.header = flattened.header; continue; } const { encryptedKey, parameters } = await encrypt_key_management_default(((_a = recipient.unprotectedHeader) === null || _a === void 0 ? void 0 : _a.alg) || ((_b = this._protectedHeader) === null || _b === void 0 ? void 0 : _b.alg) || ((_c = this._unprotectedHeader) === null || _c === void 0 ? void 0 : _c.alg), enc, recipient.key, cek, { p2c }); target.encrypted_key = encode(encryptedKey); if (recipient.unprotectedHeader || parameters) target.header = { ...recipient.unprotectedHeader, ...parameters }; } return jwe; } }; // dist/browser/runtime/subtle_dsa.js function subtleDsa(alg, algorithm) { const hash = `SHA-${alg.slice(-3)}`; switch (alg) { case "HS256": case "HS384": case "HS512": return { hash, name: "HMAC" }; case "PS256": case "PS384": case "PS512": return { hash, name: "RSA-PSS", saltLength: alg.slice(-3) >> 3 }; case "RS256": case "RS384": case "RS512": return { hash, name: "RSASSA-PKCS1-v1_5" }; case "ES256": case "ES384": case "ES512": return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve }; case "EdDSA": if (isCloudflareWorkers() && algorithm.name === "NODE-ED25519") { return { name: "NODE-ED25519", namedCurve: "NODE-ED25519" }; } return { name: algorithm.name }; default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } } // dist/browser/runtime/get_sign_verify_key.js function getCryptoKey3(alg, key, usage) { if (isCryptoKey(key)) { checkSigCryptoKey(key, alg, usage); return key; } if (key instanceof Uint8Array) { if (!alg.startsWith("HS")) { throw new TypeError(invalid_key_input_default(key, ...types)); } return webcrypto_default.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]); } throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array")); } // dist/browser/runtime/verify.js var verify = async (alg, key, signature, data) => { const cryptoKey = await getCryptoKey3(alg, key, "verify"); check_key_length_default(alg, cryptoKey); const algorithm = subtleDsa(alg, cryptoKey.algorithm); try { return await webcrypto_default.subtle.verify(algorithm, cryptoKey, signature, data); } catch (_a) { return false; } }; var verify_default = verify; // dist/browser/jws/flattened/verify.js async function flattenedVerify(jws, key, options) { var _a; if (!isObject(jws)) { throw new JWSInvalid("Flattened JWS must be an object"); } if (jws.protected === void 0 && jws.header === void 0) { throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); } if (jws.protected !== void 0 && typeof jws.protected !== "string") { throw new JWSInvalid("JWS Protected Header incorrect type"); } if (jws.payload === void 0) { throw new JWSInvalid("JWS Payload missing"); } if (typeof jws.signature !== "string") { throw new JWSInvalid("JWS Signature missing or incorrect type"); } if (jws.header !== void 0 && !isObject(jws.header)) { throw new JWSInvalid("JWS Unprotected Header incorrect type"); } let parsedProt = {}; if (jws.protected) { try { const protectedHeader = decode(jws.protected); parsedProt = JSON.parse(decoder.decode(protectedHeader)); } catch (_b) { throw new JWSInvalid("JWS Protected Header is invalid"); } } if (!is_disjoint_default(parsedProt, jws.header)) { throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); } const joseHeader = { ...parsedProt, ...jws.header }; const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader); let b64 = true; if (extensions.has("b64")) { b64 = parsedProt.b64; if (typeof b64 !== "boolean") { throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); } } const { alg } = joseHeader; if (typeof alg !== "string" || !alg) { throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); } const algorithms = options && validate_algorithms_default("algorithms", options.algorithms); if (algorithms && !algorithms.has(alg)) { throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed'); } if (b64) { if (typeof jws.payload !== "string") { throw new JWSInvalid("JWS Payload must be a string"); } } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) { throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance"); } let resolvedKey = false; if (typeof key === "function") { key = await key(parsedProt, jws); resolvedKey = true; } check_key_type_default(alg, key, "verify"); const data = concat(encoder.encode((_a = jws.protected) !== null && _a !== void 0 ? _a : ""), encoder.encode("."), typeof jws.payload === "string" ? encoder.encode(jws.payload) : jws.payload); const signature = decode(jws.signature); const verified = await verify_default(alg, key, signature, data); if (!verified) { throw new JWSSignatureVerificationFailed(); } let payload; if (b64) { payload = decode(jws.payload); } else if (typeof jws.payload === "string") { payload = encoder.encode(jws.payload); } else { payload = jws.payload; } const result = { payload }; if (jws.protected !== void 0) { result.protectedHeader = parsedProt; } if (jws.header !== void 0) { result.unprotectedHeader = jws.header; } if (resolvedKey) { return { ...result, key }; } return result; } // dist/browser/jws/compact/verify.js async function compactVerify(jws, key, options) { if (jws instanceof Uint8Array) { jws = decoder.decode(jws); } if (typeof jws !== "string") { throw new JWSInvalid("Compact JWS must be a string or Uint8Array"); } const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split("."); if (length !== 3) { throw new JWSInvalid("Invalid Compact JWS"); } const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options); const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; if (typeof key === "function") { return { ...result, key: verified.key }; } return result; } // dist/browser/jws/general/verify.js async function generalVerify(jws, key, options) { if (!isObject(jws)) { throw new JWSInvalid("General JWS must be an object"); } if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) { throw new JWSInvalid("JWS Signatures missing or incorrect type"); } for (const signature of jws.signatures) { try { return await flattenedVerify({ header: signature.header, payload: jws.payload, protected: signature.protected, signature: signature.signature }, key, options); } catch (_a) { } } throw new JWSSignatureVerificationFailed(); } // dist/browser/lib/epoch.js var epoch_default = (date) => Math.floor(date.getTime() / 1e3); // dist/browser/lib/secs.js var minute = 60; var hour = minute * 60; var day = hour * 24; var week = day * 7; var year = day * 365.25; var REGEX = /^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i; var secs_default = (str) => { const matched = REGEX.exec(str); if (!matched) { throw new TypeError("Invalid time period format"); } const value = parseFloat(matched[1]); const unit = matched[2].toLowerCase(); switch (unit) { case "sec": case "secs": case "second": case "seconds": case "s": return Math.round(value); case "minute": case "minutes": case "min": case "mins": case "m": return Math.round(value * minute); case "hour": case "hours": case "hr": case "hrs": case "h": return Math.round(value * hour); case "day": case "days": case "d": return Math.round(value * day); case "week": case "weeks": case "w": return Math.round(value * week); default: return Math.round(value * year); } }; // dist/browser/lib/jwt_claims_set.js var normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, ""); var checkAudiencePresence = (audPayload, audOption) => { if (typeof audPayload === "string") { return audOption.includes(audPayload); } if (Array.isArray(audPayload)) { return audOption.some(Set.prototype.has.bind(new Set(audPayload))); } return false; }; var jwt_claims_set_default = (protectedHeader, encodedPayload, options = {}) => { const { typ } = options; if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', "typ", "check_failed"); } let payload; try { payload = JSON.parse(decoder.decode(encodedPayload)); } catch (_a) { } if (!isObject(payload)) { throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); } const { issuer } = options; if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { throw new JWTClaimValidationFailed('unexpected "iss" claim value', "iss", "check_failed"); } const { subject } = options; if (subject && payload.sub !== subject) { throw new JWTClaimValidationFailed('unexpected "sub" claim value', "sub", "check_failed"); } const { audience } = options; if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) { throw new JWTClaimValidationFailed('unexpected "aud" claim value', "aud", "check_failed"); } let tolerance; switch (typeof options.clockTolerance) { case "string": tolerance = secs_default(options.clockTolerance); break; case "number": tolerance = options.clockTolerance; break; case "undefined": tolerance = 0; break; default: throw new TypeError("Invalid clockTolerance option type"); } const { currentDate } = options; const now = epoch_default(currentDate || /* @__PURE__ */ new Date()); if ((payload.iat !== void 0 || options.maxTokenAge) && typeof payload.iat !== "number") { throw new JWTClaimValidationFailed('"iat" claim must be a number', "iat", "invalid"); } if (payload.nbf !== void 0) { if (typeof payload.nbf !== "number") { throw new JWTClaimValidationFailed('"nbf" claim must be a number', "nbf", "invalid"); } if (payload.nbf > now + tolerance) { throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', "nbf", "check_failed"); } } if (payload.exp !== void 0) { if (typeof payload.exp !== "number") { throw new JWTClaimValidationFailed('"exp" claim must be a number', "exp", "invalid"); } if (payload.exp <= now - tolerance) { throw new JWTExpired('"exp" claim timestamp check failed', "exp", "check_failed"); } } if (options.maxTokenAge) { const age = now - payload.iat; const max = typeof options.maxTokenAge === "number" ? options.maxTokenAge : secs_default(options.maxTokenAge); if (age - tolerance > max) { throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', "iat", "check_failed"); } if (age < 0 - tolerance) { throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', "iat", "check_failed"); } } return payload; }; // dist/browser/jwt/verify.js async function jwtVerify(jwt, key, options) { var _a; const verified = await compactVerify(jwt, key, options); if (((_a = verified.protectedHeader.crit) === null || _a === void 0 ? void 0 : _a.includes("b64")) && verified.protectedHeader.b64 === false) { throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); } const payload = jwt_claims_set_default(verified.protectedHeader, verified.payload, options); const result = { payload, protectedHeader: verified.protectedHeader }; if (typeof key === "function") { return { ...result, key: verified.key }; } return result; } // dist/browser/jwt/decrypt.js async function jwtDecrypt(jwt, key, options) { const decrypted = await compactDecrypt(jwt, key, options); const payload = jwt_claims_set_default(decrypted.protectedHeader, decrypted.plaintext, options); const { protectedHeader } = decrypted; if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload.iss) { throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', "iss", "mismatch"); } if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload.sub) { throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', "sub", "mismatch"); } if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', "aud", "mismatch"); } const result = { payload, protectedHeader }; if (typeof key === "function") { return { ...result, key: decrypted.key }; } return result; } // dist/browser/jwe/compact/encrypt.js var CompactEncrypt = class { constructor(plaintext) { this._flattened = new FlattenedEncrypt(plaintext); } setContentEncryptionKey(cek) { this._flattened.setContentEncryptionKey(cek); return this; } setInitializationVector(iv) { this._flattened.setInitializationVector(iv); return this; } setProtectedHeader(protectedHeader) { this._flattened.setProtectedHeader(protectedHeader); return this; } setKeyManagementParameters(parameters) { this._flattened.setKeyManagementParameters(parameters); return this; } async encrypt(key, options) { const jwe = await this._flattened.encrypt(key, options); return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join("."); } }; // dist/browser/runtime/sign.js var sign = async (alg, key, data) => { const cryptoKey = await getCryptoKey3(alg, key, "sign"); check_key_length_default(alg, cryptoKey); const signature = await webcrypto_default.subtle.sign(subtleDsa(alg, cryptoKey.algorithm), cryptoKey, data); return new Uint8Array(signature); }; var sign_default = sign; // dist/browser/jws/flattened/sign.js var FlattenedSign = class { constructor(payload) { if (!(payload instanceof Uint8Array)) { throw new TypeError("payload must be an instance of Uint8Array"); } this._payload = payload; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError("setProtectedHeader can only be called once"); } this._protectedHeader = protectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError("setUnprotectedHeader can only be called once"); } this._unprotectedHeader = unprotectedHeader; return this; } async sign(key, options) { if (!this._protectedHeader && !this._unprotectedHeader) { throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()"); } if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader)) { throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader }; const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader); let b64 = true; if (extensions.has("b64")) { b64 = this._protectedHeader.b64; if (typeof b64 !== "boolean") { throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); } } const { alg } = joseHeader; if (typeof alg !== "string" || !alg) { throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); } check_key_type_default(alg, key, "sign"); let payload = this._payload; if (b64) { payload = encoder.encode(encode(payload)); } let protectedHeader; if (this._protectedHeader) { protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader))); } else { protectedHeader = encoder.encode(""); } const data = concat(protectedHeader, encoder.encode("."), payload); const signature = await sign_default(alg, key, data); const jws = { signature: encode(signature), payload: "" }; if (b64) { jws.payload = decoder.decode(payload); } if (this._unprotectedHeader) { jws.header = this._unprotectedHeader; } if (this._protectedHeader) { jws.protected = decoder.decode(protectedHeader); } return jws; } }; // dist/browser/jws/compact/sign.js var CompactSign = class { constructor(payload) { this._flattened = new FlattenedSign(payload); } setProtectedHeader(protectedHeader) { this._flattened.setProtectedHeader(protectedHeader); return this; } async sign(key, options) { const jws = await this._flattened.sign(key, options); if (jws.payload === void 0) { throw new TypeError("use the flattened module for creating JWS with b64: false"); } return `${jws.protected}.${jws.payload}.${jws.signature}`; } }; // dist/browser/jws/general/sign.js var IndividualSignature = class { constructor(sig, key, options) { this.parent = sig; this.key = key; this.options = options; } setProtectedHeader(protectedHeader) { if (this.protectedHeader) { throw new TypeError("setProtectedHeader can only be called once"); } this.protectedHeader = protectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this.unprotectedHeader) { throw new TypeError("setUnprotectedHeader can only be called once"); } this.unprotectedHeader = unprotectedHeader; return this; } addSignature(...args) { return this.parent.addSignature(...args); } sign(...args) { return this.parent.sign(...args); } done() { return this.parent; } }; var GeneralSign = class { constructor(payload) { this._signatures = []; this._payload = payload; } addSignature(key, options) { const signature = new IndividualSignature(this, key, options); this._signatures.push(signature); return signature; } async sign() { if (!this._signatures.length) { throw new JWSInvalid("at least one signature must be added"); } const jws = { signatures: [], payload: "" }; for (let i = 0; i < this._signatures.length; i++) { const signature = this._signatures[i]; const flattened = new FlattenedSign(this._payload); flattened.setProtectedHeader(signature.protectedHeader); flattened.setUnprotectedHeader(signature.unprotectedHeader); const { payload, ...rest } = await flattened.sign(signature.key, signature.options); if (i === 0) { jws.payload = payload; } else if (jws.payload !== payload) { throw new JWSInvalid("inconsistent use of JWS Unencoded Payload Option (RFC7797)"); } jws.signatures.push(rest); } return jws; } }; // dist/browser/jwt/produce.js var ProduceJWT = class { constructor(payload) { if (!isObject(payload)) { throw new TypeError("JWT Claims Set MUST be an object"); } this._payload = payload; } setIssuer(issuer) { this._payload = { ...this._payload, iss: issuer }; return this; } setSubject(subject) { this._payload = { ...this._payload, sub: subject }; return this; } setAudience(audience) { this._payload = { ...this._payload, aud: audience }; return this; } setJti(jwtId) { this._payload = { ...this._payload, jti: jwtId }; return this; } setNotBefore(input) { if (typeof input === "number") { this._payload = { ...this._payload, nbf: input }; } else { this._payload = { ...this._payload, nbf: epoch_default(/* @__PURE__ */ new Date()) + secs_default(input) }; } return this; } setExpirationTime(input) { if (typeof input === "number") { this._payload = { ...this._payload, exp: input }; } else { this._payload = { ...this._payload, exp: epoch_default(/* @__PURE__ */ new Date()) + secs_default(input) }; } return this; } setIssuedAt(input) { if (typeof input === "undefined") { this._payload = { ...this._payload, iat: epoch_default(/* @__PURE__ */ new Date()) }; } else { this._payload = { ...this._payload, iat: input }; } return this; } }; // dist/browser/jwt/sign.js var SignJWT = class extends ProduceJWT { setProtectedHeader(protectedHeader) { this._protectedHeader = protectedHeader; return this; } async sign(key, options) { var _a; const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload))); sig.setProtectedHeader(this._protectedHeader); if (Array.isArray((_a = this._protectedHeader) === null || _a === void 0 ? void 0 : _a.crit) && this._protectedHeader.crit.includes("b64") && this._protectedHeader.b64 === false) { throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); } return sig.sign(key, options); } }; // dist/browser/jwt/encrypt.js var EncryptJWT = class extends ProduceJWT { setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError("setProtectedHeader can only be called once"); } this._protectedHeader = protectedHeader; return this; } setKeyManagementParameters(parameters) { if (this._keyManagementParameters) { throw new TypeError("setKeyManagementParameters can only be called once"); } this._keyManagementParameters = parameters; return this; } setContentEncryptionKey(cek) { if (this._cek) { throw new TypeError("setContentEncryptionKey can only be called once"); } this._cek = cek; return this; } setInitializationVector(iv) { if (this._iv) { throw new TypeError("setInitializationVector can only be called once"); } this._iv = iv; return this; } replicateIssuerAsHeader() { this._replicateIssuerAsHeader = true; return this; } replicateSubjectAsHeader() { this._replicateSubjectAsHeader = true; return this; } replicateAudienceAsHeader() { this._replicateAudienceAsHeader = true; return this; } async encrypt(key, options) { const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload))); if (this._replicateIssuerAsHeader) { this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss }; } if (this._replicateSubjectAsHeader) { this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub }; } if (this._replicateAudienceAsHeader) { this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud }; } enc.setProtectedHeader(this._protectedHeader); if (this._iv) { enc.setInitializationVector(this._iv); } if (this._cek) { enc.setContentEncryptionKey(this._cek); } if (this._keyManagementParameters) { enc.setKeyManagementParameters(this._keyManagementParameters); } return enc.encrypt(key, options); } }; // dist/browser/jwk/thumbprint.js var check = (value, description) => { if (typeof value !== "string" || !value) { throw new JWKInvalid(`${description} missing or invalid`); } }; async function calculateJwkThumbprint(jwk, digestAlgorithm) { if (!isObject(jwk)) { throw new TypeError("JWK must be an object"); } digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : digestAlgorithm = "sha256"; if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") { throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); } let components; switch (jwk.kty) { case "EC": check(jwk.crv, '"crv" (Curve) Parameter'); check(jwk.x, '"x" (X Coordinate) Parameter'); check(jwk.y, '"y" (Y Coordinate) Parameter'); components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; break; case "OKP": check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); check(jwk.x, '"x" (Public Key) Parameter'); components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; break; case "RSA": check(jwk.e, '"e" (Exponent) Parameter'); check(jwk.n, '"n" (Modulus) Parameter'); components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; break; case "oct": check(jwk.k, '"k" (Key Value) Parameter'); components = { k: jwk.k, kty: jwk.kty }; break; default: throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); } const data = encoder.encode(JSON.stringify(components)); return encode(await digest_default(digestAlgorithm, data)); } async function calculateJwkThumbprintUri(jwk, digestAlgorithm) { digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : digestAlgorithm = "sha256"; const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm); return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; } // dist/browser/jwk/embedded.js async function EmbeddedJWK(protectedHeader, token) { const joseHeader = { ...protectedHeader, ...token.header }; if (!isObject(joseHeader.jwk)) { throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); } const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg, true); if (key instanceof Uint8Array || key.type !== "public") { throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); } return key; } // dist/browser/jwks/local.js function getKtyFromAlg(alg) { switch (typeof alg === "string" && alg.slice(0, 2)) { case "RS": case "PS": return "RSA"; case "ES": return "EC"; case "Ed": return "OKP"; default: throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); } } function isJWKSLike(jwks) { return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike); } function isJWKLike(key) { return isObject(key); } function clone(obj) { if (typeof structuredClone === "function") { return structuredClone(obj); } return JSON.parse(JSON.stringify(obj)); } var LocalJWKSet = class { constructor(jwks) { this._cached = /* @__PURE__ */ new WeakMap(); if (!isJWKSLike(jwks)) { throw new JWKSInvalid("JSON Web Key Set malformed"); } this._jwks = clone(jwks); } async getKey(protectedHeader, token) { const { alg, kid } = { ...protectedHeader, ...token.header }; const kty = getKtyFromAlg(alg); const candidates = this._jwks.keys.filter((jwk2) => { let candidate = kty === jwk2.kty; if (candidate && typeof kid === "string") { candidate = kid === jwk2.kid; } if (candidate && typeof jwk2.alg === "string") { candidate = alg === jwk2.alg; } if (candidate && typeof jwk2.use === "string") { candidate = jwk2.use === "sig"; } if (candidate && Array.isArray(jwk2.key_ops)) { candidate = jwk2.key_ops.includes("verify"); } if (candidate && alg === "EdDSA") { candidate = jwk2.crv === "Ed25519" || jwk2.crv === "Ed448"; } if (candidate) { switch (alg) { case "ES256": candidate = jwk2.crv === "P-256"; break; case "ES256K": candidate = jwk2.crv === "secp256k1"; break; case "ES384": candidate = jwk2.crv === "P-384"; break; case "ES512": candidate = jwk2.crv === "P-521"; break; } } return candidate; }); const { 0: jwk, length } = candidates; if (length === 0) { throw new JWKSNoMatchingKey(); } else if (length !== 1) { throw new JWKSMultipleMatchingKeys(); } const cached = this._cached.get(jwk) || this._cached.set(jwk, {}).get(jwk); if (cached[alg] === void 0) { const keyObject = await importJWK({ ...jwk, ext: true }, alg); if (keyObject instanceof Uint8Array || keyObject.type !== "public") { throw new JWKSInvalid("JSON Web Key Set members must be public keys"); } cached[alg] = keyObject; } return cached[alg]; } }; function createLocalJWKSet(jwks) { return LocalJWKSet.prototype.getKey.bind(new LocalJWKSet(jwks)); } // dist/browser/runtime/fetch_jwks.js var fetchJwks = async (url, timeout, options) => { let controller; let id; let timedOut = false; if (typeof AbortController === "function") { controller = new AbortController(); id = setTimeout(() => { timedOut = true; controller.abort(); }, timeout); } const response = await fetch(url.href, { signal: controller ? controller.signal : void 0, redirect: "manual", headers: options.headers }).catch((err) => { if (timedOut) throw new JWKSTimeout(); throw err; }); if (id !== void 0) clearTimeout(id); if (response.status !== 200) { throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response"); } try { return await response.json(); } catch (_a) { throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON"); } }; var fetch_jwks_default = fetchJwks; // dist/browser/jwks/remote.js var RemoteJWKSet = class extends LocalJWKSet { constructor(url, options) { super({ keys: [] }); this._jwks = void 0; if (!(url instanceof URL)) { throw new TypeError("url must be an instance of URL"); } this._url = new URL(url.href); this._options = { agent: options === null || options === void 0 ? void 0 : options.agent, headers: options === null || options === void 0 ? void 0 : options.headers }; this._timeoutDuration = typeof (options === null || options === void 0 ? void 0 : options.timeoutDuration) === "number" ? options === null || options === void 0 ? void 0 : options.timeoutDuration : 5e3; this._cooldownDuration = typeof (options === null || options === void 0 ? void 0 : options.cooldownDuration) === "number" ? options === null || options === void 0 ? void 0 : options.cooldownDuration : 3e4; this._cacheMaxAge = typeof (options === null || options === void 0 ? void 0 : options.cacheMaxAge) === "number" ? options === null || options === void 0 ? void 0 : options.cacheMaxAge : 6e5; } coolingDown() { return typeof this._jwksTimestamp === "number" ? Date.now() < this._jwksTimestamp + this._cooldownDuration : false; } fresh() { return typeof this._jwksTimestamp === "number" ? Date.now() < this._jwksTimestamp + this._cacheMaxAge : false; } async getKey(protectedHeader, token) { if (!this._jwks || !this.fresh()) { await this.reload(); } try { return await super.getKey(protectedHeader, token); } catch (err) { if (err instanceof JWKSNoMatchingKey) { if (this.coolingDown() === false) { await this.reload(); return super.getKey(protectedHeader, token); } } throw err; } } async reload() { if (this._pendingFetch && isCloudflareWorkers()) { return new Promise((resolve) => { const isDone = () => { if (this._pendingFetch === void 0) { resolve(); } else { setTimeout(isDone, 5); } }; isDone(); }); } if (!this._pendingFetch) { this._pendingFetch = fetch_jwks_default(this._url, this._timeoutDuration, this._options).then((json) => { if (!isJWKSLike(json)) { throw new JWKSInvalid("JSON Web Key Set malformed"); } this._jwks = { keys: json.keys }; this._jwksTimestamp = Date.now(); this._pendingFetch = void 0; }).catch((err) => { this._pendingFetch = void 0; throw err; }); } await this._pendingFetch; } }; function createRemoteJWKSet(url, options) { return RemoteJWKSet.prototype.getKey.bind(new RemoteJWKSet(url, options)); } // dist/browser/jwt/unsecured.js var UnsecuredJWT = class extends ProduceJWT { encode() { const header = encode(JSON.stringify({ alg: "none" })); const payload = encode(JSON.stringify(this._payload)); return `${header}.${payload}.`; } static decode(jwt, options) { if (typeof jwt !== "string") { throw new JWTInvalid("Unsecured JWT must be a string"); } const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split("."); if (length !== 3 || signature !== "") { throw new JWTInvalid("Invalid Unsecured JWT"); } let header; try { header = JSON.parse(decoder.decode(decode(encodedHeader))); if (header.alg !== "none") throw new Error(); } catch (_a) { throw new JWTInvalid("Invalid Unsecured JWT"); } const payload = jwt_claims_set_default(header, decode(encodedPayload), options); return { payload, header }; } }; // dist/browser/util/base64url.js var base64url_exports2 = {}; __export(base64url_exports2, { decode: () => decode2, encode: () => encode2 }); var encode2 = encode; var decode2 = decode; // dist/browser/util/decode_protected_header.js function decodeProtectedHeader(token) { let protectedB64u; if (typeof token === "string") { const parts = token.split("."); if (parts.length === 3 || parts.length === 5) { [protectedB64u] = parts; } } else if (typeof token === "object" && token) { if ("protected" in token) { protectedB64u = token.protected; } else { throw new TypeError("Token does not contain a Protected Header"); } } try { if (typeof protectedB64u !== "string" || !protectedB64u) { throw new Error(); } const result = JSON.parse(decoder.decode(decode2(protectedB64u))); if (!isObject(result)) { throw new Error(); } return result; } catch (_a) { throw new TypeError("Invalid Token or Protected Header formatting"); } } // dist/browser/util/decode_jwt.js function decodeJwt(jwt) { if (typeof jwt !== "string") throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string"); const { 1: payload, length } = jwt.split("."); if (length === 5) throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded"); if (length !== 3) throw new JWTInvalid("Invalid JWT"); if (!payload) throw new JWTInvalid("JWTs must contain a payload"); let decoded; try { decoded = decode2(payload); } catch (_a) { throw new JWTInvalid("Failed to parse the base64url encoded payload"); } let result; try { result = JSON.parse(decoder.decode(decoded)); } catch (_b) { throw new JWTInvalid("Failed to parse the decoded payload as JSON"); } if (!isObject(result)) throw new JWTInvalid("Invalid JWT Claims Set"); return result; } // dist/browser/runtime/generate.js async function generateSecret(alg, options) { var _a; let length; let algorithm; let keyUsages; switch (alg) { case "HS256": case "HS384": case "HS512": length = parseInt(alg.slice(-3), 10); algorithm = { name: "HMAC", hash: `SHA-${length}`, length }; keyUsages = ["sign", "verify"]; break; case "A128CBC-HS256": case "A192CBC-HS384": case "A256CBC-HS512": length = parseInt(alg.slice(-3), 10); return random_default(new Uint8Array(length >> 3)); case "A128KW": case "A192KW": case "A256KW": length = parseInt(alg.slice(1, 4), 10); algorithm = { name: "AES-KW", length }; keyUsages = ["wrapKey", "unwrapKey"]; break; case "A128GCMKW": case "A192GCMKW": case "A256GCMKW": case "A128GCM": case "A192GCM": case "A256GCM": length = parseInt(alg.slice(1, 4), 10); algorithm = { name: "AES-GCM", length }; keyUsages = ["encrypt", "decrypt"]; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } return webcrypto_default.subtle.generateKey(algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages); } function getModulusLengthOption(options) { var _a; const modulusLength = (_a = options === null || options === void 0 ? void 0 : options.modulusLength) !== null && _a !== void 0 ? _a : 2048; if (typeof modulusLength !== "number" || modulusLength < 2048) { throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used"); } return modulusLength; } async function generateKeyPair(alg, options) { var _a, _b, _c, _d; let algorithm; let keyUsages; switch (alg) { case "PS256": case "PS384": case "PS512": algorithm = { name: "RSA-PSS", hash: `SHA-${alg.slice(-3)}`, publicExponent: new Uint8Array([1, 0, 1]), modulusLength: getModulusLengthOption(options) }; keyUsages = ["sign", "verify"]; break; case "RS256": case "RS384": case "RS512": algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${alg.slice(-3)}`, publicExponent: new Uint8Array([1, 0, 1]), modulusLength: getModulusLengthOption(options) }; keyUsages = ["sign", "verify"]; break; case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": algorithm = { name: "RSA-OAEP", hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`, publicExponent: new Uint8Array([1, 0, 1]), modulusLength: getModulusLengthOption(options) }; keyUsages = ["decrypt", "unwrapKey", "encrypt", "wrapKey"]; break; case "ES256": algorithm = { name: "ECDSA", namedCurve: "P-256" }; keyUsages = ["sign", "verify"]; break; case "ES384": algorithm = { name: "ECDSA", namedCurve: "P-384" }; keyUsages = ["sign", "verify"]; break; case "ES512": algorithm = { name: "ECDSA", namedCurve: "P-521" }; keyUsages = ["sign", "verify"]; break; case "EdDSA": keyUsages = ["sign", "verify"]; const crv = (_a = options === null || options === void 0 ? void 0 : options.crv) !== null && _a !== void 0 ? _a : "Ed25519"; switch (crv) { case "Ed25519": case "Ed448": algorithm = { name: crv }; break; default: throw new JOSENotSupported("Invalid or unsupported crv option provided"); } break; case "ECDH-ES": case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": { keyUsages = ["deriveKey", "deriveBits"]; const crv2 = (_b = options === null || options === void 0 ? void 0 : options.crv) !== null && _b !== void 0 ? _b : "P-256"; switch (crv2) { case "P-256": case "P-384": case "P-521": { algorithm = { name: "ECDH", namedCurve: crv2 }; break; } case "X25519": case "X448": algorithm = { name: crv2 }; break; default: throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448"); } break; } default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } try { return await webcrypto_default.subtle.generateKey(algorithm, (_c = options === null || options === void 0 ? void 0 : options.extractable) !== null && _c !== void 0 ? _c : false, keyUsages); } catch (err) { if (algorithm.name === "Ed25519" && (err === null || err === void 0 ? void 0 : err.name) === "NotSupportedError" && isCloudflareWorkers()) { algorithm = { name: "NODE-ED25519", namedCurve: "NODE-ED25519" }; return await webcrypto_default.subtle.generateKey(algorithm, (_d = options === null || options === void 0 ? void 0 : options.extractable) !== null && _d !== void 0 ? _d : false, keyUsages); } throw err; } } // dist/browser/key/generate_key_pair.js async function generateKeyPair2(alg, options) { return generateKeyPair(alg, options); } // dist/browser/key/generate_secret.js async function generateSecret2(alg, options) { return generateSecret(alg, options); } exports.CompactEncrypt = CompactEncrypt; exports.CompactSign = CompactSign; exports.EmbeddedJWK = EmbeddedJWK; exports.EncryptJWT = EncryptJWT; exports.FlattenedEncrypt = FlattenedEncrypt; exports.FlattenedSign = FlattenedSign; exports.GeneralEncrypt = GeneralEncrypt; exports.GeneralSign = GeneralSign; exports.SignJWT = SignJWT; exports.UnsecuredJWT = UnsecuredJWT; exports.base64url = base64url_exports2; exports.calculateJwkThumbprint = calculateJwkThumbprint; exports.calculateJwkThumbprintUri = calculateJwkThumbprintUri; exports.compactDecrypt = compactDecrypt; exports.compactVerify = compactVerify; exports.createLocalJWKSet = createLocalJWKSet; exports.createRemoteJWKSet = createRemoteJWKSet; exports.decodeJwt = decodeJwt; exports.decodeProtectedHeader = decodeProtectedHeader; exports.errors = errors_exports; exports.exportJWK = exportJWK; exports.exportPKCS8 = exportPKCS8; exports.exportSPKI = exportSPKI; exports.flattenedDecrypt = flattenedDecrypt; exports.flattenedVerify = flattenedVerify; exports.generalDecrypt = generalDecrypt; exports.generalVerify = generalVerify; exports.generateKeyPair = generateKeyPair2; exports.generateSecret = generateSecret2; exports.importJWK = importJWK; exports.importPKCS8 = importPKCS8; exports.importSPKI = importSPKI; exports.importX509 = importX509; exports.jwtDecrypt = jwtDecrypt; exports.jwtVerify = jwtVerify; })); jose-4.11.4/dist/browser/index.umd.min.js000066400000000000000000001762131437043056600202240ustar00rootroot00000000000000(function(g,f){typeof exports==='object'&&typeof module!=='undefined'?f(exports):typeof define==='function'&&define.amd?define(['exports'],f):(g=typeof globalThis!=='undefined'?globalThis:g||self,f(g.jose={}));})(this,(function(exports){'use strict';var Xt=Object.defineProperty;var ct=(e,t)=>{for(var r in t)Xt(e,r,{get:t[r],enumerable:!0});};var f=crypto,b=e=>e instanceof CryptoKey;var Yt=async(e,t)=>{let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await f.subtle.digest(r,t))},xe=Yt;var E=new TextEncoder,v=new TextDecoder,He=2**32;function W(...e){let t=e.reduce((o,{length:a})=>o+a,0),r=new Uint8Array(t),n=0;return e.forEach(o=>{r.set(o,n),n+=o.length;}),r}function dt(e,t){return W(E.encode(e),new Uint8Array([0]),t)}function Be(e,t,r){if(t<0||t>=He)throw new RangeError(`value must be >= 0 and <= ${He-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r);}function Ce(e){let t=Math.floor(e/He),r=e%He,n=new Uint8Array(8);return Be(n,t,0),Be(n,r,4),n}function Pe(e){let t=new Uint8Array(4);return Be(t,e),t}function We(e){return W(Pe(e.length),e)}async function pt(e,t,r){let n=Math.ceil((t>>3)/32),o=new Uint8Array(n*32);for(let a=0;a>3)}var pe=e=>{let t=e;typeof t=="string"&&(t=E.encode(t));let r=32768,n=[];for(let o=0;ope(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),Le=e=>{let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n{let t=e;t instanceof Uint8Array&&(t=v.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return Le(t)}catch(r){throw new TypeError("The input to be decoded is not correctly encoded.")}};var ft={};ct(ft,{JOSEAlgNotAllowed:()=>B,JOSEError:()=>C,JOSENotSupported:()=>m,JWEDecryptionFailed:()=>M,JWEInvalid:()=>u,JWKInvalid:()=>ue,JWKSInvalid:()=>L,JWKSMultipleMatchingKeys:()=>fe,JWKSNoMatchingKey:()=>q,JWKSTimeout:()=>le,JWSInvalid:()=>h,JWSSignatureVerificationFailed:()=>Z,JWTClaimValidationFailed:()=>J,JWTExpired:()=>re,JWTInvalid:()=>x});var C=class extends Error{static get code(){return "ERR_JOSE_GENERIC"}constructor(t){var r;super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor);}},J=class extends C{static get code(){return "ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(t,r="unspecified",n="unspecified"){super(t),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n;}},re=class extends C{static get code(){return "ERR_JWT_EXPIRED"}constructor(t,r="unspecified",n="unspecified"){super(t),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n;}},B=class extends C{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED";}static get code(){return "ERR_JOSE_ALG_NOT_ALLOWED"}},m=class extends C{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED";}static get code(){return "ERR_JOSE_NOT_SUPPORTED"}},M=class extends C{constructor(){super(...arguments),this.code="ERR_JWE_DECRYPTION_FAILED",this.message="decryption operation failed";}static get code(){return "ERR_JWE_DECRYPTION_FAILED"}},u=class extends C{constructor(){super(...arguments),this.code="ERR_JWE_INVALID";}static get code(){return "ERR_JWE_INVALID"}},h=class extends C{constructor(){super(...arguments),this.code="ERR_JWS_INVALID";}static get code(){return "ERR_JWS_INVALID"}},x=class extends C{constructor(){super(...arguments),this.code="ERR_JWT_INVALID";}static get code(){return "ERR_JWT_INVALID"}},ue=class extends C{constructor(){super(...arguments),this.code="ERR_JWK_INVALID";}static get code(){return "ERR_JWK_INVALID"}},L=class extends C{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID";}static get code(){return "ERR_JWKS_INVALID"}},q=class extends C{constructor(){super(...arguments),this.code="ERR_JWKS_NO_MATCHING_KEY",this.message="no applicable key found in the JSON Web Key Set";}static get code(){return "ERR_JWKS_NO_MATCHING_KEY"}},fe=class extends C{constructor(){super(...arguments),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",this.message="multiple matching keys found in the JSON Web Key Set";}static get code(){return "ERR_JWKS_MULTIPLE_MATCHING_KEYS"}},le=class extends C{constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out";}static get code(){return "ERR_JWKS_TIMEOUT"}},Z=class extends C{constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed";}static get code(){return "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}};var $=f.getRandomValues.bind(f);function $e(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new m(`Unsupported JWE Algorithm: ${e}`)}}var Je=e=>$(new Uint8Array($e(e)>>3));var qt=(e,t)=>{if(t.length<<3!==$e(e))throw new u("Invalid Initialization Vector length")},Te=qt;var Zt=(e,t)=>{let r=e.byteLength<<3;if(r!==t)throw new u(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)},ne=Zt;var Qt=(e,t)=>{if(!(e instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");if(e.length!==t.length)throw new TypeError("Input buffers must have the same length");let r=e.length,n=0,o=-1;for(;++oe.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`;}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function ht(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!N(e.algorithm,"HMAC"))throw P("HMAC");let n=parseInt(t.slice(2),10);if(Ie(e.algorithm.hash)!==n)throw P(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!N(e.algorithm,"RSASSA-PKCS1-v1_5"))throw P("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(Ie(e.algorithm.hash)!==n)throw P(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!N(e.algorithm,"RSA-PSS"))throw P("RSA-PSS");let n=parseInt(t.slice(2),10);if(Ie(e.algorithm.hash)!==n)throw P(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448"){if(D()){if(N(e.algorithm,"NODE-ED25519"))break;throw P("Ed25519, Ed448, or NODE-ED25519")}throw P("Ed25519 or Ed448")}break}case"ES256":case"ES384":case"ES512":{if(!N(e.algorithm,"ECDSA"))throw P("ECDSA");let n=jt(t);if(e.algorithm.namedCurve!==n)throw P(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}mt(e,r);}function I(e,t,...r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!N(e.algorithm,"AES-GCM"))throw P("AES-GCM");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw P(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!N(e.algorithm,"AES-KW"))throw P("AES-KW");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw P(n,"algorithm.length");break}case"ECDH":{switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw P("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!N(e.algorithm,"PBKDF2"))throw P("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!N(e.algorithm,"RSA-OAEP"))throw P("RSA-OAEP");let n=parseInt(t.slice(9),10)||1;if(Ie(e.algorithm.hash)!==n)throw P(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}mt(e,r);}function yt(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`;}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var A=(e,...t)=>yt("Key must be ",e,...t);function Ge(e,t,...r){return yt(`Key for the ${e} algorithm must be `,t,...r)}var Ve=e=>b(e),y=["CryptoKey"];async function er(e,t,r,n,o,a){if(!(t instanceof Uint8Array))throw new TypeError(A(t,"Uint8Array"));let i=parseInt(e.slice(1,4),10),s=await f.subtle.importKey("raw",t.subarray(i>>3),"AES-CBC",!1,["decrypt"]),c=await f.subtle.importKey("raw",t.subarray(0,i>>3),{hash:`SHA-${i<<1}`,name:"HMAC"},!1,["sign"]),p=W(a,n,r,Ce(a.length<<3)),d=new Uint8Array((await f.subtle.sign("HMAC",c,p)).slice(0,i>>3)),l;try{l=lt(o,d);}catch(T){}if(!l)throw new M;let H;try{H=new Uint8Array(await f.subtle.decrypt({iv:n,name:"AES-CBC"},s,r));}catch(T){}if(!H)throw new M;return H}async function tr(e,t,r,n,o,a){let i;t instanceof Uint8Array?i=await f.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(I(t,e,"decrypt"),i=t);try{return new Uint8Array(await f.subtle.decrypt({additionalData:a,iv:n,name:"AES-GCM",tagLength:128},i,W(r,o)))}catch(s){throw new M}}var rr=async(e,t,r,n,o,a)=>{if(!b(t)&&!(t instanceof Uint8Array))throw new TypeError(A(t,...y,"Uint8Array"));switch(Te(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&ne(t,parseInt(e.slice(-3),10)),er(e,t,r,n,o,a);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&ne(t,parseInt(e.slice(1,4),10)),tr(e,t,r,n,o,a);default:throw new m("Unsupported JWE Content Encryption Algorithm")}},De=rr;var wt=async()=>{throw new m('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.')},Et=async()=>{throw new m('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.')};var nr=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return !0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let a of o){if(r.has(a))return !1;r.add(a);}}return !0},R=nr;function or(e){return typeof e=="object"&&e!==null}function w(e){if(!or(e)||Object.prototype.toString.call(e)!=="[object Object]")return !1;if(Object.getPrototypeOf(e)===null)return !0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var ar=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]],oe=ar;function gt(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function St(e,t,r){if(b(e))return I(e,t,r),e;if(e instanceof Uint8Array)return f.subtle.importKey("raw",e,"AES-KW",!0,[r]);throw new TypeError(A(e,...y,"Uint8Array"))}var me=async(e,t,r)=>{let n=await St(t,e,"wrapKey");gt(n,e);let o=await f.subtle.importKey("raw",r,...oe);return new Uint8Array(await f.subtle.wrapKey("raw",o,n,"AES-KW"))},he=async(e,t,r)=>{let n=await St(t,e,"unwrapKey");gt(n,e);let o=await f.subtle.unwrapKey("raw",r,n,"AES-KW",...oe);return new Uint8Array(await f.subtle.exportKey("raw",o))};async function Re(e,t,r,n,o=new Uint8Array(0),a=new Uint8Array(0)){if(!b(e))throw new TypeError(A(e,...y));if(I(e,"ECDH"),!b(t))throw new TypeError(A(t,...y));I(t,"ECDH","deriveBits");let i=W(We(E.encode(r)),We(o),We(a),Pe(n)),s;e.algorithm.name==="X25519"?s=256:e.algorithm.name==="X448"?s=448:s=Math.ceil(parseInt(e.algorithm.namedCurve.substr(-3),10)/8)<<3;let c=new Uint8Array(await f.subtle.deriveBits({name:e.algorithm.name,public:e},t,s));return pt(c,n,i)}async function At(e){if(!b(e))throw new TypeError(A(e,...y));return f.subtle.generateKey(e.algorithm,!0,["deriveBits"])}function Oe(e){if(!b(e))throw new TypeError(A(e,...y));return ["P-256","P-384","P-521"].includes(e.algorithm.namedCurve)||e.algorithm.name==="X25519"||e.algorithm.name==="X448"}function Fe(e){if(!(e instanceof Uint8Array)||e.length<8)throw new u("PBES2 Salt Input must be 8 or more octets")}function ir(e,t){if(e instanceof Uint8Array)return f.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);if(b(e))return I(e,t,"deriveBits","deriveKey"),e;throw new TypeError(A(e,...y,"Uint8Array"))}async function _t(e,t,r,n){Fe(e);let o=dt(t,e),a=parseInt(t.slice(13,16),10),i={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:o},s={length:a,name:"AES-KW"},c=await ir(n,t);if(c.usages.includes("deriveBits"))return new Uint8Array(await f.subtle.deriveBits(i,c,a));if(c.usages.includes("deriveKey"))return f.subtle.deriveKey(i,c,s,!1,["wrapKey","unwrapKey"]);throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}var vt=async(e,t,r,n=2048,o=$(new Uint8Array(16)))=>{let a=await _t(o,e,n,t);return {encryptedKey:await me(e.slice(-6),a,r),p2c:n,p2s:g(o)}},Kt=async(e,t,r,n,o)=>{let a=await _t(o,e,n,t);return he(e.slice(-6),a,r)};function ae(e){switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return "RSA-OAEP";default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Q=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};var xt=async(e,t,r)=>{if(!b(t))throw new TypeError(A(t,...y));if(I(t,e,"encrypt","wrapKey"),Q(e,t),t.usages.includes("encrypt"))return new Uint8Array(await f.subtle.encrypt(ae(e),t,r));if(t.usages.includes("wrapKey")){let n=await f.subtle.importKey("raw",r,...oe);return new Uint8Array(await f.subtle.wrapKey("raw",n,t,ae(e)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},Ht=async(e,t,r)=>{if(!b(t))throw new TypeError(A(t,...y));if(I(t,e,"decrypt","unwrapKey"),Q(e,t),t.usages.includes("decrypt"))return new Uint8Array(await f.subtle.decrypt(ae(e),t,r));if(t.usages.includes("unwrapKey")){let n=await f.subtle.unwrapKey("raw",r,t,ae(e),...oe);return new Uint8Array(await f.subtle.exportKey("raw",n))}throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')};function ye(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new m(`Unsupported JWE Algorithm: ${e}`)}}var O=e=>$(new Uint8Array(ye(e)>>3));var Ue=(e,t)=>{let r=(e.match(/.{1,64}/g)||[]).join(` `);return `-----BEGIN ${t}----- ${r} -----END ${t}-----`};var Pt=async(e,t,r)=>{if(!b(r))throw new TypeError(A(r,...y));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return Ue(pe(new Uint8Array(await f.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},Wt=e=>Pt("public","spki",e),Jt=e=>Pt("private","pkcs8",e),G=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return !1;let o=e.subarray(n,n+t.length);return o.length!==t.length?!1:o.every((a,i)=>a===t[i])||G(e,t,n+1)},Ct=e=>{switch(!0){case G(e,[42,134,72,206,61,3,1,7]):return "P-256";case G(e,[43,129,4,0,34]):return "P-384";case G(e,[43,129,4,0,35]):return "P-521";case G(e,[43,101,110]):return "X25519";case G(e,[43,101,111]):return "X448";case G(e,[43,101,112]):return "Ed25519";case G(e,[43,101,113]):return "Ed448";default:throw new m("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},Tt=async(e,t,r,n,o)=>{var a,i;let s,c,p=new Uint8Array(atob(r.replace(e,"")).split("").map(l=>l.charCodeAt(0))),d=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":s={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},c=d?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":s={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},c=d?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},c=d?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":s={name:"ECDSA",namedCurve:"P-256"},c=d?["verify"]:["sign"];break;case"ES384":s={name:"ECDSA",namedCurve:"P-384"},c=d?["verify"]:["sign"];break;case"ES512":s={name:"ECDSA",namedCurve:"P-521"},c=d?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let l=Ct(p);s=l.startsWith("P-")?{name:"ECDH",namedCurve:l}:{name:l},c=d?[]:["deriveBits"];break}case"EdDSA":s={name:Ct(p)},c=d?["verify"]:["sign"];break;default:throw new m('Invalid or unsupported "alg" (Algorithm) value')}try{return await f.subtle.importKey(t,p,s,(a=o==null?void 0:o.extractable)!==null&&a!==void 0?a:!1,c)}catch(l){if(s.name==="Ed25519"&&(l==null?void 0:l.name)==="NotSupportedError"&&D())return s={name:"NODE-ED25519",namedCurve:"NODE-ED25519"},await f.subtle.importKey(t,p,s,(i=o==null?void 0:o.extractable)!==null&&i!==void 0?i:!1,c);throw l}},It=(e,t,r)=>Tt(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),ze=(e,t,r)=>Tt(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);function sr(e){let t,r;switch(e.kty){case"oct":{switch(e.alg){case"HS256":case"HS384":case"HS512":t={name:"HMAC",hash:`SHA-${e.alg.slice(-3)}`},r=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":throw new m(`${e.alg} keys cannot be imported as CryptoKey instances`);case"A128GCM":case"A192GCM":case"A256GCM":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":t={name:"AES-GCM"},r=["encrypt","decrypt"];break;case"A128KW":case"A192KW":case"A256KW":t={name:"AES-KW"},r=["wrapKey","unwrapKey"];break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":t={name:"PBKDF2"},r=["deriveBits"];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new m('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return {algorithm:t,keyUsages:r}}var cr=async e=>{var t,r;let{algorithm:n,keyUsages:o}=sr(e),a=[n,(t=e.ext)!==null&&t!==void 0?t:!1,(r=e.key_ops)!==null&&r!==void 0?r:o];if(n.name==="PBKDF2")return f.subtle.importKey("raw",S(e.k),...a);let i={...e};delete i.alg,delete i.use;try{return await f.subtle.importKey("jwk",i,...a)}catch(s){if(n.name==="Ed25519"&&(s==null?void 0:s.name)==="NotSupportedError"&&D())return a[0]={name:"NODE-ED25519",namedCurve:"NODE-ED25519"},await f.subtle.importKey("jwk",i,...a);throw s}},Xe=cr;function Dt(e){let t=[],r=0;for(;r=128;)r=r*128+e[t]-128,t++;r=r*128+e[t]-128,t++;}let n=0;if(e[t]<128)n=e[t],t++;else if(n===128){for(n=0;e[t+n]!==0||e[t+n+1]!==0;){if(n>e.byteLength)throw new TypeError("invalid indefinite form length");n++;}let a=t+n+2;return {byteLength:a,contents:e.subarray(t,t+n),raw:e.subarray(0,a)}}else {let a=e[t]&127;t++,n=0;for(let i=0;i{if(!(t instanceof Uint8Array)){if(!Ve(t))throw new TypeError(Ge(e,t,...y,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${y.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},hr=(e,t,r)=>{if(!Ve(t))throw new TypeError(Ge(e,t,...y));if(t.type==="secret")throw new TypeError(`${y.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${y.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${y.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${y.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${y.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},yr=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?mr(e,t):hr(e,t,r);},V=yr;async function wr(e,t,r,n,o){if(!(r instanceof Uint8Array))throw new TypeError(A(r,"Uint8Array"));let a=parseInt(e.slice(1,4),10),i=await f.subtle.importKey("raw",r.subarray(a>>3),"AES-CBC",!1,["encrypt"]),s=await f.subtle.importKey("raw",r.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),c=new Uint8Array(await f.subtle.encrypt({iv:n,name:"AES-CBC"},i,t)),p=W(o,n,c,Ce(o.length<<3)),d=new Uint8Array((await f.subtle.sign("HMAC",s,p)).slice(0,a>>3));return {ciphertext:c,tag:d}}async function Er(e,t,r,n,o){let a;r instanceof Uint8Array?a=await f.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(I(r,e,"encrypt"),a=r);let i=new Uint8Array(await f.subtle.encrypt({additionalData:o,iv:n,name:"AES-GCM",tagLength:128},a,t)),s=i.slice(-16);return {ciphertext:i.slice(0,-16),tag:s}}var gr=async(e,t,r,n,o)=>{if(!b(r)&&!(r instanceof Uint8Array))throw new TypeError(A(r,...y,"Uint8Array"));switch(Te(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&ne(r,parseInt(e.slice(-3),10)),wr(e,t,r,n,o);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&ne(r,parseInt(e.slice(1,4),10)),Er(e,t,r,n,o);default:throw new m("Unsupported JWE Content Encryption Algorithm")}},we=gr;async function Ot(e,t,r,n){let o=e.slice(0,7);n||(n=Je(o));let{ciphertext:a,tag:i}=await we(o,r,t,n,new Uint8Array(0));return {encryptedKey:a,iv:g(n),tag:g(i)}}async function Ut(e,t,r,n,o){let a=e.slice(0,7);return De(a,t,r,n,o,new Uint8Array(0))}async function Sr(e,t,r,n,o){switch(V(e,t,"decrypt"),e){case"dir":{if(r!==void 0)throw new u("Encountered unexpected JWE Encrypted Key");return t}case"ECDH-ES":if(r!==void 0)throw new u("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!w(n.epk))throw new u('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!Oe(t))throw new m("ECDH with the provided key is not allowed or not supported by your javascript runtime");let a=await j(n.epk,e),i,s;if(n.apu!==void 0){if(typeof n.apu!="string")throw new u('JOSE Header "apu" (Agreement PartyUInfo) invalid');i=S(n.apu);}if(n.apv!==void 0){if(typeof n.apv!="string")throw new u('JOSE Header "apv" (Agreement PartyVInfo) invalid');s=S(n.apv);}let c=await Re(a,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?ye(n.enc):parseInt(e.slice(-5,-2),10),i,s);if(e==="ECDH-ES")return c;if(r===void 0)throw new u("JWE Encrypted Key missing");return he(e.slice(-6),c,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(r===void 0)throw new u("JWE Encrypted Key missing");return Ht(e,t,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new u("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new u('JOSE Header "p2c" (PBES2 Count) missing or invalid');let a=(o==null?void 0:o.maxPBES2Count)||1e4;if(n.p2c>a)throw new u('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new u('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return Kt(e,t,r,n.p2c,S(n.p2s))}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new u("JWE Encrypted Key missing");return he(e,t,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new u("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new u('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new u('JOSE Header "tag" (Authentication Tag) missing or invalid');let a=S(n.iv),i=S(n.tag);return Ut(e,t,r,a,i)}default:throw new m('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var Mt=Sr;function Ar(e,t,r,n,o){if(o.crit!==void 0&&n.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let i of n.crit){if(!a.has(i))throw new m(`Extension Header Parameter "${i}" is not recognized`);if(o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(a.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var U=Ar;var br=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)},Ee=br;async function ge(e,t,r){var n;if(!w(e))throw new u("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new u("JOSE Header missing");if(typeof e.iv!="string")throw new u("JWE Initialization Vector missing or incorrect type");if(typeof e.ciphertext!="string")throw new u("JWE Ciphertext missing or incorrect type");if(typeof e.tag!="string")throw new u("JWE Authentication Tag missing or incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new u("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new u("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new u("JWE AAD incorrect type");if(e.header!==void 0&&!w(e.header))throw new u("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!w(e.unprotected))throw new u("JWE Per-Recipient Unprotected Header incorrect type");let o;if(e.protected)try{let Y=S(e.protected);o=JSON.parse(v.decode(Y));}catch(Y){throw new u("JWE Protected Header is invalid")}if(!R(o,e.header,e.unprotected))throw new u("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let a={...o,...e.header,...e.unprotected};if(U(u,new Map,r==null?void 0:r.crit,o,a),a.zip!==void 0){if(!o||!o.zip)throw new u('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(a.zip!=="DEF")throw new m('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:i,enc:s}=a;if(typeof i!="string"||!i)throw new u("missing JWE Algorithm (alg) in JWE Header");if(typeof s!="string"||!s)throw new u("missing JWE Encryption Algorithm (enc) in JWE Header");let c=r&&Ee("keyManagementAlgorithms",r.keyManagementAlgorithms),p=r&&Ee("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(c&&!c.has(i))throw new B('"alg" (Algorithm) Header Parameter not allowed');if(p&&!p.has(s))throw new B('"enc" (Encryption Algorithm) Header Parameter not allowed');let d;e.encrypted_key!==void 0&&(d=S(e.encrypted_key));let l=!1;typeof t=="function"&&(t=await t(o,e),l=!0);let H;try{H=await Mt(i,t,d,a,r);}catch(Y){if(Y instanceof TypeError||Y instanceof u||Y instanceof m)throw Y;H=O(s);}let T=S(e.iv),K=S(e.tag),_=E.encode((n=e.protected)!==null&&n!==void 0?n:""),k;e.aad!==void 0?k=W(_,E.encode("."),E.encode(e.aad)):k=_;let ke=await De(s,H,S(e.ciphertext),T,K,k);a.zip==="DEF"&&(ke=await((r==null?void 0:r.inflateRaw)||wt)(ke));let te={plaintext:ke};return e.protected!==void 0&&(te.protectedHeader=o),e.aad!==void 0&&(te.additionalAuthenticatedData=S(e.aad)),e.unprotected!==void 0&&(te.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(te.unprotectedHeader=e.header),l?{...te,key:t}:te}async function Ye(e,t,r){if(e instanceof Uint8Array&&(e=v.decode(e)),typeof e!="string")throw new u("Compact JWE must be a string or Uint8Array");let{0:n,1:o,2:a,3:i,4:s,length:c}=e.split(".");if(c!==5)throw new u("Invalid Compact JWE");let p=await ge({ciphertext:i,iv:a||void 0,protected:n||void 0,tag:s||void 0,encrypted_key:o||void 0},t,r),d={plaintext:p.plaintext,protectedHeader:p.protectedHeader};return typeof t=="function"?{...d,key:p.key}:d}async function _r(e,t,r){if(!w(e))throw new u("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(w))throw new u("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new u("JWE Recipients has no members");for(let n of e.recipients)try{return await ge({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch(o){}throw new M}var vr=async e=>{if(e instanceof Uint8Array)return {kty:"oct",k:g(e)};if(!b(e))throw new TypeError(A(e,...y,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:o,...a}=await f.subtle.exportKey("jwk",e);return a},Nt=vr;async function Kr(e){return Wt(e)}async function xr(e){return Jt(e)}async function qe(e){return Nt(e)}async function Hr(e,t,r,n,o={}){let a,i,s;switch(V(e,r,"encrypt"),e){case"dir":{s=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Oe(r))throw new m("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:c,apv:p}=o,{epk:d}=o;d||(d=(await At(r)).privateKey);let{x:l,y:H,crv:T,kty:K}=await qe(d),_=await Re(r,d,e==="ECDH-ES"?t:e,e==="ECDH-ES"?ye(t):parseInt(e.slice(-5,-2),10),c,p);if(i={epk:{x:l,crv:T,kty:K}},K==="EC"&&(i.epk.y=H),c&&(i.apu=g(c)),p&&(i.apv=g(p)),e==="ECDH-ES"){s=_;break}s=n||O(t);let k=e.slice(-6);a=await me(k,_,s);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{s=n||O(t),a=await xt(e,r,s);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=n||O(t);let{p2c:c,p2s:p}=o;({encryptedKey:a,...i}=await vt(e,r,s,c,p));break}case"A128KW":case"A192KW":case"A256KW":{s=n||O(t),a=await me(e,r,s);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=n||O(t);let{iv:c}=o;({encryptedKey:a,...i}=await Ot(e,r,s,c));break}default:throw new m('Invalid or unsupported "alg" (JWE Algorithm) header value')}return {cek:s,encryptedKey:a,parameters:i}}var Me=Hr;var Ze=Symbol(),F=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=t;}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}async encrypt(t,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new u("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!R(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new u("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(U(u,new Map,r==null?void 0:r.crit,this._protectedHeader,n),n.zip!==void 0){if(!this._protectedHeader||!this._protectedHeader.zip)throw new u('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(n.zip!=="DEF")throw new m('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:o,enc:a}=n;if(typeof o!="string"||!o)throw new u('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof a!="string"||!a)throw new u('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let i;if(o==="dir"){if(this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption")}else if(o==="ECDH-ES"&&this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");let s;{let K;(({cek:s,encryptedKey:i,parameters:K}=await Me(o,a,t,this._cek,this._keyManagementParameters))),K&&(r&&Ze in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...K}:this.setUnprotectedHeader(K):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...K}:this.setProtectedHeader(K));}this._iv||(this._iv=Je(a));let c,p,d;this._protectedHeader?p=E.encode(g(JSON.stringify(this._protectedHeader))):p=E.encode(""),this._aad?(d=g(this._aad),c=W(p,E.encode("."),E.encode(d))):c=p;let l,H;if(n.zip==="DEF"){let K=await((r==null?void 0:r.deflateRaw)||Et)(this._plaintext);({ciphertext:l,tag:H}=await we(a,K,s,this._iv,c));}else ({ciphertext:l,tag:H}=await we(a,this._plaintext,s,this._iv,c));let T={ciphertext:g(l),iv:g(this._iv),tag:g(H)};return i&&(T.encrypted_key=g(i)),d&&(T.aad=d),this._protectedHeader&&(T.protected=v.decode(p)),this._sharedUnprotectedHeader&&(T.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(T.header=this._unprotectedHeader),T}};var Qe=class{constructor(t,r,n){this.parent=t,this.key=r,this.options=n;}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addRecipient(...t){return this.parent.addRecipient(...t)}encrypt(...t){return this.parent.encrypt(...t)}done(){return this.parent}},je=class{constructor(t){this._recipients=[],this._plaintext=t;}addRecipient(t,r){let n=new Qe(this,t,{crit:r==null?void 0:r.crit});return this._recipients.push(n),n}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}async encrypt(t){var r,n,o;if(!this._recipients.length)throw new u("at least one recipient must be added");if(t={deflateRaw:t==null?void 0:t.deflateRaw},this._recipients.length===1){let[c]=this._recipients,p=await new F(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(c.unprotectedHeader).encrypt(c.key,{...c.options,...t}),d={ciphertext:p.ciphertext,iv:p.iv,recipients:[{}],tag:p.tag};return p.aad&&(d.aad=p.aad),p.protected&&(d.protected=p.protected),p.unprotected&&(d.unprotected=p.unprotected),p.encrypted_key&&(d.recipients[0].encrypted_key=p.encrypted_key),p.header&&(d.recipients[0].header=p.header),d}let a;for(let c=0;c>3};case"RS256":case"RS384":case"RS512":return {hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return {hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return D()&&t.name==="NODE-ED25519"?{name:"NODE-ED25519",namedCurve:"NODE-ED25519"}:{name:t.name};default:throw new m(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}function Ae(e,t,r){if(b(t))return ht(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(A(t,...y));return f.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(A(t,...y,"Uint8Array"))}var Cr=async(e,t,r,n)=>{let o=await Ae(e,t,"verify");Q(e,o);let a=Se(e,o.algorithm);try{return await f.subtle.verify(a,o,r,n)}catch(i){return !1}},kt=Cr;async function be(e,t,r){var n;if(!w(e))throw new h("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new h('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new h("JWS Protected Header incorrect type");if(e.payload===void 0)throw new h("JWS Payload missing");if(typeof e.signature!="string")throw new h("JWS Signature missing or incorrect type");if(e.header!==void 0&&!w(e.header))throw new h("JWS Unprotected Header incorrect type");let o={};if(e.protected)try{let k=S(e.protected);o=JSON.parse(v.decode(k));}catch(k){throw new h("JWS Protected Header is invalid")}if(!R(o,e.header))throw new h("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let a={...o,...e.header},i=U(h,new Map([["b64",!0]]),r==null?void 0:r.crit,o,a),s=!0;if(i.has("b64")&&(s=o.b64,typeof s!="boolean"))throw new h('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:c}=a;if(typeof c!="string"||!c)throw new h('JWS "alg" (Algorithm) Header Parameter missing or invalid');let p=r&&Ee("algorithms",r.algorithms);if(p&&!p.has(c))throw new B('"alg" (Algorithm) Header Parameter not allowed');if(s){if(typeof e.payload!="string")throw new h("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new h("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof t=="function"&&(t=await t(o,e),d=!0),V(c,t,"verify");let l=W(E.encode((n=e.protected)!==null&&n!==void 0?n:""),E.encode("."),typeof e.payload=="string"?E.encode(e.payload):e.payload),H=S(e.signature);if(!await kt(c,t,H,l))throw new Z;let K;s?K=S(e.payload):typeof e.payload=="string"?K=E.encode(e.payload):K=e.payload;let _={payload:K};return e.protected!==void 0&&(_.protectedHeader=o),e.header!==void 0&&(_.unprotectedHeader=e.header),d?{..._,key:t}:_}async function et(e,t,r){if(e instanceof Uint8Array&&(e=v.decode(e)),typeof e!="string")throw new h("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:a,length:i}=e.split(".");if(i!==3)throw new h("Invalid Compact JWS");let s=await be({payload:o,protected:n,signature:a},t,r),c={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t=="function"?{...c,key:s.key}:c}async function Pr(e,t,r){if(!w(e))throw new h("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(w))throw new h("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await be({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch(o){}throw new Z}var ie=e=>Math.floor(e.getTime()/1e3);var Wr=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,se=e=>{let t=Wr.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}};var Bt=e=>e.toLowerCase().replace(/^application\//,""),Jr=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,ce=(e,t,r={})=>{let{typ:n}=r;if(n&&(typeof e.typ!="string"||Bt(e.typ)!==Bt(n)))throw new J('unexpected "typ" JWT header value',"typ","check_failed");let o;try{o=JSON.parse(v.decode(t));}catch(l){}if(!w(o))throw new x("JWT Claims Set must be a top-level JSON object");let{issuer:a}=r;if(a&&!(Array.isArray(a)?a:[a]).includes(o.iss))throw new J('unexpected "iss" claim value',"iss","check_failed");let{subject:i}=r;if(i&&o.sub!==i)throw new J('unexpected "sub" claim value',"sub","check_failed");let{audience:s}=r;if(s&&!Jr(o.aud,typeof s=="string"?[s]:s))throw new J('unexpected "aud" claim value',"aud","check_failed");let c;switch(typeof r.clockTolerance){case"string":c=se(r.clockTolerance);break;case"number":c=r.clockTolerance;break;case"undefined":c=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=r,d=ie(p||new Date);if((o.iat!==void 0||r.maxTokenAge)&&typeof o.iat!="number")throw new J('"iat" claim must be a number',"iat","invalid");if(o.nbf!==void 0){if(typeof o.nbf!="number")throw new J('"nbf" claim must be a number',"nbf","invalid");if(o.nbf>d+c)throw new J('"nbf" claim timestamp check failed',"nbf","check_failed")}if(o.exp!==void 0){if(typeof o.exp!="number")throw new J('"exp" claim must be a number',"exp","invalid");if(o.exp<=d-c)throw new re('"exp" claim timestamp check failed',"exp","check_failed")}if(r.maxTokenAge){let l=d-o.iat,H=typeof r.maxTokenAge=="number"?r.maxTokenAge:se(r.maxTokenAge);if(l-c>H)throw new re('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(l<0-c)throw new J('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return o};async function Tr(e,t,r){var n;let o=await et(e,t,r);if(!((n=o.protectedHeader.crit)===null||n===void 0)&&n.includes("b64")&&o.protectedHeader.b64===!1)throw new x("JWTs MUST NOT use unencoded payload");let i={payload:ce(o.protectedHeader,o.payload,r),protectedHeader:o.protectedHeader};return typeof t=="function"?{...i,key:o.key}:i}async function Ir(e,t,r){let n=await Ye(e,t,r),o=ce(n.protectedHeader,n.plaintext,r),{protectedHeader:a}=n;if(a.iss!==void 0&&a.iss!==o.iss)throw new J('replicated "iss" claim header parameter mismatch',"iss","mismatch");if(a.sub!==void 0&&a.sub!==o.sub)throw new J('replicated "sub" claim header parameter mismatch',"sub","mismatch");if(a.aud!==void 0&&JSON.stringify(a.aud)!==JSON.stringify(o.aud))throw new J('replicated "aud" claim header parameter mismatch',"aud","mismatch");let i={payload:o,protectedHeader:a};return typeof t=="function"?{...i,key:n.key}:i}var _e=class{constructor(t){this._flattened=new F(t);}setContentEncryptionKey(t){return this._flattened.setContentEncryptionKey(t),this}setInitializationVector(t){return this._flattened.setInitializationVector(t),this}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}setKeyManagementParameters(t){return this._flattened.setKeyManagementParameters(t),this}async encrypt(t,r){let n=await this._flattened.encrypt(t,r);return [n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}};var Dr=async(e,t,r)=>{let n=await Ae(e,t,"sign");Q(e,n);let o=await f.subtle.sign(Se(e,n.algorithm),n,r);return new Uint8Array(o)},Lt=Dr;var ee=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t;}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new h("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!R(this._protectedHeader,this._unprotectedHeader))throw new h("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},o=U(h,new Map([["b64",!0]]),r==null?void 0:r.crit,this._protectedHeader,n),a=!0;if(o.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new h('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new h('JWS "alg" (Algorithm) Header Parameter missing or invalid');V(i,t,"sign");let s=this._payload;a&&(s=E.encode(g(s)));let c;this._protectedHeader?c=E.encode(g(JSON.stringify(this._protectedHeader))):c=E.encode("");let p=W(c,E.encode("."),s),d=await Lt(i,t,p),l={signature:g(d),payload:""};return a&&(l.payload=v.decode(s)),this._unprotectedHeader&&(l.header=this._unprotectedHeader),this._protectedHeader&&(l.protected=v.decode(c)),l}};var ve=class{constructor(t){this._flattened=new ee(t);}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return `${n.protected}.${n.payload}.${n.signature}`}};var tt=class{constructor(t,r,n){this.parent=t,this.key=r,this.options=n;}setProtectedHeader(t){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=t,this}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addSignature(...t){return this.parent.addSignature(...t)}sign(...t){return this.parent.sign(...t)}done(){return this.parent}},rt=class{constructor(t){this._signatures=[],this._payload=t;}addSignature(t,r){let n=new tt(this,t,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new h("at least one signature must be added");let t={signatures:[],payload:""};for(let r=0;r{if(typeof e!="string"||!e)throw new ue(`${t} missing or invalid`)};async function $t(e,t){if(!w(e))throw new TypeError("JWK must be an object");if(t!=null||(t="sha256"),t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":X(e.crv,'"crv" (Curve) Parameter'),X(e.x,'"x" (X Coordinate) Parameter'),X(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":X(e.crv,'"crv" (Subtype of Key Pair) Parameter'),X(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":X(e.e,'"e" (Exponent) Parameter'),X(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":X(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new m('"kty" (Key Type) Parameter missing or unsupported')}let n=E.encode(JSON.stringify(r));return g(await xe(t,n))}async function Rr(e,t){t!=null||(t="sha256");let r=await $t(e,t);return `urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}async function Or(e,t){let r={...e,...t.header};if(!w(r.jwk))throw new h('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await j({...r.jwk,ext:!0},r.alg,!0);if(n instanceof Uint8Array||n.type!=="public")throw new h('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}function Ur(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return "RSA";case"ES":return "EC";case"Ed":return "OKP";default:throw new m('Unsupported "alg" value for a JSON Web Key Set')}}function at(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(Mr)}function Mr(e){return w(e)}function Nr(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}var de=class{constructor(t){if(this._cached=new WeakMap,!at(t))throw new L("JSON Web Key Set malformed");this._jwks=Nr(t);}async getKey(t,r){let{alg:n,kid:o}={...t,...r.header},a=Ur(n),i=this._jwks.keys.filter(d=>{let l=a===d.kty;if(l&&typeof o=="string"&&(l=o===d.kid),l&&typeof d.alg=="string"&&(l=n===d.alg),l&&typeof d.use=="string"&&(l=d.use==="sig"),l&&Array.isArray(d.key_ops)&&(l=d.key_ops.includes("verify")),l&&n==="EdDSA"&&(l=d.crv==="Ed25519"||d.crv==="Ed448"),l)switch(n){case"ES256":l=d.crv==="P-256";break;case"ES256K":l=d.crv==="secp256k1";break;case"ES384":l=d.crv==="P-384";break;case"ES512":l=d.crv==="P-521";break}return l}),{0:s,length:c}=i;if(c===0)throw new q;if(c!==1)throw new fe;let p=this._cached.get(s)||this._cached.set(s,{}).get(s);if(p[n]===void 0){let d=await j({...s,ext:!0},n);if(d instanceof Uint8Array||d.type!=="public")throw new L("JSON Web Key Set members must be public keys");p[n]=d;}return p[n]}};function kr(e){return de.prototype.getKey.bind(new de(e))}var Br=async(e,t,r)=>{let n,o,a=!1;typeof AbortController=="function"&&(n=new AbortController,o=setTimeout(()=>{a=!0,n.abort();},t));let i=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(s=>{throw a?new le:s});if(o!==void 0&&clearTimeout(o),i.status!==200)throw new C("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch(s){throw new C("Failed to parse the JSON Web Key Set HTTP response as JSON")}},Gt=Br;var Ne=class extends de{constructor(t,r){if(super({keys:[]}),this._jwks=void 0,!(t instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(t.href),this._options={agent:r==null?void 0:r.agent,headers:r==null?void 0:r.headers},this._timeoutDuration=typeof(r==null?void 0:r.timeoutDuration)=="number"?r==null?void 0:r.timeoutDuration:5e3,this._cooldownDuration=typeof(r==null?void 0:r.cooldownDuration)=="number"?r==null?void 0:r.cooldownDuration:3e4,this._cacheMaxAge=typeof(r==null?void 0:r.cacheMaxAge)=="number"?r==null?void 0:r.cacheMaxAge:6e5;}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now(){let r=()=>{this._pendingFetch===void 0?t():setTimeout(r,5);};r();});this._pendingFetch||(this._pendingFetch=Gt(this._url,this._timeoutDuration,this._options).then(t=>{if(!at(t))throw new L("JSON Web Key Set malformed");this._jwks={keys:t.keys},this._jwksTimestamp=Date.now(),this._pendingFetch=void 0;}).catch(t=>{throw this._pendingFetch=void 0,t})),await this._pendingFetch;}};function Lr(e,t){return Ne.prototype.getKey.bind(new Ne(e,t))}var it=class extends z{encode(){let t=g(JSON.stringify({alg:"none"})),r=g(JSON.stringify(this._payload));return `${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new x("Unsecured JWT must be a string");let{0:n,1:o,2:a,length:i}=t.split(".");if(i!==3||a!=="")throw new x("Invalid Unsecured JWT");let s;try{if(s=JSON.parse(v.decode(S(n))),s.alg!=="none")throw new Error}catch(p){throw new x("Invalid Unsecured JWT")}return {payload:ce(s,S(o),r),header:s}}};var Vt={};ct(Vt,{decode:()=>Ke,encode:()=>$r});var $r=g,Ke=S;function Gr(e){let t;if(typeof e=="string"){let r=e.split(".");(r.length===3||r.length===5)&&([t]=r);}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let r=JSON.parse(v.decode(Ke(t)));if(!w(r))throw new Error;return r}catch(r){throw new TypeError("Invalid Token or Protected Header formatting")}}function Vr(e){if(typeof e!="string")throw new x("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new x("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new x("Invalid JWT");if(!t)throw new x("JWTs must contain a payload");let n;try{n=Ke(t);}catch(a){throw new x("Failed to parse the base64url encoded payload")}let o;try{o=JSON.parse(v.decode(n));}catch(a){throw new x("Failed to parse the decoded payload as JSON")}if(!w(o))throw new x("Invalid JWT Claims Set");return o}async function Ft(e,t){var r;let n,o,a;switch(e){case"HS256":case"HS384":case"HS512":n=parseInt(e.slice(-3),10),o={name:"HMAC",hash:`SHA-${n}`,length:n},a=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return n=parseInt(e.slice(-3),10),$(new Uint8Array(n>>3));case"A128KW":case"A192KW":case"A256KW":n=parseInt(e.slice(1,4),10),o={name:"AES-KW",length:n},a=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":n=parseInt(e.slice(1,4),10),o={name:"AES-GCM",length:n},a=["encrypt","decrypt"];break;default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return f.subtle.generateKey(o,(r=t==null?void 0:t.extractable)!==null&&r!==void 0?r:!1,a)}function st(e){var t;let r=(t=e==null?void 0:e.modulusLength)!==null&&t!==void 0?t:2048;if(typeof r!="number"||r<2048)throw new m("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return r}async function zt(e,t){var r,n,o,a;let i,s;switch(e){case"PS256":case"PS384":case"PS512":i={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:st(t)},s=["sign","verify"];break;case"RS256":case"RS384":case"RS512":i={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:st(t)},s=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":i={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:st(t)},s=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":i={name:"ECDSA",namedCurve:"P-256"},s=["sign","verify"];break;case"ES384":i={name:"ECDSA",namedCurve:"P-384"},s=["sign","verify"];break;case"ES512":i={name:"ECDSA",namedCurve:"P-521"},s=["sign","verify"];break;case"EdDSA":s=["sign","verify"];let c=(r=t==null?void 0:t.crv)!==null&&r!==void 0?r:"Ed25519";switch(c){case"Ed25519":case"Ed448":i={name:c};break;default:throw new m("Invalid or unsupported crv option provided")}break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{s=["deriveKey","deriveBits"];let p=(n=t==null?void 0:t.crv)!==null&&n!==void 0?n:"P-256";switch(p){case"P-256":case"P-384":case"P-521":{i={name:"ECDH",namedCurve:p};break}case"X25519":case"X448":i={name:p};break;default:throw new m("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new m('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}try{return await f.subtle.generateKey(i,(o=t==null?void 0:t.extractable)!==null&&o!==void 0?o:!1,s)}catch(c){if(i.name==="Ed25519"&&(c==null?void 0:c.name)==="NotSupportedError"&&D())return i={name:"NODE-ED25519",namedCurve:"NODE-ED25519"},await f.subtle.generateKey(i,(a=t==null?void 0:t.extractable)!==null&&a!==void 0?a:!1,s);throw c}}async function Fr(e,t){return zt(e,t)}async function zr(e,t){return Ft(e,t)} exports.CompactEncrypt=_e;exports.CompactSign=ve;exports.EmbeddedJWK=Or;exports.EncryptJWT=ot;exports.FlattenedEncrypt=F;exports.FlattenedSign=ee;exports.GeneralEncrypt=je;exports.GeneralSign=rt;exports.SignJWT=nt;exports.UnsecuredJWT=it;exports.base64url=Vt;exports.calculateJwkThumbprint=$t;exports.calculateJwkThumbprintUri=Rr;exports.compactDecrypt=Ye;exports.compactVerify=et;exports.createLocalJWKSet=kr;exports.createRemoteJWKSet=Lr;exports.decodeJwt=Vr;exports.decodeProtectedHeader=Gr;exports.errors=ft;exports.exportJWK=qe;exports.exportPKCS8=xr;exports.exportSPKI=Kr;exports.flattenedDecrypt=ge;exports.flattenedVerify=be;exports.generalDecrypt=_r;exports.generalVerify=Pr;exports.generateKeyPair=Fr;exports.generateSecret=zr;exports.importJWK=j;exports.importPKCS8=lr;exports.importSPKI=ur;exports.importX509=fr;exports.jwtDecrypt=Ir;exports.jwtVerify=Tr;}));jose-4.11.4/dist/browser/jwe/000077500000000000000000000000001437043056600157645ustar00rootroot00000000000000jose-4.11.4/dist/browser/jwe/compact/000077500000000000000000000000001437043056600174125ustar00rootroot00000000000000jose-4.11.4/dist/browser/jwe/compact/decrypt.js000066400000000000000000000020601437043056600214200ustar00rootroot00000000000000import { flattenedDecrypt } from '../flattened/decrypt.js'; import { JWEInvalid } from '../../util/errors.js'; import { decoder } from '../../lib/buffer_utils.js'; export async function compactDecrypt(jwe, key, options) { if (jwe instanceof Uint8Array) { jwe = decoder.decode(jwe); } if (typeof jwe !== 'string') { throw new JWEInvalid('Compact JWE must be a string or Uint8Array'); } const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.'); if (length !== 5) { throw new JWEInvalid('Invalid Compact JWE'); } const decrypted = await flattenedDecrypt({ ciphertext, iv: (iv || undefined), protected: protectedHeader || undefined, tag: (tag || undefined), encrypted_key: encryptedKey || undefined, }, key, options); const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; if (typeof key === 'function') { return { ...result, key: decrypted.key }; } return result; } jose-4.11.4/dist/browser/jwe/compact/encrypt.js000066400000000000000000000015611437043056600214370ustar00rootroot00000000000000import { FlattenedEncrypt } from '../flattened/encrypt.js'; export class CompactEncrypt { constructor(plaintext) { this._flattened = new FlattenedEncrypt(plaintext); } setContentEncryptionKey(cek) { this._flattened.setContentEncryptionKey(cek); return this; } setInitializationVector(iv) { this._flattened.setInitializationVector(iv); return this; } setProtectedHeader(protectedHeader) { this._flattened.setProtectedHeader(protectedHeader); return this; } setKeyManagementParameters(parameters) { this._flattened.setKeyManagementParameters(parameters); return this; } async encrypt(key, options) { const jwe = await this._flattened.encrypt(key, options); return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.'); } } jose-4.11.4/dist/browser/jwe/flattened/000077500000000000000000000000001437043056600177325ustar00rootroot00000000000000jose-4.11.4/dist/browser/jwe/flattened/decrypt.js000066400000000000000000000133771437043056600217550ustar00rootroot00000000000000import { decode as base64url } from '../../runtime/base64url.js'; import decrypt from '../../runtime/decrypt.js'; import { inflate } from '../../runtime/zlib.js'; import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js'; import isDisjoint from '../../lib/is_disjoint.js'; import isObject from '../../lib/is_object.js'; import decryptKeyManagement from '../../lib/decrypt_key_management.js'; import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; import generateCek from '../../lib/cek.js'; import validateCrit from '../../lib/validate_crit.js'; import validateAlgorithms from '../../lib/validate_algorithms.js'; export async function flattenedDecrypt(jwe, key, options) { var _a; if (!isObject(jwe)) { throw new JWEInvalid('Flattened JWE must be an object'); } if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) { throw new JWEInvalid('JOSE Header missing'); } if (typeof jwe.iv !== 'string') { throw new JWEInvalid('JWE Initialization Vector missing or incorrect type'); } if (typeof jwe.ciphertext !== 'string') { throw new JWEInvalid('JWE Ciphertext missing or incorrect type'); } if (typeof jwe.tag !== 'string') { throw new JWEInvalid('JWE Authentication Tag missing or incorrect type'); } if (jwe.protected !== undefined && typeof jwe.protected !== 'string') { throw new JWEInvalid('JWE Protected Header incorrect type'); } if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') { throw new JWEInvalid('JWE Encrypted Key incorrect type'); } if (jwe.aad !== undefined && typeof jwe.aad !== 'string') { throw new JWEInvalid('JWE AAD incorrect type'); } if (jwe.header !== undefined && !isObject(jwe.header)) { throw new JWEInvalid('JWE Shared Unprotected Header incorrect type'); } if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) { throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type'); } let parsedProt; if (jwe.protected) { try { const protectedHeader = base64url(jwe.protected); parsedProt = JSON.parse(decoder.decode(protectedHeader)); } catch (_b) { throw new JWEInvalid('JWE Protected Header is invalid'); } } if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) { throw new JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint'); } const joseHeader = { ...parsedProt, ...jwe.header, ...jwe.unprotected, }; validateCrit(JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader); if (joseHeader.zip !== undefined) { if (!parsedProt || !parsedProt.zip) { throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); } if (joseHeader.zip !== 'DEF') { throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value'); } } const { alg, enc } = joseHeader; if (typeof alg !== 'string' || !alg) { throw new JWEInvalid('missing JWE Algorithm (alg) in JWE Header'); } if (typeof enc !== 'string' || !enc) { throw new JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header'); } const keyManagementAlgorithms = options && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms); const contentEncryptionAlgorithms = options && validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms); if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) { throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed'); } if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed'); } let encryptedKey; if (jwe.encrypted_key !== undefined) { encryptedKey = base64url(jwe.encrypted_key); } let resolvedKey = false; if (typeof key === 'function') { key = await key(parsedProt, jwe); resolvedKey = true; } let cek; try { cek = await decryptKeyManagement(alg, key, encryptedKey, joseHeader, options); } catch (err) { if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { throw err; } cek = generateCek(enc); } const iv = base64url(jwe.iv); const tag = base64url(jwe.tag); const protectedHeader = encoder.encode((_a = jwe.protected) !== null && _a !== void 0 ? _a : ''); let additionalData; if (jwe.aad !== undefined) { additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(jwe.aad)); } else { additionalData = protectedHeader; } let plaintext = await decrypt(enc, cek, base64url(jwe.ciphertext), iv, tag, additionalData); if (joseHeader.zip === 'DEF') { plaintext = await ((options === null || options === void 0 ? void 0 : options.inflateRaw) || inflate)(plaintext); } const result = { plaintext }; if (jwe.protected !== undefined) { result.protectedHeader = parsedProt; } if (jwe.aad !== undefined) { result.additionalAuthenticatedData = base64url(jwe.aad); } if (jwe.unprotected !== undefined) { result.sharedUnprotectedHeader = jwe.unprotected; } if (jwe.header !== undefined) { result.unprotectedHeader = jwe.header; } if (resolvedKey) { return { ...result, key }; } return result; } jose-4.11.4/dist/browser/jwe/flattened/encrypt.js000066400000000000000000000156341437043056600217650ustar00rootroot00000000000000import { encode as base64url } from '../../runtime/base64url.js'; import encrypt from '../../runtime/encrypt.js'; import { deflate } from '../../runtime/zlib.js'; import generateIv from '../../lib/iv.js'; import encryptKeyManagement from '../../lib/encrypt_key_management.js'; import { JOSENotSupported, JWEInvalid } from '../../util/errors.js'; import isDisjoint from '../../lib/is_disjoint.js'; import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; import validateCrit from '../../lib/validate_crit.js'; export const unprotected = Symbol(); export class FlattenedEncrypt { constructor(plaintext) { if (!(plaintext instanceof Uint8Array)) { throw new TypeError('plaintext must be an instance of Uint8Array'); } this._plaintext = plaintext; } setKeyManagementParameters(parameters) { if (this._keyManagementParameters) { throw new TypeError('setKeyManagementParameters can only be called once'); } this._keyManagementParameters = parameters; return this; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once'); } this._protectedHeader = protectedHeader; return this; } setSharedUnprotectedHeader(sharedUnprotectedHeader) { if (this._sharedUnprotectedHeader) { throw new TypeError('setSharedUnprotectedHeader can only be called once'); } this._sharedUnprotectedHeader = sharedUnprotectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once'); } this._unprotectedHeader = unprotectedHeader; return this; } setAdditionalAuthenticatedData(aad) { this._aad = aad; return this; } setContentEncryptionKey(cek) { if (this._cek) { throw new TypeError('setContentEncryptionKey can only be called once'); } this._cek = cek; return this; } setInitializationVector(iv) { if (this._iv) { throw new TypeError('setInitializationVector can only be called once'); } this._iv = iv; return this; } async encrypt(key, options) { if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { throw new JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()'); } if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) { throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...this._sharedUnprotectedHeader, }; validateCrit(JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader); if (joseHeader.zip !== undefined) { if (!this._protectedHeader || !this._protectedHeader.zip) { throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); } if (joseHeader.zip !== 'DEF') { throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value'); } } const { alg, enc } = joseHeader; if (typeof alg !== 'string' || !alg) { throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); } if (typeof enc !== 'string' || !enc) { throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); } let encryptedKey; if (alg === 'dir') { if (this._cek) { throw new TypeError('setContentEncryptionKey cannot be called when using Direct Encryption'); } } else if (alg === 'ECDH-ES') { if (this._cek) { throw new TypeError('setContentEncryptionKey cannot be called when using Direct Key Agreement'); } } let cek; { let parameters; ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, key, this._cek, this._keyManagementParameters)); if (parameters) { if (options && unprotected in options) { if (!this._unprotectedHeader) { this.setUnprotectedHeader(parameters); } else { this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters }; } } else { if (!this._protectedHeader) { this.setProtectedHeader(parameters); } else { this._protectedHeader = { ...this._protectedHeader, ...parameters }; } } } } this._iv || (this._iv = generateIv(enc)); let additionalData; let protectedHeader; let aadMember; if (this._protectedHeader) { protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))); } else { protectedHeader = encoder.encode(''); } if (this._aad) { aadMember = base64url(this._aad); additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember)); } else { additionalData = protectedHeader; } let ciphertext; let tag; if (joseHeader.zip === 'DEF') { const deflated = await ((options === null || options === void 0 ? void 0 : options.deflateRaw) || deflate)(this._plaintext); ({ ciphertext, tag } = await encrypt(enc, deflated, cek, this._iv, additionalData)); } else { ; ({ ciphertext, tag } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData)); } const jwe = { ciphertext: base64url(ciphertext), iv: base64url(this._iv), tag: base64url(tag), }; if (encryptedKey) { jwe.encrypted_key = base64url(encryptedKey); } if (aadMember) { jwe.aad = aadMember; } if (this._protectedHeader) { jwe.protected = decoder.decode(protectedHeader); } if (this._sharedUnprotectedHeader) { jwe.unprotected = this._sharedUnprotectedHeader; } if (this._unprotectedHeader) { jwe.header = this._unprotectedHeader; } return jwe; } } jose-4.11.4/dist/browser/jwe/general/000077500000000000000000000000001437043056600174015ustar00rootroot00000000000000jose-4.11.4/dist/browser/jwe/general/decrypt.js000066400000000000000000000021521437043056600214110ustar00rootroot00000000000000import { flattenedDecrypt } from '../flattened/decrypt.js'; import { JWEDecryptionFailed, JWEInvalid } from '../../util/errors.js'; import isObject from '../../lib/is_object.js'; export async function generalDecrypt(jwe, key, options) { if (!isObject(jwe)) { throw new JWEInvalid('General JWE must be an object'); } if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) { throw new JWEInvalid('JWE Recipients missing or incorrect type'); } if (!jwe.recipients.length) { throw new JWEInvalid('JWE Recipients has no members'); } for (const recipient of jwe.recipients) { try { return await flattenedDecrypt({ aad: jwe.aad, ciphertext: jwe.ciphertext, encrypted_key: recipient.encrypted_key, header: recipient.header, iv: jwe.iv, protected: jwe.protected, tag: jwe.tag, unprotected: jwe.unprotected, }, key, options); } catch (_a) { } } throw new JWEDecryptionFailed(); } jose-4.11.4/dist/browser/jwe/general/encrypt.js000066400000000000000000000172051437043056600214300ustar00rootroot00000000000000import { FlattenedEncrypt, unprotected } from '../flattened/encrypt.js'; import { JWEInvalid } from '../../util/errors.js'; import generateCek from '../../lib/cek.js'; import isDisjoint from '../../lib/is_disjoint.js'; import encryptKeyManagement from '../../lib/encrypt_key_management.js'; import { encode as base64url } from '../../runtime/base64url.js'; import validateCrit from '../../lib/validate_crit.js'; class IndividualRecipient { constructor(enc, key, options) { this.parent = enc; this.key = key; this.options = options; } setUnprotectedHeader(unprotectedHeader) { if (this.unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once'); } this.unprotectedHeader = unprotectedHeader; return this; } addRecipient(...args) { return this.parent.addRecipient(...args); } encrypt(...args) { return this.parent.encrypt(...args); } done() { return this.parent; } } export class GeneralEncrypt { constructor(plaintext) { this._recipients = []; this._plaintext = plaintext; } addRecipient(key, options) { const recipient = new IndividualRecipient(this, key, { crit: options === null || options === void 0 ? void 0 : options.crit }); this._recipients.push(recipient); return recipient; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once'); } this._protectedHeader = protectedHeader; return this; } setSharedUnprotectedHeader(sharedUnprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError('setSharedUnprotectedHeader can only be called once'); } this._unprotectedHeader = sharedUnprotectedHeader; return this; } setAdditionalAuthenticatedData(aad) { this._aad = aad; return this; } async encrypt(options) { var _a, _b, _c; if (!this._recipients.length) { throw new JWEInvalid('at least one recipient must be added'); } options = { deflateRaw: options === null || options === void 0 ? void 0 : options.deflateRaw }; if (this._recipients.length === 1) { const [recipient] = this._recipients; const flattened = await new FlattenedEncrypt(this._plaintext) .setAdditionalAuthenticatedData(this._aad) .setProtectedHeader(this._protectedHeader) .setSharedUnprotectedHeader(this._unprotectedHeader) .setUnprotectedHeader(recipient.unprotectedHeader) .encrypt(recipient.key, { ...recipient.options, ...options }); let jwe = { ciphertext: flattened.ciphertext, iv: flattened.iv, recipients: [{}], tag: flattened.tag, }; if (flattened.aad) jwe.aad = flattened.aad; if (flattened.protected) jwe.protected = flattened.protected; if (flattened.unprotected) jwe.unprotected = flattened.unprotected; if (flattened.encrypted_key) jwe.recipients[0].encrypted_key = flattened.encrypted_key; if (flattened.header) jwe.recipients[0].header = flattened.header; return jwe; } let enc; for (let i = 0; i < this._recipients.length; i++) { const recipient = this._recipients[i]; if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) { throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...recipient.unprotectedHeader, }; const { alg } = joseHeader; if (typeof alg !== 'string' || !alg) { throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); } if (alg === 'dir' || alg === 'ECDH-ES') { throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); } if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) { throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); } if (!enc) { enc = joseHeader.enc; } else if (enc !== joseHeader.enc) { throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); } validateCrit(JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader); if (joseHeader.zip !== undefined) { if (!this._protectedHeader || !this._protectedHeader.zip) { throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); } } } const cek = generateCek(enc); let jwe = { ciphertext: '', iv: '', recipients: [], tag: '', }; for (let i = 0; i < this._recipients.length; i++) { const recipient = this._recipients[i]; const target = {}; jwe.recipients.push(target); const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...recipient.unprotectedHeader, }; const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined; if (i === 0) { const flattened = await new FlattenedEncrypt(this._plaintext) .setAdditionalAuthenticatedData(this._aad) .setContentEncryptionKey(cek) .setProtectedHeader(this._protectedHeader) .setSharedUnprotectedHeader(this._unprotectedHeader) .setUnprotectedHeader(recipient.unprotectedHeader) .setKeyManagementParameters({ p2c }) .encrypt(recipient.key, { ...recipient.options, ...options, [unprotected]: true, }); jwe.ciphertext = flattened.ciphertext; jwe.iv = flattened.iv; jwe.tag = flattened.tag; if (flattened.aad) jwe.aad = flattened.aad; if (flattened.protected) jwe.protected = flattened.protected; if (flattened.unprotected) jwe.unprotected = flattened.unprotected; target.encrypted_key = flattened.encrypted_key; if (flattened.header) target.header = flattened.header; continue; } const { encryptedKey, parameters } = await encryptKeyManagement(((_a = recipient.unprotectedHeader) === null || _a === void 0 ? void 0 : _a.alg) || ((_b = this._protectedHeader) === null || _b === void 0 ? void 0 : _b.alg) || ((_c = this._unprotectedHeader) === null || _c === void 0 ? void 0 : _c.alg), enc, recipient.key, cek, { p2c }); target.encrypted_key = base64url(encryptedKey); if (recipient.unprotectedHeader || parameters) target.header = { ...recipient.unprotectedHeader, ...parameters }; } return jwe; } } jose-4.11.4/dist/browser/jwk/000077500000000000000000000000001437043056600157725ustar00rootroot00000000000000jose-4.11.4/dist/browser/jwk/embedded.js000066400000000000000000000012561437043056600200650ustar00rootroot00000000000000import { importJWK } from '../key/import.js'; import isObject from '../lib/is_object.js'; import { JWSInvalid } from '../util/errors.js'; export async function EmbeddedJWK(protectedHeader, token) { const joseHeader = { ...protectedHeader, ...token.header, }; if (!isObject(joseHeader.jwk)) { throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); } const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg, true); if (key instanceof Uint8Array || key.type !== 'public') { throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); } return key; } jose-4.11.4/dist/browser/jwk/thumbprint.js000066400000000000000000000045651437043056600205360ustar00rootroot00000000000000import digest from '../runtime/digest.js'; import { encode as base64url } from '../runtime/base64url.js'; import { JOSENotSupported, JWKInvalid } from '../util/errors.js'; import { encoder } from '../lib/buffer_utils.js'; import isObject from '../lib/is_object.js'; const check = (value, description) => { if (typeof value !== 'string' || !value) { throw new JWKInvalid(`${description} missing or invalid`); } }; export async function calculateJwkThumbprint(jwk, digestAlgorithm) { if (!isObject(jwk)) { throw new TypeError('JWK must be an object'); } digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256'); if (digestAlgorithm !== 'sha256' && digestAlgorithm !== 'sha384' && digestAlgorithm !== 'sha512') { throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); } let components; switch (jwk.kty) { case 'EC': check(jwk.crv, '"crv" (Curve) Parameter'); check(jwk.x, '"x" (X Coordinate) Parameter'); check(jwk.y, '"y" (Y Coordinate) Parameter'); components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; break; case 'OKP': check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); check(jwk.x, '"x" (Public Key) Parameter'); components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; break; case 'RSA': check(jwk.e, '"e" (Exponent) Parameter'); check(jwk.n, '"n" (Modulus) Parameter'); components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; break; case 'oct': check(jwk.k, '"k" (Key Value) Parameter'); components = { k: jwk.k, kty: jwk.kty }; break; default: throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); } const data = encoder.encode(JSON.stringify(components)); return base64url(await digest(digestAlgorithm, data)); } export async function calculateJwkThumbprintUri(jwk, digestAlgorithm) { digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256'); const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm); return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; } jose-4.11.4/dist/browser/jwks/000077500000000000000000000000001437043056600161555ustar00rootroot00000000000000jose-4.11.4/dist/browser/jwks/local.js000066400000000000000000000066361437043056600176200ustar00rootroot00000000000000import { importJWK } from '../key/import.js'; import { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js'; import isObject from '../lib/is_object.js'; function getKtyFromAlg(alg) { switch (typeof alg === 'string' && alg.slice(0, 2)) { case 'RS': case 'PS': return 'RSA'; case 'ES': return 'EC'; case 'Ed': return 'OKP'; default: throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); } } export function isJWKSLike(jwks) { return (jwks && typeof jwks === 'object' && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike)); } function isJWKLike(key) { return isObject(key); } function clone(obj) { if (typeof structuredClone === 'function') { return structuredClone(obj); } return JSON.parse(JSON.stringify(obj)); } export class LocalJWKSet { constructor(jwks) { this._cached = new WeakMap(); if (!isJWKSLike(jwks)) { throw new JWKSInvalid('JSON Web Key Set malformed'); } this._jwks = clone(jwks); } async getKey(protectedHeader, token) { const { alg, kid } = { ...protectedHeader, ...token.header }; const kty = getKtyFromAlg(alg); const candidates = this._jwks.keys.filter((jwk) => { let candidate = kty === jwk.kty; if (candidate && typeof kid === 'string') { candidate = kid === jwk.kid; } if (candidate && typeof jwk.alg === 'string') { candidate = alg === jwk.alg; } if (candidate && typeof jwk.use === 'string') { candidate = jwk.use === 'sig'; } if (candidate && Array.isArray(jwk.key_ops)) { candidate = jwk.key_ops.includes('verify'); } if (candidate && alg === 'EdDSA') { candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448'; } if (candidate) { switch (alg) { case 'ES256': candidate = jwk.crv === 'P-256'; break; case 'ES256K': candidate = jwk.crv === 'secp256k1'; break; case 'ES384': candidate = jwk.crv === 'P-384'; break; case 'ES512': candidate = jwk.crv === 'P-521'; break; } } return candidate; }); const { 0: jwk, length } = candidates; if (length === 0) { throw new JWKSNoMatchingKey(); } else if (length !== 1) { throw new JWKSMultipleMatchingKeys(); } const cached = this._cached.get(jwk) || this._cached.set(jwk, {}).get(jwk); if (cached[alg] === undefined) { const keyObject = await importJWK({ ...jwk, ext: true }, alg); if (keyObject instanceof Uint8Array || keyObject.type !== 'public') { throw new JWKSInvalid('JSON Web Key Set members must be public keys'); } cached[alg] = keyObject; } return cached[alg]; } } export function createLocalJWKSet(jwks) { return LocalJWKSet.prototype.getKey.bind(new LocalJWKSet(jwks)); } jose-4.11.4/dist/browser/jwks/remote.js000066400000000000000000000065371437043056600200210ustar00rootroot00000000000000import fetchJwks from '../runtime/fetch_jwks.js'; import { isCloudflareWorkers } from '../runtime/env.js'; import { JWKSInvalid, JWKSNoMatchingKey } from '../util/errors.js'; import { isJWKSLike, LocalJWKSet } from './local.js'; class RemoteJWKSet extends LocalJWKSet { constructor(url, options) { super({ keys: [] }); this._jwks = undefined; if (!(url instanceof URL)) { throw new TypeError('url must be an instance of URL'); } this._url = new URL(url.href); this._options = { agent: options === null || options === void 0 ? void 0 : options.agent, headers: options === null || options === void 0 ? void 0 : options.headers }; this._timeoutDuration = typeof (options === null || options === void 0 ? void 0 : options.timeoutDuration) === 'number' ? options === null || options === void 0 ? void 0 : options.timeoutDuration : 5000; this._cooldownDuration = typeof (options === null || options === void 0 ? void 0 : options.cooldownDuration) === 'number' ? options === null || options === void 0 ? void 0 : options.cooldownDuration : 30000; this._cacheMaxAge = typeof (options === null || options === void 0 ? void 0 : options.cacheMaxAge) === 'number' ? options === null || options === void 0 ? void 0 : options.cacheMaxAge : 600000; } coolingDown() { return typeof this._jwksTimestamp === 'number' ? Date.now() < this._jwksTimestamp + this._cooldownDuration : false; } fresh() { return typeof this._jwksTimestamp === 'number' ? Date.now() < this._jwksTimestamp + this._cacheMaxAge : false; } async getKey(protectedHeader, token) { if (!this._jwks || !this.fresh()) { await this.reload(); } try { return await super.getKey(protectedHeader, token); } catch (err) { if (err instanceof JWKSNoMatchingKey) { if (this.coolingDown() === false) { await this.reload(); return super.getKey(protectedHeader, token); } } throw err; } } async reload() { if (this._pendingFetch && isCloudflareWorkers()) { return new Promise((resolve) => { const isDone = () => { if (this._pendingFetch === undefined) { resolve(); } else { setTimeout(isDone, 5); } }; isDone(); }); } if (!this._pendingFetch) { this._pendingFetch = fetchJwks(this._url, this._timeoutDuration, this._options) .then((json) => { if (!isJWKSLike(json)) { throw new JWKSInvalid('JSON Web Key Set malformed'); } this._jwks = { keys: json.keys }; this._jwksTimestamp = Date.now(); this._pendingFetch = undefined; }) .catch((err) => { this._pendingFetch = undefined; throw err; }); } await this._pendingFetch; } } export function createRemoteJWKSet(url, options) { return RemoteJWKSet.prototype.getKey.bind(new RemoteJWKSet(url, options)); } jose-4.11.4/dist/browser/jws/000077500000000000000000000000001437043056600160025ustar00rootroot00000000000000jose-4.11.4/dist/browser/jws/compact/000077500000000000000000000000001437043056600174305ustar00rootroot00000000000000jose-4.11.4/dist/browser/jws/compact/sign.js000066400000000000000000000011431437043056600207250ustar00rootroot00000000000000import { FlattenedSign } from '../flattened/sign.js'; export class CompactSign { constructor(payload) { this._flattened = new FlattenedSign(payload); } setProtectedHeader(protectedHeader) { this._flattened.setProtectedHeader(protectedHeader); return this; } async sign(key, options) { const jws = await this._flattened.sign(key, options); if (jws.payload === undefined) { throw new TypeError('use the flattened module for creating JWS with b64: false'); } return `${jws.protected}.${jws.payload}.${jws.signature}`; } } jose-4.11.4/dist/browser/jws/compact/verify.js000066400000000000000000000016021437043056600212710ustar00rootroot00000000000000import { flattenedVerify } from '../flattened/verify.js'; import { JWSInvalid } from '../../util/errors.js'; import { decoder } from '../../lib/buffer_utils.js'; export async function compactVerify(jws, key, options) { if (jws instanceof Uint8Array) { jws = decoder.decode(jws); } if (typeof jws !== 'string') { throw new JWSInvalid('Compact JWS must be a string or Uint8Array'); } const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.'); if (length !== 3) { throw new JWSInvalid('Invalid Compact JWS'); } const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options); const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; if (typeof key === 'function') { return { ...result, key: verified.key }; } return result; } jose-4.11.4/dist/browser/jws/flattened/000077500000000000000000000000001437043056600177505ustar00rootroot00000000000000jose-4.11.4/dist/browser/jws/flattened/sign.js000066400000000000000000000063101437043056600212460ustar00rootroot00000000000000import { encode as base64url } from '../../runtime/base64url.js'; import sign from '../../runtime/sign.js'; import isDisjoint from '../../lib/is_disjoint.js'; import { JWSInvalid } from '../../util/errors.js'; import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; import checkKeyType from '../../lib/check_key_type.js'; import validateCrit from '../../lib/validate_crit.js'; export class FlattenedSign { constructor(payload) { if (!(payload instanceof Uint8Array)) { throw new TypeError('payload must be an instance of Uint8Array'); } this._payload = payload; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once'); } this._protectedHeader = protectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once'); } this._unprotectedHeader = unprotectedHeader; return this; } async sign(key, options) { if (!this._protectedHeader && !this._unprotectedHeader) { throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()'); } if (!isDisjoint(this._protectedHeader, this._unprotectedHeader)) { throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, }; const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader); let b64 = true; if (extensions.has('b64')) { b64 = this._protectedHeader.b64; if (typeof b64 !== 'boolean') { throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); } } const { alg } = joseHeader; if (typeof alg !== 'string' || !alg) { throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); } checkKeyType(alg, key, 'sign'); let payload = this._payload; if (b64) { payload = encoder.encode(base64url(payload)); } let protectedHeader; if (this._protectedHeader) { protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))); } else { protectedHeader = encoder.encode(''); } const data = concat(protectedHeader, encoder.encode('.'), payload); const signature = await sign(alg, key, data); const jws = { signature: base64url(signature), payload: '', }; if (b64) { jws.payload = decoder.decode(payload); } if (this._unprotectedHeader) { jws.header = this._unprotectedHeader; } if (this._protectedHeader) { jws.protected = decoder.decode(protectedHeader); } return jws; } } jose-4.11.4/dist/browser/jws/flattened/verify.js000066400000000000000000000101361437043056600216130ustar00rootroot00000000000000import { decode as base64url } from '../../runtime/base64url.js'; import verify from '../../runtime/verify.js'; import { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js'; import { concat, encoder, decoder } from '../../lib/buffer_utils.js'; import isDisjoint from '../../lib/is_disjoint.js'; import isObject from '../../lib/is_object.js'; import checkKeyType from '../../lib/check_key_type.js'; import validateCrit from '../../lib/validate_crit.js'; import validateAlgorithms from '../../lib/validate_algorithms.js'; export async function flattenedVerify(jws, key, options) { var _a; if (!isObject(jws)) { throw new JWSInvalid('Flattened JWS must be an object'); } if (jws.protected === undefined && jws.header === undefined) { throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); } if (jws.protected !== undefined && typeof jws.protected !== 'string') { throw new JWSInvalid('JWS Protected Header incorrect type'); } if (jws.payload === undefined) { throw new JWSInvalid('JWS Payload missing'); } if (typeof jws.signature !== 'string') { throw new JWSInvalid('JWS Signature missing or incorrect type'); } if (jws.header !== undefined && !isObject(jws.header)) { throw new JWSInvalid('JWS Unprotected Header incorrect type'); } let parsedProt = {}; if (jws.protected) { try { const protectedHeader = base64url(jws.protected); parsedProt = JSON.parse(decoder.decode(protectedHeader)); } catch (_b) { throw new JWSInvalid('JWS Protected Header is invalid'); } } if (!isDisjoint(parsedProt, jws.header)) { throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); } const joseHeader = { ...parsedProt, ...jws.header, }; const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader); let b64 = true; if (extensions.has('b64')) { b64 = parsedProt.b64; if (typeof b64 !== 'boolean') { throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); } } const { alg } = joseHeader; if (typeof alg !== 'string' || !alg) { throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); } const algorithms = options && validateAlgorithms('algorithms', options.algorithms); if (algorithms && !algorithms.has(alg)) { throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed'); } if (b64) { if (typeof jws.payload !== 'string') { throw new JWSInvalid('JWS Payload must be a string'); } } else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) { throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance'); } let resolvedKey = false; if (typeof key === 'function') { key = await key(parsedProt, jws); resolvedKey = true; } checkKeyType(alg, key, 'verify'); const data = concat(encoder.encode((_a = jws.protected) !== null && _a !== void 0 ? _a : ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload); const signature = base64url(jws.signature); const verified = await verify(alg, key, signature, data); if (!verified) { throw new JWSSignatureVerificationFailed(); } let payload; if (b64) { payload = base64url(jws.payload); } else if (typeof jws.payload === 'string') { payload = encoder.encode(jws.payload); } else { payload = jws.payload; } const result = { payload }; if (jws.protected !== undefined) { result.protectedHeader = parsedProt; } if (jws.header !== undefined) { result.unprotectedHeader = jws.header; } if (resolvedKey) { return { ...result, key }; } return result; } jose-4.11.4/dist/browser/jws/general/000077500000000000000000000000001437043056600174175ustar00rootroot00000000000000jose-4.11.4/dist/browser/jws/general/sign.js000066400000000000000000000042541437043056600207220ustar00rootroot00000000000000import { FlattenedSign } from '../flattened/sign.js'; import { JWSInvalid } from '../../util/errors.js'; class IndividualSignature { constructor(sig, key, options) { this.parent = sig; this.key = key; this.options = options; } setProtectedHeader(protectedHeader) { if (this.protectedHeader) { throw new TypeError('setProtectedHeader can only be called once'); } this.protectedHeader = protectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this.unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once'); } this.unprotectedHeader = unprotectedHeader; return this; } addSignature(...args) { return this.parent.addSignature(...args); } sign(...args) { return this.parent.sign(...args); } done() { return this.parent; } } export class GeneralSign { constructor(payload) { this._signatures = []; this._payload = payload; } addSignature(key, options) { const signature = new IndividualSignature(this, key, options); this._signatures.push(signature); return signature; } async sign() { if (!this._signatures.length) { throw new JWSInvalid('at least one signature must be added'); } const jws = { signatures: [], payload: '', }; for (let i = 0; i < this._signatures.length; i++) { const signature = this._signatures[i]; const flattened = new FlattenedSign(this._payload); flattened.setProtectedHeader(signature.protectedHeader); flattened.setUnprotectedHeader(signature.unprotectedHeader); const { payload, ...rest } = await flattened.sign(signature.key, signature.options); if (i === 0) { jws.payload = payload; } else if (jws.payload !== payload) { throw new JWSInvalid('inconsistent use of JWS Unencoded Payload Option (RFC7797)'); } jws.signatures.push(rest); } return jws; } } jose-4.11.4/dist/browser/jws/general/verify.js000066400000000000000000000016071437043056600212650ustar00rootroot00000000000000import { flattenedVerify } from '../flattened/verify.js'; import { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js'; import isObject from '../../lib/is_object.js'; export async function generalVerify(jws, key, options) { if (!isObject(jws)) { throw new JWSInvalid('General JWS must be an object'); } if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) { throw new JWSInvalid('JWS Signatures missing or incorrect type'); } for (const signature of jws.signatures) { try { return await flattenedVerify({ header: signature.header, payload: jws.payload, protected: signature.protected, signature: signature.signature, }, key, options); } catch (_a) { } } throw new JWSSignatureVerificationFailed(); } jose-4.11.4/dist/browser/jwt/000077500000000000000000000000001437043056600160035ustar00rootroot00000000000000jose-4.11.4/dist/browser/jwt/decrypt.js000066400000000000000000000023301437043056600200110ustar00rootroot00000000000000import { compactDecrypt } from '../jwe/compact/decrypt.js'; import jwtPayload from '../lib/jwt_claims_set.js'; import { JWTClaimValidationFailed } from '../util/errors.js'; export async function jwtDecrypt(jwt, key, options) { const decrypted = await compactDecrypt(jwt, key, options); const payload = jwtPayload(decrypted.protectedHeader, decrypted.plaintext, options); const { protectedHeader } = decrypted; if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) { throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', 'iss', 'mismatch'); } if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) { throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', 'sub', 'mismatch'); } if (protectedHeader.aud !== undefined && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', 'aud', 'mismatch'); } const result = { payload, protectedHeader }; if (typeof key === 'function') { return { ...result, key: decrypted.key }; } return result; } jose-4.11.4/dist/browser/jwt/encrypt.js000066400000000000000000000045431437043056600200330ustar00rootroot00000000000000import { CompactEncrypt } from '../jwe/compact/encrypt.js'; import { encoder } from '../lib/buffer_utils.js'; import { ProduceJWT } from './produce.js'; export class EncryptJWT extends ProduceJWT { setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once'); } this._protectedHeader = protectedHeader; return this; } setKeyManagementParameters(parameters) { if (this._keyManagementParameters) { throw new TypeError('setKeyManagementParameters can only be called once'); } this._keyManagementParameters = parameters; return this; } setContentEncryptionKey(cek) { if (this._cek) { throw new TypeError('setContentEncryptionKey can only be called once'); } this._cek = cek; return this; } setInitializationVector(iv) { if (this._iv) { throw new TypeError('setInitializationVector can only be called once'); } this._iv = iv; return this; } replicateIssuerAsHeader() { this._replicateIssuerAsHeader = true; return this; } replicateSubjectAsHeader() { this._replicateSubjectAsHeader = true; return this; } replicateAudienceAsHeader() { this._replicateAudienceAsHeader = true; return this; } async encrypt(key, options) { const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload))); if (this._replicateIssuerAsHeader) { this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss }; } if (this._replicateSubjectAsHeader) { this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub }; } if (this._replicateAudienceAsHeader) { this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud }; } enc.setProtectedHeader(this._protectedHeader); if (this._iv) { enc.setInitializationVector(this._iv); } if (this._cek) { enc.setContentEncryptionKey(this._cek); } if (this._keyManagementParameters) { enc.setKeyManagementParameters(this._keyManagementParameters); } return enc.encrypt(key, options); } } jose-4.11.4/dist/browser/jwt/produce.js000066400000000000000000000030751437043056600200070ustar00rootroot00000000000000import epoch from '../lib/epoch.js'; import isObject from '../lib/is_object.js'; import secs from '../lib/secs.js'; export class ProduceJWT { constructor(payload) { if (!isObject(payload)) { throw new TypeError('JWT Claims Set MUST be an object'); } this._payload = payload; } setIssuer(issuer) { this._payload = { ...this._payload, iss: issuer }; return this; } setSubject(subject) { this._payload = { ...this._payload, sub: subject }; return this; } setAudience(audience) { this._payload = { ...this._payload, aud: audience }; return this; } setJti(jwtId) { this._payload = { ...this._payload, jti: jwtId }; return this; } setNotBefore(input) { if (typeof input === 'number') { this._payload = { ...this._payload, nbf: input }; } else { this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) }; } return this; } setExpirationTime(input) { if (typeof input === 'number') { this._payload = { ...this._payload, exp: input }; } else { this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) }; } return this; } setIssuedAt(input) { if (typeof input === 'undefined') { this._payload = { ...this._payload, iat: epoch(new Date()) }; } else { this._payload = { ...this._payload, iat: input }; } return this; } } jose-4.11.4/dist/browser/jwt/sign.js000066400000000000000000000015641437043056600173070ustar00rootroot00000000000000import { CompactSign } from '../jws/compact/sign.js'; import { JWTInvalid } from '../util/errors.js'; import { encoder } from '../lib/buffer_utils.js'; import { ProduceJWT } from './produce.js'; export class SignJWT extends ProduceJWT { setProtectedHeader(protectedHeader) { this._protectedHeader = protectedHeader; return this; } async sign(key, options) { var _a; const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload))); sig.setProtectedHeader(this._protectedHeader); if (Array.isArray((_a = this._protectedHeader) === null || _a === void 0 ? void 0 : _a.crit) && this._protectedHeader.crit.includes('b64') && this._protectedHeader.b64 === false) { throw new JWTInvalid('JWTs MUST NOT use unencoded payload'); } return sig.sign(key, options); } } jose-4.11.4/dist/browser/jwt/unsecured.js000066400000000000000000000024041437043056600203360ustar00rootroot00000000000000import * as base64url from '../runtime/base64url.js'; import { decoder } from '../lib/buffer_utils.js'; import { JWTInvalid } from '../util/errors.js'; import jwtPayload from '../lib/jwt_claims_set.js'; import { ProduceJWT } from './produce.js'; export class UnsecuredJWT extends ProduceJWT { encode() { const header = base64url.encode(JSON.stringify({ alg: 'none' })); const payload = base64url.encode(JSON.stringify(this._payload)); return `${header}.${payload}.`; } static decode(jwt, options) { if (typeof jwt !== 'string') { throw new JWTInvalid('Unsecured JWT must be a string'); } const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.'); if (length !== 3 || signature !== '') { throw new JWTInvalid('Invalid Unsecured JWT'); } let header; try { header = JSON.parse(decoder.decode(base64url.decode(encodedHeader))); if (header.alg !== 'none') throw new Error(); } catch (_a) { throw new JWTInvalid('Invalid Unsecured JWT'); } const payload = jwtPayload(header, base64url.decode(encodedPayload), options); return { payload, header }; } } jose-4.11.4/dist/browser/jwt/verify.js000066400000000000000000000014131437043056600176440ustar00rootroot00000000000000import { compactVerify } from '../jws/compact/verify.js'; import jwtPayload from '../lib/jwt_claims_set.js'; import { JWTInvalid } from '../util/errors.js'; export async function jwtVerify(jwt, key, options) { var _a; const verified = await compactVerify(jwt, key, options); if (((_a = verified.protectedHeader.crit) === null || _a === void 0 ? void 0 : _a.includes('b64')) && verified.protectedHeader.b64 === false) { throw new JWTInvalid('JWTs MUST NOT use unencoded payload'); } const payload = jwtPayload(verified.protectedHeader, verified.payload, options); const result = { payload, protectedHeader: verified.protectedHeader }; if (typeof key === 'function') { return { ...result, key: verified.key }; } return result; } jose-4.11.4/dist/browser/key/000077500000000000000000000000001437043056600157675ustar00rootroot00000000000000jose-4.11.4/dist/browser/key/export.js000066400000000000000000000006021437043056600176440ustar00rootroot00000000000000import { toSPKI as exportPublic } from '../runtime/asn1.js'; import { toPKCS8 as exportPrivate } from '../runtime/asn1.js'; import keyToJWK from '../runtime/key_to_jwk.js'; export async function exportSPKI(key) { return exportPublic(key); } export async function exportPKCS8(key) { return exportPrivate(key); } export async function exportJWK(key) { return keyToJWK(key); } jose-4.11.4/dist/browser/key/generate_key_pair.js000066400000000000000000000002411437043056600217770ustar00rootroot00000000000000import { generateKeyPair as generate } from '../runtime/generate.js'; export async function generateKeyPair(alg, options) { return generate(alg, options); } jose-4.11.4/dist/browser/key/generate_secret.js000066400000000000000000000002371437043056600214660ustar00rootroot00000000000000import { generateSecret as generate } from '../runtime/generate.js'; export async function generateSecret(alg, options) { return generate(alg, options); } jose-4.11.4/dist/browser/key/import.js000066400000000000000000000111351437043056600176400ustar00rootroot00000000000000import { decode as decodeBase64URL, encodeBase64, decodeBase64 } from '../runtime/base64url.js'; import { fromSPKI as importPublic } from '../runtime/asn1.js'; import { fromPKCS8 as importPrivate } from '../runtime/asn1.js'; import asKeyObject from '../runtime/jwk_to_key.js'; import { JOSENotSupported } from '../util/errors.js'; import formatPEM from '../lib/format_pem.js'; import isObject from '../lib/is_object.js'; function getElement(seq) { let result = []; let next = 0; while (next < seq.length) { let nextPart = parseElement(seq.subarray(next)); result.push(nextPart); next += nextPart.byteLength; } return result; } function parseElement(bytes) { let position = 0; let tag = bytes[0] & 0x1f; position++; if (tag === 0x1f) { tag = 0; while (bytes[position] >= 0x80) { tag = tag * 128 + bytes[position] - 0x80; position++; } tag = tag * 128 + bytes[position] - 0x80; position++; } let length = 0; if (bytes[position] < 0x80) { length = bytes[position]; position++; } else if (length === 0x80) { length = 0; while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) { if (length > bytes.byteLength) { throw new TypeError('invalid indefinite form length'); } length++; } const byteLength = position + length + 2; return { byteLength, contents: bytes.subarray(position, position + length), raw: bytes.subarray(0, byteLength), }; } else { let numberOfDigits = bytes[position] & 0x7f; position++; length = 0; for (let i = 0; i < numberOfDigits; i++) { length = length * 256 + bytes[position]; position++; } } const byteLength = position + length; return { byteLength, contents: bytes.subarray(position, byteLength), raw: bytes.subarray(0, byteLength), }; } function spkiFromX509(buf) { const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents); return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw); } function getSPKI(x509) { const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, ''); const raw = decodeBase64(pem); return formatPEM(spkiFromX509(raw), 'PUBLIC KEY'); } export async function importSPKI(spki, alg, options) { if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) { throw new TypeError('"spki" must be SPKI formatted string'); } return importPublic(spki, alg, options); } export async function importX509(x509, alg, options) { if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) { throw new TypeError('"x509" must be X.509 formatted string'); } let spki; try { spki = getSPKI(x509); } catch (cause) { throw new TypeError('failed to parse the X.509 certificate', { cause }); } return importPublic(spki, alg, options); } export async function importPKCS8(pkcs8, alg, options) { if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) { throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); } return importPrivate(pkcs8, alg, options); } export async function importJWK(jwk, alg, octAsKeyObject) { var _a; if (!isObject(jwk)) { throw new TypeError('JWK must be an object'); } alg || (alg = jwk.alg); if (typeof alg !== 'string' || !alg) { throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); } switch (jwk.kty) { case 'oct': if (typeof jwk.k !== 'string' || !jwk.k) { throw new TypeError('missing "k" (Key Value) Parameter value'); } octAsKeyObject !== null && octAsKeyObject !== void 0 ? octAsKeyObject : (octAsKeyObject = jwk.ext !== true); if (octAsKeyObject) { return asKeyObject({ ...jwk, alg, ext: (_a = jwk.ext) !== null && _a !== void 0 ? _a : false }); } return decodeBase64URL(jwk.k); case 'RSA': if (jwk.oth !== undefined) { throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); } case 'EC': case 'OKP': return asKeyObject({ ...jwk, alg }); default: throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); } } jose-4.11.4/dist/browser/lib/000077500000000000000000000000001437043056600157455ustar00rootroot00000000000000jose-4.11.4/dist/browser/lib/aesgcmkw.js000066400000000000000000000012601437043056600201030ustar00rootroot00000000000000import encrypt from '../runtime/encrypt.js'; import decrypt from '../runtime/decrypt.js'; import generateIv from './iv.js'; import { encode as base64url } from '../runtime/base64url.js'; export async function wrap(alg, key, cek, iv) { const jweAlgorithm = alg.slice(0, 7); iv || (iv = generateIv(jweAlgorithm)); const { ciphertext: encryptedKey, tag } = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array(0)); return { encryptedKey, iv: base64url(iv), tag: base64url(tag) }; } export async function unwrap(alg, key, encryptedKey, iv, tag) { const jweAlgorithm = alg.slice(0, 7); return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0)); } jose-4.11.4/dist/browser/lib/buffer_utils.js000066400000000000000000000033161437043056600207770ustar00rootroot00000000000000import digest from '../runtime/digest.js'; export const encoder = new TextEncoder(); export const decoder = new TextDecoder(); const MAX_INT32 = 2 ** 32; export function concat(...buffers) { const size = buffers.reduce((acc, { length }) => acc + length, 0); const buf = new Uint8Array(size); let i = 0; buffers.forEach((buffer) => { buf.set(buffer, i); i += buffer.length; }); return buf; } export function p2s(alg, p2sInput) { return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput); } function writeUInt32BE(buf, value, offset) { if (value < 0 || value >= MAX_INT32) { throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); } buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset); } export function uint64be(value) { const high = Math.floor(value / MAX_INT32); const low = value % MAX_INT32; const buf = new Uint8Array(8); writeUInt32BE(buf, high, 0); writeUInt32BE(buf, low, 4); return buf; } export function uint32be(value) { const buf = new Uint8Array(4); writeUInt32BE(buf, value); return buf; } export function lengthAndInput(input) { return concat(uint32be(input.length), input); } export async function concatKdf(secret, bits, value) { const iterations = Math.ceil((bits >> 3) / 32); const res = new Uint8Array(iterations * 32); for (let iter = 0; iter < iterations; iter++) { const buf = new Uint8Array(4 + secret.length + value.length); buf.set(uint32be(iter + 1)); buf.set(secret, 4); buf.set(value, 4 + secret.length); res.set(await digest('sha256', buf), iter * 32); } return res.slice(0, bits >> 3); } jose-4.11.4/dist/browser/lib/cek.js000066400000000000000000000011321437043056600170420ustar00rootroot00000000000000import { JOSENotSupported } from '../util/errors.js'; import random from '../runtime/random.js'; export function bitLength(alg) { switch (alg) { case 'A128GCM': return 128; case 'A192GCM': return 192; case 'A256GCM': case 'A128CBC-HS256': return 256; case 'A192CBC-HS384': return 384; case 'A256CBC-HS512': return 512; default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); } } export default (alg) => random(new Uint8Array(bitLength(alg) >> 3)); jose-4.11.4/dist/browser/lib/check_iv_length.js000066400000000000000000000004241437043056600214170ustar00rootroot00000000000000import { JWEInvalid } from '../util/errors.js'; import { bitLength } from './iv.js'; const checkIvLength = (enc, iv) => { if (iv.length << 3 !== bitLength(enc)) { throw new JWEInvalid('Invalid Initialization Vector length'); } }; export default checkIvLength; jose-4.11.4/dist/browser/lib/check_key_type.js000066400000000000000000000036151437043056600212760ustar00rootroot00000000000000import { withAlg as invalidKeyInput } from './invalid_key_input.js'; import isKeyLike, { types } from '../runtime/is_key_like.js'; const symmetricTypeCheck = (alg, key) => { if (key instanceof Uint8Array) return; if (!isKeyLike(key)) { throw new TypeError(invalidKeyInput(alg, key, ...types, 'Uint8Array')); } if (key.type !== 'secret') { throw new TypeError(`${types.join(' or ')} instances for symmetric algorithms must be of type "secret"`); } }; const asymmetricTypeCheck = (alg, key, usage) => { if (!isKeyLike(key)) { throw new TypeError(invalidKeyInput(alg, key, ...types)); } if (key.type === 'secret') { throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithms must not be of type "secret"`); } if (usage === 'sign' && key.type === 'public') { throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm signing must be of type "private"`); } if (usage === 'decrypt' && key.type === 'public') { throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm decryption must be of type "private"`); } if (key.algorithm && usage === 'verify' && key.type === 'private') { throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm verifying must be of type "public"`); } if (key.algorithm && usage === 'encrypt' && key.type === 'private') { throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm encryption must be of type "public"`); } }; const checkKeyType = (alg, key, usage) => { const symmetric = alg.startsWith('HS') || alg === 'dir' || alg.startsWith('PBES2') || /^A\d{3}(?:GCM)?KW$/.test(alg); if (symmetric) { symmetricTypeCheck(alg, key); } else { asymmetricTypeCheck(alg, key, usage); } }; export default checkKeyType; jose-4.11.4/dist/browser/lib/check_p2s.js000066400000000000000000000003451437043056600201460ustar00rootroot00000000000000import { JWEInvalid } from '../util/errors.js'; export default function checkP2s(p2s) { if (!(p2s instanceof Uint8Array) || p2s.length < 8) { throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets'); } } jose-4.11.4/dist/browser/lib/crypto_key.js000066400000000000000000000126551437043056600205040ustar00rootroot00000000000000import { isCloudflareWorkers } from '../runtime/env.js'; function unusable(name, prop = 'algorithm.name') { return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); } function isAlgorithm(algorithm, name) { return algorithm.name === name; } function getHashLength(hash) { return parseInt(hash.name.slice(4), 10); } function getNamedCurve(alg) { switch (alg) { case 'ES256': return 'P-256'; case 'ES384': return 'P-384'; case 'ES512': return 'P-521'; default: throw new Error('unreachable'); } } function checkUsage(key, usages) { if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { let msg = 'CryptoKey does not support this operation, its usages must include '; if (usages.length > 2) { const last = usages.pop(); msg += `one of ${usages.join(', ')}, or ${last}.`; } else if (usages.length === 2) { msg += `one of ${usages[0]} or ${usages[1]}.`; } else { msg += `${usages[0]}.`; } throw new TypeError(msg); } } export function checkSigCryptoKey(key, alg, ...usages) { switch (alg) { case 'HS256': case 'HS384': case 'HS512': { if (!isAlgorithm(key.algorithm, 'HMAC')) throw unusable('HMAC'); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash'); break; } case 'RS256': case 'RS384': case 'RS512': { if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5')) throw unusable('RSASSA-PKCS1-v1_5'); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash'); break; } case 'PS256': case 'PS384': case 'PS512': { if (!isAlgorithm(key.algorithm, 'RSA-PSS')) throw unusable('RSA-PSS'); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash'); break; } case 'EdDSA': { if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') { if (isCloudflareWorkers()) { if (isAlgorithm(key.algorithm, 'NODE-ED25519')) break; throw unusable('Ed25519, Ed448, or NODE-ED25519'); } throw unusable('Ed25519 or Ed448'); } break; } case 'ES256': case 'ES384': case 'ES512': { if (!isAlgorithm(key.algorithm, 'ECDSA')) throw unusable('ECDSA'); const expected = getNamedCurve(alg); const actual = key.algorithm.namedCurve; if (actual !== expected) throw unusable(expected, 'algorithm.namedCurve'); break; } default: throw new TypeError('CryptoKey does not support this operation'); } checkUsage(key, usages); } export function checkEncCryptoKey(key, alg, ...usages) { switch (alg) { case 'A128GCM': case 'A192GCM': case 'A256GCM': { if (!isAlgorithm(key.algorithm, 'AES-GCM')) throw unusable('AES-GCM'); const expected = parseInt(alg.slice(1, 4), 10); const actual = key.algorithm.length; if (actual !== expected) throw unusable(expected, 'algorithm.length'); break; } case 'A128KW': case 'A192KW': case 'A256KW': { if (!isAlgorithm(key.algorithm, 'AES-KW')) throw unusable('AES-KW'); const expected = parseInt(alg.slice(1, 4), 10); const actual = key.algorithm.length; if (actual !== expected) throw unusable(expected, 'algorithm.length'); break; } case 'ECDH': { switch (key.algorithm.name) { case 'ECDH': case 'X25519': case 'X448': break; default: throw unusable('ECDH, X25519, or X448'); } break; } case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': if (!isAlgorithm(key.algorithm, 'PBKDF2')) throw unusable('PBKDF2'); break; case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': { if (!isAlgorithm(key.algorithm, 'RSA-OAEP')) throw unusable('RSA-OAEP'); const expected = parseInt(alg.slice(9), 10) || 1; const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash'); break; } default: throw new TypeError('CryptoKey does not support this operation'); } checkUsage(key, usages); } jose-4.11.4/dist/browser/lib/decrypt_key_management.js000066400000000000000000000113721437043056600230250ustar00rootroot00000000000000import { unwrap as aesKw } from '../runtime/aeskw.js'; import * as ECDH from '../runtime/ecdhes.js'; import { decrypt as pbes2Kw } from '../runtime/pbes2kw.js'; import { decrypt as rsaEs } from '../runtime/rsaes.js'; import { decode as base64url } from '../runtime/base64url.js'; import { JOSENotSupported, JWEInvalid } from '../util/errors.js'; import { bitLength as cekLength } from '../lib/cek.js'; import { importJWK } from '../key/import.js'; import checkKeyType from './check_key_type.js'; import isObject from './is_object.js'; import { unwrap as aesGcmKw } from './aesgcmkw.js'; async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { checkKeyType(alg, key, 'decrypt'); switch (alg) { case 'dir': { if (encryptedKey !== undefined) throw new JWEInvalid('Encountered unexpected JWE Encrypted Key'); return key; } case 'ECDH-ES': if (encryptedKey !== undefined) throw new JWEInvalid('Encountered unexpected JWE Encrypted Key'); case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': { if (!isObject(joseHeader.epk)) throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); if (!ECDH.ecdhAllowed(key)) throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); const epk = await importJWK(joseHeader.epk, alg); let partyUInfo; let partyVInfo; if (joseHeader.apu !== undefined) { if (typeof joseHeader.apu !== 'string') throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); partyUInfo = base64url(joseHeader.apu); } if (joseHeader.apv !== undefined) { if (typeof joseHeader.apv !== 'string') throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); partyVInfo = base64url(joseHeader.apv); } const sharedSecret = await ECDH.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); if (alg === 'ECDH-ES') return sharedSecret; if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing'); return aesKw(alg.slice(-6), sharedSecret, encryptedKey); } case 'RSA1_5': case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': { if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing'); return rsaEs(alg, key, encryptedKey); } case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': { if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing'); if (typeof joseHeader.p2c !== 'number') throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); const p2cLimit = (options === null || options === void 0 ? void 0 : options.maxPBES2Count) || 10000; if (joseHeader.p2c > p2cLimit) throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); if (typeof joseHeader.p2s !== 'string') throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); return pbes2Kw(alg, key, encryptedKey, joseHeader.p2c, base64url(joseHeader.p2s)); } case 'A128KW': case 'A192KW': case 'A256KW': { if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing'); return aesKw(alg, key, encryptedKey); } case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': { if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing'); if (typeof joseHeader.iv !== 'string') throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); if (typeof joseHeader.tag !== 'string') throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); const iv = base64url(joseHeader.iv); const tag = base64url(joseHeader.tag); return aesGcmKw(alg, key, encryptedKey, iv, tag); } default: { throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); } } } export default decryptKeyManagement; jose-4.11.4/dist/browser/lib/encrypt_key_management.js000066400000000000000000000066031437043056600230400ustar00rootroot00000000000000import { wrap as aesKw } from '../runtime/aeskw.js'; import * as ECDH from '../runtime/ecdhes.js'; import { encrypt as pbes2Kw } from '../runtime/pbes2kw.js'; import { encrypt as rsaEs } from '../runtime/rsaes.js'; import { encode as base64url } from '../runtime/base64url.js'; import generateCek, { bitLength as cekLength } from '../lib/cek.js'; import { JOSENotSupported } from '../util/errors.js'; import { exportJWK } from '../key/export.js'; import checkKeyType from './check_key_type.js'; import { wrap as aesGcmKw } from './aesgcmkw.js'; async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { let encryptedKey; let parameters; let cek; checkKeyType(alg, key, 'encrypt'); switch (alg) { case 'dir': { cek = key; break; } case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': { if (!ECDH.ecdhAllowed(key)) { throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); } const { apu, apv } = providedParameters; let { epk: ephemeralKey } = providedParameters; ephemeralKey || (ephemeralKey = (await ECDH.generateEpk(key)).privateKey); const { x, y, crv, kty } = await exportJWK(ephemeralKey); const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); parameters = { epk: { x, crv, kty } }; if (kty === 'EC') parameters.epk.y = y; if (apu) parameters.apu = base64url(apu); if (apv) parameters.apv = base64url(apv); if (alg === 'ECDH-ES') { cek = sharedSecret; break; } cek = providedCek || generateCek(enc); const kwAlg = alg.slice(-6); encryptedKey = await aesKw(kwAlg, sharedSecret, cek); break; } case 'RSA1_5': case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': { cek = providedCek || generateCek(enc); encryptedKey = await rsaEs(alg, key, cek); break; } case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': { cek = providedCek || generateCek(enc); const { p2c, p2s } = providedParameters; ({ encryptedKey, ...parameters } = await pbes2Kw(alg, key, cek, p2c, p2s)); break; } case 'A128KW': case 'A192KW': case 'A256KW': { cek = providedCek || generateCek(enc); encryptedKey = await aesKw(alg, key, cek); break; } case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': { cek = providedCek || generateCek(enc); const { iv } = providedParameters; ({ encryptedKey, ...parameters } = await aesGcmKw(alg, key, cek, iv)); break; } default: { throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); } } return { cek, encryptedKey, parameters }; } export default encryptKeyManagement; jose-4.11.4/dist/browser/lib/epoch.js000066400000000000000000000000741437043056600174020ustar00rootroot00000000000000export default (date) => Math.floor(date.getTime() / 1000); jose-4.11.4/dist/browser/lib/format_pem.js000066400000000000000000000002761437043056600204410ustar00rootroot00000000000000export default (b64, descriptor) => { const newlined = (b64.match(/.{1,64}/g) || []).join('\n'); return `-----BEGIN ${descriptor}-----\n${newlined}\n-----END ${descriptor}-----`; }; jose-4.11.4/dist/browser/lib/invalid_key_input.js000066400000000000000000000017141437043056600220230ustar00rootroot00000000000000function message(msg, actual, ...types) { if (types.length > 2) { const last = types.pop(); msg += `one of type ${types.join(', ')}, or ${last}.`; } else if (types.length === 2) { msg += `one of type ${types[0]} or ${types[1]}.`; } else { msg += `of type ${types[0]}.`; } if (actual == null) { msg += ` Received ${actual}`; } else if (typeof actual === 'function' && actual.name) { msg += ` Received function ${actual.name}`; } else if (typeof actual === 'object' && actual != null) { if (actual.constructor && actual.constructor.name) { msg += ` Received an instance of ${actual.constructor.name}`; } } return msg; } export default (actual, ...types) => { return message('Key must be ', actual, ...types); }; export function withAlg(alg, actual, ...types) { return message(`Key for the ${alg} algorithm must be `, actual, ...types); } jose-4.11.4/dist/browser/lib/is_disjoint.js000066400000000000000000000011221437043056600206150ustar00rootroot00000000000000const isDisjoint = (...headers) => { const sources = headers.filter(Boolean); if (sources.length === 0 || sources.length === 1) { return true; } let acc; for (const header of sources) { const parameters = Object.keys(header); if (!acc || acc.size === 0) { acc = new Set(parameters); continue; } for (const parameter of parameters) { if (acc.has(parameter)) { return false; } acc.add(parameter); } } return true; }; export default isDisjoint; jose-4.11.4/dist/browser/lib/is_object.js000066400000000000000000000007761437043056600202560ustar00rootroot00000000000000function isObjectLike(value) { return typeof value === 'object' && value !== null; } export default function isObject(input) { if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') { return false; } if (Object.getPrototypeOf(input) === null) { return true; } let proto = input; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(input) === proto; } jose-4.11.4/dist/browser/lib/iv.js000066400000000000000000000011371437043056600167230ustar00rootroot00000000000000import { JOSENotSupported } from '../util/errors.js'; import random from '../runtime/random.js'; export function bitLength(alg) { switch (alg) { case 'A128GCM': case 'A128GCMKW': case 'A192GCM': case 'A192GCMKW': case 'A256GCM': case 'A256GCMKW': return 96; case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': return 128; default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); } } export default (alg) => random(new Uint8Array(bitLength(alg) >> 3)); jose-4.11.4/dist/browser/lib/jwt_claims_set.js000066400000000000000000000073601437043056600213200ustar00rootroot00000000000000import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js'; import { decoder } from './buffer_utils.js'; import epoch from './epoch.js'; import secs from './secs.js'; import isObject from './is_object.js'; const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, ''); const checkAudiencePresence = (audPayload, audOption) => { if (typeof audPayload === 'string') { return audOption.includes(audPayload); } if (Array.isArray(audPayload)) { return audOption.some(Set.prototype.has.bind(new Set(audPayload))); } return false; }; export default (protectedHeader, encodedPayload, options = {}) => { const { typ } = options; if (typ && (typeof protectedHeader.typ !== 'string' || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', 'typ', 'check_failed'); } let payload; try { payload = JSON.parse(decoder.decode(encodedPayload)); } catch (_a) { } if (!isObject(payload)) { throw new JWTInvalid('JWT Claims Set must be a top-level JSON object'); } const { issuer } = options; if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { throw new JWTClaimValidationFailed('unexpected "iss" claim value', 'iss', 'check_failed'); } const { subject } = options; if (subject && payload.sub !== subject) { throw new JWTClaimValidationFailed('unexpected "sub" claim value', 'sub', 'check_failed'); } const { audience } = options; if (audience && !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) { throw new JWTClaimValidationFailed('unexpected "aud" claim value', 'aud', 'check_failed'); } let tolerance; switch (typeof options.clockTolerance) { case 'string': tolerance = secs(options.clockTolerance); break; case 'number': tolerance = options.clockTolerance; break; case 'undefined': tolerance = 0; break; default: throw new TypeError('Invalid clockTolerance option type'); } const { currentDate } = options; const now = epoch(currentDate || new Date()); if ((payload.iat !== undefined || options.maxTokenAge) && typeof payload.iat !== 'number') { throw new JWTClaimValidationFailed('"iat" claim must be a number', 'iat', 'invalid'); } if (payload.nbf !== undefined) { if (typeof payload.nbf !== 'number') { throw new JWTClaimValidationFailed('"nbf" claim must be a number', 'nbf', 'invalid'); } if (payload.nbf > now + tolerance) { throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', 'nbf', 'check_failed'); } } if (payload.exp !== undefined) { if (typeof payload.exp !== 'number') { throw new JWTClaimValidationFailed('"exp" claim must be a number', 'exp', 'invalid'); } if (payload.exp <= now - tolerance) { throw new JWTExpired('"exp" claim timestamp check failed', 'exp', 'check_failed'); } } if (options.maxTokenAge) { const age = now - payload.iat; const max = typeof options.maxTokenAge === 'number' ? options.maxTokenAge : secs(options.maxTokenAge); if (age - tolerance > max) { throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', 'iat', 'check_failed'); } if (age < 0 - tolerance) { throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', 'iat', 'check_failed'); } } return payload; }; jose-4.11.4/dist/browser/lib/secs.js000066400000000000000000000022711437043056600172420ustar00rootroot00000000000000const minute = 60; const hour = minute * 60; const day = hour * 24; const week = day * 7; const year = day * 365.25; const REGEX = /^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i; export default (str) => { const matched = REGEX.exec(str); if (!matched) { throw new TypeError('Invalid time period format'); } const value = parseFloat(matched[1]); const unit = matched[2].toLowerCase(); switch (unit) { case 'sec': case 'secs': case 'second': case 'seconds': case 's': return Math.round(value); case 'minute': case 'minutes': case 'min': case 'mins': case 'm': return Math.round(value * minute); case 'hour': case 'hours': case 'hr': case 'hrs': case 'h': return Math.round(value * hour); case 'day': case 'days': case 'd': return Math.round(value * day); case 'week': case 'weeks': case 'w': return Math.round(value * week); default: return Math.round(value * year); } }; jose-4.11.4/dist/browser/lib/validate_algorithms.js000066400000000000000000000006041437043056600223250ustar00rootroot00000000000000const validateAlgorithms = (option, algorithms) => { if (algorithms !== undefined && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) { throw new TypeError(`"${option}" option must be an array of strings`); } if (!algorithms) { return undefined; } return new Set(algorithms); }; export default validateAlgorithms; jose-4.11.4/dist/browser/lib/validate_crit.js000066400000000000000000000030611437043056600211150ustar00rootroot00000000000000import { JOSENotSupported } from '../util/errors.js'; function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { if (joseHeader.crit !== undefined && protectedHeader.crit === undefined) { throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); } if (!protectedHeader || protectedHeader.crit === undefined) { return new Set(); } if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) { throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); } let recognized; if (recognizedOption !== undefined) { recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); } else { recognized = recognizedDefault; } for (const parameter of protectedHeader.crit) { if (!recognized.has(parameter)) { throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); } if (joseHeader[parameter] === undefined) { throw new Err(`Extension Header Parameter "${parameter}" is missing`); } else if (recognized.get(parameter) && protectedHeader[parameter] === undefined) { throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); } } return new Set(protectedHeader.crit); } export default validateCrit; jose-4.11.4/dist/browser/package.json000066400000000000000000000000231437043056600174600ustar00rootroot00000000000000{"type": "module"} jose-4.11.4/dist/browser/runtime/000077500000000000000000000000001437043056600166625ustar00rootroot00000000000000jose-4.11.4/dist/browser/runtime/aeskw.js000066400000000000000000000026471437043056600203430ustar00rootroot00000000000000import bogusWebCrypto from './bogus.js'; import crypto, { isCryptoKey } from './webcrypto.js'; import { checkEncCryptoKey } from '../lib/crypto_key.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { types } from './is_key_like.js'; function checkKeySize(key, alg) { if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) { throw new TypeError(`Invalid key size for alg: ${alg}`); } } function getCryptoKey(key, alg, usage) { if (isCryptoKey(key)) { checkEncCryptoKey(key, alg, usage); return key; } if (key instanceof Uint8Array) { return crypto.subtle.importKey('raw', key, 'AES-KW', true, [usage]); } throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); } export const wrap = async (alg, key, cek) => { const cryptoKey = await getCryptoKey(key, alg, 'wrapKey'); checkKeySize(cryptoKey, alg); const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto); return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, cryptoKey, 'AES-KW')); }; export const unwrap = async (alg, key, encryptedKey) => { const cryptoKey = await getCryptoKey(key, alg, 'unwrapKey'); checkKeySize(cryptoKey, alg); const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, cryptoKey, 'AES-KW', ...bogusWebCrypto); return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek)); }; jose-4.11.4/dist/browser/runtime/asn1.js000066400000000000000000000125771437043056600200760ustar00rootroot00000000000000import { isCloudflareWorkers } from './env.js'; import crypto, { isCryptoKey } from './webcrypto.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { encodeBase64 } from './base64url.js'; import formatPEM from '../lib/format_pem.js'; import { JOSENotSupported } from '../util/errors.js'; import { types } from './is_key_like.js'; const genericExport = async (keyType, keyFormat, key) => { if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types)); } if (!key.extractable) { throw new TypeError('CryptoKey is not extractable'); } if (key.type !== keyType) { throw new TypeError(`key is not a ${keyType} key`); } return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`); }; export const toSPKI = (key) => { return genericExport('public', 'spki', key); }; export const toPKCS8 = (key) => { return genericExport('private', 'pkcs8', key); }; const findOid = (keyData, oid, from = 0) => { if (from === 0) { oid.unshift(oid.length); oid.unshift(0x06); } let i = keyData.indexOf(oid[0], from); if (i === -1) return false; const sub = keyData.subarray(i, i + oid.length); if (sub.length !== oid.length) return false; return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1); }; const getNamedCurve = (keyData) => { switch (true) { case findOid(keyData, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]): return 'P-256'; case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x22]): return 'P-384'; case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x23]): return 'P-521'; case findOid(keyData, [0x2b, 0x65, 0x6e]): return 'X25519'; case findOid(keyData, [0x2b, 0x65, 0x6f]): return 'X448'; case findOid(keyData, [0x2b, 0x65, 0x70]): return 'Ed25519'; case findOid(keyData, [0x2b, 0x65, 0x71]): return 'Ed448'; default: throw new JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type'); } }; const genericImport = async (replace, keyFormat, pem, alg, options) => { var _a, _b; let algorithm; let keyUsages; const keyData = new Uint8Array(atob(pem.replace(replace, '')) .split('') .map((c) => c.charCodeAt(0))); const isPublic = keyFormat === 'spki'; switch (alg) { case 'PS256': case 'PS384': case 'PS512': algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` }; keyUsages = isPublic ? ['verify'] : ['sign']; break; case 'RS256': case 'RS384': case 'RS512': algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` }; keyUsages = isPublic ? ['verify'] : ['sign']; break; case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': algorithm = { name: 'RSA-OAEP', hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`, }; keyUsages = isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey']; break; case 'ES256': algorithm = { name: 'ECDSA', namedCurve: 'P-256' }; keyUsages = isPublic ? ['verify'] : ['sign']; break; case 'ES384': algorithm = { name: 'ECDSA', namedCurve: 'P-384' }; keyUsages = isPublic ? ['verify'] : ['sign']; break; case 'ES512': algorithm = { name: 'ECDSA', namedCurve: 'P-521' }; keyUsages = isPublic ? ['verify'] : ['sign']; break; case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': { const namedCurve = getNamedCurve(keyData); algorithm = namedCurve.startsWith('P-') ? { name: 'ECDH', namedCurve } : { name: namedCurve }; keyUsages = isPublic ? [] : ['deriveBits']; break; } case 'EdDSA': algorithm = { name: getNamedCurve(keyData) }; keyUsages = isPublic ? ['verify'] : ['sign']; break; default: throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value'); } try { return await crypto.subtle.importKey(keyFormat, keyData, algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages); } catch (err) { if (algorithm.name === 'Ed25519' && (err === null || err === void 0 ? void 0 : err.name) === 'NotSupportedError' && isCloudflareWorkers()) { algorithm = { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' }; return await crypto.subtle.importKey(keyFormat, keyData, algorithm, (_b = options === null || options === void 0 ? void 0 : options.extractable) !== null && _b !== void 0 ? _b : false, keyUsages); } throw err; } }; export const fromPKCS8 = (pem, alg, options) => { return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, 'pkcs8', pem, alg, options); }; export const fromSPKI = (pem, alg, options) => { return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, 'spki', pem, alg, options); }; jose-4.11.4/dist/browser/runtime/base64url.js000066400000000000000000000023071437043056600210310ustar00rootroot00000000000000import { encoder, decoder } from '../lib/buffer_utils.js'; export const encodeBase64 = (input) => { let unencoded = input; if (typeof unencoded === 'string') { unencoded = encoder.encode(unencoded); } const CHUNK_SIZE = 0x8000; const arr = []; for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) { arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE))); } return btoa(arr.join('')); }; export const encode = (input) => { return encodeBase64(input).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); }; export const decodeBase64 = (encoded) => { const binary = atob(encoded); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) { bytes[i] = binary.charCodeAt(i); } return bytes; }; export const decode = (input) => { let encoded = input; if (encoded instanceof Uint8Array) { encoded = decoder.decode(encoded); } encoded = encoded.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, ''); try { return decodeBase64(encoded); } catch (_a) { throw new TypeError('The input to be decoded is not correctly encoded.'); } }; jose-4.11.4/dist/browser/runtime/bogus.js000066400000000000000000000001721437043056600203370ustar00rootroot00000000000000const bogusWebCrypto = [ { hash: 'SHA-256', name: 'HMAC' }, true, ['sign'], ]; export default bogusWebCrypto; jose-4.11.4/dist/browser/runtime/check_cek_length.js000066400000000000000000000005011437043056600224540ustar00rootroot00000000000000import { JWEInvalid } from '../util/errors.js'; const checkCekLength = (cek, expected) => { const actual = cek.byteLength << 3; if (actual !== expected) { throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); } }; export default checkCekLength; jose-4.11.4/dist/browser/runtime/check_key_length.js000066400000000000000000000005041437043056600225050ustar00rootroot00000000000000export default (alg, key) => { if (alg.startsWith('RS') || alg.startsWith('PS')) { const { modulusLength } = key.algorithm; if (typeof modulusLength !== 'number' || modulusLength < 2048) { throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); } } }; jose-4.11.4/dist/browser/runtime/decrypt.js000066400000000000000000000061471437043056600207020ustar00rootroot00000000000000import { concat, uint64be } from '../lib/buffer_utils.js'; import checkIvLength from '../lib/check_iv_length.js'; import checkCekLength from './check_cek_length.js'; import timingSafeEqual from './timing_safe_equal.js'; import { JOSENotSupported, JWEDecryptionFailed } from '../util/errors.js'; import crypto, { isCryptoKey } from './webcrypto.js'; import { checkEncCryptoKey } from '../lib/crypto_key.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { types } from './is_key_like.js'; async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) { if (!(cek instanceof Uint8Array)) { throw new TypeError(invalidKeyInput(cek, 'Uint8Array')); } const keySize = parseInt(enc.slice(1, 4), 10); const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['decrypt']); const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), { hash: `SHA-${keySize << 1}`, name: 'HMAC', }, false, ['sign']); const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); const expectedTag = new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3)); let macCheckPassed; try { macCheckPassed = timingSafeEqual(tag, expectedTag); } catch (_a) { } if (!macCheckPassed) { throw new JWEDecryptionFailed(); } let plaintext; try { plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: 'AES-CBC' }, encKey, ciphertext)); } catch (_b) { } if (!plaintext) { throw new JWEDecryptionFailed(); } return plaintext; } async function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) { let encKey; if (cek instanceof Uint8Array) { encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['decrypt']); } else { checkEncCryptoKey(cek, enc, 'decrypt'); encKey = cek; } try { return new Uint8Array(await crypto.subtle.decrypt({ additionalData: aad, iv, name: 'AES-GCM', tagLength: 128, }, encKey, concat(ciphertext, tag))); } catch (_a) { throw new JWEDecryptionFailed(); } } const decrypt = async (enc, cek, ciphertext, iv, tag, aad) => { if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')); } checkIvLength(enc, iv); switch (enc) { case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(-3), 10)); return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad); case 'A128GCM': case 'A192GCM': case 'A256GCM': if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(1, 4), 10)); return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad); default: throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); } }; export default decrypt; jose-4.11.4/dist/browser/runtime/digest.js000066400000000000000000000003551437043056600205020ustar00rootroot00000000000000import crypto from './webcrypto.js'; const digest = async (algorithm, data) => { const subtleDigest = `SHA-${algorithm.slice(-3)}`; return new Uint8Array(await crypto.subtle.digest(subtleDigest, data)); }; export default digest; jose-4.11.4/dist/browser/runtime/ecdhes.js000066400000000000000000000035731437043056600204630ustar00rootroot00000000000000import { encoder, concat, uint32be, lengthAndInput, concatKdf } from '../lib/buffer_utils.js'; import crypto, { isCryptoKey } from './webcrypto.js'; import { checkEncCryptoKey } from '../lib/crypto_key.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { types } from './is_key_like.js'; export async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) { if (!isCryptoKey(publicKey)) { throw new TypeError(invalidKeyInput(publicKey, ...types)); } checkEncCryptoKey(publicKey, 'ECDH'); if (!isCryptoKey(privateKey)) { throw new TypeError(invalidKeyInput(privateKey, ...types)); } checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits'); const value = concat(lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength)); let length; if (publicKey.algorithm.name === 'X25519') { length = 256; } else if (publicKey.algorithm.name === 'X448') { length = 448; } else { length = Math.ceil(parseInt(publicKey.algorithm.namedCurve.substr(-3), 10) / 8) << 3; } const sharedSecret = new Uint8Array(await crypto.subtle.deriveBits({ name: publicKey.algorithm.name, public: publicKey, }, privateKey, length)); return concatKdf(sharedSecret, keyLength, value); } export async function generateEpk(key) { if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types)); } return crypto.subtle.generateKey(key.algorithm, true, ['deriveBits']); } export function ecdhAllowed(key) { if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types)); } return (['P-256', 'P-384', 'P-521'].includes(key.algorithm.namedCurve) || key.algorithm.name === 'X25519' || key.algorithm.name === 'X448'); } jose-4.11.4/dist/browser/runtime/encrypt.js000066400000000000000000000053361437043056600207130ustar00rootroot00000000000000import { concat, uint64be } from '../lib/buffer_utils.js'; import checkIvLength from '../lib/check_iv_length.js'; import checkCekLength from './check_cek_length.js'; import crypto, { isCryptoKey } from './webcrypto.js'; import { checkEncCryptoKey } from '../lib/crypto_key.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { JOSENotSupported } from '../util/errors.js'; import { types } from './is_key_like.js'; async function cbcEncrypt(enc, plaintext, cek, iv, aad) { if (!(cek instanceof Uint8Array)) { throw new TypeError(invalidKeyInput(cek, 'Uint8Array')); } const keySize = parseInt(enc.slice(1, 4), 10); const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['encrypt']); const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), { hash: `SHA-${keySize << 1}`, name: 'HMAC', }, false, ['sign']); const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ iv, name: 'AES-CBC', }, encKey, plaintext)); const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); const tag = new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3)); return { ciphertext, tag }; } async function gcmEncrypt(enc, plaintext, cek, iv, aad) { let encKey; if (cek instanceof Uint8Array) { encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']); } else { checkEncCryptoKey(cek, enc, 'encrypt'); encKey = cek; } const encrypted = new Uint8Array(await crypto.subtle.encrypt({ additionalData: aad, iv, name: 'AES-GCM', tagLength: 128, }, encKey, plaintext)); const tag = encrypted.slice(-16); const ciphertext = encrypted.slice(0, -16); return { ciphertext, tag }; } const encrypt = async (enc, plaintext, cek, iv, aad) => { if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')); } checkIvLength(enc, iv); switch (enc) { case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(-3), 10)); return cbcEncrypt(enc, plaintext, cek, iv, aad); case 'A128GCM': case 'A192GCM': case 'A256GCM': if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(1, 4), 10)); return gcmEncrypt(enc, plaintext, cek, iv, aad); default: throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); } }; export default encrypt; jose-4.11.4/dist/browser/runtime/env.js000066400000000000000000000004071437043056600200110ustar00rootroot00000000000000export function isCloudflareWorkers() { return (typeof WebSocketPair !== 'undefined' || (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') || (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel')); } jose-4.11.4/dist/browser/runtime/fetch_jwks.js000066400000000000000000000020171437043056600213470ustar00rootroot00000000000000import { JOSEError, JWKSTimeout } from '../util/errors.js'; const fetchJwks = async (url, timeout, options) => { let controller; let id; let timedOut = false; if (typeof AbortController === 'function') { controller = new AbortController(); id = setTimeout(() => { timedOut = true; controller.abort(); }, timeout); } const response = await fetch(url.href, { signal: controller ? controller.signal : undefined, redirect: 'manual', headers: options.headers, }).catch((err) => { if (timedOut) throw new JWKSTimeout(); throw err; }); if (id !== undefined) clearTimeout(id); if (response.status !== 200) { throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response'); } try { return await response.json(); } catch (_a) { throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON'); } }; export default fetchJwks; jose-4.11.4/dist/browser/runtime/generate.js000066400000000000000000000137661437043056600210270ustar00rootroot00000000000000import { isCloudflareWorkers } from './env.js'; import crypto from './webcrypto.js'; import { JOSENotSupported } from '../util/errors.js'; import random from './random.js'; export async function generateSecret(alg, options) { var _a; let length; let algorithm; let keyUsages; switch (alg) { case 'HS256': case 'HS384': case 'HS512': length = parseInt(alg.slice(-3), 10); algorithm = { name: 'HMAC', hash: `SHA-${length}`, length }; keyUsages = ['sign', 'verify']; break; case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': length = parseInt(alg.slice(-3), 10); return random(new Uint8Array(length >> 3)); case 'A128KW': case 'A192KW': case 'A256KW': length = parseInt(alg.slice(1, 4), 10); algorithm = { name: 'AES-KW', length }; keyUsages = ['wrapKey', 'unwrapKey']; break; case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': case 'A128GCM': case 'A192GCM': case 'A256GCM': length = parseInt(alg.slice(1, 4), 10); algorithm = { name: 'AES-GCM', length }; keyUsages = ['encrypt', 'decrypt']; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } return crypto.subtle.generateKey(algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages); } function getModulusLengthOption(options) { var _a; const modulusLength = (_a = options === null || options === void 0 ? void 0 : options.modulusLength) !== null && _a !== void 0 ? _a : 2048; if (typeof modulusLength !== 'number' || modulusLength < 2048) { throw new JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used'); } return modulusLength; } export async function generateKeyPair(alg, options) { var _a, _b, _c, _d; let algorithm; let keyUsages; switch (alg) { case 'PS256': case 'PS384': case 'PS512': algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}`, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), modulusLength: getModulusLengthOption(options), }; keyUsages = ['sign', 'verify']; break; case 'RS256': case 'RS384': case 'RS512': algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}`, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), modulusLength: getModulusLengthOption(options), }; keyUsages = ['sign', 'verify']; break; case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': algorithm = { name: 'RSA-OAEP', hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), modulusLength: getModulusLengthOption(options), }; keyUsages = ['decrypt', 'unwrapKey', 'encrypt', 'wrapKey']; break; case 'ES256': algorithm = { name: 'ECDSA', namedCurve: 'P-256' }; keyUsages = ['sign', 'verify']; break; case 'ES384': algorithm = { name: 'ECDSA', namedCurve: 'P-384' }; keyUsages = ['sign', 'verify']; break; case 'ES512': algorithm = { name: 'ECDSA', namedCurve: 'P-521' }; keyUsages = ['sign', 'verify']; break; case 'EdDSA': keyUsages = ['sign', 'verify']; const crv = (_a = options === null || options === void 0 ? void 0 : options.crv) !== null && _a !== void 0 ? _a : 'Ed25519'; switch (crv) { case 'Ed25519': case 'Ed448': algorithm = { name: crv }; break; default: throw new JOSENotSupported('Invalid or unsupported crv option provided'); } break; case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': { keyUsages = ['deriveKey', 'deriveBits']; const crv = (_b = options === null || options === void 0 ? void 0 : options.crv) !== null && _b !== void 0 ? _b : 'P-256'; switch (crv) { case 'P-256': case 'P-384': case 'P-521': { algorithm = { name: 'ECDH', namedCurve: crv }; break; } case 'X25519': case 'X448': algorithm = { name: crv }; break; default: throw new JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448'); } break; } default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } try { return (await crypto.subtle.generateKey(algorithm, (_c = options === null || options === void 0 ? void 0 : options.extractable) !== null && _c !== void 0 ? _c : false, keyUsages)); } catch (err) { if (algorithm.name === 'Ed25519' && (err === null || err === void 0 ? void 0 : err.name) === 'NotSupportedError' && isCloudflareWorkers()) { algorithm = { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' }; return (await crypto.subtle.generateKey(algorithm, (_d = options === null || options === void 0 ? void 0 : options.extractable) !== null && _d !== void 0 ? _d : false, keyUsages)); } throw err; } } jose-4.11.4/dist/browser/runtime/get_sign_verify_key.js000066400000000000000000000013071437043056600232540ustar00rootroot00000000000000import crypto, { isCryptoKey } from './webcrypto.js'; import { checkSigCryptoKey } from '../lib/crypto_key.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { types } from './is_key_like.js'; export default function getCryptoKey(alg, key, usage) { if (isCryptoKey(key)) { checkSigCryptoKey(key, alg, usage); return key; } if (key instanceof Uint8Array) { if (!alg.startsWith('HS')) { throw new TypeError(invalidKeyInput(key, ...types)); } return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]); } throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); } jose-4.11.4/dist/browser/runtime/is_key_like.js000066400000000000000000000002141437043056600215040ustar00rootroot00000000000000import { isCryptoKey } from './webcrypto.js'; export default (key) => { return isCryptoKey(key); }; export const types = ['CryptoKey']; jose-4.11.4/dist/browser/runtime/jwk_to_key.js000066400000000000000000000135241437043056600213720ustar00rootroot00000000000000import { isCloudflareWorkers } from './env.js'; import crypto from './webcrypto.js'; import { JOSENotSupported } from '../util/errors.js'; import { decode as base64url } from './base64url.js'; function subtleMapping(jwk) { let algorithm; let keyUsages; switch (jwk.kty) { case 'oct': { switch (jwk.alg) { case 'HS256': case 'HS384': case 'HS512': algorithm = { name: 'HMAC', hash: `SHA-${jwk.alg.slice(-3)}` }; keyUsages = ['sign', 'verify']; break; case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': throw new JOSENotSupported(`${jwk.alg} keys cannot be imported as CryptoKey instances`); case 'A128GCM': case 'A192GCM': case 'A256GCM': case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': algorithm = { name: 'AES-GCM' }; keyUsages = ['encrypt', 'decrypt']; break; case 'A128KW': case 'A192KW': case 'A256KW': algorithm = { name: 'AES-KW' }; keyUsages = ['wrapKey', 'unwrapKey']; break; case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': algorithm = { name: 'PBKDF2' }; keyUsages = ['deriveBits']; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } case 'RSA': { switch (jwk.alg) { case 'PS256': case 'PS384': case 'PS512': algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` }; keyUsages = jwk.d ? ['sign'] : ['verify']; break; case 'RS256': case 'RS384': case 'RS512': algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` }; keyUsages = jwk.d ? ['sign'] : ['verify']; break; case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': algorithm = { name: 'RSA-OAEP', hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`, }; keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey']; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } case 'EC': { switch (jwk.alg) { case 'ES256': algorithm = { name: 'ECDSA', namedCurve: 'P-256' }; keyUsages = jwk.d ? ['sign'] : ['verify']; break; case 'ES384': algorithm = { name: 'ECDSA', namedCurve: 'P-384' }; keyUsages = jwk.d ? ['sign'] : ['verify']; break; case 'ES512': algorithm = { name: 'ECDSA', namedCurve: 'P-521' }; keyUsages = jwk.d ? ['sign'] : ['verify']; break; case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': algorithm = { name: 'ECDH', namedCurve: jwk.crv }; keyUsages = jwk.d ? ['deriveBits'] : []; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } case 'OKP': { switch (jwk.alg) { case 'EdDSA': algorithm = { name: jwk.crv }; keyUsages = jwk.d ? ['sign'] : ['verify']; break; case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': algorithm = { name: jwk.crv }; keyUsages = jwk.d ? ['deriveBits'] : []; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } default: throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); } return { algorithm, keyUsages }; } const parse = async (jwk) => { var _a, _b; const { algorithm, keyUsages } = subtleMapping(jwk); const rest = [ algorithm, (_a = jwk.ext) !== null && _a !== void 0 ? _a : false, (_b = jwk.key_ops) !== null && _b !== void 0 ? _b : keyUsages, ]; if (algorithm.name === 'PBKDF2') { return crypto.subtle.importKey('raw', base64url(jwk.k), ...rest); } const keyData = { ...jwk }; delete keyData.alg; delete keyData.use; try { return await crypto.subtle.importKey('jwk', keyData, ...rest); } catch (err) { if (algorithm.name === 'Ed25519' && (err === null || err === void 0 ? void 0 : err.name) === 'NotSupportedError' && isCloudflareWorkers()) { rest[0] = { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' }; return await crypto.subtle.importKey('jwk', keyData, ...rest); } throw err; } }; export default parse; jose-4.11.4/dist/browser/runtime/key_to_jwk.js000066400000000000000000000013351437043056600213670ustar00rootroot00000000000000import crypto, { isCryptoKey } from './webcrypto.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { encode as base64url } from './base64url.js'; import { types } from './is_key_like.js'; const keyToJWK = async (key) => { if (key instanceof Uint8Array) { return { kty: 'oct', k: base64url(key), }; } if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); } if (!key.extractable) { throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK'); } const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key); return jwk; }; export default keyToJWK; jose-4.11.4/dist/browser/runtime/pbes2kw.js000066400000000000000000000040461437043056600206010ustar00rootroot00000000000000import random from './random.js'; import { p2s as concatSalt } from '../lib/buffer_utils.js'; import { encode as base64url } from './base64url.js'; import { wrap, unwrap } from './aeskw.js'; import checkP2s from '../lib/check_p2s.js'; import crypto, { isCryptoKey } from './webcrypto.js'; import { checkEncCryptoKey } from '../lib/crypto_key.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { types } from './is_key_like.js'; function getCryptoKey(key, alg) { if (key instanceof Uint8Array) { return crypto.subtle.importKey('raw', key, 'PBKDF2', false, ['deriveBits']); } if (isCryptoKey(key)) { checkEncCryptoKey(key, alg, 'deriveBits', 'deriveKey'); return key; } throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); } async function deriveKey(p2s, alg, p2c, key) { checkP2s(p2s); const salt = concatSalt(alg, p2s); const keylen = parseInt(alg.slice(13, 16), 10); const subtleAlg = { hash: `SHA-${alg.slice(8, 11)}`, iterations: p2c, name: 'PBKDF2', salt, }; const wrapAlg = { length: keylen, name: 'AES-KW', }; const cryptoKey = await getCryptoKey(key, alg); if (cryptoKey.usages.includes('deriveBits')) { return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen)); } if (cryptoKey.usages.includes('deriveKey')) { return crypto.subtle.deriveKey(subtleAlg, cryptoKey, wrapAlg, false, ['wrapKey', 'unwrapKey']); } throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"'); } export const encrypt = async (alg, key, cek, p2c = 2048, p2s = random(new Uint8Array(16))) => { const derived = await deriveKey(p2s, alg, p2c, key); const encryptedKey = await wrap(alg.slice(-6), derived, cek); return { encryptedKey, p2c, p2s: base64url(p2s) }; }; export const decrypt = async (alg, key, encryptedKey, p2c, p2s) => { const derived = await deriveKey(p2s, alg, p2c, key); return unwrap(alg.slice(-6), derived, encryptedKey); }; jose-4.11.4/dist/browser/runtime/random.js000066400000000000000000000001311437043056600204730ustar00rootroot00000000000000import crypto from './webcrypto.js'; export default crypto.getRandomValues.bind(crypto); jose-4.11.4/dist/browser/runtime/rsaes.js000066400000000000000000000034621437043056600203420ustar00rootroot00000000000000import subtleAlgorithm from './subtle_rsaes.js'; import bogusWebCrypto from './bogus.js'; import crypto, { isCryptoKey } from './webcrypto.js'; import { checkEncCryptoKey } from '../lib/crypto_key.js'; import checkKeyLength from './check_key_length.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { types } from './is_key_like.js'; export const encrypt = async (alg, key, cek) => { if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types)); } checkEncCryptoKey(key, alg, 'encrypt', 'wrapKey'); checkKeyLength(alg, key); if (key.usages.includes('encrypt')) { return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek)); } if (key.usages.includes('wrapKey')) { const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto); return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, key, subtleAlgorithm(alg))); } throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation'); }; export const decrypt = async (alg, key, encryptedKey) => { if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types)); } checkEncCryptoKey(key, alg, 'decrypt', 'unwrapKey'); checkKeyLength(alg, key); if (key.usages.includes('decrypt')) { return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey)); } if (key.usages.includes('unwrapKey')) { const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, key, subtleAlgorithm(alg), ...bogusWebCrypto); return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek)); } throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation'); }; jose-4.11.4/dist/browser/runtime/sign.js000066400000000000000000000007541437043056600201660ustar00rootroot00000000000000import subtleAlgorithm from './subtle_dsa.js'; import crypto from './webcrypto.js'; import checkKeyLength from './check_key_length.js'; import getSignKey from './get_sign_verify_key.js'; const sign = async (alg, key, data) => { const cryptoKey = await getSignKey(alg, key, 'sign'); checkKeyLength(alg, cryptoKey); const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data); return new Uint8Array(signature); }; export default sign; jose-4.11.4/dist/browser/runtime/subtle_dsa.js000066400000000000000000000021231437043056600213430ustar00rootroot00000000000000import { isCloudflareWorkers } from './env.js'; import { JOSENotSupported } from '../util/errors.js'; export default function subtleDsa(alg, algorithm) { const hash = `SHA-${alg.slice(-3)}`; switch (alg) { case 'HS256': case 'HS384': case 'HS512': return { hash, name: 'HMAC' }; case 'PS256': case 'PS384': case 'PS512': return { hash, name: 'RSA-PSS', saltLength: alg.slice(-3) >> 3 }; case 'RS256': case 'RS384': case 'RS512': return { hash, name: 'RSASSA-PKCS1-v1_5' }; case 'ES256': case 'ES384': case 'ES512': return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve }; case 'EdDSA': if (isCloudflareWorkers() && algorithm.name === 'NODE-ED25519') { return { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' }; } return { name: algorithm.name }; default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } } jose-4.11.4/dist/browser/runtime/subtle_rsaes.js000066400000000000000000000006151437043056600217150ustar00rootroot00000000000000import { JOSENotSupported } from '../util/errors.js'; export default function subtleRsaEs(alg) { switch (alg) { case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': return 'RSA-OAEP'; default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } } jose-4.11.4/dist/browser/runtime/timing_safe_equal.js000066400000000000000000000010321437043056600226700ustar00rootroot00000000000000const timingSafeEqual = (a, b) => { if (!(a instanceof Uint8Array)) { throw new TypeError('First argument must be a buffer'); } if (!(b instanceof Uint8Array)) { throw new TypeError('Second argument must be a buffer'); } if (a.length !== b.length) { throw new TypeError('Input buffers must have the same length'); } const len = a.length; let out = 0; let i = -1; while (++i < len) { out |= a[i] ^ b[i]; } return out === 0; }; export default timingSafeEqual; jose-4.11.4/dist/browser/runtime/verify.js000066400000000000000000000010771437043056600205310ustar00rootroot00000000000000import subtleAlgorithm from './subtle_dsa.js'; import crypto from './webcrypto.js'; import checkKeyLength from './check_key_length.js'; import getVerifyKey from './get_sign_verify_key.js'; const verify = async (alg, key, signature, data) => { const cryptoKey = await getVerifyKey(alg, key, 'verify'); checkKeyLength(alg, cryptoKey); const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm); try { return await crypto.subtle.verify(algorithm, cryptoKey, signature, data); } catch (_a) { return false; } }; export default verify; jose-4.11.4/dist/browser/runtime/webcrypto.js000066400000000000000000000001251437043056600212340ustar00rootroot00000000000000export default crypto; export const isCryptoKey = (key) => key instanceof CryptoKey; jose-4.11.4/dist/browser/runtime/zlib.js000066400000000000000000000010721437043056600201600ustar00rootroot00000000000000import { JOSENotSupported } from '../util/errors.js'; export const inflate = async () => { throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.'); }; export const deflate = async () => { throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.'); }; jose-4.11.4/dist/browser/util/000077500000000000000000000000001437043056600161545ustar00rootroot00000000000000jose-4.11.4/dist/browser/util/base64url.js000066400000000000000000000002061437043056600203170ustar00rootroot00000000000000import * as base64url from '../runtime/base64url.js'; export const encode = base64url.encode; export const decode = base64url.decode; jose-4.11.4/dist/browser/util/decode_jwt.js000066400000000000000000000021431437043056600206210ustar00rootroot00000000000000import { decode as base64url } from './base64url.js'; import { decoder } from '../lib/buffer_utils.js'; import isObject from '../lib/is_object.js'; import { JWTInvalid } from './errors.js'; export function decodeJwt(jwt) { if (typeof jwt !== 'string') throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string'); const { 1: payload, length } = jwt.split('.'); if (length === 5) throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded'); if (length !== 3) throw new JWTInvalid('Invalid JWT'); if (!payload) throw new JWTInvalid('JWTs must contain a payload'); let decoded; try { decoded = base64url(payload); } catch (_a) { throw new JWTInvalid('Failed to parse the base64url encoded payload'); } let result; try { result = JSON.parse(decoder.decode(decoded)); } catch (_b) { throw new JWTInvalid('Failed to parse the decoded payload as JSON'); } if (!isObject(result)) throw new JWTInvalid('Invalid JWT Claims Set'); return result; } jose-4.11.4/dist/browser/util/decode_protected_header.js000066400000000000000000000020551437043056600233200ustar00rootroot00000000000000import { decode as base64url } from './base64url.js'; import { decoder } from '../lib/buffer_utils.js'; import isObject from '../lib/is_object.js'; export function decodeProtectedHeader(token) { let protectedB64u; if (typeof token === 'string') { const parts = token.split('.'); if (parts.length === 3 || parts.length === 5) { ; [protectedB64u] = parts; } } else if (typeof token === 'object' && token) { if ('protected' in token) { protectedB64u = token.protected; } else { throw new TypeError('Token does not contain a Protected Header'); } } try { if (typeof protectedB64u !== 'string' || !protectedB64u) { throw new Error(); } const result = JSON.parse(decoder.decode(base64url(protectedB64u))); if (!isObject(result)) { throw new Error(); } return result; } catch (_a) { throw new TypeError('Invalid Token or Protected Header formatting'); } } jose-4.11.4/dist/browser/util/errors.js000066400000000000000000000076601437043056600200370ustar00rootroot00000000000000export class JOSEError extends Error { static get code() { return 'ERR_JOSE_GENERIC'; } constructor(message) { var _a; super(message); this.code = 'ERR_JOSE_GENERIC'; this.name = this.constructor.name; (_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, this, this.constructor); } } export class JWTClaimValidationFailed extends JOSEError { static get code() { return 'ERR_JWT_CLAIM_VALIDATION_FAILED'; } constructor(message, claim = 'unspecified', reason = 'unspecified') { super(message); this.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'; this.claim = claim; this.reason = reason; } } export class JWTExpired extends JOSEError { static get code() { return 'ERR_JWT_EXPIRED'; } constructor(message, claim = 'unspecified', reason = 'unspecified') { super(message); this.code = 'ERR_JWT_EXPIRED'; this.claim = claim; this.reason = reason; } } export class JOSEAlgNotAllowed extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JOSE_ALG_NOT_ALLOWED'; } static get code() { return 'ERR_JOSE_ALG_NOT_ALLOWED'; } } export class JOSENotSupported extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JOSE_NOT_SUPPORTED'; } static get code() { return 'ERR_JOSE_NOT_SUPPORTED'; } } export class JWEDecryptionFailed extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWE_DECRYPTION_FAILED'; this.message = 'decryption operation failed'; } static get code() { return 'ERR_JWE_DECRYPTION_FAILED'; } } export class JWEInvalid extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWE_INVALID'; } static get code() { return 'ERR_JWE_INVALID'; } } export class JWSInvalid extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWS_INVALID'; } static get code() { return 'ERR_JWS_INVALID'; } } export class JWTInvalid extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWT_INVALID'; } static get code() { return 'ERR_JWT_INVALID'; } } export class JWKInvalid extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWK_INVALID'; } static get code() { return 'ERR_JWK_INVALID'; } } export class JWKSInvalid extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWKS_INVALID'; } static get code() { return 'ERR_JWKS_INVALID'; } } export class JWKSNoMatchingKey extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWKS_NO_MATCHING_KEY'; this.message = 'no applicable key found in the JSON Web Key Set'; } static get code() { return 'ERR_JWKS_NO_MATCHING_KEY'; } } export class JWKSMultipleMatchingKeys extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; this.message = 'multiple matching keys found in the JSON Web Key Set'; } static get code() { return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; } } export class JWKSTimeout extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWKS_TIMEOUT'; this.message = 'request timed out'; } static get code() { return 'ERR_JWKS_TIMEOUT'; } } export class JWSSignatureVerificationFailed extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; this.message = 'signature verification failed'; } static get code() { return 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; } } jose-4.11.4/dist/deno/000077500000000000000000000000001437043056600144415ustar00rootroot00000000000000jose-4.11.4/dist/deno/README.md000066400000000000000000000114321437043056600157210ustar00rootroot00000000000000# `jose` Modules API Documentation > "JSON Web Almost Everything" - JWA, JWS, JWE, JWT, JWK, JWKS with no dependencies using runtime's native crypto. ## [💗 Help the project](https://github.com/panva/jose/blob/v4.11.4/docs/https://github.com/sponsors/panva) ## Available modules **`example`** Deno import ```js import * as jose from 'https://deno.land/x/jose@v4.11.4/index.ts' ``` - JSON Web Tokens (JWT) - [Signing](https://github.com/panva/jose/blob/v4.11.4/docs/classes/jwt_sign.SignJWT.md#readme) - [Verification & JWT Claims Set Validation](https://github.com/panva/jose/blob/v4.11.4/docs/functions/jwt_verify.jwtVerify.md#readme) - Encrypted JSON Web Tokens - [Encryption](https://github.com/panva/jose/blob/v4.11.4/docs/classes/jwt_encrypt.EncryptJWT.md#readme) - [Decryption & JWT Claims Set Validation](https://github.com/panva/jose/blob/v4.11.4/docs/functions/jwt_decrypt.jwtDecrypt.md#readme) - Key Import - [JWK Import](https://github.com/panva/jose/blob/v4.11.4/docs/functions/key_import.importJWK.md#readme) - [Public Key Import (SPKI)](https://github.com/panva/jose/blob/v4.11.4/docs/functions/key_import.importSPKI.md#readme) - [Public Key Import (X.509 Certificate)](https://github.com/panva/jose/blob/v4.11.4/docs/functions/key_import.importX509.md#readme) - [Private Key Import (PKCS #8)](https://github.com/panva/jose/blob/v4.11.4/docs/functions/key_import.importPKCS8.md#readme) - JSON Web Encryption (JWE) - Encryption - [Compact](https://github.com/panva/jose/blob/v4.11.4/docs/classes/jwe_compact_encrypt.CompactEncrypt.md#readme), [Flattened](https://github.com/panva/jose/blob/v4.11.4/docs/classes/jwe_flattened_encrypt.FlattenedEncrypt.md#readme), [General](https://github.com/panva/jose/blob/v4.11.4/docs/classes/jwe_general_encrypt.GeneralEncrypt.md#readme) - Decryption - [Compact](https://github.com/panva/jose/blob/v4.11.4/docs/functions/jwe_compact_decrypt.compactDecrypt.md#readme), [Flattened](https://github.com/panva/jose/blob/v4.11.4/docs/functions/jwe_flattened_decrypt.flattenedDecrypt.md#readme), [General](https://github.com/panva/jose/blob/v4.11.4/docs/functions/jwe_general_decrypt.generalDecrypt.md#readme) - JSON Web Signature (JWS) - Signing - [Compact](https://github.com/panva/jose/blob/v4.11.4/docs/classes/jws_compact_sign.CompactSign.md#readme), [Flattened](https://github.com/panva/jose/blob/v4.11.4/docs/classes/jws_flattened_sign.FlattenedSign.md#readme), [General](https://github.com/panva/jose/blob/v4.11.4/docs/classes/jws_general_sign.GeneralSign.md#readme) - Verification - [Compact](https://github.com/panva/jose/blob/v4.11.4/docs/functions/jws_compact_verify.compactVerify.md#readme), [Flattened](https://github.com/panva/jose/blob/v4.11.4/docs/functions/jws_flattened_verify.flattenedVerify.md#readme), [General](https://github.com/panva/jose/blob/v4.11.4/docs/functions/jws_general_verify.generalVerify.md#readme) - JSON Web Key (JWK) - [Calculating JWK Thumbprint](https://github.com/panva/jose/blob/v4.11.4/docs/functions/jwk_thumbprint.calculateJwkThumbprint.md#readme) - [Calculating JWK Thumbprint URI](https://github.com/panva/jose/blob/v4.11.4/docs/functions/jwk_thumbprint.calculateJwkThumbprintUri.md#readme) - [Verification using a JWK Embedded in a JWS Header](https://github.com/panva/jose/blob/v4.11.4/docs/functions/jwk_embedded.EmbeddedJWK.md#readme) - JSON Web Key Set (JWKS) - [Verify using a local JWKSet](https://github.com/panva/jose/blob/v4.11.4/docs/functions/jwks_local.createLocalJWKSet.md#readme) - [Verify using a remote JWKSet](https://github.com/panva/jose/blob/v4.11.4/docs/functions/jwks_remote.createRemoteJWKSet.md#readme) - Key Pair or Secret Generation - [Asymmetric Key Pair Generation](https://github.com/panva/jose/blob/v4.11.4/docs/functions/key_generate_key_pair.generateKeyPair.md#readme) - [Symmetric Secret Generation](https://github.com/panva/jose/blob/v4.11.4/docs/functions/key_generate_secret.generateSecret.md#readme) - Key Export - [JWK Export](https://github.com/panva/jose/blob/v4.11.4/docs/functions/key_export.exportJWK.md#readme) - [Private Key Export](https://github.com/panva/jose/blob/v4.11.4/docs/functions/key_export.exportPKCS8.md#readme) - [Public Key Export](https://github.com/panva/jose/blob/v4.11.4/docs/functions/key_export.exportSPKI.md#readme) - Utilities - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v4.11.4/docs/functions/util_decode_protected_header.decodeProtectedHeader.md#readme) - [Decoding JWT Claims Set](https://github.com/panva/jose/blob/v4.11.4/docs/functions/util_decode_jwt.decodeJwt.md#readme) - [Unsecured JWT](https://github.com/panva/jose/blob/v4.11.4/docs/classes/jwt_unsecured.UnsecuredJWT.md#readme) - [JOSE Errors](https://github.com/panva/jose/blob/v4.11.4/docs/modules/util_errors.md#readme) [support-sponsor]: https://github.com/sponsors/panva jose-4.11.4/dist/deno/index.ts000066400000000000000000000067341437043056600161320ustar00rootroot00000000000000export { compactDecrypt } from './jwe/compact/decrypt.ts' export type { CompactDecryptGetKey } from './jwe/compact/decrypt.ts' export { flattenedDecrypt } from './jwe/flattened/decrypt.ts' export type { FlattenedDecryptGetKey } from './jwe/flattened/decrypt.ts' export { generalDecrypt } from './jwe/general/decrypt.ts' export type { GeneralDecryptGetKey } from './jwe/general/decrypt.ts' export { GeneralEncrypt } from './jwe/general/encrypt.ts' export type { Recipient } from './jwe/general/encrypt.ts' export { compactVerify } from './jws/compact/verify.ts' export type { CompactVerifyGetKey } from './jws/compact/verify.ts' export { flattenedVerify } from './jws/flattened/verify.ts' export type { FlattenedVerifyGetKey } from './jws/flattened/verify.ts' export { generalVerify } from './jws/general/verify.ts' export type { GeneralVerifyGetKey } from './jws/general/verify.ts' export { jwtVerify } from './jwt/verify.ts' export type { JWTVerifyOptions, JWTVerifyGetKey } from './jwt/verify.ts' export { jwtDecrypt } from './jwt/decrypt.ts' export type { JWTDecryptOptions, JWTDecryptGetKey } from './jwt/decrypt.ts' export type { ProduceJWT } from './jwt/produce.ts' export { CompactEncrypt } from './jwe/compact/encrypt.ts' export { FlattenedEncrypt } from './jwe/flattened/encrypt.ts' export { CompactSign } from './jws/compact/sign.ts' export { FlattenedSign } from './jws/flattened/sign.ts' export { GeneralSign } from './jws/general/sign.ts' export type { Signature } from './jws/general/sign.ts' export { SignJWT } from './jwt/sign.ts' export { EncryptJWT } from './jwt/encrypt.ts' export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.ts' export { EmbeddedJWK } from './jwk/embedded.ts' export { createLocalJWKSet } from './jwks/local.ts' export { createRemoteJWKSet } from './jwks/remote.ts' export type { RemoteJWKSetOptions } from './jwks/remote.ts' export { UnsecuredJWT } from './jwt/unsecured.ts' export type { UnsecuredResult } from './jwt/unsecured.ts' export { exportPKCS8, exportSPKI, exportJWK } from './key/export.ts' export { importSPKI, importPKCS8, importX509, importJWK } from './key/import.ts' export type { PEMImportOptions } from './key/import.ts' export { decodeProtectedHeader } from './util/decode_protected_header.ts' export { decodeJwt } from './util/decode_jwt.ts' export type { ProtectedHeaderParameters } from './util/decode_protected_header.ts' export * as errors from './util/errors.ts' export { generateKeyPair } from './key/generate_key_pair.ts' export type { GenerateKeyPairResult, GenerateKeyPairOptions } from './key/generate_key_pair.ts' export { generateSecret } from './key/generate_secret.ts' export type { GenerateSecretOptions } from './key/generate_secret.ts' export * as base64url from './util/base64url.ts' export type { KeyLike, JWK, FlattenedJWSInput, GeneralJWSInput, FlattenedJWS, GeneralJWS, JoseHeaderParameters, JWSHeaderParameters, JWEKeyManagementHeaderParameters, FlattenedJWE, GeneralJWE, JWEHeaderParameters, CritOption, DeflateOption, DecryptOptions, EncryptOptions, JWTClaimVerificationOptions, VerifyOptions, SignOptions, JWTPayload, DeflateFunction, InflateFunction, FlattenedDecryptResult, GeneralDecryptResult, CompactDecryptResult, FlattenedVerifyResult, GeneralVerifyResult, CompactVerifyResult, JWTVerifyResult, JWTDecryptResult, ResolvedKey, CompactJWEHeaderParameters, CompactJWSHeaderParameters, JWTHeaderParameters, JSONWebKeySet, } from './types.d.ts' jose-4.11.4/dist/deno/jwe/000077500000000000000000000000001437043056600152265ustar00rootroot00000000000000jose-4.11.4/dist/deno/jwe/compact/000077500000000000000000000000001437043056600166545ustar00rootroot00000000000000jose-4.11.4/dist/deno/jwe/compact/decrypt.ts000066400000000000000000000057451437043056600207110ustar00rootroot00000000000000import { flattenedDecrypt } from '../flattened/decrypt.ts' import { JWEInvalid } from '../../util/errors.ts' import { decoder } from '../../lib/buffer_utils.ts' import type { KeyLike, DecryptOptions, CompactJWEHeaderParameters, GetKeyFunction, FlattenedJWE, CompactDecryptResult, ResolvedKey, } from '../../types.d.ts' /** * Interface for Compact JWE Decryption dynamic key resolution. No token components have been * verified at the time of this function call. */ export interface CompactDecryptGetKey extends GetKeyFunction {} /** * Decrypts a Compact JWE. * * @example Usage * * ```js * const jwe = * 'eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0.nyQ19eq9ogh9wA7fFtnI2oouzy5_8b5DeLkoRMfi2yijgfTs2zEnayCEofz_qhnL-nwszabd9qUeHv0-IwvhhJJS7GUJOU3ikiIe42qcIAFme1A_Fo9CTxw4XTOy-I5qanl8So91u6hwfyN1VxAqVLsSE7_23EC-gfGEg_5znew9PyXXsOIE-K_HH7IQowRrlZ1X_bM_Liu53RzDpLDvRz59mp3S8L56YqpM8FexFGTGpEaoTcEIst375qncYt3-79IVR7gZN1RWsWgjPatfvVbnh74PglQcATSf3UUhaW0OAKn6q7r3PDx6DIKQ35bgHQg5QopuN00eIfLQL2trGw.W3grIVj5HVuAb76X.6PcuDe5D6ttWFYyv0oqqdDXfI2R8wBg1F2Q80UUA_Gv8eEimNWfxIWdLxrjzgQGSvIhxmFKuLM0.a93_Ug3uZHuczj70Zavx8Q' * * const { plaintext, protectedHeader } = await jose.compactDecrypt(jwe, privateKey) * * console.log(protectedHeader) * console.log(new TextDecoder().decode(plaintext)) * ``` * * @param jwe Compact JWE. * @param key Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export async function compactDecrypt( jwe: string | Uint8Array, key: KeyLike | Uint8Array, options?: DecryptOptions, ): Promise /** * @param jwe Compact JWE. * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export async function compactDecrypt( jwe: string | Uint8Array, getKey: CompactDecryptGetKey, options?: DecryptOptions, ): Promise export async function compactDecrypt( jwe: string | Uint8Array, key: KeyLike | Uint8Array | CompactDecryptGetKey, options?: DecryptOptions, ) { if (jwe instanceof Uint8Array) { jwe = decoder.decode(jwe) } if (typeof jwe !== 'string') { throw new JWEInvalid('Compact JWE must be a string or Uint8Array') } const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.') if (length !== 5) { throw new JWEInvalid('Invalid Compact JWE') } const decrypted = await flattenedDecrypt( { ciphertext, iv: (iv || undefined), protected: protectedHeader || undefined, tag: (tag || undefined), encrypted_key: encryptedKey || undefined, }, [1]>key, options, ) const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader! } if (typeof key === 'function') { return { ...result, key: decrypted.key } } return result } jose-4.11.4/dist/deno/jwe/compact/encrypt.ts000066400000000000000000000055321437043056600207150ustar00rootroot00000000000000import { FlattenedEncrypt } from '../flattened/encrypt.ts' import type { KeyLike, JWEKeyManagementHeaderParameters, CompactJWEHeaderParameters, EncryptOptions, } from '../../types.d.ts' /** * The CompactEncrypt class is a utility for creating Compact JWE strings. * * @example Usage * * ```js * const jwe = await new jose.CompactEncrypt( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM' }) * .encrypt(publicKey) * * console.log(jwe) * ``` */ export class CompactEncrypt { private _flattened: FlattenedEncrypt /** @param plaintext Binary representation of the plaintext to encrypt. */ constructor(plaintext: Uint8Array) { this._flattened = new FlattenedEncrypt(plaintext) } /** * Sets a content encryption key to use, by default a random suitable one is generated for the JWE * enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param cek JWE Content Encryption Key. */ setContentEncryptionKey(cek: Uint8Array) { this._flattened.setContentEncryptionKey(cek) return this } /** * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param iv JWE Initialization Vector. */ setInitializationVector(iv: Uint8Array) { this._flattened.setInitializationVector(iv) return this } /** * Sets the JWE Protected Header on the CompactEncrypt object. * * @param protectedHeader JWE Protected Header object. */ setProtectedHeader(protectedHeader: CompactJWEHeaderParameters) { this._flattened.setProtectedHeader(protectedHeader) return this } /** * Sets the JWE Key Management parameters to be used when encrypting the Content Encryption Key. * You do not need to invoke this method, it is only really intended for test and vector * validation purposes. * * @param parameters JWE Key Management parameters. */ setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters) { this._flattened.setKeyManagementParameters(parameters) return this } /** * Encrypts and resolves the value of the Compact JWE string. * * @param key Public Key or Secret to encrypt the JWE with. * @param options JWE Encryption options. */ async encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions): Promise { const jwe = await this._flattened.encrypt(key, options) return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.') } } jose-4.11.4/dist/deno/jwe/flattened/000077500000000000000000000000001437043056600171745ustar00rootroot00000000000000jose-4.11.4/dist/deno/jwe/flattened/decrypt.ts000066400000000000000000000177111437043056600212250ustar00rootroot00000000000000import { decode as base64url } from '../../runtime/base64url.ts' import decrypt from '../../runtime/decrypt.ts' import { inflate } from '../../runtime/zlib.ts' import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.ts' import isDisjoint from '../../lib/is_disjoint.ts' import isObject from '../../lib/is_object.ts' import decryptKeyManagement from '../../lib/decrypt_key_management.ts' import type { FlattenedDecryptResult, KeyLike, FlattenedJWE, JWEHeaderParameters, DecryptOptions, GetKeyFunction, ResolvedKey, } from '../../types.d.ts' import { encoder, decoder, concat } from '../../lib/buffer_utils.ts' import generateCek from '../../lib/cek.ts' import validateCrit from '../../lib/validate_crit.ts' import validateAlgorithms from '../../lib/validate_algorithms.ts' /** * Interface for Flattened JWE Decryption dynamic key resolution. No token components have been * verified at the time of this function call. */ export interface FlattenedDecryptGetKey extends GetKeyFunction {} /** * Decrypts a Flattened JWE. * * @example Usage * * ```js * const jwe = { * ciphertext: '9EzjFISUyoG-ifC2mSihfP0DPC80yeyrxhTzKt1C_VJBkxeBG0MI4Te61Pk45RAGubUvBpU9jm4', * iv: '8Fy7A_IuoX5VXG9s', * tag: 'W76IYV6arGRuDSaSyWrQNg', * encrypted_key: * 'Z6eD4UK_yFb5ZoKvKkGAdqywEG_m0e4IYo0x8Vf30LAMJcsc-_zSgIeiF82teZyYi2YYduHKoqImk7MRnoPZOlEs0Q5BNK1OgBmSOhCE8DFyqh9Zh48TCTP6lmBQ52naqoUJFMtHzu-0LwZH26hxos0GP3Dt19O379MJB837TdKKa87skq0zHaVLAquRHOBF77GI54Bc7O49d8aOrSu1VEFGMThlW2caspPRiTSePDMDPq7_WGk50izRhB3Asl9wmP9wEeaTrkJKRnQj5ips1SAZ1hDBsqEQKKukxP1HtdcopHV5_qgwU8Hjm5EwSLMluMQuiE6hwlkXGOujZLVizA', * aad: 'VGhlIEZlbGxvd3NoaXAgb2YgdGhlIFJpbmc', * protected: 'eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0', * } * * const { plaintext, protectedHeader, additionalAuthenticatedData } = * await jose.flattenedDecrypt(jwe, privateKey) * * console.log(protectedHeader) * const decoder = new TextDecoder() * console.log(decoder.decode(plaintext)) * console.log(decoder.decode(additionalAuthenticatedData)) * ``` * * @param jwe Flattened JWE. * @param key Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export function flattenedDecrypt( jwe: FlattenedJWE, key: KeyLike | Uint8Array, options?: DecryptOptions, ): Promise /** * @param jwe Flattened JWE. * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export function flattenedDecrypt( jwe: FlattenedJWE, getKey: FlattenedDecryptGetKey, options?: DecryptOptions, ): Promise export async function flattenedDecrypt( jwe: FlattenedJWE, key: KeyLike | Uint8Array | FlattenedDecryptGetKey, options?: DecryptOptions, ) { if (!isObject(jwe)) { throw new JWEInvalid('Flattened JWE must be an object') } if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) { throw new JWEInvalid('JOSE Header missing') } if (typeof jwe.iv !== 'string') { throw new JWEInvalid('JWE Initialization Vector missing or incorrect type') } if (typeof jwe.ciphertext !== 'string') { throw new JWEInvalid('JWE Ciphertext missing or incorrect type') } if (typeof jwe.tag !== 'string') { throw new JWEInvalid('JWE Authentication Tag missing or incorrect type') } if (jwe.protected !== undefined && typeof jwe.protected !== 'string') { throw new JWEInvalid('JWE Protected Header incorrect type') } if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') { throw new JWEInvalid('JWE Encrypted Key incorrect type') } if (jwe.aad !== undefined && typeof jwe.aad !== 'string') { throw new JWEInvalid('JWE AAD incorrect type') } if (jwe.header !== undefined && !isObject(jwe.header)) { throw new JWEInvalid('JWE Shared Unprotected Header incorrect type') } if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) { throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type') } let parsedProt!: JWEHeaderParameters if (jwe.protected) { try { const protectedHeader = base64url(jwe.protected) parsedProt = JSON.parse(decoder.decode(protectedHeader)) } catch { throw new JWEInvalid('JWE Protected Header is invalid') } } if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) { throw new JWEInvalid( 'JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint', ) } const joseHeader: JWEHeaderParameters = { ...parsedProt, ...jwe.header, ...jwe.unprotected, } validateCrit(JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader) if (joseHeader.zip !== undefined) { if (!parsedProt || !parsedProt.zip) { throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected') } if (joseHeader.zip !== 'DEF') { throw new JOSENotSupported( 'Unsupported JWE "zip" (Compression Algorithm) Header Parameter value', ) } } const { alg, enc } = joseHeader if (typeof alg !== 'string' || !alg) { throw new JWEInvalid('missing JWE Algorithm (alg) in JWE Header') } if (typeof enc !== 'string' || !enc) { throw new JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header') } const keyManagementAlgorithms = options && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms) const contentEncryptionAlgorithms = options && validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms) if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) { throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed') } if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed') } let encryptedKey!: Uint8Array if (jwe.encrypted_key !== undefined) { encryptedKey = base64url(jwe.encrypted_key!) } let resolvedKey = false if (typeof key === 'function') { key = await key(parsedProt, jwe) resolvedKey = true } let cek: KeyLike | Uint8Array try { cek = await decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) } catch (err) { if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { throw err } // https://www.rfc-editor.org/rfc/rfc7516#section-11.5 // To mitigate the attacks described in RFC 3218, the // recipient MUST NOT distinguish between format, padding, and length // errors of encrypted keys. It is strongly recommended, in the event // of receiving an improperly formatted key, that the recipient // substitute a randomly generated CEK and proceed to the next step, to // mitigate timing attacks. cek = generateCek(enc) } const iv = base64url(jwe.iv) const tag = base64url(jwe.tag) const protectedHeader: Uint8Array = encoder.encode(jwe.protected ?? '') let additionalData: Uint8Array if (jwe.aad !== undefined) { additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(jwe.aad)) } else { additionalData = protectedHeader } let plaintext = await decrypt(enc, cek, base64url(jwe.ciphertext), iv, tag, additionalData) if (joseHeader.zip === 'DEF') { plaintext = await (options?.inflateRaw || inflate)(plaintext) } const result: FlattenedDecryptResult = { plaintext } if (jwe.protected !== undefined) { result.protectedHeader = parsedProt } if (jwe.aad !== undefined) { result.additionalAuthenticatedData = base64url(jwe.aad!) } if (jwe.unprotected !== undefined) { result.sharedUnprotectedHeader = jwe.unprotected } if (jwe.header !== undefined) { result.unprotectedHeader = jwe.header } if (resolvedKey) { return { ...result, key } } return result } jose-4.11.4/dist/deno/jwe/flattened/encrypt.ts000066400000000000000000000224321437043056600212330ustar00rootroot00000000000000import { encode as base64url } from '../../runtime/base64url.ts' import encrypt from '../../runtime/encrypt.ts' import { deflate } from '../../runtime/zlib.ts' import type { KeyLike, FlattenedJWE, JWEHeaderParameters, JWEKeyManagementHeaderParameters, EncryptOptions, } from '../../types.d.ts' import generateIv from '../../lib/iv.ts' import encryptKeyManagement from '../../lib/encrypt_key_management.ts' import { JOSENotSupported, JWEInvalid } from '../../util/errors.ts' import isDisjoint from '../../lib/is_disjoint.ts' import { encoder, decoder, concat } from '../../lib/buffer_utils.ts' import validateCrit from '../../lib/validate_crit.ts' /** @private */ export const unprotected = Symbol() /** * The FlattenedEncrypt class is a utility for creating Flattened JWE objects. * * @example Usage * * ```js * const jwe = await new jose.FlattenedEncrypt( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM' }) * .setAdditionalAuthenticatedData(encoder.encode('The Fellowship of the Ring')) * .encrypt(publicKey) * * console.log(jwe) * ``` */ export class FlattenedEncrypt { private _plaintext: Uint8Array private _protectedHeader!: JWEHeaderParameters private _sharedUnprotectedHeader!: JWEHeaderParameters private _unprotectedHeader!: JWEHeaderParameters private _aad!: Uint8Array private _cek!: Uint8Array private _iv!: Uint8Array private _keyManagementParameters!: JWEKeyManagementHeaderParameters /** @param plaintext Binary representation of the plaintext to encrypt. */ constructor(plaintext: Uint8Array) { if (!(plaintext instanceof Uint8Array)) { throw new TypeError('plaintext must be an instance of Uint8Array') } this._plaintext = plaintext } /** * Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is * really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or * Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed * and missing. * * @param parameters JWE Key Management parameters. */ setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters) { if (this._keyManagementParameters) { throw new TypeError('setKeyManagementParameters can only be called once') } this._keyManagementParameters = parameters return this } /** * Sets the JWE Protected Header on the FlattenedEncrypt object. * * @param protectedHeader JWE Protected Header. */ setProtectedHeader(protectedHeader: JWEHeaderParameters) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once') } this._protectedHeader = protectedHeader return this } /** * Sets the JWE Shared Unprotected Header on the FlattenedEncrypt object. * * @param sharedUnprotectedHeader JWE Shared Unprotected Header. */ setSharedUnprotectedHeader(sharedUnprotectedHeader: JWEHeaderParameters) { if (this._sharedUnprotectedHeader) { throw new TypeError('setSharedUnprotectedHeader can only be called once') } this._sharedUnprotectedHeader = sharedUnprotectedHeader return this } /** * Sets the JWE Per-Recipient Unprotected Header on the FlattenedEncrypt object. * * @param unprotectedHeader JWE Per-Recipient Unprotected Header. */ setUnprotectedHeader(unprotectedHeader: JWEHeaderParameters) { if (this._unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once') } this._unprotectedHeader = unprotectedHeader return this } /** * Sets the Additional Authenticated Data on the FlattenedEncrypt object. * * @param aad Additional Authenticated Data. */ setAdditionalAuthenticatedData(aad: Uint8Array) { this._aad = aad return this } /** * Sets a content encryption key to use, by default a random suitable one is generated for the JWE * enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param cek JWE Content Encryption Key. */ setContentEncryptionKey(cek: Uint8Array) { if (this._cek) { throw new TypeError('setContentEncryptionKey can only be called once') } this._cek = cek return this } /** * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param iv JWE Initialization Vector. */ setInitializationVector(iv: Uint8Array) { if (this._iv) { throw new TypeError('setInitializationVector can only be called once') } this._iv = iv return this } /** * Encrypts and resolves the value of the Flattened JWE object. * * @param key Public Key or Secret to encrypt the JWE with. * @param options JWE Encryption options. */ async encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions) { if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { throw new JWEInvalid( 'either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()', ) } if ( !isDisjoint(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader) ) { throw new JWEInvalid( 'JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint', ) } const joseHeader: JWEHeaderParameters = { ...this._protectedHeader, ...this._unprotectedHeader, ...this._sharedUnprotectedHeader, } validateCrit(JWEInvalid, new Map(), options?.crit, this._protectedHeader, joseHeader) if (joseHeader.zip !== undefined) { if (!this._protectedHeader || !this._protectedHeader.zip) { throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected') } if (joseHeader.zip !== 'DEF') { throw new JOSENotSupported( 'Unsupported JWE "zip" (Compression Algorithm) Header Parameter value', ) } } const { alg, enc } = joseHeader if (typeof alg !== 'string' || !alg) { throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid') } if (typeof enc !== 'string' || !enc) { throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid') } let encryptedKey: Uint8Array | undefined if (alg === 'dir') { if (this._cek) { throw new TypeError('setContentEncryptionKey cannot be called when using Direct Encryption') } } else if (alg === 'ECDH-ES') { if (this._cek) { throw new TypeError( 'setContentEncryptionKey cannot be called when using Direct Key Agreement', ) } } let cek: KeyLike | Uint8Array { let parameters: { [propName: string]: unknown } | undefined ;({ cek, encryptedKey, parameters } = await encryptKeyManagement( alg, enc, key, this._cek, this._keyManagementParameters, )) if (parameters) { if (options && unprotected in options) { if (!this._unprotectedHeader) { this.setUnprotectedHeader(parameters) } else { this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters } } } else { if (!this._protectedHeader) { this.setProtectedHeader(parameters) } else { this._protectedHeader = { ...this._protectedHeader, ...parameters } } } } } this._iv ||= generateIv(enc) let additionalData: Uint8Array let protectedHeader: Uint8Array let aadMember: string | undefined if (this._protectedHeader) { protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))) } else { protectedHeader = encoder.encode('') } if (this._aad) { aadMember = base64url(this._aad) additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember)) } else { additionalData = protectedHeader } let ciphertext: Uint8Array let tag: Uint8Array if (joseHeader.zip === 'DEF') { const deflated = await (options?.deflateRaw || deflate)(this._plaintext) ;({ ciphertext, tag } = await encrypt(enc, deflated, cek, this._iv, additionalData)) } else { ;({ ciphertext, tag } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData)) } const jwe: FlattenedJWE = { ciphertext: base64url(ciphertext), iv: base64url(this._iv), tag: base64url(tag), } if (encryptedKey) { jwe.encrypted_key = base64url(encryptedKey) } if (aadMember) { jwe.aad = aadMember } if (this._protectedHeader) { jwe.protected = decoder.decode(protectedHeader) } if (this._sharedUnprotectedHeader) { jwe.unprotected = this._sharedUnprotectedHeader } if (this._unprotectedHeader) { jwe.header = this._unprotectedHeader } return jwe } } jose-4.11.4/dist/deno/jwe/general/000077500000000000000000000000001437043056600166435ustar00rootroot00000000000000jose-4.11.4/dist/deno/jwe/general/decrypt.ts000066400000000000000000000063431437043056600206730ustar00rootroot00000000000000import { flattenedDecrypt } from '../flattened/decrypt.ts' import { JWEDecryptionFailed, JWEInvalid } from '../../util/errors.ts' import type { KeyLike, DecryptOptions, JWEHeaderParameters, GetKeyFunction, FlattenedJWE, GeneralJWE, GeneralDecryptResult, ResolvedKey, } from '../../types.d.ts' import isObject from '../../lib/is_object.ts' /** * Interface for General JWE Decryption dynamic key resolution. No token components have been * verified at the time of this function call. */ export interface GeneralDecryptGetKey extends GetKeyFunction {} /** * Decrypts a General JWE. * * @example Usage * * ```js * const jwe = { * ciphertext: '9EzjFISUyoG-ifC2mSihfP0DPC80yeyrxhTzKt1C_VJBkxeBG0MI4Te61Pk45RAGubUvBpU9jm4', * iv: '8Fy7A_IuoX5VXG9s', * tag: 'W76IYV6arGRuDSaSyWrQNg', * aad: 'VGhlIEZlbGxvd3NoaXAgb2YgdGhlIFJpbmc', * protected: 'eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0', * recipients: [ * { * encrypted_key: * 'Z6eD4UK_yFb5ZoKvKkGAdqywEG_m0e4IYo0x8Vf30LAMJcsc-_zSgIeiF82teZyYi2YYduHKoqImk7MRnoPZOlEs0Q5BNK1OgBmSOhCE8DFyqh9Zh48TCTP6lmBQ52naqoUJFMtHzu-0LwZH26hxos0GP3Dt19O379MJB837TdKKa87skq0zHaVLAquRHOBF77GI54Bc7O49d8aOrSu1VEFGMThlW2caspPRiTSePDMDPq7_WGk50izRhB3Asl9wmP9wEeaTrkJKRnQj5ips1SAZ1hDBsqEQKKukxP1HtdcopHV5_qgwU8Hjm5EwSLMluMQuiE6hwlkXGOujZLVizA', * }, * ], * } * * const { plaintext, protectedHeader, additionalAuthenticatedData } = * await jose.generalDecrypt(jwe, privateKey) * * console.log(protectedHeader) * const decoder = new TextDecoder() * console.log(decoder.decode(plaintext)) * console.log(decoder.decode(additionalAuthenticatedData)) * ``` * * @param jwe General JWE. * @param key Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export function generalDecrypt( jwe: GeneralJWE, key: KeyLike | Uint8Array, options?: DecryptOptions, ): Promise /** * @param jwe General JWE. * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export function generalDecrypt( jwe: GeneralJWE, getKey: GeneralDecryptGetKey, options?: DecryptOptions, ): Promise export async function generalDecrypt( jwe: GeneralJWE, key: KeyLike | Uint8Array | GeneralDecryptGetKey, options?: DecryptOptions, ) { if (!isObject(jwe)) { throw new JWEInvalid('General JWE must be an object') } if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) { throw new JWEInvalid('JWE Recipients missing or incorrect type') } if (!jwe.recipients.length) { throw new JWEInvalid('JWE Recipients has no members') } for (const recipient of jwe.recipients) { try { return await flattenedDecrypt( { aad: jwe.aad, ciphertext: jwe.ciphertext, encrypted_key: recipient.encrypted_key, header: recipient.header, iv: jwe.iv, protected: jwe.protected, tag: jwe.tag, unprotected: jwe.unprotected, }, [1]>key, options, ) } catch { // } } throw new JWEDecryptionFailed() } jose-4.11.4/dist/deno/jwe/general/encrypt.ts000066400000000000000000000225301437043056600207010ustar00rootroot00000000000000import { FlattenedEncrypt, unprotected } from '../flattened/encrypt.ts' import { JWEInvalid } from '../../util/errors.ts' import generateCek from '../../lib/cek.ts' import isDisjoint from '../../lib/is_disjoint.ts' import encryptKeyManagement from '../../lib/encrypt_key_management.ts' import { encode as base64url } from '../../runtime/base64url.ts' import validateCrit from '../../lib/validate_crit.ts' import type { KeyLike, GeneralJWE, JWEHeaderParameters, CritOption, DeflateOption, } from '../../types.d.ts' export interface Recipient { /** * Sets the JWE Per-Recipient Unprotected Header on the Recipient object. * * @param unprotectedHeader JWE Per-Recipient Unprotected Header. */ setUnprotectedHeader(unprotectedHeader: JWEHeaderParameters): Recipient /** A shorthand for calling addRecipient() on the enclosing GeneralEncrypt instance */ addRecipient(...args: Parameters): Recipient /** A shorthand for calling encrypt() on the enclosing GeneralEncrypt instance */ encrypt(...args: Parameters): Promise /** Returns the enclosing GeneralEncrypt */ done(): GeneralEncrypt } class IndividualRecipient implements Recipient { private parent: GeneralEncrypt unprotectedHeader?: JWEHeaderParameters key: KeyLike | Uint8Array options: CritOption constructor(enc: GeneralEncrypt, key: KeyLike | Uint8Array, options: CritOption) { this.parent = enc this.key = key this.options = options } setUnprotectedHeader(unprotectedHeader: JWEHeaderParameters) { if (this.unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once') } this.unprotectedHeader = unprotectedHeader return this } addRecipient(...args: Parameters) { return this.parent.addRecipient(...args) } encrypt(...args: Parameters) { return this.parent.encrypt(...args) } done() { return this.parent } } /** * The GeneralEncrypt class is a utility for creating General JWE objects. * * @example Usage * * ```js * const jwe = await new jose.GeneralEncrypt( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .setProtectedHeader({ enc: 'A256GCM' }) * .addRecipient(ecPublicKey) * .setUnprotectedHeader({ alg: 'ECDH-ES+A256KW' }) * .addRecipient(rsaPublicKey) * .setUnprotectedHeader({ alg: 'RSA-OAEP-384' }) * .encrypt() * * console.log(jwe) * ``` */ export class GeneralEncrypt { private _plaintext: Uint8Array private _recipients: IndividualRecipient[] = [] private _protectedHeader!: JWEHeaderParameters private _unprotectedHeader!: JWEHeaderParameters private _aad!: Uint8Array /** @param plaintext Binary representation of the plaintext to encrypt. */ constructor(plaintext: Uint8Array) { this._plaintext = plaintext } /** * Adds an additional recipient for the General JWE object. * * @param key Public Key or Secret to encrypt the Content Encryption Key for the recipient with. * @param options JWE Encryption options. */ addRecipient(key: KeyLike | Uint8Array, options?: CritOption): Recipient { const recipient = new IndividualRecipient(this, key, { crit: options?.crit }) this._recipients.push(recipient) return recipient } /** * Sets the JWE Protected Header on the GeneralEncrypt object. * * @param protectedHeader JWE Protected Header object. */ setProtectedHeader(protectedHeader: JWEHeaderParameters): this { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once') } this._protectedHeader = protectedHeader return this } /** * Sets the JWE Shared Unprotected Header on the GeneralEncrypt object. * * @param sharedUnprotectedHeader JWE Shared Unprotected Header object. */ setSharedUnprotectedHeader(sharedUnprotectedHeader: JWEHeaderParameters): this { if (this._unprotectedHeader) { throw new TypeError('setSharedUnprotectedHeader can only be called once') } this._unprotectedHeader = sharedUnprotectedHeader return this } /** * Sets the Additional Authenticated Data on the GeneralEncrypt object. * * @param aad Additional Authenticated Data. */ setAdditionalAuthenticatedData(aad: Uint8Array) { this._aad = aad return this } /** * Encrypts and resolves the value of the General JWE object. * * @param options JWE Encryption options. */ async encrypt(options?: DeflateOption): Promise { if (!this._recipients.length) { throw new JWEInvalid('at least one recipient must be added') } options = { deflateRaw: options?.deflateRaw } if (this._recipients.length === 1) { const [recipient] = this._recipients const flattened = await new FlattenedEncrypt(this._plaintext) .setAdditionalAuthenticatedData(this._aad) .setProtectedHeader(this._protectedHeader) .setSharedUnprotectedHeader(this._unprotectedHeader) .setUnprotectedHeader(recipient.unprotectedHeader!) .encrypt(recipient.key, { ...recipient.options, ...options }) let jwe: GeneralJWE = { ciphertext: flattened.ciphertext, iv: flattened.iv, recipients: [{}], tag: flattened.tag, } if (flattened.aad) jwe.aad = flattened.aad if (flattened.protected) jwe.protected = flattened.protected if (flattened.unprotected) jwe.unprotected = flattened.unprotected if (flattened.encrypted_key) jwe.recipients![0].encrypted_key = flattened.encrypted_key if (flattened.header) jwe.recipients![0].header = flattened.header return jwe } let enc!: string for (let i = 0; i < this._recipients.length; i++) { const recipient = this._recipients[i] if ( !isDisjoint(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader) ) { throw new JWEInvalid( 'JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint', ) } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...recipient.unprotectedHeader, } const { alg } = joseHeader if (typeof alg !== 'string' || !alg) { throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid') } if (alg === 'dir' || alg === 'ECDH-ES') { throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient') } if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) { throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid') } if (!enc) { enc = joseHeader.enc } else if (enc !== joseHeader.enc) { throw new JWEInvalid( 'JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients', ) } validateCrit(JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader) if (joseHeader.zip !== undefined) { if (!this._protectedHeader || !this._protectedHeader.zip) { throw new JWEInvalid( 'JWE "zip" (Compression Algorithm) Header MUST be integrity protected', ) } } } const cek = generateCek(enc) let jwe: GeneralJWE = { ciphertext: '', iv: '', recipients: [], tag: '', } for (let i = 0; i < this._recipients.length; i++) { const recipient = this._recipients[i] const target: Record = {} jwe.recipients!.push(target) const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...recipient.unprotectedHeader, } const p2c = joseHeader.alg!.startsWith('PBES2') ? 2048 + i : undefined if (i === 0) { const flattened = await new FlattenedEncrypt(this._plaintext) .setAdditionalAuthenticatedData(this._aad) .setContentEncryptionKey(cek) .setProtectedHeader(this._protectedHeader) .setSharedUnprotectedHeader(this._unprotectedHeader) .setUnprotectedHeader(recipient.unprotectedHeader!) .setKeyManagementParameters({ p2c }) .encrypt(recipient.key, { ...recipient.options, ...options, // @ts-expect-error [unprotected]: true, }) jwe.ciphertext = flattened.ciphertext jwe.iv = flattened.iv jwe.tag = flattened.tag if (flattened.aad) jwe.aad = flattened.aad if (flattened.protected) jwe.protected = flattened.protected if (flattened.unprotected) jwe.unprotected = flattened.unprotected target.encrypted_key = flattened.encrypted_key! if (flattened.header) target.header = flattened.header continue } const { encryptedKey, parameters } = await encryptKeyManagement( recipient.unprotectedHeader?.alg! || this._protectedHeader?.alg! || this._unprotectedHeader?.alg!, enc, recipient.key, cek, { p2c }, ) target.encrypted_key = base64url(encryptedKey!) if (recipient.unprotectedHeader || parameters) target.header = { ...recipient.unprotectedHeader, ...parameters } } return jwe } } jose-4.11.4/dist/deno/jwk/000077500000000000000000000000001437043056600152345ustar00rootroot00000000000000jose-4.11.4/dist/deno/jwk/embedded.ts000066400000000000000000000034701437043056600173410ustar00rootroot00000000000000import type { FlattenedJWSInput, JWSHeaderParameters } from '../types.d.ts' import { importJWK } from '../key/import.ts' import isObject from '../lib/is_object.ts' import { JWSInvalid } from '../util/errors.ts' /** * EmbeddedJWK is an implementation of a GetKeyFunction intended to be used with the JWS/JWT verify * operations whenever you need to opt-in to verify signatures with a public key embedded in the * token's "jwk" (JSON Web Key) Header Parameter. It is recommended to combine this with the verify * function's `algorithms` option to define accepted JWS "alg" (Algorithm) Header Parameter values. * * @example Usage * * ```js * const jwt = * 'eyJqd2siOnsiY3J2IjoiUC0yNTYiLCJ4IjoiVU05ZzVuS25aWFlvdldBbE03NmNMejl2VG96UmpfX0NIVV9kT2wtZ09vRSIsInkiOiJkczhhZVF3MWwyY0RDQTdiQ2tPTnZ3REtwWEFidFhqdnFDbGVZSDhXc19VIiwia3R5IjoiRUMifSwiYWxnIjoiRVMyNTYifQ.eyJpc3MiOiJ1cm46ZXhhbXBsZTppc3N1ZXIiLCJhdWQiOiJ1cm46ZXhhbXBsZTphdWRpZW5jZSIsImlhdCI6MTYwNDU4MDc5NH0.60boak3_dErnW47ZPty1C0nrjeVq86EN_eK0GOq6K8w2OA0thKoBxFK4j-NuU9yZ_A9UKGxPT_G87DladBaV9g' * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, jose.EmbeddedJWK, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(protectedHeader) * console.log(payload) * ``` */ export async function EmbeddedJWK(protectedHeader: JWSHeaderParameters, token: FlattenedJWSInput) { const joseHeader = { ...protectedHeader, ...token.header, } if (!isObject(joseHeader.jwk)) { throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object') } const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg!, true) if (key instanceof Uint8Array || key.type !== 'public') { throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key') } return key } jose-4.11.4/dist/deno/jwk/thumbprint.ts000066400000000000000000000066621437043056600200120ustar00rootroot00000000000000import digest from '../runtime/digest.ts' import { encode as base64url } from '../runtime/base64url.ts' import { JOSENotSupported, JWKInvalid } from '../util/errors.ts' import { encoder } from '../lib/buffer_utils.ts' import type { JWK } from '../types.d.ts' import isObject from '../lib/is_object.ts' const check = (value: unknown, description: string) => { if (typeof value !== 'string' || !value) { throw new JWKInvalid(`${description} missing or invalid`) } } /** * Calculates a base64url-encoded JSON Web Key (JWK) Thumbprint * * @example Usage * * ```js * const thumbprint = await jose.calculateJwkThumbprint({ * kty: 'EC', * crv: 'P-256', * x: 'jJ6Flys3zK9jUhnOHf6G49Dyp5hah6CNP84-gY-n9eo', * y: 'nhI6iD5eFXgBTLt_1p3aip-5VbZeMhxeFSpjfEAf7Ww', * }) * * console.log(thumbprint) * // 'w9eYdC6_s_tLQ8lH6PUpc0mddazaqtPgeC2IgWDiqY8' * ``` * * @param jwk JSON Web Key. * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is * "sha256". * @see [RFC7638](https://www.rfc-editor.org/rfc/rfc7638) */ export async function calculateJwkThumbprint( jwk: JWK, digestAlgorithm?: 'sha256' | 'sha384' | 'sha512', ): Promise { if (!isObject(jwk)) { throw new TypeError('JWK must be an object') } digestAlgorithm ??= 'sha256' if ( digestAlgorithm !== 'sha256' && digestAlgorithm !== 'sha384' && digestAlgorithm !== 'sha512' ) { throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"') } let components: JWK switch (jwk.kty) { case 'EC': check(jwk.crv, '"crv" (Curve) Parameter') check(jwk.x, '"x" (X Coordinate) Parameter') check(jwk.y, '"y" (Y Coordinate) Parameter') components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y } break case 'OKP': check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter') check(jwk.x, '"x" (Public Key) Parameter') components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x } break case 'RSA': check(jwk.e, '"e" (Exponent) Parameter') check(jwk.n, '"n" (Modulus) Parameter') components = { e: jwk.e, kty: jwk.kty, n: jwk.n } break case 'oct': check(jwk.k, '"k" (Key Value) Parameter') components = { k: jwk.k, kty: jwk.kty } break default: throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported') } const data = encoder.encode(JSON.stringify(components)) return base64url(await digest(digestAlgorithm, data)) } /** * Calculates a JSON Web Key (JWK) Thumbprint URI * * @example Usage * * ```js * const thumbprintUri = await jose.calculateJwkThumbprintUri({ * kty: 'EC', * crv: 'P-256', * x: 'jJ6Flys3zK9jUhnOHf6G49Dyp5hah6CNP84-gY-n9eo', * y: 'nhI6iD5eFXgBTLt_1p3aip-5VbZeMhxeFSpjfEAf7Ww', * }) * * console.log(thumbprint) * // 'urn:ietf:params:oauth:jwk-thumbprint:sha-256:w9eYdC6_s_tLQ8lH6PUpc0mddazaqtPgeC2IgWDiqY8' * ``` * * @param jwk JSON Web Key. * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is * "sha256". * @see [RFC9278](https://www.rfc-editor.org/rfc/rfc9278) */ export async function calculateJwkThumbprintUri( jwk: JWK, digestAlgorithm?: 'sha256' | 'sha384' | 'sha512', ): Promise { digestAlgorithm ??= 'sha256' const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm) return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}` } jose-4.11.4/dist/deno/jwks/000077500000000000000000000000001437043056600154175ustar00rootroot00000000000000jose-4.11.4/dist/deno/jwks/local.ts000066400000000000000000000121321437043056600170600ustar00rootroot00000000000000import type { KeyLike, JWSHeaderParameters, JWK, JSONWebKeySet, FlattenedJWSInput, GetKeyFunction, } from '../types.d.ts' import { importJWK } from '../key/import.ts' import { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.ts' import isObject from '../lib/is_object.ts' function getKtyFromAlg(alg: unknown) { switch (typeof alg === 'string' && alg.slice(0, 2)) { case 'RS': case 'PS': return 'RSA' case 'ES': return 'EC' case 'Ed': return 'OKP' default: throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set') } } interface Cache { [alg: string]: KeyLike } /** @private */ export function isJWKSLike(jwks: unknown): jwks is JSONWebKeySet { return ( jwks && typeof jwks === 'object' && // @ts-expect-error Array.isArray(jwks.keys) && // @ts-expect-error jwks.keys.every(isJWKLike) ) } function isJWKLike(key: unknown) { return isObject(key) } function clone(obj: T): T { // @ts-ignore if (typeof structuredClone === 'function') { // @ts-ignore return structuredClone(obj) } return JSON.parse(JSON.stringify(obj)) } /** @private */ export class LocalJWKSet { protected _jwks?: JSONWebKeySet private _cached: WeakMap = new WeakMap() constructor(jwks: unknown) { if (!isJWKSLike(jwks)) { throw new JWKSInvalid('JSON Web Key Set malformed') } this._jwks = clone(jwks) } async getKey(protectedHeader: JWSHeaderParameters, token: FlattenedJWSInput): Promise { const { alg, kid } = { ...protectedHeader, ...token.header } const kty = getKtyFromAlg(alg) const candidates = this._jwks!.keys.filter((jwk) => { // filter keys based on the mapping of signature algorithms to Key Type let candidate = kty === jwk.kty // filter keys based on the JWK Key ID in the header if (candidate && typeof kid === 'string') { candidate = kid === jwk.kid } // filter keys based on the key's declared Algorithm if (candidate && typeof jwk.alg === 'string') { candidate = alg === jwk.alg } // filter keys based on the key's declared Public Key Use if (candidate && typeof jwk.use === 'string') { candidate = jwk.use === 'sig' } // filter keys based on the key's declared Key Operations if (candidate && Array.isArray(jwk.key_ops)) { candidate = jwk.key_ops.includes('verify') } // filter out non-applicable OKP Sub Types if (candidate && alg === 'EdDSA') { candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448' } // filter out non-applicable EC curves if (candidate) { switch (alg) { case 'ES256': candidate = jwk.crv === 'P-256' break case 'ES256K': candidate = jwk.crv === 'secp256k1' break case 'ES384': candidate = jwk.crv === 'P-384' break case 'ES512': candidate = jwk.crv === 'P-521' break } } return candidate }) const { 0: jwk, length } = candidates if (length === 0) { throw new JWKSNoMatchingKey() } else if (length !== 1) { throw new JWKSMultipleMatchingKeys() } const cached = this._cached.get(jwk) || this._cached.set(jwk, {}).get(jwk)! if (cached[alg!] === undefined) { const keyObject = await importJWK({ ...jwk, ext: true }, alg) if (keyObject instanceof Uint8Array || keyObject.type !== 'public') { throw new JWKSInvalid('JSON Web Key Set members must be public keys') } cached[alg!] = keyObject } return cached[alg!] } } /** * Returns a function that resolves to a key object from a locally stored, or otherwise available, * JSON Web Key Set. * * Only a single public key must match the selection process. * * @example Usage * * ```js * const JWKS = jose.createLocalJWKSet({ * keys: [ * { * kty: 'RSA', * e: 'AQAB', * n: '12oBZRhCiZFJLcPg59LkZZ9mdhSMTKAQZYq32k_ti5SBB6jerkh-WzOMAO664r_qyLkqHUSp3u5SbXtseZEpN3XPWGKSxjsy-1JyEFTdLSYe6f9gfrmxkUF_7DTpq0gn6rntP05g2-wFW50YO7mosfdslfrTJYWHFhJALabAeYirYD7-9kqq9ebfFMF4sRRELbv9oi36As6Q9B3Qb5_C1rAzqfao_PCsf9EPsTZsVVVkA5qoIAr47lo1ipfiBPxUCCNSdvkmDTYgvvRm6ZoMjFbvOtgyts55fXKdMWv7I9HMD5HwE9uW839PWA514qhbcIsXEYSFMPMV6fnlsiZvQQ', * alg: 'PS256', * }, * { * crv: 'P-256', * kty: 'EC', * x: 'ySK38C1jBdLwDsNWKzzBHqKYEE5Cgv-qjWvorUXk9fw', * y: '_LeQBw07cf5t57Iavn4j-BqJsAD1dpoz8gokd3sBsOo', * alg: 'ES256', * }, * ], * }) * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, JWKS, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * console.log(protectedHeader) * console.log(payload) * ``` * * @param jwks JSON Web Key Set formatted object. */ export function createLocalJWKSet( jwks: JSONWebKeySet, ): GetKeyFunction { return LocalJWKSet.prototype.getKey.bind(new LocalJWKSet(jwks)) } jose-4.11.4/dist/deno/jwks/remote.ts000066400000000000000000000123221437043056600172620ustar00rootroot00000000000000import fetchJwks from '../runtime/fetch_jwks.ts' import { isCloudflareWorkers } from '../runtime/env.ts' import type { KeyLike, JWSHeaderParameters, FlattenedJWSInput, GetKeyFunction } from '../types.d.ts' import { JWKSInvalid, JWKSNoMatchingKey } from '../util/errors.ts' import { isJWKSLike, LocalJWKSet } from './local.ts' /** Options for the remote JSON Web Key Set. */ export interface RemoteJWKSetOptions { /** * Timeout (in milliseconds) for the HTTP request. When reached the request will be aborted and * the verification will fail. Default is 5000 (5 seconds). */ timeoutDuration?: number /** * Duration (in milliseconds) for which no more HTTP requests will be triggered after a previous * successful fetch. Default is 30000 (30 seconds). */ cooldownDuration?: number /** * Maximum time (in milliseconds) between successful HTTP requests. Default is 600000 (10 * minutes). */ cacheMaxAge?: number | typeof Infinity /** * An instance of [http.Agent](https://nodejs.org/api/http.html#class-httpagent) or * [https.Agent](https://nodejs.org/api/https.html#class-httpsagent) to pass to the * [http.get](https://nodejs.org/api/http.html#httpgetoptions-callback) or * [https.get](https://nodejs.org/api/https.html#httpsgetoptions-callback) method's options. Use * when behind an http(s) proxy. This is a Node.js runtime specific option, it is ignored when * used outside of Node.js runtime. */ agent?: any /** Optional headers to be sent with the HTTP request. */ headers?: Record } class RemoteJWKSet extends LocalJWKSet { private _url: URL private _timeoutDuration: number private _cooldownDuration: number private _cacheMaxAge: number private _jwksTimestamp?: number private _pendingFetch?: Promise private _options: Pick constructor(url: unknown, options?: RemoteJWKSetOptions) { super({ keys: [] }) this._jwks = undefined if (!(url instanceof URL)) { throw new TypeError('url must be an instance of URL') } this._url = new URL(url.href) this._options = { agent: options?.agent, headers: options?.headers } this._timeoutDuration = typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000 this._cooldownDuration = typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000 this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000 } coolingDown() { return typeof this._jwksTimestamp === 'number' ? Date.now() < this._jwksTimestamp + this._cooldownDuration : false } fresh() { return typeof this._jwksTimestamp === 'number' ? Date.now() < this._jwksTimestamp + this._cacheMaxAge : false } async getKey(protectedHeader: JWSHeaderParameters, token: FlattenedJWSInput): Promise { if (!this._jwks || !this.fresh()) { await this.reload() } try { return await super.getKey(protectedHeader, token) } catch (err) { if (err instanceof JWKSNoMatchingKey) { if (this.coolingDown() === false) { await this.reload() return super.getKey(protectedHeader, token) } } throw err } } async reload() { // see https://github.com/panva/jose/issues/355 if (this._pendingFetch && isCloudflareWorkers()) { return new Promise((resolve) => { const isDone = () => { if (this._pendingFetch === undefined) { resolve() } else { setTimeout(isDone, 5) } } isDone() }) } if (!this._pendingFetch) { this._pendingFetch = fetchJwks(this._url, this._timeoutDuration, this._options) .then((json) => { if (!isJWKSLike(json)) { throw new JWKSInvalid('JSON Web Key Set malformed') } this._jwks = { keys: json.keys } this._jwksTimestamp = Date.now() this._pendingFetch = undefined }) .catch((err: Error) => { this._pendingFetch = undefined throw err }) } await this._pendingFetch } } /** * Returns a function that resolves to a key object downloaded from a remote endpoint returning a * JSON Web Key Set, that is, for example, an OAuth 2.0 or OIDC jwks_uri. Only a single public key * must match the selection process. The JSON Web Key Set is fetched when no key matches the * selection process but only as frequently as the `cooldownDuration` option allows, to prevent * abuse. * * @example Usage * * ```js * const JWKS = jose.createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs')) * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, JWKS, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * console.log(protectedHeader) * console.log(payload) * ``` * * @param url URL to fetch the JSON Web Key Set from. * @param options Options for the remote JSON Web Key Set. */ export function createRemoteJWKSet( url: URL, options?: RemoteJWKSetOptions, ): GetKeyFunction { return RemoteJWKSet.prototype.getKey.bind(new RemoteJWKSet(url, options)) } jose-4.11.4/dist/deno/jws/000077500000000000000000000000001437043056600152445ustar00rootroot00000000000000jose-4.11.4/dist/deno/jws/compact/000077500000000000000000000000001437043056600166725ustar00rootroot00000000000000jose-4.11.4/dist/deno/jws/compact/sign.ts000066400000000000000000000027321437043056600202060ustar00rootroot00000000000000import { FlattenedSign } from '../flattened/sign.ts' import type { CompactJWSHeaderParameters, KeyLike, SignOptions } from '../../types.d.ts' /** * The CompactSign class is a utility for creating Compact JWS strings. * * @example Usage * * ```js * const jws = await new jose.CompactSign( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .setProtectedHeader({ alg: 'ES256' }) * .sign(privateKey) * * console.log(jws) * ``` */ export class CompactSign { private _flattened: FlattenedSign /** @param payload Binary representation of the payload to sign. */ constructor(payload: Uint8Array) { this._flattened = new FlattenedSign(payload) } /** * Sets the JWS Protected Header on the Sign object. * * @param protectedHeader JWS Protected Header. */ setProtectedHeader(protectedHeader: CompactJWSHeaderParameters) { this._flattened.setProtectedHeader(protectedHeader) return this } /** * Signs and resolves the value of the Compact JWS string. * * @param key Private Key or Secret to sign the JWS with. * @param options JWS Sign options. */ async sign(key: KeyLike | Uint8Array, options?: SignOptions): Promise { const jws = await this._flattened.sign(key, options) if (jws.payload === undefined) { throw new TypeError('use the flattened module for creating JWS with b64: false') } return `${jws.protected}.${jws.payload}.${jws.signature}` } } jose-4.11.4/dist/deno/jws/compact/verify.ts000066400000000000000000000051421437043056600205500ustar00rootroot00000000000000import { flattenedVerify } from '../flattened/verify.ts' import { JWSInvalid } from '../../util/errors.ts' import { decoder } from '../../lib/buffer_utils.ts' import type { CompactVerifyResult, FlattenedJWSInput, GetKeyFunction, CompactJWSHeaderParameters, KeyLike, VerifyOptions, ResolvedKey, } from '../../types.d.ts' /** * Interface for Compact JWS Verification dynamic key resolution. No token components have been * verified at the time of this function call. * * See * [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) * to verify using a remote JSON Web Key Set. */ export interface CompactVerifyGetKey extends GetKeyFunction {} /** * Verifies the signature and format of and afterwards decodes the Compact JWS. * * @example Usage * * ```js * const jws = * 'eyJhbGciOiJFUzI1NiJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4.kkAs_gPPxWMI3rHuVlxHaTPfDWDoqdI8jSvuSmqV-8IHIWXg9mcAeC9ggV-45ZHRbiRJ3obUIFo1rHphPA5URg' * * const { payload, protectedHeader } = await jose.compactVerify(jws, publicKey) * * console.log(protectedHeader) * console.log(new TextDecoder().decode(payload)) * ``` * * @param jws Compact JWS. * @param key Key to verify the JWS with. * @param options JWS Verify options. */ export function compactVerify( jws: string | Uint8Array, key: KeyLike | Uint8Array, options?: VerifyOptions, ): Promise /** * @param jws Compact JWS. * @param getKey Function resolving a key to verify the JWS with. * @param options JWS Verify options. */ export function compactVerify( jws: string | Uint8Array, getKey: CompactVerifyGetKey, options?: VerifyOptions, ): Promise export async function compactVerify( jws: string | Uint8Array, key: KeyLike | Uint8Array | CompactVerifyGetKey, options?: VerifyOptions, ) { if (jws instanceof Uint8Array) { jws = decoder.decode(jws) } if (typeof jws !== 'string') { throw new JWSInvalid('Compact JWS must be a string or Uint8Array') } const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.') if (length !== 3) { throw new JWSInvalid('Invalid Compact JWS') } const verified = await flattenedVerify( { payload, protected: protectedHeader, signature }, [1]>key, options, ) const result = { payload: verified.payload, protectedHeader: verified.protectedHeader! } if (typeof key === 'function') { return { ...result, key: verified.key } } return result } jose-4.11.4/dist/deno/jws/flattened/000077500000000000000000000000001437043056600172125ustar00rootroot00000000000000jose-4.11.4/dist/deno/jws/flattened/sign.ts000066400000000000000000000102331437043056600205210ustar00rootroot00000000000000import { encode as base64url } from '../../runtime/base64url.ts' import sign from '../../runtime/sign.ts' import isDisjoint from '../../lib/is_disjoint.ts' import { JWSInvalid } from '../../util/errors.ts' import { encoder, decoder, concat } from '../../lib/buffer_utils.ts' import type { KeyLike, FlattenedJWS, JWSHeaderParameters, SignOptions } from '../../types.d.ts' import checkKeyType from '../../lib/check_key_type.ts' import validateCrit from '../../lib/validate_crit.ts' /** * The FlattenedSign class is a utility for creating Flattened JWS objects. * * @example Usage * * ```js * const jws = await new jose.FlattenedSign( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .setProtectedHeader({ alg: 'ES256' }) * .sign(privateKey) * * console.log(jws) * ``` */ export class FlattenedSign { private _payload: Uint8Array private _protectedHeader!: JWSHeaderParameters private _unprotectedHeader!: JWSHeaderParameters /** @param payload Binary representation of the payload to sign. */ constructor(payload: Uint8Array) { if (!(payload instanceof Uint8Array)) { throw new TypeError('payload must be an instance of Uint8Array') } this._payload = payload } /** * Sets the JWS Protected Header on the FlattenedSign object. * * @param protectedHeader JWS Protected Header. */ setProtectedHeader(protectedHeader: JWSHeaderParameters) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once') } this._protectedHeader = protectedHeader return this } /** * Sets the JWS Unprotected Header on the FlattenedSign object. * * @param unprotectedHeader JWS Unprotected Header. */ setUnprotectedHeader(unprotectedHeader: JWSHeaderParameters) { if (this._unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once') } this._unprotectedHeader = unprotectedHeader return this } /** * Signs and resolves the value of the Flattened JWS object. * * @param key Private Key or Secret to sign the JWS with. * @param options JWS Sign options. */ async sign(key: KeyLike | Uint8Array, options?: SignOptions): Promise { if (!this._protectedHeader && !this._unprotectedHeader) { throw new JWSInvalid( 'either setProtectedHeader or setUnprotectedHeader must be called before #sign()', ) } if (!isDisjoint(this._protectedHeader, this._unprotectedHeader)) { throw new JWSInvalid( 'JWS Protected and JWS Unprotected Header Parameter names must be disjoint', ) } const joseHeader: JWSHeaderParameters = { ...this._protectedHeader, ...this._unprotectedHeader, } const extensions = validateCrit( JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader, ) let b64: boolean = true if (extensions.has('b64')) { b64 = this._protectedHeader.b64! if (typeof b64 !== 'boolean') { throw new JWSInvalid( 'The "b64" (base64url-encode payload) Header Parameter must be a boolean', ) } } const { alg } = joseHeader if (typeof alg !== 'string' || !alg) { throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid') } checkKeyType(alg, key, 'sign') let payload = this._payload if (b64) { payload = encoder.encode(base64url(payload)) } let protectedHeader: Uint8Array if (this._protectedHeader) { protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))) } else { protectedHeader = encoder.encode('') } const data = concat(protectedHeader, encoder.encode('.'), payload) const signature = await sign(alg, key, data) const jws: FlattenedJWS = { signature: base64url(signature), payload: '', } if (b64) { jws.payload = decoder.decode(payload) } if (this._unprotectedHeader) { jws.header = this._unprotectedHeader } if (this._protectedHeader) { jws.protected = decoder.decode(protectedHeader) } return jws } } jose-4.11.4/dist/deno/jws/flattened/verify.ts000066400000000000000000000132551437043056600210740ustar00rootroot00000000000000import { decode as base64url } from '../../runtime/base64url.ts' import verify from '../../runtime/verify.ts' import { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.ts' import { concat, encoder, decoder } from '../../lib/buffer_utils.ts' import isDisjoint from '../../lib/is_disjoint.ts' import isObject from '../../lib/is_object.ts' import checkKeyType from '../../lib/check_key_type.ts' import validateCrit from '../../lib/validate_crit.ts' import validateAlgorithms from '../../lib/validate_algorithms.ts' import type { FlattenedVerifyResult, KeyLike, FlattenedJWSInput, JWSHeaderParameters, VerifyOptions, GetKeyFunction, ResolvedKey, } from '../../types.d.ts' /** * Interface for Flattened JWS Verification dynamic key resolution. No token components have been * verified at the time of this function call. * * See * [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) * to verify using a remote JSON Web Key Set. */ export interface FlattenedVerifyGetKey extends GetKeyFunction {} /** * Verifies the signature and format of and afterwards decodes the Flattened JWS. * * @example Usage * * ```js * const decoder = new TextDecoder() * const jws = { * signature: * 'FVVOXwj6kD3DqdfD9yYqfT2W9jv-Nop4kOehp_DeDGNB5dQNSPRvntBY6xH3uxlCxE8na9d_kyhYOcanpDJ0EA', * payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4', * protected: 'eyJhbGciOiJFUzI1NiJ9', * } * * const { payload, protectedHeader } = await jose.flattenedVerify(jws, publicKey) * * console.log(protectedHeader) * console.log(decoder.decode(payload)) * ``` * * @param jws Flattened JWS. * @param key Key to verify the JWS with. * @param options JWS Verify options. */ export function flattenedVerify( jws: FlattenedJWSInput, key: KeyLike | Uint8Array, options?: VerifyOptions, ): Promise /** * @param jws Flattened JWS. * @param getKey Function resolving a key to verify the JWS with. * @param options JWS Verify options. */ export function flattenedVerify( jws: FlattenedJWSInput, getKey: FlattenedVerifyGetKey, options?: VerifyOptions, ): Promise export async function flattenedVerify( jws: FlattenedJWSInput, key: KeyLike | Uint8Array | FlattenedVerifyGetKey, options?: VerifyOptions, ) { if (!isObject(jws)) { throw new JWSInvalid('Flattened JWS must be an object') } if (jws.protected === undefined && jws.header === undefined) { throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members') } if (jws.protected !== undefined && typeof jws.protected !== 'string') { throw new JWSInvalid('JWS Protected Header incorrect type') } if (jws.payload === undefined) { throw new JWSInvalid('JWS Payload missing') } if (typeof jws.signature !== 'string') { throw new JWSInvalid('JWS Signature missing or incorrect type') } if (jws.header !== undefined && !isObject(jws.header)) { throw new JWSInvalid('JWS Unprotected Header incorrect type') } let parsedProt: JWSHeaderParameters = {} if (jws.protected) { try { const protectedHeader = base64url(jws.protected) parsedProt = JSON.parse(decoder.decode(protectedHeader)) } catch { throw new JWSInvalid('JWS Protected Header is invalid') } } if (!isDisjoint(parsedProt, jws.header)) { throw new JWSInvalid( 'JWS Protected and JWS Unprotected Header Parameter names must be disjoint', ) } const joseHeader: JWSHeaderParameters = { ...parsedProt, ...jws.header, } const extensions = validateCrit( JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader, ) let b64: boolean = true if (extensions.has('b64')) { b64 = parsedProt.b64! if (typeof b64 !== 'boolean') { throw new JWSInvalid( 'The "b64" (base64url-encode payload) Header Parameter must be a boolean', ) } } const { alg } = joseHeader if (typeof alg !== 'string' || !alg) { throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid') } const algorithms = options && validateAlgorithms('algorithms', options.algorithms) if (algorithms && !algorithms.has(alg)) { throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed') } if (b64) { if (typeof jws.payload !== 'string') { throw new JWSInvalid('JWS Payload must be a string') } } else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) { throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance') } let resolvedKey = false if (typeof key === 'function') { key = await key(parsedProt, jws) resolvedKey = true } checkKeyType(alg, key, 'verify') const data = concat( encoder.encode(jws.protected ?? ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload, ) const signature = base64url(jws.signature) const verified = await verify(alg, key, signature, data) if (!verified) { throw new JWSSignatureVerificationFailed() } let payload: Uint8Array if (b64) { payload = base64url(jws.payload) } else if (typeof jws.payload === 'string') { payload = encoder.encode(jws.payload) } else { payload = jws.payload } const result: FlattenedVerifyResult = { payload } if (jws.protected !== undefined) { result.protectedHeader = parsedProt } if (jws.header !== undefined) { result.unprotectedHeader = jws.header } if (resolvedKey) { return { ...result, key } } return result } jose-4.11.4/dist/deno/jws/general/000077500000000000000000000000001437043056600166615ustar00rootroot00000000000000jose-4.11.4/dist/deno/jws/general/sign.ts000066400000000000000000000100651437043056600201730ustar00rootroot00000000000000import { FlattenedSign } from '../flattened/sign.ts' import { JWSInvalid } from '../../util/errors.ts' import type { KeyLike, GeneralJWS, JWSHeaderParameters, SignOptions } from '../../types.d.ts' export interface Signature { /** * Sets the JWS Protected Header on the Signature object. * * @param protectedHeader JWS Protected Header. */ setProtectedHeader(protectedHeader: JWSHeaderParameters): Signature /** * Sets the JWS Unprotected Header on the Signature object. * * @param unprotectedHeader JWS Unprotected Header. */ setUnprotectedHeader(unprotectedHeader: JWSHeaderParameters): Signature /** A shorthand for calling addSignature() on the enclosing GeneralSign instance */ addSignature(...args: Parameters): Signature /** A shorthand for calling encrypt() on the enclosing GeneralSign instance */ sign(...args: Parameters): Promise /** Returns the enclosing GeneralSign */ done(): GeneralSign } class IndividualSignature implements Signature { private parent: GeneralSign protectedHeader?: JWSHeaderParameters unprotectedHeader?: JWSHeaderParameters options?: SignOptions key: KeyLike | Uint8Array constructor(sig: GeneralSign, key: KeyLike | Uint8Array, options?: SignOptions) { this.parent = sig this.key = key this.options = options } setProtectedHeader(protectedHeader: JWSHeaderParameters) { if (this.protectedHeader) { throw new TypeError('setProtectedHeader can only be called once') } this.protectedHeader = protectedHeader return this } setUnprotectedHeader(unprotectedHeader: JWSHeaderParameters) { if (this.unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once') } this.unprotectedHeader = unprotectedHeader return this } addSignature(...args: Parameters) { return this.parent.addSignature(...args) } sign(...args: Parameters) { return this.parent.sign(...args) } done() { return this.parent } } /** * The GeneralSign class is a utility for creating General JWS objects. * * @example Usage * * ```js * const jws = await new jose.GeneralSign( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .addSignature(ecPrivateKey) * .setProtectedHeader({ alg: 'ES256' }) * .addSignature(rsaPrivateKey) * .setProtectedHeader({ alg: 'PS256' }) * .sign() * * console.log(jws) * ``` */ export class GeneralSign { private _payload: Uint8Array private _signatures: IndividualSignature[] = [] /** @param payload Binary representation of the payload to sign. */ constructor(payload: Uint8Array) { this._payload = payload } /** * Adds an additional signature for the General JWS object. * * @param key Private Key or Secret to sign the individual JWS signature with. * @param options JWS Sign options. */ addSignature(key: KeyLike | Uint8Array, options?: SignOptions): Signature { const signature = new IndividualSignature(this, key, options) this._signatures.push(signature) return signature } /** Signs and resolves the value of the General JWS object. */ async sign(): Promise { if (!this._signatures.length) { throw new JWSInvalid('at least one signature must be added') } const jws: GeneralJWS = { signatures: [], payload: '', } for (let i = 0; i < this._signatures.length; i++) { const signature = this._signatures[i] const flattened = new FlattenedSign(this._payload) flattened.setProtectedHeader(signature.protectedHeader!) flattened.setUnprotectedHeader(signature.unprotectedHeader!) const { payload, ...rest } = await flattened.sign(signature.key, signature.options) if (i === 0) { jws.payload = payload } else if (jws.payload !== payload) { throw new JWSInvalid('inconsistent use of JWS Unencoded Payload Option (RFC7797)') } jws.signatures.push(rest) } return jws } } jose-4.11.4/dist/deno/jws/general/verify.ts000066400000000000000000000053071437043056600205420ustar00rootroot00000000000000import { flattenedVerify } from '../flattened/verify.ts' import type { GeneralJWSInput, GeneralVerifyResult, FlattenedJWSInput, GetKeyFunction, JWSHeaderParameters, KeyLike, VerifyOptions, ResolvedKey, } from '../../types.d.ts' import { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.ts' import isObject from '../../lib/is_object.ts' /** * Interface for General JWS Verification dynamic key resolution. No token components have been * verified at the time of this function call. * * See * [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) * to verify using a remote JSON Web Key Set. */ export interface GeneralVerifyGetKey extends GetKeyFunction {} /** * Verifies the signature and format of and afterwards decodes the General JWS. * * @example Usage * * ```js * const jws = { * payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4', * signatures: [ * { * signature: * 'FVVOXwj6kD3DqdfD9yYqfT2W9jv-Nop4kOehp_DeDGNB5dQNSPRvntBY6xH3uxlCxE8na9d_kyhYOcanpDJ0EA', * protected: 'eyJhbGciOiJFUzI1NiJ9', * }, * ], * } * * const { payload, protectedHeader } = await jose.generalVerify(jws, publicKey) * * console.log(protectedHeader) * console.log(new TextDecoder().decode(payload)) * ``` * * @param jws General JWS. * @param key Key to verify the JWS with. * @param options JWS Verify options. */ export function generalVerify( jws: GeneralJWSInput, key: KeyLike | Uint8Array, options?: VerifyOptions, ): Promise /** * @param jws General JWS. * @param getKey Function resolving a key to verify the JWS with. * @param options JWS Verify options. */ export function generalVerify( jws: GeneralJWSInput, getKey: GeneralVerifyGetKey, options?: VerifyOptions, ): Promise export async function generalVerify( jws: GeneralJWSInput, key: KeyLike | Uint8Array | GeneralVerifyGetKey, options?: VerifyOptions, ) { if (!isObject(jws)) { throw new JWSInvalid('General JWS must be an object') } if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) { throw new JWSInvalid('JWS Signatures missing or incorrect type') } for (const signature of jws.signatures) { try { return await flattenedVerify( { header: signature.header, payload: jws.payload, protected: signature.protected, signature: signature.signature, }, [1]>key, options, ) } catch { // } } throw new JWSSignatureVerificationFailed() } jose-4.11.4/dist/deno/jwt/000077500000000000000000000000001437043056600152455ustar00rootroot00000000000000jose-4.11.4/dist/deno/jwt/decrypt.ts000066400000000000000000000066541437043056600173020ustar00rootroot00000000000000import { compactDecrypt } from '../jwe/compact/decrypt.ts' import type { KeyLike, DecryptOptions, JWTClaimVerificationOptions, GetKeyFunction, CompactJWEHeaderParameters, FlattenedJWE, JWTDecryptResult, ResolvedKey, } from '../types.d.ts' import jwtPayload from '../lib/jwt_claims_set.ts' import { JWTClaimValidationFailed } from '../util/errors.ts' /** Combination of JWE Decryption options and JWT Claims Set verification options. */ export interface JWTDecryptOptions extends DecryptOptions, JWTClaimVerificationOptions {} /** * Interface for JWT Decryption dynamic key resolution. No token components have been verified at * the time of this function call. */ export interface JWTDecryptGetKey extends GetKeyFunction {} /** * Verifies the JWT format (to be a JWE Compact format), decrypts the ciphertext, validates the JWT * Claims Set. * * @example Usage * * ```js * const secret = jose.base64url.decode('zH4NRP1HMALxxCFnRZABFA7GOJtzU_gIj02alfL1lvI') * const jwt = * 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..MB66qstZBPxAXKdsjet_lA.WHbtJTl4taHp7otOHLq3hBvv0yNPsPEKHYInmCPdDDeyV1kU-f-tGEiU4FxlSqkqAT2hVs8_wMNiQFAzPU1PUgIqWCPsBrPP3TtxYsrtwagpn4SvCsUsx0Mhw9ZhliAO8CLmCBQkqr_T9AcYsz5uZw.7nX9m7BGUu_u1p1qFHzyIg' * * const { payload, protectedHeader } = await jose.jwtDecrypt(jwt, secret, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(protectedHeader) * console.log(payload) * ``` * * @param jwt JSON Web Token value (encoded as JWE). * @param key Private Key or Secret to decrypt and verify the JWT with. * @param options JWT Decryption and JWT Claims Set validation options. */ export async function jwtDecrypt( jwt: string | Uint8Array, key: KeyLike | Uint8Array, options?: JWTDecryptOptions, ): Promise /** * @param jwt JSON Web Token value (encoded as JWE). * @param getKey Function resolving Private Key or Secret to decrypt and verify the JWT with. * @param options JWT Decryption and JWT Claims Set validation options. */ export async function jwtDecrypt( jwt: string | Uint8Array, getKey: JWTDecryptGetKey, options?: JWTDecryptOptions, ): Promise export async function jwtDecrypt( jwt: string | Uint8Array, key: KeyLike | Uint8Array | JWTDecryptGetKey, options?: JWTDecryptOptions, ) { const decrypted = await compactDecrypt(jwt, [1]>key, options) const payload = jwtPayload(decrypted.protectedHeader, decrypted.plaintext, options) const { protectedHeader } = decrypted if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) { throw new JWTClaimValidationFailed( 'replicated "iss" claim header parameter mismatch', 'iss', 'mismatch', ) } if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) { throw new JWTClaimValidationFailed( 'replicated "sub" claim header parameter mismatch', 'sub', 'mismatch', ) } if ( protectedHeader.aud !== undefined && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud) ) { throw new JWTClaimValidationFailed( 'replicated "aud" claim header parameter mismatch', 'aud', 'mismatch', ) } const result = { payload, protectedHeader } if (typeof key === 'function') { return { ...result, key: decrypted.key } } return result } jose-4.11.4/dist/deno/jwt/encrypt.ts000066400000000000000000000122161437043056600173030ustar00rootroot00000000000000import { CompactEncrypt } from '../jwe/compact/encrypt.ts' import type { EncryptOptions, CompactJWEHeaderParameters, JWEKeyManagementHeaderParameters, KeyLike, } from '../types.d.ts' import { encoder } from '../lib/buffer_utils.ts' import { ProduceJWT } from './produce.ts' /** * The EncryptJWT class is a utility for creating Compact JWE formatted JWT strings. * * @example Usage * * ```js * const secret = jose.base64url.decode('zH4NRP1HMALxxCFnRZABFA7GOJtzU_gIj02alfL1lvI') * const jwt = await new jose.EncryptJWT({ 'urn:example:claim': true }) * .setProtectedHeader({ alg: 'dir', enc: 'A128CBC-HS256' }) * .setIssuedAt() * .setIssuer('urn:example:issuer') * .setAudience('urn:example:audience') * .setExpirationTime('2h') * .encrypt(secret) * * console.log(jwt) * ``` */ export class EncryptJWT extends ProduceJWT { private _cek!: Uint8Array private _iv!: Uint8Array private _keyManagementParameters!: JWEKeyManagementHeaderParameters private _protectedHeader!: CompactJWEHeaderParameters private _replicateIssuerAsHeader!: boolean private _replicateSubjectAsHeader!: boolean private _replicateAudienceAsHeader!: boolean /** * Sets the JWE Protected Header on the EncryptJWT object. * * @param protectedHeader JWE Protected Header. Must contain an "alg" (JWE Algorithm) and "enc" * (JWE Encryption Algorithm) properties. */ setProtectedHeader(protectedHeader: CompactJWEHeaderParameters) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once') } this._protectedHeader = protectedHeader return this } /** * Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is * really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or * Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed * and missing. * * @param parameters JWE Key Management parameters. */ setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters) { if (this._keyManagementParameters) { throw new TypeError('setKeyManagementParameters can only be called once') } this._keyManagementParameters = parameters return this } /** * Sets a content encryption key to use, by default a random suitable one is generated for the JWE * enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param cek JWE Content Encryption Key. */ setContentEncryptionKey(cek: Uint8Array) { if (this._cek) { throw new TypeError('setContentEncryptionKey can only be called once') } this._cek = cek return this } /** * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param iv JWE Initialization Vector. */ setInitializationVector(iv: Uint8Array) { if (this._iv) { throw new TypeError('setInitializationVector can only be called once') } this._iv = iv return this } /** * Replicates the "iss" (Issuer) Claim as a JWE Protected Header Parameter as per * [RFC7519#section-5.3](https://www.rfc-editor.org/rfc/rfc7519#section-5.3). */ replicateIssuerAsHeader() { this._replicateIssuerAsHeader = true return this } /** * Replicates the "sub" (Subject) Claim as a JWE Protected Header Parameter as per * [RFC7519#section-5.3](https://www.rfc-editor.org/rfc/rfc7519#section-5.3). */ replicateSubjectAsHeader() { this._replicateSubjectAsHeader = true return this } /** * Replicates the "aud" (Audience) Claim as a JWE Protected Header Parameter as per * [RFC7519#section-5.3](https://www.rfc-editor.org/rfc/rfc7519#section-5.3). */ replicateAudienceAsHeader() { this._replicateAudienceAsHeader = true return this } /** * Encrypts and returns the JWT. * * @param key Public Key or Secret to encrypt the JWT with. * @param options JWE Encryption options. */ async encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions): Promise { const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload))) if (this._replicateIssuerAsHeader) { this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss } } if (this._replicateSubjectAsHeader) { this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub } } if (this._replicateAudienceAsHeader) { this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud } } enc.setProtectedHeader(this._protectedHeader) if (this._iv) { enc.setInitializationVector(this._iv) } if (this._cek) { enc.setContentEncryptionKey(this._cek) } if (this._keyManagementParameters) { enc.setKeyManagementParameters(this._keyManagementParameters) } return enc.encrypt(key, options) } } jose-4.11.4/dist/deno/jwt/produce.ts000066400000000000000000000055231437043056600172630ustar00rootroot00000000000000import type { JWTPayload } from '../types.d.ts' import epoch from '../lib/epoch.ts' import isObject from '../lib/is_object.ts' import secs from '../lib/secs.ts' /** Generic class for JWT producing. */ export class ProduceJWT { protected _payload!: JWTPayload /** @param payload The JWT Claims Set object. */ constructor(payload: JWTPayload) { if (!isObject(payload)) { throw new TypeError('JWT Claims Set MUST be an object') } this._payload = payload } /** * Set "iss" (Issuer) Claim. * * @param issuer "Issuer" Claim value to set on the JWT Claims Set. */ setIssuer(issuer: string) { this._payload = { ...this._payload, iss: issuer } return this } /** * Set "sub" (Subject) Claim. * * @param subject "sub" (Subject) Claim value to set on the JWT Claims Set. */ setSubject(subject: string) { this._payload = { ...this._payload, sub: subject } return this } /** * Set "aud" (Audience) Claim. * * @param audience "aud" (Audience) Claim value to set on the JWT Claims Set. */ setAudience(audience: string | string[]) { this._payload = { ...this._payload, aud: audience } return this } /** * Set "jti" (JWT ID) Claim. * * @param jwtId "jti" (JWT ID) Claim value to set on the JWT Claims Set. */ setJti(jwtId: string) { this._payload = { ...this._payload, jti: jwtId } return this } /** * Set "nbf" (Not Before) Claim. * * @param input "nbf" (Not Before) Claim value to set on the JWT Claims Set. When number is passed * that is used as a value, when string is passed it is resolved to a time span and added to the * current timestamp. */ setNotBefore(input: number | string) { if (typeof input === 'number') { this._payload = { ...this._payload, nbf: input } } else { this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) } } return this } /** * Set "exp" (Expiration Time) Claim. * * @param input "exp" (Expiration Time) Claim value to set on the JWT Claims Set. When number is * passed that is used as a value, when string is passed it is resolved to a time span and added * to the current timestamp. */ setExpirationTime(input: number | string) { if (typeof input === 'number') { this._payload = { ...this._payload, exp: input } } else { this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) } } return this } /** * Set "iat" (Issued At) Claim. * * @param input "iat" (Issued At) Claim value to set on the JWT Claims Set. Default is current * timestamp. */ setIssuedAt(input?: number) { if (typeof input === 'undefined') { this._payload = { ...this._payload, iat: epoch(new Date()) } } else { this._payload = { ...this._payload, iat: input } } return this } } jose-4.11.4/dist/deno/jwt/sign.ts000066400000000000000000000141571437043056600165650ustar00rootroot00000000000000import { CompactSign } from '../jws/compact/sign.ts' import { JWTInvalid } from '../util/errors.ts' import type { JWTHeaderParameters, KeyLike, SignOptions } from '../types.d.ts' import { encoder } from '../lib/buffer_utils.ts' import { ProduceJWT } from './produce.ts' /** * The SignJWT class is a utility for creating Compact JWS formatted JWT strings. * * @example Usage with a symmetric secret * * ```js * const secret = new TextEncoder().encode( * 'cc7e0d44fd473002f1c42167459001140ec6389b7353f8088f4d9a95f2f596f2', * ) * const alg = 'HS256' * * const jwt = await new jose.SignJWT({ 'urn:example:claim': true }) * .setProtectedHeader({ alg }) * .setIssuedAt() * .setIssuer('urn:example:issuer') * .setAudience('urn:example:audience') * .setExpirationTime('2h') * .sign(secret) * * console.log(jwt) * ``` * * @example Usage with a private PKCS#8 encoded RSA key * * ```js * const alg = 'RS256' * const pkcs8 = `-----BEGIN PRIVATE KEY----- * MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDCFg4UrY5xtulv * /NXKmL1J4qI1SopAfTNMo3X7p+kJO7plqUYjzaztcre1qfh0m33Sm1Q8oPbO/GpP * MU1/HgcceytgJ/b4UwufVVMl9BrMDYG8moDBylbVupFQS3Ly1L9i/iFG9Z9A9xzY * Zzf799A45bnvNXL6s2glzvjiRvfQ2NDF0anTcnZLcYtC7ugq1IMM+ihAcPfw8Qw2 * chN/SmP4qAM+PKaQwagmU7doqmmyN9u38AfoYZ1GCFhEs5TBBT6H6h9YdHeVtiIq * 1c+fl03biSIfLrV7dUBD39gBmXBcL/30Ya3D82mCEUC4zg/UkOfQOmkmV3Lc8YUL * QZ8EJkBLAgMBAAECggEAVuVE/KEP6323WjpbBdAIv7HGahGrgGANvbxZsIhm34ls * VOPK0XDegZkhAybMZHjRhp+gwVxX5ChC+J3cUpOBH5FNxElgW6HizD2Jcq6t6LoL * YgPSrfEHm71iHg8JsgrqfUnGYFzMJmv88C6WdCtpgG/qJV1K00/Ly1G1QKoBffEs * +v4fAMJrCbUdCz1qWto+PU+HLMEo+krfEpGgcmtZeRlDADh8cETMQlgQfQX2VWq/ * aAP4a1SXmo+j0cvRU4W5Fj0RVwNesIpetX2ZFz4p/JmB5sWFEj/fC7h5z2lq+6Bm * e2T3BHtXkIxoBW0/pYVnASC8P2puO5FnVxDmWuHDYQKBgQDTuuBd3+0tSFVEX+DU * 5qpFmHm5nyGItZRJTS+71yg5pBxq1KqNCUjAtbxR0q//fwauakh+BwRVCPOrqsUG * jBSb3NYE70Srp6elqxgkE54PwQx4Mr6exJPnseM9U4K+hULllf5yjM9edreJE1nV * NVgFjeyafQhrHKwgr7PERJ/ikwKBgQDqqsT1M+EJLmI1HtCspOG6cu7q3gf/wKRh * E8tu84i3YyBnI8uJkKy92RNVI5fvpBARe3tjSdM25rr2rcrcmF/5g6Q9ImxZPGCt * 86eOgO9ErNtbc4TEgybsP319UE4O41aKeNiBTAZKoYCxv/dMqG0j4avmWzd+foHq * gSNUvR2maQKBgQCYeqOsV2B6VPY7KIVFLd0AA9/dwvEmgAYLiA/RShDI+hwQ/5jX * uxDu37KAhqeC65sHLrmIMUt4Zdr+DRyZK3aIDNEAesPMjw/X6lCXYp1ZISD2yyym * MFGH8X8CIkstI9Faf9vf6PJKSFrC1/HA7wq17VCwrUzLvrljTMW8meM/CwKBgCpo * 2leGHLFQFKeM/iF1WuYbR1pi7gcmhY6VyTowARFDdOOu8GXYI5/bz0afvCGvAMho * DJCREv7lC/zww6zCTPYG+HOj+PjXlJFba3ixjIxYwPvyEJiDK1Ge18sB7Fl8dHNq * C5ayaqCqN1voWYUdGzxU2IA1E/5kVo5O8FesJeOhAoGBAImJbZFf+D5kA32Xxhac * 59lLWBCsocvvbd1cvDMNlRywAAyhsCb1SuX4nEAK9mrSBdfmoF2Nm3eilfsOds0f * K5mX069IKG82CMqh3Mzptd7e7lyb9lsoGO0BAtjho3cWtha/UZ70vfaMzGuZ6JmQ * ak6k+8+UFd93M4z0Qo74OhXB * -----END PRIVATE KEY----` * const privateKey = await jose.importPKCS8(pkcs8, alg) * * const jwt = await new jose.SignJWT({ 'urn:example:claim': true }) * .setProtectedHeader({ alg }) * .setIssuedAt() * .setIssuer('urn:example:issuer') * .setAudience('urn:example:audience') * .setExpirationTime('2h') * .sign(privateKey) * * console.log(jwt) * ``` * * @example Usage with a private JWK encoded RSA key * * ```js * const alg = 'RS256' * const jwk = { * kty: 'RSA', * n: 'whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw', * e: 'AQAB', * d: 'VuVE_KEP6323WjpbBdAIv7HGahGrgGANvbxZsIhm34lsVOPK0XDegZkhAybMZHjRhp-gwVxX5ChC-J3cUpOBH5FNxElgW6HizD2Jcq6t6LoLYgPSrfEHm71iHg8JsgrqfUnGYFzMJmv88C6WdCtpgG_qJV1K00_Ly1G1QKoBffEs-v4fAMJrCbUdCz1qWto-PU-HLMEo-krfEpGgcmtZeRlDADh8cETMQlgQfQX2VWq_aAP4a1SXmo-j0cvRU4W5Fj0RVwNesIpetX2ZFz4p_JmB5sWFEj_fC7h5z2lq-6Bme2T3BHtXkIxoBW0_pYVnASC8P2puO5FnVxDmWuHDYQ', * p: '07rgXd_tLUhVRF_g1OaqRZh5uZ8hiLWUSU0vu9coOaQcatSqjQlIwLW8UdKv_38GrmpIfgcEVQjzq6rFBowUm9zWBO9Eq6enpasYJBOeD8EMeDK-nsST57HjPVOCvoVC5ZX-cozPXna3iRNZ1TVYBY3smn0IaxysIK-zxESf4pM', * q: '6qrE9TPhCS5iNR7QrKThunLu6t4H_8CkYRPLbvOIt2MgZyPLiZCsvdkTVSOX76QQEXt7Y0nTNua69q3K3Jhf-YOkPSJsWTxgrfOnjoDvRKzbW3OExIMm7D99fVBODuNWinjYgUwGSqGAsb_3TKhtI-Gr5ls3fn6B6oEjVL0dpmk', * dp: 'mHqjrFdgelT2OyiFRS3dAAPf3cLxJoAGC4gP0UoQyPocEP-Y17sQ7t-ygIanguubBy65iDFLeGXa_g0cmSt2iAzRAHrDzI8P1-pQl2KdWSEg9ssspjBRh_F_AiJLLSPRWn_b3-jySkhawtfxwO8Kte1QsK1My765Y0zFvJnjPws', * dq: 'KmjaV4YcsVAUp4z-IXVa5htHWmLuByaFjpXJOjABEUN0467wZdgjn9vPRp-8Ia8AyGgMkJES_uUL_PDDrMJM9gb4c6P4-NeUkVtreLGMjFjA-_IQmIMrUZ7XywHsWXx0c2oLlrJqoKo3W-hZhR0bPFTYgDUT_mRWjk7wV6wl46E', * qi: 'iYltkV_4PmQDfZfGFpzn2UtYEKyhy-9t3Vy8Mw2VHLAADKGwJvVK5ficQAr2atIF1-agXY2bd6KV-w52zR8rmZfTr0gobzYIyqHczOm13t7uXJv2WygY7QEC2OGjdxa2Fr9RnvS99ozMa5nomZBqTqT7z5QV33czjPRCjvg6FcE', * } * const privateKey = await jose.importJWK(jwk, alg) * * const jwt = await new jose.SignJWT({ 'urn:example:claim': true }) * .setProtectedHeader({ alg }) * .setIssuedAt() * .setIssuer('urn:example:issuer') * .setAudience('urn:example:audience') * .setExpirationTime('2h') * .sign(privateKey) * * console.log(jwt) * ``` */ export class SignJWT extends ProduceJWT { private _protectedHeader!: JWTHeaderParameters /** * Sets the JWS Protected Header on the SignJWT object. * * @param protectedHeader JWS Protected Header. Must contain an "alg" (JWS Algorithm) property. */ setProtectedHeader(protectedHeader: JWTHeaderParameters) { this._protectedHeader = protectedHeader return this } /** * Signs and returns the JWT. * * @param key Private Key or Secret to sign the JWT with. * @param options JWT Sign options. */ async sign(key: KeyLike | Uint8Array, options?: SignOptions): Promise { const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload))) sig.setProtectedHeader(this._protectedHeader) if ( Array.isArray(this._protectedHeader?.crit) && this._protectedHeader.crit.includes('b64') && // @ts-expect-error this._protectedHeader.b64 === false ) { throw new JWTInvalid('JWTs MUST NOT use unencoded payload') } return sig.sign(key, options) } } jose-4.11.4/dist/deno/jwt/unsecured.ts000066400000000000000000000042511437043056600176140ustar00rootroot00000000000000import * as base64url from '../runtime/base64url.ts' import type { JWSHeaderParameters, JWTClaimVerificationOptions, JWTPayload } from '../types.d.ts' import { decoder } from '../lib/buffer_utils.ts' import { JWTInvalid } from '../util/errors.ts' import jwtPayload from '../lib/jwt_claims_set.ts' import { ProduceJWT } from './produce.ts' export interface UnsecuredResult { payload: JWTPayload header: JWSHeaderParameters } /** * The UnsecuredJWT class is a utility for dealing with `{ "alg": "none" }` Unsecured JWTs. * * @example Encoding * * ```js * const unsecuredJwt = new jose.UnsecuredJWT({ 'urn:example:claim': true }) * .setIssuedAt() * .setIssuer('urn:example:issuer') * .setAudience('urn:example:audience') * .setExpirationTime('2h') * .encode() * * console.log(unsecuredJwt) * ``` * * @example Decoding * * ```js * const payload = jose.UnsecuredJWT.decode(jwt, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(payload) * ``` */ export class UnsecuredJWT extends ProduceJWT { /** Encodes the Unsecured JWT. */ encode(): string { const header = base64url.encode(JSON.stringify({ alg: 'none' })) const payload = base64url.encode(JSON.stringify(this._payload)) return `${header}.${payload}.` } /** * Decodes an unsecured JWT. * * @param jwt Unsecured JWT to decode the payload of. * @param options JWT Claims Set validation options. */ static decode(jwt: string, options?: JWTClaimVerificationOptions): UnsecuredResult { if (typeof jwt !== 'string') { throw new JWTInvalid('Unsecured JWT must be a string') } const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.') if (length !== 3 || signature !== '') { throw new JWTInvalid('Invalid Unsecured JWT') } let header: JWSHeaderParameters try { header = JSON.parse(decoder.decode(base64url.decode(encodedHeader))) if (header.alg !== 'none') throw new Error() } catch { throw new JWTInvalid('Invalid Unsecured JWT') } const payload = jwtPayload(header, base64url.decode(encodedPayload), options) return { payload, header } } } jose-4.11.4/dist/deno/jwt/verify.ts000066400000000000000000000137171437043056600171320ustar00rootroot00000000000000import { compactVerify } from '../jws/compact/verify.ts' import type { KeyLike, VerifyOptions, JWTClaimVerificationOptions, JWTHeaderParameters, GetKeyFunction, FlattenedJWSInput, JWTVerifyResult, ResolvedKey, } from '../types.d.ts' import jwtPayload from '../lib/jwt_claims_set.ts' import { JWTInvalid } from '../util/errors.ts' /** Combination of JWS Verification options and JWT Claims Set verification options. */ export interface JWTVerifyOptions extends VerifyOptions, JWTClaimVerificationOptions {} /** * Interface for JWT Verification dynamic key resolution. No token components have been verified at * the time of this function call. * * See * [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) * to verify using a remote JSON Web Key Set. */ export interface JWTVerifyGetKey extends GetKeyFunction {} /** * Verifies the JWT format (to be a JWS Compact format), verifies the JWS signature, validates the * JWT Claims Set. * * @example Usage with a symmetric secret * * ```js * const secret = new TextEncoder().encode( * 'cc7e0d44fd473002f1c42167459001140ec6389b7353f8088f4d9a95f2f596f2', * ) * const jwt = * 'eyJhbGciOiJIUzI1NiJ9.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6dHJ1ZSwiaWF0IjoxNjY5MDU2MjMxLCJpc3MiOiJ1cm46ZXhhbXBsZTppc3N1ZXIiLCJhdWQiOiJ1cm46ZXhhbXBsZTphdWRpZW5jZSJ9.C4iSlLfAUMBq--wnC6VqD9gEOhwpRZpoRarE0m7KEnI' * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, secret, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(protectedHeader) * console.log(payload) * ``` * * @example Usage with a public SPKI encoded RSA key * * ```js * const alg = 'RS256' * const spki = `-----BEGIN PUBLIC KEY----- * MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwhYOFK2Ocbbpb/zVypi9 * SeKiNUqKQH0zTKN1+6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4H * HHsrYCf2+FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS/Yv4hRvWfQPcc2Gc3+/fQ * OOW57zVy+rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj * +KgDPjymkMGoJlO3aKppsjfbt/AH6GGdRghYRLOUwQU+h+ofWHR3lbYiKtXPn5dN * 24kiHy61e3VAQ9/YAZlwXC/99GGtw/NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZA * SwIDAQAB * -----END PUBLIC KEY-----` * const publicKey = await jose.importSPKI(spki, alg) * const jwt = * 'eyJhbGciOiJSUzI1NiJ9.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6dHJ1ZSwiaWF0IjoxNjY5MDU2NDg4LCJpc3MiOiJ1cm46ZXhhbXBsZTppc3N1ZXIiLCJhdWQiOiJ1cm46ZXhhbXBsZTphdWRpZW5jZSJ9.gXrPZ3yM_60dMXGE69dusbpzYASNA-XIOwsb5D5xYnSxyj6_D6OR_uR_1vqhUm4AxZxcrH1_-XJAve9HCw8az_QzHcN-nETt-v6stCsYrn6Bv1YOc-mSJRZ8ll57KVqLbCIbjKwerNX5r2_Qg2TwmJzQdRs-AQDhy-s_DlJd8ql6wR4n-kDZpar-pwIvz4fFIN0Fj57SXpAbLrV6Eo4Byzl0xFD8qEYEpBwjrMMfxCZXTlAVhAq6KCoGlDTwWuExps342-0UErEtyIqDnDGcrfNWiUsoo8j-29IpKd-w9-C388u-ChCxoHz--H8WmMSZzx3zTXsZ5lXLZ9IKfanDKg' * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, publicKey, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(protectedHeader) * console.log(payload) * ``` * * @example Usage with a public JWK encoded RSA key * * ```js * const alg = 'RS256' * const jwk = { * kty: 'RSA', * n: 'whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw', * e: 'AQAB', * } * const publicKey = await jose.importJWK(jwk, alg) * const jwt = * 'eyJhbGciOiJSUzI1NiJ9.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6dHJ1ZSwiaWF0IjoxNjY5MDU2NDg4LCJpc3MiOiJ1cm46ZXhhbXBsZTppc3N1ZXIiLCJhdWQiOiJ1cm46ZXhhbXBsZTphdWRpZW5jZSJ9.gXrPZ3yM_60dMXGE69dusbpzYASNA-XIOwsb5D5xYnSxyj6_D6OR_uR_1vqhUm4AxZxcrH1_-XJAve9HCw8az_QzHcN-nETt-v6stCsYrn6Bv1YOc-mSJRZ8ll57KVqLbCIbjKwerNX5r2_Qg2TwmJzQdRs-AQDhy-s_DlJd8ql6wR4n-kDZpar-pwIvz4fFIN0Fj57SXpAbLrV6Eo4Byzl0xFD8qEYEpBwjrMMfxCZXTlAVhAq6KCoGlDTwWuExps342-0UErEtyIqDnDGcrfNWiUsoo8j-29IpKd-w9-C388u-ChCxoHz--H8WmMSZzx3zTXsZ5lXLZ9IKfanDKg' * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, publicKey, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(protectedHeader) * console.log(payload) * ``` * * @param jwt JSON Web Token value (encoded as JWS). * @param key Key to verify the JWT with. * @param options JWT Decryption and JWT Claims Set validation options. */ export async function jwtVerify( jwt: string | Uint8Array, key: KeyLike | Uint8Array, options?: JWTVerifyOptions, ): Promise /** * @example Usage with a public JSON Web Key Set hosted on a remote URL * * ```js * const JWKS = jose.createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs')) * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, JWKS, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * console.log(protectedHeader) * console.log(payload) * ``` * * @param jwt JSON Web Token value (encoded as JWS). * @param getKey Function resolving a key to verify the JWT with. * @param options JWT Decryption and JWT Claims Set validation options. */ export async function jwtVerify( jwt: string | Uint8Array, getKey: JWTVerifyGetKey, options?: JWTVerifyOptions, ): Promise export async function jwtVerify( jwt: string | Uint8Array, key: KeyLike | Uint8Array | JWTVerifyGetKey, options?: JWTVerifyOptions, ) { const verified = await compactVerify(jwt, [1]>key, options) if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) { throw new JWTInvalid('JWTs MUST NOT use unencoded payload') } const payload = jwtPayload(verified.protectedHeader, verified.payload, options) const result = { payload, protectedHeader: verified.protectedHeader } if (typeof key === 'function') { return { ...result, key: verified.key } } return result } jose-4.11.4/dist/deno/key/000077500000000000000000000000001437043056600152315ustar00rootroot00000000000000jose-4.11.4/dist/deno/key/export.ts000066400000000000000000000027661437043056600171350ustar00rootroot00000000000000import { toSPKI as exportPublic } from '../runtime/asn1.ts' import { toPKCS8 as exportPrivate } from '../runtime/asn1.ts' import keyToJWK from '../runtime/key_to_jwk.ts' import type { JWK, KeyLike } from '../types.d.ts' /** * Exports a runtime-specific public key representation (KeyObject or CryptoKey) to a PEM-encoded * SPKI string format. * * @example Usage * * ```js * const spkiPem = await jose.exportSPKI(publicKey) * * console.log(spkiPem) * ``` * * @param key Key representation to transform to a PEM-encoded SPKI string format. */ export async function exportSPKI(key: KeyLike): Promise { return exportPublic(key) } /** * Exports a runtime-specific private key representation (KeyObject or CryptoKey) to a PEM-encoded * PKCS8 string format. * * @example Usage * * ```js * const pkcs8Pem = await jose.exportPKCS8(privateKey) * * console.log(pkcs8Pem) * ``` * * @param key Key representation to transform to a PEM-encoded PKCS8 string format. */ export async function exportPKCS8(key: KeyLike): Promise { return exportPrivate(key) } /** * Exports a runtime-specific key representation (KeyLike) to a JWK. * * @example Usage * * ```js * const privateJwk = await jose.exportJWK(privateKey) * const publicJwk = await jose.exportJWK(publicKey) * * console.log(privateJwk) * console.log(publicJwk) * ``` * * @param key Key representation to export as JWK. */ export async function exportJWK(key: KeyLike | Uint8Array): Promise { return keyToJWK(key) } jose-4.11.4/dist/deno/key/generate_key_pair.ts000066400000000000000000000034331437043056600212610ustar00rootroot00000000000000import { generateKeyPair as generate } from '../runtime/generate.ts' import type { KeyLike } from '../types.d.ts' export interface GenerateKeyPairResult { /** The generated Private Key. */ privateKey: KeyLike /** Public Key corresponding to the generated Private Key. */ publicKey: KeyLike } export interface GenerateKeyPairOptions { /** * The EC "crv" (Curve) or OKP "crv" (Subtype of Key Pair) value to generate. The curve must be * both supported on the runtime as well as applicable for the given JWA algorithm identifier. */ crv?: string /** * A hint for RSA algorithms to generate an RSA key of a given `modulusLength` (Key size in bits). * JOSE requires 2048 bits or larger. Default is 2048. */ modulusLength?: number /** * (Web Cryptography API specific) The value to use as * [SubtleCrypto.generateKey()](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey) * `extractable` argument. Default is false. */ extractable?: boolean } /** * Generates a private and a public key for a given JWA algorithm identifier. This can only generate * asymmetric key pairs. For symmetric secrets use the `generateSecret` function. * * Note: Under Web Cryptography API runtime the `privateKey` is generated with `extractable` set to * `false` by default. * * @example Usage * * ```js * const { publicKey, privateKey } = await jose.generateKeyPair('PS256') * console.log(publicKey) * console.log(privateKey) * ``` * * @param alg JWA Algorithm Identifier to be used with the generated key pair. * @param options Additional options passed down to the key pair generation. */ export async function generateKeyPair( alg: string, options?: GenerateKeyPairOptions, ): Promise { return generate(alg, options) } jose-4.11.4/dist/deno/key/generate_secret.ts000066400000000000000000000020221437043056600207340ustar00rootroot00000000000000import { generateSecret as generate } from '../runtime/generate.ts' import type { KeyLike } from '../types.d.ts' export interface GenerateSecretOptions { /** * (Web Cryptography API specific) The value to use as * [SubtleCrypto.generateKey()](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey) * `extractable` argument. Default is false. */ extractable?: boolean } /** * Generates a symmetric secret key for a given JWA algorithm identifier. * * Note: Under Web Cryptography API runtime the secret key is generated with `extractable` set to * `false` by default. * * @example Usage * * ```js * const secret = await jose.generateSecret('HS256') * console.log(secret) * ``` * * @param alg JWA Algorithm Identifier to be used with the generated secret. * @param options Additional options passed down to the secret generation. */ export async function generateSecret( alg: string, options?: GenerateSecretOptions, ): Promise { return generate(alg, options) } jose-4.11.4/dist/deno/key/import.ts000066400000000000000000000215161437043056600171200ustar00rootroot00000000000000import { decode as decodeBase64URL, encodeBase64, decodeBase64 } from '../runtime/base64url.ts' import { fromSPKI as importPublic } from '../runtime/asn1.ts' import { fromPKCS8 as importPrivate } from '../runtime/asn1.ts' import asKeyObject from '../runtime/jwk_to_key.ts' import { JOSENotSupported } from '../util/errors.ts' import formatPEM from '../lib/format_pem.ts' import isObject from '../lib/is_object.ts' import type { JWK, KeyLike } from '../types.d.ts' function getElement(seq: Uint8Array) { let result = [] let next = 0 while (next < seq.length) { let nextPart = parseElement(seq.subarray(next)) result.push(nextPart) next += nextPart.byteLength } return result } function parseElement(bytes: Uint8Array) { let position = 0 // tag let tag = bytes[0] & 0x1f position++ if (tag === 0x1f) { tag = 0 while (bytes[position] >= 0x80) { tag = tag * 128 + bytes[position] - 0x80 position++ } tag = tag * 128 + bytes[position] - 0x80 position++ } // length let length = 0 if (bytes[position] < 0x80) { length = bytes[position] position++ } else if (length === 0x80) { length = 0 while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) { if (length > bytes.byteLength) { throw new TypeError('invalid indefinite form length') } length++ } const byteLength = position + length + 2 return { byteLength, contents: bytes.subarray(position, position + length), raw: bytes.subarray(0, byteLength), } } else { let numberOfDigits = bytes[position] & 0x7f position++ length = 0 for (let i = 0; i < numberOfDigits; i++) { length = length * 256 + bytes[position] position++ } } const byteLength = position + length return { byteLength, contents: bytes.subarray(position, byteLength), raw: bytes.subarray(0, byteLength), } } function spkiFromX509(buf: Uint8Array) { const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents) return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw) } function getSPKI(x509: string): string { const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, '') const raw = decodeBase64(pem) return formatPEM(spkiFromX509(raw), 'PUBLIC KEY') } export interface PEMImportOptions { /** * (Web Cryptography API specific) The value to use as * [SubtleCrypto.importKey()](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey) * `extractable` argument. Default is false. */ extractable?: boolean } /** * Imports a PEM-encoded SPKI string as a runtime-specific public key representation (KeyObject or * CryptoKey). See [Algorithm Key Requirements](https://github.com/panva/jose/issues/210) to learn * about key to algorithm requirements and mapping. * * @example Usage * * ```js * const algorithm = 'ES256' * const spki = `-----BEGIN PUBLIC KEY----- * MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFlHHWfLk0gLBbsLTcuCrbCqoHqmM * YJepMC+Q+Dd6RBmBiA41evUsNMwLeN+PNFqib+xwi9JkJ8qhZkq8Y/IzGg== * -----END PUBLIC KEY-----` * const ecPublicKey = await jose.importSPKI(spki, algorithm) * ``` * * @param pem PEM-encoded SPKI string * @param alg JSON Web Algorithm identifier to be used with the imported key. */ export async function importSPKI( spki: string, alg: string, options?: PEMImportOptions, ): Promise { if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) { throw new TypeError('"spki" must be SPKI formatted string') } return importPublic(spki, alg, options) } /** * Imports the SPKI from an X.509 string certificate as a runtime-specific public key representation * (KeyObject or CryptoKey). See [Algorithm Key * Requirements](https://github.com/panva/jose/issues/210) to learn about key to algorithm * requirements and mapping. * * @example Usage * * ```js * const algorithm = 'ES256' * const x509 = `-----BEGIN CERTIFICATE----- * MIIBXjCCAQSgAwIBAgIGAXvykuMKMAoGCCqGSM49BAMCMDYxNDAyBgNVBAMMK3Np * QXBNOXpBdk1VaXhXVWVGaGtjZXg1NjJRRzFyQUhXaV96UlFQTVpQaG8wHhcNMjEw * OTE3MDcwNTE3WhcNMjIwNzE0MDcwNTE3WjA2MTQwMgYDVQQDDCtzaUFwTTl6QXZN * VWl4V1VlRmhrY2V4NTYyUUcxckFIV2lfelJRUE1aUGhvMFkwEwYHKoZIzj0CAQYI * KoZIzj0DAQcDQgAE8PbPvCv5D5xBFHEZlBp/q5OEUymq7RIgWIi7tkl9aGSpYE35 * UH+kBKDnphJO3odpPZ5gvgKs2nwRWcrDnUjYLDAKBggqhkjOPQQDAgNIADBFAiEA * 1yyMTRe66MhEXID9+uVub7woMkNYd0LhSHwKSPMUUTkCIFQGsfm1ecXOpeGOufAh * v+A1QWZMuTWqYt+uh/YSRNDn * -----END CERTIFICATE-----` * const ecPublicKey = await jose.importX509(x509, algorithm) * ``` * * @param pem X.509 certificate string * @param alg JSON Web Algorithm identifier to be used with the imported key. */ export async function importX509( x509: string, alg: string, options?: PEMImportOptions, ): Promise { if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) { throw new TypeError('"x509" must be X.509 formatted string') } let spki: string try { spki = getSPKI(x509) } catch (cause) { // @ts-ignore throw new TypeError('failed to parse the X.509 certificate', { cause }) } return importPublic(spki, alg, options) } /** * Imports a PEM-encoded PKCS#8 string as a runtime-specific private key representation (KeyObject * or CryptoKey). See [Algorithm Key Requirements](https://github.com/panva/jose/issues/210) to * learn about key to algorithm requirements and mapping. Encrypted keys are not supported. * * @example Usage * * ```js * const algorithm = 'ES256' * const pkcs8 = `-----BEGIN PRIVATE KEY----- * MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgiyvo0X+VQ0yIrOaN * nlrnUclopnvuuMfoc8HHly3505OhRANCAAQWUcdZ8uTSAsFuwtNy4KtsKqgeqYxg * l6kwL5D4N3pEGYGIDjV69Sw0zAt43480WqJv7HCL0mQnyqFmSrxj8jMa * -----END PRIVATE KEY-----` * const ecPrivateKey = await jose.importPKCS8(pkcs8, algorithm) * ``` * * @param pem PEM-encoded PKCS#8 string * @param alg JSON Web Algorithm identifier to be used with the imported key. */ export async function importPKCS8( pkcs8: string, alg: string, options?: PEMImportOptions, ): Promise { if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) { throw new TypeError('"pkcs8" must be PKCS#8 formatted string') } return importPrivate(pkcs8, alg, options) } /** * Imports a JWK to a runtime-specific key representation (KeyLike). Either JWK "alg" (Algorithm) * Parameter must be present or the optional "alg" argument. When running on a runtime using [Web * Cryptography API](https://www.w3.org/TR/WebCryptoAPI/) the jwk parameters "use", "key_ops", and * "ext" are also used in the resulting `CryptoKey`. See [Algorithm Key * Requirements](https://github.com/panva/jose/issues/210) to learn about key to algorithm * requirements and mapping. * * @example Usage * * ```js * const ecPublicKey = await jose.importJWK( * { * crv: 'P-256', * kty: 'EC', * x: 'ySK38C1jBdLwDsNWKzzBHqKYEE5Cgv-qjWvorUXk9fw', * y: '_LeQBw07cf5t57Iavn4j-BqJsAD1dpoz8gokd3sBsOo', * }, * 'ES256', * ) * * const rsaPublicKey = await jose.importJWK( * { * kty: 'RSA', * e: 'AQAB', * n: '12oBZRhCiZFJLcPg59LkZZ9mdhSMTKAQZYq32k_ti5SBB6jerkh-WzOMAO664r_qyLkqHUSp3u5SbXtseZEpN3XPWGKSxjsy-1JyEFTdLSYe6f9gfrmxkUF_7DTpq0gn6rntP05g2-wFW50YO7mosfdslfrTJYWHFhJALabAeYirYD7-9kqq9ebfFMF4sRRELbv9oi36As6Q9B3Qb5_C1rAzqfao_PCsf9EPsTZsVVVkA5qoIAr47lo1ipfiBPxUCCNSdvkmDTYgvvRm6ZoMjFbvOtgyts55fXKdMWv7I9HMD5HwE9uW839PWA514qhbcIsXEYSFMPMV6fnlsiZvQQ', * }, * 'PS256', * ) * ``` * * @param jwk JSON Web Key. * @param alg JSON Web Algorithm identifier to be used with the imported key. Default is the "alg" * property on the JWK. * @param octAsKeyObject Forces a symmetric key to be imported to a KeyObject or CryptoKey. Default * is true unless JWK "ext" (Extractable) is true. */ export async function importJWK( jwk: JWK, alg?: string, octAsKeyObject?: boolean, ): Promise { if (!isObject(jwk)) { throw new TypeError('JWK must be an object') } alg ||= jwk.alg if (typeof alg !== 'string' || !alg) { throw new TypeError('"alg" argument is required when "jwk.alg" is not present') } switch (jwk.kty) { case 'oct': if (typeof jwk.k !== 'string' || !jwk.k) { throw new TypeError('missing "k" (Key Value) Parameter value') } octAsKeyObject ??= jwk.ext !== true if (octAsKeyObject) { return asKeyObject({ ...jwk, alg, ext: jwk.ext ?? false }) } return decodeBase64URL(jwk.k) case 'RSA': if (jwk.oth !== undefined) { throw new JOSENotSupported( 'RSA JWK "oth" (Other Primes Info) Parameter value is not supported', ) } case 'EC': case 'OKP': return asKeyObject({ ...jwk, alg }) default: throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value') } } jose-4.11.4/dist/deno/lib/000077500000000000000000000000001437043056600152075ustar00rootroot00000000000000jose-4.11.4/dist/deno/lib/aesgcmkw.ts000066400000000000000000000014351437043056600173630ustar00rootroot00000000000000import encrypt from '../runtime/encrypt.ts' import decrypt from '../runtime/decrypt.ts' import generateIv from './iv.ts' import { encode as base64url } from '../runtime/base64url.ts' export async function wrap(alg: string, key: unknown, cek: Uint8Array, iv?: Uint8Array) { const jweAlgorithm = alg.slice(0, 7) iv ||= generateIv(jweAlgorithm) const { ciphertext: encryptedKey, tag } = await encrypt( jweAlgorithm, cek, key, iv, new Uint8Array(0), ) return { encryptedKey, iv: base64url(iv), tag: base64url(tag) } } export async function unwrap( alg: string, key: unknown, encryptedKey: Uint8Array, iv: Uint8Array, tag: Uint8Array, ) { const jweAlgorithm = alg.slice(0, 7) return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0)) } jose-4.11.4/dist/deno/lib/buffer_utils.ts000066400000000000000000000033541437043056600202550ustar00rootroot00000000000000import digest from '../runtime/digest.ts' export const encoder = new TextEncoder() export const decoder = new TextDecoder() const MAX_INT32 = 2 ** 32 export function concat(...buffers: Uint8Array[]): Uint8Array { const size = buffers.reduce((acc, { length }) => acc + length, 0) const buf = new Uint8Array(size) let i = 0 buffers.forEach((buffer) => { buf.set(buffer, i) i += buffer.length }) return buf } export function p2s(alg: string, p2sInput: Uint8Array) { return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput) } function writeUInt32BE(buf: Uint8Array, value: number, offset?: number) { if (value < 0 || value >= MAX_INT32) { throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`) } buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset) } export function uint64be(value: number) { const high = Math.floor(value / MAX_INT32) const low = value % MAX_INT32 const buf = new Uint8Array(8) writeUInt32BE(buf, high, 0) writeUInt32BE(buf, low, 4) return buf } export function uint32be(value: number) { const buf = new Uint8Array(4) writeUInt32BE(buf, value) return buf } export function lengthAndInput(input: Uint8Array) { return concat(uint32be(input.length), input) } export async function concatKdf(secret: Uint8Array, bits: number, value: Uint8Array) { const iterations = Math.ceil((bits >> 3) / 32) const res = new Uint8Array(iterations * 32) for (let iter = 0; iter < iterations; iter++) { const buf = new Uint8Array(4 + secret.length + value.length) buf.set(uint32be(iter + 1)) buf.set(secret, 4) buf.set(value, 4 + secret.length) res.set(await digest('sha256', buf), iter * 32) } return res.slice(0, bits >> 3) } jose-4.11.4/dist/deno/lib/cek.ts000066400000000000000000000010521437043056600163170ustar00rootroot00000000000000import { JOSENotSupported } from '../util/errors.ts' import random from '../runtime/random.ts' export function bitLength(alg: string) { switch (alg) { case 'A128GCM': return 128 case 'A192GCM': return 192 case 'A256GCM': case 'A128CBC-HS256': return 256 case 'A192CBC-HS384': return 384 case 'A256CBC-HS512': return 512 default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`) } } export default (alg: string): Uint8Array => random(new Uint8Array(bitLength(alg) >> 3)) jose-4.11.4/dist/deno/lib/check_iv_length.ts000066400000000000000000000004351437043056600206750ustar00rootroot00000000000000import { JWEInvalid } from '../util/errors.ts' import { bitLength } from './iv.ts' const checkIvLength = (enc: string, iv: Uint8Array) => { if (iv.length << 3 !== bitLength(enc)) { throw new JWEInvalid('Invalid Initialization Vector length') } } export default checkIvLength jose-4.11.4/dist/deno/lib/check_key_type.ts000066400000000000000000000041321437043056600205450ustar00rootroot00000000000000import { withAlg as invalidKeyInput } from './invalid_key_input.ts' import isKeyLike, { types } from '../runtime/is_key_like.ts' const symmetricTypeCheck = (alg: string, key: unknown) => { if (key instanceof Uint8Array) return if (!isKeyLike(key)) { throw new TypeError(invalidKeyInput(alg, key, ...types, 'Uint8Array')) } if (key.type !== 'secret') { throw new TypeError( `${types.join(' or ')} instances for symmetric algorithms must be of type "secret"`, ) } } const asymmetricTypeCheck = (alg: string, key: unknown, usage: string) => { if (!isKeyLike(key)) { throw new TypeError(invalidKeyInput(alg, key, ...types)) } if (key.type === 'secret') { throw new TypeError( `${types.join(' or ')} instances for asymmetric algorithms must not be of type "secret"`, ) } if (usage === 'sign' && key.type === 'public') { throw new TypeError( `${types.join(' or ')} instances for asymmetric algorithm signing must be of type "private"`, ) } if (usage === 'decrypt' && key.type === 'public') { throw new TypeError( `${types.join( ' or ', )} instances for asymmetric algorithm decryption must be of type "private"`, ) } // KeyObject allows this but CryptoKey does not. if ((key).algorithm && usage === 'verify' && key.type === 'private') { throw new TypeError( `${types.join(' or ')} instances for asymmetric algorithm verifying must be of type "public"`, ) } // KeyObject allows this but CryptoKey does not. if ((key).algorithm && usage === 'encrypt' && key.type === 'private') { throw new TypeError( `${types.join( ' or ', )} instances for asymmetric algorithm encryption must be of type "public"`, ) } } const checkKeyType = (alg: string, key: unknown, usage: string): void => { const symmetric = alg.startsWith('HS') || alg === 'dir' || alg.startsWith('PBES2') || /^A\d{3}(?:GCM)?KW$/.test(alg) if (symmetric) { symmetricTypeCheck(alg, key) } else { asymmetricTypeCheck(alg, key, usage) } } export default checkKeyType jose-4.11.4/dist/deno/lib/check_p2s.ts000066400000000000000000000003501437043056600174160ustar00rootroot00000000000000import { JWEInvalid } from '../util/errors.ts' export default function checkP2s(p2s: Uint8Array) { if (!(p2s instanceof Uint8Array) || p2s.length < 8) { throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets') } } jose-4.11.4/dist/deno/lib/crypto_key.ts000066400000000000000000000114451437043056600177540ustar00rootroot00000000000000import { isCloudflareWorkers } from '../runtime/env.ts' function unusable(name: string | number, prop = 'algorithm.name') { return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`) } function isAlgorithm(algorithm: any, name: string): algorithm is T { return algorithm.name === name } function getHashLength(hash: KeyAlgorithm) { return parseInt(hash.name.slice(4), 10) } function getNamedCurve(alg: string) { switch (alg) { case 'ES256': return 'P-256' case 'ES384': return 'P-384' case 'ES512': return 'P-521' default: throw new Error('unreachable') } } function checkUsage(key: CryptoKey, usages: KeyUsage[]) { if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { let msg = 'CryptoKey does not support this operation, its usages must include ' if (usages.length > 2) { const last = usages.pop() msg += `one of ${usages.join(', ')}, or ${last}.` } else if (usages.length === 2) { msg += `one of ${usages[0]} or ${usages[1]}.` } else { msg += `${usages[0]}.` } throw new TypeError(msg) } } export function checkSigCryptoKey(key: CryptoKey, alg: string, ...usages: KeyUsage[]) { switch (alg) { case 'HS256': case 'HS384': case 'HS512': { if (!isAlgorithm(key.algorithm, 'HMAC')) throw unusable('HMAC') const expected = parseInt(alg.slice(2), 10) const actual = getHashLength(key.algorithm.hash) if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash') break } case 'RS256': case 'RS384': case 'RS512': { if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5')) throw unusable('RSASSA-PKCS1-v1_5') const expected = parseInt(alg.slice(2), 10) const actual = getHashLength(key.algorithm.hash) if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash') break } case 'PS256': case 'PS384': case 'PS512': { if (!isAlgorithm(key.algorithm, 'RSA-PSS')) throw unusable('RSA-PSS') const expected = parseInt(alg.slice(2), 10) const actual = getHashLength(key.algorithm.hash) if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash') break } case 'EdDSA': { if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') { if (isCloudflareWorkers()) { if (isAlgorithm(key.algorithm, 'NODE-ED25519')) break throw unusable('Ed25519, Ed448, or NODE-ED25519') } throw unusable('Ed25519 or Ed448') } break } case 'ES256': case 'ES384': case 'ES512': { if (!isAlgorithm(key.algorithm, 'ECDSA')) throw unusable('ECDSA') const expected = getNamedCurve(alg) const actual = key.algorithm.namedCurve if (actual !== expected) throw unusable(expected, 'algorithm.namedCurve') break } default: throw new TypeError('CryptoKey does not support this operation') } checkUsage(key, usages) } export function checkEncCryptoKey(key: CryptoKey, alg: string, ...usages: KeyUsage[]) { switch (alg) { case 'A128GCM': case 'A192GCM': case 'A256GCM': { if (!isAlgorithm(key.algorithm, 'AES-GCM')) throw unusable('AES-GCM') const expected = parseInt(alg.slice(1, 4), 10) const actual = key.algorithm.length if (actual !== expected) throw unusable(expected, 'algorithm.length') break } case 'A128KW': case 'A192KW': case 'A256KW': { if (!isAlgorithm(key.algorithm, 'AES-KW')) throw unusable('AES-KW') const expected = parseInt(alg.slice(1, 4), 10) const actual = key.algorithm.length if (actual !== expected) throw unusable(expected, 'algorithm.length') break } case 'ECDH': { switch (key.algorithm.name) { case 'ECDH': case 'X25519': case 'X448': break default: throw unusable('ECDH, X25519, or X448') } break } case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': if (!isAlgorithm(key.algorithm, 'PBKDF2')) throw unusable('PBKDF2') break case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': { if (!isAlgorithm(key.algorithm, 'RSA-OAEP')) throw unusable('RSA-OAEP') const expected = parseInt(alg.slice(9), 10) || 1 const actual = getHashLength(key.algorithm.hash) if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash') break } default: throw new TypeError('CryptoKey does not support this operation') } checkUsage(key, usages) } jose-4.11.4/dist/deno/lib/decrypt_key_management.ts000066400000000000000000000113551437043056600223020ustar00rootroot00000000000000import { unwrap as aesKw } from '../runtime/aeskw.ts' import * as ECDH from '../runtime/ecdhes.ts' import { decrypt as pbes2Kw } from '../runtime/pbes2kw.ts' import { decrypt as rsaEs } from '../runtime/rsaes.ts' import { decode as base64url } from '../runtime/base64url.ts' import type { DecryptOptions, JWEHeaderParameters, KeyLike, JWK } from '../types.d.ts' import { JOSENotSupported, JWEInvalid } from '../util/errors.ts' import { bitLength as cekLength } from '../lib/cek.ts' import { importJWK } from '../key/import.ts' import checkKeyType from './check_key_type.ts' import isObject from './is_object.ts' import { unwrap as aesGcmKw } from './aesgcmkw.ts' async function decryptKeyManagement( alg: string, key: KeyLike | Uint8Array, encryptedKey: Uint8Array | undefined, joseHeader: JWEHeaderParameters, options?: DecryptOptions, ): Promise { checkKeyType(alg, key, 'decrypt') switch (alg) { case 'dir': { // Direct Encryption if (encryptedKey !== undefined) throw new JWEInvalid('Encountered unexpected JWE Encrypted Key') return key } case 'ECDH-ES': // Direct Key Agreement if (encryptedKey !== undefined) throw new JWEInvalid('Encountered unexpected JWE Encrypted Key') case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': { // Direct Key Agreement if (!isObject(joseHeader.epk)) throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`) if (!ECDH.ecdhAllowed(key)) throw new JOSENotSupported( 'ECDH with the provided key is not allowed or not supported by your javascript runtime', ) const epk = await importJWK(joseHeader.epk, alg) let partyUInfo!: Uint8Array let partyVInfo!: Uint8Array if (joseHeader.apu !== undefined) { if (typeof joseHeader.apu !== 'string') throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`) partyUInfo = base64url(joseHeader.apu) } if (joseHeader.apv !== undefined) { if (typeof joseHeader.apv !== 'string') throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`) partyVInfo = base64url(joseHeader.apv) } const sharedSecret = await ECDH.deriveKey( epk, key, alg === 'ECDH-ES' ? joseHeader.enc! : alg, alg === 'ECDH-ES' ? cekLength(joseHeader.enc!) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo, ) if (alg === 'ECDH-ES') return sharedSecret // Key Agreement with Key Wrapping if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing') return aesKw(alg.slice(-6), sharedSecret, encryptedKey) } case 'RSA1_5': case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': { // Key Encryption (RSA) if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing') return rsaEs(alg, key, encryptedKey) } case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': { // Key Encryption (PBES2) if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing') if (typeof joseHeader.p2c !== 'number') throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`) const p2cLimit = options?.maxPBES2Count || 10_000 if (joseHeader.p2c > p2cLimit) throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`) if (typeof joseHeader.p2s !== 'string') throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`) return pbes2Kw(alg, key, encryptedKey, joseHeader.p2c, base64url(joseHeader.p2s)) } case 'A128KW': case 'A192KW': case 'A256KW': { // Key Wrapping (AES KW) if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing') return aesKw(alg, key, encryptedKey) } case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': { // Key Wrapping (AES GCM KW) if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing') if (typeof joseHeader.iv !== 'string') throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`) if (typeof joseHeader.tag !== 'string') throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`) const iv = base64url(joseHeader.iv) const tag = base64url(joseHeader.tag) return aesGcmKw(alg, key, encryptedKey, iv, tag) } default: { throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value') } } } export default decryptKeyManagement jose-4.11.4/dist/deno/lib/encrypt_key_management.ts000066400000000000000000000072161437043056600223150ustar00rootroot00000000000000import { wrap as aesKw } from '../runtime/aeskw.ts' import * as ECDH from '../runtime/ecdhes.ts' import { encrypt as pbes2Kw } from '../runtime/pbes2kw.ts' import { encrypt as rsaEs } from '../runtime/rsaes.ts' import { encode as base64url } from '../runtime/base64url.ts' import type { KeyLike, JWEKeyManagementHeaderParameters, JWEHeaderParameters, JWK, } from '../types.d.ts' import generateCek, { bitLength as cekLength } from '../lib/cek.ts' import { JOSENotSupported } from '../util/errors.ts' import { exportJWK } from '../key/export.ts' import checkKeyType from './check_key_type.ts' import { wrap as aesGcmKw } from './aesgcmkw.ts' async function encryptKeyManagement( alg: string, enc: string, key: KeyLike | Uint8Array, providedCek?: Uint8Array, providedParameters: JWEKeyManagementHeaderParameters = {}, ): Promise<{ cek: KeyLike | Uint8Array encryptedKey?: Uint8Array parameters?: JWEHeaderParameters }> { let encryptedKey: Uint8Array | undefined let parameters: (JWEHeaderParameters & { epk?: JWK }) | undefined let cek: KeyLike | Uint8Array checkKeyType(alg, key, 'encrypt') switch (alg) { case 'dir': { // Direct Encryption cek = key break } case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': { // Direct Key Agreement if (!ECDH.ecdhAllowed(key)) { throw new JOSENotSupported( 'ECDH with the provided key is not allowed or not supported by your javascript runtime', ) } const { apu, apv } = providedParameters let { epk: ephemeralKey } = providedParameters ephemeralKey ||= (await ECDH.generateEpk(key)).privateKey const { x, y, crv, kty } = await exportJWK(ephemeralKey!) const sharedSecret = await ECDH.deriveKey( key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv, ) parameters = { epk: { x, crv, kty } } if (kty === 'EC') parameters.epk!.y = y if (apu) parameters.apu = base64url(apu) if (apv) parameters.apv = base64url(apv) if (alg === 'ECDH-ES') { cek = sharedSecret break } // Key Agreement with Key Wrapping cek = providedCek || generateCek(enc) const kwAlg = alg.slice(-6) encryptedKey = await aesKw(kwAlg, sharedSecret, cek) break } case 'RSA1_5': case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': { // Key Encryption (RSA) cek = providedCek || generateCek(enc) encryptedKey = await rsaEs(alg, key, cek) break } case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': { // Key Encryption (PBES2) cek = providedCek || generateCek(enc) const { p2c, p2s } = providedParameters ;({ encryptedKey, ...parameters } = await pbes2Kw(alg, key, cek, p2c, p2s)) break } case 'A128KW': case 'A192KW': case 'A256KW': { // Key Wrapping (AES KW) cek = providedCek || generateCek(enc) encryptedKey = await aesKw(alg, key, cek) break } case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': { // Key Wrapping (AES GCM KW) cek = providedCek || generateCek(enc) const { iv } = providedParameters ;({ encryptedKey, ...parameters } = await aesGcmKw(alg, key, cek, iv)) break } default: { throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value') } } return { cek, encryptedKey, parameters } } export default encryptKeyManagement jose-4.11.4/dist/deno/lib/epoch.ts000066400000000000000000000001011437043056600166450ustar00rootroot00000000000000export default (date: Date) => Math.floor(date.getTime() / 1000) jose-4.11.4/dist/deno/lib/format_pem.ts000066400000000000000000000003071437043056600177100ustar00rootroot00000000000000export default (b64: string, descriptor: string) => { const newlined = (b64.match(/.{1,64}/g) || []).join('\n') return `-----BEGIN ${descriptor}-----\n${newlined}\n-----END ${descriptor}-----` } jose-4.11.4/dist/deno/lib/invalid_key_input.ts000066400000000000000000000017021437043056600212740ustar00rootroot00000000000000function message(msg: string, actual: unknown, ...types: string[]) { if (types.length > 2) { const last = types.pop() msg += `one of type ${types.join(', ')}, or ${last}.` } else if (types.length === 2) { msg += `one of type ${types[0]} or ${types[1]}.` } else { msg += `of type ${types[0]}.` } if (actual == null) { msg += ` Received ${actual}` } else if (typeof actual === 'function' && actual.name) { msg += ` Received function ${actual.name}` } else if (typeof actual === 'object' && actual != null) { if (actual.constructor && actual.constructor.name) { msg += ` Received an instance of ${actual.constructor.name}` } } return msg } export default (actual: unknown, ...types: string[]) => { return message('Key must be ', actual, ...types) } export function withAlg(alg: string, actual: unknown, ...types: string[]) { return message(`Key for the ${alg} algorithm must be `, actual, ...types) } jose-4.11.4/dist/deno/lib/is_disjoint.ts000066400000000000000000000010621437043056600200740ustar00rootroot00000000000000const isDisjoint = (...headers: Array) => { const sources = headers.filter(Boolean) if (sources.length === 0 || sources.length === 1) { return true } let acc!: Set for (const header of sources) { const parameters = Object.keys(header) if (!acc || acc.size === 0) { acc = new Set(parameters) continue } for (const parameter of parameters) { if (acc.has(parameter)) { return false } acc.add(parameter) } } return true } export default isDisjoint jose-4.11.4/dist/deno/lib/is_object.ts000066400000000000000000000010051437043056600175140ustar00rootroot00000000000000function isObjectLike(value: unknown) { return typeof value === 'object' && value !== null } export default function isObject(input: unknown): input is T { if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') { return false } if (Object.getPrototypeOf(input) === null) { return true } let proto = input while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto) } return Object.getPrototypeOf(input) === proto } jose-4.11.4/dist/deno/lib/iv.ts000066400000000000000000000010701437043056600161730ustar00rootroot00000000000000import { JOSENotSupported } from '../util/errors.ts' import random from '../runtime/random.ts' export function bitLength(alg: string) { switch (alg) { case 'A128GCM': case 'A128GCMKW': case 'A192GCM': case 'A192GCMKW': case 'A256GCM': case 'A256GCMKW': return 96 case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': return 128 default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`) } } export default (alg: string): Uint8Array => random(new Uint8Array(bitLength(alg) >> 3)) jose-4.11.4/dist/deno/lib/jwt_claims_set.ts000066400000000000000000000077571437043056600206060ustar00rootroot00000000000000import type { JWTPayload, JWTClaimVerificationOptions, JWEHeaderParameters, JWSHeaderParameters, } from '../types.d.ts' import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.ts' import { decoder } from './buffer_utils.ts' import epoch from './epoch.ts' import secs from './secs.ts' import isObject from './is_object.ts' const normalizeTyp = (value: string) => value.toLowerCase().replace(/^application\//, '') const checkAudiencePresence = (audPayload: unknown, audOption: unknown[]) => { if (typeof audPayload === 'string') { return audOption.includes(audPayload) } if (Array.isArray(audPayload)) { // Each principal intended to process the JWT MUST // identify itself with a value in the audience claim return audOption.some(Set.prototype.has.bind(new Set(audPayload))) } return false } export default ( protectedHeader: JWEHeaderParameters | JWSHeaderParameters, encodedPayload: Uint8Array, options: JWTClaimVerificationOptions = {}, ) => { const { typ } = options if ( typ && (typeof protectedHeader!.typ !== 'string' || normalizeTyp(protectedHeader!.typ) !== normalizeTyp(typ)) ) { throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', 'typ', 'check_failed') } let payload!: { [propName: string]: unknown } try { payload = JSON.parse(decoder.decode(encodedPayload)) } catch { // } if (!isObject(payload)) { throw new JWTInvalid('JWT Claims Set must be a top-level JSON object') } const { issuer } = options if (issuer && !((Array.isArray(issuer) ? issuer : [issuer])).includes(payload.iss!)) { throw new JWTClaimValidationFailed('unexpected "iss" claim value', 'iss', 'check_failed') } const { subject } = options if (subject && payload.sub !== subject) { throw new JWTClaimValidationFailed('unexpected "sub" claim value', 'sub', 'check_failed') } const { audience } = options if ( audience && !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience) ) { throw new JWTClaimValidationFailed('unexpected "aud" claim value', 'aud', 'check_failed') } let tolerance: number switch (typeof options.clockTolerance) { case 'string': tolerance = secs(options.clockTolerance) break case 'number': tolerance = options.clockTolerance break case 'undefined': tolerance = 0 break default: throw new TypeError('Invalid clockTolerance option type') } const { currentDate } = options const now = epoch(currentDate || new Date()) if ((payload.iat !== undefined || options.maxTokenAge) && typeof payload.iat !== 'number') { throw new JWTClaimValidationFailed('"iat" claim must be a number', 'iat', 'invalid') } if (payload.nbf !== undefined) { if (typeof payload.nbf !== 'number') { throw new JWTClaimValidationFailed('"nbf" claim must be a number', 'nbf', 'invalid') } if (payload.nbf > now + tolerance) { throw new JWTClaimValidationFailed( '"nbf" claim timestamp check failed', 'nbf', 'check_failed', ) } } if (payload.exp !== undefined) { if (typeof payload.exp !== 'number') { throw new JWTClaimValidationFailed('"exp" claim must be a number', 'exp', 'invalid') } if (payload.exp <= now - tolerance) { throw new JWTExpired('"exp" claim timestamp check failed', 'exp', 'check_failed') } } if (options.maxTokenAge) { const age = now - payload.iat! const max = typeof options.maxTokenAge === 'number' ? options.maxTokenAge : secs(options.maxTokenAge) if (age - tolerance > max) { throw new JWTExpired( '"iat" claim timestamp check failed (too far in the past)', 'iat', 'check_failed', ) } if (age < 0 - tolerance) { throw new JWTClaimValidationFailed( '"iat" claim timestamp check failed (it should be in the past)', 'iat', 'check_failed', ) } } return payload } jose-4.11.4/dist/deno/lib/secs.ts000066400000000000000000000021061437043056600165130ustar00rootroot00000000000000const minute = 60 const hour = minute * 60 const day = hour * 24 const week = day * 7 const year = day * 365.25 const REGEX = /^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i export default (str: string): number => { const matched = REGEX.exec(str) if (!matched) { throw new TypeError('Invalid time period format') } const value = parseFloat(matched[1]) const unit = matched[2].toLowerCase() switch (unit) { case 'sec': case 'secs': case 'second': case 'seconds': case 's': return Math.round(value) case 'minute': case 'minutes': case 'min': case 'mins': case 'm': return Math.round(value * minute) case 'hour': case 'hours': case 'hr': case 'hrs': case 'h': return Math.round(value * hour) case 'day': case 'days': case 'd': return Math.round(value * day) case 'week': case 'weeks': case 'w': return Math.round(value * week) // years matched default: return Math.round(value * year) } } jose-4.11.4/dist/deno/lib/validate_algorithms.ts000066400000000000000000000006071437043056600216040ustar00rootroot00000000000000const validateAlgorithms = (option: string, algorithms?: string[]) => { if ( algorithms !== undefined && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string')) ) { throw new TypeError(`"${option}" option must be an array of strings`) } if (!algorithms) { return undefined } return new Set(algorithms) } export default validateAlgorithms jose-4.11.4/dist/deno/lib/validate_crit.ts000066400000000000000000000034101437043056600203670ustar00rootroot00000000000000import { JOSENotSupported, JWEInvalid, JWSInvalid } from '../util/errors.ts' interface CritCheckHeader { b64?: boolean crit?: string[] [propName: string]: unknown } function validateCrit( Err: typeof JWEInvalid | typeof JWSInvalid, recognizedDefault: Map, recognizedOption: { [propName: string]: boolean } | undefined, protectedHeader: CritCheckHeader, joseHeader: CritCheckHeader, ) { if (joseHeader.crit !== undefined && protectedHeader.crit === undefined) { throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected') } if (!protectedHeader || protectedHeader.crit === undefined) { return new Set() } if ( !Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input: string) => typeof input !== 'string' || input.length === 0) ) { throw new Err( '"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present', ) } let recognized: Map if (recognizedOption !== undefined) { recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]) } else { recognized = recognizedDefault } for (const parameter of protectedHeader.crit) { if (!recognized.has(parameter)) { throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`) } if (joseHeader[parameter] === undefined) { throw new Err(`Extension Header Parameter "${parameter}" is missing`) } else if (recognized.get(parameter) && protectedHeader[parameter] === undefined) { throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`) } } return new Set(protectedHeader.crit) } export default validateCrit jose-4.11.4/dist/deno/runtime/000077500000000000000000000000001437043056600161245ustar00rootroot00000000000000jose-4.11.4/dist/deno/runtime/aeskw.ts000066400000000000000000000033731437043056600176140ustar00rootroot00000000000000import type { AesKwUnwrapFunction, AesKwWrapFunction } from './interfaces.d.ts' import bogusWebCrypto from './bogus.ts' import crypto, { isCryptoKey } from './webcrypto.ts' import { checkEncCryptoKey } from '../lib/crypto_key.ts' import invalidKeyInput from '../lib/invalid_key_input.ts' import { types } from './is_key_like.ts' function checkKeySize(key: CryptoKey, alg: string) { if ((key.algorithm).length !== parseInt(alg.slice(1, 4), 10)) { throw new TypeError(`Invalid key size for alg: ${alg}`) } } function getCryptoKey(key: unknown, alg: string, usage: KeyUsage) { if (isCryptoKey(key)) { checkEncCryptoKey(key, alg, usage) return key } if (key instanceof Uint8Array) { return crypto.subtle.importKey('raw', key, 'AES-KW', true, [usage]) } throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')) } export const wrap: AesKwWrapFunction = async (alg: string, key: unknown, cek: Uint8Array) => { const cryptoKey = await getCryptoKey(key, alg, 'wrapKey') checkKeySize(cryptoKey, alg) // we're importing the cek to end up with CryptoKey instance that can be wrapped, the algorithm used is irrelevant const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto) return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, cryptoKey, 'AES-KW')) } export const unwrap: AesKwUnwrapFunction = async ( alg: string, key: unknown, encryptedKey: Uint8Array, ) => { const cryptoKey = await getCryptoKey(key, alg, 'unwrapKey') checkKeySize(cryptoKey, alg) const cryptoKeyCek = await crypto.subtle.unwrapKey( 'raw', encryptedKey, cryptoKey, 'AES-KW', ...bogusWebCrypto, ) return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek)) } jose-4.11.4/dist/deno/runtime/asn1.ts000066400000000000000000000123151437043056600173400ustar00rootroot00000000000000import { isCloudflareWorkers } from './env.ts' import crypto, { isCryptoKey } from './webcrypto.ts' import type { PEMExportFunction, PEMImportFunction } from './interfaces.d.ts' import invalidKeyInput from '../lib/invalid_key_input.ts' import { encodeBase64 } from './base64url.ts' import formatPEM from '../lib/format_pem.ts' import { JOSENotSupported } from '../util/errors.ts' import { types } from './is_key_like.ts' import type { PEMImportOptions } from '../key/import.ts' const genericExport = async ( keyType: 'private' | 'public', keyFormat: 'spki' | 'pkcs8', key: unknown, ) => { if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types)) } if (!key.extractable) { throw new TypeError('CryptoKey is not extractable') } if (key.type !== keyType) { throw new TypeError(`key is not a ${keyType} key`) } return formatPEM( encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`, ) } export const toSPKI: PEMExportFunction = (key) => { return genericExport('public', 'spki', key) } export const toPKCS8: PEMExportFunction = (key) => { return genericExport('private', 'pkcs8', key) } const findOid = (keyData: Uint8Array, oid: number[], from = 0): boolean => { if (from === 0) { oid.unshift(oid.length) oid.unshift(0x06) } let i = keyData.indexOf(oid[0], from) if (i === -1) return false const sub = keyData.subarray(i, i + oid.length) if (sub.length !== oid.length) return false return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1) } const getNamedCurve = (keyData: Uint8Array): string => { switch (true) { case findOid(keyData, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]): return 'P-256' case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x22]): return 'P-384' case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x23]): return 'P-521' case findOid(keyData, [0x2b, 0x65, 0x6e]): return 'X25519' case findOid(keyData, [0x2b, 0x65, 0x6f]): return 'X448' case findOid(keyData, [0x2b, 0x65, 0x70]): return 'Ed25519' case findOid(keyData, [0x2b, 0x65, 0x71]): return 'Ed448' default: throw new JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type') } } const genericImport = async ( replace: RegExp, keyFormat: 'spki' | 'pkcs8', pem: string, alg: string, options?: PEMImportOptions, ) => { let algorithm: RsaHashedImportParams | EcKeyAlgorithm | Algorithm let keyUsages: KeyUsage[] const keyData = new Uint8Array( atob(pem.replace(replace, '')) .split('') .map((c) => c.charCodeAt(0)), ) const isPublic = keyFormat === 'spki' switch (alg) { case 'PS256': case 'PS384': case 'PS512': algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` } keyUsages = isPublic ? ['verify'] : ['sign'] break case 'RS256': case 'RS384': case 'RS512': algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` } keyUsages = isPublic ? ['verify'] : ['sign'] break case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': algorithm = { name: 'RSA-OAEP', hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`, } keyUsages = isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey'] break case 'ES256': algorithm = { name: 'ECDSA', namedCurve: 'P-256' } keyUsages = isPublic ? ['verify'] : ['sign'] break case 'ES384': algorithm = { name: 'ECDSA', namedCurve: 'P-384' } keyUsages = isPublic ? ['verify'] : ['sign'] break case 'ES512': algorithm = { name: 'ECDSA', namedCurve: 'P-521' } keyUsages = isPublic ? ['verify'] : ['sign'] break case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': { const namedCurve = getNamedCurve(keyData) algorithm = namedCurve.startsWith('P-') ? { name: 'ECDH', namedCurve } : { name: namedCurve } keyUsages = isPublic ? [] : ['deriveBits'] break } case 'EdDSA': algorithm = { name: getNamedCurve(keyData) } keyUsages = isPublic ? ['verify'] : ['sign'] break default: throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value') } try { return await crypto.subtle.importKey( keyFormat, keyData, algorithm, options?.extractable ?? false, keyUsages, ) } catch (err) { if ( algorithm.name === 'Ed25519' && (err)?.name === 'NotSupportedError' && isCloudflareWorkers() ) { algorithm = { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' } return await crypto.subtle.importKey( keyFormat, keyData, algorithm, options?.extractable ?? false, keyUsages, ) } throw err } } export const fromPKCS8: PEMImportFunction = (pem, alg, options?) => { return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, 'pkcs8', pem, alg, options) } export const fromSPKI: PEMImportFunction = (pem, alg, options?) => { return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, 'spki', pem, alg, options) } jose-4.11.4/dist/deno/runtime/base64url.ts000066400000000000000000000023261437043056600203060ustar00rootroot00000000000000import { encoder, decoder } from '../lib/buffer_utils.ts' export const encodeBase64 = (input: Uint8Array | string) => { let unencoded = input if (typeof unencoded === 'string') { unencoded = encoder.encode(unencoded) } const CHUNK_SIZE = 0x8000 const arr = [] for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) { // @ts-expect-error arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE))) } return btoa(arr.join('')) } export const encode = (input: Uint8Array | string) => { return encodeBase64(input).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_') } export const decodeBase64 = (encoded: string): Uint8Array => { const binary = atob(encoded) const bytes = new Uint8Array(binary.length) for (let i = 0; i < binary.length; i++) { bytes[i] = binary.charCodeAt(i) } return bytes } export const decode = (input: Uint8Array | string) => { let encoded = input if (encoded instanceof Uint8Array) { encoded = decoder.decode(encoded) } encoded = encoded.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '') try { return decodeBase64(encoded) } catch { throw new TypeError('The input to be decoded is not correctly encoded.') } } jose-4.11.4/dist/deno/runtime/bogus.ts000066400000000000000000000002341437043056600176120ustar00rootroot00000000000000const bogusWebCrypto: [HmacImportParams, boolean, KeyUsage[]] = [ { hash: 'SHA-256', name: 'HMAC' }, true, ['sign'], ] export default bogusWebCrypto jose-4.11.4/dist/deno/runtime/check_cek_length.ts000066400000000000000000000005251437043056600217360ustar00rootroot00000000000000import { JWEInvalid } from '../util/errors.ts' const checkCekLength = (cek: Uint8Array, expected: number) => { const actual = cek.byteLength << 3 if (actual !== expected) { throw new JWEInvalid( `Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`, ) } } export default checkCekLength jose-4.11.4/dist/deno/runtime/check_key_length.ts000066400000000000000000000005171437043056600217650ustar00rootroot00000000000000export default (alg: string, key: CryptoKey) => { if (alg.startsWith('RS') || alg.startsWith('PS')) { const { modulusLength } = key.algorithm if (typeof modulusLength !== 'number' || modulusLength < 2048) { throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`) } } } jose-4.11.4/dist/deno/runtime/decrypt.ts000066400000000000000000000065331437043056600201550ustar00rootroot00000000000000import { concat, uint64be } from '../lib/buffer_utils.ts' import type { DecryptFunction } from './interfaces.d.ts' import checkIvLength from '../lib/check_iv_length.ts' import checkCekLength from './check_cek_length.ts' import timingSafeEqual from './timing_safe_equal.ts' import { JOSENotSupported, JWEDecryptionFailed } from '../util/errors.ts' import crypto, { isCryptoKey } from './webcrypto.ts' import { checkEncCryptoKey } from '../lib/crypto_key.ts' import invalidKeyInput from '../lib/invalid_key_input.ts' import { types } from './is_key_like.ts' async function cbcDecrypt( enc: string, cek: Uint8Array | CryptoKey, ciphertext: Uint8Array, iv: Uint8Array, tag: Uint8Array, aad: Uint8Array, ) { if (!(cek instanceof Uint8Array)) { throw new TypeError(invalidKeyInput(cek, 'Uint8Array')) } const keySize = parseInt(enc.slice(1, 4), 10) const encKey = await crypto.subtle.importKey( 'raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['decrypt'], ) const macKey = await crypto.subtle.importKey( 'raw', cek.subarray(0, keySize >> 3), { hash: `SHA-${keySize << 1}`, name: 'HMAC', }, false, ['sign'], ) const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)) const expectedTag = new Uint8Array( (await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3), ) let macCheckPassed!: boolean try { macCheckPassed = timingSafeEqual(tag, expectedTag) } catch { // } if (!macCheckPassed) { throw new JWEDecryptionFailed() } let plaintext!: Uint8Array try { plaintext = new Uint8Array( await crypto.subtle.decrypt({ iv, name: 'AES-CBC' }, encKey, ciphertext), ) } catch { // } if (!plaintext) { throw new JWEDecryptionFailed() } return plaintext } async function gcmDecrypt( enc: string, cek: Uint8Array | CryptoKey, ciphertext: Uint8Array, iv: Uint8Array, tag: Uint8Array, aad: Uint8Array, ) { let encKey: CryptoKey if (cek instanceof Uint8Array) { encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['decrypt']) } else { checkEncCryptoKey(cek, enc, 'decrypt') encKey = cek } try { return new Uint8Array( await crypto.subtle.decrypt( { additionalData: aad, iv, name: 'AES-GCM', tagLength: 128, }, encKey, concat(ciphertext, tag), ), ) } catch { throw new JWEDecryptionFailed() } } const decrypt: DecryptFunction = async ( enc: string, cek: unknown, ciphertext: Uint8Array, iv: Uint8Array, tag: Uint8Array, aad: Uint8Array, ) => { if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')) } checkIvLength(enc, iv) switch (enc) { case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(-3), 10)) return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) case 'A128GCM': case 'A192GCM': case 'A256GCM': if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(1, 4), 10)) return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) default: throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm') } } export default decrypt jose-4.11.4/dist/deno/runtime/digest.ts000066400000000000000000000005651437043056600177610ustar00rootroot00000000000000import crypto from './webcrypto.ts' import type { DigestFunction } from './interfaces.d.ts' const digest: DigestFunction = async ( algorithm: 'sha256' | 'sha384' | 'sha512', data: Uint8Array, ): Promise => { const subtleDigest = `SHA-${algorithm.slice(-3)}` return new Uint8Array(await crypto.subtle.digest(subtleDigest, data)) } export default digest jose-4.11.4/dist/deno/runtime/ecdhes.ts000066400000000000000000000037551437043056600177410ustar00rootroot00000000000000import { encoder, concat, uint32be, lengthAndInput, concatKdf } from '../lib/buffer_utils.ts' import crypto, { isCryptoKey } from './webcrypto.ts' import { checkEncCryptoKey } from '../lib/crypto_key.ts' import invalidKeyInput from '../lib/invalid_key_input.ts' import { types } from './is_key_like.ts' export async function deriveKey( publicKey: unknown, privateKey: unknown, algorithm: string, keyLength: number, apu: Uint8Array = new Uint8Array(0), apv: Uint8Array = new Uint8Array(0), ) { if (!isCryptoKey(publicKey)) { throw new TypeError(invalidKeyInput(publicKey, ...types)) } checkEncCryptoKey(publicKey, 'ECDH') if (!isCryptoKey(privateKey)) { throw new TypeError(invalidKeyInput(privateKey, ...types)) } checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits') const value = concat( lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength), ) let length: number if (publicKey.algorithm.name === 'X25519') { length = 256 } else if (publicKey.algorithm.name === 'X448') { length = 448 } else { length = Math.ceil(parseInt((publicKey.algorithm).namedCurve.substr(-3), 10) / 8) << 3 } const sharedSecret = new Uint8Array( await crypto.subtle.deriveBits( { name: publicKey.algorithm.name, public: publicKey, }, privateKey, length, ), ) return concatKdf(sharedSecret, keyLength, value) } export async function generateEpk(key: unknown) { if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types)) } return crypto.subtle.generateKey(key.algorithm, true, ['deriveBits']) } export function ecdhAllowed(key: unknown) { if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types)) } return ( ['P-256', 'P-384', 'P-521'].includes((key.algorithm).namedCurve) || key.algorithm.name === 'X25519' || key.algorithm.name === 'X448' ) } jose-4.11.4/dist/deno/runtime/encrypt.ts000066400000000000000000000057431437043056600201710ustar00rootroot00000000000000import { concat, uint64be } from '../lib/buffer_utils.ts' import type { EncryptFunction } from './interfaces.d.ts' import checkIvLength from '../lib/check_iv_length.ts' import checkCekLength from './check_cek_length.ts' import crypto, { isCryptoKey } from './webcrypto.ts' import { checkEncCryptoKey } from '../lib/crypto_key.ts' import invalidKeyInput from '../lib/invalid_key_input.ts' import { JOSENotSupported } from '../util/errors.ts' import { types } from './is_key_like.ts' async function cbcEncrypt( enc: string, plaintext: Uint8Array, cek: Uint8Array | CryptoKey, iv: Uint8Array, aad: Uint8Array, ) { if (!(cek instanceof Uint8Array)) { throw new TypeError(invalidKeyInput(cek, 'Uint8Array')) } const keySize = parseInt(enc.slice(1, 4), 10) const encKey = await crypto.subtle.importKey( 'raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['encrypt'], ) const macKey = await crypto.subtle.importKey( 'raw', cek.subarray(0, keySize >> 3), { hash: `SHA-${keySize << 1}`, name: 'HMAC', }, false, ['sign'], ) const ciphertext = new Uint8Array( await crypto.subtle.encrypt( { iv, name: 'AES-CBC', }, encKey, plaintext, ), ) const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)) const tag = new Uint8Array( (await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3), ) return { ciphertext, tag } } async function gcmEncrypt( enc: string, plaintext: Uint8Array, cek: Uint8Array | CryptoKey, iv: Uint8Array, aad: Uint8Array, ) { let encKey: CryptoKey if (cek instanceof Uint8Array) { encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']) } else { checkEncCryptoKey(cek, enc, 'encrypt') encKey = cek } const encrypted = new Uint8Array( await crypto.subtle.encrypt( { additionalData: aad, iv, name: 'AES-GCM', tagLength: 128, }, encKey, plaintext, ), ) const tag = encrypted.slice(-16) const ciphertext = encrypted.slice(0, -16) return { ciphertext, tag } } const encrypt: EncryptFunction = async ( enc: string, plaintext: Uint8Array, cek: unknown, iv: Uint8Array, aad: Uint8Array, ) => { if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')) } checkIvLength(enc, iv) switch (enc) { case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(-3), 10)) return cbcEncrypt(enc, plaintext, cek, iv, aad) case 'A128GCM': case 'A192GCM': case 'A256GCM': if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(1, 4), 10)) return gcmEncrypt(enc, plaintext, cek, iv, aad) default: throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm') } } export default encrypt jose-4.11.4/dist/deno/runtime/env.ts000066400000000000000000000004721437043056600172670ustar00rootroot00000000000000export function isCloudflareWorkers() { return ( // @ts-ignore typeof WebSocketPair !== 'undefined' || // @ts-ignore (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') || // @ts-ignore (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel') ) } jose-4.11.4/dist/deno/runtime/fetch_jwks.ts000066400000000000000000000021641437043056600206260ustar00rootroot00000000000000import type { FetchFunction } from './interfaces.d.ts' import { JOSEError, JWKSTimeout } from '../util/errors.ts' type AcceptedRequestOptions = Pick const fetchJwks: FetchFunction = async ( url: URL, timeout: number, options: AcceptedRequestOptions, ) => { let controller!: AbortController let id!: ReturnType let timedOut = false if (typeof AbortController === 'function') { controller = new AbortController() id = setTimeout(() => { timedOut = true controller.abort() }, timeout) } const response = await fetch(url.href, { signal: controller ? controller.signal : undefined, redirect: 'manual', headers: options.headers, }).catch((err) => { if (timedOut) throw new JWKSTimeout() throw err }) if (id !== undefined) clearTimeout(id) if (response.status !== 200) { throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response') } try { return await response.json() } catch { throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON') } } export default fetchJwks jose-4.11.4/dist/deno/runtime/generate.ts000066400000000000000000000122501437043056600202660ustar00rootroot00000000000000import { isCloudflareWorkers } from './env.ts' import crypto from './webcrypto.ts' import { JOSENotSupported } from '../util/errors.ts' import random from './random.ts' import type { GenerateKeyPairOptions } from '../key/generate_key_pair.ts' import type { GenerateSecretOptions } from '../key/generate_secret.ts' export async function generateSecret(alg: string, options?: GenerateSecretOptions) { let length: number let algorithm: AesKeyGenParams | HmacKeyGenParams let keyUsages: KeyUsage[] switch (alg) { case 'HS256': case 'HS384': case 'HS512': length = parseInt(alg.slice(-3), 10) algorithm = { name: 'HMAC', hash: `SHA-${length}`, length } keyUsages = ['sign', 'verify'] break case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': length = parseInt(alg.slice(-3), 10) return random(new Uint8Array(length >> 3)) case 'A128KW': case 'A192KW': case 'A256KW': length = parseInt(alg.slice(1, 4), 10) algorithm = { name: 'AES-KW', length } keyUsages = ['wrapKey', 'unwrapKey'] break case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': case 'A128GCM': case 'A192GCM': case 'A256GCM': length = parseInt(alg.slice(1, 4), 10) algorithm = { name: 'AES-GCM', length } keyUsages = ['encrypt', 'decrypt'] break default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value') } return >( (crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages)) ) } function getModulusLengthOption(options?: GenerateKeyPairOptions) { const modulusLength = options?.modulusLength ?? 2048 if (typeof modulusLength !== 'number' || modulusLength < 2048) { throw new JOSENotSupported( 'Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used', ) } return modulusLength } export async function generateKeyPair(alg: string, options?: GenerateKeyPairOptions) { let algorithm: RsaHashedKeyGenParams | EcKeyGenParams | KeyAlgorithm let keyUsages: KeyUsage[] switch (alg) { case 'PS256': case 'PS384': case 'PS512': algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}`, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), modulusLength: getModulusLengthOption(options), } keyUsages = ['sign', 'verify'] break case 'RS256': case 'RS384': case 'RS512': algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}`, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), modulusLength: getModulusLengthOption(options), } keyUsages = ['sign', 'verify'] break case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': algorithm = { name: 'RSA-OAEP', hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), modulusLength: getModulusLengthOption(options), } keyUsages = ['decrypt', 'unwrapKey', 'encrypt', 'wrapKey'] break case 'ES256': algorithm = { name: 'ECDSA', namedCurve: 'P-256' } keyUsages = ['sign', 'verify'] break case 'ES384': algorithm = { name: 'ECDSA', namedCurve: 'P-384' } keyUsages = ['sign', 'verify'] break case 'ES512': algorithm = { name: 'ECDSA', namedCurve: 'P-521' } keyUsages = ['sign', 'verify'] break case 'EdDSA': keyUsages = ['sign', 'verify'] const crv = options?.crv ?? 'Ed25519' switch (crv) { case 'Ed25519': case 'Ed448': algorithm = { name: crv } break default: throw new JOSENotSupported('Invalid or unsupported crv option provided') } break case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': { keyUsages = ['deriveKey', 'deriveBits'] const crv = options?.crv ?? 'P-256' switch (crv) { case 'P-256': case 'P-384': case 'P-521': { algorithm = { name: 'ECDH', namedCurve: crv } break } case 'X25519': case 'X448': algorithm = { name: crv } break default: throw new JOSENotSupported( 'Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448', ) } break } default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value') } try { return <{ publicKey: CryptoKey; privateKey: CryptoKey }>( await crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages) ) } catch (err) { if ( algorithm.name === 'Ed25519' && (err)?.name === 'NotSupportedError' && isCloudflareWorkers() ) { algorithm = { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' } return <{ publicKey: CryptoKey; privateKey: CryptoKey }>( await crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages) ) } throw err } } jose-4.11.4/dist/deno/runtime/get_sign_verify_key.ts000066400000000000000000000013351437043056600225310ustar00rootroot00000000000000import crypto, { isCryptoKey } from './webcrypto.ts' import { checkSigCryptoKey } from '../lib/crypto_key.ts' import invalidKeyInput from '../lib/invalid_key_input.ts' import { types } from './is_key_like.ts' export default function getCryptoKey(alg: string, key: unknown, usage: KeyUsage) { if (isCryptoKey(key)) { checkSigCryptoKey(key, alg, usage) return key } if (key instanceof Uint8Array) { if (!alg.startsWith('HS')) { throw new TypeError(invalidKeyInput(key, ...types)) } return crypto.subtle.importKey( 'raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage], ) } throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')) } jose-4.11.4/dist/deno/runtime/interfaces.d.ts000066400000000000000000000043771437043056600210540ustar00rootroot00000000000000import type { JWK, KeyLike } from '../types.d.ts' import type { PEMImportOptions } from '../key/import.ts' type AsyncOrSync = Promise | T export interface TimingSafeEqual { (a: Uint8Array, b: Uint8Array): boolean } export interface SignFunction { (alg: string, key: unknown, data: Uint8Array): Promise } export interface VerifyFunction { (alg: string, key: unknown, signature: Uint8Array, data: Uint8Array): Promise } export interface AesKwWrapFunction { (alg: string, key: unknown, cek: Uint8Array): AsyncOrSync } export interface AesKwUnwrapFunction { (alg: string, key: unknown, encryptedKey: Uint8Array): AsyncOrSync } export interface RsaEsEncryptFunction { (alg: string, key: unknown, cek: Uint8Array): AsyncOrSync } export interface RsaEsDecryptFunction { (alg: string, key: unknown, encryptedKey: Uint8Array): AsyncOrSync } export interface Pbes2KWEncryptFunction { (alg: string, key: unknown, cek: Uint8Array, p2c?: number, p2s?: Uint8Array): Promise<{ encryptedKey: Uint8Array p2c: number p2s: string }> } export interface Pbes2KWDecryptFunction { ( alg: string, key: unknown, encryptedKey: Uint8Array, p2c: number, p2s: Uint8Array, ): Promise } export interface EncryptFunction { (enc: string, plaintext: Uint8Array, cek: unknown, iv: Uint8Array, aad: Uint8Array): AsyncOrSync<{ ciphertext: Uint8Array tag: Uint8Array }> } export interface DecryptFunction { ( enc: string, cek: unknown, ciphertext: Uint8Array, iv: Uint8Array, tag: Uint8Array, additionalData: Uint8Array, ): AsyncOrSync } export interface FetchFunction { (url: URL, timeout: number, options?: any): Promise<{ [propName: string]: unknown }> } export interface DigestFunction { (digest: 'sha256' | 'sha384' | 'sha512', data: Uint8Array): AsyncOrSync } export interface JWKImportFunction { (jwk: JWK): AsyncOrSync } export interface PEMImportFunction { (pem: string, alg: string, options?: PEMImportOptions): AsyncOrSync } interface ExportFunction { (key: unknown): AsyncOrSync } export type JWKExportFunction = ExportFunction export type PEMExportFunction = ExportFunction jose-4.11.4/dist/deno/runtime/is_key_like.ts000066400000000000000000000003161437043056600207630ustar00rootroot00000000000000import type { KeyLike } from '../types.d.ts' import { isCryptoKey } from './webcrypto.ts' export default (key: unknown): key is KeyLike => { return isCryptoKey(key) } export const types = ['CryptoKey'] jose-4.11.4/dist/deno/runtime/jwk_to_key.ts000066400000000000000000000120601437043056600206400ustar00rootroot00000000000000import { isCloudflareWorkers } from './env.ts' import crypto from './webcrypto.ts' import type { JWKImportFunction } from './interfaces.d.ts' import { JOSENotSupported } from '../util/errors.ts' import type { JWK } from '../types.d.ts' import { decode as base64url } from './base64url.ts' function subtleMapping(jwk: JWK): { algorithm: RsaHashedImportParams | EcKeyAlgorithm | Algorithm keyUsages: KeyUsage[] } { let algorithm: RsaHashedImportParams | EcKeyAlgorithm | Algorithm let keyUsages: KeyUsage[] switch (jwk.kty) { case 'oct': { switch (jwk.alg) { case 'HS256': case 'HS384': case 'HS512': algorithm = { name: 'HMAC', hash: `SHA-${jwk.alg.slice(-3)}` } keyUsages = ['sign', 'verify'] break case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': throw new JOSENotSupported(`${jwk.alg} keys cannot be imported as CryptoKey instances`) case 'A128GCM': case 'A192GCM': case 'A256GCM': case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': algorithm = { name: 'AES-GCM' } keyUsages = ['encrypt', 'decrypt'] break case 'A128KW': case 'A192KW': case 'A256KW': algorithm = { name: 'AES-KW' } keyUsages = ['wrapKey', 'unwrapKey'] break case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': algorithm = { name: 'PBKDF2' } keyUsages = ['deriveBits'] break default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value') } break } case 'RSA': { switch (jwk.alg) { case 'PS256': case 'PS384': case 'PS512': algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` } keyUsages = jwk.d ? ['sign'] : ['verify'] break case 'RS256': case 'RS384': case 'RS512': algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` } keyUsages = jwk.d ? ['sign'] : ['verify'] break case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': algorithm = { name: 'RSA-OAEP', hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`, } keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'] break default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value') } break } case 'EC': { switch (jwk.alg) { case 'ES256': algorithm = { name: 'ECDSA', namedCurve: 'P-256' } keyUsages = jwk.d ? ['sign'] : ['verify'] break case 'ES384': algorithm = { name: 'ECDSA', namedCurve: 'P-384' } keyUsages = jwk.d ? ['sign'] : ['verify'] break case 'ES512': algorithm = { name: 'ECDSA', namedCurve: 'P-521' } keyUsages = jwk.d ? ['sign'] : ['verify'] break case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': algorithm = { name: 'ECDH', namedCurve: jwk.crv! } keyUsages = jwk.d ? ['deriveBits'] : [] break default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value') } break } case 'OKP': { switch (jwk.alg) { case 'EdDSA': algorithm = { name: jwk.crv! } keyUsages = jwk.d ? ['sign'] : ['verify'] break case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': algorithm = { name: jwk.crv! } keyUsages = jwk.d ? ['deriveBits'] : [] break default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value') } break } default: throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value') } return { algorithm, keyUsages } } const parse: JWKImportFunction = async (jwk: JWK): Promise => { const { algorithm, keyUsages } = subtleMapping(jwk) const rest: [RsaHashedImportParams | EcKeyAlgorithm | Algorithm, boolean, KeyUsage[]] = [ algorithm, jwk.ext ?? false, jwk.key_ops ?? keyUsages, ] if (algorithm.name === 'PBKDF2') { return crypto.subtle.importKey('raw', base64url(jwk.k!), ...rest) } const keyData: JWK = { ...jwk } delete keyData.alg delete keyData.use try { return await crypto.subtle.importKey('jwk', keyData, ...rest) } catch (err) { if ( algorithm.name === 'Ed25519' && (err)?.name === 'NotSupportedError' && isCloudflareWorkers() ) { rest[0] = { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' } return await crypto.subtle.importKey('jwk', keyData, ...rest) } throw err } } export default parse jose-4.11.4/dist/deno/runtime/key_to_jwk.ts000066400000000000000000000014731437043056600206460ustar00rootroot00000000000000import crypto, { isCryptoKey } from './webcrypto.ts' import type { JWKExportFunction } from './interfaces.d.ts' import type { JWK } from '../types.d.ts' import invalidKeyInput from '../lib/invalid_key_input.ts' import { encode as base64url } from './base64url.ts' import { types } from './is_key_like.ts' const keyToJWK: JWKExportFunction = async (key: unknown): Promise => { if (key instanceof Uint8Array) { return { kty: 'oct', k: base64url(key), } } if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')) } if (!key.extractable) { throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK') } const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key) return jwk } export default keyToJWK jose-4.11.4/dist/deno/runtime/pbes2kw.ts000066400000000000000000000043671437043056600200630ustar00rootroot00000000000000import type { Pbes2KWDecryptFunction, Pbes2KWEncryptFunction } from './interfaces.d.ts' import random from './random.ts' import { p2s as concatSalt } from '../lib/buffer_utils.ts' import { encode as base64url } from './base64url.ts' import { wrap, unwrap } from './aeskw.ts' import checkP2s from '../lib/check_p2s.ts' import crypto, { isCryptoKey } from './webcrypto.ts' import { checkEncCryptoKey } from '../lib/crypto_key.ts' import invalidKeyInput from '../lib/invalid_key_input.ts' import { types } from './is_key_like.ts' function getCryptoKey(key: unknown, alg: string) { if (key instanceof Uint8Array) { return crypto.subtle.importKey('raw', key, 'PBKDF2', false, ['deriveBits']) } if (isCryptoKey(key)) { checkEncCryptoKey(key, alg, 'deriveBits', 'deriveKey') return key } throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')) } async function deriveKey(p2s: Uint8Array, alg: string, p2c: number, key: unknown) { checkP2s(p2s) const salt = concatSalt(alg, p2s) const keylen = parseInt(alg.slice(13, 16), 10) const subtleAlg = { hash: `SHA-${alg.slice(8, 11)}`, iterations: p2c, name: 'PBKDF2', salt, } const wrapAlg = { length: keylen, name: 'AES-KW', } const cryptoKey = await getCryptoKey(key, alg) if (cryptoKey.usages.includes('deriveBits')) { return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen)) } if (cryptoKey.usages.includes('deriveKey')) { return crypto.subtle.deriveKey(subtleAlg, cryptoKey, wrapAlg, false, ['wrapKey', 'unwrapKey']) } throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"') } export const encrypt: Pbes2KWEncryptFunction = async ( alg: string, key: unknown, cek: Uint8Array, p2c: number = 2048, p2s: Uint8Array = random(new Uint8Array(16)), ) => { const derived = await deriveKey(p2s, alg, p2c, key) const encryptedKey = await wrap(alg.slice(-6), derived, cek) return { encryptedKey, p2c, p2s: base64url(p2s) } } export const decrypt: Pbes2KWDecryptFunction = async ( alg: string, key: unknown, encryptedKey: Uint8Array, p2c: number, p2s: Uint8Array, ) => { const derived = await deriveKey(p2s, alg, p2c, key) return unwrap(alg.slice(-6), derived, encryptedKey) } jose-4.11.4/dist/deno/runtime/random.ts000066400000000000000000000001301437043056600177460ustar00rootroot00000000000000import crypto from './webcrypto.ts' export default crypto.getRandomValues.bind(crypto) jose-4.11.4/dist/deno/runtime/rsaes.ts000066400000000000000000000041361437043056600176150ustar00rootroot00000000000000import type { RsaEsDecryptFunction, RsaEsEncryptFunction } from './interfaces.d.ts' import subtleAlgorithm from './subtle_rsaes.ts' import bogusWebCrypto from './bogus.ts' import crypto, { isCryptoKey } from './webcrypto.ts' import { checkEncCryptoKey } from '../lib/crypto_key.ts' import checkKeyLength from './check_key_length.ts' import invalidKeyInput from '../lib/invalid_key_input.ts' import { types } from './is_key_like.ts' export const encrypt: RsaEsEncryptFunction = async (alg: string, key: unknown, cek: Uint8Array) => { if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types)) } checkEncCryptoKey(key, alg, 'encrypt', 'wrapKey') checkKeyLength(alg, key) if (key.usages.includes('encrypt')) { return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek)) } if (key.usages.includes('wrapKey')) { // we're importing the cek to end up with CryptoKey instance that can be wrapped, the algorithm used is irrelevant const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto) return new Uint8Array( await crypto.subtle.wrapKey('raw', cryptoKeyCek, key, subtleAlgorithm(alg)), ) } throw new TypeError( 'RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation', ) } export const decrypt: RsaEsDecryptFunction = async ( alg: string, key: unknown, encryptedKey: Uint8Array, ) => { if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types)) } checkEncCryptoKey(key, alg, 'decrypt', 'unwrapKey') checkKeyLength(alg, key) if (key.usages.includes('decrypt')) { return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey)) } if (key.usages.includes('unwrapKey')) { const cryptoKeyCek = await crypto.subtle.unwrapKey( 'raw', encryptedKey, key, subtleAlgorithm(alg), ...bogusWebCrypto, ) return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek)) } throw new TypeError( 'RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation', ) } jose-4.11.4/dist/deno/runtime/sign.ts000066400000000000000000000010721437043056600174340ustar00rootroot00000000000000import type { SignFunction } from './interfaces.d.ts' import subtleAlgorithm from './subtle_dsa.ts' import crypto from './webcrypto.ts' import checkKeyLength from './check_key_length.ts' import getSignKey from './get_sign_verify_key.ts' const sign: SignFunction = async (alg, key: unknown, data) => { const cryptoKey = await getSignKey(alg, key, 'sign') checkKeyLength(alg, cryptoKey) const signature = await crypto.subtle.sign( subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data, ) return new Uint8Array(signature) } export default sign jose-4.11.4/dist/deno/runtime/subtle_dsa.ts000066400000000000000000000020711437043056600206210ustar00rootroot00000000000000import { isCloudflareWorkers } from './env.ts' import { JOSENotSupported } from '../util/errors.ts' export default function subtleDsa(alg: string, algorithm: KeyAlgorithm | EcKeyAlgorithm) { const hash = `SHA-${alg.slice(-3)}` switch (alg) { case 'HS256': case 'HS384': case 'HS512': return { hash, name: 'HMAC' } case 'PS256': case 'PS384': case 'PS512': // @ts-expect-error return { hash, name: 'RSA-PSS', saltLength: alg.slice(-3) >> 3 } case 'RS256': case 'RS384': case 'RS512': return { hash, name: 'RSASSA-PKCS1-v1_5' } case 'ES256': case 'ES384': case 'ES512': return { hash, name: 'ECDSA', namedCurve: (algorithm).namedCurve } case 'EdDSA': if (isCloudflareWorkers() && algorithm.name === 'NODE-ED25519') { return { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' } } return { name: algorithm.name } default: throw new JOSENotSupported( `alg ${alg} is not supported either by JOSE or your javascript runtime`, ) } } jose-4.11.4/dist/deno/runtime/subtle_rsaes.ts000066400000000000000000000006001437043056600211630ustar00rootroot00000000000000import { JOSENotSupported } from '../util/errors.ts' export default function subtleRsaEs(alg: string) { switch (alg) { case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': return 'RSA-OAEP' default: throw new JOSENotSupported( `alg ${alg} is not supported either by JOSE or your javascript runtime`, ) } } jose-4.11.4/dist/deno/runtime/timing_safe_equal.ts000066400000000000000000000010651437043056600221520ustar00rootroot00000000000000import type { TimingSafeEqual } from './interfaces.d.ts' const timingSafeEqual: TimingSafeEqual = (a, b) => { if (!(a instanceof Uint8Array)) { throw new TypeError('First argument must be a buffer') } if (!(b instanceof Uint8Array)) { throw new TypeError('Second argument must be a buffer') } if (a.length !== b.length) { throw new TypeError('Input buffers must have the same length') } const len = a.length let out = 0 let i = -1 while (++i < len) { out |= a[i] ^ b[i] } return out === 0 } export default timingSafeEqual jose-4.11.4/dist/deno/runtime/verify.ts000066400000000000000000000011521437043056600177770ustar00rootroot00000000000000import type { VerifyFunction } from './interfaces.d.ts' import subtleAlgorithm from './subtle_dsa.ts' import crypto from './webcrypto.ts' import checkKeyLength from './check_key_length.ts' import getVerifyKey from './get_sign_verify_key.ts' const verify: VerifyFunction = async (alg, key: unknown, signature, data) => { const cryptoKey = await getVerifyKey(alg, key, 'verify') checkKeyLength(alg, cryptoKey) const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm) try { return await crypto.subtle.verify(algorithm, cryptoKey, signature, data) } catch { return false } } export default verify jose-4.11.4/dist/deno/runtime/webcrypto.ts000066400000000000000000000001571437043056600205150ustar00rootroot00000000000000export default crypto export const isCryptoKey = (key: unknown): key is CryptoKey => key instanceof CryptoKey jose-4.11.4/dist/deno/runtime/zlib.ts000066400000000000000000000012541437043056600174360ustar00rootroot00000000000000import { JOSENotSupported } from '../util/errors.ts' import type { InflateFunction, DeflateFunction } from '../types.d.ts' export const inflate: InflateFunction = async () => { throw new JOSENotSupported( 'JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.', ) } export const deflate: DeflateFunction = async () => { throw new JOSENotSupported( 'JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.', ) } jose-4.11.4/dist/deno/types.d.ts000066400000000000000000000500711437043056600164020ustar00rootroot00000000000000/** * KeyLike are runtime-specific classes representing asymmetric keys or symmetric secrets. These are * instances of [CryptoKey](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) and * additionally [KeyObject](https://nodejs.org/api/crypto.html#class-keyobject) in Node.js runtime. * [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) * instances are also accepted as symmetric secret representation only. * * [Key Import Functions](../modules/key_import.md#readme) can be used to import PEM, or JWK * formatted asymmetric keys and certificates to these runtime-specific representations. * * In Node.js the [Buffer](https://nodejs.org/api/buffer.html#buffer) class is a subclass of * Uint8Array and so Buffer can be provided for symmetric secrets as well. * * [KeyObject](https://nodejs.org/api/crypto.html#class-keyobject) is a representation of a * key/secret available in the Node.js runtime. In addition to the import functions of this library * you may use the runtime APIs * [crypto.createPublicKey](https://nodejs.org/api/crypto.html#cryptocreatepublickeykey), * [crypto.createPrivateKey](https://nodejs.org/api/crypto.html#cryptocreateprivatekeykey), and * [crypto.createSecretKey](https://nodejs.org/api/crypto.html#cryptocreatesecretkeykey-encoding) to * obtain a KeyObject from your existing key material. * * [CryptoKey](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) is a representation of a * key/secret available in the Browser and Web-interoperable runtimes. In addition to the import * functions of this library you may use the * [SubtleCrypto.importKey](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey) * API to obtain a CryptoKey from your existing key material. * * @example Import a PEM-encoded SPKI Public Key * * ```js * const algorithm = 'ES256' * const spki = `-----BEGIN PUBLIC KEY----- * MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFlHHWfLk0gLBbsLTcuCrbCqoHqmM * YJepMC+Q+Dd6RBmBiA41evUsNMwLeN+PNFqib+xwi9JkJ8qhZkq8Y/IzGg== * -----END PUBLIC KEY-----` * const ecPublicKey = await jose.importSPKI(spki, algorithm) * ``` * * @example Import a X.509 Certificate * * ```js * const algorithm = 'ES256' * const x509 = `-----BEGIN CERTIFICATE----- * MIIBXjCCAQSgAwIBAgIGAXvykuMKMAoGCCqGSM49BAMCMDYxNDAyBgNVBAMMK3Np * QXBNOXpBdk1VaXhXVWVGaGtjZXg1NjJRRzFyQUhXaV96UlFQTVpQaG8wHhcNMjEw * OTE3MDcwNTE3WhcNMjIwNzE0MDcwNTE3WjA2MTQwMgYDVQQDDCtzaUFwTTl6QXZN * VWl4V1VlRmhrY2V4NTYyUUcxckFIV2lfelJRUE1aUGhvMFkwEwYHKoZIzj0CAQYI * KoZIzj0DAQcDQgAE8PbPvCv5D5xBFHEZlBp/q5OEUymq7RIgWIi7tkl9aGSpYE35 * UH+kBKDnphJO3odpPZ5gvgKs2nwRWcrDnUjYLDAKBggqhkjOPQQDAgNIADBFAiEA * 1yyMTRe66MhEXID9+uVub7woMkNYd0LhSHwKSPMUUTkCIFQGsfm1ecXOpeGOufAh * v+A1QWZMuTWqYt+uh/YSRNDn * -----END CERTIFICATE-----` * const ecPublicKey = await jose.importX509(x509, algorithm) * ``` * * @example Import a PEM-encoded PKCS8 Private Key * * ```js * const algorithm = 'ES256' * const pkcs8 = `-----BEGIN PRIVATE KEY----- * MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgiyvo0X+VQ0yIrOaN * nlrnUclopnvuuMfoc8HHly3505OhRANCAAQWUcdZ8uTSAsFuwtNy4KtsKqgeqYxg * l6kwL5D4N3pEGYGIDjV69Sw0zAt43480WqJv7HCL0mQnyqFmSrxj8jMa * -----END PRIVATE KEY-----` * const ecPrivateKey = await jose.importPKCS8(pkcs8, algorithm) * ``` * * @example Import a JSON Web Key (JWK) * * ```js * const ecPublicKey = await jose.importJWK( * { * crv: 'P-256', * kty: 'EC', * x: 'ySK38C1jBdLwDsNWKzzBHqKYEE5Cgv-qjWvorUXk9fw', * y: '_LeQBw07cf5t57Iavn4j-BqJsAD1dpoz8gokd3sBsOo', * }, * 'ES256', * ) * * const rsaPublicKey = await jose.importJWK( * { * kty: 'RSA', * e: 'AQAB', * n: '12oBZRhCiZFJLcPg59LkZZ9mdhSMTKAQZYq32k_ti5SBB6jerkh-WzOMAO664r_qyLkqHUSp3u5SbXtseZEpN3XPWGKSxjsy-1JyEFTdLSYe6f9gfrmxkUF_7DTpq0gn6rntP05g2-wFW50YO7mosfdslfrTJYWHFhJALabAeYirYD7-9kqq9ebfFMF4sRRELbv9oi36As6Q9B3Qb5_C1rAzqfao_PCsf9EPsTZsVVVkA5qoIAr47lo1ipfiBPxUCCNSdvkmDTYgvvRm6ZoMjFbvOtgyts55fXKdMWv7I9HMD5HwE9uW839PWA514qhbcIsXEYSFMPMV6fnlsiZvQQ', * }, * 'PS256', * ) * ``` */ export type KeyLike = { type: string } /** * JSON Web Key ([JWK](https://www.rfc-editor.org/rfc/rfc7517)). "RSA", "EC", "OKP", and "oct" key * types are supported. */ export interface JWK { /** JWK "alg" (Algorithm) Parameter. */ alg?: string crv?: string d?: string dp?: string dq?: string e?: string /** JWK "ext" (Extractable) Parameter. */ ext?: boolean k?: string /** JWK "key_ops" (Key Operations) Parameter. */ key_ops?: string[] /** JWK "kid" (Key ID) Parameter. */ kid?: string /** JWK "kty" (Key Type) Parameter. */ kty?: string n?: string oth?: Array<{ d?: string r?: string t?: string }> p?: string q?: string qi?: string /** JWK "use" (Public Key Use) Parameter. */ use?: string x?: string y?: string /** JWK "x5c" (X.509 Certificate Chain) Parameter. */ x5c?: string[] /** JWK "x5t" (X.509 Certificate SHA-1 Thumbprint) Parameter. */ x5t?: string /** "x5t#S256" (X.509 Certificate SHA-256 Thumbprint) Parameter. */ 'x5t#S256'?: string /** JWK "x5u" (X.509 URL) Parameter. */ x5u?: string [propName: string]: unknown } /** * Generic Interface for consuming operations dynamic key resolution. No token components have been * verified at the time of this function call. * * If you cannot match a key suitable for the token, throw an error instead. * * @param protectedHeader JWE or JWS Protected Header. * @param token The consumed JWE or JWS token. */ export interface GetKeyFunction { (protectedHeader: T, token: T2): Promise | KeyLike | Uint8Array } /** * Flattened JWS definition for verify function inputs, allows payload as Uint8Array for detached * signature validation. */ export interface FlattenedJWSInput { /** * The "header" member MUST be present and contain the value JWS Unprotected Header when the JWS * Unprotected Header value is non- empty; otherwise, it MUST be absent. This value is represented * as an unencoded JSON object, rather than as a string. These Header Parameter values are not * integrity protected. */ header?: JWSHeaderParameters /** * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When RFC7797 * "b64": false is used the value passed may also be a Uint8Array. */ payload: string | Uint8Array /** * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWS Protected * Header)) when the JWS Protected Header value is non-empty; otherwise, it MUST be absent. These * Header Parameter values are integrity protected. */ protected?: string /** The "signature" member MUST be present and contain the value BASE64URL(JWS Signature). */ signature: string } /** * General JWS definition for verify function inputs, allows payload as Uint8Array for detached * signature validation. */ export interface GeneralJWSInput { /** * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When RFC7797 * "b64": false is used the value passed may also be a Uint8Array. */ payload: string | Uint8Array /** * The "signatures" member value MUST be an array of JSON objects. Each object represents a * signature or MAC over the JWS Payload and the JWS Protected Header. */ signatures: Omit[] } /** * Flattened JWS definition. Payload is returned as an empty string when JWS Unencoded Payload * Option [RFC7797](https://www.rfc-editor.org/rfc/rfc7797) is used. */ export interface FlattenedJWS extends Partial { payload: string signature: string } /** * General JWS definition. Payload is returned as an empty string when JWS Unencoded Payload Option * [RFC7797](https://www.rfc-editor.org/rfc/rfc7797) is used. */ export interface GeneralJWS { payload: string signatures: Omit[] } export interface JoseHeaderParameters { /** "kid" (Key ID) Header Parameter. */ kid?: string /** "x5t" (X.509 Certificate SHA-1 Thumbprint) Header Parameter. */ x5t?: string /** "x5c" (X.509 Certificate Chain) Header Parameter. */ x5c?: string[] /** "x5u" (X.509 URL) Header Parameter. */ x5u?: string /** "jku" (JWK Set URL) Header Parameter. */ jku?: string /** "jwk" (JSON Web Key) Header Parameter. */ jwk?: Pick /** "typ" (Type) Header Parameter. */ typ?: string /** "cty" (Content Type) Header Parameter. */ cty?: string } /** Recognized JWS Header Parameters, any other Header Members may also be present. */ export interface JWSHeaderParameters extends JoseHeaderParameters { /** JWS "alg" (Algorithm) Header Parameter. */ alg?: string /** * This JWS Extension Header Parameter modifies the JWS Payload representation and the JWS Signing * Input computation as per [RFC7797](https://www.rfc-editor.org/rfc/rfc7797). */ b64?: boolean /** JWS "crit" (Critical) Header Parameter. */ crit?: string[] /** Any other JWS Header member. */ [propName: string]: unknown } /** Recognized JWE Key Management-related Header Parameters. */ export interface JWEKeyManagementHeaderParameters { apu?: Uint8Array apv?: Uint8Array /** * @deprecated You should not use this parameter. It is only really intended for test and vector * validation purposes. */ p2c?: number /** * @deprecated You should not use this parameter. It is only really intended for test and vector * validation purposes. */ p2s?: Uint8Array /** * @deprecated You should not use this parameter. It is only really intended for test and vector * validation purposes. */ iv?: Uint8Array /** * @deprecated You should not use this parameter. It is only really intended for test and vector * validation purposes. */ epk?: KeyLike } /** Flattened JWE definition. */ export interface FlattenedJWE { /** * The "aad" member MUST be present and contain the value BASE64URL(JWE AAD)) when the JWE AAD * value is non-empty; otherwise, it MUST be absent. A JWE AAD value can be included to supply a * base64url-encoded value to be integrity protected but not encrypted. */ aad?: string /** The "ciphertext" member MUST be present and contain the value BASE64URL(JWE Ciphertext). */ ciphertext: string /** * The "encrypted_key" member MUST be present and contain the value BASE64URL(JWE Encrypted Key) * when the JWE Encrypted Key value is non-empty; otherwise, it MUST be absent. */ encrypted_key?: string /** * The "header" member MUST be present and contain the value JWE Per- Recipient Unprotected Header * when the JWE Per-Recipient Unprotected Header value is non-empty; otherwise, it MUST be absent. * This value is represented as an unencoded JSON object, rather than as a string. These Header * Parameter values are not integrity protected. */ header?: JWEHeaderParameters /** * The "iv" member MUST be present and contain the value BASE64URL(JWE Initialization Vector) when * the JWE Initialization Vector value is non-empty; otherwise, it MUST be absent. */ iv: string /** * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWE Protected * Header)) when the JWE Protected Header value is non-empty; otherwise, it MUST be absent. These * Header Parameter values are integrity protected. */ protected?: string /** * The "tag" member MUST be present and contain the value BASE64URL(JWE Authentication Tag) when * the JWE Authentication Tag value is non-empty; otherwise, it MUST be absent. */ tag: string /** * The "unprotected" member MUST be present and contain the value JWE Shared Unprotected Header * when the JWE Shared Unprotected Header value is non-empty; otherwise, it MUST be absent. This * value is represented as an unencoded JSON object, rather than as a string. These Header * Parameter values are not integrity protected. */ unprotected?: JWEHeaderParameters } export interface GeneralJWE extends Omit { recipients: Pick[] } /** Recognized JWE Header Parameters, any other Header members may also be present. */ export interface JWEHeaderParameters extends JoseHeaderParameters { /** JWE "alg" (Algorithm) Header Parameter. */ alg?: string /** JWE "enc" (Encryption Algorithm) Header Parameter. */ enc?: string /** JWE "crit" (Critical) Header Parameter. */ crit?: string[] /** JWE "zip" (Compression Algorithm) Header Parameter. */ zip?: string /** Any other JWE Header member. */ [propName: string]: unknown } /** Shared Interface with a "crit" property for all sign, verify, encrypt and decrypt operations. */ export interface CritOption { /** * An object with keys representing recognized "crit" (Critical) Header Parameter names. The value * for those is either `true` or `false`. `true` when the Header Parameter MUST be integrity * protected, `false` when it's irrelevant. * * This makes the "Extension Header Parameter "..." is not recognized" error go away. * * Use this when a given JWS/JWT/JWE profile requires the use of proprietary non-registered "crit" * (Critical) Header Parameters. This will only make sure the Header Parameter is syntactically * correct when provided and that it is optionally integrity protected. It will not process the * Header Parameter in any way or reject the operation if it is missing. You MUST still verify the * Header Parameter was present and process it according to the profile's validation steps after * the operation succeeds. * * The JWS extension Header Parameter `b64` is always recognized and processed properly. No other * registered Header Parameters that need this kind of default built-in treatment are currently * available. */ crit?: { [propName: string]: boolean } } /** JWE Decryption options. */ export interface DecryptOptions extends CritOption { /** A list of accepted JWE "alg" (Algorithm) Header Parameter values. */ keyManagementAlgorithms?: string[] /** * A list of accepted JWE "enc" (Encryption Algorithm) Header Parameter values. By default all * "enc" (Encryption Algorithm) values applicable for the used key/secret are allowed. */ contentEncryptionAlgorithms?: string[] /** * In a browser runtime you have to provide an implementation for Inflate Raw when you expect JWEs * with compressed plaintext. */ inflateRaw?: InflateFunction /** * (PBES2 Key Management Algorithms only) Maximum allowed "p2c" (PBES2 Count) Header Parameter * value. The PBKDF2 iteration count defines the algorithm's computational expense. By default * this value is set to 10000. */ maxPBES2Count?: number } /** JWE Deflate option. */ export interface DeflateOption { /** * In a browser runtime you have to provide an implementation for Deflate Raw when you will be * producing JWEs with compressed plaintext. */ deflateRaw?: DeflateFunction } /** JWE Encryption options. */ export interface EncryptOptions extends CritOption, DeflateOption {} /** JWT Claims Set verification options. */ export interface JWTClaimVerificationOptions { /** Expected JWT "aud" (Audience) Claim value(s). */ audience?: string | string[] /** * Expected clock tolerance * * - In seconds when number (e.g. 5) * - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). */ clockTolerance?: string | number /** Expected JWT "iss" (Issuer) Claim value(s). */ issuer?: string | string[] /** * Maximum time elapsed (in seconds) from the JWT "iat" (Issued At) Claim value. * * - In seconds when number (e.g. 5) * - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). */ maxTokenAge?: string | number /** Expected JWT "sub" (Subject) Claim value. */ subject?: string /** Expected JWT "typ" (Type) Header Parameter value. */ typ?: string /** Date to use when comparing NumericDate claims, defaults to `new Date()`. */ currentDate?: Date } /** JWS Verification options. */ export interface VerifyOptions extends CritOption { /** * A list of accepted JWS "alg" (Algorithm) Header Parameter values. By default all "alg" * (Algorithm) values applicable for the used key/secret are allowed. Note: "none" is never * accepted. */ algorithms?: string[] } /** JWS Signing options. */ export interface SignOptions extends CritOption {} /** Recognized JWT Claims Set members, any other members may also be present. */ export interface JWTPayload { /** * JWT Issuer * * @see [RFC7519#section-4.1.1](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.1) */ iss?: string /** * JWT Subject * * @see [RFC7519#section-4.1.2](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.2) */ sub?: string /** JWT Audience [RFC7519#section-4.1.3](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3). */ aud?: string | string[] /** * JWT ID * * @see [RFC7519#section-4.1.7](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7) */ jti?: string /** * JWT Not Before * * @see [RFC7519#section-4.1.5](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.5) */ nbf?: number /** * JWT Expiration Time * * @see [RFC7519#section-4.1.4](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4) */ exp?: number /** * JWT Issued At * * @see [RFC7519#section-4.1.6](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6) */ iat?: number /** Any other JWT Claim Set member. */ [propName: string]: unknown } /** * Deflate Raw implementation, e.g. promisified * [zlib.deflateRaw](https://nodejs.org/api/zlib.html#zlibdeflaterawbuffer-options-callback). */ export interface DeflateFunction { (input: Uint8Array): Promise } /** * Inflate Raw implementation, e.g. promisified * [zlib.inflateRaw](https://nodejs.org/api/zlib.html#zlibinflaterawbuffer-options-callback). */ export interface InflateFunction { (input: Uint8Array): Promise } export interface FlattenedDecryptResult { /** JWE AAD. */ additionalAuthenticatedData?: Uint8Array /** Plaintext. */ plaintext: Uint8Array /** JWE Protected Header. */ protectedHeader?: JWEHeaderParameters /** JWE Shared Unprotected Header. */ sharedUnprotectedHeader?: JWEHeaderParameters /** JWE Per-Recipient Unprotected Header. */ unprotectedHeader?: JWEHeaderParameters } export interface GeneralDecryptResult extends FlattenedDecryptResult {} export interface CompactDecryptResult { /** Plaintext. */ plaintext: Uint8Array /** JWE Protected Header. */ protectedHeader: CompactJWEHeaderParameters } export interface FlattenedVerifyResult { /** JWS Payload. */ payload: Uint8Array /** JWS Protected Header. */ protectedHeader?: JWSHeaderParameters /** JWS Unprotected Header. */ unprotectedHeader?: JWSHeaderParameters } export interface GeneralVerifyResult extends FlattenedVerifyResult {} export interface CompactVerifyResult { /** JWS Payload. */ payload: Uint8Array /** JWS Protected Header. */ protectedHeader: CompactJWSHeaderParameters } export interface JWTVerifyResult { /** JWT Claims Set. */ payload: JWTPayload /** JWS Protected Header. */ protectedHeader: JWTHeaderParameters } export interface JWTDecryptResult { /** JWT Claims Set. */ payload: JWTPayload /** JWE Protected Header. */ protectedHeader: CompactJWEHeaderParameters } export interface ResolvedKey { /** Key resolved from the key resolver function. */ key: KeyLike | Uint8Array } /** Recognized Compact JWS Header Parameters, any other Header Members may also be present. */ export interface CompactJWSHeaderParameters extends JWSHeaderParameters { alg: string } /** Recognized Signed JWT Header Parameters, any other Header Members may also be present. */ export interface JWTHeaderParameters extends CompactJWSHeaderParameters { b64?: true } /** Recognized Compact JWE Header Parameters, any other Header Members may also be present. */ export interface CompactJWEHeaderParameters extends JWEHeaderParameters { alg: string enc: string } /** JSON Web Key Set */ export interface JSONWebKeySet { keys: JWK[] } jose-4.11.4/dist/deno/util/000077500000000000000000000000001437043056600154165ustar00rootroot00000000000000jose-4.11.4/dist/deno/util/base64url.ts000066400000000000000000000010751437043056600176000ustar00rootroot00000000000000import * as base64url from '../runtime/base64url.ts' /** * Utility function to encode a string or Uint8Array as a base64url string. * * @param input Value that will be base64url-encoded. */ interface Base64UrlEncode { (input: Uint8Array | string): string } /** * Utility function to decode a base64url encoded string. * * @param input Value that will be base64url-decoded. */ interface Base64UrlDecode { (input: Uint8Array | string): Uint8Array } export const encode: Base64UrlEncode = base64url.encode export const decode: Base64UrlDecode = base64url.decode jose-4.11.4/dist/deno/util/decode_jwt.ts000066400000000000000000000031141437043056600200740ustar00rootroot00000000000000import { decode as base64url } from './base64url.ts' import { decoder } from '../lib/buffer_utils.ts' import isObject from '../lib/is_object.ts' import type { JWTPayload } from '../types.d.ts' import { JWTInvalid } from './errors.ts' /** * Decodes a signed JSON Web Token payload. This does not validate the JWT Claims Set types or * values. This does not validate the JWS Signature. For a proper Signed JWT Claims Set validation * and JWS signature verification use `jose.jwtVerify()`. For an encrypted JWT Claims Set validation * and JWE decryption use `jose.jwtDecrypt()`. * * @example Usage * * ```js * const claims = jose.decodeJwt(token) * console.log(claims) * ``` * * @param jwt JWT token in compact JWS serialization. */ export function decodeJwt(jwt: string) { if (typeof jwt !== 'string') throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string') const { 1: payload, length } = jwt.split('.') if (length === 5) throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded') if (length !== 3) throw new JWTInvalid('Invalid JWT') if (!payload) throw new JWTInvalid('JWTs must contain a payload') let decoded: Uint8Array try { decoded = base64url(payload) } catch { throw new JWTInvalid('Failed to parse the base64url encoded payload') } let result: unknown try { result = JSON.parse(decoder.decode(decoded)) } catch { throw new JWTInvalid('Failed to parse the decoded payload as JSON') } if (!isObject(result)) throw new JWTInvalid('Invalid JWT Claims Set') return result } jose-4.11.4/dist/deno/util/decode_protected_header.ts000066400000000000000000000026671437043056600226050ustar00rootroot00000000000000import { decode as base64url } from './base64url.ts' import { decoder } from '../lib/buffer_utils.ts' import isObject from '../lib/is_object.ts' import type { JWSHeaderParameters, JWEHeaderParameters } from '../types.d.ts' export type ProtectedHeaderParameters = JWSHeaderParameters & JWEHeaderParameters /** * Decodes the Protected Header of a JWE/JWS/JWT token utilizing any JOSE serialization. * * @example Usage * * ```js * const protectedHeader = jose.decodeProtectedHeader(token) * console.log(protectedHeader) * ``` * * @param token JWE/JWS/JWT token in any JOSE serialization. */ export function decodeProtectedHeader(token: string | object) { let protectedB64u!: string if (typeof token === 'string') { const parts = token.split('.') if (parts.length === 3 || parts.length === 5) { ;[protectedB64u] = parts } } else if (typeof token === 'object' && token) { if ('protected' in token) { protectedB64u = (<{ protected: string }>token).protected } else { throw new TypeError('Token does not contain a Protected Header') } } try { if (typeof protectedB64u !== 'string' || !protectedB64u) { throw new Error() } const result = JSON.parse(decoder.decode(base64url(protectedB64u!))) if (!isObject(result)) { throw new Error() } return result } catch { throw new TypeError('Invalid Token or Protected Header formatting') } } jose-4.11.4/dist/deno/util/errors.ts000066400000000000000000000113151437043056600173030ustar00rootroot00000000000000/** A generic Error subclass that all other specific JOSE Error subclasses inherit from. */ export class JOSEError extends Error { /** A unique error code for the particular error subclass. */ static get code(): string { return 'ERR_JOSE_GENERIC' } /** A unique error code for the particular error subclass. */ code: string = 'ERR_JOSE_GENERIC' constructor(message?: string) { super(message) this.name = this.constructor.name // @ts-ignore Error.captureStackTrace?.(this, this.constructor) } } /** An error subclass thrown when a JWT Claim Set member validation fails. */ export class JWTClaimValidationFailed extends JOSEError { static get code(): 'ERR_JWT_CLAIM_VALIDATION_FAILED' { return 'ERR_JWT_CLAIM_VALIDATION_FAILED' } code = 'ERR_JWT_CLAIM_VALIDATION_FAILED' /** The Claim for which the validation failed. */ claim: string /** Reason code for the validation failure. */ reason: string constructor(message: string, claim = 'unspecified', reason = 'unspecified') { super(message) this.claim = claim this.reason = reason } } /** An error subclass thrown when a JWT is expired. */ export class JWTExpired extends JOSEError implements JWTClaimValidationFailed { static get code(): 'ERR_JWT_EXPIRED' { return 'ERR_JWT_EXPIRED' } code = 'ERR_JWT_EXPIRED' /** The Claim for which the validation failed. */ claim: string /** Reason code for the validation failure. */ reason: string constructor(message: string, claim = 'unspecified', reason = 'unspecified') { super(message) this.claim = claim this.reason = reason } } /** An error subclass thrown when a JOSE Algorithm is not allowed per developer preference. */ export class JOSEAlgNotAllowed extends JOSEError { static get code(): 'ERR_JOSE_ALG_NOT_ALLOWED' { return 'ERR_JOSE_ALG_NOT_ALLOWED' } code = 'ERR_JOSE_ALG_NOT_ALLOWED' } /** * An error subclass thrown when a particular feature or algorithm is not supported by this * implementation or JOSE in general. */ export class JOSENotSupported extends JOSEError { static get code(): 'ERR_JOSE_NOT_SUPPORTED' { return 'ERR_JOSE_NOT_SUPPORTED' } code = 'ERR_JOSE_NOT_SUPPORTED' } /** An error subclass thrown when a JWE ciphertext decryption fails. */ export class JWEDecryptionFailed extends JOSEError { static get code(): 'ERR_JWE_DECRYPTION_FAILED' { return 'ERR_JWE_DECRYPTION_FAILED' } code = 'ERR_JWE_DECRYPTION_FAILED' message = 'decryption operation failed' } /** An error subclass thrown when a JWE is invalid. */ export class JWEInvalid extends JOSEError { static get code(): 'ERR_JWE_INVALID' { return 'ERR_JWE_INVALID' } code = 'ERR_JWE_INVALID' } /** An error subclass thrown when a JWS is invalid. */ export class JWSInvalid extends JOSEError { static get code(): 'ERR_JWS_INVALID' { return 'ERR_JWS_INVALID' } code = 'ERR_JWS_INVALID' } /** An error subclass thrown when a JWT is invalid. */ export class JWTInvalid extends JOSEError { static get code(): 'ERR_JWT_INVALID' { return 'ERR_JWT_INVALID' } code = 'ERR_JWT_INVALID' } /** An error subclass thrown when a JWK is invalid. */ export class JWKInvalid extends JOSEError { static get code(): 'ERR_JWK_INVALID' { return 'ERR_JWK_INVALID' } code = 'ERR_JWK_INVALID' } /** An error subclass thrown when a JWKS is invalid. */ export class JWKSInvalid extends JOSEError { static get code(): 'ERR_JWKS_INVALID' { return 'ERR_JWKS_INVALID' } code = 'ERR_JWKS_INVALID' } /** An error subclass thrown when no keys match from a JWKS. */ export class JWKSNoMatchingKey extends JOSEError { static get code(): 'ERR_JWKS_NO_MATCHING_KEY' { return 'ERR_JWKS_NO_MATCHING_KEY' } code = 'ERR_JWKS_NO_MATCHING_KEY' message = 'no applicable key found in the JSON Web Key Set' } /** An error subclass thrown when multiple keys match from a JWKS. */ export class JWKSMultipleMatchingKeys extends JOSEError { static get code(): 'ERR_JWKS_MULTIPLE_MATCHING_KEYS' { return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS' } code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS' message = 'multiple matching keys found in the JSON Web Key Set' } /** Timeout was reached when retrieving the JWKS response. */ export class JWKSTimeout extends JOSEError { static get code(): 'ERR_JWKS_TIMEOUT' { return 'ERR_JWKS_TIMEOUT' } code = 'ERR_JWKS_TIMEOUT' message = 'request timed out' } /** An error subclass thrown when JWS signature verification fails. */ export class JWSSignatureVerificationFailed extends JOSEError { static get code(): 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED' { return 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED' } code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED' message = 'signature verification failed' } jose-4.11.4/dist/node/000077500000000000000000000000001437043056600144415ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/000077500000000000000000000000001437043056600152205ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/index.js000066400000000000000000000150771437043056600166770ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.base64url = exports.generateSecret = exports.generateKeyPair = exports.errors = exports.decodeJwt = exports.decodeProtectedHeader = exports.importJWK = exports.importX509 = exports.importPKCS8 = exports.importSPKI = exports.exportJWK = exports.exportSPKI = exports.exportPKCS8 = exports.UnsecuredJWT = exports.createRemoteJWKSet = exports.createLocalJWKSet = exports.EmbeddedJWK = exports.calculateJwkThumbprintUri = exports.calculateJwkThumbprint = exports.EncryptJWT = exports.SignJWT = exports.GeneralSign = exports.FlattenedSign = exports.CompactSign = exports.FlattenedEncrypt = exports.CompactEncrypt = exports.jwtDecrypt = exports.jwtVerify = exports.generalVerify = exports.flattenedVerify = exports.compactVerify = exports.GeneralEncrypt = exports.generalDecrypt = exports.flattenedDecrypt = exports.compactDecrypt = void 0; var decrypt_js_1 = require("./jwe/compact/decrypt.js"); Object.defineProperty(exports, "compactDecrypt", { enumerable: true, get: function () { return decrypt_js_1.compactDecrypt; } }); var decrypt_js_2 = require("./jwe/flattened/decrypt.js"); Object.defineProperty(exports, "flattenedDecrypt", { enumerable: true, get: function () { return decrypt_js_2.flattenedDecrypt; } }); var decrypt_js_3 = require("./jwe/general/decrypt.js"); Object.defineProperty(exports, "generalDecrypt", { enumerable: true, get: function () { return decrypt_js_3.generalDecrypt; } }); var encrypt_js_1 = require("./jwe/general/encrypt.js"); Object.defineProperty(exports, "GeneralEncrypt", { enumerable: true, get: function () { return encrypt_js_1.GeneralEncrypt; } }); var verify_js_1 = require("./jws/compact/verify.js"); Object.defineProperty(exports, "compactVerify", { enumerable: true, get: function () { return verify_js_1.compactVerify; } }); var verify_js_2 = require("./jws/flattened/verify.js"); Object.defineProperty(exports, "flattenedVerify", { enumerable: true, get: function () { return verify_js_2.flattenedVerify; } }); var verify_js_3 = require("./jws/general/verify.js"); Object.defineProperty(exports, "generalVerify", { enumerable: true, get: function () { return verify_js_3.generalVerify; } }); var verify_js_4 = require("./jwt/verify.js"); Object.defineProperty(exports, "jwtVerify", { enumerable: true, get: function () { return verify_js_4.jwtVerify; } }); var decrypt_js_4 = require("./jwt/decrypt.js"); Object.defineProperty(exports, "jwtDecrypt", { enumerable: true, get: function () { return decrypt_js_4.jwtDecrypt; } }); var encrypt_js_2 = require("./jwe/compact/encrypt.js"); Object.defineProperty(exports, "CompactEncrypt", { enumerable: true, get: function () { return encrypt_js_2.CompactEncrypt; } }); var encrypt_js_3 = require("./jwe/flattened/encrypt.js"); Object.defineProperty(exports, "FlattenedEncrypt", { enumerable: true, get: function () { return encrypt_js_3.FlattenedEncrypt; } }); var sign_js_1 = require("./jws/compact/sign.js"); Object.defineProperty(exports, "CompactSign", { enumerable: true, get: function () { return sign_js_1.CompactSign; } }); var sign_js_2 = require("./jws/flattened/sign.js"); Object.defineProperty(exports, "FlattenedSign", { enumerable: true, get: function () { return sign_js_2.FlattenedSign; } }); var sign_js_3 = require("./jws/general/sign.js"); Object.defineProperty(exports, "GeneralSign", { enumerable: true, get: function () { return sign_js_3.GeneralSign; } }); var sign_js_4 = require("./jwt/sign.js"); Object.defineProperty(exports, "SignJWT", { enumerable: true, get: function () { return sign_js_4.SignJWT; } }); var encrypt_js_4 = require("./jwt/encrypt.js"); Object.defineProperty(exports, "EncryptJWT", { enumerable: true, get: function () { return encrypt_js_4.EncryptJWT; } }); var thumbprint_js_1 = require("./jwk/thumbprint.js"); Object.defineProperty(exports, "calculateJwkThumbprint", { enumerable: true, get: function () { return thumbprint_js_1.calculateJwkThumbprint; } }); Object.defineProperty(exports, "calculateJwkThumbprintUri", { enumerable: true, get: function () { return thumbprint_js_1.calculateJwkThumbprintUri; } }); var embedded_js_1 = require("./jwk/embedded.js"); Object.defineProperty(exports, "EmbeddedJWK", { enumerable: true, get: function () { return embedded_js_1.EmbeddedJWK; } }); var local_js_1 = require("./jwks/local.js"); Object.defineProperty(exports, "createLocalJWKSet", { enumerable: true, get: function () { return local_js_1.createLocalJWKSet; } }); var remote_js_1 = require("./jwks/remote.js"); Object.defineProperty(exports, "createRemoteJWKSet", { enumerable: true, get: function () { return remote_js_1.createRemoteJWKSet; } }); var unsecured_js_1 = require("./jwt/unsecured.js"); Object.defineProperty(exports, "UnsecuredJWT", { enumerable: true, get: function () { return unsecured_js_1.UnsecuredJWT; } }); var export_js_1 = require("./key/export.js"); Object.defineProperty(exports, "exportPKCS8", { enumerable: true, get: function () { return export_js_1.exportPKCS8; } }); Object.defineProperty(exports, "exportSPKI", { enumerable: true, get: function () { return export_js_1.exportSPKI; } }); Object.defineProperty(exports, "exportJWK", { enumerable: true, get: function () { return export_js_1.exportJWK; } }); var import_js_1 = require("./key/import.js"); Object.defineProperty(exports, "importSPKI", { enumerable: true, get: function () { return import_js_1.importSPKI; } }); Object.defineProperty(exports, "importPKCS8", { enumerable: true, get: function () { return import_js_1.importPKCS8; } }); Object.defineProperty(exports, "importX509", { enumerable: true, get: function () { return import_js_1.importX509; } }); Object.defineProperty(exports, "importJWK", { enumerable: true, get: function () { return import_js_1.importJWK; } }); var decode_protected_header_js_1 = require("./util/decode_protected_header.js"); Object.defineProperty(exports, "decodeProtectedHeader", { enumerable: true, get: function () { return decode_protected_header_js_1.decodeProtectedHeader; } }); var decode_jwt_js_1 = require("./util/decode_jwt.js"); Object.defineProperty(exports, "decodeJwt", { enumerable: true, get: function () { return decode_jwt_js_1.decodeJwt; } }); exports.errors = require("./util/errors.js"); var generate_key_pair_js_1 = require("./key/generate_key_pair.js"); Object.defineProperty(exports, "generateKeyPair", { enumerable: true, get: function () { return generate_key_pair_js_1.generateKeyPair; } }); var generate_secret_js_1 = require("./key/generate_secret.js"); Object.defineProperty(exports, "generateSecret", { enumerable: true, get: function () { return generate_secret_js_1.generateSecret; } }); exports.base64url = require("./util/base64url.js"); jose-4.11.4/dist/node/cjs/jwe/000077500000000000000000000000001437043056600160055ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/jwe/compact/000077500000000000000000000000001437043056600174335ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/jwe/compact/decrypt.js000066400000000000000000000024061437043056600214450ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.compactDecrypt = void 0; const decrypt_js_1 = require("../flattened/decrypt.js"); const errors_js_1 = require("../../util/errors.js"); const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); async function compactDecrypt(jwe, key, options) { if (jwe instanceof Uint8Array) { jwe = buffer_utils_js_1.decoder.decode(jwe); } if (typeof jwe !== 'string') { throw new errors_js_1.JWEInvalid('Compact JWE must be a string or Uint8Array'); } const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.'); if (length !== 5) { throw new errors_js_1.JWEInvalid('Invalid Compact JWE'); } const decrypted = await (0, decrypt_js_1.flattenedDecrypt)({ ciphertext, iv: (iv || undefined), protected: protectedHeader || undefined, tag: (tag || undefined), encrypted_key: encryptedKey || undefined, }, key, options); const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; if (typeof key === 'function') { return { ...result, key: decrypted.key }; } return result; } exports.compactDecrypt = compactDecrypt; jose-4.11.4/dist/node/cjs/jwe/compact/encrypt.js000066400000000000000000000020131437043056600214510ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CompactEncrypt = void 0; const encrypt_js_1 = require("../flattened/encrypt.js"); class CompactEncrypt { constructor(plaintext) { this._flattened = new encrypt_js_1.FlattenedEncrypt(plaintext); } setContentEncryptionKey(cek) { this._flattened.setContentEncryptionKey(cek); return this; } setInitializationVector(iv) { this._flattened.setInitializationVector(iv); return this; } setProtectedHeader(protectedHeader) { this._flattened.setProtectedHeader(protectedHeader); return this; } setKeyManagementParameters(parameters) { this._flattened.setKeyManagementParameters(parameters); return this; } async encrypt(key, options) { const jwe = await this._flattened.encrypt(key, options); return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.'); } } exports.CompactEncrypt = CompactEncrypt; jose-4.11.4/dist/node/cjs/jwe/flattened/000077500000000000000000000000001437043056600177535ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/jwe/flattened/decrypt.js000066400000000000000000000150521437043056600217660ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.flattenedDecrypt = void 0; const base64url_js_1 = require("../../runtime/base64url.js"); const decrypt_js_1 = require("../../runtime/decrypt.js"); const zlib_js_1 = require("../../runtime/zlib.js"); const errors_js_1 = require("../../util/errors.js"); const is_disjoint_js_1 = require("../../lib/is_disjoint.js"); const is_object_js_1 = require("../../lib/is_object.js"); const decrypt_key_management_js_1 = require("../../lib/decrypt_key_management.js"); const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); const cek_js_1 = require("../../lib/cek.js"); const validate_crit_js_1 = require("../../lib/validate_crit.js"); const validate_algorithms_js_1 = require("../../lib/validate_algorithms.js"); async function flattenedDecrypt(jwe, key, options) { var _a; if (!(0, is_object_js_1.default)(jwe)) { throw new errors_js_1.JWEInvalid('Flattened JWE must be an object'); } if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) { throw new errors_js_1.JWEInvalid('JOSE Header missing'); } if (typeof jwe.iv !== 'string') { throw new errors_js_1.JWEInvalid('JWE Initialization Vector missing or incorrect type'); } if (typeof jwe.ciphertext !== 'string') { throw new errors_js_1.JWEInvalid('JWE Ciphertext missing or incorrect type'); } if (typeof jwe.tag !== 'string') { throw new errors_js_1.JWEInvalid('JWE Authentication Tag missing or incorrect type'); } if (jwe.protected !== undefined && typeof jwe.protected !== 'string') { throw new errors_js_1.JWEInvalid('JWE Protected Header incorrect type'); } if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') { throw new errors_js_1.JWEInvalid('JWE Encrypted Key incorrect type'); } if (jwe.aad !== undefined && typeof jwe.aad !== 'string') { throw new errors_js_1.JWEInvalid('JWE AAD incorrect type'); } if (jwe.header !== undefined && !(0, is_object_js_1.default)(jwe.header)) { throw new errors_js_1.JWEInvalid('JWE Shared Unprotected Header incorrect type'); } if (jwe.unprotected !== undefined && !(0, is_object_js_1.default)(jwe.unprotected)) { throw new errors_js_1.JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type'); } let parsedProt; if (jwe.protected) { try { const protectedHeader = (0, base64url_js_1.decode)(jwe.protected); parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader)); } catch { throw new errors_js_1.JWEInvalid('JWE Protected Header is invalid'); } } if (!(0, is_disjoint_js_1.default)(parsedProt, jwe.header, jwe.unprotected)) { throw new errors_js_1.JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint'); } const joseHeader = { ...parsedProt, ...jwe.header, ...jwe.unprotected, }; (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader); if (joseHeader.zip !== undefined) { if (!parsedProt || !parsedProt.zip) { throw new errors_js_1.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); } if (joseHeader.zip !== 'DEF') { throw new errors_js_1.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value'); } } const { alg, enc } = joseHeader; if (typeof alg !== 'string' || !alg) { throw new errors_js_1.JWEInvalid('missing JWE Algorithm (alg) in JWE Header'); } if (typeof enc !== 'string' || !enc) { throw new errors_js_1.JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header'); } const keyManagementAlgorithms = options && (0, validate_algorithms_js_1.default)('keyManagementAlgorithms', options.keyManagementAlgorithms); const contentEncryptionAlgorithms = options && (0, validate_algorithms_js_1.default)('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms); if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) { throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed'); } if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { throw new errors_js_1.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed'); } let encryptedKey; if (jwe.encrypted_key !== undefined) { encryptedKey = (0, base64url_js_1.decode)(jwe.encrypted_key); } let resolvedKey = false; if (typeof key === 'function') { key = await key(parsedProt, jwe); resolvedKey = true; } let cek; try { cek = await (0, decrypt_key_management_js_1.default)(alg, key, encryptedKey, joseHeader, options); } catch (err) { if (err instanceof TypeError || err instanceof errors_js_1.JWEInvalid || err instanceof errors_js_1.JOSENotSupported) { throw err; } cek = (0, cek_js_1.default)(enc); } const iv = (0, base64url_js_1.decode)(jwe.iv); const tag = (0, base64url_js_1.decode)(jwe.tag); const protectedHeader = buffer_utils_js_1.encoder.encode((_a = jwe.protected) !== null && _a !== void 0 ? _a : ''); let additionalData; if (jwe.aad !== undefined) { additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), buffer_utils_js_1.encoder.encode(jwe.aad)); } else { additionalData = protectedHeader; } let plaintext = await (0, decrypt_js_1.default)(enc, cek, (0, base64url_js_1.decode)(jwe.ciphertext), iv, tag, additionalData); if (joseHeader.zip === 'DEF') { plaintext = await ((options === null || options === void 0 ? void 0 : options.inflateRaw) || zlib_js_1.inflate)(plaintext); } const result = { plaintext }; if (jwe.protected !== undefined) { result.protectedHeader = parsedProt; } if (jwe.aad !== undefined) { result.additionalAuthenticatedData = (0, base64url_js_1.decode)(jwe.aad); } if (jwe.unprotected !== undefined) { result.sharedUnprotectedHeader = jwe.unprotected; } if (jwe.header !== undefined) { result.unprotectedHeader = jwe.header; } if (resolvedKey) { return { ...result, key }; } return result; } exports.flattenedDecrypt = flattenedDecrypt; jose-4.11.4/dist/node/cjs/jwe/flattened/encrypt.js000066400000000000000000000167771437043056600220170ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FlattenedEncrypt = exports.unprotected = void 0; const base64url_js_1 = require("../../runtime/base64url.js"); const encrypt_js_1 = require("../../runtime/encrypt.js"); const zlib_js_1 = require("../../runtime/zlib.js"); const iv_js_1 = require("../../lib/iv.js"); const encrypt_key_management_js_1 = require("../../lib/encrypt_key_management.js"); const errors_js_1 = require("../../util/errors.js"); const is_disjoint_js_1 = require("../../lib/is_disjoint.js"); const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); const validate_crit_js_1 = require("../../lib/validate_crit.js"); exports.unprotected = Symbol(); class FlattenedEncrypt { constructor(plaintext) { if (!(plaintext instanceof Uint8Array)) { throw new TypeError('plaintext must be an instance of Uint8Array'); } this._plaintext = plaintext; } setKeyManagementParameters(parameters) { if (this._keyManagementParameters) { throw new TypeError('setKeyManagementParameters can only be called once'); } this._keyManagementParameters = parameters; return this; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once'); } this._protectedHeader = protectedHeader; return this; } setSharedUnprotectedHeader(sharedUnprotectedHeader) { if (this._sharedUnprotectedHeader) { throw new TypeError('setSharedUnprotectedHeader can only be called once'); } this._sharedUnprotectedHeader = sharedUnprotectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once'); } this._unprotectedHeader = unprotectedHeader; return this; } setAdditionalAuthenticatedData(aad) { this._aad = aad; return this; } setContentEncryptionKey(cek) { if (this._cek) { throw new TypeError('setContentEncryptionKey can only be called once'); } this._cek = cek; return this; } setInitializationVector(iv) { if (this._iv) { throw new TypeError('setInitializationVector can only be called once'); } this._iv = iv; return this; } async encrypt(key, options) { if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { throw new errors_js_1.JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()'); } if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) { throw new errors_js_1.JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...this._sharedUnprotectedHeader, }; (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader); if (joseHeader.zip !== undefined) { if (!this._protectedHeader || !this._protectedHeader.zip) { throw new errors_js_1.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); } if (joseHeader.zip !== 'DEF') { throw new errors_js_1.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value'); } } const { alg, enc } = joseHeader; if (typeof alg !== 'string' || !alg) { throw new errors_js_1.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); } if (typeof enc !== 'string' || !enc) { throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); } let encryptedKey; if (alg === 'dir') { if (this._cek) { throw new TypeError('setContentEncryptionKey cannot be called when using Direct Encryption'); } } else if (alg === 'ECDH-ES') { if (this._cek) { throw new TypeError('setContentEncryptionKey cannot be called when using Direct Key Agreement'); } } let cek; { let parameters; ({ cek, encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(alg, enc, key, this._cek, this._keyManagementParameters)); if (parameters) { if (options && exports.unprotected in options) { if (!this._unprotectedHeader) { this.setUnprotectedHeader(parameters); } else { this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters }; } } else { if (!this._protectedHeader) { this.setProtectedHeader(parameters); } else { this._protectedHeader = { ...this._protectedHeader, ...parameters }; } } } } this._iv || (this._iv = (0, iv_js_1.default)(enc)); let additionalData; let protectedHeader; let aadMember; if (this._protectedHeader) { protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader))); } else { protectedHeader = buffer_utils_js_1.encoder.encode(''); } if (this._aad) { aadMember = (0, base64url_js_1.encode)(this._aad); additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), buffer_utils_js_1.encoder.encode(aadMember)); } else { additionalData = protectedHeader; } let ciphertext; let tag; if (joseHeader.zip === 'DEF') { const deflated = await ((options === null || options === void 0 ? void 0 : options.deflateRaw) || zlib_js_1.deflate)(this._plaintext); ({ ciphertext, tag } = await (0, encrypt_js_1.default)(enc, deflated, cek, this._iv, additionalData)); } else { ; ({ ciphertext, tag } = await (0, encrypt_js_1.default)(enc, this._plaintext, cek, this._iv, additionalData)); } const jwe = { ciphertext: (0, base64url_js_1.encode)(ciphertext), iv: (0, base64url_js_1.encode)(this._iv), tag: (0, base64url_js_1.encode)(tag), }; if (encryptedKey) { jwe.encrypted_key = (0, base64url_js_1.encode)(encryptedKey); } if (aadMember) { jwe.aad = aadMember; } if (this._protectedHeader) { jwe.protected = buffer_utils_js_1.decoder.decode(protectedHeader); } if (this._sharedUnprotectedHeader) { jwe.unprotected = this._sharedUnprotectedHeader; } if (this._unprotectedHeader) { jwe.header = this._unprotectedHeader; } return jwe; } } exports.FlattenedEncrypt = FlattenedEncrypt; jose-4.11.4/dist/node/cjs/jwe/general/000077500000000000000000000000001437043056600174225ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/jwe/general/decrypt.js000066400000000000000000000025151437043056600214350ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generalDecrypt = void 0; const decrypt_js_1 = require("../flattened/decrypt.js"); const errors_js_1 = require("../../util/errors.js"); const is_object_js_1 = require("../../lib/is_object.js"); async function generalDecrypt(jwe, key, options) { if (!(0, is_object_js_1.default)(jwe)) { throw new errors_js_1.JWEInvalid('General JWE must be an object'); } if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(is_object_js_1.default)) { throw new errors_js_1.JWEInvalid('JWE Recipients missing or incorrect type'); } if (!jwe.recipients.length) { throw new errors_js_1.JWEInvalid('JWE Recipients has no members'); } for (const recipient of jwe.recipients) { try { return await (0, decrypt_js_1.flattenedDecrypt)({ aad: jwe.aad, ciphertext: jwe.ciphertext, encrypted_key: recipient.encrypted_key, header: recipient.header, iv: jwe.iv, protected: jwe.protected, tag: jwe.tag, unprotected: jwe.unprotected, }, key, options); } catch { } } throw new errors_js_1.JWEDecryptionFailed(); } exports.generalDecrypt = generalDecrypt; jose-4.11.4/dist/node/cjs/jwe/general/encrypt.js000066400000000000000000000200031437043056600214370ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GeneralEncrypt = void 0; const encrypt_js_1 = require("../flattened/encrypt.js"); const errors_js_1 = require("../../util/errors.js"); const cek_js_1 = require("../../lib/cek.js"); const is_disjoint_js_1 = require("../../lib/is_disjoint.js"); const encrypt_key_management_js_1 = require("../../lib/encrypt_key_management.js"); const base64url_js_1 = require("../../runtime/base64url.js"); const validate_crit_js_1 = require("../../lib/validate_crit.js"); class IndividualRecipient { constructor(enc, key, options) { this.parent = enc; this.key = key; this.options = options; } setUnprotectedHeader(unprotectedHeader) { if (this.unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once'); } this.unprotectedHeader = unprotectedHeader; return this; } addRecipient(...args) { return this.parent.addRecipient(...args); } encrypt(...args) { return this.parent.encrypt(...args); } done() { return this.parent; } } class GeneralEncrypt { constructor(plaintext) { this._recipients = []; this._plaintext = plaintext; } addRecipient(key, options) { const recipient = new IndividualRecipient(this, key, { crit: options === null || options === void 0 ? void 0 : options.crit }); this._recipients.push(recipient); return recipient; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once'); } this._protectedHeader = protectedHeader; return this; } setSharedUnprotectedHeader(sharedUnprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError('setSharedUnprotectedHeader can only be called once'); } this._unprotectedHeader = sharedUnprotectedHeader; return this; } setAdditionalAuthenticatedData(aad) { this._aad = aad; return this; } async encrypt(options) { var _a, _b, _c; if (!this._recipients.length) { throw new errors_js_1.JWEInvalid('at least one recipient must be added'); } options = { deflateRaw: options === null || options === void 0 ? void 0 : options.deflateRaw }; if (this._recipients.length === 1) { const [recipient] = this._recipients; const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext) .setAdditionalAuthenticatedData(this._aad) .setProtectedHeader(this._protectedHeader) .setSharedUnprotectedHeader(this._unprotectedHeader) .setUnprotectedHeader(recipient.unprotectedHeader) .encrypt(recipient.key, { ...recipient.options, ...options }); let jwe = { ciphertext: flattened.ciphertext, iv: flattened.iv, recipients: [{}], tag: flattened.tag, }; if (flattened.aad) jwe.aad = flattened.aad; if (flattened.protected) jwe.protected = flattened.protected; if (flattened.unprotected) jwe.unprotected = flattened.unprotected; if (flattened.encrypted_key) jwe.recipients[0].encrypted_key = flattened.encrypted_key; if (flattened.header) jwe.recipients[0].header = flattened.header; return jwe; } let enc; for (let i = 0; i < this._recipients.length; i++) { const recipient = this._recipients[i]; if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) { throw new errors_js_1.JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...recipient.unprotectedHeader, }; const { alg } = joseHeader; if (typeof alg !== 'string' || !alg) { throw new errors_js_1.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); } if (alg === 'dir' || alg === 'ECDH-ES') { throw new errors_js_1.JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); } if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) { throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); } if (!enc) { enc = joseHeader.enc; } else if (enc !== joseHeader.enc) { throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); } (0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader); if (joseHeader.zip !== undefined) { if (!this._protectedHeader || !this._protectedHeader.zip) { throw new errors_js_1.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); } } } const cek = (0, cek_js_1.default)(enc); let jwe = { ciphertext: '', iv: '', recipients: [], tag: '', }; for (let i = 0; i < this._recipients.length; i++) { const recipient = this._recipients[i]; const target = {}; jwe.recipients.push(target); const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...recipient.unprotectedHeader, }; const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined; if (i === 0) { const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext) .setAdditionalAuthenticatedData(this._aad) .setContentEncryptionKey(cek) .setProtectedHeader(this._protectedHeader) .setSharedUnprotectedHeader(this._unprotectedHeader) .setUnprotectedHeader(recipient.unprotectedHeader) .setKeyManagementParameters({ p2c }) .encrypt(recipient.key, { ...recipient.options, ...options, [encrypt_js_1.unprotected]: true, }); jwe.ciphertext = flattened.ciphertext; jwe.iv = flattened.iv; jwe.tag = flattened.tag; if (flattened.aad) jwe.aad = flattened.aad; if (flattened.protected) jwe.protected = flattened.protected; if (flattened.unprotected) jwe.unprotected = flattened.unprotected; target.encrypted_key = flattened.encrypted_key; if (flattened.header) target.header = flattened.header; continue; } const { encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(((_a = recipient.unprotectedHeader) === null || _a === void 0 ? void 0 : _a.alg) || ((_b = this._protectedHeader) === null || _b === void 0 ? void 0 : _b.alg) || ((_c = this._unprotectedHeader) === null || _c === void 0 ? void 0 : _c.alg), enc, recipient.key, cek, { p2c }); target.encrypted_key = (0, base64url_js_1.encode)(encryptedKey); if (recipient.unprotectedHeader || parameters) target.header = { ...recipient.unprotectedHeader, ...parameters }; } return jwe; } } exports.GeneralEncrypt = GeneralEncrypt; jose-4.11.4/dist/node/cjs/jwk/000077500000000000000000000000001437043056600160135ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/jwk/embedded.js000066400000000000000000000016011437043056600201000ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EmbeddedJWK = void 0; const import_js_1 = require("../key/import.js"); const is_object_js_1 = require("../lib/is_object.js"); const errors_js_1 = require("../util/errors.js"); async function EmbeddedJWK(protectedHeader, token) { const joseHeader = { ...protectedHeader, ...token.header, }; if (!(0, is_object_js_1.default)(joseHeader.jwk)) { throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); } const key = await (0, import_js_1.importJWK)({ ...joseHeader.jwk, ext: true }, joseHeader.alg, true); if (key instanceof Uint8Array || key.type !== 'public') { throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); } return key; } exports.EmbeddedJWK = EmbeddedJWK; jose-4.11.4/dist/node/cjs/jwk/thumbprint.js000066400000000000000000000053451437043056600205540ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.calculateJwkThumbprintUri = exports.calculateJwkThumbprint = void 0; const digest_js_1 = require("../runtime/digest.js"); const base64url_js_1 = require("../runtime/base64url.js"); const errors_js_1 = require("../util/errors.js"); const buffer_utils_js_1 = require("../lib/buffer_utils.js"); const is_object_js_1 = require("../lib/is_object.js"); const check = (value, description) => { if (typeof value !== 'string' || !value) { throw new errors_js_1.JWKInvalid(`${description} missing or invalid`); } }; async function calculateJwkThumbprint(jwk, digestAlgorithm) { if (!(0, is_object_js_1.default)(jwk)) { throw new TypeError('JWK must be an object'); } digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256'); if (digestAlgorithm !== 'sha256' && digestAlgorithm !== 'sha384' && digestAlgorithm !== 'sha512') { throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); } let components; switch (jwk.kty) { case 'EC': check(jwk.crv, '"crv" (Curve) Parameter'); check(jwk.x, '"x" (X Coordinate) Parameter'); check(jwk.y, '"y" (Y Coordinate) Parameter'); components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; break; case 'OKP': check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); check(jwk.x, '"x" (Public Key) Parameter'); components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; break; case 'RSA': check(jwk.e, '"e" (Exponent) Parameter'); check(jwk.n, '"n" (Modulus) Parameter'); components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; break; case 'oct': check(jwk.k, '"k" (Key Value) Parameter'); components = { k: jwk.k, kty: jwk.kty }; break; default: throw new errors_js_1.JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); } const data = buffer_utils_js_1.encoder.encode(JSON.stringify(components)); return (0, base64url_js_1.encode)(await (0, digest_js_1.default)(digestAlgorithm, data)); } exports.calculateJwkThumbprint = calculateJwkThumbprint; async function calculateJwkThumbprintUri(jwk, digestAlgorithm) { digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256'); const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm); return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; } exports.calculateJwkThumbprintUri = calculateJwkThumbprintUri; jose-4.11.4/dist/node/cjs/jwks/000077500000000000000000000000001437043056600161765ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/jwks/local.js000066400000000000000000000073071437043056600176350ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createLocalJWKSet = exports.LocalJWKSet = exports.isJWKSLike = void 0; const import_js_1 = require("../key/import.js"); const errors_js_1 = require("../util/errors.js"); const is_object_js_1 = require("../lib/is_object.js"); function getKtyFromAlg(alg) { switch (typeof alg === 'string' && alg.slice(0, 2)) { case 'RS': case 'PS': return 'RSA'; case 'ES': return 'EC'; case 'Ed': return 'OKP'; default: throw new errors_js_1.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); } } function isJWKSLike(jwks) { return (jwks && typeof jwks === 'object' && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike)); } exports.isJWKSLike = isJWKSLike; function isJWKLike(key) { return (0, is_object_js_1.default)(key); } function clone(obj) { if (typeof structuredClone === 'function') { return structuredClone(obj); } return JSON.parse(JSON.stringify(obj)); } class LocalJWKSet { constructor(jwks) { this._cached = new WeakMap(); if (!isJWKSLike(jwks)) { throw new errors_js_1.JWKSInvalid('JSON Web Key Set malformed'); } this._jwks = clone(jwks); } async getKey(protectedHeader, token) { const { alg, kid } = { ...protectedHeader, ...token.header }; const kty = getKtyFromAlg(alg); const candidates = this._jwks.keys.filter((jwk) => { let candidate = kty === jwk.kty; if (candidate && typeof kid === 'string') { candidate = kid === jwk.kid; } if (candidate && typeof jwk.alg === 'string') { candidate = alg === jwk.alg; } if (candidate && typeof jwk.use === 'string') { candidate = jwk.use === 'sig'; } if (candidate && Array.isArray(jwk.key_ops)) { candidate = jwk.key_ops.includes('verify'); } if (candidate && alg === 'EdDSA') { candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448'; } if (candidate) { switch (alg) { case 'ES256': candidate = jwk.crv === 'P-256'; break; case 'ES256K': candidate = jwk.crv === 'secp256k1'; break; case 'ES384': candidate = jwk.crv === 'P-384'; break; case 'ES512': candidate = jwk.crv === 'P-521'; break; } } return candidate; }); const { 0: jwk, length } = candidates; if (length === 0) { throw new errors_js_1.JWKSNoMatchingKey(); } else if (length !== 1) { throw new errors_js_1.JWKSMultipleMatchingKeys(); } const cached = this._cached.get(jwk) || this._cached.set(jwk, {}).get(jwk); if (cached[alg] === undefined) { const keyObject = await (0, import_js_1.importJWK)({ ...jwk, ext: true }, alg); if (keyObject instanceof Uint8Array || keyObject.type !== 'public') { throw new errors_js_1.JWKSInvalid('JSON Web Key Set members must be public keys'); } cached[alg] = keyObject; } return cached[alg]; } } exports.LocalJWKSet = LocalJWKSet; function createLocalJWKSet(jwks) { return LocalJWKSet.prototype.getKey.bind(new LocalJWKSet(jwks)); } exports.createLocalJWKSet = createLocalJWKSet; jose-4.11.4/dist/node/cjs/jwks/remote.js000066400000000000000000000070621437043056600200340ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createRemoteJWKSet = void 0; const fetch_jwks_js_1 = require("../runtime/fetch_jwks.js"); const env_js_1 = require("../runtime/env.js"); const errors_js_1 = require("../util/errors.js"); const local_js_1 = require("./local.js"); class RemoteJWKSet extends local_js_1.LocalJWKSet { constructor(url, options) { super({ keys: [] }); this._jwks = undefined; if (!(url instanceof URL)) { throw new TypeError('url must be an instance of URL'); } this._url = new URL(url.href); this._options = { agent: options === null || options === void 0 ? void 0 : options.agent, headers: options === null || options === void 0 ? void 0 : options.headers }; this._timeoutDuration = typeof (options === null || options === void 0 ? void 0 : options.timeoutDuration) === 'number' ? options === null || options === void 0 ? void 0 : options.timeoutDuration : 5000; this._cooldownDuration = typeof (options === null || options === void 0 ? void 0 : options.cooldownDuration) === 'number' ? options === null || options === void 0 ? void 0 : options.cooldownDuration : 30000; this._cacheMaxAge = typeof (options === null || options === void 0 ? void 0 : options.cacheMaxAge) === 'number' ? options === null || options === void 0 ? void 0 : options.cacheMaxAge : 600000; } coolingDown() { return typeof this._jwksTimestamp === 'number' ? Date.now() < this._jwksTimestamp + this._cooldownDuration : false; } fresh() { return typeof this._jwksTimestamp === 'number' ? Date.now() < this._jwksTimestamp + this._cacheMaxAge : false; } async getKey(protectedHeader, token) { if (!this._jwks || !this.fresh()) { await this.reload(); } try { return await super.getKey(protectedHeader, token); } catch (err) { if (err instanceof errors_js_1.JWKSNoMatchingKey) { if (this.coolingDown() === false) { await this.reload(); return super.getKey(protectedHeader, token); } } throw err; } } async reload() { if (this._pendingFetch && (0, env_js_1.isCloudflareWorkers)()) { return new Promise((resolve) => { const isDone = () => { if (this._pendingFetch === undefined) { resolve(); } else { setTimeout(isDone, 5); } }; isDone(); }); } if (!this._pendingFetch) { this._pendingFetch = (0, fetch_jwks_js_1.default)(this._url, this._timeoutDuration, this._options) .then((json) => { if (!(0, local_js_1.isJWKSLike)(json)) { throw new errors_js_1.JWKSInvalid('JSON Web Key Set malformed'); } this._jwks = { keys: json.keys }; this._jwksTimestamp = Date.now(); this._pendingFetch = undefined; }) .catch((err) => { this._pendingFetch = undefined; throw err; }); } await this._pendingFetch; } } function createRemoteJWKSet(url, options) { return RemoteJWKSet.prototype.getKey.bind(new RemoteJWKSet(url, options)); } exports.createRemoteJWKSet = createRemoteJWKSet; jose-4.11.4/dist/node/cjs/jws/000077500000000000000000000000001437043056600160235ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/jws/compact/000077500000000000000000000000001437043056600174515ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/jws/compact/sign.js000066400000000000000000000013611437043056600207500ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CompactSign = void 0; const sign_js_1 = require("../flattened/sign.js"); class CompactSign { constructor(payload) { this._flattened = new sign_js_1.FlattenedSign(payload); } setProtectedHeader(protectedHeader) { this._flattened.setProtectedHeader(protectedHeader); return this; } async sign(key, options) { const jws = await this._flattened.sign(key, options); if (jws.payload === undefined) { throw new TypeError('use the flattened module for creating JWS with b64: false'); } return `${jws.protected}.${jws.payload}.${jws.signature}`; } } exports.CompactSign = CompactSign; jose-4.11.4/dist/node/cjs/jws/compact/verify.js000066400000000000000000000021241437043056600213120ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.compactVerify = void 0; const verify_js_1 = require("../flattened/verify.js"); const errors_js_1 = require("../../util/errors.js"); const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); async function compactVerify(jws, key, options) { if (jws instanceof Uint8Array) { jws = buffer_utils_js_1.decoder.decode(jws); } if (typeof jws !== 'string') { throw new errors_js_1.JWSInvalid('Compact JWS must be a string or Uint8Array'); } const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.'); if (length !== 3) { throw new errors_js_1.JWSInvalid('Invalid Compact JWS'); } const verified = await (0, verify_js_1.flattenedVerify)({ payload, protected: protectedHeader, signature }, key, options); const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; if (typeof key === 'function') { return { ...result, key: verified.key }; } return result; } exports.compactVerify = compactVerify; jose-4.11.4/dist/node/cjs/jws/flattened/000077500000000000000000000000001437043056600177715ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/jws/flattened/sign.js000066400000000000000000000072671437043056600213030ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FlattenedSign = void 0; const base64url_js_1 = require("../../runtime/base64url.js"); const sign_js_1 = require("../../runtime/sign.js"); const is_disjoint_js_1 = require("../../lib/is_disjoint.js"); const errors_js_1 = require("../../util/errors.js"); const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); const check_key_type_js_1 = require("../../lib/check_key_type.js"); const validate_crit_js_1 = require("../../lib/validate_crit.js"); class FlattenedSign { constructor(payload) { if (!(payload instanceof Uint8Array)) { throw new TypeError('payload must be an instance of Uint8Array'); } this._payload = payload; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once'); } this._protectedHeader = protectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once'); } this._unprotectedHeader = unprotectedHeader; return this; } async sign(key, options) { if (!this._protectedHeader && !this._unprotectedHeader) { throw new errors_js_1.JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()'); } if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader)) { throw new errors_js_1.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, }; const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader); let b64 = true; if (extensions.has('b64')) { b64 = this._protectedHeader.b64; if (typeof b64 !== 'boolean') { throw new errors_js_1.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); } } const { alg } = joseHeader; if (typeof alg !== 'string' || !alg) { throw new errors_js_1.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); } (0, check_key_type_js_1.default)(alg, key, 'sign'); let payload = this._payload; if (b64) { payload = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(payload)); } let protectedHeader; if (this._protectedHeader) { protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader))); } else { protectedHeader = buffer_utils_js_1.encoder.encode(''); } const data = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), payload); const signature = await (0, sign_js_1.default)(alg, key, data); const jws = { signature: (0, base64url_js_1.encode)(signature), payload: '', }; if (b64) { jws.payload = buffer_utils_js_1.decoder.decode(payload); } if (this._unprotectedHeader) { jws.header = this._unprotectedHeader; } if (this._protectedHeader) { jws.protected = buffer_utils_js_1.decoder.decode(protectedHeader); } return jws; } } exports.FlattenedSign = FlattenedSign; jose-4.11.4/dist/node/cjs/jws/flattened/verify.js000066400000000000000000000113201437043056600216300ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.flattenedVerify = void 0; const base64url_js_1 = require("../../runtime/base64url.js"); const verify_js_1 = require("../../runtime/verify.js"); const errors_js_1 = require("../../util/errors.js"); const buffer_utils_js_1 = require("../../lib/buffer_utils.js"); const is_disjoint_js_1 = require("../../lib/is_disjoint.js"); const is_object_js_1 = require("../../lib/is_object.js"); const check_key_type_js_1 = require("../../lib/check_key_type.js"); const validate_crit_js_1 = require("../../lib/validate_crit.js"); const validate_algorithms_js_1 = require("../../lib/validate_algorithms.js"); async function flattenedVerify(jws, key, options) { var _a; if (!(0, is_object_js_1.default)(jws)) { throw new errors_js_1.JWSInvalid('Flattened JWS must be an object'); } if (jws.protected === undefined && jws.header === undefined) { throw new errors_js_1.JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); } if (jws.protected !== undefined && typeof jws.protected !== 'string') { throw new errors_js_1.JWSInvalid('JWS Protected Header incorrect type'); } if (jws.payload === undefined) { throw new errors_js_1.JWSInvalid('JWS Payload missing'); } if (typeof jws.signature !== 'string') { throw new errors_js_1.JWSInvalid('JWS Signature missing or incorrect type'); } if (jws.header !== undefined && !(0, is_object_js_1.default)(jws.header)) { throw new errors_js_1.JWSInvalid('JWS Unprotected Header incorrect type'); } let parsedProt = {}; if (jws.protected) { try { const protectedHeader = (0, base64url_js_1.decode)(jws.protected); parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader)); } catch { throw new errors_js_1.JWSInvalid('JWS Protected Header is invalid'); } } if (!(0, is_disjoint_js_1.default)(parsedProt, jws.header)) { throw new errors_js_1.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); } const joseHeader = { ...parsedProt, ...jws.header, }; const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader); let b64 = true; if (extensions.has('b64')) { b64 = parsedProt.b64; if (typeof b64 !== 'boolean') { throw new errors_js_1.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); } } const { alg } = joseHeader; if (typeof alg !== 'string' || !alg) { throw new errors_js_1.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); } const algorithms = options && (0, validate_algorithms_js_1.default)('algorithms', options.algorithms); if (algorithms && !algorithms.has(alg)) { throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed'); } if (b64) { if (typeof jws.payload !== 'string') { throw new errors_js_1.JWSInvalid('JWS Payload must be a string'); } } else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) { throw new errors_js_1.JWSInvalid('JWS Payload must be a string or an Uint8Array instance'); } let resolvedKey = false; if (typeof key === 'function') { key = await key(parsedProt, jws); resolvedKey = true; } (0, check_key_type_js_1.default)(alg, key, 'verify'); const data = (0, buffer_utils_js_1.concat)(buffer_utils_js_1.encoder.encode((_a = jws.protected) !== null && _a !== void 0 ? _a : ''), buffer_utils_js_1.encoder.encode('.'), typeof jws.payload === 'string' ? buffer_utils_js_1.encoder.encode(jws.payload) : jws.payload); const signature = (0, base64url_js_1.decode)(jws.signature); const verified = await (0, verify_js_1.default)(alg, key, signature, data); if (!verified) { throw new errors_js_1.JWSSignatureVerificationFailed(); } let payload; if (b64) { payload = (0, base64url_js_1.decode)(jws.payload); } else if (typeof jws.payload === 'string') { payload = buffer_utils_js_1.encoder.encode(jws.payload); } else { payload = jws.payload; } const result = { payload }; if (jws.protected !== undefined) { result.protectedHeader = parsedProt; } if (jws.header !== undefined) { result.unprotectedHeader = jws.header; } if (resolvedKey) { return { ...result, key }; } return result; } exports.flattenedVerify = flattenedVerify; jose-4.11.4/dist/node/cjs/jws/general/000077500000000000000000000000001437043056600174405ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/jws/general/sign.js000066400000000000000000000045241437043056600207430ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GeneralSign = void 0; const sign_js_1 = require("../flattened/sign.js"); const errors_js_1 = require("../../util/errors.js"); class IndividualSignature { constructor(sig, key, options) { this.parent = sig; this.key = key; this.options = options; } setProtectedHeader(protectedHeader) { if (this.protectedHeader) { throw new TypeError('setProtectedHeader can only be called once'); } this.protectedHeader = protectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this.unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once'); } this.unprotectedHeader = unprotectedHeader; return this; } addSignature(...args) { return this.parent.addSignature(...args); } sign(...args) { return this.parent.sign(...args); } done() { return this.parent; } } class GeneralSign { constructor(payload) { this._signatures = []; this._payload = payload; } addSignature(key, options) { const signature = new IndividualSignature(this, key, options); this._signatures.push(signature); return signature; } async sign() { if (!this._signatures.length) { throw new errors_js_1.JWSInvalid('at least one signature must be added'); } const jws = { signatures: [], payload: '', }; for (let i = 0; i < this._signatures.length; i++) { const signature = this._signatures[i]; const flattened = new sign_js_1.FlattenedSign(this._payload); flattened.setProtectedHeader(signature.protectedHeader); flattened.setUnprotectedHeader(signature.unprotectedHeader); const { payload, ...rest } = await flattened.sign(signature.key, signature.options); if (i === 0) { jws.payload = payload; } else if (jws.payload !== payload) { throw new errors_js_1.JWSInvalid('inconsistent use of JWS Unencoded Payload Option (RFC7797)'); } jws.signatures.push(rest); } return jws; } } exports.GeneralSign = GeneralSign; jose-4.11.4/dist/node/cjs/jws/general/verify.js000066400000000000000000000021171437043056600213030ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generalVerify = void 0; const verify_js_1 = require("../flattened/verify.js"); const errors_js_1 = require("../../util/errors.js"); const is_object_js_1 = require("../../lib/is_object.js"); async function generalVerify(jws, key, options) { if (!(0, is_object_js_1.default)(jws)) { throw new errors_js_1.JWSInvalid('General JWS must be an object'); } if (!Array.isArray(jws.signatures) || !jws.signatures.every(is_object_js_1.default)) { throw new errors_js_1.JWSInvalid('JWS Signatures missing or incorrect type'); } for (const signature of jws.signatures) { try { return await (0, verify_js_1.flattenedVerify)({ header: signature.header, payload: jws.payload, protected: signature.protected, signature: signature.signature, }, key, options); } catch { } } throw new errors_js_1.JWSSignatureVerificationFailed(); } exports.generalVerify = generalVerify; jose-4.11.4/dist/node/cjs/jwt/000077500000000000000000000000001437043056600160245ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/jwt/decrypt.js000066400000000000000000000026511437043056600200400ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.jwtDecrypt = void 0; const decrypt_js_1 = require("../jwe/compact/decrypt.js"); const jwt_claims_set_js_1 = require("../lib/jwt_claims_set.js"); const errors_js_1 = require("../util/errors.js"); async function jwtDecrypt(jwt, key, options) { const decrypted = await (0, decrypt_js_1.compactDecrypt)(jwt, key, options); const payload = (0, jwt_claims_set_js_1.default)(decrypted.protectedHeader, decrypted.plaintext, options); const { protectedHeader } = decrypted; if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) { throw new errors_js_1.JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', 'iss', 'mismatch'); } if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) { throw new errors_js_1.JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', 'sub', 'mismatch'); } if (protectedHeader.aud !== undefined && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { throw new errors_js_1.JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', 'aud', 'mismatch'); } const result = { payload, protectedHeader }; if (typeof key === 'function') { return { ...result, key: decrypted.key }; } return result; } exports.jwtDecrypt = jwtDecrypt; jose-4.11.4/dist/node/cjs/jwt/encrypt.js000066400000000000000000000050401437043056600200450ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EncryptJWT = void 0; const encrypt_js_1 = require("../jwe/compact/encrypt.js"); const buffer_utils_js_1 = require("../lib/buffer_utils.js"); const produce_js_1 = require("./produce.js"); class EncryptJWT extends produce_js_1.ProduceJWT { setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once'); } this._protectedHeader = protectedHeader; return this; } setKeyManagementParameters(parameters) { if (this._keyManagementParameters) { throw new TypeError('setKeyManagementParameters can only be called once'); } this._keyManagementParameters = parameters; return this; } setContentEncryptionKey(cek) { if (this._cek) { throw new TypeError('setContentEncryptionKey can only be called once'); } this._cek = cek; return this; } setInitializationVector(iv) { if (this._iv) { throw new TypeError('setInitializationVector can only be called once'); } this._iv = iv; return this; } replicateIssuerAsHeader() { this._replicateIssuerAsHeader = true; return this; } replicateSubjectAsHeader() { this._replicateSubjectAsHeader = true; return this; } replicateAudienceAsHeader() { this._replicateAudienceAsHeader = true; return this; } async encrypt(key, options) { const enc = new encrypt_js_1.CompactEncrypt(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload))); if (this._replicateIssuerAsHeader) { this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss }; } if (this._replicateSubjectAsHeader) { this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub }; } if (this._replicateAudienceAsHeader) { this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud }; } enc.setProtectedHeader(this._protectedHeader); if (this._iv) { enc.setInitializationVector(this._iv); } if (this._cek) { enc.setContentEncryptionKey(this._cek); } if (this._keyManagementParameters) { enc.setKeyManagementParameters(this._keyManagementParameters); } return enc.encrypt(key, options); } } exports.EncryptJWT = EncryptJWT; jose-4.11.4/dist/node/cjs/jwt/produce.js000066400000000000000000000035151437043056600200270ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ProduceJWT = void 0; const epoch_js_1 = require("../lib/epoch.js"); const is_object_js_1 = require("../lib/is_object.js"); const secs_js_1 = require("../lib/secs.js"); class ProduceJWT { constructor(payload) { if (!(0, is_object_js_1.default)(payload)) { throw new TypeError('JWT Claims Set MUST be an object'); } this._payload = payload; } setIssuer(issuer) { this._payload = { ...this._payload, iss: issuer }; return this; } setSubject(subject) { this._payload = { ...this._payload, sub: subject }; return this; } setAudience(audience) { this._payload = { ...this._payload, aud: audience }; return this; } setJti(jwtId) { this._payload = { ...this._payload, jti: jwtId }; return this; } setNotBefore(input) { if (typeof input === 'number') { this._payload = { ...this._payload, nbf: input }; } else { this._payload = { ...this._payload, nbf: (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input) }; } return this; } setExpirationTime(input) { if (typeof input === 'number') { this._payload = { ...this._payload, exp: input }; } else { this._payload = { ...this._payload, exp: (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input) }; } return this; } setIssuedAt(input) { if (typeof input === 'undefined') { this._payload = { ...this._payload, iat: (0, epoch_js_1.default)(new Date()) }; } else { this._payload = { ...this._payload, iat: input }; } return this; } } exports.ProduceJWT = ProduceJWT; jose-4.11.4/dist/node/cjs/jwt/sign.js000066400000000000000000000020631437043056600173230ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SignJWT = void 0; const sign_js_1 = require("../jws/compact/sign.js"); const errors_js_1 = require("../util/errors.js"); const buffer_utils_js_1 = require("../lib/buffer_utils.js"); const produce_js_1 = require("./produce.js"); class SignJWT extends produce_js_1.ProduceJWT { setProtectedHeader(protectedHeader) { this._protectedHeader = protectedHeader; return this; } async sign(key, options) { var _a; const sig = new sign_js_1.CompactSign(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload))); sig.setProtectedHeader(this._protectedHeader); if (Array.isArray((_a = this._protectedHeader) === null || _a === void 0 ? void 0 : _a.crit) && this._protectedHeader.crit.includes('b64') && this._protectedHeader.b64 === false) { throw new errors_js_1.JWTInvalid('JWTs MUST NOT use unencoded payload'); } return sig.sign(key, options); } } exports.SignJWT = SignJWT; jose-4.11.4/dist/node/cjs/jwt/unsecured.js000066400000000000000000000030001437043056600203500ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UnsecuredJWT = void 0; const base64url = require("../runtime/base64url.js"); const buffer_utils_js_1 = require("../lib/buffer_utils.js"); const errors_js_1 = require("../util/errors.js"); const jwt_claims_set_js_1 = require("../lib/jwt_claims_set.js"); const produce_js_1 = require("./produce.js"); class UnsecuredJWT extends produce_js_1.ProduceJWT { encode() { const header = base64url.encode(JSON.stringify({ alg: 'none' })); const payload = base64url.encode(JSON.stringify(this._payload)); return `${header}.${payload}.`; } static decode(jwt, options) { if (typeof jwt !== 'string') { throw new errors_js_1.JWTInvalid('Unsecured JWT must be a string'); } const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.'); if (length !== 3 || signature !== '') { throw new errors_js_1.JWTInvalid('Invalid Unsecured JWT'); } let header; try { header = JSON.parse(buffer_utils_js_1.decoder.decode(base64url.decode(encodedHeader))); if (header.alg !== 'none') throw new Error(); } catch { throw new errors_js_1.JWTInvalid('Invalid Unsecured JWT'); } const payload = (0, jwt_claims_set_js_1.default)(header, base64url.decode(encodedPayload), options); return { payload, header }; } } exports.UnsecuredJWT = UnsecuredJWT; jose-4.11.4/dist/node/cjs/jwt/verify.js000066400000000000000000000017161437043056600176730ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.jwtVerify = void 0; const verify_js_1 = require("../jws/compact/verify.js"); const jwt_claims_set_js_1 = require("../lib/jwt_claims_set.js"); const errors_js_1 = require("../util/errors.js"); async function jwtVerify(jwt, key, options) { var _a; const verified = await (0, verify_js_1.compactVerify)(jwt, key, options); if (((_a = verified.protectedHeader.crit) === null || _a === void 0 ? void 0 : _a.includes('b64')) && verified.protectedHeader.b64 === false) { throw new errors_js_1.JWTInvalid('JWTs MUST NOT use unencoded payload'); } const payload = (0, jwt_claims_set_js_1.default)(verified.protectedHeader, verified.payload, options); const result = { payload, protectedHeader: verified.protectedHeader }; if (typeof key === 'function') { return { ...result, key: verified.key }; } return result; } exports.jwtVerify = jwtVerify; jose-4.11.4/dist/node/cjs/key/000077500000000000000000000000001437043056600160105ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/key/export.js000066400000000000000000000011741437043056600176720ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.exportJWK = exports.exportPKCS8 = exports.exportSPKI = void 0; const asn1_js_1 = require("../runtime/asn1.js"); const asn1_js_2 = require("../runtime/asn1.js"); const key_to_jwk_js_1 = require("../runtime/key_to_jwk.js"); async function exportSPKI(key) { return (0, asn1_js_1.toSPKI)(key); } exports.exportSPKI = exportSPKI; async function exportPKCS8(key) { return (0, asn1_js_2.toPKCS8)(key); } exports.exportPKCS8 = exportPKCS8; async function exportJWK(key) { return (0, key_to_jwk_js_1.default)(key); } exports.exportJWK = exportJWK; jose-4.11.4/dist/node/cjs/key/generate_key_pair.js000066400000000000000000000005011437043056600220170ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateKeyPair = void 0; const generate_js_1 = require("../runtime/generate.js"); async function generateKeyPair(alg, options) { return (0, generate_js_1.generateKeyPair)(alg, options); } exports.generateKeyPair = generateKeyPair; jose-4.11.4/dist/node/cjs/key/generate_secret.js000066400000000000000000000004741437043056600215120ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateSecret = void 0; const generate_js_1 = require("../runtime/generate.js"); async function generateSecret(alg, options) { return (0, generate_js_1.generateSecret)(alg, options); } exports.generateSecret = generateSecret; jose-4.11.4/dist/node/cjs/key/import.js000066400000000000000000000117711437043056600176670ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.importJWK = exports.importPKCS8 = exports.importX509 = exports.importSPKI = void 0; const base64url_js_1 = require("../runtime/base64url.js"); const asn1_js_1 = require("../runtime/asn1.js"); const asn1_js_2 = require("../runtime/asn1.js"); const jwk_to_key_js_1 = require("../runtime/jwk_to_key.js"); const errors_js_1 = require("../util/errors.js"); const format_pem_js_1 = require("../lib/format_pem.js"); const is_object_js_1 = require("../lib/is_object.js"); function getElement(seq) { let result = []; let next = 0; while (next < seq.length) { let nextPart = parseElement(seq.subarray(next)); result.push(nextPart); next += nextPart.byteLength; } return result; } function parseElement(bytes) { let position = 0; let tag = bytes[0] & 0x1f; position++; if (tag === 0x1f) { tag = 0; while (bytes[position] >= 0x80) { tag = tag * 128 + bytes[position] - 0x80; position++; } tag = tag * 128 + bytes[position] - 0x80; position++; } let length = 0; if (bytes[position] < 0x80) { length = bytes[position]; position++; } else if (length === 0x80) { length = 0; while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) { if (length > bytes.byteLength) { throw new TypeError('invalid indefinite form length'); } length++; } const byteLength = position + length + 2; return { byteLength, contents: bytes.subarray(position, position + length), raw: bytes.subarray(0, byteLength), }; } else { let numberOfDigits = bytes[position] & 0x7f; position++; length = 0; for (let i = 0; i < numberOfDigits; i++) { length = length * 256 + bytes[position]; position++; } } const byteLength = position + length; return { byteLength, contents: bytes.subarray(position, byteLength), raw: bytes.subarray(0, byteLength), }; } function spkiFromX509(buf) { const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents); return (0, base64url_js_1.encodeBase64)(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw); } function getSPKI(x509) { const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, ''); const raw = (0, base64url_js_1.decodeBase64)(pem); return (0, format_pem_js_1.default)(spkiFromX509(raw), 'PUBLIC KEY'); } async function importSPKI(spki, alg, options) { if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) { throw new TypeError('"spki" must be SPKI formatted string'); } return (0, asn1_js_1.fromSPKI)(spki, alg, options); } exports.importSPKI = importSPKI; async function importX509(x509, alg, options) { if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) { throw new TypeError('"x509" must be X.509 formatted string'); } let spki; try { spki = getSPKI(x509); } catch (cause) { throw new TypeError('failed to parse the X.509 certificate', { cause }); } return (0, asn1_js_1.fromSPKI)(spki, alg, options); } exports.importX509 = importX509; async function importPKCS8(pkcs8, alg, options) { if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) { throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); } return (0, asn1_js_2.fromPKCS8)(pkcs8, alg, options); } exports.importPKCS8 = importPKCS8; async function importJWK(jwk, alg, octAsKeyObject) { var _a; if (!(0, is_object_js_1.default)(jwk)) { throw new TypeError('JWK must be an object'); } alg || (alg = jwk.alg); if (typeof alg !== 'string' || !alg) { throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); } switch (jwk.kty) { case 'oct': if (typeof jwk.k !== 'string' || !jwk.k) { throw new TypeError('missing "k" (Key Value) Parameter value'); } octAsKeyObject !== null && octAsKeyObject !== void 0 ? octAsKeyObject : (octAsKeyObject = jwk.ext !== true); if (octAsKeyObject) { return (0, jwk_to_key_js_1.default)({ ...jwk, alg, ext: (_a = jwk.ext) !== null && _a !== void 0 ? _a : false }); } return (0, base64url_js_1.decode)(jwk.k); case 'RSA': if (jwk.oth !== undefined) { throw new errors_js_1.JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); } case 'EC': case 'OKP': return (0, jwk_to_key_js_1.default)({ ...jwk, alg }); default: throw new errors_js_1.JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); } } exports.importJWK = importJWK; jose-4.11.4/dist/node/cjs/lib/000077500000000000000000000000001437043056600157665ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/lib/aesgcmkw.js000066400000000000000000000016471437043056600201350ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.unwrap = exports.wrap = void 0; const encrypt_js_1 = require("../runtime/encrypt.js"); const decrypt_js_1 = require("../runtime/decrypt.js"); const iv_js_1 = require("./iv.js"); const base64url_js_1 = require("../runtime/base64url.js"); async function wrap(alg, key, cek, iv) { const jweAlgorithm = alg.slice(0, 7); iv || (iv = (0, iv_js_1.default)(jweAlgorithm)); const { ciphertext: encryptedKey, tag } = await (0, encrypt_js_1.default)(jweAlgorithm, cek, key, iv, new Uint8Array(0)); return { encryptedKey, iv: (0, base64url_js_1.encode)(iv), tag: (0, base64url_js_1.encode)(tag) }; } exports.wrap = wrap; async function unwrap(alg, key, encryptedKey, iv, tag) { const jweAlgorithm = alg.slice(0, 7); return (0, decrypt_js_1.default)(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0)); } exports.unwrap = unwrap; jose-4.11.4/dist/node/cjs/lib/buffer_utils.js000066400000000000000000000041271437043056600210210ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.concatKdf = exports.lengthAndInput = exports.uint32be = exports.uint64be = exports.p2s = exports.concat = exports.decoder = exports.encoder = void 0; const digest_js_1 = require("../runtime/digest.js"); exports.encoder = new TextEncoder(); exports.decoder = new TextDecoder(); const MAX_INT32 = 2 ** 32; function concat(...buffers) { const size = buffers.reduce((acc, { length }) => acc + length, 0); const buf = new Uint8Array(size); let i = 0; buffers.forEach((buffer) => { buf.set(buffer, i); i += buffer.length; }); return buf; } exports.concat = concat; function p2s(alg, p2sInput) { return concat(exports.encoder.encode(alg), new Uint8Array([0]), p2sInput); } exports.p2s = p2s; function writeUInt32BE(buf, value, offset) { if (value < 0 || value >= MAX_INT32) { throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); } buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset); } function uint64be(value) { const high = Math.floor(value / MAX_INT32); const low = value % MAX_INT32; const buf = new Uint8Array(8); writeUInt32BE(buf, high, 0); writeUInt32BE(buf, low, 4); return buf; } exports.uint64be = uint64be; function uint32be(value) { const buf = new Uint8Array(4); writeUInt32BE(buf, value); return buf; } exports.uint32be = uint32be; function lengthAndInput(input) { return concat(uint32be(input.length), input); } exports.lengthAndInput = lengthAndInput; async function concatKdf(secret, bits, value) { const iterations = Math.ceil((bits >> 3) / 32); const res = new Uint8Array(iterations * 32); for (let iter = 0; iter < iterations; iter++) { const buf = new Uint8Array(4 + secret.length + value.length); buf.set(uint32be(iter + 1)); buf.set(secret, 4); buf.set(value, 4 + secret.length); res.set(await (0, digest_js_1.default)('sha256', buf), iter * 32); } return res.slice(0, bits >> 3); } exports.concatKdf = concatKdf; jose-4.11.4/dist/node/cjs/lib/cek.js000066400000000000000000000014021437043056600170630ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.bitLength = void 0; const errors_js_1 = require("../util/errors.js"); const random_js_1 = require("../runtime/random.js"); function bitLength(alg) { switch (alg) { case 'A128GCM': return 128; case 'A192GCM': return 192; case 'A256GCM': case 'A128CBC-HS256': return 256; case 'A192CBC-HS384': return 384; case 'A256CBC-HS512': return 512; default: throw new errors_js_1.JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); } } exports.bitLength = bitLength; exports.default = (alg) => (0, random_js_1.default)(new Uint8Array(bitLength(alg) >> 3)); jose-4.11.4/dist/node/cjs/lib/check_iv_length.js000066400000000000000000000005761437043056600214500ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const errors_js_1 = require("../util/errors.js"); const iv_js_1 = require("./iv.js"); const checkIvLength = (enc, iv) => { if (iv.length << 3 !== (0, iv_js_1.bitLength)(enc)) { throw new errors_js_1.JWEInvalid('Invalid Initialization Vector length'); } }; exports.default = checkIvLength; jose-4.11.4/dist/node/cjs/lib/check_key_type.js000066400000000000000000000042631437043056600213170ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const invalid_key_input_js_1 = require("./invalid_key_input.js"); const is_key_like_js_1 = require("../runtime/is_key_like.js"); const symmetricTypeCheck = (alg, key) => { if (key instanceof Uint8Array) return; if (!(0, is_key_like_js_1.default)(key)) { throw new TypeError((0, invalid_key_input_js_1.withAlg)(alg, key, ...is_key_like_js_1.types, 'Uint8Array')); } if (key.type !== 'secret') { throw new TypeError(`${is_key_like_js_1.types.join(' or ')} instances for symmetric algorithms must be of type "secret"`); } }; const asymmetricTypeCheck = (alg, key, usage) => { if (!(0, is_key_like_js_1.default)(key)) { throw new TypeError((0, invalid_key_input_js_1.withAlg)(alg, key, ...is_key_like_js_1.types)); } if (key.type === 'secret') { throw new TypeError(`${is_key_like_js_1.types.join(' or ')} instances for asymmetric algorithms must not be of type "secret"`); } if (usage === 'sign' && key.type === 'public') { throw new TypeError(`${is_key_like_js_1.types.join(' or ')} instances for asymmetric algorithm signing must be of type "private"`); } if (usage === 'decrypt' && key.type === 'public') { throw new TypeError(`${is_key_like_js_1.types.join(' or ')} instances for asymmetric algorithm decryption must be of type "private"`); } if (key.algorithm && usage === 'verify' && key.type === 'private') { throw new TypeError(`${is_key_like_js_1.types.join(' or ')} instances for asymmetric algorithm verifying must be of type "public"`); } if (key.algorithm && usage === 'encrypt' && key.type === 'private') { throw new TypeError(`${is_key_like_js_1.types.join(' or ')} instances for asymmetric algorithm encryption must be of type "public"`); } }; const checkKeyType = (alg, key, usage) => { const symmetric = alg.startsWith('HS') || alg === 'dir' || alg.startsWith('PBES2') || /^A\d{3}(?:GCM)?KW$/.test(alg); if (symmetric) { symmetricTypeCheck(alg, key); } else { asymmetricTypeCheck(alg, key, usage); } }; exports.default = checkKeyType; jose-4.11.4/dist/node/cjs/lib/check_p2s.js000066400000000000000000000005151437043056600201660ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const errors_js_1 = require("../util/errors.js"); function checkP2s(p2s) { if (!(p2s instanceof Uint8Array) || p2s.length < 8) { throw new errors_js_1.JWEInvalid('PBES2 Salt Input must be 8 or more octets'); } } exports.default = checkP2s; jose-4.11.4/dist/node/cjs/lib/crypto_key.js000066400000000000000000000132161437043056600205170ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkEncCryptoKey = exports.checkSigCryptoKey = void 0; const env_js_1 = require("../runtime/env.js"); function unusable(name, prop = 'algorithm.name') { return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); } function isAlgorithm(algorithm, name) { return algorithm.name === name; } function getHashLength(hash) { return parseInt(hash.name.slice(4), 10); } function getNamedCurve(alg) { switch (alg) { case 'ES256': return 'P-256'; case 'ES384': return 'P-384'; case 'ES512': return 'P-521'; default: throw new Error('unreachable'); } } function checkUsage(key, usages) { if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { let msg = 'CryptoKey does not support this operation, its usages must include '; if (usages.length > 2) { const last = usages.pop(); msg += `one of ${usages.join(', ')}, or ${last}.`; } else if (usages.length === 2) { msg += `one of ${usages[0]} or ${usages[1]}.`; } else { msg += `${usages[0]}.`; } throw new TypeError(msg); } } function checkSigCryptoKey(key, alg, ...usages) { switch (alg) { case 'HS256': case 'HS384': case 'HS512': { if (!isAlgorithm(key.algorithm, 'HMAC')) throw unusable('HMAC'); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash'); break; } case 'RS256': case 'RS384': case 'RS512': { if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5')) throw unusable('RSASSA-PKCS1-v1_5'); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash'); break; } case 'PS256': case 'PS384': case 'PS512': { if (!isAlgorithm(key.algorithm, 'RSA-PSS')) throw unusable('RSA-PSS'); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash'); break; } case 'EdDSA': { if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') { if ((0, env_js_1.isCloudflareWorkers)()) { if (isAlgorithm(key.algorithm, 'NODE-ED25519')) break; throw unusable('Ed25519, Ed448, or NODE-ED25519'); } throw unusable('Ed25519 or Ed448'); } break; } case 'ES256': case 'ES384': case 'ES512': { if (!isAlgorithm(key.algorithm, 'ECDSA')) throw unusable('ECDSA'); const expected = getNamedCurve(alg); const actual = key.algorithm.namedCurve; if (actual !== expected) throw unusable(expected, 'algorithm.namedCurve'); break; } default: throw new TypeError('CryptoKey does not support this operation'); } checkUsage(key, usages); } exports.checkSigCryptoKey = checkSigCryptoKey; function checkEncCryptoKey(key, alg, ...usages) { switch (alg) { case 'A128GCM': case 'A192GCM': case 'A256GCM': { if (!isAlgorithm(key.algorithm, 'AES-GCM')) throw unusable('AES-GCM'); const expected = parseInt(alg.slice(1, 4), 10); const actual = key.algorithm.length; if (actual !== expected) throw unusable(expected, 'algorithm.length'); break; } case 'A128KW': case 'A192KW': case 'A256KW': { if (!isAlgorithm(key.algorithm, 'AES-KW')) throw unusable('AES-KW'); const expected = parseInt(alg.slice(1, 4), 10); const actual = key.algorithm.length; if (actual !== expected) throw unusable(expected, 'algorithm.length'); break; } case 'ECDH': { switch (key.algorithm.name) { case 'ECDH': case 'X25519': case 'X448': break; default: throw unusable('ECDH, X25519, or X448'); } break; } case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': if (!isAlgorithm(key.algorithm, 'PBKDF2')) throw unusable('PBKDF2'); break; case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': { if (!isAlgorithm(key.algorithm, 'RSA-OAEP')) throw unusable('RSA-OAEP'); const expected = parseInt(alg.slice(9), 10) || 1; const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash'); break; } default: throw new TypeError('CryptoKey does not support this operation'); } checkUsage(key, usages); } exports.checkEncCryptoKey = checkEncCryptoKey; jose-4.11.4/dist/node/cjs/lib/decrypt_key_management.js000066400000000000000000000123571437043056600230520ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const aeskw_js_1 = require("../runtime/aeskw.js"); const ECDH = require("../runtime/ecdhes.js"); const pbes2kw_js_1 = require("../runtime/pbes2kw.js"); const rsaes_js_1 = require("../runtime/rsaes.js"); const base64url_js_1 = require("../runtime/base64url.js"); const errors_js_1 = require("../util/errors.js"); const cek_js_1 = require("../lib/cek.js"); const import_js_1 = require("../key/import.js"); const check_key_type_js_1 = require("./check_key_type.js"); const is_object_js_1 = require("./is_object.js"); const aesgcmkw_js_1 = require("./aesgcmkw.js"); async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { (0, check_key_type_js_1.default)(alg, key, 'decrypt'); switch (alg) { case 'dir': { if (encryptedKey !== undefined) throw new errors_js_1.JWEInvalid('Encountered unexpected JWE Encrypted Key'); return key; } case 'ECDH-ES': if (encryptedKey !== undefined) throw new errors_js_1.JWEInvalid('Encountered unexpected JWE Encrypted Key'); case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': { if (!(0, is_object_js_1.default)(joseHeader.epk)) throw new errors_js_1.JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); if (!ECDH.ecdhAllowed(key)) throw new errors_js_1.JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); const epk = await (0, import_js_1.importJWK)(joseHeader.epk, alg); let partyUInfo; let partyVInfo; if (joseHeader.apu !== undefined) { if (typeof joseHeader.apu !== 'string') throw new errors_js_1.JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); partyUInfo = (0, base64url_js_1.decode)(joseHeader.apu); } if (joseHeader.apv !== undefined) { if (typeof joseHeader.apv !== 'string') throw new errors_js_1.JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); partyVInfo = (0, base64url_js_1.decode)(joseHeader.apv); } const sharedSecret = await ECDH.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? (0, cek_js_1.bitLength)(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); if (alg === 'ECDH-ES') return sharedSecret; if (encryptedKey === undefined) throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); return (0, aeskw_js_1.unwrap)(alg.slice(-6), sharedSecret, encryptedKey); } case 'RSA1_5': case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': { if (encryptedKey === undefined) throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); return (0, rsaes_js_1.decrypt)(alg, key, encryptedKey); } case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': { if (encryptedKey === undefined) throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); if (typeof joseHeader.p2c !== 'number') throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); const p2cLimit = (options === null || options === void 0 ? void 0 : options.maxPBES2Count) || 10000; if (joseHeader.p2c > p2cLimit) throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); if (typeof joseHeader.p2s !== 'string') throw new errors_js_1.JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); return (0, pbes2kw_js_1.decrypt)(alg, key, encryptedKey, joseHeader.p2c, (0, base64url_js_1.decode)(joseHeader.p2s)); } case 'A128KW': case 'A192KW': case 'A256KW': { if (encryptedKey === undefined) throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); return (0, aeskw_js_1.unwrap)(alg, key, encryptedKey); } case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': { if (encryptedKey === undefined) throw new errors_js_1.JWEInvalid('JWE Encrypted Key missing'); if (typeof joseHeader.iv !== 'string') throw new errors_js_1.JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); if (typeof joseHeader.tag !== 'string') throw new errors_js_1.JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); const iv = (0, base64url_js_1.decode)(joseHeader.iv); const tag = (0, base64url_js_1.decode)(joseHeader.tag); return (0, aesgcmkw_js_1.unwrap)(alg, key, encryptedKey, iv, tag); } default: { throw new errors_js_1.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); } } } exports.default = decryptKeyManagement; jose-4.11.4/dist/node/cjs/lib/encrypt_key_management.js000066400000000000000000000072421437043056600230610ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const aeskw_js_1 = require("../runtime/aeskw.js"); const ECDH = require("../runtime/ecdhes.js"); const pbes2kw_js_1 = require("../runtime/pbes2kw.js"); const rsaes_js_1 = require("../runtime/rsaes.js"); const base64url_js_1 = require("../runtime/base64url.js"); const cek_js_1 = require("../lib/cek.js"); const errors_js_1 = require("../util/errors.js"); const export_js_1 = require("../key/export.js"); const check_key_type_js_1 = require("./check_key_type.js"); const aesgcmkw_js_1 = require("./aesgcmkw.js"); async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { let encryptedKey; let parameters; let cek; (0, check_key_type_js_1.default)(alg, key, 'encrypt'); switch (alg) { case 'dir': { cek = key; break; } case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': { if (!ECDH.ecdhAllowed(key)) { throw new errors_js_1.JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); } const { apu, apv } = providedParameters; let { epk: ephemeralKey } = providedParameters; ephemeralKey || (ephemeralKey = (await ECDH.generateEpk(key)).privateKey); const { x, y, crv, kty } = await (0, export_js_1.exportJWK)(ephemeralKey); const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? (0, cek_js_1.bitLength)(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); parameters = { epk: { x, crv, kty } }; if (kty === 'EC') parameters.epk.y = y; if (apu) parameters.apu = (0, base64url_js_1.encode)(apu); if (apv) parameters.apv = (0, base64url_js_1.encode)(apv); if (alg === 'ECDH-ES') { cek = sharedSecret; break; } cek = providedCek || (0, cek_js_1.default)(enc); const kwAlg = alg.slice(-6); encryptedKey = await (0, aeskw_js_1.wrap)(kwAlg, sharedSecret, cek); break; } case 'RSA1_5': case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': { cek = providedCek || (0, cek_js_1.default)(enc); encryptedKey = await (0, rsaes_js_1.encrypt)(alg, key, cek); break; } case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': { cek = providedCek || (0, cek_js_1.default)(enc); const { p2c, p2s } = providedParameters; ({ encryptedKey, ...parameters } = await (0, pbes2kw_js_1.encrypt)(alg, key, cek, p2c, p2s)); break; } case 'A128KW': case 'A192KW': case 'A256KW': { cek = providedCek || (0, cek_js_1.default)(enc); encryptedKey = await (0, aeskw_js_1.wrap)(alg, key, cek); break; } case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': { cek = providedCek || (0, cek_js_1.default)(enc); const { iv } = providedParameters; ({ encryptedKey, ...parameters } = await (0, aesgcmkw_js_1.wrap)(alg, key, cek, iv)); break; } default: { throw new errors_js_1.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); } } return { cek, encryptedKey, parameters }; } exports.default = encryptKeyManagement; jose-4.11.4/dist/node/cjs/lib/epoch.js000066400000000000000000000002141437043056600174170ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = (date) => Math.floor(date.getTime() / 1000); jose-4.11.4/dist/node/cjs/lib/format_pem.js000066400000000000000000000004161437043056600204560ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = (b64, descriptor) => { const newlined = (b64.match(/.{1,64}/g) || []).join('\n'); return `-----BEGIN ${descriptor}-----\n${newlined}\n-----END ${descriptor}-----`; }; jose-4.11.4/dist/node/cjs/lib/invalid_key_input.js000066400000000000000000000021121437043056600220350ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.withAlg = void 0; function message(msg, actual, ...types) { if (types.length > 2) { const last = types.pop(); msg += `one of type ${types.join(', ')}, or ${last}.`; } else if (types.length === 2) { msg += `one of type ${types[0]} or ${types[1]}.`; } else { msg += `of type ${types[0]}.`; } if (actual == null) { msg += ` Received ${actual}`; } else if (typeof actual === 'function' && actual.name) { msg += ` Received function ${actual.name}`; } else if (typeof actual === 'object' && actual != null) { if (actual.constructor && actual.constructor.name) { msg += ` Received an instance of ${actual.constructor.name}`; } } return msg; } exports.default = (actual, ...types) => { return message('Key must be ', actual, ...types); }; function withAlg(alg, actual, ...types) { return message(`Key for the ${alg} algorithm must be `, actual, ...types); } exports.withAlg = withAlg; jose-4.11.4/dist/node/cjs/lib/is_disjoint.js000066400000000000000000000012421437043056600206410ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const isDisjoint = (...headers) => { const sources = headers.filter(Boolean); if (sources.length === 0 || sources.length === 1) { return true; } let acc; for (const header of sources) { const parameters = Object.keys(header); if (!acc || acc.size === 0) { acc = new Set(parameters); continue; } for (const parameter of parameters) { if (acc.has(parameter)) { return false; } acc.add(parameter); } } return true; }; exports.default = isDisjoint; jose-4.11.4/dist/node/cjs/lib/is_object.js000066400000000000000000000011301437043056600202600ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isObjectLike(value) { return typeof value === 'object' && value !== null; } function isObject(input) { if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') { return false; } if (Object.getPrototypeOf(input) === null) { return true; } let proto = input; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(input) === proto; } exports.default = isObject; jose-4.11.4/dist/node/cjs/lib/iv.js000066400000000000000000000014071437043056600167440ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.bitLength = void 0; const errors_js_1 = require("../util/errors.js"); const random_js_1 = require("../runtime/random.js"); function bitLength(alg) { switch (alg) { case 'A128GCM': case 'A128GCMKW': case 'A192GCM': case 'A192GCMKW': case 'A256GCM': case 'A256GCMKW': return 96; case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': return 128; default: throw new errors_js_1.JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); } } exports.bitLength = bitLength; exports.default = (alg) => (0, random_js_1.default)(new Uint8Array(bitLength(alg) >> 3)); jose-4.11.4/dist/node/cjs/lib/jwt_claims_set.js000066400000000000000000000100541437043056600213330ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const errors_js_1 = require("../util/errors.js"); const buffer_utils_js_1 = require("./buffer_utils.js"); const epoch_js_1 = require("./epoch.js"); const secs_js_1 = require("./secs.js"); const is_object_js_1 = require("./is_object.js"); const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, ''); const checkAudiencePresence = (audPayload, audOption) => { if (typeof audPayload === 'string') { return audOption.includes(audPayload); } if (Array.isArray(audPayload)) { return audOption.some(Set.prototype.has.bind(new Set(audPayload))); } return false; }; exports.default = (protectedHeader, encodedPayload, options = {}) => { const { typ } = options; if (typ && (typeof protectedHeader.typ !== 'string' || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { throw new errors_js_1.JWTClaimValidationFailed('unexpected "typ" JWT header value', 'typ', 'check_failed'); } let payload; try { payload = JSON.parse(buffer_utils_js_1.decoder.decode(encodedPayload)); } catch { } if (!(0, is_object_js_1.default)(payload)) { throw new errors_js_1.JWTInvalid('JWT Claims Set must be a top-level JSON object'); } const { issuer } = options; if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { throw new errors_js_1.JWTClaimValidationFailed('unexpected "iss" claim value', 'iss', 'check_failed'); } const { subject } = options; if (subject && payload.sub !== subject) { throw new errors_js_1.JWTClaimValidationFailed('unexpected "sub" claim value', 'sub', 'check_failed'); } const { audience } = options; if (audience && !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) { throw new errors_js_1.JWTClaimValidationFailed('unexpected "aud" claim value', 'aud', 'check_failed'); } let tolerance; switch (typeof options.clockTolerance) { case 'string': tolerance = (0, secs_js_1.default)(options.clockTolerance); break; case 'number': tolerance = options.clockTolerance; break; case 'undefined': tolerance = 0; break; default: throw new TypeError('Invalid clockTolerance option type'); } const { currentDate } = options; const now = (0, epoch_js_1.default)(currentDate || new Date()); if ((payload.iat !== undefined || options.maxTokenAge) && typeof payload.iat !== 'number') { throw new errors_js_1.JWTClaimValidationFailed('"iat" claim must be a number', 'iat', 'invalid'); } if (payload.nbf !== undefined) { if (typeof payload.nbf !== 'number') { throw new errors_js_1.JWTClaimValidationFailed('"nbf" claim must be a number', 'nbf', 'invalid'); } if (payload.nbf > now + tolerance) { throw new errors_js_1.JWTClaimValidationFailed('"nbf" claim timestamp check failed', 'nbf', 'check_failed'); } } if (payload.exp !== undefined) { if (typeof payload.exp !== 'number') { throw new errors_js_1.JWTClaimValidationFailed('"exp" claim must be a number', 'exp', 'invalid'); } if (payload.exp <= now - tolerance) { throw new errors_js_1.JWTExpired('"exp" claim timestamp check failed', 'exp', 'check_failed'); } } if (options.maxTokenAge) { const age = now - payload.iat; const max = typeof options.maxTokenAge === 'number' ? options.maxTokenAge : (0, secs_js_1.default)(options.maxTokenAge); if (age - tolerance > max) { throw new errors_js_1.JWTExpired('"iat" claim timestamp check failed (too far in the past)', 'iat', 'check_failed'); } if (age < 0 - tolerance) { throw new errors_js_1.JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', 'iat', 'check_failed'); } } return payload; }; jose-4.11.4/dist/node/cjs/lib/secs.js000066400000000000000000000024111437043056600172570ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const minute = 60; const hour = minute * 60; const day = hour * 24; const week = day * 7; const year = day * 365.25; const REGEX = /^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i; exports.default = (str) => { const matched = REGEX.exec(str); if (!matched) { throw new TypeError('Invalid time period format'); } const value = parseFloat(matched[1]); const unit = matched[2].toLowerCase(); switch (unit) { case 'sec': case 'secs': case 'second': case 'seconds': case 's': return Math.round(value); case 'minute': case 'minutes': case 'min': case 'mins': case 'm': return Math.round(value * minute); case 'hour': case 'hours': case 'hr': case 'hrs': case 'h': return Math.round(value * hour); case 'day': case 'days': case 'd': return Math.round(value * day); case 'week': case 'weeks': case 'w': return Math.round(value * week); default: return Math.round(value * year); } }; jose-4.11.4/dist/node/cjs/lib/validate_algorithms.js000066400000000000000000000007241437043056600223510ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const validateAlgorithms = (option, algorithms) => { if (algorithms !== undefined && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) { throw new TypeError(`"${option}" option must be an array of strings`); } if (!algorithms) { return undefined; } return new Set(algorithms); }; exports.default = validateAlgorithms; jose-4.11.4/dist/node/cjs/lib/validate_crit.js000066400000000000000000000032111437043056600211330ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const errors_js_1 = require("../util/errors.js"); function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { if (joseHeader.crit !== undefined && protectedHeader.crit === undefined) { throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); } if (!protectedHeader || protectedHeader.crit === undefined) { return new Set(); } if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) { throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); } let recognized; if (recognizedOption !== undefined) { recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); } else { recognized = recognizedDefault; } for (const parameter of protectedHeader.crit) { if (!recognized.has(parameter)) { throw new errors_js_1.JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); } if (joseHeader[parameter] === undefined) { throw new Err(`Extension Header Parameter "${parameter}" is missing`); } else if (recognized.get(parameter) && protectedHeader[parameter] === undefined) { throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); } } return new Set(protectedHeader.crit); } exports.default = validateCrit; jose-4.11.4/dist/node/cjs/runtime/000077500000000000000000000000001437043056600167035ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/runtime/aeskw.js000066400000000000000000000047341437043056600203630ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.unwrap = exports.wrap = void 0; const buffer_1 = require("buffer"); const crypto_1 = require("crypto"); const errors_js_1 = require("../util/errors.js"); const buffer_utils_js_1 = require("../lib/buffer_utils.js"); const webcrypto_js_1 = require("./webcrypto.js"); const crypto_key_js_1 = require("../lib/crypto_key.js"); const is_key_object_js_1 = require("./is_key_object.js"); const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); const ciphers_js_1 = require("./ciphers.js"); const is_key_like_js_1 = require("./is_key_like.js"); function checkKeySize(key, alg) { if (key.symmetricKeySize << 3 !== parseInt(alg.slice(1, 4), 10)) { throw new TypeError(`Invalid key size for alg: ${alg}`); } } function ensureKeyObject(key, alg, usage) { if ((0, is_key_object_js_1.default)(key)) { return key; } if (key instanceof Uint8Array) { return (0, crypto_1.createSecretKey)(key); } if ((0, webcrypto_js_1.isCryptoKey)(key)) { (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, usage); return crypto_1.KeyObject.from(key); } throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); } const wrap = (alg, key, cek) => { const size = parseInt(alg.slice(1, 4), 10); const algorithm = `aes${size}-wrap`; if (!(0, ciphers_js_1.default)(algorithm)) { throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } const keyObject = ensureKeyObject(key, alg, 'wrapKey'); checkKeySize(keyObject, alg); const cipher = (0, crypto_1.createCipheriv)(algorithm, keyObject, buffer_1.Buffer.alloc(8, 0xa6)); return (0, buffer_utils_js_1.concat)(cipher.update(cek), cipher.final()); }; exports.wrap = wrap; const unwrap = (alg, key, encryptedKey) => { const size = parseInt(alg.slice(1, 4), 10); const algorithm = `aes${size}-wrap`; if (!(0, ciphers_js_1.default)(algorithm)) { throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } const keyObject = ensureKeyObject(key, alg, 'unwrapKey'); checkKeySize(keyObject, alg); const cipher = (0, crypto_1.createDecipheriv)(algorithm, keyObject, buffer_1.Buffer.alloc(8, 0xa6)); return (0, buffer_utils_js_1.concat)(cipher.update(encryptedKey), cipher.final()); }; exports.unwrap = unwrap; jose-4.11.4/dist/node/cjs/runtime/asn1.js000066400000000000000000000034071437043056600201070ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fromSPKI = exports.fromPKCS8 = exports.toPKCS8 = exports.toSPKI = void 0; const crypto_1 = require("crypto"); const buffer_1 = require("buffer"); const webcrypto_js_1 = require("./webcrypto.js"); const is_key_object_js_1 = require("./is_key_object.js"); const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); const is_key_like_js_1 = require("./is_key_like.js"); const genericExport = (keyType, keyFormat, key) => { let keyObject; if ((0, webcrypto_js_1.isCryptoKey)(key)) { if (!key.extractable) { throw new TypeError('CryptoKey is not extractable'); } keyObject = crypto_1.KeyObject.from(key); } else if ((0, is_key_object_js_1.default)(key)) { keyObject = key; } else { throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types)); } if (keyObject.type !== keyType) { throw new TypeError(`key is not a ${keyType} key`); } return keyObject.export({ format: 'pem', type: keyFormat }); }; const toSPKI = (key) => { return genericExport('public', 'spki', key); }; exports.toSPKI = toSPKI; const toPKCS8 = (key) => { return genericExport('private', 'pkcs8', key); }; exports.toPKCS8 = toPKCS8; const fromPKCS8 = (pem) => (0, crypto_1.createPrivateKey)({ key: buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, ''), 'base64'), type: 'pkcs8', format: 'der', }); exports.fromPKCS8 = fromPKCS8; const fromSPKI = (pem) => (0, crypto_1.createPublicKey)({ key: buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, ''), 'base64'), type: 'spki', format: 'der', }); exports.fromSPKI = fromSPKI; jose-4.11.4/dist/node/cjs/runtime/asn1_sequence_decoder.js000066400000000000000000000025521437043056600234640ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tagInteger = 0x02; const tagSequence = 0x30; class Asn1SequenceDecoder { constructor(buffer) { if (buffer[0] !== tagSequence) { throw new TypeError(); } this.buffer = buffer; this.offset = 1; const len = this.decodeLength(); if (len !== buffer.length - this.offset) { throw new TypeError(); } } decodeLength() { let length = this.buffer[this.offset++]; if (length & 0x80) { const nBytes = length & ~0x80; length = 0; for (let i = 0; i < nBytes; i++) length = (length << 8) | this.buffer[this.offset + i]; this.offset += nBytes; } return length; } unsignedInteger() { if (this.buffer[this.offset++] !== tagInteger) { throw new TypeError(); } let length = this.decodeLength(); if (this.buffer[this.offset] === 0) { this.offset++; length--; } const result = this.buffer.slice(this.offset, this.offset + length); this.offset += length; return result; } end() { if (this.offset !== this.buffer.length) { throw new TypeError(); } } } exports.default = Asn1SequenceDecoder; jose-4.11.4/dist/node/cjs/runtime/asn1_sequence_encoder.js000066400000000000000000000070601437043056600234750ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const buffer_1 = require("buffer"); const errors_js_1 = require("../util/errors.js"); const tagInteger = 0x02; const tagBitStr = 0x03; const tagOctStr = 0x04; const tagSequence = 0x30; const bZero = buffer_1.Buffer.from([0x00]); const bTagInteger = buffer_1.Buffer.from([tagInteger]); const bTagBitStr = buffer_1.Buffer.from([tagBitStr]); const bTagSequence = buffer_1.Buffer.from([tagSequence]); const bTagOctStr = buffer_1.Buffer.from([tagOctStr]); const encodeLength = (len) => { if (len < 128) return buffer_1.Buffer.from([len]); const buffer = buffer_1.Buffer.alloc(5); buffer.writeUInt32BE(len, 1); let offset = 1; while (buffer[offset] === 0) offset++; buffer[offset - 1] = 0x80 | (5 - offset); return buffer.slice(offset - 1); }; const oids = new Map([ ['P-256', buffer_1.Buffer.from('06 08 2A 86 48 CE 3D 03 01 07'.replace(/ /g, ''), 'hex')], ['secp256k1', buffer_1.Buffer.from('06 05 2B 81 04 00 0A'.replace(/ /g, ''), 'hex')], ['P-384', buffer_1.Buffer.from('06 05 2B 81 04 00 22'.replace(/ /g, ''), 'hex')], ['P-521', buffer_1.Buffer.from('06 05 2B 81 04 00 23'.replace(/ /g, ''), 'hex')], ['ecPublicKey', buffer_1.Buffer.from('06 07 2A 86 48 CE 3D 02 01'.replace(/ /g, ''), 'hex')], ['X25519', buffer_1.Buffer.from('06 03 2B 65 6E'.replace(/ /g, ''), 'hex')], ['X448', buffer_1.Buffer.from('06 03 2B 65 6F'.replace(/ /g, ''), 'hex')], ['Ed25519', buffer_1.Buffer.from('06 03 2B 65 70'.replace(/ /g, ''), 'hex')], ['Ed448', buffer_1.Buffer.from('06 03 2B 65 71'.replace(/ /g, ''), 'hex')], ]); class DumbAsn1Encoder { constructor() { this.length = 0; this.elements = []; } oidFor(oid) { const bOid = oids.get(oid); if (!bOid) { throw new errors_js_1.JOSENotSupported('Invalid or unsupported OID'); } this.elements.push(bOid); this.length += bOid.length; } zero() { this.elements.push(bTagInteger, buffer_1.Buffer.from([0x01]), bZero); this.length += 3; } one() { this.elements.push(bTagInteger, buffer_1.Buffer.from([0x01]), buffer_1.Buffer.from([0x01])); this.length += 3; } unsignedInteger(integer) { if (integer[0] & 0x80) { const len = encodeLength(integer.length + 1); this.elements.push(bTagInteger, len, bZero, integer); this.length += 2 + len.length + integer.length; } else { let i = 0; while (integer[i] === 0 && (integer[i + 1] & 0x80) === 0) i++; const len = encodeLength(integer.length - i); this.elements.push(bTagInteger, encodeLength(integer.length - i), integer.slice(i)); this.length += 1 + len.length + integer.length - i; } } octStr(octStr) { const len = encodeLength(octStr.length); this.elements.push(bTagOctStr, encodeLength(octStr.length), octStr); this.length += 1 + len.length + octStr.length; } bitStr(bitS) { const len = encodeLength(bitS.length + 1); this.elements.push(bTagBitStr, encodeLength(bitS.length + 1), bZero, bitS); this.length += 1 + len.length + bitS.length + 1; } add(seq) { this.elements.push(seq); this.length += seq.length; } end(tag = bTagSequence) { const len = encodeLength(this.length); return buffer_1.Buffer.concat([tag, len, ...this.elements], 1 + len.length + this.length); } } exports.default = DumbAsn1Encoder; jose-4.11.4/dist/node/cjs/runtime/base64url.js000066400000000000000000000021211437043056600210440ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.decode = exports.encode = exports.encodeBase64 = exports.decodeBase64 = void 0; const buffer_1 = require("buffer"); const buffer_utils_js_1 = require("../lib/buffer_utils.js"); let encode; exports.encode = encode; function normalize(input) { let encoded = input; if (encoded instanceof Uint8Array) { encoded = buffer_utils_js_1.decoder.decode(encoded); } return encoded; } if (buffer_1.Buffer.isEncoding('base64url')) { exports.encode = encode = (input) => buffer_1.Buffer.from(input).toString('base64url'); } else { exports.encode = encode = (input) => buffer_1.Buffer.from(input).toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); } const decodeBase64 = (input) => buffer_1.Buffer.from(input, 'base64'); exports.decodeBase64 = decodeBase64; const encodeBase64 = (input) => buffer_1.Buffer.from(input).toString('base64'); exports.encodeBase64 = encodeBase64; const decode = (input) => buffer_1.Buffer.from(normalize(input), 'base64'); exports.decode = decode; jose-4.11.4/dist/node/cjs/runtime/cbc_tag.js000066400000000000000000000010241437043056600206200ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const crypto_1 = require("crypto"); const buffer_utils_js_1 = require("../lib/buffer_utils.js"); function cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) { const macData = (0, buffer_utils_js_1.concat)(aad, iv, ciphertext, (0, buffer_utils_js_1.uint64be)(aad.length << 3)); const hmac = (0, crypto_1.createHmac)(`sha${macSize}`, macKey); hmac.update(macData); return hmac.digest().slice(0, keySize >> 3); } exports.default = cbcTag; jose-4.11.4/dist/node/cjs/runtime/check_cek_length.js000066400000000000000000000026471437043056600225120ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const errors_js_1 = require("../util/errors.js"); const is_key_object_js_1 = require("./is_key_object.js"); const checkCekLength = (enc, cek) => { let expected; switch (enc) { case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': expected = parseInt(enc.slice(-3), 10); break; case 'A128GCM': case 'A192GCM': case 'A256GCM': expected = parseInt(enc.slice(1, 4), 10); break; default: throw new errors_js_1.JOSENotSupported(`Content Encryption Algorithm ${enc} is not supported either by JOSE or your javascript runtime`); } if (cek instanceof Uint8Array) { const actual = cek.byteLength << 3; if (actual !== expected) { throw new errors_js_1.JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); } return; } if ((0, is_key_object_js_1.default)(cek) && cek.type === 'secret') { const actual = cek.symmetricKeySize << 3; if (actual !== expected) { throw new errors_js_1.JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); } return; } throw new TypeError('Invalid Content Encryption Key type'); }; exports.default = checkCekLength; jose-4.11.4/dist/node/cjs/runtime/check_modulus_length.js000066400000000000000000000033171437043056600234330ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.setModulusLength = exports.weakMap = void 0; exports.weakMap = new WeakMap(); const getLength = (buf, index) => { let len = buf.readUInt8(1); if ((len & 0x80) === 0) { if (index === 0) { return len; } return getLength(buf.subarray(2 + len), index - 1); } const num = len & 0x7f; len = 0; for (let i = 0; i < num; i++) { len <<= 8; const j = buf.readUInt8(2 + i); len |= j; } if (index === 0) { return len; } return getLength(buf.subarray(2 + len), index - 1); }; const getLengthOfSeqIndex = (sequence, index) => { const len = sequence.readUInt8(1); if ((len & 0x80) === 0) { return getLength(sequence.subarray(2), index); } const num = len & 0x7f; return getLength(sequence.subarray(2 + num), index); }; const getModulusLength = (key) => { var _a, _b; if (exports.weakMap.has(key)) { return exports.weakMap.get(key); } const modulusLength = (_b = (_a = key.asymmetricKeyDetails) === null || _a === void 0 ? void 0 : _a.modulusLength) !== null && _b !== void 0 ? _b : (getLengthOfSeqIndex(key.export({ format: 'der', type: 'pkcs1' }), key.type === 'private' ? 1 : 0) - 1) << 3; exports.weakMap.set(key, modulusLength); return modulusLength; }; const setModulusLength = (keyObject, modulusLength) => { exports.weakMap.set(keyObject, modulusLength); }; exports.setModulusLength = setModulusLength; exports.default = (key, alg) => { if (getModulusLength(key) < 2048) { throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); } }; jose-4.11.4/dist/node/cjs/runtime/ciphers.js000066400000000000000000000004071437043056600206770ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const crypto_1 = require("crypto"); let ciphers; exports.default = (algorithm) => { ciphers || (ciphers = new Set((0, crypto_1.getCiphers)())); return ciphers.has(algorithm); }; jose-4.11.4/dist/node/cjs/runtime/decrypt.js000066400000000000000000000073311437043056600207170ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const crypto_1 = require("crypto"); const check_iv_length_js_1 = require("../lib/check_iv_length.js"); const check_cek_length_js_1 = require("./check_cek_length.js"); const buffer_utils_js_1 = require("../lib/buffer_utils.js"); const errors_js_1 = require("../util/errors.js"); const timing_safe_equal_js_1 = require("./timing_safe_equal.js"); const cbc_tag_js_1 = require("./cbc_tag.js"); const webcrypto_js_1 = require("./webcrypto.js"); const crypto_key_js_1 = require("../lib/crypto_key.js"); const is_key_object_js_1 = require("./is_key_object.js"); const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); const ciphers_js_1 = require("./ciphers.js"); const is_key_like_js_1 = require("./is_key_like.js"); function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) { const keySize = parseInt(enc.slice(1, 4), 10); if ((0, is_key_object_js_1.default)(cek)) { cek = cek.export(); } const encKey = cek.subarray(keySize >> 3); const macKey = cek.subarray(0, keySize >> 3); const macSize = parseInt(enc.slice(-3), 10); const algorithm = `aes-${keySize}-cbc`; if (!(0, ciphers_js_1.default)(algorithm)) { throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); } const expectedTag = (0, cbc_tag_js_1.default)(aad, iv, ciphertext, macSize, macKey, keySize); let macCheckPassed; try { macCheckPassed = (0, timing_safe_equal_js_1.default)(tag, expectedTag); } catch { } if (!macCheckPassed) { throw new errors_js_1.JWEDecryptionFailed(); } let plaintext; try { const decipher = (0, crypto_1.createDecipheriv)(algorithm, encKey, iv); plaintext = (0, buffer_utils_js_1.concat)(decipher.update(ciphertext), decipher.final()); } catch { } if (!plaintext) { throw new errors_js_1.JWEDecryptionFailed(); } return plaintext; } function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) { const keySize = parseInt(enc.slice(1, 4), 10); const algorithm = `aes-${keySize}-gcm`; if (!(0, ciphers_js_1.default)(algorithm)) { throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); } try { const decipher = (0, crypto_1.createDecipheriv)(algorithm, cek, iv, { authTagLength: 16 }); decipher.setAuthTag(tag); if (aad.byteLength) { decipher.setAAD(aad, { plaintextLength: ciphertext.length }); } const plaintext = decipher.update(ciphertext); decipher.final(); return plaintext; } catch { throw new errors_js_1.JWEDecryptionFailed(); } } const decrypt = (enc, cek, ciphertext, iv, tag, aad) => { let key; if ((0, webcrypto_js_1.isCryptoKey)(cek)) { (0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, 'decrypt'); key = crypto_1.KeyObject.from(cek); } else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) { key = cek; } else { throw new TypeError((0, invalid_key_input_js_1.default)(cek, ...is_key_like_js_1.types, 'Uint8Array')); } (0, check_cek_length_js_1.default)(enc, key); (0, check_iv_length_js_1.default)(enc, iv); switch (enc) { case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': return cbcDecrypt(enc, key, ciphertext, iv, tag, aad); case 'A128GCM': case 'A192GCM': case 'A256GCM': return gcmDecrypt(enc, key, ciphertext, iv, tag, aad); default: throw new errors_js_1.JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); } }; exports.default = decrypt; jose-4.11.4/dist/node/cjs/runtime/digest.js000066400000000000000000000003521437043056600205200ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const crypto_1 = require("crypto"); const digest = (algorithm, data) => (0, crypto_1.createHash)(algorithm).update(data).digest(); exports.default = digest; jose-4.11.4/dist/node/cjs/runtime/dsa_digest.js000066400000000000000000000013071437043056600213500ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const errors_js_1 = require("../util/errors.js"); function dsaDigest(alg) { switch (alg) { case 'PS256': case 'RS256': case 'ES256': case 'ES256K': return 'sha256'; case 'PS384': case 'RS384': case 'ES384': return 'sha384'; case 'PS512': case 'RS512': case 'ES512': return 'sha512'; case 'EdDSA': return undefined; default: throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } } exports.default = dsaDigest; jose-4.11.4/dist/node/cjs/runtime/ecdhes.js000066400000000000000000000061471437043056600205040ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ecdhAllowed = exports.generateEpk = exports.deriveKey = void 0; const crypto_1 = require("crypto"); const util_1 = require("util"); const get_named_curve_js_1 = require("./get_named_curve.js"); const buffer_utils_js_1 = require("../lib/buffer_utils.js"); const errors_js_1 = require("../util/errors.js"); const webcrypto_js_1 = require("./webcrypto.js"); const crypto_key_js_1 = require("../lib/crypto_key.js"); const is_key_object_js_1 = require("./is_key_object.js"); const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); const is_key_like_js_1 = require("./is_key_like.js"); const generateKeyPair = (0, util_1.promisify)(crypto_1.generateKeyPair); async function deriveKey(publicKee, privateKee, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) { let publicKey; if ((0, webcrypto_js_1.isCryptoKey)(publicKee)) { (0, crypto_key_js_1.checkEncCryptoKey)(publicKee, 'ECDH'); publicKey = crypto_1.KeyObject.from(publicKee); } else if ((0, is_key_object_js_1.default)(publicKee)) { publicKey = publicKee; } else { throw new TypeError((0, invalid_key_input_js_1.default)(publicKee, ...is_key_like_js_1.types)); } let privateKey; if ((0, webcrypto_js_1.isCryptoKey)(privateKee)) { (0, crypto_key_js_1.checkEncCryptoKey)(privateKee, 'ECDH', 'deriveBits'); privateKey = crypto_1.KeyObject.from(privateKee); } else if ((0, is_key_object_js_1.default)(privateKee)) { privateKey = privateKee; } else { throw new TypeError((0, invalid_key_input_js_1.default)(privateKee, ...is_key_like_js_1.types)); } const value = (0, buffer_utils_js_1.concat)((0, buffer_utils_js_1.lengthAndInput)(buffer_utils_js_1.encoder.encode(algorithm)), (0, buffer_utils_js_1.lengthAndInput)(apu), (0, buffer_utils_js_1.lengthAndInput)(apv), (0, buffer_utils_js_1.uint32be)(keyLength)); const sharedSecret = (0, crypto_1.diffieHellman)({ privateKey, publicKey }); return (0, buffer_utils_js_1.concatKdf)(sharedSecret, keyLength, value); } exports.deriveKey = deriveKey; async function generateEpk(kee) { let key; if ((0, webcrypto_js_1.isCryptoKey)(kee)) { key = crypto_1.KeyObject.from(kee); } else if ((0, is_key_object_js_1.default)(kee)) { key = kee; } else { throw new TypeError((0, invalid_key_input_js_1.default)(kee, ...is_key_like_js_1.types)); } switch (key.asymmetricKeyType) { case 'x25519': return generateKeyPair('x25519'); case 'x448': { return generateKeyPair('x448'); } case 'ec': { const namedCurve = (0, get_named_curve_js_1.default)(key); return generateKeyPair('ec', { namedCurve }); } default: throw new errors_js_1.JOSENotSupported('Invalid or unsupported EPK'); } } exports.generateEpk = generateEpk; const ecdhAllowed = (key) => ['P-256', 'P-384', 'P-521', 'X25519', 'X448'].includes((0, get_named_curve_js_1.default)(key)); exports.ecdhAllowed = ecdhAllowed; jose-4.11.4/dist/node/cjs/runtime/encrypt.js000066400000000000000000000062321437043056600207300ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const crypto_1 = require("crypto"); const check_iv_length_js_1 = require("../lib/check_iv_length.js"); const check_cek_length_js_1 = require("./check_cek_length.js"); const buffer_utils_js_1 = require("../lib/buffer_utils.js"); const cbc_tag_js_1 = require("./cbc_tag.js"); const webcrypto_js_1 = require("./webcrypto.js"); const crypto_key_js_1 = require("../lib/crypto_key.js"); const is_key_object_js_1 = require("./is_key_object.js"); const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); const errors_js_1 = require("../util/errors.js"); const ciphers_js_1 = require("./ciphers.js"); const is_key_like_js_1 = require("./is_key_like.js"); function cbcEncrypt(enc, plaintext, cek, iv, aad) { const keySize = parseInt(enc.slice(1, 4), 10); if ((0, is_key_object_js_1.default)(cek)) { cek = cek.export(); } const encKey = cek.subarray(keySize >> 3); const macKey = cek.subarray(0, keySize >> 3); const algorithm = `aes-${keySize}-cbc`; if (!(0, ciphers_js_1.default)(algorithm)) { throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); } const cipher = (0, crypto_1.createCipheriv)(algorithm, encKey, iv); const ciphertext = (0, buffer_utils_js_1.concat)(cipher.update(plaintext), cipher.final()); const macSize = parseInt(enc.slice(-3), 10); const tag = (0, cbc_tag_js_1.default)(aad, iv, ciphertext, macSize, macKey, keySize); return { ciphertext, tag }; } function gcmEncrypt(enc, plaintext, cek, iv, aad) { const keySize = parseInt(enc.slice(1, 4), 10); const algorithm = `aes-${keySize}-gcm`; if (!(0, ciphers_js_1.default)(algorithm)) { throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); } const cipher = (0, crypto_1.createCipheriv)(algorithm, cek, iv, { authTagLength: 16 }); if (aad.byteLength) { cipher.setAAD(aad, { plaintextLength: plaintext.length }); } const ciphertext = cipher.update(plaintext); cipher.final(); const tag = cipher.getAuthTag(); return { ciphertext, tag }; } const encrypt = (enc, plaintext, cek, iv, aad) => { let key; if ((0, webcrypto_js_1.isCryptoKey)(cek)) { (0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, 'encrypt'); key = crypto_1.KeyObject.from(cek); } else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) { key = cek; } else { throw new TypeError((0, invalid_key_input_js_1.default)(cek, ...is_key_like_js_1.types, 'Uint8Array')); } (0, check_cek_length_js_1.default)(enc, key); (0, check_iv_length_js_1.default)(enc, iv); switch (enc) { case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': return cbcEncrypt(enc, plaintext, key, iv, aad); case 'A128GCM': case 'A192GCM': case 'A256GCM': return gcmEncrypt(enc, plaintext, key, iv, aad); default: throw new errors_js_1.JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); } }; exports.default = encrypt; jose-4.11.4/dist/node/cjs/runtime/env.js000066400000000000000000000003331437043056600200300ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isCloudflareWorkers = void 0; function isCloudflareWorkers() { return false; } exports.isCloudflareWorkers = isCloudflareWorkers; jose-4.11.4/dist/node/cjs/runtime/fetch_jwks.js000066400000000000000000000026641437043056600214000ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const http = require("http"); const https = require("https"); const events_1 = require("events"); const errors_js_1 = require("../util/errors.js"); const buffer_utils_js_1 = require("../lib/buffer_utils.js"); const fetchJwks = async (url, timeout, options) => { let get; switch (url.protocol) { case 'https:': get = https.get; break; case 'http:': get = http.get; break; default: throw new TypeError('Unsupported URL protocol.'); } const { agent, headers } = options; const req = get(url.href, { agent, timeout, headers, }); const [response] = (await Promise.race([(0, events_1.once)(req, 'response'), (0, events_1.once)(req, 'timeout')])); if (!response) { req.destroy(); throw new errors_js_1.JWKSTimeout(); } if (response.statusCode !== 200) { throw new errors_js_1.JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response'); } const parts = []; for await (const part of response) { parts.push(part); } try { return JSON.parse(buffer_utils_js_1.decoder.decode((0, buffer_utils_js_1.concat)(...parts))); } catch { throw new errors_js_1.JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON'); } }; exports.default = fetchJwks; jose-4.11.4/dist/node/cjs/runtime/flags.js000066400000000000000000000010751437043056600203400ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.jwkImport = exports.jwkExport = exports.rsaPssParams = exports.oneShotCallback = void 0; const [major, minor] = process.versions.node.split('.').map((str) => parseInt(str, 10)); exports.oneShotCallback = major >= 16 || (major === 15 && minor >= 13); exports.rsaPssParams = !('electron' in process.versions) && (major >= 17 || (major === 16 && minor >= 9)); exports.jwkExport = major >= 16 || (major === 15 && minor >= 9); exports.jwkImport = major >= 16 || (major === 15 && minor >= 12); jose-4.11.4/dist/node/cjs/runtime/generate.js000066400000000000000000000102401437043056600210300ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateKeyPair = exports.generateSecret = void 0; const crypto_1 = require("crypto"); const util_1 = require("util"); const random_js_1 = require("./random.js"); const check_modulus_length_js_1 = require("./check_modulus_length.js"); const errors_js_1 = require("../util/errors.js"); const generate = (0, util_1.promisify)(crypto_1.generateKeyPair); async function generateSecret(alg, options) { let length; switch (alg) { case 'HS256': case 'HS384': case 'HS512': case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': length = parseInt(alg.slice(-3), 10); break; case 'A128KW': case 'A192KW': case 'A256KW': case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': case 'A128GCM': case 'A192GCM': case 'A256GCM': length = parseInt(alg.slice(1, 4), 10); break; default: throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } return (0, crypto_1.createSecretKey)((0, random_js_1.default)(new Uint8Array(length >> 3))); } exports.generateSecret = generateSecret; async function generateKeyPair(alg, options) { var _a, _b; switch (alg) { case 'RS256': case 'RS384': case 'RS512': case 'PS256': case 'PS384': case 'PS512': case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': case 'RSA1_5': { const modulusLength = (_a = options === null || options === void 0 ? void 0 : options.modulusLength) !== null && _a !== void 0 ? _a : 2048; if (typeof modulusLength !== 'number' || modulusLength < 2048) { throw new errors_js_1.JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used'); } const keypair = await generate('rsa', { modulusLength, publicExponent: 0x10001, }); (0, check_modulus_length_js_1.setModulusLength)(keypair.privateKey, modulusLength); (0, check_modulus_length_js_1.setModulusLength)(keypair.publicKey, modulusLength); return keypair; } case 'ES256': return generate('ec', { namedCurve: 'P-256' }); case 'ES256K': return generate('ec', { namedCurve: 'secp256k1' }); case 'ES384': return generate('ec', { namedCurve: 'P-384' }); case 'ES512': return generate('ec', { namedCurve: 'P-521' }); case 'EdDSA': { switch (options === null || options === void 0 ? void 0 : options.crv) { case undefined: case 'Ed25519': return generate('ed25519'); case 'Ed448': return generate('ed448'); default: throw new errors_js_1.JOSENotSupported('Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448'); } } case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': const crv = (_b = options === null || options === void 0 ? void 0 : options.crv) !== null && _b !== void 0 ? _b : 'P-256'; switch (crv) { case undefined: case 'P-256': case 'P-384': case 'P-521': return generate('ec', { namedCurve: crv }); case 'X25519': return generate('x25519'); case 'X448': return generate('x448'); default: throw new errors_js_1.JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448'); } default: throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } } exports.generateKeyPair = generateKeyPair; jose-4.11.4/dist/node/cjs/runtime/get_named_curve.js000066400000000000000000000070421437043056600223730ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.setCurve = exports.weakMap = void 0; const buffer_1 = require("buffer"); const crypto_1 = require("crypto"); const errors_js_1 = require("../util/errors.js"); const webcrypto_js_1 = require("./webcrypto.js"); const is_key_object_js_1 = require("./is_key_object.js"); const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); const is_key_like_js_1 = require("./is_key_like.js"); const p256 = buffer_1.Buffer.from([42, 134, 72, 206, 61, 3, 1, 7]); const p384 = buffer_1.Buffer.from([43, 129, 4, 0, 34]); const p521 = buffer_1.Buffer.from([43, 129, 4, 0, 35]); const secp256k1 = buffer_1.Buffer.from([43, 129, 4, 0, 10]); exports.weakMap = new WeakMap(); const namedCurveToJOSE = (namedCurve) => { switch (namedCurve) { case 'prime256v1': return 'P-256'; case 'secp384r1': return 'P-384'; case 'secp521r1': return 'P-521'; case 'secp256k1': return 'secp256k1'; default: throw new errors_js_1.JOSENotSupported('Unsupported key curve for this operation'); } }; const getNamedCurve = (kee, raw) => { var _a; let key; if ((0, webcrypto_js_1.isCryptoKey)(kee)) { key = crypto_1.KeyObject.from(kee); } else if ((0, is_key_object_js_1.default)(kee)) { key = kee; } else { throw new TypeError((0, invalid_key_input_js_1.default)(kee, ...is_key_like_js_1.types)); } if (key.type === 'secret') { throw new TypeError('only "private" or "public" type keys can be used for this operation'); } switch (key.asymmetricKeyType) { case 'ed25519': case 'ed448': return `Ed${key.asymmetricKeyType.slice(2)}`; case 'x25519': case 'x448': return `X${key.asymmetricKeyType.slice(1)}`; case 'ec': { if (exports.weakMap.has(key)) { return exports.weakMap.get(key); } let namedCurve = (_a = key.asymmetricKeyDetails) === null || _a === void 0 ? void 0 : _a.namedCurve; if (!namedCurve && key.type === 'private') { namedCurve = getNamedCurve((0, crypto_1.createPublicKey)(key), true); } else if (!namedCurve) { const buf = key.export({ format: 'der', type: 'spki' }); const i = buf[1] < 128 ? 14 : 15; const len = buf[i]; const curveOid = buf.slice(i + 1, i + 1 + len); if (curveOid.equals(p256)) { namedCurve = 'prime256v1'; } else if (curveOid.equals(p384)) { namedCurve = 'secp384r1'; } else if (curveOid.equals(p521)) { namedCurve = 'secp521r1'; } else if (curveOid.equals(secp256k1)) { namedCurve = 'secp256k1'; } else { throw new errors_js_1.JOSENotSupported('Unsupported key curve for this operation'); } } if (raw) return namedCurve; const curve = namedCurveToJOSE(namedCurve); exports.weakMap.set(key, curve); return curve; } default: throw new TypeError('Invalid asymmetric key type for this operation'); } }; function setCurve(keyObject, curve) { exports.weakMap.set(keyObject, curve); } exports.setCurve = setCurve; exports.default = getNamedCurve; jose-4.11.4/dist/node/cjs/runtime/get_sign_verify_key.js000066400000000000000000000017661437043056600233060ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const crypto_1 = require("crypto"); const webcrypto_js_1 = require("./webcrypto.js"); const crypto_key_js_1 = require("../lib/crypto_key.js"); const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); const is_key_like_js_1 = require("./is_key_like.js"); function getSignVerifyKey(alg, key, usage) { if (key instanceof Uint8Array) { if (!alg.startsWith('HS')) { throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types)); } return (0, crypto_1.createSecretKey)(key); } if (key instanceof crypto_1.KeyObject) { return key; } if ((0, webcrypto_js_1.isCryptoKey)(key)) { (0, crypto_key_js_1.checkSigCryptoKey)(key, alg, usage); return crypto_1.KeyObject.from(key); } throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); } exports.default = getSignVerifyKey; jose-4.11.4/dist/node/cjs/runtime/hmac_digest.js000066400000000000000000000007721437043056600215160ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const errors_js_1 = require("../util/errors.js"); function hmacDigest(alg) { switch (alg) { case 'HS256': return 'sha256'; case 'HS384': return 'sha384'; case 'HS512': return 'sha512'; default: throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } } exports.default = hmacDigest; jose-4.11.4/dist/node/cjs/runtime/is_key_like.js000066400000000000000000000010371437043056600215310ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.types = void 0; const webcrypto_js_1 = require("./webcrypto.js"); const is_key_object_js_1 = require("./is_key_object.js"); exports.default = (key) => (0, is_key_object_js_1.default)(key) || (0, webcrypto_js_1.isCryptoKey)(key); const types = ['KeyObject']; exports.types = types; if (globalThis.CryptoKey || (webcrypto_js_1.default === null || webcrypto_js_1.default === void 0 ? void 0 : webcrypto_js_1.default.CryptoKey)) { types.push('CryptoKey'); } jose-4.11.4/dist/node/cjs/runtime/is_key_object.js000066400000000000000000000004441437043056600220540ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const crypto_1 = require("crypto"); const util = require("util"); exports.default = util.types.isKeyObject ? (obj) => util.types.isKeyObject(obj) : (obj) => obj != null && obj instanceof crypto_1.KeyObject; jose-4.11.4/dist/node/cjs/runtime/jwk_to_key.js000066400000000000000000000126371437043056600214170ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const buffer_1 = require("buffer"); const crypto_1 = require("crypto"); const base64url_js_1 = require("./base64url.js"); const errors_js_1 = require("../util/errors.js"); const get_named_curve_js_1 = require("./get_named_curve.js"); const check_modulus_length_js_1 = require("./check_modulus_length.js"); const asn1_sequence_encoder_js_1 = require("./asn1_sequence_encoder.js"); const flags_js_1 = require("./flags.js"); const parse = (jwk) => { if (flags_js_1.jwkImport && jwk.kty !== 'oct') { return jwk.d ? (0, crypto_1.createPrivateKey)({ format: 'jwk', key: jwk }) : (0, crypto_1.createPublicKey)({ format: 'jwk', key: jwk }); } switch (jwk.kty) { case 'oct': { return (0, crypto_1.createSecretKey)((0, base64url_js_1.decode)(jwk.k)); } case 'RSA': { const enc = new asn1_sequence_encoder_js_1.default(); const isPrivate = jwk.d !== undefined; const modulus = buffer_1.Buffer.from(jwk.n, 'base64'); const exponent = buffer_1.Buffer.from(jwk.e, 'base64'); if (isPrivate) { enc.zero(); enc.unsignedInteger(modulus); enc.unsignedInteger(exponent); enc.unsignedInteger(buffer_1.Buffer.from(jwk.d, 'base64')); enc.unsignedInteger(buffer_1.Buffer.from(jwk.p, 'base64')); enc.unsignedInteger(buffer_1.Buffer.from(jwk.q, 'base64')); enc.unsignedInteger(buffer_1.Buffer.from(jwk.dp, 'base64')); enc.unsignedInteger(buffer_1.Buffer.from(jwk.dq, 'base64')); enc.unsignedInteger(buffer_1.Buffer.from(jwk.qi, 'base64')); } else { enc.unsignedInteger(modulus); enc.unsignedInteger(exponent); } const der = enc.end(); const createInput = { key: der, format: 'der', type: 'pkcs1', }; const keyObject = isPrivate ? (0, crypto_1.createPrivateKey)(createInput) : (0, crypto_1.createPublicKey)(createInput); (0, check_modulus_length_js_1.setModulusLength)(keyObject, modulus.length << 3); return keyObject; } case 'EC': { const enc = new asn1_sequence_encoder_js_1.default(); const isPrivate = jwk.d !== undefined; const pub = buffer_1.Buffer.concat([ buffer_1.Buffer.alloc(1, 4), buffer_1.Buffer.from(jwk.x, 'base64'), buffer_1.Buffer.from(jwk.y, 'base64'), ]); if (isPrivate) { enc.zero(); const enc$1 = new asn1_sequence_encoder_js_1.default(); enc$1.oidFor('ecPublicKey'); enc$1.oidFor(jwk.crv); enc.add(enc$1.end()); const enc$2 = new asn1_sequence_encoder_js_1.default(); enc$2.one(); enc$2.octStr(buffer_1.Buffer.from(jwk.d, 'base64')); const enc$3 = new asn1_sequence_encoder_js_1.default(); enc$3.bitStr(pub); const f2 = enc$3.end(buffer_1.Buffer.from([0xa1])); enc$2.add(f2); const f = enc$2.end(); const enc$4 = new asn1_sequence_encoder_js_1.default(); enc$4.add(f); const f3 = enc$4.end(buffer_1.Buffer.from([0x04])); enc.add(f3); const der = enc.end(); const keyObject = (0, crypto_1.createPrivateKey)({ key: der, format: 'der', type: 'pkcs8' }); (0, get_named_curve_js_1.setCurve)(keyObject, jwk.crv); return keyObject; } const enc$1 = new asn1_sequence_encoder_js_1.default(); enc$1.oidFor('ecPublicKey'); enc$1.oidFor(jwk.crv); enc.add(enc$1.end()); enc.bitStr(pub); const der = enc.end(); const keyObject = (0, crypto_1.createPublicKey)({ key: der, format: 'der', type: 'spki' }); (0, get_named_curve_js_1.setCurve)(keyObject, jwk.crv); return keyObject; } case 'OKP': { const enc = new asn1_sequence_encoder_js_1.default(); const isPrivate = jwk.d !== undefined; if (isPrivate) { enc.zero(); const enc$1 = new asn1_sequence_encoder_js_1.default(); enc$1.oidFor(jwk.crv); enc.add(enc$1.end()); const enc$2 = new asn1_sequence_encoder_js_1.default(); enc$2.octStr(buffer_1.Buffer.from(jwk.d, 'base64')); const f = enc$2.end(buffer_1.Buffer.from([0x04])); enc.add(f); const der = enc.end(); return (0, crypto_1.createPrivateKey)({ key: der, format: 'der', type: 'pkcs8' }); } const enc$1 = new asn1_sequence_encoder_js_1.default(); enc$1.oidFor(jwk.crv); enc.add(enc$1.end()); enc.bitStr(buffer_1.Buffer.from(jwk.x, 'base64')); const der = enc.end(); return (0, crypto_1.createPublicKey)({ key: der, format: 'der', type: 'spki' }); } default: throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); } }; exports.default = parse; jose-4.11.4/dist/node/cjs/runtime/key_to_jwk.js000066400000000000000000000160141437043056600214100ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const crypto_1 = require("crypto"); const base64url_js_1 = require("./base64url.js"); const asn1_sequence_decoder_js_1 = require("./asn1_sequence_decoder.js"); const errors_js_1 = require("../util/errors.js"); const get_named_curve_js_1 = require("./get_named_curve.js"); const webcrypto_js_1 = require("./webcrypto.js"); const is_key_object_js_1 = require("./is_key_object.js"); const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); const is_key_like_js_1 = require("./is_key_like.js"); const flags_js_1 = require("./flags.js"); const keyToJWK = (key) => { let keyObject; if ((0, webcrypto_js_1.isCryptoKey)(key)) { if (!key.extractable) { throw new TypeError('CryptoKey is not extractable'); } keyObject = crypto_1.KeyObject.from(key); } else if ((0, is_key_object_js_1.default)(key)) { keyObject = key; } else if (key instanceof Uint8Array) { return { kty: 'oct', k: (0, base64url_js_1.encode)(key), }; } else { throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); } if (flags_js_1.jwkExport) { if (keyObject.type !== 'secret' && !['rsa', 'ec', 'ed25519', 'x25519', 'ed448', 'x448'].includes(keyObject.asymmetricKeyType)) { throw new errors_js_1.JOSENotSupported('Unsupported key asymmetricKeyType'); } return keyObject.export({ format: 'jwk' }); } switch (keyObject.type) { case 'secret': return { kty: 'oct', k: (0, base64url_js_1.encode)(keyObject.export()), }; case 'private': case 'public': { switch (keyObject.asymmetricKeyType) { case 'rsa': { const der = keyObject.export({ format: 'der', type: 'pkcs1' }); const dec = new asn1_sequence_decoder_js_1.default(der); if (keyObject.type === 'private') { dec.unsignedInteger(); } const n = (0, base64url_js_1.encode)(dec.unsignedInteger()); const e = (0, base64url_js_1.encode)(dec.unsignedInteger()); let jwk; if (keyObject.type === 'private') { jwk = { d: (0, base64url_js_1.encode)(dec.unsignedInteger()), p: (0, base64url_js_1.encode)(dec.unsignedInteger()), q: (0, base64url_js_1.encode)(dec.unsignedInteger()), dp: (0, base64url_js_1.encode)(dec.unsignedInteger()), dq: (0, base64url_js_1.encode)(dec.unsignedInteger()), qi: (0, base64url_js_1.encode)(dec.unsignedInteger()), }; } dec.end(); return { kty: 'RSA', n, e, ...jwk }; } case 'ec': { const crv = (0, get_named_curve_js_1.default)(keyObject); let len; let offset; let correction; switch (crv) { case 'secp256k1': len = 64; offset = 31 + 2; correction = -1; break; case 'P-256': len = 64; offset = 34 + 2; correction = -1; break; case 'P-384': len = 96; offset = 33 + 2; correction = -3; break; case 'P-521': len = 132; offset = 33 + 2; correction = -3; break; default: throw new errors_js_1.JOSENotSupported('Unsupported curve'); } if (keyObject.type === 'public') { const der = keyObject.export({ type: 'spki', format: 'der' }); return { kty: 'EC', crv, x: (0, base64url_js_1.encode)(der.subarray(-len, -len / 2)), y: (0, base64url_js_1.encode)(der.subarray(-len / 2)), }; } const der = keyObject.export({ type: 'pkcs8', format: 'der' }); if (der.length < 100) { offset += correction; } return { ...keyToJWK((0, crypto_1.createPublicKey)(keyObject)), d: (0, base64url_js_1.encode)(der.subarray(offset, offset + len / 2)), }; } case 'ed25519': case 'x25519': { const crv = (0, get_named_curve_js_1.default)(keyObject); if (keyObject.type === 'public') { const der = keyObject.export({ type: 'spki', format: 'der' }); return { kty: 'OKP', crv, x: (0, base64url_js_1.encode)(der.subarray(-32)), }; } const der = keyObject.export({ type: 'pkcs8', format: 'der' }); return { ...keyToJWK((0, crypto_1.createPublicKey)(keyObject)), d: (0, base64url_js_1.encode)(der.subarray(-32)), }; } case 'ed448': case 'x448': { const crv = (0, get_named_curve_js_1.default)(keyObject); if (keyObject.type === 'public') { const der = keyObject.export({ type: 'spki', format: 'der' }); return { kty: 'OKP', crv, x: (0, base64url_js_1.encode)(der.subarray(crv === 'Ed448' ? -57 : -56)), }; } const der = keyObject.export({ type: 'pkcs8', format: 'der' }); return { ...keyToJWK((0, crypto_1.createPublicKey)(keyObject)), d: (0, base64url_js_1.encode)(der.subarray(crv === 'Ed448' ? -57 : -56)), }; } default: throw new errors_js_1.JOSENotSupported('Unsupported key asymmetricKeyType'); } } default: throw new errors_js_1.JOSENotSupported('Unsupported key type'); } }; exports.default = keyToJWK; jose-4.11.4/dist/node/cjs/runtime/node_key.js000066400000000000000000000071341437043056600210430ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const crypto_1 = require("crypto"); const get_named_curve_js_1 = require("./get_named_curve.js"); const errors_js_1 = require("../util/errors.js"); const check_modulus_length_js_1 = require("./check_modulus_length.js"); const flags_js_1 = require("./flags.js"); const PSS = { padding: crypto_1.constants.RSA_PKCS1_PSS_PADDING, saltLength: crypto_1.constants.RSA_PSS_SALTLEN_DIGEST, }; const ecCurveAlgMap = new Map([ ['ES256', 'P-256'], ['ES256K', 'secp256k1'], ['ES384', 'P-384'], ['ES512', 'P-521'], ]); function keyForCrypto(alg, key) { switch (alg) { case 'EdDSA': if (!['ed25519', 'ed448'].includes(key.asymmetricKeyType)) { throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448'); } return key; case 'RS256': case 'RS384': case 'RS512': if (key.asymmetricKeyType !== 'rsa') { throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); } (0, check_modulus_length_js_1.default)(key, alg); return key; case flags_js_1.rsaPssParams && 'PS256': case flags_js_1.rsaPssParams && 'PS384': case flags_js_1.rsaPssParams && 'PS512': if (key.asymmetricKeyType === 'rsa-pss') { const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails; const length = parseInt(alg.slice(-3), 10); if (hashAlgorithm !== undefined && (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm)) { throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${alg}`); } if (saltLength !== undefined && saltLength > length >> 3) { throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${alg}`); } } else if (key.asymmetricKeyType !== 'rsa') { throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss'); } (0, check_modulus_length_js_1.default)(key, alg); return { key, ...PSS }; case !flags_js_1.rsaPssParams && 'PS256': case !flags_js_1.rsaPssParams && 'PS384': case !flags_js_1.rsaPssParams && 'PS512': if (key.asymmetricKeyType !== 'rsa') { throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); } (0, check_modulus_length_js_1.default)(key, alg); return { key, ...PSS }; case 'ES256': case 'ES256K': case 'ES384': case 'ES512': { if (key.asymmetricKeyType !== 'ec') { throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ec'); } const actual = (0, get_named_curve_js_1.default)(key); const expected = ecCurveAlgMap.get(alg); if (actual !== expected) { throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`); } return { dsaEncoding: 'ieee-p1363', key }; } default: throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } } exports.default = keyForCrypto; jose-4.11.4/dist/node/cjs/runtime/pbes2kw.js000066400000000000000000000043761437043056600206300ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.decrypt = exports.encrypt = void 0; const util_1 = require("util"); const crypto_1 = require("crypto"); const random_js_1 = require("./random.js"); const buffer_utils_js_1 = require("../lib/buffer_utils.js"); const base64url_js_1 = require("./base64url.js"); const aeskw_js_1 = require("./aeskw.js"); const check_p2s_js_1 = require("../lib/check_p2s.js"); const webcrypto_js_1 = require("./webcrypto.js"); const crypto_key_js_1 = require("../lib/crypto_key.js"); const is_key_object_js_1 = require("./is_key_object.js"); const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); const is_key_like_js_1 = require("./is_key_like.js"); const pbkdf2 = (0, util_1.promisify)(crypto_1.pbkdf2); function getPassword(key, alg) { if ((0, is_key_object_js_1.default)(key)) { return key.export(); } if (key instanceof Uint8Array) { return key; } if ((0, webcrypto_js_1.isCryptoKey)(key)) { (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, 'deriveBits', 'deriveKey'); return crypto_1.KeyObject.from(key).export(); } throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array')); } const encrypt = async (alg, key, cek, p2c = 2048, p2s = (0, random_js_1.default)(new Uint8Array(16))) => { (0, check_p2s_js_1.default)(p2s); const salt = (0, buffer_utils_js_1.p2s)(alg, p2s); const keylen = parseInt(alg.slice(13, 16), 10) >> 3; const password = getPassword(key, alg); const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`); const encryptedKey = await (0, aeskw_js_1.wrap)(alg.slice(-6), derivedKey, cek); return { encryptedKey, p2c, p2s: (0, base64url_js_1.encode)(p2s) }; }; exports.encrypt = encrypt; const decrypt = async (alg, key, encryptedKey, p2c, p2s) => { (0, check_p2s_js_1.default)(p2s); const salt = (0, buffer_utils_js_1.p2s)(alg, p2s); const keylen = parseInt(alg.slice(13, 16), 10) >> 3; const password = getPassword(key, alg); const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`); return (0, aeskw_js_1.unwrap)(alg.slice(-6), derivedKey, encryptedKey); }; exports.decrypt = decrypt; jose-4.11.4/dist/node/cjs/runtime/random.js000066400000000000000000000004001437043056600205130ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var crypto_1 = require("crypto"); Object.defineProperty(exports, "default", { enumerable: true, get: function () { return crypto_1.randomFillSync; } }); jose-4.11.4/dist/node/cjs/runtime/rsaes.js000066400000000000000000000047461437043056600203710ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.decrypt = exports.encrypt = void 0; const crypto_1 = require("crypto"); const check_modulus_length_js_1 = require("./check_modulus_length.js"); const webcrypto_js_1 = require("./webcrypto.js"); const crypto_key_js_1 = require("../lib/crypto_key.js"); const is_key_object_js_1 = require("./is_key_object.js"); const invalid_key_input_js_1 = require("../lib/invalid_key_input.js"); const is_key_like_js_1 = require("./is_key_like.js"); const checkKey = (key, alg) => { if (key.asymmetricKeyType !== 'rsa') { throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); } (0, check_modulus_length_js_1.default)(key, alg); }; const resolvePadding = (alg) => { switch (alg) { case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': return crypto_1.constants.RSA_PKCS1_OAEP_PADDING; case 'RSA1_5': return crypto_1.constants.RSA_PKCS1_PADDING; default: return undefined; } }; const resolveOaepHash = (alg) => { switch (alg) { case 'RSA-OAEP': return 'sha1'; case 'RSA-OAEP-256': return 'sha256'; case 'RSA-OAEP-384': return 'sha384'; case 'RSA-OAEP-512': return 'sha512'; default: return undefined; } }; function ensureKeyObject(key, alg, ...usages) { if ((0, is_key_object_js_1.default)(key)) { return key; } if ((0, webcrypto_js_1.isCryptoKey)(key)) { (0, crypto_key_js_1.checkEncCryptoKey)(key, alg, ...usages); return crypto_1.KeyObject.from(key); } throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types)); } const encrypt = (alg, key, cek) => { const padding = resolvePadding(alg); const oaepHash = resolveOaepHash(alg); const keyObject = ensureKeyObject(key, alg, 'wrapKey', 'encrypt'); checkKey(keyObject, alg); return (0, crypto_1.publicEncrypt)({ key: keyObject, oaepHash, padding }, cek); }; exports.encrypt = encrypt; const decrypt = (alg, key, encryptedKey) => { const padding = resolvePadding(alg); const oaepHash = resolveOaepHash(alg); const keyObject = ensureKeyObject(key, alg, 'unwrapKey', 'decrypt'); checkKey(keyObject, alg); return (0, crypto_1.privateDecrypt)({ key: keyObject, oaepHash, padding }, encryptedKey); }; exports.decrypt = decrypt; jose-4.11.4/dist/node/cjs/runtime/sign.js000066400000000000000000000016641437043056600202100ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const crypto = require("crypto"); const util_1 = require("util"); const dsa_digest_js_1 = require("./dsa_digest.js"); const hmac_digest_js_1 = require("./hmac_digest.js"); const node_key_js_1 = require("./node_key.js"); const get_sign_verify_key_js_1 = require("./get_sign_verify_key.js"); let oneShotSign; if (crypto.sign.length > 3) { oneShotSign = (0, util_1.promisify)(crypto.sign); } else { oneShotSign = crypto.sign; } const sign = async (alg, key, data) => { const keyObject = (0, get_sign_verify_key_js_1.default)(alg, key, 'sign'); if (alg.startsWith('HS')) { const hmac = crypto.createHmac((0, hmac_digest_js_1.default)(alg), keyObject); hmac.update(data); return hmac.digest(); } return oneShotSign((0, dsa_digest_js_1.default)(alg), data, (0, node_key_js_1.default)(alg, keyObject)); }; exports.default = sign; jose-4.11.4/dist/node/cjs/runtime/timing_safe_equal.js000066400000000000000000000003061437043056600227140ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const crypto_1 = require("crypto"); const timingSafeEqual = crypto_1.timingSafeEqual; exports.default = timingSafeEqual; jose-4.11.4/dist/node/cjs/runtime/verify.js000066400000000000000000000024021437043056600205430ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const crypto = require("crypto"); const util_1 = require("util"); const dsa_digest_js_1 = require("./dsa_digest.js"); const node_key_js_1 = require("./node_key.js"); const sign_js_1 = require("./sign.js"); const get_sign_verify_key_js_1 = require("./get_sign_verify_key.js"); const flags_js_1 = require("./flags.js"); let oneShotVerify; if (crypto.verify.length > 4 && flags_js_1.oneShotCallback) { oneShotVerify = (0, util_1.promisify)(crypto.verify); } else { oneShotVerify = crypto.verify; } const verify = async (alg, key, signature, data) => { const keyObject = (0, get_sign_verify_key_js_1.default)(alg, key, 'verify'); if (alg.startsWith('HS')) { const expected = await (0, sign_js_1.default)(alg, keyObject, data); const actual = signature; try { return crypto.timingSafeEqual(actual, expected); } catch { return false; } } const algorithm = (0, dsa_digest_js_1.default)(alg); const keyInput = (0, node_key_js_1.default)(alg, keyObject); try { return await oneShotVerify(algorithm, data, keyInput, signature); } catch { return false; } }; exports.default = verify; jose-4.11.4/dist/node/cjs/runtime/webcrypto.js000066400000000000000000000005421437043056600212600ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isCryptoKey = void 0; const crypto = require("crypto"); const util = require("util"); const webcrypto = crypto.webcrypto; exports.default = webcrypto; exports.isCryptoKey = util.types.isCryptoKey ? (key) => util.types.isCryptoKey(key) : (key) => false; jose-4.11.4/dist/node/cjs/runtime/zlib.js000066400000000000000000000007051437043056600202030ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.deflate = exports.inflate = void 0; const util_1 = require("util"); const zlib_1 = require("zlib"); const inflateRaw = (0, util_1.promisify)(zlib_1.inflateRaw); const deflateRaw = (0, util_1.promisify)(zlib_1.deflateRaw); const inflate = (input) => inflateRaw(input); exports.inflate = inflate; const deflate = (input) => deflateRaw(input); exports.deflate = deflate; jose-4.11.4/dist/node/cjs/util/000077500000000000000000000000001437043056600161755ustar00rootroot00000000000000jose-4.11.4/dist/node/cjs/util/base64url.js000066400000000000000000000003631437043056600203440ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.decode = exports.encode = void 0; const base64url = require("../runtime/base64url.js"); exports.encode = base64url.encode; exports.decode = base64url.decode; jose-4.11.4/dist/node/cjs/util/decode_jwt.js000066400000000000000000000025701437043056600206460ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.decodeJwt = void 0; const base64url_js_1 = require("./base64url.js"); const buffer_utils_js_1 = require("../lib/buffer_utils.js"); const is_object_js_1 = require("../lib/is_object.js"); const errors_js_1 = require("./errors.js"); function decodeJwt(jwt) { if (typeof jwt !== 'string') throw new errors_js_1.JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string'); const { 1: payload, length } = jwt.split('.'); if (length === 5) throw new errors_js_1.JWTInvalid('Only JWTs using Compact JWS serialization can be decoded'); if (length !== 3) throw new errors_js_1.JWTInvalid('Invalid JWT'); if (!payload) throw new errors_js_1.JWTInvalid('JWTs must contain a payload'); let decoded; try { decoded = (0, base64url_js_1.decode)(payload); } catch { throw new errors_js_1.JWTInvalid('Failed to parse the base64url encoded payload'); } let result; try { result = JSON.parse(buffer_utils_js_1.decoder.decode(decoded)); } catch { throw new errors_js_1.JWTInvalid('Failed to parse the decoded payload as JSON'); } if (!(0, is_object_js_1.default)(result)) throw new errors_js_1.JWTInvalid('Invalid JWT Claims Set'); return result; } exports.decodeJwt = decodeJwt; jose-4.11.4/dist/node/cjs/util/decode_protected_header.js000066400000000000000000000024251437043056600233420ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.decodeProtectedHeader = void 0; const base64url_js_1 = require("./base64url.js"); const buffer_utils_js_1 = require("../lib/buffer_utils.js"); const is_object_js_1 = require("../lib/is_object.js"); function decodeProtectedHeader(token) { let protectedB64u; if (typeof token === 'string') { const parts = token.split('.'); if (parts.length === 3 || parts.length === 5) { ; [protectedB64u] = parts; } } else if (typeof token === 'object' && token) { if ('protected' in token) { protectedB64u = token.protected; } else { throw new TypeError('Token does not contain a Protected Header'); } } try { if (typeof protectedB64u !== 'string' || !protectedB64u) { throw new Error(); } const result = JSON.parse(buffer_utils_js_1.decoder.decode((0, base64url_js_1.decode)(protectedB64u))); if (!(0, is_object_js_1.default)(result)) { throw new Error(); } return result; } catch { throw new TypeError('Invalid Token or Protected Header formatting'); } } exports.decodeProtectedHeader = decodeProtectedHeader; jose-4.11.4/dist/node/cjs/util/errors.js000066400000000000000000000116601437043056600200530ustar00rootroot00000000000000"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.JWSSignatureVerificationFailed = exports.JWKSTimeout = exports.JWKSMultipleMatchingKeys = exports.JWKSNoMatchingKey = exports.JWKSInvalid = exports.JWKInvalid = exports.JWTInvalid = exports.JWSInvalid = exports.JWEInvalid = exports.JWEDecryptionFailed = exports.JOSENotSupported = exports.JOSEAlgNotAllowed = exports.JWTExpired = exports.JWTClaimValidationFailed = exports.JOSEError = void 0; class JOSEError extends Error { static get code() { return 'ERR_JOSE_GENERIC'; } constructor(message) { var _a; super(message); this.code = 'ERR_JOSE_GENERIC'; this.name = this.constructor.name; (_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, this, this.constructor); } } exports.JOSEError = JOSEError; class JWTClaimValidationFailed extends JOSEError { static get code() { return 'ERR_JWT_CLAIM_VALIDATION_FAILED'; } constructor(message, claim = 'unspecified', reason = 'unspecified') { super(message); this.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'; this.claim = claim; this.reason = reason; } } exports.JWTClaimValidationFailed = JWTClaimValidationFailed; class JWTExpired extends JOSEError { static get code() { return 'ERR_JWT_EXPIRED'; } constructor(message, claim = 'unspecified', reason = 'unspecified') { super(message); this.code = 'ERR_JWT_EXPIRED'; this.claim = claim; this.reason = reason; } } exports.JWTExpired = JWTExpired; class JOSEAlgNotAllowed extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JOSE_ALG_NOT_ALLOWED'; } static get code() { return 'ERR_JOSE_ALG_NOT_ALLOWED'; } } exports.JOSEAlgNotAllowed = JOSEAlgNotAllowed; class JOSENotSupported extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JOSE_NOT_SUPPORTED'; } static get code() { return 'ERR_JOSE_NOT_SUPPORTED'; } } exports.JOSENotSupported = JOSENotSupported; class JWEDecryptionFailed extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWE_DECRYPTION_FAILED'; this.message = 'decryption operation failed'; } static get code() { return 'ERR_JWE_DECRYPTION_FAILED'; } } exports.JWEDecryptionFailed = JWEDecryptionFailed; class JWEInvalid extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWE_INVALID'; } static get code() { return 'ERR_JWE_INVALID'; } } exports.JWEInvalid = JWEInvalid; class JWSInvalid extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWS_INVALID'; } static get code() { return 'ERR_JWS_INVALID'; } } exports.JWSInvalid = JWSInvalid; class JWTInvalid extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWT_INVALID'; } static get code() { return 'ERR_JWT_INVALID'; } } exports.JWTInvalid = JWTInvalid; class JWKInvalid extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWK_INVALID'; } static get code() { return 'ERR_JWK_INVALID'; } } exports.JWKInvalid = JWKInvalid; class JWKSInvalid extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWKS_INVALID'; } static get code() { return 'ERR_JWKS_INVALID'; } } exports.JWKSInvalid = JWKSInvalid; class JWKSNoMatchingKey extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWKS_NO_MATCHING_KEY'; this.message = 'no applicable key found in the JSON Web Key Set'; } static get code() { return 'ERR_JWKS_NO_MATCHING_KEY'; } } exports.JWKSNoMatchingKey = JWKSNoMatchingKey; class JWKSMultipleMatchingKeys extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; this.message = 'multiple matching keys found in the JSON Web Key Set'; } static get code() { return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; } } exports.JWKSMultipleMatchingKeys = JWKSMultipleMatchingKeys; class JWKSTimeout extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWKS_TIMEOUT'; this.message = 'request timed out'; } static get code() { return 'ERR_JWKS_TIMEOUT'; } } exports.JWKSTimeout = JWKSTimeout; class JWSSignatureVerificationFailed extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; this.message = 'signature verification failed'; } static get code() { return 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; } } exports.JWSSignatureVerificationFailed = JWSSignatureVerificationFailed; jose-4.11.4/dist/node/esm/000077500000000000000000000000001437043056600152255ustar00rootroot00000000000000jose-4.11.4/dist/node/esm/index.js000066400000000000000000000032051437043056600166720ustar00rootroot00000000000000export { compactDecrypt } from './jwe/compact/decrypt.js'; export { flattenedDecrypt } from './jwe/flattened/decrypt.js'; export { generalDecrypt } from './jwe/general/decrypt.js'; export { GeneralEncrypt } from './jwe/general/encrypt.js'; export { compactVerify } from './jws/compact/verify.js'; export { flattenedVerify } from './jws/flattened/verify.js'; export { generalVerify } from './jws/general/verify.js'; export { jwtVerify } from './jwt/verify.js'; export { jwtDecrypt } from './jwt/decrypt.js'; export { CompactEncrypt } from './jwe/compact/encrypt.js'; export { FlattenedEncrypt } from './jwe/flattened/encrypt.js'; export { CompactSign } from './jws/compact/sign.js'; export { FlattenedSign } from './jws/flattened/sign.js'; export { GeneralSign } from './jws/general/sign.js'; export { SignJWT } from './jwt/sign.js'; export { EncryptJWT } from './jwt/encrypt.js'; export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.js'; export { EmbeddedJWK } from './jwk/embedded.js'; export { createLocalJWKSet } from './jwks/local.js'; export { createRemoteJWKSet } from './jwks/remote.js'; export { UnsecuredJWT } from './jwt/unsecured.js'; export { exportPKCS8, exportSPKI, exportJWK } from './key/export.js'; export { importSPKI, importPKCS8, importX509, importJWK } from './key/import.js'; export { decodeProtectedHeader } from './util/decode_protected_header.js'; export { decodeJwt } from './util/decode_jwt.js'; export * as errors from './util/errors.js'; export { generateKeyPair } from './key/generate_key_pair.js'; export { generateSecret } from './key/generate_secret.js'; export * as base64url from './util/base64url.js'; jose-4.11.4/dist/node/esm/jwe/000077500000000000000000000000001437043056600160125ustar00rootroot00000000000000jose-4.11.4/dist/node/esm/jwe/compact/000077500000000000000000000000001437043056600174405ustar00rootroot00000000000000jose-4.11.4/dist/node/esm/jwe/compact/decrypt.js000066400000000000000000000020601437043056600214460ustar00rootroot00000000000000import { flattenedDecrypt } from '../flattened/decrypt.js'; import { JWEInvalid } from '../../util/errors.js'; import { decoder } from '../../lib/buffer_utils.js'; export async function compactDecrypt(jwe, key, options) { if (jwe instanceof Uint8Array) { jwe = decoder.decode(jwe); } if (typeof jwe !== 'string') { throw new JWEInvalid('Compact JWE must be a string or Uint8Array'); } const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.'); if (length !== 5) { throw new JWEInvalid('Invalid Compact JWE'); } const decrypted = await flattenedDecrypt({ ciphertext, iv: (iv || undefined), protected: protectedHeader || undefined, tag: (tag || undefined), encrypted_key: encryptedKey || undefined, }, key, options); const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader }; if (typeof key === 'function') { return { ...result, key: decrypted.key }; } return result; } jose-4.11.4/dist/node/esm/jwe/compact/encrypt.js000066400000000000000000000015611437043056600214650ustar00rootroot00000000000000import { FlattenedEncrypt } from '../flattened/encrypt.js'; export class CompactEncrypt { constructor(plaintext) { this._flattened = new FlattenedEncrypt(plaintext); } setContentEncryptionKey(cek) { this._flattened.setContentEncryptionKey(cek); return this; } setInitializationVector(iv) { this._flattened.setInitializationVector(iv); return this; } setProtectedHeader(protectedHeader) { this._flattened.setProtectedHeader(protectedHeader); return this; } setKeyManagementParameters(parameters) { this._flattened.setKeyManagementParameters(parameters); return this; } async encrypt(key, options) { const jwe = await this._flattened.encrypt(key, options); return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.'); } } jose-4.11.4/dist/node/esm/jwe/flattened/000077500000000000000000000000001437043056600177605ustar00rootroot00000000000000jose-4.11.4/dist/node/esm/jwe/flattened/decrypt.js000066400000000000000000000133721437043056600217760ustar00rootroot00000000000000import { decode as base64url } from '../../runtime/base64url.js'; import decrypt from '../../runtime/decrypt.js'; import { inflate } from '../../runtime/zlib.js'; import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js'; import isDisjoint from '../../lib/is_disjoint.js'; import isObject from '../../lib/is_object.js'; import decryptKeyManagement from '../../lib/decrypt_key_management.js'; import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; import generateCek from '../../lib/cek.js'; import validateCrit from '../../lib/validate_crit.js'; import validateAlgorithms from '../../lib/validate_algorithms.js'; export async function flattenedDecrypt(jwe, key, options) { var _a; if (!isObject(jwe)) { throw new JWEInvalid('Flattened JWE must be an object'); } if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) { throw new JWEInvalid('JOSE Header missing'); } if (typeof jwe.iv !== 'string') { throw new JWEInvalid('JWE Initialization Vector missing or incorrect type'); } if (typeof jwe.ciphertext !== 'string') { throw new JWEInvalid('JWE Ciphertext missing or incorrect type'); } if (typeof jwe.tag !== 'string') { throw new JWEInvalid('JWE Authentication Tag missing or incorrect type'); } if (jwe.protected !== undefined && typeof jwe.protected !== 'string') { throw new JWEInvalid('JWE Protected Header incorrect type'); } if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') { throw new JWEInvalid('JWE Encrypted Key incorrect type'); } if (jwe.aad !== undefined && typeof jwe.aad !== 'string') { throw new JWEInvalid('JWE AAD incorrect type'); } if (jwe.header !== undefined && !isObject(jwe.header)) { throw new JWEInvalid('JWE Shared Unprotected Header incorrect type'); } if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) { throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type'); } let parsedProt; if (jwe.protected) { try { const protectedHeader = base64url(jwe.protected); parsedProt = JSON.parse(decoder.decode(protectedHeader)); } catch { throw new JWEInvalid('JWE Protected Header is invalid'); } } if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) { throw new JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint'); } const joseHeader = { ...parsedProt, ...jwe.header, ...jwe.unprotected, }; validateCrit(JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader); if (joseHeader.zip !== undefined) { if (!parsedProt || !parsedProt.zip) { throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); } if (joseHeader.zip !== 'DEF') { throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value'); } } const { alg, enc } = joseHeader; if (typeof alg !== 'string' || !alg) { throw new JWEInvalid('missing JWE Algorithm (alg) in JWE Header'); } if (typeof enc !== 'string' || !enc) { throw new JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header'); } const keyManagementAlgorithms = options && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms); const contentEncryptionAlgorithms = options && validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms); if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) { throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed'); } if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed'); } let encryptedKey; if (jwe.encrypted_key !== undefined) { encryptedKey = base64url(jwe.encrypted_key); } let resolvedKey = false; if (typeof key === 'function') { key = await key(parsedProt, jwe); resolvedKey = true; } let cek; try { cek = await decryptKeyManagement(alg, key, encryptedKey, joseHeader, options); } catch (err) { if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { throw err; } cek = generateCek(enc); } const iv = base64url(jwe.iv); const tag = base64url(jwe.tag); const protectedHeader = encoder.encode((_a = jwe.protected) !== null && _a !== void 0 ? _a : ''); let additionalData; if (jwe.aad !== undefined) { additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(jwe.aad)); } else { additionalData = protectedHeader; } let plaintext = await decrypt(enc, cek, base64url(jwe.ciphertext), iv, tag, additionalData); if (joseHeader.zip === 'DEF') { plaintext = await ((options === null || options === void 0 ? void 0 : options.inflateRaw) || inflate)(plaintext); } const result = { plaintext }; if (jwe.protected !== undefined) { result.protectedHeader = parsedProt; } if (jwe.aad !== undefined) { result.additionalAuthenticatedData = base64url(jwe.aad); } if (jwe.unprotected !== undefined) { result.sharedUnprotectedHeader = jwe.unprotected; } if (jwe.header !== undefined) { result.unprotectedHeader = jwe.header; } if (resolvedKey) { return { ...result, key }; } return result; } jose-4.11.4/dist/node/esm/jwe/flattened/encrypt.js000066400000000000000000000156341437043056600220130ustar00rootroot00000000000000import { encode as base64url } from '../../runtime/base64url.js'; import encrypt from '../../runtime/encrypt.js'; import { deflate } from '../../runtime/zlib.js'; import generateIv from '../../lib/iv.js'; import encryptKeyManagement from '../../lib/encrypt_key_management.js'; import { JOSENotSupported, JWEInvalid } from '../../util/errors.js'; import isDisjoint from '../../lib/is_disjoint.js'; import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; import validateCrit from '../../lib/validate_crit.js'; export const unprotected = Symbol(); export class FlattenedEncrypt { constructor(plaintext) { if (!(plaintext instanceof Uint8Array)) { throw new TypeError('plaintext must be an instance of Uint8Array'); } this._plaintext = plaintext; } setKeyManagementParameters(parameters) { if (this._keyManagementParameters) { throw new TypeError('setKeyManagementParameters can only be called once'); } this._keyManagementParameters = parameters; return this; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once'); } this._protectedHeader = protectedHeader; return this; } setSharedUnprotectedHeader(sharedUnprotectedHeader) { if (this._sharedUnprotectedHeader) { throw new TypeError('setSharedUnprotectedHeader can only be called once'); } this._sharedUnprotectedHeader = sharedUnprotectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once'); } this._unprotectedHeader = unprotectedHeader; return this; } setAdditionalAuthenticatedData(aad) { this._aad = aad; return this; } setContentEncryptionKey(cek) { if (this._cek) { throw new TypeError('setContentEncryptionKey can only be called once'); } this._cek = cek; return this; } setInitializationVector(iv) { if (this._iv) { throw new TypeError('setInitializationVector can only be called once'); } this._iv = iv; return this; } async encrypt(key, options) { if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { throw new JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()'); } if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) { throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...this._sharedUnprotectedHeader, }; validateCrit(JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader); if (joseHeader.zip !== undefined) { if (!this._protectedHeader || !this._protectedHeader.zip) { throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); } if (joseHeader.zip !== 'DEF') { throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value'); } } const { alg, enc } = joseHeader; if (typeof alg !== 'string' || !alg) { throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); } if (typeof enc !== 'string' || !enc) { throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); } let encryptedKey; if (alg === 'dir') { if (this._cek) { throw new TypeError('setContentEncryptionKey cannot be called when using Direct Encryption'); } } else if (alg === 'ECDH-ES') { if (this._cek) { throw new TypeError('setContentEncryptionKey cannot be called when using Direct Key Agreement'); } } let cek; { let parameters; ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, key, this._cek, this._keyManagementParameters)); if (parameters) { if (options && unprotected in options) { if (!this._unprotectedHeader) { this.setUnprotectedHeader(parameters); } else { this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters }; } } else { if (!this._protectedHeader) { this.setProtectedHeader(parameters); } else { this._protectedHeader = { ...this._protectedHeader, ...parameters }; } } } } this._iv || (this._iv = generateIv(enc)); let additionalData; let protectedHeader; let aadMember; if (this._protectedHeader) { protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))); } else { protectedHeader = encoder.encode(''); } if (this._aad) { aadMember = base64url(this._aad); additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember)); } else { additionalData = protectedHeader; } let ciphertext; let tag; if (joseHeader.zip === 'DEF') { const deflated = await ((options === null || options === void 0 ? void 0 : options.deflateRaw) || deflate)(this._plaintext); ({ ciphertext, tag } = await encrypt(enc, deflated, cek, this._iv, additionalData)); } else { ; ({ ciphertext, tag } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData)); } const jwe = { ciphertext: base64url(ciphertext), iv: base64url(this._iv), tag: base64url(tag), }; if (encryptedKey) { jwe.encrypted_key = base64url(encryptedKey); } if (aadMember) { jwe.aad = aadMember; } if (this._protectedHeader) { jwe.protected = decoder.decode(protectedHeader); } if (this._sharedUnprotectedHeader) { jwe.unprotected = this._sharedUnprotectedHeader; } if (this._unprotectedHeader) { jwe.header = this._unprotectedHeader; } return jwe; } } jose-4.11.4/dist/node/esm/jwe/general/000077500000000000000000000000001437043056600174275ustar00rootroot00000000000000jose-4.11.4/dist/node/esm/jwe/general/decrypt.js000066400000000000000000000021451437043056600214410ustar00rootroot00000000000000import { flattenedDecrypt } from '../flattened/decrypt.js'; import { JWEDecryptionFailed, JWEInvalid } from '../../util/errors.js'; import isObject from '../../lib/is_object.js'; export async function generalDecrypt(jwe, key, options) { if (!isObject(jwe)) { throw new JWEInvalid('General JWE must be an object'); } if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) { throw new JWEInvalid('JWE Recipients missing or incorrect type'); } if (!jwe.recipients.length) { throw new JWEInvalid('JWE Recipients has no members'); } for (const recipient of jwe.recipients) { try { return await flattenedDecrypt({ aad: jwe.aad, ciphertext: jwe.ciphertext, encrypted_key: recipient.encrypted_key, header: recipient.header, iv: jwe.iv, protected: jwe.protected, tag: jwe.tag, unprotected: jwe.unprotected, }, key, options); } catch { } } throw new JWEDecryptionFailed(); } jose-4.11.4/dist/node/esm/jwe/general/encrypt.js000066400000000000000000000172051437043056600214560ustar00rootroot00000000000000import { FlattenedEncrypt, unprotected } from '../flattened/encrypt.js'; import { JWEInvalid } from '../../util/errors.js'; import generateCek from '../../lib/cek.js'; import isDisjoint from '../../lib/is_disjoint.js'; import encryptKeyManagement from '../../lib/encrypt_key_management.js'; import { encode as base64url } from '../../runtime/base64url.js'; import validateCrit from '../../lib/validate_crit.js'; class IndividualRecipient { constructor(enc, key, options) { this.parent = enc; this.key = key; this.options = options; } setUnprotectedHeader(unprotectedHeader) { if (this.unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once'); } this.unprotectedHeader = unprotectedHeader; return this; } addRecipient(...args) { return this.parent.addRecipient(...args); } encrypt(...args) { return this.parent.encrypt(...args); } done() { return this.parent; } } export class GeneralEncrypt { constructor(plaintext) { this._recipients = []; this._plaintext = plaintext; } addRecipient(key, options) { const recipient = new IndividualRecipient(this, key, { crit: options === null || options === void 0 ? void 0 : options.crit }); this._recipients.push(recipient); return recipient; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once'); } this._protectedHeader = protectedHeader; return this; } setSharedUnprotectedHeader(sharedUnprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError('setSharedUnprotectedHeader can only be called once'); } this._unprotectedHeader = sharedUnprotectedHeader; return this; } setAdditionalAuthenticatedData(aad) { this._aad = aad; return this; } async encrypt(options) { var _a, _b, _c; if (!this._recipients.length) { throw new JWEInvalid('at least one recipient must be added'); } options = { deflateRaw: options === null || options === void 0 ? void 0 : options.deflateRaw }; if (this._recipients.length === 1) { const [recipient] = this._recipients; const flattened = await new FlattenedEncrypt(this._plaintext) .setAdditionalAuthenticatedData(this._aad) .setProtectedHeader(this._protectedHeader) .setSharedUnprotectedHeader(this._unprotectedHeader) .setUnprotectedHeader(recipient.unprotectedHeader) .encrypt(recipient.key, { ...recipient.options, ...options }); let jwe = { ciphertext: flattened.ciphertext, iv: flattened.iv, recipients: [{}], tag: flattened.tag, }; if (flattened.aad) jwe.aad = flattened.aad; if (flattened.protected) jwe.protected = flattened.protected; if (flattened.unprotected) jwe.unprotected = flattened.unprotected; if (flattened.encrypted_key) jwe.recipients[0].encrypted_key = flattened.encrypted_key; if (flattened.header) jwe.recipients[0].header = flattened.header; return jwe; } let enc; for (let i = 0; i < this._recipients.length; i++) { const recipient = this._recipients[i]; if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) { throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint'); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...recipient.unprotectedHeader, }; const { alg } = joseHeader; if (typeof alg !== 'string' || !alg) { throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid'); } if (alg === 'dir' || alg === 'ECDH-ES') { throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient'); } if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) { throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid'); } if (!enc) { enc = joseHeader.enc; } else if (enc !== joseHeader.enc) { throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients'); } validateCrit(JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader); if (joseHeader.zip !== undefined) { if (!this._protectedHeader || !this._protectedHeader.zip) { throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected'); } } } const cek = generateCek(enc); let jwe = { ciphertext: '', iv: '', recipients: [], tag: '', }; for (let i = 0; i < this._recipients.length; i++) { const recipient = this._recipients[i]; const target = {}; jwe.recipients.push(target); const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...recipient.unprotectedHeader, }; const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined; if (i === 0) { const flattened = await new FlattenedEncrypt(this._plaintext) .setAdditionalAuthenticatedData(this._aad) .setContentEncryptionKey(cek) .setProtectedHeader(this._protectedHeader) .setSharedUnprotectedHeader(this._unprotectedHeader) .setUnprotectedHeader(recipient.unprotectedHeader) .setKeyManagementParameters({ p2c }) .encrypt(recipient.key, { ...recipient.options, ...options, [unprotected]: true, }); jwe.ciphertext = flattened.ciphertext; jwe.iv = flattened.iv; jwe.tag = flattened.tag; if (flattened.aad) jwe.aad = flattened.aad; if (flattened.protected) jwe.protected = flattened.protected; if (flattened.unprotected) jwe.unprotected = flattened.unprotected; target.encrypted_key = flattened.encrypted_key; if (flattened.header) target.header = flattened.header; continue; } const { encryptedKey, parameters } = await encryptKeyManagement(((_a = recipient.unprotectedHeader) === null || _a === void 0 ? void 0 : _a.alg) || ((_b = this._protectedHeader) === null || _b === void 0 ? void 0 : _b.alg) || ((_c = this._unprotectedHeader) === null || _c === void 0 ? void 0 : _c.alg), enc, recipient.key, cek, { p2c }); target.encrypted_key = base64url(encryptedKey); if (recipient.unprotectedHeader || parameters) target.header = { ...recipient.unprotectedHeader, ...parameters }; } return jwe; } } jose-4.11.4/dist/node/esm/jwk/000077500000000000000000000000001437043056600160205ustar00rootroot00000000000000jose-4.11.4/dist/node/esm/jwk/embedded.js000066400000000000000000000012561437043056600201130ustar00rootroot00000000000000import { importJWK } from '../key/import.js'; import isObject from '../lib/is_object.js'; import { JWSInvalid } from '../util/errors.js'; export async function EmbeddedJWK(protectedHeader, token) { const joseHeader = { ...protectedHeader, ...token.header, }; if (!isObject(joseHeader.jwk)) { throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object'); } const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg, true); if (key instanceof Uint8Array || key.type !== 'public') { throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key'); } return key; } jose-4.11.4/dist/node/esm/jwk/thumbprint.js000066400000000000000000000045651437043056600205640ustar00rootroot00000000000000import digest from '../runtime/digest.js'; import { encode as base64url } from '../runtime/base64url.js'; import { JOSENotSupported, JWKInvalid } from '../util/errors.js'; import { encoder } from '../lib/buffer_utils.js'; import isObject from '../lib/is_object.js'; const check = (value, description) => { if (typeof value !== 'string' || !value) { throw new JWKInvalid(`${description} missing or invalid`); } }; export async function calculateJwkThumbprint(jwk, digestAlgorithm) { if (!isObject(jwk)) { throw new TypeError('JWK must be an object'); } digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256'); if (digestAlgorithm !== 'sha256' && digestAlgorithm !== 'sha384' && digestAlgorithm !== 'sha512') { throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"'); } let components; switch (jwk.kty) { case 'EC': check(jwk.crv, '"crv" (Curve) Parameter'); check(jwk.x, '"x" (X Coordinate) Parameter'); check(jwk.y, '"y" (Y Coordinate) Parameter'); components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }; break; case 'OKP': check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter'); check(jwk.x, '"x" (Public Key) Parameter'); components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }; break; case 'RSA': check(jwk.e, '"e" (Exponent) Parameter'); check(jwk.n, '"n" (Modulus) Parameter'); components = { e: jwk.e, kty: jwk.kty, n: jwk.n }; break; case 'oct': check(jwk.k, '"k" (Key Value) Parameter'); components = { k: jwk.k, kty: jwk.kty }; break; default: throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported'); } const data = encoder.encode(JSON.stringify(components)); return base64url(await digest(digestAlgorithm, data)); } export async function calculateJwkThumbprintUri(jwk, digestAlgorithm) { digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256'); const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm); return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`; } jose-4.11.4/dist/node/esm/jwks/000077500000000000000000000000001437043056600162035ustar00rootroot00000000000000jose-4.11.4/dist/node/esm/jwks/local.js000066400000000000000000000066361437043056600176460ustar00rootroot00000000000000import { importJWK } from '../key/import.js'; import { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js'; import isObject from '../lib/is_object.js'; function getKtyFromAlg(alg) { switch (typeof alg === 'string' && alg.slice(0, 2)) { case 'RS': case 'PS': return 'RSA'; case 'ES': return 'EC'; case 'Ed': return 'OKP'; default: throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set'); } } export function isJWKSLike(jwks) { return (jwks && typeof jwks === 'object' && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike)); } function isJWKLike(key) { return isObject(key); } function clone(obj) { if (typeof structuredClone === 'function') { return structuredClone(obj); } return JSON.parse(JSON.stringify(obj)); } export class LocalJWKSet { constructor(jwks) { this._cached = new WeakMap(); if (!isJWKSLike(jwks)) { throw new JWKSInvalid('JSON Web Key Set malformed'); } this._jwks = clone(jwks); } async getKey(protectedHeader, token) { const { alg, kid } = { ...protectedHeader, ...token.header }; const kty = getKtyFromAlg(alg); const candidates = this._jwks.keys.filter((jwk) => { let candidate = kty === jwk.kty; if (candidate && typeof kid === 'string') { candidate = kid === jwk.kid; } if (candidate && typeof jwk.alg === 'string') { candidate = alg === jwk.alg; } if (candidate && typeof jwk.use === 'string') { candidate = jwk.use === 'sig'; } if (candidate && Array.isArray(jwk.key_ops)) { candidate = jwk.key_ops.includes('verify'); } if (candidate && alg === 'EdDSA') { candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448'; } if (candidate) { switch (alg) { case 'ES256': candidate = jwk.crv === 'P-256'; break; case 'ES256K': candidate = jwk.crv === 'secp256k1'; break; case 'ES384': candidate = jwk.crv === 'P-384'; break; case 'ES512': candidate = jwk.crv === 'P-521'; break; } } return candidate; }); const { 0: jwk, length } = candidates; if (length === 0) { throw new JWKSNoMatchingKey(); } else if (length !== 1) { throw new JWKSMultipleMatchingKeys(); } const cached = this._cached.get(jwk) || this._cached.set(jwk, {}).get(jwk); if (cached[alg] === undefined) { const keyObject = await importJWK({ ...jwk, ext: true }, alg); if (keyObject instanceof Uint8Array || keyObject.type !== 'public') { throw new JWKSInvalid('JSON Web Key Set members must be public keys'); } cached[alg] = keyObject; } return cached[alg]; } } export function createLocalJWKSet(jwks) { return LocalJWKSet.prototype.getKey.bind(new LocalJWKSet(jwks)); } jose-4.11.4/dist/node/esm/jwks/remote.js000066400000000000000000000065371437043056600200470ustar00rootroot00000000000000import fetchJwks from '../runtime/fetch_jwks.js'; import { isCloudflareWorkers } from '../runtime/env.js'; import { JWKSInvalid, JWKSNoMatchingKey } from '../util/errors.js'; import { isJWKSLike, LocalJWKSet } from './local.js'; class RemoteJWKSet extends LocalJWKSet { constructor(url, options) { super({ keys: [] }); this._jwks = undefined; if (!(url instanceof URL)) { throw new TypeError('url must be an instance of URL'); } this._url = new URL(url.href); this._options = { agent: options === null || options === void 0 ? void 0 : options.agent, headers: options === null || options === void 0 ? void 0 : options.headers }; this._timeoutDuration = typeof (options === null || options === void 0 ? void 0 : options.timeoutDuration) === 'number' ? options === null || options === void 0 ? void 0 : options.timeoutDuration : 5000; this._cooldownDuration = typeof (options === null || options === void 0 ? void 0 : options.cooldownDuration) === 'number' ? options === null || options === void 0 ? void 0 : options.cooldownDuration : 30000; this._cacheMaxAge = typeof (options === null || options === void 0 ? void 0 : options.cacheMaxAge) === 'number' ? options === null || options === void 0 ? void 0 : options.cacheMaxAge : 600000; } coolingDown() { return typeof this._jwksTimestamp === 'number' ? Date.now() < this._jwksTimestamp + this._cooldownDuration : false; } fresh() { return typeof this._jwksTimestamp === 'number' ? Date.now() < this._jwksTimestamp + this._cacheMaxAge : false; } async getKey(protectedHeader, token) { if (!this._jwks || !this.fresh()) { await this.reload(); } try { return await super.getKey(protectedHeader, token); } catch (err) { if (err instanceof JWKSNoMatchingKey) { if (this.coolingDown() === false) { await this.reload(); return super.getKey(protectedHeader, token); } } throw err; } } async reload() { if (this._pendingFetch && isCloudflareWorkers()) { return new Promise((resolve) => { const isDone = () => { if (this._pendingFetch === undefined) { resolve(); } else { setTimeout(isDone, 5); } }; isDone(); }); } if (!this._pendingFetch) { this._pendingFetch = fetchJwks(this._url, this._timeoutDuration, this._options) .then((json) => { if (!isJWKSLike(json)) { throw new JWKSInvalid('JSON Web Key Set malformed'); } this._jwks = { keys: json.keys }; this._jwksTimestamp = Date.now(); this._pendingFetch = undefined; }) .catch((err) => { this._pendingFetch = undefined; throw err; }); } await this._pendingFetch; } } export function createRemoteJWKSet(url, options) { return RemoteJWKSet.prototype.getKey.bind(new RemoteJWKSet(url, options)); } jose-4.11.4/dist/node/esm/jws/000077500000000000000000000000001437043056600160305ustar00rootroot00000000000000jose-4.11.4/dist/node/esm/jws/compact/000077500000000000000000000000001437043056600174565ustar00rootroot00000000000000jose-4.11.4/dist/node/esm/jws/compact/sign.js000066400000000000000000000011431437043056600207530ustar00rootroot00000000000000import { FlattenedSign } from '../flattened/sign.js'; export class CompactSign { constructor(payload) { this._flattened = new FlattenedSign(payload); } setProtectedHeader(protectedHeader) { this._flattened.setProtectedHeader(protectedHeader); return this; } async sign(key, options) { const jws = await this._flattened.sign(key, options); if (jws.payload === undefined) { throw new TypeError('use the flattened module for creating JWS with b64: false'); } return `${jws.protected}.${jws.payload}.${jws.signature}`; } } jose-4.11.4/dist/node/esm/jws/compact/verify.js000066400000000000000000000016021437043056600213170ustar00rootroot00000000000000import { flattenedVerify } from '../flattened/verify.js'; import { JWSInvalid } from '../../util/errors.js'; import { decoder } from '../../lib/buffer_utils.js'; export async function compactVerify(jws, key, options) { if (jws instanceof Uint8Array) { jws = decoder.decode(jws); } if (typeof jws !== 'string') { throw new JWSInvalid('Compact JWS must be a string or Uint8Array'); } const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.'); if (length !== 3) { throw new JWSInvalid('Invalid Compact JWS'); } const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options); const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; if (typeof key === 'function') { return { ...result, key: verified.key }; } return result; } jose-4.11.4/dist/node/esm/jws/flattened/000077500000000000000000000000001437043056600177765ustar00rootroot00000000000000jose-4.11.4/dist/node/esm/jws/flattened/sign.js000066400000000000000000000063101437043056600212740ustar00rootroot00000000000000import { encode as base64url } from '../../runtime/base64url.js'; import sign from '../../runtime/sign.js'; import isDisjoint from '../../lib/is_disjoint.js'; import { JWSInvalid } from '../../util/errors.js'; import { encoder, decoder, concat } from '../../lib/buffer_utils.js'; import checkKeyType from '../../lib/check_key_type.js'; import validateCrit from '../../lib/validate_crit.js'; export class FlattenedSign { constructor(payload) { if (!(payload instanceof Uint8Array)) { throw new TypeError('payload must be an instance of Uint8Array'); } this._payload = payload; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once'); } this._protectedHeader = protectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once'); } this._unprotectedHeader = unprotectedHeader; return this; } async sign(key, options) { if (!this._protectedHeader && !this._unprotectedHeader) { throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()'); } if (!isDisjoint(this._protectedHeader, this._unprotectedHeader)) { throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, }; const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader); let b64 = true; if (extensions.has('b64')) { b64 = this._protectedHeader.b64; if (typeof b64 !== 'boolean') { throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); } } const { alg } = joseHeader; if (typeof alg !== 'string' || !alg) { throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); } checkKeyType(alg, key, 'sign'); let payload = this._payload; if (b64) { payload = encoder.encode(base64url(payload)); } let protectedHeader; if (this._protectedHeader) { protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))); } else { protectedHeader = encoder.encode(''); } const data = concat(protectedHeader, encoder.encode('.'), payload); const signature = await sign(alg, key, data); const jws = { signature: base64url(signature), payload: '', }; if (b64) { jws.payload = decoder.decode(payload); } if (this._unprotectedHeader) { jws.header = this._unprotectedHeader; } if (this._protectedHeader) { jws.protected = decoder.decode(protectedHeader); } return jws; } } jose-4.11.4/dist/node/esm/jws/flattened/verify.js000066400000000000000000000101311437043056600216340ustar00rootroot00000000000000import { decode as base64url } from '../../runtime/base64url.js'; import verify from '../../runtime/verify.js'; import { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js'; import { concat, encoder, decoder } from '../../lib/buffer_utils.js'; import isDisjoint from '../../lib/is_disjoint.js'; import isObject from '../../lib/is_object.js'; import checkKeyType from '../../lib/check_key_type.js'; import validateCrit from '../../lib/validate_crit.js'; import validateAlgorithms from '../../lib/validate_algorithms.js'; export async function flattenedVerify(jws, key, options) { var _a; if (!isObject(jws)) { throw new JWSInvalid('Flattened JWS must be an object'); } if (jws.protected === undefined && jws.header === undefined) { throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); } if (jws.protected !== undefined && typeof jws.protected !== 'string') { throw new JWSInvalid('JWS Protected Header incorrect type'); } if (jws.payload === undefined) { throw new JWSInvalid('JWS Payload missing'); } if (typeof jws.signature !== 'string') { throw new JWSInvalid('JWS Signature missing or incorrect type'); } if (jws.header !== undefined && !isObject(jws.header)) { throw new JWSInvalid('JWS Unprotected Header incorrect type'); } let parsedProt = {}; if (jws.protected) { try { const protectedHeader = base64url(jws.protected); parsedProt = JSON.parse(decoder.decode(protectedHeader)); } catch { throw new JWSInvalid('JWS Protected Header is invalid'); } } if (!isDisjoint(parsedProt, jws.header)) { throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint'); } const joseHeader = { ...parsedProt, ...jws.header, }; const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader); let b64 = true; if (extensions.has('b64')) { b64 = parsedProt.b64; if (typeof b64 !== 'boolean') { throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); } } const { alg } = joseHeader; if (typeof alg !== 'string' || !alg) { throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); } const algorithms = options && validateAlgorithms('algorithms', options.algorithms); if (algorithms && !algorithms.has(alg)) { throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed'); } if (b64) { if (typeof jws.payload !== 'string') { throw new JWSInvalid('JWS Payload must be a string'); } } else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) { throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance'); } let resolvedKey = false; if (typeof key === 'function') { key = await key(parsedProt, jws); resolvedKey = true; } checkKeyType(alg, key, 'verify'); const data = concat(encoder.encode((_a = jws.protected) !== null && _a !== void 0 ? _a : ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload); const signature = base64url(jws.signature); const verified = await verify(alg, key, signature, data); if (!verified) { throw new JWSSignatureVerificationFailed(); } let payload; if (b64) { payload = base64url(jws.payload); } else if (typeof jws.payload === 'string') { payload = encoder.encode(jws.payload); } else { payload = jws.payload; } const result = { payload }; if (jws.protected !== undefined) { result.protectedHeader = parsedProt; } if (jws.header !== undefined) { result.unprotectedHeader = jws.header; } if (resolvedKey) { return { ...result, key }; } return result; } jose-4.11.4/dist/node/esm/jws/general/000077500000000000000000000000001437043056600174455ustar00rootroot00000000000000jose-4.11.4/dist/node/esm/jws/general/sign.js000066400000000000000000000042541437043056600207500ustar00rootroot00000000000000import { FlattenedSign } from '../flattened/sign.js'; import { JWSInvalid } from '../../util/errors.js'; class IndividualSignature { constructor(sig, key, options) { this.parent = sig; this.key = key; this.options = options; } setProtectedHeader(protectedHeader) { if (this.protectedHeader) { throw new TypeError('setProtectedHeader can only be called once'); } this.protectedHeader = protectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this.unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once'); } this.unprotectedHeader = unprotectedHeader; return this; } addSignature(...args) { return this.parent.addSignature(...args); } sign(...args) { return this.parent.sign(...args); } done() { return this.parent; } } export class GeneralSign { constructor(payload) { this._signatures = []; this._payload = payload; } addSignature(key, options) { const signature = new IndividualSignature(this, key, options); this._signatures.push(signature); return signature; } async sign() { if (!this._signatures.length) { throw new JWSInvalid('at least one signature must be added'); } const jws = { signatures: [], payload: '', }; for (let i = 0; i < this._signatures.length; i++) { const signature = this._signatures[i]; const flattened = new FlattenedSign(this._payload); flattened.setProtectedHeader(signature.protectedHeader); flattened.setUnprotectedHeader(signature.unprotectedHeader); const { payload, ...rest } = await flattened.sign(signature.key, signature.options); if (i === 0) { jws.payload = payload; } else if (jws.payload !== payload) { throw new JWSInvalid('inconsistent use of JWS Unencoded Payload Option (RFC7797)'); } jws.signatures.push(rest); } return jws; } } jose-4.11.4/dist/node/esm/jws/general/verify.js000066400000000000000000000016021437043056600213060ustar00rootroot00000000000000import { flattenedVerify } from '../flattened/verify.js'; import { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js'; import isObject from '../../lib/is_object.js'; export async function generalVerify(jws, key, options) { if (!isObject(jws)) { throw new JWSInvalid('General JWS must be an object'); } if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) { throw new JWSInvalid('JWS Signatures missing or incorrect type'); } for (const signature of jws.signatures) { try { return await flattenedVerify({ header: signature.header, payload: jws.payload, protected: signature.protected, signature: signature.signature, }, key, options); } catch { } } throw new JWSSignatureVerificationFailed(); } jose-4.11.4/dist/node/esm/jwt/000077500000000000000000000000001437043056600160315ustar00rootroot00000000000000jose-4.11.4/dist/node/esm/jwt/decrypt.js000066400000000000000000000023301437043056600200370ustar00rootroot00000000000000import { compactDecrypt } from '../jwe/compact/decrypt.js'; import jwtPayload from '../lib/jwt_claims_set.js'; import { JWTClaimValidationFailed } from '../util/errors.js'; export async function jwtDecrypt(jwt, key, options) { const decrypted = await compactDecrypt(jwt, key, options); const payload = jwtPayload(decrypted.protectedHeader, decrypted.plaintext, options); const { protectedHeader } = decrypted; if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) { throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', 'iss', 'mismatch'); } if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) { throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', 'sub', 'mismatch'); } if (protectedHeader.aud !== undefined && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) { throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', 'aud', 'mismatch'); } const result = { payload, protectedHeader }; if (typeof key === 'function') { return { ...result, key: decrypted.key }; } return result; } jose-4.11.4/dist/node/esm/jwt/encrypt.js000066400000000000000000000045431437043056600200610ustar00rootroot00000000000000import { CompactEncrypt } from '../jwe/compact/encrypt.js'; import { encoder } from '../lib/buffer_utils.js'; import { ProduceJWT } from './produce.js'; export class EncryptJWT extends ProduceJWT { setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once'); } this._protectedHeader = protectedHeader; return this; } setKeyManagementParameters(parameters) { if (this._keyManagementParameters) { throw new TypeError('setKeyManagementParameters can only be called once'); } this._keyManagementParameters = parameters; return this; } setContentEncryptionKey(cek) { if (this._cek) { throw new TypeError('setContentEncryptionKey can only be called once'); } this._cek = cek; return this; } setInitializationVector(iv) { if (this._iv) { throw new TypeError('setInitializationVector can only be called once'); } this._iv = iv; return this; } replicateIssuerAsHeader() { this._replicateIssuerAsHeader = true; return this; } replicateSubjectAsHeader() { this._replicateSubjectAsHeader = true; return this; } replicateAudienceAsHeader() { this._replicateAudienceAsHeader = true; return this; } async encrypt(key, options) { const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload))); if (this._replicateIssuerAsHeader) { this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss }; } if (this._replicateSubjectAsHeader) { this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub }; } if (this._replicateAudienceAsHeader) { this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud }; } enc.setProtectedHeader(this._protectedHeader); if (this._iv) { enc.setInitializationVector(this._iv); } if (this._cek) { enc.setContentEncryptionKey(this._cek); } if (this._keyManagementParameters) { enc.setKeyManagementParameters(this._keyManagementParameters); } return enc.encrypt(key, options); } } jose-4.11.4/dist/node/esm/jwt/produce.js000066400000000000000000000030751437043056600200350ustar00rootroot00000000000000import epoch from '../lib/epoch.js'; import isObject from '../lib/is_object.js'; import secs from '../lib/secs.js'; export class ProduceJWT { constructor(payload) { if (!isObject(payload)) { throw new TypeError('JWT Claims Set MUST be an object'); } this._payload = payload; } setIssuer(issuer) { this._payload = { ...this._payload, iss: issuer }; return this; } setSubject(subject) { this._payload = { ...this._payload, sub: subject }; return this; } setAudience(audience) { this._payload = { ...this._payload, aud: audience }; return this; } setJti(jwtId) { this._payload = { ...this._payload, jti: jwtId }; return this; } setNotBefore(input) { if (typeof input === 'number') { this._payload = { ...this._payload, nbf: input }; } else { this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) }; } return this; } setExpirationTime(input) { if (typeof input === 'number') { this._payload = { ...this._payload, exp: input }; } else { this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) }; } return this; } setIssuedAt(input) { if (typeof input === 'undefined') { this._payload = { ...this._payload, iat: epoch(new Date()) }; } else { this._payload = { ...this._payload, iat: input }; } return this; } } jose-4.11.4/dist/node/esm/jwt/sign.js000066400000000000000000000015641437043056600173350ustar00rootroot00000000000000import { CompactSign } from '../jws/compact/sign.js'; import { JWTInvalid } from '../util/errors.js'; import { encoder } from '../lib/buffer_utils.js'; import { ProduceJWT } from './produce.js'; export class SignJWT extends ProduceJWT { setProtectedHeader(protectedHeader) { this._protectedHeader = protectedHeader; return this; } async sign(key, options) { var _a; const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload))); sig.setProtectedHeader(this._protectedHeader); if (Array.isArray((_a = this._protectedHeader) === null || _a === void 0 ? void 0 : _a.crit) && this._protectedHeader.crit.includes('b64') && this._protectedHeader.b64 === false) { throw new JWTInvalid('JWTs MUST NOT use unencoded payload'); } return sig.sign(key, options); } } jose-4.11.4/dist/node/esm/jwt/unsecured.js000066400000000000000000000023771437043056600203750ustar00rootroot00000000000000import * as base64url from '../runtime/base64url.js'; import { decoder } from '../lib/buffer_utils.js'; import { JWTInvalid } from '../util/errors.js'; import jwtPayload from '../lib/jwt_claims_set.js'; import { ProduceJWT } from './produce.js'; export class UnsecuredJWT extends ProduceJWT { encode() { const header = base64url.encode(JSON.stringify({ alg: 'none' })); const payload = base64url.encode(JSON.stringify(this._payload)); return `${header}.${payload}.`; } static decode(jwt, options) { if (typeof jwt !== 'string') { throw new JWTInvalid('Unsecured JWT must be a string'); } const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.'); if (length !== 3 || signature !== '') { throw new JWTInvalid('Invalid Unsecured JWT'); } let header; try { header = JSON.parse(decoder.decode(base64url.decode(encodedHeader))); if (header.alg !== 'none') throw new Error(); } catch { throw new JWTInvalid('Invalid Unsecured JWT'); } const payload = jwtPayload(header, base64url.decode(encodedPayload), options); return { payload, header }; } } jose-4.11.4/dist/node/esm/jwt/verify.js000066400000000000000000000014131437043056600176720ustar00rootroot00000000000000import { compactVerify } from '../jws/compact/verify.js'; import jwtPayload from '../lib/jwt_claims_set.js'; import { JWTInvalid } from '../util/errors.js'; export async function jwtVerify(jwt, key, options) { var _a; const verified = await compactVerify(jwt, key, options); if (((_a = verified.protectedHeader.crit) === null || _a === void 0 ? void 0 : _a.includes('b64')) && verified.protectedHeader.b64 === false) { throw new JWTInvalid('JWTs MUST NOT use unencoded payload'); } const payload = jwtPayload(verified.protectedHeader, verified.payload, options); const result = { payload, protectedHeader: verified.protectedHeader }; if (typeof key === 'function') { return { ...result, key: verified.key }; } return result; } jose-4.11.4/dist/node/esm/key/000077500000000000000000000000001437043056600160155ustar00rootroot00000000000000jose-4.11.4/dist/node/esm/key/export.js000066400000000000000000000006021437043056600176720ustar00rootroot00000000000000import { toSPKI as exportPublic } from '../runtime/asn1.js'; import { toPKCS8 as exportPrivate } from '../runtime/asn1.js'; import keyToJWK from '../runtime/key_to_jwk.js'; export async function exportSPKI(key) { return exportPublic(key); } export async function exportPKCS8(key) { return exportPrivate(key); } export async function exportJWK(key) { return keyToJWK(key); } jose-4.11.4/dist/node/esm/key/generate_key_pair.js000066400000000000000000000002411437043056600220250ustar00rootroot00000000000000import { generateKeyPair as generate } from '../runtime/generate.js'; export async function generateKeyPair(alg, options) { return generate(alg, options); } jose-4.11.4/dist/node/esm/key/generate_secret.js000066400000000000000000000002371437043056600215140ustar00rootroot00000000000000import { generateSecret as generate } from '../runtime/generate.js'; export async function generateSecret(alg, options) { return generate(alg, options); } jose-4.11.4/dist/node/esm/key/import.js000066400000000000000000000111351437043056600176660ustar00rootroot00000000000000import { decode as decodeBase64URL, encodeBase64, decodeBase64 } from '../runtime/base64url.js'; import { fromSPKI as importPublic } from '../runtime/asn1.js'; import { fromPKCS8 as importPrivate } from '../runtime/asn1.js'; import asKeyObject from '../runtime/jwk_to_key.js'; import { JOSENotSupported } from '../util/errors.js'; import formatPEM from '../lib/format_pem.js'; import isObject from '../lib/is_object.js'; function getElement(seq) { let result = []; let next = 0; while (next < seq.length) { let nextPart = parseElement(seq.subarray(next)); result.push(nextPart); next += nextPart.byteLength; } return result; } function parseElement(bytes) { let position = 0; let tag = bytes[0] & 0x1f; position++; if (tag === 0x1f) { tag = 0; while (bytes[position] >= 0x80) { tag = tag * 128 + bytes[position] - 0x80; position++; } tag = tag * 128 + bytes[position] - 0x80; position++; } let length = 0; if (bytes[position] < 0x80) { length = bytes[position]; position++; } else if (length === 0x80) { length = 0; while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) { if (length > bytes.byteLength) { throw new TypeError('invalid indefinite form length'); } length++; } const byteLength = position + length + 2; return { byteLength, contents: bytes.subarray(position, position + length), raw: bytes.subarray(0, byteLength), }; } else { let numberOfDigits = bytes[position] & 0x7f; position++; length = 0; for (let i = 0; i < numberOfDigits; i++) { length = length * 256 + bytes[position]; position++; } } const byteLength = position + length; return { byteLength, contents: bytes.subarray(position, byteLength), raw: bytes.subarray(0, byteLength), }; } function spkiFromX509(buf) { const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents); return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw); } function getSPKI(x509) { const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, ''); const raw = decodeBase64(pem); return formatPEM(spkiFromX509(raw), 'PUBLIC KEY'); } export async function importSPKI(spki, alg, options) { if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) { throw new TypeError('"spki" must be SPKI formatted string'); } return importPublic(spki, alg, options); } export async function importX509(x509, alg, options) { if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) { throw new TypeError('"x509" must be X.509 formatted string'); } let spki; try { spki = getSPKI(x509); } catch (cause) { throw new TypeError('failed to parse the X.509 certificate', { cause }); } return importPublic(spki, alg, options); } export async function importPKCS8(pkcs8, alg, options) { if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) { throw new TypeError('"pkcs8" must be PKCS#8 formatted string'); } return importPrivate(pkcs8, alg, options); } export async function importJWK(jwk, alg, octAsKeyObject) { var _a; if (!isObject(jwk)) { throw new TypeError('JWK must be an object'); } alg || (alg = jwk.alg); if (typeof alg !== 'string' || !alg) { throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); } switch (jwk.kty) { case 'oct': if (typeof jwk.k !== 'string' || !jwk.k) { throw new TypeError('missing "k" (Key Value) Parameter value'); } octAsKeyObject !== null && octAsKeyObject !== void 0 ? octAsKeyObject : (octAsKeyObject = jwk.ext !== true); if (octAsKeyObject) { return asKeyObject({ ...jwk, alg, ext: (_a = jwk.ext) !== null && _a !== void 0 ? _a : false }); } return decodeBase64URL(jwk.k); case 'RSA': if (jwk.oth !== undefined) { throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); } case 'EC': case 'OKP': return asKeyObject({ ...jwk, alg }); default: throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); } } jose-4.11.4/dist/node/esm/lib/000077500000000000000000000000001437043056600157735ustar00rootroot00000000000000jose-4.11.4/dist/node/esm/lib/aesgcmkw.js000066400000000000000000000012601437043056600201310ustar00rootroot00000000000000import encrypt from '../runtime/encrypt.js'; import decrypt from '../runtime/decrypt.js'; import generateIv from './iv.js'; import { encode as base64url } from '../runtime/base64url.js'; export async function wrap(alg, key, cek, iv) { const jweAlgorithm = alg.slice(0, 7); iv || (iv = generateIv(jweAlgorithm)); const { ciphertext: encryptedKey, tag } = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array(0)); return { encryptedKey, iv: base64url(iv), tag: base64url(tag) }; } export async function unwrap(alg, key, encryptedKey, iv, tag) { const jweAlgorithm = alg.slice(0, 7); return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0)); } jose-4.11.4/dist/node/esm/lib/buffer_utils.js000066400000000000000000000033161437043056600210250ustar00rootroot00000000000000import digest from '../runtime/digest.js'; export const encoder = new TextEncoder(); export const decoder = new TextDecoder(); const MAX_INT32 = 2 ** 32; export function concat(...buffers) { const size = buffers.reduce((acc, { length }) => acc + length, 0); const buf = new Uint8Array(size); let i = 0; buffers.forEach((buffer) => { buf.set(buffer, i); i += buffer.length; }); return buf; } export function p2s(alg, p2sInput) { return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput); } function writeUInt32BE(buf, value, offset) { if (value < 0 || value >= MAX_INT32) { throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`); } buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset); } export function uint64be(value) { const high = Math.floor(value / MAX_INT32); const low = value % MAX_INT32; const buf = new Uint8Array(8); writeUInt32BE(buf, high, 0); writeUInt32BE(buf, low, 4); return buf; } export function uint32be(value) { const buf = new Uint8Array(4); writeUInt32BE(buf, value); return buf; } export function lengthAndInput(input) { return concat(uint32be(input.length), input); } export async function concatKdf(secret, bits, value) { const iterations = Math.ceil((bits >> 3) / 32); const res = new Uint8Array(iterations * 32); for (let iter = 0; iter < iterations; iter++) { const buf = new Uint8Array(4 + secret.length + value.length); buf.set(uint32be(iter + 1)); buf.set(secret, 4); buf.set(value, 4 + secret.length); res.set(await digest('sha256', buf), iter * 32); } return res.slice(0, bits >> 3); } jose-4.11.4/dist/node/esm/lib/cek.js000066400000000000000000000011321437043056600170700ustar00rootroot00000000000000import { JOSENotSupported } from '../util/errors.js'; import random from '../runtime/random.js'; export function bitLength(alg) { switch (alg) { case 'A128GCM': return 128; case 'A192GCM': return 192; case 'A256GCM': case 'A128CBC-HS256': return 256; case 'A192CBC-HS384': return 384; case 'A256CBC-HS512': return 512; default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); } } export default (alg) => random(new Uint8Array(bitLength(alg) >> 3)); jose-4.11.4/dist/node/esm/lib/check_iv_length.js000066400000000000000000000004241437043056600214450ustar00rootroot00000000000000import { JWEInvalid } from '../util/errors.js'; import { bitLength } from './iv.js'; const checkIvLength = (enc, iv) => { if (iv.length << 3 !== bitLength(enc)) { throw new JWEInvalid('Invalid Initialization Vector length'); } }; export default checkIvLength; jose-4.11.4/dist/node/esm/lib/check_key_type.js000066400000000000000000000036151437043056600213240ustar00rootroot00000000000000import { withAlg as invalidKeyInput } from './invalid_key_input.js'; import isKeyLike, { types } from '../runtime/is_key_like.js'; const symmetricTypeCheck = (alg, key) => { if (key instanceof Uint8Array) return; if (!isKeyLike(key)) { throw new TypeError(invalidKeyInput(alg, key, ...types, 'Uint8Array')); } if (key.type !== 'secret') { throw new TypeError(`${types.join(' or ')} instances for symmetric algorithms must be of type "secret"`); } }; const asymmetricTypeCheck = (alg, key, usage) => { if (!isKeyLike(key)) { throw new TypeError(invalidKeyInput(alg, key, ...types)); } if (key.type === 'secret') { throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithms must not be of type "secret"`); } if (usage === 'sign' && key.type === 'public') { throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm signing must be of type "private"`); } if (usage === 'decrypt' && key.type === 'public') { throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm decryption must be of type "private"`); } if (key.algorithm && usage === 'verify' && key.type === 'private') { throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm verifying must be of type "public"`); } if (key.algorithm && usage === 'encrypt' && key.type === 'private') { throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm encryption must be of type "public"`); } }; const checkKeyType = (alg, key, usage) => { const symmetric = alg.startsWith('HS') || alg === 'dir' || alg.startsWith('PBES2') || /^A\d{3}(?:GCM)?KW$/.test(alg); if (symmetric) { symmetricTypeCheck(alg, key); } else { asymmetricTypeCheck(alg, key, usage); } }; export default checkKeyType; jose-4.11.4/dist/node/esm/lib/check_p2s.js000066400000000000000000000003451437043056600201740ustar00rootroot00000000000000import { JWEInvalid } from '../util/errors.js'; export default function checkP2s(p2s) { if (!(p2s instanceof Uint8Array) || p2s.length < 8) { throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets'); } } jose-4.11.4/dist/node/esm/lib/crypto_key.js000066400000000000000000000126551437043056600205320ustar00rootroot00000000000000import { isCloudflareWorkers } from '../runtime/env.js'; function unusable(name, prop = 'algorithm.name') { return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); } function isAlgorithm(algorithm, name) { return algorithm.name === name; } function getHashLength(hash) { return parseInt(hash.name.slice(4), 10); } function getNamedCurve(alg) { switch (alg) { case 'ES256': return 'P-256'; case 'ES384': return 'P-384'; case 'ES512': return 'P-521'; default: throw new Error('unreachable'); } } function checkUsage(key, usages) { if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { let msg = 'CryptoKey does not support this operation, its usages must include '; if (usages.length > 2) { const last = usages.pop(); msg += `one of ${usages.join(', ')}, or ${last}.`; } else if (usages.length === 2) { msg += `one of ${usages[0]} or ${usages[1]}.`; } else { msg += `${usages[0]}.`; } throw new TypeError(msg); } } export function checkSigCryptoKey(key, alg, ...usages) { switch (alg) { case 'HS256': case 'HS384': case 'HS512': { if (!isAlgorithm(key.algorithm, 'HMAC')) throw unusable('HMAC'); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash'); break; } case 'RS256': case 'RS384': case 'RS512': { if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5')) throw unusable('RSASSA-PKCS1-v1_5'); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash'); break; } case 'PS256': case 'PS384': case 'PS512': { if (!isAlgorithm(key.algorithm, 'RSA-PSS')) throw unusable('RSA-PSS'); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash'); break; } case 'EdDSA': { if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') { if (isCloudflareWorkers()) { if (isAlgorithm(key.algorithm, 'NODE-ED25519')) break; throw unusable('Ed25519, Ed448, or NODE-ED25519'); } throw unusable('Ed25519 or Ed448'); } break; } case 'ES256': case 'ES384': case 'ES512': { if (!isAlgorithm(key.algorithm, 'ECDSA')) throw unusable('ECDSA'); const expected = getNamedCurve(alg); const actual = key.algorithm.namedCurve; if (actual !== expected) throw unusable(expected, 'algorithm.namedCurve'); break; } default: throw new TypeError('CryptoKey does not support this operation'); } checkUsage(key, usages); } export function checkEncCryptoKey(key, alg, ...usages) { switch (alg) { case 'A128GCM': case 'A192GCM': case 'A256GCM': { if (!isAlgorithm(key.algorithm, 'AES-GCM')) throw unusable('AES-GCM'); const expected = parseInt(alg.slice(1, 4), 10); const actual = key.algorithm.length; if (actual !== expected) throw unusable(expected, 'algorithm.length'); break; } case 'A128KW': case 'A192KW': case 'A256KW': { if (!isAlgorithm(key.algorithm, 'AES-KW')) throw unusable('AES-KW'); const expected = parseInt(alg.slice(1, 4), 10); const actual = key.algorithm.length; if (actual !== expected) throw unusable(expected, 'algorithm.length'); break; } case 'ECDH': { switch (key.algorithm.name) { case 'ECDH': case 'X25519': case 'X448': break; default: throw unusable('ECDH, X25519, or X448'); } break; } case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': if (!isAlgorithm(key.algorithm, 'PBKDF2')) throw unusable('PBKDF2'); break; case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': { if (!isAlgorithm(key.algorithm, 'RSA-OAEP')) throw unusable('RSA-OAEP'); const expected = parseInt(alg.slice(9), 10) || 1; const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash'); break; } default: throw new TypeError('CryptoKey does not support this operation'); } checkUsage(key, usages); } jose-4.11.4/dist/node/esm/lib/decrypt_key_management.js000066400000000000000000000113721437043056600230530ustar00rootroot00000000000000import { unwrap as aesKw } from '../runtime/aeskw.js'; import * as ECDH from '../runtime/ecdhes.js'; import { decrypt as pbes2Kw } from '../runtime/pbes2kw.js'; import { decrypt as rsaEs } from '../runtime/rsaes.js'; import { decode as base64url } from '../runtime/base64url.js'; import { JOSENotSupported, JWEInvalid } from '../util/errors.js'; import { bitLength as cekLength } from '../lib/cek.js'; import { importJWK } from '../key/import.js'; import checkKeyType from './check_key_type.js'; import isObject from './is_object.js'; import { unwrap as aesGcmKw } from './aesgcmkw.js'; async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) { checkKeyType(alg, key, 'decrypt'); switch (alg) { case 'dir': { if (encryptedKey !== undefined) throw new JWEInvalid('Encountered unexpected JWE Encrypted Key'); return key; } case 'ECDH-ES': if (encryptedKey !== undefined) throw new JWEInvalid('Encountered unexpected JWE Encrypted Key'); case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': { if (!isObject(joseHeader.epk)) throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`); if (!ECDH.ecdhAllowed(key)) throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); const epk = await importJWK(joseHeader.epk, alg); let partyUInfo; let partyVInfo; if (joseHeader.apu !== undefined) { if (typeof joseHeader.apu !== 'string') throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`); partyUInfo = base64url(joseHeader.apu); } if (joseHeader.apv !== undefined) { if (typeof joseHeader.apv !== 'string') throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`); partyVInfo = base64url(joseHeader.apv); } const sharedSecret = await ECDH.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo); if (alg === 'ECDH-ES') return sharedSecret; if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing'); return aesKw(alg.slice(-6), sharedSecret, encryptedKey); } case 'RSA1_5': case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': { if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing'); return rsaEs(alg, key, encryptedKey); } case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': { if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing'); if (typeof joseHeader.p2c !== 'number') throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`); const p2cLimit = (options === null || options === void 0 ? void 0 : options.maxPBES2Count) || 10000; if (joseHeader.p2c > p2cLimit) throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`); if (typeof joseHeader.p2s !== 'string') throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`); return pbes2Kw(alg, key, encryptedKey, joseHeader.p2c, base64url(joseHeader.p2s)); } case 'A128KW': case 'A192KW': case 'A256KW': { if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing'); return aesKw(alg, key, encryptedKey); } case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': { if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing'); if (typeof joseHeader.iv !== 'string') throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`); if (typeof joseHeader.tag !== 'string') throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`); const iv = base64url(joseHeader.iv); const tag = base64url(joseHeader.tag); return aesGcmKw(alg, key, encryptedKey, iv, tag); } default: { throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); } } } export default decryptKeyManagement; jose-4.11.4/dist/node/esm/lib/encrypt_key_management.js000066400000000000000000000066031437043056600230660ustar00rootroot00000000000000import { wrap as aesKw } from '../runtime/aeskw.js'; import * as ECDH from '../runtime/ecdhes.js'; import { encrypt as pbes2Kw } from '../runtime/pbes2kw.js'; import { encrypt as rsaEs } from '../runtime/rsaes.js'; import { encode as base64url } from '../runtime/base64url.js'; import generateCek, { bitLength as cekLength } from '../lib/cek.js'; import { JOSENotSupported } from '../util/errors.js'; import { exportJWK } from '../key/export.js'; import checkKeyType from './check_key_type.js'; import { wrap as aesGcmKw } from './aesgcmkw.js'; async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) { let encryptedKey; let parameters; let cek; checkKeyType(alg, key, 'encrypt'); switch (alg) { case 'dir': { cek = key; break; } case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': { if (!ECDH.ecdhAllowed(key)) { throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime'); } const { apu, apv } = providedParameters; let { epk: ephemeralKey } = providedParameters; ephemeralKey || (ephemeralKey = (await ECDH.generateEpk(key)).privateKey); const { x, y, crv, kty } = await exportJWK(ephemeralKey); const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv); parameters = { epk: { x, crv, kty } }; if (kty === 'EC') parameters.epk.y = y; if (apu) parameters.apu = base64url(apu); if (apv) parameters.apv = base64url(apv); if (alg === 'ECDH-ES') { cek = sharedSecret; break; } cek = providedCek || generateCek(enc); const kwAlg = alg.slice(-6); encryptedKey = await aesKw(kwAlg, sharedSecret, cek); break; } case 'RSA1_5': case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': { cek = providedCek || generateCek(enc); encryptedKey = await rsaEs(alg, key, cek); break; } case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': { cek = providedCek || generateCek(enc); const { p2c, p2s } = providedParameters; ({ encryptedKey, ...parameters } = await pbes2Kw(alg, key, cek, p2c, p2s)); break; } case 'A128KW': case 'A192KW': case 'A256KW': { cek = providedCek || generateCek(enc); encryptedKey = await aesKw(alg, key, cek); break; } case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': { cek = providedCek || generateCek(enc); const { iv } = providedParameters; ({ encryptedKey, ...parameters } = await aesGcmKw(alg, key, cek, iv)); break; } default: { throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value'); } } return { cek, encryptedKey, parameters }; } export default encryptKeyManagement; jose-4.11.4/dist/node/esm/lib/epoch.js000066400000000000000000000000741437043056600174300ustar00rootroot00000000000000export default (date) => Math.floor(date.getTime() / 1000); jose-4.11.4/dist/node/esm/lib/format_pem.js000066400000000000000000000002761437043056600204670ustar00rootroot00000000000000export default (b64, descriptor) => { const newlined = (b64.match(/.{1,64}/g) || []).join('\n'); return `-----BEGIN ${descriptor}-----\n${newlined}\n-----END ${descriptor}-----`; }; jose-4.11.4/dist/node/esm/lib/invalid_key_input.js000066400000000000000000000017141437043056600220510ustar00rootroot00000000000000function message(msg, actual, ...types) { if (types.length > 2) { const last = types.pop(); msg += `one of type ${types.join(', ')}, or ${last}.`; } else if (types.length === 2) { msg += `one of type ${types[0]} or ${types[1]}.`; } else { msg += `of type ${types[0]}.`; } if (actual == null) { msg += ` Received ${actual}`; } else if (typeof actual === 'function' && actual.name) { msg += ` Received function ${actual.name}`; } else if (typeof actual === 'object' && actual != null) { if (actual.constructor && actual.constructor.name) { msg += ` Received an instance of ${actual.constructor.name}`; } } return msg; } export default (actual, ...types) => { return message('Key must be ', actual, ...types); }; export function withAlg(alg, actual, ...types) { return message(`Key for the ${alg} algorithm must be `, actual, ...types); } jose-4.11.4/dist/node/esm/lib/is_disjoint.js000066400000000000000000000011221437043056600206430ustar00rootroot00000000000000const isDisjoint = (...headers) => { const sources = headers.filter(Boolean); if (sources.length === 0 || sources.length === 1) { return true; } let acc; for (const header of sources) { const parameters = Object.keys(header); if (!acc || acc.size === 0) { acc = new Set(parameters); continue; } for (const parameter of parameters) { if (acc.has(parameter)) { return false; } acc.add(parameter); } } return true; }; export default isDisjoint; jose-4.11.4/dist/node/esm/lib/is_object.js000066400000000000000000000007761437043056600203040ustar00rootroot00000000000000function isObjectLike(value) { return typeof value === 'object' && value !== null; } export default function isObject(input) { if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') { return false; } if (Object.getPrototypeOf(input) === null) { return true; } let proto = input; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(input) === proto; } jose-4.11.4/dist/node/esm/lib/iv.js000066400000000000000000000011371437043056600167510ustar00rootroot00000000000000import { JOSENotSupported } from '../util/errors.js'; import random from '../runtime/random.js'; export function bitLength(alg) { switch (alg) { case 'A128GCM': case 'A128GCMKW': case 'A192GCM': case 'A192GCMKW': case 'A256GCM': case 'A256GCMKW': return 96; case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': return 128; default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); } } export default (alg) => random(new Uint8Array(bitLength(alg) >> 3)); jose-4.11.4/dist/node/esm/lib/jwt_claims_set.js000066400000000000000000000073531437043056600213500ustar00rootroot00000000000000import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js'; import { decoder } from './buffer_utils.js'; import epoch from './epoch.js'; import secs from './secs.js'; import isObject from './is_object.js'; const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, ''); const checkAudiencePresence = (audPayload, audOption) => { if (typeof audPayload === 'string') { return audOption.includes(audPayload); } if (Array.isArray(audPayload)) { return audOption.some(Set.prototype.has.bind(new Set(audPayload))); } return false; }; export default (protectedHeader, encodedPayload, options = {}) => { const { typ } = options; if (typ && (typeof protectedHeader.typ !== 'string' || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', 'typ', 'check_failed'); } let payload; try { payload = JSON.parse(decoder.decode(encodedPayload)); } catch { } if (!isObject(payload)) { throw new JWTInvalid('JWT Claims Set must be a top-level JSON object'); } const { issuer } = options; if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { throw new JWTClaimValidationFailed('unexpected "iss" claim value', 'iss', 'check_failed'); } const { subject } = options; if (subject && payload.sub !== subject) { throw new JWTClaimValidationFailed('unexpected "sub" claim value', 'sub', 'check_failed'); } const { audience } = options; if (audience && !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) { throw new JWTClaimValidationFailed('unexpected "aud" claim value', 'aud', 'check_failed'); } let tolerance; switch (typeof options.clockTolerance) { case 'string': tolerance = secs(options.clockTolerance); break; case 'number': tolerance = options.clockTolerance; break; case 'undefined': tolerance = 0; break; default: throw new TypeError('Invalid clockTolerance option type'); } const { currentDate } = options; const now = epoch(currentDate || new Date()); if ((payload.iat !== undefined || options.maxTokenAge) && typeof payload.iat !== 'number') { throw new JWTClaimValidationFailed('"iat" claim must be a number', 'iat', 'invalid'); } if (payload.nbf !== undefined) { if (typeof payload.nbf !== 'number') { throw new JWTClaimValidationFailed('"nbf" claim must be a number', 'nbf', 'invalid'); } if (payload.nbf > now + tolerance) { throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', 'nbf', 'check_failed'); } } if (payload.exp !== undefined) { if (typeof payload.exp !== 'number') { throw new JWTClaimValidationFailed('"exp" claim must be a number', 'exp', 'invalid'); } if (payload.exp <= now - tolerance) { throw new JWTExpired('"exp" claim timestamp check failed', 'exp', 'check_failed'); } } if (options.maxTokenAge) { const age = now - payload.iat; const max = typeof options.maxTokenAge === 'number' ? options.maxTokenAge : secs(options.maxTokenAge); if (age - tolerance > max) { throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', 'iat', 'check_failed'); } if (age < 0 - tolerance) { throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', 'iat', 'check_failed'); } } return payload; }; jose-4.11.4/dist/node/esm/lib/secs.js000066400000000000000000000022711437043056600172700ustar00rootroot00000000000000const minute = 60; const hour = minute * 60; const day = hour * 24; const week = day * 7; const year = day * 365.25; const REGEX = /^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i; export default (str) => { const matched = REGEX.exec(str); if (!matched) { throw new TypeError('Invalid time period format'); } const value = parseFloat(matched[1]); const unit = matched[2].toLowerCase(); switch (unit) { case 'sec': case 'secs': case 'second': case 'seconds': case 's': return Math.round(value); case 'minute': case 'minutes': case 'min': case 'mins': case 'm': return Math.round(value * minute); case 'hour': case 'hours': case 'hr': case 'hrs': case 'h': return Math.round(value * hour); case 'day': case 'days': case 'd': return Math.round(value * day); case 'week': case 'weeks': case 'w': return Math.round(value * week); default: return Math.round(value * year); } }; jose-4.11.4/dist/node/esm/lib/validate_algorithms.js000066400000000000000000000006041437043056600223530ustar00rootroot00000000000000const validateAlgorithms = (option, algorithms) => { if (algorithms !== undefined && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) { throw new TypeError(`"${option}" option must be an array of strings`); } if (!algorithms) { return undefined; } return new Set(algorithms); }; export default validateAlgorithms; jose-4.11.4/dist/node/esm/lib/validate_crit.js000066400000000000000000000030611437043056600211430ustar00rootroot00000000000000import { JOSENotSupported } from '../util/errors.js'; function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { if (joseHeader.crit !== undefined && protectedHeader.crit === undefined) { throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); } if (!protectedHeader || protectedHeader.crit === undefined) { return new Set(); } if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) { throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); } let recognized; if (recognizedOption !== undefined) { recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); } else { recognized = recognizedDefault; } for (const parameter of protectedHeader.crit) { if (!recognized.has(parameter)) { throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); } if (joseHeader[parameter] === undefined) { throw new Err(`Extension Header Parameter "${parameter}" is missing`); } else if (recognized.get(parameter) && protectedHeader[parameter] === undefined) { throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); } } return new Set(protectedHeader.crit); } export default validateCrit; jose-4.11.4/dist/node/esm/package.json000066400000000000000000000000231437043056600175060ustar00rootroot00000000000000{"type": "module"} jose-4.11.4/dist/node/esm/runtime/000077500000000000000000000000001437043056600167105ustar00rootroot00000000000000jose-4.11.4/dist/node/esm/runtime/aeskw.js000066400000000000000000000040631437043056600203630ustar00rootroot00000000000000import { Buffer } from 'buffer'; import { KeyObject, createDecipheriv, createCipheriv, createSecretKey } from 'crypto'; import { JOSENotSupported } from '../util/errors.js'; import { concat } from '../lib/buffer_utils.js'; import { isCryptoKey } from './webcrypto.js'; import { checkEncCryptoKey } from '../lib/crypto_key.js'; import isKeyObject from './is_key_object.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import supported from './ciphers.js'; import { types } from './is_key_like.js'; function checkKeySize(key, alg) { if (key.symmetricKeySize << 3 !== parseInt(alg.slice(1, 4), 10)) { throw new TypeError(`Invalid key size for alg: ${alg}`); } } function ensureKeyObject(key, alg, usage) { if (isKeyObject(key)) { return key; } if (key instanceof Uint8Array) { return createSecretKey(key); } if (isCryptoKey(key)) { checkEncCryptoKey(key, alg, usage); return KeyObject.from(key); } throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); } export const wrap = (alg, key, cek) => { const size = parseInt(alg.slice(1, 4), 10); const algorithm = `aes${size}-wrap`; if (!supported(algorithm)) { throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } const keyObject = ensureKeyObject(key, alg, 'wrapKey'); checkKeySize(keyObject, alg); const cipher = createCipheriv(algorithm, keyObject, Buffer.alloc(8, 0xa6)); return concat(cipher.update(cek), cipher.final()); }; export const unwrap = (alg, key, encryptedKey) => { const size = parseInt(alg.slice(1, 4), 10); const algorithm = `aes${size}-wrap`; if (!supported(algorithm)) { throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } const keyObject = ensureKeyObject(key, alg, 'unwrapKey'); checkKeySize(keyObject, alg); const cipher = createDecipheriv(algorithm, keyObject, Buffer.alloc(8, 0xa6)); return concat(cipher.update(encryptedKey), cipher.final()); }; jose-4.11.4/dist/node/esm/runtime/asn1.js000066400000000000000000000026101437043056600201070ustar00rootroot00000000000000import { createPrivateKey, createPublicKey, KeyObject } from 'crypto'; import { Buffer } from 'buffer'; import { isCryptoKey } from './webcrypto.js'; import isKeyObject from './is_key_object.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { types } from './is_key_like.js'; const genericExport = (keyType, keyFormat, key) => { let keyObject; if (isCryptoKey(key)) { if (!key.extractable) { throw new TypeError('CryptoKey is not extractable'); } keyObject = KeyObject.from(key); } else if (isKeyObject(key)) { keyObject = key; } else { throw new TypeError(invalidKeyInput(key, ...types)); } if (keyObject.type !== keyType) { throw new TypeError(`key is not a ${keyType} key`); } return keyObject.export({ format: 'pem', type: keyFormat }); }; export const toSPKI = (key) => { return genericExport('public', 'spki', key); }; export const toPKCS8 = (key) => { return genericExport('private', 'pkcs8', key); }; export const fromPKCS8 = (pem) => createPrivateKey({ key: Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, ''), 'base64'), type: 'pkcs8', format: 'der', }); export const fromSPKI = (pem) => createPublicKey({ key: Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, ''), 'base64'), type: 'spki', format: 'der', }); jose-4.11.4/dist/node/esm/runtime/asn1_sequence_decoder.js000066400000000000000000000024051437043056600234660ustar00rootroot00000000000000const tagInteger = 0x02; const tagSequence = 0x30; export default class Asn1SequenceDecoder { constructor(buffer) { if (buffer[0] !== tagSequence) { throw new TypeError(); } this.buffer = buffer; this.offset = 1; const len = this.decodeLength(); if (len !== buffer.length - this.offset) { throw new TypeError(); } } decodeLength() { let length = this.buffer[this.offset++]; if (length & 0x80) { const nBytes = length & ~0x80; length = 0; for (let i = 0; i < nBytes; i++) length = (length << 8) | this.buffer[this.offset + i]; this.offset += nBytes; } return length; } unsignedInteger() { if (this.buffer[this.offset++] !== tagInteger) { throw new TypeError(); } let length = this.decodeLength(); if (this.buffer[this.offset] === 0) { this.offset++; length--; } const result = this.buffer.slice(this.offset, this.offset + length); this.offset += length; return result; } end() { if (this.offset !== this.buffer.length) { throw new TypeError(); } } } jose-4.11.4/dist/node/esm/runtime/asn1_sequence_encoder.js000066400000000000000000000064201437043056600235010ustar00rootroot00000000000000import { Buffer } from 'buffer'; import { JOSENotSupported } from '../util/errors.js'; const tagInteger = 0x02; const tagBitStr = 0x03; const tagOctStr = 0x04; const tagSequence = 0x30; const bZero = Buffer.from([0x00]); const bTagInteger = Buffer.from([tagInteger]); const bTagBitStr = Buffer.from([tagBitStr]); const bTagSequence = Buffer.from([tagSequence]); const bTagOctStr = Buffer.from([tagOctStr]); const encodeLength = (len) => { if (len < 128) return Buffer.from([len]); const buffer = Buffer.alloc(5); buffer.writeUInt32BE(len, 1); let offset = 1; while (buffer[offset] === 0) offset++; buffer[offset - 1] = 0x80 | (5 - offset); return buffer.slice(offset - 1); }; const oids = new Map([ ['P-256', Buffer.from('06 08 2A 86 48 CE 3D 03 01 07'.replace(/ /g, ''), 'hex')], ['secp256k1', Buffer.from('06 05 2B 81 04 00 0A'.replace(/ /g, ''), 'hex')], ['P-384', Buffer.from('06 05 2B 81 04 00 22'.replace(/ /g, ''), 'hex')], ['P-521', Buffer.from('06 05 2B 81 04 00 23'.replace(/ /g, ''), 'hex')], ['ecPublicKey', Buffer.from('06 07 2A 86 48 CE 3D 02 01'.replace(/ /g, ''), 'hex')], ['X25519', Buffer.from('06 03 2B 65 6E'.replace(/ /g, ''), 'hex')], ['X448', Buffer.from('06 03 2B 65 6F'.replace(/ /g, ''), 'hex')], ['Ed25519', Buffer.from('06 03 2B 65 70'.replace(/ /g, ''), 'hex')], ['Ed448', Buffer.from('06 03 2B 65 71'.replace(/ /g, ''), 'hex')], ]); export default class DumbAsn1Encoder { constructor() { this.length = 0; this.elements = []; } oidFor(oid) { const bOid = oids.get(oid); if (!bOid) { throw new JOSENotSupported('Invalid or unsupported OID'); } this.elements.push(bOid); this.length += bOid.length; } zero() { this.elements.push(bTagInteger, Buffer.from([0x01]), bZero); this.length += 3; } one() { this.elements.push(bTagInteger, Buffer.from([0x01]), Buffer.from([0x01])); this.length += 3; } unsignedInteger(integer) { if (integer[0] & 0x80) { const len = encodeLength(integer.length + 1); this.elements.push(bTagInteger, len, bZero, integer); this.length += 2 + len.length + integer.length; } else { let i = 0; while (integer[i] === 0 && (integer[i + 1] & 0x80) === 0) i++; const len = encodeLength(integer.length - i); this.elements.push(bTagInteger, encodeLength(integer.length - i), integer.slice(i)); this.length += 1 + len.length + integer.length - i; } } octStr(octStr) { const len = encodeLength(octStr.length); this.elements.push(bTagOctStr, encodeLength(octStr.length), octStr); this.length += 1 + len.length + octStr.length; } bitStr(bitS) { const len = encodeLength(bitS.length + 1); this.elements.push(bTagBitStr, encodeLength(bitS.length + 1), bZero, bitS); this.length += 1 + len.length + bitS.length + 1; } add(seq) { this.elements.push(seq); this.length += seq.length; } end(tag = bTagSequence) { const len = encodeLength(this.length); return Buffer.concat([tag, len, ...this.elements], 1 + len.length + this.length); } } jose-4.11.4/dist/node/esm/runtime/base64url.js000066400000000000000000000013401437043056600210530ustar00rootroot00000000000000import { Buffer } from 'buffer'; import { decoder } from '../lib/buffer_utils.js'; let encode; function normalize(input) { let encoded = input; if (encoded instanceof Uint8Array) { encoded = decoder.decode(encoded); } return encoded; } if (Buffer.isEncoding('base64url')) { encode = (input) => Buffer.from(input).toString('base64url'); } else { encode = (input) => Buffer.from(input).toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); } export const decodeBase64 = (input) => Buffer.from(input, 'base64'); export const encodeBase64 = (input) => Buffer.from(input).toString('base64'); export { encode }; export const decode = (input) => Buffer.from(normalize(input), 'base64'); jose-4.11.4/dist/node/esm/runtime/cbc_tag.js000066400000000000000000000005771437043056600206410ustar00rootroot00000000000000import { createHmac } from 'crypto'; import { concat, uint64be } from '../lib/buffer_utils.js'; export default function cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) { const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)); const hmac = createHmac(`sha${macSize}`, macKey); hmac.update(macData); return hmac.digest().slice(0, keySize >> 3); } jose-4.11.4/dist/node/esm/runtime/check_cek_length.js000066400000000000000000000024431437043056600225110ustar00rootroot00000000000000import { JWEInvalid, JOSENotSupported } from '../util/errors.js'; import isKeyObject from './is_key_object.js'; const checkCekLength = (enc, cek) => { let expected; switch (enc) { case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': expected = parseInt(enc.slice(-3), 10); break; case 'A128GCM': case 'A192GCM': case 'A256GCM': expected = parseInt(enc.slice(1, 4), 10); break; default: throw new JOSENotSupported(`Content Encryption Algorithm ${enc} is not supported either by JOSE or your javascript runtime`); } if (cek instanceof Uint8Array) { const actual = cek.byteLength << 3; if (actual !== expected) { throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); } return; } if (isKeyObject(cek) && cek.type === 'secret') { const actual = cek.symmetricKeySize << 3; if (actual !== expected) { throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`); } return; } throw new TypeError('Invalid Content Encryption Key type'); }; export default checkCekLength; jose-4.11.4/dist/node/esm/runtime/check_modulus_length.js000066400000000000000000000030111437043056600234270ustar00rootroot00000000000000export const weakMap = new WeakMap(); const getLength = (buf, index) => { let len = buf.readUInt8(1); if ((len & 0x80) === 0) { if (index === 0) { return len; } return getLength(buf.subarray(2 + len), index - 1); } const num = len & 0x7f; len = 0; for (let i = 0; i < num; i++) { len <<= 8; const j = buf.readUInt8(2 + i); len |= j; } if (index === 0) { return len; } return getLength(buf.subarray(2 + len), index - 1); }; const getLengthOfSeqIndex = (sequence, index) => { const len = sequence.readUInt8(1); if ((len & 0x80) === 0) { return getLength(sequence.subarray(2), index); } const num = len & 0x7f; return getLength(sequence.subarray(2 + num), index); }; const getModulusLength = (key) => { var _a, _b; if (weakMap.has(key)) { return weakMap.get(key); } const modulusLength = (_b = (_a = key.asymmetricKeyDetails) === null || _a === void 0 ? void 0 : _a.modulusLength) !== null && _b !== void 0 ? _b : (getLengthOfSeqIndex(key.export({ format: 'der', type: 'pkcs1' }), key.type === 'private' ? 1 : 0) - 1) << 3; weakMap.set(key, modulusLength); return modulusLength; }; export const setModulusLength = (keyObject, modulusLength) => { weakMap.set(keyObject, modulusLength); }; export default (key, alg) => { if (getModulusLength(key) < 2048) { throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); } }; jose-4.11.4/dist/node/esm/runtime/ciphers.js000066400000000000000000000002521437043056600207020ustar00rootroot00000000000000import { getCiphers } from 'crypto'; let ciphers; export default (algorithm) => { ciphers || (ciphers = new Set(getCiphers())); return ciphers.has(algorithm); }; jose-4.11.4/dist/node/esm/runtime/decrypt.js000066400000000000000000000063411437043056600207240ustar00rootroot00000000000000import { createDecipheriv, KeyObject } from 'crypto'; import checkIvLength from '../lib/check_iv_length.js'; import checkCekLength from './check_cek_length.js'; import { concat } from '../lib/buffer_utils.js'; import { JOSENotSupported, JWEDecryptionFailed } from '../util/errors.js'; import timingSafeEqual from './timing_safe_equal.js'; import cbcTag from './cbc_tag.js'; import { isCryptoKey } from './webcrypto.js'; import { checkEncCryptoKey } from '../lib/crypto_key.js'; import isKeyObject from './is_key_object.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import supported from './ciphers.js'; import { types } from './is_key_like.js'; function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) { const keySize = parseInt(enc.slice(1, 4), 10); if (isKeyObject(cek)) { cek = cek.export(); } const encKey = cek.subarray(keySize >> 3); const macKey = cek.subarray(0, keySize >> 3); const macSize = parseInt(enc.slice(-3), 10); const algorithm = `aes-${keySize}-cbc`; if (!supported(algorithm)) { throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); } const expectedTag = cbcTag(aad, iv, ciphertext, macSize, macKey, keySize); let macCheckPassed; try { macCheckPassed = timingSafeEqual(tag, expectedTag); } catch { } if (!macCheckPassed) { throw new JWEDecryptionFailed(); } let plaintext; try { const decipher = createDecipheriv(algorithm, encKey, iv); plaintext = concat(decipher.update(ciphertext), decipher.final()); } catch { } if (!plaintext) { throw new JWEDecryptionFailed(); } return plaintext; } function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) { const keySize = parseInt(enc.slice(1, 4), 10); const algorithm = `aes-${keySize}-gcm`; if (!supported(algorithm)) { throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); } try { const decipher = createDecipheriv(algorithm, cek, iv, { authTagLength: 16 }); decipher.setAuthTag(tag); if (aad.byteLength) { decipher.setAAD(aad, { plaintextLength: ciphertext.length }); } const plaintext = decipher.update(ciphertext); decipher.final(); return plaintext; } catch { throw new JWEDecryptionFailed(); } } const decrypt = (enc, cek, ciphertext, iv, tag, aad) => { let key; if (isCryptoKey(cek)) { checkEncCryptoKey(cek, enc, 'decrypt'); key = KeyObject.from(cek); } else if (cek instanceof Uint8Array || isKeyObject(cek)) { key = cek; } else { throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')); } checkCekLength(enc, key); checkIvLength(enc, iv); switch (enc) { case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': return cbcDecrypt(enc, key, ciphertext, iv, tag, aad); case 'A128GCM': case 'A192GCM': case 'A256GCM': return gcmDecrypt(enc, key, ciphertext, iv, tag, aad); default: throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); } }; export default decrypt; jose-4.11.4/dist/node/esm/runtime/digest.js000066400000000000000000000002151437043056600205230ustar00rootroot00000000000000import { createHash } from 'crypto'; const digest = (algorithm, data) => createHash(algorithm).update(data).digest(); export default digest; jose-4.11.4/dist/node/esm/runtime/dsa_digest.js000066400000000000000000000011441437043056600213540ustar00rootroot00000000000000import { JOSENotSupported } from '../util/errors.js'; export default function dsaDigest(alg) { switch (alg) { case 'PS256': case 'RS256': case 'ES256': case 'ES256K': return 'sha256'; case 'PS384': case 'RS384': case 'ES384': return 'sha384'; case 'PS512': case 'RS512': case 'ES512': return 'sha512'; case 'EdDSA': return undefined; default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } } jose-4.11.4/dist/node/esm/runtime/ecdhes.js000066400000000000000000000046171437043056600205110ustar00rootroot00000000000000import { diffieHellman, generateKeyPair as generateKeyPairCb, KeyObject } from 'crypto'; import { promisify } from 'util'; import getNamedCurve from './get_named_curve.js'; import { encoder, concat, uint32be, lengthAndInput, concatKdf } from '../lib/buffer_utils.js'; import { JOSENotSupported } from '../util/errors.js'; import { isCryptoKey } from './webcrypto.js'; import { checkEncCryptoKey } from '../lib/crypto_key.js'; import isKeyObject from './is_key_object.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { types } from './is_key_like.js'; const generateKeyPair = promisify(generateKeyPairCb); export async function deriveKey(publicKee, privateKee, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) { let publicKey; if (isCryptoKey(publicKee)) { checkEncCryptoKey(publicKee, 'ECDH'); publicKey = KeyObject.from(publicKee); } else if (isKeyObject(publicKee)) { publicKey = publicKee; } else { throw new TypeError(invalidKeyInput(publicKee, ...types)); } let privateKey; if (isCryptoKey(privateKee)) { checkEncCryptoKey(privateKee, 'ECDH', 'deriveBits'); privateKey = KeyObject.from(privateKee); } else if (isKeyObject(privateKee)) { privateKey = privateKee; } else { throw new TypeError(invalidKeyInput(privateKee, ...types)); } const value = concat(lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength)); const sharedSecret = diffieHellman({ privateKey, publicKey }); return concatKdf(sharedSecret, keyLength, value); } export async function generateEpk(kee) { let key; if (isCryptoKey(kee)) { key = KeyObject.from(kee); } else if (isKeyObject(kee)) { key = kee; } else { throw new TypeError(invalidKeyInput(kee, ...types)); } switch (key.asymmetricKeyType) { case 'x25519': return generateKeyPair('x25519'); case 'x448': { return generateKeyPair('x448'); } case 'ec': { const namedCurve = getNamedCurve(key); return generateKeyPair('ec', { namedCurve }); } default: throw new JOSENotSupported('Invalid or unsupported EPK'); } } export const ecdhAllowed = (key) => ['P-256', 'P-384', 'P-521', 'X25519', 'X448'].includes(getNamedCurve(key)); jose-4.11.4/dist/node/esm/runtime/encrypt.js000066400000000000000000000053171437043056600207400ustar00rootroot00000000000000import { createCipheriv, KeyObject } from 'crypto'; import checkIvLength from '../lib/check_iv_length.js'; import checkCekLength from './check_cek_length.js'; import { concat } from '../lib/buffer_utils.js'; import cbcTag from './cbc_tag.js'; import { isCryptoKey } from './webcrypto.js'; import { checkEncCryptoKey } from '../lib/crypto_key.js'; import isKeyObject from './is_key_object.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { JOSENotSupported } from '../util/errors.js'; import supported from './ciphers.js'; import { types } from './is_key_like.js'; function cbcEncrypt(enc, plaintext, cek, iv, aad) { const keySize = parseInt(enc.slice(1, 4), 10); if (isKeyObject(cek)) { cek = cek.export(); } const encKey = cek.subarray(keySize >> 3); const macKey = cek.subarray(0, keySize >> 3); const algorithm = `aes-${keySize}-cbc`; if (!supported(algorithm)) { throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); } const cipher = createCipheriv(algorithm, encKey, iv); const ciphertext = concat(cipher.update(plaintext), cipher.final()); const macSize = parseInt(enc.slice(-3), 10); const tag = cbcTag(aad, iv, ciphertext, macSize, macKey, keySize); return { ciphertext, tag }; } function gcmEncrypt(enc, plaintext, cek, iv, aad) { const keySize = parseInt(enc.slice(1, 4), 10); const algorithm = `aes-${keySize}-gcm`; if (!supported(algorithm)) { throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`); } const cipher = createCipheriv(algorithm, cek, iv, { authTagLength: 16 }); if (aad.byteLength) { cipher.setAAD(aad, { plaintextLength: plaintext.length }); } const ciphertext = cipher.update(plaintext); cipher.final(); const tag = cipher.getAuthTag(); return { ciphertext, tag }; } const encrypt = (enc, plaintext, cek, iv, aad) => { let key; if (isCryptoKey(cek)) { checkEncCryptoKey(cek, enc, 'encrypt'); key = KeyObject.from(cek); } else if (cek instanceof Uint8Array || isKeyObject(cek)) { key = cek; } else { throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')); } checkCekLength(enc, key); checkIvLength(enc, iv); switch (enc) { case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': return cbcEncrypt(enc, plaintext, key, iv, aad); case 'A128GCM': case 'A192GCM': case 'A256GCM': return gcmEncrypt(enc, plaintext, key, iv, aad); default: throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm'); } }; export default encrypt; jose-4.11.4/dist/node/esm/runtime/env.js000066400000000000000000000000741437043056600200370ustar00rootroot00000000000000export function isCloudflareWorkers() { return false; } jose-4.11.4/dist/node/esm/runtime/fetch_jwks.js000066400000000000000000000023751437043056600214040ustar00rootroot00000000000000import * as http from 'http'; import * as https from 'https'; import { once } from 'events'; import { JOSEError, JWKSTimeout } from '../util/errors.js'; import { concat, decoder } from '../lib/buffer_utils.js'; const fetchJwks = async (url, timeout, options) => { let get; switch (url.protocol) { case 'https:': get = https.get; break; case 'http:': get = http.get; break; default: throw new TypeError('Unsupported URL protocol.'); } const { agent, headers } = options; const req = get(url.href, { agent, timeout, headers, }); const [response] = (await Promise.race([once(req, 'response'), once(req, 'timeout')])); if (!response) { req.destroy(); throw new JWKSTimeout(); } if (response.statusCode !== 200) { throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response'); } const parts = []; for await (const part of response) { parts.push(part); } try { return JSON.parse(decoder.decode(concat(...parts))); } catch { throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON'); } }; export default fetchJwks; jose-4.11.4/dist/node/esm/runtime/flags.js000066400000000000000000000006431437043056600203450ustar00rootroot00000000000000const [major, minor] = process.versions.node.split('.').map((str) => parseInt(str, 10)); export const oneShotCallback = major >= 16 || (major === 15 && minor >= 13); export const rsaPssParams = !('electron' in process.versions) && (major >= 17 || (major === 16 && minor >= 9)); export const jwkExport = major >= 16 || (major === 15 && minor >= 9); export const jwkImport = major >= 16 || (major === 15 && minor >= 12); jose-4.11.4/dist/node/esm/runtime/generate.js000066400000000000000000000075031437043056600210450ustar00rootroot00000000000000import { createSecretKey, generateKeyPair as generateKeyPairCb } from 'crypto'; import { promisify } from 'util'; import random from './random.js'; import { setModulusLength } from './check_modulus_length.js'; import { JOSENotSupported } from '../util/errors.js'; const generate = promisify(generateKeyPairCb); export async function generateSecret(alg, options) { let length; switch (alg) { case 'HS256': case 'HS384': case 'HS512': case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': length = parseInt(alg.slice(-3), 10); break; case 'A128KW': case 'A192KW': case 'A256KW': case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': case 'A128GCM': case 'A192GCM': case 'A256GCM': length = parseInt(alg.slice(1, 4), 10); break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } return createSecretKey(random(new Uint8Array(length >> 3))); } export async function generateKeyPair(alg, options) { var _a, _b; switch (alg) { case 'RS256': case 'RS384': case 'RS512': case 'PS256': case 'PS384': case 'PS512': case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': case 'RSA1_5': { const modulusLength = (_a = options === null || options === void 0 ? void 0 : options.modulusLength) !== null && _a !== void 0 ? _a : 2048; if (typeof modulusLength !== 'number' || modulusLength < 2048) { throw new JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used'); } const keypair = await generate('rsa', { modulusLength, publicExponent: 0x10001, }); setModulusLength(keypair.privateKey, modulusLength); setModulusLength(keypair.publicKey, modulusLength); return keypair; } case 'ES256': return generate('ec', { namedCurve: 'P-256' }); case 'ES256K': return generate('ec', { namedCurve: 'secp256k1' }); case 'ES384': return generate('ec', { namedCurve: 'P-384' }); case 'ES512': return generate('ec', { namedCurve: 'P-521' }); case 'EdDSA': { switch (options === null || options === void 0 ? void 0 : options.crv) { case undefined: case 'Ed25519': return generate('ed25519'); case 'Ed448': return generate('ed448'); default: throw new JOSENotSupported('Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448'); } } case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': const crv = (_b = options === null || options === void 0 ? void 0 : options.crv) !== null && _b !== void 0 ? _b : 'P-256'; switch (crv) { case undefined: case 'P-256': case 'P-384': case 'P-521': return generate('ec', { namedCurve: crv }); case 'X25519': return generate('x25519'); case 'X448': return generate('x448'); default: throw new JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448'); } default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } } jose-4.11.4/dist/node/esm/runtime/get_named_curve.js000066400000000000000000000062761437043056600224100ustar00rootroot00000000000000import { Buffer } from 'buffer'; import { createPublicKey, KeyObject } from 'crypto'; import { JOSENotSupported } from '../util/errors.js'; import { isCryptoKey } from './webcrypto.js'; import isKeyObject from './is_key_object.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { types } from './is_key_like.js'; const p256 = Buffer.from([42, 134, 72, 206, 61, 3, 1, 7]); const p384 = Buffer.from([43, 129, 4, 0, 34]); const p521 = Buffer.from([43, 129, 4, 0, 35]); const secp256k1 = Buffer.from([43, 129, 4, 0, 10]); export const weakMap = new WeakMap(); const namedCurveToJOSE = (namedCurve) => { switch (namedCurve) { case 'prime256v1': return 'P-256'; case 'secp384r1': return 'P-384'; case 'secp521r1': return 'P-521'; case 'secp256k1': return 'secp256k1'; default: throw new JOSENotSupported('Unsupported key curve for this operation'); } }; const getNamedCurve = (kee, raw) => { var _a; let key; if (isCryptoKey(kee)) { key = KeyObject.from(kee); } else if (isKeyObject(kee)) { key = kee; } else { throw new TypeError(invalidKeyInput(kee, ...types)); } if (key.type === 'secret') { throw new TypeError('only "private" or "public" type keys can be used for this operation'); } switch (key.asymmetricKeyType) { case 'ed25519': case 'ed448': return `Ed${key.asymmetricKeyType.slice(2)}`; case 'x25519': case 'x448': return `X${key.asymmetricKeyType.slice(1)}`; case 'ec': { if (weakMap.has(key)) { return weakMap.get(key); } let namedCurve = (_a = key.asymmetricKeyDetails) === null || _a === void 0 ? void 0 : _a.namedCurve; if (!namedCurve && key.type === 'private') { namedCurve = getNamedCurve(createPublicKey(key), true); } else if (!namedCurve) { const buf = key.export({ format: 'der', type: 'spki' }); const i = buf[1] < 128 ? 14 : 15; const len = buf[i]; const curveOid = buf.slice(i + 1, i + 1 + len); if (curveOid.equals(p256)) { namedCurve = 'prime256v1'; } else if (curveOid.equals(p384)) { namedCurve = 'secp384r1'; } else if (curveOid.equals(p521)) { namedCurve = 'secp521r1'; } else if (curveOid.equals(secp256k1)) { namedCurve = 'secp256k1'; } else { throw new JOSENotSupported('Unsupported key curve for this operation'); } } if (raw) return namedCurve; const curve = namedCurveToJOSE(namedCurve); weakMap.set(key, curve); return curve; } default: throw new TypeError('Invalid asymmetric key type for this operation'); } }; export function setCurve(keyObject, curve) { weakMap.set(keyObject, curve); } export default getNamedCurve; jose-4.11.4/dist/node/esm/runtime/get_sign_verify_key.js000066400000000000000000000013671437043056600233100ustar00rootroot00000000000000import { KeyObject, createSecretKey } from 'crypto'; import { isCryptoKey } from './webcrypto.js'; import { checkSigCryptoKey } from '../lib/crypto_key.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { types } from './is_key_like.js'; export default function getSignVerifyKey(alg, key, usage) { if (key instanceof Uint8Array) { if (!alg.startsWith('HS')) { throw new TypeError(invalidKeyInput(key, ...types)); } return createSecretKey(key); } if (key instanceof KeyObject) { return key; } if (isCryptoKey(key)) { checkSigCryptoKey(key, alg, usage); return KeyObject.from(key); } throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); } jose-4.11.4/dist/node/esm/runtime/hmac_digest.js000066400000000000000000000006261437043056600215210ustar00rootroot00000000000000import { JOSENotSupported } from '../util/errors.js'; export default function hmacDigest(alg) { switch (alg) { case 'HS256': return 'sha256'; case 'HS384': return 'sha384'; case 'HS512': return 'sha512'; default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } } jose-4.11.4/dist/node/esm/runtime/is_key_like.js000066400000000000000000000005361437043056600215410ustar00rootroot00000000000000import webcrypto, { isCryptoKey } from './webcrypto.js'; import isKeyObject from './is_key_object.js'; export default (key) => isKeyObject(key) || isCryptoKey(key); const types = ['KeyObject']; if (globalThis.CryptoKey || (webcrypto === null || webcrypto === void 0 ? void 0 : webcrypto.CryptoKey)) { types.push('CryptoKey'); } export { types }; jose-4.11.4/dist/node/esm/runtime/is_key_object.js000066400000000000000000000003131437043056600220540ustar00rootroot00000000000000import { KeyObject } from 'crypto'; import * as util from 'util'; export default util.types.isKeyObject ? (obj) => util.types.isKeyObject(obj) : (obj) => obj != null && obj instanceof KeyObject; jose-4.11.4/dist/node/esm/runtime/jwk_to_key.js000066400000000000000000000114301437043056600214120ustar00rootroot00000000000000import { Buffer } from 'buffer'; import { createPrivateKey, createPublicKey, createSecretKey } from 'crypto'; import { decode as base64url } from './base64url.js'; import { JOSENotSupported } from '../util/errors.js'; import { setCurve } from './get_named_curve.js'; import { setModulusLength } from './check_modulus_length.js'; import Asn1SequenceEncoder from './asn1_sequence_encoder.js'; import { jwkImport } from './flags.js'; const parse = (jwk) => { if (jwkImport && jwk.kty !== 'oct') { return jwk.d ? createPrivateKey({ format: 'jwk', key: jwk }) : createPublicKey({ format: 'jwk', key: jwk }); } switch (jwk.kty) { case 'oct': { return createSecretKey(base64url(jwk.k)); } case 'RSA': { const enc = new Asn1SequenceEncoder(); const isPrivate = jwk.d !== undefined; const modulus = Buffer.from(jwk.n, 'base64'); const exponent = Buffer.from(jwk.e, 'base64'); if (isPrivate) { enc.zero(); enc.unsignedInteger(modulus); enc.unsignedInteger(exponent); enc.unsignedInteger(Buffer.from(jwk.d, 'base64')); enc.unsignedInteger(Buffer.from(jwk.p, 'base64')); enc.unsignedInteger(Buffer.from(jwk.q, 'base64')); enc.unsignedInteger(Buffer.from(jwk.dp, 'base64')); enc.unsignedInteger(Buffer.from(jwk.dq, 'base64')); enc.unsignedInteger(Buffer.from(jwk.qi, 'base64')); } else { enc.unsignedInteger(modulus); enc.unsignedInteger(exponent); } const der = enc.end(); const createInput = { key: der, format: 'der', type: 'pkcs1', }; const keyObject = isPrivate ? createPrivateKey(createInput) : createPublicKey(createInput); setModulusLength(keyObject, modulus.length << 3); return keyObject; } case 'EC': { const enc = new Asn1SequenceEncoder(); const isPrivate = jwk.d !== undefined; const pub = Buffer.concat([ Buffer.alloc(1, 4), Buffer.from(jwk.x, 'base64'), Buffer.from(jwk.y, 'base64'), ]); if (isPrivate) { enc.zero(); const enc$1 = new Asn1SequenceEncoder(); enc$1.oidFor('ecPublicKey'); enc$1.oidFor(jwk.crv); enc.add(enc$1.end()); const enc$2 = new Asn1SequenceEncoder(); enc$2.one(); enc$2.octStr(Buffer.from(jwk.d, 'base64')); const enc$3 = new Asn1SequenceEncoder(); enc$3.bitStr(pub); const f2 = enc$3.end(Buffer.from([0xa1])); enc$2.add(f2); const f = enc$2.end(); const enc$4 = new Asn1SequenceEncoder(); enc$4.add(f); const f3 = enc$4.end(Buffer.from([0x04])); enc.add(f3); const der = enc.end(); const keyObject = createPrivateKey({ key: der, format: 'der', type: 'pkcs8' }); setCurve(keyObject, jwk.crv); return keyObject; } const enc$1 = new Asn1SequenceEncoder(); enc$1.oidFor('ecPublicKey'); enc$1.oidFor(jwk.crv); enc.add(enc$1.end()); enc.bitStr(pub); const der = enc.end(); const keyObject = createPublicKey({ key: der, format: 'der', type: 'spki' }); setCurve(keyObject, jwk.crv); return keyObject; } case 'OKP': { const enc = new Asn1SequenceEncoder(); const isPrivate = jwk.d !== undefined; if (isPrivate) { enc.zero(); const enc$1 = new Asn1SequenceEncoder(); enc$1.oidFor(jwk.crv); enc.add(enc$1.end()); const enc$2 = new Asn1SequenceEncoder(); enc$2.octStr(Buffer.from(jwk.d, 'base64')); const f = enc$2.end(Buffer.from([0x04])); enc.add(f); const der = enc.end(); return createPrivateKey({ key: der, format: 'der', type: 'pkcs8' }); } const enc$1 = new Asn1SequenceEncoder(); enc$1.oidFor(jwk.crv); enc.add(enc$1.end()); enc.bitStr(Buffer.from(jwk.x, 'base64')); const der = enc.end(); return createPublicKey({ key: der, format: 'der', type: 'spki' }); } default: throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); } }; export default parse; jose-4.11.4/dist/node/esm/runtime/key_to_jwk.js000066400000000000000000000145541437043056600214240ustar00rootroot00000000000000import { KeyObject, createPublicKey } from 'crypto'; import { encode as base64url } from './base64url.js'; import Asn1SequenceDecoder from './asn1_sequence_decoder.js'; import { JOSENotSupported } from '../util/errors.js'; import getNamedCurve from './get_named_curve.js'; import { isCryptoKey } from './webcrypto.js'; import isKeyObject from './is_key_object.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { types } from './is_key_like.js'; import { jwkExport } from './flags.js'; const keyToJWK = (key) => { let keyObject; if (isCryptoKey(key)) { if (!key.extractable) { throw new TypeError('CryptoKey is not extractable'); } keyObject = KeyObject.from(key); } else if (isKeyObject(key)) { keyObject = key; } else if (key instanceof Uint8Array) { return { kty: 'oct', k: base64url(key), }; } else { throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); } if (jwkExport) { if (keyObject.type !== 'secret' && !['rsa', 'ec', 'ed25519', 'x25519', 'ed448', 'x448'].includes(keyObject.asymmetricKeyType)) { throw new JOSENotSupported('Unsupported key asymmetricKeyType'); } return keyObject.export({ format: 'jwk' }); } switch (keyObject.type) { case 'secret': return { kty: 'oct', k: base64url(keyObject.export()), }; case 'private': case 'public': { switch (keyObject.asymmetricKeyType) { case 'rsa': { const der = keyObject.export({ format: 'der', type: 'pkcs1' }); const dec = new Asn1SequenceDecoder(der); if (keyObject.type === 'private') { dec.unsignedInteger(); } const n = base64url(dec.unsignedInteger()); const e = base64url(dec.unsignedInteger()); let jwk; if (keyObject.type === 'private') { jwk = { d: base64url(dec.unsignedInteger()), p: base64url(dec.unsignedInteger()), q: base64url(dec.unsignedInteger()), dp: base64url(dec.unsignedInteger()), dq: base64url(dec.unsignedInteger()), qi: base64url(dec.unsignedInteger()), }; } dec.end(); return { kty: 'RSA', n, e, ...jwk }; } case 'ec': { const crv = getNamedCurve(keyObject); let len; let offset; let correction; switch (crv) { case 'secp256k1': len = 64; offset = 31 + 2; correction = -1; break; case 'P-256': len = 64; offset = 34 + 2; correction = -1; break; case 'P-384': len = 96; offset = 33 + 2; correction = -3; break; case 'P-521': len = 132; offset = 33 + 2; correction = -3; break; default: throw new JOSENotSupported('Unsupported curve'); } if (keyObject.type === 'public') { const der = keyObject.export({ type: 'spki', format: 'der' }); return { kty: 'EC', crv, x: base64url(der.subarray(-len, -len / 2)), y: base64url(der.subarray(-len / 2)), }; } const der = keyObject.export({ type: 'pkcs8', format: 'der' }); if (der.length < 100) { offset += correction; } return { ...keyToJWK(createPublicKey(keyObject)), d: base64url(der.subarray(offset, offset + len / 2)), }; } case 'ed25519': case 'x25519': { const crv = getNamedCurve(keyObject); if (keyObject.type === 'public') { const der = keyObject.export({ type: 'spki', format: 'der' }); return { kty: 'OKP', crv, x: base64url(der.subarray(-32)), }; } const der = keyObject.export({ type: 'pkcs8', format: 'der' }); return { ...keyToJWK(createPublicKey(keyObject)), d: base64url(der.subarray(-32)), }; } case 'ed448': case 'x448': { const crv = getNamedCurve(keyObject); if (keyObject.type === 'public') { const der = keyObject.export({ type: 'spki', format: 'der' }); return { kty: 'OKP', crv, x: base64url(der.subarray(crv === 'Ed448' ? -57 : -56)), }; } const der = keyObject.export({ type: 'pkcs8', format: 'der' }); return { ...keyToJWK(createPublicKey(keyObject)), d: base64url(der.subarray(crv === 'Ed448' ? -57 : -56)), }; } default: throw new JOSENotSupported('Unsupported key asymmetricKeyType'); } } default: throw new JOSENotSupported('Unsupported key type'); } }; export default keyToJWK; jose-4.11.4/dist/node/esm/runtime/node_key.js000066400000000000000000000064731437043056600210550ustar00rootroot00000000000000import { constants } from 'crypto'; import getNamedCurve from './get_named_curve.js'; import { JOSENotSupported } from '../util/errors.js'; import checkModulusLength from './check_modulus_length.js'; import { rsaPssParams } from './flags.js'; const PSS = { padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: constants.RSA_PSS_SALTLEN_DIGEST, }; const ecCurveAlgMap = new Map([ ['ES256', 'P-256'], ['ES256K', 'secp256k1'], ['ES384', 'P-384'], ['ES512', 'P-521'], ]); export default function keyForCrypto(alg, key) { switch (alg) { case 'EdDSA': if (!['ed25519', 'ed448'].includes(key.asymmetricKeyType)) { throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448'); } return key; case 'RS256': case 'RS384': case 'RS512': if (key.asymmetricKeyType !== 'rsa') { throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); } checkModulusLength(key, alg); return key; case rsaPssParams && 'PS256': case rsaPssParams && 'PS384': case rsaPssParams && 'PS512': if (key.asymmetricKeyType === 'rsa-pss') { const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails; const length = parseInt(alg.slice(-3), 10); if (hashAlgorithm !== undefined && (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm)) { throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${alg}`); } if (saltLength !== undefined && saltLength > length >> 3) { throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${alg}`); } } else if (key.asymmetricKeyType !== 'rsa') { throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss'); } checkModulusLength(key, alg); return { key, ...PSS }; case !rsaPssParams && 'PS256': case !rsaPssParams && 'PS384': case !rsaPssParams && 'PS512': if (key.asymmetricKeyType !== 'rsa') { throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); } checkModulusLength(key, alg); return { key, ...PSS }; case 'ES256': case 'ES256K': case 'ES384': case 'ES512': { if (key.asymmetricKeyType !== 'ec') { throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ec'); } const actual = getNamedCurve(key); const expected = ecCurveAlgMap.get(alg); if (actual !== expected) { throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`); } return { dsaEncoding: 'ieee-p1363', key }; } default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } } jose-4.11.4/dist/node/esm/runtime/pbes2kw.js000066400000000000000000000034641437043056600206320ustar00rootroot00000000000000import { promisify } from 'util'; import { KeyObject, pbkdf2 as pbkdf2cb } from 'crypto'; import random from './random.js'; import { p2s as concatSalt } from '../lib/buffer_utils.js'; import { encode as base64url } from './base64url.js'; import { wrap, unwrap } from './aeskw.js'; import checkP2s from '../lib/check_p2s.js'; import { isCryptoKey } from './webcrypto.js'; import { checkEncCryptoKey } from '../lib/crypto_key.js'; import isKeyObject from './is_key_object.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { types } from './is_key_like.js'; const pbkdf2 = promisify(pbkdf2cb); function getPassword(key, alg) { if (isKeyObject(key)) { return key.export(); } if (key instanceof Uint8Array) { return key; } if (isCryptoKey(key)) { checkEncCryptoKey(key, alg, 'deriveBits', 'deriveKey'); return KeyObject.from(key).export(); } throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')); } export const encrypt = async (alg, key, cek, p2c = 2048, p2s = random(new Uint8Array(16))) => { checkP2s(p2s); const salt = concatSalt(alg, p2s); const keylen = parseInt(alg.slice(13, 16), 10) >> 3; const password = getPassword(key, alg); const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`); const encryptedKey = await wrap(alg.slice(-6), derivedKey, cek); return { encryptedKey, p2c, p2s: base64url(p2s) }; }; export const decrypt = async (alg, key, encryptedKey, p2c, p2s) => { checkP2s(p2s); const salt = concatSalt(alg, p2s); const keylen = parseInt(alg.slice(13, 16), 10) >> 3; const password = getPassword(key, alg); const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`); return unwrap(alg.slice(-6), derivedKey, encryptedKey); }; jose-4.11.4/dist/node/esm/runtime/random.js000066400000000000000000000000641437043056600205260ustar00rootroot00000000000000export { randomFillSync as default } from 'crypto'; jose-4.11.4/dist/node/esm/runtime/rsaes.js000066400000000000000000000042171437043056600203670ustar00rootroot00000000000000import { KeyObject, publicEncrypt, constants, privateDecrypt } from 'crypto'; import checkModulusLength from './check_modulus_length.js'; import { isCryptoKey } from './webcrypto.js'; import { checkEncCryptoKey } from '../lib/crypto_key.js'; import isKeyObject from './is_key_object.js'; import invalidKeyInput from '../lib/invalid_key_input.js'; import { types } from './is_key_like.js'; const checkKey = (key, alg) => { if (key.asymmetricKeyType !== 'rsa') { throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa'); } checkModulusLength(key, alg); }; const resolvePadding = (alg) => { switch (alg) { case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': return constants.RSA_PKCS1_OAEP_PADDING; case 'RSA1_5': return constants.RSA_PKCS1_PADDING; default: return undefined; } }; const resolveOaepHash = (alg) => { switch (alg) { case 'RSA-OAEP': return 'sha1'; case 'RSA-OAEP-256': return 'sha256'; case 'RSA-OAEP-384': return 'sha384'; case 'RSA-OAEP-512': return 'sha512'; default: return undefined; } }; function ensureKeyObject(key, alg, ...usages) { if (isKeyObject(key)) { return key; } if (isCryptoKey(key)) { checkEncCryptoKey(key, alg, ...usages); return KeyObject.from(key); } throw new TypeError(invalidKeyInput(key, ...types)); } export const encrypt = (alg, key, cek) => { const padding = resolvePadding(alg); const oaepHash = resolveOaepHash(alg); const keyObject = ensureKeyObject(key, alg, 'wrapKey', 'encrypt'); checkKey(keyObject, alg); return publicEncrypt({ key: keyObject, oaepHash, padding }, cek); }; export const decrypt = (alg, key, encryptedKey) => { const padding = resolvePadding(alg); const oaepHash = resolveOaepHash(alg); const keyObject = ensureKeyObject(key, alg, 'unwrapKey', 'decrypt'); checkKey(keyObject, alg); return privateDecrypt({ key: keyObject, oaepHash, padding }, encryptedKey); }; jose-4.11.4/dist/node/esm/runtime/sign.js000066400000000000000000000013241437043056600202060ustar00rootroot00000000000000import * as crypto from 'crypto'; import { promisify } from 'util'; import nodeDigest from './dsa_digest.js'; import hmacDigest from './hmac_digest.js'; import nodeKey from './node_key.js'; import getSignKey from './get_sign_verify_key.js'; let oneShotSign; if (crypto.sign.length > 3) { oneShotSign = promisify(crypto.sign); } else { oneShotSign = crypto.sign; } const sign = async (alg, key, data) => { const keyObject = getSignKey(alg, key, 'sign'); if (alg.startsWith('HS')) { const hmac = crypto.createHmac(hmacDigest(alg), keyObject); hmac.update(data); return hmac.digest(); } return oneShotSign(nodeDigest(alg), data, nodeKey(alg, keyObject)); }; export default sign; jose-4.11.4/dist/node/esm/runtime/timing_safe_equal.js000066400000000000000000000001601437043056600227170ustar00rootroot00000000000000import { timingSafeEqual as impl } from 'crypto'; const timingSafeEqual = impl; export default timingSafeEqual; jose-4.11.4/dist/node/esm/runtime/verify.js000066400000000000000000000020411437043056600205470ustar00rootroot00000000000000import * as crypto from 'crypto'; import { promisify } from 'util'; import nodeDigest from './dsa_digest.js'; import nodeKey from './node_key.js'; import sign from './sign.js'; import getVerifyKey from './get_sign_verify_key.js'; import { oneShotCallback } from './flags.js'; let oneShotVerify; if (crypto.verify.length > 4 && oneShotCallback) { oneShotVerify = promisify(crypto.verify); } else { oneShotVerify = crypto.verify; } const verify = async (alg, key, signature, data) => { const keyObject = getVerifyKey(alg, key, 'verify'); if (alg.startsWith('HS')) { const expected = await sign(alg, keyObject, data); const actual = signature; try { return crypto.timingSafeEqual(actual, expected); } catch { return false; } } const algorithm = nodeDigest(alg); const keyInput = nodeKey(alg, keyObject); try { return await oneShotVerify(algorithm, data, keyInput, signature); } catch { return false; } }; export default verify; jose-4.11.4/dist/node/esm/runtime/webcrypto.js000066400000000000000000000003711437043056600212650ustar00rootroot00000000000000import * as crypto from 'crypto'; import * as util from 'util'; const webcrypto = crypto.webcrypto; export default webcrypto; export const isCryptoKey = util.types.isCryptoKey ? (key) => util.types.isCryptoKey(key) : (key) => false; jose-4.11.4/dist/node/esm/runtime/zlib.js000066400000000000000000000004631437043056600202110ustar00rootroot00000000000000import { promisify } from 'util'; import { inflateRaw as inflateRawCb, deflateRaw as deflateRawCb } from 'zlib'; const inflateRaw = promisify(inflateRawCb); const deflateRaw = promisify(deflateRawCb); export const inflate = (input) => inflateRaw(input); export const deflate = (input) => deflateRaw(input); jose-4.11.4/dist/node/esm/util/000077500000000000000000000000001437043056600162025ustar00rootroot00000000000000jose-4.11.4/dist/node/esm/util/base64url.js000066400000000000000000000002061437043056600203450ustar00rootroot00000000000000import * as base64url from '../runtime/base64url.js'; export const encode = base64url.encode; export const decode = base64url.decode; jose-4.11.4/dist/node/esm/util/decode_jwt.js000066400000000000000000000021311437043056600206440ustar00rootroot00000000000000import { decode as base64url } from './base64url.js'; import { decoder } from '../lib/buffer_utils.js'; import isObject from '../lib/is_object.js'; import { JWTInvalid } from './errors.js'; export function decodeJwt(jwt) { if (typeof jwt !== 'string') throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string'); const { 1: payload, length } = jwt.split('.'); if (length === 5) throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded'); if (length !== 3) throw new JWTInvalid('Invalid JWT'); if (!payload) throw new JWTInvalid('JWTs must contain a payload'); let decoded; try { decoded = base64url(payload); } catch { throw new JWTInvalid('Failed to parse the base64url encoded payload'); } let result; try { result = JSON.parse(decoder.decode(decoded)); } catch { throw new JWTInvalid('Failed to parse the decoded payload as JSON'); } if (!isObject(result)) throw new JWTInvalid('Invalid JWT Claims Set'); return result; } jose-4.11.4/dist/node/esm/util/decode_protected_header.js000066400000000000000000000020501437043056600233410ustar00rootroot00000000000000import { decode as base64url } from './base64url.js'; import { decoder } from '../lib/buffer_utils.js'; import isObject from '../lib/is_object.js'; export function decodeProtectedHeader(token) { let protectedB64u; if (typeof token === 'string') { const parts = token.split('.'); if (parts.length === 3 || parts.length === 5) { ; [protectedB64u] = parts; } } else if (typeof token === 'object' && token) { if ('protected' in token) { protectedB64u = token.protected; } else { throw new TypeError('Token does not contain a Protected Header'); } } try { if (typeof protectedB64u !== 'string' || !protectedB64u) { throw new Error(); } const result = JSON.parse(decoder.decode(base64url(protectedB64u))); if (!isObject(result)) { throw new Error(); } return result; } catch { throw new TypeError('Invalid Token or Protected Header formatting'); } } jose-4.11.4/dist/node/esm/util/errors.js000066400000000000000000000076601437043056600200650ustar00rootroot00000000000000export class JOSEError extends Error { static get code() { return 'ERR_JOSE_GENERIC'; } constructor(message) { var _a; super(message); this.code = 'ERR_JOSE_GENERIC'; this.name = this.constructor.name; (_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, this, this.constructor); } } export class JWTClaimValidationFailed extends JOSEError { static get code() { return 'ERR_JWT_CLAIM_VALIDATION_FAILED'; } constructor(message, claim = 'unspecified', reason = 'unspecified') { super(message); this.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'; this.claim = claim; this.reason = reason; } } export class JWTExpired extends JOSEError { static get code() { return 'ERR_JWT_EXPIRED'; } constructor(message, claim = 'unspecified', reason = 'unspecified') { super(message); this.code = 'ERR_JWT_EXPIRED'; this.claim = claim; this.reason = reason; } } export class JOSEAlgNotAllowed extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JOSE_ALG_NOT_ALLOWED'; } static get code() { return 'ERR_JOSE_ALG_NOT_ALLOWED'; } } export class JOSENotSupported extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JOSE_NOT_SUPPORTED'; } static get code() { return 'ERR_JOSE_NOT_SUPPORTED'; } } export class JWEDecryptionFailed extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWE_DECRYPTION_FAILED'; this.message = 'decryption operation failed'; } static get code() { return 'ERR_JWE_DECRYPTION_FAILED'; } } export class JWEInvalid extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWE_INVALID'; } static get code() { return 'ERR_JWE_INVALID'; } } export class JWSInvalid extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWS_INVALID'; } static get code() { return 'ERR_JWS_INVALID'; } } export class JWTInvalid extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWT_INVALID'; } static get code() { return 'ERR_JWT_INVALID'; } } export class JWKInvalid extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWK_INVALID'; } static get code() { return 'ERR_JWK_INVALID'; } } export class JWKSInvalid extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWKS_INVALID'; } static get code() { return 'ERR_JWKS_INVALID'; } } export class JWKSNoMatchingKey extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWKS_NO_MATCHING_KEY'; this.message = 'no applicable key found in the JSON Web Key Set'; } static get code() { return 'ERR_JWKS_NO_MATCHING_KEY'; } } export class JWKSMultipleMatchingKeys extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; this.message = 'multiple matching keys found in the JSON Web Key Set'; } static get code() { return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; } } export class JWKSTimeout extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWKS_TIMEOUT'; this.message = 'request timed out'; } static get code() { return 'ERR_JWKS_TIMEOUT'; } } export class JWSSignatureVerificationFailed extends JOSEError { constructor() { super(...arguments); this.code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; this.message = 'signature verification failed'; } static get code() { return 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; } } jose-4.11.4/dist/types/000077500000000000000000000000001437043056600146605ustar00rootroot00000000000000jose-4.11.4/dist/types/index.d.ts000066400000000000000000000064471437043056600165740ustar00rootroot00000000000000export { compactDecrypt } from './jwe/compact/decrypt'; export type { CompactDecryptGetKey } from './jwe/compact/decrypt'; export { flattenedDecrypt } from './jwe/flattened/decrypt'; export type { FlattenedDecryptGetKey } from './jwe/flattened/decrypt'; export { generalDecrypt } from './jwe/general/decrypt'; export type { GeneralDecryptGetKey } from './jwe/general/decrypt'; export { GeneralEncrypt } from './jwe/general/encrypt'; export type { Recipient } from './jwe/general/encrypt'; export { compactVerify } from './jws/compact/verify'; export type { CompactVerifyGetKey } from './jws/compact/verify'; export { flattenedVerify } from './jws/flattened/verify'; export type { FlattenedVerifyGetKey } from './jws/flattened/verify'; export { generalVerify } from './jws/general/verify'; export type { GeneralVerifyGetKey } from './jws/general/verify'; export { jwtVerify } from './jwt/verify'; export type { JWTVerifyOptions, JWTVerifyGetKey } from './jwt/verify'; export { jwtDecrypt } from './jwt/decrypt'; export type { JWTDecryptOptions, JWTDecryptGetKey } from './jwt/decrypt'; export type { ProduceJWT } from './jwt/produce'; export { CompactEncrypt } from './jwe/compact/encrypt'; export { FlattenedEncrypt } from './jwe/flattened/encrypt'; export { CompactSign } from './jws/compact/sign'; export { FlattenedSign } from './jws/flattened/sign'; export { GeneralSign } from './jws/general/sign'; export type { Signature } from './jws/general/sign'; export { SignJWT } from './jwt/sign'; export { EncryptJWT } from './jwt/encrypt'; export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint'; export { EmbeddedJWK } from './jwk/embedded'; export { createLocalJWKSet } from './jwks/local'; export { createRemoteJWKSet } from './jwks/remote'; export type { RemoteJWKSetOptions } from './jwks/remote'; export { UnsecuredJWT } from './jwt/unsecured'; export type { UnsecuredResult } from './jwt/unsecured'; export { exportPKCS8, exportSPKI, exportJWK } from './key/export'; export { importSPKI, importPKCS8, importX509, importJWK } from './key/import'; export type { PEMImportOptions } from './key/import'; export { decodeProtectedHeader } from './util/decode_protected_header'; export { decodeJwt } from './util/decode_jwt'; export type { ProtectedHeaderParameters } from './util/decode_protected_header'; export * as errors from './util/errors'; export { generateKeyPair } from './key/generate_key_pair'; export type { GenerateKeyPairResult, GenerateKeyPairOptions } from './key/generate_key_pair'; export { generateSecret } from './key/generate_secret'; export type { GenerateSecretOptions } from './key/generate_secret'; export * as base64url from './util/base64url'; export type { KeyLike, JWK, FlattenedJWSInput, GeneralJWSInput, FlattenedJWS, GeneralJWS, JoseHeaderParameters, JWSHeaderParameters, JWEKeyManagementHeaderParameters, FlattenedJWE, GeneralJWE, JWEHeaderParameters, CritOption, DeflateOption, DecryptOptions, EncryptOptions, JWTClaimVerificationOptions, VerifyOptions, SignOptions, JWTPayload, DeflateFunction, InflateFunction, FlattenedDecryptResult, GeneralDecryptResult, CompactDecryptResult, FlattenedVerifyResult, GeneralVerifyResult, CompactVerifyResult, JWTVerifyResult, JWTDecryptResult, ResolvedKey, CompactJWEHeaderParameters, CompactJWSHeaderParameters, JWTHeaderParameters, JSONWebKeySet, } from './types'; jose-4.11.4/dist/types/jwe/000077500000000000000000000000001437043056600154455ustar00rootroot00000000000000jose-4.11.4/dist/types/jwe/compact/000077500000000000000000000000001437043056600170735ustar00rootroot00000000000000jose-4.11.4/dist/types/jwe/compact/decrypt.d.ts000066400000000000000000000034121437043056600213370ustar00rootroot00000000000000import type { KeyLike, DecryptOptions, CompactJWEHeaderParameters, GetKeyFunction, FlattenedJWE, CompactDecryptResult, ResolvedKey } from '../../types'; /** * Interface for Compact JWE Decryption dynamic key resolution. No token components have been * verified at the time of this function call. */ export interface CompactDecryptGetKey extends GetKeyFunction { } /** * Decrypts a Compact JWE. * * @example Usage * * ```js * const jwe = * 'eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0.nyQ19eq9ogh9wA7fFtnI2oouzy5_8b5DeLkoRMfi2yijgfTs2zEnayCEofz_qhnL-nwszabd9qUeHv0-IwvhhJJS7GUJOU3ikiIe42qcIAFme1A_Fo9CTxw4XTOy-I5qanl8So91u6hwfyN1VxAqVLsSE7_23EC-gfGEg_5znew9PyXXsOIE-K_HH7IQowRrlZ1X_bM_Liu53RzDpLDvRz59mp3S8L56YqpM8FexFGTGpEaoTcEIst375qncYt3-79IVR7gZN1RWsWgjPatfvVbnh74PglQcATSf3UUhaW0OAKn6q7r3PDx6DIKQ35bgHQg5QopuN00eIfLQL2trGw.W3grIVj5HVuAb76X.6PcuDe5D6ttWFYyv0oqqdDXfI2R8wBg1F2Q80UUA_Gv8eEimNWfxIWdLxrjzgQGSvIhxmFKuLM0.a93_Ug3uZHuczj70Zavx8Q' * * const { plaintext, protectedHeader } = await jose.compactDecrypt(jwe, privateKey) * * console.log(protectedHeader) * console.log(new TextDecoder().decode(plaintext)) * ``` * * @param jwe Compact JWE. * @param key Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export declare function compactDecrypt(jwe: string | Uint8Array, key: KeyLike | Uint8Array, options?: DecryptOptions): Promise; /** * @param jwe Compact JWE. * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export declare function compactDecrypt(jwe: string | Uint8Array, getKey: CompactDecryptGetKey, options?: DecryptOptions): Promise; jose-4.11.4/dist/types/jwe/compact/encrypt.d.ts000066400000000000000000000045521437043056600213570ustar00rootroot00000000000000import type { KeyLike, JWEKeyManagementHeaderParameters, CompactJWEHeaderParameters, EncryptOptions } from '../../types'; /** * The CompactEncrypt class is a utility for creating Compact JWE strings. * * @example Usage * * ```js * const jwe = await new jose.CompactEncrypt( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM' }) * .encrypt(publicKey) * * console.log(jwe) * ``` */ export declare class CompactEncrypt { private _flattened; /** @param plaintext Binary representation of the plaintext to encrypt. */ constructor(plaintext: Uint8Array); /** * Sets a content encryption key to use, by default a random suitable one is generated for the JWE * enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param cek JWE Content Encryption Key. */ setContentEncryptionKey(cek: Uint8Array): this; /** * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param iv JWE Initialization Vector. */ setInitializationVector(iv: Uint8Array): this; /** * Sets the JWE Protected Header on the CompactEncrypt object. * * @param protectedHeader JWE Protected Header object. */ setProtectedHeader(protectedHeader: CompactJWEHeaderParameters): this; /** * Sets the JWE Key Management parameters to be used when encrypting the Content Encryption Key. * You do not need to invoke this method, it is only really intended for test and vector * validation purposes. * * @param parameters JWE Key Management parameters. */ setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters): this; /** * Encrypts and resolves the value of the Compact JWE string. * * @param key Public Key or Secret to encrypt the JWE with. * @param options JWE Encryption options. */ encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions): Promise; } jose-4.11.4/dist/types/jwe/flattened/000077500000000000000000000000001437043056600174135ustar00rootroot00000000000000jose-4.11.4/dist/types/jwe/flattened/decrypt.d.ts000066400000000000000000000040321437043056600216560ustar00rootroot00000000000000import type { FlattenedDecryptResult, KeyLike, FlattenedJWE, JWEHeaderParameters, DecryptOptions, GetKeyFunction, ResolvedKey } from '../../types'; /** * Interface for Flattened JWE Decryption dynamic key resolution. No token components have been * verified at the time of this function call. */ export interface FlattenedDecryptGetKey extends GetKeyFunction { } /** * Decrypts a Flattened JWE. * * @example Usage * * ```js * const jwe = { * ciphertext: '9EzjFISUyoG-ifC2mSihfP0DPC80yeyrxhTzKt1C_VJBkxeBG0MI4Te61Pk45RAGubUvBpU9jm4', * iv: '8Fy7A_IuoX5VXG9s', * tag: 'W76IYV6arGRuDSaSyWrQNg', * encrypted_key: * 'Z6eD4UK_yFb5ZoKvKkGAdqywEG_m0e4IYo0x8Vf30LAMJcsc-_zSgIeiF82teZyYi2YYduHKoqImk7MRnoPZOlEs0Q5BNK1OgBmSOhCE8DFyqh9Zh48TCTP6lmBQ52naqoUJFMtHzu-0LwZH26hxos0GP3Dt19O379MJB837TdKKa87skq0zHaVLAquRHOBF77GI54Bc7O49d8aOrSu1VEFGMThlW2caspPRiTSePDMDPq7_WGk50izRhB3Asl9wmP9wEeaTrkJKRnQj5ips1SAZ1hDBsqEQKKukxP1HtdcopHV5_qgwU8Hjm5EwSLMluMQuiE6hwlkXGOujZLVizA', * aad: 'VGhlIEZlbGxvd3NoaXAgb2YgdGhlIFJpbmc', * protected: 'eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0', * } * * const { plaintext, protectedHeader, additionalAuthenticatedData } = * await jose.flattenedDecrypt(jwe, privateKey) * * console.log(protectedHeader) * const decoder = new TextDecoder() * console.log(decoder.decode(plaintext)) * console.log(decoder.decode(additionalAuthenticatedData)) * ``` * * @param jwe Flattened JWE. * @param key Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export declare function flattenedDecrypt(jwe: FlattenedJWE, key: KeyLike | Uint8Array, options?: DecryptOptions): Promise; /** * @param jwe Flattened JWE. * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export declare function flattenedDecrypt(jwe: FlattenedJWE, getKey: FlattenedDecryptGetKey, options?: DecryptOptions): Promise; jose-4.11.4/dist/types/jwe/flattened/encrypt.d.ts000066400000000000000000000067601437043056600217020ustar00rootroot00000000000000import type { KeyLike, FlattenedJWE, JWEHeaderParameters, JWEKeyManagementHeaderParameters, EncryptOptions } from '../../types'; /** @private */ export declare const unprotected: unique symbol; /** * The FlattenedEncrypt class is a utility for creating Flattened JWE objects. * * @example Usage * * ```js * const jwe = await new jose.FlattenedEncrypt( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM' }) * .setAdditionalAuthenticatedData(encoder.encode('The Fellowship of the Ring')) * .encrypt(publicKey) * * console.log(jwe) * ``` */ export declare class FlattenedEncrypt { private _plaintext; private _protectedHeader; private _sharedUnprotectedHeader; private _unprotectedHeader; private _aad; private _cek; private _iv; private _keyManagementParameters; /** @param plaintext Binary representation of the plaintext to encrypt. */ constructor(plaintext: Uint8Array); /** * Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is * really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or * Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed * and missing. * * @param parameters JWE Key Management parameters. */ setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters): this; /** * Sets the JWE Protected Header on the FlattenedEncrypt object. * * @param protectedHeader JWE Protected Header. */ setProtectedHeader(protectedHeader: JWEHeaderParameters): this; /** * Sets the JWE Shared Unprotected Header on the FlattenedEncrypt object. * * @param sharedUnprotectedHeader JWE Shared Unprotected Header. */ setSharedUnprotectedHeader(sharedUnprotectedHeader: JWEHeaderParameters): this; /** * Sets the JWE Per-Recipient Unprotected Header on the FlattenedEncrypt object. * * @param unprotectedHeader JWE Per-Recipient Unprotected Header. */ setUnprotectedHeader(unprotectedHeader: JWEHeaderParameters): this; /** * Sets the Additional Authenticated Data on the FlattenedEncrypt object. * * @param aad Additional Authenticated Data. */ setAdditionalAuthenticatedData(aad: Uint8Array): this; /** * Sets a content encryption key to use, by default a random suitable one is generated for the JWE * enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param cek JWE Content Encryption Key. */ setContentEncryptionKey(cek: Uint8Array): this; /** * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param iv JWE Initialization Vector. */ setInitializationVector(iv: Uint8Array): this; /** * Encrypts and resolves the value of the Flattened JWE object. * * @param key Public Key or Secret to encrypt the JWE with. * @param options JWE Encryption options. */ encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions): Promise; } jose-4.11.4/dist/types/jwe/general/000077500000000000000000000000001437043056600170625ustar00rootroot00000000000000jose-4.11.4/dist/types/jwe/general/decrypt.d.ts000066400000000000000000000040641437043056600213320ustar00rootroot00000000000000import type { KeyLike, DecryptOptions, JWEHeaderParameters, GetKeyFunction, FlattenedJWE, GeneralJWE, GeneralDecryptResult, ResolvedKey } from '../../types'; /** * Interface for General JWE Decryption dynamic key resolution. No token components have been * verified at the time of this function call. */ export interface GeneralDecryptGetKey extends GetKeyFunction { } /** * Decrypts a General JWE. * * @example Usage * * ```js * const jwe = { * ciphertext: '9EzjFISUyoG-ifC2mSihfP0DPC80yeyrxhTzKt1C_VJBkxeBG0MI4Te61Pk45RAGubUvBpU9jm4', * iv: '8Fy7A_IuoX5VXG9s', * tag: 'W76IYV6arGRuDSaSyWrQNg', * aad: 'VGhlIEZlbGxvd3NoaXAgb2YgdGhlIFJpbmc', * protected: 'eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0', * recipients: [ * { * encrypted_key: * 'Z6eD4UK_yFb5ZoKvKkGAdqywEG_m0e4IYo0x8Vf30LAMJcsc-_zSgIeiF82teZyYi2YYduHKoqImk7MRnoPZOlEs0Q5BNK1OgBmSOhCE8DFyqh9Zh48TCTP6lmBQ52naqoUJFMtHzu-0LwZH26hxos0GP3Dt19O379MJB837TdKKa87skq0zHaVLAquRHOBF77GI54Bc7O49d8aOrSu1VEFGMThlW2caspPRiTSePDMDPq7_WGk50izRhB3Asl9wmP9wEeaTrkJKRnQj5ips1SAZ1hDBsqEQKKukxP1HtdcopHV5_qgwU8Hjm5EwSLMluMQuiE6hwlkXGOujZLVizA', * }, * ], * } * * const { plaintext, protectedHeader, additionalAuthenticatedData } = * await jose.generalDecrypt(jwe, privateKey) * * console.log(protectedHeader) * const decoder = new TextDecoder() * console.log(decoder.decode(plaintext)) * console.log(decoder.decode(additionalAuthenticatedData)) * ``` * * @param jwe General JWE. * @param key Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export declare function generalDecrypt(jwe: GeneralJWE, key: KeyLike | Uint8Array, options?: DecryptOptions): Promise; /** * @param jwe General JWE. * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export declare function generalDecrypt(jwe: GeneralJWE, getKey: GeneralDecryptGetKey, options?: DecryptOptions): Promise; jose-4.11.4/dist/types/jwe/general/encrypt.d.ts000066400000000000000000000053551437043056600213500ustar00rootroot00000000000000import type { KeyLike, GeneralJWE, JWEHeaderParameters, CritOption, DeflateOption } from '../../types'; export interface Recipient { /** * Sets the JWE Per-Recipient Unprotected Header on the Recipient object. * * @param unprotectedHeader JWE Per-Recipient Unprotected Header. */ setUnprotectedHeader(unprotectedHeader: JWEHeaderParameters): Recipient; /** A shorthand for calling addRecipient() on the enclosing GeneralEncrypt instance */ addRecipient(...args: Parameters): Recipient; /** A shorthand for calling encrypt() on the enclosing GeneralEncrypt instance */ encrypt(...args: Parameters): Promise; /** Returns the enclosing GeneralEncrypt */ done(): GeneralEncrypt; } /** * The GeneralEncrypt class is a utility for creating General JWE objects. * * @example Usage * * ```js * const jwe = await new jose.GeneralEncrypt( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .setProtectedHeader({ enc: 'A256GCM' }) * .addRecipient(ecPublicKey) * .setUnprotectedHeader({ alg: 'ECDH-ES+A256KW' }) * .addRecipient(rsaPublicKey) * .setUnprotectedHeader({ alg: 'RSA-OAEP-384' }) * .encrypt() * * console.log(jwe) * ``` */ export declare class GeneralEncrypt { private _plaintext; private _recipients; private _protectedHeader; private _unprotectedHeader; private _aad; /** @param plaintext Binary representation of the plaintext to encrypt. */ constructor(plaintext: Uint8Array); /** * Adds an additional recipient for the General JWE object. * * @param key Public Key or Secret to encrypt the Content Encryption Key for the recipient with. * @param options JWE Encryption options. */ addRecipient(key: KeyLike | Uint8Array, options?: CritOption): Recipient; /** * Sets the JWE Protected Header on the GeneralEncrypt object. * * @param protectedHeader JWE Protected Header object. */ setProtectedHeader(protectedHeader: JWEHeaderParameters): this; /** * Sets the JWE Shared Unprotected Header on the GeneralEncrypt object. * * @param sharedUnprotectedHeader JWE Shared Unprotected Header object. */ setSharedUnprotectedHeader(sharedUnprotectedHeader: JWEHeaderParameters): this; /** * Sets the Additional Authenticated Data on the GeneralEncrypt object. * * @param aad Additional Authenticated Data. */ setAdditionalAuthenticatedData(aad: Uint8Array): this; /** * Encrypts and resolves the value of the General JWE object. * * @param options JWE Encryption options. */ encrypt(options?: DeflateOption): Promise; } jose-4.11.4/dist/types/jwk/000077500000000000000000000000001437043056600154535ustar00rootroot00000000000000jose-4.11.4/dist/types/jwk/embedded.d.ts000066400000000000000000000024151437043056600200000ustar00rootroot00000000000000import type { FlattenedJWSInput, JWSHeaderParameters } from '../types'; /** * EmbeddedJWK is an implementation of a GetKeyFunction intended to be used with the JWS/JWT verify * operations whenever you need to opt-in to verify signatures with a public key embedded in the * token's "jwk" (JSON Web Key) Header Parameter. It is recommended to combine this with the verify * function's `algorithms` option to define accepted JWS "alg" (Algorithm) Header Parameter values. * * @example Usage * * ```js * const jwt = * 'eyJqd2siOnsiY3J2IjoiUC0yNTYiLCJ4IjoiVU05ZzVuS25aWFlvdldBbE03NmNMejl2VG96UmpfX0NIVV9kT2wtZ09vRSIsInkiOiJkczhhZVF3MWwyY0RDQTdiQ2tPTnZ3REtwWEFidFhqdnFDbGVZSDhXc19VIiwia3R5IjoiRUMifSwiYWxnIjoiRVMyNTYifQ.eyJpc3MiOiJ1cm46ZXhhbXBsZTppc3N1ZXIiLCJhdWQiOiJ1cm46ZXhhbXBsZTphdWRpZW5jZSIsImlhdCI6MTYwNDU4MDc5NH0.60boak3_dErnW47ZPty1C0nrjeVq86EN_eK0GOq6K8w2OA0thKoBxFK4j-NuU9yZ_A9UKGxPT_G87DladBaV9g' * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, jose.EmbeddedJWK, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(protectedHeader) * console.log(payload) * ``` */ export declare function EmbeddedJWK(protectedHeader: JWSHeaderParameters, token: FlattenedJWSInput): Promise; jose-4.11.4/dist/types/jwk/thumbprint.d.ts000066400000000000000000000027671437043056600204550ustar00rootroot00000000000000import type { JWK } from '../types'; /** * Calculates a base64url-encoded JSON Web Key (JWK) Thumbprint * * @example Usage * * ```js * const thumbprint = await jose.calculateJwkThumbprint({ * kty: 'EC', * crv: 'P-256', * x: 'jJ6Flys3zK9jUhnOHf6G49Dyp5hah6CNP84-gY-n9eo', * y: 'nhI6iD5eFXgBTLt_1p3aip-5VbZeMhxeFSpjfEAf7Ww', * }) * * console.log(thumbprint) * // 'w9eYdC6_s_tLQ8lH6PUpc0mddazaqtPgeC2IgWDiqY8' * ``` * * @param jwk JSON Web Key. * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is * "sha256". * @see [RFC7638](https://www.rfc-editor.org/rfc/rfc7638) */ export declare function calculateJwkThumbprint(jwk: JWK, digestAlgorithm?: 'sha256' | 'sha384' | 'sha512'): Promise; /** * Calculates a JSON Web Key (JWK) Thumbprint URI * * @example Usage * * ```js * const thumbprintUri = await jose.calculateJwkThumbprintUri({ * kty: 'EC', * crv: 'P-256', * x: 'jJ6Flys3zK9jUhnOHf6G49Dyp5hah6CNP84-gY-n9eo', * y: 'nhI6iD5eFXgBTLt_1p3aip-5VbZeMhxeFSpjfEAf7Ww', * }) * * console.log(thumbprint) * // 'urn:ietf:params:oauth:jwk-thumbprint:sha-256:w9eYdC6_s_tLQ8lH6PUpc0mddazaqtPgeC2IgWDiqY8' * ``` * * @param jwk JSON Web Key. * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is * "sha256". * @see [RFC9278](https://www.rfc-editor.org/rfc/rfc9278) */ export declare function calculateJwkThumbprintUri(jwk: JWK, digestAlgorithm?: 'sha256' | 'sha384' | 'sha512'): Promise; jose-4.11.4/dist/types/jwks/000077500000000000000000000000001437043056600156365ustar00rootroot00000000000000jose-4.11.4/dist/types/jwks/local.d.ts000066400000000000000000000033521437043056600175250ustar00rootroot00000000000000import type { KeyLike, JWSHeaderParameters, JSONWebKeySet, FlattenedJWSInput, GetKeyFunction } from '../types'; /** @private */ export declare function isJWKSLike(jwks: unknown): jwks is JSONWebKeySet; /** @private */ export declare class LocalJWKSet { protected _jwks?: JSONWebKeySet; private _cached; constructor(jwks: unknown); getKey(protectedHeader: JWSHeaderParameters, token: FlattenedJWSInput): Promise; } /** * Returns a function that resolves to a key object from a locally stored, or otherwise available, * JSON Web Key Set. * * Only a single public key must match the selection process. * * @example Usage * * ```js * const JWKS = jose.createLocalJWKSet({ * keys: [ * { * kty: 'RSA', * e: 'AQAB', * n: '12oBZRhCiZFJLcPg59LkZZ9mdhSMTKAQZYq32k_ti5SBB6jerkh-WzOMAO664r_qyLkqHUSp3u5SbXtseZEpN3XPWGKSxjsy-1JyEFTdLSYe6f9gfrmxkUF_7DTpq0gn6rntP05g2-wFW50YO7mosfdslfrTJYWHFhJALabAeYirYD7-9kqq9ebfFMF4sRRELbv9oi36As6Q9B3Qb5_C1rAzqfao_PCsf9EPsTZsVVVkA5qoIAr47lo1ipfiBPxUCCNSdvkmDTYgvvRm6ZoMjFbvOtgyts55fXKdMWv7I9HMD5HwE9uW839PWA514qhbcIsXEYSFMPMV6fnlsiZvQQ', * alg: 'PS256', * }, * { * crv: 'P-256', * kty: 'EC', * x: 'ySK38C1jBdLwDsNWKzzBHqKYEE5Cgv-qjWvorUXk9fw', * y: '_LeQBw07cf5t57Iavn4j-BqJsAD1dpoz8gokd3sBsOo', * alg: 'ES256', * }, * ], * }) * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, JWKS, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * console.log(protectedHeader) * console.log(payload) * ``` * * @param jwks JSON Web Key Set formatted object. */ export declare function createLocalJWKSet(jwks: JSONWebKeySet): GetKeyFunction; jose-4.11.4/dist/types/jwks/remote.d.ts000066400000000000000000000045371437043056600177340ustar00rootroot00000000000000import type { JWSHeaderParameters, FlattenedJWSInput, GetKeyFunction } from '../types'; /** Options for the remote JSON Web Key Set. */ export interface RemoteJWKSetOptions { /** * Timeout (in milliseconds) for the HTTP request. When reached the request will be aborted and * the verification will fail. Default is 5000 (5 seconds). */ timeoutDuration?: number; /** * Duration (in milliseconds) for which no more HTTP requests will be triggered after a previous * successful fetch. Default is 30000 (30 seconds). */ cooldownDuration?: number; /** * Maximum time (in milliseconds) between successful HTTP requests. Default is 600000 (10 * minutes). */ cacheMaxAge?: number | typeof Infinity; /** * An instance of [http.Agent](https://nodejs.org/api/http.html#class-httpagent) or * [https.Agent](https://nodejs.org/api/https.html#class-httpsagent) to pass to the * [http.get](https://nodejs.org/api/http.html#httpgetoptions-callback) or * [https.get](https://nodejs.org/api/https.html#httpsgetoptions-callback) method's options. Use * when behind an http(s) proxy. This is a Node.js runtime specific option, it is ignored when * used outside of Node.js runtime. */ agent?: any; /** Optional headers to be sent with the HTTP request. */ headers?: Record; } /** * Returns a function that resolves to a key object downloaded from a remote endpoint returning a * JSON Web Key Set, that is, for example, an OAuth 2.0 or OIDC jwks_uri. Only a single public key * must match the selection process. The JSON Web Key Set is fetched when no key matches the * selection process but only as frequently as the `cooldownDuration` option allows, to prevent * abuse. * * @example Usage * * ```js * const JWKS = jose.createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs')) * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, JWKS, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * console.log(protectedHeader) * console.log(payload) * ``` * * @param url URL to fetch the JSON Web Key Set from. * @param options Options for the remote JSON Web Key Set. */ export declare function createRemoteJWKSet(url: URL, options?: RemoteJWKSetOptions): GetKeyFunction; jose-4.11.4/dist/types/jws/000077500000000000000000000000001437043056600154635ustar00rootroot00000000000000jose-4.11.4/dist/types/jws/compact/000077500000000000000000000000001437043056600171115ustar00rootroot00000000000000jose-4.11.4/dist/types/jws/compact/sign.d.ts000066400000000000000000000020641437043056600206450ustar00rootroot00000000000000import type { CompactJWSHeaderParameters, KeyLike, SignOptions } from '../../types'; /** * The CompactSign class is a utility for creating Compact JWS strings. * * @example Usage * * ```js * const jws = await new jose.CompactSign( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .setProtectedHeader({ alg: 'ES256' }) * .sign(privateKey) * * console.log(jws) * ``` */ export declare class CompactSign { private _flattened; /** @param payload Binary representation of the payload to sign. */ constructor(payload: Uint8Array); /** * Sets the JWS Protected Header on the Sign object. * * @param protectedHeader JWS Protected Header. */ setProtectedHeader(protectedHeader: CompactJWSHeaderParameters): this; /** * Signs and resolves the value of the Compact JWS string. * * @param key Private Key or Secret to sign the JWS with. * @param options JWS Sign options. */ sign(key: KeyLike | Uint8Array, options?: SignOptions): Promise; } jose-4.11.4/dist/types/jws/compact/verify.d.ts000066400000000000000000000031441437043056600212110ustar00rootroot00000000000000import type { CompactVerifyResult, FlattenedJWSInput, GetKeyFunction, CompactJWSHeaderParameters, KeyLike, VerifyOptions, ResolvedKey } from '../../types'; /** * Interface for Compact JWS Verification dynamic key resolution. No token components have been * verified at the time of this function call. * * See * [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) * to verify using a remote JSON Web Key Set. */ export interface CompactVerifyGetKey extends GetKeyFunction { } /** * Verifies the signature and format of and afterwards decodes the Compact JWS. * * @example Usage * * ```js * const jws = * 'eyJhbGciOiJFUzI1NiJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4.kkAs_gPPxWMI3rHuVlxHaTPfDWDoqdI8jSvuSmqV-8IHIWXg9mcAeC9ggV-45ZHRbiRJ3obUIFo1rHphPA5URg' * * const { payload, protectedHeader } = await jose.compactVerify(jws, publicKey) * * console.log(protectedHeader) * console.log(new TextDecoder().decode(payload)) * ``` * * @param jws Compact JWS. * @param key Key to verify the JWS with. * @param options JWS Verify options. */ export declare function compactVerify(jws: string | Uint8Array, key: KeyLike | Uint8Array, options?: VerifyOptions): Promise; /** * @param jws Compact JWS. * @param getKey Function resolving a key to verify the JWS with. * @param options JWS Verify options. */ export declare function compactVerify(jws: string | Uint8Array, getKey: CompactVerifyGetKey, options?: VerifyOptions): Promise; jose-4.11.4/dist/types/jws/flattened/000077500000000000000000000000001437043056600174315ustar00rootroot00000000000000jose-4.11.4/dist/types/jws/flattened/sign.d.ts000066400000000000000000000025441437043056600211700ustar00rootroot00000000000000import type { KeyLike, FlattenedJWS, JWSHeaderParameters, SignOptions } from '../../types'; /** * The FlattenedSign class is a utility for creating Flattened JWS objects. * * @example Usage * * ```js * const jws = await new jose.FlattenedSign( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .setProtectedHeader({ alg: 'ES256' }) * .sign(privateKey) * * console.log(jws) * ``` */ export declare class FlattenedSign { private _payload; private _protectedHeader; private _unprotectedHeader; /** @param payload Binary representation of the payload to sign. */ constructor(payload: Uint8Array); /** * Sets the JWS Protected Header on the FlattenedSign object. * * @param protectedHeader JWS Protected Header. */ setProtectedHeader(protectedHeader: JWSHeaderParameters): this; /** * Sets the JWS Unprotected Header on the FlattenedSign object. * * @param unprotectedHeader JWS Unprotected Header. */ setUnprotectedHeader(unprotectedHeader: JWSHeaderParameters): this; /** * Signs and resolves the value of the Flattened JWS object. * * @param key Private Key or Secret to sign the JWS with. * @param options JWS Sign options. */ sign(key: KeyLike | Uint8Array, options?: SignOptions): Promise; } jose-4.11.4/dist/types/jws/flattened/verify.d.ts000066400000000000000000000033171437043056600215330ustar00rootroot00000000000000import type { FlattenedVerifyResult, KeyLike, FlattenedJWSInput, JWSHeaderParameters, VerifyOptions, GetKeyFunction, ResolvedKey } from '../../types'; /** * Interface for Flattened JWS Verification dynamic key resolution. No token components have been * verified at the time of this function call. * * See * [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) * to verify using a remote JSON Web Key Set. */ export interface FlattenedVerifyGetKey extends GetKeyFunction { } /** * Verifies the signature and format of and afterwards decodes the Flattened JWS. * * @example Usage * * ```js * const decoder = new TextDecoder() * const jws = { * signature: * 'FVVOXwj6kD3DqdfD9yYqfT2W9jv-Nop4kOehp_DeDGNB5dQNSPRvntBY6xH3uxlCxE8na9d_kyhYOcanpDJ0EA', * payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4', * protected: 'eyJhbGciOiJFUzI1NiJ9', * } * * const { payload, protectedHeader } = await jose.flattenedVerify(jws, publicKey) * * console.log(protectedHeader) * console.log(decoder.decode(payload)) * ``` * * @param jws Flattened JWS. * @param key Key to verify the JWS with. * @param options JWS Verify options. */ export declare function flattenedVerify(jws: FlattenedJWSInput, key: KeyLike | Uint8Array, options?: VerifyOptions): Promise; /** * @param jws Flattened JWS. * @param getKey Function resolving a key to verify the JWS with. * @param options JWS Verify options. */ export declare function flattenedVerify(jws: FlattenedJWSInput, getKey: FlattenedVerifyGetKey, options?: VerifyOptions): Promise; jose-4.11.4/dist/types/jws/general/000077500000000000000000000000001437043056600171005ustar00rootroot00000000000000jose-4.11.4/dist/types/jws/general/sign.d.ts000066400000000000000000000036671437043056600206460ustar00rootroot00000000000000import type { KeyLike, GeneralJWS, JWSHeaderParameters, SignOptions } from '../../types'; export interface Signature { /** * Sets the JWS Protected Header on the Signature object. * * @param protectedHeader JWS Protected Header. */ setProtectedHeader(protectedHeader: JWSHeaderParameters): Signature; /** * Sets the JWS Unprotected Header on the Signature object. * * @param unprotectedHeader JWS Unprotected Header. */ setUnprotectedHeader(unprotectedHeader: JWSHeaderParameters): Signature; /** A shorthand for calling addSignature() on the enclosing GeneralSign instance */ addSignature(...args: Parameters): Signature; /** A shorthand for calling encrypt() on the enclosing GeneralSign instance */ sign(...args: Parameters): Promise; /** Returns the enclosing GeneralSign */ done(): GeneralSign; } /** * The GeneralSign class is a utility for creating General JWS objects. * * @example Usage * * ```js * const jws = await new jose.GeneralSign( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .addSignature(ecPrivateKey) * .setProtectedHeader({ alg: 'ES256' }) * .addSignature(rsaPrivateKey) * .setProtectedHeader({ alg: 'PS256' }) * .sign() * * console.log(jws) * ``` */ export declare class GeneralSign { private _payload; private _signatures; /** @param payload Binary representation of the payload to sign. */ constructor(payload: Uint8Array); /** * Adds an additional signature for the General JWS object. * * @param key Private Key or Secret to sign the individual JWS signature with. * @param options JWS Sign options. */ addSignature(key: KeyLike | Uint8Array, options?: SignOptions): Signature; /** Signs and resolves the value of the General JWS object. */ sign(): Promise; } jose-4.11.4/dist/types/jws/general/verify.d.ts000066400000000000000000000033271437043056600212030ustar00rootroot00000000000000import type { GeneralJWSInput, GeneralVerifyResult, FlattenedJWSInput, GetKeyFunction, JWSHeaderParameters, KeyLike, VerifyOptions, ResolvedKey } from '../../types'; /** * Interface for General JWS Verification dynamic key resolution. No token components have been * verified at the time of this function call. * * See * [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) * to verify using a remote JSON Web Key Set. */ export interface GeneralVerifyGetKey extends GetKeyFunction { } /** * Verifies the signature and format of and afterwards decodes the General JWS. * * @example Usage * * ```js * const jws = { * payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4', * signatures: [ * { * signature: * 'FVVOXwj6kD3DqdfD9yYqfT2W9jv-Nop4kOehp_DeDGNB5dQNSPRvntBY6xH3uxlCxE8na9d_kyhYOcanpDJ0EA', * protected: 'eyJhbGciOiJFUzI1NiJ9', * }, * ], * } * * const { payload, protectedHeader } = await jose.generalVerify(jws, publicKey) * * console.log(protectedHeader) * console.log(new TextDecoder().decode(payload)) * ``` * * @param jws General JWS. * @param key Key to verify the JWS with. * @param options JWS Verify options. */ export declare function generalVerify(jws: GeneralJWSInput, key: KeyLike | Uint8Array, options?: VerifyOptions): Promise; /** * @param jws General JWS. * @param getKey Function resolving a key to verify the JWS with. * @param options JWS Verify options. */ export declare function generalVerify(jws: GeneralJWSInput, getKey: GeneralVerifyGetKey, options?: VerifyOptions): Promise; jose-4.11.4/dist/types/jwt/000077500000000000000000000000001437043056600154645ustar00rootroot00000000000000jose-4.11.4/dist/types/jwt/decrypt.d.ts000066400000000000000000000040171437043056600177320ustar00rootroot00000000000000import type { KeyLike, DecryptOptions, JWTClaimVerificationOptions, GetKeyFunction, CompactJWEHeaderParameters, FlattenedJWE, JWTDecryptResult, ResolvedKey } from '../types'; /** Combination of JWE Decryption options and JWT Claims Set verification options. */ export interface JWTDecryptOptions extends DecryptOptions, JWTClaimVerificationOptions { } /** * Interface for JWT Decryption dynamic key resolution. No token components have been verified at * the time of this function call. */ export interface JWTDecryptGetKey extends GetKeyFunction { } /** * Verifies the JWT format (to be a JWE Compact format), decrypts the ciphertext, validates the JWT * Claims Set. * * @example Usage * * ```js * const secret = jose.base64url.decode('zH4NRP1HMALxxCFnRZABFA7GOJtzU_gIj02alfL1lvI') * const jwt = * 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..MB66qstZBPxAXKdsjet_lA.WHbtJTl4taHp7otOHLq3hBvv0yNPsPEKHYInmCPdDDeyV1kU-f-tGEiU4FxlSqkqAT2hVs8_wMNiQFAzPU1PUgIqWCPsBrPP3TtxYsrtwagpn4SvCsUsx0Mhw9ZhliAO8CLmCBQkqr_T9AcYsz5uZw.7nX9m7BGUu_u1p1qFHzyIg' * * const { payload, protectedHeader } = await jose.jwtDecrypt(jwt, secret, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(protectedHeader) * console.log(payload) * ``` * * @param jwt JSON Web Token value (encoded as JWE). * @param key Private Key or Secret to decrypt and verify the JWT with. * @param options JWT Decryption and JWT Claims Set validation options. */ export declare function jwtDecrypt(jwt: string | Uint8Array, key: KeyLike | Uint8Array, options?: JWTDecryptOptions): Promise; /** * @param jwt JSON Web Token value (encoded as JWE). * @param getKey Function resolving Private Key or Secret to decrypt and verify the JWT with. * @param options JWT Decryption and JWT Claims Set validation options. */ export declare function jwtDecrypt(jwt: string | Uint8Array, getKey: JWTDecryptGetKey, options?: JWTDecryptOptions): Promise; jose-4.11.4/dist/types/jwt/encrypt.d.ts000066400000000000000000000066661437043056600177600ustar00rootroot00000000000000import type { EncryptOptions, CompactJWEHeaderParameters, JWEKeyManagementHeaderParameters, KeyLike } from '../types'; import { ProduceJWT } from './produce'; /** * The EncryptJWT class is a utility for creating Compact JWE formatted JWT strings. * * @example Usage * * ```js * const secret = jose.base64url.decode('zH4NRP1HMALxxCFnRZABFA7GOJtzU_gIj02alfL1lvI') * const jwt = await new jose.EncryptJWT({ 'urn:example:claim': true }) * .setProtectedHeader({ alg: 'dir', enc: 'A128CBC-HS256' }) * .setIssuedAt() * .setIssuer('urn:example:issuer') * .setAudience('urn:example:audience') * .setExpirationTime('2h') * .encrypt(secret) * * console.log(jwt) * ``` */ export declare class EncryptJWT extends ProduceJWT { private _cek; private _iv; private _keyManagementParameters; private _protectedHeader; private _replicateIssuerAsHeader; private _replicateSubjectAsHeader; private _replicateAudienceAsHeader; /** * Sets the JWE Protected Header on the EncryptJWT object. * * @param protectedHeader JWE Protected Header. Must contain an "alg" (JWE Algorithm) and "enc" * (JWE Encryption Algorithm) properties. */ setProtectedHeader(protectedHeader: CompactJWEHeaderParameters): this; /** * Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is * really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or * Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed * and missing. * * @param parameters JWE Key Management parameters. */ setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters): this; /** * Sets a content encryption key to use, by default a random suitable one is generated for the JWE * enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param cek JWE Content Encryption Key. */ setContentEncryptionKey(cek: Uint8Array): this; /** * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param iv JWE Initialization Vector. */ setInitializationVector(iv: Uint8Array): this; /** * Replicates the "iss" (Issuer) Claim as a JWE Protected Header Parameter as per * [RFC7519#section-5.3](https://www.rfc-editor.org/rfc/rfc7519#section-5.3). */ replicateIssuerAsHeader(): this; /** * Replicates the "sub" (Subject) Claim as a JWE Protected Header Parameter as per * [RFC7519#section-5.3](https://www.rfc-editor.org/rfc/rfc7519#section-5.3). */ replicateSubjectAsHeader(): this; /** * Replicates the "aud" (Audience) Claim as a JWE Protected Header Parameter as per * [RFC7519#section-5.3](https://www.rfc-editor.org/rfc/rfc7519#section-5.3). */ replicateAudienceAsHeader(): this; /** * Encrypts and returns the JWT. * * @param key Public Key or Secret to encrypt the JWT with. * @param options JWE Encryption options. */ encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions): Promise; } jose-4.11.4/dist/types/jwt/produce.d.ts000066400000000000000000000035061437043056600177230ustar00rootroot00000000000000import type { JWTPayload } from '../types'; /** Generic class for JWT producing. */ export declare class ProduceJWT { protected _payload: JWTPayload; /** @param payload The JWT Claims Set object. */ constructor(payload: JWTPayload); /** * Set "iss" (Issuer) Claim. * * @param issuer "Issuer" Claim value to set on the JWT Claims Set. */ setIssuer(issuer: string): this; /** * Set "sub" (Subject) Claim. * * @param subject "sub" (Subject) Claim value to set on the JWT Claims Set. */ setSubject(subject: string): this; /** * Set "aud" (Audience) Claim. * * @param audience "aud" (Audience) Claim value to set on the JWT Claims Set. */ setAudience(audience: string | string[]): this; /** * Set "jti" (JWT ID) Claim. * * @param jwtId "jti" (JWT ID) Claim value to set on the JWT Claims Set. */ setJti(jwtId: string): this; /** * Set "nbf" (Not Before) Claim. * * @param input "nbf" (Not Before) Claim value to set on the JWT Claims Set. When number is passed * that is used as a value, when string is passed it is resolved to a time span and added to the * current timestamp. */ setNotBefore(input: number | string): this; /** * Set "exp" (Expiration Time) Claim. * * @param input "exp" (Expiration Time) Claim value to set on the JWT Claims Set. When number is * passed that is used as a value, when string is passed it is resolved to a time span and added * to the current timestamp. */ setExpirationTime(input: number | string): this; /** * Set "iat" (Issued At) Claim. * * @param input "iat" (Issued At) Claim value to set on the JWT Claims Set. Default is current * timestamp. */ setIssuedAt(input?: number): this; } jose-4.11.4/dist/types/jwt/sign.d.ts000066400000000000000000000127621437043056600172260ustar00rootroot00000000000000import type { JWTHeaderParameters, KeyLike, SignOptions } from '../types'; import { ProduceJWT } from './produce'; /** * The SignJWT class is a utility for creating Compact JWS formatted JWT strings. * * @example Usage with a symmetric secret * * ```js * const secret = new TextEncoder().encode( * 'cc7e0d44fd473002f1c42167459001140ec6389b7353f8088f4d9a95f2f596f2', * ) * const alg = 'HS256' * * const jwt = await new jose.SignJWT({ 'urn:example:claim': true }) * .setProtectedHeader({ alg }) * .setIssuedAt() * .setIssuer('urn:example:issuer') * .setAudience('urn:example:audience') * .setExpirationTime('2h') * .sign(secret) * * console.log(jwt) * ``` * * @example Usage with a private PKCS#8 encoded RSA key * * ```js * const alg = 'RS256' * const pkcs8 = `-----BEGIN PRIVATE KEY----- * MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDCFg4UrY5xtulv * /NXKmL1J4qI1SopAfTNMo3X7p+kJO7plqUYjzaztcre1qfh0m33Sm1Q8oPbO/GpP * MU1/HgcceytgJ/b4UwufVVMl9BrMDYG8moDBylbVupFQS3Ly1L9i/iFG9Z9A9xzY * Zzf799A45bnvNXL6s2glzvjiRvfQ2NDF0anTcnZLcYtC7ugq1IMM+ihAcPfw8Qw2 * chN/SmP4qAM+PKaQwagmU7doqmmyN9u38AfoYZ1GCFhEs5TBBT6H6h9YdHeVtiIq * 1c+fl03biSIfLrV7dUBD39gBmXBcL/30Ya3D82mCEUC4zg/UkOfQOmkmV3Lc8YUL * QZ8EJkBLAgMBAAECggEAVuVE/KEP6323WjpbBdAIv7HGahGrgGANvbxZsIhm34ls * VOPK0XDegZkhAybMZHjRhp+gwVxX5ChC+J3cUpOBH5FNxElgW6HizD2Jcq6t6LoL * YgPSrfEHm71iHg8JsgrqfUnGYFzMJmv88C6WdCtpgG/qJV1K00/Ly1G1QKoBffEs * +v4fAMJrCbUdCz1qWto+PU+HLMEo+krfEpGgcmtZeRlDADh8cETMQlgQfQX2VWq/ * aAP4a1SXmo+j0cvRU4W5Fj0RVwNesIpetX2ZFz4p/JmB5sWFEj/fC7h5z2lq+6Bm * e2T3BHtXkIxoBW0/pYVnASC8P2puO5FnVxDmWuHDYQKBgQDTuuBd3+0tSFVEX+DU * 5qpFmHm5nyGItZRJTS+71yg5pBxq1KqNCUjAtbxR0q//fwauakh+BwRVCPOrqsUG * jBSb3NYE70Srp6elqxgkE54PwQx4Mr6exJPnseM9U4K+hULllf5yjM9edreJE1nV * NVgFjeyafQhrHKwgr7PERJ/ikwKBgQDqqsT1M+EJLmI1HtCspOG6cu7q3gf/wKRh * E8tu84i3YyBnI8uJkKy92RNVI5fvpBARe3tjSdM25rr2rcrcmF/5g6Q9ImxZPGCt * 86eOgO9ErNtbc4TEgybsP319UE4O41aKeNiBTAZKoYCxv/dMqG0j4avmWzd+foHq * gSNUvR2maQKBgQCYeqOsV2B6VPY7KIVFLd0AA9/dwvEmgAYLiA/RShDI+hwQ/5jX * uxDu37KAhqeC65sHLrmIMUt4Zdr+DRyZK3aIDNEAesPMjw/X6lCXYp1ZISD2yyym * MFGH8X8CIkstI9Faf9vf6PJKSFrC1/HA7wq17VCwrUzLvrljTMW8meM/CwKBgCpo * 2leGHLFQFKeM/iF1WuYbR1pi7gcmhY6VyTowARFDdOOu8GXYI5/bz0afvCGvAMho * DJCREv7lC/zww6zCTPYG+HOj+PjXlJFba3ixjIxYwPvyEJiDK1Ge18sB7Fl8dHNq * C5ayaqCqN1voWYUdGzxU2IA1E/5kVo5O8FesJeOhAoGBAImJbZFf+D5kA32Xxhac * 59lLWBCsocvvbd1cvDMNlRywAAyhsCb1SuX4nEAK9mrSBdfmoF2Nm3eilfsOds0f * K5mX069IKG82CMqh3Mzptd7e7lyb9lsoGO0BAtjho3cWtha/UZ70vfaMzGuZ6JmQ * ak6k+8+UFd93M4z0Qo74OhXB * -----END PRIVATE KEY----` * const privateKey = await jose.importPKCS8(pkcs8, alg) * * const jwt = await new jose.SignJWT({ 'urn:example:claim': true }) * .setProtectedHeader({ alg }) * .setIssuedAt() * .setIssuer('urn:example:issuer') * .setAudience('urn:example:audience') * .setExpirationTime('2h') * .sign(privateKey) * * console.log(jwt) * ``` * * @example Usage with a private JWK encoded RSA key * * ```js * const alg = 'RS256' * const jwk = { * kty: 'RSA', * n: 'whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw', * e: 'AQAB', * d: 'VuVE_KEP6323WjpbBdAIv7HGahGrgGANvbxZsIhm34lsVOPK0XDegZkhAybMZHjRhp-gwVxX5ChC-J3cUpOBH5FNxElgW6HizD2Jcq6t6LoLYgPSrfEHm71iHg8JsgrqfUnGYFzMJmv88C6WdCtpgG_qJV1K00_Ly1G1QKoBffEs-v4fAMJrCbUdCz1qWto-PU-HLMEo-krfEpGgcmtZeRlDADh8cETMQlgQfQX2VWq_aAP4a1SXmo-j0cvRU4W5Fj0RVwNesIpetX2ZFz4p_JmB5sWFEj_fC7h5z2lq-6Bme2T3BHtXkIxoBW0_pYVnASC8P2puO5FnVxDmWuHDYQ', * p: '07rgXd_tLUhVRF_g1OaqRZh5uZ8hiLWUSU0vu9coOaQcatSqjQlIwLW8UdKv_38GrmpIfgcEVQjzq6rFBowUm9zWBO9Eq6enpasYJBOeD8EMeDK-nsST57HjPVOCvoVC5ZX-cozPXna3iRNZ1TVYBY3smn0IaxysIK-zxESf4pM', * q: '6qrE9TPhCS5iNR7QrKThunLu6t4H_8CkYRPLbvOIt2MgZyPLiZCsvdkTVSOX76QQEXt7Y0nTNua69q3K3Jhf-YOkPSJsWTxgrfOnjoDvRKzbW3OExIMm7D99fVBODuNWinjYgUwGSqGAsb_3TKhtI-Gr5ls3fn6B6oEjVL0dpmk', * dp: 'mHqjrFdgelT2OyiFRS3dAAPf3cLxJoAGC4gP0UoQyPocEP-Y17sQ7t-ygIanguubBy65iDFLeGXa_g0cmSt2iAzRAHrDzI8P1-pQl2KdWSEg9ssspjBRh_F_AiJLLSPRWn_b3-jySkhawtfxwO8Kte1QsK1My765Y0zFvJnjPws', * dq: 'KmjaV4YcsVAUp4z-IXVa5htHWmLuByaFjpXJOjABEUN0467wZdgjn9vPRp-8Ia8AyGgMkJES_uUL_PDDrMJM9gb4c6P4-NeUkVtreLGMjFjA-_IQmIMrUZ7XywHsWXx0c2oLlrJqoKo3W-hZhR0bPFTYgDUT_mRWjk7wV6wl46E', * qi: 'iYltkV_4PmQDfZfGFpzn2UtYEKyhy-9t3Vy8Mw2VHLAADKGwJvVK5ficQAr2atIF1-agXY2bd6KV-w52zR8rmZfTr0gobzYIyqHczOm13t7uXJv2WygY7QEC2OGjdxa2Fr9RnvS99ozMa5nomZBqTqT7z5QV33czjPRCjvg6FcE', * } * const privateKey = await jose.importJWK(jwk, alg) * * const jwt = await new jose.SignJWT({ 'urn:example:claim': true }) * .setProtectedHeader({ alg }) * .setIssuedAt() * .setIssuer('urn:example:issuer') * .setAudience('urn:example:audience') * .setExpirationTime('2h') * .sign(privateKey) * * console.log(jwt) * ``` */ export declare class SignJWT extends ProduceJWT { private _protectedHeader; /** * Sets the JWS Protected Header on the SignJWT object. * * @param protectedHeader JWS Protected Header. Must contain an "alg" (JWS Algorithm) property. */ setProtectedHeader(protectedHeader: JWTHeaderParameters): this; /** * Signs and returns the JWT. * * @param key Private Key or Secret to sign the JWT with. * @param options JWT Sign options. */ sign(key: KeyLike | Uint8Array, options?: SignOptions): Promise; } jose-4.11.4/dist/types/jwt/unsecured.d.ts000066400000000000000000000022631437043056600202560ustar00rootroot00000000000000import type { JWSHeaderParameters, JWTClaimVerificationOptions, JWTPayload } from '../types'; import { ProduceJWT } from './produce'; export interface UnsecuredResult { payload: JWTPayload; header: JWSHeaderParameters; } /** * The UnsecuredJWT class is a utility for dealing with `{ "alg": "none" }` Unsecured JWTs. * * @example Encoding * * ```js * const unsecuredJwt = new jose.UnsecuredJWT({ 'urn:example:claim': true }) * .setIssuedAt() * .setIssuer('urn:example:issuer') * .setAudience('urn:example:audience') * .setExpirationTime('2h') * .encode() * * console.log(unsecuredJwt) * ``` * * @example Decoding * * ```js * const payload = jose.UnsecuredJWT.decode(jwt, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(payload) * ``` */ export declare class UnsecuredJWT extends ProduceJWT { /** Encodes the Unsecured JWT. */ encode(): string; /** * Decodes an unsecured JWT. * * @param jwt Unsecured JWT to decode the payload of. * @param options JWT Claims Set validation options. */ static decode(jwt: string, options?: JWTClaimVerificationOptions): UnsecuredResult; } jose-4.11.4/dist/types/jwt/verify.d.ts000066400000000000000000000121771437043056600175720ustar00rootroot00000000000000import type { KeyLike, VerifyOptions, JWTClaimVerificationOptions, JWTHeaderParameters, GetKeyFunction, FlattenedJWSInput, JWTVerifyResult, ResolvedKey } from '../types'; /** Combination of JWS Verification options and JWT Claims Set verification options. */ export interface JWTVerifyOptions extends VerifyOptions, JWTClaimVerificationOptions { } /** * Interface for JWT Verification dynamic key resolution. No token components have been verified at * the time of this function call. * * See * [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) * to verify using a remote JSON Web Key Set. */ export interface JWTVerifyGetKey extends GetKeyFunction { } /** * Verifies the JWT format (to be a JWS Compact format), verifies the JWS signature, validates the * JWT Claims Set. * * @example Usage with a symmetric secret * * ```js * const secret = new TextEncoder().encode( * 'cc7e0d44fd473002f1c42167459001140ec6389b7353f8088f4d9a95f2f596f2', * ) * const jwt = * 'eyJhbGciOiJIUzI1NiJ9.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6dHJ1ZSwiaWF0IjoxNjY5MDU2MjMxLCJpc3MiOiJ1cm46ZXhhbXBsZTppc3N1ZXIiLCJhdWQiOiJ1cm46ZXhhbXBsZTphdWRpZW5jZSJ9.C4iSlLfAUMBq--wnC6VqD9gEOhwpRZpoRarE0m7KEnI' * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, secret, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(protectedHeader) * console.log(payload) * ``` * * @example Usage with a public SPKI encoded RSA key * * ```js * const alg = 'RS256' * const spki = `-----BEGIN PUBLIC KEY----- * MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwhYOFK2Ocbbpb/zVypi9 * SeKiNUqKQH0zTKN1+6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4H * HHsrYCf2+FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS/Yv4hRvWfQPcc2Gc3+/fQ * OOW57zVy+rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj * +KgDPjymkMGoJlO3aKppsjfbt/AH6GGdRghYRLOUwQU+h+ofWHR3lbYiKtXPn5dN * 24kiHy61e3VAQ9/YAZlwXC/99GGtw/NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZA * SwIDAQAB * -----END PUBLIC KEY-----` * const publicKey = await jose.importSPKI(spki, alg) * const jwt = * 'eyJhbGciOiJSUzI1NiJ9.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6dHJ1ZSwiaWF0IjoxNjY5MDU2NDg4LCJpc3MiOiJ1cm46ZXhhbXBsZTppc3N1ZXIiLCJhdWQiOiJ1cm46ZXhhbXBsZTphdWRpZW5jZSJ9.gXrPZ3yM_60dMXGE69dusbpzYASNA-XIOwsb5D5xYnSxyj6_D6OR_uR_1vqhUm4AxZxcrH1_-XJAve9HCw8az_QzHcN-nETt-v6stCsYrn6Bv1YOc-mSJRZ8ll57KVqLbCIbjKwerNX5r2_Qg2TwmJzQdRs-AQDhy-s_DlJd8ql6wR4n-kDZpar-pwIvz4fFIN0Fj57SXpAbLrV6Eo4Byzl0xFD8qEYEpBwjrMMfxCZXTlAVhAq6KCoGlDTwWuExps342-0UErEtyIqDnDGcrfNWiUsoo8j-29IpKd-w9-C388u-ChCxoHz--H8WmMSZzx3zTXsZ5lXLZ9IKfanDKg' * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, publicKey, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(protectedHeader) * console.log(payload) * ``` * * @example Usage with a public JWK encoded RSA key * * ```js * const alg = 'RS256' * const jwk = { * kty: 'RSA', * n: 'whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw', * e: 'AQAB', * } * const publicKey = await jose.importJWK(jwk, alg) * const jwt = * 'eyJhbGciOiJSUzI1NiJ9.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6dHJ1ZSwiaWF0IjoxNjY5MDU2NDg4LCJpc3MiOiJ1cm46ZXhhbXBsZTppc3N1ZXIiLCJhdWQiOiJ1cm46ZXhhbXBsZTphdWRpZW5jZSJ9.gXrPZ3yM_60dMXGE69dusbpzYASNA-XIOwsb5D5xYnSxyj6_D6OR_uR_1vqhUm4AxZxcrH1_-XJAve9HCw8az_QzHcN-nETt-v6stCsYrn6Bv1YOc-mSJRZ8ll57KVqLbCIbjKwerNX5r2_Qg2TwmJzQdRs-AQDhy-s_DlJd8ql6wR4n-kDZpar-pwIvz4fFIN0Fj57SXpAbLrV6Eo4Byzl0xFD8qEYEpBwjrMMfxCZXTlAVhAq6KCoGlDTwWuExps342-0UErEtyIqDnDGcrfNWiUsoo8j-29IpKd-w9-C388u-ChCxoHz--H8WmMSZzx3zTXsZ5lXLZ9IKfanDKg' * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, publicKey, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(protectedHeader) * console.log(payload) * ``` * * @param jwt JSON Web Token value (encoded as JWS). * @param key Key to verify the JWT with. * @param options JWT Decryption and JWT Claims Set validation options. */ export declare function jwtVerify(jwt: string | Uint8Array, key: KeyLike | Uint8Array, options?: JWTVerifyOptions): Promise; /** * @example Usage with a public JSON Web Key Set hosted on a remote URL * * ```js * const JWKS = jose.createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs')) * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, JWKS, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * console.log(protectedHeader) * console.log(payload) * ``` * * @param jwt JSON Web Token value (encoded as JWS). * @param getKey Function resolving a key to verify the JWT with. * @param options JWT Decryption and JWT Claims Set validation options. */ export declare function jwtVerify(jwt: string | Uint8Array, getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): Promise; jose-4.11.4/dist/types/key/000077500000000000000000000000001437043056600154505ustar00rootroot00000000000000jose-4.11.4/dist/types/key/export.d.ts000066400000000000000000000023631437043056600175670ustar00rootroot00000000000000import type { JWK, KeyLike } from '../types'; /** * Exports a runtime-specific public key representation (KeyObject or CryptoKey) to a PEM-encoded * SPKI string format. * * @example Usage * * ```js * const spkiPem = await jose.exportSPKI(publicKey) * * console.log(spkiPem) * ``` * * @param key Key representation to transform to a PEM-encoded SPKI string format. */ export declare function exportSPKI(key: KeyLike): Promise; /** * Exports a runtime-specific private key representation (KeyObject or CryptoKey) to a PEM-encoded * PKCS8 string format. * * @example Usage * * ```js * const pkcs8Pem = await jose.exportPKCS8(privateKey) * * console.log(pkcs8Pem) * ``` * * @param key Key representation to transform to a PEM-encoded PKCS8 string format. */ export declare function exportPKCS8(key: KeyLike): Promise; /** * Exports a runtime-specific key representation (KeyLike) to a JWK. * * @example Usage * * ```js * const privateJwk = await jose.exportJWK(privateKey) * const publicJwk = await jose.exportJWK(publicKey) * * console.log(privateJwk) * console.log(publicJwk) * ``` * * @param key Key representation to export as JWK. */ export declare function exportJWK(key: KeyLike | Uint8Array): Promise; jose-4.11.4/dist/types/key/generate_key_pair.d.ts000066400000000000000000000033201437043056600217150ustar00rootroot00000000000000import type { KeyLike } from '../types'; export interface GenerateKeyPairResult { /** The generated Private Key. */ privateKey: KeyLike; /** Public Key corresponding to the generated Private Key. */ publicKey: KeyLike; } export interface GenerateKeyPairOptions { /** * The EC "crv" (Curve) or OKP "crv" (Subtype of Key Pair) value to generate. The curve must be * both supported on the runtime as well as applicable for the given JWA algorithm identifier. */ crv?: string; /** * A hint for RSA algorithms to generate an RSA key of a given `modulusLength` (Key size in bits). * JOSE requires 2048 bits or larger. Default is 2048. */ modulusLength?: number; /** * (Web Cryptography API specific) The value to use as * [SubtleCrypto.generateKey()](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey) * `extractable` argument. Default is false. */ extractable?: boolean; } /** * Generates a private and a public key for a given JWA algorithm identifier. This can only generate * asymmetric key pairs. For symmetric secrets use the `generateSecret` function. * * Note: Under Web Cryptography API runtime the `privateKey` is generated with `extractable` set to * `false` by default. * * @example Usage * * ```js * const { publicKey, privateKey } = await jose.generateKeyPair('PS256') * console.log(publicKey) * console.log(privateKey) * ``` * * @param alg JWA Algorithm Identifier to be used with the generated key pair. * @param options Additional options passed down to the key pair generation. */ export declare function generateKeyPair(alg: string, options?: GenerateKeyPairOptions): Promise; jose-4.11.4/dist/types/key/generate_secret.d.ts000066400000000000000000000016541437043056600214070ustar00rootroot00000000000000import type { KeyLike } from '../types'; export interface GenerateSecretOptions { /** * (Web Cryptography API specific) The value to use as * [SubtleCrypto.generateKey()](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey) * `extractable` argument. Default is false. */ extractable?: boolean; } /** * Generates a symmetric secret key for a given JWA algorithm identifier. * * Note: Under Web Cryptography API runtime the secret key is generated with `extractable` set to * `false` by default. * * @example Usage * * ```js * const secret = await jose.generateSecret('HS256') * console.log(secret) * ``` * * @param alg JWA Algorithm Identifier to be used with the generated secret. * @param options Additional options passed down to the secret generation. */ export declare function generateSecret(alg: string, options?: GenerateSecretOptions): Promise; jose-4.11.4/dist/types/key/import.d.ts000066400000000000000000000115651437043056600175640ustar00rootroot00000000000000import type { JWK, KeyLike } from '../types'; export interface PEMImportOptions { /** * (Web Cryptography API specific) The value to use as * [SubtleCrypto.importKey()](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey) * `extractable` argument. Default is false. */ extractable?: boolean; } /** * Imports a PEM-encoded SPKI string as a runtime-specific public key representation (KeyObject or * CryptoKey). See [Algorithm Key Requirements](https://github.com/panva/jose/issues/210) to learn * about key to algorithm requirements and mapping. * * @example Usage * * ```js * const algorithm = 'ES256' * const spki = `-----BEGIN PUBLIC KEY----- * MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFlHHWfLk0gLBbsLTcuCrbCqoHqmM * YJepMC+Q+Dd6RBmBiA41evUsNMwLeN+PNFqib+xwi9JkJ8qhZkq8Y/IzGg== * -----END PUBLIC KEY-----` * const ecPublicKey = await jose.importSPKI(spki, algorithm) * ``` * * @param pem PEM-encoded SPKI string * @param alg JSON Web Algorithm identifier to be used with the imported key. */ export declare function importSPKI(spki: string, alg: string, options?: PEMImportOptions): Promise; /** * Imports the SPKI from an X.509 string certificate as a runtime-specific public key representation * (KeyObject or CryptoKey). See [Algorithm Key * Requirements](https://github.com/panva/jose/issues/210) to learn about key to algorithm * requirements and mapping. * * @example Usage * * ```js * const algorithm = 'ES256' * const x509 = `-----BEGIN CERTIFICATE----- * MIIBXjCCAQSgAwIBAgIGAXvykuMKMAoGCCqGSM49BAMCMDYxNDAyBgNVBAMMK3Np * QXBNOXpBdk1VaXhXVWVGaGtjZXg1NjJRRzFyQUhXaV96UlFQTVpQaG8wHhcNMjEw * OTE3MDcwNTE3WhcNMjIwNzE0MDcwNTE3WjA2MTQwMgYDVQQDDCtzaUFwTTl6QXZN * VWl4V1VlRmhrY2V4NTYyUUcxckFIV2lfelJRUE1aUGhvMFkwEwYHKoZIzj0CAQYI * KoZIzj0DAQcDQgAE8PbPvCv5D5xBFHEZlBp/q5OEUymq7RIgWIi7tkl9aGSpYE35 * UH+kBKDnphJO3odpPZ5gvgKs2nwRWcrDnUjYLDAKBggqhkjOPQQDAgNIADBFAiEA * 1yyMTRe66MhEXID9+uVub7woMkNYd0LhSHwKSPMUUTkCIFQGsfm1ecXOpeGOufAh * v+A1QWZMuTWqYt+uh/YSRNDn * -----END CERTIFICATE-----` * const ecPublicKey = await jose.importX509(x509, algorithm) * ``` * * @param pem X.509 certificate string * @param alg JSON Web Algorithm identifier to be used with the imported key. */ export declare function importX509(x509: string, alg: string, options?: PEMImportOptions): Promise; /** * Imports a PEM-encoded PKCS#8 string as a runtime-specific private key representation (KeyObject * or CryptoKey). See [Algorithm Key Requirements](https://github.com/panva/jose/issues/210) to * learn about key to algorithm requirements and mapping. Encrypted keys are not supported. * * @example Usage * * ```js * const algorithm = 'ES256' * const pkcs8 = `-----BEGIN PRIVATE KEY----- * MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgiyvo0X+VQ0yIrOaN * nlrnUclopnvuuMfoc8HHly3505OhRANCAAQWUcdZ8uTSAsFuwtNy4KtsKqgeqYxg * l6kwL5D4N3pEGYGIDjV69Sw0zAt43480WqJv7HCL0mQnyqFmSrxj8jMa * -----END PRIVATE KEY-----` * const ecPrivateKey = await jose.importPKCS8(pkcs8, algorithm) * ``` * * @param pem PEM-encoded PKCS#8 string * @param alg JSON Web Algorithm identifier to be used with the imported key. */ export declare function importPKCS8(pkcs8: string, alg: string, options?: PEMImportOptions): Promise; /** * Imports a JWK to a runtime-specific key representation (KeyLike). Either JWK "alg" (Algorithm) * Parameter must be present or the optional "alg" argument. When running on a runtime using [Web * Cryptography API](https://www.w3.org/TR/WebCryptoAPI/) the jwk parameters "use", "key_ops", and * "ext" are also used in the resulting `CryptoKey`. See [Algorithm Key * Requirements](https://github.com/panva/jose/issues/210) to learn about key to algorithm * requirements and mapping. * * @example Usage * * ```js * const ecPublicKey = await jose.importJWK( * { * crv: 'P-256', * kty: 'EC', * x: 'ySK38C1jBdLwDsNWKzzBHqKYEE5Cgv-qjWvorUXk9fw', * y: '_LeQBw07cf5t57Iavn4j-BqJsAD1dpoz8gokd3sBsOo', * }, * 'ES256', * ) * * const rsaPublicKey = await jose.importJWK( * { * kty: 'RSA', * e: 'AQAB', * n: '12oBZRhCiZFJLcPg59LkZZ9mdhSMTKAQZYq32k_ti5SBB6jerkh-WzOMAO664r_qyLkqHUSp3u5SbXtseZEpN3XPWGKSxjsy-1JyEFTdLSYe6f9gfrmxkUF_7DTpq0gn6rntP05g2-wFW50YO7mosfdslfrTJYWHFhJALabAeYirYD7-9kqq9ebfFMF4sRRELbv9oi36As6Q9B3Qb5_C1rAzqfao_PCsf9EPsTZsVVVkA5qoIAr47lo1ipfiBPxUCCNSdvkmDTYgvvRm6ZoMjFbvOtgyts55fXKdMWv7I9HMD5HwE9uW839PWA514qhbcIsXEYSFMPMV6fnlsiZvQQ', * }, * 'PS256', * ) * ``` * * @param jwk JSON Web Key. * @param alg JSON Web Algorithm identifier to be used with the imported key. Default is the "alg" * property on the JWK. * @param octAsKeyObject Forces a symmetric key to be imported to a KeyObject or CryptoKey. Default * is true unless JWK "ext" (Extractable) is true. */ export declare function importJWK(jwk: JWK, alg?: string, octAsKeyObject?: boolean): Promise; jose-4.11.4/dist/types/types.d.ts000066400000000000000000000500711437043056600166210ustar00rootroot00000000000000/** * KeyLike are runtime-specific classes representing asymmetric keys or symmetric secrets. These are * instances of [CryptoKey](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) and * additionally [KeyObject](https://nodejs.org/api/crypto.html#class-keyobject) in Node.js runtime. * [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) * instances are also accepted as symmetric secret representation only. * * [Key Import Functions](../modules/key_import.md#readme) can be used to import PEM, or JWK * formatted asymmetric keys and certificates to these runtime-specific representations. * * In Node.js the [Buffer](https://nodejs.org/api/buffer.html#buffer) class is a subclass of * Uint8Array and so Buffer can be provided for symmetric secrets as well. * * [KeyObject](https://nodejs.org/api/crypto.html#class-keyobject) is a representation of a * key/secret available in the Node.js runtime. In addition to the import functions of this library * you may use the runtime APIs * [crypto.createPublicKey](https://nodejs.org/api/crypto.html#cryptocreatepublickeykey), * [crypto.createPrivateKey](https://nodejs.org/api/crypto.html#cryptocreateprivatekeykey), and * [crypto.createSecretKey](https://nodejs.org/api/crypto.html#cryptocreatesecretkeykey-encoding) to * obtain a KeyObject from your existing key material. * * [CryptoKey](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) is a representation of a * key/secret available in the Browser and Web-interoperable runtimes. In addition to the import * functions of this library you may use the * [SubtleCrypto.importKey](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey) * API to obtain a CryptoKey from your existing key material. * * @example Import a PEM-encoded SPKI Public Key * * ```js * const algorithm = 'ES256' * const spki = `-----BEGIN PUBLIC KEY----- * MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFlHHWfLk0gLBbsLTcuCrbCqoHqmM * YJepMC+Q+Dd6RBmBiA41evUsNMwLeN+PNFqib+xwi9JkJ8qhZkq8Y/IzGg== * -----END PUBLIC KEY-----` * const ecPublicKey = await jose.importSPKI(spki, algorithm) * ``` * * @example Import a X.509 Certificate * * ```js * const algorithm = 'ES256' * const x509 = `-----BEGIN CERTIFICATE----- * MIIBXjCCAQSgAwIBAgIGAXvykuMKMAoGCCqGSM49BAMCMDYxNDAyBgNVBAMMK3Np * QXBNOXpBdk1VaXhXVWVGaGtjZXg1NjJRRzFyQUhXaV96UlFQTVpQaG8wHhcNMjEw * OTE3MDcwNTE3WhcNMjIwNzE0MDcwNTE3WjA2MTQwMgYDVQQDDCtzaUFwTTl6QXZN * VWl4V1VlRmhrY2V4NTYyUUcxckFIV2lfelJRUE1aUGhvMFkwEwYHKoZIzj0CAQYI * KoZIzj0DAQcDQgAE8PbPvCv5D5xBFHEZlBp/q5OEUymq7RIgWIi7tkl9aGSpYE35 * UH+kBKDnphJO3odpPZ5gvgKs2nwRWcrDnUjYLDAKBggqhkjOPQQDAgNIADBFAiEA * 1yyMTRe66MhEXID9+uVub7woMkNYd0LhSHwKSPMUUTkCIFQGsfm1ecXOpeGOufAh * v+A1QWZMuTWqYt+uh/YSRNDn * -----END CERTIFICATE-----` * const ecPublicKey = await jose.importX509(x509, algorithm) * ``` * * @example Import a PEM-encoded PKCS8 Private Key * * ```js * const algorithm = 'ES256' * const pkcs8 = `-----BEGIN PRIVATE KEY----- * MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgiyvo0X+VQ0yIrOaN * nlrnUclopnvuuMfoc8HHly3505OhRANCAAQWUcdZ8uTSAsFuwtNy4KtsKqgeqYxg * l6kwL5D4N3pEGYGIDjV69Sw0zAt43480WqJv7HCL0mQnyqFmSrxj8jMa * -----END PRIVATE KEY-----` * const ecPrivateKey = await jose.importPKCS8(pkcs8, algorithm) * ``` * * @example Import a JSON Web Key (JWK) * * ```js * const ecPublicKey = await jose.importJWK( * { * crv: 'P-256', * kty: 'EC', * x: 'ySK38C1jBdLwDsNWKzzBHqKYEE5Cgv-qjWvorUXk9fw', * y: '_LeQBw07cf5t57Iavn4j-BqJsAD1dpoz8gokd3sBsOo', * }, * 'ES256', * ) * * const rsaPublicKey = await jose.importJWK( * { * kty: 'RSA', * e: 'AQAB', * n: '12oBZRhCiZFJLcPg59LkZZ9mdhSMTKAQZYq32k_ti5SBB6jerkh-WzOMAO664r_qyLkqHUSp3u5SbXtseZEpN3XPWGKSxjsy-1JyEFTdLSYe6f9gfrmxkUF_7DTpq0gn6rntP05g2-wFW50YO7mosfdslfrTJYWHFhJALabAeYirYD7-9kqq9ebfFMF4sRRELbv9oi36As6Q9B3Qb5_C1rAzqfao_PCsf9EPsTZsVVVkA5qoIAr47lo1ipfiBPxUCCNSdvkmDTYgvvRm6ZoMjFbvOtgyts55fXKdMWv7I9HMD5HwE9uW839PWA514qhbcIsXEYSFMPMV6fnlsiZvQQ', * }, * 'PS256', * ) * ``` */ export type KeyLike = { type: string } /** * JSON Web Key ([JWK](https://www.rfc-editor.org/rfc/rfc7517)). "RSA", "EC", "OKP", and "oct" key * types are supported. */ export interface JWK { /** JWK "alg" (Algorithm) Parameter. */ alg?: string crv?: string d?: string dp?: string dq?: string e?: string /** JWK "ext" (Extractable) Parameter. */ ext?: boolean k?: string /** JWK "key_ops" (Key Operations) Parameter. */ key_ops?: string[] /** JWK "kid" (Key ID) Parameter. */ kid?: string /** JWK "kty" (Key Type) Parameter. */ kty?: string n?: string oth?: Array<{ d?: string r?: string t?: string }> p?: string q?: string qi?: string /** JWK "use" (Public Key Use) Parameter. */ use?: string x?: string y?: string /** JWK "x5c" (X.509 Certificate Chain) Parameter. */ x5c?: string[] /** JWK "x5t" (X.509 Certificate SHA-1 Thumbprint) Parameter. */ x5t?: string /** "x5t#S256" (X.509 Certificate SHA-256 Thumbprint) Parameter. */ 'x5t#S256'?: string /** JWK "x5u" (X.509 URL) Parameter. */ x5u?: string [propName: string]: unknown } /** * Generic Interface for consuming operations dynamic key resolution. No token components have been * verified at the time of this function call. * * If you cannot match a key suitable for the token, throw an error instead. * * @param protectedHeader JWE or JWS Protected Header. * @param token The consumed JWE or JWS token. */ export interface GetKeyFunction { (protectedHeader: T, token: T2): Promise | KeyLike | Uint8Array } /** * Flattened JWS definition for verify function inputs, allows payload as Uint8Array for detached * signature validation. */ export interface FlattenedJWSInput { /** * The "header" member MUST be present and contain the value JWS Unprotected Header when the JWS * Unprotected Header value is non- empty; otherwise, it MUST be absent. This value is represented * as an unencoded JSON object, rather than as a string. These Header Parameter values are not * integrity protected. */ header?: JWSHeaderParameters /** * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When RFC7797 * "b64": false is used the value passed may also be a Uint8Array. */ payload: string | Uint8Array /** * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWS Protected * Header)) when the JWS Protected Header value is non-empty; otherwise, it MUST be absent. These * Header Parameter values are integrity protected. */ protected?: string /** The "signature" member MUST be present and contain the value BASE64URL(JWS Signature). */ signature: string } /** * General JWS definition for verify function inputs, allows payload as Uint8Array for detached * signature validation. */ export interface GeneralJWSInput { /** * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When RFC7797 * "b64": false is used the value passed may also be a Uint8Array. */ payload: string | Uint8Array /** * The "signatures" member value MUST be an array of JSON objects. Each object represents a * signature or MAC over the JWS Payload and the JWS Protected Header. */ signatures: Omit[] } /** * Flattened JWS definition. Payload is returned as an empty string when JWS Unencoded Payload * Option [RFC7797](https://www.rfc-editor.org/rfc/rfc7797) is used. */ export interface FlattenedJWS extends Partial { payload: string signature: string } /** * General JWS definition. Payload is returned as an empty string when JWS Unencoded Payload Option * [RFC7797](https://www.rfc-editor.org/rfc/rfc7797) is used. */ export interface GeneralJWS { payload: string signatures: Omit[] } export interface JoseHeaderParameters { /** "kid" (Key ID) Header Parameter. */ kid?: string /** "x5t" (X.509 Certificate SHA-1 Thumbprint) Header Parameter. */ x5t?: string /** "x5c" (X.509 Certificate Chain) Header Parameter. */ x5c?: string[] /** "x5u" (X.509 URL) Header Parameter. */ x5u?: string /** "jku" (JWK Set URL) Header Parameter. */ jku?: string /** "jwk" (JSON Web Key) Header Parameter. */ jwk?: Pick /** "typ" (Type) Header Parameter. */ typ?: string /** "cty" (Content Type) Header Parameter. */ cty?: string } /** Recognized JWS Header Parameters, any other Header Members may also be present. */ export interface JWSHeaderParameters extends JoseHeaderParameters { /** JWS "alg" (Algorithm) Header Parameter. */ alg?: string /** * This JWS Extension Header Parameter modifies the JWS Payload representation and the JWS Signing * Input computation as per [RFC7797](https://www.rfc-editor.org/rfc/rfc7797). */ b64?: boolean /** JWS "crit" (Critical) Header Parameter. */ crit?: string[] /** Any other JWS Header member. */ [propName: string]: unknown } /** Recognized JWE Key Management-related Header Parameters. */ export interface JWEKeyManagementHeaderParameters { apu?: Uint8Array apv?: Uint8Array /** * @deprecated You should not use this parameter. It is only really intended for test and vector * validation purposes. */ p2c?: number /** * @deprecated You should not use this parameter. It is only really intended for test and vector * validation purposes. */ p2s?: Uint8Array /** * @deprecated You should not use this parameter. It is only really intended for test and vector * validation purposes. */ iv?: Uint8Array /** * @deprecated You should not use this parameter. It is only really intended for test and vector * validation purposes. */ epk?: KeyLike } /** Flattened JWE definition. */ export interface FlattenedJWE { /** * The "aad" member MUST be present and contain the value BASE64URL(JWE AAD)) when the JWE AAD * value is non-empty; otherwise, it MUST be absent. A JWE AAD value can be included to supply a * base64url-encoded value to be integrity protected but not encrypted. */ aad?: string /** The "ciphertext" member MUST be present and contain the value BASE64URL(JWE Ciphertext). */ ciphertext: string /** * The "encrypted_key" member MUST be present and contain the value BASE64URL(JWE Encrypted Key) * when the JWE Encrypted Key value is non-empty; otherwise, it MUST be absent. */ encrypted_key?: string /** * The "header" member MUST be present and contain the value JWE Per- Recipient Unprotected Header * when the JWE Per-Recipient Unprotected Header value is non-empty; otherwise, it MUST be absent. * This value is represented as an unencoded JSON object, rather than as a string. These Header * Parameter values are not integrity protected. */ header?: JWEHeaderParameters /** * The "iv" member MUST be present and contain the value BASE64URL(JWE Initialization Vector) when * the JWE Initialization Vector value is non-empty; otherwise, it MUST be absent. */ iv: string /** * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWE Protected * Header)) when the JWE Protected Header value is non-empty; otherwise, it MUST be absent. These * Header Parameter values are integrity protected. */ protected?: string /** * The "tag" member MUST be present and contain the value BASE64URL(JWE Authentication Tag) when * the JWE Authentication Tag value is non-empty; otherwise, it MUST be absent. */ tag: string /** * The "unprotected" member MUST be present and contain the value JWE Shared Unprotected Header * when the JWE Shared Unprotected Header value is non-empty; otherwise, it MUST be absent. This * value is represented as an unencoded JSON object, rather than as a string. These Header * Parameter values are not integrity protected. */ unprotected?: JWEHeaderParameters } export interface GeneralJWE extends Omit { recipients: Pick[] } /** Recognized JWE Header Parameters, any other Header members may also be present. */ export interface JWEHeaderParameters extends JoseHeaderParameters { /** JWE "alg" (Algorithm) Header Parameter. */ alg?: string /** JWE "enc" (Encryption Algorithm) Header Parameter. */ enc?: string /** JWE "crit" (Critical) Header Parameter. */ crit?: string[] /** JWE "zip" (Compression Algorithm) Header Parameter. */ zip?: string /** Any other JWE Header member. */ [propName: string]: unknown } /** Shared Interface with a "crit" property for all sign, verify, encrypt and decrypt operations. */ export interface CritOption { /** * An object with keys representing recognized "crit" (Critical) Header Parameter names. The value * for those is either `true` or `false`. `true` when the Header Parameter MUST be integrity * protected, `false` when it's irrelevant. * * This makes the "Extension Header Parameter "..." is not recognized" error go away. * * Use this when a given JWS/JWT/JWE profile requires the use of proprietary non-registered "crit" * (Critical) Header Parameters. This will only make sure the Header Parameter is syntactically * correct when provided and that it is optionally integrity protected. It will not process the * Header Parameter in any way or reject the operation if it is missing. You MUST still verify the * Header Parameter was present and process it according to the profile's validation steps after * the operation succeeds. * * The JWS extension Header Parameter `b64` is always recognized and processed properly. No other * registered Header Parameters that need this kind of default built-in treatment are currently * available. */ crit?: { [propName: string]: boolean } } /** JWE Decryption options. */ export interface DecryptOptions extends CritOption { /** A list of accepted JWE "alg" (Algorithm) Header Parameter values. */ keyManagementAlgorithms?: string[] /** * A list of accepted JWE "enc" (Encryption Algorithm) Header Parameter values. By default all * "enc" (Encryption Algorithm) values applicable for the used key/secret are allowed. */ contentEncryptionAlgorithms?: string[] /** * In a browser runtime you have to provide an implementation for Inflate Raw when you expect JWEs * with compressed plaintext. */ inflateRaw?: InflateFunction /** * (PBES2 Key Management Algorithms only) Maximum allowed "p2c" (PBES2 Count) Header Parameter * value. The PBKDF2 iteration count defines the algorithm's computational expense. By default * this value is set to 10000. */ maxPBES2Count?: number } /** JWE Deflate option. */ export interface DeflateOption { /** * In a browser runtime you have to provide an implementation for Deflate Raw when you will be * producing JWEs with compressed plaintext. */ deflateRaw?: DeflateFunction } /** JWE Encryption options. */ export interface EncryptOptions extends CritOption, DeflateOption {} /** JWT Claims Set verification options. */ export interface JWTClaimVerificationOptions { /** Expected JWT "aud" (Audience) Claim value(s). */ audience?: string | string[] /** * Expected clock tolerance * * - In seconds when number (e.g. 5) * - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). */ clockTolerance?: string | number /** Expected JWT "iss" (Issuer) Claim value(s). */ issuer?: string | string[] /** * Maximum time elapsed (in seconds) from the JWT "iat" (Issued At) Claim value. * * - In seconds when number (e.g. 5) * - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). */ maxTokenAge?: string | number /** Expected JWT "sub" (Subject) Claim value. */ subject?: string /** Expected JWT "typ" (Type) Header Parameter value. */ typ?: string /** Date to use when comparing NumericDate claims, defaults to `new Date()`. */ currentDate?: Date } /** JWS Verification options. */ export interface VerifyOptions extends CritOption { /** * A list of accepted JWS "alg" (Algorithm) Header Parameter values. By default all "alg" * (Algorithm) values applicable for the used key/secret are allowed. Note: "none" is never * accepted. */ algorithms?: string[] } /** JWS Signing options. */ export interface SignOptions extends CritOption {} /** Recognized JWT Claims Set members, any other members may also be present. */ export interface JWTPayload { /** * JWT Issuer * * @see [RFC7519#section-4.1.1](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.1) */ iss?: string /** * JWT Subject * * @see [RFC7519#section-4.1.2](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.2) */ sub?: string /** JWT Audience [RFC7519#section-4.1.3](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3). */ aud?: string | string[] /** * JWT ID * * @see [RFC7519#section-4.1.7](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7) */ jti?: string /** * JWT Not Before * * @see [RFC7519#section-4.1.5](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.5) */ nbf?: number /** * JWT Expiration Time * * @see [RFC7519#section-4.1.4](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4) */ exp?: number /** * JWT Issued At * * @see [RFC7519#section-4.1.6](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6) */ iat?: number /** Any other JWT Claim Set member. */ [propName: string]: unknown } /** * Deflate Raw implementation, e.g. promisified * [zlib.deflateRaw](https://nodejs.org/api/zlib.html#zlibdeflaterawbuffer-options-callback). */ export interface DeflateFunction { (input: Uint8Array): Promise } /** * Inflate Raw implementation, e.g. promisified * [zlib.inflateRaw](https://nodejs.org/api/zlib.html#zlibinflaterawbuffer-options-callback). */ export interface InflateFunction { (input: Uint8Array): Promise } export interface FlattenedDecryptResult { /** JWE AAD. */ additionalAuthenticatedData?: Uint8Array /** Plaintext. */ plaintext: Uint8Array /** JWE Protected Header. */ protectedHeader?: JWEHeaderParameters /** JWE Shared Unprotected Header. */ sharedUnprotectedHeader?: JWEHeaderParameters /** JWE Per-Recipient Unprotected Header. */ unprotectedHeader?: JWEHeaderParameters } export interface GeneralDecryptResult extends FlattenedDecryptResult {} export interface CompactDecryptResult { /** Plaintext. */ plaintext: Uint8Array /** JWE Protected Header. */ protectedHeader: CompactJWEHeaderParameters } export interface FlattenedVerifyResult { /** JWS Payload. */ payload: Uint8Array /** JWS Protected Header. */ protectedHeader?: JWSHeaderParameters /** JWS Unprotected Header. */ unprotectedHeader?: JWSHeaderParameters } export interface GeneralVerifyResult extends FlattenedVerifyResult {} export interface CompactVerifyResult { /** JWS Payload. */ payload: Uint8Array /** JWS Protected Header. */ protectedHeader: CompactJWSHeaderParameters } export interface JWTVerifyResult { /** JWT Claims Set. */ payload: JWTPayload /** JWS Protected Header. */ protectedHeader: JWTHeaderParameters } export interface JWTDecryptResult { /** JWT Claims Set. */ payload: JWTPayload /** JWE Protected Header. */ protectedHeader: CompactJWEHeaderParameters } export interface ResolvedKey { /** Key resolved from the key resolver function. */ key: KeyLike | Uint8Array } /** Recognized Compact JWS Header Parameters, any other Header Members may also be present. */ export interface CompactJWSHeaderParameters extends JWSHeaderParameters { alg: string } /** Recognized Signed JWT Header Parameters, any other Header Members may also be present. */ export interface JWTHeaderParameters extends CompactJWSHeaderParameters { b64?: true } /** Recognized Compact JWE Header Parameters, any other Header Members may also be present. */ export interface CompactJWEHeaderParameters extends JWEHeaderParameters { alg: string enc: string } /** JSON Web Key Set */ export interface JSONWebKeySet { keys: JWK[] } jose-4.11.4/dist/types/util/000077500000000000000000000000001437043056600156355ustar00rootroot00000000000000jose-4.11.4/dist/types/util/base64url.d.ts000066400000000000000000000010031437043056600202300ustar00rootroot00000000000000/** * Utility function to encode a string or Uint8Array as a base64url string. * * @param input Value that will be base64url-encoded. */ interface Base64UrlEncode { (input: Uint8Array | string): string; } /** * Utility function to decode a base64url encoded string. * * @param input Value that will be base64url-decoded. */ interface Base64UrlDecode { (input: Uint8Array | string): Uint8Array; } export declare const encode: Base64UrlEncode; export declare const decode: Base64UrlDecode; export {}; jose-4.11.4/dist/types/util/decode_jwt.d.ts000066400000000000000000000011461437043056600205400ustar00rootroot00000000000000import type { JWTPayload } from '../types'; /** * Decodes a signed JSON Web Token payload. This does not validate the JWT Claims Set types or * values. This does not validate the JWS Signature. For a proper Signed JWT Claims Set validation * and JWS signature verification use `jose.jwtVerify()`. For an encrypted JWT Claims Set validation * and JWE decryption use `jose.jwtDecrypt()`. * * @example Usage * * ```js * const claims = jose.decodeJwt(token) * console.log(claims) * ``` * * @param jwt JWT token in compact JWS serialization. */ export declare function decodeJwt(jwt: string): JWTPayload; jose-4.11.4/dist/types/util/decode_protected_header.d.ts000066400000000000000000000010451437043056600232330ustar00rootroot00000000000000import type { JWSHeaderParameters, JWEHeaderParameters } from '../types'; export type ProtectedHeaderParameters = JWSHeaderParameters & JWEHeaderParameters; /** * Decodes the Protected Header of a JWE/JWS/JWT token utilizing any JOSE serialization. * * @example Usage * * ```js * const protectedHeader = jose.decodeProtectedHeader(token) * console.log(protectedHeader) * ``` * * @param token JWE/JWS/JWT token in any JOSE serialization. */ export declare function decodeProtectedHeader(token: string | object): ProtectedHeaderParameters; jose-4.11.4/dist/types/util/errors.d.ts000066400000000000000000000071231437043056600177460ustar00rootroot00000000000000/** A generic Error subclass that all other specific JOSE Error subclasses inherit from. */ export declare class JOSEError extends Error { /** A unique error code for the particular error subclass. */ static get code(): string; /** A unique error code for the particular error subclass. */ code: string; constructor(message?: string); } /** An error subclass thrown when a JWT Claim Set member validation fails. */ export declare class JWTClaimValidationFailed extends JOSEError { static get code(): 'ERR_JWT_CLAIM_VALIDATION_FAILED'; code: string; /** The Claim for which the validation failed. */ claim: string; /** Reason code for the validation failure. */ reason: string; constructor(message: string, claim?: string, reason?: string); } /** An error subclass thrown when a JWT is expired. */ export declare class JWTExpired extends JOSEError implements JWTClaimValidationFailed { static get code(): 'ERR_JWT_EXPIRED'; code: string; /** The Claim for which the validation failed. */ claim: string; /** Reason code for the validation failure. */ reason: string; constructor(message: string, claim?: string, reason?: string); } /** An error subclass thrown when a JOSE Algorithm is not allowed per developer preference. */ export declare class JOSEAlgNotAllowed extends JOSEError { static get code(): 'ERR_JOSE_ALG_NOT_ALLOWED'; code: string; } /** * An error subclass thrown when a particular feature or algorithm is not supported by this * implementation or JOSE in general. */ export declare class JOSENotSupported extends JOSEError { static get code(): 'ERR_JOSE_NOT_SUPPORTED'; code: string; } /** An error subclass thrown when a JWE ciphertext decryption fails. */ export declare class JWEDecryptionFailed extends JOSEError { static get code(): 'ERR_JWE_DECRYPTION_FAILED'; code: string; message: string; } /** An error subclass thrown when a JWE is invalid. */ export declare class JWEInvalid extends JOSEError { static get code(): 'ERR_JWE_INVALID'; code: string; } /** An error subclass thrown when a JWS is invalid. */ export declare class JWSInvalid extends JOSEError { static get code(): 'ERR_JWS_INVALID'; code: string; } /** An error subclass thrown when a JWT is invalid. */ export declare class JWTInvalid extends JOSEError { static get code(): 'ERR_JWT_INVALID'; code: string; } /** An error subclass thrown when a JWK is invalid. */ export declare class JWKInvalid extends JOSEError { static get code(): 'ERR_JWK_INVALID'; code: string; } /** An error subclass thrown when a JWKS is invalid. */ export declare class JWKSInvalid extends JOSEError { static get code(): 'ERR_JWKS_INVALID'; code: string; } /** An error subclass thrown when no keys match from a JWKS. */ export declare class JWKSNoMatchingKey extends JOSEError { static get code(): 'ERR_JWKS_NO_MATCHING_KEY'; code: string; message: string; } /** An error subclass thrown when multiple keys match from a JWKS. */ export declare class JWKSMultipleMatchingKeys extends JOSEError { static get code(): 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'; code: string; message: string; } /** Timeout was reached when retrieving the JWKS response. */ export declare class JWKSTimeout extends JOSEError { static get code(): 'ERR_JWKS_TIMEOUT'; code: string; message: string; } /** An error subclass thrown when JWS signature verification fails. */ export declare class JWSSignatureVerificationFailed extends JOSEError { static get code(): 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'; code: string; message: string; } jose-4.11.4/docs/000077500000000000000000000000001437043056600135015ustar00rootroot00000000000000jose-4.11.4/docs/README.md000066400000000000000000000064151437043056600147660ustar00rootroot00000000000000# `jose` Modules API Documentation > "JSON Web Almost Everything" - JWA, JWS, JWE, JWT, JWK, JWKS with no dependencies using runtime's native crypto. ## [💗 Help the project](https://github.com/sponsors/panva) ## Available modules **`example`** ESM import ```js import * as jose from 'jose' ``` **`example`** CJS require ```js const jose = require('jose') ``` **`example`** Deno import ```js import * as jose from 'https://deno.land/x/jose@v4.11.4/index.ts' ``` - JSON Web Tokens (JWT) - [Signing](classes/jwt_sign.SignJWT.md#readme) - [Verification & JWT Claims Set Validation](functions/jwt_verify.jwtVerify.md#readme) - Encrypted JSON Web Tokens - [Encryption](classes/jwt_encrypt.EncryptJWT.md#readme) - [Decryption & JWT Claims Set Validation](functions/jwt_decrypt.jwtDecrypt.md#readme) - Key Import - [JWK Import](functions/key_import.importJWK.md#readme) - [Public Key Import (SPKI)](functions/key_import.importSPKI.md#readme) - [Public Key Import (X.509 Certificate)](functions/key_import.importX509.md#readme) - [Private Key Import (PKCS #8)](functions/key_import.importPKCS8.md#readme) - JSON Web Encryption (JWE) - Encryption - [Compact](classes/jwe_compact_encrypt.CompactEncrypt.md#readme), [Flattened](classes/jwe_flattened_encrypt.FlattenedEncrypt.md#readme), [General](classes/jwe_general_encrypt.GeneralEncrypt.md#readme) - Decryption - [Compact](functions/jwe_compact_decrypt.compactDecrypt.md#readme), [Flattened](functions/jwe_flattened_decrypt.flattenedDecrypt.md#readme), [General](functions/jwe_general_decrypt.generalDecrypt.md#readme) - JSON Web Signature (JWS) - Signing - [Compact](classes/jws_compact_sign.CompactSign.md#readme), [Flattened](classes/jws_flattened_sign.FlattenedSign.md#readme), [General](classes/jws_general_sign.GeneralSign.md#readme) - Verification - [Compact](functions/jws_compact_verify.compactVerify.md#readme), [Flattened](functions/jws_flattened_verify.flattenedVerify.md#readme), [General](functions/jws_general_verify.generalVerify.md#readme) - JSON Web Key (JWK) - [Calculating JWK Thumbprint](functions/jwk_thumbprint.calculateJwkThumbprint.md#readme) - [Calculating JWK Thumbprint URI](functions/jwk_thumbprint.calculateJwkThumbprintUri.md#readme) - [Verification using a JWK Embedded in a JWS Header](functions/jwk_embedded.EmbeddedJWK.md#readme) - JSON Web Key Set (JWKS) - [Verify using a local JWKSet](functions/jwks_local.createLocalJWKSet.md#readme) - [Verify using a remote JWKSet](functions/jwks_remote.createRemoteJWKSet.md#readme) - Key Pair or Secret Generation - [Asymmetric Key Pair Generation](functions/key_generate_key_pair.generateKeyPair.md#readme) - [Symmetric Secret Generation](functions/key_generate_secret.generateSecret.md#readme) - Key Export - [JWK Export](functions/key_export.exportJWK.md#readme) - [Private Key Export](functions/key_export.exportPKCS8.md#readme) - [Public Key Export](functions/key_export.exportSPKI.md#readme) - Utilities - [Decoding Token's Protected Header](functions/util_decode_protected_header.decodeProtectedHeader.md#readme) - [Decoding JWT Claims Set](functions/util_decode_jwt.decodeJwt.md#readme) - [Unsecured JWT](classes/jwt_unsecured.UnsecuredJWT.md#readme) - [JOSE Errors](modules/util_errors.md#readme) [support-sponsor]: https://github.com/sponsors/panva jose-4.11.4/docs/classes/000077500000000000000000000000001437043056600151365ustar00rootroot00000000000000jose-4.11.4/docs/classes/jwe_compact_encrypt.CompactEncrypt.md000066400000000000000000000077161437043056600244640ustar00rootroot00000000000000# Class: CompactEncrypt [💗 Help the project](https://github.com/sponsors/panva) The CompactEncrypt class is a utility for creating Compact JWE strings. **`example`** Usage ```js const jwe = await new jose.CompactEncrypt( new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), ) .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM' }) .encrypt(publicKey) console.log(jwe) ``` ## Table of contents ### Constructors - [constructor](jwe_compact_encrypt.CompactEncrypt.md#constructor) ### Methods - [encrypt](jwe_compact_encrypt.CompactEncrypt.md#encrypt) - [setContentEncryptionKey](jwe_compact_encrypt.CompactEncrypt.md#setcontentencryptionkey) - [setInitializationVector](jwe_compact_encrypt.CompactEncrypt.md#setinitializationvector) - [setKeyManagementParameters](jwe_compact_encrypt.CompactEncrypt.md#setkeymanagementparameters) - [setProtectedHeader](jwe_compact_encrypt.CompactEncrypt.md#setprotectedheader) ## Constructors ### constructor • **new CompactEncrypt**(`plaintext`) #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `plaintext` | `Uint8Array` | Binary representation of the plaintext to encrypt. | ## Methods ### encrypt ▸ **encrypt**(`key`, `options?`): `Promise`<`string`\> Encrypts and resolves the value of the Compact JWE string. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Public Key or Secret to encrypt the JWE with. | | `options?` | [`EncryptOptions`](../interfaces/types.EncryptOptions.md) | JWE Encryption options. | #### Returns `Promise`<`string`\> ___ ### setContentEncryptionKey ▸ **setContentEncryptionKey**(`cek`): [`CompactEncrypt`](jwe_compact_encrypt.CompactEncrypt.md) Sets a content encryption key to use, by default a random suitable one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. **`deprecated`** You should not use this method. It is only really intended for test and vector validation purposes. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `cek` | `Uint8Array` | JWE Content Encryption Key. | #### Returns [`CompactEncrypt`](jwe_compact_encrypt.CompactEncrypt.md) ___ ### setInitializationVector ▸ **setInitializationVector**(`iv`): [`CompactEncrypt`](jwe_compact_encrypt.CompactEncrypt.md) Sets the JWE Initialization Vector to use for content encryption, by default a random suitable one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. **`deprecated`** You should not use this method. It is only really intended for test and vector validation purposes. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `iv` | `Uint8Array` | JWE Initialization Vector. | #### Returns [`CompactEncrypt`](jwe_compact_encrypt.CompactEncrypt.md) ___ ### setKeyManagementParameters ▸ **setKeyManagementParameters**(`parameters`): [`CompactEncrypt`](jwe_compact_encrypt.CompactEncrypt.md) Sets the JWE Key Management parameters to be used when encrypting the Content Encryption Key. You do not need to invoke this method, it is only really intended for test and vector validation purposes. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `parameters` | [`JWEKeyManagementHeaderParameters`](../interfaces/types.JWEKeyManagementHeaderParameters.md) | JWE Key Management parameters. | #### Returns [`CompactEncrypt`](jwe_compact_encrypt.CompactEncrypt.md) ___ ### setProtectedHeader ▸ **setProtectedHeader**(`protectedHeader`): [`CompactEncrypt`](jwe_compact_encrypt.CompactEncrypt.md) Sets the JWE Protected Header on the CompactEncrypt object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `protectedHeader` | [`CompactJWEHeaderParameters`](../interfaces/types.CompactJWEHeaderParameters.md) | JWE Protected Header object. | #### Returns [`CompactEncrypt`](jwe_compact_encrypt.CompactEncrypt.md) jose-4.11.4/docs/classes/jwe_flattened_encrypt.FlattenedEncrypt.md000066400000000000000000000140161437043056600253130ustar00rootroot00000000000000# Class: FlattenedEncrypt [💗 Help the project](https://github.com/sponsors/panva) The FlattenedEncrypt class is a utility for creating Flattened JWE objects. **`example`** Usage ```js const jwe = await new jose.FlattenedEncrypt( new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), ) .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM' }) .setAdditionalAuthenticatedData(encoder.encode('The Fellowship of the Ring')) .encrypt(publicKey) console.log(jwe) ``` ## Table of contents ### Constructors - [constructor](jwe_flattened_encrypt.FlattenedEncrypt.md#constructor) ### Methods - [encrypt](jwe_flattened_encrypt.FlattenedEncrypt.md#encrypt) - [setAdditionalAuthenticatedData](jwe_flattened_encrypt.FlattenedEncrypt.md#setadditionalauthenticateddata) - [setContentEncryptionKey](jwe_flattened_encrypt.FlattenedEncrypt.md#setcontentencryptionkey) - [setInitializationVector](jwe_flattened_encrypt.FlattenedEncrypt.md#setinitializationvector) - [setKeyManagementParameters](jwe_flattened_encrypt.FlattenedEncrypt.md#setkeymanagementparameters) - [setProtectedHeader](jwe_flattened_encrypt.FlattenedEncrypt.md#setprotectedheader) - [setSharedUnprotectedHeader](jwe_flattened_encrypt.FlattenedEncrypt.md#setsharedunprotectedheader) - [setUnprotectedHeader](jwe_flattened_encrypt.FlattenedEncrypt.md#setunprotectedheader) ## Constructors ### constructor • **new FlattenedEncrypt**(`plaintext`) #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `plaintext` | `Uint8Array` | Binary representation of the plaintext to encrypt. | ## Methods ### encrypt ▸ **encrypt**(`key`, `options?`): `Promise`<[`FlattenedJWE`](../interfaces/types.FlattenedJWE.md)\> Encrypts and resolves the value of the Flattened JWE object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Public Key or Secret to encrypt the JWE with. | | `options?` | [`EncryptOptions`](../interfaces/types.EncryptOptions.md) | JWE Encryption options. | #### Returns `Promise`<[`FlattenedJWE`](../interfaces/types.FlattenedJWE.md)\> ___ ### setAdditionalAuthenticatedData ▸ **setAdditionalAuthenticatedData**(`aad`): [`FlattenedEncrypt`](jwe_flattened_encrypt.FlattenedEncrypt.md) Sets the Additional Authenticated Data on the FlattenedEncrypt object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `aad` | `Uint8Array` | Additional Authenticated Data. | #### Returns [`FlattenedEncrypt`](jwe_flattened_encrypt.FlattenedEncrypt.md) ___ ### setContentEncryptionKey ▸ **setContentEncryptionKey**(`cek`): [`FlattenedEncrypt`](jwe_flattened_encrypt.FlattenedEncrypt.md) Sets a content encryption key to use, by default a random suitable one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. **`deprecated`** You should not use this method. It is only really intended for test and vector validation purposes. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `cek` | `Uint8Array` | JWE Content Encryption Key. | #### Returns [`FlattenedEncrypt`](jwe_flattened_encrypt.FlattenedEncrypt.md) ___ ### setInitializationVector ▸ **setInitializationVector**(`iv`): [`FlattenedEncrypt`](jwe_flattened_encrypt.FlattenedEncrypt.md) Sets the JWE Initialization Vector to use for content encryption, by default a random suitable one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. **`deprecated`** You should not use this method. It is only really intended for test and vector validation purposes. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `iv` | `Uint8Array` | JWE Initialization Vector. | #### Returns [`FlattenedEncrypt`](jwe_flattened_encrypt.FlattenedEncrypt.md) ___ ### setKeyManagementParameters ▸ **setKeyManagementParameters**(`parameters`): [`FlattenedEncrypt`](jwe_flattened_encrypt.FlattenedEncrypt.md) Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed and missing. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `parameters` | [`JWEKeyManagementHeaderParameters`](../interfaces/types.JWEKeyManagementHeaderParameters.md) | JWE Key Management parameters. | #### Returns [`FlattenedEncrypt`](jwe_flattened_encrypt.FlattenedEncrypt.md) ___ ### setProtectedHeader ▸ **setProtectedHeader**(`protectedHeader`): [`FlattenedEncrypt`](jwe_flattened_encrypt.FlattenedEncrypt.md) Sets the JWE Protected Header on the FlattenedEncrypt object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `protectedHeader` | [`JWEHeaderParameters`](../interfaces/types.JWEHeaderParameters.md) | JWE Protected Header. | #### Returns [`FlattenedEncrypt`](jwe_flattened_encrypt.FlattenedEncrypt.md) ___ ### setSharedUnprotectedHeader ▸ **setSharedUnprotectedHeader**(`sharedUnprotectedHeader`): [`FlattenedEncrypt`](jwe_flattened_encrypt.FlattenedEncrypt.md) Sets the JWE Shared Unprotected Header on the FlattenedEncrypt object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `sharedUnprotectedHeader` | [`JWEHeaderParameters`](../interfaces/types.JWEHeaderParameters.md) | JWE Shared Unprotected Header. | #### Returns [`FlattenedEncrypt`](jwe_flattened_encrypt.FlattenedEncrypt.md) ___ ### setUnprotectedHeader ▸ **setUnprotectedHeader**(`unprotectedHeader`): [`FlattenedEncrypt`](jwe_flattened_encrypt.FlattenedEncrypt.md) Sets the JWE Per-Recipient Unprotected Header on the FlattenedEncrypt object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `unprotectedHeader` | [`JWEHeaderParameters`](../interfaces/types.JWEHeaderParameters.md) | JWE Per-Recipient Unprotected Header. | #### Returns [`FlattenedEncrypt`](jwe_flattened_encrypt.FlattenedEncrypt.md) jose-4.11.4/docs/classes/jwe_general_encrypt.GeneralEncrypt.md000066400000000000000000000072701437043056600244350ustar00rootroot00000000000000# Class: GeneralEncrypt [💗 Help the project](https://github.com/sponsors/panva) The GeneralEncrypt class is a utility for creating General JWE objects. **`example`** Usage ```js const jwe = await new jose.GeneralEncrypt( new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), ) .setProtectedHeader({ enc: 'A256GCM' }) .addRecipient(ecPublicKey) .setUnprotectedHeader({ alg: 'ECDH-ES+A256KW' }) .addRecipient(rsaPublicKey) .setUnprotectedHeader({ alg: 'RSA-OAEP-384' }) .encrypt() console.log(jwe) ``` ## Table of contents ### Constructors - [constructor](jwe_general_encrypt.GeneralEncrypt.md#constructor) ### Methods - [addRecipient](jwe_general_encrypt.GeneralEncrypt.md#addrecipient) - [encrypt](jwe_general_encrypt.GeneralEncrypt.md#encrypt) - [setAdditionalAuthenticatedData](jwe_general_encrypt.GeneralEncrypt.md#setadditionalauthenticateddata) - [setProtectedHeader](jwe_general_encrypt.GeneralEncrypt.md#setprotectedheader) - [setSharedUnprotectedHeader](jwe_general_encrypt.GeneralEncrypt.md#setsharedunprotectedheader) ## Constructors ### constructor • **new GeneralEncrypt**(`plaintext`) #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `plaintext` | `Uint8Array` | Binary representation of the plaintext to encrypt. | ## Methods ### addRecipient ▸ **addRecipient**(`key`, `options?`): [`Recipient`](../interfaces/jwe_general_encrypt.Recipient.md) Adds an additional recipient for the General JWE object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Public Key or Secret to encrypt the Content Encryption Key for the recipient with. | | `options?` | [`CritOption`](../interfaces/types.CritOption.md) | JWE Encryption options. | #### Returns [`Recipient`](../interfaces/jwe_general_encrypt.Recipient.md) ___ ### encrypt ▸ **encrypt**(`options?`): `Promise`<[`GeneralJWE`](../interfaces/types.GeneralJWE.md)\> Encrypts and resolves the value of the General JWE object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `options?` | [`DeflateOption`](../interfaces/types.DeflateOption.md) | JWE Encryption options. | #### Returns `Promise`<[`GeneralJWE`](../interfaces/types.GeneralJWE.md)\> ___ ### setAdditionalAuthenticatedData ▸ **setAdditionalAuthenticatedData**(`aad`): [`GeneralEncrypt`](jwe_general_encrypt.GeneralEncrypt.md) Sets the Additional Authenticated Data on the GeneralEncrypt object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `aad` | `Uint8Array` | Additional Authenticated Data. | #### Returns [`GeneralEncrypt`](jwe_general_encrypt.GeneralEncrypt.md) ___ ### setProtectedHeader ▸ **setProtectedHeader**(`protectedHeader`): [`GeneralEncrypt`](jwe_general_encrypt.GeneralEncrypt.md) Sets the JWE Protected Header on the GeneralEncrypt object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `protectedHeader` | [`JWEHeaderParameters`](../interfaces/types.JWEHeaderParameters.md) | JWE Protected Header object. | #### Returns [`GeneralEncrypt`](jwe_general_encrypt.GeneralEncrypt.md) ___ ### setSharedUnprotectedHeader ▸ **setSharedUnprotectedHeader**(`sharedUnprotectedHeader`): [`GeneralEncrypt`](jwe_general_encrypt.GeneralEncrypt.md) Sets the JWE Shared Unprotected Header on the GeneralEncrypt object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `sharedUnprotectedHeader` | [`JWEHeaderParameters`](../interfaces/types.JWEHeaderParameters.md) | JWE Shared Unprotected Header object. | #### Returns [`GeneralEncrypt`](jwe_general_encrypt.GeneralEncrypt.md) jose-4.11.4/docs/classes/jws_compact_sign.CompactSign.md000066400000000000000000000033371437043056600232250ustar00rootroot00000000000000# Class: CompactSign [💗 Help the project](https://github.com/sponsors/panva) The CompactSign class is a utility for creating Compact JWS strings. **`example`** Usage ```js const jws = await new jose.CompactSign( new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), ) .setProtectedHeader({ alg: 'ES256' }) .sign(privateKey) console.log(jws) ``` ## Table of contents ### Constructors - [constructor](jws_compact_sign.CompactSign.md#constructor) ### Methods - [setProtectedHeader](jws_compact_sign.CompactSign.md#setprotectedheader) - [sign](jws_compact_sign.CompactSign.md#sign) ## Constructors ### constructor • **new CompactSign**(`payload`) #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `payload` | `Uint8Array` | Binary representation of the payload to sign. | ## Methods ### setProtectedHeader ▸ **setProtectedHeader**(`protectedHeader`): [`CompactSign`](jws_compact_sign.CompactSign.md) Sets the JWS Protected Header on the Sign object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `protectedHeader` | [`CompactJWSHeaderParameters`](../interfaces/types.CompactJWSHeaderParameters.md) | JWS Protected Header. | #### Returns [`CompactSign`](jws_compact_sign.CompactSign.md) ___ ### sign ▸ **sign**(`key`, `options?`): `Promise`<`string`\> Signs and resolves the value of the Compact JWS string. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Private Key or Secret to sign the JWS with. | | `options?` | [`SignOptions`](../interfaces/types.SignOptions.md) | JWS Sign options. | #### Returns `Promise`<`string`\> jose-4.11.4/docs/classes/jws_flattened_sign.FlattenedSign.md000066400000000000000000000046011437043056600240600ustar00rootroot00000000000000# Class: FlattenedSign [💗 Help the project](https://github.com/sponsors/panva) The FlattenedSign class is a utility for creating Flattened JWS objects. **`example`** Usage ```js const jws = await new jose.FlattenedSign( new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), ) .setProtectedHeader({ alg: 'ES256' }) .sign(privateKey) console.log(jws) ``` ## Table of contents ### Constructors - [constructor](jws_flattened_sign.FlattenedSign.md#constructor) ### Methods - [setProtectedHeader](jws_flattened_sign.FlattenedSign.md#setprotectedheader) - [setUnprotectedHeader](jws_flattened_sign.FlattenedSign.md#setunprotectedheader) - [sign](jws_flattened_sign.FlattenedSign.md#sign) ## Constructors ### constructor • **new FlattenedSign**(`payload`) #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `payload` | `Uint8Array` | Binary representation of the payload to sign. | ## Methods ### setProtectedHeader ▸ **setProtectedHeader**(`protectedHeader`): [`FlattenedSign`](jws_flattened_sign.FlattenedSign.md) Sets the JWS Protected Header on the FlattenedSign object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `protectedHeader` | [`JWSHeaderParameters`](../interfaces/types.JWSHeaderParameters.md) | JWS Protected Header. | #### Returns [`FlattenedSign`](jws_flattened_sign.FlattenedSign.md) ___ ### setUnprotectedHeader ▸ **setUnprotectedHeader**(`unprotectedHeader`): [`FlattenedSign`](jws_flattened_sign.FlattenedSign.md) Sets the JWS Unprotected Header on the FlattenedSign object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `unprotectedHeader` | [`JWSHeaderParameters`](../interfaces/types.JWSHeaderParameters.md) | JWS Unprotected Header. | #### Returns [`FlattenedSign`](jws_flattened_sign.FlattenedSign.md) ___ ### sign ▸ **sign**(`key`, `options?`): `Promise`<[`FlattenedJWS`](../interfaces/types.FlattenedJWS.md)\> Signs and resolves the value of the Flattened JWS object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Private Key or Secret to sign the JWS with. | | `options?` | [`SignOptions`](../interfaces/types.SignOptions.md) | JWS Sign options. | #### Returns `Promise`<[`FlattenedJWS`](../interfaces/types.FlattenedJWS.md)\> jose-4.11.4/docs/classes/jws_general_sign.GeneralSign.md000066400000000000000000000033011437043056600231720ustar00rootroot00000000000000# Class: GeneralSign [💗 Help the project](https://github.com/sponsors/panva) The GeneralSign class is a utility for creating General JWS objects. **`example`** Usage ```js const jws = await new jose.GeneralSign( new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), ) .addSignature(ecPrivateKey) .setProtectedHeader({ alg: 'ES256' }) .addSignature(rsaPrivateKey) .setProtectedHeader({ alg: 'PS256' }) .sign() console.log(jws) ``` ## Table of contents ### Constructors - [constructor](jws_general_sign.GeneralSign.md#constructor) ### Methods - [addSignature](jws_general_sign.GeneralSign.md#addsignature) - [sign](jws_general_sign.GeneralSign.md#sign) ## Constructors ### constructor • **new GeneralSign**(`payload`) #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `payload` | `Uint8Array` | Binary representation of the payload to sign. | ## Methods ### addSignature ▸ **addSignature**(`key`, `options?`): [`Signature`](../interfaces/jws_general_sign.Signature.md) Adds an additional signature for the General JWS object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Private Key or Secret to sign the individual JWS signature with. | | `options?` | [`SignOptions`](../interfaces/types.SignOptions.md) | JWS Sign options. | #### Returns [`Signature`](../interfaces/jws_general_sign.Signature.md) ___ ### sign ▸ **sign**(): `Promise`<[`GeneralJWS`](../interfaces/types.GeneralJWS.md)\> Signs and resolves the value of the General JWS object. #### Returns `Promise`<[`GeneralJWS`](../interfaces/types.GeneralJWS.md)\> jose-4.11.4/docs/classes/jwt_encrypt.EncryptJWT.md000066400000000000000000000204641437043056600220460ustar00rootroot00000000000000# Class: EncryptJWT [💗 Help the project](https://github.com/sponsors/panva) The EncryptJWT class is a utility for creating Compact JWE formatted JWT strings. **`example`** Usage ```js const secret = jose.base64url.decode('zH4NRP1HMALxxCFnRZABFA7GOJtzU_gIj02alfL1lvI') const jwt = await new jose.EncryptJWT({ 'urn:example:claim': true }) .setProtectedHeader({ alg: 'dir', enc: 'A128CBC-HS256' }) .setIssuedAt() .setIssuer('urn:example:issuer') .setAudience('urn:example:audience') .setExpirationTime('2h') .encrypt(secret) console.log(jwt) ``` ## Table of contents ### Constructors - [constructor](jwt_encrypt.EncryptJWT.md#constructor) ### Methods - [encrypt](jwt_encrypt.EncryptJWT.md#encrypt) - [replicateAudienceAsHeader](jwt_encrypt.EncryptJWT.md#replicateaudienceasheader) - [replicateIssuerAsHeader](jwt_encrypt.EncryptJWT.md#replicateissuerasheader) - [replicateSubjectAsHeader](jwt_encrypt.EncryptJWT.md#replicatesubjectasheader) - [setAudience](jwt_encrypt.EncryptJWT.md#setaudience) - [setContentEncryptionKey](jwt_encrypt.EncryptJWT.md#setcontentencryptionkey) - [setExpirationTime](jwt_encrypt.EncryptJWT.md#setexpirationtime) - [setInitializationVector](jwt_encrypt.EncryptJWT.md#setinitializationvector) - [setIssuedAt](jwt_encrypt.EncryptJWT.md#setissuedat) - [setIssuer](jwt_encrypt.EncryptJWT.md#setissuer) - [setJti](jwt_encrypt.EncryptJWT.md#setjti) - [setKeyManagementParameters](jwt_encrypt.EncryptJWT.md#setkeymanagementparameters) - [setNotBefore](jwt_encrypt.EncryptJWT.md#setnotbefore) - [setProtectedHeader](jwt_encrypt.EncryptJWT.md#setprotectedheader) - [setSubject](jwt_encrypt.EncryptJWT.md#setsubject) ## Constructors ### constructor • **new EncryptJWT**(`payload`) #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `payload` | [`JWTPayload`](../interfaces/types.JWTPayload.md) | The JWT Claims Set object. | ## Methods ### encrypt ▸ **encrypt**(`key`, `options?`): `Promise`<`string`\> Encrypts and returns the JWT. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Public Key or Secret to encrypt the JWT with. | | `options?` | [`EncryptOptions`](../interfaces/types.EncryptOptions.md) | JWE Encryption options. | #### Returns `Promise`<`string`\> ___ ### replicateAudienceAsHeader ▸ **replicateAudienceAsHeader**(): [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) Replicates the "aud" (Audience) Claim as a JWE Protected Header Parameter as per [RFC7519#section-5.3](https://www.rfc-editor.org/rfc/rfc7519#section-5.3). #### Returns [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) ___ ### replicateIssuerAsHeader ▸ **replicateIssuerAsHeader**(): [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) Replicates the "iss" (Issuer) Claim as a JWE Protected Header Parameter as per [RFC7519#section-5.3](https://www.rfc-editor.org/rfc/rfc7519#section-5.3). #### Returns [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) ___ ### replicateSubjectAsHeader ▸ **replicateSubjectAsHeader**(): [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) Replicates the "sub" (Subject) Claim as a JWE Protected Header Parameter as per [RFC7519#section-5.3](https://www.rfc-editor.org/rfc/rfc7519#section-5.3). #### Returns [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) ___ ### setAudience ▸ **setAudience**(`audience`): [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) Set "aud" (Audience) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `audience` | `string` \| `string`[] | "aud" (Audience) Claim value to set on the JWT Claims Set. | #### Returns [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) ___ ### setContentEncryptionKey ▸ **setContentEncryptionKey**(`cek`): [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) Sets a content encryption key to use, by default a random suitable one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. **`deprecated`** You should not use this method. It is only really intended for test and vector validation purposes. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `cek` | `Uint8Array` | JWE Content Encryption Key. | #### Returns [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) ___ ### setExpirationTime ▸ **setExpirationTime**(`input`): [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) Set "exp" (Expiration Time) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `input` | `string` \| `number` | "exp" (Expiration Time) Claim value to set on the JWT Claims Set. When number is passed that is used as a value, when string is passed it is resolved to a time span and added to the current timestamp. | #### Returns [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) ___ ### setInitializationVector ▸ **setInitializationVector**(`iv`): [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) Sets the JWE Initialization Vector to use for content encryption, by default a random suitable one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. **`deprecated`** You should not use this method. It is only really intended for test and vector validation purposes. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `iv` | `Uint8Array` | JWE Initialization Vector. | #### Returns [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) ___ ### setIssuedAt ▸ **setIssuedAt**(`input?`): [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) Set "iat" (Issued At) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `input?` | `number` | "iat" (Issued At) Claim value to set on the JWT Claims Set. Default is current timestamp. | #### Returns [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) ___ ### setIssuer ▸ **setIssuer**(`issuer`): [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) Set "iss" (Issuer) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `issuer` | `string` | "Issuer" Claim value to set on the JWT Claims Set. | #### Returns [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) ___ ### setJti ▸ **setJti**(`jwtId`): [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) Set "jti" (JWT ID) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwtId` | `string` | "jti" (JWT ID) Claim value to set on the JWT Claims Set. | #### Returns [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) ___ ### setKeyManagementParameters ▸ **setKeyManagementParameters**(`parameters`): [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed and missing. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `parameters` | [`JWEKeyManagementHeaderParameters`](../interfaces/types.JWEKeyManagementHeaderParameters.md) | JWE Key Management parameters. | #### Returns [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) ___ ### setNotBefore ▸ **setNotBefore**(`input`): [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) Set "nbf" (Not Before) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `input` | `string` \| `number` | "nbf" (Not Before) Claim value to set on the JWT Claims Set. When number is passed that is used as a value, when string is passed it is resolved to a time span and added to the current timestamp. | #### Returns [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) ___ ### setProtectedHeader ▸ **setProtectedHeader**(`protectedHeader`): [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) Sets the JWE Protected Header on the EncryptJWT object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `protectedHeader` | [`CompactJWEHeaderParameters`](../interfaces/types.CompactJWEHeaderParameters.md) | JWE Protected Header. Must contain an "alg" (JWE Algorithm) and "enc" (JWE Encryption Algorithm) properties. | #### Returns [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) ___ ### setSubject ▸ **setSubject**(`subject`): [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) Set "sub" (Subject) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `subject` | `string` | "sub" (Subject) Claim value to set on the JWT Claims Set. | #### Returns [`EncryptJWT`](jwt_encrypt.EncryptJWT.md) jose-4.11.4/docs/classes/jwt_produce.ProduceJWT.md000066400000000000000000000070531437043056600217770ustar00rootroot00000000000000# Class: ProduceJWT [💗 Help the project](https://github.com/sponsors/panva) Generic class for JWT producing. ## Table of contents ### Constructors - [constructor](jwt_produce.ProduceJWT.md#constructor) ### Methods - [setAudience](jwt_produce.ProduceJWT.md#setaudience) - [setExpirationTime](jwt_produce.ProduceJWT.md#setexpirationtime) - [setIssuedAt](jwt_produce.ProduceJWT.md#setissuedat) - [setIssuer](jwt_produce.ProduceJWT.md#setissuer) - [setJti](jwt_produce.ProduceJWT.md#setjti) - [setNotBefore](jwt_produce.ProduceJWT.md#setnotbefore) - [setSubject](jwt_produce.ProduceJWT.md#setsubject) ## Constructors ### constructor • **new ProduceJWT**(`payload`) #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `payload` | [`JWTPayload`](../interfaces/types.JWTPayload.md) | The JWT Claims Set object. | ## Methods ### setAudience ▸ **setAudience**(`audience`): [`ProduceJWT`](jwt_produce.ProduceJWT.md) Set "aud" (Audience) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `audience` | `string` \| `string`[] | "aud" (Audience) Claim value to set on the JWT Claims Set. | #### Returns [`ProduceJWT`](jwt_produce.ProduceJWT.md) ___ ### setExpirationTime ▸ **setExpirationTime**(`input`): [`ProduceJWT`](jwt_produce.ProduceJWT.md) Set "exp" (Expiration Time) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `input` | `string` \| `number` | "exp" (Expiration Time) Claim value to set on the JWT Claims Set. When number is passed that is used as a value, when string is passed it is resolved to a time span and added to the current timestamp. | #### Returns [`ProduceJWT`](jwt_produce.ProduceJWT.md) ___ ### setIssuedAt ▸ **setIssuedAt**(`input?`): [`ProduceJWT`](jwt_produce.ProduceJWT.md) Set "iat" (Issued At) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `input?` | `number` | "iat" (Issued At) Claim value to set on the JWT Claims Set. Default is current timestamp. | #### Returns [`ProduceJWT`](jwt_produce.ProduceJWT.md) ___ ### setIssuer ▸ **setIssuer**(`issuer`): [`ProduceJWT`](jwt_produce.ProduceJWT.md) Set "iss" (Issuer) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `issuer` | `string` | "Issuer" Claim value to set on the JWT Claims Set. | #### Returns [`ProduceJWT`](jwt_produce.ProduceJWT.md) ___ ### setJti ▸ **setJti**(`jwtId`): [`ProduceJWT`](jwt_produce.ProduceJWT.md) Set "jti" (JWT ID) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwtId` | `string` | "jti" (JWT ID) Claim value to set on the JWT Claims Set. | #### Returns [`ProduceJWT`](jwt_produce.ProduceJWT.md) ___ ### setNotBefore ▸ **setNotBefore**(`input`): [`ProduceJWT`](jwt_produce.ProduceJWT.md) Set "nbf" (Not Before) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `input` | `string` \| `number` | "nbf" (Not Before) Claim value to set on the JWT Claims Set. When number is passed that is used as a value, when string is passed it is resolved to a time span and added to the current timestamp. | #### Returns [`ProduceJWT`](jwt_produce.ProduceJWT.md) ___ ### setSubject ▸ **setSubject**(`subject`): [`ProduceJWT`](jwt_produce.ProduceJWT.md) Set "sub" (Subject) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `subject` | `string` | "sub" (Subject) Claim value to set on the JWT Claims Set. | #### Returns [`ProduceJWT`](jwt_produce.ProduceJWT.md) jose-4.11.4/docs/classes/jwt_sign.SignJWT.md000066400000000000000000000215421437043056600205740ustar00rootroot00000000000000# Class: SignJWT [💗 Help the project](https://github.com/sponsors/panva) The SignJWT class is a utility for creating Compact JWS formatted JWT strings. **`example`** Usage with a symmetric secret ```js const secret = new TextEncoder().encode( 'cc7e0d44fd473002f1c42167459001140ec6389b7353f8088f4d9a95f2f596f2', ) const alg = 'HS256' const jwt = await new jose.SignJWT({ 'urn:example:claim': true }) .setProtectedHeader({ alg }) .setIssuedAt() .setIssuer('urn:example:issuer') .setAudience('urn:example:audience') .setExpirationTime('2h') .sign(secret) console.log(jwt) ``` **`example`** Usage with a private PKCS#8 encoded RSA key ```js const alg = 'RS256' const pkcs8 = `-----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDCFg4UrY5xtulv /NXKmL1J4qI1SopAfTNMo3X7p+kJO7plqUYjzaztcre1qfh0m33Sm1Q8oPbO/GpP MU1/HgcceytgJ/b4UwufVVMl9BrMDYG8moDBylbVupFQS3Ly1L9i/iFG9Z9A9xzY Zzf799A45bnvNXL6s2glzvjiRvfQ2NDF0anTcnZLcYtC7ugq1IMM+ihAcPfw8Qw2 chN/SmP4qAM+PKaQwagmU7doqmmyN9u38AfoYZ1GCFhEs5TBBT6H6h9YdHeVtiIq 1c+fl03biSIfLrV7dUBD39gBmXBcL/30Ya3D82mCEUC4zg/UkOfQOmkmV3Lc8YUL QZ8EJkBLAgMBAAECggEAVuVE/KEP6323WjpbBdAIv7HGahGrgGANvbxZsIhm34ls VOPK0XDegZkhAybMZHjRhp+gwVxX5ChC+J3cUpOBH5FNxElgW6HizD2Jcq6t6LoL YgPSrfEHm71iHg8JsgrqfUnGYFzMJmv88C6WdCtpgG/qJV1K00/Ly1G1QKoBffEs +v4fAMJrCbUdCz1qWto+PU+HLMEo+krfEpGgcmtZeRlDADh8cETMQlgQfQX2VWq/ aAP4a1SXmo+j0cvRU4W5Fj0RVwNesIpetX2ZFz4p/JmB5sWFEj/fC7h5z2lq+6Bm e2T3BHtXkIxoBW0/pYVnASC8P2puO5FnVxDmWuHDYQKBgQDTuuBd3+0tSFVEX+DU 5qpFmHm5nyGItZRJTS+71yg5pBxq1KqNCUjAtbxR0q//fwauakh+BwRVCPOrqsUG jBSb3NYE70Srp6elqxgkE54PwQx4Mr6exJPnseM9U4K+hULllf5yjM9edreJE1nV NVgFjeyafQhrHKwgr7PERJ/ikwKBgQDqqsT1M+EJLmI1HtCspOG6cu7q3gf/wKRh E8tu84i3YyBnI8uJkKy92RNVI5fvpBARe3tjSdM25rr2rcrcmF/5g6Q9ImxZPGCt 86eOgO9ErNtbc4TEgybsP319UE4O41aKeNiBTAZKoYCxv/dMqG0j4avmWzd+foHq gSNUvR2maQKBgQCYeqOsV2B6VPY7KIVFLd0AA9/dwvEmgAYLiA/RShDI+hwQ/5jX uxDu37KAhqeC65sHLrmIMUt4Zdr+DRyZK3aIDNEAesPMjw/X6lCXYp1ZISD2yyym MFGH8X8CIkstI9Faf9vf6PJKSFrC1/HA7wq17VCwrUzLvrljTMW8meM/CwKBgCpo 2leGHLFQFKeM/iF1WuYbR1pi7gcmhY6VyTowARFDdOOu8GXYI5/bz0afvCGvAMho DJCREv7lC/zww6zCTPYG+HOj+PjXlJFba3ixjIxYwPvyEJiDK1Ge18sB7Fl8dHNq C5ayaqCqN1voWYUdGzxU2IA1E/5kVo5O8FesJeOhAoGBAImJbZFf+D5kA32Xxhac 59lLWBCsocvvbd1cvDMNlRywAAyhsCb1SuX4nEAK9mrSBdfmoF2Nm3eilfsOds0f K5mX069IKG82CMqh3Mzptd7e7lyb9lsoGO0BAtjho3cWtha/UZ70vfaMzGuZ6JmQ ak6k+8+UFd93M4z0Qo74OhXB -----END PRIVATE KEY----` const privateKey = await jose.importPKCS8(pkcs8, alg) const jwt = await new jose.SignJWT({ 'urn:example:claim': true }) .setProtectedHeader({ alg }) .setIssuedAt() .setIssuer('urn:example:issuer') .setAudience('urn:example:audience') .setExpirationTime('2h') .sign(privateKey) console.log(jwt) ``` **`example`** Usage with a private JWK encoded RSA key ```js const alg = 'RS256' const jwk = { kty: 'RSA', n: 'whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw', e: 'AQAB', d: 'VuVE_KEP6323WjpbBdAIv7HGahGrgGANvbxZsIhm34lsVOPK0XDegZkhAybMZHjRhp-gwVxX5ChC-J3cUpOBH5FNxElgW6HizD2Jcq6t6LoLYgPSrfEHm71iHg8JsgrqfUnGYFzMJmv88C6WdCtpgG_qJV1K00_Ly1G1QKoBffEs-v4fAMJrCbUdCz1qWto-PU-HLMEo-krfEpGgcmtZeRlDADh8cETMQlgQfQX2VWq_aAP4a1SXmo-j0cvRU4W5Fj0RVwNesIpetX2ZFz4p_JmB5sWFEj_fC7h5z2lq-6Bme2T3BHtXkIxoBW0_pYVnASC8P2puO5FnVxDmWuHDYQ', p: '07rgXd_tLUhVRF_g1OaqRZh5uZ8hiLWUSU0vu9coOaQcatSqjQlIwLW8UdKv_38GrmpIfgcEVQjzq6rFBowUm9zWBO9Eq6enpasYJBOeD8EMeDK-nsST57HjPVOCvoVC5ZX-cozPXna3iRNZ1TVYBY3smn0IaxysIK-zxESf4pM', q: '6qrE9TPhCS5iNR7QrKThunLu6t4H_8CkYRPLbvOIt2MgZyPLiZCsvdkTVSOX76QQEXt7Y0nTNua69q3K3Jhf-YOkPSJsWTxgrfOnjoDvRKzbW3OExIMm7D99fVBODuNWinjYgUwGSqGAsb_3TKhtI-Gr5ls3fn6B6oEjVL0dpmk', dp: 'mHqjrFdgelT2OyiFRS3dAAPf3cLxJoAGC4gP0UoQyPocEP-Y17sQ7t-ygIanguubBy65iDFLeGXa_g0cmSt2iAzRAHrDzI8P1-pQl2KdWSEg9ssspjBRh_F_AiJLLSPRWn_b3-jySkhawtfxwO8Kte1QsK1My765Y0zFvJnjPws', dq: 'KmjaV4YcsVAUp4z-IXVa5htHWmLuByaFjpXJOjABEUN0467wZdgjn9vPRp-8Ia8AyGgMkJES_uUL_PDDrMJM9gb4c6P4-NeUkVtreLGMjFjA-_IQmIMrUZ7XywHsWXx0c2oLlrJqoKo3W-hZhR0bPFTYgDUT_mRWjk7wV6wl46E', qi: 'iYltkV_4PmQDfZfGFpzn2UtYEKyhy-9t3Vy8Mw2VHLAADKGwJvVK5ficQAr2atIF1-agXY2bd6KV-w52zR8rmZfTr0gobzYIyqHczOm13t7uXJv2WygY7QEC2OGjdxa2Fr9RnvS99ozMa5nomZBqTqT7z5QV33czjPRCjvg6FcE', } const privateKey = await jose.importJWK(jwk, alg) const jwt = await new jose.SignJWT({ 'urn:example:claim': true }) .setProtectedHeader({ alg }) .setIssuedAt() .setIssuer('urn:example:issuer') .setAudience('urn:example:audience') .setExpirationTime('2h') .sign(privateKey) console.log(jwt) ``` ## Table of contents ### Constructors - [constructor](jwt_sign.SignJWT.md#constructor) ### Methods - [setAudience](jwt_sign.SignJWT.md#setaudience) - [setExpirationTime](jwt_sign.SignJWT.md#setexpirationtime) - [setIssuedAt](jwt_sign.SignJWT.md#setissuedat) - [setIssuer](jwt_sign.SignJWT.md#setissuer) - [setJti](jwt_sign.SignJWT.md#setjti) - [setNotBefore](jwt_sign.SignJWT.md#setnotbefore) - [setProtectedHeader](jwt_sign.SignJWT.md#setprotectedheader) - [setSubject](jwt_sign.SignJWT.md#setsubject) - [sign](jwt_sign.SignJWT.md#sign) ## Constructors ### constructor • **new SignJWT**(`payload`) #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `payload` | [`JWTPayload`](../interfaces/types.JWTPayload.md) | The JWT Claims Set object. | ## Methods ### setAudience ▸ **setAudience**(`audience`): [`SignJWT`](jwt_sign.SignJWT.md) Set "aud" (Audience) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `audience` | `string` \| `string`[] | "aud" (Audience) Claim value to set on the JWT Claims Set. | #### Returns [`SignJWT`](jwt_sign.SignJWT.md) ___ ### setExpirationTime ▸ **setExpirationTime**(`input`): [`SignJWT`](jwt_sign.SignJWT.md) Set "exp" (Expiration Time) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `input` | `string` \| `number` | "exp" (Expiration Time) Claim value to set on the JWT Claims Set. When number is passed that is used as a value, when string is passed it is resolved to a time span and added to the current timestamp. | #### Returns [`SignJWT`](jwt_sign.SignJWT.md) ___ ### setIssuedAt ▸ **setIssuedAt**(`input?`): [`SignJWT`](jwt_sign.SignJWT.md) Set "iat" (Issued At) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `input?` | `number` | "iat" (Issued At) Claim value to set on the JWT Claims Set. Default is current timestamp. | #### Returns [`SignJWT`](jwt_sign.SignJWT.md) ___ ### setIssuer ▸ **setIssuer**(`issuer`): [`SignJWT`](jwt_sign.SignJWT.md) Set "iss" (Issuer) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `issuer` | `string` | "Issuer" Claim value to set on the JWT Claims Set. | #### Returns [`SignJWT`](jwt_sign.SignJWT.md) ___ ### setJti ▸ **setJti**(`jwtId`): [`SignJWT`](jwt_sign.SignJWT.md) Set "jti" (JWT ID) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwtId` | `string` | "jti" (JWT ID) Claim value to set on the JWT Claims Set. | #### Returns [`SignJWT`](jwt_sign.SignJWT.md) ___ ### setNotBefore ▸ **setNotBefore**(`input`): [`SignJWT`](jwt_sign.SignJWT.md) Set "nbf" (Not Before) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `input` | `string` \| `number` | "nbf" (Not Before) Claim value to set on the JWT Claims Set. When number is passed that is used as a value, when string is passed it is resolved to a time span and added to the current timestamp. | #### Returns [`SignJWT`](jwt_sign.SignJWT.md) ___ ### setProtectedHeader ▸ **setProtectedHeader**(`protectedHeader`): [`SignJWT`](jwt_sign.SignJWT.md) Sets the JWS Protected Header on the SignJWT object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `protectedHeader` | [`JWTHeaderParameters`](../interfaces/types.JWTHeaderParameters.md) | JWS Protected Header. Must contain an "alg" (JWS Algorithm) property. | #### Returns [`SignJWT`](jwt_sign.SignJWT.md) ___ ### setSubject ▸ **setSubject**(`subject`): [`SignJWT`](jwt_sign.SignJWT.md) Set "sub" (Subject) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `subject` | `string` | "sub" (Subject) Claim value to set on the JWT Claims Set. | #### Returns [`SignJWT`](jwt_sign.SignJWT.md) ___ ### sign ▸ **sign**(`key`, `options?`): `Promise`<`string`\> Signs and returns the JWT. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Private Key or Secret to sign the JWT with. | | `options?` | [`SignOptions`](../interfaces/types.SignOptions.md) | JWT Sign options. | #### Returns `Promise`<`string`\> jose-4.11.4/docs/classes/jwt_unsecured.UnsecuredJWT.md000066400000000000000000000115411437043056600226640ustar00rootroot00000000000000# Class: UnsecuredJWT [💗 Help the project](https://github.com/sponsors/panva) The UnsecuredJWT class is a utility for dealing with `{ "alg": "none" }` Unsecured JWTs. **`example`** Encoding ```js const unsecuredJwt = new jose.UnsecuredJWT({ 'urn:example:claim': true }) .setIssuedAt() .setIssuer('urn:example:issuer') .setAudience('urn:example:audience') .setExpirationTime('2h') .encode() console.log(unsecuredJwt) ``` **`example`** Decoding ```js const payload = jose.UnsecuredJWT.decode(jwt, { issuer: 'urn:example:issuer', audience: 'urn:example:audience', }) console.log(payload) ``` ## Table of contents ### Constructors - [constructor](jwt_unsecured.UnsecuredJWT.md#constructor) ### Methods - [decode](jwt_unsecured.UnsecuredJWT.md#decode) - [encode](jwt_unsecured.UnsecuredJWT.md#encode) - [setAudience](jwt_unsecured.UnsecuredJWT.md#setaudience) - [setExpirationTime](jwt_unsecured.UnsecuredJWT.md#setexpirationtime) - [setIssuedAt](jwt_unsecured.UnsecuredJWT.md#setissuedat) - [setIssuer](jwt_unsecured.UnsecuredJWT.md#setissuer) - [setJti](jwt_unsecured.UnsecuredJWT.md#setjti) - [setNotBefore](jwt_unsecured.UnsecuredJWT.md#setnotbefore) - [setSubject](jwt_unsecured.UnsecuredJWT.md#setsubject) ## Constructors ### constructor • **new UnsecuredJWT**(`payload`) #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `payload` | [`JWTPayload`](../interfaces/types.JWTPayload.md) | The JWT Claims Set object. | ## Methods ### decode ▸ `Static` **decode**(`jwt`, `options?`): [`UnsecuredResult`](../interfaces/jwt_unsecured.UnsecuredResult.md) Decodes an unsecured JWT. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwt` | `string` | Unsecured JWT to decode the payload of. | | `options?` | [`JWTClaimVerificationOptions`](../interfaces/types.JWTClaimVerificationOptions.md) | JWT Claims Set validation options. | #### Returns [`UnsecuredResult`](../interfaces/jwt_unsecured.UnsecuredResult.md) ___ ### encode ▸ **encode**(): `string` Encodes the Unsecured JWT. #### Returns `string` ___ ### setAudience ▸ **setAudience**(`audience`): [`UnsecuredJWT`](jwt_unsecured.UnsecuredJWT.md) Set "aud" (Audience) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `audience` | `string` \| `string`[] | "aud" (Audience) Claim value to set on the JWT Claims Set. | #### Returns [`UnsecuredJWT`](jwt_unsecured.UnsecuredJWT.md) ___ ### setExpirationTime ▸ **setExpirationTime**(`input`): [`UnsecuredJWT`](jwt_unsecured.UnsecuredJWT.md) Set "exp" (Expiration Time) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `input` | `string` \| `number` | "exp" (Expiration Time) Claim value to set on the JWT Claims Set. When number is passed that is used as a value, when string is passed it is resolved to a time span and added to the current timestamp. | #### Returns [`UnsecuredJWT`](jwt_unsecured.UnsecuredJWT.md) ___ ### setIssuedAt ▸ **setIssuedAt**(`input?`): [`UnsecuredJWT`](jwt_unsecured.UnsecuredJWT.md) Set "iat" (Issued At) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `input?` | `number` | "iat" (Issued At) Claim value to set on the JWT Claims Set. Default is current timestamp. | #### Returns [`UnsecuredJWT`](jwt_unsecured.UnsecuredJWT.md) ___ ### setIssuer ▸ **setIssuer**(`issuer`): [`UnsecuredJWT`](jwt_unsecured.UnsecuredJWT.md) Set "iss" (Issuer) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `issuer` | `string` | "Issuer" Claim value to set on the JWT Claims Set. | #### Returns [`UnsecuredJWT`](jwt_unsecured.UnsecuredJWT.md) ___ ### setJti ▸ **setJti**(`jwtId`): [`UnsecuredJWT`](jwt_unsecured.UnsecuredJWT.md) Set "jti" (JWT ID) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwtId` | `string` | "jti" (JWT ID) Claim value to set on the JWT Claims Set. | #### Returns [`UnsecuredJWT`](jwt_unsecured.UnsecuredJWT.md) ___ ### setNotBefore ▸ **setNotBefore**(`input`): [`UnsecuredJWT`](jwt_unsecured.UnsecuredJWT.md) Set "nbf" (Not Before) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `input` | `string` \| `number` | "nbf" (Not Before) Claim value to set on the JWT Claims Set. When number is passed that is used as a value, when string is passed it is resolved to a time span and added to the current timestamp. | #### Returns [`UnsecuredJWT`](jwt_unsecured.UnsecuredJWT.md) ___ ### setSubject ▸ **setSubject**(`subject`): [`UnsecuredJWT`](jwt_unsecured.UnsecuredJWT.md) Set "sub" (Subject) Claim. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `subject` | `string` | "sub" (Subject) Claim value to set on the JWT Claims Set. | #### Returns [`UnsecuredJWT`](jwt_unsecured.UnsecuredJWT.md) jose-4.11.4/docs/classes/util_errors.JOSEAlgNotAllowed.md000066400000000000000000000015761437043056600232160ustar00rootroot00000000000000# Class: JOSEAlgNotAllowed [💗 Help the project](https://github.com/sponsors/panva) An error subclass thrown when a JOSE Algorithm is not allowed per developer preference. ## Table of contents ### Constructors - [constructor](util_errors.JOSEAlgNotAllowed.md#constructor) ### Properties - [code](util_errors.JOSEAlgNotAllowed.md#code) ### Accessors - [code](util_errors.JOSEAlgNotAllowed.md#code-1) ## Constructors ### constructor • **new JOSEAlgNotAllowed**(`message?`) #### Parameters | Name | Type | | :------ | :------ | | `message?` | `string` | ## Properties ### code • **code**: `string` = `'ERR_JOSE_ALG_NOT_ALLOWED'` A unique error code for the particular error subclass. ## Accessors ### code • `Static` `get` **code**(): ``"ERR_JOSE_ALG_NOT_ALLOWED"`` A unique error code for the particular error subclass. #### Returns ``"ERR_JOSE_ALG_NOT_ALLOWED"`` jose-4.11.4/docs/classes/util_errors.JOSEError.md000066400000000000000000000014371437043056600216070ustar00rootroot00000000000000# Class: JOSEError [💗 Help the project](https://github.com/sponsors/panva) A generic Error subclass that all other specific JOSE Error subclasses inherit from. ## Table of contents ### Constructors - [constructor](util_errors.JOSEError.md#constructor) ### Properties - [code](util_errors.JOSEError.md#code) ### Accessors - [code](util_errors.JOSEError.md#code-1) ## Constructors ### constructor • **new JOSEError**(`message?`) #### Parameters | Name | Type | | :------ | :------ | | `message?` | `string` | ## Properties ### code • **code**: `string` = `'ERR_JOSE_GENERIC'` A unique error code for the particular error subclass. ## Accessors ### code • `Static` `get` **code**(): `string` A unique error code for the particular error subclass. #### Returns `string` jose-4.11.4/docs/classes/util_errors.JOSENotSupported.md000066400000000000000000000016271437043056600231650ustar00rootroot00000000000000# Class: JOSENotSupported [💗 Help the project](https://github.com/sponsors/panva) An error subclass thrown when a particular feature or algorithm is not supported by this implementation or JOSE in general. ## Table of contents ### Constructors - [constructor](util_errors.JOSENotSupported.md#constructor) ### Properties - [code](util_errors.JOSENotSupported.md#code) ### Accessors - [code](util_errors.JOSENotSupported.md#code-1) ## Constructors ### constructor • **new JOSENotSupported**(`message?`) #### Parameters | Name | Type | | :------ | :------ | | `message?` | `string` | ## Properties ### code • **code**: `string` = `'ERR_JOSE_NOT_SUPPORTED'` A unique error code for the particular error subclass. ## Accessors ### code • `Static` `get` **code**(): ``"ERR_JOSE_NOT_SUPPORTED"`` A unique error code for the particular error subclass. #### Returns ``"ERR_JOSE_NOT_SUPPORTED"`` jose-4.11.4/docs/classes/util_errors.JWEDecryptionFailed.md000066400000000000000000000017731437043056600236330ustar00rootroot00000000000000# Class: JWEDecryptionFailed [💗 Help the project](https://github.com/sponsors/panva) An error subclass thrown when a JWE ciphertext decryption fails. ## Table of contents ### Constructors - [constructor](util_errors.JWEDecryptionFailed.md#constructor) ### Properties - [code](util_errors.JWEDecryptionFailed.md#code) - [message](util_errors.JWEDecryptionFailed.md#message) ### Accessors - [code](util_errors.JWEDecryptionFailed.md#code-1) ## Constructors ### constructor • **new JWEDecryptionFailed**(`message?`) #### Parameters | Name | Type | | :------ | :------ | | `message?` | `string` | ## Properties ### code • **code**: `string` = `'ERR_JWE_DECRYPTION_FAILED'` A unique error code for the particular error subclass. ___ ### message • **message**: `string` = `'decryption operation failed'` ## Accessors ### code • `Static` `get` **code**(): ``"ERR_JWE_DECRYPTION_FAILED"`` A unique error code for the particular error subclass. #### Returns ``"ERR_JWE_DECRYPTION_FAILED"`` jose-4.11.4/docs/classes/util_errors.JWEInvalid.md000066400000000000000000000014301437043056600217620ustar00rootroot00000000000000# Class: JWEInvalid [💗 Help the project](https://github.com/sponsors/panva) An error subclass thrown when a JWE is invalid. ## Table of contents ### Constructors - [constructor](util_errors.JWEInvalid.md#constructor) ### Properties - [code](util_errors.JWEInvalid.md#code) ### Accessors - [code](util_errors.JWEInvalid.md#code-1) ## Constructors ### constructor • **new JWEInvalid**(`message?`) #### Parameters | Name | Type | | :------ | :------ | | `message?` | `string` | ## Properties ### code • **code**: `string` = `'ERR_JWE_INVALID'` A unique error code for the particular error subclass. ## Accessors ### code • `Static` `get` **code**(): ``"ERR_JWE_INVALID"`` A unique error code for the particular error subclass. #### Returns ``"ERR_JWE_INVALID"`` jose-4.11.4/docs/classes/util_errors.JWKInvalid.md000066400000000000000000000014301437043056600217700ustar00rootroot00000000000000# Class: JWKInvalid [💗 Help the project](https://github.com/sponsors/panva) An error subclass thrown when a JWK is invalid. ## Table of contents ### Constructors - [constructor](util_errors.JWKInvalid.md#constructor) ### Properties - [code](util_errors.JWKInvalid.md#code) ### Accessors - [code](util_errors.JWKInvalid.md#code-1) ## Constructors ### constructor • **new JWKInvalid**(`message?`) #### Parameters | Name | Type | | :------ | :------ | | `message?` | `string` | ## Properties ### code • **code**: `string` = `'ERR_JWK_INVALID'` A unique error code for the particular error subclass. ## Accessors ### code • `Static` `get` **code**(): ``"ERR_JWK_INVALID"`` A unique error code for the particular error subclass. #### Returns ``"ERR_JWK_INVALID"`` jose-4.11.4/docs/classes/util_errors.JWKSInvalid.md000066400000000000000000000014411437043056600221150ustar00rootroot00000000000000# Class: JWKSInvalid [💗 Help the project](https://github.com/sponsors/panva) An error subclass thrown when a JWKS is invalid. ## Table of contents ### Constructors - [constructor](util_errors.JWKSInvalid.md#constructor) ### Properties - [code](util_errors.JWKSInvalid.md#code) ### Accessors - [code](util_errors.JWKSInvalid.md#code-1) ## Constructors ### constructor • **new JWKSInvalid**(`message?`) #### Parameters | Name | Type | | :------ | :------ | | `message?` | `string` | ## Properties ### code • **code**: `string` = `'ERR_JWKS_INVALID'` A unique error code for the particular error subclass. ## Accessors ### code • `Static` `get` **code**(): ``"ERR_JWKS_INVALID"`` A unique error code for the particular error subclass. #### Returns ``"ERR_JWKS_INVALID"`` jose-4.11.4/docs/classes/util_errors.JWKSMultipleMatchingKeys.md000066400000000000000000000021021437043056600246240ustar00rootroot00000000000000# Class: JWKSMultipleMatchingKeys [💗 Help the project](https://github.com/sponsors/panva) An error subclass thrown when multiple keys match from a JWKS. ## Table of contents ### Constructors - [constructor](util_errors.JWKSMultipleMatchingKeys.md#constructor) ### Properties - [code](util_errors.JWKSMultipleMatchingKeys.md#code) - [message](util_errors.JWKSMultipleMatchingKeys.md#message) ### Accessors - [code](util_errors.JWKSMultipleMatchingKeys.md#code-1) ## Constructors ### constructor • **new JWKSMultipleMatchingKeys**(`message?`) #### Parameters | Name | Type | | :------ | :------ | | `message?` | `string` | ## Properties ### code • **code**: `string` = `'ERR_JWKS_MULTIPLE_MATCHING_KEYS'` A unique error code for the particular error subclass. ___ ### message • **message**: `string` = `'multiple matching keys found in the JSON Web Key Set'` ## Accessors ### code • `Static` `get` **code**(): ``"ERR_JWKS_MULTIPLE_MATCHING_KEYS"`` A unique error code for the particular error subclass. #### Returns ``"ERR_JWKS_MULTIPLE_MATCHING_KEYS"`` jose-4.11.4/docs/classes/util_errors.JWKSNoMatchingKey.md000066400000000000000000000017701437043056600232340ustar00rootroot00000000000000# Class: JWKSNoMatchingKey [💗 Help the project](https://github.com/sponsors/panva) An error subclass thrown when no keys match from a JWKS. ## Table of contents ### Constructors - [constructor](util_errors.JWKSNoMatchingKey.md#constructor) ### Properties - [code](util_errors.JWKSNoMatchingKey.md#code) - [message](util_errors.JWKSNoMatchingKey.md#message) ### Accessors - [code](util_errors.JWKSNoMatchingKey.md#code-1) ## Constructors ### constructor • **new JWKSNoMatchingKey**(`message?`) #### Parameters | Name | Type | | :------ | :------ | | `message?` | `string` | ## Properties ### code • **code**: `string` = `'ERR_JWKS_NO_MATCHING_KEY'` A unique error code for the particular error subclass. ___ ### message • **message**: `string` = `'no applicable key found in the JSON Web Key Set'` ## Accessors ### code • `Static` `get` **code**(): ``"ERR_JWKS_NO_MATCHING_KEY"`` A unique error code for the particular error subclass. #### Returns ``"ERR_JWKS_NO_MATCHING_KEY"`` jose-4.11.4/docs/classes/util_errors.JWKSTimeout.md000066400000000000000000000016341437043056600221610ustar00rootroot00000000000000# Class: JWKSTimeout [💗 Help the project](https://github.com/sponsors/panva) Timeout was reached when retrieving the JWKS response. ## Table of contents ### Constructors - [constructor](util_errors.JWKSTimeout.md#constructor) ### Properties - [code](util_errors.JWKSTimeout.md#code) - [message](util_errors.JWKSTimeout.md#message) ### Accessors - [code](util_errors.JWKSTimeout.md#code-1) ## Constructors ### constructor • **new JWKSTimeout**(`message?`) #### Parameters | Name | Type | | :------ | :------ | | `message?` | `string` | ## Properties ### code • **code**: `string` = `'ERR_JWKS_TIMEOUT'` A unique error code for the particular error subclass. ___ ### message • **message**: `string` = `'request timed out'` ## Accessors ### code • `Static` `get` **code**(): ``"ERR_JWKS_TIMEOUT"`` A unique error code for the particular error subclass. #### Returns ``"ERR_JWKS_TIMEOUT"`` jose-4.11.4/docs/classes/util_errors.JWSInvalid.md000066400000000000000000000014301437043056600220000ustar00rootroot00000000000000# Class: JWSInvalid [💗 Help the project](https://github.com/sponsors/panva) An error subclass thrown when a JWS is invalid. ## Table of contents ### Constructors - [constructor](util_errors.JWSInvalid.md#constructor) ### Properties - [code](util_errors.JWSInvalid.md#code) ### Accessors - [code](util_errors.JWSInvalid.md#code-1) ## Constructors ### constructor • **new JWSInvalid**(`message?`) #### Parameters | Name | Type | | :------ | :------ | | `message?` | `string` | ## Properties ### code • **code**: `string` = `'ERR_JWS_INVALID'` A unique error code for the particular error subclass. ## Accessors ### code • `Static` `get` **code**(): ``"ERR_JWS_INVALID"`` A unique error code for the particular error subclass. #### Returns ``"ERR_JWS_INVALID"`` jose-4.11.4/docs/classes/util_errors.JWSSignatureVerificationFailed.md000066400000000000000000000021421437043056600260240ustar00rootroot00000000000000# Class: JWSSignatureVerificationFailed [💗 Help the project](https://github.com/sponsors/panva) An error subclass thrown when JWS signature verification fails. ## Table of contents ### Constructors - [constructor](util_errors.JWSSignatureVerificationFailed.md#constructor) ### Properties - [code](util_errors.JWSSignatureVerificationFailed.md#code) - [message](util_errors.JWSSignatureVerificationFailed.md#message) ### Accessors - [code](util_errors.JWSSignatureVerificationFailed.md#code-1) ## Constructors ### constructor • **new JWSSignatureVerificationFailed**(`message?`) #### Parameters | Name | Type | | :------ | :------ | | `message?` | `string` | ## Properties ### code • **code**: `string` = `'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'` A unique error code for the particular error subclass. ___ ### message • **message**: `string` = `'signature verification failed'` ## Accessors ### code • `Static` `get` **code**(): ``"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"`` A unique error code for the particular error subclass. #### Returns ``"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"`` jose-4.11.4/docs/classes/util_errors.JWTClaimValidationFailed.md000066400000000000000000000026201437043056600245620ustar00rootroot00000000000000# Class: JWTClaimValidationFailed [💗 Help the project](https://github.com/sponsors/panva) An error subclass thrown when a JWT Claim Set member validation fails. ## Implemented by - [`JWTExpired`](util_errors.JWTExpired.md) ## Table of contents ### Constructors - [constructor](util_errors.JWTClaimValidationFailed.md#constructor) ### Properties - [claim](util_errors.JWTClaimValidationFailed.md#claim) - [code](util_errors.JWTClaimValidationFailed.md#code) - [reason](util_errors.JWTClaimValidationFailed.md#reason) ### Accessors - [code](util_errors.JWTClaimValidationFailed.md#code-1) ## Constructors ### constructor • **new JWTClaimValidationFailed**(`message`, `claim?`, `reason?`) #### Parameters | Name | Type | Default value | | :------ | :------ | :------ | | `message` | `string` | `undefined` | | `claim` | `string` | `'unspecified'` | | `reason` | `string` | `'unspecified'` | ## Properties ### claim • **claim**: `string` The Claim for which the validation failed. ___ ### code • **code**: `string` = `'ERR_JWT_CLAIM_VALIDATION_FAILED'` A unique error code for the particular error subclass. ___ ### reason • **reason**: `string` Reason code for the validation failure. ## Accessors ### code • `Static` `get` **code**(): ``"ERR_JWT_CLAIM_VALIDATION_FAILED"`` A unique error code for the particular error subclass. #### Returns ``"ERR_JWT_CLAIM_VALIDATION_FAILED"`` jose-4.11.4/docs/classes/util_errors.JWTExpired.md000066400000000000000000000023771437043056600220260ustar00rootroot00000000000000# Class: JWTExpired [💗 Help the project](https://github.com/sponsors/panva) An error subclass thrown when a JWT is expired. ## Implements - [`JWTClaimValidationFailed`](util_errors.JWTClaimValidationFailed.md) ## Table of contents ### Constructors - [constructor](util_errors.JWTExpired.md#constructor) ### Properties - [claim](util_errors.JWTExpired.md#claim) - [code](util_errors.JWTExpired.md#code) - [reason](util_errors.JWTExpired.md#reason) ### Accessors - [code](util_errors.JWTExpired.md#code-1) ## Constructors ### constructor • **new JWTExpired**(`message`, `claim?`, `reason?`) #### Parameters | Name | Type | Default value | | :------ | :------ | :------ | | `message` | `string` | `undefined` | | `claim` | `string` | `'unspecified'` | | `reason` | `string` | `'unspecified'` | ## Properties ### claim • **claim**: `string` The Claim for which the validation failed. ___ ### code • **code**: `string` = `'ERR_JWT_EXPIRED'` A unique error code for the particular error subclass. ___ ### reason • **reason**: `string` Reason code for the validation failure. ## Accessors ### code • `Static` `get` **code**(): ``"ERR_JWT_EXPIRED"`` A unique error code for the particular error subclass. #### Returns ``"ERR_JWT_EXPIRED"`` jose-4.11.4/docs/classes/util_errors.JWTInvalid.md000066400000000000000000000014301437043056600220010ustar00rootroot00000000000000# Class: JWTInvalid [💗 Help the project](https://github.com/sponsors/panva) An error subclass thrown when a JWT is invalid. ## Table of contents ### Constructors - [constructor](util_errors.JWTInvalid.md#constructor) ### Properties - [code](util_errors.JWTInvalid.md#code) ### Accessors - [code](util_errors.JWTInvalid.md#code-1) ## Constructors ### constructor • **new JWTInvalid**(`message?`) #### Parameters | Name | Type | | :------ | :------ | | `message?` | `string` | ## Properties ### code • **code**: `string` = `'ERR_JWT_INVALID'` A unique error code for the particular error subclass. ## Accessors ### code • `Static` `get` **code**(): ``"ERR_JWT_INVALID"`` A unique error code for the particular error subclass. #### Returns ``"ERR_JWT_INVALID"`` jose-4.11.4/docs/functions/000077500000000000000000000000001437043056600155115ustar00rootroot00000000000000jose-4.11.4/docs/functions/jwe_compact_decrypt.compactDecrypt.md000066400000000000000000000041511437043056600250410ustar00rootroot00000000000000# Function: compactDecrypt [💗 Help the project](https://github.com/sponsors/panva) ▸ **compactDecrypt**(`jwe`, `key`, `options?`): `Promise`<[`CompactDecryptResult`](../interfaces/types.CompactDecryptResult.md)\> Decrypts a Compact JWE. **`example`** Usage ```js const jwe = 'eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0.nyQ19eq9ogh9wA7fFtnI2oouzy5_8b5DeLkoRMfi2yijgfTs2zEnayCEofz_qhnL-nwszabd9qUeHv0-IwvhhJJS7GUJOU3ikiIe42qcIAFme1A_Fo9CTxw4XTOy-I5qanl8So91u6hwfyN1VxAqVLsSE7_23EC-gfGEg_5znew9PyXXsOIE-K_HH7IQowRrlZ1X_bM_Liu53RzDpLDvRz59mp3S8L56YqpM8FexFGTGpEaoTcEIst375qncYt3-79IVR7gZN1RWsWgjPatfvVbnh74PglQcATSf3UUhaW0OAKn6q7r3PDx6DIKQ35bgHQg5QopuN00eIfLQL2trGw.W3grIVj5HVuAb76X.6PcuDe5D6ttWFYyv0oqqdDXfI2R8wBg1F2Q80UUA_Gv8eEimNWfxIWdLxrjzgQGSvIhxmFKuLM0.a93_Ug3uZHuczj70Zavx8Q' const { plaintext, protectedHeader } = await jose.compactDecrypt(jwe, privateKey) console.log(protectedHeader) console.log(new TextDecoder().decode(plaintext)) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwe` | `string` \| `Uint8Array` | Compact JWE. | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Private Key or Secret to decrypt the JWE with. | | `options?` | [`DecryptOptions`](../interfaces/types.DecryptOptions.md) | JWE Decryption options. | #### Returns `Promise`<[`CompactDecryptResult`](../interfaces/types.CompactDecryptResult.md)\> ▸ **compactDecrypt**(`jwe`, `getKey`, `options?`): `Promise`<[`CompactDecryptResult`](../interfaces/types.CompactDecryptResult.md) & [`ResolvedKey`](../interfaces/types.ResolvedKey.md)\> #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwe` | `string` \| `Uint8Array` | Compact JWE. | | `getKey` | [`CompactDecryptGetKey`](../interfaces/jwe_compact_decrypt.CompactDecryptGetKey.md) | Function resolving Private Key or Secret to decrypt the JWE with. | | `options?` | [`DecryptOptions`](../interfaces/types.DecryptOptions.md) | JWE Decryption options. | #### Returns `Promise`<[`CompactDecryptResult`](../interfaces/types.CompactDecryptResult.md) & [`ResolvedKey`](../interfaces/types.ResolvedKey.md)\> jose-4.11.4/docs/functions/jwe_flattened_decrypt.flattenedDecrypt.md000066400000000000000000000046611437043056600257070ustar00rootroot00000000000000# Function: flattenedDecrypt [💗 Help the project](https://github.com/sponsors/panva) ▸ **flattenedDecrypt**(`jwe`, `key`, `options?`): `Promise`<[`FlattenedDecryptResult`](../interfaces/types.FlattenedDecryptResult.md)\> Decrypts a Flattened JWE. **`example`** Usage ```js const jwe = { ciphertext: '9EzjFISUyoG-ifC2mSihfP0DPC80yeyrxhTzKt1C_VJBkxeBG0MI4Te61Pk45RAGubUvBpU9jm4', iv: '8Fy7A_IuoX5VXG9s', tag: 'W76IYV6arGRuDSaSyWrQNg', encrypted_key: 'Z6eD4UK_yFb5ZoKvKkGAdqywEG_m0e4IYo0x8Vf30LAMJcsc-_zSgIeiF82teZyYi2YYduHKoqImk7MRnoPZOlEs0Q5BNK1OgBmSOhCE8DFyqh9Zh48TCTP6lmBQ52naqoUJFMtHzu-0LwZH26hxos0GP3Dt19O379MJB837TdKKa87skq0zHaVLAquRHOBF77GI54Bc7O49d8aOrSu1VEFGMThlW2caspPRiTSePDMDPq7_WGk50izRhB3Asl9wmP9wEeaTrkJKRnQj5ips1SAZ1hDBsqEQKKukxP1HtdcopHV5_qgwU8Hjm5EwSLMluMQuiE6hwlkXGOujZLVizA', aad: 'VGhlIEZlbGxvd3NoaXAgb2YgdGhlIFJpbmc', protected: 'eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0', } const { plaintext, protectedHeader, additionalAuthenticatedData } = await jose.flattenedDecrypt(jwe, privateKey) console.log(protectedHeader) const decoder = new TextDecoder() console.log(decoder.decode(plaintext)) console.log(decoder.decode(additionalAuthenticatedData)) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwe` | [`FlattenedJWE`](../interfaces/types.FlattenedJWE.md) | Flattened JWE. | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Private Key or Secret to decrypt the JWE with. | | `options?` | [`DecryptOptions`](../interfaces/types.DecryptOptions.md) | JWE Decryption options. | #### Returns `Promise`<[`FlattenedDecryptResult`](../interfaces/types.FlattenedDecryptResult.md)\> ▸ **flattenedDecrypt**(`jwe`, `getKey`, `options?`): `Promise`<[`FlattenedDecryptResult`](../interfaces/types.FlattenedDecryptResult.md) & [`ResolvedKey`](../interfaces/types.ResolvedKey.md)\> #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwe` | [`FlattenedJWE`](../interfaces/types.FlattenedJWE.md) | Flattened JWE. | | `getKey` | [`FlattenedDecryptGetKey`](../interfaces/jwe_flattened_decrypt.FlattenedDecryptGetKey.md) | Function resolving Private Key or Secret to decrypt the JWE with. | | `options?` | [`DecryptOptions`](../interfaces/types.DecryptOptions.md) | JWE Decryption options. | #### Returns `Promise`<[`FlattenedDecryptResult`](../interfaces/types.FlattenedDecryptResult.md) & [`ResolvedKey`](../interfaces/types.ResolvedKey.md)\> jose-4.11.4/docs/functions/jwe_general_decrypt.generalDecrypt.md000066400000000000000000000046571437043056600250320ustar00rootroot00000000000000# Function: generalDecrypt [💗 Help the project](https://github.com/sponsors/panva) ▸ **generalDecrypt**(`jwe`, `key`, `options?`): `Promise`<[`GeneralDecryptResult`](../interfaces/types.GeneralDecryptResult.md)\> Decrypts a General JWE. **`example`** Usage ```js const jwe = { ciphertext: '9EzjFISUyoG-ifC2mSihfP0DPC80yeyrxhTzKt1C_VJBkxeBG0MI4Te61Pk45RAGubUvBpU9jm4', iv: '8Fy7A_IuoX5VXG9s', tag: 'W76IYV6arGRuDSaSyWrQNg', aad: 'VGhlIEZlbGxvd3NoaXAgb2YgdGhlIFJpbmc', protected: 'eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0', recipients: [ { encrypted_key: 'Z6eD4UK_yFb5ZoKvKkGAdqywEG_m0e4IYo0x8Vf30LAMJcsc-_zSgIeiF82teZyYi2YYduHKoqImk7MRnoPZOlEs0Q5BNK1OgBmSOhCE8DFyqh9Zh48TCTP6lmBQ52naqoUJFMtHzu-0LwZH26hxos0GP3Dt19O379MJB837TdKKa87skq0zHaVLAquRHOBF77GI54Bc7O49d8aOrSu1VEFGMThlW2caspPRiTSePDMDPq7_WGk50izRhB3Asl9wmP9wEeaTrkJKRnQj5ips1SAZ1hDBsqEQKKukxP1HtdcopHV5_qgwU8Hjm5EwSLMluMQuiE6hwlkXGOujZLVizA', }, ], } const { plaintext, protectedHeader, additionalAuthenticatedData } = await jose.generalDecrypt(jwe, privateKey) console.log(protectedHeader) const decoder = new TextDecoder() console.log(decoder.decode(plaintext)) console.log(decoder.decode(additionalAuthenticatedData)) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwe` | [`GeneralJWE`](../interfaces/types.GeneralJWE.md) | General JWE. | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Private Key or Secret to decrypt the JWE with. | | `options?` | [`DecryptOptions`](../interfaces/types.DecryptOptions.md) | JWE Decryption options. | #### Returns `Promise`<[`GeneralDecryptResult`](../interfaces/types.GeneralDecryptResult.md)\> ▸ **generalDecrypt**(`jwe`, `getKey`, `options?`): `Promise`<[`GeneralDecryptResult`](../interfaces/types.GeneralDecryptResult.md) & [`ResolvedKey`](../interfaces/types.ResolvedKey.md)\> #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwe` | [`GeneralJWE`](../interfaces/types.GeneralJWE.md) | General JWE. | | `getKey` | [`GeneralDecryptGetKey`](../interfaces/jwe_general_decrypt.GeneralDecryptGetKey.md) | Function resolving Private Key or Secret to decrypt the JWE with. | | `options?` | [`DecryptOptions`](../interfaces/types.DecryptOptions.md) | JWE Decryption options. | #### Returns `Promise`<[`GeneralDecryptResult`](../interfaces/types.GeneralDecryptResult.md) & [`ResolvedKey`](../interfaces/types.ResolvedKey.md)\> jose-4.11.4/docs/functions/jwk_embedded.EmbeddedJWK.md000066400000000000000000000027371437043056600225140ustar00rootroot00000000000000# Function: EmbeddedJWK [💗 Help the project](https://github.com/sponsors/panva) ▸ **EmbeddedJWK**(`protectedHeader`, `token`): `Promise`<[`KeyLike`](../types/types.KeyLike.md)\> EmbeddedJWK is an implementation of a GetKeyFunction intended to be used with the JWS/JWT verify operations whenever you need to opt-in to verify signatures with a public key embedded in the token's "jwk" (JSON Web Key) Header Parameter. It is recommended to combine this with the verify function's `algorithms` option to define accepted JWS "alg" (Algorithm) Header Parameter values. **`example`** Usage ```js const jwt = 'eyJqd2siOnsiY3J2IjoiUC0yNTYiLCJ4IjoiVU05ZzVuS25aWFlvdldBbE03NmNMejl2VG96UmpfX0NIVV9kT2wtZ09vRSIsInkiOiJkczhhZVF3MWwyY0RDQTdiQ2tPTnZ3REtwWEFidFhqdnFDbGVZSDhXc19VIiwia3R5IjoiRUMifSwiYWxnIjoiRVMyNTYifQ.eyJpc3MiOiJ1cm46ZXhhbXBsZTppc3N1ZXIiLCJhdWQiOiJ1cm46ZXhhbXBsZTphdWRpZW5jZSIsImlhdCI6MTYwNDU4MDc5NH0.60boak3_dErnW47ZPty1C0nrjeVq86EN_eK0GOq6K8w2OA0thKoBxFK4j-NuU9yZ_A9UKGxPT_G87DladBaV9g' const { payload, protectedHeader } = await jose.jwtVerify(jwt, jose.EmbeddedJWK, { issuer: 'urn:example:issuer', audience: 'urn:example:audience', }) console.log(protectedHeader) console.log(payload) ``` #### Parameters | Name | Type | | :------ | :------ | | `protectedHeader` | [`JWSHeaderParameters`](../interfaces/types.JWSHeaderParameters.md) | | `token` | [`FlattenedJWSInput`](../interfaces/types.FlattenedJWSInput.md) | #### Returns `Promise`<[`KeyLike`](../types/types.KeyLike.md)\> jose-4.11.4/docs/functions/jwk_thumbprint.calculateJwkThumbprint.md000066400000000000000000000016351437043056600255740ustar00rootroot00000000000000# Function: calculateJwkThumbprint [💗 Help the project](https://github.com/sponsors/panva) ▸ **calculateJwkThumbprint**(`jwk`, `digestAlgorithm?`): `Promise`<`string`\> Calculates a base64url-encoded JSON Web Key (JWK) Thumbprint **`example`** Usage ```js const thumbprint = await jose.calculateJwkThumbprint({ kty: 'EC', crv: 'P-256', x: 'jJ6Flys3zK9jUhnOHf6G49Dyp5hah6CNP84-gY-n9eo', y: 'nhI6iD5eFXgBTLt_1p3aip-5VbZeMhxeFSpjfEAf7Ww', }) console.log(thumbprint) // 'w9eYdC6_s_tLQ8lH6PUpc0mddazaqtPgeC2IgWDiqY8' ``` **`see`** [RFC7638](https://www.rfc-editor.org/rfc/rfc7638) #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwk` | [`JWK`](../interfaces/types.JWK.md) | JSON Web Key. | | `digestAlgorithm?` | ``"sha256"`` \| ``"sha384"`` \| ``"sha512"`` | Digest Algorithm to use for calculating the thumbprint. Default is "sha256". | #### Returns `Promise`<`string`\> jose-4.11.4/docs/functions/jwk_thumbprint.calculateJwkThumbprintUri.md000066400000000000000000000017101437043056600262460ustar00rootroot00000000000000# Function: calculateJwkThumbprintUri [💗 Help the project](https://github.com/sponsors/panva) ▸ **calculateJwkThumbprintUri**(`jwk`, `digestAlgorithm?`): `Promise`<`string`\> Calculates a JSON Web Key (JWK) Thumbprint URI **`example`** Usage ```js const thumbprintUri = await jose.calculateJwkThumbprintUri({ kty: 'EC', crv: 'P-256', x: 'jJ6Flys3zK9jUhnOHf6G49Dyp5hah6CNP84-gY-n9eo', y: 'nhI6iD5eFXgBTLt_1p3aip-5VbZeMhxeFSpjfEAf7Ww', }) console.log(thumbprint) // 'urn:ietf:params:oauth:jwk-thumbprint:sha-256:w9eYdC6_s_tLQ8lH6PUpc0mddazaqtPgeC2IgWDiqY8' ``` **`see`** [RFC9278](https://www.rfc-editor.org/rfc/rfc9278) #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwk` | [`JWK`](../interfaces/types.JWK.md) | JSON Web Key. | | `digestAlgorithm?` | ``"sha256"`` \| ``"sha384"`` \| ``"sha512"`` | Digest Algorithm to use for calculating the thumbprint. Default is "sha256". | #### Returns `Promise`<`string`\> jose-4.11.4/docs/functions/jwks_local.createLocalJWKSet.md000066400000000000000000000033561437043056600234370ustar00rootroot00000000000000# Function: createLocalJWKSet [💗 Help the project](https://github.com/sponsors/panva) ▸ **createLocalJWKSet**(`jwks`): [`GetKeyFunction`](../interfaces/types.GetKeyFunction.md)<[`JWSHeaderParameters`](../interfaces/types.JWSHeaderParameters.md), [`FlattenedJWSInput`](../interfaces/types.FlattenedJWSInput.md)\> Returns a function that resolves to a key object from a locally stored, or otherwise available, JSON Web Key Set. Only a single public key must match the selection process. **`example`** Usage ```js const JWKS = jose.createLocalJWKSet({ keys: [ { kty: 'RSA', e: 'AQAB', n: '12oBZRhCiZFJLcPg59LkZZ9mdhSMTKAQZYq32k_ti5SBB6jerkh-WzOMAO664r_qyLkqHUSp3u5SbXtseZEpN3XPWGKSxjsy-1JyEFTdLSYe6f9gfrmxkUF_7DTpq0gn6rntP05g2-wFW50YO7mosfdslfrTJYWHFhJALabAeYirYD7-9kqq9ebfFMF4sRRELbv9oi36As6Q9B3Qb5_C1rAzqfao_PCsf9EPsTZsVVVkA5qoIAr47lo1ipfiBPxUCCNSdvkmDTYgvvRm6ZoMjFbvOtgyts55fXKdMWv7I9HMD5HwE9uW839PWA514qhbcIsXEYSFMPMV6fnlsiZvQQ', alg: 'PS256', }, { crv: 'P-256', kty: 'EC', x: 'ySK38C1jBdLwDsNWKzzBHqKYEE5Cgv-qjWvorUXk9fw', y: '_LeQBw07cf5t57Iavn4j-BqJsAD1dpoz8gokd3sBsOo', alg: 'ES256', }, ], }) const { payload, protectedHeader } = await jose.jwtVerify(jwt, JWKS, { issuer: 'urn:example:issuer', audience: 'urn:example:audience', }) console.log(protectedHeader) console.log(payload) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwks` | [`JSONWebKeySet`](../interfaces/types.JSONWebKeySet.md) | JSON Web Key Set formatted object. | #### Returns [`GetKeyFunction`](../interfaces/types.GetKeyFunction.md)<[`JWSHeaderParameters`](../interfaces/types.JWSHeaderParameters.md), [`FlattenedJWSInput`](../interfaces/types.FlattenedJWSInput.md)\> jose-4.11.4/docs/functions/jwks_remote.createRemoteJWKSet.md000066400000000000000000000030431437043056600240320ustar00rootroot00000000000000# Function: createRemoteJWKSet [💗 Help the project](https://github.com/sponsors/panva) ▸ **createRemoteJWKSet**(`url`, `options?`): [`GetKeyFunction`](../interfaces/types.GetKeyFunction.md)<[`JWSHeaderParameters`](../interfaces/types.JWSHeaderParameters.md), [`FlattenedJWSInput`](../interfaces/types.FlattenedJWSInput.md)\> Returns a function that resolves to a key object downloaded from a remote endpoint returning a JSON Web Key Set, that is, for example, an OAuth 2.0 or OIDC jwks_uri. Only a single public key must match the selection process. The JSON Web Key Set is fetched when no key matches the selection process but only as frequently as the `cooldownDuration` option allows, to prevent abuse. **`example`** Usage ```js const JWKS = jose.createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs')) const { payload, protectedHeader } = await jose.jwtVerify(jwt, JWKS, { issuer: 'urn:example:issuer', audience: 'urn:example:audience', }) console.log(protectedHeader) console.log(payload) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `url` | [`URL`]( https://developer.mozilla.org/en-US/docs/Web/API/URL ) | URL to fetch the JSON Web Key Set from. | | `options?` | [`RemoteJWKSetOptions`](../interfaces/jwks_remote.RemoteJWKSetOptions.md) | Options for the remote JSON Web Key Set. | #### Returns [`GetKeyFunction`](../interfaces/types.GetKeyFunction.md)<[`JWSHeaderParameters`](../interfaces/types.JWSHeaderParameters.md), [`FlattenedJWSInput`](../interfaces/types.FlattenedJWSInput.md)\> jose-4.11.4/docs/functions/jws_compact_verify.compactVerify.md000066400000000000000000000034231437043056600245440ustar00rootroot00000000000000# Function: compactVerify [💗 Help the project](https://github.com/sponsors/panva) ▸ **compactVerify**(`jws`, `key`, `options?`): `Promise`<[`CompactVerifyResult`](../interfaces/types.CompactVerifyResult.md)\> Verifies the signature and format of and afterwards decodes the Compact JWS. **`example`** Usage ```js const jws = 'eyJhbGciOiJFUzI1NiJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4.kkAs_gPPxWMI3rHuVlxHaTPfDWDoqdI8jSvuSmqV-8IHIWXg9mcAeC9ggV-45ZHRbiRJ3obUIFo1rHphPA5URg' const { payload, protectedHeader } = await jose.compactVerify(jws, publicKey) console.log(protectedHeader) console.log(new TextDecoder().decode(payload)) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jws` | `string` \| `Uint8Array` | Compact JWS. | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Key to verify the JWS with. | | `options?` | [`VerifyOptions`](../interfaces/types.VerifyOptions.md) | JWS Verify options. | #### Returns `Promise`<[`CompactVerifyResult`](../interfaces/types.CompactVerifyResult.md)\> ▸ **compactVerify**(`jws`, `getKey`, `options?`): `Promise`<[`CompactVerifyResult`](../interfaces/types.CompactVerifyResult.md) & [`ResolvedKey`](../interfaces/types.ResolvedKey.md)\> #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jws` | `string` \| `Uint8Array` | Compact JWS. | | `getKey` | [`CompactVerifyGetKey`](../interfaces/jws_compact_verify.CompactVerifyGetKey.md) | Function resolving a key to verify the JWS with. | | `options?` | [`VerifyOptions`](../interfaces/types.VerifyOptions.md) | JWS Verify options. | #### Returns `Promise`<[`CompactVerifyResult`](../interfaces/types.CompactVerifyResult.md) & [`ResolvedKey`](../interfaces/types.ResolvedKey.md)\> jose-4.11.4/docs/functions/jws_flattened_verify.flattenedVerify.md000066400000000000000000000037171437043056600254120ustar00rootroot00000000000000# Function: flattenedVerify [💗 Help the project](https://github.com/sponsors/panva) ▸ **flattenedVerify**(`jws`, `key`, `options?`): `Promise`<[`FlattenedVerifyResult`](../interfaces/types.FlattenedVerifyResult.md)\> Verifies the signature and format of and afterwards decodes the Flattened JWS. **`example`** Usage ```js const decoder = new TextDecoder() const jws = { signature: 'FVVOXwj6kD3DqdfD9yYqfT2W9jv-Nop4kOehp_DeDGNB5dQNSPRvntBY6xH3uxlCxE8na9d_kyhYOcanpDJ0EA', payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4', protected: 'eyJhbGciOiJFUzI1NiJ9', } const { payload, protectedHeader } = await jose.flattenedVerify(jws, publicKey) console.log(protectedHeader) console.log(decoder.decode(payload)) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jws` | [`FlattenedJWSInput`](../interfaces/types.FlattenedJWSInput.md) | Flattened JWS. | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Key to verify the JWS with. | | `options?` | [`VerifyOptions`](../interfaces/types.VerifyOptions.md) | JWS Verify options. | #### Returns `Promise`<[`FlattenedVerifyResult`](../interfaces/types.FlattenedVerifyResult.md)\> ▸ **flattenedVerify**(`jws`, `getKey`, `options?`): `Promise`<[`FlattenedVerifyResult`](../interfaces/types.FlattenedVerifyResult.md) & [`ResolvedKey`](../interfaces/types.ResolvedKey.md)\> #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jws` | [`FlattenedJWSInput`](../interfaces/types.FlattenedJWSInput.md) | Flattened JWS. | | `getKey` | [`FlattenedVerifyGetKey`](../interfaces/jws_flattened_verify.FlattenedVerifyGetKey.md) | Function resolving a key to verify the JWS with. | | `options?` | [`VerifyOptions`](../interfaces/types.VerifyOptions.md) | JWS Verify options. | #### Returns `Promise`<[`FlattenedVerifyResult`](../interfaces/types.FlattenedVerifyResult.md) & [`ResolvedKey`](../interfaces/types.ResolvedKey.md)\> jose-4.11.4/docs/functions/jws_general_verify.generalVerify.md000066400000000000000000000036711437043056600245270ustar00rootroot00000000000000# Function: generalVerify [💗 Help the project](https://github.com/sponsors/panva) ▸ **generalVerify**(`jws`, `key`, `options?`): `Promise`<[`GeneralVerifyResult`](../interfaces/types.GeneralVerifyResult.md)\> Verifies the signature and format of and afterwards decodes the General JWS. **`example`** Usage ```js const jws = { payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4', signatures: [ { signature: 'FVVOXwj6kD3DqdfD9yYqfT2W9jv-Nop4kOehp_DeDGNB5dQNSPRvntBY6xH3uxlCxE8na9d_kyhYOcanpDJ0EA', protected: 'eyJhbGciOiJFUzI1NiJ9', }, ], } const { payload, protectedHeader } = await jose.generalVerify(jws, publicKey) console.log(protectedHeader) console.log(new TextDecoder().decode(payload)) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jws` | [`GeneralJWSInput`](../interfaces/types.GeneralJWSInput.md) | General JWS. | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Key to verify the JWS with. | | `options?` | [`VerifyOptions`](../interfaces/types.VerifyOptions.md) | JWS Verify options. | #### Returns `Promise`<[`GeneralVerifyResult`](../interfaces/types.GeneralVerifyResult.md)\> ▸ **generalVerify**(`jws`, `getKey`, `options?`): `Promise`<[`GeneralVerifyResult`](../interfaces/types.GeneralVerifyResult.md) & [`ResolvedKey`](../interfaces/types.ResolvedKey.md)\> #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jws` | [`GeneralJWSInput`](../interfaces/types.GeneralJWSInput.md) | General JWS. | | `getKey` | [`GeneralVerifyGetKey`](../interfaces/jws_general_verify.GeneralVerifyGetKey.md) | Function resolving a key to verify the JWS with. | | `options?` | [`VerifyOptions`](../interfaces/types.VerifyOptions.md) | JWS Verify options. | #### Returns `Promise`<[`GeneralVerifyResult`](../interfaces/types.GeneralVerifyResult.md) & [`ResolvedKey`](../interfaces/types.ResolvedKey.md)\> jose-4.11.4/docs/functions/jwt_decrypt.jwtDecrypt.md000066400000000000000000000042161437043056600225320ustar00rootroot00000000000000# Function: jwtDecrypt [💗 Help the project](https://github.com/sponsors/panva) ▸ **jwtDecrypt**(`jwt`, `key`, `options?`): `Promise`<[`JWTDecryptResult`](../interfaces/types.JWTDecryptResult.md)\> Verifies the JWT format (to be a JWE Compact format), decrypts the ciphertext, validates the JWT Claims Set. **`example`** Usage ```js const secret = jose.base64url.decode('zH4NRP1HMALxxCFnRZABFA7GOJtzU_gIj02alfL1lvI') const jwt = 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..MB66qstZBPxAXKdsjet_lA.WHbtJTl4taHp7otOHLq3hBvv0yNPsPEKHYInmCPdDDeyV1kU-f-tGEiU4FxlSqkqAT2hVs8_wMNiQFAzPU1PUgIqWCPsBrPP3TtxYsrtwagpn4SvCsUsx0Mhw9ZhliAO8CLmCBQkqr_T9AcYsz5uZw.7nX9m7BGUu_u1p1qFHzyIg' const { payload, protectedHeader } = await jose.jwtDecrypt(jwt, secret, { issuer: 'urn:example:issuer', audience: 'urn:example:audience', }) console.log(protectedHeader) console.log(payload) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwt` | `string` \| `Uint8Array` | JSON Web Token value (encoded as JWE). | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Private Key or Secret to decrypt and verify the JWT with. | | `options?` | [`JWTDecryptOptions`](../interfaces/jwt_decrypt.JWTDecryptOptions.md) | JWT Decryption and JWT Claims Set validation options. | #### Returns `Promise`<[`JWTDecryptResult`](../interfaces/types.JWTDecryptResult.md)\> ▸ **jwtDecrypt**(`jwt`, `getKey`, `options?`): `Promise`<[`JWTDecryptResult`](../interfaces/types.JWTDecryptResult.md) & [`ResolvedKey`](../interfaces/types.ResolvedKey.md)\> #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwt` | `string` \| `Uint8Array` | JSON Web Token value (encoded as JWE). | | `getKey` | [`JWTDecryptGetKey`](../interfaces/jwt_decrypt.JWTDecryptGetKey.md) | Function resolving Private Key or Secret to decrypt and verify the JWT with. | | `options?` | [`JWTDecryptOptions`](../interfaces/jwt_decrypt.JWTDecryptOptions.md) | JWT Decryption and JWT Claims Set validation options. | #### Returns `Promise`<[`JWTDecryptResult`](../interfaces/types.JWTDecryptResult.md) & [`ResolvedKey`](../interfaces/types.ResolvedKey.md)\> jose-4.11.4/docs/functions/jwt_verify.jwtVerify.md000066400000000000000000000116671437043056600222260ustar00rootroot00000000000000# Function: jwtVerify [💗 Help the project](https://github.com/sponsors/panva) ▸ **jwtVerify**(`jwt`, `key`, `options?`): `Promise`<[`JWTVerifyResult`](../interfaces/types.JWTVerifyResult.md)\> Verifies the JWT format (to be a JWS Compact format), verifies the JWS signature, validates the JWT Claims Set. **`example`** Usage with a symmetric secret ```js const secret = new TextEncoder().encode( 'cc7e0d44fd473002f1c42167459001140ec6389b7353f8088f4d9a95f2f596f2', ) const jwt = 'eyJhbGciOiJIUzI1NiJ9.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6dHJ1ZSwiaWF0IjoxNjY5MDU2MjMxLCJpc3MiOiJ1cm46ZXhhbXBsZTppc3N1ZXIiLCJhdWQiOiJ1cm46ZXhhbXBsZTphdWRpZW5jZSJ9.C4iSlLfAUMBq--wnC6VqD9gEOhwpRZpoRarE0m7KEnI' const { payload, protectedHeader } = await jose.jwtVerify(jwt, secret, { issuer: 'urn:example:issuer', audience: 'urn:example:audience', }) console.log(protectedHeader) console.log(payload) ``` **`example`** Usage with a public SPKI encoded RSA key ```js const alg = 'RS256' const spki = `-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwhYOFK2Ocbbpb/zVypi9 SeKiNUqKQH0zTKN1+6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4H HHsrYCf2+FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS/Yv4hRvWfQPcc2Gc3+/fQ OOW57zVy+rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj +KgDPjymkMGoJlO3aKppsjfbt/AH6GGdRghYRLOUwQU+h+ofWHR3lbYiKtXPn5dN 24kiHy61e3VAQ9/YAZlwXC/99GGtw/NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZA SwIDAQAB -----END PUBLIC KEY-----` const publicKey = await jose.importSPKI(spki, alg) const jwt = 'eyJhbGciOiJSUzI1NiJ9.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6dHJ1ZSwiaWF0IjoxNjY5MDU2NDg4LCJpc3MiOiJ1cm46ZXhhbXBsZTppc3N1ZXIiLCJhdWQiOiJ1cm46ZXhhbXBsZTphdWRpZW5jZSJ9.gXrPZ3yM_60dMXGE69dusbpzYASNA-XIOwsb5D5xYnSxyj6_D6OR_uR_1vqhUm4AxZxcrH1_-XJAve9HCw8az_QzHcN-nETt-v6stCsYrn6Bv1YOc-mSJRZ8ll57KVqLbCIbjKwerNX5r2_Qg2TwmJzQdRs-AQDhy-s_DlJd8ql6wR4n-kDZpar-pwIvz4fFIN0Fj57SXpAbLrV6Eo4Byzl0xFD8qEYEpBwjrMMfxCZXTlAVhAq6KCoGlDTwWuExps342-0UErEtyIqDnDGcrfNWiUsoo8j-29IpKd-w9-C388u-ChCxoHz--H8WmMSZzx3zTXsZ5lXLZ9IKfanDKg' const { payload, protectedHeader } = await jose.jwtVerify(jwt, publicKey, { issuer: 'urn:example:issuer', audience: 'urn:example:audience', }) console.log(protectedHeader) console.log(payload) ``` **`example`** Usage with a public JWK encoded RSA key ```js const alg = 'RS256' const jwk = { kty: 'RSA', n: 'whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw', e: 'AQAB', } const publicKey = await jose.importJWK(jwk, alg) const jwt = 'eyJhbGciOiJSUzI1NiJ9.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6dHJ1ZSwiaWF0IjoxNjY5MDU2NDg4LCJpc3MiOiJ1cm46ZXhhbXBsZTppc3N1ZXIiLCJhdWQiOiJ1cm46ZXhhbXBsZTphdWRpZW5jZSJ9.gXrPZ3yM_60dMXGE69dusbpzYASNA-XIOwsb5D5xYnSxyj6_D6OR_uR_1vqhUm4AxZxcrH1_-XJAve9HCw8az_QzHcN-nETt-v6stCsYrn6Bv1YOc-mSJRZ8ll57KVqLbCIbjKwerNX5r2_Qg2TwmJzQdRs-AQDhy-s_DlJd8ql6wR4n-kDZpar-pwIvz4fFIN0Fj57SXpAbLrV6Eo4Byzl0xFD8qEYEpBwjrMMfxCZXTlAVhAq6KCoGlDTwWuExps342-0UErEtyIqDnDGcrfNWiUsoo8j-29IpKd-w9-C388u-ChCxoHz--H8WmMSZzx3zTXsZ5lXLZ9IKfanDKg' const { payload, protectedHeader } = await jose.jwtVerify(jwt, publicKey, { issuer: 'urn:example:issuer', audience: 'urn:example:audience', }) console.log(protectedHeader) console.log(payload) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwt` | `string` \| `Uint8Array` | JSON Web Token value (encoded as JWS). | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Key to verify the JWT with. | | `options?` | [`JWTVerifyOptions`](../interfaces/jwt_verify.JWTVerifyOptions.md) | JWT Decryption and JWT Claims Set validation options. | #### Returns `Promise`<[`JWTVerifyResult`](../interfaces/types.JWTVerifyResult.md)\> ▸ **jwtVerify**(`jwt`, `getKey`, `options?`): `Promise`<[`JWTVerifyResult`](../interfaces/types.JWTVerifyResult.md) & [`ResolvedKey`](../interfaces/types.ResolvedKey.md)\> **`example`** Usage with a public JSON Web Key Set hosted on a remote URL ```js const JWKS = jose.createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs')) const { payload, protectedHeader } = await jose.jwtVerify(jwt, JWKS, { issuer: 'urn:example:issuer', audience: 'urn:example:audience', }) console.log(protectedHeader) console.log(payload) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwt` | `string` \| `Uint8Array` | JSON Web Token value (encoded as JWS). | | `getKey` | [`JWTVerifyGetKey`](../interfaces/jwt_verify.JWTVerifyGetKey.md) | Function resolving a key to verify the JWT with. | | `options?` | [`JWTVerifyOptions`](../interfaces/jwt_verify.JWTVerifyOptions.md) | JWT Decryption and JWT Claims Set validation options. | #### Returns `Promise`<[`JWTVerifyResult`](../interfaces/types.JWTVerifyResult.md) & [`ResolvedKey`](../interfaces/types.ResolvedKey.md)\> jose-4.11.4/docs/functions/key_export.exportJWK.md000066400000000000000000000012171437043056600221210ustar00rootroot00000000000000# Function: exportJWK [💗 Help the project](https://github.com/sponsors/panva) ▸ **exportJWK**(`key`): `Promise`<[`JWK`](../interfaces/types.JWK.md)\> Exports a runtime-specific key representation (KeyLike) to a JWK. **`example`** Usage ```js const privateJwk = await jose.exportJWK(privateKey) const publicJwk = await jose.exportJWK(publicKey) console.log(privateJwk) console.log(publicJwk) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `key` | `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) | Key representation to export as JWK. | #### Returns `Promise`<[`JWK`](../interfaces/types.JWK.md)\> jose-4.11.4/docs/functions/key_export.exportPKCS8.md000066400000000000000000000011261437043056600223150ustar00rootroot00000000000000# Function: exportPKCS8 [💗 Help the project](https://github.com/sponsors/panva) ▸ **exportPKCS8**(`key`): `Promise`<`string`\> Exports a runtime-specific private key representation (KeyObject or CryptoKey) to a PEM-encoded PKCS8 string format. **`example`** Usage ```js const pkcs8Pem = await jose.exportPKCS8(privateKey) console.log(pkcs8Pem) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `key` | [`KeyLike`](../types/types.KeyLike.md) | Key representation to transform to a PEM-encoded PKCS8 string format. | #### Returns `Promise`<`string`\> jose-4.11.4/docs/functions/key_export.exportSPKI.md000066400000000000000000000011151437043056600222310ustar00rootroot00000000000000# Function: exportSPKI [💗 Help the project](https://github.com/sponsors/panva) ▸ **exportSPKI**(`key`): `Promise`<`string`\> Exports a runtime-specific public key representation (KeyObject or CryptoKey) to a PEM-encoded SPKI string format. **`example`** Usage ```js const spkiPem = await jose.exportSPKI(publicKey) console.log(spkiPem) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `key` | [`KeyLike`](../types/types.KeyLike.md) | Key representation to transform to a PEM-encoded SPKI string format. | #### Returns `Promise`<`string`\> jose-4.11.4/docs/functions/key_generate_key_pair.generateKeyPair.md000066400000000000000000000021511437043056600254350ustar00rootroot00000000000000# Function: generateKeyPair [💗 Help the project](https://github.com/sponsors/panva) ▸ **generateKeyPair**(`alg`, `options?`): `Promise`<[`GenerateKeyPairResult`](../interfaces/key_generate_key_pair.GenerateKeyPairResult.md)\> Generates a private and a public key for a given JWA algorithm identifier. This can only generate asymmetric key pairs. For symmetric secrets use the `generateSecret` function. Note: Under Web Cryptography API runtime the `privateKey` is generated with `extractable` set to `false` by default. **`example`** Usage ```js const { publicKey, privateKey } = await jose.generateKeyPair('PS256') console.log(publicKey) console.log(privateKey) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `alg` | `string` | JWA Algorithm Identifier to be used with the generated key pair. | | `options?` | [`GenerateKeyPairOptions`](../interfaces/key_generate_key_pair.GenerateKeyPairOptions.md) | Additional options passed down to the key pair generation. | #### Returns `Promise`<[`GenerateKeyPairResult`](../interfaces/key_generate_key_pair.GenerateKeyPairResult.md)\> jose-4.11.4/docs/functions/key_generate_secret.generateSecret.md000066400000000000000000000016021437043056600250000ustar00rootroot00000000000000# Function: generateSecret [💗 Help the project](https://github.com/sponsors/panva) ▸ **generateSecret**(`alg`, `options?`): `Promise`<[`KeyLike`](../types/types.KeyLike.md) \| `Uint8Array`\> Generates a symmetric secret key for a given JWA algorithm identifier. Note: Under Web Cryptography API runtime the secret key is generated with `extractable` set to `false` by default. **`example`** Usage ```js const secret = await jose.generateSecret('HS256') console.log(secret) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `alg` | `string` | JWA Algorithm Identifier to be used with the generated secret. | | `options?` | [`GenerateSecretOptions`](../interfaces/key_generate_secret.GenerateSecretOptions.md) | Additional options passed down to the secret generation. | #### Returns `Promise`<[`KeyLike`](../types/types.KeyLike.md) \| `Uint8Array`\> jose-4.11.4/docs/functions/key_import.importJWK.md000066400000000000000000000035231437043056600221050ustar00rootroot00000000000000# Function: importJWK [💗 Help the project](https://github.com/sponsors/panva) ▸ **importJWK**(`jwk`, `alg?`, `octAsKeyObject?`): `Promise`<[`KeyLike`](../types/types.KeyLike.md) \| `Uint8Array`\> Imports a JWK to a runtime-specific key representation (KeyLike). Either JWK "alg" (Algorithm) Parameter must be present or the optional "alg" argument. When running on a runtime using [Web Cryptography API](https://www.w3.org/TR/WebCryptoAPI/) the jwk parameters "use", "key_ops", and "ext" are also used in the resulting `CryptoKey`. See [Algorithm Key Requirements](https://github.com/panva/jose/issues/210) to learn about key to algorithm requirements and mapping. **`example`** Usage ```js const ecPublicKey = await jose.importJWK( { crv: 'P-256', kty: 'EC', x: 'ySK38C1jBdLwDsNWKzzBHqKYEE5Cgv-qjWvorUXk9fw', y: '_LeQBw07cf5t57Iavn4j-BqJsAD1dpoz8gokd3sBsOo', }, 'ES256', ) const rsaPublicKey = await jose.importJWK( { kty: 'RSA', e: 'AQAB', n: '12oBZRhCiZFJLcPg59LkZZ9mdhSMTKAQZYq32k_ti5SBB6jerkh-WzOMAO664r_qyLkqHUSp3u5SbXtseZEpN3XPWGKSxjsy-1JyEFTdLSYe6f9gfrmxkUF_7DTpq0gn6rntP05g2-wFW50YO7mosfdslfrTJYWHFhJALabAeYirYD7-9kqq9ebfFMF4sRRELbv9oi36As6Q9B3Qb5_C1rAzqfao_PCsf9EPsTZsVVVkA5qoIAr47lo1ipfiBPxUCCNSdvkmDTYgvvRm6ZoMjFbvOtgyts55fXKdMWv7I9HMD5HwE9uW839PWA514qhbcIsXEYSFMPMV6fnlsiZvQQ', }, 'PS256', ) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwk` | [`JWK`](../interfaces/types.JWK.md) | JSON Web Key. | | `alg?` | `string` | JSON Web Algorithm identifier to be used with the imported key. Default is the "alg" property on the JWK. | | `octAsKeyObject?` | `boolean` | Forces a symmetric key to be imported to a KeyObject or CryptoKey. Default is true unless JWK "ext" (Extractable) is true. | #### Returns `Promise`<[`KeyLike`](../types/types.KeyLike.md) \| `Uint8Array`\> jose-4.11.4/docs/functions/key_import.importPKCS8.md000066400000000000000000000022451437043056600223020ustar00rootroot00000000000000# Function: importPKCS8 [💗 Help the project](https://github.com/sponsors/panva) ▸ **importPKCS8**(`pkcs8`, `alg`, `options?`): `Promise`<[`KeyLike`](../types/types.KeyLike.md)\> Imports a PEM-encoded PKCS#8 string as a runtime-specific private key representation (KeyObject or CryptoKey). See [Algorithm Key Requirements](https://github.com/panva/jose/issues/210) to learn about key to algorithm requirements and mapping. Encrypted keys are not supported. **`example`** Usage ```js const algorithm = 'ES256' const pkcs8 = `-----BEGIN PRIVATE KEY----- MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgiyvo0X+VQ0yIrOaN nlrnUclopnvuuMfoc8HHly3505OhRANCAAQWUcdZ8uTSAsFuwtNy4KtsKqgeqYxg l6kwL5D4N3pEGYGIDjV69Sw0zAt43480WqJv7HCL0mQnyqFmSrxj8jMa -----END PRIVATE KEY-----` const ecPrivateKey = await jose.importPKCS8(pkcs8, algorithm) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `pkcs8` | `string` | - | | `alg` | `string` | JSON Web Algorithm identifier to be used with the imported key. | | `options?` | [`PEMImportOptions`](../interfaces/key_import.PEMImportOptions.md) | - | #### Returns `Promise`<[`KeyLike`](../types/types.KeyLike.md)\> jose-4.11.4/docs/functions/key_import.importSPKI.md000066400000000000000000000020711437043056600222150ustar00rootroot00000000000000# Function: importSPKI [💗 Help the project](https://github.com/sponsors/panva) ▸ **importSPKI**(`spki`, `alg`, `options?`): `Promise`<[`KeyLike`](../types/types.KeyLike.md)\> Imports a PEM-encoded SPKI string as a runtime-specific public key representation (KeyObject or CryptoKey). See [Algorithm Key Requirements](https://github.com/panva/jose/issues/210) to learn about key to algorithm requirements and mapping. **`example`** Usage ```js const algorithm = 'ES256' const spki = `-----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFlHHWfLk0gLBbsLTcuCrbCqoHqmM YJepMC+Q+Dd6RBmBiA41evUsNMwLeN+PNFqib+xwi9JkJ8qhZkq8Y/IzGg== -----END PUBLIC KEY-----` const ecPublicKey = await jose.importSPKI(spki, algorithm) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `spki` | `string` | - | | `alg` | `string` | JSON Web Algorithm identifier to be used with the imported key. | | `options?` | [`PEMImportOptions`](../interfaces/key_import.PEMImportOptions.md) | - | #### Returns `Promise`<[`KeyLike`](../types/types.KeyLike.md)\> jose-4.11.4/docs/functions/key_import.importX509.md000066400000000000000000000026551437043056600221240ustar00rootroot00000000000000# Function: importX509 [💗 Help the project](https://github.com/sponsors/panva) ▸ **importX509**(`x509`, `alg`, `options?`): `Promise`<[`KeyLike`](../types/types.KeyLike.md)\> Imports the SPKI from an X.509 string certificate as a runtime-specific public key representation (KeyObject or CryptoKey). See [Algorithm Key Requirements](https://github.com/panva/jose/issues/210) to learn about key to algorithm requirements and mapping. **`example`** Usage ```js const algorithm = 'ES256' const x509 = `-----BEGIN CERTIFICATE----- MIIBXjCCAQSgAwIBAgIGAXvykuMKMAoGCCqGSM49BAMCMDYxNDAyBgNVBAMMK3Np QXBNOXpBdk1VaXhXVWVGaGtjZXg1NjJRRzFyQUhXaV96UlFQTVpQaG8wHhcNMjEw OTE3MDcwNTE3WhcNMjIwNzE0MDcwNTE3WjA2MTQwMgYDVQQDDCtzaUFwTTl6QXZN VWl4V1VlRmhrY2V4NTYyUUcxckFIV2lfelJRUE1aUGhvMFkwEwYHKoZIzj0CAQYI KoZIzj0DAQcDQgAE8PbPvCv5D5xBFHEZlBp/q5OEUymq7RIgWIi7tkl9aGSpYE35 UH+kBKDnphJO3odpPZ5gvgKs2nwRWcrDnUjYLDAKBggqhkjOPQQDAgNIADBFAiEA 1yyMTRe66MhEXID9+uVub7woMkNYd0LhSHwKSPMUUTkCIFQGsfm1ecXOpeGOufAh v+A1QWZMuTWqYt+uh/YSRNDn -----END CERTIFICATE-----` const ecPublicKey = await jose.importX509(x509, algorithm) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `x509` | `string` | - | | `alg` | `string` | JSON Web Algorithm identifier to be used with the imported key. | | `options?` | [`PEMImportOptions`](../interfaces/key_import.PEMImportOptions.md) | - | #### Returns `Promise`<[`KeyLike`](../types/types.KeyLike.md)\> jose-4.11.4/docs/functions/util_base64url.decode.md000066400000000000000000000003611437043056600221210ustar00rootroot00000000000000# Function: decode [💗 Help the project](https://github.com/sponsors/panva) ▸ **decode**(`input`): `Uint8Array` #### Parameters | Name | Type | | :------ | :------ | | `input` | `string` \| `Uint8Array` | #### Returns `Uint8Array` jose-4.11.4/docs/functions/util_base64url.encode.md000066400000000000000000000003511437043056600221320ustar00rootroot00000000000000# Function: encode [💗 Help the project](https://github.com/sponsors/panva) ▸ **encode**(`input`): `string` #### Parameters | Name | Type | | :------ | :------ | | `input` | `string` \| `Uint8Array` | #### Returns `string` jose-4.11.4/docs/functions/util_decode_jwt.decodeJwt.md000066400000000000000000000014231437043056600231060ustar00rootroot00000000000000# Function: decodeJwt [💗 Help the project](https://github.com/sponsors/panva) ▸ **decodeJwt**(`jwt`): [`JWTPayload`](../interfaces/types.JWTPayload.md) Decodes a signed JSON Web Token payload. This does not validate the JWT Claims Set types or values. This does not validate the JWS Signature. For a proper Signed JWT Claims Set validation and JWS signature verification use `jose.jwtVerify()`. For an encrypted JWT Claims Set validation and JWE decryption use `jose.jwtDecrypt()`. **`example`** Usage ```js const claims = jose.decodeJwt(token) console.log(claims) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `jwt` | `string` | JWT token in compact JWS serialization. | #### Returns [`JWTPayload`](../interfaces/types.JWTPayload.md) jose-4.11.4/docs/functions/util_decode_protected_header.decodeProtectedHeader.md000066400000000000000000000013121437043056600300760ustar00rootroot00000000000000# Function: decodeProtectedHeader [💗 Help the project](https://github.com/sponsors/panva) ▸ **decodeProtectedHeader**(`token`): [`ProtectedHeaderParameters`](../types/util_decode_protected_header.ProtectedHeaderParameters.md) Decodes the Protected Header of a JWE/JWS/JWT token utilizing any JOSE serialization. **`example`** Usage ```js const protectedHeader = jose.decodeProtectedHeader(token) console.log(protectedHeader) ``` #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `token` | `string` \| `object` | JWE/JWS/JWT token in any JOSE serialization. | #### Returns [`ProtectedHeaderParameters`](../types/util_decode_protected_header.ProtectedHeaderParameters.md) jose-4.11.4/docs/interfaces/000077500000000000000000000000001437043056600156245ustar00rootroot00000000000000jose-4.11.4/docs/interfaces/jwe_compact_decrypt.CompactDecryptGetKey.md000066400000000000000000000014331437043056600262250ustar00rootroot00000000000000# Interface: CompactDecryptGetKey [💗 Help the project](https://github.com/sponsors/panva) ## Callable ### CompactDecryptGetKey ▸ **CompactDecryptGetKey**(`protectedHeader`, `token`): `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> Interface for Compact JWE Decryption dynamic key resolution. No token components have been verified at the time of this function call. #### Parameters | Name | Type | | :------ | :------ | | `protectedHeader` | [`CompactJWEHeaderParameters`](types.CompactJWEHeaderParameters.md) | | `token` | [`FlattenedJWE`](types.FlattenedJWE.md) | #### Returns `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> jose-4.11.4/docs/interfaces/jwe_flattened_decrypt.FlattenedDecryptGetKey.md000066400000000000000000000014441437043056600270670ustar00rootroot00000000000000# Interface: FlattenedDecryptGetKey [💗 Help the project](https://github.com/sponsors/panva) ## Callable ### FlattenedDecryptGetKey ▸ **FlattenedDecryptGetKey**(`protectedHeader`, `token`): `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> Interface for Flattened JWE Decryption dynamic key resolution. No token components have been verified at the time of this function call. #### Parameters | Name | Type | | :------ | :------ | | `protectedHeader` | `undefined` \| [`JWEHeaderParameters`](types.JWEHeaderParameters.md) | | `token` | [`FlattenedJWE`](types.FlattenedJWE.md) | #### Returns `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> jose-4.11.4/docs/interfaces/jwe_general_decrypt.GeneralDecryptGetKey.md000066400000000000000000000014151437043056600262030ustar00rootroot00000000000000# Interface: GeneralDecryptGetKey [💗 Help the project](https://github.com/sponsors/panva) ## Callable ### GeneralDecryptGetKey ▸ **GeneralDecryptGetKey**(`protectedHeader`, `token`): `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> Interface for General JWE Decryption dynamic key resolution. No token components have been verified at the time of this function call. #### Parameters | Name | Type | | :------ | :------ | | `protectedHeader` | [`JWEHeaderParameters`](types.JWEHeaderParameters.md) | | `token` | [`FlattenedJWE`](types.FlattenedJWE.md) | #### Returns `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> jose-4.11.4/docs/interfaces/jwe_general_encrypt.Recipient.md000066400000000000000000000033451437043056600241220ustar00rootroot00000000000000# Interface: Recipient [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Methods - [addRecipient](jwe_general_encrypt.Recipient.md#addrecipient) - [done](jwe_general_encrypt.Recipient.md#done) - [encrypt](jwe_general_encrypt.Recipient.md#encrypt) - [setUnprotectedHeader](jwe_general_encrypt.Recipient.md#setunprotectedheader) ## Methods ### addRecipient ▸ **addRecipient**(`...args`): [`Recipient`](jwe_general_encrypt.Recipient.md) A shorthand for calling addRecipient() on the enclosing GeneralEncrypt instance #### Parameters | Name | Type | | :------ | :------ | | `...args` | [key: Uint8Array \| KeyLike, options?: CritOption] | #### Returns [`Recipient`](jwe_general_encrypt.Recipient.md) ___ ### done ▸ **done**(): [`GeneralEncrypt`](../classes/jwe_general_encrypt.GeneralEncrypt.md) Returns the enclosing GeneralEncrypt #### Returns [`GeneralEncrypt`](../classes/jwe_general_encrypt.GeneralEncrypt.md) ___ ### encrypt ▸ **encrypt**(`...args`): `Promise`<[`GeneralJWE`](types.GeneralJWE.md)\> A shorthand for calling encrypt() on the enclosing GeneralEncrypt instance #### Parameters | Name | Type | | :------ | :------ | | `...args` | [options?: DeflateOption] | #### Returns `Promise`<[`GeneralJWE`](types.GeneralJWE.md)\> ___ ### setUnprotectedHeader ▸ **setUnprotectedHeader**(`unprotectedHeader`): [`Recipient`](jwe_general_encrypt.Recipient.md) Sets the JWE Per-Recipient Unprotected Header on the Recipient object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `unprotectedHeader` | [`JWEHeaderParameters`](types.JWEHeaderParameters.md) | JWE Per-Recipient Unprotected Header. | #### Returns [`Recipient`](jwe_general_encrypt.Recipient.md) jose-4.11.4/docs/interfaces/jwks_remote.RemoteJWKSetOptions.md000066400000000000000000000033111437043056600243330ustar00rootroot00000000000000# Interface: RemoteJWKSetOptions [💗 Help the project](https://github.com/sponsors/panva) Options for the remote JSON Web Key Set. ## Table of contents ### Properties - [agent](jwks_remote.RemoteJWKSetOptions.md#agent) - [cacheMaxAge](jwks_remote.RemoteJWKSetOptions.md#cachemaxage) - [cooldownDuration](jwks_remote.RemoteJWKSetOptions.md#cooldownduration) - [headers](jwks_remote.RemoteJWKSetOptions.md#headers) - [timeoutDuration](jwks_remote.RemoteJWKSetOptions.md#timeoutduration) ## Properties ### agent • `Optional` **agent**: `any` An instance of [http.Agent](https://nodejs.org/api/http.html#class-httpagent) or [https.Agent](https://nodejs.org/api/https.html#class-httpsagent) to pass to the [http.get](https://nodejs.org/api/http.html#httpgetoptions-callback) or [https.get](https://nodejs.org/api/https.html#httpsgetoptions-callback) method's options. Use when behind an http(s) proxy. This is a Node.js runtime specific option, it is ignored when used outside of Node.js runtime. ___ ### cacheMaxAge • `Optional` **cacheMaxAge**: `number` Maximum time (in milliseconds) between successful HTTP requests. Default is 600000 (10 minutes). ___ ### cooldownDuration • `Optional` **cooldownDuration**: `number` Duration (in milliseconds) for which no more HTTP requests will be triggered after a previous successful fetch. Default is 30000 (30 seconds). ___ ### headers • `Optional` **headers**: `Record`<`string`, `string`\> Optional headers to be sent with the HTTP request. ___ ### timeoutDuration • `Optional` **timeoutDuration**: `number` Timeout (in milliseconds) for the HTTP request. When reached the request will be aborted and the verification will fail. Default is 5000 (5 seconds). jose-4.11.4/docs/interfaces/jws_compact_verify.CompactVerifyGetKey.md000066400000000000000000000016651437043056600257360ustar00rootroot00000000000000# Interface: CompactVerifyGetKey [💗 Help the project](https://github.com/sponsors/panva) ## Callable ### CompactVerifyGetKey ▸ **CompactVerifyGetKey**(`protectedHeader`, `token`): `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> Interface for Compact JWS Verification dynamic key resolution. No token components have been verified at the time of this function call. See [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) to verify using a remote JSON Web Key Set. #### Parameters | Name | Type | | :------ | :------ | | `protectedHeader` | [`CompactJWSHeaderParameters`](types.CompactJWSHeaderParameters.md) | | `token` | [`FlattenedJWSInput`](types.FlattenedJWSInput.md) | #### Returns `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> jose-4.11.4/docs/interfaces/jws_flattened_verify.FlattenedVerifyGetKey.md000066400000000000000000000016761437043056600266000ustar00rootroot00000000000000# Interface: FlattenedVerifyGetKey [💗 Help the project](https://github.com/sponsors/panva) ## Callable ### FlattenedVerifyGetKey ▸ **FlattenedVerifyGetKey**(`protectedHeader`, `token`): `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> Interface for Flattened JWS Verification dynamic key resolution. No token components have been verified at the time of this function call. See [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) to verify using a remote JSON Web Key Set. #### Parameters | Name | Type | | :------ | :------ | | `protectedHeader` | `undefined` \| [`JWSHeaderParameters`](types.JWSHeaderParameters.md) | | `token` | [`FlattenedJWSInput`](types.FlattenedJWSInput.md) | #### Returns `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> jose-4.11.4/docs/interfaces/jws_general_sign.Signature.md000066400000000000000000000041411437043056600234260ustar00rootroot00000000000000# Interface: Signature [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Methods - [addSignature](jws_general_sign.Signature.md#addsignature) - [done](jws_general_sign.Signature.md#done) - [setProtectedHeader](jws_general_sign.Signature.md#setprotectedheader) - [setUnprotectedHeader](jws_general_sign.Signature.md#setunprotectedheader) - [sign](jws_general_sign.Signature.md#sign) ## Methods ### addSignature ▸ **addSignature**(`...args`): [`Signature`](jws_general_sign.Signature.md) A shorthand for calling addSignature() on the enclosing GeneralSign instance #### Parameters | Name | Type | | :------ | :------ | | `...args` | [key: Uint8Array \| KeyLike, options?: SignOptions] | #### Returns [`Signature`](jws_general_sign.Signature.md) ___ ### done ▸ **done**(): [`GeneralSign`](../classes/jws_general_sign.GeneralSign.md) Returns the enclosing GeneralSign #### Returns [`GeneralSign`](../classes/jws_general_sign.GeneralSign.md) ___ ### setProtectedHeader ▸ **setProtectedHeader**(`protectedHeader`): [`Signature`](jws_general_sign.Signature.md) Sets the JWS Protected Header on the Signature object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `protectedHeader` | [`JWSHeaderParameters`](types.JWSHeaderParameters.md) | JWS Protected Header. | #### Returns [`Signature`](jws_general_sign.Signature.md) ___ ### setUnprotectedHeader ▸ **setUnprotectedHeader**(`unprotectedHeader`): [`Signature`](jws_general_sign.Signature.md) Sets the JWS Unprotected Header on the Signature object. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `unprotectedHeader` | [`JWSHeaderParameters`](types.JWSHeaderParameters.md) | JWS Unprotected Header. | #### Returns [`Signature`](jws_general_sign.Signature.md) ___ ### sign ▸ **sign**(`...args`): `Promise`<[`GeneralJWS`](types.GeneralJWS.md)\> A shorthand for calling encrypt() on the enclosing GeneralSign instance #### Parameters | Name | Type | | :------ | :------ | | `...args` | [] | #### Returns `Promise`<[`GeneralJWS`](types.GeneralJWS.md)\> jose-4.11.4/docs/interfaces/jws_general_verify.GeneralVerifyGetKey.md000066400000000000000000000016471437043056600257140ustar00rootroot00000000000000# Interface: GeneralVerifyGetKey [💗 Help the project](https://github.com/sponsors/panva) ## Callable ### GeneralVerifyGetKey ▸ **GeneralVerifyGetKey**(`protectedHeader`, `token`): `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> Interface for General JWS Verification dynamic key resolution. No token components have been verified at the time of this function call. See [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) to verify using a remote JSON Web Key Set. #### Parameters | Name | Type | | :------ | :------ | | `protectedHeader` | [`JWSHeaderParameters`](types.JWSHeaderParameters.md) | | `token` | [`FlattenedJWSInput`](types.FlattenedJWSInput.md) | #### Returns `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> jose-4.11.4/docs/interfaces/jwt_decrypt.JWTDecryptGetKey.md000066400000000000000000000014071437043056600236150ustar00rootroot00000000000000# Interface: JWTDecryptGetKey [💗 Help the project](https://github.com/sponsors/panva) ## Callable ### JWTDecryptGetKey ▸ **JWTDecryptGetKey**(`protectedHeader`, `token`): `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> Interface for JWT Decryption dynamic key resolution. No token components have been verified at the time of this function call. #### Parameters | Name | Type | | :------ | :------ | | `protectedHeader` | [`CompactJWEHeaderParameters`](types.CompactJWEHeaderParameters.md) | | `token` | [`FlattenedJWE`](types.FlattenedJWE.md) | #### Returns `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> jose-4.11.4/docs/interfaces/jwt_decrypt.JWTDecryptOptions.md000066400000000000000000000076721437043056600240720ustar00rootroot00000000000000# Interface: JWTDecryptOptions [💗 Help the project](https://github.com/sponsors/panva) Combination of JWE Decryption options and JWT Claims Set verification options. ## Table of contents ### Properties - [audience](jwt_decrypt.JWTDecryptOptions.md#audience) - [clockTolerance](jwt_decrypt.JWTDecryptOptions.md#clocktolerance) - [contentEncryptionAlgorithms](jwt_decrypt.JWTDecryptOptions.md#contentencryptionalgorithms) - [crit](jwt_decrypt.JWTDecryptOptions.md#crit) - [currentDate](jwt_decrypt.JWTDecryptOptions.md#currentdate) - [inflateRaw](jwt_decrypt.JWTDecryptOptions.md#inflateraw) - [issuer](jwt_decrypt.JWTDecryptOptions.md#issuer) - [keyManagementAlgorithms](jwt_decrypt.JWTDecryptOptions.md#keymanagementalgorithms) - [maxPBES2Count](jwt_decrypt.JWTDecryptOptions.md#maxpbes2count) - [maxTokenAge](jwt_decrypt.JWTDecryptOptions.md#maxtokenage) - [subject](jwt_decrypt.JWTDecryptOptions.md#subject) - [typ](jwt_decrypt.JWTDecryptOptions.md#typ) ## Properties ### audience • `Optional` **audience**: `string` \| `string`[] Expected JWT "aud" (Audience) Claim value(s). ___ ### clockTolerance • `Optional` **clockTolerance**: `string` \| `number` Expected clock tolerance - In seconds when number (e.g. 5) - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). ___ ### contentEncryptionAlgorithms • `Optional` **contentEncryptionAlgorithms**: `string`[] A list of accepted JWE "enc" (Encryption Algorithm) Header Parameter values. By default all "enc" (Encryption Algorithm) values applicable for the used key/secret are allowed. ___ ### crit • `Optional` **crit**: `Object` An object with keys representing recognized "crit" (Critical) Header Parameter names. The value for those is either `true` or `false`. `true` when the Header Parameter MUST be integrity protected, `false` when it's irrelevant. This makes the "Extension Header Parameter "..." is not recognized" error go away. Use this when a given JWS/JWT/JWE profile requires the use of proprietary non-registered "crit" (Critical) Header Parameters. This will only make sure the Header Parameter is syntactically correct when provided and that it is optionally integrity protected. It will not process the Header Parameter in any way or reject the operation if it is missing. You MUST still verify the Header Parameter was present and process it according to the profile's validation steps after the operation succeeds. The JWS extension Header Parameter `b64` is always recognized and processed properly. No other registered Header Parameters that need this kind of default built-in treatment are currently available. ___ ### currentDate • `Optional` **currentDate**: `Date` Date to use when comparing NumericDate claims, defaults to `new Date()`. ___ ### inflateRaw • `Optional` **inflateRaw**: [`InflateFunction`](types.InflateFunction.md) In a browser runtime you have to provide an implementation for Inflate Raw when you expect JWEs with compressed plaintext. ___ ### issuer • `Optional` **issuer**: `string` \| `string`[] Expected JWT "iss" (Issuer) Claim value(s). ___ ### keyManagementAlgorithms • `Optional` **keyManagementAlgorithms**: `string`[] A list of accepted JWE "alg" (Algorithm) Header Parameter values. ___ ### maxPBES2Count • `Optional` **maxPBES2Count**: `number` (PBES2 Key Management Algorithms only) Maximum allowed "p2c" (PBES2 Count) Header Parameter value. The PBKDF2 iteration count defines the algorithm's computational expense. By default this value is set to 10000. ___ ### maxTokenAge • `Optional` **maxTokenAge**: `string` \| `number` Maximum time elapsed (in seconds) from the JWT "iat" (Issued At) Claim value. - In seconds when number (e.g. 5) - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). ___ ### subject • `Optional` **subject**: `string` Expected JWT "sub" (Subject) Claim value. ___ ### typ • `Optional` **typ**: `string` Expected JWT "typ" (Type) Header Parameter value. jose-4.11.4/docs/interfaces/jwt_unsecured.UnsecuredResult.md000066400000000000000000000006241437043056600241640ustar00rootroot00000000000000# Interface: UnsecuredResult [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Properties - [header](jwt_unsecured.UnsecuredResult.md#header) - [payload](jwt_unsecured.UnsecuredResult.md#payload) ## Properties ### header • **header**: [`JWSHeaderParameters`](types.JWSHeaderParameters.md) ___ ### payload • **payload**: [`JWTPayload`](types.JWTPayload.md) jose-4.11.4/docs/interfaces/jwt_verify.JWTVerifyGetKey.md000066400000000000000000000016231437043056600233010ustar00rootroot00000000000000# Interface: JWTVerifyGetKey [💗 Help the project](https://github.com/sponsors/panva) ## Callable ### JWTVerifyGetKey ▸ **JWTVerifyGetKey**(`protectedHeader`, `token`): `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> Interface for JWT Verification dynamic key resolution. No token components have been verified at the time of this function call. See [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) to verify using a remote JSON Web Key Set. #### Parameters | Name | Type | | :------ | :------ | | `protectedHeader` | [`JWTHeaderParameters`](types.JWTHeaderParameters.md) | | `token` | [`FlattenedJWSInput`](types.FlattenedJWSInput.md) | #### Returns `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> jose-4.11.4/docs/interfaces/jwt_verify.JWTVerifyOptions.md000066400000000000000000000060061437043056600235440ustar00rootroot00000000000000# Interface: JWTVerifyOptions [💗 Help the project](https://github.com/sponsors/panva) Combination of JWS Verification options and JWT Claims Set verification options. ## Table of contents ### Properties - [algorithms](jwt_verify.JWTVerifyOptions.md#algorithms) - [audience](jwt_verify.JWTVerifyOptions.md#audience) - [clockTolerance](jwt_verify.JWTVerifyOptions.md#clocktolerance) - [crit](jwt_verify.JWTVerifyOptions.md#crit) - [currentDate](jwt_verify.JWTVerifyOptions.md#currentdate) - [issuer](jwt_verify.JWTVerifyOptions.md#issuer) - [maxTokenAge](jwt_verify.JWTVerifyOptions.md#maxtokenage) - [subject](jwt_verify.JWTVerifyOptions.md#subject) - [typ](jwt_verify.JWTVerifyOptions.md#typ) ## Properties ### algorithms • `Optional` **algorithms**: `string`[] A list of accepted JWS "alg" (Algorithm) Header Parameter values. By default all "alg" (Algorithm) values applicable for the used key/secret are allowed. Note: "none" is never accepted. ___ ### audience • `Optional` **audience**: `string` \| `string`[] Expected JWT "aud" (Audience) Claim value(s). ___ ### clockTolerance • `Optional` **clockTolerance**: `string` \| `number` Expected clock tolerance - In seconds when number (e.g. 5) - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). ___ ### crit • `Optional` **crit**: `Object` An object with keys representing recognized "crit" (Critical) Header Parameter names. The value for those is either `true` or `false`. `true` when the Header Parameter MUST be integrity protected, `false` when it's irrelevant. This makes the "Extension Header Parameter "..." is not recognized" error go away. Use this when a given JWS/JWT/JWE profile requires the use of proprietary non-registered "crit" (Critical) Header Parameters. This will only make sure the Header Parameter is syntactically correct when provided and that it is optionally integrity protected. It will not process the Header Parameter in any way or reject the operation if it is missing. You MUST still verify the Header Parameter was present and process it according to the profile's validation steps after the operation succeeds. The JWS extension Header Parameter `b64` is always recognized and processed properly. No other registered Header Parameters that need this kind of default built-in treatment are currently available. ___ ### currentDate • `Optional` **currentDate**: `Date` Date to use when comparing NumericDate claims, defaults to `new Date()`. ___ ### issuer • `Optional` **issuer**: `string` \| `string`[] Expected JWT "iss" (Issuer) Claim value(s). ___ ### maxTokenAge • `Optional` **maxTokenAge**: `string` \| `number` Maximum time elapsed (in seconds) from the JWT "iat" (Issued At) Claim value. - In seconds when number (e.g. 5) - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). ___ ### subject • `Optional` **subject**: `string` Expected JWT "sub" (Subject) Claim value. ___ ### typ • `Optional` **typ**: `string` Expected JWT "typ" (Type) Header Parameter value. jose-4.11.4/docs/interfaces/key_generate_key_pair.GenerateKeyPairOptions.md000066400000000000000000000020671437043056600270720ustar00rootroot00000000000000# Interface: GenerateKeyPairOptions [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Properties - [crv](key_generate_key_pair.GenerateKeyPairOptions.md#crv) - [extractable](key_generate_key_pair.GenerateKeyPairOptions.md#extractable) - [modulusLength](key_generate_key_pair.GenerateKeyPairOptions.md#moduluslength) ## Properties ### crv • `Optional` **crv**: `string` The EC "crv" (Curve) or OKP "crv" (Subtype of Key Pair) value to generate. The curve must be both supported on the runtime as well as applicable for the given JWA algorithm identifier. ___ ### extractable • `Optional` **extractable**: `boolean` (Web Cryptography API specific) The value to use as [SubtleCrypto.generateKey()](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey) `extractable` argument. Default is false. ___ ### modulusLength • `Optional` **modulusLength**: `number` A hint for RSA algorithms to generate an RSA key of a given `modulusLength` (Key size in bits). JOSE requires 2048 bits or larger. Default is 2048. jose-4.11.4/docs/interfaces/key_generate_key_pair.GenerateKeyPairResult.md000066400000000000000000000010261437043056600267070ustar00rootroot00000000000000# Interface: GenerateKeyPairResult [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Properties - [privateKey](key_generate_key_pair.GenerateKeyPairResult.md#privatekey) - [publicKey](key_generate_key_pair.GenerateKeyPairResult.md#publickey) ## Properties ### privateKey • **privateKey**: [`KeyLike`](../types/types.KeyLike.md) The generated Private Key. ___ ### publicKey • **publicKey**: [`KeyLike`](../types/types.KeyLike.md) Public Key corresponding to the generated Private Key. jose-4.11.4/docs/interfaces/key_generate_secret.GenerateSecretOptions.md000066400000000000000000000007421437043056600264330ustar00rootroot00000000000000# Interface: GenerateSecretOptions [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Properties - [extractable](key_generate_secret.GenerateSecretOptions.md#extractable) ## Properties ### extractable • `Optional` **extractable**: `boolean` (Web Cryptography API specific) The value to use as [SubtleCrypto.generateKey()](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey) `extractable` argument. Default is false. jose-4.11.4/docs/interfaces/key_import.PEMImportOptions.md000066400000000000000000000007131437043056600235200ustar00rootroot00000000000000# Interface: PEMImportOptions [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Properties - [extractable](key_import.PEMImportOptions.md#extractable) ## Properties ### extractable • `Optional` **extractable**: `boolean` (Web Cryptography API specific) The value to use as [SubtleCrypto.importKey()](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey) `extractable` argument. Default is false. jose-4.11.4/docs/interfaces/types.CompactDecryptResult.md000066400000000000000000000007311437043056600234320ustar00rootroot00000000000000# Interface: CompactDecryptResult [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Properties - [plaintext](types.CompactDecryptResult.md#plaintext) - [protectedHeader](types.CompactDecryptResult.md#protectedheader) ## Properties ### plaintext • **plaintext**: `Uint8Array` Plaintext. ___ ### protectedHeader • **protectedHeader**: [`CompactJWEHeaderParameters`](types.CompactJWEHeaderParameters.md) JWE Protected Header. jose-4.11.4/docs/interfaces/types.CompactJWEHeaderParameters.md000066400000000000000000000037201437043056600244040ustar00rootroot00000000000000# Interface: CompactJWEHeaderParameters [💗 Help the project](https://github.com/sponsors/panva) Recognized Compact JWE Header Parameters, any other Header Members may also be present. ## Table of contents ### Properties - [alg](types.CompactJWEHeaderParameters.md#alg) - [enc](types.CompactJWEHeaderParameters.md#enc) - [crit](types.CompactJWEHeaderParameters.md#crit) - [cty](types.CompactJWEHeaderParameters.md#cty) - [jku](types.CompactJWEHeaderParameters.md#jku) - [jwk](types.CompactJWEHeaderParameters.md#jwk) - [kid](types.CompactJWEHeaderParameters.md#kid) - [typ](types.CompactJWEHeaderParameters.md#typ) - [x5c](types.CompactJWEHeaderParameters.md#x5c) - [x5t](types.CompactJWEHeaderParameters.md#x5t) - [x5u](types.CompactJWEHeaderParameters.md#x5u) - [zip](types.CompactJWEHeaderParameters.md#zip) ## Properties ### alg • **alg**: `string` JWE "alg" (Algorithm) Header Parameter. ___ ### enc • **enc**: `string` JWE "enc" (Encryption Algorithm) Header Parameter. ___ ### crit • `Optional` **crit**: `string`[] JWE "crit" (Critical) Header Parameter. ___ ### cty • `Optional` **cty**: `string` "cty" (Content Type) Header Parameter. ___ ### jku • `Optional` **jku**: `string` "jku" (JWK Set URL) Header Parameter. ___ ### jwk • `Optional` **jwk**: `Pick`<[`JWK`](types.JWK.md), ``"crv"`` \| ``"e"`` \| ``"kty"`` \| ``"n"`` \| ``"x"`` \| ``"y"``\> "jwk" (JSON Web Key) Header Parameter. ___ ### kid • `Optional` **kid**: `string` "kid" (Key ID) Header Parameter. ___ ### typ • `Optional` **typ**: `string` "typ" (Type) Header Parameter. ___ ### x5c • `Optional` **x5c**: `string`[] "x5c" (X.509 Certificate Chain) Header Parameter. ___ ### x5t • `Optional` **x5t**: `string` "x5t" (X.509 Certificate SHA-1 Thumbprint) Header Parameter. ___ ### x5u • `Optional` **x5u**: `string` "x5u" (X.509 URL) Header Parameter. ___ ### zip • `Optional` **zip**: `string` JWE "zip" (Compression Algorithm) Header Parameter. jose-4.11.4/docs/interfaces/types.CompactJWSHeaderParameters.md000066400000000000000000000036771437043056600244350ustar00rootroot00000000000000# Interface: CompactJWSHeaderParameters [💗 Help the project](https://github.com/sponsors/panva) Recognized Compact JWS Header Parameters, any other Header Members may also be present. ## Table of contents ### Properties - [alg](types.CompactJWSHeaderParameters.md#alg) - [b64](types.CompactJWSHeaderParameters.md#b64) - [crit](types.CompactJWSHeaderParameters.md#crit) - [cty](types.CompactJWSHeaderParameters.md#cty) - [jku](types.CompactJWSHeaderParameters.md#jku) - [jwk](types.CompactJWSHeaderParameters.md#jwk) - [kid](types.CompactJWSHeaderParameters.md#kid) - [typ](types.CompactJWSHeaderParameters.md#typ) - [x5c](types.CompactJWSHeaderParameters.md#x5c) - [x5t](types.CompactJWSHeaderParameters.md#x5t) - [x5u](types.CompactJWSHeaderParameters.md#x5u) ## Properties ### alg • **alg**: `string` JWS "alg" (Algorithm) Header Parameter. ___ ### b64 • `Optional` **b64**: `boolean` This JWS Extension Header Parameter modifies the JWS Payload representation and the JWS Signing Input computation as per [RFC7797](https://www.rfc-editor.org/rfc/rfc7797). ___ ### crit • `Optional` **crit**: `string`[] JWS "crit" (Critical) Header Parameter. ___ ### cty • `Optional` **cty**: `string` "cty" (Content Type) Header Parameter. ___ ### jku • `Optional` **jku**: `string` "jku" (JWK Set URL) Header Parameter. ___ ### jwk • `Optional` **jwk**: `Pick`<[`JWK`](types.JWK.md), ``"crv"`` \| ``"e"`` \| ``"kty"`` \| ``"n"`` \| ``"x"`` \| ``"y"``\> "jwk" (JSON Web Key) Header Parameter. ___ ### kid • `Optional` **kid**: `string` "kid" (Key ID) Header Parameter. ___ ### typ • `Optional` **typ**: `string` "typ" (Type) Header Parameter. ___ ### x5c • `Optional` **x5c**: `string`[] "x5c" (X.509 Certificate Chain) Header Parameter. ___ ### x5t • `Optional` **x5t**: `string` "x5t" (X.509 Certificate SHA-1 Thumbprint) Header Parameter. ___ ### x5u • `Optional` **x5u**: `string` "x5u" (X.509 URL) Header Parameter. jose-4.11.4/docs/interfaces/types.CompactVerifyResult.md000066400000000000000000000007201437043056600232620ustar00rootroot00000000000000# Interface: CompactVerifyResult [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Properties - [payload](types.CompactVerifyResult.md#payload) - [protectedHeader](types.CompactVerifyResult.md#protectedheader) ## Properties ### payload • **payload**: `Uint8Array` JWS Payload. ___ ### protectedHeader • **protectedHeader**: [`CompactJWSHeaderParameters`](types.CompactJWSHeaderParameters.md) JWS Protected Header. jose-4.11.4/docs/interfaces/types.CritOption.md000066400000000000000000000024521437043056600214060ustar00rootroot00000000000000# Interface: CritOption [💗 Help the project](https://github.com/sponsors/panva) Shared Interface with a "crit" property for all sign, verify, encrypt and decrypt operations. ## Table of contents ### Properties - [crit](types.CritOption.md#crit) ## Properties ### crit • `Optional` **crit**: `Object` An object with keys representing recognized "crit" (Critical) Header Parameter names. The value for those is either `true` or `false`. `true` when the Header Parameter MUST be integrity protected, `false` when it's irrelevant. This makes the "Extension Header Parameter "..." is not recognized" error go away. Use this when a given JWS/JWT/JWE profile requires the use of proprietary non-registered "crit" (Critical) Header Parameters. This will only make sure the Header Parameter is syntactically correct when provided and that it is optionally integrity protected. It will not process the Header Parameter in any way or reject the operation if it is missing. You MUST still verify the Header Parameter was present and process it according to the profile's validation steps after the operation succeeds. The JWS extension Header Parameter `b64` is always recognized and processed properly. No other registered Header Parameters that need this kind of default built-in treatment are currently available. jose-4.11.4/docs/interfaces/types.DecryptOptions.md000066400000000000000000000046421437043056600223050ustar00rootroot00000000000000# Interface: DecryptOptions [💗 Help the project](https://github.com/sponsors/panva) JWE Decryption options. ## Table of contents ### Properties - [contentEncryptionAlgorithms](types.DecryptOptions.md#contentencryptionalgorithms) - [crit](types.DecryptOptions.md#crit) - [inflateRaw](types.DecryptOptions.md#inflateraw) - [keyManagementAlgorithms](types.DecryptOptions.md#keymanagementalgorithms) - [maxPBES2Count](types.DecryptOptions.md#maxpbes2count) ## Properties ### contentEncryptionAlgorithms • `Optional` **contentEncryptionAlgorithms**: `string`[] A list of accepted JWE "enc" (Encryption Algorithm) Header Parameter values. By default all "enc" (Encryption Algorithm) values applicable for the used key/secret are allowed. ___ ### crit • `Optional` **crit**: `Object` An object with keys representing recognized "crit" (Critical) Header Parameter names. The value for those is either `true` or `false`. `true` when the Header Parameter MUST be integrity protected, `false` when it's irrelevant. This makes the "Extension Header Parameter "..." is not recognized" error go away. Use this when a given JWS/JWT/JWE profile requires the use of proprietary non-registered "crit" (Critical) Header Parameters. This will only make sure the Header Parameter is syntactically correct when provided and that it is optionally integrity protected. It will not process the Header Parameter in any way or reject the operation if it is missing. You MUST still verify the Header Parameter was present and process it according to the profile's validation steps after the operation succeeds. The JWS extension Header Parameter `b64` is always recognized and processed properly. No other registered Header Parameters that need this kind of default built-in treatment are currently available. ___ ### inflateRaw • `Optional` **inflateRaw**: [`InflateFunction`](types.InflateFunction.md) In a browser runtime you have to provide an implementation for Inflate Raw when you expect JWEs with compressed plaintext. ___ ### keyManagementAlgorithms • `Optional` **keyManagementAlgorithms**: `string`[] A list of accepted JWE "alg" (Algorithm) Header Parameter values. ___ ### maxPBES2Count • `Optional` **maxPBES2Count**: `number` (PBES2 Key Management Algorithms only) Maximum allowed "p2c" (PBES2 Count) Header Parameter value. The PBKDF2 iteration count defines the algorithm's computational expense. By default this value is set to 10000. jose-4.11.4/docs/interfaces/types.DeflateFunction.md000066400000000000000000000006731437043056600223710ustar00rootroot00000000000000# Interface: DeflateFunction [💗 Help the project](https://github.com/sponsors/panva) ## Callable ### DeflateFunction ▸ **DeflateFunction**(`input`): `Promise`<`Uint8Array`\> Deflate Raw implementation, e.g. promisified [zlib.deflateRaw](https://nodejs.org/api/zlib.html#zlibdeflaterawbuffer-options-callback). #### Parameters | Name | Type | | :------ | :------ | | `input` | `Uint8Array` | #### Returns `Promise`<`Uint8Array`\> jose-4.11.4/docs/interfaces/types.DeflateOption.md000066400000000000000000000006711437043056600220520ustar00rootroot00000000000000# Interface: DeflateOption [💗 Help the project](https://github.com/sponsors/panva) JWE Deflate option. ## Table of contents ### Properties - [deflateRaw](types.DeflateOption.md#deflateraw) ## Properties ### deflateRaw • `Optional` **deflateRaw**: [`DeflateFunction`](types.DeflateFunction.md) In a browser runtime you have to provide an implementation for Deflate Raw when you will be producing JWEs with compressed plaintext. jose-4.11.4/docs/interfaces/types.EncryptOptions.md000066400000000000000000000030111437043056600223040ustar00rootroot00000000000000# Interface: EncryptOptions [💗 Help the project](https://github.com/sponsors/panva) JWE Encryption options. ## Table of contents ### Properties - [crit](types.EncryptOptions.md#crit) - [deflateRaw](types.EncryptOptions.md#deflateraw) ## Properties ### crit • `Optional` **crit**: `Object` An object with keys representing recognized "crit" (Critical) Header Parameter names. The value for those is either `true` or `false`. `true` when the Header Parameter MUST be integrity protected, `false` when it's irrelevant. This makes the "Extension Header Parameter "..." is not recognized" error go away. Use this when a given JWS/JWT/JWE profile requires the use of proprietary non-registered "crit" (Critical) Header Parameters. This will only make sure the Header Parameter is syntactically correct when provided and that it is optionally integrity protected. It will not process the Header Parameter in any way or reject the operation if it is missing. You MUST still verify the Header Parameter was present and process it according to the profile's validation steps after the operation succeeds. The JWS extension Header Parameter `b64` is always recognized and processed properly. No other registered Header Parameters that need this kind of default built-in treatment are currently available. ___ ### deflateRaw • `Optional` **deflateRaw**: [`DeflateFunction`](types.DeflateFunction.md) In a browser runtime you have to provide an implementation for Deflate Raw when you will be producing JWEs with compressed plaintext. jose-4.11.4/docs/interfaces/types.FlattenedDecryptResult.md000066400000000000000000000022121437043056600237460ustar00rootroot00000000000000# Interface: FlattenedDecryptResult [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Properties - [plaintext](types.FlattenedDecryptResult.md#plaintext) - [additionalAuthenticatedData](types.FlattenedDecryptResult.md#additionalauthenticateddata) - [protectedHeader](types.FlattenedDecryptResult.md#protectedheader) - [sharedUnprotectedHeader](types.FlattenedDecryptResult.md#sharedunprotectedheader) - [unprotectedHeader](types.FlattenedDecryptResult.md#unprotectedheader) ## Properties ### plaintext • **plaintext**: `Uint8Array` Plaintext. ___ ### additionalAuthenticatedData • `Optional` **additionalAuthenticatedData**: `Uint8Array` JWE AAD. ___ ### protectedHeader • `Optional` **protectedHeader**: [`JWEHeaderParameters`](types.JWEHeaderParameters.md) JWE Protected Header. ___ ### sharedUnprotectedHeader • `Optional` **sharedUnprotectedHeader**: [`JWEHeaderParameters`](types.JWEHeaderParameters.md) JWE Shared Unprotected Header. ___ ### unprotectedHeader • `Optional` **unprotectedHeader**: [`JWEHeaderParameters`](types.JWEHeaderParameters.md) JWE Per-Recipient Unprotected Header. jose-4.11.4/docs/interfaces/types.FlattenedJWE.md000066400000000000000000000053261437043056600215730ustar00rootroot00000000000000# Interface: FlattenedJWE [💗 Help the project](https://github.com/sponsors/panva) Flattened JWE definition. ## Table of contents ### Properties - [ciphertext](types.FlattenedJWE.md#ciphertext) - [iv](types.FlattenedJWE.md#iv) - [tag](types.FlattenedJWE.md#tag) - [aad](types.FlattenedJWE.md#aad) - [encrypted\_key](types.FlattenedJWE.md#encrypted_key) - [header](types.FlattenedJWE.md#header) - [protected](types.FlattenedJWE.md#protected) - [unprotected](types.FlattenedJWE.md#unprotected) ## Properties ### ciphertext • **ciphertext**: `string` The "ciphertext" member MUST be present and contain the value BASE64URL(JWE Ciphertext). ___ ### iv • **iv**: `string` The "iv" member MUST be present and contain the value BASE64URL(JWE Initialization Vector) when the JWE Initialization Vector value is non-empty; otherwise, it MUST be absent. ___ ### tag • **tag**: `string` The "tag" member MUST be present and contain the value BASE64URL(JWE Authentication Tag) when the JWE Authentication Tag value is non-empty; otherwise, it MUST be absent. ___ ### aad • `Optional` **aad**: `string` The "aad" member MUST be present and contain the value BASE64URL(JWE AAD)) when the JWE AAD value is non-empty; otherwise, it MUST be absent. A JWE AAD value can be included to supply a base64url-encoded value to be integrity protected but not encrypted. ___ ### encrypted\_key • `Optional` **encrypted\_key**: `string` The "encrypted_key" member MUST be present and contain the value BASE64URL(JWE Encrypted Key) when the JWE Encrypted Key value is non-empty; otherwise, it MUST be absent. ___ ### header • `Optional` **header**: [`JWEHeaderParameters`](types.JWEHeaderParameters.md) The "header" member MUST be present and contain the value JWE Per- Recipient Unprotected Header when the JWE Per-Recipient Unprotected Header value is non-empty; otherwise, it MUST be absent. This value is represented as an unencoded JSON object, rather than as a string. These Header Parameter values are not integrity protected. ___ ### protected • `Optional` **protected**: `string` The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWE Protected Header)) when the JWE Protected Header value is non-empty; otherwise, it MUST be absent. These Header Parameter values are integrity protected. ___ ### unprotected • `Optional` **unprotected**: [`JWEHeaderParameters`](types.JWEHeaderParameters.md) The "unprotected" member MUST be present and contain the value JWE Shared Unprotected Header when the JWE Shared Unprotected Header value is non-empty; otherwise, it MUST be absent. This value is represented as an unencoded JSON object, rather than as a string. These Header Parameter values are not integrity protected. jose-4.11.4/docs/interfaces/types.FlattenedJWS.md000066400000000000000000000023601437043056600216040ustar00rootroot00000000000000# Interface: FlattenedJWS [💗 Help the project](https://github.com/sponsors/panva) Flattened JWS definition. Payload is returned as an empty string when JWS Unencoded Payload Option [RFC7797](https://www.rfc-editor.org/rfc/rfc7797) is used. ## Table of contents ### Properties - [payload](types.FlattenedJWS.md#payload) - [signature](types.FlattenedJWS.md#signature) - [header](types.FlattenedJWS.md#header) - [protected](types.FlattenedJWS.md#protected) ## Properties ### payload • **payload**: `string` ___ ### signature • **signature**: `string` ___ ### header • `Optional` **header**: [`JWSHeaderParameters`](types.JWSHeaderParameters.md) The "header" member MUST be present and contain the value JWS Unprotected Header when the JWS Unprotected Header value is non- empty; otherwise, it MUST be absent. This value is represented as an unencoded JSON object, rather than as a string. These Header Parameter values are not integrity protected. ___ ### protected • `Optional` **protected**: `string` The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWS Protected Header)) when the JWS Protected Header value is non-empty; otherwise, it MUST be absent. These Header Parameter values are integrity protected. jose-4.11.4/docs/interfaces/types.FlattenedJWSInput.md000066400000000000000000000027511437043056600226300ustar00rootroot00000000000000# Interface: FlattenedJWSInput [💗 Help the project](https://github.com/sponsors/panva) Flattened JWS definition for verify function inputs, allows payload as Uint8Array for detached signature validation. ## Table of contents ### Properties - [payload](types.FlattenedJWSInput.md#payload) - [signature](types.FlattenedJWSInput.md#signature) - [header](types.FlattenedJWSInput.md#header) - [protected](types.FlattenedJWSInput.md#protected) ## Properties ### payload • **payload**: `string` \| `Uint8Array` The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When RFC7797 "b64": false is used the value passed may also be a Uint8Array. ___ ### signature • **signature**: `string` The "signature" member MUST be present and contain the value BASE64URL(JWS Signature). ___ ### header • `Optional` **header**: [`JWSHeaderParameters`](types.JWSHeaderParameters.md) The "header" member MUST be present and contain the value JWS Unprotected Header when the JWS Unprotected Header value is non- empty; otherwise, it MUST be absent. This value is represented as an unencoded JSON object, rather than as a string. These Header Parameter values are not integrity protected. ___ ### protected • `Optional` **protected**: `string` The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWS Protected Header)) when the JWS Protected Header value is non-empty; otherwise, it MUST be absent. These Header Parameter values are integrity protected. jose-4.11.4/docs/interfaces/types.FlattenedVerifyResult.md000066400000000000000000000012551437043056600236060ustar00rootroot00000000000000# Interface: FlattenedVerifyResult [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Properties - [payload](types.FlattenedVerifyResult.md#payload) - [protectedHeader](types.FlattenedVerifyResult.md#protectedheader) - [unprotectedHeader](types.FlattenedVerifyResult.md#unprotectedheader) ## Properties ### payload • **payload**: `Uint8Array` JWS Payload. ___ ### protectedHeader • `Optional` **protectedHeader**: [`JWSHeaderParameters`](types.JWSHeaderParameters.md) JWS Protected Header. ___ ### unprotectedHeader • `Optional` **unprotectedHeader**: [`JWSHeaderParameters`](types.JWSHeaderParameters.md) JWS Unprotected Header. jose-4.11.4/docs/interfaces/types.GeneralDecryptResult.md000066400000000000000000000021761437043056600234260ustar00rootroot00000000000000# Interface: GeneralDecryptResult [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Properties - [plaintext](types.GeneralDecryptResult.md#plaintext) - [additionalAuthenticatedData](types.GeneralDecryptResult.md#additionalauthenticateddata) - [protectedHeader](types.GeneralDecryptResult.md#protectedheader) - [sharedUnprotectedHeader](types.GeneralDecryptResult.md#sharedunprotectedheader) - [unprotectedHeader](types.GeneralDecryptResult.md#unprotectedheader) ## Properties ### plaintext • **plaintext**: `Uint8Array` Plaintext. ___ ### additionalAuthenticatedData • `Optional` **additionalAuthenticatedData**: `Uint8Array` JWE AAD. ___ ### protectedHeader • `Optional` **protectedHeader**: [`JWEHeaderParameters`](types.JWEHeaderParameters.md) JWE Protected Header. ___ ### sharedUnprotectedHeader • `Optional` **sharedUnprotectedHeader**: [`JWEHeaderParameters`](types.JWEHeaderParameters.md) JWE Shared Unprotected Header. ___ ### unprotectedHeader • `Optional` **unprotectedHeader**: [`JWEHeaderParameters`](types.JWEHeaderParameters.md) JWE Per-Recipient Unprotected Header. jose-4.11.4/docs/interfaces/types.GeneralJWE.md000066400000000000000000000041341437043056600212360ustar00rootroot00000000000000# Interface: GeneralJWE [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Properties - [ciphertext](types.GeneralJWE.md#ciphertext) - [iv](types.GeneralJWE.md#iv) - [recipients](types.GeneralJWE.md#recipients) - [tag](types.GeneralJWE.md#tag) - [aad](types.GeneralJWE.md#aad) - [protected](types.GeneralJWE.md#protected) - [unprotected](types.GeneralJWE.md#unprotected) ## Properties ### ciphertext • **ciphertext**: `string` The "ciphertext" member MUST be present and contain the value BASE64URL(JWE Ciphertext). ___ ### iv • **iv**: `string` The "iv" member MUST be present and contain the value BASE64URL(JWE Initialization Vector) when the JWE Initialization Vector value is non-empty; otherwise, it MUST be absent. ___ ### recipients • **recipients**: `Pick`<[`FlattenedJWE`](types.FlattenedJWE.md), ``"header"`` \| ``"encrypted_key"``\>[] ___ ### tag • **tag**: `string` The "tag" member MUST be present and contain the value BASE64URL(JWE Authentication Tag) when the JWE Authentication Tag value is non-empty; otherwise, it MUST be absent. ___ ### aad • `Optional` **aad**: `string` The "aad" member MUST be present and contain the value BASE64URL(JWE AAD)) when the JWE AAD value is non-empty; otherwise, it MUST be absent. A JWE AAD value can be included to supply a base64url-encoded value to be integrity protected but not encrypted. ___ ### protected • `Optional` **protected**: `string` The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWE Protected Header)) when the JWE Protected Header value is non-empty; otherwise, it MUST be absent. These Header Parameter values are integrity protected. ___ ### unprotected • `Optional` **unprotected**: [`JWEHeaderParameters`](types.JWEHeaderParameters.md) The "unprotected" member MUST be present and contain the value JWE Shared Unprotected Header when the JWE Shared Unprotected Header value is non-empty; otherwise, it MUST be absent. This value is represented as an unencoded JSON object, rather than as a string. These Header Parameter values are not integrity protected. jose-4.11.4/docs/interfaces/types.GeneralJWS.md000066400000000000000000000010351437043056600212510ustar00rootroot00000000000000# Interface: GeneralJWS [💗 Help the project](https://github.com/sponsors/panva) General JWS definition. Payload is returned as an empty string when JWS Unencoded Payload Option [RFC7797](https://www.rfc-editor.org/rfc/rfc7797) is used. ## Table of contents ### Properties - [payload](types.GeneralJWS.md#payload) - [signatures](types.GeneralJWS.md#signatures) ## Properties ### payload • **payload**: `string` ___ ### signatures • **signatures**: `Omit`<[`FlattenedJWSInput`](types.FlattenedJWSInput.md), ``"payload"``\>[] jose-4.11.4/docs/interfaces/types.GeneralJWSInput.md000066400000000000000000000015221437043056600222720ustar00rootroot00000000000000# Interface: GeneralJWSInput [💗 Help the project](https://github.com/sponsors/panva) General JWS definition for verify function inputs, allows payload as Uint8Array for detached signature validation. ## Table of contents ### Properties - [payload](types.GeneralJWSInput.md#payload) - [signatures](types.GeneralJWSInput.md#signatures) ## Properties ### payload • **payload**: `string` \| `Uint8Array` The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When RFC7797 "b64": false is used the value passed may also be a Uint8Array. ___ ### signatures • **signatures**: `Omit`<[`FlattenedJWSInput`](types.FlattenedJWSInput.md), ``"payload"``\>[] The "signatures" member value MUST be an array of JSON objects. Each object represents a signature or MAC over the JWS Payload and the JWS Protected Header. jose-4.11.4/docs/interfaces/types.GeneralVerifyResult.md000066400000000000000000000012451437043056600232540ustar00rootroot00000000000000# Interface: GeneralVerifyResult [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Properties - [payload](types.GeneralVerifyResult.md#payload) - [protectedHeader](types.GeneralVerifyResult.md#protectedheader) - [unprotectedHeader](types.GeneralVerifyResult.md#unprotectedheader) ## Properties ### payload • **payload**: `Uint8Array` JWS Payload. ___ ### protectedHeader • `Optional` **protectedHeader**: [`JWSHeaderParameters`](types.JWSHeaderParameters.md) JWS Protected Header. ___ ### unprotectedHeader • `Optional` **unprotectedHeader**: [`JWSHeaderParameters`](types.JWSHeaderParameters.md) JWS Unprotected Header. jose-4.11.4/docs/interfaces/types.GetKeyFunction.md000066400000000000000000000016221437043056600222100ustar00rootroot00000000000000# Interface: GetKeyFunction [💗 Help the project](https://github.com/sponsors/panva) ## Type parameters | Name | | :------ | | `T` | | `T2` | ## Callable ### GetKeyFunction ▸ **GetKeyFunction**(`protectedHeader`, `token`): `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> Generic Interface for consuming operations dynamic key resolution. No token components have been verified at the time of this function call. If you cannot match a key suitable for the token, throw an error instead. #### Parameters | Name | Type | Description | | :------ | :------ | :------ | | `protectedHeader` | `T` | JWE or JWS Protected Header. | | `token` | `T2` | The consumed JWE or JWS token. | #### Returns `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) \| `Promise`<`Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md)\> jose-4.11.4/docs/interfaces/types.InflateFunction.md000066400000000000000000000006731437043056600224070ustar00rootroot00000000000000# Interface: InflateFunction [💗 Help the project](https://github.com/sponsors/panva) ## Callable ### InflateFunction ▸ **InflateFunction**(`input`): `Promise`<`Uint8Array`\> Inflate Raw implementation, e.g. promisified [zlib.inflateRaw](https://nodejs.org/api/zlib.html#zlibinflaterawbuffer-options-callback). #### Parameters | Name | Type | | :------ | :------ | | `input` | `Uint8Array` | #### Returns `Promise`<`Uint8Array`\> jose-4.11.4/docs/interfaces/types.JSONWebKeySet.md000066400000000000000000000003661437043056600216520ustar00rootroot00000000000000# Interface: JSONWebKeySet [💗 Help the project](https://github.com/sponsors/panva) JSON Web Key Set ## Table of contents ### Properties - [keys](types.JSONWebKeySet.md#keys) ## Properties ### keys • **keys**: [`JWK`](types.JWK.md)[] jose-4.11.4/docs/interfaces/types.JWEHeaderParameters.md000066400000000000000000000036031437043056600230750ustar00rootroot00000000000000# Interface: JWEHeaderParameters [💗 Help the project](https://github.com/sponsors/panva) Recognized JWE Header Parameters, any other Header members may also be present. ## Table of contents ### Properties - [alg](types.JWEHeaderParameters.md#alg) - [crit](types.JWEHeaderParameters.md#crit) - [cty](types.JWEHeaderParameters.md#cty) - [enc](types.JWEHeaderParameters.md#enc) - [jku](types.JWEHeaderParameters.md#jku) - [jwk](types.JWEHeaderParameters.md#jwk) - [kid](types.JWEHeaderParameters.md#kid) - [typ](types.JWEHeaderParameters.md#typ) - [x5c](types.JWEHeaderParameters.md#x5c) - [x5t](types.JWEHeaderParameters.md#x5t) - [x5u](types.JWEHeaderParameters.md#x5u) - [zip](types.JWEHeaderParameters.md#zip) ## Properties ### alg • `Optional` **alg**: `string` JWE "alg" (Algorithm) Header Parameter. ___ ### crit • `Optional` **crit**: `string`[] JWE "crit" (Critical) Header Parameter. ___ ### cty • `Optional` **cty**: `string` "cty" (Content Type) Header Parameter. ___ ### enc • `Optional` **enc**: `string` JWE "enc" (Encryption Algorithm) Header Parameter. ___ ### jku • `Optional` **jku**: `string` "jku" (JWK Set URL) Header Parameter. ___ ### jwk • `Optional` **jwk**: `Pick`<[`JWK`](types.JWK.md), ``"crv"`` \| ``"e"`` \| ``"kty"`` \| ``"n"`` \| ``"x"`` \| ``"y"``\> "jwk" (JSON Web Key) Header Parameter. ___ ### kid • `Optional` **kid**: `string` "kid" (Key ID) Header Parameter. ___ ### typ • `Optional` **typ**: `string` "typ" (Type) Header Parameter. ___ ### x5c • `Optional` **x5c**: `string`[] "x5c" (X.509 Certificate Chain) Header Parameter. ___ ### x5t • `Optional` **x5t**: `string` "x5t" (X.509 Certificate SHA-1 Thumbprint) Header Parameter. ___ ### x5u • `Optional` **x5u**: `string` "x5u" (X.509 URL) Header Parameter. ___ ### zip • `Optional` **zip**: `string` JWE "zip" (Compression Algorithm) Header Parameter. jose-4.11.4/docs/interfaces/types.JWEKeyManagementHeaderParameters.md000066400000000000000000000025251437043056600255450ustar00rootroot00000000000000# Interface: JWEKeyManagementHeaderParameters [💗 Help the project](https://github.com/sponsors/panva) Recognized JWE Key Management-related Header Parameters. ## Table of contents ### Properties - [apu](types.JWEKeyManagementHeaderParameters.md#apu) - [apv](types.JWEKeyManagementHeaderParameters.md#apv) - [epk](types.JWEKeyManagementHeaderParameters.md#epk) - [iv](types.JWEKeyManagementHeaderParameters.md#iv) - [p2c](types.JWEKeyManagementHeaderParameters.md#p2c) - [p2s](types.JWEKeyManagementHeaderParameters.md#p2s) ## Properties ### apu • `Optional` **apu**: `Uint8Array` ___ ### apv • `Optional` **apv**: `Uint8Array` ___ ### epk • `Optional` **epk**: [`KeyLike`](../types/types.KeyLike.md) **`deprecated`** You should not use this parameter. It is only really intended for test and vector validation purposes. ___ ### iv • `Optional` **iv**: `Uint8Array` **`deprecated`** You should not use this parameter. It is only really intended for test and vector validation purposes. ___ ### p2c • `Optional` **p2c**: `number` **`deprecated`** You should not use this parameter. It is only really intended for test and vector validation purposes. ___ ### p2s • `Optional` **p2s**: `Uint8Array` **`deprecated`** You should not use this parameter. It is only really intended for test and vector validation purposes. jose-4.11.4/docs/interfaces/types.JWK.md000066400000000000000000000045141437043056600177500ustar00rootroot00000000000000# Interface: JWK [💗 Help the project](https://github.com/sponsors/panva) JSON Web Key ([JWK](https://www.rfc-editor.org/rfc/rfc7517)). "RSA", "EC", "OKP", and "oct" key types are supported. ## Table of contents ### Properties - [alg](types.JWK.md#alg) - [crv](types.JWK.md#crv) - [d](types.JWK.md#d) - [dp](types.JWK.md#dp) - [dq](types.JWK.md#dq) - [e](types.JWK.md#e) - [ext](types.JWK.md#ext) - [k](types.JWK.md#k) - [key\_ops](types.JWK.md#key_ops) - [kid](types.JWK.md#kid) - [kty](types.JWK.md#kty) - [n](types.JWK.md#n) - [oth](types.JWK.md#oth) - [p](types.JWK.md#p) - [q](types.JWK.md#q) - [qi](types.JWK.md#qi) - [use](types.JWK.md#use) - [x](types.JWK.md#x) - [x5c](types.JWK.md#x5c) - [x5t](types.JWK.md#x5t) - [x5t#S256](types.JWK.md#x5t#s256) - [x5u](types.JWK.md#x5u) - [y](types.JWK.md#y) ## Properties ### alg • `Optional` **alg**: `string` JWK "alg" (Algorithm) Parameter. ___ ### crv • `Optional` **crv**: `string` ___ ### d • `Optional` **d**: `string` ___ ### dp • `Optional` **dp**: `string` ___ ### dq • `Optional` **dq**: `string` ___ ### e • `Optional` **e**: `string` ___ ### ext • `Optional` **ext**: `boolean` JWK "ext" (Extractable) Parameter. ___ ### k • `Optional` **k**: `string` ___ ### key\_ops • `Optional` **key\_ops**: `string`[] JWK "key_ops" (Key Operations) Parameter. ___ ### kid • `Optional` **kid**: `string` JWK "kid" (Key ID) Parameter. ___ ### kty • `Optional` **kty**: `string` JWK "kty" (Key Type) Parameter. ___ ### n • `Optional` **n**: `string` ___ ### oth • `Optional` **oth**: { `d?`: `string` ; `r?`: `string` ; `t?`: `string` }[] ___ ### p • `Optional` **p**: `string` ___ ### q • `Optional` **q**: `string` ___ ### qi • `Optional` **qi**: `string` ___ ### use • `Optional` **use**: `string` JWK "use" (Public Key Use) Parameter. ___ ### x • `Optional` **x**: `string` ___ ### x5c • `Optional` **x5c**: `string`[] JWK "x5c" (X.509 Certificate Chain) Parameter. ___ ### x5t • `Optional` **x5t**: `string` JWK "x5t" (X.509 Certificate SHA-1 Thumbprint) Parameter. ___ ### x5t#S256 • `Optional` **x5t#S256**: `string` "x5t#S256" (X.509 Certificate SHA-256 Thumbprint) Parameter. ___ ### x5u • `Optional` **x5u**: `string` JWK "x5u" (X.509 URL) Parameter. ___ ### y • `Optional` **y**: `string` jose-4.11.4/docs/interfaces/types.JWSHeaderParameters.md000066400000000000000000000035561437043056600231220ustar00rootroot00000000000000# Interface: JWSHeaderParameters [💗 Help the project](https://github.com/sponsors/panva) Recognized JWS Header Parameters, any other Header Members may also be present. ## Table of contents ### Properties - [alg](types.JWSHeaderParameters.md#alg) - [b64](types.JWSHeaderParameters.md#b64) - [crit](types.JWSHeaderParameters.md#crit) - [cty](types.JWSHeaderParameters.md#cty) - [jku](types.JWSHeaderParameters.md#jku) - [jwk](types.JWSHeaderParameters.md#jwk) - [kid](types.JWSHeaderParameters.md#kid) - [typ](types.JWSHeaderParameters.md#typ) - [x5c](types.JWSHeaderParameters.md#x5c) - [x5t](types.JWSHeaderParameters.md#x5t) - [x5u](types.JWSHeaderParameters.md#x5u) ## Properties ### alg • `Optional` **alg**: `string` JWS "alg" (Algorithm) Header Parameter. ___ ### b64 • `Optional` **b64**: `boolean` This JWS Extension Header Parameter modifies the JWS Payload representation and the JWS Signing Input computation as per [RFC7797](https://www.rfc-editor.org/rfc/rfc7797). ___ ### crit • `Optional` **crit**: `string`[] JWS "crit" (Critical) Header Parameter. ___ ### cty • `Optional` **cty**: `string` "cty" (Content Type) Header Parameter. ___ ### jku • `Optional` **jku**: `string` "jku" (JWK Set URL) Header Parameter. ___ ### jwk • `Optional` **jwk**: `Pick`<[`JWK`](types.JWK.md), ``"crv"`` \| ``"e"`` \| ``"kty"`` \| ``"n"`` \| ``"x"`` \| ``"y"``\> "jwk" (JSON Web Key) Header Parameter. ___ ### kid • `Optional` **kid**: `string` "kid" (Key ID) Header Parameter. ___ ### typ • `Optional` **typ**: `string` "typ" (Type) Header Parameter. ___ ### x5c • `Optional` **x5c**: `string`[] "x5c" (X.509 Certificate Chain) Header Parameter. ___ ### x5t • `Optional` **x5t**: `string` "x5t" (X.509 Certificate SHA-1 Thumbprint) Header Parameter. ___ ### x5u • `Optional` **x5u**: `string` "x5u" (X.509 URL) Header Parameter. jose-4.11.4/docs/interfaces/types.JWTClaimVerificationOptions.md000066400000000000000000000032111437043056600246370ustar00rootroot00000000000000# Interface: JWTClaimVerificationOptions [💗 Help the project](https://github.com/sponsors/panva) JWT Claims Set verification options. ## Table of contents ### Properties - [audience](types.JWTClaimVerificationOptions.md#audience) - [clockTolerance](types.JWTClaimVerificationOptions.md#clocktolerance) - [currentDate](types.JWTClaimVerificationOptions.md#currentdate) - [issuer](types.JWTClaimVerificationOptions.md#issuer) - [maxTokenAge](types.JWTClaimVerificationOptions.md#maxtokenage) - [subject](types.JWTClaimVerificationOptions.md#subject) - [typ](types.JWTClaimVerificationOptions.md#typ) ## Properties ### audience • `Optional` **audience**: `string` \| `string`[] Expected JWT "aud" (Audience) Claim value(s). ___ ### clockTolerance • `Optional` **clockTolerance**: `string` \| `number` Expected clock tolerance - In seconds when number (e.g. 5) - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). ___ ### currentDate • `Optional` **currentDate**: `Date` Date to use when comparing NumericDate claims, defaults to `new Date()`. ___ ### issuer • `Optional` **issuer**: `string` \| `string`[] Expected JWT "iss" (Issuer) Claim value(s). ___ ### maxTokenAge • `Optional` **maxTokenAge**: `string` \| `number` Maximum time elapsed (in seconds) from the JWT "iat" (Issued At) Claim value. - In seconds when number (e.g. 5) - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). ___ ### subject • `Optional` **subject**: `string` Expected JWT "sub" (Subject) Claim value. ___ ### typ • `Optional` **typ**: `string` Expected JWT "typ" (Type) Header Parameter value. jose-4.11.4/docs/interfaces/types.JWTDecryptResult.md000066400000000000000000000007411437043056600225110ustar00rootroot00000000000000# Interface: JWTDecryptResult [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Properties - [payload](types.JWTDecryptResult.md#payload) - [protectedHeader](types.JWTDecryptResult.md#protectedheader) ## Properties ### payload • **payload**: [`JWTPayload`](types.JWTPayload.md) JWT Claims Set. ___ ### protectedHeader • **protectedHeader**: [`CompactJWEHeaderParameters`](types.CompactJWEHeaderParameters.md) JWE Protected Header. jose-4.11.4/docs/interfaces/types.JWTHeaderParameters.md000066400000000000000000000035511437043056600231160ustar00rootroot00000000000000# Interface: JWTHeaderParameters [💗 Help the project](https://github.com/sponsors/panva) Recognized Signed JWT Header Parameters, any other Header Members may also be present. ## Table of contents ### Properties - [alg](types.JWTHeaderParameters.md#alg) - [b64](types.JWTHeaderParameters.md#b64) - [crit](types.JWTHeaderParameters.md#crit) - [cty](types.JWTHeaderParameters.md#cty) - [jku](types.JWTHeaderParameters.md#jku) - [jwk](types.JWTHeaderParameters.md#jwk) - [kid](types.JWTHeaderParameters.md#kid) - [typ](types.JWTHeaderParameters.md#typ) - [x5c](types.JWTHeaderParameters.md#x5c) - [x5t](types.JWTHeaderParameters.md#x5t) - [x5u](types.JWTHeaderParameters.md#x5u) ## Properties ### alg • **alg**: `string` JWS "alg" (Algorithm) Header Parameter. ___ ### b64 • `Optional` **b64**: ``true`` This JWS Extension Header Parameter modifies the JWS Payload representation and the JWS Signing Input computation as per [RFC7797](https://www.rfc-editor.org/rfc/rfc7797). ___ ### crit • `Optional` **crit**: `string`[] JWS "crit" (Critical) Header Parameter. ___ ### cty • `Optional` **cty**: `string` "cty" (Content Type) Header Parameter. ___ ### jku • `Optional` **jku**: `string` "jku" (JWK Set URL) Header Parameter. ___ ### jwk • `Optional` **jwk**: `Pick`<[`JWK`](types.JWK.md), ``"crv"`` \| ``"e"`` \| ``"kty"`` \| ``"n"`` \| ``"x"`` \| ``"y"``\> "jwk" (JSON Web Key) Header Parameter. ___ ### kid • `Optional` **kid**: `string` "kid" (Key ID) Header Parameter. ___ ### typ • `Optional` **typ**: `string` "typ" (Type) Header Parameter. ___ ### x5c • `Optional` **x5c**: `string`[] "x5c" (X.509 Certificate Chain) Header Parameter. ___ ### x5t • `Optional` **x5t**: `string` "x5t" (X.509 Certificate SHA-1 Thumbprint) Header Parameter. ___ ### x5u • `Optional` **x5u**: `string` "x5u" (X.509 URL) Header Parameter. jose-4.11.4/docs/interfaces/types.JWTPayload.md000066400000000000000000000027351437043056600212760ustar00rootroot00000000000000# Interface: JWTPayload [💗 Help the project](https://github.com/sponsors/panva) Recognized JWT Claims Set members, any other members may also be present. ## Table of contents ### Properties - [aud](types.JWTPayload.md#aud) - [exp](types.JWTPayload.md#exp) - [iat](types.JWTPayload.md#iat) - [iss](types.JWTPayload.md#iss) - [jti](types.JWTPayload.md#jti) - [nbf](types.JWTPayload.md#nbf) - [sub](types.JWTPayload.md#sub) ## Properties ### aud • `Optional` **aud**: `string` \| `string`[] JWT Audience [RFC7519#section-4.1.3](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3). ___ ### exp • `Optional` **exp**: `number` JWT Expiration Time **`see`** [RFC7519#section-4.1.4](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4) ___ ### iat • `Optional` **iat**: `number` JWT Issued At **`see`** [RFC7519#section-4.1.6](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6) ___ ### iss • `Optional` **iss**: `string` JWT Issuer **`see`** [RFC7519#section-4.1.1](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.1) ___ ### jti • `Optional` **jti**: `string` JWT ID **`see`** [RFC7519#section-4.1.7](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7) ___ ### nbf • `Optional` **nbf**: `number` JWT Not Before **`see`** [RFC7519#section-4.1.5](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.5) ___ ### sub • `Optional` **sub**: `string` JWT Subject **`see`** [RFC7519#section-4.1.2](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.2) jose-4.11.4/docs/interfaces/types.JWTVerifyResult.md000066400000000000000000000007201437043056600223400ustar00rootroot00000000000000# Interface: JWTVerifyResult [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Properties - [payload](types.JWTVerifyResult.md#payload) - [protectedHeader](types.JWTVerifyResult.md#protectedheader) ## Properties ### payload • **payload**: [`JWTPayload`](types.JWTPayload.md) JWT Claims Set. ___ ### protectedHeader • **protectedHeader**: [`JWTHeaderParameters`](types.JWTHeaderParameters.md) JWS Protected Header. jose-4.11.4/docs/interfaces/types.JoseHeaderParameters.md000066400000000000000000000024221437043056600233460ustar00rootroot00000000000000# Interface: JoseHeaderParameters [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Properties - [cty](types.JoseHeaderParameters.md#cty) - [jku](types.JoseHeaderParameters.md#jku) - [jwk](types.JoseHeaderParameters.md#jwk) - [kid](types.JoseHeaderParameters.md#kid) - [typ](types.JoseHeaderParameters.md#typ) - [x5c](types.JoseHeaderParameters.md#x5c) - [x5t](types.JoseHeaderParameters.md#x5t) - [x5u](types.JoseHeaderParameters.md#x5u) ## Properties ### cty • `Optional` **cty**: `string` "cty" (Content Type) Header Parameter. ___ ### jku • `Optional` **jku**: `string` "jku" (JWK Set URL) Header Parameter. ___ ### jwk • `Optional` **jwk**: `Pick`<[`JWK`](types.JWK.md), ``"crv"`` \| ``"e"`` \| ``"kty"`` \| ``"n"`` \| ``"x"`` \| ``"y"``\> "jwk" (JSON Web Key) Header Parameter. ___ ### kid • `Optional` **kid**: `string` "kid" (Key ID) Header Parameter. ___ ### typ • `Optional` **typ**: `string` "typ" (Type) Header Parameter. ___ ### x5c • `Optional` **x5c**: `string`[] "x5c" (X.509 Certificate Chain) Header Parameter. ___ ### x5t • `Optional` **x5t**: `string` "x5t" (X.509 Certificate SHA-1 Thumbprint) Header Parameter. ___ ### x5u • `Optional` **x5u**: `string` "x5u" (X.509 URL) Header Parameter. jose-4.11.4/docs/interfaces/types.ResolvedKey.md000066400000000000000000000004511437043056600215450ustar00rootroot00000000000000# Interface: ResolvedKey [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Properties - [key](types.ResolvedKey.md#key) ## Properties ### key • **key**: `Uint8Array` \| [`KeyLike`](../types/types.KeyLike.md) Key resolved from the key resolver function. jose-4.11.4/docs/interfaces/types.SignOptions.md000066400000000000000000000023431437043056600215670ustar00rootroot00000000000000# Interface: SignOptions [💗 Help the project](https://github.com/sponsors/panva) JWS Signing options. ## Table of contents ### Properties - [crit](types.SignOptions.md#crit) ## Properties ### crit • `Optional` **crit**: `Object` An object with keys representing recognized "crit" (Critical) Header Parameter names. The value for those is either `true` or `false`. `true` when the Header Parameter MUST be integrity protected, `false` when it's irrelevant. This makes the "Extension Header Parameter "..." is not recognized" error go away. Use this when a given JWS/JWT/JWE profile requires the use of proprietary non-registered "crit" (Critical) Header Parameters. This will only make sure the Header Parameter is syntactically correct when provided and that it is optionally integrity protected. It will not process the Header Parameter in any way or reject the operation if it is missing. You MUST still verify the Header Parameter was present and process it according to the profile's validation steps after the operation succeeds. The JWS extension Header Parameter `b64` is always recognized and processed properly. No other registered Header Parameters that need this kind of default built-in treatment are currently available. jose-4.11.4/docs/interfaces/types.VerifyOptions.md000066400000000000000000000030311437043056600221260ustar00rootroot00000000000000# Interface: VerifyOptions [💗 Help the project](https://github.com/sponsors/panva) JWS Verification options. ## Table of contents ### Properties - [algorithms](types.VerifyOptions.md#algorithms) - [crit](types.VerifyOptions.md#crit) ## Properties ### algorithms • `Optional` **algorithms**: `string`[] A list of accepted JWS "alg" (Algorithm) Header Parameter values. By default all "alg" (Algorithm) values applicable for the used key/secret are allowed. Note: "none" is never accepted. ___ ### crit • `Optional` **crit**: `Object` An object with keys representing recognized "crit" (Critical) Header Parameter names. The value for those is either `true` or `false`. `true` when the Header Parameter MUST be integrity protected, `false` when it's irrelevant. This makes the "Extension Header Parameter "..." is not recognized" error go away. Use this when a given JWS/JWT/JWE profile requires the use of proprietary non-registered "crit" (Critical) Header Parameters. This will only make sure the Header Parameter is syntactically correct when provided and that it is optionally integrity protected. It will not process the Header Parameter in any way or reject the operation if it is missing. You MUST still verify the Header Parameter was present and process it according to the profile's validation steps after the operation succeeds. The JWS extension Header Parameter `b64` is always recognized and processed properly. No other registered Header Parameters that need this kind of default built-in treatment are currently available. jose-4.11.4/docs/modules/000077500000000000000000000000001437043056600151515ustar00rootroot00000000000000jose-4.11.4/docs/modules/jwe_compact_decrypt.md000066400000000000000000000004541437043056600215230ustar00rootroot00000000000000# Module: jwe/compact/decrypt [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [compactDecrypt](../functions/jwe_compact_decrypt.compactDecrypt.md) ### Interfaces - [CompactDecryptGetKey](../interfaces/jwe_compact_decrypt.CompactDecryptGetKey.md) jose-4.11.4/docs/modules/jwe_compact_encrypt.md000066400000000000000000000003031437043056600215260ustar00rootroot00000000000000# Module: jwe/compact/encrypt [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Classes - [CompactEncrypt](../classes/jwe_compact_encrypt.CompactEncrypt.md) jose-4.11.4/docs/modules/jwe_flattened_decrypt.md000066400000000000000000000004721437043056600220430ustar00rootroot00000000000000# Module: jwe/flattened/decrypt [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [flattenedDecrypt](../functions/jwe_flattened_decrypt.flattenedDecrypt.md) ### Interfaces - [FlattenedDecryptGetKey](../interfaces/jwe_flattened_decrypt.FlattenedDecryptGetKey.md) jose-4.11.4/docs/modules/jwe_flattened_encrypt.md000066400000000000000000000003131437043056600220470ustar00rootroot00000000000000# Module: jwe/flattened/encrypt [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Classes - [FlattenedEncrypt](../classes/jwe_flattened_encrypt.FlattenedEncrypt.md) jose-4.11.4/docs/modules/jwe_general_decrypt.md000066400000000000000000000004541437043056600215120ustar00rootroot00000000000000# Module: jwe/general/decrypt [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [generalDecrypt](../functions/jwe_general_decrypt.generalDecrypt.md) ### Interfaces - [GeneralDecryptGetKey](../interfaces/jwe_general_decrypt.GeneralDecryptGetKey.md) jose-4.11.4/docs/modules/jwe_general_encrypt.md000066400000000000000000000004221437043056600215170ustar00rootroot00000000000000# Module: jwe/general/encrypt [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Interfaces - [Recipient](../interfaces/jwe_general_encrypt.Recipient.md) ### Classes - [GeneralEncrypt](../classes/jwe_general_encrypt.GeneralEncrypt.md) jose-4.11.4/docs/modules/jwk_embedded.md000066400000000000000000000002631437043056600201000ustar00rootroot00000000000000# Module: jwk/embedded [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [EmbeddedJWK](../functions/jwk_embedded.EmbeddedJWK.md) jose-4.11.4/docs/modules/jwk_thumbprint.md000066400000000000000000000004451437043056600205450ustar00rootroot00000000000000# Module: jwk/thumbprint [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [calculateJwkThumbprint](../functions/jwk_thumbprint.calculateJwkThumbprint.md) - [calculateJwkThumbprintUri](../functions/jwk_thumbprint.calculateJwkThumbprintUri.md) jose-4.11.4/docs/modules/jwks_local.md000066400000000000000000000002731437043056600176250ustar00rootroot00000000000000# Module: jwks/local [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [createLocalJWKSet](../functions/jwks_local.createLocalJWKSet.md) jose-4.11.4/docs/modules/jwks_remote.md000066400000000000000000000004321437043056600200230ustar00rootroot00000000000000# Module: jwks/remote [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md) ### Interfaces - [RemoteJWKSetOptions](../interfaces/jwks_remote.RemoteJWKSetOptions.md) jose-4.11.4/docs/modules/jws_compact_sign.md000066400000000000000000000002671437043056600210310ustar00rootroot00000000000000# Module: jws/compact/sign [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Classes - [CompactSign](../classes/jws_compact_sign.CompactSign.md) jose-4.11.4/docs/modules/jws_compact_verify.md000066400000000000000000000004451437043056600213730ustar00rootroot00000000000000# Module: jws/compact/verify [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [compactVerify](../functions/jws_compact_verify.compactVerify.md) ### Interfaces - [CompactVerifyGetKey](../interfaces/jws_compact_verify.CompactVerifyGetKey.md) jose-4.11.4/docs/modules/jws_flattened_sign.md000066400000000000000000000002771437043056600213520ustar00rootroot00000000000000# Module: jws/flattened/sign [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Classes - [FlattenedSign](../classes/jws_flattened_sign.FlattenedSign.md) jose-4.11.4/docs/modules/jws_flattened_verify.md000066400000000000000000000004631437043056600217130ustar00rootroot00000000000000# Module: jws/flattened/verify [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [flattenedVerify](../functions/jws_flattened_verify.flattenedVerify.md) ### Interfaces - [FlattenedVerifyGetKey](../interfaces/jws_flattened_verify.FlattenedVerifyGetKey.md) jose-4.11.4/docs/modules/jws_general_sign.md000066400000000000000000000004031437043056600210100ustar00rootroot00000000000000# Module: jws/general/sign [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Interfaces - [Signature](../interfaces/jws_general_sign.Signature.md) ### Classes - [GeneralSign](../classes/jws_general_sign.GeneralSign.md) jose-4.11.4/docs/modules/jws_general_verify.md000066400000000000000000000004451437043056600213620ustar00rootroot00000000000000# Module: jws/general/verify [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [generalVerify](../functions/jws_general_verify.generalVerify.md) ### Interfaces - [GeneralVerifyGetKey](../interfaces/jws_general_verify.GeneralVerifyGetKey.md) jose-4.11.4/docs/modules/jwt_decrypt.md000066400000000000000000000005121437043056600200270ustar00rootroot00000000000000# Module: jwt/decrypt [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [jwtDecrypt](../functions/jwt_decrypt.jwtDecrypt.md) ### Interfaces - [JWTDecryptGetKey](../interfaces/jwt_decrypt.JWTDecryptGetKey.md) - [JWTDecryptOptions](../interfaces/jwt_decrypt.JWTDecryptOptions.md) jose-4.11.4/docs/modules/jwt_encrypt.md000066400000000000000000000002531437043056600200430ustar00rootroot00000000000000# Module: jwt/encrypt [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Classes - [EncryptJWT](../classes/jwt_encrypt.EncryptJWT.md) jose-4.11.4/docs/modules/jwt_produce.md000066400000000000000000000002531437043056600200200ustar00rootroot00000000000000# Module: jwt/produce [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Classes - [ProduceJWT](../classes/jwt_produce.ProduceJWT.md) jose-4.11.4/docs/modules/jwt_sign.md000066400000000000000000000002371437043056600173210ustar00rootroot00000000000000# Module: jwt/sign [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Classes - [SignJWT](../classes/jwt_sign.SignJWT.md) jose-4.11.4/docs/modules/jwt_unsecured.md000066400000000000000000000004101437043056600203470ustar00rootroot00000000000000# Module: jwt/unsecured [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Interfaces - [UnsecuredResult](../interfaces/jwt_unsecured.UnsecuredResult.md) ### Classes - [UnsecuredJWT](../classes/jwt_unsecured.UnsecuredJWT.md) jose-4.11.4/docs/modules/jwt_verify.md000066400000000000000000000005001437043056600176560ustar00rootroot00000000000000# Module: jwt/verify [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [jwtVerify](../functions/jwt_verify.jwtVerify.md) ### Interfaces - [JWTVerifyGetKey](../interfaces/jwt_verify.JWTVerifyGetKey.md) - [JWTVerifyOptions](../interfaces/jwt_verify.JWTVerifyOptions.md) jose-4.11.4/docs/modules/key_export.md000066400000000000000000000004311437043056600176620ustar00rootroot00000000000000# Module: key/export [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [exportJWK](../functions/key_export.exportJWK.md) - [exportPKCS8](../functions/key_export.exportPKCS8.md) - [exportSPKI](../functions/key_export.exportSPKI.md) jose-4.11.4/docs/modules/key_generate_key_pair.md000066400000000000000000000006221437043056600220200ustar00rootroot00000000000000# Module: key/generate\_key\_pair [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [generateKeyPair](../functions/key_generate_key_pair.generateKeyPair.md) ### Interfaces - [GenerateKeyPairOptions](../interfaces/key_generate_key_pair.GenerateKeyPairOptions.md) - [GenerateKeyPairResult](../interfaces/key_generate_key_pair.GenerateKeyPairResult.md) jose-4.11.4/docs/modules/key_generate_secret.md000066400000000000000000000004571437043056600215100ustar00rootroot00000000000000# Module: key/generate\_secret [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [generateSecret](../functions/key_generate_secret.generateSecret.md) ### Interfaces - [GenerateSecretOptions](../interfaces/key_generate_secret.GenerateSecretOptions.md) jose-4.11.4/docs/modules/key_import.md000066400000000000000000000006431437043056600176600ustar00rootroot00000000000000# Module: key/import [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [importJWK](../functions/key_import.importJWK.md) - [importPKCS8](../functions/key_import.importPKCS8.md) - [importSPKI](../functions/key_import.importSPKI.md) - [importX509](../functions/key_import.importX509.md) ### Interfaces - [PEMImportOptions](../interfaces/key_import.PEMImportOptions.md) jose-4.11.4/docs/modules/types.md000066400000000000000000000044771437043056600166530ustar00rootroot00000000000000# Module: types [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Type Aliases - [KeyLike](../types/types.KeyLike.md) ### Interfaces - [CompactDecryptResult](../interfaces/types.CompactDecryptResult.md) - [CompactJWEHeaderParameters](../interfaces/types.CompactJWEHeaderParameters.md) - [CompactJWSHeaderParameters](../interfaces/types.CompactJWSHeaderParameters.md) - [CompactVerifyResult](../interfaces/types.CompactVerifyResult.md) - [CritOption](../interfaces/types.CritOption.md) - [DecryptOptions](../interfaces/types.DecryptOptions.md) - [DeflateFunction](../interfaces/types.DeflateFunction.md) - [DeflateOption](../interfaces/types.DeflateOption.md) - [EncryptOptions](../interfaces/types.EncryptOptions.md) - [FlattenedDecryptResult](../interfaces/types.FlattenedDecryptResult.md) - [FlattenedJWE](../interfaces/types.FlattenedJWE.md) - [FlattenedJWS](../interfaces/types.FlattenedJWS.md) - [FlattenedJWSInput](../interfaces/types.FlattenedJWSInput.md) - [FlattenedVerifyResult](../interfaces/types.FlattenedVerifyResult.md) - [GeneralDecryptResult](../interfaces/types.GeneralDecryptResult.md) - [GeneralJWE](../interfaces/types.GeneralJWE.md) - [GeneralJWS](../interfaces/types.GeneralJWS.md) - [GeneralJWSInput](../interfaces/types.GeneralJWSInput.md) - [GeneralVerifyResult](../interfaces/types.GeneralVerifyResult.md) - [GetKeyFunction](../interfaces/types.GetKeyFunction.md) - [InflateFunction](../interfaces/types.InflateFunction.md) - [JSONWebKeySet](../interfaces/types.JSONWebKeySet.md) - [JWEHeaderParameters](../interfaces/types.JWEHeaderParameters.md) - [JWEKeyManagementHeaderParameters](../interfaces/types.JWEKeyManagementHeaderParameters.md) - [JWK](../interfaces/types.JWK.md) - [JWSHeaderParameters](../interfaces/types.JWSHeaderParameters.md) - [JWTClaimVerificationOptions](../interfaces/types.JWTClaimVerificationOptions.md) - [JWTDecryptResult](../interfaces/types.JWTDecryptResult.md) - [JWTHeaderParameters](../interfaces/types.JWTHeaderParameters.md) - [JWTPayload](../interfaces/types.JWTPayload.md) - [JWTVerifyResult](../interfaces/types.JWTVerifyResult.md) - [JoseHeaderParameters](../interfaces/types.JoseHeaderParameters.md) - [ResolvedKey](../interfaces/types.ResolvedKey.md) - [SignOptions](../interfaces/types.SignOptions.md) - [VerifyOptions](../interfaces/types.VerifyOptions.md) jose-4.11.4/docs/modules/util_base64url.md000066400000000000000000000003371437043056600203420ustar00rootroot00000000000000# Module: util/base64url [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [decode](../functions/util_base64url.decode.md) - [encode](../functions/util_base64url.encode.md) jose-4.11.4/docs/modules/util_decode_jwt.md000066400000000000000000000002661437043056600206430ustar00rootroot00000000000000# Module: util/decode\_jwt [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [decodeJwt](../functions/util_decode_jwt.decodeJwt.md) jose-4.11.4/docs/modules/util_decode_protected_header.md000066400000000000000000000005361437043056600233400ustar00rootroot00000000000000# Module: util/decode\_protected\_header [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Functions - [decodeProtectedHeader](../functions/util_decode_protected_header.decodeProtectedHeader.md) ### Type Aliases - [ProtectedHeaderParameters](../types/util_decode_protected_header.ProtectedHeaderParameters.md) jose-4.11.4/docs/modules/util_errors.md000066400000000000000000000020551437043056600200460ustar00rootroot00000000000000# Module: util/errors [💗 Help the project](https://github.com/sponsors/panva) ## Table of contents ### Classes - [JOSEAlgNotAllowed](../classes/util_errors.JOSEAlgNotAllowed.md) - [JOSEError](../classes/util_errors.JOSEError.md) - [JOSENotSupported](../classes/util_errors.JOSENotSupported.md) - [JWEDecryptionFailed](../classes/util_errors.JWEDecryptionFailed.md) - [JWEInvalid](../classes/util_errors.JWEInvalid.md) - [JWKInvalid](../classes/util_errors.JWKInvalid.md) - [JWKSInvalid](../classes/util_errors.JWKSInvalid.md) - [JWKSMultipleMatchingKeys](../classes/util_errors.JWKSMultipleMatchingKeys.md) - [JWKSNoMatchingKey](../classes/util_errors.JWKSNoMatchingKey.md) - [JWKSTimeout](../classes/util_errors.JWKSTimeout.md) - [JWSInvalid](../classes/util_errors.JWSInvalid.md) - [JWSSignatureVerificationFailed](../classes/util_errors.JWSSignatureVerificationFailed.md) - [JWTClaimValidationFailed](../classes/util_errors.JWTClaimValidationFailed.md) - [JWTExpired](../classes/util_errors.JWTExpired.md) - [JWTInvalid](../classes/util_errors.JWTInvalid.md) jose-4.11.4/docs/types/000077500000000000000000000000001437043056600146455ustar00rootroot00000000000000jose-4.11.4/docs/types/types.KeyLike.md000066400000000000000000000077541437043056600177040ustar00rootroot00000000000000# Type alias: KeyLike [💗 Help the project](https://github.com/sponsors/panva) Ƭ **KeyLike**: `Object` KeyLike are runtime-specific classes representing asymmetric keys or symmetric secrets. These are instances of [CryptoKey](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) and additionally [KeyObject](https://nodejs.org/api/crypto.html#class-keyobject) in Node.js runtime. [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instances are also accepted as symmetric secret representation only. [Key Import Functions](../modules/key_import.md#readme) can be used to import PEM, or JWK formatted asymmetric keys and certificates to these runtime-specific representations. In Node.js the [Buffer](https://nodejs.org/api/buffer.html#buffer) class is a subclass of Uint8Array and so Buffer can be provided for symmetric secrets as well. [KeyObject](https://nodejs.org/api/crypto.html#class-keyobject) is a representation of a key/secret available in the Node.js runtime. In addition to the import functions of this library you may use the runtime APIs [crypto.createPublicKey](https://nodejs.org/api/crypto.html#cryptocreatepublickeykey), [crypto.createPrivateKey](https://nodejs.org/api/crypto.html#cryptocreateprivatekeykey), and [crypto.createSecretKey](https://nodejs.org/api/crypto.html#cryptocreatesecretkeykey-encoding) to obtain a KeyObject from your existing key material. [CryptoKey](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) is a representation of a key/secret available in the Browser and Web-interoperable runtimes. In addition to the import functions of this library you may use the [SubtleCrypto.importKey](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey) API to obtain a CryptoKey from your existing key material. **`example`** Import a PEM-encoded SPKI Public Key ```js const algorithm = 'ES256' const spki = `-----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFlHHWfLk0gLBbsLTcuCrbCqoHqmM YJepMC+Q+Dd6RBmBiA41evUsNMwLeN+PNFqib+xwi9JkJ8qhZkq8Y/IzGg== -----END PUBLIC KEY-----` const ecPublicKey = await jose.importSPKI(spki, algorithm) ``` **`example`** Import a X.509 Certificate ```js const algorithm = 'ES256' const x509 = `-----BEGIN CERTIFICATE----- MIIBXjCCAQSgAwIBAgIGAXvykuMKMAoGCCqGSM49BAMCMDYxNDAyBgNVBAMMK3Np QXBNOXpBdk1VaXhXVWVGaGtjZXg1NjJRRzFyQUhXaV96UlFQTVpQaG8wHhcNMjEw OTE3MDcwNTE3WhcNMjIwNzE0MDcwNTE3WjA2MTQwMgYDVQQDDCtzaUFwTTl6QXZN VWl4V1VlRmhrY2V4NTYyUUcxckFIV2lfelJRUE1aUGhvMFkwEwYHKoZIzj0CAQYI KoZIzj0DAQcDQgAE8PbPvCv5D5xBFHEZlBp/q5OEUymq7RIgWIi7tkl9aGSpYE35 UH+kBKDnphJO3odpPZ5gvgKs2nwRWcrDnUjYLDAKBggqhkjOPQQDAgNIADBFAiEA 1yyMTRe66MhEXID9+uVub7woMkNYd0LhSHwKSPMUUTkCIFQGsfm1ecXOpeGOufAh v+A1QWZMuTWqYt+uh/YSRNDn -----END CERTIFICATE-----` const ecPublicKey = await jose.importX509(x509, algorithm) ``` **`example`** Import a PEM-encoded PKCS8 Private Key ```js const algorithm = 'ES256' const pkcs8 = `-----BEGIN PRIVATE KEY----- MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgiyvo0X+VQ0yIrOaN nlrnUclopnvuuMfoc8HHly3505OhRANCAAQWUcdZ8uTSAsFuwtNy4KtsKqgeqYxg l6kwL5D4N3pEGYGIDjV69Sw0zAt43480WqJv7HCL0mQnyqFmSrxj8jMa -----END PRIVATE KEY-----` const ecPrivateKey = await jose.importPKCS8(pkcs8, algorithm) ``` **`example`** Import a JSON Web Key (JWK) ```js const ecPublicKey = await jose.importJWK( { crv: 'P-256', kty: 'EC', x: 'ySK38C1jBdLwDsNWKzzBHqKYEE5Cgv-qjWvorUXk9fw', y: '_LeQBw07cf5t57Iavn4j-BqJsAD1dpoz8gokd3sBsOo', }, 'ES256', ) const rsaPublicKey = await jose.importJWK( { kty: 'RSA', e: 'AQAB', n: '12oBZRhCiZFJLcPg59LkZZ9mdhSMTKAQZYq32k_ti5SBB6jerkh-WzOMAO664r_qyLkqHUSp3u5SbXtseZEpN3XPWGKSxjsy-1JyEFTdLSYe6f9gfrmxkUF_7DTpq0gn6rntP05g2-wFW50YO7mosfdslfrTJYWHFhJALabAeYirYD7-9kqq9ebfFMF4sRRELbv9oi36As6Q9B3Qb5_C1rAzqfao_PCsf9EPsTZsVVVkA5qoIAr47lo1ipfiBPxUCCNSdvkmDTYgvvRm6ZoMjFbvOtgyts55fXKdMWv7I9HMD5HwE9uW839PWA514qhbcIsXEYSFMPMV6fnlsiZvQQ', }, 'PS256', ) ``` #### Type declaration | Name | Type | | :------ | :------ | | `type` | `string` | jose-4.11.4/docs/types/util_decode_protected_header.ProtectedHeaderParameters.md000066400000000000000000000004211437043056600301120ustar00rootroot00000000000000# Type alias: ProtectedHeaderParameters [💗 Help the project](https://github.com/sponsors/panva) Ƭ **ProtectedHeaderParameters**: [`JWSHeaderParameters`](../interfaces/types.JWSHeaderParameters.md) & [`JWEHeaderParameters`](../interfaces/types.JWEHeaderParameters.md) jose-4.11.4/package-lock.json000066400000000000000000005235031437043056600157750ustar00rootroot00000000000000{ "name": "jose", "version": "4.11.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "jose", "version": "4.11.4", "license": "MIT", "devDependencies": { "@types/node": "^18.11.9", "@types/qunit": "^2.19.3", "ava": "^5.1.0", "edge-runtime": "^2.0.4", "esbuild": "^0.17.0", "nock": "^13.1.3", "npm-run-all": "^4.1.5", "patch-package": "^6.5.0", "prettier": "^2.8.0", "prettier-plugin-jsdoc": "^0.4.2", "qunit": "^2.19.2", "rollup": "^3.4.0", "tar": "^6.1.12", "timekeeper": "^2.2.0", "typedoc": "^0.23.21", "typedoc-plugin-markdown": "^3.13.6", "typescript": "^4.9.3" }, "funding": { "url": "https://github.com/sponsors/panva" } }, "node_modules/@edge-runtime/format": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/@edge-runtime/format/-/format-2.0.0.tgz", "integrity": "sha512-y0KPyCwbIiuRDc8qZ9JHJZp+SFqeHOTEpbAFwmXtEhK1sJsKhF3j+R8zn2TtpW3TKMb7d62RWbiqo3gZWwWkMQ==", "dev": true, "engines": { "node": ">=14" } }, "node_modules/@edge-runtime/primitives": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@edge-runtime/primitives/-/primitives-2.0.3.tgz", "integrity": "sha512-+y39BANcePTGKAE+0R8xX3UFzwTqWQOVUaC+UXsKjA45jGNfZCkGnJgGjJPXZftmxiLcl9R2lYyDvHN+55dUlw==", "dev": true, "engines": { "node": ">=14" } }, "node_modules/@edge-runtime/vm": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@edge-runtime/vm/-/vm-2.0.3.tgz", "integrity": "sha512-l0fTtkBIPozgr8vQ46LXCSrp40WBWSNFQy/wGpydAsXznm6So90/ZsZD9hFLiudT2dnPJAWFtdNHcTpEKv8smA==", "dev": true, "dependencies": { "@edge-runtime/primitives": "2.0.3" }, "engines": { "node": ">=14" } }, "node_modules/@esbuild/android-arm": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.6.tgz", "integrity": "sha512-bSC9YVUjADDy1gae8RrioINU6e1lCkg3VGVwm0QQ2E1CWcC4gnMce9+B6RpxuSsrsXsk1yojn7sp1fnG8erE2g==", "cpu": [ "arm" ], "dev": true, "optional": true, "os": [ "android" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/android-arm64": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.17.6.tgz", "integrity": "sha512-YnYSCceN/dUzUr5kdtUzB+wZprCafuD89Hs0Aqv9QSdwhYQybhXTaSTcrl6X/aWThn1a/j0eEpUBGOE7269REg==", "cpu": [ "arm64" ], "dev": true, "optional": true, "os": [ "android" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/android-x64": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.17.6.tgz", "integrity": "sha512-MVcYcgSO7pfu/x34uX9u2QIZHmXAB7dEiLQC5bBl5Ryqtpj9lT2sg3gNDEsrPEmimSJW2FXIaxqSQ501YLDsZQ==", "cpu": [ "x64" ], "dev": true, "optional": true, "os": [ "android" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/darwin-arm64": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.17.6.tgz", "integrity": "sha512-bsDRvlbKMQMt6Wl08nHtFz++yoZHsyTOxnjfB2Q95gato+Yi4WnRl13oC2/PJJA9yLCoRv9gqT/EYX0/zDsyMA==", "cpu": [ "arm64" ], "dev": true, "optional": true, "os": [ "darwin" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/darwin-x64": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.6.tgz", "integrity": "sha512-xh2A5oPrYRfMFz74QXIQTQo8uA+hYzGWJFoeTE8EvoZGHb+idyV4ATaukaUvnnxJiauhs/fPx3vYhU4wiGfosg==", "cpu": [ "x64" ], "dev": true, "optional": true, "os": [ "darwin" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/freebsd-arm64": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.17.6.tgz", "integrity": "sha512-EnUwjRc1inT4ccZh4pB3v1cIhohE2S4YXlt1OvI7sw/+pD+dIE4smwekZlEPIwY6PhU6oDWwITrQQm5S2/iZgg==", "cpu": [ "arm64" ], "dev": true, "optional": true, "os": [ "freebsd" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/freebsd-x64": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.17.6.tgz", "integrity": "sha512-Uh3HLWGzH6FwpviUcLMKPCbZUAFzv67Wj5MTwK6jn89b576SR2IbEp+tqUHTr8DIl0iDmBAf51MVaP7pw6PY5Q==", "cpu": [ "x64" ], "dev": true, "optional": true, "os": [ "freebsd" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/linux-arm": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.17.6.tgz", "integrity": "sha512-7YdGiurNt7lqO0Bf/U9/arrPWPqdPqcV6JCZda4LZgEn+PTQ5SMEI4MGR52Bfn3+d6bNEGcWFzlIxiQdS48YUw==", "cpu": [ "arm" ], "dev": true, "optional": true, "os": [ "linux" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/linux-arm64": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.6.tgz", "integrity": "sha512-bUR58IFOMJX523aDVozswnlp5yry7+0cRLCXDsxnUeQYJik1DukMY+apBsLOZJblpH+K7ox7YrKrHmJoWqVR9w==", "cpu": [ "arm64" ], "dev": true, "optional": true, "os": [ "linux" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/linux-ia32": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.17.6.tgz", "integrity": "sha512-ujp8uoQCM9FRcbDfkqECoARsLnLfCUhKARTP56TFPog8ie9JG83D5GVKjQ6yVrEVdMie1djH86fm98eY3quQkQ==", "cpu": [ "ia32" ], "dev": true, "optional": true, "os": [ "linux" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/linux-loong64": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.17.6.tgz", "integrity": "sha512-y2NX1+X/Nt+izj9bLoiaYB9YXT/LoaQFYvCkVD77G/4F+/yuVXYCWz4SE9yr5CBMbOxOfBcy/xFL4LlOeNlzYQ==", "cpu": [ "loong64" ], "dev": true, "optional": true, "os": [ "linux" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/linux-mips64el": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.17.6.tgz", "integrity": "sha512-09AXKB1HDOzXD+j3FdXCiL/MWmZP0Ex9eR8DLMBVcHorrWJxWmY8Nms2Nm41iRM64WVx7bA/JVHMv081iP2kUA==", "cpu": [ "mips64el" ], "dev": true, "optional": true, "os": [ "linux" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/linux-ppc64": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.17.6.tgz", "integrity": "sha512-AmLhMzkM8JuqTIOhxnX4ubh0XWJIznEynRnZAVdA2mMKE6FAfwT2TWKTwdqMG+qEaeyDPtfNoZRpJbD4ZBv0Tg==", "cpu": [ "ppc64" ], "dev": true, "optional": true, "os": [ "linux" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/linux-riscv64": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.17.6.tgz", "integrity": "sha512-Y4Ri62PfavhLQhFbqucysHOmRamlTVK10zPWlqjNbj2XMea+BOs4w6ASKwQwAiqf9ZqcY9Ab7NOU4wIgpxwoSQ==", "cpu": [ "riscv64" ], "dev": true, "optional": true, "os": [ "linux" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/linux-s390x": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.17.6.tgz", "integrity": "sha512-SPUiz4fDbnNEm3JSdUW8pBJ/vkop3M1YwZAVwvdwlFLoJwKEZ9L98l3tzeyMzq27CyepDQ3Qgoba44StgbiN5Q==", "cpu": [ "s390x" ], "dev": true, "optional": true, "os": [ "linux" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/linux-x64": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.6.tgz", "integrity": "sha512-a3yHLmOodHrzuNgdpB7peFGPx1iJ2x6m+uDvhP2CKdr2CwOaqEFMeSqYAHU7hG+RjCq8r2NFujcd/YsEsFgTGw==", "cpu": [ "x64" ], "dev": true, "optional": true, "os": [ "linux" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/netbsd-x64": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.6.tgz", "integrity": "sha512-EanJqcU/4uZIBreTrnbnre2DXgXSa+Gjap7ifRfllpmyAU7YMvaXmljdArptTHmjrkkKm9BK6GH5D5Yo+p6y5A==", "cpu": [ "x64" ], "dev": true, "optional": true, "os": [ "netbsd" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/openbsd-x64": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.6.tgz", "integrity": "sha512-xaxeSunhQRsTNGFanoOkkLtnmMn5QbA0qBhNet/XLVsc+OVkpIWPHcr3zTW2gxVU5YOHFbIHR9ODuaUdNza2Vw==", "cpu": [ "x64" ], "dev": true, "optional": true, "os": [ "openbsd" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/sunos-x64": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.17.6.tgz", "integrity": "sha512-gnMnMPg5pfMkZvhHee21KbKdc6W3GR8/JuE0Da1kjwpK6oiFU3nqfHuVPgUX2rsOx9N2SadSQTIYV1CIjYG+xw==", "cpu": [ "x64" ], "dev": true, "optional": true, "os": [ "sunos" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/win32-arm64": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.6.tgz", "integrity": "sha512-G95n7vP1UnGJPsVdKXllAJPtqjMvFYbN20e8RK8LVLhlTiSOH1sd7+Gt7rm70xiG+I5tM58nYgwWrLs6I1jHqg==", "cpu": [ "arm64" ], "dev": true, "optional": true, "os": [ "win32" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/win32-ia32": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.17.6.tgz", "integrity": "sha512-96yEFzLhq5bv9jJo5JhTs1gI+1cKQ83cUpyxHuGqXVwQtY5Eq54ZEsKs8veKtiKwlrNimtckHEkj4mRh4pPjsg==", "cpu": [ "ia32" ], "dev": true, "optional": true, "os": [ "win32" ], "engines": { "node": ">=12" } }, "node_modules/@esbuild/win32-x64": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.6.tgz", "integrity": "sha512-n6d8MOyUrNp6G4VSpRcgjs5xj4A91svJSaiwLIDWVWEsZtpN5FA9NlBbZHDmAJc2e8e6SF4tkBD3HAvPF+7igA==", "cpu": [ "x64" ], "dev": true, "optional": true, "os": [ "win32" ], "engines": { "node": ">=12" } }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", "dev": true, "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" }, "engines": { "node": ">= 8" } }, "node_modules/@nodelib/fs.stat": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", "dev": true, "engines": { "node": ">= 8" } }, "node_modules/@nodelib/fs.walk": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", "dev": true, "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" }, "engines": { "node": ">= 8" } }, "node_modules/@types/debug": { "version": "4.1.7", "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.7.tgz", "integrity": "sha512-9AonUzyTjXXhEOa0DnqpzZi6VHlqKMswga9EXjpXnnqxwLtdvPPtlO8evrI5D9S6asFRCQ6v+wpiUKbw+vKqyg==", "dev": true, "dependencies": { "@types/ms": "*" } }, "node_modules/@types/mdast": { "version": "3.0.10", "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-3.0.10.tgz", "integrity": "sha512-W864tg/Osz1+9f4lrGTZpCSO5/z4608eUp19tbozkq2HJK6i3z1kT0H9tlADXuYIb1YYOBByU4Jsqkk75q48qA==", "dev": true, "dependencies": { "@types/unist": "*" } }, "node_modules/@types/ms": { "version": "0.7.31", "resolved": "https://registry.npmjs.org/@types/ms/-/ms-0.7.31.tgz", "integrity": "sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA==", "dev": true }, "node_modules/@types/node": { "version": "18.13.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.13.0.tgz", "integrity": "sha512-gC3TazRzGoOnoKAhUx+Q0t8S9Tzs74z7m0ipwGpSqQrleP14hKxP4/JUeEQcD3W1/aIpnWl8pHowI7WokuZpXg==", "dev": true }, "node_modules/@types/qunit": { "version": "2.19.4", "resolved": "https://registry.npmjs.org/@types/qunit/-/qunit-2.19.4.tgz", "integrity": "sha512-EocRiD2JRWrOaA0dnyyLX083DIo1p3OSBBiGODcHaMzOFhteXtvRRp0kKsiYYqynnBSMqnqRI92iE32axdoXZw==", "dev": true }, "node_modules/@types/unist": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.6.tgz", "integrity": "sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ==", "dev": true }, "node_modules/@yarnpkg/lockfile": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@yarnpkg/lockfile/-/lockfile-1.1.0.tgz", "integrity": "sha512-GpSwvyXOcOOlV70vbnzjj4fW5xW/FdUF6nQEt1ENy7m4ZCczi1+/buVUPAqmGfqznsORNFzUMjctTIp8a9tuCQ==", "dev": true }, "node_modules/acorn": { "version": "8.8.2", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.2.tgz", "integrity": "sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw==", "dev": true, "bin": { "acorn": "bin/acorn" }, "engines": { "node": ">=0.4.0" } }, "node_modules/acorn-walk": { "version": "8.2.0", "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", "dev": true, "engines": { "node": ">=0.4.0" } }, "node_modules/aggregate-error": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-4.0.1.tgz", "integrity": "sha512-0poP0T7el6Vq3rstR8Mn4V/IQrpBLO6POkUSrN7RhyY+GF/InCFShQzsQ39T25gkHhLgSLByyAz+Kjb+c2L98w==", "dev": true, "dependencies": { "clean-stack": "^4.0.0", "indent-string": "^5.0.0" }, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/ansi-regex": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz", "integrity": "sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==", "dev": true, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/chalk/ansi-regex?sponsor=1" } }, "node_modules/ansi-styles": { "version": "6.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", "dev": true, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, "node_modules/anymatch": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", "dev": true, "dependencies": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" }, "engines": { "node": ">= 8" } }, "node_modules/argparse": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", "dev": true, "dependencies": { "sprintf-js": "~1.0.2" } }, "node_modules/array-find-index": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz", "integrity": "sha512-M1HQyIXcBGtVywBt8WVdim+lrNaK7VHp99Qt5pSNziXznKHViIBbXWtfRTpEFpF/c4FdfxNAsCCwPp5phBYJtw==", "dev": true, "engines": { "node": ">=0.10.0" } }, "node_modules/arrgv": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/arrgv/-/arrgv-1.0.2.tgz", "integrity": "sha512-a4eg4yhp7mmruZDQFqVMlxNRFGi/i1r87pt8SDHy0/I8PqSXoUTlWZRdAZo0VXgvEARcujbtTk8kiZRi1uDGRw==", "dev": true, "engines": { "node": ">=8.0.0" } }, "node_modules/arrify": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/arrify/-/arrify-3.0.0.tgz", "integrity": "sha512-tLkvA81vQG/XqE2mjDkGQHoOINtMHtysSnemrmoGe6PydDPMRbVugqyk4A6V/WDWEfm3l+0d8anA9r8cv/5Jaw==", "dev": true, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/at-least-node": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz", "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==", "dev": true, "engines": { "node": ">= 4.0.0" } }, "node_modules/ava": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/ava/-/ava-5.2.0.tgz", "integrity": "sha512-W8yxFXJr/P68JP55eMpQIa6AiXhCX3VeuajM8nolyWNExcMDD6rnIWKTjw0B/+GkFHBIaN6Jd0LtcMThcoqVfg==", "dev": true, "dependencies": { "acorn": "^8.8.1", "acorn-walk": "^8.2.0", "ansi-styles": "^6.2.1", "arrgv": "^1.0.2", "arrify": "^3.0.0", "callsites": "^4.0.0", "cbor": "^8.1.0", "chalk": "^5.2.0", "chokidar": "^3.5.3", "chunkd": "^2.0.1", "ci-info": "^3.7.1", "ci-parallel-vars": "^1.0.1", "clean-yaml-object": "^0.1.0", "cli-truncate": "^3.1.0", "code-excerpt": "^4.0.0", "common-path-prefix": "^3.0.0", "concordance": "^5.0.4", "currently-unhandled": "^0.4.1", "debug": "^4.3.4", "del": "^7.0.0", "emittery": "^1.0.1", "figures": "^5.0.0", "globby": "^13.1.3", "ignore-by-default": "^2.1.0", "indent-string": "^5.0.0", "is-error": "^2.2.2", "is-plain-object": "^5.0.0", "is-promise": "^4.0.0", "matcher": "^5.0.0", "mem": "^9.0.2", "ms": "^2.1.3", "p-event": "^5.0.1", "p-map": "^5.5.0", "picomatch": "^2.3.1", "pkg-conf": "^4.0.0", "plur": "^5.1.0", "pretty-ms": "^8.0.0", "resolve-cwd": "^3.0.0", "slash": "^3.0.0", "stack-utils": "^2.0.6", "strip-ansi": "^7.0.1", "supertap": "^3.0.1", "temp-dir": "^3.0.0", "write-file-atomic": "^5.0.0", "yargs": "^17.6.2" }, "bin": { "ava": "entrypoints/cli.mjs" }, "engines": { "node": ">=14.19 <15 || >=16.15 <17 || >=18" }, "peerDependencies": { "@ava/typescript": "*" }, "peerDependenciesMeta": { "@ava/typescript": { "optional": true } } }, "node_modules/available-typed-arrays": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz", "integrity": "sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw==", "dev": true, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "dev": true }, "node_modules/binary-extensions": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", "dev": true, "engines": { "node": ">=8" } }, "node_modules/binary-searching": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/binary-searching/-/binary-searching-2.0.5.tgz", "integrity": "sha512-v4N2l3RxL+m4zDxyxz3Ne2aTmiPn8ZUpKFpdPtO+ItW1NcTCXA7JeHG5GMBSvoKSkQZ9ycS+EouDVxYB9ufKWA==", "dev": true }, "node_modules/blueimp-md5": { "version": "2.19.0", "resolved": "https://registry.npmjs.org/blueimp-md5/-/blueimp-md5-2.19.0.tgz", "integrity": "sha512-DRQrD6gJyy8FbiE4s+bDoXS9hiW3Vbx5uCdwvcCf3zLHL+Iv7LtGHLpr+GZV8rHG8tK766FGYBwRbu8pELTt+w==", "dev": true }, "node_modules/brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", "dev": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "node_modules/braces": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", "dev": true, "dependencies": { "fill-range": "^7.0.1" }, "engines": { "node": ">=8" } }, "node_modules/call-bind": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", "dev": true, "dependencies": { "function-bind": "^1.1.1", "get-intrinsic": "^1.0.2" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/callsites": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-4.0.0.tgz", "integrity": "sha512-y3jRROutgpKdz5vzEhWM34TidDU8vkJppF8dszITeb1PQmSqV3DTxyV8G/lyO/DNvtE1YTedehmw9MPZsCBHxQ==", "dev": true, "engines": { "node": ">=12.20" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/cbor": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/cbor/-/cbor-8.1.0.tgz", "integrity": "sha512-DwGjNW9omn6EwP70aXsn7FQJx5kO12tX0bZkaTjzdVFM6/7nhA4t0EENocKGx6D2Bch9PE2KzCUf5SceBdeijg==", "dev": true, "dependencies": { "nofilter": "^3.1.0" }, "engines": { "node": ">=12.19" } }, "node_modules/chalk": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.2.0.tgz", "integrity": "sha512-ree3Gqw/nazQAPuJJEy+avdl7QfZMcUvmHIKgEZkGL+xOBzRvup5Hxo6LHuMceSxOabuJLJm5Yp/92R9eMmMvA==", "dev": true, "engines": { "node": "^12.17.0 || ^14.13 || >=16.0.0" }, "funding": { "url": "https://github.com/chalk/chalk?sponsor=1" } }, "node_modules/character-entities": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==", "dev": true, "funding": { "type": "github", "url": "https://github.com/sponsors/wooorm" } }, "node_modules/chokidar": { "version": "3.5.3", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", "dev": true, "funding": [ { "type": "individual", "url": "https://paulmillr.com/funding/" } ], "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", "readdirp": "~3.6.0" }, "engines": { "node": ">= 8.10.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "node_modules/chownr": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", "dev": true, "engines": { "node": ">=10" } }, "node_modules/chunkd": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/chunkd/-/chunkd-2.0.1.tgz", "integrity": "sha512-7d58XsFmOq0j6el67Ug9mHf9ELUXsQXYJBkyxhH/k+6Ke0qXRnv0kbemx+Twc6fRJ07C49lcbdgm9FL1Ei/6SQ==", "dev": true }, "node_modules/ci-info": { "version": "3.7.1", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.7.1.tgz", "integrity": "sha512-4jYS4MOAaCIStSRwiuxc4B8MYhIe676yO1sYGzARnjXkWpmzZMMYxY6zu8WYWDhSuth5zhrQ1rhNSibyyvv4/w==", "dev": true, "funding": [ { "type": "github", "url": "https://github.com/sponsors/sibiraj-s" } ], "engines": { "node": ">=8" } }, "node_modules/ci-parallel-vars": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/ci-parallel-vars/-/ci-parallel-vars-1.0.1.tgz", "integrity": "sha512-uvzpYrpmidaoxvIQHM+rKSrigjOe9feHYbw4uOI2gdfe1C3xIlxO+kVXq83WQWNniTf8bAxVpy+cQeFQsMERKg==", "dev": true }, "node_modules/clean-stack": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-4.2.0.tgz", "integrity": "sha512-LYv6XPxoyODi36Dp976riBtSY27VmFo+MKqEU9QCCWyTrdEPDog+RWA7xQWHi6Vbp61j5c4cdzzX1NidnwtUWg==", "dev": true, "dependencies": { "escape-string-regexp": "5.0.0" }, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/clean-yaml-object": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/clean-yaml-object/-/clean-yaml-object-0.1.0.tgz", "integrity": "sha512-3yONmlN9CSAkzNwnRCiJQ7Q2xK5mWuEfL3PuTZcAUzhObbXsfsnMptJzXwz93nc5zn9V9TwCVMmV7w4xsm43dw==", "dev": true, "engines": { "node": ">=0.10.0" } }, "node_modules/cli-truncate": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-3.1.0.tgz", "integrity": "sha512-wfOBkjXteqSnI59oPcJkcPl/ZmwvMMOj340qUIY1SKZCv0B9Cf4D4fAucRkIKQmsIuYK3x1rrgU7MeGRruiuiA==", "dev": true, "dependencies": { "slice-ansi": "^5.0.0", "string-width": "^5.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/cliui": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", "dev": true, "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" }, "engines": { "node": ">=12" } }, "node_modules/cliui/node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, "engines": { "node": ">=8" } }, "node_modules/cliui/node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "dev": true }, "node_modules/cliui/node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true, "engines": { "node": ">=8" } }, "node_modules/cliui/node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" }, "engines": { "node": ">=8" } }, "node_modules/cliui/node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, "dependencies": { "ansi-regex": "^5.0.1" }, "engines": { "node": ">=8" } }, "node_modules/code-excerpt": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/code-excerpt/-/code-excerpt-4.0.0.tgz", "integrity": "sha512-xxodCmBen3iy2i0WtAK8FlFNrRzjUqjRsMfho58xT/wvZU1YTM3fCnRjcy1gJPMepaRlgm/0e6w8SpWHpn3/cA==", "dev": true, "dependencies": { "convert-to-spaces": "^2.0.1" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" } }, "node_modules/color-convert": { "version": "1.9.3", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", "dev": true, "dependencies": { "color-name": "1.1.3" } }, "node_modules/color-name": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", "dev": true }, "node_modules/commander": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", "dev": true, "engines": { "node": ">= 10" } }, "node_modules/comment-parser": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/comment-parser/-/comment-parser-1.3.1.tgz", "integrity": "sha512-B52sN2VNghyq5ofvUsqZjmk6YkihBX5vMSChmSK9v4ShjKf3Vk5Xcmgpw4o+iIgtrnM/u5FiMpz9VKb8lpBveA==", "dev": true, "engines": { "node": ">= 12.0.0" } }, "node_modules/common-path-prefix": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/common-path-prefix/-/common-path-prefix-3.0.0.tgz", "integrity": "sha512-QE33hToZseCH3jS0qN96O/bSh3kaw/h+Tq7ngyY9eWDUnTlTNUyqfqvCXioLe5Na5jFsL78ra/wuBU4iuEgd4w==", "dev": true }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", "dev": true }, "node_modules/concordance": { "version": "5.0.4", "resolved": "https://registry.npmjs.org/concordance/-/concordance-5.0.4.tgz", "integrity": "sha512-OAcsnTEYu1ARJqWVGwf4zh4JDfHZEaSNlNccFmt8YjB2l/n19/PF2viLINHc57vO4FKIAFl2FWASIGZZWZ2Kxw==", "dev": true, "dependencies": { "date-time": "^3.1.0", "esutils": "^2.0.3", "fast-diff": "^1.2.0", "js-string-escape": "^1.0.1", "lodash": "^4.17.15", "md5-hex": "^3.0.1", "semver": "^7.3.2", "well-known-symbols": "^2.0.0" }, "engines": { "node": ">=10.18.0 <11 || >=12.14.0 <13 || >=14" } }, "node_modules/convert-hrtime": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/convert-hrtime/-/convert-hrtime-3.0.0.tgz", "integrity": "sha512-7V+KqSvMiHp8yWDuwfww06XleMWVVB9b9tURBx+G7UTADuo5hYPuowKloz4OzOqbPezxgo+fdQ1522WzPG4OeA==", "dev": true, "engines": { "node": ">=8" } }, "node_modules/convert-to-spaces": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/convert-to-spaces/-/convert-to-spaces-2.0.1.tgz", "integrity": "sha512-rcQ1bsQO9799wq24uE5AM2tAILy4gXGIK/njFWcVQkGNZ96edlpY+A7bjwvzjYvLDyzmG1MmMLZhpcsb+klNMQ==", "dev": true, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" } }, "node_modules/cross-spawn": { "version": "6.0.5", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", "dev": true, "dependencies": { "nice-try": "^1.0.4", "path-key": "^2.0.1", "semver": "^5.5.0", "shebang-command": "^1.2.0", "which": "^1.2.9" }, "engines": { "node": ">=4.8" } }, "node_modules/cross-spawn/node_modules/semver": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", "dev": true, "bin": { "semver": "bin/semver" } }, "node_modules/currently-unhandled": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/currently-unhandled/-/currently-unhandled-0.4.1.tgz", "integrity": "sha512-/fITjgjGU50vjQ4FH6eUoYu+iUoUKIXws2hL15JJpIR+BbTxaXQsMuuyjtNh2WqsSBS5nsaZHFsFecyw5CCAng==", "dev": true, "dependencies": { "array-find-index": "^1.0.1" }, "engines": { "node": ">=0.10.0" } }, "node_modules/date-time": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/date-time/-/date-time-3.1.0.tgz", "integrity": "sha512-uqCUKXE5q1PNBXjPqvwhwJf9SwMoAHBgWJ6DcrnS5o+W2JOiIILl0JEdVD8SGujrNS02GGxgwAg2PN2zONgtjg==", "dev": true, "dependencies": { "time-zone": "^1.0.0" }, "engines": { "node": ">=6" } }, "node_modules/debug": { "version": "4.3.4", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", "dev": true, "dependencies": { "ms": "2.1.2" }, "engines": { "node": ">=6.0" }, "peerDependenciesMeta": { "supports-color": { "optional": true } } }, "node_modules/debug/node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", "dev": true }, "node_modules/decode-named-character-reference": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.0.2.tgz", "integrity": "sha512-O8x12RzrUF8xyVcY0KJowWsmaJxQbmy0/EtnNtHRpsOcT7dFk5W598coHqBVpmWo1oQQfsCqfCmkZN5DJrZVdg==", "dev": true, "dependencies": { "character-entities": "^2.0.0" }, "funding": { "type": "github", "url": "https://github.com/sponsors/wooorm" } }, "node_modules/define-properties": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.4.tgz", "integrity": "sha512-uckOqKcfaVvtBdsVkdPv3XjveQJsNQqmhXgRi8uhvWWuPYZCNlzT8qAyblUgNoXdHdjMTzAqeGjAoli8f+bzPA==", "dev": true, "dependencies": { "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/del": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/del/-/del-7.0.0.tgz", "integrity": "sha512-tQbV/4u5WVB8HMJr08pgw0b6nG4RGt/tj+7Numvq+zqcvUFeMaIWWOUFltiU+6go8BSO2/ogsB4EasDaj0y68Q==", "dev": true, "dependencies": { "globby": "^13.1.2", "graceful-fs": "^4.2.10", "is-glob": "^4.0.3", "is-path-cwd": "^3.0.0", "is-path-inside": "^4.0.0", "p-map": "^5.5.0", "rimraf": "^3.0.2", "slash": "^4.0.0" }, "engines": { "node": ">=14.16" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/del/node_modules/slash": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-4.0.0.tgz", "integrity": "sha512-3dOsAHXXUkQTpOYcoAxLIorMTp4gIQr5IW3iVb7A7lFIp0VHhnynm9izx6TssdrIcVIESAlVjtnO2K8bg+Coew==", "dev": true, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/dequal": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", "dev": true, "engines": { "node": ">=6" } }, "node_modules/diff": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/diff/-/diff-5.1.0.tgz", "integrity": "sha512-D+mk+qE8VC/PAUrlAU34N+VfXev0ghe5ywmpqrawphmVZc1bEfn56uo9qpyGp1p4xpzOHkSW4ztBd6L7Xx4ACw==", "dev": true, "engines": { "node": ">=0.3.1" } }, "node_modules/dir-glob": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", "dev": true, "dependencies": { "path-type": "^4.0.0" }, "engines": { "node": ">=8" } }, "node_modules/eastasianwidth": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", "dev": true }, "node_modules/edge-runtime": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/edge-runtime/-/edge-runtime-2.0.4.tgz", "integrity": "sha512-/9wE50kDLiHImvAiAJkpTmsNCWauRVLnHN2grYCDYdJsKwTVOZenqUN6o6DMIjK8q6yKM3H/0CTVFiRIu0yppA==", "dev": true, "dependencies": { "@edge-runtime/format": "2.0.0", "@edge-runtime/vm": "2.0.3", "exit-hook": "2.2.1", "mri": "1.2.0", "picocolors": "1.0.0", "pretty-bytes": "5.6.0", "pretty-ms": "7.0.1", "time-span": "4.0.0" }, "bin": { "edge-runtime": "dist/cli/index.js" }, "engines": { "node": ">=14" } }, "node_modules/edge-runtime/node_modules/parse-ms": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/parse-ms/-/parse-ms-2.1.0.tgz", "integrity": "sha512-kHt7kzLoS9VBZfUsiKjv43mr91ea+U05EyKkEtqp7vNbHxmaVuEqN7XxeEVnGrMtYOAxGrDElSi96K7EgO1zCA==", "dev": true, "engines": { "node": ">=6" } }, "node_modules/edge-runtime/node_modules/pretty-ms": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-7.0.1.tgz", "integrity": "sha512-973driJZvxiGOQ5ONsFhOF/DtzPMOMtgC11kCpUrPGMTgqp2q/1gwzCquocrN33is0VZ5GFHXZYMM9l6h67v2Q==", "dev": true, "dependencies": { "parse-ms": "^2.1.0" }, "engines": { "node": ">=10" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/emittery": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/emittery/-/emittery-1.0.1.tgz", "integrity": "sha512-2ID6FdrMD9KDLldGesP6317G78K7km/kMcwItRtVFva7I/cSEOIaLpewaUb+YLXVwdAp3Ctfxh/V5zIl1sj7dQ==", "dev": true, "engines": { "node": ">=14.16" }, "funding": { "url": "https://github.com/sindresorhus/emittery?sponsor=1" } }, "node_modules/emoji-regex": { "version": "9.2.2", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", "dev": true }, "node_modules/error-ex": { "version": "1.3.2", "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", "dev": true, "dependencies": { "is-arrayish": "^0.2.1" } }, "node_modules/es-abstract": { "version": "1.21.1", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.21.1.tgz", "integrity": "sha512-QudMsPOz86xYz/1dG1OuGBKOELjCh99IIWHLzy5znUB6j8xG2yMA7bfTV86VSqKF+Y/H08vQPR+9jyXpuC6hfg==", "dev": true, "dependencies": { "available-typed-arrays": "^1.0.5", "call-bind": "^1.0.2", "es-set-tostringtag": "^2.0.1", "es-to-primitive": "^1.2.1", "function-bind": "^1.1.1", "function.prototype.name": "^1.1.5", "get-intrinsic": "^1.1.3", "get-symbol-description": "^1.0.0", "globalthis": "^1.0.3", "gopd": "^1.0.1", "has": "^1.0.3", "has-property-descriptors": "^1.0.0", "has-proto": "^1.0.1", "has-symbols": "^1.0.3", "internal-slot": "^1.0.4", "is-array-buffer": "^3.0.1", "is-callable": "^1.2.7", "is-negative-zero": "^2.0.2", "is-regex": "^1.1.4", "is-shared-array-buffer": "^1.0.2", "is-string": "^1.0.7", "is-typed-array": "^1.1.10", "is-weakref": "^1.0.2", "object-inspect": "^1.12.2", "object-keys": "^1.1.1", "object.assign": "^4.1.4", "regexp.prototype.flags": "^1.4.3", "safe-regex-test": "^1.0.0", "string.prototype.trimend": "^1.0.6", "string.prototype.trimstart": "^1.0.6", "typed-array-length": "^1.0.4", "unbox-primitive": "^1.0.2", "which-typed-array": "^1.1.9" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/es-set-tostringtag": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.1.tgz", "integrity": "sha512-g3OMbtlwY3QewlqAiMLI47KywjWZoEytKr8pf6iTC8uJq5bIAH52Z9pnQ8pVL6whrCto53JZDuUIsifGeLorTg==", "dev": true, "dependencies": { "get-intrinsic": "^1.1.3", "has": "^1.0.3", "has-tostringtag": "^1.0.0" }, "engines": { "node": ">= 0.4" } }, "node_modules/es-to-primitive": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", "dev": true, "dependencies": { "is-callable": "^1.1.4", "is-date-object": "^1.0.1", "is-symbol": "^1.0.2" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/esbuild": { "version": "0.17.6", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.17.6.tgz", "integrity": "sha512-TKFRp9TxrJDdRWfSsSERKEovm6v30iHnrjlcGhLBOtReE28Yp1VSBRfO3GTaOFMoxsNerx4TjrhzSuma9ha83Q==", "dev": true, "hasInstallScript": true, "bin": { "esbuild": "bin/esbuild" }, "engines": { "node": ">=12" }, "optionalDependencies": { "@esbuild/android-arm": "0.17.6", "@esbuild/android-arm64": "0.17.6", "@esbuild/android-x64": "0.17.6", "@esbuild/darwin-arm64": "0.17.6", "@esbuild/darwin-x64": "0.17.6", "@esbuild/freebsd-arm64": "0.17.6", "@esbuild/freebsd-x64": "0.17.6", "@esbuild/linux-arm": "0.17.6", "@esbuild/linux-arm64": "0.17.6", "@esbuild/linux-ia32": "0.17.6", "@esbuild/linux-loong64": "0.17.6", "@esbuild/linux-mips64el": "0.17.6", "@esbuild/linux-ppc64": "0.17.6", "@esbuild/linux-riscv64": "0.17.6", "@esbuild/linux-s390x": "0.17.6", "@esbuild/linux-x64": "0.17.6", "@esbuild/netbsd-x64": "0.17.6", "@esbuild/openbsd-x64": "0.17.6", "@esbuild/sunos-x64": "0.17.6", "@esbuild/win32-arm64": "0.17.6", "@esbuild/win32-ia32": "0.17.6", "@esbuild/win32-x64": "0.17.6" } }, "node_modules/escalade": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", "dev": true, "engines": { "node": ">=6" } }, "node_modules/escape-string-regexp": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz", "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==", "dev": true, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/esprima": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", "dev": true, "bin": { "esparse": "bin/esparse.js", "esvalidate": "bin/esvalidate.js" }, "engines": { "node": ">=4" } }, "node_modules/esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", "dev": true, "engines": { "node": ">=0.10.0" } }, "node_modules/exit-hook": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/exit-hook/-/exit-hook-2.2.1.tgz", "integrity": "sha512-eNTPlAD67BmP31LDINZ3U7HSF8l57TxOY2PmBJ1shpCvpnxBF93mWCE8YHBnXs8qiUZJc9WDcWIeC3a2HIAMfw==", "dev": true, "engines": { "node": ">=6" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/fast-diff": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.2.0.tgz", "integrity": "sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w==", "dev": true }, "node_modules/fast-glob": { "version": "3.2.12", "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.12.tgz", "integrity": "sha512-DVj4CQIYYow0BlaelwK1pHl5n5cRSJfM60UA0zK891sVInoPri2Ekj7+e1CT3/3qxXenpI+nBBmQAcJPJgaj4w==", "dev": true, "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.4" }, "engines": { "node": ">=8.6.0" } }, "node_modules/fastq": { "version": "1.15.0", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.15.0.tgz", "integrity": "sha512-wBrocU2LCXXa+lWBt8RoIRD89Fi8OdABODa/kEnyeyjS5aZO5/GNvI5sEINADqP/h8M29UHTHUb53sUu5Ihqdw==", "dev": true, "dependencies": { "reusify": "^1.0.4" } }, "node_modules/figures": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/figures/-/figures-5.0.0.tgz", "integrity": "sha512-ej8ksPF4x6e5wvK9yevct0UCXh8TTFlWGVLlgjZuoBH1HwjIfKE/IdL5mq89sFA7zELi1VhKpmtDnrs7zWyeyg==", "dev": true, "dependencies": { "escape-string-regexp": "^5.0.0", "is-unicode-supported": "^1.2.0" }, "engines": { "node": ">=14" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/fill-range": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", "dev": true, "dependencies": { "to-regex-range": "^5.0.1" }, "engines": { "node": ">=8" } }, "node_modules/find-up": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-6.3.0.tgz", "integrity": "sha512-v2ZsoEuVHYy8ZIlYqwPe/39Cy+cFDzp4dXPaxNvkEuouymu+2Jbz0PxpKarJHYJTmv2HWT3O382qY8l4jMWthw==", "dev": true, "dependencies": { "locate-path": "^7.1.0", "path-exists": "^5.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/find-yarn-workspace-root": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/find-yarn-workspace-root/-/find-yarn-workspace-root-2.0.0.tgz", "integrity": "sha512-1IMnbjt4KzsQfnhnzNd8wUEgXZ44IzZaZmnLYx7D5FZlaHt2gW20Cri8Q+E/t5tIj4+epTBub+2Zxu/vNILzqQ==", "dev": true, "dependencies": { "micromatch": "^4.0.2" } }, "node_modules/for-each": { "version": "0.3.3", "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", "integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==", "dev": true, "dependencies": { "is-callable": "^1.1.3" } }, "node_modules/fs-extra": { "version": "9.1.0", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", "dev": true, "dependencies": { "at-least-node": "^1.0.0", "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" }, "engines": { "node": ">=10" } }, "node_modules/fs-minipass": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", "dev": true, "dependencies": { "minipass": "^3.0.0" }, "engines": { "node": ">= 8" } }, "node_modules/fs-minipass/node_modules/minipass": { "version": "3.3.6", "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", "dev": true, "dependencies": { "yallist": "^4.0.0" }, "engines": { "node": ">=8" } }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", "dev": true }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "dev": true, "hasInstallScript": true, "optional": true, "os": [ "darwin" ], "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, "node_modules/function-bind": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", "dev": true }, "node_modules/function.prototype.name": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.5.tgz", "integrity": "sha512-uN7m/BzVKQnCUF/iW8jYea67v++2u7m5UgENbHRtdDVclOUP+FMPlCNdmk0h/ysGyo2tavMJEDqJAkJdRa1vMA==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.1.3", "es-abstract": "^1.19.0", "functions-have-names": "^1.2.2" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/functions-have-names": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", "dev": true, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "dev": true, "engines": { "node": "6.* || 8.* || >= 10.*" } }, "node_modules/get-intrinsic": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.0.tgz", "integrity": "sha512-L049y6nFOuom5wGyRc3/gdTLO94dySVKRACj1RmJZBQXlbTMhtNIgkWkUHq+jYmZvKf14EW1EoJnnjbmoHij0Q==", "dev": true, "dependencies": { "function-bind": "^1.1.1", "has": "^1.0.3", "has-symbols": "^1.0.3" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/get-symbol-description": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.0.0.tgz", "integrity": "sha512-2EmdH1YvIQiZpltCNgkuiUnyukzxM/R6NDJX31Ke3BG1Nq5b0S2PhX59UKi9vZpPDQVdqn+1IcaAwnzTT5vCjw==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "get-intrinsic": "^1.1.1" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/glob": { "version": "7.2.3", "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", "dev": true, "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" }, "engines": { "node": "*" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/glob-parent": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "dev": true, "dependencies": { "is-glob": "^4.0.1" }, "engines": { "node": ">= 6" } }, "node_modules/globalthis": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.3.tgz", "integrity": "sha512-sFdI5LyBiNTHjRd7cGPWapiHWMOXKyuBNX/cWJ3NfzrZQVa8GI/8cofCl74AOVqq9W5kNmguTIzJ/1s2gyI9wA==", "dev": true, "dependencies": { "define-properties": "^1.1.3" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/globalyzer": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/globalyzer/-/globalyzer-0.1.0.tgz", "integrity": "sha512-40oNTM9UfG6aBmuKxk/giHn5nQ8RVz/SS4Ir6zgzOv9/qC3kKZ9v4etGTcJbEl/NyVQH7FGU7d+X1egr57Md2Q==", "dev": true }, "node_modules/globby": { "version": "13.1.3", "resolved": "https://registry.npmjs.org/globby/-/globby-13.1.3.tgz", "integrity": "sha512-8krCNHXvlCgHDpegPzleMq07yMYTO2sXKASmZmquEYWEmCx6J5UTRbp5RwMJkTJGtcQ44YpiUYUiN0b9mzy8Bw==", "dev": true, "dependencies": { "dir-glob": "^3.0.1", "fast-glob": "^3.2.11", "ignore": "^5.2.0", "merge2": "^1.4.1", "slash": "^4.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/globby/node_modules/slash": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-4.0.0.tgz", "integrity": "sha512-3dOsAHXXUkQTpOYcoAxLIorMTp4gIQr5IW3iVb7A7lFIp0VHhnynm9izx6TssdrIcVIESAlVjtnO2K8bg+Coew==", "dev": true, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/globrex": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/globrex/-/globrex-0.1.2.tgz", "integrity": "sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg==", "dev": true }, "node_modules/gopd": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", "dev": true, "dependencies": { "get-intrinsic": "^1.1.3" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/graceful-fs": { "version": "4.2.10", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.10.tgz", "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==", "dev": true }, "node_modules/handlebars": { "version": "4.7.7", "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.7.tgz", "integrity": "sha512-aAcXm5OAfE/8IXkcZvCepKU3VzW1/39Fb5ZuqMtgI/hT8X2YgoMvBY5dLhq/cpOvw7Lk1nK/UF71aLG/ZnVYRA==", "dev": true, "dependencies": { "minimist": "^1.2.5", "neo-async": "^2.6.0", "source-map": "^0.6.1", "wordwrap": "^1.0.0" }, "bin": { "handlebars": "bin/handlebars" }, "engines": { "node": ">=0.4.7" }, "optionalDependencies": { "uglify-js": "^3.1.4" } }, "node_modules/has": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", "dev": true, "dependencies": { "function-bind": "^1.1.1" }, "engines": { "node": ">= 0.4.0" } }, "node_modules/has-bigints": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", "integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==", "dev": true, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", "dev": true, "engines": { "node": ">=4" } }, "node_modules/has-property-descriptors": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.0.tgz", "integrity": "sha512-62DVLZGoiEBDHQyqG4w9xCuZ7eJEwNmJRWw2VY84Oedb7WFcA27fiEVe8oUQx9hAUJ4ekurquucTGwsyO1XGdQ==", "dev": true, "dependencies": { "get-intrinsic": "^1.1.1" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/has-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.1.tgz", "integrity": "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==", "dev": true, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/has-symbols": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", "dev": true, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/has-tostringtag": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", "dev": true, "dependencies": { "has-symbols": "^1.0.2" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/hosted-git-info": { "version": "2.8.9", "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz", "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==", "dev": true }, "node_modules/ignore": { "version": "5.2.4", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", "dev": true, "engines": { "node": ">= 4" } }, "node_modules/ignore-by-default": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-2.1.0.tgz", "integrity": "sha512-yiWd4GVmJp0Q6ghmM2B/V3oZGRmjrKLXvHR3TE1nfoXsmoggllfZUQe74EN0fJdPFZu2NIvNdrMMLm3OsV7Ohw==", "dev": true, "engines": { "node": ">=10 <11 || >=12 <13 || >=14" } }, "node_modules/imurmurhash": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", "dev": true, "engines": { "node": ">=0.8.19" } }, "node_modules/indent-string": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-5.0.0.tgz", "integrity": "sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg==", "dev": true, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", "dev": true, "dependencies": { "once": "^1.3.0", "wrappy": "1" } }, "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "dev": true }, "node_modules/internal-slot": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.4.tgz", "integrity": "sha512-tA8URYccNzMo94s5MQZgH8NB/XTa6HsOo0MLfXTKKEnHVVdegzaQoFZ7Jp44bdvLvY2waT5dc+j5ICEswhi7UQ==", "dev": true, "dependencies": { "get-intrinsic": "^1.1.3", "has": "^1.0.3", "side-channel": "^1.0.4" }, "engines": { "node": ">= 0.4" } }, "node_modules/irregular-plurals": { "version": "3.4.0", "resolved": "https://registry.npmjs.org/irregular-plurals/-/irregular-plurals-3.4.0.tgz", "integrity": "sha512-YXxECO/W6N9aMBVKMKKZ8TXESgq7EFrp3emCGGUcrYY1cgJIeZjoB75MTu8qi+NAKntS9NwPU8VdcQ3r6E6aWQ==", "dev": true, "engines": { "node": ">=8" } }, "node_modules/is-array-buffer": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.1.tgz", "integrity": "sha512-ASfLknmY8Xa2XtB4wmbz13Wu202baeA18cJBCeCy0wXUHZF0IPyVEXqKEcd+t2fNSLLL1vC6k7lxZEojNbISXQ==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "get-intrinsic": "^1.1.3", "is-typed-array": "^1.1.10" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-arrayish": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", "dev": true }, "node_modules/is-bigint": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz", "integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==", "dev": true, "dependencies": { "has-bigints": "^1.0.1" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-binary-path": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", "dev": true, "dependencies": { "binary-extensions": "^2.0.0" }, "engines": { "node": ">=8" } }, "node_modules/is-boolean-object": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz", "integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "has-tostringtag": "^1.0.0" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-callable": { "version": "1.2.7", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", "dev": true, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-ci": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz", "integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==", "dev": true, "dependencies": { "ci-info": "^2.0.0" }, "bin": { "is-ci": "bin.js" } }, "node_modules/is-ci/node_modules/ci-info": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==", "dev": true }, "node_modules/is-core-module": { "version": "2.11.0", "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.11.0.tgz", "integrity": "sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==", "dev": true, "dependencies": { "has": "^1.0.3" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-date-object": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz", "integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==", "dev": true, "dependencies": { "has-tostringtag": "^1.0.0" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-docker": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", "dev": true, "bin": { "is-docker": "cli.js" }, "engines": { "node": ">=8" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-error": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/is-error/-/is-error-2.2.2.tgz", "integrity": "sha512-IOQqts/aHWbiisY5DuPJQ0gcbvaLFCa7fBa9xoLfxBZvQ+ZI/Zh9xoI7Gk+G64N0FdK4AbibytHht2tWgpJWLg==", "dev": true }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", "dev": true, "engines": { "node": ">=0.10.0" } }, "node_modules/is-fullwidth-code-point": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz", "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==", "dev": true, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-glob": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", "dev": true, "dependencies": { "is-extglob": "^2.1.1" }, "engines": { "node": ">=0.10.0" } }, "node_modules/is-negative-zero": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.2.tgz", "integrity": "sha512-dqJvarLawXsFbNDeJW7zAz8ItJ9cd28YufuuFzh0G8pNHjJMnY08Dv7sYX2uF5UpQOwieAeOExEYAWWfu7ZZUA==", "dev": true, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "dev": true, "engines": { "node": ">=0.12.0" } }, "node_modules/is-number-object": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz", "integrity": "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==", "dev": true, "dependencies": { "has-tostringtag": "^1.0.0" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-path-cwd": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-3.0.0.tgz", "integrity": "sha512-kyiNFFLU0Ampr6SDZitD/DwUo4Zs1nSdnygUBqsu3LooL00Qvb5j+UnvApUn/TTj1J3OuE6BTdQ5rudKmU2ZaA==", "dev": true, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-path-inside": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-4.0.0.tgz", "integrity": "sha512-lJJV/5dYS+RcL8uQdBDW9c9uWFLLBNRyFhnAKXw5tVqLlKZ4RMGZKv+YQ/IA3OhD+RpbJa1LLFM1FQPGyIXvOA==", "dev": true, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-plain-object": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz", "integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==", "dev": true, "engines": { "node": ">=0.10.0" } }, "node_modules/is-promise": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", "dev": true }, "node_modules/is-regex": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", "integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "has-tostringtag": "^1.0.0" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-shared-array-buffer": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.2.tgz", "integrity": "sha512-sqN2UDu1/0y6uvXyStCOzyhAjCSlHceFoMKJW8W9EU9cvic/QdsZ0kEU93HEy3IUEFZIiH/3w+AH/UQbPHNdhA==", "dev": true, "dependencies": { "call-bind": "^1.0.2" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-string": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz", "integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==", "dev": true, "dependencies": { "has-tostringtag": "^1.0.0" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-symbol": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz", "integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==", "dev": true, "dependencies": { "has-symbols": "^1.0.2" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-typed-array": { "version": "1.1.10", "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.10.tgz", "integrity": "sha512-PJqgEHiWZvMpaFZ3uTc8kHPM4+4ADTlDniuQL7cU/UDA0Ql7F70yGfHph3cLNe+c9toaigv+DFzTJKhc2CtO6A==", "dev": true, "dependencies": { "available-typed-arrays": "^1.0.5", "call-bind": "^1.0.2", "for-each": "^0.3.3", "gopd": "^1.0.1", "has-tostringtag": "^1.0.0" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-unicode-supported": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-1.3.0.tgz", "integrity": "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ==", "dev": true, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-weakref": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.2.tgz", "integrity": "sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ==", "dev": true, "dependencies": { "call-bind": "^1.0.2" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-wsl": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", "dev": true, "dependencies": { "is-docker": "^2.0.0" }, "engines": { "node": ">=8" } }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", "dev": true }, "node_modules/js-string-escape": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/js-string-escape/-/js-string-escape-1.0.1.tgz", "integrity": "sha512-Smw4xcfIQ5LVjAOuJCvN/zIodzA/BBSsluuoSykP+lUvScIi4U6RJLfwHet5cxFnCswUjISV8oAXaqaJDY3chg==", "dev": true, "engines": { "node": ">= 0.8" } }, "node_modules/js-yaml": { "version": "3.14.1", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", "dev": true, "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "node_modules/json-parse-better-errors": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", "dev": true }, "node_modules/json-stringify-safe": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==", "dev": true }, "node_modules/jsonc-parser": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.2.0.tgz", "integrity": "sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w==", "dev": true }, "node_modules/jsonfile": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", "dev": true, "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "node_modules/klaw-sync": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/klaw-sync/-/klaw-sync-6.0.0.tgz", "integrity": "sha512-nIeuVSzdCCs6TDPTqI8w1Yre34sSq7AkZ4B3sfOBbI2CgVSB4Du4aLQijFU2+lhAFCwt9+42Hel6lQNIv6AntQ==", "dev": true, "dependencies": { "graceful-fs": "^4.1.11" } }, "node_modules/kleur": { "version": "4.1.5", "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", "dev": true, "engines": { "node": ">=6" } }, "node_modules/load-json-file": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-7.0.1.tgz", "integrity": "sha512-Gnxj3ev3mB5TkVBGad0JM6dmLiQL+o0t23JPBZ9sd+yvSLk05mFoqKBw5N8gbbkU4TNXyqCgIrl/VM17OgUIgQ==", "dev": true, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/locate-path": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-7.1.1.tgz", "integrity": "sha512-vJXaRMJgRVD3+cUZs3Mncj2mxpt5mP0EmNOsxRSZRMlbqjvxzDEOIUWXGmavo0ZC9+tNZCBLQ66reA11nbpHZg==", "dev": true, "dependencies": { "p-locate": "^6.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/lodash": { "version": "4.17.21", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", "dev": true }, "node_modules/lru-cache": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", "dev": true, "dependencies": { "yallist": "^4.0.0" }, "engines": { "node": ">=10" } }, "node_modules/lunr": { "version": "2.3.9", "resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.9.tgz", "integrity": "sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==", "dev": true }, "node_modules/map-age-cleaner": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/map-age-cleaner/-/map-age-cleaner-0.1.3.tgz", "integrity": "sha512-bJzx6nMoP6PDLPBFmg7+xRKeFZvFboMrGlxmNj9ClvX53KrmvM5bXFXEWjbz4cz1AFn+jWJ9z/DJSz7hrs0w3w==", "dev": true, "dependencies": { "p-defer": "^1.0.0" }, "engines": { "node": ">=6" } }, "node_modules/marked": { "version": "4.2.12", "resolved": "https://registry.npmjs.org/marked/-/marked-4.2.12.tgz", "integrity": "sha512-yr8hSKa3Fv4D3jdZmtMMPghgVt6TWbk86WQaWhDloQjRSQhMMYCAro7jP7VDJrjjdV8pxVxMssXS8B8Y5DZ5aw==", "dev": true, "bin": { "marked": "bin/marked.js" }, "engines": { "node": ">= 12" } }, "node_modules/matcher": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/matcher/-/matcher-5.0.0.tgz", "integrity": "sha512-s2EMBOWtXFc8dgqvoAzKJXxNHibcdJMV0gwqKUaw9E2JBJuGUK7DrNKrA6g/i+v72TT16+6sVm5mS3thaMLQUw==", "dev": true, "dependencies": { "escape-string-regexp": "^5.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/md5-hex": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/md5-hex/-/md5-hex-3.0.1.tgz", "integrity": "sha512-BUiRtTtV39LIJwinWBjqVsU9xhdnz7/i889V859IBFpuqGAj6LuOvHv5XLbgZ2R7ptJoJaEcxkv88/h25T7Ciw==", "dev": true, "dependencies": { "blueimp-md5": "^2.10.0" }, "engines": { "node": ">=8" } }, "node_modules/mdast-util-from-markdown": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-1.3.0.tgz", "integrity": "sha512-HN3W1gRIuN/ZW295c7zi7g9lVBllMgZE40RxCX37wrTPWXCWtpvOZdfnuK+1WNpvZje6XuJeI3Wnb4TJEUem+g==", "dev": true, "dependencies": { "@types/mdast": "^3.0.0", "@types/unist": "^2.0.0", "decode-named-character-reference": "^1.0.0", "mdast-util-to-string": "^3.1.0", "micromark": "^3.0.0", "micromark-util-decode-numeric-character-reference": "^1.0.0", "micromark-util-decode-string": "^1.0.0", "micromark-util-normalize-identifier": "^1.0.0", "micromark-util-symbol": "^1.0.0", "micromark-util-types": "^1.0.0", "unist-util-stringify-position": "^3.0.0", "uvu": "^0.5.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/unified" } }, "node_modules/mdast-util-to-string": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-3.1.1.tgz", "integrity": "sha512-tGvhT94e+cVnQt8JWE9/b3cUQZWS732TJxXHktvP+BYo62PpYD53Ls/6cC60rW21dW+txxiM4zMdc6abASvZKA==", "dev": true, "dependencies": { "@types/mdast": "^3.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/unified" } }, "node_modules/mem": { "version": "9.0.2", "resolved": "https://registry.npmjs.org/mem/-/mem-9.0.2.tgz", "integrity": "sha512-F2t4YIv9XQUBHt6AOJ0y7lSmP1+cY7Fm1DRh9GClTGzKST7UWLMx6ly9WZdLH/G/ppM5RL4MlQfRT71ri9t19A==", "dev": true, "dependencies": { "map-age-cleaner": "^0.1.3", "mimic-fn": "^4.0.0" }, "engines": { "node": ">=12.20" }, "funding": { "url": "https://github.com/sindresorhus/mem?sponsor=1" } }, "node_modules/memorystream": { "version": "0.3.1", "resolved": "https://registry.npmjs.org/memorystream/-/memorystream-0.3.1.tgz", "integrity": "sha512-S3UwM3yj5mtUSEfP41UZmt/0SCoVYUcU1rkXv+BQ5Ig8ndL4sPoJNBUJERafdPb5jjHJGuMgytgKvKIf58XNBw==", "dev": true, "engines": { "node": ">= 0.10.0" } }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", "dev": true, "engines": { "node": ">= 8" } }, "node_modules/micromark": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/micromark/-/micromark-3.1.0.tgz", "integrity": "sha512-6Mj0yHLdUZjHnOPgr5xfWIMqMWS12zDN6iws9SLuSz76W8jTtAv24MN4/CL7gJrl5vtxGInkkqDv/JIoRsQOvA==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", "decode-named-character-reference": "^1.0.0", "micromark-core-commonmark": "^1.0.1", "micromark-factory-space": "^1.0.0", "micromark-util-character": "^1.0.0", "micromark-util-chunked": "^1.0.0", "micromark-util-combine-extensions": "^1.0.0", "micromark-util-decode-numeric-character-reference": "^1.0.0", "micromark-util-encode": "^1.0.0", "micromark-util-normalize-identifier": "^1.0.0", "micromark-util-resolve-all": "^1.0.0", "micromark-util-sanitize-uri": "^1.0.0", "micromark-util-subtokenize": "^1.0.0", "micromark-util-symbol": "^1.0.0", "micromark-util-types": "^1.0.1", "uvu": "^0.5.0" } }, "node_modules/micromark-core-commonmark": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-1.0.6.tgz", "integrity": "sha512-K+PkJTxqjFfSNkfAhp4GB+cZPfQd6dxtTXnf+RjZOV7T4EEXnvgzOcnp+eSTmpGk9d1S9sL6/lqrgSNn/s0HZA==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "decode-named-character-reference": "^1.0.0", "micromark-factory-destination": "^1.0.0", "micromark-factory-label": "^1.0.0", "micromark-factory-space": "^1.0.0", "micromark-factory-title": "^1.0.0", "micromark-factory-whitespace": "^1.0.0", "micromark-util-character": "^1.0.0", "micromark-util-chunked": "^1.0.0", "micromark-util-classify-character": "^1.0.0", "micromark-util-html-tag-name": "^1.0.0", "micromark-util-normalize-identifier": "^1.0.0", "micromark-util-resolve-all": "^1.0.0", "micromark-util-subtokenize": "^1.0.0", "micromark-util-symbol": "^1.0.0", "micromark-util-types": "^1.0.1", "uvu": "^0.5.0" } }, "node_modules/micromark-factory-destination": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-1.0.0.tgz", "integrity": "sha512-eUBA7Rs1/xtTVun9TmV3gjfPz2wEwgK5R5xcbIM5ZYAtvGF6JkyaDsj0agx8urXnO31tEO6Ug83iVH3tdedLnw==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "micromark-util-character": "^1.0.0", "micromark-util-symbol": "^1.0.0", "micromark-util-types": "^1.0.0" } }, "node_modules/micromark-factory-label": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-1.0.2.tgz", "integrity": "sha512-CTIwxlOnU7dEshXDQ+dsr2n+yxpP0+fn271pu0bwDIS8uqfFcumXpj5mLn3hSC8iw2MUr6Gx8EcKng1dD7i6hg==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "micromark-util-character": "^1.0.0", "micromark-util-symbol": "^1.0.0", "micromark-util-types": "^1.0.0", "uvu": "^0.5.0" } }, "node_modules/micromark-factory-space": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-1.0.0.tgz", "integrity": "sha512-qUmqs4kj9a5yBnk3JMLyjtWYN6Mzfcx8uJfi5XAveBniDevmZasdGBba5b4QsvRcAkmvGo5ACmSUmyGiKTLZew==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "micromark-util-character": "^1.0.0", "micromark-util-types": "^1.0.0" } }, "node_modules/micromark-factory-title": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-1.0.2.tgz", "integrity": "sha512-zily+Nr4yFqgMGRKLpTVsNl5L4PMu485fGFDOQJQBl2NFpjGte1e86zC0da93wf97jrc4+2G2GQudFMHn3IX+A==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "micromark-factory-space": "^1.0.0", "micromark-util-character": "^1.0.0", "micromark-util-symbol": "^1.0.0", "micromark-util-types": "^1.0.0", "uvu": "^0.5.0" } }, "node_modules/micromark-factory-whitespace": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-1.0.0.tgz", "integrity": "sha512-Qx7uEyahU1lt1RnsECBiuEbfr9INjQTGa6Err+gF3g0Tx4YEviPbqqGKNv/NrBaE7dVHdn1bVZKM/n5I/Bak7A==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "micromark-factory-space": "^1.0.0", "micromark-util-character": "^1.0.0", "micromark-util-symbol": "^1.0.0", "micromark-util-types": "^1.0.0" } }, "node_modules/micromark-util-character": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-1.1.0.tgz", "integrity": "sha512-agJ5B3unGNJ9rJvADMJ5ZiYjBRyDpzKAOk01Kpi1TKhlT1APx3XZk6eN7RtSz1erbWHC2L8T3xLZ81wdtGRZzg==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "micromark-util-symbol": "^1.0.0", "micromark-util-types": "^1.0.0" } }, "node_modules/micromark-util-chunked": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-1.0.0.tgz", "integrity": "sha512-5e8xTis5tEZKgesfbQMKRCyzvffRRUX+lK/y+DvsMFdabAicPkkZV6gO+FEWi9RfuKKoxxPwNL+dFF0SMImc1g==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "micromark-util-symbol": "^1.0.0" } }, "node_modules/micromark-util-classify-character": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-1.0.0.tgz", "integrity": "sha512-F8oW2KKrQRb3vS5ud5HIqBVkCqQi224Nm55o5wYLzY/9PwHGXC01tr3d7+TqHHz6zrKQ72Okwtvm/xQm6OVNZA==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "micromark-util-character": "^1.0.0", "micromark-util-symbol": "^1.0.0", "micromark-util-types": "^1.0.0" } }, "node_modules/micromark-util-combine-extensions": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-1.0.0.tgz", "integrity": "sha512-J8H058vFBdo/6+AsjHp2NF7AJ02SZtWaVUjsayNFeAiydTxUwViQPxN0Hf8dp4FmCQi0UUFovFsEyRSUmFH3MA==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "micromark-util-chunked": "^1.0.0", "micromark-util-types": "^1.0.0" } }, "node_modules/micromark-util-decode-numeric-character-reference": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-1.0.0.tgz", "integrity": "sha512-OzO9AI5VUtrTD7KSdagf4MWgHMtET17Ua1fIpXTpuhclCqD8egFWo85GxSGvxgkGS74bEahvtM0WP0HjvV0e4w==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "micromark-util-symbol": "^1.0.0" } }, "node_modules/micromark-util-decode-string": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/micromark-util-decode-string/-/micromark-util-decode-string-1.0.2.tgz", "integrity": "sha512-DLT5Ho02qr6QWVNYbRZ3RYOSSWWFuH3tJexd3dgN1odEuPNxCngTCXJum7+ViRAd9BbdxCvMToPOD/IvVhzG6Q==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "decode-named-character-reference": "^1.0.0", "micromark-util-character": "^1.0.0", "micromark-util-decode-numeric-character-reference": "^1.0.0", "micromark-util-symbol": "^1.0.0" } }, "node_modules/micromark-util-encode": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-1.0.1.tgz", "integrity": "sha512-U2s5YdnAYexjKDel31SVMPbfi+eF8y1U4pfiRW/Y8EFVCy/vgxk/2wWTxzcqE71LHtCuCzlBDRU2a5CQ5j+mQA==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ] }, "node_modules/micromark-util-html-tag-name": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-1.1.0.tgz", "integrity": "sha512-BKlClMmYROy9UiV03SwNmckkjn8QHVaWkqoAqzivabvdGcwNGMMMH/5szAnywmsTBUzDsU57/mFi0sp4BQO6dA==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ] }, "node_modules/micromark-util-normalize-identifier": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-1.0.0.tgz", "integrity": "sha512-yg+zrL14bBTFrQ7n35CmByWUTFsgst5JhA4gJYoty4Dqzj4Z4Fr/DHekSS5aLfH9bdlfnSvKAWsAgJhIbogyBg==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "micromark-util-symbol": "^1.0.0" } }, "node_modules/micromark-util-resolve-all": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-1.0.0.tgz", "integrity": "sha512-CB/AGk98u50k42kvgaMM94wzBqozSzDDaonKU7P7jwQIuH2RU0TeBqGYJz2WY1UdihhjweivStrJ2JdkdEmcfw==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "micromark-util-types": "^1.0.0" } }, "node_modules/micromark-util-sanitize-uri": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-1.1.0.tgz", "integrity": "sha512-RoxtuSCX6sUNtxhbmsEFQfWzs8VN7cTctmBPvYivo98xb/kDEoTCtJQX5wyzIYEmk/lvNFTat4hL8oW0KndFpg==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "micromark-util-character": "^1.0.0", "micromark-util-encode": "^1.0.0", "micromark-util-symbol": "^1.0.0" } }, "node_modules/micromark-util-subtokenize": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-1.0.2.tgz", "integrity": "sha512-d90uqCnXp/cy4G881Ub4psE57Sf8YD0pim9QdjCRNjfas2M1u6Lbt+XZK9gnHL2XFhnozZiEdCa9CNfXSfQ6xA==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ], "dependencies": { "micromark-util-chunked": "^1.0.0", "micromark-util-symbol": "^1.0.0", "micromark-util-types": "^1.0.0", "uvu": "^0.5.0" } }, "node_modules/micromark-util-symbol": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-1.0.1.tgz", "integrity": "sha512-oKDEMK2u5qqAptasDAwWDXq0tG9AssVwAx3E9bBF3t/shRIGsWIRG+cGafs2p/SnDSOecnt6hZPCE2o6lHfFmQ==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ] }, "node_modules/micromark-util-types": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-1.0.2.tgz", "integrity": "sha512-DCfg/T8fcrhrRKTPjRrw/5LLvdGV7BHySf/1LOZx7TzWZdYRjogNtyNq885z3nNallwr3QUKARjqvHqX1/7t+w==", "dev": true, "funding": [ { "type": "GitHub Sponsors", "url": "https://github.com/sponsors/unifiedjs" }, { "type": "OpenCollective", "url": "https://opencollective.com/unified" } ] }, "node_modules/micromatch": { "version": "4.0.5", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", "dev": true, "dependencies": { "braces": "^3.0.2", "picomatch": "^2.3.1" }, "engines": { "node": ">=8.6" } }, "node_modules/mimic-fn": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==", "dev": true, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "dev": true, "dependencies": { "brace-expansion": "^1.1.7" }, "engines": { "node": "*" } }, "node_modules/minimist": { "version": "1.2.7", "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz", "integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==", "dev": true, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/minipass": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/minipass/-/minipass-4.0.2.tgz", "integrity": "sha512-4Hbzei7ZyBp+1aw0874YWpKOubZd/jc53/XU+gkYry1QV+VvrbO8icLM5CUtm4F0hyXn85DXYKEMIS26gitD3A==", "dev": true, "engines": { "node": ">=8" } }, "node_modules/minizlib": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", "dev": true, "dependencies": { "minipass": "^3.0.0", "yallist": "^4.0.0" }, "engines": { "node": ">= 8" } }, "node_modules/minizlib/node_modules/minipass": { "version": "3.3.6", "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", "dev": true, "dependencies": { "yallist": "^4.0.0" }, "engines": { "node": ">=8" } }, "node_modules/mkdirp": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", "dev": true, "bin": { "mkdirp": "bin/cmd.js" }, "engines": { "node": ">=10" } }, "node_modules/mri": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", "dev": true, "engines": { "node": ">=4" } }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "dev": true }, "node_modules/neo-async": { "version": "2.6.2", "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", "dev": true }, "node_modules/nice-try": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", "dev": true }, "node_modules/nock": { "version": "13.3.0", "resolved": "https://registry.npmjs.org/nock/-/nock-13.3.0.tgz", "integrity": "sha512-HHqYQ6mBeiMc+N038w8LkMpDCRquCHWeNmN3v6645P3NhN2+qXOBqvPqo7Rt1VyCMzKhJ733wZqw5B7cQVFNPg==", "dev": true, "dependencies": { "debug": "^4.1.0", "json-stringify-safe": "^5.0.1", "lodash": "^4.17.21", "propagate": "^2.0.0" }, "engines": { "node": ">= 10.13" } }, "node_modules/node-watch": { "version": "0.7.3", "resolved": "https://registry.npmjs.org/node-watch/-/node-watch-0.7.3.tgz", "integrity": "sha512-3l4E8uMPY1HdMMryPRUAl+oIHtXtyiTlIiESNSVSNxcPfzAFzeTbXFQkZfAwBbo0B1qMSG8nUABx+Gd+YrbKrQ==", "dev": true, "engines": { "node": ">=6" } }, "node_modules/nofilter": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/nofilter/-/nofilter-3.1.0.tgz", "integrity": "sha512-l2NNj07e9afPnhAhvgVrCD/oy2Ai1yfLpuo3EpiO1jFTsB4sFz6oIfAfSZyQzVpkZQ9xS8ZS5g1jCBgq4Hwo0g==", "dev": true, "engines": { "node": ">=12.19" } }, "node_modules/normalize-package-data": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", "dev": true, "dependencies": { "hosted-git-info": "^2.1.4", "resolve": "^1.10.0", "semver": "2 || 3 || 4 || 5", "validate-npm-package-license": "^3.0.1" } }, "node_modules/normalize-package-data/node_modules/semver": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", "dev": true, "bin": { "semver": "bin/semver" } }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", "dev": true, "engines": { "node": ">=0.10.0" } }, "node_modules/npm-run-all": { "version": "4.1.5", "resolved": "https://registry.npmjs.org/npm-run-all/-/npm-run-all-4.1.5.tgz", "integrity": "sha512-Oo82gJDAVcaMdi3nuoKFavkIHBRVqQ1qvMb+9LHk/cF4P6B2m8aP04hGf7oL6wZ9BuGwX1onlLhpuoofSyoQDQ==", "dev": true, "dependencies": { "ansi-styles": "^3.2.1", "chalk": "^2.4.1", "cross-spawn": "^6.0.5", "memorystream": "^0.3.1", "minimatch": "^3.0.4", "pidtree": "^0.3.0", "read-pkg": "^3.0.0", "shell-quote": "^1.6.1", "string.prototype.padend": "^3.0.0" }, "bin": { "npm-run-all": "bin/npm-run-all/index.js", "run-p": "bin/run-p/index.js", "run-s": "bin/run-s/index.js" }, "engines": { "node": ">= 4" } }, "node_modules/npm-run-all/node_modules/ansi-styles": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", "dev": true, "dependencies": { "color-convert": "^1.9.0" }, "engines": { "node": ">=4" } }, "node_modules/npm-run-all/node_modules/chalk": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "dev": true, "dependencies": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" }, "engines": { "node": ">=4" } }, "node_modules/npm-run-all/node_modules/escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", "dev": true, "engines": { "node": ">=0.8.0" } }, "node_modules/object-inspect": { "version": "1.12.3", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.3.tgz", "integrity": "sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g==", "dev": true, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/object-keys": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", "dev": true, "engines": { "node": ">= 0.4" } }, "node_modules/object.assign": { "version": "4.1.4", "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.4.tgz", "integrity": "sha512-1mxKf0e58bvyjSCtKYY4sRe9itRk3PJpquJOjeIkz885CczcI4IvJJDLPS72oowuSh+pBxUFROpX+TU++hxhZQ==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.1.4", "has-symbols": "^1.0.3", "object-keys": "^1.1.1" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", "dev": true, "dependencies": { "wrappy": "1" } }, "node_modules/open": { "version": "7.4.2", "resolved": "https://registry.npmjs.org/open/-/open-7.4.2.tgz", "integrity": "sha512-MVHddDVweXZF3awtlAS+6pgKLlm/JgxZ90+/NBurBoQctVOOB/zDdVjcyPzQ+0laDGbsWgrRkflI65sQeOgT9Q==", "dev": true, "dependencies": { "is-docker": "^2.0.0", "is-wsl": "^2.1.1" }, "engines": { "node": ">=8" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/os-tmpdir": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", "dev": true, "engines": { "node": ">=0.10.0" } }, "node_modules/p-defer": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/p-defer/-/p-defer-1.0.0.tgz", "integrity": "sha512-wB3wfAxZpk2AzOfUMJNL+d36xothRSyj8EXOa4f6GMqYDN9BJaaSISbsk+wS9abmnebVw95C2Kb5t85UmpCxuw==", "dev": true, "engines": { "node": ">=4" } }, "node_modules/p-event": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/p-event/-/p-event-5.0.1.tgz", "integrity": "sha512-dd589iCQ7m1L0bmC5NLlVYfy3TbBEsMUfWx9PyAgPeIcFZ/E2yaTZ4Rz4MiBmmJShviiftHVXOqfnfzJ6kyMrQ==", "dev": true, "dependencies": { "p-timeout": "^5.0.2" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/p-limit": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-4.0.0.tgz", "integrity": "sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ==", "dev": true, "dependencies": { "yocto-queue": "^1.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/p-locate": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-6.0.0.tgz", "integrity": "sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw==", "dev": true, "dependencies": { "p-limit": "^4.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/p-map": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/p-map/-/p-map-5.5.0.tgz", "integrity": "sha512-VFqfGDHlx87K66yZrNdI4YGtD70IRyd+zSvgks6mzHPRNkoKy+9EKP4SFC77/vTTQYmRmti7dvqC+m5jBrBAcg==", "dev": true, "dependencies": { "aggregate-error": "^4.0.0" }, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/p-timeout": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-5.1.0.tgz", "integrity": "sha512-auFDyzzzGZZZdHz3BtET9VEz0SE/uMEAx7uWfGPucfzEwwe/xH0iVeZibQmANYE/hp9T2+UUZT5m+BKyrDp3Ew==", "dev": true, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/parse-json": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", "integrity": "sha512-aOIos8bujGN93/8Ox/jPLh7RwVnPEysynVFE+fQZyg6jKELEHwzgKdLRFHUgXJL6kylijVSBC4BvN9OmsB48Rw==", "dev": true, "dependencies": { "error-ex": "^1.3.1", "json-parse-better-errors": "^1.0.1" }, "engines": { "node": ">=4" } }, "node_modules/parse-ms": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/parse-ms/-/parse-ms-3.0.0.tgz", "integrity": "sha512-Tpb8Z7r7XbbtBTrM9UhpkzzaMrqA2VXMT3YChzYltwV3P3pM6t8wl7TvpMnSTosz1aQAdVib7kdoys7vYOPerw==", "dev": true, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/patch-package": { "version": "6.5.1", "resolved": "https://registry.npmjs.org/patch-package/-/patch-package-6.5.1.tgz", "integrity": "sha512-I/4Zsalfhc6bphmJTlrLoOcAF87jcxko4q0qsv4bGcurbr8IskEOtdnt9iCmsQVGL1B+iUhSQqweyTLJfCF9rA==", "dev": true, "dependencies": { "@yarnpkg/lockfile": "^1.1.0", "chalk": "^4.1.2", "cross-spawn": "^6.0.5", "find-yarn-workspace-root": "^2.0.0", "fs-extra": "^9.0.0", "is-ci": "^2.0.0", "klaw-sync": "^6.0.0", "minimist": "^1.2.6", "open": "^7.4.2", "rimraf": "^2.6.3", "semver": "^5.6.0", "slash": "^2.0.0", "tmp": "^0.0.33", "yaml": "^1.10.2" }, "bin": { "patch-package": "index.js" }, "engines": { "node": ">=10", "npm": ">5" } }, "node_modules/patch-package/node_modules/ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "dependencies": { "color-convert": "^2.0.1" }, "engines": { "node": ">=8" }, "funding": { "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, "node_modules/patch-package/node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" }, "engines": { "node": ">=10" }, "funding": { "url": "https://github.com/chalk/chalk?sponsor=1" } }, "node_modules/patch-package/node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, "dependencies": { "color-name": "~1.1.4" }, "engines": { "node": ">=7.0.0" } }, "node_modules/patch-package/node_modules/color-name": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, "node_modules/patch-package/node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true, "engines": { "node": ">=8" } }, "node_modules/patch-package/node_modules/rimraf": { "version": "2.7.1", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", "dev": true, "dependencies": { "glob": "^7.1.3" }, "bin": { "rimraf": "bin.js" } }, "node_modules/patch-package/node_modules/semver": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", "dev": true, "bin": { "semver": "bin/semver" } }, "node_modules/patch-package/node_modules/slash": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", "dev": true, "engines": { "node": ">=6" } }, "node_modules/patch-package/node_modules/supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, "dependencies": { "has-flag": "^4.0.0" }, "engines": { "node": ">=8" } }, "node_modules/path-exists": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-5.0.0.tgz", "integrity": "sha512-RjhtfwJOxzcFmNOi6ltcbcu4Iu+FL3zEj83dk4kAS+fVpTxXLO1b38RvJgT/0QwvV/L3aY9TAnyv0EOqW4GoMQ==", "dev": true, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" } }, "node_modules/path-is-absolute": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", "dev": true, "engines": { "node": ">=0.10.0" } }, "node_modules/path-key": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", "integrity": "sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw==", "dev": true, "engines": { "node": ">=4" } }, "node_modules/path-parse": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", "dev": true }, "node_modules/path-type": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", "dev": true, "engines": { "node": ">=8" } }, "node_modules/picocolors": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", "dev": true }, "node_modules/picomatch": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", "dev": true, "engines": { "node": ">=8.6" }, "funding": { "url": "https://github.com/sponsors/jonschlinkert" } }, "node_modules/pidtree": { "version": "0.3.1", "resolved": "https://registry.npmjs.org/pidtree/-/pidtree-0.3.1.tgz", "integrity": "sha512-qQbW94hLHEqCg7nhby4yRC7G2+jYHY4Rguc2bjw7Uug4GIJuu1tvf2uHaZv5Q8zdt+WKJ6qK1FOI6amaWUo5FA==", "dev": true, "bin": { "pidtree": "bin/pidtree.js" }, "engines": { "node": ">=0.10" } }, "node_modules/pify": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", "integrity": "sha512-C3FsVNH1udSEX48gGX1xfvwTWfsYWj5U+8/uK15BGzIGrKoUpghX8hWZwa/OFnakBiiVNmBvemTJR5mcy7iPcg==", "dev": true, "engines": { "node": ">=4" } }, "node_modules/pkg-conf": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/pkg-conf/-/pkg-conf-4.0.0.tgz", "integrity": "sha512-7dmgi4UY4qk+4mj5Cd8v/GExPo0K+SlY+hulOSdfZ/T6jVH6//y7NtzZo5WrfhDBxuQ0jCa7fLZmNaNh7EWL/w==", "dev": true, "dependencies": { "find-up": "^6.0.0", "load-json-file": "^7.0.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/plur": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/plur/-/plur-5.1.0.tgz", "integrity": "sha512-VP/72JeXqak2KiOzjgKtQen5y3IZHn+9GOuLDafPv0eXa47xq0At93XahYBs26MsifCQ4enGKwbjBTKgb9QJXg==", "dev": true, "dependencies": { "irregular-plurals": "^3.3.0" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/prettier": { "version": "2.8.3", "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.3.tgz", "integrity": "sha512-tJ/oJ4amDihPoufT5sM0Z1SKEuKay8LfVAMlbbhnnkvt6BUserZylqo2PN+p9KeljLr0OHa2rXHU1T8reeoTrw==", "dev": true, "bin": { "prettier": "bin-prettier.js" }, "engines": { "node": ">=10.13.0" }, "funding": { "url": "https://github.com/prettier/prettier?sponsor=1" } }, "node_modules/prettier-plugin-jsdoc": { "version": "0.4.2", "resolved": "https://registry.npmjs.org/prettier-plugin-jsdoc/-/prettier-plugin-jsdoc-0.4.2.tgz", "integrity": "sha512-w2jnAQm3z0GAG0bhzVJeehzDtrhGMSxJjit5ApCc2oxWfc7+jmLAkbtdOXaSpfwZz3IWkk+PiQPeRrLNpbM+Mw==", "dev": true, "dependencies": { "binary-searching": "^2.0.5", "comment-parser": "^1.3.1", "mdast-util-from-markdown": "^1.2.0" }, "engines": { "node": ">=12.0.0" }, "peerDependencies": { "prettier": ">=2.1.2" } }, "node_modules/pretty-bytes": { "version": "5.6.0", "resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-5.6.0.tgz", "integrity": "sha512-FFw039TmrBqFK8ma/7OL3sDz/VytdtJr044/QUJtH0wK9lb9jLq9tJyIxUwtQJHwar2BqtiA4iCWSwo9JLkzFg==", "dev": true, "engines": { "node": ">=6" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/pretty-ms": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-8.0.0.tgz", "integrity": "sha512-ASJqOugUF1bbzI35STMBUpZqdfYKlJugy6JBziGi2EE+AL5JPJGSzvpeVXojxrr0ViUYoToUjb5kjSEGf7Y83Q==", "dev": true, "dependencies": { "parse-ms": "^3.0.0" }, "engines": { "node": ">=14.16" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/propagate": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/propagate/-/propagate-2.0.1.tgz", "integrity": "sha512-vGrhOavPSTz4QVNuBNdcNXePNdNMaO1xj9yBeH1ScQPjk/rhg9sSlCXPhMkFuaNNW/syTvYqsnbIJxMBfRbbag==", "dev": true, "engines": { "node": ">= 8" } }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", "dev": true, "funding": [ { "type": "github", "url": "https://github.com/sponsors/feross" }, { "type": "patreon", "url": "https://www.patreon.com/feross" }, { "type": "consulting", "url": "https://feross.org/support" } ] }, "node_modules/qunit": { "version": "2.19.4", "resolved": "https://registry.npmjs.org/qunit/-/qunit-2.19.4.tgz", "integrity": "sha512-aqUzzUeCqlleWYKlpgfdHHw9C6KxkB9H3wNfiBg5yHqQMzy0xw/pbCRHYFkjl8MsP/t8qkTQE+JTYL71azgiew==", "dev": true, "dependencies": { "commander": "7.2.0", "node-watch": "0.7.3", "tiny-glob": "0.2.9" }, "bin": { "qunit": "bin/qunit.js" }, "engines": { "node": ">=10" } }, "node_modules/read-pkg": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", "integrity": "sha512-BLq/cCO9two+lBgiTYNqD6GdtK8s4NpaWrl6/rCO9w0TUS8oJl7cmToOZfRYllKTISY6nt1U7jQ53brmKqY6BA==", "dev": true, "dependencies": { "load-json-file": "^4.0.0", "normalize-package-data": "^2.3.2", "path-type": "^3.0.0" }, "engines": { "node": ">=4" } }, "node_modules/read-pkg/node_modules/load-json-file": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", "integrity": "sha512-Kx8hMakjX03tiGTLAIdJ+lL0htKnXjEZN6hk/tozf/WOuYGdZBJrZ+rCJRbVCugsjB3jMLn9746NsQIf5VjBMw==", "dev": true, "dependencies": { "graceful-fs": "^4.1.2", "parse-json": "^4.0.0", "pify": "^3.0.0", "strip-bom": "^3.0.0" }, "engines": { "node": ">=4" } }, "node_modules/read-pkg/node_modules/path-type": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", "dev": true, "dependencies": { "pify": "^3.0.0" }, "engines": { "node": ">=4" } }, "node_modules/readdirp": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", "dev": true, "dependencies": { "picomatch": "^2.2.1" }, "engines": { "node": ">=8.10.0" } }, "node_modules/regexp.prototype.flags": { "version": "1.4.3", "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.4.3.tgz", "integrity": "sha512-fjggEOO3slI6Wvgjwflkc4NFRCTZAu5CnNfBd5qOMYhWdn67nJBBu34/TkD++eeFmd8C9r9jfXJ27+nSiRkSUA==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.1.3", "functions-have-names": "^1.2.2" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", "dev": true, "engines": { "node": ">=0.10.0" } }, "node_modules/resolve": { "version": "1.22.1", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", "dev": true, "dependencies": { "is-core-module": "^2.9.0", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, "bin": { "resolve": "bin/resolve" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/resolve-cwd": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", "dev": true, "dependencies": { "resolve-from": "^5.0.0" }, "engines": { "node": ">=8" } }, "node_modules/resolve-from": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", "dev": true, "engines": { "node": ">=8" } }, "node_modules/reusify": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", "dev": true, "engines": { "iojs": ">=1.0.0", "node": ">=0.10.0" } }, "node_modules/rimraf": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", "dev": true, "dependencies": { "glob": "^7.1.3" }, "bin": { "rimraf": "bin.js" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/rollup": { "version": "3.14.0", "resolved": "https://registry.npmjs.org/rollup/-/rollup-3.14.0.tgz", "integrity": "sha512-o23sdgCLcLSe3zIplT9nQ1+r97okuaiR+vmAPZPTDYB7/f3tgWIYNyiQveMsZwshBT0is4eGax/HH83Q7CG+/Q==", "dev": true, "bin": { "rollup": "dist/bin/rollup" }, "engines": { "node": ">=14.18.0", "npm": ">=8.0.0" }, "optionalDependencies": { "fsevents": "~2.3.2" } }, "node_modules/run-parallel": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", "dev": true, "funding": [ { "type": "github", "url": "https://github.com/sponsors/feross" }, { "type": "patreon", "url": "https://www.patreon.com/feross" }, { "type": "consulting", "url": "https://feross.org/support" } ], "dependencies": { "queue-microtask": "^1.2.2" } }, "node_modules/sade": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==", "dev": true, "dependencies": { "mri": "^1.1.0" }, "engines": { "node": ">=6" } }, "node_modules/safe-regex-test": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.0.0.tgz", "integrity": "sha512-JBUUzyOgEwXQY1NuPtvcj/qcBDbDmEvWufhlnXZIm75DEHp+afM1r1ujJpJsV/gSM4t59tpDyPi1sd6ZaPFfsA==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "get-intrinsic": "^1.1.3", "is-regex": "^1.1.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/semver": { "version": "7.3.8", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz", "integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==", "dev": true, "dependencies": { "lru-cache": "^6.0.0" }, "bin": { "semver": "bin/semver.js" }, "engines": { "node": ">=10" } }, "node_modules/serialize-error": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz", "integrity": "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==", "dev": true, "dependencies": { "type-fest": "^0.13.1" }, "engines": { "node": ">=10" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/shebang-command": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", "integrity": "sha512-EV3L1+UQWGor21OmnvojK36mhg+TyIKDh3iFBKBohr5xeXIhNBcx8oWdgkTEEQ+BEFFYdLRuqMfd5L84N1V5Vg==", "dev": true, "dependencies": { "shebang-regex": "^1.0.0" }, "engines": { "node": ">=0.10.0" } }, "node_modules/shebang-regex": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", "integrity": "sha512-wpoSFAxys6b2a2wHZ1XpDSgD7N9iVjg29Ph9uV/uaP9Ex/KXlkTZTeddxDPSYQpgvzKLGJke2UU0AzoGCjNIvQ==", "dev": true, "engines": { "node": ">=0.10.0" } }, "node_modules/shell-quote": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.0.tgz", "integrity": "sha512-QHsz8GgQIGKlRi24yFc6a6lN69Idnx634w49ay6+jA5yFh7a1UY+4Rp6HPx/L/1zcEDPEij8cIsiqR6bQsE5VQ==", "dev": true, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/shiki": { "version": "0.12.1", "resolved": "https://registry.npmjs.org/shiki/-/shiki-0.12.1.tgz", "integrity": "sha512-aieaV1m349rZINEBkjxh2QbBvFFQOlgqYTNtCal82hHj4dDZ76oMlQIX+C7ryerBTDiga3e5NfH6smjdJ02BbQ==", "dev": true, "dependencies": { "jsonc-parser": "^3.2.0", "vscode-oniguruma": "^1.7.0", "vscode-textmate": "^8.0.0" } }, "node_modules/side-channel": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", "dev": true, "dependencies": { "call-bind": "^1.0.0", "get-intrinsic": "^1.0.2", "object-inspect": "^1.9.0" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/signal-exit": { "version": "3.0.7", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", "dev": true }, "node_modules/slash": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", "dev": true, "engines": { "node": ">=8" } }, "node_modules/slice-ansi": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-5.0.0.tgz", "integrity": "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==", "dev": true, "dependencies": { "ansi-styles": "^6.0.0", "is-fullwidth-code-point": "^4.0.0" }, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/chalk/slice-ansi?sponsor=1" } }, "node_modules/source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true, "engines": { "node": ">=0.10.0" } }, "node_modules/spdx-correct": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.1.tgz", "integrity": "sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w==", "dev": true, "dependencies": { "spdx-expression-parse": "^3.0.0", "spdx-license-ids": "^3.0.0" } }, "node_modules/spdx-exceptions": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz", "integrity": "sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==", "dev": true }, "node_modules/spdx-expression-parse": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", "dev": true, "dependencies": { "spdx-exceptions": "^2.1.0", "spdx-license-ids": "^3.0.0" } }, "node_modules/spdx-license-ids": { "version": "3.0.12", "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.12.tgz", "integrity": "sha512-rr+VVSXtRhO4OHbXUiAF7xW3Bo9DuuF6C5jH+q/x15j2jniycgKbxU09Hr0WqlSLUs4i4ltHGXqTe7VHclYWyA==", "dev": true }, "node_modules/sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", "dev": true }, "node_modules/stack-utils": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", "dev": true, "dependencies": { "escape-string-regexp": "^2.0.0" }, "engines": { "node": ">=10" } }, "node_modules/stack-utils/node_modules/escape-string-regexp": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", "dev": true, "engines": { "node": ">=8" } }, "node_modules/string-width": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", "dev": true, "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" }, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/string.prototype.padend": { "version": "3.1.4", "resolved": "https://registry.npmjs.org/string.prototype.padend/-/string.prototype.padend-3.1.4.tgz", "integrity": "sha512-67otBXoksdjsnXXRUq+KMVTdlVRZ2af422Y0aTyTjVaoQkGr3mxl2Bc5emi7dOQ3OGVVQQskmLEWwFXwommpNw==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.1.4", "es-abstract": "^1.20.4" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/string.prototype.trimend": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.6.tgz", "integrity": "sha512-JySq+4mrPf9EsDBEDYMOb/lM7XQLulwg5R/m1r0PXEFqrV0qHvl58sdTilSXtKOflCsK2E8jxf+GKC0T07RWwQ==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.1.4", "es-abstract": "^1.20.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/string.prototype.trimstart": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.6.tgz", "integrity": "sha512-omqjMDaY92pbn5HOX7f9IccLA+U1tA9GvtU4JrodiXFfYB7jPzzHpRzpglLAjtUV6bB557zwClJezTqnAiYnQA==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.1.4", "es-abstract": "^1.20.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/strip-ansi": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.0.1.tgz", "integrity": "sha512-cXNxvT8dFNRVfhVME3JAe98mkXDYN2O1l7jmcwMnOslDeESg1rF/OZMtK0nRAhiari1unG5cD4jG3rapUAkLbw==", "dev": true, "dependencies": { "ansi-regex": "^6.0.1" }, "engines": { "node": ">=12" }, "funding": { "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, "node_modules/strip-bom": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", "dev": true, "engines": { "node": ">=4" } }, "node_modules/supertap": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/supertap/-/supertap-3.0.1.tgz", "integrity": "sha512-u1ZpIBCawJnO+0QePsEiOknOfCRq0yERxiAchT0i4li0WHNUJbf0evXXSXOcCAR4M8iMDoajXYmstm/qO81Isw==", "dev": true, "dependencies": { "indent-string": "^5.0.0", "js-yaml": "^3.14.1", "serialize-error": "^7.0.1", "strip-ansi": "^7.0.1" }, "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" } }, "node_modules/supports-color": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", "dev": true, "dependencies": { "has-flag": "^3.0.0" }, "engines": { "node": ">=4" } }, "node_modules/supports-preserve-symlinks-flag": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", "dev": true, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/tar": { "version": "6.1.13", "resolved": "https://registry.npmjs.org/tar/-/tar-6.1.13.tgz", "integrity": "sha512-jdIBIN6LTIe2jqzay/2vtYLlBHa3JF42ot3h1dW8Q0PaAG4v8rm0cvpVePtau5C6OKXGGcgO9q2AMNSWxiLqKw==", "dev": true, "dependencies": { "chownr": "^2.0.0", "fs-minipass": "^2.0.0", "minipass": "^4.0.0", "minizlib": "^2.1.1", "mkdirp": "^1.0.3", "yallist": "^4.0.0" }, "engines": { "node": ">=10" } }, "node_modules/temp-dir": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/temp-dir/-/temp-dir-3.0.0.tgz", "integrity": "sha512-nHc6S/bwIilKHNRgK/3jlhDoIHcp45YgyiwcAk46Tr0LfEqGBVpmiAyuiuxeVE44m3mXnEeVhaipLOEWmH+Njw==", "dev": true, "engines": { "node": ">=14.16" } }, "node_modules/time-span": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/time-span/-/time-span-4.0.0.tgz", "integrity": "sha512-MyqZCTGLDZ77u4k+jqg4UlrzPTPZ49NDlaekU6uuFaJLzPIN1woaRXCbGeqOfxwc3Y37ZROGAJ614Rdv7Olt+g==", "dev": true, "dependencies": { "convert-hrtime": "^3.0.0" }, "engines": { "node": ">=10" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/time-zone": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/time-zone/-/time-zone-1.0.0.tgz", "integrity": "sha512-TIsDdtKo6+XrPtiTm1ssmMngN1sAhyKnTO2kunQWqNPWIVvCm15Wmw4SWInwTVgJ5u/Tr04+8Ei9TNcw4x4ONA==", "dev": true, "engines": { "node": ">=4" } }, "node_modules/timekeeper": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/timekeeper/-/timekeeper-2.2.0.tgz", "integrity": "sha512-W3AmPTJWZkRwu+iSNxPIsLZ2ByADsOLbbLxe46UJyWj3mlYLlwucKiq+/dPm0l9wTzqoF3/2PH0AGFCebjq23A==", "dev": true }, "node_modules/tiny-glob": { "version": "0.2.9", "resolved": "https://registry.npmjs.org/tiny-glob/-/tiny-glob-0.2.9.tgz", "integrity": "sha512-g/55ssRPUjShh+xkfx9UPDXqhckHEsHr4Vd9zX55oSdGZc/MD0m3sferOkwWtp98bv+kcVfEHtRJgBVJzelrzg==", "dev": true, "dependencies": { "globalyzer": "0.1.0", "globrex": "^0.1.2" } }, "node_modules/tmp": { "version": "0.0.33", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", "dev": true, "dependencies": { "os-tmpdir": "~1.0.2" }, "engines": { "node": ">=0.6.0" } }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", "dev": true, "dependencies": { "is-number": "^7.0.0" }, "engines": { "node": ">=8.0" } }, "node_modules/type-fest": { "version": "0.13.1", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz", "integrity": "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==", "dev": true, "engines": { "node": ">=10" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/typed-array-length": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.4.tgz", "integrity": "sha512-KjZypGq+I/H7HI5HlOoGHkWUUGq+Q0TPhQurLbyrVrvnKTBgzLhIJ7j6J/XTQOi0d1RjyZ0wdas8bKs2p0x3Ng==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "for-each": "^0.3.3", "is-typed-array": "^1.1.9" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/typedoc": { "version": "0.23.24", "resolved": "https://registry.npmjs.org/typedoc/-/typedoc-0.23.24.tgz", "integrity": "sha512-bfmy8lNQh+WrPYcJbtjQ6JEEsVl/ce1ZIXyXhyW+a1vFrjO39t6J8sL/d6FfAGrJTc7McCXgk9AanYBSNvLdIA==", "dev": true, "dependencies": { "lunr": "^2.3.9", "marked": "^4.2.5", "minimatch": "^5.1.2", "shiki": "^0.12.1" }, "bin": { "typedoc": "bin/typedoc" }, "engines": { "node": ">= 14.14" }, "peerDependencies": { "typescript": "4.6.x || 4.7.x || 4.8.x || 4.9.x" } }, "node_modules/typedoc-plugin-markdown": { "version": "3.14.0", "resolved": "https://registry.npmjs.org/typedoc-plugin-markdown/-/typedoc-plugin-markdown-3.14.0.tgz", "integrity": "sha512-UyQLkLRkfTFhLdhSf3RRpA3nNInGn+k6sll2vRXjflaMNwQAAiB61SYbisNZTg16t4K1dt1bPQMMGLrxS0GZ0Q==", "dev": true, "dependencies": { "handlebars": "^4.7.7" }, "peerDependencies": { "typedoc": ">=0.23.0" } }, "node_modules/typedoc/node_modules/brace-expansion": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", "dev": true, "dependencies": { "balanced-match": "^1.0.0" } }, "node_modules/typedoc/node_modules/minimatch": { "version": "5.1.6", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", "dev": true, "dependencies": { "brace-expansion": "^2.0.1" }, "engines": { "node": ">=10" } }, "node_modules/typescript": { "version": "4.9.5", "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", "dev": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" }, "engines": { "node": ">=4.2.0" } }, "node_modules/uglify-js": { "version": "3.17.4", "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.17.4.tgz", "integrity": "sha512-T9q82TJI9e/C1TAxYvfb16xO120tMVFZrGA3f9/P4424DNu6ypK103y0GPFVa17yotwSyZW5iYXgjYHkGrJW/g==", "dev": true, "optional": true, "bin": { "uglifyjs": "bin/uglifyjs" }, "engines": { "node": ">=0.8.0" } }, "node_modules/unbox-primitive": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.2.tgz", "integrity": "sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "has-bigints": "^1.0.2", "has-symbols": "^1.0.3", "which-boxed-primitive": "^1.0.2" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/unist-util-stringify-position": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-3.0.3.tgz", "integrity": "sha512-k5GzIBZ/QatR8N5X2y+drfpWG8IDBzdnVj6OInRNWm1oXrzydiaAT2OQiA8DPRRZyAKb9b6I2a6PxYklZD0gKg==", "dev": true, "dependencies": { "@types/unist": "^2.0.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/unified" } }, "node_modules/universalify": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz", "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==", "dev": true, "engines": { "node": ">= 10.0.0" } }, "node_modules/uvu": { "version": "0.5.6", "resolved": "https://registry.npmjs.org/uvu/-/uvu-0.5.6.tgz", "integrity": "sha512-+g8ENReyr8YsOc6fv/NVJs2vFdHBnBNdfE49rshrTzDWOlUx4Gq7KOS2GD8eqhy2j+Ejq29+SbKH8yjkAqXqoA==", "dev": true, "dependencies": { "dequal": "^2.0.0", "diff": "^5.0.0", "kleur": "^4.0.3", "sade": "^1.7.3" }, "bin": { "uvu": "bin.js" }, "engines": { "node": ">=8" } }, "node_modules/validate-npm-package-license": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", "dev": true, "dependencies": { "spdx-correct": "^3.0.0", "spdx-expression-parse": "^3.0.0" } }, "node_modules/vscode-oniguruma": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/vscode-oniguruma/-/vscode-oniguruma-1.7.0.tgz", "integrity": "sha512-L9WMGRfrjOhgHSdOYgCt/yRMsXzLDJSL7BPrOZt73gU0iWO4mpqzqQzOz5srxqTvMBaR0XZTSrVWo4j55Rc6cA==", "dev": true }, "node_modules/vscode-textmate": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/vscode-textmate/-/vscode-textmate-8.0.0.tgz", "integrity": "sha512-AFbieoL7a5LMqcnOF04ji+rpXadgOXnZsxQr//r83kLPr7biP7am3g9zbaZIaBGwBRWeSvoMD4mgPdX3e4NWBg==", "dev": true }, "node_modules/well-known-symbols": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/well-known-symbols/-/well-known-symbols-2.0.0.tgz", "integrity": "sha512-ZMjC3ho+KXo0BfJb7JgtQ5IBuvnShdlACNkKkdsqBmYw3bPAaJfPeYUo6tLUaT5tG/Gkh7xkpBhKRQ9e7pyg9Q==", "dev": true, "engines": { "node": ">=6" } }, "node_modules/which": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", "dev": true, "dependencies": { "isexe": "^2.0.0" }, "bin": { "which": "bin/which" } }, "node_modules/which-boxed-primitive": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz", "integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==", "dev": true, "dependencies": { "is-bigint": "^1.0.1", "is-boolean-object": "^1.1.0", "is-number-object": "^1.0.4", "is-string": "^1.0.5", "is-symbol": "^1.0.3" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/which-typed-array": { "version": "1.1.9", "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.9.tgz", "integrity": "sha512-w9c4xkx6mPidwp7180ckYWfMmvxpjlZuIudNtDf4N/tTAUB8VJbX25qZoAsrtGuYNnGw3pa0AXgbGKRB8/EceA==", "dev": true, "dependencies": { "available-typed-arrays": "^1.0.5", "call-bind": "^1.0.2", "for-each": "^0.3.3", "gopd": "^1.0.1", "has-tostringtag": "^1.0.0", "is-typed-array": "^1.1.10" }, "engines": { "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/wordwrap": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", "integrity": "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==", "dev": true }, "node_modules/wrap-ansi": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", "dev": true, "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" }, "engines": { "node": ">=10" }, "funding": { "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, "node_modules/wrap-ansi/node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, "engines": { "node": ">=8" } }, "node_modules/wrap-ansi/node_modules/ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, "dependencies": { "color-convert": "^2.0.1" }, "engines": { "node": ">=8" }, "funding": { "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, "node_modules/wrap-ansi/node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "dev": true, "dependencies": { "color-name": "~1.1.4" }, "engines": { "node": ">=7.0.0" } }, "node_modules/wrap-ansi/node_modules/color-name": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, "node_modules/wrap-ansi/node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "dev": true }, "node_modules/wrap-ansi/node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true, "engines": { "node": ">=8" } }, "node_modules/wrap-ansi/node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" }, "engines": { "node": ">=8" } }, "node_modules/wrap-ansi/node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, "dependencies": { "ansi-regex": "^5.0.1" }, "engines": { "node": ">=8" } }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "dev": true }, "node_modules/write-file-atomic": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-5.0.0.tgz", "integrity": "sha512-R7NYMnHSlV42K54lwY9lvW6MnSm1HSJqZL3xiSgi9E7//FYaI74r2G0rd+/X6VAMkHEdzxQaU5HUOXWUz5kA/w==", "dev": true, "dependencies": { "imurmurhash": "^0.1.4", "signal-exit": "^3.0.7" }, "engines": { "node": "^14.17.0 || ^16.13.0 || >=18.0.0" } }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", "dev": true, "engines": { "node": ">=10" } }, "node_modules/yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", "dev": true }, "node_modules/yaml": { "version": "1.10.2", "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz", "integrity": "sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==", "dev": true, "engines": { "node": ">= 6" } }, "node_modules/yargs": { "version": "17.6.2", "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.6.2.tgz", "integrity": "sha512-1/9UrdHjDZc0eOU0HxOHoS78C69UD3JRMvzlJ7S79S2nTaWRA/whGCTV8o9e/N/1Va9YIV7Q4sOxD8VV4pCWOw==", "dev": true, "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" }, "engines": { "node": ">=12" } }, "node_modules/yargs-parser": { "version": "21.1.1", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", "dev": true, "engines": { "node": ">=12" } }, "node_modules/yargs/node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, "engines": { "node": ">=8" } }, "node_modules/yargs/node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "dev": true }, "node_modules/yargs/node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true, "engines": { "node": ">=8" } }, "node_modules/yargs/node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" }, "engines": { "node": ">=8" } }, "node_modules/yargs/node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, "dependencies": { "ansi-regex": "^5.0.1" }, "engines": { "node": ">=8" } }, "node_modules/yocto-queue": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.0.0.tgz", "integrity": "sha512-9bnSc/HEW2uRy67wc+T8UwauLuPJVn28jb+GtJY16iiKWyvmYJRXVT4UamsAEGQfPohgr2q4Tq0sQbQlxTfi1g==", "dev": true, "engines": { "node": ">=12.20" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } } } } jose-4.11.4/package.json000066400000000000000000000127751437043056600150530ustar00rootroot00000000000000{ "name": "jose", "version": "4.11.4", "description": "'JSON Web Almost Everything' - JWA, JWS, JWE, JWT, JWK, JWKS for Node.js, Browser, Cloudflare Workers, Deno, Bun, and other Web-interoperable runtimes", "keywords": [ "browser", "bun", "cloudflare", "compact", "decode", "decrypt", "deno", "detached", "ec", "ecdsa", "eddsa", "edge", "electron", "embedded", "encrypt", "flattened", "general", "isomorphic", "jose", "json web token", "jsonwebtoken", "jwa", "jwe", "jwk", "jwks", "jws", "jwt", "netlify", "next", "nextjs", "oct", "okp", "payload", "pem", "pkcs8", "rsa", "secp256k1", "sign", "signature", "spki", "universal", "validate", "vercel", "verify", "webcrypto", "workers", "x509" ], "homepage": "https://github.com/panva/jose", "repository": "panva/jose", "funding": { "url": "https://github.com/sponsors/panva" }, "license": "MIT", "author": "Filip Skokan ", "sideEffects": false, "imports": { "#dist": { "import": "./dist/node/esm/index.js", "require": "./dist/node/cjs/index.js" }, "#dist/*": { "import": "./dist/node/esm/*.js", "require": "./dist/node/cjs/*.js" }, "#dist/webapi/*": { "import": "./dist/browser/*.js" }, "#dist/webapi": { "import": "./dist/browser/index.js" } }, "exports": { ".": { "types": "./dist/types/index.d.ts", "bun": "./dist/browser/index.js", "deno": "./dist/browser/index.js", "browser": "./dist/browser/index.js", "worker": "./dist/browser/index.js", "import": "./dist/node/esm/index.js", "require": "./dist/node/cjs/index.js" }, "./package.json": "./package.json" }, "main": "./dist/node/cjs/index.js", "browser": "./dist/browser/index.js", "types": "./dist/types/index.d.ts", "files": [ "dist/**/package.json", "dist/**/*.js", "dist/types/**/*.d.ts", "!dist/**/*.bundle.js", "!dist/**/*.umd.js", "!dist/**/*.min.js", "!dist/node/webcrypto/**/*", "!dist/types/runtime/*", "!dist/types/lib/*", "!dist/deno/**/*" ], "scripts": { "build": "tsc", "build-all": "run-s clear build:*", "build:browser": "run-s runtime-browser 'build -- -p ./tsconfig/browser.json' && echo '{\"type\": \"module\"}'> dist/browser/package.json", "build:browser-bundle": "esbuild --bundle dist/browser/index.js --format=esm --target=es2018 --outfile=dist/browser/index.bundle.js", "build:browser-bundle-min": "esbuild --minify --bundle dist/browser/index.js --format=esm --target=es2018 --outfile=dist/browser/index.bundle.min.js", "build:browser-umd": "rollup dist/browser/index.bundle.js --format umd --name jose -o dist/browser/index.umd.js && rollup dist/browser/index.bundle.min.js --compact --format umd --name jose -o dist/browser/index.umd.min.js", "build:deno": "npm run-script runtime-deno && find dist/deno -name '*.ts' -type f -print0 | xargs -0 sed -i.bak -e \"s/\\.js'/.ts'/g\" -e \"s/\\.d'/.d.ts'/g\" && npm run-script sedcleanup", "build:types": "npm run-script build -- -p ./tsconfig/types.json && cd src && find . -name '*.d.ts' -maxdepth 2 -type f -exec rsync -R \"{}\" ../dist/types \\; && cd .. && run-s -s types:find | xargs -0 sed -i.bak -e \"s/\\.js'/'/g\" -e \"s/\\.d'/'/g\" && npm run-script sedcleanup", "build:node-cjs": "run-s runtime-node 'build -- -p ./tsconfig/node-cjs.json'", "build:node-esm": "run-s runtime-node 'build -- -p ./tsconfig/node-esm.json' && echo '{\"type\": \"module\"}'> dist/node/esm/package.json", "clear": "rm -Rf dist", "sedcleanup": "find . -name '*.bak' -type f -print0 | xargs -0 rm -f", "docs:generate": "typedoc", "runtime-browser": "run-s runtime:clear runtime:browser:* runtime:refs", "runtime-deno": "npm run-script runtime-browser && mkdir -p dist/deno && cp -R src/. dist/deno && rm -R dist/deno/runtime/browser dist/deno/runtime/node", "runtime-node": "run-s runtime:clear runtime:node:* runtime:refs", "runtime:browser:copy": "cp ./src/runtime/browser/*.ts ./src/runtime", "runtime:clear": "run-s -s runtime:find | xargs -0 rm -f", "runtime:find": "find src/runtime -not -name '*.d.ts' -maxdepth 1 -type f -print0", "types:find": "find dist/types -name '*.d.ts' -type f -print0", "runtime:node:copy": "cp ./src/runtime/node/*.ts ./src/runtime", "runtime:refs": "run-s -s runtime:find | xargs -0 sed -i.bak -e \"s/'\\.\\.\\//'\\.\\//g\" -e \"s/'\\.\\/\\.\\./'../g\" && npm run-script sedcleanup", "test": "ava", "format": "prettier --loglevel silent --write ./test ./tap ./src ./tools ./cookbook", "tap:browsers": "./tap/.browsers.sh", "tap:bun": "./tap/.bun.sh", "tap:deno": "./tap/.deno.sh", "tap:edge-runtime": "./tap/.edge-runtime.sh", "tap:electron": "./tap/.electron.sh", "tap:node": "bash -c './tap/.node.sh'", "tap:workers": "./tap/.workers.sh" }, "devDependencies": { "@types/node": "^18.11.9", "@types/qunit": "^2.19.3", "ava": "^5.1.0", "edge-runtime": "^2.0.4", "esbuild": "^0.17.0", "nock": "^13.1.3", "npm-run-all": "^4.1.5", "patch-package": "^6.5.0", "prettier": "^2.8.0", "prettier-plugin-jsdoc": "^0.4.2", "qunit": "^2.19.2", "rollup": "^3.4.0", "tar": "^6.1.12", "timekeeper": "^2.2.0", "typedoc": "^0.23.21", "typedoc-plugin-markdown": "^3.13.6", "typescript": "^4.9.3" }, "deno": "./dist/browser/index.js" } jose-4.11.4/patches/000077500000000000000000000000001437043056600142005ustar00rootroot00000000000000jose-4.11.4/patches/typedoc+0.23.24.patch000066400000000000000000000016011437043056600174700ustar00rootroot00000000000000diff --git a/node_modules/typedoc/dist/lib/converter/plugins/CommentPlugin.js b/node_modules/typedoc/dist/lib/converter/plugins/CommentPlugin.js index 0a17453..de5914f 100644 --- a/node_modules/typedoc/dist/lib/converter/plugins/CommentPlugin.js +++ b/node_modules/typedoc/dist/lib/converter/plugins/CommentPlugin.js @@ -257,7 +257,7 @@ let CommentPlugin = class CommentPlugin extends components_1.ConverterComponent context.logger.warn(`The label "${reflection.label}" for ${reflection.getFriendlyFullName()} cannot be referenced with a declaration reference. ` + `Labels may only contain A-Z, 0-9, and _, and may not start with a number.`); } - mergeSeeTags(reflection.comment); + // mergeSeeTags(reflection.comment); } if (!(reflection instanceof models_1.DeclarationReflection)) { return; jose-4.11.4/patches/typedoc-plugin-markdown+3.14.0.patch000066400000000000000000000117451437043056600225330ustar00rootroot00000000000000diff --git a/node_modules/typedoc-plugin-markdown/dist/resources/helpers/comments.js b/node_modules/typedoc-plugin-markdown/dist/resources/helpers/comments.js index 4af3202..892533a 100644 --- a/node_modules/typedoc-plugin-markdown/dist/resources/helpers/comments.js +++ b/node_modules/typedoc-plugin-markdown/dist/resources/helpers/comments.js @@ -12,7 +12,7 @@ function default_1() { if ((_a = comment.blockTags) === null || _a === void 0 ? void 0 : _a.length) { const tags = comment.blockTags .filter((tag) => tag.tag !== '@returns') - .map((tag) => `**\`${(0, utils_1.camelToTitleCase)(tag.tag.substring(1))}\`**\n\n${Handlebars.helpers.comment(tag.content)}`); + .map((tag) => `**\`${tag.tag.substring(1)}\`** ${Handlebars.helpers.comment(tag.content)}`); md.push(tags.join('\n\n')); } return md.join('\n\n'); diff --git a/node_modules/typedoc-plugin-markdown/dist/resources/helpers/toc.js b/node_modules/typedoc-plugin-markdown/dist/resources/helpers/toc.js index ca0cf27..bd4fc68 100644 --- a/node_modules/typedoc-plugin-markdown/dist/resources/helpers/toc.js +++ b/node_modules/typedoc-plugin-markdown/dist/resources/helpers/toc.js @@ -17,7 +17,15 @@ function default_1(theme) { md.push(`## Table of contents\n\n`); } const headingLevel = hideInPageTOC ? `##` : `###`; - (_b = this.groups) === null || _b === void 0 ? void 0 : _b.forEach((group) => { + function functionsOrConstructorsFirst(ary) { + const idx = ary.findIndex((group) => group.title === 'Functions' || group.title === 'Constructors') + if (idx) { + const [functions] = ary.splice(idx, 1) + ary.unshift(functions) + } + return ary + } + (_b = this.groups) === null || _b === void 0 ? void 0 : functionsOrConstructorsFirst(_b).forEach((group) => { const groupTitle = group.title; if (group.categories) { group.categories.forEach((category) => { diff --git a/node_modules/typedoc-plugin-markdown/dist/resources/partials/member.declaration.hbs b/node_modules/typedoc-plugin-markdown/dist/resources/partials/member.declaration.hbs index 32c9e62..03a30b0 100644 --- a/node_modules/typedoc-plugin-markdown/dist/resources/partials/member.declaration.hbs +++ b/node_modules/typedoc-plugin-markdown/dist/resources/partials/member.declaration.hbs @@ -16,20 +16,6 @@ {{#if type.declaration}} -{{#if type.declaration.indexSignature}} - -{{#with type.declaration.indexSignature}} - -#### Index signature - -{{{indexSignatureTitle}}} - -{{> comment}} - -{{/with}} - -{{/if}} - {{#if type.declaration.signatures}} {{#if type.declaration.children}} diff --git a/node_modules/typedoc-plugin-markdown/dist/resources/partials/member.sources.hbs b/node_modules/typedoc-plugin-markdown/dist/resources/partials/member.sources.hbs index f642b49..89d6772 100644 --- a/node_modules/typedoc-plugin-markdown/dist/resources/partials/member.sources.hbs +++ b/node_modules/typedoc-plugin-markdown/dist/resources/partials/member.sources.hbs @@ -1,39 +1,3 @@ -{{#if implementationOf}} - -#### Implementation of - -{{#with implementationOf}} - -{{typeAndParent}} - -{{/with}} - -{{/if}} - -{{#if inheritedFrom}} - -#### Inherited from - -{{#with inheritedFrom}} - -{{{typeAndParent}}} - -{{/with}} - -{{/if}} - -{{#if overwrites}} - -#### Overrides - -{{#with overwrites}} - -{{typeAndParent}} - -{{/with}} - -{{/if}} - {{#if sources}} #### Defined in diff --git a/node_modules/typedoc-plugin-markdown/dist/resources/partials/title.hbs b/node_modules/typedoc-plugin-markdown/dist/resources/partials/title.hbs index 68b4dba..ece55a4 100644 --- a/node_modules/typedoc-plugin-markdown/dist/resources/partials/title.hbs +++ b/node_modules/typedoc-plugin-markdown/dist/resources/partials/title.hbs @@ -4,4 +4,4 @@ {{/ifShowPageTitle}} -{{{reflectionPath}}} \ No newline at end of file +[💗 Help the project](https://github.com/sponsors/panva) diff --git a/node_modules/typedoc-plugin-markdown/dist/resources/templates/reflection.hbs b/node_modules/typedoc-plugin-markdown/dist/resources/templates/reflection.hbs index 6a29bf7..f9dcbc4 100644 --- a/node_modules/typedoc-plugin-markdown/dist/resources/templates/reflection.hbs +++ b/node_modules/typedoc-plugin-markdown/dist/resources/templates/reflection.hbs @@ -24,18 +24,6 @@ {{/if}} -{{#ifShowTypeHierarchy}} - -## Hierarchy - -{{#with model.typeHierarchy}} - -{{{hierarchy 0}}} - -{{/with}} - -{{/ifShowTypeHierarchy}} - {{#if model.implementedTypes}} ## Implements @@ -74,24 +62,6 @@ {{/if}} -{{#if model.indexSignature}} - -## Indexable - -{{#with model}} - -{{#with indexSignature}} - -{{{indexSignatureTitle}}} - -{{> comment}} - -{{/with}} - -{{/with}} - -{{/if}} - {{#with model}} {{> main}} jose-4.11.4/src/000077500000000000000000000000001437043056600133405ustar00rootroot00000000000000jose-4.11.4/src/index.ts000066400000000000000000000067311437043056600150260ustar00rootroot00000000000000export { compactDecrypt } from './jwe/compact/decrypt.js' export type { CompactDecryptGetKey } from './jwe/compact/decrypt.js' export { flattenedDecrypt } from './jwe/flattened/decrypt.js' export type { FlattenedDecryptGetKey } from './jwe/flattened/decrypt.js' export { generalDecrypt } from './jwe/general/decrypt.js' export type { GeneralDecryptGetKey } from './jwe/general/decrypt.js' export { GeneralEncrypt } from './jwe/general/encrypt.js' export type { Recipient } from './jwe/general/encrypt.js' export { compactVerify } from './jws/compact/verify.js' export type { CompactVerifyGetKey } from './jws/compact/verify.js' export { flattenedVerify } from './jws/flattened/verify.js' export type { FlattenedVerifyGetKey } from './jws/flattened/verify.js' export { generalVerify } from './jws/general/verify.js' export type { GeneralVerifyGetKey } from './jws/general/verify.js' export { jwtVerify } from './jwt/verify.js' export type { JWTVerifyOptions, JWTVerifyGetKey } from './jwt/verify.js' export { jwtDecrypt } from './jwt/decrypt.js' export type { JWTDecryptOptions, JWTDecryptGetKey } from './jwt/decrypt.js' export type { ProduceJWT } from './jwt/produce.js' export { CompactEncrypt } from './jwe/compact/encrypt.js' export { FlattenedEncrypt } from './jwe/flattened/encrypt.js' export { CompactSign } from './jws/compact/sign.js' export { FlattenedSign } from './jws/flattened/sign.js' export { GeneralSign } from './jws/general/sign.js' export type { Signature } from './jws/general/sign.js' export { SignJWT } from './jwt/sign.js' export { EncryptJWT } from './jwt/encrypt.js' export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.js' export { EmbeddedJWK } from './jwk/embedded.js' export { createLocalJWKSet } from './jwks/local.js' export { createRemoteJWKSet } from './jwks/remote.js' export type { RemoteJWKSetOptions } from './jwks/remote.js' export { UnsecuredJWT } from './jwt/unsecured.js' export type { UnsecuredResult } from './jwt/unsecured.js' export { exportPKCS8, exportSPKI, exportJWK } from './key/export.js' export { importSPKI, importPKCS8, importX509, importJWK } from './key/import.js' export type { PEMImportOptions } from './key/import.js' export { decodeProtectedHeader } from './util/decode_protected_header.js' export { decodeJwt } from './util/decode_jwt.js' export type { ProtectedHeaderParameters } from './util/decode_protected_header.js' export * as errors from './util/errors.js' export { generateKeyPair } from './key/generate_key_pair.js' export type { GenerateKeyPairResult, GenerateKeyPairOptions } from './key/generate_key_pair.js' export { generateSecret } from './key/generate_secret.js' export type { GenerateSecretOptions } from './key/generate_secret.js' export * as base64url from './util/base64url.js' export type { KeyLike, JWK, FlattenedJWSInput, GeneralJWSInput, FlattenedJWS, GeneralJWS, JoseHeaderParameters, JWSHeaderParameters, JWEKeyManagementHeaderParameters, FlattenedJWE, GeneralJWE, JWEHeaderParameters, CritOption, DeflateOption, DecryptOptions, EncryptOptions, JWTClaimVerificationOptions, VerifyOptions, SignOptions, JWTPayload, DeflateFunction, InflateFunction, FlattenedDecryptResult, GeneralDecryptResult, CompactDecryptResult, FlattenedVerifyResult, GeneralVerifyResult, CompactVerifyResult, JWTVerifyResult, JWTDecryptResult, ResolvedKey, CompactJWEHeaderParameters, CompactJWSHeaderParameters, JWTHeaderParameters, JSONWebKeySet, } from './types.d' jose-4.11.4/src/jwe/000077500000000000000000000000001437043056600141255ustar00rootroot00000000000000jose-4.11.4/src/jwe/compact/000077500000000000000000000000001437043056600155535ustar00rootroot00000000000000jose-4.11.4/src/jwe/compact/decrypt.ts000066400000000000000000000057421437043056600176050ustar00rootroot00000000000000import { flattenedDecrypt } from '../flattened/decrypt.js' import { JWEInvalid } from '../../util/errors.js' import { decoder } from '../../lib/buffer_utils.js' import type { KeyLike, DecryptOptions, CompactJWEHeaderParameters, GetKeyFunction, FlattenedJWE, CompactDecryptResult, ResolvedKey, } from '../../types.d' /** * Interface for Compact JWE Decryption dynamic key resolution. No token components have been * verified at the time of this function call. */ export interface CompactDecryptGetKey extends GetKeyFunction {} /** * Decrypts a Compact JWE. * * @example Usage * * ```js * const jwe = * 'eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0.nyQ19eq9ogh9wA7fFtnI2oouzy5_8b5DeLkoRMfi2yijgfTs2zEnayCEofz_qhnL-nwszabd9qUeHv0-IwvhhJJS7GUJOU3ikiIe42qcIAFme1A_Fo9CTxw4XTOy-I5qanl8So91u6hwfyN1VxAqVLsSE7_23EC-gfGEg_5znew9PyXXsOIE-K_HH7IQowRrlZ1X_bM_Liu53RzDpLDvRz59mp3S8L56YqpM8FexFGTGpEaoTcEIst375qncYt3-79IVR7gZN1RWsWgjPatfvVbnh74PglQcATSf3UUhaW0OAKn6q7r3PDx6DIKQ35bgHQg5QopuN00eIfLQL2trGw.W3grIVj5HVuAb76X.6PcuDe5D6ttWFYyv0oqqdDXfI2R8wBg1F2Q80UUA_Gv8eEimNWfxIWdLxrjzgQGSvIhxmFKuLM0.a93_Ug3uZHuczj70Zavx8Q' * * const { plaintext, protectedHeader } = await jose.compactDecrypt(jwe, privateKey) * * console.log(protectedHeader) * console.log(new TextDecoder().decode(plaintext)) * ``` * * @param jwe Compact JWE. * @param key Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export async function compactDecrypt( jwe: string | Uint8Array, key: KeyLike | Uint8Array, options?: DecryptOptions, ): Promise /** * @param jwe Compact JWE. * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export async function compactDecrypt( jwe: string | Uint8Array, getKey: CompactDecryptGetKey, options?: DecryptOptions, ): Promise export async function compactDecrypt( jwe: string | Uint8Array, key: KeyLike | Uint8Array | CompactDecryptGetKey, options?: DecryptOptions, ) { if (jwe instanceof Uint8Array) { jwe = decoder.decode(jwe) } if (typeof jwe !== 'string') { throw new JWEInvalid('Compact JWE must be a string or Uint8Array') } const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.') if (length !== 5) { throw new JWEInvalid('Invalid Compact JWE') } const decrypted = await flattenedDecrypt( { ciphertext, iv: (iv || undefined), protected: protectedHeader || undefined, tag: (tag || undefined), encrypted_key: encryptedKey || undefined, }, [1]>key, options, ) const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader! } if (typeof key === 'function') { return { ...result, key: decrypted.key } } return result } jose-4.11.4/src/jwe/compact/encrypt.ts000066400000000000000000000055271437043056600176200ustar00rootroot00000000000000import { FlattenedEncrypt } from '../flattened/encrypt.js' import type { KeyLike, JWEKeyManagementHeaderParameters, CompactJWEHeaderParameters, EncryptOptions, } from '../../types.d' /** * The CompactEncrypt class is a utility for creating Compact JWE strings. * * @example Usage * * ```js * const jwe = await new jose.CompactEncrypt( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM' }) * .encrypt(publicKey) * * console.log(jwe) * ``` */ export class CompactEncrypt { private _flattened: FlattenedEncrypt /** @param plaintext Binary representation of the plaintext to encrypt. */ constructor(plaintext: Uint8Array) { this._flattened = new FlattenedEncrypt(plaintext) } /** * Sets a content encryption key to use, by default a random suitable one is generated for the JWE * enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param cek JWE Content Encryption Key. */ setContentEncryptionKey(cek: Uint8Array) { this._flattened.setContentEncryptionKey(cek) return this } /** * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param iv JWE Initialization Vector. */ setInitializationVector(iv: Uint8Array) { this._flattened.setInitializationVector(iv) return this } /** * Sets the JWE Protected Header on the CompactEncrypt object. * * @param protectedHeader JWE Protected Header object. */ setProtectedHeader(protectedHeader: CompactJWEHeaderParameters) { this._flattened.setProtectedHeader(protectedHeader) return this } /** * Sets the JWE Key Management parameters to be used when encrypting the Content Encryption Key. * You do not need to invoke this method, it is only really intended for test and vector * validation purposes. * * @param parameters JWE Key Management parameters. */ setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters) { this._flattened.setKeyManagementParameters(parameters) return this } /** * Encrypts and resolves the value of the Compact JWE string. * * @param key Public Key or Secret to encrypt the JWE with. * @param options JWE Encryption options. */ async encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions): Promise { const jwe = await this._flattened.encrypt(key, options) return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.') } } jose-4.11.4/src/jwe/flattened/000077500000000000000000000000001437043056600160735ustar00rootroot00000000000000jose-4.11.4/src/jwe/flattened/decrypt.ts000066400000000000000000000177061437043056600201300ustar00rootroot00000000000000import { decode as base64url } from '../../runtime/base64url.js' import decrypt from '../../runtime/decrypt.js' import { inflate } from '../../runtime/zlib.js' import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js' import isDisjoint from '../../lib/is_disjoint.js' import isObject from '../../lib/is_object.js' import decryptKeyManagement from '../../lib/decrypt_key_management.js' import type { FlattenedDecryptResult, KeyLike, FlattenedJWE, JWEHeaderParameters, DecryptOptions, GetKeyFunction, ResolvedKey, } from '../../types.d' import { encoder, decoder, concat } from '../../lib/buffer_utils.js' import generateCek from '../../lib/cek.js' import validateCrit from '../../lib/validate_crit.js' import validateAlgorithms from '../../lib/validate_algorithms.js' /** * Interface for Flattened JWE Decryption dynamic key resolution. No token components have been * verified at the time of this function call. */ export interface FlattenedDecryptGetKey extends GetKeyFunction {} /** * Decrypts a Flattened JWE. * * @example Usage * * ```js * const jwe = { * ciphertext: '9EzjFISUyoG-ifC2mSihfP0DPC80yeyrxhTzKt1C_VJBkxeBG0MI4Te61Pk45RAGubUvBpU9jm4', * iv: '8Fy7A_IuoX5VXG9s', * tag: 'W76IYV6arGRuDSaSyWrQNg', * encrypted_key: * 'Z6eD4UK_yFb5ZoKvKkGAdqywEG_m0e4IYo0x8Vf30LAMJcsc-_zSgIeiF82teZyYi2YYduHKoqImk7MRnoPZOlEs0Q5BNK1OgBmSOhCE8DFyqh9Zh48TCTP6lmBQ52naqoUJFMtHzu-0LwZH26hxos0GP3Dt19O379MJB837TdKKa87skq0zHaVLAquRHOBF77GI54Bc7O49d8aOrSu1VEFGMThlW2caspPRiTSePDMDPq7_WGk50izRhB3Asl9wmP9wEeaTrkJKRnQj5ips1SAZ1hDBsqEQKKukxP1HtdcopHV5_qgwU8Hjm5EwSLMluMQuiE6hwlkXGOujZLVizA', * aad: 'VGhlIEZlbGxvd3NoaXAgb2YgdGhlIFJpbmc', * protected: 'eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0', * } * * const { plaintext, protectedHeader, additionalAuthenticatedData } = * await jose.flattenedDecrypt(jwe, privateKey) * * console.log(protectedHeader) * const decoder = new TextDecoder() * console.log(decoder.decode(plaintext)) * console.log(decoder.decode(additionalAuthenticatedData)) * ``` * * @param jwe Flattened JWE. * @param key Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export function flattenedDecrypt( jwe: FlattenedJWE, key: KeyLike | Uint8Array, options?: DecryptOptions, ): Promise /** * @param jwe Flattened JWE. * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export function flattenedDecrypt( jwe: FlattenedJWE, getKey: FlattenedDecryptGetKey, options?: DecryptOptions, ): Promise export async function flattenedDecrypt( jwe: FlattenedJWE, key: KeyLike | Uint8Array | FlattenedDecryptGetKey, options?: DecryptOptions, ) { if (!isObject(jwe)) { throw new JWEInvalid('Flattened JWE must be an object') } if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) { throw new JWEInvalid('JOSE Header missing') } if (typeof jwe.iv !== 'string') { throw new JWEInvalid('JWE Initialization Vector missing or incorrect type') } if (typeof jwe.ciphertext !== 'string') { throw new JWEInvalid('JWE Ciphertext missing or incorrect type') } if (typeof jwe.tag !== 'string') { throw new JWEInvalid('JWE Authentication Tag missing or incorrect type') } if (jwe.protected !== undefined && typeof jwe.protected !== 'string') { throw new JWEInvalid('JWE Protected Header incorrect type') } if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') { throw new JWEInvalid('JWE Encrypted Key incorrect type') } if (jwe.aad !== undefined && typeof jwe.aad !== 'string') { throw new JWEInvalid('JWE AAD incorrect type') } if (jwe.header !== undefined && !isObject(jwe.header)) { throw new JWEInvalid('JWE Shared Unprotected Header incorrect type') } if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) { throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type') } let parsedProt!: JWEHeaderParameters if (jwe.protected) { try { const protectedHeader = base64url(jwe.protected) parsedProt = JSON.parse(decoder.decode(protectedHeader)) } catch { throw new JWEInvalid('JWE Protected Header is invalid') } } if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) { throw new JWEInvalid( 'JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint', ) } const joseHeader: JWEHeaderParameters = { ...parsedProt, ...jwe.header, ...jwe.unprotected, } validateCrit(JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader) if (joseHeader.zip !== undefined) { if (!parsedProt || !parsedProt.zip) { throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected') } if (joseHeader.zip !== 'DEF') { throw new JOSENotSupported( 'Unsupported JWE "zip" (Compression Algorithm) Header Parameter value', ) } } const { alg, enc } = joseHeader if (typeof alg !== 'string' || !alg) { throw new JWEInvalid('missing JWE Algorithm (alg) in JWE Header') } if (typeof enc !== 'string' || !enc) { throw new JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header') } const keyManagementAlgorithms = options && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms) const contentEncryptionAlgorithms = options && validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms) if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) { throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed') } if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) { throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed') } let encryptedKey!: Uint8Array if (jwe.encrypted_key !== undefined) { encryptedKey = base64url(jwe.encrypted_key!) } let resolvedKey = false if (typeof key === 'function') { key = await key(parsedProt, jwe) resolvedKey = true } let cek: KeyLike | Uint8Array try { cek = await decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) } catch (err) { if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) { throw err } // https://www.rfc-editor.org/rfc/rfc7516#section-11.5 // To mitigate the attacks described in RFC 3218, the // recipient MUST NOT distinguish between format, padding, and length // errors of encrypted keys. It is strongly recommended, in the event // of receiving an improperly formatted key, that the recipient // substitute a randomly generated CEK and proceed to the next step, to // mitigate timing attacks. cek = generateCek(enc) } const iv = base64url(jwe.iv) const tag = base64url(jwe.tag) const protectedHeader: Uint8Array = encoder.encode(jwe.protected ?? '') let additionalData: Uint8Array if (jwe.aad !== undefined) { additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(jwe.aad)) } else { additionalData = protectedHeader } let plaintext = await decrypt(enc, cek, base64url(jwe.ciphertext), iv, tag, additionalData) if (joseHeader.zip === 'DEF') { plaintext = await (options?.inflateRaw || inflate)(plaintext) } const result: FlattenedDecryptResult = { plaintext } if (jwe.protected !== undefined) { result.protectedHeader = parsedProt } if (jwe.aad !== undefined) { result.additionalAuthenticatedData = base64url(jwe.aad!) } if (jwe.unprotected !== undefined) { result.sharedUnprotectedHeader = jwe.unprotected } if (jwe.header !== undefined) { result.unprotectedHeader = jwe.header } if (resolvedKey) { return { ...result, key } } return result } jose-4.11.4/src/jwe/flattened/encrypt.ts000066400000000000000000000224271437043056600201360ustar00rootroot00000000000000import { encode as base64url } from '../../runtime/base64url.js' import encrypt from '../../runtime/encrypt.js' import { deflate } from '../../runtime/zlib.js' import type { KeyLike, FlattenedJWE, JWEHeaderParameters, JWEKeyManagementHeaderParameters, EncryptOptions, } from '../../types.d' import generateIv from '../../lib/iv.js' import encryptKeyManagement from '../../lib/encrypt_key_management.js' import { JOSENotSupported, JWEInvalid } from '../../util/errors.js' import isDisjoint from '../../lib/is_disjoint.js' import { encoder, decoder, concat } from '../../lib/buffer_utils.js' import validateCrit from '../../lib/validate_crit.js' /** @private */ export const unprotected = Symbol() /** * The FlattenedEncrypt class is a utility for creating Flattened JWE objects. * * @example Usage * * ```js * const jwe = await new jose.FlattenedEncrypt( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM' }) * .setAdditionalAuthenticatedData(encoder.encode('The Fellowship of the Ring')) * .encrypt(publicKey) * * console.log(jwe) * ``` */ export class FlattenedEncrypt { private _plaintext: Uint8Array private _protectedHeader!: JWEHeaderParameters private _sharedUnprotectedHeader!: JWEHeaderParameters private _unprotectedHeader!: JWEHeaderParameters private _aad!: Uint8Array private _cek!: Uint8Array private _iv!: Uint8Array private _keyManagementParameters!: JWEKeyManagementHeaderParameters /** @param plaintext Binary representation of the plaintext to encrypt. */ constructor(plaintext: Uint8Array) { if (!(plaintext instanceof Uint8Array)) { throw new TypeError('plaintext must be an instance of Uint8Array') } this._plaintext = plaintext } /** * Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is * really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or * Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed * and missing. * * @param parameters JWE Key Management parameters. */ setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters) { if (this._keyManagementParameters) { throw new TypeError('setKeyManagementParameters can only be called once') } this._keyManagementParameters = parameters return this } /** * Sets the JWE Protected Header on the FlattenedEncrypt object. * * @param protectedHeader JWE Protected Header. */ setProtectedHeader(protectedHeader: JWEHeaderParameters) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once') } this._protectedHeader = protectedHeader return this } /** * Sets the JWE Shared Unprotected Header on the FlattenedEncrypt object. * * @param sharedUnprotectedHeader JWE Shared Unprotected Header. */ setSharedUnprotectedHeader(sharedUnprotectedHeader: JWEHeaderParameters) { if (this._sharedUnprotectedHeader) { throw new TypeError('setSharedUnprotectedHeader can only be called once') } this._sharedUnprotectedHeader = sharedUnprotectedHeader return this } /** * Sets the JWE Per-Recipient Unprotected Header on the FlattenedEncrypt object. * * @param unprotectedHeader JWE Per-Recipient Unprotected Header. */ setUnprotectedHeader(unprotectedHeader: JWEHeaderParameters) { if (this._unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once') } this._unprotectedHeader = unprotectedHeader return this } /** * Sets the Additional Authenticated Data on the FlattenedEncrypt object. * * @param aad Additional Authenticated Data. */ setAdditionalAuthenticatedData(aad: Uint8Array) { this._aad = aad return this } /** * Sets a content encryption key to use, by default a random suitable one is generated for the JWE * enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param cek JWE Content Encryption Key. */ setContentEncryptionKey(cek: Uint8Array) { if (this._cek) { throw new TypeError('setContentEncryptionKey can only be called once') } this._cek = cek return this } /** * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param iv JWE Initialization Vector. */ setInitializationVector(iv: Uint8Array) { if (this._iv) { throw new TypeError('setInitializationVector can only be called once') } this._iv = iv return this } /** * Encrypts and resolves the value of the Flattened JWE object. * * @param key Public Key or Secret to encrypt the JWE with. * @param options JWE Encryption options. */ async encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions) { if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) { throw new JWEInvalid( 'either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()', ) } if ( !isDisjoint(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader) ) { throw new JWEInvalid( 'JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint', ) } const joseHeader: JWEHeaderParameters = { ...this._protectedHeader, ...this._unprotectedHeader, ...this._sharedUnprotectedHeader, } validateCrit(JWEInvalid, new Map(), options?.crit, this._protectedHeader, joseHeader) if (joseHeader.zip !== undefined) { if (!this._protectedHeader || !this._protectedHeader.zip) { throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected') } if (joseHeader.zip !== 'DEF') { throw new JOSENotSupported( 'Unsupported JWE "zip" (Compression Algorithm) Header Parameter value', ) } } const { alg, enc } = joseHeader if (typeof alg !== 'string' || !alg) { throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid') } if (typeof enc !== 'string' || !enc) { throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid') } let encryptedKey: Uint8Array | undefined if (alg === 'dir') { if (this._cek) { throw new TypeError('setContentEncryptionKey cannot be called when using Direct Encryption') } } else if (alg === 'ECDH-ES') { if (this._cek) { throw new TypeError( 'setContentEncryptionKey cannot be called when using Direct Key Agreement', ) } } let cek: KeyLike | Uint8Array { let parameters: { [propName: string]: unknown } | undefined ;({ cek, encryptedKey, parameters } = await encryptKeyManagement( alg, enc, key, this._cek, this._keyManagementParameters, )) if (parameters) { if (options && unprotected in options) { if (!this._unprotectedHeader) { this.setUnprotectedHeader(parameters) } else { this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters } } } else { if (!this._protectedHeader) { this.setProtectedHeader(parameters) } else { this._protectedHeader = { ...this._protectedHeader, ...parameters } } } } } this._iv ||= generateIv(enc) let additionalData: Uint8Array let protectedHeader: Uint8Array let aadMember: string | undefined if (this._protectedHeader) { protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))) } else { protectedHeader = encoder.encode('') } if (this._aad) { aadMember = base64url(this._aad) additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember)) } else { additionalData = protectedHeader } let ciphertext: Uint8Array let tag: Uint8Array if (joseHeader.zip === 'DEF') { const deflated = await (options?.deflateRaw || deflate)(this._plaintext) ;({ ciphertext, tag } = await encrypt(enc, deflated, cek, this._iv, additionalData)) } else { ;({ ciphertext, tag } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData)) } const jwe: FlattenedJWE = { ciphertext: base64url(ciphertext), iv: base64url(this._iv), tag: base64url(tag), } if (encryptedKey) { jwe.encrypted_key = base64url(encryptedKey) } if (aadMember) { jwe.aad = aadMember } if (this._protectedHeader) { jwe.protected = decoder.decode(protectedHeader) } if (this._sharedUnprotectedHeader) { jwe.unprotected = this._sharedUnprotectedHeader } if (this._unprotectedHeader) { jwe.header = this._unprotectedHeader } return jwe } } jose-4.11.4/src/jwe/general/000077500000000000000000000000001437043056600155425ustar00rootroot00000000000000jose-4.11.4/src/jwe/general/decrypt.ts000066400000000000000000000063401437043056600175670ustar00rootroot00000000000000import { flattenedDecrypt } from '../flattened/decrypt.js' import { JWEDecryptionFailed, JWEInvalid } from '../../util/errors.js' import type { KeyLike, DecryptOptions, JWEHeaderParameters, GetKeyFunction, FlattenedJWE, GeneralJWE, GeneralDecryptResult, ResolvedKey, } from '../../types.d' import isObject from '../../lib/is_object.js' /** * Interface for General JWE Decryption dynamic key resolution. No token components have been * verified at the time of this function call. */ export interface GeneralDecryptGetKey extends GetKeyFunction {} /** * Decrypts a General JWE. * * @example Usage * * ```js * const jwe = { * ciphertext: '9EzjFISUyoG-ifC2mSihfP0DPC80yeyrxhTzKt1C_VJBkxeBG0MI4Te61Pk45RAGubUvBpU9jm4', * iv: '8Fy7A_IuoX5VXG9s', * tag: 'W76IYV6arGRuDSaSyWrQNg', * aad: 'VGhlIEZlbGxvd3NoaXAgb2YgdGhlIFJpbmc', * protected: 'eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIn0', * recipients: [ * { * encrypted_key: * 'Z6eD4UK_yFb5ZoKvKkGAdqywEG_m0e4IYo0x8Vf30LAMJcsc-_zSgIeiF82teZyYi2YYduHKoqImk7MRnoPZOlEs0Q5BNK1OgBmSOhCE8DFyqh9Zh48TCTP6lmBQ52naqoUJFMtHzu-0LwZH26hxos0GP3Dt19O379MJB837TdKKa87skq0zHaVLAquRHOBF77GI54Bc7O49d8aOrSu1VEFGMThlW2caspPRiTSePDMDPq7_WGk50izRhB3Asl9wmP9wEeaTrkJKRnQj5ips1SAZ1hDBsqEQKKukxP1HtdcopHV5_qgwU8Hjm5EwSLMluMQuiE6hwlkXGOujZLVizA', * }, * ], * } * * const { plaintext, protectedHeader, additionalAuthenticatedData } = * await jose.generalDecrypt(jwe, privateKey) * * console.log(protectedHeader) * const decoder = new TextDecoder() * console.log(decoder.decode(plaintext)) * console.log(decoder.decode(additionalAuthenticatedData)) * ``` * * @param jwe General JWE. * @param key Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export function generalDecrypt( jwe: GeneralJWE, key: KeyLike | Uint8Array, options?: DecryptOptions, ): Promise /** * @param jwe General JWE. * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. * @param options JWE Decryption options. */ export function generalDecrypt( jwe: GeneralJWE, getKey: GeneralDecryptGetKey, options?: DecryptOptions, ): Promise export async function generalDecrypt( jwe: GeneralJWE, key: KeyLike | Uint8Array | GeneralDecryptGetKey, options?: DecryptOptions, ) { if (!isObject(jwe)) { throw new JWEInvalid('General JWE must be an object') } if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) { throw new JWEInvalid('JWE Recipients missing or incorrect type') } if (!jwe.recipients.length) { throw new JWEInvalid('JWE Recipients has no members') } for (const recipient of jwe.recipients) { try { return await flattenedDecrypt( { aad: jwe.aad, ciphertext: jwe.ciphertext, encrypted_key: recipient.encrypted_key, header: recipient.header, iv: jwe.iv, protected: jwe.protected, tag: jwe.tag, unprotected: jwe.unprotected, }, [1]>key, options, ) } catch { // } } throw new JWEDecryptionFailed() } jose-4.11.4/src/jwe/general/encrypt.ts000066400000000000000000000225251437043056600176040ustar00rootroot00000000000000import { FlattenedEncrypt, unprotected } from '../flattened/encrypt.js' import { JWEInvalid } from '../../util/errors.js' import generateCek from '../../lib/cek.js' import isDisjoint from '../../lib/is_disjoint.js' import encryptKeyManagement from '../../lib/encrypt_key_management.js' import { encode as base64url } from '../../runtime/base64url.js' import validateCrit from '../../lib/validate_crit.js' import type { KeyLike, GeneralJWE, JWEHeaderParameters, CritOption, DeflateOption, } from '../../types.d' export interface Recipient { /** * Sets the JWE Per-Recipient Unprotected Header on the Recipient object. * * @param unprotectedHeader JWE Per-Recipient Unprotected Header. */ setUnprotectedHeader(unprotectedHeader: JWEHeaderParameters): Recipient /** A shorthand for calling addRecipient() on the enclosing GeneralEncrypt instance */ addRecipient(...args: Parameters): Recipient /** A shorthand for calling encrypt() on the enclosing GeneralEncrypt instance */ encrypt(...args: Parameters): Promise /** Returns the enclosing GeneralEncrypt */ done(): GeneralEncrypt } class IndividualRecipient implements Recipient { private parent: GeneralEncrypt unprotectedHeader?: JWEHeaderParameters key: KeyLike | Uint8Array options: CritOption constructor(enc: GeneralEncrypt, key: KeyLike | Uint8Array, options: CritOption) { this.parent = enc this.key = key this.options = options } setUnprotectedHeader(unprotectedHeader: JWEHeaderParameters) { if (this.unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once') } this.unprotectedHeader = unprotectedHeader return this } addRecipient(...args: Parameters) { return this.parent.addRecipient(...args) } encrypt(...args: Parameters) { return this.parent.encrypt(...args) } done() { return this.parent } } /** * The GeneralEncrypt class is a utility for creating General JWE objects. * * @example Usage * * ```js * const jwe = await new jose.GeneralEncrypt( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .setProtectedHeader({ enc: 'A256GCM' }) * .addRecipient(ecPublicKey) * .setUnprotectedHeader({ alg: 'ECDH-ES+A256KW' }) * .addRecipient(rsaPublicKey) * .setUnprotectedHeader({ alg: 'RSA-OAEP-384' }) * .encrypt() * * console.log(jwe) * ``` */ export class GeneralEncrypt { private _plaintext: Uint8Array private _recipients: IndividualRecipient[] = [] private _protectedHeader!: JWEHeaderParameters private _unprotectedHeader!: JWEHeaderParameters private _aad!: Uint8Array /** @param plaintext Binary representation of the plaintext to encrypt. */ constructor(plaintext: Uint8Array) { this._plaintext = plaintext } /** * Adds an additional recipient for the General JWE object. * * @param key Public Key or Secret to encrypt the Content Encryption Key for the recipient with. * @param options JWE Encryption options. */ addRecipient(key: KeyLike | Uint8Array, options?: CritOption): Recipient { const recipient = new IndividualRecipient(this, key, { crit: options?.crit }) this._recipients.push(recipient) return recipient } /** * Sets the JWE Protected Header on the GeneralEncrypt object. * * @param protectedHeader JWE Protected Header object. */ setProtectedHeader(protectedHeader: JWEHeaderParameters): this { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once') } this._protectedHeader = protectedHeader return this } /** * Sets the JWE Shared Unprotected Header on the GeneralEncrypt object. * * @param sharedUnprotectedHeader JWE Shared Unprotected Header object. */ setSharedUnprotectedHeader(sharedUnprotectedHeader: JWEHeaderParameters): this { if (this._unprotectedHeader) { throw new TypeError('setSharedUnprotectedHeader can only be called once') } this._unprotectedHeader = sharedUnprotectedHeader return this } /** * Sets the Additional Authenticated Data on the GeneralEncrypt object. * * @param aad Additional Authenticated Data. */ setAdditionalAuthenticatedData(aad: Uint8Array) { this._aad = aad return this } /** * Encrypts and resolves the value of the General JWE object. * * @param options JWE Encryption options. */ async encrypt(options?: DeflateOption): Promise { if (!this._recipients.length) { throw new JWEInvalid('at least one recipient must be added') } options = { deflateRaw: options?.deflateRaw } if (this._recipients.length === 1) { const [recipient] = this._recipients const flattened = await new FlattenedEncrypt(this._plaintext) .setAdditionalAuthenticatedData(this._aad) .setProtectedHeader(this._protectedHeader) .setSharedUnprotectedHeader(this._unprotectedHeader) .setUnprotectedHeader(recipient.unprotectedHeader!) .encrypt(recipient.key, { ...recipient.options, ...options }) let jwe: GeneralJWE = { ciphertext: flattened.ciphertext, iv: flattened.iv, recipients: [{}], tag: flattened.tag, } if (flattened.aad) jwe.aad = flattened.aad if (flattened.protected) jwe.protected = flattened.protected if (flattened.unprotected) jwe.unprotected = flattened.unprotected if (flattened.encrypted_key) jwe.recipients![0].encrypted_key = flattened.encrypted_key if (flattened.header) jwe.recipients![0].header = flattened.header return jwe } let enc!: string for (let i = 0; i < this._recipients.length; i++) { const recipient = this._recipients[i] if ( !isDisjoint(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader) ) { throw new JWEInvalid( 'JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint', ) } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...recipient.unprotectedHeader, } const { alg } = joseHeader if (typeof alg !== 'string' || !alg) { throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid') } if (alg === 'dir' || alg === 'ECDH-ES') { throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient') } if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) { throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid') } if (!enc) { enc = joseHeader.enc } else if (enc !== joseHeader.enc) { throw new JWEInvalid( 'JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients', ) } validateCrit(JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader) if (joseHeader.zip !== undefined) { if (!this._protectedHeader || !this._protectedHeader.zip) { throw new JWEInvalid( 'JWE "zip" (Compression Algorithm) Header MUST be integrity protected', ) } } } const cek = generateCek(enc) let jwe: GeneralJWE = { ciphertext: '', iv: '', recipients: [], tag: '', } for (let i = 0; i < this._recipients.length; i++) { const recipient = this._recipients[i] const target: Record = {} jwe.recipients!.push(target) const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader, ...recipient.unprotectedHeader, } const p2c = joseHeader.alg!.startsWith('PBES2') ? 2048 + i : undefined if (i === 0) { const flattened = await new FlattenedEncrypt(this._plaintext) .setAdditionalAuthenticatedData(this._aad) .setContentEncryptionKey(cek) .setProtectedHeader(this._protectedHeader) .setSharedUnprotectedHeader(this._unprotectedHeader) .setUnprotectedHeader(recipient.unprotectedHeader!) .setKeyManagementParameters({ p2c }) .encrypt(recipient.key, { ...recipient.options, ...options, // @ts-expect-error [unprotected]: true, }) jwe.ciphertext = flattened.ciphertext jwe.iv = flattened.iv jwe.tag = flattened.tag if (flattened.aad) jwe.aad = flattened.aad if (flattened.protected) jwe.protected = flattened.protected if (flattened.unprotected) jwe.unprotected = flattened.unprotected target.encrypted_key = flattened.encrypted_key! if (flattened.header) target.header = flattened.header continue } const { encryptedKey, parameters } = await encryptKeyManagement( recipient.unprotectedHeader?.alg! || this._protectedHeader?.alg! || this._unprotectedHeader?.alg!, enc, recipient.key, cek, { p2c }, ) target.encrypted_key = base64url(encryptedKey!) if (recipient.unprotectedHeader || parameters) target.header = { ...recipient.unprotectedHeader, ...parameters } } return jwe } } jose-4.11.4/src/jwk/000077500000000000000000000000001437043056600141335ustar00rootroot00000000000000jose-4.11.4/src/jwk/embedded.ts000066400000000000000000000034651437043056600162440ustar00rootroot00000000000000import type { FlattenedJWSInput, JWSHeaderParameters } from '../types.d' import { importJWK } from '../key/import.js' import isObject from '../lib/is_object.js' import { JWSInvalid } from '../util/errors.js' /** * EmbeddedJWK is an implementation of a GetKeyFunction intended to be used with the JWS/JWT verify * operations whenever you need to opt-in to verify signatures with a public key embedded in the * token's "jwk" (JSON Web Key) Header Parameter. It is recommended to combine this with the verify * function's `algorithms` option to define accepted JWS "alg" (Algorithm) Header Parameter values. * * @example Usage * * ```js * const jwt = * 'eyJqd2siOnsiY3J2IjoiUC0yNTYiLCJ4IjoiVU05ZzVuS25aWFlvdldBbE03NmNMejl2VG96UmpfX0NIVV9kT2wtZ09vRSIsInkiOiJkczhhZVF3MWwyY0RDQTdiQ2tPTnZ3REtwWEFidFhqdnFDbGVZSDhXc19VIiwia3R5IjoiRUMifSwiYWxnIjoiRVMyNTYifQ.eyJpc3MiOiJ1cm46ZXhhbXBsZTppc3N1ZXIiLCJhdWQiOiJ1cm46ZXhhbXBsZTphdWRpZW5jZSIsImlhdCI6MTYwNDU4MDc5NH0.60boak3_dErnW47ZPty1C0nrjeVq86EN_eK0GOq6K8w2OA0thKoBxFK4j-NuU9yZ_A9UKGxPT_G87DladBaV9g' * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, jose.EmbeddedJWK, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(protectedHeader) * console.log(payload) * ``` */ export async function EmbeddedJWK(protectedHeader: JWSHeaderParameters, token: FlattenedJWSInput) { const joseHeader = { ...protectedHeader, ...token.header, } if (!isObject(joseHeader.jwk)) { throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object') } const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg!, true) if (key instanceof Uint8Array || key.type !== 'public') { throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key') } return key } jose-4.11.4/src/jwk/thumbprint.ts000066400000000000000000000066571437043056600167150ustar00rootroot00000000000000import digest from '../runtime/digest.js' import { encode as base64url } from '../runtime/base64url.js' import { JOSENotSupported, JWKInvalid } from '../util/errors.js' import { encoder } from '../lib/buffer_utils.js' import type { JWK } from '../types.d' import isObject from '../lib/is_object.js' const check = (value: unknown, description: string) => { if (typeof value !== 'string' || !value) { throw new JWKInvalid(`${description} missing or invalid`) } } /** * Calculates a base64url-encoded JSON Web Key (JWK) Thumbprint * * @example Usage * * ```js * const thumbprint = await jose.calculateJwkThumbprint({ * kty: 'EC', * crv: 'P-256', * x: 'jJ6Flys3zK9jUhnOHf6G49Dyp5hah6CNP84-gY-n9eo', * y: 'nhI6iD5eFXgBTLt_1p3aip-5VbZeMhxeFSpjfEAf7Ww', * }) * * console.log(thumbprint) * // 'w9eYdC6_s_tLQ8lH6PUpc0mddazaqtPgeC2IgWDiqY8' * ``` * * @param jwk JSON Web Key. * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is * "sha256". * @see [RFC7638](https://www.rfc-editor.org/rfc/rfc7638) */ export async function calculateJwkThumbprint( jwk: JWK, digestAlgorithm?: 'sha256' | 'sha384' | 'sha512', ): Promise { if (!isObject(jwk)) { throw new TypeError('JWK must be an object') } digestAlgorithm ??= 'sha256' if ( digestAlgorithm !== 'sha256' && digestAlgorithm !== 'sha384' && digestAlgorithm !== 'sha512' ) { throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"') } let components: JWK switch (jwk.kty) { case 'EC': check(jwk.crv, '"crv" (Curve) Parameter') check(jwk.x, '"x" (X Coordinate) Parameter') check(jwk.y, '"y" (Y Coordinate) Parameter') components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y } break case 'OKP': check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter') check(jwk.x, '"x" (Public Key) Parameter') components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x } break case 'RSA': check(jwk.e, '"e" (Exponent) Parameter') check(jwk.n, '"n" (Modulus) Parameter') components = { e: jwk.e, kty: jwk.kty, n: jwk.n } break case 'oct': check(jwk.k, '"k" (Key Value) Parameter') components = { k: jwk.k, kty: jwk.kty } break default: throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported') } const data = encoder.encode(JSON.stringify(components)) return base64url(await digest(digestAlgorithm, data)) } /** * Calculates a JSON Web Key (JWK) Thumbprint URI * * @example Usage * * ```js * const thumbprintUri = await jose.calculateJwkThumbprintUri({ * kty: 'EC', * crv: 'P-256', * x: 'jJ6Flys3zK9jUhnOHf6G49Dyp5hah6CNP84-gY-n9eo', * y: 'nhI6iD5eFXgBTLt_1p3aip-5VbZeMhxeFSpjfEAf7Ww', * }) * * console.log(thumbprint) * // 'urn:ietf:params:oauth:jwk-thumbprint:sha-256:w9eYdC6_s_tLQ8lH6PUpc0mddazaqtPgeC2IgWDiqY8' * ``` * * @param jwk JSON Web Key. * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is * "sha256". * @see [RFC9278](https://www.rfc-editor.org/rfc/rfc9278) */ export async function calculateJwkThumbprintUri( jwk: JWK, digestAlgorithm?: 'sha256' | 'sha384' | 'sha512', ): Promise { digestAlgorithm ??= 'sha256' const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm) return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}` } jose-4.11.4/src/jwks/000077500000000000000000000000001437043056600143165ustar00rootroot00000000000000jose-4.11.4/src/jwks/local.ts000066400000000000000000000121271437043056600157630ustar00rootroot00000000000000import type { KeyLike, JWSHeaderParameters, JWK, JSONWebKeySet, FlattenedJWSInput, GetKeyFunction, } from '../types.d' import { importJWK } from '../key/import.js' import { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js' import isObject from '../lib/is_object.js' function getKtyFromAlg(alg: unknown) { switch (typeof alg === 'string' && alg.slice(0, 2)) { case 'RS': case 'PS': return 'RSA' case 'ES': return 'EC' case 'Ed': return 'OKP' default: throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set') } } interface Cache { [alg: string]: KeyLike } /** @private */ export function isJWKSLike(jwks: unknown): jwks is JSONWebKeySet { return ( jwks && typeof jwks === 'object' && // @ts-expect-error Array.isArray(jwks.keys) && // @ts-expect-error jwks.keys.every(isJWKLike) ) } function isJWKLike(key: unknown) { return isObject(key) } function clone(obj: T): T { // @ts-ignore if (typeof structuredClone === 'function') { // @ts-ignore return structuredClone(obj) } return JSON.parse(JSON.stringify(obj)) } /** @private */ export class LocalJWKSet { protected _jwks?: JSONWebKeySet private _cached: WeakMap = new WeakMap() constructor(jwks: unknown) { if (!isJWKSLike(jwks)) { throw new JWKSInvalid('JSON Web Key Set malformed') } this._jwks = clone(jwks) } async getKey(protectedHeader: JWSHeaderParameters, token: FlattenedJWSInput): Promise { const { alg, kid } = { ...protectedHeader, ...token.header } const kty = getKtyFromAlg(alg) const candidates = this._jwks!.keys.filter((jwk) => { // filter keys based on the mapping of signature algorithms to Key Type let candidate = kty === jwk.kty // filter keys based on the JWK Key ID in the header if (candidate && typeof kid === 'string') { candidate = kid === jwk.kid } // filter keys based on the key's declared Algorithm if (candidate && typeof jwk.alg === 'string') { candidate = alg === jwk.alg } // filter keys based on the key's declared Public Key Use if (candidate && typeof jwk.use === 'string') { candidate = jwk.use === 'sig' } // filter keys based on the key's declared Key Operations if (candidate && Array.isArray(jwk.key_ops)) { candidate = jwk.key_ops.includes('verify') } // filter out non-applicable OKP Sub Types if (candidate && alg === 'EdDSA') { candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448' } // filter out non-applicable EC curves if (candidate) { switch (alg) { case 'ES256': candidate = jwk.crv === 'P-256' break case 'ES256K': candidate = jwk.crv === 'secp256k1' break case 'ES384': candidate = jwk.crv === 'P-384' break case 'ES512': candidate = jwk.crv === 'P-521' break } } return candidate }) const { 0: jwk, length } = candidates if (length === 0) { throw new JWKSNoMatchingKey() } else if (length !== 1) { throw new JWKSMultipleMatchingKeys() } const cached = this._cached.get(jwk) || this._cached.set(jwk, {}).get(jwk)! if (cached[alg!] === undefined) { const keyObject = await importJWK({ ...jwk, ext: true }, alg) if (keyObject instanceof Uint8Array || keyObject.type !== 'public') { throw new JWKSInvalid('JSON Web Key Set members must be public keys') } cached[alg!] = keyObject } return cached[alg!] } } /** * Returns a function that resolves to a key object from a locally stored, or otherwise available, * JSON Web Key Set. * * Only a single public key must match the selection process. * * @example Usage * * ```js * const JWKS = jose.createLocalJWKSet({ * keys: [ * { * kty: 'RSA', * e: 'AQAB', * n: '12oBZRhCiZFJLcPg59LkZZ9mdhSMTKAQZYq32k_ti5SBB6jerkh-WzOMAO664r_qyLkqHUSp3u5SbXtseZEpN3XPWGKSxjsy-1JyEFTdLSYe6f9gfrmxkUF_7DTpq0gn6rntP05g2-wFW50YO7mosfdslfrTJYWHFhJALabAeYirYD7-9kqq9ebfFMF4sRRELbv9oi36As6Q9B3Qb5_C1rAzqfao_PCsf9EPsTZsVVVkA5qoIAr47lo1ipfiBPxUCCNSdvkmDTYgvvRm6ZoMjFbvOtgyts55fXKdMWv7I9HMD5HwE9uW839PWA514qhbcIsXEYSFMPMV6fnlsiZvQQ', * alg: 'PS256', * }, * { * crv: 'P-256', * kty: 'EC', * x: 'ySK38C1jBdLwDsNWKzzBHqKYEE5Cgv-qjWvorUXk9fw', * y: '_LeQBw07cf5t57Iavn4j-BqJsAD1dpoz8gokd3sBsOo', * alg: 'ES256', * }, * ], * }) * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, JWKS, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * console.log(protectedHeader) * console.log(payload) * ``` * * @param jwks JSON Web Key Set formatted object. */ export function createLocalJWKSet( jwks: JSONWebKeySet, ): GetKeyFunction { return LocalJWKSet.prototype.getKey.bind(new LocalJWKSet(jwks)) } jose-4.11.4/src/jwks/remote.ts000066400000000000000000000123171437043056600161650ustar00rootroot00000000000000import fetchJwks from '../runtime/fetch_jwks.js' import { isCloudflareWorkers } from '../runtime/env.js' import type { KeyLike, JWSHeaderParameters, FlattenedJWSInput, GetKeyFunction } from '../types.d' import { JWKSInvalid, JWKSNoMatchingKey } from '../util/errors.js' import { isJWKSLike, LocalJWKSet } from './local.js' /** Options for the remote JSON Web Key Set. */ export interface RemoteJWKSetOptions { /** * Timeout (in milliseconds) for the HTTP request. When reached the request will be aborted and * the verification will fail. Default is 5000 (5 seconds). */ timeoutDuration?: number /** * Duration (in milliseconds) for which no more HTTP requests will be triggered after a previous * successful fetch. Default is 30000 (30 seconds). */ cooldownDuration?: number /** * Maximum time (in milliseconds) between successful HTTP requests. Default is 600000 (10 * minutes). */ cacheMaxAge?: number | typeof Infinity /** * An instance of [http.Agent](https://nodejs.org/api/http.html#class-httpagent) or * [https.Agent](https://nodejs.org/api/https.html#class-httpsagent) to pass to the * [http.get](https://nodejs.org/api/http.html#httpgetoptions-callback) or * [https.get](https://nodejs.org/api/https.html#httpsgetoptions-callback) method's options. Use * when behind an http(s) proxy. This is a Node.js runtime specific option, it is ignored when * used outside of Node.js runtime. */ agent?: any /** Optional headers to be sent with the HTTP request. */ headers?: Record } class RemoteJWKSet extends LocalJWKSet { private _url: URL private _timeoutDuration: number private _cooldownDuration: number private _cacheMaxAge: number private _jwksTimestamp?: number private _pendingFetch?: Promise private _options: Pick constructor(url: unknown, options?: RemoteJWKSetOptions) { super({ keys: [] }) this._jwks = undefined if (!(url instanceof URL)) { throw new TypeError('url must be an instance of URL') } this._url = new URL(url.href) this._options = { agent: options?.agent, headers: options?.headers } this._timeoutDuration = typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000 this._cooldownDuration = typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000 this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000 } coolingDown() { return typeof this._jwksTimestamp === 'number' ? Date.now() < this._jwksTimestamp + this._cooldownDuration : false } fresh() { return typeof this._jwksTimestamp === 'number' ? Date.now() < this._jwksTimestamp + this._cacheMaxAge : false } async getKey(protectedHeader: JWSHeaderParameters, token: FlattenedJWSInput): Promise { if (!this._jwks || !this.fresh()) { await this.reload() } try { return await super.getKey(protectedHeader, token) } catch (err) { if (err instanceof JWKSNoMatchingKey) { if (this.coolingDown() === false) { await this.reload() return super.getKey(protectedHeader, token) } } throw err } } async reload() { // see https://github.com/panva/jose/issues/355 if (this._pendingFetch && isCloudflareWorkers()) { return new Promise((resolve) => { const isDone = () => { if (this._pendingFetch === undefined) { resolve() } else { setTimeout(isDone, 5) } } isDone() }) } if (!this._pendingFetch) { this._pendingFetch = fetchJwks(this._url, this._timeoutDuration, this._options) .then((json) => { if (!isJWKSLike(json)) { throw new JWKSInvalid('JSON Web Key Set malformed') } this._jwks = { keys: json.keys } this._jwksTimestamp = Date.now() this._pendingFetch = undefined }) .catch((err: Error) => { this._pendingFetch = undefined throw err }) } await this._pendingFetch } } /** * Returns a function that resolves to a key object downloaded from a remote endpoint returning a * JSON Web Key Set, that is, for example, an OAuth 2.0 or OIDC jwks_uri. Only a single public key * must match the selection process. The JSON Web Key Set is fetched when no key matches the * selection process but only as frequently as the `cooldownDuration` option allows, to prevent * abuse. * * @example Usage * * ```js * const JWKS = jose.createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs')) * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, JWKS, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * console.log(protectedHeader) * console.log(payload) * ``` * * @param url URL to fetch the JSON Web Key Set from. * @param options Options for the remote JSON Web Key Set. */ export function createRemoteJWKSet( url: URL, options?: RemoteJWKSetOptions, ): GetKeyFunction { return RemoteJWKSet.prototype.getKey.bind(new RemoteJWKSet(url, options)) } jose-4.11.4/src/jws/000077500000000000000000000000001437043056600141435ustar00rootroot00000000000000jose-4.11.4/src/jws/compact/000077500000000000000000000000001437043056600155715ustar00rootroot00000000000000jose-4.11.4/src/jws/compact/sign.ts000066400000000000000000000027271437043056600171110ustar00rootroot00000000000000import { FlattenedSign } from '../flattened/sign.js' import type { CompactJWSHeaderParameters, KeyLike, SignOptions } from '../../types.d' /** * The CompactSign class is a utility for creating Compact JWS strings. * * @example Usage * * ```js * const jws = await new jose.CompactSign( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .setProtectedHeader({ alg: 'ES256' }) * .sign(privateKey) * * console.log(jws) * ``` */ export class CompactSign { private _flattened: FlattenedSign /** @param payload Binary representation of the payload to sign. */ constructor(payload: Uint8Array) { this._flattened = new FlattenedSign(payload) } /** * Sets the JWS Protected Header on the Sign object. * * @param protectedHeader JWS Protected Header. */ setProtectedHeader(protectedHeader: CompactJWSHeaderParameters) { this._flattened.setProtectedHeader(protectedHeader) return this } /** * Signs and resolves the value of the Compact JWS string. * * @param key Private Key or Secret to sign the JWS with. * @param options JWS Sign options. */ async sign(key: KeyLike | Uint8Array, options?: SignOptions): Promise { const jws = await this._flattened.sign(key, options) if (jws.payload === undefined) { throw new TypeError('use the flattened module for creating JWS with b64: false') } return `${jws.protected}.${jws.payload}.${jws.signature}` } } jose-4.11.4/src/jws/compact/verify.ts000066400000000000000000000051371437043056600174530ustar00rootroot00000000000000import { flattenedVerify } from '../flattened/verify.js' import { JWSInvalid } from '../../util/errors.js' import { decoder } from '../../lib/buffer_utils.js' import type { CompactVerifyResult, FlattenedJWSInput, GetKeyFunction, CompactJWSHeaderParameters, KeyLike, VerifyOptions, ResolvedKey, } from '../../types.d' /** * Interface for Compact JWS Verification dynamic key resolution. No token components have been * verified at the time of this function call. * * See * [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) * to verify using a remote JSON Web Key Set. */ export interface CompactVerifyGetKey extends GetKeyFunction {} /** * Verifies the signature and format of and afterwards decodes the Compact JWS. * * @example Usage * * ```js * const jws = * 'eyJhbGciOiJFUzI1NiJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4.kkAs_gPPxWMI3rHuVlxHaTPfDWDoqdI8jSvuSmqV-8IHIWXg9mcAeC9ggV-45ZHRbiRJ3obUIFo1rHphPA5URg' * * const { payload, protectedHeader } = await jose.compactVerify(jws, publicKey) * * console.log(protectedHeader) * console.log(new TextDecoder().decode(payload)) * ``` * * @param jws Compact JWS. * @param key Key to verify the JWS with. * @param options JWS Verify options. */ export function compactVerify( jws: string | Uint8Array, key: KeyLike | Uint8Array, options?: VerifyOptions, ): Promise /** * @param jws Compact JWS. * @param getKey Function resolving a key to verify the JWS with. * @param options JWS Verify options. */ export function compactVerify( jws: string | Uint8Array, getKey: CompactVerifyGetKey, options?: VerifyOptions, ): Promise export async function compactVerify( jws: string | Uint8Array, key: KeyLike | Uint8Array | CompactVerifyGetKey, options?: VerifyOptions, ) { if (jws instanceof Uint8Array) { jws = decoder.decode(jws) } if (typeof jws !== 'string') { throw new JWSInvalid('Compact JWS must be a string or Uint8Array') } const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.') if (length !== 3) { throw new JWSInvalid('Invalid Compact JWS') } const verified = await flattenedVerify( { payload, protected: protectedHeader, signature }, [1]>key, options, ) const result = { payload: verified.payload, protectedHeader: verified.protectedHeader! } if (typeof key === 'function') { return { ...result, key: verified.key } } return result } jose-4.11.4/src/jws/flattened/000077500000000000000000000000001437043056600161115ustar00rootroot00000000000000jose-4.11.4/src/jws/flattened/sign.ts000066400000000000000000000102301437043056600174150ustar00rootroot00000000000000import { encode as base64url } from '../../runtime/base64url.js' import sign from '../../runtime/sign.js' import isDisjoint from '../../lib/is_disjoint.js' import { JWSInvalid } from '../../util/errors.js' import { encoder, decoder, concat } from '../../lib/buffer_utils.js' import type { KeyLike, FlattenedJWS, JWSHeaderParameters, SignOptions } from '../../types.d' import checkKeyType from '../../lib/check_key_type.js' import validateCrit from '../../lib/validate_crit.js' /** * The FlattenedSign class is a utility for creating Flattened JWS objects. * * @example Usage * * ```js * const jws = await new jose.FlattenedSign( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .setProtectedHeader({ alg: 'ES256' }) * .sign(privateKey) * * console.log(jws) * ``` */ export class FlattenedSign { private _payload: Uint8Array private _protectedHeader!: JWSHeaderParameters private _unprotectedHeader!: JWSHeaderParameters /** @param payload Binary representation of the payload to sign. */ constructor(payload: Uint8Array) { if (!(payload instanceof Uint8Array)) { throw new TypeError('payload must be an instance of Uint8Array') } this._payload = payload } /** * Sets the JWS Protected Header on the FlattenedSign object. * * @param protectedHeader JWS Protected Header. */ setProtectedHeader(protectedHeader: JWSHeaderParameters) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once') } this._protectedHeader = protectedHeader return this } /** * Sets the JWS Unprotected Header on the FlattenedSign object. * * @param unprotectedHeader JWS Unprotected Header. */ setUnprotectedHeader(unprotectedHeader: JWSHeaderParameters) { if (this._unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once') } this._unprotectedHeader = unprotectedHeader return this } /** * Signs and resolves the value of the Flattened JWS object. * * @param key Private Key or Secret to sign the JWS with. * @param options JWS Sign options. */ async sign(key: KeyLike | Uint8Array, options?: SignOptions): Promise { if (!this._protectedHeader && !this._unprotectedHeader) { throw new JWSInvalid( 'either setProtectedHeader or setUnprotectedHeader must be called before #sign()', ) } if (!isDisjoint(this._protectedHeader, this._unprotectedHeader)) { throw new JWSInvalid( 'JWS Protected and JWS Unprotected Header Parameter names must be disjoint', ) } const joseHeader: JWSHeaderParameters = { ...this._protectedHeader, ...this._unprotectedHeader, } const extensions = validateCrit( JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader, ) let b64: boolean = true if (extensions.has('b64')) { b64 = this._protectedHeader.b64! if (typeof b64 !== 'boolean') { throw new JWSInvalid( 'The "b64" (base64url-encode payload) Header Parameter must be a boolean', ) } } const { alg } = joseHeader if (typeof alg !== 'string' || !alg) { throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid') } checkKeyType(alg, key, 'sign') let payload = this._payload if (b64) { payload = encoder.encode(base64url(payload)) } let protectedHeader: Uint8Array if (this._protectedHeader) { protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader))) } else { protectedHeader = encoder.encode('') } const data = concat(protectedHeader, encoder.encode('.'), payload) const signature = await sign(alg, key, data) const jws: FlattenedJWS = { signature: base64url(signature), payload: '', } if (b64) { jws.payload = decoder.decode(payload) } if (this._unprotectedHeader) { jws.header = this._unprotectedHeader } if (this._protectedHeader) { jws.protected = decoder.decode(protectedHeader) } return jws } } jose-4.11.4/src/jws/flattened/verify.ts000066400000000000000000000132521437043056600177700ustar00rootroot00000000000000import { decode as base64url } from '../../runtime/base64url.js' import verify from '../../runtime/verify.js' import { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js' import { concat, encoder, decoder } from '../../lib/buffer_utils.js' import isDisjoint from '../../lib/is_disjoint.js' import isObject from '../../lib/is_object.js' import checkKeyType from '../../lib/check_key_type.js' import validateCrit from '../../lib/validate_crit.js' import validateAlgorithms from '../../lib/validate_algorithms.js' import type { FlattenedVerifyResult, KeyLike, FlattenedJWSInput, JWSHeaderParameters, VerifyOptions, GetKeyFunction, ResolvedKey, } from '../../types.d' /** * Interface for Flattened JWS Verification dynamic key resolution. No token components have been * verified at the time of this function call. * * See * [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) * to verify using a remote JSON Web Key Set. */ export interface FlattenedVerifyGetKey extends GetKeyFunction {} /** * Verifies the signature and format of and afterwards decodes the Flattened JWS. * * @example Usage * * ```js * const decoder = new TextDecoder() * const jws = { * signature: * 'FVVOXwj6kD3DqdfD9yYqfT2W9jv-Nop4kOehp_DeDGNB5dQNSPRvntBY6xH3uxlCxE8na9d_kyhYOcanpDJ0EA', * payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4', * protected: 'eyJhbGciOiJFUzI1NiJ9', * } * * const { payload, protectedHeader } = await jose.flattenedVerify(jws, publicKey) * * console.log(protectedHeader) * console.log(decoder.decode(payload)) * ``` * * @param jws Flattened JWS. * @param key Key to verify the JWS with. * @param options JWS Verify options. */ export function flattenedVerify( jws: FlattenedJWSInput, key: KeyLike | Uint8Array, options?: VerifyOptions, ): Promise /** * @param jws Flattened JWS. * @param getKey Function resolving a key to verify the JWS with. * @param options JWS Verify options. */ export function flattenedVerify( jws: FlattenedJWSInput, getKey: FlattenedVerifyGetKey, options?: VerifyOptions, ): Promise export async function flattenedVerify( jws: FlattenedJWSInput, key: KeyLike | Uint8Array | FlattenedVerifyGetKey, options?: VerifyOptions, ) { if (!isObject(jws)) { throw new JWSInvalid('Flattened JWS must be an object') } if (jws.protected === undefined && jws.header === undefined) { throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members') } if (jws.protected !== undefined && typeof jws.protected !== 'string') { throw new JWSInvalid('JWS Protected Header incorrect type') } if (jws.payload === undefined) { throw new JWSInvalid('JWS Payload missing') } if (typeof jws.signature !== 'string') { throw new JWSInvalid('JWS Signature missing or incorrect type') } if (jws.header !== undefined && !isObject(jws.header)) { throw new JWSInvalid('JWS Unprotected Header incorrect type') } let parsedProt: JWSHeaderParameters = {} if (jws.protected) { try { const protectedHeader = base64url(jws.protected) parsedProt = JSON.parse(decoder.decode(protectedHeader)) } catch { throw new JWSInvalid('JWS Protected Header is invalid') } } if (!isDisjoint(parsedProt, jws.header)) { throw new JWSInvalid( 'JWS Protected and JWS Unprotected Header Parameter names must be disjoint', ) } const joseHeader: JWSHeaderParameters = { ...parsedProt, ...jws.header, } const extensions = validateCrit( JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader, ) let b64: boolean = true if (extensions.has('b64')) { b64 = parsedProt.b64! if (typeof b64 !== 'boolean') { throw new JWSInvalid( 'The "b64" (base64url-encode payload) Header Parameter must be a boolean', ) } } const { alg } = joseHeader if (typeof alg !== 'string' || !alg) { throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid') } const algorithms = options && validateAlgorithms('algorithms', options.algorithms) if (algorithms && !algorithms.has(alg)) { throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed') } if (b64) { if (typeof jws.payload !== 'string') { throw new JWSInvalid('JWS Payload must be a string') } } else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) { throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance') } let resolvedKey = false if (typeof key === 'function') { key = await key(parsedProt, jws) resolvedKey = true } checkKeyType(alg, key, 'verify') const data = concat( encoder.encode(jws.protected ?? ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload, ) const signature = base64url(jws.signature) const verified = await verify(alg, key, signature, data) if (!verified) { throw new JWSSignatureVerificationFailed() } let payload: Uint8Array if (b64) { payload = base64url(jws.payload) } else if (typeof jws.payload === 'string') { payload = encoder.encode(jws.payload) } else { payload = jws.payload } const result: FlattenedVerifyResult = { payload } if (jws.protected !== undefined) { result.protectedHeader = parsedProt } if (jws.header !== undefined) { result.unprotectedHeader = jws.header } if (resolvedKey) { return { ...result, key } } return result } jose-4.11.4/src/jws/general/000077500000000000000000000000001437043056600155605ustar00rootroot00000000000000jose-4.11.4/src/jws/general/sign.ts000066400000000000000000000100621437043056600170670ustar00rootroot00000000000000import { FlattenedSign } from '../flattened/sign.js' import { JWSInvalid } from '../../util/errors.js' import type { KeyLike, GeneralJWS, JWSHeaderParameters, SignOptions } from '../../types.d' export interface Signature { /** * Sets the JWS Protected Header on the Signature object. * * @param protectedHeader JWS Protected Header. */ setProtectedHeader(protectedHeader: JWSHeaderParameters): Signature /** * Sets the JWS Unprotected Header on the Signature object. * * @param unprotectedHeader JWS Unprotected Header. */ setUnprotectedHeader(unprotectedHeader: JWSHeaderParameters): Signature /** A shorthand for calling addSignature() on the enclosing GeneralSign instance */ addSignature(...args: Parameters): Signature /** A shorthand for calling encrypt() on the enclosing GeneralSign instance */ sign(...args: Parameters): Promise /** Returns the enclosing GeneralSign */ done(): GeneralSign } class IndividualSignature implements Signature { private parent: GeneralSign protectedHeader?: JWSHeaderParameters unprotectedHeader?: JWSHeaderParameters options?: SignOptions key: KeyLike | Uint8Array constructor(sig: GeneralSign, key: KeyLike | Uint8Array, options?: SignOptions) { this.parent = sig this.key = key this.options = options } setProtectedHeader(protectedHeader: JWSHeaderParameters) { if (this.protectedHeader) { throw new TypeError('setProtectedHeader can only be called once') } this.protectedHeader = protectedHeader return this } setUnprotectedHeader(unprotectedHeader: JWSHeaderParameters) { if (this.unprotectedHeader) { throw new TypeError('setUnprotectedHeader can only be called once') } this.unprotectedHeader = unprotectedHeader return this } addSignature(...args: Parameters) { return this.parent.addSignature(...args) } sign(...args: Parameters) { return this.parent.sign(...args) } done() { return this.parent } } /** * The GeneralSign class is a utility for creating General JWS objects. * * @example Usage * * ```js * const jws = await new jose.GeneralSign( * new TextEncoder().encode('It’s a dangerous business, Frodo, going out your door.'), * ) * .addSignature(ecPrivateKey) * .setProtectedHeader({ alg: 'ES256' }) * .addSignature(rsaPrivateKey) * .setProtectedHeader({ alg: 'PS256' }) * .sign() * * console.log(jws) * ``` */ export class GeneralSign { private _payload: Uint8Array private _signatures: IndividualSignature[] = [] /** @param payload Binary representation of the payload to sign. */ constructor(payload: Uint8Array) { this._payload = payload } /** * Adds an additional signature for the General JWS object. * * @param key Private Key or Secret to sign the individual JWS signature with. * @param options JWS Sign options. */ addSignature(key: KeyLike | Uint8Array, options?: SignOptions): Signature { const signature = new IndividualSignature(this, key, options) this._signatures.push(signature) return signature } /** Signs and resolves the value of the General JWS object. */ async sign(): Promise { if (!this._signatures.length) { throw new JWSInvalid('at least one signature must be added') } const jws: GeneralJWS = { signatures: [], payload: '', } for (let i = 0; i < this._signatures.length; i++) { const signature = this._signatures[i] const flattened = new FlattenedSign(this._payload) flattened.setProtectedHeader(signature.protectedHeader!) flattened.setUnprotectedHeader(signature.unprotectedHeader!) const { payload, ...rest } = await flattened.sign(signature.key, signature.options) if (i === 0) { jws.payload = payload } else if (jws.payload !== payload) { throw new JWSInvalid('inconsistent use of JWS Unencoded Payload Option (RFC7797)') } jws.signatures.push(rest) } return jws } } jose-4.11.4/src/jws/general/verify.ts000066400000000000000000000053041437043056600174360ustar00rootroot00000000000000import { flattenedVerify } from '../flattened/verify.js' import type { GeneralJWSInput, GeneralVerifyResult, FlattenedJWSInput, GetKeyFunction, JWSHeaderParameters, KeyLike, VerifyOptions, ResolvedKey, } from '../../types.d' import { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js' import isObject from '../../lib/is_object.js' /** * Interface for General JWS Verification dynamic key resolution. No token components have been * verified at the time of this function call. * * See * [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) * to verify using a remote JSON Web Key Set. */ export interface GeneralVerifyGetKey extends GetKeyFunction {} /** * Verifies the signature and format of and afterwards decodes the General JWS. * * @example Usage * * ```js * const jws = { * payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4', * signatures: [ * { * signature: * 'FVVOXwj6kD3DqdfD9yYqfT2W9jv-Nop4kOehp_DeDGNB5dQNSPRvntBY6xH3uxlCxE8na9d_kyhYOcanpDJ0EA', * protected: 'eyJhbGciOiJFUzI1NiJ9', * }, * ], * } * * const { payload, protectedHeader } = await jose.generalVerify(jws, publicKey) * * console.log(protectedHeader) * console.log(new TextDecoder().decode(payload)) * ``` * * @param jws General JWS. * @param key Key to verify the JWS with. * @param options JWS Verify options. */ export function generalVerify( jws: GeneralJWSInput, key: KeyLike | Uint8Array, options?: VerifyOptions, ): Promise /** * @param jws General JWS. * @param getKey Function resolving a key to verify the JWS with. * @param options JWS Verify options. */ export function generalVerify( jws: GeneralJWSInput, getKey: GeneralVerifyGetKey, options?: VerifyOptions, ): Promise export async function generalVerify( jws: GeneralJWSInput, key: KeyLike | Uint8Array | GeneralVerifyGetKey, options?: VerifyOptions, ) { if (!isObject(jws)) { throw new JWSInvalid('General JWS must be an object') } if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) { throw new JWSInvalid('JWS Signatures missing or incorrect type') } for (const signature of jws.signatures) { try { return await flattenedVerify( { header: signature.header, payload: jws.payload, protected: signature.protected, signature: signature.signature, }, [1]>key, options, ) } catch { // } } throw new JWSSignatureVerificationFailed() } jose-4.11.4/src/jwt/000077500000000000000000000000001437043056600141445ustar00rootroot00000000000000jose-4.11.4/src/jwt/decrypt.ts000066400000000000000000000066511437043056600161760ustar00rootroot00000000000000import { compactDecrypt } from '../jwe/compact/decrypt.js' import type { KeyLike, DecryptOptions, JWTClaimVerificationOptions, GetKeyFunction, CompactJWEHeaderParameters, FlattenedJWE, JWTDecryptResult, ResolvedKey, } from '../types.d' import jwtPayload from '../lib/jwt_claims_set.js' import { JWTClaimValidationFailed } from '../util/errors.js' /** Combination of JWE Decryption options and JWT Claims Set verification options. */ export interface JWTDecryptOptions extends DecryptOptions, JWTClaimVerificationOptions {} /** * Interface for JWT Decryption dynamic key resolution. No token components have been verified at * the time of this function call. */ export interface JWTDecryptGetKey extends GetKeyFunction {} /** * Verifies the JWT format (to be a JWE Compact format), decrypts the ciphertext, validates the JWT * Claims Set. * * @example Usage * * ```js * const secret = jose.base64url.decode('zH4NRP1HMALxxCFnRZABFA7GOJtzU_gIj02alfL1lvI') * const jwt = * 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..MB66qstZBPxAXKdsjet_lA.WHbtJTl4taHp7otOHLq3hBvv0yNPsPEKHYInmCPdDDeyV1kU-f-tGEiU4FxlSqkqAT2hVs8_wMNiQFAzPU1PUgIqWCPsBrPP3TtxYsrtwagpn4SvCsUsx0Mhw9ZhliAO8CLmCBQkqr_T9AcYsz5uZw.7nX9m7BGUu_u1p1qFHzyIg' * * const { payload, protectedHeader } = await jose.jwtDecrypt(jwt, secret, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(protectedHeader) * console.log(payload) * ``` * * @param jwt JSON Web Token value (encoded as JWE). * @param key Private Key or Secret to decrypt and verify the JWT with. * @param options JWT Decryption and JWT Claims Set validation options. */ export async function jwtDecrypt( jwt: string | Uint8Array, key: KeyLike | Uint8Array, options?: JWTDecryptOptions, ): Promise /** * @param jwt JSON Web Token value (encoded as JWE). * @param getKey Function resolving Private Key or Secret to decrypt and verify the JWT with. * @param options JWT Decryption and JWT Claims Set validation options. */ export async function jwtDecrypt( jwt: string | Uint8Array, getKey: JWTDecryptGetKey, options?: JWTDecryptOptions, ): Promise export async function jwtDecrypt( jwt: string | Uint8Array, key: KeyLike | Uint8Array | JWTDecryptGetKey, options?: JWTDecryptOptions, ) { const decrypted = await compactDecrypt(jwt, [1]>key, options) const payload = jwtPayload(decrypted.protectedHeader, decrypted.plaintext, options) const { protectedHeader } = decrypted if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) { throw new JWTClaimValidationFailed( 'replicated "iss" claim header parameter mismatch', 'iss', 'mismatch', ) } if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) { throw new JWTClaimValidationFailed( 'replicated "sub" claim header parameter mismatch', 'sub', 'mismatch', ) } if ( protectedHeader.aud !== undefined && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud) ) { throw new JWTClaimValidationFailed( 'replicated "aud" claim header parameter mismatch', 'aud', 'mismatch', ) } const result = { payload, protectedHeader } if (typeof key === 'function') { return { ...result, key: decrypted.key } } return result } jose-4.11.4/src/jwt/encrypt.ts000066400000000000000000000122131437043056600161770ustar00rootroot00000000000000import { CompactEncrypt } from '../jwe/compact/encrypt.js' import type { EncryptOptions, CompactJWEHeaderParameters, JWEKeyManagementHeaderParameters, KeyLike, } from '../types.d' import { encoder } from '../lib/buffer_utils.js' import { ProduceJWT } from './produce.js' /** * The EncryptJWT class is a utility for creating Compact JWE formatted JWT strings. * * @example Usage * * ```js * const secret = jose.base64url.decode('zH4NRP1HMALxxCFnRZABFA7GOJtzU_gIj02alfL1lvI') * const jwt = await new jose.EncryptJWT({ 'urn:example:claim': true }) * .setProtectedHeader({ alg: 'dir', enc: 'A128CBC-HS256' }) * .setIssuedAt() * .setIssuer('urn:example:issuer') * .setAudience('urn:example:audience') * .setExpirationTime('2h') * .encrypt(secret) * * console.log(jwt) * ``` */ export class EncryptJWT extends ProduceJWT { private _cek!: Uint8Array private _iv!: Uint8Array private _keyManagementParameters!: JWEKeyManagementHeaderParameters private _protectedHeader!: CompactJWEHeaderParameters private _replicateIssuerAsHeader!: boolean private _replicateSubjectAsHeader!: boolean private _replicateAudienceAsHeader!: boolean /** * Sets the JWE Protected Header on the EncryptJWT object. * * @param protectedHeader JWE Protected Header. Must contain an "alg" (JWE Algorithm) and "enc" * (JWE Encryption Algorithm) properties. */ setProtectedHeader(protectedHeader: CompactJWEHeaderParameters) { if (this._protectedHeader) { throw new TypeError('setProtectedHeader can only be called once') } this._protectedHeader = protectedHeader return this } /** * Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is * really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or * Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed * and missing. * * @param parameters JWE Key Management parameters. */ setKeyManagementParameters(parameters: JWEKeyManagementHeaderParameters) { if (this._keyManagementParameters) { throw new TypeError('setKeyManagementParameters can only be called once') } this._keyManagementParameters = parameters return this } /** * Sets a content encryption key to use, by default a random suitable one is generated for the JWE * enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param cek JWE Content Encryption Key. */ setContentEncryptionKey(cek: Uint8Array) { if (this._cek) { throw new TypeError('setContentEncryptionKey can only be called once') } this._cek = cek return this } /** * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter. * * @deprecated You should not use this method. It is only really intended for test and vector * validation purposes. * @param iv JWE Initialization Vector. */ setInitializationVector(iv: Uint8Array) { if (this._iv) { throw new TypeError('setInitializationVector can only be called once') } this._iv = iv return this } /** * Replicates the "iss" (Issuer) Claim as a JWE Protected Header Parameter as per * [RFC7519#section-5.3](https://www.rfc-editor.org/rfc/rfc7519#section-5.3). */ replicateIssuerAsHeader() { this._replicateIssuerAsHeader = true return this } /** * Replicates the "sub" (Subject) Claim as a JWE Protected Header Parameter as per * [RFC7519#section-5.3](https://www.rfc-editor.org/rfc/rfc7519#section-5.3). */ replicateSubjectAsHeader() { this._replicateSubjectAsHeader = true return this } /** * Replicates the "aud" (Audience) Claim as a JWE Protected Header Parameter as per * [RFC7519#section-5.3](https://www.rfc-editor.org/rfc/rfc7519#section-5.3). */ replicateAudienceAsHeader() { this._replicateAudienceAsHeader = true return this } /** * Encrypts and returns the JWT. * * @param key Public Key or Secret to encrypt the JWT with. * @param options JWE Encryption options. */ async encrypt(key: KeyLike | Uint8Array, options?: EncryptOptions): Promise { const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload))) if (this._replicateIssuerAsHeader) { this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss } } if (this._replicateSubjectAsHeader) { this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub } } if (this._replicateAudienceAsHeader) { this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud } } enc.setProtectedHeader(this._protectedHeader) if (this._iv) { enc.setInitializationVector(this._iv) } if (this._cek) { enc.setContentEncryptionKey(this._cek) } if (this._keyManagementParameters) { enc.setKeyManagementParameters(this._keyManagementParameters) } return enc.encrypt(key, options) } } jose-4.11.4/src/jwt/produce.ts000066400000000000000000000055201437043056600161570ustar00rootroot00000000000000import type { JWTPayload } from '../types.d' import epoch from '../lib/epoch.js' import isObject from '../lib/is_object.js' import secs from '../lib/secs.js' /** Generic class for JWT producing. */ export class ProduceJWT { protected _payload!: JWTPayload /** @param payload The JWT Claims Set object. */ constructor(payload: JWTPayload) { if (!isObject(payload)) { throw new TypeError('JWT Claims Set MUST be an object') } this._payload = payload } /** * Set "iss" (Issuer) Claim. * * @param issuer "Issuer" Claim value to set on the JWT Claims Set. */ setIssuer(issuer: string) { this._payload = { ...this._payload, iss: issuer } return this } /** * Set "sub" (Subject) Claim. * * @param subject "sub" (Subject) Claim value to set on the JWT Claims Set. */ setSubject(subject: string) { this._payload = { ...this._payload, sub: subject } return this } /** * Set "aud" (Audience) Claim. * * @param audience "aud" (Audience) Claim value to set on the JWT Claims Set. */ setAudience(audience: string | string[]) { this._payload = { ...this._payload, aud: audience } return this } /** * Set "jti" (JWT ID) Claim. * * @param jwtId "jti" (JWT ID) Claim value to set on the JWT Claims Set. */ setJti(jwtId: string) { this._payload = { ...this._payload, jti: jwtId } return this } /** * Set "nbf" (Not Before) Claim. * * @param input "nbf" (Not Before) Claim value to set on the JWT Claims Set. When number is passed * that is used as a value, when string is passed it is resolved to a time span and added to the * current timestamp. */ setNotBefore(input: number | string) { if (typeof input === 'number') { this._payload = { ...this._payload, nbf: input } } else { this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) } } return this } /** * Set "exp" (Expiration Time) Claim. * * @param input "exp" (Expiration Time) Claim value to set on the JWT Claims Set. When number is * passed that is used as a value, when string is passed it is resolved to a time span and added * to the current timestamp. */ setExpirationTime(input: number | string) { if (typeof input === 'number') { this._payload = { ...this._payload, exp: input } } else { this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) } } return this } /** * Set "iat" (Issued At) Claim. * * @param input "iat" (Issued At) Claim value to set on the JWT Claims Set. Default is current * timestamp. */ setIssuedAt(input?: number) { if (typeof input === 'undefined') { this._payload = { ...this._payload, iat: epoch(new Date()) } } else { this._payload = { ...this._payload, iat: input } } return this } } jose-4.11.4/src/jwt/sign.ts000066400000000000000000000141541437043056600154610ustar00rootroot00000000000000import { CompactSign } from '../jws/compact/sign.js' import { JWTInvalid } from '../util/errors.js' import type { JWTHeaderParameters, KeyLike, SignOptions } from '../types.d' import { encoder } from '../lib/buffer_utils.js' import { ProduceJWT } from './produce.js' /** * The SignJWT class is a utility for creating Compact JWS formatted JWT strings. * * @example Usage with a symmetric secret * * ```js * const secret = new TextEncoder().encode( * 'cc7e0d44fd473002f1c42167459001140ec6389b7353f8088f4d9a95f2f596f2', * ) * const alg = 'HS256' * * const jwt = await new jose.SignJWT({ 'urn:example:claim': true }) * .setProtectedHeader({ alg }) * .setIssuedAt() * .setIssuer('urn:example:issuer') * .setAudience('urn:example:audience') * .setExpirationTime('2h') * .sign(secret) * * console.log(jwt) * ``` * * @example Usage with a private PKCS#8 encoded RSA key * * ```js * const alg = 'RS256' * const pkcs8 = `-----BEGIN PRIVATE KEY----- * MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDCFg4UrY5xtulv * /NXKmL1J4qI1SopAfTNMo3X7p+kJO7plqUYjzaztcre1qfh0m33Sm1Q8oPbO/GpP * MU1/HgcceytgJ/b4UwufVVMl9BrMDYG8moDBylbVupFQS3Ly1L9i/iFG9Z9A9xzY * Zzf799A45bnvNXL6s2glzvjiRvfQ2NDF0anTcnZLcYtC7ugq1IMM+ihAcPfw8Qw2 * chN/SmP4qAM+PKaQwagmU7doqmmyN9u38AfoYZ1GCFhEs5TBBT6H6h9YdHeVtiIq * 1c+fl03biSIfLrV7dUBD39gBmXBcL/30Ya3D82mCEUC4zg/UkOfQOmkmV3Lc8YUL * QZ8EJkBLAgMBAAECggEAVuVE/KEP6323WjpbBdAIv7HGahGrgGANvbxZsIhm34ls * VOPK0XDegZkhAybMZHjRhp+gwVxX5ChC+J3cUpOBH5FNxElgW6HizD2Jcq6t6LoL * YgPSrfEHm71iHg8JsgrqfUnGYFzMJmv88C6WdCtpgG/qJV1K00/Ly1G1QKoBffEs * +v4fAMJrCbUdCz1qWto+PU+HLMEo+krfEpGgcmtZeRlDADh8cETMQlgQfQX2VWq/ * aAP4a1SXmo+j0cvRU4W5Fj0RVwNesIpetX2ZFz4p/JmB5sWFEj/fC7h5z2lq+6Bm * e2T3BHtXkIxoBW0/pYVnASC8P2puO5FnVxDmWuHDYQKBgQDTuuBd3+0tSFVEX+DU * 5qpFmHm5nyGItZRJTS+71yg5pBxq1KqNCUjAtbxR0q//fwauakh+BwRVCPOrqsUG * jBSb3NYE70Srp6elqxgkE54PwQx4Mr6exJPnseM9U4K+hULllf5yjM9edreJE1nV * NVgFjeyafQhrHKwgr7PERJ/ikwKBgQDqqsT1M+EJLmI1HtCspOG6cu7q3gf/wKRh * E8tu84i3YyBnI8uJkKy92RNVI5fvpBARe3tjSdM25rr2rcrcmF/5g6Q9ImxZPGCt * 86eOgO9ErNtbc4TEgybsP319UE4O41aKeNiBTAZKoYCxv/dMqG0j4avmWzd+foHq * gSNUvR2maQKBgQCYeqOsV2B6VPY7KIVFLd0AA9/dwvEmgAYLiA/RShDI+hwQ/5jX * uxDu37KAhqeC65sHLrmIMUt4Zdr+DRyZK3aIDNEAesPMjw/X6lCXYp1ZISD2yyym * MFGH8X8CIkstI9Faf9vf6PJKSFrC1/HA7wq17VCwrUzLvrljTMW8meM/CwKBgCpo * 2leGHLFQFKeM/iF1WuYbR1pi7gcmhY6VyTowARFDdOOu8GXYI5/bz0afvCGvAMho * DJCREv7lC/zww6zCTPYG+HOj+PjXlJFba3ixjIxYwPvyEJiDK1Ge18sB7Fl8dHNq * C5ayaqCqN1voWYUdGzxU2IA1E/5kVo5O8FesJeOhAoGBAImJbZFf+D5kA32Xxhac * 59lLWBCsocvvbd1cvDMNlRywAAyhsCb1SuX4nEAK9mrSBdfmoF2Nm3eilfsOds0f * K5mX069IKG82CMqh3Mzptd7e7lyb9lsoGO0BAtjho3cWtha/UZ70vfaMzGuZ6JmQ * ak6k+8+UFd93M4z0Qo74OhXB * -----END PRIVATE KEY----` * const privateKey = await jose.importPKCS8(pkcs8, alg) * * const jwt = await new jose.SignJWT({ 'urn:example:claim': true }) * .setProtectedHeader({ alg }) * .setIssuedAt() * .setIssuer('urn:example:issuer') * .setAudience('urn:example:audience') * .setExpirationTime('2h') * .sign(privateKey) * * console.log(jwt) * ``` * * @example Usage with a private JWK encoded RSA key * * ```js * const alg = 'RS256' * const jwk = { * kty: 'RSA', * n: 'whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw', * e: 'AQAB', * d: 'VuVE_KEP6323WjpbBdAIv7HGahGrgGANvbxZsIhm34lsVOPK0XDegZkhAybMZHjRhp-gwVxX5ChC-J3cUpOBH5FNxElgW6HizD2Jcq6t6LoLYgPSrfEHm71iHg8JsgrqfUnGYFzMJmv88C6WdCtpgG_qJV1K00_Ly1G1QKoBffEs-v4fAMJrCbUdCz1qWto-PU-HLMEo-krfEpGgcmtZeRlDADh8cETMQlgQfQX2VWq_aAP4a1SXmo-j0cvRU4W5Fj0RVwNesIpetX2ZFz4p_JmB5sWFEj_fC7h5z2lq-6Bme2T3BHtXkIxoBW0_pYVnASC8P2puO5FnVxDmWuHDYQ', * p: '07rgXd_tLUhVRF_g1OaqRZh5uZ8hiLWUSU0vu9coOaQcatSqjQlIwLW8UdKv_38GrmpIfgcEVQjzq6rFBowUm9zWBO9Eq6enpasYJBOeD8EMeDK-nsST57HjPVOCvoVC5ZX-cozPXna3iRNZ1TVYBY3smn0IaxysIK-zxESf4pM', * q: '6qrE9TPhCS5iNR7QrKThunLu6t4H_8CkYRPLbvOIt2MgZyPLiZCsvdkTVSOX76QQEXt7Y0nTNua69q3K3Jhf-YOkPSJsWTxgrfOnjoDvRKzbW3OExIMm7D99fVBODuNWinjYgUwGSqGAsb_3TKhtI-Gr5ls3fn6B6oEjVL0dpmk', * dp: 'mHqjrFdgelT2OyiFRS3dAAPf3cLxJoAGC4gP0UoQyPocEP-Y17sQ7t-ygIanguubBy65iDFLeGXa_g0cmSt2iAzRAHrDzI8P1-pQl2KdWSEg9ssspjBRh_F_AiJLLSPRWn_b3-jySkhawtfxwO8Kte1QsK1My765Y0zFvJnjPws', * dq: 'KmjaV4YcsVAUp4z-IXVa5htHWmLuByaFjpXJOjABEUN0467wZdgjn9vPRp-8Ia8AyGgMkJES_uUL_PDDrMJM9gb4c6P4-NeUkVtreLGMjFjA-_IQmIMrUZ7XywHsWXx0c2oLlrJqoKo3W-hZhR0bPFTYgDUT_mRWjk7wV6wl46E', * qi: 'iYltkV_4PmQDfZfGFpzn2UtYEKyhy-9t3Vy8Mw2VHLAADKGwJvVK5ficQAr2atIF1-agXY2bd6KV-w52zR8rmZfTr0gobzYIyqHczOm13t7uXJv2WygY7QEC2OGjdxa2Fr9RnvS99ozMa5nomZBqTqT7z5QV33czjPRCjvg6FcE', * } * const privateKey = await jose.importJWK(jwk, alg) * * const jwt = await new jose.SignJWT({ 'urn:example:claim': true }) * .setProtectedHeader({ alg }) * .setIssuedAt() * .setIssuer('urn:example:issuer') * .setAudience('urn:example:audience') * .setExpirationTime('2h') * .sign(privateKey) * * console.log(jwt) * ``` */ export class SignJWT extends ProduceJWT { private _protectedHeader!: JWTHeaderParameters /** * Sets the JWS Protected Header on the SignJWT object. * * @param protectedHeader JWS Protected Header. Must contain an "alg" (JWS Algorithm) property. */ setProtectedHeader(protectedHeader: JWTHeaderParameters) { this._protectedHeader = protectedHeader return this } /** * Signs and returns the JWT. * * @param key Private Key or Secret to sign the JWT with. * @param options JWT Sign options. */ async sign(key: KeyLike | Uint8Array, options?: SignOptions): Promise { const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload))) sig.setProtectedHeader(this._protectedHeader) if ( Array.isArray(this._protectedHeader?.crit) && this._protectedHeader.crit.includes('b64') && // @ts-expect-error this._protectedHeader.b64 === false ) { throw new JWTInvalid('JWTs MUST NOT use unencoded payload') } return sig.sign(key, options) } } jose-4.11.4/src/jwt/unsecured.ts000066400000000000000000000042461437043056600165170ustar00rootroot00000000000000import * as base64url from '../runtime/base64url.js' import type { JWSHeaderParameters, JWTClaimVerificationOptions, JWTPayload } from '../types.d' import { decoder } from '../lib/buffer_utils.js' import { JWTInvalid } from '../util/errors.js' import jwtPayload from '../lib/jwt_claims_set.js' import { ProduceJWT } from './produce.js' export interface UnsecuredResult { payload: JWTPayload header: JWSHeaderParameters } /** * The UnsecuredJWT class is a utility for dealing with `{ "alg": "none" }` Unsecured JWTs. * * @example Encoding * * ```js * const unsecuredJwt = new jose.UnsecuredJWT({ 'urn:example:claim': true }) * .setIssuedAt() * .setIssuer('urn:example:issuer') * .setAudience('urn:example:audience') * .setExpirationTime('2h') * .encode() * * console.log(unsecuredJwt) * ``` * * @example Decoding * * ```js * const payload = jose.UnsecuredJWT.decode(jwt, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(payload) * ``` */ export class UnsecuredJWT extends ProduceJWT { /** Encodes the Unsecured JWT. */ encode(): string { const header = base64url.encode(JSON.stringify({ alg: 'none' })) const payload = base64url.encode(JSON.stringify(this._payload)) return `${header}.${payload}.` } /** * Decodes an unsecured JWT. * * @param jwt Unsecured JWT to decode the payload of. * @param options JWT Claims Set validation options. */ static decode(jwt: string, options?: JWTClaimVerificationOptions): UnsecuredResult { if (typeof jwt !== 'string') { throw new JWTInvalid('Unsecured JWT must be a string') } const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.') if (length !== 3 || signature !== '') { throw new JWTInvalid('Invalid Unsecured JWT') } let header: JWSHeaderParameters try { header = JSON.parse(decoder.decode(base64url.decode(encodedHeader))) if (header.alg !== 'none') throw new Error() } catch { throw new JWTInvalid('Invalid Unsecured JWT') } const payload = jwtPayload(header, base64url.decode(encodedPayload), options) return { payload, header } } } jose-4.11.4/src/jwt/verify.ts000066400000000000000000000137141437043056600160260ustar00rootroot00000000000000import { compactVerify } from '../jws/compact/verify.js' import type { KeyLike, VerifyOptions, JWTClaimVerificationOptions, JWTHeaderParameters, GetKeyFunction, FlattenedJWSInput, JWTVerifyResult, ResolvedKey, } from '../types.d' import jwtPayload from '../lib/jwt_claims_set.js' import { JWTInvalid } from '../util/errors.js' /** Combination of JWS Verification options and JWT Claims Set verification options. */ export interface JWTVerifyOptions extends VerifyOptions, JWTClaimVerificationOptions {} /** * Interface for JWT Verification dynamic key resolution. No token components have been verified at * the time of this function call. * * See * [createRemoteJWKSet](../functions/jwks_remote.createRemoteJWKSet.md#function-createremotejwkset) * to verify using a remote JSON Web Key Set. */ export interface JWTVerifyGetKey extends GetKeyFunction {} /** * Verifies the JWT format (to be a JWS Compact format), verifies the JWS signature, validates the * JWT Claims Set. * * @example Usage with a symmetric secret * * ```js * const secret = new TextEncoder().encode( * 'cc7e0d44fd473002f1c42167459001140ec6389b7353f8088f4d9a95f2f596f2', * ) * const jwt = * 'eyJhbGciOiJIUzI1NiJ9.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6dHJ1ZSwiaWF0IjoxNjY5MDU2MjMxLCJpc3MiOiJ1cm46ZXhhbXBsZTppc3N1ZXIiLCJhdWQiOiJ1cm46ZXhhbXBsZTphdWRpZW5jZSJ9.C4iSlLfAUMBq--wnC6VqD9gEOhwpRZpoRarE0m7KEnI' * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, secret, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(protectedHeader) * console.log(payload) * ``` * * @example Usage with a public SPKI encoded RSA key * * ```js * const alg = 'RS256' * const spki = `-----BEGIN PUBLIC KEY----- * MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwhYOFK2Ocbbpb/zVypi9 * SeKiNUqKQH0zTKN1+6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4H * HHsrYCf2+FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS/Yv4hRvWfQPcc2Gc3+/fQ * OOW57zVy+rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj * +KgDPjymkMGoJlO3aKppsjfbt/AH6GGdRghYRLOUwQU+h+ofWHR3lbYiKtXPn5dN * 24kiHy61e3VAQ9/YAZlwXC/99GGtw/NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZA * SwIDAQAB * -----END PUBLIC KEY-----` * const publicKey = await jose.importSPKI(spki, alg) * const jwt = * 'eyJhbGciOiJSUzI1NiJ9.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6dHJ1ZSwiaWF0IjoxNjY5MDU2NDg4LCJpc3MiOiJ1cm46ZXhhbXBsZTppc3N1ZXIiLCJhdWQiOiJ1cm46ZXhhbXBsZTphdWRpZW5jZSJ9.gXrPZ3yM_60dMXGE69dusbpzYASNA-XIOwsb5D5xYnSxyj6_D6OR_uR_1vqhUm4AxZxcrH1_-XJAve9HCw8az_QzHcN-nETt-v6stCsYrn6Bv1YOc-mSJRZ8ll57KVqLbCIbjKwerNX5r2_Qg2TwmJzQdRs-AQDhy-s_DlJd8ql6wR4n-kDZpar-pwIvz4fFIN0Fj57SXpAbLrV6Eo4Byzl0xFD8qEYEpBwjrMMfxCZXTlAVhAq6KCoGlDTwWuExps342-0UErEtyIqDnDGcrfNWiUsoo8j-29IpKd-w9-C388u-ChCxoHz--H8WmMSZzx3zTXsZ5lXLZ9IKfanDKg' * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, publicKey, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(protectedHeader) * console.log(payload) * ``` * * @example Usage with a public JWK encoded RSA key * * ```js * const alg = 'RS256' * const jwk = { * kty: 'RSA', * n: 'whYOFK2Ocbbpb_zVypi9SeKiNUqKQH0zTKN1-6fpCTu6ZalGI82s7XK3tan4dJt90ptUPKD2zvxqTzFNfx4HHHsrYCf2-FMLn1VTJfQazA2BvJqAwcpW1bqRUEty8tS_Yv4hRvWfQPcc2Gc3-_fQOOW57zVy-rNoJc744kb30NjQxdGp03J2S3GLQu7oKtSDDPooQHD38PEMNnITf0pj-KgDPjymkMGoJlO3aKppsjfbt_AH6GGdRghYRLOUwQU-h-ofWHR3lbYiKtXPn5dN24kiHy61e3VAQ9_YAZlwXC_99GGtw_NpghFAuM4P1JDn0DppJldy3PGFC0GfBCZASw', * e: 'AQAB', * } * const publicKey = await jose.importJWK(jwk, alg) * const jwt = * 'eyJhbGciOiJSUzI1NiJ9.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6dHJ1ZSwiaWF0IjoxNjY5MDU2NDg4LCJpc3MiOiJ1cm46ZXhhbXBsZTppc3N1ZXIiLCJhdWQiOiJ1cm46ZXhhbXBsZTphdWRpZW5jZSJ9.gXrPZ3yM_60dMXGE69dusbpzYASNA-XIOwsb5D5xYnSxyj6_D6OR_uR_1vqhUm4AxZxcrH1_-XJAve9HCw8az_QzHcN-nETt-v6stCsYrn6Bv1YOc-mSJRZ8ll57KVqLbCIbjKwerNX5r2_Qg2TwmJzQdRs-AQDhy-s_DlJd8ql6wR4n-kDZpar-pwIvz4fFIN0Fj57SXpAbLrV6Eo4Byzl0xFD8qEYEpBwjrMMfxCZXTlAVhAq6KCoGlDTwWuExps342-0UErEtyIqDnDGcrfNWiUsoo8j-29IpKd-w9-C388u-ChCxoHz--H8WmMSZzx3zTXsZ5lXLZ9IKfanDKg' * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, publicKey, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * * console.log(protectedHeader) * console.log(payload) * ``` * * @param jwt JSON Web Token value (encoded as JWS). * @param key Key to verify the JWT with. * @param options JWT Decryption and JWT Claims Set validation options. */ export async function jwtVerify( jwt: string | Uint8Array, key: KeyLike | Uint8Array, options?: JWTVerifyOptions, ): Promise /** * @example Usage with a public JSON Web Key Set hosted on a remote URL * * ```js * const JWKS = jose.createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs')) * * const { payload, protectedHeader } = await jose.jwtVerify(jwt, JWKS, { * issuer: 'urn:example:issuer', * audience: 'urn:example:audience', * }) * console.log(protectedHeader) * console.log(payload) * ``` * * @param jwt JSON Web Token value (encoded as JWS). * @param getKey Function resolving a key to verify the JWT with. * @param options JWT Decryption and JWT Claims Set validation options. */ export async function jwtVerify( jwt: string | Uint8Array, getKey: JWTVerifyGetKey, options?: JWTVerifyOptions, ): Promise export async function jwtVerify( jwt: string | Uint8Array, key: KeyLike | Uint8Array | JWTVerifyGetKey, options?: JWTVerifyOptions, ) { const verified = await compactVerify(jwt, [1]>key, options) if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) { throw new JWTInvalid('JWTs MUST NOT use unencoded payload') } const payload = jwtPayload(verified.protectedHeader, verified.payload, options) const result = { payload, protectedHeader: verified.protectedHeader } if (typeof key === 'function') { return { ...result, key: verified.key } } return result } jose-4.11.4/src/key/000077500000000000000000000000001437043056600141305ustar00rootroot00000000000000jose-4.11.4/src/key/export.ts000066400000000000000000000027631437043056600160310ustar00rootroot00000000000000import { toSPKI as exportPublic } from '../runtime/asn1.js' import { toPKCS8 as exportPrivate } from '../runtime/asn1.js' import keyToJWK from '../runtime/key_to_jwk.js' import type { JWK, KeyLike } from '../types.d' /** * Exports a runtime-specific public key representation (KeyObject or CryptoKey) to a PEM-encoded * SPKI string format. * * @example Usage * * ```js * const spkiPem = await jose.exportSPKI(publicKey) * * console.log(spkiPem) * ``` * * @param key Key representation to transform to a PEM-encoded SPKI string format. */ export async function exportSPKI(key: KeyLike): Promise { return exportPublic(key) } /** * Exports a runtime-specific private key representation (KeyObject or CryptoKey) to a PEM-encoded * PKCS8 string format. * * @example Usage * * ```js * const pkcs8Pem = await jose.exportPKCS8(privateKey) * * console.log(pkcs8Pem) * ``` * * @param key Key representation to transform to a PEM-encoded PKCS8 string format. */ export async function exportPKCS8(key: KeyLike): Promise { return exportPrivate(key) } /** * Exports a runtime-specific key representation (KeyLike) to a JWK. * * @example Usage * * ```js * const privateJwk = await jose.exportJWK(privateKey) * const publicJwk = await jose.exportJWK(publicKey) * * console.log(privateJwk) * console.log(publicJwk) * ``` * * @param key Key representation to export as JWK. */ export async function exportJWK(key: KeyLike | Uint8Array): Promise { return keyToJWK(key) } jose-4.11.4/src/key/generate_key_pair.ts000066400000000000000000000034301437043056600201550ustar00rootroot00000000000000import { generateKeyPair as generate } from '../runtime/generate.js' import type { KeyLike } from '../types.d' export interface GenerateKeyPairResult { /** The generated Private Key. */ privateKey: KeyLike /** Public Key corresponding to the generated Private Key. */ publicKey: KeyLike } export interface GenerateKeyPairOptions { /** * The EC "crv" (Curve) or OKP "crv" (Subtype of Key Pair) value to generate. The curve must be * both supported on the runtime as well as applicable for the given JWA algorithm identifier. */ crv?: string /** * A hint for RSA algorithms to generate an RSA key of a given `modulusLength` (Key size in bits). * JOSE requires 2048 bits or larger. Default is 2048. */ modulusLength?: number /** * (Web Cryptography API specific) The value to use as * [SubtleCrypto.generateKey()](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey) * `extractable` argument. Default is false. */ extractable?: boolean } /** * Generates a private and a public key for a given JWA algorithm identifier. This can only generate * asymmetric key pairs. For symmetric secrets use the `generateSecret` function. * * Note: Under Web Cryptography API runtime the `privateKey` is generated with `extractable` set to * `false` by default. * * @example Usage * * ```js * const { publicKey, privateKey } = await jose.generateKeyPair('PS256') * console.log(publicKey) * console.log(privateKey) * ``` * * @param alg JWA Algorithm Identifier to be used with the generated key pair. * @param options Additional options passed down to the key pair generation. */ export async function generateKeyPair( alg: string, options?: GenerateKeyPairOptions, ): Promise { return generate(alg, options) } jose-4.11.4/src/key/generate_secret.ts000066400000000000000000000020171437043056600176370ustar00rootroot00000000000000import { generateSecret as generate } from '../runtime/generate.js' import type { KeyLike } from '../types.d' export interface GenerateSecretOptions { /** * (Web Cryptography API specific) The value to use as * [SubtleCrypto.generateKey()](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey) * `extractable` argument. Default is false. */ extractable?: boolean } /** * Generates a symmetric secret key for a given JWA algorithm identifier. * * Note: Under Web Cryptography API runtime the secret key is generated with `extractable` set to * `false` by default. * * @example Usage * * ```js * const secret = await jose.generateSecret('HS256') * console.log(secret) * ``` * * @param alg JWA Algorithm Identifier to be used with the generated secret. * @param options Additional options passed down to the secret generation. */ export async function generateSecret( alg: string, options?: GenerateSecretOptions, ): Promise { return generate(alg, options) } jose-4.11.4/src/key/import.ts000066400000000000000000000215131437043056600160140ustar00rootroot00000000000000import { decode as decodeBase64URL, encodeBase64, decodeBase64 } from '../runtime/base64url.js' import { fromSPKI as importPublic } from '../runtime/asn1.js' import { fromPKCS8 as importPrivate } from '../runtime/asn1.js' import asKeyObject from '../runtime/jwk_to_key.js' import { JOSENotSupported } from '../util/errors.js' import formatPEM from '../lib/format_pem.js' import isObject from '../lib/is_object.js' import type { JWK, KeyLike } from '../types.d' function getElement(seq: Uint8Array) { let result = [] let next = 0 while (next < seq.length) { let nextPart = parseElement(seq.subarray(next)) result.push(nextPart) next += nextPart.byteLength } return result } function parseElement(bytes: Uint8Array) { let position = 0 // tag let tag = bytes[0] & 0x1f position++ if (tag === 0x1f) { tag = 0 while (bytes[position] >= 0x80) { tag = tag * 128 + bytes[position] - 0x80 position++ } tag = tag * 128 + bytes[position] - 0x80 position++ } // length let length = 0 if (bytes[position] < 0x80) { length = bytes[position] position++ } else if (length === 0x80) { length = 0 while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) { if (length > bytes.byteLength) { throw new TypeError('invalid indefinite form length') } length++ } const byteLength = position + length + 2 return { byteLength, contents: bytes.subarray(position, position + length), raw: bytes.subarray(0, byteLength), } } else { let numberOfDigits = bytes[position] & 0x7f position++ length = 0 for (let i = 0; i < numberOfDigits; i++) { length = length * 256 + bytes[position] position++ } } const byteLength = position + length return { byteLength, contents: bytes.subarray(position, byteLength), raw: bytes.subarray(0, byteLength), } } function spkiFromX509(buf: Uint8Array) { const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents) return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw) } function getSPKI(x509: string): string { const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, '') const raw = decodeBase64(pem) return formatPEM(spkiFromX509(raw), 'PUBLIC KEY') } export interface PEMImportOptions { /** * (Web Cryptography API specific) The value to use as * [SubtleCrypto.importKey()](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey) * `extractable` argument. Default is false. */ extractable?: boolean } /** * Imports a PEM-encoded SPKI string as a runtime-specific public key representation (KeyObject or * CryptoKey). See [Algorithm Key Requirements](https://github.com/panva/jose/issues/210) to learn * about key to algorithm requirements and mapping. * * @example Usage * * ```js * const algorithm = 'ES256' * const spki = `-----BEGIN PUBLIC KEY----- * MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFlHHWfLk0gLBbsLTcuCrbCqoHqmM * YJepMC+Q+Dd6RBmBiA41evUsNMwLeN+PNFqib+xwi9JkJ8qhZkq8Y/IzGg== * -----END PUBLIC KEY-----` * const ecPublicKey = await jose.importSPKI(spki, algorithm) * ``` * * @param pem PEM-encoded SPKI string * @param alg JSON Web Algorithm identifier to be used with the imported key. */ export async function importSPKI( spki: string, alg: string, options?: PEMImportOptions, ): Promise { if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) { throw new TypeError('"spki" must be SPKI formatted string') } return importPublic(spki, alg, options) } /** * Imports the SPKI from an X.509 string certificate as a runtime-specific public key representation * (KeyObject or CryptoKey). See [Algorithm Key * Requirements](https://github.com/panva/jose/issues/210) to learn about key to algorithm * requirements and mapping. * * @example Usage * * ```js * const algorithm = 'ES256' * const x509 = `-----BEGIN CERTIFICATE----- * MIIBXjCCAQSgAwIBAgIGAXvykuMKMAoGCCqGSM49BAMCMDYxNDAyBgNVBAMMK3Np * QXBNOXpBdk1VaXhXVWVGaGtjZXg1NjJRRzFyQUhXaV96UlFQTVpQaG8wHhcNMjEw * OTE3MDcwNTE3WhcNMjIwNzE0MDcwNTE3WjA2MTQwMgYDVQQDDCtzaUFwTTl6QXZN * VWl4V1VlRmhrY2V4NTYyUUcxckFIV2lfelJRUE1aUGhvMFkwEwYHKoZIzj0CAQYI * KoZIzj0DAQcDQgAE8PbPvCv5D5xBFHEZlBp/q5OEUymq7RIgWIi7tkl9aGSpYE35 * UH+kBKDnphJO3odpPZ5gvgKs2nwRWcrDnUjYLDAKBggqhkjOPQQDAgNIADBFAiEA * 1yyMTRe66MhEXID9+uVub7woMkNYd0LhSHwKSPMUUTkCIFQGsfm1ecXOpeGOufAh * v+A1QWZMuTWqYt+uh/YSRNDn * -----END CERTIFICATE-----` * const ecPublicKey = await jose.importX509(x509, algorithm) * ``` * * @param pem X.509 certificate string * @param alg JSON Web Algorithm identifier to be used with the imported key. */ export async function importX509( x509: string, alg: string, options?: PEMImportOptions, ): Promise { if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) { throw new TypeError('"x509" must be X.509 formatted string') } let spki: string try { spki = getSPKI(x509) } catch (cause) { // @ts-ignore throw new TypeError('failed to parse the X.509 certificate', { cause }) } return importPublic(spki, alg, options) } /** * Imports a PEM-encoded PKCS#8 string as a runtime-specific private key representation (KeyObject * or CryptoKey). See [Algorithm Key Requirements](https://github.com/panva/jose/issues/210) to * learn about key to algorithm requirements and mapping. Encrypted keys are not supported. * * @example Usage * * ```js * const algorithm = 'ES256' * const pkcs8 = `-----BEGIN PRIVATE KEY----- * MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgiyvo0X+VQ0yIrOaN * nlrnUclopnvuuMfoc8HHly3505OhRANCAAQWUcdZ8uTSAsFuwtNy4KtsKqgeqYxg * l6kwL5D4N3pEGYGIDjV69Sw0zAt43480WqJv7HCL0mQnyqFmSrxj8jMa * -----END PRIVATE KEY-----` * const ecPrivateKey = await jose.importPKCS8(pkcs8, algorithm) * ``` * * @param pem PEM-encoded PKCS#8 string * @param alg JSON Web Algorithm identifier to be used with the imported key. */ export async function importPKCS8( pkcs8: string, alg: string, options?: PEMImportOptions, ): Promise { if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) { throw new TypeError('"pkcs8" must be PKCS#8 formatted string') } return importPrivate(pkcs8, alg, options) } /** * Imports a JWK to a runtime-specific key representation (KeyLike). Either JWK "alg" (Algorithm) * Parameter must be present or the optional "alg" argument. When running on a runtime using [Web * Cryptography API](https://www.w3.org/TR/WebCryptoAPI/) the jwk parameters "use", "key_ops", and * "ext" are also used in the resulting `CryptoKey`. See [Algorithm Key * Requirements](https://github.com/panva/jose/issues/210) to learn about key to algorithm * requirements and mapping. * * @example Usage * * ```js * const ecPublicKey = await jose.importJWK( * { * crv: 'P-256', * kty: 'EC', * x: 'ySK38C1jBdLwDsNWKzzBHqKYEE5Cgv-qjWvorUXk9fw', * y: '_LeQBw07cf5t57Iavn4j-BqJsAD1dpoz8gokd3sBsOo', * }, * 'ES256', * ) * * const rsaPublicKey = await jose.importJWK( * { * kty: 'RSA', * e: 'AQAB', * n: '12oBZRhCiZFJLcPg59LkZZ9mdhSMTKAQZYq32k_ti5SBB6jerkh-WzOMAO664r_qyLkqHUSp3u5SbXtseZEpN3XPWGKSxjsy-1JyEFTdLSYe6f9gfrmxkUF_7DTpq0gn6rntP05g2-wFW50YO7mosfdslfrTJYWHFhJALabAeYirYD7-9kqq9ebfFMF4sRRELbv9oi36As6Q9B3Qb5_C1rAzqfao_PCsf9EPsTZsVVVkA5qoIAr47lo1ipfiBPxUCCNSdvkmDTYgvvRm6ZoMjFbvOtgyts55fXKdMWv7I9HMD5HwE9uW839PWA514qhbcIsXEYSFMPMV6fnlsiZvQQ', * }, * 'PS256', * ) * ``` * * @param jwk JSON Web Key. * @param alg JSON Web Algorithm identifier to be used with the imported key. Default is the "alg" * property on the JWK. * @param octAsKeyObject Forces a symmetric key to be imported to a KeyObject or CryptoKey. Default * is true unless JWK "ext" (Extractable) is true. */ export async function importJWK( jwk: JWK, alg?: string, octAsKeyObject?: boolean, ): Promise { if (!isObject(jwk)) { throw new TypeError('JWK must be an object') } alg ||= jwk.alg if (typeof alg !== 'string' || !alg) { throw new TypeError('"alg" argument is required when "jwk.alg" is not present') } switch (jwk.kty) { case 'oct': if (typeof jwk.k !== 'string' || !jwk.k) { throw new TypeError('missing "k" (Key Value) Parameter value') } octAsKeyObject ??= jwk.ext !== true if (octAsKeyObject) { return asKeyObject({ ...jwk, alg, ext: jwk.ext ?? false }) } return decodeBase64URL(jwk.k) case 'RSA': if (jwk.oth !== undefined) { throw new JOSENotSupported( 'RSA JWK "oth" (Other Primes Info) Parameter value is not supported', ) } case 'EC': case 'OKP': return asKeyObject({ ...jwk, alg }) default: throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value') } } jose-4.11.4/src/lib/000077500000000000000000000000001437043056600141065ustar00rootroot00000000000000jose-4.11.4/src/lib/aesgcmkw.ts000066400000000000000000000014351437043056600162620ustar00rootroot00000000000000import encrypt from '../runtime/encrypt.js' import decrypt from '../runtime/decrypt.js' import generateIv from './iv.js' import { encode as base64url } from '../runtime/base64url.js' export async function wrap(alg: string, key: unknown, cek: Uint8Array, iv?: Uint8Array) { const jweAlgorithm = alg.slice(0, 7) iv ||= generateIv(jweAlgorithm) const { ciphertext: encryptedKey, tag } = await encrypt( jweAlgorithm, cek, key, iv, new Uint8Array(0), ) return { encryptedKey, iv: base64url(iv), tag: base64url(tag) } } export async function unwrap( alg: string, key: unknown, encryptedKey: Uint8Array, iv: Uint8Array, tag: Uint8Array, ) { const jweAlgorithm = alg.slice(0, 7) return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0)) } jose-4.11.4/src/lib/buffer_utils.ts000066400000000000000000000033541437043056600171540ustar00rootroot00000000000000import digest from '../runtime/digest.js' export const encoder = new TextEncoder() export const decoder = new TextDecoder() const MAX_INT32 = 2 ** 32 export function concat(...buffers: Uint8Array[]): Uint8Array { const size = buffers.reduce((acc, { length }) => acc + length, 0) const buf = new Uint8Array(size) let i = 0 buffers.forEach((buffer) => { buf.set(buffer, i) i += buffer.length }) return buf } export function p2s(alg: string, p2sInput: Uint8Array) { return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput) } function writeUInt32BE(buf: Uint8Array, value: number, offset?: number) { if (value < 0 || value >= MAX_INT32) { throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`) } buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset) } export function uint64be(value: number) { const high = Math.floor(value / MAX_INT32) const low = value % MAX_INT32 const buf = new Uint8Array(8) writeUInt32BE(buf, high, 0) writeUInt32BE(buf, low, 4) return buf } export function uint32be(value: number) { const buf = new Uint8Array(4) writeUInt32BE(buf, value) return buf } export function lengthAndInput(input: Uint8Array) { return concat(uint32be(input.length), input) } export async function concatKdf(secret: Uint8Array, bits: number, value: Uint8Array) { const iterations = Math.ceil((bits >> 3) / 32) const res = new Uint8Array(iterations * 32) for (let iter = 0; iter < iterations; iter++) { const buf = new Uint8Array(4 + secret.length + value.length) buf.set(uint32be(iter + 1)) buf.set(secret, 4) buf.set(value, 4 + secret.length) res.set(await digest('sha256', buf), iter * 32) } return res.slice(0, bits >> 3) } jose-4.11.4/src/lib/cek.ts000066400000000000000000000010521437043056600152160ustar00rootroot00000000000000import { JOSENotSupported } from '../util/errors.js' import random from '../runtime/random.js' export function bitLength(alg: string) { switch (alg) { case 'A128GCM': return 128 case 'A192GCM': return 192 case 'A256GCM': case 'A128CBC-HS256': return 256 case 'A192CBC-HS384': return 384 case 'A256CBC-HS512': return 512 default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`) } } export default (alg: string): Uint8Array => random(new Uint8Array(bitLength(alg) >> 3)) jose-4.11.4/src/lib/check_iv_length.ts000066400000000000000000000004351437043056600175740ustar00rootroot00000000000000import { JWEInvalid } from '../util/errors.js' import { bitLength } from './iv.js' const checkIvLength = (enc: string, iv: Uint8Array) => { if (iv.length << 3 !== bitLength(enc)) { throw new JWEInvalid('Invalid Initialization Vector length') } } export default checkIvLength jose-4.11.4/src/lib/check_key_type.ts000066400000000000000000000041321437043056600174440ustar00rootroot00000000000000import { withAlg as invalidKeyInput } from './invalid_key_input.js' import isKeyLike, { types } from '../runtime/is_key_like.js' const symmetricTypeCheck = (alg: string, key: unknown) => { if (key instanceof Uint8Array) return if (!isKeyLike(key)) { throw new TypeError(invalidKeyInput(alg, key, ...types, 'Uint8Array')) } if (key.type !== 'secret') { throw new TypeError( `${types.join(' or ')} instances for symmetric algorithms must be of type "secret"`, ) } } const asymmetricTypeCheck = (alg: string, key: unknown, usage: string) => { if (!isKeyLike(key)) { throw new TypeError(invalidKeyInput(alg, key, ...types)) } if (key.type === 'secret') { throw new TypeError( `${types.join(' or ')} instances for asymmetric algorithms must not be of type "secret"`, ) } if (usage === 'sign' && key.type === 'public') { throw new TypeError( `${types.join(' or ')} instances for asymmetric algorithm signing must be of type "private"`, ) } if (usage === 'decrypt' && key.type === 'public') { throw new TypeError( `${types.join( ' or ', )} instances for asymmetric algorithm decryption must be of type "private"`, ) } // KeyObject allows this but CryptoKey does not. if ((key).algorithm && usage === 'verify' && key.type === 'private') { throw new TypeError( `${types.join(' or ')} instances for asymmetric algorithm verifying must be of type "public"`, ) } // KeyObject allows this but CryptoKey does not. if ((key).algorithm && usage === 'encrypt' && key.type === 'private') { throw new TypeError( `${types.join( ' or ', )} instances for asymmetric algorithm encryption must be of type "public"`, ) } } const checkKeyType = (alg: string, key: unknown, usage: string): void => { const symmetric = alg.startsWith('HS') || alg === 'dir' || alg.startsWith('PBES2') || /^A\d{3}(?:GCM)?KW$/.test(alg) if (symmetric) { symmetricTypeCheck(alg, key) } else { asymmetricTypeCheck(alg, key, usage) } } export default checkKeyType jose-4.11.4/src/lib/check_p2s.ts000066400000000000000000000003501437043056600163150ustar00rootroot00000000000000import { JWEInvalid } from '../util/errors.js' export default function checkP2s(p2s: Uint8Array) { if (!(p2s instanceof Uint8Array) || p2s.length < 8) { throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets') } } jose-4.11.4/src/lib/crypto_key.ts000066400000000000000000000114451437043056600166530ustar00rootroot00000000000000import { isCloudflareWorkers } from '../runtime/env.js' function unusable(name: string | number, prop = 'algorithm.name') { return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`) } function isAlgorithm(algorithm: any, name: string): algorithm is T { return algorithm.name === name } function getHashLength(hash: KeyAlgorithm) { return parseInt(hash.name.slice(4), 10) } function getNamedCurve(alg: string) { switch (alg) { case 'ES256': return 'P-256' case 'ES384': return 'P-384' case 'ES512': return 'P-521' default: throw new Error('unreachable') } } function checkUsage(key: CryptoKey, usages: KeyUsage[]) { if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { let msg = 'CryptoKey does not support this operation, its usages must include ' if (usages.length > 2) { const last = usages.pop() msg += `one of ${usages.join(', ')}, or ${last}.` } else if (usages.length === 2) { msg += `one of ${usages[0]} or ${usages[1]}.` } else { msg += `${usages[0]}.` } throw new TypeError(msg) } } export function checkSigCryptoKey(key: CryptoKey, alg: string, ...usages: KeyUsage[]) { switch (alg) { case 'HS256': case 'HS384': case 'HS512': { if (!isAlgorithm(key.algorithm, 'HMAC')) throw unusable('HMAC') const expected = parseInt(alg.slice(2), 10) const actual = getHashLength(key.algorithm.hash) if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash') break } case 'RS256': case 'RS384': case 'RS512': { if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5')) throw unusable('RSASSA-PKCS1-v1_5') const expected = parseInt(alg.slice(2), 10) const actual = getHashLength(key.algorithm.hash) if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash') break } case 'PS256': case 'PS384': case 'PS512': { if (!isAlgorithm(key.algorithm, 'RSA-PSS')) throw unusable('RSA-PSS') const expected = parseInt(alg.slice(2), 10) const actual = getHashLength(key.algorithm.hash) if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash') break } case 'EdDSA': { if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') { if (isCloudflareWorkers()) { if (isAlgorithm(key.algorithm, 'NODE-ED25519')) break throw unusable('Ed25519, Ed448, or NODE-ED25519') } throw unusable('Ed25519 or Ed448') } break } case 'ES256': case 'ES384': case 'ES512': { if (!isAlgorithm(key.algorithm, 'ECDSA')) throw unusable('ECDSA') const expected = getNamedCurve(alg) const actual = key.algorithm.namedCurve if (actual !== expected) throw unusable(expected, 'algorithm.namedCurve') break } default: throw new TypeError('CryptoKey does not support this operation') } checkUsage(key, usages) } export function checkEncCryptoKey(key: CryptoKey, alg: string, ...usages: KeyUsage[]) { switch (alg) { case 'A128GCM': case 'A192GCM': case 'A256GCM': { if (!isAlgorithm(key.algorithm, 'AES-GCM')) throw unusable('AES-GCM') const expected = parseInt(alg.slice(1, 4), 10) const actual = key.algorithm.length if (actual !== expected) throw unusable(expected, 'algorithm.length') break } case 'A128KW': case 'A192KW': case 'A256KW': { if (!isAlgorithm(key.algorithm, 'AES-KW')) throw unusable('AES-KW') const expected = parseInt(alg.slice(1, 4), 10) const actual = key.algorithm.length if (actual !== expected) throw unusable(expected, 'algorithm.length') break } case 'ECDH': { switch (key.algorithm.name) { case 'ECDH': case 'X25519': case 'X448': break default: throw unusable('ECDH, X25519, or X448') } break } case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': if (!isAlgorithm(key.algorithm, 'PBKDF2')) throw unusable('PBKDF2') break case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': { if (!isAlgorithm(key.algorithm, 'RSA-OAEP')) throw unusable('RSA-OAEP') const expected = parseInt(alg.slice(9), 10) || 1 const actual = getHashLength(key.algorithm.hash) if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash') break } default: throw new TypeError('CryptoKey does not support this operation') } checkUsage(key, usages) } jose-4.11.4/src/lib/decrypt_key_management.ts000066400000000000000000000113521437043056600211760ustar00rootroot00000000000000import { unwrap as aesKw } from '../runtime/aeskw.js' import * as ECDH from '../runtime/ecdhes.js' import { decrypt as pbes2Kw } from '../runtime/pbes2kw.js' import { decrypt as rsaEs } from '../runtime/rsaes.js' import { decode as base64url } from '../runtime/base64url.js' import type { DecryptOptions, JWEHeaderParameters, KeyLike, JWK } from '../types.d' import { JOSENotSupported, JWEInvalid } from '../util/errors.js' import { bitLength as cekLength } from '../lib/cek.js' import { importJWK } from '../key/import.js' import checkKeyType from './check_key_type.js' import isObject from './is_object.js' import { unwrap as aesGcmKw } from './aesgcmkw.js' async function decryptKeyManagement( alg: string, key: KeyLike | Uint8Array, encryptedKey: Uint8Array | undefined, joseHeader: JWEHeaderParameters, options?: DecryptOptions, ): Promise { checkKeyType(alg, key, 'decrypt') switch (alg) { case 'dir': { // Direct Encryption if (encryptedKey !== undefined) throw new JWEInvalid('Encountered unexpected JWE Encrypted Key') return key } case 'ECDH-ES': // Direct Key Agreement if (encryptedKey !== undefined) throw new JWEInvalid('Encountered unexpected JWE Encrypted Key') case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': { // Direct Key Agreement if (!isObject(joseHeader.epk)) throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`) if (!ECDH.ecdhAllowed(key)) throw new JOSENotSupported( 'ECDH with the provided key is not allowed or not supported by your javascript runtime', ) const epk = await importJWK(joseHeader.epk, alg) let partyUInfo!: Uint8Array let partyVInfo!: Uint8Array if (joseHeader.apu !== undefined) { if (typeof joseHeader.apu !== 'string') throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`) partyUInfo = base64url(joseHeader.apu) } if (joseHeader.apv !== undefined) { if (typeof joseHeader.apv !== 'string') throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`) partyVInfo = base64url(joseHeader.apv) } const sharedSecret = await ECDH.deriveKey( epk, key, alg === 'ECDH-ES' ? joseHeader.enc! : alg, alg === 'ECDH-ES' ? cekLength(joseHeader.enc!) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo, ) if (alg === 'ECDH-ES') return sharedSecret // Key Agreement with Key Wrapping if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing') return aesKw(alg.slice(-6), sharedSecret, encryptedKey) } case 'RSA1_5': case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': { // Key Encryption (RSA) if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing') return rsaEs(alg, key, encryptedKey) } case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': { // Key Encryption (PBES2) if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing') if (typeof joseHeader.p2c !== 'number') throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`) const p2cLimit = options?.maxPBES2Count || 10_000 if (joseHeader.p2c > p2cLimit) throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`) if (typeof joseHeader.p2s !== 'string') throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`) return pbes2Kw(alg, key, encryptedKey, joseHeader.p2c, base64url(joseHeader.p2s)) } case 'A128KW': case 'A192KW': case 'A256KW': { // Key Wrapping (AES KW) if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing') return aesKw(alg, key, encryptedKey) } case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': { // Key Wrapping (AES GCM KW) if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing') if (typeof joseHeader.iv !== 'string') throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`) if (typeof joseHeader.tag !== 'string') throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`) const iv = base64url(joseHeader.iv) const tag = base64url(joseHeader.tag) return aesGcmKw(alg, key, encryptedKey, iv, tag) } default: { throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value') } } } export default decryptKeyManagement jose-4.11.4/src/lib/encrypt_key_management.ts000066400000000000000000000072131437043056600212110ustar00rootroot00000000000000import { wrap as aesKw } from '../runtime/aeskw.js' import * as ECDH from '../runtime/ecdhes.js' import { encrypt as pbes2Kw } from '../runtime/pbes2kw.js' import { encrypt as rsaEs } from '../runtime/rsaes.js' import { encode as base64url } from '../runtime/base64url.js' import type { KeyLike, JWEKeyManagementHeaderParameters, JWEHeaderParameters, JWK, } from '../types.d' import generateCek, { bitLength as cekLength } from '../lib/cek.js' import { JOSENotSupported } from '../util/errors.js' import { exportJWK } from '../key/export.js' import checkKeyType from './check_key_type.js' import { wrap as aesGcmKw } from './aesgcmkw.js' async function encryptKeyManagement( alg: string, enc: string, key: KeyLike | Uint8Array, providedCek?: Uint8Array, providedParameters: JWEKeyManagementHeaderParameters = {}, ): Promise<{ cek: KeyLike | Uint8Array encryptedKey?: Uint8Array parameters?: JWEHeaderParameters }> { let encryptedKey: Uint8Array | undefined let parameters: (JWEHeaderParameters & { epk?: JWK }) | undefined let cek: KeyLike | Uint8Array checkKeyType(alg, key, 'encrypt') switch (alg) { case 'dir': { // Direct Encryption cek = key break } case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': { // Direct Key Agreement if (!ECDH.ecdhAllowed(key)) { throw new JOSENotSupported( 'ECDH with the provided key is not allowed or not supported by your javascript runtime', ) } const { apu, apv } = providedParameters let { epk: ephemeralKey } = providedParameters ephemeralKey ||= (await ECDH.generateEpk(key)).privateKey const { x, y, crv, kty } = await exportJWK(ephemeralKey!) const sharedSecret = await ECDH.deriveKey( key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv, ) parameters = { epk: { x, crv, kty } } if (kty === 'EC') parameters.epk!.y = y if (apu) parameters.apu = base64url(apu) if (apv) parameters.apv = base64url(apv) if (alg === 'ECDH-ES') { cek = sharedSecret break } // Key Agreement with Key Wrapping cek = providedCek || generateCek(enc) const kwAlg = alg.slice(-6) encryptedKey = await aesKw(kwAlg, sharedSecret, cek) break } case 'RSA1_5': case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': { // Key Encryption (RSA) cek = providedCek || generateCek(enc) encryptedKey = await rsaEs(alg, key, cek) break } case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': { // Key Encryption (PBES2) cek = providedCek || generateCek(enc) const { p2c, p2s } = providedParameters ;({ encryptedKey, ...parameters } = await pbes2Kw(alg, key, cek, p2c, p2s)) break } case 'A128KW': case 'A192KW': case 'A256KW': { // Key Wrapping (AES KW) cek = providedCek || generateCek(enc) encryptedKey = await aesKw(alg, key, cek) break } case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': { // Key Wrapping (AES GCM KW) cek = providedCek || generateCek(enc) const { iv } = providedParameters ;({ encryptedKey, ...parameters } = await aesGcmKw(alg, key, cek, iv)) break } default: { throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value') } } return { cek, encryptedKey, parameters } } export default encryptKeyManagement jose-4.11.4/src/lib/epoch.ts000066400000000000000000000001011437043056600155440ustar00rootroot00000000000000export default (date: Date) => Math.floor(date.getTime() / 1000) jose-4.11.4/src/lib/format_pem.ts000066400000000000000000000003071437043056600166070ustar00rootroot00000000000000export default (b64: string, descriptor: string) => { const newlined = (b64.match(/.{1,64}/g) || []).join('\n') return `-----BEGIN ${descriptor}-----\n${newlined}\n-----END ${descriptor}-----` } jose-4.11.4/src/lib/invalid_key_input.ts000066400000000000000000000017021437043056600201730ustar00rootroot00000000000000function message(msg: string, actual: unknown, ...types: string[]) { if (types.length > 2) { const last = types.pop() msg += `one of type ${types.join(', ')}, or ${last}.` } else if (types.length === 2) { msg += `one of type ${types[0]} or ${types[1]}.` } else { msg += `of type ${types[0]}.` } if (actual == null) { msg += ` Received ${actual}` } else if (typeof actual === 'function' && actual.name) { msg += ` Received function ${actual.name}` } else if (typeof actual === 'object' && actual != null) { if (actual.constructor && actual.constructor.name) { msg += ` Received an instance of ${actual.constructor.name}` } } return msg } export default (actual: unknown, ...types: string[]) => { return message('Key must be ', actual, ...types) } export function withAlg(alg: string, actual: unknown, ...types: string[]) { return message(`Key for the ${alg} algorithm must be `, actual, ...types) } jose-4.11.4/src/lib/is_disjoint.ts000066400000000000000000000010621437043056600167730ustar00rootroot00000000000000const isDisjoint = (...headers: Array) => { const sources = headers.filter(Boolean) if (sources.length === 0 || sources.length === 1) { return true } let acc!: Set for (const header of sources) { const parameters = Object.keys(header) if (!acc || acc.size === 0) { acc = new Set(parameters) continue } for (const parameter of parameters) { if (acc.has(parameter)) { return false } acc.add(parameter) } } return true } export default isDisjoint jose-4.11.4/src/lib/is_object.ts000066400000000000000000000010051437043056600164130ustar00rootroot00000000000000function isObjectLike(value: unknown) { return typeof value === 'object' && value !== null } export default function isObject(input: unknown): input is T { if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') { return false } if (Object.getPrototypeOf(input) === null) { return true } let proto = input while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto) } return Object.getPrototypeOf(input) === proto } jose-4.11.4/src/lib/iv.ts000066400000000000000000000010701437043056600150720ustar00rootroot00000000000000import { JOSENotSupported } from '../util/errors.js' import random from '../runtime/random.js' export function bitLength(alg: string) { switch (alg) { case 'A128GCM': case 'A128GCMKW': case 'A192GCM': case 'A192GCMKW': case 'A256GCM': case 'A256GCMKW': return 96 case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': return 128 default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`) } } export default (alg: string): Uint8Array => random(new Uint8Array(bitLength(alg) >> 3)) jose-4.11.4/src/lib/jwt_claims_set.ts000066400000000000000000000077541437043056600175020ustar00rootroot00000000000000import type { JWTPayload, JWTClaimVerificationOptions, JWEHeaderParameters, JWSHeaderParameters, } from '../types.d' import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js' import { decoder } from './buffer_utils.js' import epoch from './epoch.js' import secs from './secs.js' import isObject from './is_object.js' const normalizeTyp = (value: string) => value.toLowerCase().replace(/^application\//, '') const checkAudiencePresence = (audPayload: unknown, audOption: unknown[]) => { if (typeof audPayload === 'string') { return audOption.includes(audPayload) } if (Array.isArray(audPayload)) { // Each principal intended to process the JWT MUST // identify itself with a value in the audience claim return audOption.some(Set.prototype.has.bind(new Set(audPayload))) } return false } export default ( protectedHeader: JWEHeaderParameters | JWSHeaderParameters, encodedPayload: Uint8Array, options: JWTClaimVerificationOptions = {}, ) => { const { typ } = options if ( typ && (typeof protectedHeader!.typ !== 'string' || normalizeTyp(protectedHeader!.typ) !== normalizeTyp(typ)) ) { throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', 'typ', 'check_failed') } let payload!: { [propName: string]: unknown } try { payload = JSON.parse(decoder.decode(encodedPayload)) } catch { // } if (!isObject(payload)) { throw new JWTInvalid('JWT Claims Set must be a top-level JSON object') } const { issuer } = options if (issuer && !((Array.isArray(issuer) ? issuer : [issuer])).includes(payload.iss!)) { throw new JWTClaimValidationFailed('unexpected "iss" claim value', 'iss', 'check_failed') } const { subject } = options if (subject && payload.sub !== subject) { throw new JWTClaimValidationFailed('unexpected "sub" claim value', 'sub', 'check_failed') } const { audience } = options if ( audience && !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience) ) { throw new JWTClaimValidationFailed('unexpected "aud" claim value', 'aud', 'check_failed') } let tolerance: number switch (typeof options.clockTolerance) { case 'string': tolerance = secs(options.clockTolerance) break case 'number': tolerance = options.clockTolerance break case 'undefined': tolerance = 0 break default: throw new TypeError('Invalid clockTolerance option type') } const { currentDate } = options const now = epoch(currentDate || new Date()) if ((payload.iat !== undefined || options.maxTokenAge) && typeof payload.iat !== 'number') { throw new JWTClaimValidationFailed('"iat" claim must be a number', 'iat', 'invalid') } if (payload.nbf !== undefined) { if (typeof payload.nbf !== 'number') { throw new JWTClaimValidationFailed('"nbf" claim must be a number', 'nbf', 'invalid') } if (payload.nbf > now + tolerance) { throw new JWTClaimValidationFailed( '"nbf" claim timestamp check failed', 'nbf', 'check_failed', ) } } if (payload.exp !== undefined) { if (typeof payload.exp !== 'number') { throw new JWTClaimValidationFailed('"exp" claim must be a number', 'exp', 'invalid') } if (payload.exp <= now - tolerance) { throw new JWTExpired('"exp" claim timestamp check failed', 'exp', 'check_failed') } } if (options.maxTokenAge) { const age = now - payload.iat! const max = typeof options.maxTokenAge === 'number' ? options.maxTokenAge : secs(options.maxTokenAge) if (age - tolerance > max) { throw new JWTExpired( '"iat" claim timestamp check failed (too far in the past)', 'iat', 'check_failed', ) } if (age < 0 - tolerance) { throw new JWTClaimValidationFailed( '"iat" claim timestamp check failed (it should be in the past)', 'iat', 'check_failed', ) } } return payload } jose-4.11.4/src/lib/secs.ts000066400000000000000000000021061437043056600154120ustar00rootroot00000000000000const minute = 60 const hour = minute * 60 const day = hour * 24 const week = day * 7 const year = day * 365.25 const REGEX = /^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i export default (str: string): number => { const matched = REGEX.exec(str) if (!matched) { throw new TypeError('Invalid time period format') } const value = parseFloat(matched[1]) const unit = matched[2].toLowerCase() switch (unit) { case 'sec': case 'secs': case 'second': case 'seconds': case 's': return Math.round(value) case 'minute': case 'minutes': case 'min': case 'mins': case 'm': return Math.round(value * minute) case 'hour': case 'hours': case 'hr': case 'hrs': case 'h': return Math.round(value * hour) case 'day': case 'days': case 'd': return Math.round(value * day) case 'week': case 'weeks': case 'w': return Math.round(value * week) // years matched default: return Math.round(value * year) } } jose-4.11.4/src/lib/validate_algorithms.ts000066400000000000000000000006071437043056600205030ustar00rootroot00000000000000const validateAlgorithms = (option: string, algorithms?: string[]) => { if ( algorithms !== undefined && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string')) ) { throw new TypeError(`"${option}" option must be an array of strings`) } if (!algorithms) { return undefined } return new Set(algorithms) } export default validateAlgorithms jose-4.11.4/src/lib/validate_crit.ts000066400000000000000000000034101437043056600172660ustar00rootroot00000000000000import { JOSENotSupported, JWEInvalid, JWSInvalid } from '../util/errors.js' interface CritCheckHeader { b64?: boolean crit?: string[] [propName: string]: unknown } function validateCrit( Err: typeof JWEInvalid | typeof JWSInvalid, recognizedDefault: Map, recognizedOption: { [propName: string]: boolean } | undefined, protectedHeader: CritCheckHeader, joseHeader: CritCheckHeader, ) { if (joseHeader.crit !== undefined && protectedHeader.crit === undefined) { throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected') } if (!protectedHeader || protectedHeader.crit === undefined) { return new Set() } if ( !Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input: string) => typeof input !== 'string' || input.length === 0) ) { throw new Err( '"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present', ) } let recognized: Map if (recognizedOption !== undefined) { recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]) } else { recognized = recognizedDefault } for (const parameter of protectedHeader.crit) { if (!recognized.has(parameter)) { throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`) } if (joseHeader[parameter] === undefined) { throw new Err(`Extension Header Parameter "${parameter}" is missing`) } else if (recognized.get(parameter) && protectedHeader[parameter] === undefined) { throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`) } } return new Set(protectedHeader.crit) } export default validateCrit jose-4.11.4/src/runtime/000077500000000000000000000000001437043056600150235ustar00rootroot00000000000000jose-4.11.4/src/runtime/browser/000077500000000000000000000000001437043056600165065ustar00rootroot00000000000000jose-4.11.4/src/runtime/browser/aeskw.ts000066400000000000000000000033771437043056600202020ustar00rootroot00000000000000import type { AesKwUnwrapFunction, AesKwWrapFunction } from '../interfaces.d' import bogusWebCrypto from './bogus.js' import crypto, { isCryptoKey } from './webcrypto.js' import { checkEncCryptoKey } from '../../lib/crypto_key.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import { types } from './is_key_like.js' function checkKeySize(key: CryptoKey, alg: string) { if ((key.algorithm).length !== parseInt(alg.slice(1, 4), 10)) { throw new TypeError(`Invalid key size for alg: ${alg}`) } } function getCryptoKey(key: unknown, alg: string, usage: KeyUsage) { if (isCryptoKey(key)) { checkEncCryptoKey(key, alg, usage) return key } if (key instanceof Uint8Array) { return crypto.subtle.importKey('raw', key, 'AES-KW', true, [usage]) } throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')) } export const wrap: AesKwWrapFunction = async (alg: string, key: unknown, cek: Uint8Array) => { const cryptoKey = await getCryptoKey(key, alg, 'wrapKey') checkKeySize(cryptoKey, alg) // we're importing the cek to end up with CryptoKey instance that can be wrapped, the algorithm used is irrelevant const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto) return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, cryptoKey, 'AES-KW')) } export const unwrap: AesKwUnwrapFunction = async ( alg: string, key: unknown, encryptedKey: Uint8Array, ) => { const cryptoKey = await getCryptoKey(key, alg, 'unwrapKey') checkKeySize(cryptoKey, alg) const cryptoKeyCek = await crypto.subtle.unwrapKey( 'raw', encryptedKey, cryptoKey, 'AES-KW', ...bogusWebCrypto, ) return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek)) } jose-4.11.4/src/runtime/browser/asn1.ts000066400000000000000000000123271437043056600177250ustar00rootroot00000000000000import { isCloudflareWorkers } from './env.js' import crypto, { isCryptoKey } from './webcrypto.js' import type { PEMExportFunction, PEMImportFunction } from '../interfaces.d' import invalidKeyInput from '../../lib/invalid_key_input.js' import { encodeBase64 } from './base64url.js' import formatPEM from '../../lib/format_pem.js' import { JOSENotSupported } from '../../util/errors.js' import { types } from './is_key_like.js' import type { PEMImportOptions } from '../../key/import.js' const genericExport = async ( keyType: 'private' | 'public', keyFormat: 'spki' | 'pkcs8', key: unknown, ) => { if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types)) } if (!key.extractable) { throw new TypeError('CryptoKey is not extractable') } if (key.type !== keyType) { throw new TypeError(`key is not a ${keyType} key`) } return formatPEM( encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`, ) } export const toSPKI: PEMExportFunction = (key) => { return genericExport('public', 'spki', key) } export const toPKCS8: PEMExportFunction = (key) => { return genericExport('private', 'pkcs8', key) } const findOid = (keyData: Uint8Array, oid: number[], from = 0): boolean => { if (from === 0) { oid.unshift(oid.length) oid.unshift(0x06) } let i = keyData.indexOf(oid[0], from) if (i === -1) return false const sub = keyData.subarray(i, i + oid.length) if (sub.length !== oid.length) return false return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1) } const getNamedCurve = (keyData: Uint8Array): string => { switch (true) { case findOid(keyData, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]): return 'P-256' case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x22]): return 'P-384' case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x23]): return 'P-521' case findOid(keyData, [0x2b, 0x65, 0x6e]): return 'X25519' case findOid(keyData, [0x2b, 0x65, 0x6f]): return 'X448' case findOid(keyData, [0x2b, 0x65, 0x70]): return 'Ed25519' case findOid(keyData, [0x2b, 0x65, 0x71]): return 'Ed448' default: throw new JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type') } } const genericImport = async ( replace: RegExp, keyFormat: 'spki' | 'pkcs8', pem: string, alg: string, options?: PEMImportOptions, ) => { let algorithm: RsaHashedImportParams | EcKeyAlgorithm | Algorithm let keyUsages: KeyUsage[] const keyData = new Uint8Array( atob(pem.replace(replace, '')) .split('') .map((c) => c.charCodeAt(0)), ) const isPublic = keyFormat === 'spki' switch (alg) { case 'PS256': case 'PS384': case 'PS512': algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` } keyUsages = isPublic ? ['verify'] : ['sign'] break case 'RS256': case 'RS384': case 'RS512': algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` } keyUsages = isPublic ? ['verify'] : ['sign'] break case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': algorithm = { name: 'RSA-OAEP', hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`, } keyUsages = isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey'] break case 'ES256': algorithm = { name: 'ECDSA', namedCurve: 'P-256' } keyUsages = isPublic ? ['verify'] : ['sign'] break case 'ES384': algorithm = { name: 'ECDSA', namedCurve: 'P-384' } keyUsages = isPublic ? ['verify'] : ['sign'] break case 'ES512': algorithm = { name: 'ECDSA', namedCurve: 'P-521' } keyUsages = isPublic ? ['verify'] : ['sign'] break case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': { const namedCurve = getNamedCurve(keyData) algorithm = namedCurve.startsWith('P-') ? { name: 'ECDH', namedCurve } : { name: namedCurve } keyUsages = isPublic ? [] : ['deriveBits'] break } case 'EdDSA': algorithm = { name: getNamedCurve(keyData) } keyUsages = isPublic ? ['verify'] : ['sign'] break default: throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value') } try { return await crypto.subtle.importKey( keyFormat, keyData, algorithm, options?.extractable ?? false, keyUsages, ) } catch (err) { if ( algorithm.name === 'Ed25519' && (err)?.name === 'NotSupportedError' && isCloudflareWorkers() ) { algorithm = { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' } return await crypto.subtle.importKey( keyFormat, keyData, algorithm, options?.extractable ?? false, keyUsages, ) } throw err } } export const fromPKCS8: PEMImportFunction = (pem, alg, options?) => { return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, 'pkcs8', pem, alg, options) } export const fromSPKI: PEMImportFunction = (pem, alg, options?) => { return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, 'spki', pem, alg, options) } jose-4.11.4/src/runtime/browser/base64url.ts000066400000000000000000000023311437043056600206640ustar00rootroot00000000000000import { encoder, decoder } from '../../lib/buffer_utils.js' export const encodeBase64 = (input: Uint8Array | string) => { let unencoded = input if (typeof unencoded === 'string') { unencoded = encoder.encode(unencoded) } const CHUNK_SIZE = 0x8000 const arr = [] for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) { // @ts-expect-error arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE))) } return btoa(arr.join('')) } export const encode = (input: Uint8Array | string) => { return encodeBase64(input).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_') } export const decodeBase64 = (encoded: string): Uint8Array => { const binary = atob(encoded) const bytes = new Uint8Array(binary.length) for (let i = 0; i < binary.length; i++) { bytes[i] = binary.charCodeAt(i) } return bytes } export const decode = (input: Uint8Array | string) => { let encoded = input if (encoded instanceof Uint8Array) { encoded = decoder.decode(encoded) } encoded = encoded.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '') try { return decodeBase64(encoded) } catch { throw new TypeError('The input to be decoded is not correctly encoded.') } } jose-4.11.4/src/runtime/browser/bogus.ts000066400000000000000000000002341437043056600201740ustar00rootroot00000000000000const bogusWebCrypto: [HmacImportParams, boolean, KeyUsage[]] = [ { hash: 'SHA-256', name: 'HMAC' }, true, ['sign'], ] export default bogusWebCrypto jose-4.11.4/src/runtime/browser/check_cek_length.ts000066400000000000000000000005301437043056600223140ustar00rootroot00000000000000import { JWEInvalid } from '../../util/errors.js' const checkCekLength = (cek: Uint8Array, expected: number) => { const actual = cek.byteLength << 3 if (actual !== expected) { throw new JWEInvalid( `Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`, ) } } export default checkCekLength jose-4.11.4/src/runtime/browser/check_key_length.ts000066400000000000000000000005171437043056600223470ustar00rootroot00000000000000export default (alg: string, key: CryptoKey) => { if (alg.startsWith('RS') || alg.startsWith('PS')) { const { modulusLength } = key.algorithm if (typeof modulusLength !== 'number' || modulusLength < 2048) { throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`) } } } jose-4.11.4/src/runtime/browser/decrypt.ts000066400000000000000000000065501437043056600205360ustar00rootroot00000000000000import { concat, uint64be } from '../../lib/buffer_utils.js' import type { DecryptFunction } from '../interfaces.d' import checkIvLength from '../../lib/check_iv_length.js' import checkCekLength from './check_cek_length.js' import timingSafeEqual from './timing_safe_equal.js' import { JOSENotSupported, JWEDecryptionFailed } from '../../util/errors.js' import crypto, { isCryptoKey } from './webcrypto.js' import { checkEncCryptoKey } from '../../lib/crypto_key.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import { types } from './is_key_like.js' async function cbcDecrypt( enc: string, cek: Uint8Array | CryptoKey, ciphertext: Uint8Array, iv: Uint8Array, tag: Uint8Array, aad: Uint8Array, ) { if (!(cek instanceof Uint8Array)) { throw new TypeError(invalidKeyInput(cek, 'Uint8Array')) } const keySize = parseInt(enc.slice(1, 4), 10) const encKey = await crypto.subtle.importKey( 'raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['decrypt'], ) const macKey = await crypto.subtle.importKey( 'raw', cek.subarray(0, keySize >> 3), { hash: `SHA-${keySize << 1}`, name: 'HMAC', }, false, ['sign'], ) const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)) const expectedTag = new Uint8Array( (await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3), ) let macCheckPassed!: boolean try { macCheckPassed = timingSafeEqual(tag, expectedTag) } catch { // } if (!macCheckPassed) { throw new JWEDecryptionFailed() } let plaintext!: Uint8Array try { plaintext = new Uint8Array( await crypto.subtle.decrypt({ iv, name: 'AES-CBC' }, encKey, ciphertext), ) } catch { // } if (!plaintext) { throw new JWEDecryptionFailed() } return plaintext } async function gcmDecrypt( enc: string, cek: Uint8Array | CryptoKey, ciphertext: Uint8Array, iv: Uint8Array, tag: Uint8Array, aad: Uint8Array, ) { let encKey: CryptoKey if (cek instanceof Uint8Array) { encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['decrypt']) } else { checkEncCryptoKey(cek, enc, 'decrypt') encKey = cek } try { return new Uint8Array( await crypto.subtle.decrypt( { additionalData: aad, iv, name: 'AES-GCM', tagLength: 128, }, encKey, concat(ciphertext, tag), ), ) } catch { throw new JWEDecryptionFailed() } } const decrypt: DecryptFunction = async ( enc: string, cek: unknown, ciphertext: Uint8Array, iv: Uint8Array, tag: Uint8Array, aad: Uint8Array, ) => { if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')) } checkIvLength(enc, iv) switch (enc) { case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(-3), 10)) return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) case 'A128GCM': case 'A192GCM': case 'A256GCM': if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(1, 4), 10)) return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) default: throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm') } } export default decrypt jose-4.11.4/src/runtime/browser/digest.ts000066400000000000000000000005631437043056600203410ustar00rootroot00000000000000import crypto from './webcrypto.js' import type { DigestFunction } from '../interfaces.d' const digest: DigestFunction = async ( algorithm: 'sha256' | 'sha384' | 'sha512', data: Uint8Array, ): Promise => { const subtleDigest = `SHA-${algorithm.slice(-3)}` return new Uint8Array(await crypto.subtle.digest(subtleDigest, data)) } export default digest jose-4.11.4/src/runtime/browser/ecdhes.ts000066400000000000000000000037661437043056600203250ustar00rootroot00000000000000import { encoder, concat, uint32be, lengthAndInput, concatKdf } from '../../lib/buffer_utils.js' import crypto, { isCryptoKey } from './webcrypto.js' import { checkEncCryptoKey } from '../../lib/crypto_key.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import { types } from './is_key_like.js' export async function deriveKey( publicKey: unknown, privateKey: unknown, algorithm: string, keyLength: number, apu: Uint8Array = new Uint8Array(0), apv: Uint8Array = new Uint8Array(0), ) { if (!isCryptoKey(publicKey)) { throw new TypeError(invalidKeyInput(publicKey, ...types)) } checkEncCryptoKey(publicKey, 'ECDH') if (!isCryptoKey(privateKey)) { throw new TypeError(invalidKeyInput(privateKey, ...types)) } checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits') const value = concat( lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength), ) let length: number if (publicKey.algorithm.name === 'X25519') { length = 256 } else if (publicKey.algorithm.name === 'X448') { length = 448 } else { length = Math.ceil(parseInt((publicKey.algorithm).namedCurve.substr(-3), 10) / 8) << 3 } const sharedSecret = new Uint8Array( await crypto.subtle.deriveBits( { name: publicKey.algorithm.name, public: publicKey, }, privateKey, length, ), ) return concatKdf(sharedSecret, keyLength, value) } export async function generateEpk(key: unknown) { if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types)) } return crypto.subtle.generateKey(key.algorithm, true, ['deriveBits']) } export function ecdhAllowed(key: unknown) { if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types)) } return ( ['P-256', 'P-384', 'P-521'].includes((key.algorithm).namedCurve) || key.algorithm.name === 'X25519' || key.algorithm.name === 'X448' ) } jose-4.11.4/src/runtime/browser/encrypt.ts000066400000000000000000000057601437043056600205520ustar00rootroot00000000000000import { concat, uint64be } from '../../lib/buffer_utils.js' import type { EncryptFunction } from '../interfaces.d' import checkIvLength from '../../lib/check_iv_length.js' import checkCekLength from './check_cek_length.js' import crypto, { isCryptoKey } from './webcrypto.js' import { checkEncCryptoKey } from '../../lib/crypto_key.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import { JOSENotSupported } from '../../util/errors.js' import { types } from './is_key_like.js' async function cbcEncrypt( enc: string, plaintext: Uint8Array, cek: Uint8Array | CryptoKey, iv: Uint8Array, aad: Uint8Array, ) { if (!(cek instanceof Uint8Array)) { throw new TypeError(invalidKeyInput(cek, 'Uint8Array')) } const keySize = parseInt(enc.slice(1, 4), 10) const encKey = await crypto.subtle.importKey( 'raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['encrypt'], ) const macKey = await crypto.subtle.importKey( 'raw', cek.subarray(0, keySize >> 3), { hash: `SHA-${keySize << 1}`, name: 'HMAC', }, false, ['sign'], ) const ciphertext = new Uint8Array( await crypto.subtle.encrypt( { iv, name: 'AES-CBC', }, encKey, plaintext, ), ) const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)) const tag = new Uint8Array( (await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3), ) return { ciphertext, tag } } async function gcmEncrypt( enc: string, plaintext: Uint8Array, cek: Uint8Array | CryptoKey, iv: Uint8Array, aad: Uint8Array, ) { let encKey: CryptoKey if (cek instanceof Uint8Array) { encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']) } else { checkEncCryptoKey(cek, enc, 'encrypt') encKey = cek } const encrypted = new Uint8Array( await crypto.subtle.encrypt( { additionalData: aad, iv, name: 'AES-GCM', tagLength: 128, }, encKey, plaintext, ), ) const tag = encrypted.slice(-16) const ciphertext = encrypted.slice(0, -16) return { ciphertext, tag } } const encrypt: EncryptFunction = async ( enc: string, plaintext: Uint8Array, cek: unknown, iv: Uint8Array, aad: Uint8Array, ) => { if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) { throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')) } checkIvLength(enc, iv) switch (enc) { case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(-3), 10)) return cbcEncrypt(enc, plaintext, cek, iv, aad) case 'A128GCM': case 'A192GCM': case 'A256GCM': if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(1, 4), 10)) return gcmEncrypt(enc, plaintext, cek, iv, aad) default: throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm') } } export default encrypt jose-4.11.4/src/runtime/browser/env.ts000066400000000000000000000004721437043056600176510ustar00rootroot00000000000000export function isCloudflareWorkers() { return ( // @ts-ignore typeof WebSocketPair !== 'undefined' || // @ts-ignore (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') || // @ts-ignore (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel') ) } jose-4.11.4/src/runtime/browser/fetch_jwks.ts000066400000000000000000000021651437043056600212110ustar00rootroot00000000000000import type { FetchFunction } from '../interfaces.d' import { JOSEError, JWKSTimeout } from '../../util/errors.js' type AcceptedRequestOptions = Pick const fetchJwks: FetchFunction = async ( url: URL, timeout: number, options: AcceptedRequestOptions, ) => { let controller!: AbortController let id!: ReturnType let timedOut = false if (typeof AbortController === 'function') { controller = new AbortController() id = setTimeout(() => { timedOut = true controller.abort() }, timeout) } const response = await fetch(url.href, { signal: controller ? controller.signal : undefined, redirect: 'manual', headers: options.headers, }).catch((err) => { if (timedOut) throw new JWKSTimeout() throw err }) if (id !== undefined) clearTimeout(id) if (response.status !== 200) { throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response') } try { return await response.json() } catch { throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON') } } export default fetchJwks jose-4.11.4/src/runtime/browser/generate.ts000066400000000000000000000122611437043056600206520ustar00rootroot00000000000000import { isCloudflareWorkers } from './env.js' import crypto from './webcrypto.js' import { JOSENotSupported } from '../../util/errors.js' import random from './random.js' import type { GenerateKeyPairOptions } from '../../key/generate_key_pair.js' import type { GenerateSecretOptions } from '../../key/generate_secret.js' export async function generateSecret(alg: string, options?: GenerateSecretOptions) { let length: number let algorithm: AesKeyGenParams | HmacKeyGenParams let keyUsages: KeyUsage[] switch (alg) { case 'HS256': case 'HS384': case 'HS512': length = parseInt(alg.slice(-3), 10) algorithm = { name: 'HMAC', hash: `SHA-${length}`, length } keyUsages = ['sign', 'verify'] break case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': length = parseInt(alg.slice(-3), 10) return random(new Uint8Array(length >> 3)) case 'A128KW': case 'A192KW': case 'A256KW': length = parseInt(alg.slice(1, 4), 10) algorithm = { name: 'AES-KW', length } keyUsages = ['wrapKey', 'unwrapKey'] break case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': case 'A128GCM': case 'A192GCM': case 'A256GCM': length = parseInt(alg.slice(1, 4), 10) algorithm = { name: 'AES-GCM', length } keyUsages = ['encrypt', 'decrypt'] break default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value') } return >( (crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages)) ) } function getModulusLengthOption(options?: GenerateKeyPairOptions) { const modulusLength = options?.modulusLength ?? 2048 if (typeof modulusLength !== 'number' || modulusLength < 2048) { throw new JOSENotSupported( 'Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used', ) } return modulusLength } export async function generateKeyPair(alg: string, options?: GenerateKeyPairOptions) { let algorithm: RsaHashedKeyGenParams | EcKeyGenParams | KeyAlgorithm let keyUsages: KeyUsage[] switch (alg) { case 'PS256': case 'PS384': case 'PS512': algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}`, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), modulusLength: getModulusLengthOption(options), } keyUsages = ['sign', 'verify'] break case 'RS256': case 'RS384': case 'RS512': algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}`, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), modulusLength: getModulusLengthOption(options), } keyUsages = ['sign', 'verify'] break case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': algorithm = { name: 'RSA-OAEP', hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), modulusLength: getModulusLengthOption(options), } keyUsages = ['decrypt', 'unwrapKey', 'encrypt', 'wrapKey'] break case 'ES256': algorithm = { name: 'ECDSA', namedCurve: 'P-256' } keyUsages = ['sign', 'verify'] break case 'ES384': algorithm = { name: 'ECDSA', namedCurve: 'P-384' } keyUsages = ['sign', 'verify'] break case 'ES512': algorithm = { name: 'ECDSA', namedCurve: 'P-521' } keyUsages = ['sign', 'verify'] break case 'EdDSA': keyUsages = ['sign', 'verify'] const crv = options?.crv ?? 'Ed25519' switch (crv) { case 'Ed25519': case 'Ed448': algorithm = { name: crv } break default: throw new JOSENotSupported('Invalid or unsupported crv option provided') } break case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': { keyUsages = ['deriveKey', 'deriveBits'] const crv = options?.crv ?? 'P-256' switch (crv) { case 'P-256': case 'P-384': case 'P-521': { algorithm = { name: 'ECDH', namedCurve: crv } break } case 'X25519': case 'X448': algorithm = { name: crv } break default: throw new JOSENotSupported( 'Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448', ) } break } default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value') } try { return <{ publicKey: CryptoKey; privateKey: CryptoKey }>( await crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages) ) } catch (err) { if ( algorithm.name === 'Ed25519' && (err)?.name === 'NotSupportedError' && isCloudflareWorkers() ) { algorithm = { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' } return <{ publicKey: CryptoKey; privateKey: CryptoKey }>( await crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages) ) } throw err } } jose-4.11.4/src/runtime/browser/get_sign_verify_key.ts000066400000000000000000000013431437043056600231120ustar00rootroot00000000000000import crypto, { isCryptoKey } from './webcrypto.js' import { checkSigCryptoKey } from '../../lib/crypto_key.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import { types } from './is_key_like.js' export default function getCryptoKey(alg: string, key: unknown, usage: KeyUsage) { if (isCryptoKey(key)) { checkSigCryptoKey(key, alg, usage) return key } if (key instanceof Uint8Array) { if (!alg.startsWith('HS')) { throw new TypeError(invalidKeyInput(key, ...types)) } return crypto.subtle.importKey( 'raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage], ) } throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')) } jose-4.11.4/src/runtime/browser/is_key_like.ts000066400000000000000000000003161437043056600213450ustar00rootroot00000000000000import type { KeyLike } from '../../types.d' import { isCryptoKey } from './webcrypto.js' export default (key: unknown): key is KeyLike => { return isCryptoKey(key) } export const types = ['CryptoKey'] jose-4.11.4/src/runtime/browser/jwk_to_key.ts000066400000000000000000000120611437043056600212230ustar00rootroot00000000000000import { isCloudflareWorkers } from './env.js' import crypto from './webcrypto.js' import type { JWKImportFunction } from '../interfaces.d' import { JOSENotSupported } from '../../util/errors.js' import type { JWK } from '../../types.d' import { decode as base64url } from './base64url.js' function subtleMapping(jwk: JWK): { algorithm: RsaHashedImportParams | EcKeyAlgorithm | Algorithm keyUsages: KeyUsage[] } { let algorithm: RsaHashedImportParams | EcKeyAlgorithm | Algorithm let keyUsages: KeyUsage[] switch (jwk.kty) { case 'oct': { switch (jwk.alg) { case 'HS256': case 'HS384': case 'HS512': algorithm = { name: 'HMAC', hash: `SHA-${jwk.alg.slice(-3)}` } keyUsages = ['sign', 'verify'] break case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': throw new JOSENotSupported(`${jwk.alg} keys cannot be imported as CryptoKey instances`) case 'A128GCM': case 'A192GCM': case 'A256GCM': case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': algorithm = { name: 'AES-GCM' } keyUsages = ['encrypt', 'decrypt'] break case 'A128KW': case 'A192KW': case 'A256KW': algorithm = { name: 'AES-KW' } keyUsages = ['wrapKey', 'unwrapKey'] break case 'PBES2-HS256+A128KW': case 'PBES2-HS384+A192KW': case 'PBES2-HS512+A256KW': algorithm = { name: 'PBKDF2' } keyUsages = ['deriveBits'] break default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value') } break } case 'RSA': { switch (jwk.alg) { case 'PS256': case 'PS384': case 'PS512': algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` } keyUsages = jwk.d ? ['sign'] : ['verify'] break case 'RS256': case 'RS384': case 'RS512': algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` } keyUsages = jwk.d ? ['sign'] : ['verify'] break case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': algorithm = { name: 'RSA-OAEP', hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`, } keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'] break default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value') } break } case 'EC': { switch (jwk.alg) { case 'ES256': algorithm = { name: 'ECDSA', namedCurve: 'P-256' } keyUsages = jwk.d ? ['sign'] : ['verify'] break case 'ES384': algorithm = { name: 'ECDSA', namedCurve: 'P-384' } keyUsages = jwk.d ? ['sign'] : ['verify'] break case 'ES512': algorithm = { name: 'ECDSA', namedCurve: 'P-521' } keyUsages = jwk.d ? ['sign'] : ['verify'] break case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': algorithm = { name: 'ECDH', namedCurve: jwk.crv! } keyUsages = jwk.d ? ['deriveBits'] : [] break default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value') } break } case 'OKP': { switch (jwk.alg) { case 'EdDSA': algorithm = { name: jwk.crv! } keyUsages = jwk.d ? ['sign'] : ['verify'] break case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': algorithm = { name: jwk.crv! } keyUsages = jwk.d ? ['deriveBits'] : [] break default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value') } break } default: throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value') } return { algorithm, keyUsages } } const parse: JWKImportFunction = async (jwk: JWK): Promise => { const { algorithm, keyUsages } = subtleMapping(jwk) const rest: [RsaHashedImportParams | EcKeyAlgorithm | Algorithm, boolean, KeyUsage[]] = [ algorithm, jwk.ext ?? false, jwk.key_ops ?? keyUsages, ] if (algorithm.name === 'PBKDF2') { return crypto.subtle.importKey('raw', base64url(jwk.k!), ...rest) } const keyData: JWK = { ...jwk } delete keyData.alg delete keyData.use try { return await crypto.subtle.importKey('jwk', keyData, ...rest) } catch (err) { if ( algorithm.name === 'Ed25519' && (err)?.name === 'NotSupportedError' && isCloudflareWorkers() ) { rest[0] = { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' } return await crypto.subtle.importKey('jwk', keyData, ...rest) } throw err } } export default parse jose-4.11.4/src/runtime/browser/key_to_jwk.ts000066400000000000000000000014741437043056600212310ustar00rootroot00000000000000import crypto, { isCryptoKey } from './webcrypto.js' import type { JWKExportFunction } from '../interfaces.d' import type { JWK } from '../../types.d' import invalidKeyInput from '../../lib/invalid_key_input.js' import { encode as base64url } from './base64url.js' import { types } from './is_key_like.js' const keyToJWK: JWKExportFunction = async (key: unknown): Promise => { if (key instanceof Uint8Array) { return { kty: 'oct', k: base64url(key), } } if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')) } if (!key.extractable) { throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK') } const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key) return jwk } export default keyToJWK jose-4.11.4/src/runtime/browser/pbes2kw.ts000066400000000000000000000044011437043056600204320ustar00rootroot00000000000000import type { Pbes2KWDecryptFunction, Pbes2KWEncryptFunction } from '../interfaces.d' import random from './random.js' import { p2s as concatSalt } from '../../lib/buffer_utils.js' import { encode as base64url } from './base64url.js' import { wrap, unwrap } from './aeskw.js' import checkP2s from '../../lib/check_p2s.js' import crypto, { isCryptoKey } from './webcrypto.js' import { checkEncCryptoKey } from '../../lib/crypto_key.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import { types } from './is_key_like.js' function getCryptoKey(key: unknown, alg: string) { if (key instanceof Uint8Array) { return crypto.subtle.importKey('raw', key, 'PBKDF2', false, ['deriveBits']) } if (isCryptoKey(key)) { checkEncCryptoKey(key, alg, 'deriveBits', 'deriveKey') return key } throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')) } async function deriveKey(p2s: Uint8Array, alg: string, p2c: number, key: unknown) { checkP2s(p2s) const salt = concatSalt(alg, p2s) const keylen = parseInt(alg.slice(13, 16), 10) const subtleAlg = { hash: `SHA-${alg.slice(8, 11)}`, iterations: p2c, name: 'PBKDF2', salt, } const wrapAlg = { length: keylen, name: 'AES-KW', } const cryptoKey = await getCryptoKey(key, alg) if (cryptoKey.usages.includes('deriveBits')) { return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen)) } if (cryptoKey.usages.includes('deriveKey')) { return crypto.subtle.deriveKey(subtleAlg, cryptoKey, wrapAlg, false, ['wrapKey', 'unwrapKey']) } throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"') } export const encrypt: Pbes2KWEncryptFunction = async ( alg: string, key: unknown, cek: Uint8Array, p2c: number = 2048, p2s: Uint8Array = random(new Uint8Array(16)), ) => { const derived = await deriveKey(p2s, alg, p2c, key) const encryptedKey = await wrap(alg.slice(-6), derived, cek) return { encryptedKey, p2c, p2s: base64url(p2s) } } export const decrypt: Pbes2KWDecryptFunction = async ( alg: string, key: unknown, encryptedKey: Uint8Array, p2c: number, p2s: Uint8Array, ) => { const derived = await deriveKey(p2s, alg, p2c, key) return unwrap(alg.slice(-6), derived, encryptedKey) } jose-4.11.4/src/runtime/browser/random.ts000066400000000000000000000001301437043056600203300ustar00rootroot00000000000000import crypto from './webcrypto.js' export default crypto.getRandomValues.bind(crypto) jose-4.11.4/src/runtime/browser/rsaes.ts000066400000000000000000000041421437043056600201740ustar00rootroot00000000000000import type { RsaEsDecryptFunction, RsaEsEncryptFunction } from '../interfaces.d' import subtleAlgorithm from './subtle_rsaes.js' import bogusWebCrypto from './bogus.js' import crypto, { isCryptoKey } from './webcrypto.js' import { checkEncCryptoKey } from '../../lib/crypto_key.js' import checkKeyLength from './check_key_length.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import { types } from './is_key_like.js' export const encrypt: RsaEsEncryptFunction = async (alg: string, key: unknown, cek: Uint8Array) => { if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types)) } checkEncCryptoKey(key, alg, 'encrypt', 'wrapKey') checkKeyLength(alg, key) if (key.usages.includes('encrypt')) { return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek)) } if (key.usages.includes('wrapKey')) { // we're importing the cek to end up with CryptoKey instance that can be wrapped, the algorithm used is irrelevant const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto) return new Uint8Array( await crypto.subtle.wrapKey('raw', cryptoKeyCek, key, subtleAlgorithm(alg)), ) } throw new TypeError( 'RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation', ) } export const decrypt: RsaEsDecryptFunction = async ( alg: string, key: unknown, encryptedKey: Uint8Array, ) => { if (!isCryptoKey(key)) { throw new TypeError(invalidKeyInput(key, ...types)) } checkEncCryptoKey(key, alg, 'decrypt', 'unwrapKey') checkKeyLength(alg, key) if (key.usages.includes('decrypt')) { return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey)) } if (key.usages.includes('unwrapKey')) { const cryptoKeyCek = await crypto.subtle.unwrapKey( 'raw', encryptedKey, key, subtleAlgorithm(alg), ...bogusWebCrypto, ) return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek)) } throw new TypeError( 'RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation', ) } jose-4.11.4/src/runtime/browser/sign.ts000066400000000000000000000010701437043056600200140ustar00rootroot00000000000000import type { SignFunction } from '../interfaces.d' import subtleAlgorithm from './subtle_dsa.js' import crypto from './webcrypto.js' import checkKeyLength from './check_key_length.js' import getSignKey from './get_sign_verify_key.js' const sign: SignFunction = async (alg, key: unknown, data) => { const cryptoKey = await getSignKey(alg, key, 'sign') checkKeyLength(alg, cryptoKey) const signature = await crypto.subtle.sign( subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data, ) return new Uint8Array(signature) } export default sign jose-4.11.4/src/runtime/browser/subtle_dsa.ts000066400000000000000000000020741437043056600212060ustar00rootroot00000000000000import { isCloudflareWorkers } from './env.js' import { JOSENotSupported } from '../../util/errors.js' export default function subtleDsa(alg: string, algorithm: KeyAlgorithm | EcKeyAlgorithm) { const hash = `SHA-${alg.slice(-3)}` switch (alg) { case 'HS256': case 'HS384': case 'HS512': return { hash, name: 'HMAC' } case 'PS256': case 'PS384': case 'PS512': // @ts-expect-error return { hash, name: 'RSA-PSS', saltLength: alg.slice(-3) >> 3 } case 'RS256': case 'RS384': case 'RS512': return { hash, name: 'RSASSA-PKCS1-v1_5' } case 'ES256': case 'ES384': case 'ES512': return { hash, name: 'ECDSA', namedCurve: (algorithm).namedCurve } case 'EdDSA': if (isCloudflareWorkers() && algorithm.name === 'NODE-ED25519') { return { name: 'NODE-ED25519', namedCurve: 'NODE-ED25519' } } return { name: algorithm.name } default: throw new JOSENotSupported( `alg ${alg} is not supported either by JOSE or your javascript runtime`, ) } } jose-4.11.4/src/runtime/browser/subtle_rsaes.ts000066400000000000000000000006031437043056600215500ustar00rootroot00000000000000import { JOSENotSupported } from '../../util/errors.js' export default function subtleRsaEs(alg: string) { switch (alg) { case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': return 'RSA-OAEP' default: throw new JOSENotSupported( `alg ${alg} is not supported either by JOSE or your javascript runtime`, ) } } jose-4.11.4/src/runtime/browser/timing_safe_equal.ts000066400000000000000000000010631437043056600225320ustar00rootroot00000000000000import type { TimingSafeEqual } from '../interfaces.d' const timingSafeEqual: TimingSafeEqual = (a, b) => { if (!(a instanceof Uint8Array)) { throw new TypeError('First argument must be a buffer') } if (!(b instanceof Uint8Array)) { throw new TypeError('Second argument must be a buffer') } if (a.length !== b.length) { throw new TypeError('Input buffers must have the same length') } const len = a.length let out = 0 let i = -1 while (++i < len) { out |= a[i] ^ b[i] } return out === 0 } export default timingSafeEqual jose-4.11.4/src/runtime/browser/verify.ts000066400000000000000000000011501437043056600203570ustar00rootroot00000000000000import type { VerifyFunction } from '../interfaces.d' import subtleAlgorithm from './subtle_dsa.js' import crypto from './webcrypto.js' import checkKeyLength from './check_key_length.js' import getVerifyKey from './get_sign_verify_key.js' const verify: VerifyFunction = async (alg, key: unknown, signature, data) => { const cryptoKey = await getVerifyKey(alg, key, 'verify') checkKeyLength(alg, cryptoKey) const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm) try { return await crypto.subtle.verify(algorithm, cryptoKey, signature, data) } catch { return false } } export default verify jose-4.11.4/src/runtime/browser/webcrypto.ts000066400000000000000000000001571437043056600210770ustar00rootroot00000000000000export default crypto export const isCryptoKey = (key: unknown): key is CryptoKey => key instanceof CryptoKey jose-4.11.4/src/runtime/browser/zlib.ts000066400000000000000000000012571437043056600200230ustar00rootroot00000000000000import { JOSENotSupported } from '../../util/errors.js' import type { InflateFunction, DeflateFunction } from '../../types.d' export const inflate: InflateFunction = async () => { throw new JOSENotSupported( 'JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.', ) } export const deflate: DeflateFunction = async () => { throw new JOSENotSupported( 'JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.', ) } jose-4.11.4/src/runtime/interfaces.d.ts000066400000000000000000000043741437043056600177500ustar00rootroot00000000000000import type { JWK, KeyLike } from '../types.d' import type { PEMImportOptions } from '../key/import.js' type AsyncOrSync = Promise | T export interface TimingSafeEqual { (a: Uint8Array, b: Uint8Array): boolean } export interface SignFunction { (alg: string, key: unknown, data: Uint8Array): Promise } export interface VerifyFunction { (alg: string, key: unknown, signature: Uint8Array, data: Uint8Array): Promise } export interface AesKwWrapFunction { (alg: string, key: unknown, cek: Uint8Array): AsyncOrSync } export interface AesKwUnwrapFunction { (alg: string, key: unknown, encryptedKey: Uint8Array): AsyncOrSync } export interface RsaEsEncryptFunction { (alg: string, key: unknown, cek: Uint8Array): AsyncOrSync } export interface RsaEsDecryptFunction { (alg: string, key: unknown, encryptedKey: Uint8Array): AsyncOrSync } export interface Pbes2KWEncryptFunction { (alg: string, key: unknown, cek: Uint8Array, p2c?: number, p2s?: Uint8Array): Promise<{ encryptedKey: Uint8Array p2c: number p2s: string }> } export interface Pbes2KWDecryptFunction { ( alg: string, key: unknown, encryptedKey: Uint8Array, p2c: number, p2s: Uint8Array, ): Promise } export interface EncryptFunction { (enc: string, plaintext: Uint8Array, cek: unknown, iv: Uint8Array, aad: Uint8Array): AsyncOrSync<{ ciphertext: Uint8Array tag: Uint8Array }> } export interface DecryptFunction { ( enc: string, cek: unknown, ciphertext: Uint8Array, iv: Uint8Array, tag: Uint8Array, additionalData: Uint8Array, ): AsyncOrSync } export interface FetchFunction { (url: URL, timeout: number, options?: any): Promise<{ [propName: string]: unknown }> } export interface DigestFunction { (digest: 'sha256' | 'sha384' | 'sha512', data: Uint8Array): AsyncOrSync } export interface JWKImportFunction { (jwk: JWK): AsyncOrSync } export interface PEMImportFunction { (pem: string, alg: string, options?: PEMImportOptions): AsyncOrSync } interface ExportFunction { (key: unknown): AsyncOrSync } export type JWKExportFunction = ExportFunction export type PEMExportFunction = ExportFunction jose-4.11.4/src/runtime/node/000077500000000000000000000000001437043056600157505ustar00rootroot00000000000000jose-4.11.4/src/runtime/node/aeskw.ts000066400000000000000000000043301437043056600174320ustar00rootroot00000000000000import { Buffer } from 'buffer' import { KeyObject, createDecipheriv, createCipheriv, createSecretKey } from 'crypto' import { JOSENotSupported } from '../../util/errors.js' import type { AesKwUnwrapFunction, AesKwWrapFunction } from '../interfaces.d' import { concat } from '../../lib/buffer_utils.js' import { isCryptoKey } from './webcrypto.js' import { checkEncCryptoKey } from '../../lib/crypto_key.js' import isKeyObject from './is_key_object.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import supported from './ciphers.js' import { types } from './is_key_like.js' function checkKeySize(key: KeyObject, alg: string) { if (key.symmetricKeySize! << 3 !== parseInt(alg.slice(1, 4), 10)) { throw new TypeError(`Invalid key size for alg: ${alg}`) } } function ensureKeyObject(key: unknown, alg: string, usage: KeyUsage) { if (isKeyObject(key)) { return key } if (key instanceof Uint8Array) { return createSecretKey(key) } if (isCryptoKey(key)) { checkEncCryptoKey(key, alg, usage) return KeyObject.from(key) } throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')) } export const wrap: AesKwWrapFunction = (alg: string, key: unknown, cek: Uint8Array) => { const size = parseInt(alg.slice(1, 4), 10) const algorithm = `aes${size}-wrap` if (!supported(algorithm)) { throw new JOSENotSupported( `alg ${alg} is not supported either by JOSE or your javascript runtime`, ) } const keyObject = ensureKeyObject(key, alg, 'wrapKey') checkKeySize(keyObject, alg) const cipher = createCipheriv(algorithm, keyObject, Buffer.alloc(8, 0xa6)) return concat(cipher.update(cek), cipher.final()) } export const unwrap: AesKwUnwrapFunction = ( alg: string, key: unknown, encryptedKey: Uint8Array, ) => { const size = parseInt(alg.slice(1, 4), 10) const algorithm = `aes${size}-wrap` if (!supported(algorithm)) { throw new JOSENotSupported( `alg ${alg} is not supported either by JOSE or your javascript runtime`, ) } const keyObject = ensureKeyObject(key, alg, 'unwrapKey') checkKeySize(keyObject, alg) const cipher = createDecipheriv(algorithm, keyObject, Buffer.alloc(8, 0xa6)) return concat(cipher.update(encryptedKey), cipher.final()) } jose-4.11.4/src/runtime/node/asn1.ts000066400000000000000000000030611437043056600171620ustar00rootroot00000000000000import { createPrivateKey, createPublicKey, KeyObject } from 'crypto' import { Buffer } from 'buffer' import { isCryptoKey } from './webcrypto.js' import type { PEMExportFunction, PEMImportFunction } from '../interfaces.d' import isKeyObject from './is_key_object.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import { types } from './is_key_like.js' const genericExport = ( keyType: 'private' | 'public', keyFormat: 'spki' | 'pkcs8', key: unknown, ) => { let keyObject: KeyObject if (isCryptoKey(key)) { if (!key.extractable) { throw new TypeError('CryptoKey is not extractable') } keyObject = KeyObject.from(key) } else if (isKeyObject(key)) { keyObject = key } else { throw new TypeError(invalidKeyInput(key, ...types)) } if (keyObject.type !== keyType) { throw new TypeError(`key is not a ${keyType} key`) } return keyObject.export({ format: 'pem', type: keyFormat }) } export const toSPKI: PEMExportFunction = (key) => { return genericExport('public', 'spki', key) } export const toPKCS8: PEMExportFunction = (key) => { return genericExport('private', 'pkcs8', key) } export const fromPKCS8: PEMImportFunction = (pem) => createPrivateKey({ key: Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, ''), 'base64'), type: 'pkcs8', format: 'der', }) export const fromSPKI: PEMImportFunction = (pem) => createPublicKey({ key: Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, ''), 'base64'), type: 'spki', format: 'der', }) jose-4.11.4/src/runtime/node/asn1_sequence_decoder.ts000066400000000000000000000023731437043056600225440ustar00rootroot00000000000000const tagInteger = 0x02 const tagSequence = 0x30 /** The end justifies the means. */ export default class Asn1SequenceDecoder { buffer: Buffer offset: number constructor(buffer: Buffer) { if (buffer[0] !== tagSequence) { throw new TypeError() } this.buffer = buffer this.offset = 1 const len = this.decodeLength() if (len !== buffer.length - this.offset) { throw new TypeError() } } decodeLength() { let length = this.buffer[this.offset++] if (length & 0x80) { // Long form. const nBytes = length & ~0x80 length = 0 for (let i = 0; i < nBytes; i++) length = (length << 8) | this.buffer[this.offset + i] this.offset += nBytes } return length } unsignedInteger() { if (this.buffer[this.offset++] !== tagInteger) { throw new TypeError() } let length = this.decodeLength() // There may be exactly one leading zero (if the next byte's MSB is set). if (this.buffer[this.offset] === 0) { this.offset++ length-- } const result = this.buffer.slice(this.offset, this.offset + length) this.offset += length return result } end() { if (this.offset !== this.buffer.length) { throw new TypeError() } } } jose-4.11.4/src/runtime/node/asn1_sequence_encoder.ts000066400000000000000000000061731437043056600225600ustar00rootroot00000000000000import { Buffer } from 'buffer' import { JOSENotSupported } from '../../util/errors.js' const tagInteger = 0x02 const tagBitStr = 0x03 const tagOctStr = 0x04 const tagSequence = 0x30 const bZero = Buffer.from([0x00]) const bTagInteger = Buffer.from([tagInteger]) const bTagBitStr = Buffer.from([tagBitStr]) const bTagSequence = Buffer.from([tagSequence]) const bTagOctStr = Buffer.from([tagOctStr]) const encodeLength = (len: number) => { if (len < 128) return Buffer.from([len]) const buffer = Buffer.alloc(5) buffer.writeUInt32BE(len, 1) let offset = 1 while (buffer[offset] === 0) offset++ buffer[offset - 1] = 0x80 | (5 - offset) return buffer.slice(offset - 1) } const oids = new Map([ ['P-256', Buffer.from('06 08 2A 86 48 CE 3D 03 01 07'.replace(/ /g, ''), 'hex')], ['secp256k1', Buffer.from('06 05 2B 81 04 00 0A'.replace(/ /g, ''), 'hex')], ['P-384', Buffer.from('06 05 2B 81 04 00 22'.replace(/ /g, ''), 'hex')], ['P-521', Buffer.from('06 05 2B 81 04 00 23'.replace(/ /g, ''), 'hex')], ['ecPublicKey', Buffer.from('06 07 2A 86 48 CE 3D 02 01'.replace(/ /g, ''), 'hex')], ['X25519', Buffer.from('06 03 2B 65 6E'.replace(/ /g, ''), 'hex')], ['X448', Buffer.from('06 03 2B 65 6F'.replace(/ /g, ''), 'hex')], ['Ed25519', Buffer.from('06 03 2B 65 70'.replace(/ /g, ''), 'hex')], ['Ed448', Buffer.from('06 03 2B 65 71'.replace(/ /g, ''), 'hex')], ]) /** The end justifies the means. */ export default class DumbAsn1Encoder { length: number elements: Buffer[] constructor() { this.length = 0 this.elements = [] } oidFor(oid: string) { const bOid = oids.get(oid) if (!bOid) { throw new JOSENotSupported('Invalid or unsupported OID') } this.elements.push(bOid) this.length += bOid.length } zero() { this.elements.push(bTagInteger, Buffer.from([0x01]), bZero) this.length += 3 } one() { this.elements.push(bTagInteger, Buffer.from([0x01]), Buffer.from([0x01])) this.length += 3 } unsignedInteger(integer: Buffer) { if (integer[0] & 0x80) { const len = encodeLength(integer.length + 1) this.elements.push(bTagInteger, len, bZero, integer) this.length += 2 + len.length + integer.length } else { let i = 0 while (integer[i] === 0 && (integer[i + 1] & 0x80) === 0) i++ const len = encodeLength(integer.length - i) this.elements.push(bTagInteger, encodeLength(integer.length - i), integer.slice(i)) this.length += 1 + len.length + integer.length - i } } octStr(octStr: Buffer) { const len = encodeLength(octStr.length) this.elements.push(bTagOctStr, encodeLength(octStr.length), octStr) this.length += 1 + len.length + octStr.length } bitStr(bitS: Buffer) { const len = encodeLength(bitS.length + 1) this.elements.push(bTagBitStr, encodeLength(bitS.length + 1), bZero, bitS) this.length += 1 + len.length + bitS.length + 1 } add(seq: Buffer) { this.elements.push(seq) this.length += seq.length } end(tag = bTagSequence) { const len = encodeLength(this.length) return Buffer.concat([tag, len, ...this.elements], 1 + len.length + this.length) } } jose-4.11.4/src/runtime/node/base64url.ts000066400000000000000000000014761437043056600201370ustar00rootroot00000000000000import { Buffer } from 'buffer' import { decoder } from '../../lib/buffer_utils.js' let encode: (input: Uint8Array | string) => string function normalize(input: string | Uint8Array) { let encoded = input if (encoded instanceof Uint8Array) { encoded = decoder.decode(encoded) } return encoded } if (Buffer.isEncoding('base64url')) { encode = (input) => Buffer.from(input).toString('base64url') } else { encode = (input) => Buffer.from(input).toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_') } export const decodeBase64 = (input: string) => Buffer.from(input, 'base64') export const encodeBase64 = (input: Uint8Array | string) => Buffer.from(input).toString('base64') export { encode } export const decode = (input: Uint8Array | string) => Buffer.from(normalize(input), 'base64') jose-4.11.4/src/runtime/node/cbc_tag.ts000066400000000000000000000007041437043056600177030ustar00rootroot00000000000000import { createHmac } from 'crypto' import { concat, uint64be } from '../../lib/buffer_utils.js' export default function cbcTag( aad: Uint8Array, iv: Uint8Array, ciphertext: Uint8Array, macSize: number, macKey: Uint8Array, keySize: number, ) { const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3)) const hmac = createHmac(`sha${macSize}`, macKey) hmac.update(macData) return hmac.digest().slice(0, keySize >> 3) } jose-4.11.4/src/runtime/node/check_cek_length.ts000066400000000000000000000024431437043056600215630ustar00rootroot00000000000000import { KeyObject } from 'crypto' import { JWEInvalid, JOSENotSupported } from '../../util/errors.js' import isKeyObject from './is_key_object.js' const checkCekLength = (enc: string, cek: KeyObject | Uint8Array) => { let expected: number switch (enc) { case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': expected = parseInt(enc.slice(-3), 10) break case 'A128GCM': case 'A192GCM': case 'A256GCM': expected = parseInt(enc.slice(1, 4), 10) break default: throw new JOSENotSupported( `Content Encryption Algorithm ${enc} is not supported either by JOSE or your javascript runtime`, ) } if (cek instanceof Uint8Array) { const actual = cek.byteLength << 3 if (actual !== expected) { throw new JWEInvalid( `Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`, ) } return } if (isKeyObject(cek) && cek.type === 'secret') { const actual = cek.symmetricKeySize! << 3 if (actual !== expected) { throw new JWEInvalid( `Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`, ) } return } throw new TypeError('Invalid Content Encryption Key type') } export default checkCekLength jose-4.11.4/src/runtime/node/check_modulus_length.ts000066400000000000000000000031121437043056600225030ustar00rootroot00000000000000import type { KeyObject } from 'crypto' export const weakMap: WeakMap = new WeakMap() const getLength = (buf: Buffer, index: number): number => { let len = buf.readUInt8(1) // Short form if ((len & 0x80) === 0) { if (index === 0) { return len } return getLength(buf.subarray(2 + len), index - 1) } // Long form const num = len & 0x7f len = 0 for (let i = 0; i < num; i++) { len <<= 8 const j = buf.readUInt8(2 + i) len |= j } if (index === 0) { return len } return getLength(buf.subarray(2 + len), index - 1) } const getLengthOfSeqIndex = (sequence: Buffer, index: number): number => { const len = sequence.readUInt8(1) // short form if ((len & 0x80) === 0) { return getLength(sequence.subarray(2), index) } // Long form const num = len & 0x7f return getLength(sequence.subarray(2 + num), index) } const getModulusLength = (key: KeyObject): number => { if (weakMap.has(key)) { return weakMap.get(key)! } const modulusLength: number = key.asymmetricKeyDetails?.modulusLength ?? (getLengthOfSeqIndex( key.export({ format: 'der', type: 'pkcs1' }), key.type === 'private' ? 1 : 0, ) - 1) << 3 weakMap.set(key, modulusLength) return modulusLength } export const setModulusLength = (keyObject: KeyObject, modulusLength: number) => { weakMap.set(keyObject, modulusLength) } export default (key: KeyObject, alg: string) => { if (getModulusLength(key) < 2048) { throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`) } } jose-4.11.4/src/runtime/node/ciphers.ts000066400000000000000000000002551437043056600177570ustar00rootroot00000000000000import { getCiphers } from 'crypto' let ciphers: Set export default (algorithm: string) => { ciphers ||= new Set(getCiphers()) return ciphers.has(algorithm) } jose-4.11.4/src/runtime/node/decrypt.ts000066400000000000000000000066671437043056600200110ustar00rootroot00000000000000import { createDecipheriv, KeyObject } from 'crypto' import type { CipherGCMTypes } from 'crypto' import type { DecryptFunction } from '../interfaces.d' import checkIvLength from '../../lib/check_iv_length.js' import checkCekLength from './check_cek_length.js' import { concat } from '../../lib/buffer_utils.js' import { JOSENotSupported, JWEDecryptionFailed } from '../../util/errors.js' import timingSafeEqual from './timing_safe_equal.js' import cbcTag from './cbc_tag.js' import { isCryptoKey } from './webcrypto.js' import { checkEncCryptoKey } from '../../lib/crypto_key.js' import isKeyObject from './is_key_object.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import supported from './ciphers.js' import { types } from './is_key_like.js' function cbcDecrypt( enc: string, cek: KeyObject | Uint8Array, ciphertext: Uint8Array, iv: Uint8Array, tag: Uint8Array, aad: Uint8Array, ) { const keySize = parseInt(enc.slice(1, 4), 10) if (isKeyObject(cek)) { cek = cek.export() } const encKey = cek.subarray(keySize >> 3) const macKey = cek.subarray(0, keySize >> 3) const macSize = parseInt(enc.slice(-3), 10) const algorithm = `aes-${keySize}-cbc` if (!supported(algorithm)) { throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`) } const expectedTag = cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) let macCheckPassed!: boolean try { macCheckPassed = timingSafeEqual(tag, expectedTag) } catch { // } if (!macCheckPassed) { throw new JWEDecryptionFailed() } let plaintext!: Uint8Array try { const decipher = createDecipheriv(algorithm, encKey, iv) plaintext = concat(decipher.update(ciphertext), decipher.final()) } catch { // } if (!plaintext) { throw new JWEDecryptionFailed() } return plaintext } function gcmDecrypt( enc: string, cek: KeyObject | Uint8Array, ciphertext: Uint8Array, iv: Uint8Array, tag: Uint8Array, aad: Uint8Array, ) { const keySize = parseInt(enc.slice(1, 4), 10) const algorithm = `aes-${keySize}-gcm` if (!supported(algorithm)) { throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`) } try { const decipher = createDecipheriv(algorithm, cek, iv, { authTagLength: 16 }) decipher.setAuthTag(tag) if (aad.byteLength) { decipher.setAAD(aad, { plaintextLength: ciphertext.length }) } const plaintext = decipher.update(ciphertext) decipher.final() return plaintext } catch { throw new JWEDecryptionFailed() } } const decrypt: DecryptFunction = ( enc: string, cek: unknown, ciphertext: Uint8Array, iv: Uint8Array, tag: Uint8Array, aad: Uint8Array, ) => { let key: KeyObject | Uint8Array if (isCryptoKey(cek)) { checkEncCryptoKey(cek, enc, 'decrypt') key = KeyObject.from(cek) } else if (cek instanceof Uint8Array || isKeyObject(cek)) { key = cek } else { throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')) } checkCekLength(enc, key) checkIvLength(enc, iv) switch (enc) { case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': return cbcDecrypt(enc, key, ciphertext, iv, tag, aad) case 'A128GCM': case 'A192GCM': case 'A256GCM': return gcmDecrypt(enc, key, ciphertext, iv, tag, aad) default: throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm') } } export default decrypt jose-4.11.4/src/runtime/node/digest.ts000066400000000000000000000004201437043056600175730ustar00rootroot00000000000000import { createHash } from 'crypto' import type { DigestFunction } from '../interfaces.d' const digest: DigestFunction = ( algorithm: 'sha256' | 'sha384' | 'sha512', data: Uint8Array, ): Uint8Array => createHash(algorithm).update(data).digest() export default digest jose-4.11.4/src/runtime/node/dsa_digest.ts000066400000000000000000000010551437043056600204270ustar00rootroot00000000000000import { JOSENotSupported } from '../../util/errors.js' export default function dsaDigest(alg: string) { switch (alg) { case 'PS256': case 'RS256': case 'ES256': case 'ES256K': return 'sha256' case 'PS384': case 'RS384': case 'ES384': return 'sha384' case 'PS512': case 'RS512': case 'ES512': return 'sha512' case 'EdDSA': return undefined default: throw new JOSENotSupported( `alg ${alg} is not supported either by JOSE or your javascript runtime`, ) } } jose-4.11.4/src/runtime/node/ecdhes.ts000066400000000000000000000045631437043056600175630ustar00rootroot00000000000000import { diffieHellman, generateKeyPair as generateKeyPairCb, KeyObject } from 'crypto' import { promisify } from 'util' import getNamedCurve from './get_named_curve.js' import { encoder, concat, uint32be, lengthAndInput, concatKdf } from '../../lib/buffer_utils.js' import { JOSENotSupported } from '../../util/errors.js' import { isCryptoKey } from './webcrypto.js' import { checkEncCryptoKey } from '../../lib/crypto_key.js' import isKeyObject from './is_key_object.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import { types } from './is_key_like.js' const generateKeyPair = promisify(generateKeyPairCb) export async function deriveKey( publicKee: unknown, privateKee: unknown, algorithm: string, keyLength: number, apu: Uint8Array = new Uint8Array(0), apv: Uint8Array = new Uint8Array(0), ) { let publicKey: KeyObject if (isCryptoKey(publicKee)) { checkEncCryptoKey(publicKee, 'ECDH') publicKey = KeyObject.from(publicKee) } else if (isKeyObject(publicKee)) { publicKey = publicKee } else { throw new TypeError(invalidKeyInput(publicKee, ...types)) } let privateKey: KeyObject if (isCryptoKey(privateKee)) { checkEncCryptoKey(privateKee, 'ECDH', 'deriveBits') privateKey = KeyObject.from(privateKee) } else if (isKeyObject(privateKee)) { privateKey = privateKee } else { throw new TypeError(invalidKeyInput(privateKee, ...types)) } const value = concat( lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength), ) const sharedSecret = diffieHellman({ privateKey, publicKey }) return concatKdf(sharedSecret, keyLength, value) } export async function generateEpk(kee: unknown) { let key: KeyObject if (isCryptoKey(kee)) { key = KeyObject.from(kee) } else if (isKeyObject(kee)) { key = kee } else { throw new TypeError(invalidKeyInput(kee, ...types)) } switch (key.asymmetricKeyType) { case 'x25519': return generateKeyPair('x25519') case 'x448': { return generateKeyPair('x448') } case 'ec': { const namedCurve = getNamedCurve(key) return generateKeyPair('ec', { namedCurve }) } default: throw new JOSENotSupported('Invalid or unsupported EPK') } } export const ecdhAllowed = (key: unknown) => ['P-256', 'P-384', 'P-521', 'X25519', 'X448'].includes(getNamedCurve(key)) jose-4.11.4/src/runtime/node/encrypt.ts000066400000000000000000000056541437043056600200160ustar00rootroot00000000000000import { createCipheriv, KeyObject } from 'crypto' import type { CipherGCMTypes } from 'crypto' import type { EncryptFunction } from '../interfaces.d' import checkIvLength from '../../lib/check_iv_length.js' import checkCekLength from './check_cek_length.js' import { concat } from '../../lib/buffer_utils.js' import cbcTag from './cbc_tag.js' import { isCryptoKey } from './webcrypto.js' import { checkEncCryptoKey } from '../../lib/crypto_key.js' import isKeyObject from './is_key_object.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import { JOSENotSupported } from '../../util/errors.js' import supported from './ciphers.js' import { types } from './is_key_like.js' function cbcEncrypt( enc: string, plaintext: Uint8Array, cek: KeyObject | Uint8Array, iv: Uint8Array, aad: Uint8Array, ) { const keySize = parseInt(enc.slice(1, 4), 10) if (isKeyObject(cek)) { cek = cek.export() } const encKey = cek.subarray(keySize >> 3) const macKey = cek.subarray(0, keySize >> 3) const algorithm = `aes-${keySize}-cbc` if (!supported(algorithm)) { throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`) } const cipher = createCipheriv(algorithm, encKey, iv) const ciphertext = concat(cipher.update(plaintext), cipher.final()) const macSize = parseInt(enc.slice(-3), 10) const tag = cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) return { ciphertext, tag } } function gcmEncrypt( enc: string, plaintext: Uint8Array, cek: KeyObject | Uint8Array, iv: Uint8Array, aad: Uint8Array, ) { const keySize = parseInt(enc.slice(1, 4), 10) const algorithm = `aes-${keySize}-gcm` if (!supported(algorithm)) { throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`) } const cipher = createCipheriv(algorithm, cek, iv, { authTagLength: 16 }) if (aad.byteLength) { cipher.setAAD(aad, { plaintextLength: plaintext.length }) } const ciphertext = cipher.update(plaintext) cipher.final() const tag = cipher.getAuthTag() return { ciphertext, tag } } const encrypt: EncryptFunction = ( enc: string, plaintext: Uint8Array, cek: unknown, iv: Uint8Array, aad: Uint8Array, ) => { let key: KeyObject | Uint8Array if (isCryptoKey(cek)) { checkEncCryptoKey(cek, enc, 'encrypt') key = KeyObject.from(cek) } else if (cek instanceof Uint8Array || isKeyObject(cek)) { key = cek } else { throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array')) } checkCekLength(enc, key) checkIvLength(enc, iv) switch (enc) { case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': return cbcEncrypt(enc, plaintext, key, iv, aad) case 'A128GCM': case 'A192GCM': case 'A256GCM': return gcmEncrypt(enc, plaintext, key, iv, aad) default: throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm') } } export default encrypt jose-4.11.4/src/runtime/node/env.ts000066400000000000000000000000711437043056600171060ustar00rootroot00000000000000export function isCloudflareWorkers() { return false } jose-4.11.4/src/runtime/node/fetch_jwks.ts000066400000000000000000000030151437043056600204460ustar00rootroot00000000000000import * as http from 'http' import * as https from 'https' import { once } from 'events' import type { ClientRequest, IncomingMessage } from 'http' import type { RequestOptions } from 'https' import type { FetchFunction } from '../interfaces.d' import { JOSEError, JWKSTimeout } from '../../util/errors.js' import { concat, decoder } from '../../lib/buffer_utils.js' type AcceptedRequestOptions = Pick const fetchJwks: FetchFunction = async ( url: URL, timeout: number, options: AcceptedRequestOptions, ) => { let get: (...args: Parameters) => ClientRequest switch (url.protocol) { case 'https:': get = https.get break case 'http:': get = http.get break default: throw new TypeError('Unsupported URL protocol.') } const { agent, headers } = options const req = get(url.href, { agent, timeout, headers, }) const [response] = <[IncomingMessage]>( await Promise.race([once(req, 'response'), once(req, 'timeout')]) ) // timeout reached if (!response) { req.destroy() throw new JWKSTimeout() } if (response.statusCode !== 200) { throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response') } const parts = [] for await (const part of response) { parts.push(part) } try { return JSON.parse(decoder.decode(concat(...parts))) } catch { throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON') } } export default fetchJwks jose-4.11.4/src/runtime/node/flags.ts000066400000000000000000000006411437043056600174150ustar00rootroot00000000000000const [major, minor] = process.versions.node.split('.').map((str) => parseInt(str, 10)) export const oneShotCallback = major >= 16 || (major === 15 && minor >= 13) export const rsaPssParams = !('electron' in process.versions) && (major >= 17 || (major === 16 && minor >= 9)) export const jwkExport = major >= 16 || (major === 15 && minor >= 9) export const jwkImport = major >= 16 || (major === 15 && minor >= 12) jose-4.11.4/src/runtime/node/generate.ts000066400000000000000000000066211437043056600201170ustar00rootroot00000000000000import { createSecretKey, generateKeyPair as generateKeyPairCb } from 'crypto' import { promisify } from 'util' import random from './random.js' import { setModulusLength } from './check_modulus_length.js' import { JOSENotSupported } from '../../util/errors.js' import type { GenerateKeyPairOptions } from '../../key/generate_key_pair.js' import type { GenerateSecretOptions } from '../../key/generate_secret.js' const generate = promisify(generateKeyPairCb) // @ts-expect-error export async function generateSecret(alg: string, options?: GenerateSecretOptions) { let length: number switch (alg) { case 'HS256': case 'HS384': case 'HS512': case 'A128CBC-HS256': case 'A192CBC-HS384': case 'A256CBC-HS512': length = parseInt(alg.slice(-3), 10) break case 'A128KW': case 'A192KW': case 'A256KW': case 'A128GCMKW': case 'A192GCMKW': case 'A256GCMKW': case 'A128GCM': case 'A192GCM': case 'A256GCM': length = parseInt(alg.slice(1, 4), 10) break default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value') } return createSecretKey(random(new Uint8Array(length >> 3))) } export async function generateKeyPair(alg: string, options?: GenerateKeyPairOptions) { switch (alg) { case 'RS256': case 'RS384': case 'RS512': case 'PS256': case 'PS384': case 'PS512': case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': case 'RSA1_5': { const modulusLength = options?.modulusLength ?? 2048 if (typeof modulusLength !== 'number' || modulusLength < 2048) { throw new JOSENotSupported( 'Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used', ) } const keypair = await generate('rsa', { modulusLength, publicExponent: 0x10001, }) setModulusLength(keypair.privateKey, modulusLength) setModulusLength(keypair.publicKey, modulusLength) return keypair } case 'ES256': return generate('ec', { namedCurve: 'P-256' }) case 'ES256K': return generate('ec', { namedCurve: 'secp256k1' }) case 'ES384': return generate('ec', { namedCurve: 'P-384' }) case 'ES512': return generate('ec', { namedCurve: 'P-521' }) case 'EdDSA': { switch (options?.crv) { case undefined: case 'Ed25519': return generate('ed25519') case 'Ed448': return generate('ed448') default: throw new JOSENotSupported( 'Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448', ) } } case 'ECDH-ES': case 'ECDH-ES+A128KW': case 'ECDH-ES+A192KW': case 'ECDH-ES+A256KW': const crv = options?.crv ?? 'P-256' switch (crv) { case undefined: case 'P-256': case 'P-384': case 'P-521': return generate('ec', { namedCurve: crv }) case 'X25519': return generate('x25519') case 'X448': return generate('x448') default: throw new JOSENotSupported( 'Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448', ) } default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value') } } jose-4.11.4/src/runtime/node/get_named_curve.ts000066400000000000000000000054151437043056600214540ustar00rootroot00000000000000import { Buffer } from 'buffer' import { createPublicKey, KeyObject } from 'crypto' import { JOSENotSupported } from '../../util/errors.js' import { isCryptoKey } from './webcrypto.js' import isKeyObject from './is_key_object.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import { types } from './is_key_like.js' const p256 = Buffer.from([42, 134, 72, 206, 61, 3, 1, 7]) const p384 = Buffer.from([43, 129, 4, 0, 34]) const p521 = Buffer.from([43, 129, 4, 0, 35]) const secp256k1 = Buffer.from([43, 129, 4, 0, 10]) export const weakMap: WeakMap = new WeakMap() const namedCurveToJOSE = (namedCurve: string) => { switch (namedCurve) { case 'prime256v1': return 'P-256' case 'secp384r1': return 'P-384' case 'secp521r1': return 'P-521' case 'secp256k1': return 'secp256k1' default: throw new JOSENotSupported('Unsupported key curve for this operation') } } const getNamedCurve = (kee: unknown, raw?: boolean): string => { let key: KeyObject if (isCryptoKey(kee)) { key = KeyObject.from(kee) } else if (isKeyObject(kee)) { key = kee } else { throw new TypeError(invalidKeyInput(kee, ...types)) } if (key.type === 'secret') { throw new TypeError('only "private" or "public" type keys can be used for this operation') } switch (key.asymmetricKeyType) { case 'ed25519': case 'ed448': return `Ed${key.asymmetricKeyType.slice(2)}` case 'x25519': case 'x448': return `X${key.asymmetricKeyType.slice(1)}` case 'ec': { if (weakMap.has(key)) { return weakMap.get(key)! } let namedCurve = key.asymmetricKeyDetails?.namedCurve if (!namedCurve && key.type === 'private') { namedCurve = getNamedCurve(createPublicKey(key), true) } else if (!namedCurve) { const buf = key.export({ format: 'der', type: 'spki' }) const i = buf[1] < 128 ? 14 : 15 const len = buf[i] const curveOid = buf.slice(i + 1, i + 1 + len) if (curveOid.equals(p256)) { namedCurve = 'prime256v1' } else if (curveOid.equals(p384)) { namedCurve = 'secp384r1' } else if (curveOid.equals(p521)) { namedCurve = 'secp521r1' } else if (curveOid.equals(secp256k1)) { namedCurve = 'secp256k1' } else { throw new JOSENotSupported('Unsupported key curve for this operation') } } if (raw) return namedCurve const curve = namedCurveToJOSE(namedCurve) weakMap.set(key, curve) return curve } default: throw new TypeError('Invalid asymmetric key type for this operation') } } export function setCurve(keyObject: KeyObject, curve: string) { weakMap.set(keyObject, curve) } export default getNamedCurve jose-4.11.4/src/runtime/node/get_sign_verify_key.ts000066400000000000000000000013421437043056600223530ustar00rootroot00000000000000import { KeyObject, createSecretKey } from 'crypto' import { isCryptoKey } from './webcrypto.js' import { checkSigCryptoKey } from '../../lib/crypto_key.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import { types } from './is_key_like.js' export default function getSignVerifyKey(alg: string, key: unknown, usage: KeyUsage) { if (key instanceof Uint8Array) { if (!alg.startsWith('HS')) { throw new TypeError(invalidKeyInput(key, ...types)) } return createSecretKey(key) } if (key instanceof KeyObject) { return key } if (isCryptoKey(key)) { checkSigCryptoKey(key, alg, usage) return KeyObject.from(key) } throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')) } jose-4.11.4/src/runtime/node/hmac_digest.ts000066400000000000000000000006021437043056600205650ustar00rootroot00000000000000import { JOSENotSupported } from '../../util/errors.js' export default function hmacDigest(alg: string) { switch (alg) { case 'HS256': return 'sha256' case 'HS384': return 'sha384' case 'HS512': return 'sha512' default: throw new JOSENotSupported( `alg ${alg} is not supported either by JOSE or your javascript runtime`, ) } } jose-4.11.4/src/runtime/node/is_key_like.ts000066400000000000000000000005671437043056600206170ustar00rootroot00000000000000import type { KeyLike } from '../../types.d' import webcrypto, { isCryptoKey } from './webcrypto.js' import isKeyObject from './is_key_object.js' export default (key: unknown): key is KeyLike => isKeyObject(key) || isCryptoKey(key) const types = ['KeyObject'] // @ts-ignore if (globalThis.CryptoKey || webcrypto?.CryptoKey) { types.push('CryptoKey') } export { types } jose-4.11.4/src/runtime/node/is_key_object.ts000066400000000000000000000003731437043056600211340ustar00rootroot00000000000000import { KeyObject } from 'crypto' import * as util from 'util' export default util.types.isKeyObject ? (obj: unknown): obj is KeyObject => util.types.isKeyObject(obj) : (obj: unknown): obj is KeyObject => obj != null && obj instanceof KeyObject jose-4.11.4/src/runtime/node/jwk_to_key.ts000066400000000000000000000104451437043056600204710ustar00rootroot00000000000000import { Buffer } from 'buffer' import { createPrivateKey, createPublicKey, createSecretKey } from 'crypto' import type { KeyObject, PublicKeyInput, PrivateKeyInput } from 'crypto' import type { JWKImportFunction } from '../interfaces.d' import { decode as base64url } from './base64url.js' import { JOSENotSupported } from '../../util/errors.js' import { setCurve } from './get_named_curve.js' import { setModulusLength } from './check_modulus_length.js' import Asn1SequenceEncoder from './asn1_sequence_encoder.js' import type { JWK } from '../../types.d' import { jwkImport } from './flags.js' const parse: JWKImportFunction = (jwk: JWK): KeyObject => { if (jwkImport && jwk.kty !== 'oct') { return jwk.d ? createPrivateKey({ format: 'jwk', key: jwk }) : createPublicKey({ format: 'jwk', key: jwk }) } switch (jwk.kty) { case 'oct': { return createSecretKey(base64url(jwk.k!)) } case 'RSA': { const enc = new Asn1SequenceEncoder() const isPrivate = jwk.d !== undefined const modulus = Buffer.from(jwk.n!, 'base64') const exponent = Buffer.from(jwk.e!, 'base64') if (isPrivate) { enc.zero() enc.unsignedInteger(modulus) enc.unsignedInteger(exponent) enc.unsignedInteger(Buffer.from(jwk.d!, 'base64')) enc.unsignedInteger(Buffer.from(jwk.p!, 'base64')) enc.unsignedInteger(Buffer.from(jwk.q!, 'base64')) enc.unsignedInteger(Buffer.from(jwk.dp!, 'base64')) enc.unsignedInteger(Buffer.from(jwk.dq!, 'base64')) enc.unsignedInteger(Buffer.from(jwk.qi!, 'base64')) } else { enc.unsignedInteger(modulus) enc.unsignedInteger(exponent) } const der = enc.end() const createInput: PublicKeyInput & PrivateKeyInput = { key: der, format: 'der', type: 'pkcs1', } const keyObject = isPrivate ? createPrivateKey(createInput) : createPublicKey(createInput) setModulusLength(keyObject, modulus.length << 3) return keyObject } case 'EC': { const enc = new Asn1SequenceEncoder() const isPrivate = jwk.d !== undefined const pub = Buffer.concat([ Buffer.alloc(1, 4), Buffer.from(jwk.x!, 'base64'), Buffer.from(jwk.y!, 'base64'), ]) if (isPrivate) { enc.zero() const enc$1 = new Asn1SequenceEncoder() enc$1.oidFor('ecPublicKey') enc$1.oidFor(jwk.crv!) enc.add(enc$1.end()) const enc$2 = new Asn1SequenceEncoder() enc$2.one() enc$2.octStr(Buffer.from(jwk.d!, 'base64')) const enc$3 = new Asn1SequenceEncoder() enc$3.bitStr(pub) const f2 = enc$3.end(Buffer.from([0xa1])) enc$2.add(f2) const f = enc$2.end() const enc$4 = new Asn1SequenceEncoder() enc$4.add(f) const f3 = enc$4.end(Buffer.from([0x04])) enc.add(f3) const der = enc.end() const keyObject = createPrivateKey({ key: der, format: 'der', type: 'pkcs8' }) setCurve(keyObject, jwk.crv!) return keyObject } const enc$1 = new Asn1SequenceEncoder() enc$1.oidFor('ecPublicKey') enc$1.oidFor(jwk.crv!) enc.add(enc$1.end()) enc.bitStr(pub) const der = enc.end() const keyObject = createPublicKey({ key: der, format: 'der', type: 'spki' }) setCurve(keyObject, jwk.crv!) return keyObject } case 'OKP': { const enc = new Asn1SequenceEncoder() const isPrivate = jwk.d !== undefined if (isPrivate) { enc.zero() const enc$1 = new Asn1SequenceEncoder() enc$1.oidFor(jwk.crv!) enc.add(enc$1.end()) const enc$2 = new Asn1SequenceEncoder() enc$2.octStr(Buffer.from(jwk.d!, 'base64')) const f = enc$2.end(Buffer.from([0x04])) enc.add(f) const der = enc.end() return createPrivateKey({ key: der, format: 'der', type: 'pkcs8' }) } const enc$1 = new Asn1SequenceEncoder() enc$1.oidFor(jwk.crv!) enc.add(enc$1.end()) enc.bitStr(Buffer.from(jwk.x!, 'base64')) const der = enc.end() return createPublicKey({ key: der, format: 'der', type: 'spki' }) } default: throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value') } } export default parse jose-4.11.4/src/runtime/node/key_to_jwk.ts000066400000000000000000000122471437043056600204730ustar00rootroot00000000000000import { KeyObject, createPublicKey } from 'crypto' import type { JWKExportFunction } from '../interfaces.d' import type { JWK } from '../../types.d' import { encode as base64url } from './base64url.js' import Asn1SequenceDecoder from './asn1_sequence_decoder.js' import { JOSENotSupported } from '../../util/errors.js' import getNamedCurve from './get_named_curve.js' import { isCryptoKey } from './webcrypto.js' import isKeyObject from './is_key_object.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import { types } from './is_key_like.js' import { jwkExport } from './flags.js' const keyToJWK: JWKExportFunction = (key: unknown): JWK => { let keyObject: KeyObject if (isCryptoKey(key)) { if (!key.extractable) { throw new TypeError('CryptoKey is not extractable') } keyObject = KeyObject.from(key) } else if (isKeyObject(key)) { keyObject = key } else if (key instanceof Uint8Array) { return { kty: 'oct', k: base64url(key), } } else { throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')) } if (jwkExport) { if ( keyObject.type !== 'secret' && !['rsa', 'ec', 'ed25519', 'x25519', 'ed448', 'x448'].includes(keyObject.asymmetricKeyType!) ) { throw new JOSENotSupported('Unsupported key asymmetricKeyType') } return keyObject.export({ format: 'jwk' }) } switch (keyObject.type) { case 'secret': return { kty: 'oct', k: base64url(keyObject.export()), } case 'private': case 'public': { switch (keyObject.asymmetricKeyType) { case 'rsa': { const der = keyObject.export({ format: 'der', type: 'pkcs1' }) const dec = new Asn1SequenceDecoder(der) if (keyObject.type === 'private') { dec.unsignedInteger() // TODO: Don't ignore this } const n = base64url(dec.unsignedInteger()) const e = base64url(dec.unsignedInteger()) let jwk: JWK if (keyObject.type === 'private') { jwk = { d: base64url(dec.unsignedInteger()), p: base64url(dec.unsignedInteger()), q: base64url(dec.unsignedInteger()), dp: base64url(dec.unsignedInteger()), dq: base64url(dec.unsignedInteger()), qi: base64url(dec.unsignedInteger()), } } dec.end() return { kty: 'RSA', n, e, ...jwk! } } case 'ec': { const crv = getNamedCurve(keyObject) let len: number let offset: number let correction: number switch (crv) { case 'secp256k1': len = 64 offset = 31 + 2 correction = -1 break case 'P-256': len = 64 offset = 34 + 2 correction = -1 break case 'P-384': len = 96 offset = 33 + 2 correction = -3 break case 'P-521': len = 132 offset = 33 + 2 correction = -3 break default: throw new JOSENotSupported('Unsupported curve') } if (keyObject.type === 'public') { const der = keyObject.export({ type: 'spki', format: 'der' }) return { kty: 'EC', crv, x: base64url(der.subarray(-len, -len / 2)), y: base64url(der.subarray(-len / 2)), } } const der = keyObject.export({ type: 'pkcs8', format: 'der' }) if (der.length < 100) { offset += correction } return { ...keyToJWK(createPublicKey(keyObject)), d: base64url(der.subarray(offset, offset + len / 2)), } } case 'ed25519': case 'x25519': { const crv = getNamedCurve(keyObject) if (keyObject.type === 'public') { const der = keyObject.export({ type: 'spki', format: 'der' }) return { kty: 'OKP', crv, x: base64url(der.subarray(-32)), } } const der = keyObject.export({ type: 'pkcs8', format: 'der' }) return { ...keyToJWK(createPublicKey(keyObject)), d: base64url(der.subarray(-32)), } } case 'ed448': case 'x448': { const crv = getNamedCurve(keyObject) if (keyObject.type === 'public') { const der = keyObject.export({ type: 'spki', format: 'der' }) return { kty: 'OKP', crv, x: base64url(der.subarray(crv === 'Ed448' ? -57 : -56)), } } const der = keyObject.export({ type: 'pkcs8', format: 'der' }) return { ...keyToJWK(createPublicKey(keyObject)), d: base64url(der.subarray(crv === 'Ed448' ? -57 : -56)), } } default: throw new JOSENotSupported('Unsupported key asymmetricKeyType') } } default: throw new JOSENotSupported('Unsupported key type') } } export default keyToJWK jose-4.11.4/src/runtime/node/node_key.ts000066400000000000000000000063171437043056600201240ustar00rootroot00000000000000import { constants } from 'crypto' import type { KeyObject, SignKeyObjectInput } from 'crypto' import getNamedCurve from './get_named_curve.js' import { JOSENotSupported } from '../../util/errors.js' import checkModulusLength from './check_modulus_length.js' import { rsaPssParams } from './flags.js' const PSS = { padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: constants.RSA_PSS_SALTLEN_DIGEST, } const ecCurveAlgMap = new Map([ ['ES256', 'P-256'], ['ES256K', 'secp256k1'], ['ES384', 'P-384'], ['ES512', 'P-521'], ]) export default function keyForCrypto(alg: string, key: KeyObject): KeyObject | SignKeyObjectInput { switch (alg) { case 'EdDSA': if (!['ed25519', 'ed448'].includes(key.asymmetricKeyType!)) { throw new TypeError( 'Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448', ) } return key case 'RS256': case 'RS384': case 'RS512': if (key.asymmetricKeyType !== 'rsa') { throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa') } checkModulusLength(key, alg) return key case rsaPssParams && 'PS256': case rsaPssParams && 'PS384': case rsaPssParams && 'PS512': if (key.asymmetricKeyType === 'rsa-pss') { const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails! const length = parseInt(alg.slice(-3), 10) if ( hashAlgorithm !== undefined && (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm) ) { throw new TypeError( `Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${alg}`, ) } if (saltLength !== undefined && saltLength > length >> 3) { throw new TypeError( `Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${alg}`, ) } } else if (key.asymmetricKeyType !== 'rsa') { throw new TypeError( 'Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss', ) } checkModulusLength(key, alg) return { key, ...PSS } case !rsaPssParams && 'PS256': case !rsaPssParams && 'PS384': case !rsaPssParams && 'PS512': if (key.asymmetricKeyType !== 'rsa') { throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa') } checkModulusLength(key, alg) return { key, ...PSS } case 'ES256': case 'ES256K': case 'ES384': case 'ES512': { if (key.asymmetricKeyType !== 'ec') { throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ec') } const actual = getNamedCurve(key) const expected = ecCurveAlgMap.get(alg) if (actual !== expected) { throw new TypeError( `Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`, ) } return { dsaEncoding: 'ieee-p1363', key } } default: throw new JOSENotSupported( `alg ${alg} is not supported either by JOSE or your javascript runtime`, ) } } jose-4.11.4/src/runtime/node/pbes2kw.ts000066400000000000000000000040021437043056600176710ustar00rootroot00000000000000import { promisify } from 'util' import { KeyObject, pbkdf2 as pbkdf2cb } from 'crypto' import type { Pbes2KWDecryptFunction, Pbes2KWEncryptFunction } from '../interfaces.d' import random from './random.js' import { p2s as concatSalt } from '../../lib/buffer_utils.js' import { encode as base64url } from './base64url.js' import { wrap, unwrap } from './aeskw.js' import checkP2s from '../../lib/check_p2s.js' import { isCryptoKey } from './webcrypto.js' import { checkEncCryptoKey } from '../../lib/crypto_key.js' import isKeyObject from './is_key_object.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import { types } from './is_key_like.js' const pbkdf2 = promisify(pbkdf2cb) function getPassword(key: unknown, alg: string) { if (isKeyObject(key)) { return key.export() } if (key instanceof Uint8Array) { return key } if (isCryptoKey(key)) { checkEncCryptoKey(key, alg, 'deriveBits', 'deriveKey') return KeyObject.from(key).export() } throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array')) } export const encrypt: Pbes2KWEncryptFunction = async ( alg: string, key: unknown, cek: Uint8Array, p2c: number = 2048, p2s: Uint8Array = random(new Uint8Array(16)), ) => { checkP2s(p2s) const salt = concatSalt(alg, p2s) const keylen = parseInt(alg.slice(13, 16), 10) >> 3 const password = getPassword(key, alg) const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`) const encryptedKey = await wrap(alg.slice(-6), derivedKey, cek) return { encryptedKey, p2c, p2s: base64url(p2s) } } export const decrypt: Pbes2KWDecryptFunction = async ( alg: string, key: unknown, encryptedKey: Uint8Array, p2c: number, p2s: Uint8Array, ) => { checkP2s(p2s) const salt = concatSalt(alg, p2s) const keylen = parseInt(alg.slice(13, 16), 10) >> 3 const password = getPassword(key, alg) const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`) return unwrap(alg.slice(-6), derivedKey, encryptedKey) } jose-4.11.4/src/runtime/node/random.ts000066400000000000000000000000631437043056600175770ustar00rootroot00000000000000export { randomFillSync as default } from 'crypto' jose-4.11.4/src/runtime/node/rsaes.ts000066400000000000000000000043421437043056600174400ustar00rootroot00000000000000import { KeyObject, publicEncrypt, constants, privateDecrypt } from 'crypto' import type { RsaEsDecryptFunction, RsaEsEncryptFunction } from '../interfaces.d' import checkModulusLength from './check_modulus_length.js' import { isCryptoKey } from './webcrypto.js' import { checkEncCryptoKey } from '../../lib/crypto_key.js' import isKeyObject from './is_key_object.js' import invalidKeyInput from '../../lib/invalid_key_input.js' import { types } from './is_key_like.js' const checkKey = (key: KeyObject, alg: string) => { if (key.asymmetricKeyType !== 'rsa') { throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa') } checkModulusLength(key, alg) } const resolvePadding = (alg: string) => { switch (alg) { case 'RSA-OAEP': case 'RSA-OAEP-256': case 'RSA-OAEP-384': case 'RSA-OAEP-512': return constants.RSA_PKCS1_OAEP_PADDING case 'RSA1_5': return constants.RSA_PKCS1_PADDING default: return undefined } } const resolveOaepHash = (alg: string) => { switch (alg) { case 'RSA-OAEP': return 'sha1' case 'RSA-OAEP-256': return 'sha256' case 'RSA-OAEP-384': return 'sha384' case 'RSA-OAEP-512': return 'sha512' default: return undefined } } function ensureKeyObject(key: unknown, alg: string, ...usages: KeyUsage[]) { if (isKeyObject(key)) { return key } if (isCryptoKey(key)) { checkEncCryptoKey(key, alg, ...usages) return KeyObject.from(key) } throw new TypeError(invalidKeyInput(key, ...types)) } export const encrypt: RsaEsEncryptFunction = (alg: string, key: unknown, cek: Uint8Array) => { const padding = resolvePadding(alg) const oaepHash = resolveOaepHash(alg) const keyObject = ensureKeyObject(key, alg, 'wrapKey', 'encrypt') checkKey(keyObject, alg) return publicEncrypt({ key: keyObject, oaepHash, padding }, cek) } export const decrypt: RsaEsDecryptFunction = ( alg: string, key: unknown, encryptedKey: Uint8Array, ) => { const padding = resolvePadding(alg) const oaepHash = resolveOaepHash(alg) const keyObject = ensureKeyObject(key, alg, 'unwrapKey', 'decrypt') checkKey(keyObject, alg) return privateDecrypt({ key: keyObject, oaepHash, padding }, encryptedKey) } jose-4.11.4/src/runtime/node/sign.ts000066400000000000000000000015701437043056600172630ustar00rootroot00000000000000import * as crypto from 'crypto' import { promisify } from 'util' import type { SignFunction } from '../interfaces.d' import nodeDigest from './dsa_digest.js' import hmacDigest from './hmac_digest.js' import nodeKey from './node_key.js' import getSignKey from './get_sign_verify_key.js' let oneShotSign: ( alg: string | undefined, data: Uint8Array, key: ReturnType, ) => Promise | Uint8Array if (crypto.sign.length > 3) { oneShotSign = promisify(crypto.sign) } else { oneShotSign = crypto.sign } const sign: SignFunction = async (alg, key: unknown, data) => { const keyObject = getSignKey(alg, key, 'sign') if (alg.startsWith('HS')) { const hmac = crypto.createHmac(hmacDigest(alg), keyObject) hmac.update(data) return hmac.digest() } return oneShotSign(nodeDigest(alg), data, nodeKey(alg, keyObject)) } export default sign jose-4.11.4/src/runtime/node/timing_safe_equal.ts000066400000000000000000000002701437043056600217730ustar00rootroot00000000000000import { timingSafeEqual as impl } from 'crypto' import type { TimingSafeEqual } from '../interfaces.d' const timingSafeEqual: TimingSafeEqual = impl export default timingSafeEqual jose-4.11.4/src/runtime/node/verify.ts000066400000000000000000000023231437043056600176240ustar00rootroot00000000000000import * as crypto from 'crypto' import { promisify } from 'util' import type { VerifyFunction } from '../interfaces.d' import nodeDigest from './dsa_digest.js' import nodeKey from './node_key.js' import sign from './sign.js' import getVerifyKey from './get_sign_verify_key.js' import { oneShotCallback } from './flags.js' let oneShotVerify: ( alg: string | undefined, data: Uint8Array, key: ReturnType, signature: Uint8Array, ) => Promise | boolean if (crypto.verify.length > 4 && oneShotCallback) { oneShotVerify = promisify(crypto.verify) } else { oneShotVerify = crypto.verify } const verify: VerifyFunction = async (alg, key: unknown, signature, data) => { const keyObject = getVerifyKey(alg, key, 'verify') if (alg.startsWith('HS')) { const expected = await sign(alg, keyObject, data) const actual = signature try { return crypto.timingSafeEqual(actual, expected) } catch { // handle incorrect signature lengths return false } } const algorithm = nodeDigest(alg) const keyInput = nodeKey(alg, keyObject) try { return await oneShotVerify(algorithm, data, keyInput, signature) } catch { return false } } export default verify jose-4.11.4/src/runtime/node/webcrypto.ts000066400000000000000000000005171437043056600203410ustar00rootroot00000000000000import * as crypto from 'crypto' import * as util from 'util' // @ts-ignore const webcrypto = crypto.webcrypto export default webcrypto export const isCryptoKey = util.types.isCryptoKey ? (key: unknown): key is CryptoKey => util.types.isCryptoKey(key) : // @ts-expect-error (key: unknown): key is CryptoKey => false jose-4.11.4/src/runtime/node/zlib.ts000066400000000000000000000006601437043056600172620ustar00rootroot00000000000000import { promisify } from 'util' import { inflateRaw as inflateRawCb, deflateRaw as deflateRawCb } from 'zlib' import type { InflateFunction, DeflateFunction } from '../../types.d' const inflateRaw = promisify(inflateRawCb) const deflateRaw = promisify(deflateRawCb) export const inflate: InflateFunction = (input: Uint8Array) => inflateRaw(input) export const deflate: DeflateFunction = (input: Uint8Array) => deflateRaw(input) jose-4.11.4/src/types.d.ts000066400000000000000000000500711437043056600153010ustar00rootroot00000000000000/** * KeyLike are runtime-specific classes representing asymmetric keys or symmetric secrets. These are * instances of [CryptoKey](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) and * additionally [KeyObject](https://nodejs.org/api/crypto.html#class-keyobject) in Node.js runtime. * [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) * instances are also accepted as symmetric secret representation only. * * [Key Import Functions](../modules/key_import.md#readme) can be used to import PEM, or JWK * formatted asymmetric keys and certificates to these runtime-specific representations. * * In Node.js the [Buffer](https://nodejs.org/api/buffer.html#buffer) class is a subclass of * Uint8Array and so Buffer can be provided for symmetric secrets as well. * * [KeyObject](https://nodejs.org/api/crypto.html#class-keyobject) is a representation of a * key/secret available in the Node.js runtime. In addition to the import functions of this library * you may use the runtime APIs * [crypto.createPublicKey](https://nodejs.org/api/crypto.html#cryptocreatepublickeykey), * [crypto.createPrivateKey](https://nodejs.org/api/crypto.html#cryptocreateprivatekeykey), and * [crypto.createSecretKey](https://nodejs.org/api/crypto.html#cryptocreatesecretkeykey-encoding) to * obtain a KeyObject from your existing key material. * * [CryptoKey](https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey) is a representation of a * key/secret available in the Browser and Web-interoperable runtimes. In addition to the import * functions of this library you may use the * [SubtleCrypto.importKey](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey) * API to obtain a CryptoKey from your existing key material. * * @example Import a PEM-encoded SPKI Public Key * * ```js * const algorithm = 'ES256' * const spki = `-----BEGIN PUBLIC KEY----- * MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEFlHHWfLk0gLBbsLTcuCrbCqoHqmM * YJepMC+Q+Dd6RBmBiA41evUsNMwLeN+PNFqib+xwi9JkJ8qhZkq8Y/IzGg== * -----END PUBLIC KEY-----` * const ecPublicKey = await jose.importSPKI(spki, algorithm) * ``` * * @example Import a X.509 Certificate * * ```js * const algorithm = 'ES256' * const x509 = `-----BEGIN CERTIFICATE----- * MIIBXjCCAQSgAwIBAgIGAXvykuMKMAoGCCqGSM49BAMCMDYxNDAyBgNVBAMMK3Np * QXBNOXpBdk1VaXhXVWVGaGtjZXg1NjJRRzFyQUhXaV96UlFQTVpQaG8wHhcNMjEw * OTE3MDcwNTE3WhcNMjIwNzE0MDcwNTE3WjA2MTQwMgYDVQQDDCtzaUFwTTl6QXZN * VWl4V1VlRmhrY2V4NTYyUUcxckFIV2lfelJRUE1aUGhvMFkwEwYHKoZIzj0CAQYI * KoZIzj0DAQcDQgAE8PbPvCv5D5xBFHEZlBp/q5OEUymq7RIgWIi7tkl9aGSpYE35 * UH+kBKDnphJO3odpPZ5gvgKs2nwRWcrDnUjYLDAKBggqhkjOPQQDAgNIADBFAiEA * 1yyMTRe66MhEXID9+uVub7woMkNYd0LhSHwKSPMUUTkCIFQGsfm1ecXOpeGOufAh * v+A1QWZMuTWqYt+uh/YSRNDn * -----END CERTIFICATE-----` * const ecPublicKey = await jose.importX509(x509, algorithm) * ``` * * @example Import a PEM-encoded PKCS8 Private Key * * ```js * const algorithm = 'ES256' * const pkcs8 = `-----BEGIN PRIVATE KEY----- * MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgiyvo0X+VQ0yIrOaN * nlrnUclopnvuuMfoc8HHly3505OhRANCAAQWUcdZ8uTSAsFuwtNy4KtsKqgeqYxg * l6kwL5D4N3pEGYGIDjV69Sw0zAt43480WqJv7HCL0mQnyqFmSrxj8jMa * -----END PRIVATE KEY-----` * const ecPrivateKey = await jose.importPKCS8(pkcs8, algorithm) * ``` * * @example Import a JSON Web Key (JWK) * * ```js * const ecPublicKey = await jose.importJWK( * { * crv: 'P-256', * kty: 'EC', * x: 'ySK38C1jBdLwDsNWKzzBHqKYEE5Cgv-qjWvorUXk9fw', * y: '_LeQBw07cf5t57Iavn4j-BqJsAD1dpoz8gokd3sBsOo', * }, * 'ES256', * ) * * const rsaPublicKey = await jose.importJWK( * { * kty: 'RSA', * e: 'AQAB', * n: '12oBZRhCiZFJLcPg59LkZZ9mdhSMTKAQZYq32k_ti5SBB6jerkh-WzOMAO664r_qyLkqHUSp3u5SbXtseZEpN3XPWGKSxjsy-1JyEFTdLSYe6f9gfrmxkUF_7DTpq0gn6rntP05g2-wFW50YO7mosfdslfrTJYWHFhJALabAeYirYD7-9kqq9ebfFMF4sRRELbv9oi36As6Q9B3Qb5_C1rAzqfao_PCsf9EPsTZsVVVkA5qoIAr47lo1ipfiBPxUCCNSdvkmDTYgvvRm6ZoMjFbvOtgyts55fXKdMWv7I9HMD5HwE9uW839PWA514qhbcIsXEYSFMPMV6fnlsiZvQQ', * }, * 'PS256', * ) * ``` */ export type KeyLike = { type: string } /** * JSON Web Key ([JWK](https://www.rfc-editor.org/rfc/rfc7517)). "RSA", "EC", "OKP", and "oct" key * types are supported. */ export interface JWK { /** JWK "alg" (Algorithm) Parameter. */ alg?: string crv?: string d?: string dp?: string dq?: string e?: string /** JWK "ext" (Extractable) Parameter. */ ext?: boolean k?: string /** JWK "key_ops" (Key Operations) Parameter. */ key_ops?: string[] /** JWK "kid" (Key ID) Parameter. */ kid?: string /** JWK "kty" (Key Type) Parameter. */ kty?: string n?: string oth?: Array<{ d?: string r?: string t?: string }> p?: string q?: string qi?: string /** JWK "use" (Public Key Use) Parameter. */ use?: string x?: string y?: string /** JWK "x5c" (X.509 Certificate Chain) Parameter. */ x5c?: string[] /** JWK "x5t" (X.509 Certificate SHA-1 Thumbprint) Parameter. */ x5t?: string /** "x5t#S256" (X.509 Certificate SHA-256 Thumbprint) Parameter. */ 'x5t#S256'?: string /** JWK "x5u" (X.509 URL) Parameter. */ x5u?: string [propName: string]: unknown } /** * Generic Interface for consuming operations dynamic key resolution. No token components have been * verified at the time of this function call. * * If you cannot match a key suitable for the token, throw an error instead. * * @param protectedHeader JWE or JWS Protected Header. * @param token The consumed JWE or JWS token. */ export interface GetKeyFunction { (protectedHeader: T, token: T2): Promise | KeyLike | Uint8Array } /** * Flattened JWS definition for verify function inputs, allows payload as Uint8Array for detached * signature validation. */ export interface FlattenedJWSInput { /** * The "header" member MUST be present and contain the value JWS Unprotected Header when the JWS * Unprotected Header value is non- empty; otherwise, it MUST be absent. This value is represented * as an unencoded JSON object, rather than as a string. These Header Parameter values are not * integrity protected. */ header?: JWSHeaderParameters /** * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When RFC7797 * "b64": false is used the value passed may also be a Uint8Array. */ payload: string | Uint8Array /** * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWS Protected * Header)) when the JWS Protected Header value is non-empty; otherwise, it MUST be absent. These * Header Parameter values are integrity protected. */ protected?: string /** The "signature" member MUST be present and contain the value BASE64URL(JWS Signature). */ signature: string } /** * General JWS definition for verify function inputs, allows payload as Uint8Array for detached * signature validation. */ export interface GeneralJWSInput { /** * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When RFC7797 * "b64": false is used the value passed may also be a Uint8Array. */ payload: string | Uint8Array /** * The "signatures" member value MUST be an array of JSON objects. Each object represents a * signature or MAC over the JWS Payload and the JWS Protected Header. */ signatures: Omit[] } /** * Flattened JWS definition. Payload is returned as an empty string when JWS Unencoded Payload * Option [RFC7797](https://www.rfc-editor.org/rfc/rfc7797) is used. */ export interface FlattenedJWS extends Partial { payload: string signature: string } /** * General JWS definition. Payload is returned as an empty string when JWS Unencoded Payload Option * [RFC7797](https://www.rfc-editor.org/rfc/rfc7797) is used. */ export interface GeneralJWS { payload: string signatures: Omit[] } export interface JoseHeaderParameters { /** "kid" (Key ID) Header Parameter. */ kid?: string /** "x5t" (X.509 Certificate SHA-1 Thumbprint) Header Parameter. */ x5t?: string /** "x5c" (X.509 Certificate Chain) Header Parameter. */ x5c?: string[] /** "x5u" (X.509 URL) Header Parameter. */ x5u?: string /** "jku" (JWK Set URL) Header Parameter. */ jku?: string /** "jwk" (JSON Web Key) Header Parameter. */ jwk?: Pick /** "typ" (Type) Header Parameter. */ typ?: string /** "cty" (Content Type) Header Parameter. */ cty?: string } /** Recognized JWS Header Parameters, any other Header Members may also be present. */ export interface JWSHeaderParameters extends JoseHeaderParameters { /** JWS "alg" (Algorithm) Header Parameter. */ alg?: string /** * This JWS Extension Header Parameter modifies the JWS Payload representation and the JWS Signing * Input computation as per [RFC7797](https://www.rfc-editor.org/rfc/rfc7797). */ b64?: boolean /** JWS "crit" (Critical) Header Parameter. */ crit?: string[] /** Any other JWS Header member. */ [propName: string]: unknown } /** Recognized JWE Key Management-related Header Parameters. */ export interface JWEKeyManagementHeaderParameters { apu?: Uint8Array apv?: Uint8Array /** * @deprecated You should not use this parameter. It is only really intended for test and vector * validation purposes. */ p2c?: number /** * @deprecated You should not use this parameter. It is only really intended for test and vector * validation purposes. */ p2s?: Uint8Array /** * @deprecated You should not use this parameter. It is only really intended for test and vector * validation purposes. */ iv?: Uint8Array /** * @deprecated You should not use this parameter. It is only really intended for test and vector * validation purposes. */ epk?: KeyLike } /** Flattened JWE definition. */ export interface FlattenedJWE { /** * The "aad" member MUST be present and contain the value BASE64URL(JWE AAD)) when the JWE AAD * value is non-empty; otherwise, it MUST be absent. A JWE AAD value can be included to supply a * base64url-encoded value to be integrity protected but not encrypted. */ aad?: string /** The "ciphertext" member MUST be present and contain the value BASE64URL(JWE Ciphertext). */ ciphertext: string /** * The "encrypted_key" member MUST be present and contain the value BASE64URL(JWE Encrypted Key) * when the JWE Encrypted Key value is non-empty; otherwise, it MUST be absent. */ encrypted_key?: string /** * The "header" member MUST be present and contain the value JWE Per- Recipient Unprotected Header * when the JWE Per-Recipient Unprotected Header value is non-empty; otherwise, it MUST be absent. * This value is represented as an unencoded JSON object, rather than as a string. These Header * Parameter values are not integrity protected. */ header?: JWEHeaderParameters /** * The "iv" member MUST be present and contain the value BASE64URL(JWE Initialization Vector) when * the JWE Initialization Vector value is non-empty; otherwise, it MUST be absent. */ iv: string /** * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWE Protected * Header)) when the JWE Protected Header value is non-empty; otherwise, it MUST be absent. These * Header Parameter values are integrity protected. */ protected?: string /** * The "tag" member MUST be present and contain the value BASE64URL(JWE Authentication Tag) when * the JWE Authentication Tag value is non-empty; otherwise, it MUST be absent. */ tag: string /** * The "unprotected" member MUST be present and contain the value JWE Shared Unprotected Header * when the JWE Shared Unprotected Header value is non-empty; otherwise, it MUST be absent. This * value is represented as an unencoded JSON object, rather than as a string. These Header * Parameter values are not integrity protected. */ unprotected?: JWEHeaderParameters } export interface GeneralJWE extends Omit { recipients: Pick[] } /** Recognized JWE Header Parameters, any other Header members may also be present. */ export interface JWEHeaderParameters extends JoseHeaderParameters { /** JWE "alg" (Algorithm) Header Parameter. */ alg?: string /** JWE "enc" (Encryption Algorithm) Header Parameter. */ enc?: string /** JWE "crit" (Critical) Header Parameter. */ crit?: string[] /** JWE "zip" (Compression Algorithm) Header Parameter. */ zip?: string /** Any other JWE Header member. */ [propName: string]: unknown } /** Shared Interface with a "crit" property for all sign, verify, encrypt and decrypt operations. */ export interface CritOption { /** * An object with keys representing recognized "crit" (Critical) Header Parameter names. The value * for those is either `true` or `false`. `true` when the Header Parameter MUST be integrity * protected, `false` when it's irrelevant. * * This makes the "Extension Header Parameter "..." is not recognized" error go away. * * Use this when a given JWS/JWT/JWE profile requires the use of proprietary non-registered "crit" * (Critical) Header Parameters. This will only make sure the Header Parameter is syntactically * correct when provided and that it is optionally integrity protected. It will not process the * Header Parameter in any way or reject the operation if it is missing. You MUST still verify the * Header Parameter was present and process it according to the profile's validation steps after * the operation succeeds. * * The JWS extension Header Parameter `b64` is always recognized and processed properly. No other * registered Header Parameters that need this kind of default built-in treatment are currently * available. */ crit?: { [propName: string]: boolean } } /** JWE Decryption options. */ export interface DecryptOptions extends CritOption { /** A list of accepted JWE "alg" (Algorithm) Header Parameter values. */ keyManagementAlgorithms?: string[] /** * A list of accepted JWE "enc" (Encryption Algorithm) Header Parameter values. By default all * "enc" (Encryption Algorithm) values applicable for the used key/secret are allowed. */ contentEncryptionAlgorithms?: string[] /** * In a browser runtime you have to provide an implementation for Inflate Raw when you expect JWEs * with compressed plaintext. */ inflateRaw?: InflateFunction /** * (PBES2 Key Management Algorithms only) Maximum allowed "p2c" (PBES2 Count) Header Parameter * value. The PBKDF2 iteration count defines the algorithm's computational expense. By default * this value is set to 10000. */ maxPBES2Count?: number } /** JWE Deflate option. */ export interface DeflateOption { /** * In a browser runtime you have to provide an implementation for Deflate Raw when you will be * producing JWEs with compressed plaintext. */ deflateRaw?: DeflateFunction } /** JWE Encryption options. */ export interface EncryptOptions extends CritOption, DeflateOption {} /** JWT Claims Set verification options. */ export interface JWTClaimVerificationOptions { /** Expected JWT "aud" (Audience) Claim value(s). */ audience?: string | string[] /** * Expected clock tolerance * * - In seconds when number (e.g. 5) * - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). */ clockTolerance?: string | number /** Expected JWT "iss" (Issuer) Claim value(s). */ issuer?: string | string[] /** * Maximum time elapsed (in seconds) from the JWT "iat" (Issued At) Claim value. * * - In seconds when number (e.g. 5) * - Parsed as seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours"). */ maxTokenAge?: string | number /** Expected JWT "sub" (Subject) Claim value. */ subject?: string /** Expected JWT "typ" (Type) Header Parameter value. */ typ?: string /** Date to use when comparing NumericDate claims, defaults to `new Date()`. */ currentDate?: Date } /** JWS Verification options. */ export interface VerifyOptions extends CritOption { /** * A list of accepted JWS "alg" (Algorithm) Header Parameter values. By default all "alg" * (Algorithm) values applicable for the used key/secret are allowed. Note: "none" is never * accepted. */ algorithms?: string[] } /** JWS Signing options. */ export interface SignOptions extends CritOption {} /** Recognized JWT Claims Set members, any other members may also be present. */ export interface JWTPayload { /** * JWT Issuer * * @see [RFC7519#section-4.1.1](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.1) */ iss?: string /** * JWT Subject * * @see [RFC7519#section-4.1.2](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.2) */ sub?: string /** JWT Audience [RFC7519#section-4.1.3](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3). */ aud?: string | string[] /** * JWT ID * * @see [RFC7519#section-4.1.7](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7) */ jti?: string /** * JWT Not Before * * @see [RFC7519#section-4.1.5](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.5) */ nbf?: number /** * JWT Expiration Time * * @see [RFC7519#section-4.1.4](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4) */ exp?: number /** * JWT Issued At * * @see [RFC7519#section-4.1.6](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6) */ iat?: number /** Any other JWT Claim Set member. */ [propName: string]: unknown } /** * Deflate Raw implementation, e.g. promisified * [zlib.deflateRaw](https://nodejs.org/api/zlib.html#zlibdeflaterawbuffer-options-callback). */ export interface DeflateFunction { (input: Uint8Array): Promise } /** * Inflate Raw implementation, e.g. promisified * [zlib.inflateRaw](https://nodejs.org/api/zlib.html#zlibinflaterawbuffer-options-callback). */ export interface InflateFunction { (input: Uint8Array): Promise } export interface FlattenedDecryptResult { /** JWE AAD. */ additionalAuthenticatedData?: Uint8Array /** Plaintext. */ plaintext: Uint8Array /** JWE Protected Header. */ protectedHeader?: JWEHeaderParameters /** JWE Shared Unprotected Header. */ sharedUnprotectedHeader?: JWEHeaderParameters /** JWE Per-Recipient Unprotected Header. */ unprotectedHeader?: JWEHeaderParameters } export interface GeneralDecryptResult extends FlattenedDecryptResult {} export interface CompactDecryptResult { /** Plaintext. */ plaintext: Uint8Array /** JWE Protected Header. */ protectedHeader: CompactJWEHeaderParameters } export interface FlattenedVerifyResult { /** JWS Payload. */ payload: Uint8Array /** JWS Protected Header. */ protectedHeader?: JWSHeaderParameters /** JWS Unprotected Header. */ unprotectedHeader?: JWSHeaderParameters } export interface GeneralVerifyResult extends FlattenedVerifyResult {} export interface CompactVerifyResult { /** JWS Payload. */ payload: Uint8Array /** JWS Protected Header. */ protectedHeader: CompactJWSHeaderParameters } export interface JWTVerifyResult { /** JWT Claims Set. */ payload: JWTPayload /** JWS Protected Header. */ protectedHeader: JWTHeaderParameters } export interface JWTDecryptResult { /** JWT Claims Set. */ payload: JWTPayload /** JWE Protected Header. */ protectedHeader: CompactJWEHeaderParameters } export interface ResolvedKey { /** Key resolved from the key resolver function. */ key: KeyLike | Uint8Array } /** Recognized Compact JWS Header Parameters, any other Header Members may also be present. */ export interface CompactJWSHeaderParameters extends JWSHeaderParameters { alg: string } /** Recognized Signed JWT Header Parameters, any other Header Members may also be present. */ export interface JWTHeaderParameters extends CompactJWSHeaderParameters { b64?: true } /** Recognized Compact JWE Header Parameters, any other Header Members may also be present. */ export interface CompactJWEHeaderParameters extends JWEHeaderParameters { alg: string enc: string } /** JSON Web Key Set */ export interface JSONWebKeySet { keys: JWK[] } jose-4.11.4/src/util/000077500000000000000000000000001437043056600143155ustar00rootroot00000000000000jose-4.11.4/src/util/base64url.ts000066400000000000000000000010751437043056600164770ustar00rootroot00000000000000import * as base64url from '../runtime/base64url.js' /** * Utility function to encode a string or Uint8Array as a base64url string. * * @param input Value that will be base64url-encoded. */ interface Base64UrlEncode { (input: Uint8Array | string): string } /** * Utility function to decode a base64url encoded string. * * @param input Value that will be base64url-decoded. */ interface Base64UrlDecode { (input: Uint8Array | string): Uint8Array } export const encode: Base64UrlEncode = base64url.encode export const decode: Base64UrlDecode = base64url.decode jose-4.11.4/src/util/decode_jwt.ts000066400000000000000000000031111437043056600167700ustar00rootroot00000000000000import { decode as base64url } from './base64url.js' import { decoder } from '../lib/buffer_utils.js' import isObject from '../lib/is_object.js' import type { JWTPayload } from '../types.d' import { JWTInvalid } from './errors.js' /** * Decodes a signed JSON Web Token payload. This does not validate the JWT Claims Set types or * values. This does not validate the JWS Signature. For a proper Signed JWT Claims Set validation * and JWS signature verification use `jose.jwtVerify()`. For an encrypted JWT Claims Set validation * and JWE decryption use `jose.jwtDecrypt()`. * * @example Usage * * ```js * const claims = jose.decodeJwt(token) * console.log(claims) * ``` * * @param jwt JWT token in compact JWS serialization. */ export function decodeJwt(jwt: string) { if (typeof jwt !== 'string') throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string') const { 1: payload, length } = jwt.split('.') if (length === 5) throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded') if (length !== 3) throw new JWTInvalid('Invalid JWT') if (!payload) throw new JWTInvalid('JWTs must contain a payload') let decoded: Uint8Array try { decoded = base64url(payload) } catch { throw new JWTInvalid('Failed to parse the base64url encoded payload') } let result: unknown try { result = JSON.parse(decoder.decode(decoded)) } catch { throw new JWTInvalid('Failed to parse the decoded payload as JSON') } if (!isObject(result)) throw new JWTInvalid('Invalid JWT Claims Set') return result } jose-4.11.4/src/util/decode_protected_header.ts000066400000000000000000000026641437043056600215010ustar00rootroot00000000000000import { decode as base64url } from './base64url.js' import { decoder } from '../lib/buffer_utils.js' import isObject from '../lib/is_object.js' import type { JWSHeaderParameters, JWEHeaderParameters } from '../types.d' export type ProtectedHeaderParameters = JWSHeaderParameters & JWEHeaderParameters /** * Decodes the Protected Header of a JWE/JWS/JWT token utilizing any JOSE serialization. * * @example Usage * * ```js * const protectedHeader = jose.decodeProtectedHeader(token) * console.log(protectedHeader) * ``` * * @param token JWE/JWS/JWT token in any JOSE serialization. */ export function decodeProtectedHeader(token: string | object) { let protectedB64u!: string if (typeof token === 'string') { const parts = token.split('.') if (parts.length === 3 || parts.length === 5) { ;[protectedB64u] = parts } } else if (typeof token === 'object' && token) { if ('protected' in token) { protectedB64u = (<{ protected: string }>token).protected } else { throw new TypeError('Token does not contain a Protected Header') } } try { if (typeof protectedB64u !== 'string' || !protectedB64u) { throw new Error() } const result = JSON.parse(decoder.decode(base64url(protectedB64u!))) if (!isObject(result)) { throw new Error() } return result } catch { throw new TypeError('Invalid Token or Protected Header formatting') } } jose-4.11.4/src/util/errors.ts000066400000000000000000000113151437043056600162020ustar00rootroot00000000000000/** A generic Error subclass that all other specific JOSE Error subclasses inherit from. */ export class JOSEError extends Error { /** A unique error code for the particular error subclass. */ static get code(): string { return 'ERR_JOSE_GENERIC' } /** A unique error code for the particular error subclass. */ code: string = 'ERR_JOSE_GENERIC' constructor(message?: string) { super(message) this.name = this.constructor.name // @ts-ignore Error.captureStackTrace?.(this, this.constructor) } } /** An error subclass thrown when a JWT Claim Set member validation fails. */ export class JWTClaimValidationFailed extends JOSEError { static get code(): 'ERR_JWT_CLAIM_VALIDATION_FAILED' { return 'ERR_JWT_CLAIM_VALIDATION_FAILED' } code = 'ERR_JWT_CLAIM_VALIDATION_FAILED' /** The Claim for which the validation failed. */ claim: string /** Reason code for the validation failure. */ reason: string constructor(message: string, claim = 'unspecified', reason = 'unspecified') { super(message) this.claim = claim this.reason = reason } } /** An error subclass thrown when a JWT is expired. */ export class JWTExpired extends JOSEError implements JWTClaimValidationFailed { static get code(): 'ERR_JWT_EXPIRED' { return 'ERR_JWT_EXPIRED' } code = 'ERR_JWT_EXPIRED' /** The Claim for which the validation failed. */ claim: string /** Reason code for the validation failure. */ reason: string constructor(message: string, claim = 'unspecified', reason = 'unspecified') { super(message) this.claim = claim this.reason = reason } } /** An error subclass thrown when a JOSE Algorithm is not allowed per developer preference. */ export class JOSEAlgNotAllowed extends JOSEError { static get code(): 'ERR_JOSE_ALG_NOT_ALLOWED' { return 'ERR_JOSE_ALG_NOT_ALLOWED' } code = 'ERR_JOSE_ALG_NOT_ALLOWED' } /** * An error subclass thrown when a particular feature or algorithm is not supported by this * implementation or JOSE in general. */ export class JOSENotSupported extends JOSEError { static get code(): 'ERR_JOSE_NOT_SUPPORTED' { return 'ERR_JOSE_NOT_SUPPORTED' } code = 'ERR_JOSE_NOT_SUPPORTED' } /** An error subclass thrown when a JWE ciphertext decryption fails. */ export class JWEDecryptionFailed extends JOSEError { static get code(): 'ERR_JWE_DECRYPTION_FAILED' { return 'ERR_JWE_DECRYPTION_FAILED' } code = 'ERR_JWE_DECRYPTION_FAILED' message = 'decryption operation failed' } /** An error subclass thrown when a JWE is invalid. */ export class JWEInvalid extends JOSEError { static get code(): 'ERR_JWE_INVALID' { return 'ERR_JWE_INVALID' } code = 'ERR_JWE_INVALID' } /** An error subclass thrown when a JWS is invalid. */ export class JWSInvalid extends JOSEError { static get code(): 'ERR_JWS_INVALID' { return 'ERR_JWS_INVALID' } code = 'ERR_JWS_INVALID' } /** An error subclass thrown when a JWT is invalid. */ export class JWTInvalid extends JOSEError { static get code(): 'ERR_JWT_INVALID' { return 'ERR_JWT_INVALID' } code = 'ERR_JWT_INVALID' } /** An error subclass thrown when a JWK is invalid. */ export class JWKInvalid extends JOSEError { static get code(): 'ERR_JWK_INVALID' { return 'ERR_JWK_INVALID' } code = 'ERR_JWK_INVALID' } /** An error subclass thrown when a JWKS is invalid. */ export class JWKSInvalid extends JOSEError { static get code(): 'ERR_JWKS_INVALID' { return 'ERR_JWKS_INVALID' } code = 'ERR_JWKS_INVALID' } /** An error subclass thrown when no keys match from a JWKS. */ export class JWKSNoMatchingKey extends JOSEError { static get code(): 'ERR_JWKS_NO_MATCHING_KEY' { return 'ERR_JWKS_NO_MATCHING_KEY' } code = 'ERR_JWKS_NO_MATCHING_KEY' message = 'no applicable key found in the JSON Web Key Set' } /** An error subclass thrown when multiple keys match from a JWKS. */ export class JWKSMultipleMatchingKeys extends JOSEError { static get code(): 'ERR_JWKS_MULTIPLE_MATCHING_KEYS' { return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS' } code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS' message = 'multiple matching keys found in the JSON Web Key Set' } /** Timeout was reached when retrieving the JWKS response. */ export class JWKSTimeout extends JOSEError { static get code(): 'ERR_JWKS_TIMEOUT' { return 'ERR_JWKS_TIMEOUT' } code = 'ERR_JWKS_TIMEOUT' message = 'request timed out' } /** An error subclass thrown when JWS signature verification fails. */ export class JWSSignatureVerificationFailed extends JOSEError { static get code(): 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED' { return 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED' } code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED' message = 'signature verification failed' } jose-4.11.4/tap/000077500000000000000000000000001437043056600133355ustar00rootroot00000000000000jose-4.11.4/tap/.browser.ts000066400000000000000000000012671437043056600154540ustar00rootroot00000000000000import { t, Selector } from 'testcafe' fixture('test suite').page('https://important-clam-66.deno.dev') import * as fs from 'node:fs' const script = fs.readFileSync('./tap/run-browser.js', { encoding: 'utf-8' }) const scriptTag = Selector('script') test('passes tests', async (user) => { await user.typeText('#js', script, { paste: true }).click('[type=submit]') await scriptTag() let stats do { await new Promise((resolve) => setTimeout(resolve, 1000)) stats = await t.eval(() => globalThis.stats) } while (!stats) const { log } = await t.getBrowserConsoleMessages() for (const entry of log) { console.log(entry) } await t.expect(stats?.failed).eql(0) }) jose-4.11.4/tap/.browsers.sh000077500000000000000000000013171437043056600156220ustar00rootroot00000000000000#!/bin/bash ./node_modules/.bin/esbuild \ --log-level=warning \ --format=esm \ --bundle \ --target=esnext \ --outfile=tap/run-browser.js \ tap/run-browser.ts HOSTNAME="localhost" SSL="" if [[ -z $CI ]]; then BROWSER="chrome:headless" else if [[ "$BROWSER" == "browserstack"* ]]; then if [[ "$BROWSER" != "browserstack:android"* ]]; then HOSTNAME="jose.panva.me" SSL="key=./letsencrypt/config/live/jose.panva.me/privkey.pem;cert=./letsencrypt/config/live/jose.panva.me/cert.pem;rejectUnauthorized=true;" fi BROWSER=$(NODE_PATH=$(npm root -g) node ./tap/browserstack.cjs $BROWSER) fi fi testcafe "$BROWSER" --skip-js-errors --ssl "$SSL" --hostname "$HOSTNAME" tap/.browser.ts jose-4.11.4/tap/.bun.sh000077500000000000000000000000421437043056600145320ustar00rootroot00000000000000~/.bun/bin/bun run tap/run-bun.ts jose-4.11.4/tap/.deno.sh000077500000000000000000000001231437043056600146730ustar00rootroot00000000000000deno run --allow-read --allow-net --import-map tap/import_map.json tap/run-deno.ts jose-4.11.4/tap/.edge-runtime.mjs000066400000000000000000000006071437043056600165160ustar00rootroot00000000000000import * as fs from 'node:fs' import { EdgeRuntime } from 'edge-runtime' const script = fs.readFileSync('./tap/run-edge-runtime.js', { encoding: 'utf-8' }) const runtime = new EdgeRuntime() runtime.evaluate(script) let stats do { await new Promise((resolve) => setTimeout(resolve, 1000)) ;({ stats } = runtime.context) } while (!stats) if (stats?.failed !== 0) { process.exit(1) } jose-4.11.4/tap/.edge-runtime.sh000077500000000000000000000003201437043056600163320ustar00rootroot00000000000000#!/bin/bash ./node_modules/.bin/esbuild \ --log-level=warning \ --format=esm \ --bundle \ --target=esnext \ --outfile=tap/run-edge-runtime.js \ tap/run-edge-runtime.ts node tap/.edge-runtime.mjs jose-4.11.4/tap/.electron.sh000077500000000000000000000004451437043056600155700ustar00rootroot00000000000000#!/bin/bash ./node_modules/.bin/esbuild \ --log-level=warning \ --format=esm \ --bundle \ --platform=node \ --external:electron \ --external:#dist \ --target=esnext \ --outfile=tap/run-electron.js \ tap/run-electron.ts source .electron_flags.sh electron tap/run-electron.js jose-4.11.4/tap/.node.sh000077500000000000000000000016501437043056600147010ustar00rootroot00000000000000#!/bin/bash ./node_modules/.bin/esbuild \ --log-level=warning \ --format=esm \ --bundle \ --platform=node \ --external:#dist \ --external:#dist/webapi \ --target=esnext \ --outfile=tap/run-node.mjs \ tap/run-node.ts source .node_flags.sh node tap/run-node.mjs '#dist' NODE_CRYPTO_API=$? node -e 'process.exit(parseInt(process.versions.node, 10))' &> /dev/null NODE_VERSION=$? if [[ "$NODE_VERSION" -le 14 ]]; then exit $NODE_CRYPTO_API fi node tap/run-node.mjs '#dist/webapi' WEB_CRYPTO_API=$? node tap/run-node.mjs '#dist/hybrid' HYBRID=$? echo "" echo "node:crypto" test $NODE_CRYPTO_API -eq 0 && echo " passed" || echo " failed" echo "" echo "WebCryptoAPI" test $WEB_CRYPTO_API -eq 0 && echo " passed" || echo " failed" echo "" echo "node:crypto with CryptoKey" test $HYBRID -eq 0 && echo " passed" || echo " failed" test $WEB_CRYPTO_API -eq 0 && test $NODE_CRYPTO_API -eq 0 && test $HYBRID -eq 0 jose-4.11.4/tap/.workers.sh000077500000000000000000000021021437043056600154410ustar00rootroot00000000000000#!/bin/bash COMPATIBILITY_DATE=$(NODE_PATH=$(npm root -g) node -p "require('workerd').compatibilityDate") WORKERD_VERSION=$(npm ls --global --json | jq '.dependencies.workerd.version') ./node_modules/.bin/esbuild \ --log-level=warning \ --format=esm \ --bundle \ --define:WORKERD_VERSION=$WORKERD_VERSION \ --target=esnext \ --outfile=tap/run-workers.js \ tap/run-workers.ts cat < $(pwd)/tap/.workers.capnp using Workerd = import "/workerd/workerd.capnp"; const config :Workerd.Config = ( services = [ (name = "main", worker = .tapWorker), ], sockets = [ # Serve HTTP on port 8080. ( name = "http", address = "*:8080", http = (), service = "main" ), ] ); const tapWorker :Workerd.Worker = ( modules = [ (name = "worker", esModule = embed "run-workers.js") ], compatibilityDate = "$COMPATIBILITY_DATE", ); EOT workerd serve --verbose $(pwd)/tap/.workers.capnp & sleep 1 failed=$(curl -s http://localhost:8080 | jq '.failed') kill $(ps aux | grep 'workerd' | grep -v 'grep' | awk '{print $2}') test $failed -eq 0 jose-4.11.4/tap/aes.ts000066400000000000000000000027221437043056600144600ustar00rootroot00000000000000import type QUnit from 'qunit' import * as env from './env.js' import type * as jose from '../src/index.js' import random from './random.js' import * as roundtrip from './encrypt.js' export default (QUnit: QUnit, lib: typeof jose) => { const { module, test } = QUnit module('aes.ts') type Vector = [string, boolean] const algorithms: Vector[] = [ ['A128GCM', true], ['A192GCM', !env.isChromium], ['A256GCM', true], ['A128CBC-HS256', true], ['A192CBC-HS384', !env.isChromium], ['A256CBC-HS512', true], ] function title(vector: Vector) { const [enc, works] = vector let result = '' if (!works) { result = '[not supported] ' } result += `${enc}` return result } function secretsFor(enc: string) { return [ lib.generateSecret(enc), random(parseInt(enc.endsWith('GCM') ? enc.slice(1, 4) : enc.slice(-3)) >> 3), ] } for (const vector of algorithms) { const [enc, works] = vector const execute = async (t: typeof QUnit.assert) => { for await (const secret of secretsFor(enc)) { await roundtrip.jwe(t, lib, 'dir', enc, secret) } } const jwt = async (t: typeof QUnit.assert) => { await roundtrip.jwt(t, lib, 'dir', enc, await secretsFor(enc)[0]) } if (works) { test(title(vector), execute) test(`${title(vector)} JWT`, jwt) } else { test(title(vector), async (t) => { await t.rejects(execute(t)) }) } } } jose-4.11.4/tap/aeskw.ts000066400000000000000000000027021437043056600150200ustar00rootroot00000000000000import type QUnit from 'qunit' import * as env from './env.js' import type * as jose from '../src/index.js' import random from './random.js' import * as roundtrip from './encrypt.js' export default (QUnit: QUnit, lib: typeof jose) => { const { module, test } = QUnit module('aeskw.ts') type Vector = [string, boolean] const algorithms: Vector[] = [ ['A128KW', !env.isElectron], ['A192KW', !(env.isChromium || env.isElectron)], ['A256KW', !env.isElectron], ['A128GCMKW', true], ['A192GCMKW', !env.isChromium], ['A256GCMKW', true], ] function title(vector: Vector) { const [alg, works] = vector let result = '' if (!works) { result = '[not supported] ' } result += `${alg}` return result } function secretsFor(alg: string) { return [lib.generateSecret(alg), random(parseInt(alg.slice(1, 4), 10) >> 3)] } for (const vector of algorithms) { const [alg, works] = vector const execute = async (t: typeof QUnit.assert) => { for await (const secret of secretsFor(alg)) { await roundtrip.jwe(t, lib, alg, 'A128GCM', secret) } } const jwt = async (t: typeof QUnit.assert) => { await roundtrip.jwt(t, lib, alg, 'A128GCM', await secretsFor(alg)[0]) } if (works) { test(title(vector), execute) test(`${title(vector)} JWT`, jwt) } else { test(title(vector), async (t) => { await t.rejects(execute(t)) }) } } } jose-4.11.4/tap/browserstack.cjs000066400000000000000000000021001437043056600165400ustar00rootroot00000000000000const browserstack = require('testcafe-browser-provider-browserstack') const { parseArgs } = require('node:util') const { positionals: { 0: identifier }, } = parseArgs({ allowPositionals: true }) function majorMinorSort(a, b) { const va = parseFloat(a.split('@')[1]) const vb = parseFloat(b.split('@')[1]) return va < vb ? 1 : -1 } browserstack .init() .then(() => browserstack.getBrowserList()) .then((browserlist) => { let result switch (identifier) { case 'browserstack:android': ;[result] = browserlist.filter((id) => id.startsWith('Google Pixel')).sort(majorMinorSort) break case 'browserstack:safari': ;[result] = browserlist .filter((id) => !!new RegExp(`safari@\\\d+\\\.\\\d+:[^W]`).exec(id)) .sort(majorMinorSort) break case 'browserstack:ios': ;[result] = browserlist.filter((id) => id.startsWith('iPhone')).sort(majorMinorSort) break default: throw new TypeError('unsupported browser identifier') } console.log(`browserstack:${result}`) }) jose-4.11.4/tap/cookbook.ts000066400000000000000000000213201437043056600155110ustar00rootroot00000000000000import type QUnit from 'qunit' import * as env from './env.js' import type * as jose from '../src/index.js' // @ts-ignore import jwsVectors from '../cookbook/jws.mjs' // @ts-ignore import jweVectors from '../cookbook/jwe.mjs' export default (QUnit: QUnit, lib: typeof jose) => { const { module, test } = QUnit const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) const pubjwk = (jwk: jose.JWK) => { let { d, p, q, dp, dq, qi, ...publicJwk } = jwk return publicJwk } { module('jws cookbook') const flattened = { Sign: lib.FlattenedSign, verify: lib.flattenedVerify, } const compact = { Sign: lib.CompactSign, verify: lib.compactVerify, } function supported(vector: any) { if (vector.input.alg === 'ES512') { return !env.isDeno } if (vector.input.alg === 'EdDSA') { return env.isDeno || env.isWorkers || env.isNode || env.isElectron } return true } const execute = (vector: any) => async (t: typeof QUnit.assert) => { const reproducible = !!vector.reproducible const privateKey = await lib.importJWK(vector.input.key, vector.input.alg) const publicKey = await lib.importJWK(pubjwk(vector.input.key), vector.input.alg) if (reproducible) { // sign and compare results are the same const runs = [[flattened, vector.output.json_flat]] if (vector.signing.protected?.b64 !== undefined) { runs.push([compact, vector.output.compact]) } for (const [serialization, expectedResult] of runs) { if (!expectedResult) { continue } const sign = new serialization.Sign(encode(vector.input.payload)) if (vector.signing.protected) { sign.setProtectedHeader(vector.signing.protected) } if (vector.signing.unprotected) { sign.setUnprotectedHeader(vector.signing.unprotected) } const result = await sign.sign(privateKey) if (vector.signing.protected?.b64 === false) { await serialization.verify( { ...result, payload: encode(vector.input.payload) }, publicKey, ) } else { await serialization.verify(result, publicKey) } if (typeof result === 'object') { Object.entries(expectedResult).forEach(([prop, expected]) => { if (prop === 'payload' && vector.signing.protected?.b64 === false) { return } t.equal(JSON.stringify(result[prop]), JSON.stringify(expected)) }) } else { t.equal(result, expectedResult) } } } else { const sign = new flattened.Sign(encode(vector.input.payload)) if (vector.signing.protected) { sign.setProtectedHeader(vector.signing.protected) } if (vector.signing.unprotected) { sign.setUnprotectedHeader(vector.signing.unprotected) } const result = await sign.sign(privateKey) await flattened.verify(result, publicKey) } if (vector.output.json_flat) { await flattened.verify(vector.output.json_flat, publicKey) } if (vector.output.compact) { await compact.verify(vector.output.compact, publicKey) } t.ok(1) } for (const vector of jwsVectors) { if (supported(vector)) { test(vector.title, execute(vector)) } else { test(`[not supported] ${vector.title}`, async (t) => { await t.rejects(execute(vector)(t)) }) } } } { module('jwe cookbook') const flattened = { Encrypt: lib.FlattenedEncrypt, decrypt: lib.flattenedDecrypt, } const compact = { Encrypt: lib.CompactEncrypt, decrypt: lib.compactDecrypt, } function supported(vector: any) { if (vector.webcrypto === false && !(env.isNodeCrypto || env.isElectron)) { return false } if (env.isElectron && vector.electron === false) { return false } if (vector.input.zip && !env.hasZlib) { return false } return true } const toJWK = (input: string | jose.JWK) => { if (typeof input === 'string') { return { kty: 'oct', k: lib.base64url.encode(encode(input)), } } return input } const execute = (vector: any) => async (t: typeof QUnit.assert) => { const dir = vector.input.alg === 'dir' const reproducible = !!vector.reproducible if (reproducible) { // sign and compare results are the same for (const [serialization, expectedResult] of [ [flattened, vector.output.json_flat], [compact, vector.output.compact], ]) { if (!expectedResult) { continue } const encrypt = new serialization.Encrypt(encode(vector.input.plaintext)) if (vector.encrypting_content.protected) { encrypt.setProtectedHeader(vector.encrypting_content.protected) } if (vector.encrypting_content.unprotected) { encrypt.setSharedUnprotectedHeader(vector.encrypting_content.unprotected) } const { cek, iv } = vector.generated if (cek) { encrypt.setContentEncryptionKey(lib.base64url.decode(cek)) } if (iv) { encrypt.setInitializationVector(lib.base64url.decode(iv)) } if (vector.input.aad) { encrypt.setAdditionalAuthenticatedData(encode(vector.input.aad)) } const keyManagementParameters: jose.JWEKeyManagementHeaderParameters = {} if (vector.encrypting_key && vector.encrypting_key.iv) { keyManagementParameters.iv = lib.base64url.decode(vector.encrypting_key.iv) } if (vector.encrypting_key && vector.encrypting_key.iteration_count) { keyManagementParameters.p2c = vector.encrypting_key.iteration_count } if (vector.encrypting_key && vector.encrypting_key.salt) { keyManagementParameters.p2s = lib.base64url.decode(vector.encrypting_key.salt) } if (vector.encrypting_key && vector.encrypting_key.epk) { keyManagementParameters.epk = ( await lib.importJWK(vector.encrypting_key.epk, vector.input.alg) ) } if (Object.keys(keyManagementParameters).length !== 0) { encrypt.setKeyManagementParameters(keyManagementParameters) } const publicKey = await lib.importJWK( pubjwk(toJWK(vector.input.pwd || vector.input.key)), dir ? vector.input.enc : vector.input.alg, ) const result = await encrypt.encrypt(publicKey) if (typeof result === 'object') { Object.entries(expectedResult).forEach(([prop, expected]) => { t.equal(JSON.stringify(result[prop]), JSON.stringify(expected)) }) } else { t.equal(result, expectedResult) } } } else { const encrypt = new flattened.Encrypt(encode(vector.input.plaintext)) if (vector.encrypting_content.protected) { encrypt.setProtectedHeader(vector.encrypting_content.protected) } if (vector.encrypting_content.unprotected) { encrypt.setUnprotectedHeader(vector.encrypting_content.unprotected) } const privateKey = ( await lib.importJWK( toJWK(vector.input.pwd || vector.input.key), dir ? vector.input.enc : vector.input.alg, true, ) ) let publicKey if (privateKey.type === 'secret') { publicKey = privateKey } else { publicKey = await lib.importJWK( pubjwk(toJWK(vector.input.pwd || vector.input.key)), dir ? vector.input.enc : vector.input.alg, ) } const result = await encrypt.encrypt(publicKey) await flattened.decrypt(result, privateKey) } const privateKey = await lib.importJWK( toJWK(vector.input.pwd || vector.input.key), dir ? vector.input.enc : vector.input.alg, ) if (vector.output.json_flat) { await flattened.decrypt(vector.output.json_flat, privateKey) } if (vector.output.compact) { await compact.decrypt(vector.output.compact, privateKey) } t.ok(1) } for (const vector of jweVectors) { if (supported(vector)) { test(vector.title, execute(vector)) } else { test(`[not supported] ${vector.title}`, async (t) => { await t.rejects(execute(vector)(t)) }) } } } } jose-4.11.4/tap/ecdh.ts000066400000000000000000000032001437043056600146030ustar00rootroot00000000000000import type QUnit from 'qunit' import * as env from './env.js' import type * as jose from '../src/index.js' import * as roundtrip from './encrypt.js' export default (QUnit: QUnit, lib: typeof jose) => { const { module, test } = QUnit module('ecdh.ts') const kps: Record = {} type Vector = [string, boolean] | [string, boolean, jose.GenerateKeyPairOptions] const algorithms: Vector[] = [ ['ECDH-ES', true], ['ECDH-ES', true, { crv: 'P-384' }], ['ECDH-ES', !env.isDeno, { crv: 'P-521' }], ['ECDH-ES', false, { crv: 'secp256k1' }], ['ECDH-ES', env.isNode || env.isElectron, { crv: 'X25519' }], ['ECDH-ES', env.isNode, { crv: 'X448' }], ] function title(vector: Vector) { const [alg, works, options] = vector let result = '' if (!works) { result = '[not supported] ' } result += `${alg} ${options?.crv || 'P-256'}` return result } for (const vector of algorithms) { const [alg, works, options] = vector const k = options?.crv || alg const execute = async (t: typeof QUnit.assert) => { if (!kps[k]) { kps[k] = await lib.generateKeyPair(alg, options) } await roundtrip.jwe(t, lib, alg, 'A128GCM', kps[k]) } const jwt = async (t: typeof QUnit.assert) => { if (!kps[k]) { kps[k] = await lib.generateKeyPair(alg, options) } await roundtrip.jwt(t, lib, alg, 'A128GCM', kps[k]) } if (works) { test(title(vector), execute) test(`${title(vector)} JWT`, jwt) } else { test(title(vector), async (t) => { await t.rejects(execute(t)) }) } } } jose-4.11.4/tap/encrypt.ts000066400000000000000000000032401437043056600153700ustar00rootroot00000000000000import type QUnit from 'qunit' import type * as jose from '../src/index.js' import random from './random.js' function isKeyPair( input: Uint8Array | jose.KeyLike | jose.GenerateKeyPairResult, ): input is jose.GenerateKeyPairResult { return 'publicKey' in input && 'privateKey' in input } export async function jwe( t: typeof QUnit.assert, lib: typeof jose, alg: string, enc: string, secretOrKeyPair: Uint8Array | jose.KeyLike | jose.GenerateKeyPairResult, cleartext = random(), ) { const eKey = isKeyPair(secretOrKeyPair) ? secretOrKeyPair.publicKey : secretOrKeyPair const dKey = isKeyPair(secretOrKeyPair) ? secretOrKeyPair.privateKey : secretOrKeyPair const aad = random() const jwe = await new lib.FlattenedEncrypt(cleartext) .setProtectedHeader({ alg, enc }) .setAdditionalAuthenticatedData(aad) .encrypt(eKey) const decrypted = await lib.flattenedDecrypt(jwe, dKey) t.deepEqual([...decrypted.plaintext], [...cleartext]) t.deepEqual([...decrypted.additionalAuthenticatedData!], [...aad]) } export async function jwt( t: typeof QUnit.assert, lib: typeof jose, alg: string, enc: string, secretOrKeyPair: Uint8Array | jose.KeyLike | jose.GenerateKeyPairResult, ) { const eKey = isKeyPair(secretOrKeyPair) ? secretOrKeyPair.publicKey : secretOrKeyPair const dKey = isKeyPair(secretOrKeyPair) ? secretOrKeyPair.privateKey : secretOrKeyPair const jwt = await new lib.EncryptJWT({ foo: 'bar' }) .setProtectedHeader({ alg, enc }) .encrypt(eKey) const decrypted = await lib.jwtDecrypt(jwt, dKey) t.propContains(decrypted, { payload: { foo: 'bar', }, protectedHeader: { alg, enc, }, }) } jose-4.11.4/tap/env.ts000066400000000000000000000022231437043056600144740ustar00rootroot00000000000000// @ts-ignore export const isBun = typeof Bun !== 'undefined' // @ts-ignore export const isElectron = typeof process !== 'undefined' && process.versions.electron !== undefined // @ts-ignore export const isNode = !isBun && !isElectron && typeof process !== 'undefined' // @ts-ignore export const isNodeCrypto = isNode && [...process.argv].reverse()[0] === '#dist' // @ts-ignore export const isNodeWebCrypto = isNode && [...process.argv].reverse()[0] !== '#dist' // @ts-ignore export const isDeno = typeof Deno !== 'undefined' // @ts-ignore export const isEdgeRuntime = typeof EdgeRuntime !== 'undefined' export const isBrowser = typeof navigator !== 'undefined' && navigator.userAgent?.startsWith?.('Mozilla/5.0 ') export const isWorkers = typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers' export const isChromium = isBrowser && (await import( // @ts-ignore 'https://cdn.jsdelivr.net/npm/bowser@2.11.0/src/bowser.js' ).then(({ default: Bowser }) => Bowser.parse(window.navigator.userAgent).engine.name === 'Blink')) // @ts-ignore export const hasZlib = isNode && [...process.argv].reverse()[0] !== '#dist/webapi' jose-4.11.4/tap/fixtures.ts000066400000000000000000000365371437043056600155740ustar00rootroot00000000000000export const KEYS = { Ed25519: { jwk: { crv: 'Ed25519', d: 'lootR5J6UdF-1tvFpnCZzr2N9AmRwgX92MzH_uuaGCQ', kty: 'OKP', x: 'lBZ9GShvbQEtyyaGs-0Nd4aurH7ERq6UOIvXGb5_tXA', }, pkcs8: '-----BEGIN PRIVATE KEY-----\n' + 'MC4CAQAwBQYDK2VwBCIEIJaKLUeSelHRftbbxaZwmc69jfQJkcIF/djMx/7rmhgk\n' + '-----END PRIVATE KEY-----\n', spki: '-----BEGIN PUBLIC KEY-----\n' + 'MCowBQYDK2VwAyEAlBZ9GShvbQEtyyaGs+0Nd4aurH7ERq6UOIvXGb5/tXA=\n' + '-----END PUBLIC KEY-----\n', x509: '-----BEGIN CERTIFICATE-----\n' + 'MIIBoTCCAVOgAwIBAgIUde5G4y+mtbb0eRISc7vnINRbSXkwBQYDK2VwMEUxCzAJ\n' + 'BgNVBAYTAkNaMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5l\n' + 'dCBXaWRnaXRzIFB0eSBMdGQwIBcNMjIxMDExMTIyMTUzWhgPMjEyMjA5MTcxMjIx\n' + 'NTNaMEUxCzAJBgNVBAYTAkNaMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQK\n' + 'DBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwKjAFBgMrZXADIQCUFn0ZKG9tAS3L\n' + 'Joaz7Q13hq6sfsRGrpQ4i9cZvn+1cKNTMFEwHQYDVR0OBBYEFAATzoAtBcYTcOdY\n' + 'jkcQqsWXipnSMB8GA1UdIwQYMBaAFAATzoAtBcYTcOdYjkcQqsWXipnSMA8GA1Ud\n' + 'EwEB/wQFMAMBAf8wBQYDK2VwA0EApfw+9jSO0x0IorDfdr5ZVGRBVgrfrd9XhxqQ\n' + 'Krphj6cA4Ls9aMYAHf5w+OW9D/t3a9p6mYm78AKIdBsPEtT1AQ==\n' + '-----END CERTIFICATE-----\n', }, Ed448: { jwk: { crv: 'Ed448', d: '35yNO4M8bgte2BEjaCxrx9epQhzZ4VqF5GhjDaBHGPHHCznFXtmQuOps4XvrNpnVUtiawY4j3FCq', kty: 'OKP', x: 'pNAfXkImnUHY52ePCZoU4TKCnrq8baLpCiboNxlmN2AbG2xqmLW5F1DA3lsf-S6GWVIfXPysVd0A', }, pkcs8: '-----BEGIN PRIVATE KEY-----\n' + 'MEcCAQAwBQYDK2VxBDsEOd+cjTuDPG4LXtgRI2gsa8fXqUIc2eFaheRoYw2gRxjx\n' + 'xws5xV7ZkLjqbOF76zaZ1VLYmsGOI9xQqg==\n' + '-----END PRIVATE KEY-----\n', spki: '-----BEGIN PUBLIC KEY-----\n' + 'MEMwBQYDK2VxAzoApNAfXkImnUHY52ePCZoU4TKCnrq8baLpCiboNxlmN2AbG2xq\n' + 'mLW5F1DA3lsf+S6GWVIfXPysVd0A\n' + '-----END PUBLIC KEY-----\n', x509: '-----BEGIN CERTIFICATE-----\n' + 'MIIB7DCCAWygAwIBAgIUL85nVDm2evUiy7tWzGv6OxRjclswBQYDK2VxMEUxCzAJ\n' + 'BgNVBAYTAkNaMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5l\n' + 'dCBXaWRnaXRzIFB0eSBMdGQwIBcNMjIxMDExMTIyMTQwWhgPMjEyMjA5MTcxMjIx\n' + 'NDBaMEUxCzAJBgNVBAYTAkNaMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQK\n' + 'DBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwQzAFBgMrZXEDOgCk0B9eQiadQdjn\n' + 'Z48JmhThMoKeurxtoukKJug3GWY3YBsbbGqYtbkXUMDeWx/5LoZZUh9c/KxV3QCj\n' + 'UzBRMB0GA1UdDgQWBBSA9Hb5PA/vVojQWg4Per+myWHvCzAfBgNVHSMEGDAWgBSA\n' + '9Hb5PA/vVojQWg4Per+myWHvCzAPBgNVHRMBAf8EBTADAQH/MAUGAytlcQNzAN9G\n' + '9bFcVViH8c/zexozB/QCtueCu2kLNCLM9auSlFoHEy8u7+Gxyg1O+3bc43YxBObB\n' + '+wwH7G+8gKKOkFL/43b7o2HNOlZUDHcWAP25cGY6lDFUvQDc0FGO0ge+h4tt075x\n' + 'e52JbhpyuHQlrWYQqHQSAA==\n' + '-----END CERTIFICATE-----\n', }, P256: { jwk: { crv: 'P-256', d: 'WBuVA9Z5CghAbxxspv2j1SiHur5BIR-PSDedvQOzun8', kty: 'EC', x: '4CsFZERaJG_bMfC8AZNAtXbMT4hS6UHTQDsFDVFmZWs', y: '-geyNWMPfctokhFckoSvx-tb_zfRoLZG1fqb3sqaNWw', }, pkcs8: '-----BEGIN PRIVATE KEY-----\n' + 'MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgWBuVA9Z5CghAbxxs\n' + 'pv2j1SiHur5BIR+PSDedvQOzun+hRANCAATgKwVkRFokb9sx8LwBk0C1dsxPiFLp\n' + 'QdNAOwUNUWZla/oHsjVjD33LaJIRXJKEr8frW/830aC2RtX6m97KmjVs\n' + '-----END PRIVATE KEY-----\n', spki: '-----BEGIN PUBLIC KEY-----\n' + 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE4CsFZERaJG/bMfC8AZNAtXbMT4hS\n' + '6UHTQDsFDVFmZWv6B7I1Yw99y2iSEVyShK/H61v/N9GgtkbV+pveypo1bA==\n' + '-----END PUBLIC KEY-----\n', x509: '-----BEGIN CERTIFICATE-----\n' + 'MIIBCTCBsAIJAP3LUepKb7jlMAoGCCqGSM49BAMCMA0xCzAJBgNVBAYTAkNaMB4X\n' + 'DTIyMTAxMTEyMjUwOVoXDTIzMTAwNjEyMjUwOVowDTELMAkGA1UEBhMCQ1owWTAT\n' + 'BgcqhkjOPQIBBggqhkjOPQMBBwNCAATgKwVkRFokb9sx8LwBk0C1dsxPiFLpQdNA\n' + 'OwUNUWZla/oHsjVjD33LaJIRXJKEr8frW/830aC2RtX6m97KmjVsMAoGCCqGSM49\n' + 'BAMCA0gAMEUCIQDUxxIyJy8FQvrou0eGSLzAoNNKrYLIeI/OJzBIu6VkZwIgZvHb\n' + 'W78UlObaQoVHfmO5TbgLpIEiskde4STWKDYIZmI=\n' + '-----END CERTIFICATE-----\n', }, P384: { jwk: { crv: 'P-384', d: '5bt5RH4yyhwdtO2_gDHUgLn8aJqvlOaMHAznINEvkucDqiwrXL4ul42yNpx3biuM', kty: 'EC', x: 'sb8kfa8h1WbOGJC8lOMBEeXBYOM-EQNJjBSl7Ro5uiDI8Bk3cZpz0XPztPSHTXbw', y: '4tyg6L2MAzZ53Sj7l8O7yYYGOYtpNmuoV8vDSjjk_X7KQY-s0G3uT30uoSWvN0vH', }, pkcs8: '-----BEGIN PRIVATE KEY-----\n' + 'MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDDlu3lEfjLKHB207b+A\n' + 'MdSAufxomq+U5owcDOcg0S+S5wOqLCtcvi6XjbI2nHduK4yhZANiAASxvyR9ryHV\n' + 'Zs4YkLyU4wER5cFg4z4RA0mMFKXtGjm6IMjwGTdxmnPRc/O09IdNdvDi3KDovYwD\n' + 'NnndKPuXw7vJhgY5i2k2a6hXy8NKOOT9fspBj6zQbe5PfS6hJa83S8c=\n' + '-----END PRIVATE KEY-----\n', spki: '-----BEGIN PUBLIC KEY-----\n' + 'MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEsb8kfa8h1WbOGJC8lOMBEeXBYOM+EQNJ\n' + 'jBSl7Ro5uiDI8Bk3cZpz0XPztPSHTXbw4tyg6L2MAzZ53Sj7l8O7yYYGOYtpNmuo\n' + 'V8vDSjjk/X7KQY+s0G3uT30uoSWvN0vH\n' + '-----END PUBLIC KEY-----\n', x509: '-----BEGIN CERTIFICATE-----\n' + 'MIIBRTCBzQIJAL/fppsFowYgMAoGCCqGSM49BAMCMA0xCzAJBgNVBAYTAkNaMB4X\n' + 'DTIyMTAxMTEyMjUyMloXDTIzMTAwNjEyMjUyMlowDTELMAkGA1UEBhMCQ1owdjAQ\n' + 'BgcqhkjOPQIBBgUrgQQAIgNiAASxvyR9ryHVZs4YkLyU4wER5cFg4z4RA0mMFKXt\n' + 'Gjm6IMjwGTdxmnPRc/O09IdNdvDi3KDovYwDNnndKPuXw7vJhgY5i2k2a6hXy8NK\n' + 'OOT9fspBj6zQbe5PfS6hJa83S8cwCgYIKoZIzj0EAwIDZwAwZAIwRc/RKmaCus0F\n' + '7/q6D5fPafPTU1iLIcgpdK9pS+7tsCY8UZF2j5fSTFbYG39XaMEYAjB+piZKxCxh\n' + '/9jkdLz6ax866tMp9hQNTYU98lO44IQXhcEqh13zR3Bek4KhEnpkWiE=\n' + '-----END CERTIFICATE-----\n', }, P521: { jwk: { crv: 'P-521', d: 'Ae6uBN9ZtZD-yfB_--VPF_aEXTUlPENfj0mepT0chVvfi4BfWvs9NNCrv3YtWl1Q2FdYPop8Ch5_aiiiAH0QnmxH', kty: 'EC', x: 'AV6RoNRH5egig9TgU5CKHCf2H6XW7Rlqs_LZZKnQKJCZP_1x6RBw2Qgwwy8VCvUd_C_oxv45jU-boutt_ewcx7Wo', y: 'Abou9L-hVPMkzKNpJPGvhWnAhHNL1DKsXTAty-BmNBZPGtEwWsod8Vv2KN8wcIc7ts3dLedTPIn77O63V32t-cc5', }, pkcs8: '-----BEGIN PRIVATE KEY-----\n' + 'MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIB7q4E31m1kP7J8H/7\n' + '5U8X9oRdNSU8Q1+PSZ6lPRyFW9+LgF9a+z000Ku/di1aXVDYV1g+inwKHn9qKKIA\n' + 'fRCebEehgYkDgYYABAFekaDUR+XoIoPU4FOQihwn9h+l1u0ZarPy2WSp0CiQmT/9\n' + 'cekQcNkIMMMvFQr1Hfwv6Mb+OY1Pm6Lrbf3sHMe1qAG6LvS/oVTzJMyjaSTxr4Vp\n' + 'wIRzS9QyrF0wLcvgZjQWTxrRMFrKHfFb9ijfMHCHO7bN3S3nUzyJ++zut1d9rfnH\n' + 'OQ==\n' + '-----END PRIVATE KEY-----\n', spki: '-----BEGIN PUBLIC KEY-----\n' + 'MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBXpGg1Efl6CKD1OBTkIocJ/Yfpdbt\n' + 'GWqz8tlkqdAokJk//XHpEHDZCDDDLxUK9R38L+jG/jmNT5ui62397BzHtagBui70\n' + 'v6FU8yTMo2kk8a+FacCEc0vUMqxdMC3L4GY0Fk8a0TBayh3xW/Yo3zBwhzu2zd0t\n' + '51M8ifvs7rdXfa35xzk=\n' + '-----END PUBLIC KEY-----\n', x509: '-----BEGIN CERTIFICATE-----\n' + 'MIIBkDCB8wIJALGXk5Wy5tmGMAoGCCqGSM49BAMCMA0xCzAJBgNVBAYTAkNaMB4X\n' + 'DTIyMTAxMTEyMjUzNFoXDTIzMTAwNjEyMjUzNFowDTELMAkGA1UEBhMCQ1owgZsw\n' + 'EAYHKoZIzj0CAQYFK4EEACMDgYYABAFekaDUR+XoIoPU4FOQihwn9h+l1u0ZarPy\n' + '2WSp0CiQmT/9cekQcNkIMMMvFQr1Hfwv6Mb+OY1Pm6Lrbf3sHMe1qAG6LvS/oVTz\n' + 'JMyjaSTxr4VpwIRzS9QyrF0wLcvgZjQWTxrRMFrKHfFb9ijfMHCHO7bN3S3nUzyJ\n' + '++zut1d9rfnHOTAKBggqhkjOPQQDAgOBiwAwgYcCQgCfBR/x6atEB5KAaYmNOiKm\n' + 'OHhQISZU62ayPDipxsXf9vh4OK5WDdI4SmC1du07kAlwa2tFVSvz7vkMXGGXVYBr\n' + 'PQJBSjIXjpo07m26F0Jmv0OVX2on98+GN7xP8pRCviAuQj8UWKIQvwnj3esymVWb\n' + 'kmEjhnWo8H38/2wddwksoxHvinU=\n' + '-----END CERTIFICATE-----\n', }, RSA: { jwk: { d: 'B2Uk38NDKaU7ISmT2nqrQSuC5-fvZSJz4XHaWlVm-7lSV4OE1q7Z2fve9c93Q6Bkb8r6gwpTX_AFcWu6NbJmkascpOa5FhhGjffhxFxCKMRkT6ERt6PanHvLGKrk8UJsibjH_ds7UihOH-jd046jtoJjYHv7hmT3Rf0uttzGd6PDMHaZfp8xCjbAYZUFqW91O0hw3x1ZESsWyAS353JIjePzK5JmY7T7jbd-t6_M-u8i8-lv60Q8mvY0Np8iZadA3dFntIl0J4pwHGQGCC45mCAFIs6dgbVvyor7Eg82oDXHH3oOXIwYDi64Aw91EqxF8CdEByIV3_GphBzikEtTDw', dp: 'lRCClYTQvzgsVoVJjdyADVtceVsH7KfwpFxnrot_V40XJkUmiHj2yWGld8kB78q66faOavY-TFpmFlo-BQpEiXCDGzCqNCLJ-lF_ZnWyARfQHBBQPFHH2MqaNiS29yjpt7V4vc4z1DL_v5CaiR1wq9AZTABIUf8l2dAkHFrSTKk', dq: 'DMfbSrlSf71Ng5WuZxtENbQOSTOOP3rIyYibdPzbjJyb5raj09XQW_EJiaM45qbSwJfzFOnrFrQcoOJYmQTlHkVMcnXis2r1WXT0So32_D_kDevNZjHFG4PvqnK4ToV_GCGy1IbG4vHdjyMmHtG00zy9-02j7WV8-OerFP7QIAk', e: 'AQAB', kty: 'RSA', n: 'wINok6pE72n8ry3P6EIR-4B9oJmudAK_Q9mKkbG7eZlnP2Nvn5Fq6IhbsLn-ygT9OO_PzT23UdkxnjF8DUgSt7fVStQ40z4_lHVSPVIQeeDkML9Pipu1zUx6RqweUZdXnoN0JFNM93iUfJEvEukYxrWAeFVrRL2DU2E8DSrlJUyCO-c2NaO3YFsFdowW8pviMAnOs39VZNemiQtT-D4fg48dRX5bkrzjaRymhY7bWGelts0FhrNb6Jy-WMnSPxqpozbQ0ODI4kGQYSrKiUNLDfnSUAR-o5I4Hp2bkOrXt6lLccNu0PpPksVAWzTLyFtixxC9APKyUJSKQ7zNpKhqwQ', p: '4EqeWf4b6BJ_7v0Dwa_prSvDRylomA_IZpSDP_1Cqy24IFP1dBzdqm0gYbLNq3xQJkhptbBbC7xOPt4Zz0n-wJOHOkGf31m5-Gc4BiR9fTOEdFRtEQJyLfPu-7D9UbJH_bz_zsOQw9TDzllZp1H9X87AzkkkMfqjinxC749tJ1s', q: '27qzE-tl4V0HT_8PGI6YG2rphRfe5PArRSFgRmampXve6d_vgu5IpZEoNG7YGcT_J6tcdxF19-M2VEeNyqTPl2X91ba-RjkAByOTcT4n57-M4aK9yJt8un8BPBBNco42GmDnb5ZkC1UwJrrHc8QSmTjDBmvvjJYNUseWeYvCrRM', qi: 'yjY4FSvy_h8BXcbZJq1rLpMiEAqI3yMZ2wK8THJSfD37xbhil5PrDzzOluM_qkaC1aKTTAksFsx8f5AOEePCyjW095OBQe379EizSIC_EnByBdkfms8u5VOOKrZUI6I024QMhFsWCodaDDoNg-xXGD-viRtxpam9ZxVnyLRDOdg', }, pkcs8: '-----BEGIN PRIVATE KEY-----\n' + 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDAg2iTqkTvafyv\n' + 'Lc/oQhH7gH2gma50Ar9D2YqRsbt5mWc/Y2+fkWroiFuwuf7KBP0478/NPbdR2TGe\n' + 'MXwNSBK3t9VK1DjTPj+UdVI9UhB54OQwv0+Km7XNTHpGrB5Rl1eeg3QkU0z3eJR8\n' + 'kS8S6RjGtYB4VWtEvYNTYTwNKuUlTII75zY1o7dgWwV2jBbym+IwCc6zf1Vk16aJ\n' + 'C1P4Ph+Djx1FfluSvONpHKaFjttYZ6W2zQWGs1vonL5YydI/GqmjNtDQ4MjiQZBh\n' + 'KsqJQ0sN+dJQBH6jkjgenZuQ6te3qUtxw27Q+k+SxUBbNMvIW2LHEL0A8rJQlIpD\n' + 'vM2kqGrBAgMBAAECggEAB2Uk38NDKaU7ISmT2nqrQSuC5+fvZSJz4XHaWlVm+7lS\n' + 'V4OE1q7Z2fve9c93Q6Bkb8r6gwpTX/AFcWu6NbJmkascpOa5FhhGjffhxFxCKMRk\n' + 'T6ERt6PanHvLGKrk8UJsibjH/ds7UihOH+jd046jtoJjYHv7hmT3Rf0uttzGd6PD\n' + 'MHaZfp8xCjbAYZUFqW91O0hw3x1ZESsWyAS353JIjePzK5JmY7T7jbd+t6/M+u8i\n' + '8+lv60Q8mvY0Np8iZadA3dFntIl0J4pwHGQGCC45mCAFIs6dgbVvyor7Eg82oDXH\n' + 'H3oOXIwYDi64Aw91EqxF8CdEByIV3/GphBzikEtTDwKBgQDgSp5Z/hvoEn/u/QPB\n' + 'r+mtK8NHKWiYD8hmlIM//UKrLbggU/V0HN2qbSBhss2rfFAmSGm1sFsLvE4+3hnP\n' + 'Sf7Ak4c6QZ/fWbn4ZzgGJH19M4R0VG0RAnIt8+77sP1Rskf9vP/Ow5DD1MPOWVmn\n' + 'Uf1fzsDOSSQx+qOKfELvj20nWwKBgQDburMT62XhXQdP/w8YjpgbaumFF97k8CtF\n' + 'IWBGZqale97p3++C7kilkSg0btgZxP8nq1x3EXX34zZUR43KpM+XZf3Vtr5GOQAH\n' + 'I5NxPifnv4zhor3Im3y6fwE8EE1yjjYaYOdvlmQLVTAmusdzxBKZOMMGa++Mlg1S\n' + 'x5Z5i8KtEwKBgQCVEIKVhNC/OCxWhUmN3IANW1x5Wwfsp/CkXGeui39XjRcmRSaI\n' + 'ePbJYaV3yQHvyrrp9o5q9j5MWmYWWj4FCkSJcIMbMKo0Isn6UX9mdbIBF9AcEFA8\n' + 'UcfYypo2JLb3KOm3tXi9zjPUMv+/kJqJHXCr0BlMAEhR/yXZ0CQcWtJMqQKBgAzH\n' + '20q5Un+9TYOVrmcbRDW0Dkkzjj96yMmIm3T824ycm+a2o9PV0FvxCYmjOOam0sCX\n' + '8xTp6xa0HKDiWJkE5R5FTHJ14rNq9Vl09EqN9vw/5A3rzWYxxRuD76pyuE6Ffxgh\n' + 'stSGxuLx3Y8jJh7RtNM8vftNo+1lfPjnqxT+0CAJAoGBAMo2OBUr8v4fAV3G2Sat\n' + 'ay6TIhAKiN8jGdsCvExyUnw9+8W4YpeT6w88zpbjP6pGgtWik0wJLBbMfH+QDhHj\n' + 'wso1tPeTgUHt+/RIs0iAvxJwcgXZH5rPLuVTjiq2VCOiNNuEDIRbFgqHWgw6DYPs\n' + 'Vxg/r4kbcaWpvWcVZ8i0QznY\n' + '-----END PRIVATE KEY-----\n', spki: '-----BEGIN PUBLIC KEY-----\n' + 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwINok6pE72n8ry3P6EIR\n' + '+4B9oJmudAK/Q9mKkbG7eZlnP2Nvn5Fq6IhbsLn+ygT9OO/PzT23UdkxnjF8DUgS\n' + 't7fVStQ40z4/lHVSPVIQeeDkML9Pipu1zUx6RqweUZdXnoN0JFNM93iUfJEvEukY\n' + 'xrWAeFVrRL2DU2E8DSrlJUyCO+c2NaO3YFsFdowW8pviMAnOs39VZNemiQtT+D4f\n' + 'g48dRX5bkrzjaRymhY7bWGelts0FhrNb6Jy+WMnSPxqpozbQ0ODI4kGQYSrKiUNL\n' + 'DfnSUAR+o5I4Hp2bkOrXt6lLccNu0PpPksVAWzTLyFtixxC9APKyUJSKQ7zNpKhq\n' + 'wQIDAQAB\n' + '-----END PUBLIC KEY-----\n', x509: '-----BEGIN CERTIFICATE-----\n' + 'MIICljCCAX4CCQDz0yP7UQpRIjANBgkqhkiG9w0BAQsFADANMQswCQYDVQQGEwJD\n' + 'WjAeFw0yMjEwMTExMjI2NTVaFw0yMzEwMDYxMjI2NTVaMA0xCzAJBgNVBAYTAkNa\n' + 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwINok6pE72n8ry3P6EIR\n' + '+4B9oJmudAK/Q9mKkbG7eZlnP2Nvn5Fq6IhbsLn+ygT9OO/PzT23UdkxnjF8DUgS\n' + 't7fVStQ40z4/lHVSPVIQeeDkML9Pipu1zUx6RqweUZdXnoN0JFNM93iUfJEvEukY\n' + 'xrWAeFVrRL2DU2E8DSrlJUyCO+c2NaO3YFsFdowW8pviMAnOs39VZNemiQtT+D4f\n' + 'g48dRX5bkrzjaRymhY7bWGelts0FhrNb6Jy+WMnSPxqpozbQ0ODI4kGQYSrKiUNL\n' + 'DfnSUAR+o5I4Hp2bkOrXt6lLccNu0PpPksVAWzTLyFtixxC9APKyUJSKQ7zNpKhq\n' + 'wQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQCgIGx+4WgwLtSGAxquNk7pMoewqyCx\n' + 'PO1v/3Snte5sHcn2+yBHaVeRrbnvniJIUNWnvGs/MuGA5fhsSgRBeXqOsLq0eprX\n' + 'YfPG7PG532NoaZ97Gp9X/YH3tTLCh/gyp0kQ2R0eci6f3J7nDzSPazHskEGTujHS\n' + 'uSczHvQsD8HdAd2CsZLPp02NgKhiG4VwMP2CeaUTG/62eZp/fGEAAqrXn4YoHsnY\n' + 'DPCORtzlkel/kV8r0/ktXt+fWoPIpn3dUaHDwi9V9RMkML9IMyLYFfLnpfxFMqdg\n' + '7KWOOFnaMmoDLlICZk7Ym3SjNt86hzmJ+eWiUuHAdFN4PeKj9wXd0t90\n' + '-----END CERTIFICATE-----\n', }, X25519: { jwk: { crv: 'X25519', d: 'WCN6m3ZhxgzgsmacDlbq_O347na7uQe6cW8T6ZJ19mw', kty: 'OKP', x: 'aq1ZuCRIE3XXXcRpbC_txuESJ4KFH8VwQlz1nVa8Ugk', }, pkcs8: '-----BEGIN PRIVATE KEY-----\n' + 'MC4CAQAwBQYDK2VuBCIEIFgjept2YcYM4LJmnA5W6vzt+O52u7kHunFvE+mSdfZs\n' + '-----END PRIVATE KEY-----\n', spki: '-----BEGIN PUBLIC KEY-----\n' + 'MCowBQYDK2VuAyEAaq1ZuCRIE3XXXcRpbC/txuESJ4KFH8VwQlz1nVa8Ugk=\n' + '-----END PUBLIC KEY-----\n', x509: undefined, }, X448: { jwk: { crv: 'X448', d: 'tMpYXWcUg7vGrUcZ1cUMVodjB6rWSOaBKgmaigThaInGRTCmaWPDYrE93wwPmyxOhVYRsmIRFv0', kty: 'OKP', x: 'jk-IiddcEYNq6CwHnqsQleaB86W2tUITnIMwkurT5BUdw2YpJxQt9rgnEZQW0KnQE-ORhEl0kaA', }, pkcs8: '-----BEGIN PRIVATE KEY-----\n' + 'MEYCAQAwBQYDK2VvBDoEOLTKWF1nFIO7xq1HGdXFDFaHYweq1kjmgSoJmooE4WiJ\n' + 'xkUwpmljw2KxPd8MD5ssToVWEbJiERb9\n' + '-----END PRIVATE KEY-----\n', spki: '-----BEGIN PUBLIC KEY-----\n' + 'MEIwBQYDK2VvAzkAjk+IiddcEYNq6CwHnqsQleaB86W2tUITnIMwkurT5BUdw2Yp\n' + 'JxQt9rgnEZQW0KnQE+ORhEl0kaA=\n' + '-----END PUBLIC KEY-----\n', x509: undefined, }, secp256k1: { jwk: { crv: 'secp256k1', d: '4FnXRICPA8cKwNZhg1XvGS3cyWXzuJ17imMFjlgn42w', kty: 'EC', x: 'hwxzC9RSkkBmbBche2iTjNCLbB7XG6h5lfHmOXTQDmQ', y: 'xzddq8Sa9Gn6EOCeYghU6uyWQoh1mWAHx0p6Zd0N9Bo', }, pkcs8: '-----BEGIN PRIVATE KEY-----\n' + 'MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQg4FnXRICPA8cKwNZhg1Xv\n' + 'GS3cyWXzuJ17imMFjlgn42yhRANCAASHDHML1FKSQGZsFyF7aJOM0ItsHtcbqHmV\n' + '8eY5dNAOZMc3XavEmvRp+hDgnmIIVOrslkKIdZlgB8dKemXdDfQa\n' + '-----END PRIVATE KEY-----\n', spki: '-----BEGIN PUBLIC KEY-----\n' + 'MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEhwxzC9RSkkBmbBche2iTjNCLbB7XG6h5\n' + 'lfHmOXTQDmTHN12rxJr0afoQ4J5iCFTq7JZCiHWZYAfHSnpl3Q30Gg==\n' + '-----END PUBLIC KEY-----\n', x509: '-----BEGIN CERTIFICATE-----\n' + 'MIIBBTCBrQIJAMqeTnxEXkWqMAoGCCqGSM49BAMCMA0xCzAJBgNVBAYTAkNaMB4X\n' + 'DTIyMTAxMTEyMjUxNFoXDTIzMTAwNjEyMjUxNFowDTELMAkGA1UEBhMCQ1owVjAQ\n' + 'BgcqhkjOPQIBBgUrgQQACgNCAASHDHML1FKSQGZsFyF7aJOM0ItsHtcbqHmV8eY5\n' + 'dNAOZMc3XavEmvRp+hDgnmIIVOrslkKIdZlgB8dKemXdDfQaMAoGCCqGSM49BAMC\n' + 'A0cAMEQCICLsIR+59yZbMsxvtYMH+Lmlko0/ihPHU/vbpfc7XXa1AiALT04GYkMx\n' + '/xy0TNunfynvxfMAX+9x+3tO8g/KbPZp7w==\n' + '-----END CERTIFICATE-----\n', }, } jose-4.11.4/tap/generate_options.ts000066400000000000000000000033471437043056600172610ustar00rootroot00000000000000import type QUnit from 'qunit' import type * as jose from '../src/index.js' export default async (QUnit: QUnit, lib: typeof jose) => { const { module, test } = QUnit module('generate_options.ts') const isWebCrypto = typeof CryptoKey !== 'undefined' && (await lib.generateSecret('HS256')) instanceof CryptoKey if (isWebCrypto) { for (const extractable of [undefined, true, false]) { test(`secret CryptoKey extractable: ${extractable ?? 'default (false)'}`, async (t) => { const expected = extractable ?? false const secret = await lib.generateSecret('HS256', { extractable }) t.equal(secret.extractable, expected) }) } for (const extractable of [undefined, true, false]) { test(`CryptoKeyPair extractable: ${extractable ?? 'default (false)'}`, async (t) => { const expected = extractable ?? false const kp = await lib.generateKeyPair('ES256', { extractable }) t.equal(kp.privateKey.extractable, expected) t.equal(kp.publicKey.extractable, true) }) } } for (const modulusLength of [undefined, 2048, 3072]) { test(`RSA modulusLength ${modulusLength ?? 'default (2048)'}`, async (t) => { const expected = modulusLength ?? 2048 const { publicKey } = await lib.generateKeyPair('RS256', { modulusLength }) if (isWebCrypto) { t.equal((publicKey.algorithm).modulusLength, expected) // @ts-ignore } else if (publicKey.asymmetricKeyDetails) { // @ts-ignore t.equal(publicKey.asymmetricKeyDetails.modulusLength, expected) } else { // @ts-ignore t.true(parseInt(process.versions.node, 10) < 16) } }) } } jose-4.11.4/tap/hmac.ts000066400000000000000000000021321437043056600146130ustar00rootroot00000000000000import type QUnit from 'qunit' import type * as jose from '../src/index.js' import random from './random.js' import * as roundtrip from './sign.js' export default (QUnit: QUnit, lib: typeof jose) => { const { module, test } = QUnit module('hmac.ts') const algorithms = ['HS256', 'HS384', 'HS512'] function digestSizeSecretsFor(alg: string) { return [lib.generateSecret(alg), random(parseInt(alg.slice(2, 5), 10) >> 3)] } function nonDigestSizeSecretFor(alg: string) { const length = parseInt(alg.slice(2, 5), 10) >> 3 return [random(length - 1), random(length + 1)] } for (const alg of algorithms) { test(alg, async (t) => { for await (const secret of digestSizeSecretsFor(alg)) { await roundtrip.jws(t, lib, alg, secret) } }) test(`${alg} w/ non-digest output length secrets`, async (t) => { for await (const secret of nonDigestSizeSecretFor(alg)) { await roundtrip.jws(t, lib, alg, secret) } }) test(`${alg} JWT`, async (t) => { await roundtrip.jwt(t, lib, alg, await digestSizeSecretsFor(alg)[0]) }) } } jose-4.11.4/tap/import_map.json000066400000000000000000000012511437043056600163760ustar00rootroot00000000000000{ "imports": { "#dist/webapi": "../dist/deno/index.ts", "./aes.js": "./aes.ts", "./aeskw.js": "./aeskw.ts", "./cookbook.js": "./cookbook.ts", "./ecdh.js": "./ecdh.ts", "./encrypt.js": "./encrypt.ts", "./env.js": "./env.ts", "./fixtures.js": "./fixtures.ts", "./generate_options.js": "./generate_options.ts", "./hmac.js": "./hmac.ts", "./jwk.js": "./jwk.ts", "./jwks.js": "./jwks.ts", "./jws.js": "./jws.ts", "./noop.js": "./noop.ts", "./pbes2.js": "./pbes2.ts", "./pem.js": "./pem.ts", "./random.js": "./random.ts", "./rsaes.js": "./rsaes.ts", "./run.js": "./run.ts", "./sign.js": "./sign.ts" } } jose-4.11.4/tap/jwk.ts000066400000000000000000000054721437043056600145100ustar00rootroot00000000000000import type QUnit from 'qunit' import * as env from './env.js' import { KEYS } from './fixtures.js' import type * as jose from '../src/index.js' export default (QUnit: QUnit, lib: typeof jose) => { const { module, test } = QUnit module('jwk.ts') type Vector = [string, JsonWebKey, boolean] | [string, JsonWebKey, boolean, boolean] const algorithms: Vector[] = [ ['ECDH-ES', KEYS.P256.jwk, true], ['ECDH-ES', KEYS.P384.jwk, true], ['ECDH-ES', KEYS.P521.jwk, !env.isDeno], ['ECDH-ES', KEYS.X25519.jwk, env.isDeno || env.isNode || env.isElectron, env.isDeno], ['ECDH-ES', KEYS.X448.jwk, env.isNode], ['EdDSA', KEYS.Ed25519.jwk, env.isDeno || env.isNode || env.isElectron || env.isWorkers], ['EdDSA', KEYS.Ed448.jwk, env.isNode], ['ES256', KEYS.P256.jwk, true], ['ES256K', KEYS.secp256k1.jwk, env.isNodeCrypto], ['ES384', KEYS.P384.jwk, true], ['ES512', KEYS.P521.jwk, !env.isDeno], ['PS256', KEYS.RSA.jwk, true], ['PS384', KEYS.RSA.jwk, true], ['PS512', KEYS.RSA.jwk, true], ['RS256', KEYS.RSA.jwk, true], ['RS384', KEYS.RSA.jwk, true], ['RS512', KEYS.RSA.jwk, true], ['RSA-OAEP-256', KEYS.RSA.jwk, true], ['RSA-OAEP-384', KEYS.RSA.jwk, true], ['RSA-OAEP-512', KEYS.RSA.jwk, true], ['RSA-OAEP', KEYS.RSA.jwk, true], ['RSA1_5', KEYS.RSA.jwk, env.isNodeCrypto || env.isElectron], ] function publicJwk(jwk: JsonWebKey) { const { d, p, q, dp, dq, qi, k, ...result } = jwk return result } for (const vector of algorithms.slice()) { algorithms.push([vector[0], publicJwk(vector[1]), vector[2]]) } function title(alg: string, jwk: JsonWebKey, works: boolean) { let result = '' if (!works) { result = '[not supported] ' } result += `${alg} ` if (alg === 'EdDSA' || alg === 'ECDH-ES') { result += `${jwk.crv} ` } result += jwk.d ? 'Private' : 'Public' result += ' JWK Import' return result } for (const vector of algorithms) { const [alg, jwk] = vector let [, , works, exportNotImplemented] = vector const execute = async (t: typeof QUnit.assert) => { const key = await lib.importJWK({ ...jwk, ext: true }, alg) if (exportNotImplemented) { try { await lib.exportJWK(key) throw new Error() } catch (err) { t.strictEqual((err).name, 'NotSupportedError') } } else { const exported = await lib.exportJWK(key) for (const prop of [...new Set([...Object.keys(jwk), ...Object.keys(exported)])]) { t.strictEqual(exported[prop], jwk[prop], `${prop} mismatch`) } } t.ok(1) } if (works) { test(title(alg, jwk, works), execute) } else { test(title(alg, jwk, works), async (t) => { await t.rejects(execute(t)) }) } } } jose-4.11.4/tap/jwks.ts000066400000000000000000000014671437043056600146730ustar00rootroot00000000000000import type QUnit from 'qunit' import type * as jose from '../src/index.js' export default (QUnit: QUnit, lib: typeof jose) => { const { module, test } = QUnit module('jwks.ts') const jwksUri = 'https://www.googleapis.com/oauth2/v3/certs' test('fetches the JWKSet', async (t: typeof QUnit.assert) => { const response = await fetch(jwksUri).then((r) => r.json()) const { alg, kid } = response.keys[0] const jwks = lib.createRemoteJWKSet(new URL(jwksUri)) await t.rejects( (async () => jwks({ alg: 'RS256' }, {}))(), 'multiple matching keys found in the JSON Web Key Set', ) await t.rejects( (async () => jwks({ kid: 'foo', alg: 'RS256' }, {}))(), 'no applicable key found in the JSON Web Key Set', ) t.ok(await jwks({ alg, kid }, {})) }) } jose-4.11.4/tap/jws.ts000066400000000000000000000033441437043056600145140ustar00rootroot00000000000000import type QUnit from 'qunit' import * as env from './env.js' import type * as jose from '../src/index.js' import * as roundtrip from './sign.js' export default (QUnit: QUnit, lib: typeof jose) => { const { module, test } = QUnit module('jws.ts') type Vector = [string, boolean] | [string, boolean, jose.GenerateKeyPairOptions] const algorithms: Vector[] = [ ['EdDSA', env.isDeno || env.isWorkers || env.isNode || env.isElectron], ['EdDSA', env.isNode, { crv: 'Ed448' }], ['ES256', true], ['ES256K', env.isNodeCrypto], ['ES384', true], ['ES512', !env.isDeno], ['PS256', true], ['PS384', true], ['PS512', true], ['RS256', true], ['RS384', true], ['RS512', true], ] const kps: Record = {} function title(vector: Vector) { const [alg, works, options] = vector let result = '' if (!works) { result = '[not supported] ' } result += `${alg}` if (options) { result += `, ${JSON.stringify(options)}` } return result } for (const vector of algorithms) { const [alg, works, options] = vector const k = options?.crv || alg const execute = async (t: typeof QUnit.assert) => { if (!kps[k]) { kps[k] = await lib.generateKeyPair(alg, options) } await roundtrip.jws(t, lib, alg, kps[k]) } const jwt = async (t: typeof QUnit.assert) => { if (!kps[k]) { kps[k] = await lib.generateKeyPair(alg, options) } await roundtrip.jwt(t, lib, alg, kps[k]) } if (works) { test(title(vector), execute) test(`${title(vector)} JWT`, jwt) } else { test(title(vector), async (t) => { await t.rejects(execute(t)) }) } } } jose-4.11.4/tap/noop.ts000066400000000000000000000002211437043056600146530ustar00rootroot00000000000000import type QUnit from 'qunit' import type * as jose from '../src/index.js' // @ts-ignore export default (QUnit: QUnit, lib: typeof jose) => {} jose-4.11.4/tap/pbes2.ts000066400000000000000000000024351437043056600147240ustar00rootroot00000000000000import type QUnit from 'qunit' import * as env from './env.js' import type * as jose from '../src/index.js' import * as roundtrip from './encrypt.js' export default (QUnit: QUnit, lib: typeof jose) => { const { module, test } = QUnit module('pbes2.ts') type Vector = [string, boolean] const algorithms: Vector[] = [ ['PBES2-HS256+A128KW', !env.isElectron], ['PBES2-HS384+A192KW', !env.isChromium && !env.isElectron], ['PBES2-HS512+A256KW', !env.isElectron], ] function title(vector: Vector) { const [alg, works] = vector let result = '' if (!works) { result = '[not supported] ' } result += `${alg}` return result } for (const vector of algorithms) { const [alg, works] = vector const execute = async (t: typeof QUnit.assert) => { const password = new TextEncoder().encode('letmein') await roundtrip.jwe(t, lib, alg, 'A128GCM', password) } const jwt = async (t: typeof QUnit.assert) => { const password = new TextEncoder().encode('letmein') await roundtrip.jwt(t, lib, alg, 'A128GCM', password) } if (works) { test(title(vector), execute) test(`${title(vector)} JWT`, jwt) } else { test(title(vector), async (t) => { await t.rejects(execute(t)) }) } } } jose-4.11.4/tap/pem.ts000066400000000000000000000123641437043056600144740ustar00rootroot00000000000000import type QUnit from 'qunit' import * as env from './env.js' import { KEYS } from './fixtures.js' import type * as jose from '../src/index.js' function normalize(pem: string) { return pem.replace(/\s+$/, '') } export default (QUnit: QUnit, lib: typeof jose) => { const { module, test } = QUnit module('pem.ts') type Vector = [string | string[], string, boolean] const algorithms: Vector[] = [ ['ES256', KEYS.P256.pkcs8, true], ['ES256', KEYS.P256.spki, true], ['ES256', KEYS.P256.x509, true], ['ES256K', KEYS.secp256k1.pkcs8, env.isNodeCrypto], ['ES256K', KEYS.secp256k1.spki, env.isNodeCrypto], ['ES256K', KEYS.secp256k1.x509, env.isNodeCrypto], ['ES384', KEYS.P384.pkcs8, true], ['ES384', KEYS.P384.spki, true], ['ES384', KEYS.P384.x509, true], ['ES512', KEYS.P521.pkcs8, !env.isDeno], ['ES512', KEYS.P521.spki, !env.isDeno], ['ES512', KEYS.P521.x509, !env.isDeno], ['PS256', KEYS.RSA.pkcs8, true], ['PS256', KEYS.RSA.spki, true], ['PS256', KEYS.RSA.x509, true], ['PS384', KEYS.RSA.pkcs8, true], ['PS384', KEYS.RSA.spki, true], ['PS384', KEYS.RSA.x509, true], ['PS512', KEYS.RSA.pkcs8, true], ['PS512', KEYS.RSA.spki, true], ['PS512', KEYS.RSA.x509, true], ['RS256', KEYS.RSA.pkcs8, true], ['RS256', KEYS.RSA.spki, true], ['RS256', KEYS.RSA.x509, true], ['RS384', KEYS.RSA.pkcs8, true], ['RS384', KEYS.RSA.spki, true], ['RS384', KEYS.RSA.x509, true], ['RS512', KEYS.RSA.pkcs8, true], ['RS512', KEYS.RSA.spki, true], ['RS512', KEYS.RSA.x509, true], ['RSA-OAEP-256', KEYS.RSA.pkcs8, true], ['RSA-OAEP-256', KEYS.RSA.spki, true], ['RSA-OAEP-256', KEYS.RSA.x509, true], ['RSA-OAEP-384', KEYS.RSA.pkcs8, true], ['RSA-OAEP-384', KEYS.RSA.spki, true], ['RSA-OAEP-384', KEYS.RSA.x509, true], ['RSA-OAEP-512', KEYS.RSA.pkcs8, true], ['RSA-OAEP-512', KEYS.RSA.spki, true], ['RSA-OAEP-512', KEYS.RSA.x509, true], ['RSA-OAEP', KEYS.RSA.pkcs8, true], ['RSA-OAEP', KEYS.RSA.spki, true], ['RSA-OAEP', KEYS.RSA.x509, true], ['RSA1_5', KEYS.RSA.pkcs8, env.isNodeCrypto || env.isElectron], ['RSA1_5', KEYS.RSA.spki, env.isNodeCrypto || env.isElectron], ['RSA1_5', KEYS.RSA.x509, env.isNodeCrypto || env.isElectron], [['ECDH-ES', 'P-256'], KEYS.P256.pkcs8, true], [['ECDH-ES', 'P-256'], KEYS.P256.spki, true], [['ECDH-ES', 'P-256'], KEYS.P256.x509, true], [['ECDH-ES', 'P-384'], KEYS.P384.pkcs8, true], [['ECDH-ES', 'P-384'], KEYS.P384.spki, true], [['ECDH-ES', 'P-384'], KEYS.P384.x509, true], [['ECDH-ES', 'P-521'], KEYS.P521.pkcs8, !env.isDeno], [['ECDH-ES', 'P-521'], KEYS.P521.spki, !env.isDeno], [['ECDH-ES', 'P-521'], KEYS.P521.x509, !env.isDeno], [['ECDH-ES', 'X25519'], KEYS.X25519.pkcs8, env.isDeno || env.isNode || env.isElectron], [['ECDH-ES', 'X25519'], KEYS.X25519.spki, env.isDeno || env.isNode || env.isElectron], [['ECDH-ES', 'X448'], KEYS.X448.pkcs8, env.isNode], [['ECDH-ES', 'X448'], KEYS.X448.spki, env.isNode], [ ['EdDSA', 'Ed25519'], KEYS.Ed25519.pkcs8, env.isWorkers || env.isDeno || env.isNode || env.isElectron, ], [ ['EdDSA', 'Ed25519'], KEYS.Ed25519.spki, env.isWorkers || env.isDeno || env.isNode || env.isElectron, ], [ ['EdDSA', 'Ed25519'], KEYS.Ed25519.x509, env.isWorkers || env.isDeno || env.isNode || env.isElectron, ], [['EdDSA', 'Ed448'], KEYS.Ed448.pkcs8, env.isNode], [['EdDSA', 'Ed448'], KEYS.Ed448.spki, env.isNode], [['EdDSA', 'Ed448'], KEYS.Ed448.x509, env.isNode], ] function title(alg: string, crv: string | undefined, pem: string, works: boolean) { let result = '' if (!works) { result = '[not supported] ' } result += `${alg} ` if (crv) result += `${crv} ` result += pem.startsWith('-----BEGIN PRIVATE KEY-----') ? 'PKCS8 Private Key Import' : pem.startsWith('-----BEGIN PUBLIC KEY-----') ? 'SPKI Public Key Import' : 'X.509 Certificate Import' return result } for (const vector of algorithms) { const [, pem, works] = vector let [alg] = vector let crv!: string if (Array.isArray(alg)) { ;[alg, crv] = alg } let importFn: typeof lib.importSPKI | typeof lib.importPKCS8 | typeof lib.importX509 let exportFn: typeof lib.exportSPKI | typeof lib.exportPKCS8 | undefined = undefined switch (true) { case pem.startsWith('-----BEGIN PRIVATE KEY-----'): { importFn = lib.importPKCS8 exportFn = lib.exportPKCS8 break } case pem.startsWith('-----BEGIN PUBLIC KEY-----'): { importFn = lib.importSPKI exportFn = lib.exportSPKI break } case pem.startsWith('-----BEGIN CERTIFICATE-----'): { importFn = lib.importX509 break } default: continue } const execute = async (t: typeof QUnit.assert) => { const k = await importFn(pem, alg, { extractable: true }) if (exportFn) { t.strictEqual(normalize(await exportFn(k)), normalize(pem)) } t.ok(1) } if (works) { test(title(alg, crv, pem, works), execute) } else { test(title(alg, crv, pem, works), async (t) => { await t.rejects(execute(t)) }) } } } jose-4.11.4/tap/random.ts000066400000000000000000000004101437043056600151600ustar00rootroot00000000000000// @ts-ignore const nodeCrypto = await import('crypto').catch(() => {}) export default (byteLength = 16) => { try { return crypto.getRandomValues(new Uint8Array(byteLength)) } catch { return nodeCrypto.randomFillSync(new Uint8Array(byteLength)) } } jose-4.11.4/tap/rsaes.ts000066400000000000000000000026171437043056600150300ustar00rootroot00000000000000import type QUnit from 'qunit' import * as env from './env.js' import type * as jose from '../src/index.js' import * as roundtrip from './encrypt.js' export default (QUnit: QUnit, lib: typeof jose) => { const { module, test } = QUnit module('rsaes.ts') const kps: Record = {} type Vector = [string, boolean] const algorithms: Vector[] = [ ['RSA1_5', env.isNodeCrypto || env.isElectron], ['RSA-OAEP', true], ['RSA-OAEP-256', true], ['RSA-OAEP-384', true], ['RSA-OAEP-512', true], ] function title(vector: Vector) { const [alg, works] = vector let result = '' if (!works) { result = '[not supported] ' } result += `${alg}` return result } for (const vector of algorithms) { const [alg, works] = vector const execute = async (t: typeof QUnit.assert) => { if (!kps[alg]) { kps[alg] = await lib.generateKeyPair(alg) } await roundtrip.jwe(t, lib, alg, 'A128GCM', kps[alg]) } const jwt = async (t: typeof QUnit.assert) => { if (!kps[alg]) { kps[alg] = await lib.generateKeyPair(alg) } await roundtrip.jwt(t, lib, alg, 'A128GCM', kps[alg]) } if (works) { test(title(vector), execute) test(`${title(vector)} JWT`, jwt) } else { test(title(vector), async (t) => { await t.rejects(execute(t)) }) } } } jose-4.11.4/tap/run-browser.ts000066400000000000000000000002631437043056600161730ustar00rootroot00000000000000import QUnit from 'qunit' import run from './run.js' // @ts-ignore import * as lib from '#dist/webapi' run(QUnit, lib, (stats) => { // @ts-ignore globalThis.stats = stats }) jose-4.11.4/tap/run-bun.ts000066400000000000000000000004101437043056600152660ustar00rootroot00000000000000import QUnit from 'qunit' import run from './run.js' // @ts-ignore import * as lib from '#dist/webapi' const stats: QUnit.DoneDetails = await new Promise((resolve) => { run(QUnit, lib, resolve) }) if (stats?.failed !== 0) { // @ts-ignore process.exit(1) } jose-4.11.4/tap/run-deno.ts000066400000000000000000000003701437043056600154340ustar00rootroot00000000000000import 'https://cdnjs.cloudflare.com/ajax/libs/qunit/2.19.3/qunit.js' import run from './run.js' // @ts-ignore import * as lib from '#dist/webapi' run(QUnit, lib, (stats) => { if (stats?.failed !== 0) { // @ts-ignore Deno.exit(1) } }) jose-4.11.4/tap/run-edge-runtime.ts000066400000000000000000000002631437043056600170750ustar00rootroot00000000000000import QUnit from 'qunit' import run from './run.js' // @ts-ignore import * as lib from '#dist/webapi' run(QUnit, lib, (stats) => { // @ts-ignore globalThis.stats = stats }) jose-4.11.4/tap/run-electron.ts000066400000000000000000000004751437043056600163300ustar00rootroot00000000000000// @ts-ignore const { app } = require('electron') import QUnit from 'qunit' import run from './run.js' // @ts-ignore const lib = require('#dist') app.on('ready', () => { run(QUnit, lib, (stats) => { if (stats?.failed !== 0) { // @ts-ignore app.exit(1) } else { app.exit(0) } }) }) jose-4.11.4/tap/run-node.ts000066400000000000000000000020521437043056600154330ustar00rootroot00000000000000import QUnit from 'qunit' import run from './run.js' import type * as jose from '../src/index.js' let lib: typeof jose // @ts-ignore switch ([...process.argv].reverse()[0]) { case '#dist': // @ts-ignore lib = await import('#dist') break case '#dist/webapi': // @ts-ignore lib = await import('#dist/webapi') break case '#dist/hybrid': // @ts-ignore lib = { ...(await import('#dist')) } // @ts-ignore const keys = await import('#dist/webapi') Object.assign(lib, { exportJWK: keys.exportJWK, exportPKCS8: keys.exportPKCS8, exportSPKI: keys.exportSPKI, generateKeyPair: keys.generateKeyPair, generateSecret: keys.generateSecret, importJWK: keys.importJWK, importPKCS8: keys.importPKCS8, importSPKI: keys.importSPKI, importX509: keys.importX509, }) break default: throw new Error() } const stats: QUnit.DoneDetails = await new Promise((resolve) => { run(QUnit, lib, resolve) }) if (stats?.failed !== 0) { // @ts-ignore process.exitCode = 1 } jose-4.11.4/tap/run-workers.ts000066400000000000000000000005211437043056600162010ustar00rootroot00000000000000import QUnit from 'qunit' import run from './run.js' // @ts-ignore import * as lib from '#dist/webapi' export default { async fetch() { const results = await new Promise((resolve) => { run(QUnit, lib, (results) => { resolve(results) }) }) // @ts-ignore return Response.json({ ...results }) }, } jose-4.11.4/tap/run.ts000066400000000000000000000016171437043056600145160ustar00rootroot00000000000000import type QUnit from 'qunit' import type * as jose from '../src/index.js' const skipFetch = // @ts-ignore typeof fetch === 'undefined' || (typeof process !== 'undefined' && 'CITGM' in process.env) export default async ( QUnit: QUnit, lib: typeof jose, done: (details: QUnit.DoneDetails) => void, ) => { // @ts-ignore QUnit.reporters.tap.init(QUnit) QUnit.config.autostart = false const modules = await Promise.all([ !skipFetch ? import('./jwks.js') : import('./noop.js'), import('./aes.js'), import('./aeskw.js'), import('./cookbook.js'), import('./ecdh.js'), import('./generate_options.js'), import('./hmac.js'), import('./jwk.js'), import('./jws.js'), import('./pbes2.js'), import('./pem.js'), import('./rsaes.js'), ]) for (const { default: module } of modules) { await module(QUnit, lib) } QUnit.start() QUnit.done(done) } jose-4.11.4/tap/sign.ts000066400000000000000000000026671437043056600146600ustar00rootroot00000000000000import type QUnit from 'qunit' import type * as jose from '../src/index.js' import random from './random.js' function isKeyPair( input: Uint8Array | jose.KeyLike | jose.GenerateKeyPairResult, ): input is jose.GenerateKeyPairResult { return 'publicKey' in input && 'privateKey' in input } export async function jws( t: typeof QUnit.assert, lib: typeof jose, alg: string, secretOrKeyPair: Uint8Array | jose.KeyLike | jose.GenerateKeyPairResult, payload = random(), ) { const sKey = isKeyPair(secretOrKeyPair) ? secretOrKeyPair.privateKey : secretOrKeyPair const vKey = isKeyPair(secretOrKeyPair) ? secretOrKeyPair.publicKey : secretOrKeyPair const jws = await new lib.FlattenedSign(payload).setProtectedHeader({ alg }).sign(sKey) const verified = await lib.flattenedVerify(jws, vKey) t.deepEqual([...verified.payload], [...payload]) } export async function jwt( t: typeof QUnit.assert, lib: typeof jose, alg: string, secretOrKeyPair: Uint8Array | jose.KeyLike | jose.GenerateKeyPairResult, ) { const sKey = isKeyPair(secretOrKeyPair) ? secretOrKeyPair.privateKey : secretOrKeyPair const vKey = isKeyPair(secretOrKeyPair) ? secretOrKeyPair.publicKey : secretOrKeyPair const jwt = await new lib.SignJWT({ foo: 'bar' }).setProtectedHeader({ alg }).sign(sKey) const verified = await lib.jwtVerify(jwt, vKey) t.deepEqual(verified, { payload: { foo: 'bar', }, protectedHeader: { alg, }, }) } jose-4.11.4/tap/tsconfig.json000066400000000000000000000005021437043056600160410ustar00rootroot00000000000000{ "include": ["**/*.ts"], "compilerOptions": { "target": "ES2020", "module": "ES2022", "moduleResolution": "Node", "types": [], "allowSyntheticDefaultImports": true, "strict": true, "noEmit": true, "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitAny": true } } jose-4.11.4/test/000077500000000000000000000000001437043056600135305ustar00rootroot00000000000000jose-4.11.4/test/.require.mjs000066400000000000000000000001341437043056600157730ustar00rootroot00000000000000import { createRequire } from 'module' globalThis.require = createRequire(import.meta.url) jose-4.11.4/test/dist.mjs000066400000000000000000000011001437043056600151760ustar00rootroot00000000000000import test from 'ava' let root let keyRoot if ('WEBCRYPTO' in process.env) { root = keyRoot = '#dist/webcrypto' } else if ('CRYPTOKEY' in process.env) { root = '#dist' keyRoot = '#dist/webcrypto' } else if ('WEBAPI' in process.env) { root = keyRoot = '#dist/webapi' } else { root = keyRoot = '#dist' } export { root, keyRoot } export function conditional({ webcrypto = 1 } = {}) { let run = test if ( !webcrypto && ('WEBCRYPTO' in process.env || 'WEBAPI' in process.env || 'CRYPTOKEY' in process.env) ) { run = run.failing } return run } jose-4.11.4/test/jwe/000077500000000000000000000000001437043056600143155ustar00rootroot00000000000000jose-4.11.4/test/jwe/compact.decrypt.test.mjs000066400000000000000000000007331437043056600211100ustar00rootroot00000000000000import test from 'ava' import { root } from '../dist.mjs' const { CompactEncrypt, compactDecrypt, base64url } = await import(root) test('JWE format validation', async (t) => { await t.throwsAsync(compactDecrypt(null, new Uint8Array(0)), { message: 'Compact JWE must be a string or Uint8Array', code: 'ERR_JWE_INVALID', }) await t.throwsAsync(compactDecrypt('...', new Uint8Array(0)), { message: 'Invalid Compact JWE', code: 'ERR_JWE_INVALID', }) }) jose-4.11.4/test/jwe/compact.encrypt.test.mjs000066400000000000000000000062521437043056600211240ustar00rootroot00000000000000import test from 'ava' import { root } from '../dist.mjs' const { CompactEncrypt } = await import(root) test.before(async (t) => { const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) t.context.plaintext = encode('It’s a dangerous business, Frodo, going out your door.') t.context.initializationVector = new Uint8Array(12) t.context.secret = new Uint8Array(16) }) test('CompactEncrypt', async (t) => { const jwe = await new CompactEncrypt(t.context.plaintext) .setInitializationVector(t.context.initializationVector) .setProtectedHeader({ alg: 'dir', enc: 'A128GCM' }) .encrypt(t.context.secret) t.deepEqual( jwe, 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..AAAAAAAAAAAAAAAA.Svw4TvnFg_PTTKPXFteMF4Lmisk8ODBNko7607TNs49EbT0BKRz9tEep2dmks9KPvD-CfX7hW1M.Y5cdeOSFYNyxcPWQlrVFzw', ) }) test('CompactEncrypt.prototype.setProtectedHeader', (t) => { t.throws( () => new CompactEncrypt(t.context.plaintext).setProtectedHeader({}).setProtectedHeader({}), { instanceOf: TypeError, message: 'setProtectedHeader can only be called once', }, ) }) test('CompactEncrypt.prototype.setKeyManagementParameters', (t) => { t.throws( () => new CompactEncrypt(t.context.plaintext) .setKeyManagementParameters({}) .setKeyManagementParameters({}), { instanceOf: TypeError, message: 'setKeyManagementParameters can only be called once', }, ) }) test('CompactEncrypt.prototype.setInitializationVector', (t) => { t.throws( () => new CompactEncrypt(t.context.plaintext) .setInitializationVector(t.context.initializationVector) .setInitializationVector(t.context.initializationVector), { instanceOf: TypeError, message: 'setInitializationVector can only be called once', }, ) }) test('CompactEncrypt.prototype.setContentEncryptionKey', (t) => { t.throws( () => new CompactEncrypt(t.context.plaintext) .setContentEncryptionKey(t.context.secret) .setContentEncryptionKey(t.context.secret), { instanceOf: TypeError, message: 'setContentEncryptionKey can only be called once', }, ) }) test('CompactEncrypt.prototype.encrypt must have a JOSE header', async (t) => { await t.throwsAsync(new CompactEncrypt(t.context.plaintext).encrypt(t.context.secret), { code: 'ERR_JWE_INVALID', message: 'either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()', }) }) test('CompactEncrypt.prototype.encrypt JOSE header have an alg', async (t) => { await t.throwsAsync( new CompactEncrypt(t.context.plaintext) .setProtectedHeader({ enc: 'A128GCM' }) .encrypt(t.context.secret), { code: 'ERR_JWE_INVALID', message: 'JWE "alg" (Algorithm) Header Parameter missing or invalid', }, ) }) test('CompactEncrypt.prototype.encrypt JOSE header have an enc', async (t) => { await t.throwsAsync( new CompactEncrypt(t.context.plaintext) .setProtectedHeader({ alg: 'dir' }) .encrypt(t.context.secret), { code: 'ERR_JWE_INVALID', message: 'JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid', }, ) }) jose-4.11.4/test/jwe/flattened.decrypt.test.mjs000066400000000000000000000142671437043056600214370ustar00rootroot00000000000000import test from 'ava' import * as crypto from 'crypto' import { root } from '../dist.mjs' const { FlattenedEncrypt, flattenedDecrypt, base64url } = await import(root) test.before(async (t) => { const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) t.context.plaintext = encode('It’s a dangerous business, Frodo, going out your door.') t.context.additionalAuthenticatedData = encode('The Fellowship of the Ring') t.context.initializationVector = new Uint8Array(12) t.context.secret = new Uint8Array(16) }) test('JWE format validation', async (t) => { const fullJwe = await new FlattenedEncrypt(t.context.plaintext) .setProtectedHeader({ bar: 'baz' }) .setUnprotectedHeader({ foo: 'bar' }) .setSharedUnprotectedHeader({ alg: 'dir', enc: 'A128GCM' }) .setAdditionalAuthenticatedData(t.context.additionalAuthenticatedData) .encrypt(t.context.secret) { await t.throwsAsync(flattenedDecrypt(null, t.context.secret), { message: 'Flattened JWE must be an object', code: 'ERR_JWE_INVALID', }) } { const jwe = { ...fullJwe } delete jwe.protected delete jwe.header delete jwe.unprotected await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), { message: 'JOSE Header missing', code: 'ERR_JWE_INVALID', }) } { const jwe = { ...fullJwe } delete jwe.iv const assertion = { message: 'JWE Initialization Vector missing or incorrect type', code: 'ERR_JWE_INVALID', } await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), assertion) jwe.iv = null await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), assertion) } { const jwe = { ...fullJwe } delete jwe.ciphertext const assertion = { message: 'JWE Ciphertext missing or incorrect type', code: 'ERR_JWE_INVALID', } await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), assertion) jwe.ciphertext = null await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), assertion) } { const jwe = { ...fullJwe } delete jwe.tag const assertion = { message: 'JWE Authentication Tag missing or incorrect type', code: 'ERR_JWE_INVALID', } await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), assertion) jwe.tag = null await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), assertion) } { const jwe = { ...fullJwe } jwe.protected = null await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), { message: 'JWE Protected Header incorrect type', code: 'ERR_JWE_INVALID', }) } { const jwe = { ...fullJwe } const assertion = { message: 'JWE Protected Header is invalid', code: 'ERR_JWE_INVALID', } jwe.protected = `1${jwe.protected}` await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), assertion) } { const jwe = { ...fullJwe } jwe.encrypted_key = null await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), { message: 'JWE Encrypted Key incorrect type', code: 'ERR_JWE_INVALID', }) } { const jwe = { ...fullJwe } jwe.aad = null await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), { message: 'JWE AAD incorrect type', code: 'ERR_JWE_INVALID', }) } { const jwe = { ...fullJwe } jwe.header = null await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), { message: 'JWE Shared Unprotected Header incorrect type', code: 'ERR_JWE_INVALID', }) } { const jwe = { ...fullJwe } jwe.unprotected = null await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), { message: 'JWE Per-Recipient Unprotected Header incorrect type', code: 'ERR_JWE_INVALID', }) } { const jwe = { ...fullJwe } jwe.unprotected = { foo: 'bar' } await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), { message: 'JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint', code: 'ERR_JWE_INVALID', }) } { const jwe = { ...fullJwe } jwe.unprotected = { enc: 'A128GCM' } await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), { message: 'missing JWE Algorithm (alg) in JWE Header', code: 'ERR_JWE_INVALID', }) } { const jwe = { ...fullJwe } jwe.unprotected = { alg: 'dir' } await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), { message: 'missing JWE Encryption Algorithm (enc) in JWE Header', code: 'ERR_JWE_INVALID', }) } { const jwe = { ...fullJwe } jwe.encrypted_key = 'foo' await t.throwsAsync(flattenedDecrypt(jwe, t.context.secret), { message: 'Encountered unexpected JWE Encrypted Key', code: 'ERR_JWE_INVALID', }) } }) test('AES CBC + HMAC', async (t) => { const secret = crypto.randomFillSync(new Uint8Array(32)) const jwe = await new FlattenedEncrypt(t.context.plaintext) .setProtectedHeader({ alg: 'dir', enc: 'A128CBC-HS256' }) .encrypt(secret) { const jweBadTag = { ...jwe } jweBadTag.tag = 'foo' await t.throwsAsync(flattenedDecrypt(jweBadTag, secret), { code: 'ERR_JWE_DECRYPTION_FAILED', message: 'decryption operation failed', }) } { const jweBadEnc = { ...jwe } jweBadEnc.ciphertext = 'foo' await t.throwsAsync(flattenedDecrypt(jweBadEnc, secret), { code: 'ERR_JWE_DECRYPTION_FAILED', message: 'decryption operation failed', }) } { const altSecret = new Uint8Array(32) altSecret.set(secret.slice(0, 16), 16) altSecret.set(secret.slice(16), 0) await t.throwsAsync(flattenedDecrypt(jwe, altSecret), { code: 'ERR_JWE_DECRYPTION_FAILED', message: 'decryption operation failed', }) } }) test('decrypt PBES2 p2c limit', async (t) => { const jwe = await new FlattenedEncrypt(new Uint8Array(0)) .setProtectedHeader({ alg: 'PBES2-HS256+A128KW', enc: 'A128CBC-HS256' }) .setKeyManagementParameters({ p2c: 2049 }) .encrypt(new Uint8Array(32)) await t.throwsAsync(flattenedDecrypt(jwe, new Uint8Array(32), { maxPBES2Count: 2048 }), { message: 'JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds', code: 'ERR_JWE_INVALID', }) }) jose-4.11.4/test/jwe/flattened.encrypt.test.mjs000066400000000000000000000155771437043056600214560ustar00rootroot00000000000000import test from 'ava' import { root } from '../dist.mjs' const { FlattenedEncrypt, decodeProtectedHeader } = await import(root) test.before(async (t) => { const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) t.context.plaintext = encode('It’s a dangerous business, Frodo, going out your door.') t.context.additionalAuthenticatedData = encode('The Fellowship of the Ring') t.context.initializationVector = new Uint8Array(12) t.context.secret = new Uint8Array(16) }) test('FlattenedEncrypt', async (t) => { { const jwe = await new FlattenedEncrypt(t.context.plaintext) .setInitializationVector(t.context.initializationVector) .setProtectedHeader({ alg: 'dir' }) .setUnprotectedHeader({ enc: 'A128GCM' }) .encrypt(t.context.secret) t.deepEqual(jwe, { ciphertext: 'Svw4TvnFg_PTTKPXFteMF4Lmisk8ODBNko7607TNs49EbT0BKRz9tEep2dmks9KPvD-CfX7hW1M', header: { enc: 'A128GCM', }, iv: 'AAAAAAAAAAAAAAAA', protected: 'eyJhbGciOiJkaXIifQ', tag: 'OYBq53cJNorm8LoZf4SwsA', }) } { const jwe = await new FlattenedEncrypt(t.context.plaintext) .setInitializationVector(t.context.initializationVector) .setProtectedHeader({ alg: 'dir' }) .setSharedUnprotectedHeader({ enc: 'A128GCM' }) .encrypt(t.context.secret) t.deepEqual(jwe, { ciphertext: 'Svw4TvnFg_PTTKPXFteMF4Lmisk8ODBNko7607TNs49EbT0BKRz9tEep2dmks9KPvD-CfX7hW1M', unprotected: { enc: 'A128GCM', }, iv: 'AAAAAAAAAAAAAAAA', protected: 'eyJhbGciOiJkaXIifQ', tag: 'OYBq53cJNorm8LoZf4SwsA', }) } { const jwe = await new FlattenedEncrypt(t.context.plaintext) .setInitializationVector(t.context.initializationVector) .setSharedUnprotectedHeader({ alg: 'dir', enc: 'A128GCM' }) .encrypt(t.context.secret) t.deepEqual(jwe, { ciphertext: 'Svw4TvnFg_PTTKPXFteMF4Lmisk8ODBNko7607TNs49EbT0BKRz9tEep2dmks9KPvD-CfX7hW1M', unprotected: { alg: 'dir', enc: 'A128GCM', }, iv: 'AAAAAAAAAAAAAAAA', tag: 'vrBCoJmYwG3M6xCZ5VSR3g', }) } { const jwe = await new FlattenedEncrypt(t.context.plaintext) .setInitializationVector(t.context.initializationVector) .setProtectedHeader({ alg: 'dir' }) .setAdditionalAuthenticatedData(t.context.additionalAuthenticatedData) .setSharedUnprotectedHeader({ enc: 'A128GCM' }) .encrypt(t.context.secret) t.deepEqual(jwe, { aad: 'VGhlIEZlbGxvd3NoaXAgb2YgdGhlIFJpbmc', ciphertext: 'Svw4TvnFg_PTTKPXFteMF4Lmisk8ODBNko7607TNs49EbT0BKRz9tEep2dmks9KPvD-CfX7hW1M', unprotected: { enc: 'A128GCM', }, iv: 'AAAAAAAAAAAAAAAA', protected: 'eyJhbGciOiJkaXIifQ', tag: 'gEwNlfPZ-O-dG7dTFkhMyQ', }) } { for (const value of [ undefined, null, {}, '', 'foo', 1, 0, true, false, [], new FlattenedEncrypt(new Uint8Array()), ]) { t.throws(() => new FlattenedEncrypt(value), { instanceOf: TypeError, message: 'plaintext must be an instance of Uint8Array', }) } } }) test('FlattenedEncrypt.prototype.setProtectedHeader', (t) => { t.throws( () => new FlattenedEncrypt(t.context.plaintext).setProtectedHeader({}).setProtectedHeader({}), { instanceOf: TypeError, message: 'setProtectedHeader can only be called once', }, ) }) test('FlattenedEncrypt.prototype.setUnprotectedHeader', (t) => { t.throws( () => new FlattenedEncrypt(t.context.plaintext).setUnprotectedHeader({}).setUnprotectedHeader({}), { instanceOf: TypeError, message: 'setUnprotectedHeader can only be called once', }, ) }) test('FlattenedEncrypt.prototype.setSharedUnprotectedHeader', (t) => { t.throws( () => new FlattenedEncrypt(t.context.plaintext) .setSharedUnprotectedHeader({}) .setSharedUnprotectedHeader({}), { instanceOf: TypeError, message: 'setSharedUnprotectedHeader can only be called once', }, ) }) test('FlattenedEncrypt.prototype.setInitializationVector', (t) => { t.throws( () => new FlattenedEncrypt(t.context.plaintext) .setInitializationVector(t.context.initializationVector) .setInitializationVector(t.context.initializationVector), { instanceOf: TypeError, message: 'setInitializationVector can only be called once', }, ) }) test('FlattenedEncrypt.prototype.setContentEncryptionKey', (t) => { t.throws( () => new FlattenedEncrypt(t.context.plaintext) .setContentEncryptionKey(t.context.secret) .setContentEncryptionKey(t.context.secret), { instanceOf: TypeError, message: 'setContentEncryptionKey can only be called once', }, ) }) test('FlattenedEncrypt.prototype.encrypt must have a JOSE header', async (t) => { await t.throwsAsync(new FlattenedEncrypt(t.context.plaintext).encrypt(t.context.secret), { code: 'ERR_JWE_INVALID', message: 'either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()', }) }) test('FlattenedEncrypt.prototype.encrypt JOSE header must be disjoint', async (t) => { await t.throwsAsync( new FlattenedEncrypt(t.context.plaintext) .setProtectedHeader({ alg: 'dir', enc: 'A128GCM' }) .setUnprotectedHeader({ alg: 'dir' }) .encrypt(t.context.secret), { code: 'ERR_JWE_INVALID', message: 'JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint', }, ) await t.throwsAsync( new FlattenedEncrypt(t.context.plaintext) .setProtectedHeader({ alg: 'dir', enc: 'A128GCM' }) .setSharedUnprotectedHeader({ alg: 'dir' }) .encrypt(t.context.secret), { code: 'ERR_JWE_INVALID', message: 'JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint', }, ) }) test('FlattenedEncrypt.prototype.encrypt JOSE header have an alg', async (t) => { await t.throwsAsync( new FlattenedEncrypt(t.context.plaintext) .setProtectedHeader({ enc: 'A128GCM' }) .encrypt(t.context.secret), { code: 'ERR_JWE_INVALID', message: 'JWE "alg" (Algorithm) Header Parameter missing or invalid', }, ) }) test('FlattenedEncrypt.prototype.encrypt JOSE header have an enc', async (t) => { await t.throwsAsync( new FlattenedEncrypt(t.context.plaintext) .setProtectedHeader({ alg: 'dir' }) .encrypt(t.context.secret), { code: 'ERR_JWE_INVALID', message: 'JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid', }, ) }) test('Default PBES2 Count', async (t) => { t.is( decodeProtectedHeader( await new FlattenedEncrypt(t.context.plaintext) .setProtectedHeader({ alg: 'PBES2-HS256+A128KW', enc: 'A128GCM' }) .encrypt(t.context.secret), ).p2c, 2048, ) }) jose-4.11.4/test/jwe/general.test.mjs000066400000000000000000000144751437043056600174360ustar00rootroot00000000000000import test from 'ava' import * as crypto from 'crypto' import { root } from '../dist.mjs' const { GeneralEncrypt, generalDecrypt, generateKeyPair, base64url } = await import(root) test.before(async (t) => { const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) t.context.plaintext = encode('It’s a dangerous business, Frodo, going out your door.') t.context.additionalAuthenticatedData = encode('The Fellowship of the Ring') t.context.initializationVector = crypto.randomFillSync(new Uint8Array(12)) t.context.secret = crypto.randomFillSync(new Uint8Array(32)) t.context.secret2 = crypto.randomFillSync(new Uint8Array(16)) }) test('General JWE encryption', async (t) => { const generalJwe = await new GeneralEncrypt(t.context.plaintext) .setAdditionalAuthenticatedData(t.context.additionalAuthenticatedData) .setProtectedHeader({ enc: 'A256GCM' }) .setSharedUnprotectedHeader({ foo: 'bar' }) .addRecipient(t.context.secret) .setUnprotectedHeader({ alg: 'A256GCMKW' }) .addRecipient(t.context.secret2) .setUnprotectedHeader({ alg: 'A128GCMKW' }) .encrypt() t.true(generalJwe.aad && typeof generalJwe.aad === 'string') t.true(generalJwe.ciphertext && typeof generalJwe.ciphertext === 'string') t.true(generalJwe.iv && typeof generalJwe.iv === 'string') t.true(generalJwe.protected && typeof generalJwe.protected === 'string') t.true( generalJwe.unprotected && typeof generalJwe.unprotected === 'object' && Object.keys(generalJwe.unprotected).length === 1, ) t.true(generalJwe.tag && typeof generalJwe.tag === 'string') t.is(generalJwe.recipients.length, 2) for (const recipient of generalJwe.recipients) { t.true(recipient.encrypted_key && typeof recipient.encrypted_key === 'string') t.true( recipient.header && typeof recipient.header === 'object' && Object.keys(recipient.header).length !== 0, ) } for (const secret of [t.context.secret, t.context.secret2]) { await generalDecrypt(generalJwe, secret) } }) test('General JWE encryption (single recipient dir)', async (t) => { const generalJwe = await new GeneralEncrypt(t.context.plaintext) .setAdditionalAuthenticatedData(t.context.additionalAuthenticatedData) .setProtectedHeader({ enc: 'A256GCM' }) .setSharedUnprotectedHeader({ alg: 'A256GCMKW' }) .addRecipient(t.context.secret) .encrypt() t.true(generalJwe.aad && typeof generalJwe.aad === 'string') t.true(generalJwe.ciphertext && typeof generalJwe.ciphertext === 'string') t.true(generalJwe.iv && typeof generalJwe.iv === 'string') t.true(generalJwe.protected && typeof generalJwe.protected === 'string') t.true(generalJwe.tag && typeof generalJwe.tag === 'string') t.true( generalJwe.unprotected && typeof generalJwe.unprotected === 'object' && Object.keys(generalJwe.unprotected).length === 1, ) t.is(generalJwe.recipients.length, 1) t.true( generalJwe.recipients[0].encrypted_key && typeof generalJwe.recipients[0].encrypted_key === 'string', ) t.false('header' in generalJwe.recipients[0]) await generalDecrypt(generalJwe, t.context.secret) }) test('General JWE encryption (single recipient ECDH-ES)', async (t) => { const kp = await generateKeyPair('ECDH-ES') const generalJwe = await new GeneralEncrypt(t.context.plaintext) .setAdditionalAuthenticatedData(t.context.additionalAuthenticatedData) .setProtectedHeader({ enc: 'A256GCM' }) .setSharedUnprotectedHeader({ alg: 'ECDH-ES' }) .addRecipient(kp.publicKey) .encrypt() t.true(generalJwe.aad && typeof generalJwe.aad === 'string') t.true(generalJwe.ciphertext && typeof generalJwe.ciphertext === 'string') t.true(generalJwe.iv && typeof generalJwe.iv === 'string') t.true(generalJwe.protected && typeof generalJwe.protected === 'string') t.true(generalJwe.tag && typeof generalJwe.tag === 'string') t.deepEqual(generalJwe.recipients, [{}]) t.true( generalJwe.unprotected && typeof generalJwe.unprotected === 'object' && Object.keys(generalJwe.unprotected).length === 1, ) await generalDecrypt(generalJwe, kp.privateKey) }) test('General JWE format validation', async (t) => { const encrypt = new GeneralEncrypt(t.context.plaintext) .setProtectedHeader({ bar: 'baz' }) .setSharedUnprotectedHeader({ foo: 'bar' }) .setAdditionalAuthenticatedData(t.context.additionalAuthenticatedData) encrypt.addRecipient(t.context.secret).setUnprotectedHeader({ alg: 'A256GCMKW', enc: 'A256GCM' }) const generalJwe = await encrypt.encrypt() { await t.throwsAsync(generalDecrypt(null, t.context.secret), { message: 'General JWE must be an object', code: 'ERR_JWE_INVALID', }) } { await t.throwsAsync(generalDecrypt({ recipients: null }, t.context.secret), { message: 'JWE Recipients missing or incorrect type', code: 'ERR_JWE_INVALID', }) } { await t.throwsAsync(generalDecrypt({ recipients: [null] }, t.context.secret), { message: 'JWE Recipients missing or incorrect type', code: 'ERR_JWE_INVALID', }) } { const jwe = { ...generalJwe, recipients: [] } await t.throwsAsync(generalDecrypt(jwe, t.context.secret), { message: 'JWE Recipients has no members', code: 'ERR_JWE_INVALID', }) } { const jwe = { ...generalJwe, recipients: [{}] } await t.throwsAsync(generalDecrypt(jwe, t.context.secret), { message: 'decryption operation failed', code: 'ERR_JWE_DECRYPTION_FAILED', }) } { const jwe = { ...generalJwe, recipients: [generalJwe.recipients[0]] } await t.notThrowsAsync(generalDecrypt(jwe, t.context.secret)) } { const jwe = { ...generalJwe, recipients: [generalJwe.recipients[0], {}] } await t.notThrowsAsync(generalDecrypt(jwe, t.context.secret)) } { const jwe = { ...generalJwe, recipients: [{}, generalJwe.recipients[0]] } await t.notThrowsAsync(generalDecrypt(jwe, t.context.secret)) } }) test('Default PBES2 Count', async (t) => { const jwe = await new GeneralEncrypt(t.context.plaintext) .setProtectedHeader({ alg: 'PBES2-HS256+A128KW', enc: 'A128GCM' }) .addRecipient(t.context.secret) .addRecipient(t.context.secret) .encrypt(t.context.secret) const [{ header: bob }, { header: charlie }] = jwe.recipients t.is(bob.p2c, 2048) t.true(bob.p2c < charlie.p2c) t.true(bob.p2s !== charlie.p2s) }) jose-4.11.4/test/jwk/000077500000000000000000000000001437043056600143235ustar00rootroot00000000000000jose-4.11.4/test/jwk/embedded.test.mjs000066400000000000000000000046541437043056600175560ustar00rootroot00000000000000import test from 'ava' import { root, keyRoot } from '../dist.mjs' const { FlattenedSign, flattenedVerify } = await import(root) const { importJWK, EmbeddedJWK } = await import(keyRoot) function pubjwk(jwk) { const { d, p, q, dp, dq, qi, ext, alg, ...publicJwk } = jwk return publicJwk } test.before(async (t) => { const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) t.context.key = { crv: 'P-256', alg: 'ES256', ext: false, x: 'Sp3KpzPjwcCF04_W2GvSSf-vGDvp3Iv2kQYqAjnMB-Y', y: 'lZmecT2quXe0i9f7b4qHvDAFDpxs0oxCoJx4tOOqsks', d: 'hRVo5TGE_d_4tQC1KEQIlCdo9rteZmLSmaMPpFOjeDI', kty: 'EC', } const privateKey = await importJWK(t.context.key) t.context.token = await new FlattenedSign( encode('It’s a dangerous business, Frodo, going out your door.'), ) .setProtectedHeader({ alg: 'ES256', jwk: pubjwk(t.context.key) }) .sign(privateKey) t.context.tokenMissingJwk = await new FlattenedSign( encode('It’s a dangerous business, Frodo, going out your door.'), ) .setProtectedHeader({ alg: 'ES256' }) .sign(privateKey) t.context.tokenInvalidJWK = await new FlattenedSign( encode('It’s a dangerous business, Frodo, going out your door.'), ) .setProtectedHeader({ alg: 'ES256', jwk: null }) .sign(privateKey) t.context.tokenPrivateJWK = await new FlattenedSign( encode('It’s a dangerous business, Frodo, going out your door.'), ) .setProtectedHeader({ alg: 'ES256', jwk: t.context.key }) .sign(privateKey) }) test('EmbeddedJWK', async (t) => { await t.notThrowsAsync(async () => { const { key: resolvedKey } = await flattenedVerify(t.context.token, EmbeddedJWK) t.truthy(resolvedKey) t.is(resolvedKey.type, 'public') }) }) test('EmbeddedJWK requires "jwk" to be an object', async (t) => { await t.throwsAsync(flattenedVerify(t.context.tokenMissingJwk, EmbeddedJWK), { code: 'ERR_JWS_INVALID', message: '"jwk" (JSON Web Key) Header Parameter must be a JSON object', }) await t.throwsAsync(flattenedVerify(t.context.tokenInvalidJWK, EmbeddedJWK), { code: 'ERR_JWS_INVALID', message: '"jwk" (JSON Web Key) Header Parameter must be a JSON object', }) }) test('EmbeddedJWK requires "jwk" to be a public one', async (t) => { await t.throwsAsync(flattenedVerify(t.context.tokenPrivateJWK, EmbeddedJWK), { code: 'ERR_JWS_INVALID', message: '"jwk" (JSON Web Key) Header Parameter must be a public key', }) }) jose-4.11.4/test/jwk/issue-459.test.mjs000066400000000000000000000031671437043056600174720ustar00rootroot00000000000000import test from 'ava' import { keyRoot } from '../dist.mjs' const { importX509 } = await import(keyRoot) const cert = `-----BEGIN CERTIFICATE----- MIID5jCCAs6gAwIBAgIBAjANBgkqhkiG9w0BAQsFADB7MQswCQYDVQQGEwJVUzEL MAkGA1UECBMCVE4xEDAOBgNVBAoTB01TSUdOSUExDDAKBgNVBAsTA1JORDEXMBUG A1UEAxMOTVNJR05JQSBSTkQgQ0ExJjAkBgkqhkiG9w0BCQEWF3BhdmxvLmx5c292 QG1zaWduaWEuY29tMB4XDTE5MTExMzA4MjAwMFoXDTI4MTExMzA4MjAwMFowgYAx CzAJBgNVBAYTAlVTMQswCQYDVQQIEwJUTjEQMA4GA1UEChMHTVNJR05JQTEUMBIG A1UECxMLTVNJR05JQSBSTkQxFDASBgNVBAMTC01TSUdOSUEgUk5EMSYwJAYJKoZI hvcNAQkBFhdwYXZsby5seXNvdkBtc2lnbmlhLmNvbTCCASIwDQYJKoZIhvcNAQEB BQADggEPADCCAQoCggEBAKRoo30zttpiFlBKnOAmlOcT07xPms7Z6/ZdN9KnE/Po NQx7g6+Ap6b+trA2WDG80jEtwAy5XJcm81rBvJJvjwWQhiPjhXHvEibl+5zTYEXQ tvl3qKNdikXuXPBLI/rwmZTNZd2aa5biVoLEY+cQVLOjdAZS9ZIkeuLYeLEZfNky 7rLa4XyRO4W4XEUWgafOp+ZSXATOz48XCb+fmaek4d8epsVJ/X3Qww9I9mqg8QA7 /EH9ASOYvbMzOjSuDjYBCRq4SJw/YBJDnBcBJSESzLJDDCJQyP4BOD2+P5UZ/OWS NyzEDCLfLsiCVjdt0mNXrn/tGpdLoy1rVfC2SOAoZEUCAwEAAaNvMG0wDAYDVR0T AQH/BAIwADAdBgNVHQ4EFgQUU/luo/bbBOlrQ7wrC3+ggkITcSYwCwYDVR0PBAQD AgSwMBEGCWCGSAGG+EIBAQQEAwIFoDAeBglghkgBhvhCAQ0EERYPeGNhIGNlcnRp ZmljYXRlMA0GCSqGSIb3DQEBCwUAA4IBAQAXroFZ9FeP10gtQguptDo6U0SIAB9n qjN1IktyqatfUuVtThuxXAb3QQ7kYmGCZEaOIKoFdVc8i9aR5ZrYC1VIN4+cGLv7 P36Zl2q4i2G/X0QzniPPvsPyOUXeTVs3k6Sxe07uWdxsglq9LcVW++PvGYzotZP+ ZtmTzYAQtgadhPNo7+QmTO1FDju9p9hTFK7WhmXAO48bF9jrFiTkbwmo6PdlQiqi PQYlbfO0XV727QUZ1YyG8rR/3VVRsBOmwZBKCj0dkh9eiRcNpJloqe1uZ83EBG/W Cic5wE9P+Ol/pFNJFpfjXMsmT8lkCK954aYf2xoH1bHkONYAEEk0iQu/ -----END CERTIFICATE-----` test('https://github.com/panva/jose/issues/459', (t) => { return t.notThrowsAsync(() => importX509(cert, 'RS256')) }) jose-4.11.4/test/jwk/jwk2key.test.mjs000066400000000000000000000073701437043056600174110ustar00rootroot00000000000000import test from 'ava' import { conditional, keyRoot } from '../dist.mjs' const { importJWK, exportJWK } = await import(keyRoot) test('JWK must be an object', async (t) => { await t.throwsAsync(importJWK(true), { instanceOf: TypeError, message: 'JWK must be an object', }) await t.throwsAsync(importJWK(null), { instanceOf: TypeError, message: 'JWK must be an object', }) await t.throwsAsync(importJWK(Boolean), { instanceOf: TypeError, message: 'JWK must be an object', }) await t.throwsAsync(importJWK([]), { instanceOf: TypeError, message: 'JWK must be an object', }) await t.throwsAsync(importJWK(''), { instanceOf: TypeError, message: 'JWK must be an object', }) const nullPrototype = Object.create(null) nullPrototype.crv = 'P-256' nullPrototype.kty = 'EC' nullPrototype.x = 'q3zAwR_kUwtdLEwtB2oVfucXiLHmEhu9bJUFYjJxYGs' nullPrototype.y = '8h0D-ONoU-iZqrq28TyUxEULxuGwJZGMJYTMbeMshvI' await t.notThrowsAsync(importJWK(nullPrototype, 'ES256')) }) test('JWK kty must be recognized', async (t) => { await t.throwsAsync(importJWK({ kty: 'unrecognized' }, 'HS256'), { code: 'ERR_JOSE_NOT_SUPPORTED', message: 'Unsupported "kty" (Key Type) Parameter value', }) }) test('alg argument must be present if jwk does not have alg', async (t) => { const oct = { k: 'FyCq1CKBflh3I5gikEjpYrdOXllzxB_yc02za8ERknI', kty: 'oct', } await t.throwsAsync(importJWK(oct), { instanceOf: TypeError, message: '"alg" argument is required when "jwk.alg" is not present', }) await t.notThrowsAsync(importJWK(oct, 'HS256')) await t.notThrowsAsync(importJWK({ ...oct, alg: 'HS256' })) }) test('oct JWK must have "k"', async (t) => { await t.throwsAsync(importJWK({ kty: 'oct' }, 'HS256'), { instanceOf: TypeError, message: 'missing "k" (Key Value) Parameter value', }) }) test('RSA JWK with oth is not supported', async (t) => { await t.throwsAsync(importJWK({ kty: 'RSA', oth: [] }, 'RS256'), { code: 'ERR_JOSE_NOT_SUPPORTED', message: 'RSA JWK "oth" (Other Primes Info) Parameter value is not supported', }) }) test('oct JWK (ext: true)', async (t) => { const oct = { k: 'FyCq1CKBflh3I5gikEjpYrdOXllzxB_yc02za8ERknI', kty: 'oct', ext: true, } t.deepEqual( [...(await importJWK(oct, 'HS256'))], [ 23, 32, 170, 212, 34, 129, 126, 88, 119, 35, 152, 34, 144, 72, 233, 98, 183, 78, 94, 89, 115, 196, 31, 242, 115, 77, 179, 107, 193, 17, 146, 114, ], ) const k = await importJWK(oct, 'HS256', true) t.true('type' in k) t.is(k.type, 'secret') if ('extractable' in k) { t.is(k.extractable, true) } }) test('oct JWK (ext: false)', async (t) => { const oct = { k: 'FyCq1CKBflh3I5gikEjpYrdOXllzxB_yc02za8ERknI', kty: 'oct', ext: false, } const k = await importJWK(oct, 'HS256', true) t.true('type' in k) t.is(k.type, 'secret') if ('extractable' in k) { t.is(k.extractable, false) } }) test('oct JWK (ext missing)', async (t) => { const oct = { k: 'FyCq1CKBflh3I5gikEjpYrdOXllzxB_yc02za8ERknI', kty: 'oct', } const k = await importJWK(oct, 'HS256', true) t.true('type' in k) t.is(k.type, 'secret') if ('extractable' in k) { t.is(k.extractable, false) } }) test('Uin8tArray can be transformed to a JWK', async (t) => { t.deepEqual( await exportJWK(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])), { k: 'AQIDBAUGBwgJCgsMDQ4P', kty: 'oct', }, ) }) test('secret KeyLike can be transformed to a JWK', async (t) => { const keylike = await importJWK( { ext: true, k: 'AQIDBAUGBwgJCgsMDQ4P', kty: 'oct', }, 'HS256', true, ) t.deepEqual(await exportJWK(keylike), { k: 'AQIDBAUGBwgJCgsMDQ4P', kty: 'oct', }) }) jose-4.11.4/test/jwk/thumbprint.test.mjs000066400000000000000000000131031437043056600202060ustar00rootroot00000000000000import test from 'ava' import { keyRoot } from '../dist.mjs' const { calculateJwkThumbprint, calculateJwkThumbprintUri } = await import(keyRoot) const jwk = { kty: 'RSA', n: '0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw', e: 'AQAB', alg: 'RS256', } test('https://www.rfc-editor.org/rfc/rfc7638#section-3.1', async (t) => { t.is(await calculateJwkThumbprint(jwk), 'NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs') t.is(await calculateJwkThumbprint(jwk, 'sha256'), 'NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs') t.is( await calculateJwkThumbprint(jwk, 'sha384'), 'R9_OfJjSjaw8Fuum86UzK5ixTdN9bo9BaqPSiseq89DWfmqCdpSgUHus-cxDUNc8', ) t.is( await calculateJwkThumbprint(jwk, 'sha512'), 'DpvEwocfn3FjeWWQjcJHzWrpKTIymKwgoL1xVgQcud48-qZDSRCr1zfWZQdHAJn_ciqXqPTSARyg-L-NyNGpVA', ) }) test('https://www.rfc-editor.org/rfc/rfc9278', async (t) => { t.is( await calculateJwkThumbprintUri(jwk), 'urn:ietf:params:oauth:jwk-thumbprint:sha-256:NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs', ) t.is( await calculateJwkThumbprintUri(jwk, 'sha256'), 'urn:ietf:params:oauth:jwk-thumbprint:sha-256:NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs', ) t.is( await calculateJwkThumbprintUri(jwk, 'sha384'), 'urn:ietf:params:oauth:jwk-thumbprint:sha-384:R9_OfJjSjaw8Fuum86UzK5ixTdN9bo9BaqPSiseq89DWfmqCdpSgUHus-cxDUNc8', ) t.is( await calculateJwkThumbprintUri(jwk, 'sha512'), 'urn:ietf:params:oauth:jwk-thumbprint:sha-512:DpvEwocfn3FjeWWQjcJHzWrpKTIymKwgoL1xVgQcud48-qZDSRCr1zfWZQdHAJn_ciqXqPTSARyg-L-NyNGpVA', ) }) test('JWK must be an object', async (t) => { await t.throwsAsync(calculateJwkThumbprint(true), { instanceOf: TypeError, message: 'JWK must be an object', }) await t.throwsAsync(calculateJwkThumbprint(null), { instanceOf: TypeError, message: 'JWK must be an object', }) await t.throwsAsync(calculateJwkThumbprint(Boolean), { instanceOf: TypeError, message: 'JWK must be an object', }) await t.throwsAsync(calculateJwkThumbprint([]), { instanceOf: TypeError, message: 'JWK must be an object', }) await t.throwsAsync(calculateJwkThumbprint(''), { instanceOf: TypeError, message: 'JWK must be an object', }) const nullPrototype = Object.create(null) nullPrototype.crv = 'P-256' nullPrototype.kty = 'EC' nullPrototype.x = 'q3zAwR_kUwtdLEwtB2oVfucXiLHmEhu9bJUFYjJxYGs' nullPrototype.y = '8h0D-ONoU-iZqrq28TyUxEULxuGwJZGMJYTMbeMshvI' await t.notThrowsAsync(calculateJwkThumbprint(nullPrototype)) }) test('JWK kty must be recognized', async (t) => { await t.throwsAsync(calculateJwkThumbprint({ kty: 'unrecognized' }), { code: 'ERR_JOSE_NOT_SUPPORTED', message: '"kty" (Key Type) Parameter missing or unsupported', }) }) test('EC JWK', async (t) => { const ec = { crv: 'P-256', kty: 'EC', x: 'q3zAwR_kUwtdLEwtB2oVfucXiLHmEhu9bJUFYjJxYGs', y: '8h0D-ONoU-iZqrq28TyUxEULxuGwJZGMJYTMbeMshvI', } await t.throwsAsync(calculateJwkThumbprint({ ...ec, crv: undefined }), { code: 'ERR_JWK_INVALID', message: '"crv" (Curve) Parameter missing or invalid', }) await t.throwsAsync(calculateJwkThumbprint({ ...ec, x: undefined }), { code: 'ERR_JWK_INVALID', message: '"x" (X Coordinate) Parameter missing or invalid', }) await t.throwsAsync(calculateJwkThumbprint({ ...ec, y: undefined }), { code: 'ERR_JWK_INVALID', message: '"y" (Y Coordinate) Parameter missing or invalid', }) t.is(await calculateJwkThumbprint(ec), 'ZrBaai73Hi8Fg4MElvDGzIne2NsbI75RHubOViHYE5Q') }) test('OKP JWK', async (t) => { const okp = { crv: 'Ed25519', kty: 'OKP', x: '5fL1GDeyNTIxtuzTeFnvZTo4Oz0EkMfAdhIJA-EFn0w', } await t.throwsAsync(calculateJwkThumbprint({ ...okp, crv: undefined }), { code: 'ERR_JWK_INVALID', message: '"crv" (Subtype of Key Pair) Parameter missing or invalid', }) await t.throwsAsync(calculateJwkThumbprint({ ...okp, x: undefined }), { code: 'ERR_JWK_INVALID', message: '"x" (Public Key) Parameter missing or invalid', }) t.is(await calculateJwkThumbprint(okp), '1OzNmMHhNzbSJyoePAtdoVedRZlFvER3K3RAzCrfX0k') }) test('RSA JWK', async (t) => { const rsa = { e: 'AQAB', kty: 'RSA', n: 'ok6WYUlmj2J1p-Sm0kwaZlAbWetUooe2LR6iAOJfntavWlyBO0shK_550YG3lQ6R1YeKisNAqbQ1pjqo3vwvR_v_AWtZ1gY1h6KX4DhCv0nNMexZ4g67LxEweoQ4_InMMiwMyQ3CRVJ3P1w0TQZYqzfSye-llY39tyzHeHeuotgrZrM427iUuIJdN38nZ2vW9VpK3bo_Nsvl12ZBe6x7DBzWEFHqQDFyjy8lH8EZyxqDArLA7T5OAcEdkm3RI8jBbsrUD9IySCE5SdEU3n0VGNGkT88DFU85QGvLpL2ITbGX0amaJvxYjIRhIYTfZS6Mqoxr6K1LIwP8pu0VD2Ca5Q', } await t.throwsAsync(calculateJwkThumbprint({ ...rsa, e: undefined }), { code: 'ERR_JWK_INVALID', message: '"e" (Exponent) Parameter missing or invalid', }) await t.throwsAsync(calculateJwkThumbprint({ ...rsa, n: undefined }), { code: 'ERR_JWK_INVALID', message: '"n" (Modulus) Parameter missing or invalid', }) t.is(await calculateJwkThumbprint(rsa), 'dQiQXSGtV4XcPK143Cu2-ZSsQtVNjQZrleUMs9nLnKQ') }) test('oct JWK', async (t) => { const oct = { k: 'FyCq1CKBflh3I5gikEjpYrdOXllzxB_yc02za8ERknI', kty: 'oct', } await t.throwsAsync(calculateJwkThumbprint({ ...oct, k: undefined }), { code: 'ERR_JWK_INVALID', message: '"k" (Key Value) Parameter missing or invalid', }) t.is(await calculateJwkThumbprint(oct), 'prDKy90VJzrDTpm8-W2Q_pv_kzrX_zyZ7ANjRAasDxc') }) jose-4.11.4/test/jwks/000077500000000000000000000000001437043056600145065ustar00rootroot00000000000000jose-4.11.4/test/jwks/local.test.mjs000066400000000000000000000220471437043056600172760ustar00rootroot00000000000000import test from 'ava' import { root, keyRoot } from '../dist.mjs' const { jwtVerify, SignJWT, FlattenedSign, flattenedVerify, GeneralSign, generalVerify, CompactSign, compactVerify, } = await import(root) const { importJWK, createLocalJWKSet } = await import(keyRoot) test('LocalJWKSet', async (t) => { for (const f of [ null, {}, { keys: null }, { keys: {} }, { keys: [null] }, { keys: [0] }, { keys: [undefined] }, { keys: [[]] }, 1, Boolean, ]) { t.throws(() => createLocalJWKSet(f), { code: 'ERR_JWKS_INVALID' }) } const keys = [ { e: 'AQAB', n: 'wAR7gpvDJx2cUR15R1gyBYxEXanhOIDzk7evzadBpNCEpf6HA6utqMrf8dZ3EXSslKPSPBD5Qrz63kc2u8y7NqzwJQIi_i5xR6AxAyWLG3_kOHBwxnct6talLCZqgr8pDwnyP1BPnIaNf2hZxgS-UZbHCAVycd1n2qCdyb4FzFhcaNtiOLg5VSfgvtOdhHQlDXW-DBvwatpd9HzzTP6l5MZRyQ-N_AoGbIfhNCZRUfnb-A8IBPSqXBWN4TEpt-0yHAOIhWnSpu66AYE4f1efZdHVFCTQZ13e5bS-5RQra4pfmGqU9hog1j1SpHnDTia-s__qGi43rev2MqzY-qeUlw', d: 'buWn14TSLtMhJo_ZLWU4bo_WJCoq0xFWm-eodyOz-9YZ5iycGXibcTLKJ8fvOHuj-KysjNhYvTybvqhuagQR08AJabZUM2zrK6zO4bxbHOS-EAKQf27xbAHPnzIIrb5tnivmZr6hXAsxyXWg84ZlzIVCKdXLhQuUIWZF-u_uNVeJSUTDMRVTL2J0mzAGTXqi-yHejapEeLS7lFXDe6cpDnBVXauJfB4GmSUOjxtdAEVW7uGNQJGarGwRz6l3Tpy_xQiYl8e_IrU1N6qAN_HJEBrdgfK7js93RcsxHGbtdnj1ylevZqGFpB1UXrWE4JSz3sJgyXrmKNFFWOCjalMccQ', p: '98OCXxur1omXdjfWkDubqkI3xRehVQryIhqt0go-1yLS4Nwa7KyrdAbzTo81bCHN0A-NlmIvHA4YZc8QUHftq65s4nCbb3g_CwTfGCJEVCvoaTO2EE6Pd8VrGu2PVsN4SM52Gc0TNJGS54yUhyCWDTi1onUBEg8gnqpMSoWuaVM', q: 'xmaRdSJf4wN5Vse5jiIjZy5jy9veHHhzXxTmW25epr9KTMERUDDCzX0bNbnF8jCvDFN5ebzcEe-9nkWyzJ17wVcJTouEfw8A5pBPcx6Gr8Kd8WIrUjuom4xu-4619kMItoV4j62_nq3p0QUGot_6CgUdq63PCp9Fh-sHv8wViy0', dp: '0OCXwbzfYu_-rCCpGFHYi3Jl-BhS4BJpTc02K3SNw-vM4ttNK6jqptfRObLMNAxPqg_iqxy9YKaVdQdbVqu0yF811rVepVw3sf96YatJ9bhKqJ566EaC91ONV1dd16TVfHPq5xeYEGKF-gXvlfgn6J-dqYeAzovIUVt7E_ydrJc', dq: 'sYDOnqe0dhyDkNp77ugoGIZujtMVcw9o2SaPujmSwUjfprANV1tozgQiNf0RVk-sLTD5u6r2ka2WTmY5Q8uaDy5Zi0ZTsoGv4pg2HN6wzcsnF_EmpRnvDcuk97eEoOD0iKf9Zz6h88vRJ0qB13Lf99r_4rtMQ0qgIKxscHKcy7k', qi: '7uvpgL15VFjd_zjhU0fPVeTzAa6Vg3P3Q2v5DLwLkAIlQDqF50maTYztxtxssVNJtEMIxKefwrmGkyVCXNhrGHZDoj7wj-2o0k878bQqtltCO2TPm9TSYZgW7dR3ji0t4Msc5DcrQL002M_Vxqr9MAunQcAsnulRTepQM2n-aOc', kty: 'RSA', kid: 'ZuLUAgyr6RQV3ERjDukHzOO_90rVbrPiE1vD_HtPFuM', }, { e: 'AQAB', n: '0PjQVV2ZAT27Y0h7hfAWWcnPetORCvR1_gHvEUxtlrlnhZia7utHl7BCJH9HP17YHMMBeeEkmUDflYoUL6MDl4DYHgVDq8jZfu1pxH1XqrpeswqOVoReknEe0F5kRt_mPtIoShI2Qv-pxGAw392akAXTirVRLL4Fn_0Oiifxp182P7eTPy41rlKDevLHuKHBZzzaes_33YE2epY2YCLp9k3mZ-tJEei2qiq0T1fERQicGUL8kppOnz0cDNuKRBHyYtXWhjhuDQ8OZQHNLfte9cqzTJMJ4Leu4MGjikSZMsk-_aRFnXtYHH0orwY-giSenRnwNaReAXaR1Px9ReljAQ', d: 'LXGufKH6IBb4pUKh-iKX-ba1dBSGOkenUTHCd5STUG_JX3gsWUC5NPeTqrQzHkjV3otZytN3TgyZkr-QXDurEEtotD6Y1Ma85aljkuNfKTWWWoE1KwNmPZp0BQRB8lfGjmrNcC49tpw6owX4GvbqId_ifQupN32rY3t4qfq9xpO9SAqZF0oUMoS7xE0zChsCJmNYpD9jx87p5Vud1naeaZPlvwWW0ITV4kp2zjYSbBh5DkI52rSrGjkuzlsJ_lKJk5YB557OHhN9XTRBnjqlwwWevh6QAoUivqpcelcplgmfxTHoII1opovYXn8AVt-DbGSO_7LLJ0Sw9sJR5GAqcQ', p: '9RdDqZ3O73lH6nWUGi0abQRRfgvj-HM0zP7GSDQ185l-ZByletl1VuJ86qYJTUY8Q3Gagv6_eXmQMo_14-0wT_FPUMiTMYsjw5QNgFgjlJTM1AayS_U5ddix_Ut7Kti7EXgM0gsavsIazv2-xwCrFzD4sa-t2FWELzzWxgt8wbs', q: '2kX8MN8ItGnn7NnPx-0iqe8kkhy5s9gJRiD3mxN9E6xzRCnf488yhc3aBwI9kZzQtV0XVjX5VhCws5vnJv9b7KA8NATDhpGNrqy2h9ncmsjTTjafUg3jb6QG08kIKDR-A97Mc-MJbIUNzYs10BAG4z9wk7t1bdo4gZJEvjiXVHM', dp: 'Ahggy-I9Um6G3soCafbYsvXGfH09hXH2kYnbx-IqU9qL6e8UuugAyK1Gw_qHOdHP0gO2fkgO-sq_IK96OmhccVJuixIrr9CwjYtGUkJui2Z6GZW1EFEYHJmta6ypcMRJVOzhrynJILgn4nzolGq9C4WvmlUV9zND3eN3MloGxuE', dq: 'uXKWlusX2TjVvM0-FO2r8tdkqeNP_7XAA15FIPOI5Cszb6loOIQ0t6wy3puPteSXClBCYJPQ-MeLab4-wUpaTovBOq0FdpK53ruNBZUbMkMIDL6p1CxKnPKufkeh747RtfYYnSk7O4E8PfNV0CWdxHuE6W9ukNvEAIpGb5tjL3M', qi: '3BLQ03cHEmO8nUT7U8M_H_JciEWAH8XWh_9nihIhXzLKYbNmWM16Ah0F9DUg0GPeiG7e_08ZJ4X3oK1bHnnXdns6NSOEoULWfHl5LUY5PoFPYaBDy3f6td2SCTE83p1YzegXKysWEk1snA2ROq4UEfz1vL8v64RtwR3SvNrAyOI', kty: 'RSA', alg: 'RS256', kid: 'hJU8GvYjtifxLVuBDSNmhLBF19wQHaZvQhfpT3wKzpE', }, { crv: 'P-256', x: 'fqCXPnWs3sSfwztvwYU9SthmRdoT4WCXxS8eD8icF6U', y: 'nP6GIc42c61hoKqPcZqkvzhzIJkBV3Jw3g8sGG7UeP8', d: 'XikZvoy8ayRpOnuz7ont2DkgMxp_kmmg1EKcuIJWX_E', kty: 'EC', kid: 'a-5xuiQoRqlLBtec9jRpXoGTVOP10SGnj2Und0CHHxw', }, ] const jwks = { keys: [ { e: 'AQAB', n: 'wAR7gpvDJx2cUR15R1gyBYxEXanhOIDzk7evzadBpNCEpf6HA6utqMrf8dZ3EXSslKPSPBD5Qrz63kc2u8y7NqzwJQIi_i5xR6AxAyWLG3_kOHBwxnct6talLCZqgr8pDwnyP1BPnIaNf2hZxgS-UZbHCAVycd1n2qCdyb4FzFhcaNtiOLg5VSfgvtOdhHQlDXW-DBvwatpd9HzzTP6l5MZRyQ-N_AoGbIfhNCZRUfnb-A8IBPSqXBWN4TEpt-0yHAOIhWnSpu66AYE4f1efZdHVFCTQZ13e5bS-5RQra4pfmGqU9hog1j1SpHnDTia-s__qGi43rev2MqzY-qeUlw', kty: 'RSA', kid: 'ZuLUAgyr6RQV3ERjDukHzOO_90rVbrPiE1vD_HtPFuM', }, { e: 'AQAB', n: '0PjQVV2ZAT27Y0h7hfAWWcnPetORCvR1_gHvEUxtlrlnhZia7utHl7BCJH9HP17YHMMBeeEkmUDflYoUL6MDl4DYHgVDq8jZfu1pxH1XqrpeswqOVoReknEe0F5kRt_mPtIoShI2Qv-pxGAw392akAXTirVRLL4Fn_0Oiifxp182P7eTPy41rlKDevLHuKHBZzzaes_33YE2epY2YCLp9k3mZ-tJEei2qiq0T1fERQicGUL8kppOnz0cDNuKRBHyYtXWhjhuDQ8OZQHNLfte9cqzTJMJ4Leu4MGjikSZMsk-_aRFnXtYHH0orwY-giSenRnwNaReAXaR1Px9ReljAQ', alg: 'RS256', kty: 'RSA', kid: 'hJU8GvYjtifxLVuBDSNmhLBF19wQHaZvQhfpT3wKzpE', }, { crv: 'P-256', x: 'fqCXPnWs3sSfwztvwYU9SthmRdoT4WCXxS8eD8icF6U', y: 'nP6GIc42c61hoKqPcZqkvzhzIJkBV3Jw3g8sGG7UeP8', kty: 'EC', kid: 'a-5xuiQoRqlLBtec9jRpXoGTVOP10SGnj2Und0CHHxw', }, { e: 'AQAB', n: '0PjQVV2ZAT27Y0h7hfAWWcnPetORCvR1_gHvEUxtlrlnhZia7utHl7BCJH9HP17YHMMBeeEkmUDflYoUL6MDl4DYHgVDq8jZfu1pxH1XqrpeswqOVoReknEe0F5kRt_mPtIoShI2Qv-pxGAw392akAXTirVRLL4Fn_0Oiifxp182P7eTPy41rlKDevLHuKHBZzzaes_33YE2epY2YCLp9k3mZ-tJEei2qiq0T1fERQicGUL8kppOnz0cDNuKRBHyYtXWhjhuDQ8OZQHNLfte9cqzTJMJ4Leu4MGjikSZMsk-_aRFnXtYHH0orwY-giSenRnwNaReAXaR1Px9ReljAQ', alg: 'RS256', kty: 'RSA', use: 'enc', }, { e: 'AQAB', n: '0PjQVV2ZAT27Y0h7hfAWWcnPetORCvR1_gHvEUxtlrlnhZia7utHl7BCJH9HP17YHMMBeeEkmUDflYoUL6MDl4DYHgVDq8jZfu1pxH1XqrpeswqOVoReknEe0F5kRt_mPtIoShI2Qv-pxGAw392akAXTirVRLL4Fn_0Oiifxp182P7eTPy41rlKDevLHuKHBZzzaes_33YE2epY2YCLp9k3mZ-tJEei2qiq0T1fERQicGUL8kppOnz0cDNuKRBHyYtXWhjhuDQ8OZQHNLfte9cqzTJMJ4Leu4MGjikSZMsk-_aRFnXtYHH0orwY-giSenRnwNaReAXaR1Px9ReljAQ', alg: 'RS256', kty: 'RSA', use: 'sig', key_ops: [], }, ], } const JWKS = createLocalJWKSet(jwks) // Signed JWT { const [jwk] = keys const key = await importJWK({ ...jwk, alg: 'PS256' }) const jwt = await new SignJWT({}).setProtectedHeader({ alg: 'PS256', kid: jwk.kid }).sign(key) await t.notThrowsAsync(async () => { const { key: resolvedKey } = await jwtVerify(jwt, JWKS) t.truthy(resolvedKey) t.is(resolvedKey.type, 'public') }) } // Compact JWS { const [jwk] = keys const key = await importJWK({ ...jwk, alg: 'PS256' }) const jws = await new CompactSign(new Uint8Array(1)) .setProtectedHeader({ alg: 'PS256', kid: jwk.kid }) .sign(key) await t.notThrowsAsync(async () => { const { key: resolvedKey } = await compactVerify(jws, JWKS) t.truthy(resolvedKey) t.is(resolvedKey.type, 'public') }) } // Flattened JWS { const [jwk] = keys const key = await importJWK({ ...jwk, alg: 'PS256' }) const jws = await new FlattenedSign(new Uint8Array(1)) .setProtectedHeader({ alg: 'PS256' }) .setUnprotectedHeader({ kid: jwk.kid }) .sign(key) await t.notThrowsAsync(async () => { const { key: resolvedKey } = await flattenedVerify(jws, JWKS) t.truthy(resolvedKey) t.is(resolvedKey.type, 'public') }) } // General JWS { const [jwk] = keys const key = await importJWK({ ...jwk, alg: 'PS256' }) const jws = await new GeneralSign(new Uint8Array(1)) .addSignature(key) .setProtectedHeader({ alg: 'PS256' }) .setUnprotectedHeader({ kid: jwk.kid }) .sign() await t.notThrowsAsync(async () => { const { key: resolvedKey } = await generalVerify(jws, JWKS) t.truthy(resolvedKey) t.is(resolvedKey.type, 'public') }) } { const [jwk] = keys const key = await importJWK({ ...jwk, alg: 'RS256' }) const jwt = await new SignJWT({}).setProtectedHeader({ alg: 'RS256' }).sign(key) await t.throwsAsync(jwtVerify(jwt, JWKS), { code: 'ERR_JWKS_MULTIPLE_MATCHING_KEYS', message: 'multiple matching keys found in the JSON Web Key Set', }) } { const [, jwk] = keys const key = await importJWK({ ...jwk, alg: 'PS256' }) const jwt = await new SignJWT({}).setProtectedHeader({ alg: 'PS256', kid: jwk.kid }).sign(key) await t.throwsAsync(jwtVerify(jwt, JWKS), { code: 'ERR_JWKS_NO_MATCHING_KEY', message: 'no applicable key found in the JSON Web Key Set', }) } { const [, , jwk] = keys const key = await importJWK({ ...jwk, alg: 'ES256' }) const jwt = await new SignJWT({}).setProtectedHeader({ alg: 'ES256' }).sign(key) await t.notThrowsAsync(jwtVerify(jwt, JWKS)) } }) jose-4.11.4/test/jwks/remote.test.mjs000066400000000000000000000404121437043056600174730ustar00rootroot00000000000000import test from 'ava' import nock from 'nock' import timekeeper from 'timekeeper' import { createServer } from 'http' import { once } from 'events' import { root, keyRoot } from '../dist.mjs' const skipOnUndiciTest = 'WEBAPI' in process.env ? test.skip : test const skipOnUndiciTestSerial = 'WEBAPI' in process.env ? test.skip : test.serial const skipOnUndiciTestAndCI = 'WEBAPI' in process.env || 'CI' in process.env ? test.skip : test.serial const { jwtVerify, SignJWT, FlattenedSign, flattenedVerify, GeneralSign, generalVerify, CompactSign, compactVerify, } = await import(root) const { importJWK, createRemoteJWKSet } = await import(keyRoot) const now = 1604416038 test.before(async (t) => { nock.disableNetConnect() t.context.server = createServer().unref().listen(3000) t.context.server.removeAllListeners('request') await once(t.context.server, 'listening') }) test.after(async (t) => { nock.enableNetConnect() await new Promise((resolve) => t.context.server.close(resolve)) }) test.afterEach(() => { nock.disableNetConnect() }) test.afterEach((t) => { t.context.server.removeAllListeners('request') t.true(nock.isDone()) nock.cleanAll() }) test.afterEach(() => timekeeper.reset()) skipOnUndiciTestSerial('RemoteJWKSet', async (t) => { const keys = [ { e: 'AQAB', n: 'wAR7gpvDJx2cUR15R1gyBYxEXanhOIDzk7evzadBpNCEpf6HA6utqMrf8dZ3EXSslKPSPBD5Qrz63kc2u8y7NqzwJQIi_i5xR6AxAyWLG3_kOHBwxnct6talLCZqgr8pDwnyP1BPnIaNf2hZxgS-UZbHCAVycd1n2qCdyb4FzFhcaNtiOLg5VSfgvtOdhHQlDXW-DBvwatpd9HzzTP6l5MZRyQ-N_AoGbIfhNCZRUfnb-A8IBPSqXBWN4TEpt-0yHAOIhWnSpu66AYE4f1efZdHVFCTQZ13e5bS-5RQra4pfmGqU9hog1j1SpHnDTia-s__qGi43rev2MqzY-qeUlw', d: 'buWn14TSLtMhJo_ZLWU4bo_WJCoq0xFWm-eodyOz-9YZ5iycGXibcTLKJ8fvOHuj-KysjNhYvTybvqhuagQR08AJabZUM2zrK6zO4bxbHOS-EAKQf27xbAHPnzIIrb5tnivmZr6hXAsxyXWg84ZlzIVCKdXLhQuUIWZF-u_uNVeJSUTDMRVTL2J0mzAGTXqi-yHejapEeLS7lFXDe6cpDnBVXauJfB4GmSUOjxtdAEVW7uGNQJGarGwRz6l3Tpy_xQiYl8e_IrU1N6qAN_HJEBrdgfK7js93RcsxHGbtdnj1ylevZqGFpB1UXrWE4JSz3sJgyXrmKNFFWOCjalMccQ', p: '98OCXxur1omXdjfWkDubqkI3xRehVQryIhqt0go-1yLS4Nwa7KyrdAbzTo81bCHN0A-NlmIvHA4YZc8QUHftq65s4nCbb3g_CwTfGCJEVCvoaTO2EE6Pd8VrGu2PVsN4SM52Gc0TNJGS54yUhyCWDTi1onUBEg8gnqpMSoWuaVM', q: 'xmaRdSJf4wN5Vse5jiIjZy5jy9veHHhzXxTmW25epr9KTMERUDDCzX0bNbnF8jCvDFN5ebzcEe-9nkWyzJ17wVcJTouEfw8A5pBPcx6Gr8Kd8WIrUjuom4xu-4619kMItoV4j62_nq3p0QUGot_6CgUdq63PCp9Fh-sHv8wViy0', dp: '0OCXwbzfYu_-rCCpGFHYi3Jl-BhS4BJpTc02K3SNw-vM4ttNK6jqptfRObLMNAxPqg_iqxy9YKaVdQdbVqu0yF811rVepVw3sf96YatJ9bhKqJ566EaC91ONV1dd16TVfHPq5xeYEGKF-gXvlfgn6J-dqYeAzovIUVt7E_ydrJc', dq: 'sYDOnqe0dhyDkNp77ugoGIZujtMVcw9o2SaPujmSwUjfprANV1tozgQiNf0RVk-sLTD5u6r2ka2WTmY5Q8uaDy5Zi0ZTsoGv4pg2HN6wzcsnF_EmpRnvDcuk97eEoOD0iKf9Zz6h88vRJ0qB13Lf99r_4rtMQ0qgIKxscHKcy7k', qi: '7uvpgL15VFjd_zjhU0fPVeTzAa6Vg3P3Q2v5DLwLkAIlQDqF50maTYztxtxssVNJtEMIxKefwrmGkyVCXNhrGHZDoj7wj-2o0k878bQqtltCO2TPm9TSYZgW7dR3ji0t4Msc5DcrQL002M_Vxqr9MAunQcAsnulRTepQM2n-aOc', kty: 'RSA', kid: 'ZuLUAgyr6RQV3ERjDukHzOO_90rVbrPiE1vD_HtPFuM', }, { e: 'AQAB', n: '0PjQVV2ZAT27Y0h7hfAWWcnPetORCvR1_gHvEUxtlrlnhZia7utHl7BCJH9HP17YHMMBeeEkmUDflYoUL6MDl4DYHgVDq8jZfu1pxH1XqrpeswqOVoReknEe0F5kRt_mPtIoShI2Qv-pxGAw392akAXTirVRLL4Fn_0Oiifxp182P7eTPy41rlKDevLHuKHBZzzaes_33YE2epY2YCLp9k3mZ-tJEei2qiq0T1fERQicGUL8kppOnz0cDNuKRBHyYtXWhjhuDQ8OZQHNLfte9cqzTJMJ4Leu4MGjikSZMsk-_aRFnXtYHH0orwY-giSenRnwNaReAXaR1Px9ReljAQ', d: 'LXGufKH6IBb4pUKh-iKX-ba1dBSGOkenUTHCd5STUG_JX3gsWUC5NPeTqrQzHkjV3otZytN3TgyZkr-QXDurEEtotD6Y1Ma85aljkuNfKTWWWoE1KwNmPZp0BQRB8lfGjmrNcC49tpw6owX4GvbqId_ifQupN32rY3t4qfq9xpO9SAqZF0oUMoS7xE0zChsCJmNYpD9jx87p5Vud1naeaZPlvwWW0ITV4kp2zjYSbBh5DkI52rSrGjkuzlsJ_lKJk5YB557OHhN9XTRBnjqlwwWevh6QAoUivqpcelcplgmfxTHoII1opovYXn8AVt-DbGSO_7LLJ0Sw9sJR5GAqcQ', p: '9RdDqZ3O73lH6nWUGi0abQRRfgvj-HM0zP7GSDQ185l-ZByletl1VuJ86qYJTUY8Q3Gagv6_eXmQMo_14-0wT_FPUMiTMYsjw5QNgFgjlJTM1AayS_U5ddix_Ut7Kti7EXgM0gsavsIazv2-xwCrFzD4sa-t2FWELzzWxgt8wbs', q: '2kX8MN8ItGnn7NnPx-0iqe8kkhy5s9gJRiD3mxN9E6xzRCnf488yhc3aBwI9kZzQtV0XVjX5VhCws5vnJv9b7KA8NATDhpGNrqy2h9ncmsjTTjafUg3jb6QG08kIKDR-A97Mc-MJbIUNzYs10BAG4z9wk7t1bdo4gZJEvjiXVHM', dp: 'Ahggy-I9Um6G3soCafbYsvXGfH09hXH2kYnbx-IqU9qL6e8UuugAyK1Gw_qHOdHP0gO2fkgO-sq_IK96OmhccVJuixIrr9CwjYtGUkJui2Z6GZW1EFEYHJmta6ypcMRJVOzhrynJILgn4nzolGq9C4WvmlUV9zND3eN3MloGxuE', dq: 'uXKWlusX2TjVvM0-FO2r8tdkqeNP_7XAA15FIPOI5Cszb6loOIQ0t6wy3puPteSXClBCYJPQ-MeLab4-wUpaTovBOq0FdpK53ruNBZUbMkMIDL6p1CxKnPKufkeh747RtfYYnSk7O4E8PfNV0CWdxHuE6W9ukNvEAIpGb5tjL3M', qi: '3BLQ03cHEmO8nUT7U8M_H_JciEWAH8XWh_9nihIhXzLKYbNmWM16Ah0F9DUg0GPeiG7e_08ZJ4X3oK1bHnnXdns6NSOEoULWfHl5LUY5PoFPYaBDy3f6td2SCTE83p1YzegXKysWEk1snA2ROq4UEfz1vL8v64RtwR3SvNrAyOI', kty: 'RSA', alg: 'RS256', kid: 'hJU8GvYjtifxLVuBDSNmhLBF19wQHaZvQhfpT3wKzpE', }, { crv: 'P-256', x: 'fqCXPnWs3sSfwztvwYU9SthmRdoT4WCXxS8eD8icF6U', y: 'nP6GIc42c61hoKqPcZqkvzhzIJkBV3Jw3g8sGG7UeP8', d: 'XikZvoy8ayRpOnuz7ont2DkgMxp_kmmg1EKcuIJWX_E', kty: 'EC', kid: 'a-5xuiQoRqlLBtec9jRpXoGTVOP10SGnj2Und0CHHxw', }, ] const jwks = { keys: [ { e: 'AQAB', n: 'wAR7gpvDJx2cUR15R1gyBYxEXanhOIDzk7evzadBpNCEpf6HA6utqMrf8dZ3EXSslKPSPBD5Qrz63kc2u8y7NqzwJQIi_i5xR6AxAyWLG3_kOHBwxnct6talLCZqgr8pDwnyP1BPnIaNf2hZxgS-UZbHCAVycd1n2qCdyb4FzFhcaNtiOLg5VSfgvtOdhHQlDXW-DBvwatpd9HzzTP6l5MZRyQ-N_AoGbIfhNCZRUfnb-A8IBPSqXBWN4TEpt-0yHAOIhWnSpu66AYE4f1efZdHVFCTQZ13e5bS-5RQra4pfmGqU9hog1j1SpHnDTia-s__qGi43rev2MqzY-qeUlw', kty: 'RSA', kid: 'ZuLUAgyr6RQV3ERjDukHzOO_90rVbrPiE1vD_HtPFuM', }, { e: 'AQAB', n: '0PjQVV2ZAT27Y0h7hfAWWcnPetORCvR1_gHvEUxtlrlnhZia7utHl7BCJH9HP17YHMMBeeEkmUDflYoUL6MDl4DYHgVDq8jZfu1pxH1XqrpeswqOVoReknEe0F5kRt_mPtIoShI2Qv-pxGAw392akAXTirVRLL4Fn_0Oiifxp182P7eTPy41rlKDevLHuKHBZzzaes_33YE2epY2YCLp9k3mZ-tJEei2qiq0T1fERQicGUL8kppOnz0cDNuKRBHyYtXWhjhuDQ8OZQHNLfte9cqzTJMJ4Leu4MGjikSZMsk-_aRFnXtYHH0orwY-giSenRnwNaReAXaR1Px9ReljAQ', alg: 'RS256', kty: 'RSA', kid: 'hJU8GvYjtifxLVuBDSNmhLBF19wQHaZvQhfpT3wKzpE', }, { crv: 'P-256', x: 'fqCXPnWs3sSfwztvwYU9SthmRdoT4WCXxS8eD8icF6U', y: 'nP6GIc42c61hoKqPcZqkvzhzIJkBV3Jw3g8sGG7UeP8', kty: 'EC', kid: 'a-5xuiQoRqlLBtec9jRpXoGTVOP10SGnj2Und0CHHxw', }, { e: 'AQAB', n: '0PjQVV2ZAT27Y0h7hfAWWcnPetORCvR1_gHvEUxtlrlnhZia7utHl7BCJH9HP17YHMMBeeEkmUDflYoUL6MDl4DYHgVDq8jZfu1pxH1XqrpeswqOVoReknEe0F5kRt_mPtIoShI2Qv-pxGAw392akAXTirVRLL4Fn_0Oiifxp182P7eTPy41rlKDevLHuKHBZzzaes_33YE2epY2YCLp9k3mZ-tJEei2qiq0T1fERQicGUL8kppOnz0cDNuKRBHyYtXWhjhuDQ8OZQHNLfte9cqzTJMJ4Leu4MGjikSZMsk-_aRFnXtYHH0orwY-giSenRnwNaReAXaR1Px9ReljAQ', alg: 'RS256', kty: 'RSA', use: 'enc', }, { e: 'AQAB', n: '0PjQVV2ZAT27Y0h7hfAWWcnPetORCvR1_gHvEUxtlrlnhZia7utHl7BCJH9HP17YHMMBeeEkmUDflYoUL6MDl4DYHgVDq8jZfu1pxH1XqrpeswqOVoReknEe0F5kRt_mPtIoShI2Qv-pxGAw392akAXTirVRLL4Fn_0Oiifxp182P7eTPy41rlKDevLHuKHBZzzaes_33YE2epY2YCLp9k3mZ-tJEei2qiq0T1fERQicGUL8kppOnz0cDNuKRBHyYtXWhjhuDQ8OZQHNLfte9cqzTJMJ4Leu4MGjikSZMsk-_aRFnXtYHH0orwY-giSenRnwNaReAXaR1Px9ReljAQ', alg: 'RS256', kty: 'RSA', use: 'sig', key_ops: [], }, ], } nock('https://as.example.com').get('/jwks').reply(200, jwks) const url = new URL('https://as.example.com/jwks') const JWKS = createRemoteJWKSet(url) // Signed JWT { const [jwk] = keys const key = await importJWK({ ...jwk, alg: 'PS256' }) const jwt = await new SignJWT({}).setProtectedHeader({ alg: 'PS256', kid: jwk.kid }).sign(key) await t.notThrowsAsync(async () => { const { key: resolvedKey } = await jwtVerify(jwt, JWKS) t.truthy(resolvedKey) t.is(resolvedKey.type, 'public') }) } // Compact JWS { const [jwk] = keys const key = await importJWK({ ...jwk, alg: 'PS256' }) const jws = await new CompactSign(new Uint8Array(1)) .setProtectedHeader({ alg: 'PS256', kid: jwk.kid }) .sign(key) await t.notThrowsAsync(async () => { const { key: resolvedKey } = await compactVerify(jws, JWKS) t.truthy(resolvedKey) t.is(resolvedKey.type, 'public') }) } // Flattened JWS { const [jwk] = keys const key = await importJWK({ ...jwk, alg: 'PS256' }) const jws = await new FlattenedSign(new Uint8Array(1)) .setProtectedHeader({ alg: 'PS256' }) .setUnprotectedHeader({ kid: jwk.kid }) .sign(key) await t.notThrowsAsync(async () => { const { key: resolvedKey } = await flattenedVerify(jws, JWKS) t.truthy(resolvedKey) t.is(resolvedKey.type, 'public') }) } // General JWS { const [jwk] = keys const key = await importJWK({ ...jwk, alg: 'PS256' }) const jws = await new GeneralSign(new Uint8Array(1)) .addSignature(key) .setProtectedHeader({ alg: 'PS256' }) .setUnprotectedHeader({ kid: jwk.kid }) .sign() await t.notThrowsAsync(async () => { const { key: resolvedKey } = await generalVerify(jws, JWKS) t.truthy(resolvedKey) t.is(resolvedKey.type, 'public') }) } { const [jwk] = keys const key = await importJWK({ ...jwk, alg: 'RS256' }) const jwt = await new SignJWT({}).setProtectedHeader({ alg: 'RS256' }).sign(key) await t.throwsAsync(jwtVerify(jwt, JWKS), { code: 'ERR_JWKS_MULTIPLE_MATCHING_KEYS', message: 'multiple matching keys found in the JSON Web Key Set', }) } { const [, jwk] = keys const key = await importJWK({ ...jwk, alg: 'PS256' }) const jwt = await new SignJWT({}).setProtectedHeader({ alg: 'PS256', kid: jwk.kid }).sign(key) await t.throwsAsync(jwtVerify(jwt, JWKS), { code: 'ERR_JWKS_NO_MATCHING_KEY', message: 'no applicable key found in the JSON Web Key Set', }) } { const [, , jwk] = keys const key = await importJWK({ ...jwk, alg: 'ES256' }) const jwt = await new SignJWT({}).setProtectedHeader({ alg: 'ES256' }).sign(key) await t.notThrowsAsync(jwtVerify(jwt, JWKS)) } }) skipOnUndiciTestSerial('refreshes the JWKS once off cooldown', async (t) => { timekeeper.freeze(now * 1000) let jwk = { crv: 'P-256', x: 'fqCXPnWs3sSfwztvwYU9SthmRdoT4WCXxS8eD8icF6U', y: 'nP6GIc42c61hoKqPcZqkvzhzIJkBV3Jw3g8sGG7UeP8', d: 'XikZvoy8ayRpOnuz7ont2DkgMxp_kmmg1EKcuIJWX_E', kty: 'EC', } const jwks = { keys: [ { crv: 'P-256', x: 'fqCXPnWs3sSfwztvwYU9SthmRdoT4WCXxS8eD8icF6U', y: 'nP6GIc42c61hoKqPcZqkvzhzIJkBV3Jw3g8sGG7UeP8', kty: 'EC', kid: 'one', }, ], } const scope = nock('https://as.example.com').get('/jwks').once().reply(200, jwks) const url = new URL('https://as.example.com/jwks') const JWKS = createRemoteJWKSet(url) const key = await importJWK({ ...jwk, alg: 'ES256' }) { const jwt = await new SignJWT({}).setProtectedHeader({ alg: 'ES256', kid: 'one' }).sign(key) await t.notThrowsAsync(jwtVerify(jwt, JWKS)) await t.notThrowsAsync(jwtVerify(jwt, JWKS)) } { const jwt = await new SignJWT({}).setProtectedHeader({ alg: 'ES256', kid: 'two' }).sign(key) await t.throwsAsync(jwtVerify(jwt, JWKS), { code: 'ERR_JWKS_NO_MATCHING_KEY', message: 'no applicable key found in the JSON Web Key Set', }) jwks.keys[0].kid = 'two' scope.get('/jwks').once().reply(200, jwks) timekeeper.travel((now + 30) * 1000) await t.notThrowsAsync(jwtVerify(jwt, JWKS)) } }) skipOnUndiciTestSerial('refreshes the JWKS once stale', async (t) => { timekeeper.freeze(now * 1000) let jwk = { crv: 'P-256', x: 'fqCXPnWs3sSfwztvwYU9SthmRdoT4WCXxS8eD8icF6U', y: 'nP6GIc42c61hoKqPcZqkvzhzIJkBV3Jw3g8sGG7UeP8', d: 'XikZvoy8ayRpOnuz7ont2DkgMxp_kmmg1EKcuIJWX_E', kty: 'EC', } const jwks = { keys: [ { crv: 'P-256', x: 'fqCXPnWs3sSfwztvwYU9SthmRdoT4WCXxS8eD8icF6U', y: 'nP6GIc42c61hoKqPcZqkvzhzIJkBV3Jw3g8sGG7UeP8', kty: 'EC', kid: 'one', }, ], } nock('https://as.example.com').get('/jwks').twice().reply(200, jwks) const url = new URL('https://as.example.com/jwks') const JWKS = createRemoteJWKSet(url, { cacheMaxAge: 60 * 10 * 1000 }) const key = await importJWK({ ...jwk, alg: 'ES256' }) { const jwt = await new SignJWT({}).setProtectedHeader({ alg: 'ES256', kid: 'one' }).sign(key) await t.notThrowsAsync(jwtVerify(jwt, JWKS)) await t.notThrowsAsync(jwtVerify(jwt, JWKS)) timekeeper.travel((now + 60 * 10) * 1000) await t.notThrowsAsync(jwtVerify(jwt, JWKS)) } }) skipOnUndiciTestSerial('can be configured to never be stale', async (t) => { timekeeper.freeze(now * 1000) let jwk = { crv: 'P-256', x: 'fqCXPnWs3sSfwztvwYU9SthmRdoT4WCXxS8eD8icF6U', y: 'nP6GIc42c61hoKqPcZqkvzhzIJkBV3Jw3g8sGG7UeP8', d: 'XikZvoy8ayRpOnuz7ont2DkgMxp_kmmg1EKcuIJWX_E', kty: 'EC', } const jwks = { keys: [ { crv: 'P-256', x: 'fqCXPnWs3sSfwztvwYU9SthmRdoT4WCXxS8eD8icF6U', y: 'nP6GIc42c61hoKqPcZqkvzhzIJkBV3Jw3g8sGG7UeP8', kty: 'EC', kid: 'one', }, ], } nock('https://as.example.com').get('/jwks').once().reply(200, jwks) const url = new URL('https://as.example.com/jwks') const JWKS = createRemoteJWKSet(url, { cacheMaxAge: Infinity }) const key = await importJWK({ ...jwk, alg: 'ES256' }) { const jwt = await new SignJWT({}).setProtectedHeader({ alg: 'ES256', kid: 'one' }).sign(key) await t.notThrowsAsync(jwtVerify(jwt, JWKS)) await t.notThrowsAsync(jwtVerify(jwt, JWKS)) timekeeper.travel((now + 60 * 10) * 1000) await t.notThrowsAsync(jwtVerify(jwt, JWKS)) } }) skipOnUndiciTestSerial('throws on invalid JWKSet', async (t) => { const scope = nock('https://as.example.com').get('/jwks').once().reply(200, 'null') const url = new URL('https://as.example.com/jwks') const JWKS = createRemoteJWKSet(url) await t.throwsAsync(JWKS({ alg: 'RS256' }, {}), { code: 'ERR_JWKS_INVALID', message: 'JSON Web Key Set malformed', }) scope.get('/jwks').once().reply(200, {}) await t.throwsAsync(JWKS({ alg: 'RS256' }, {}), { code: 'ERR_JWKS_INVALID', message: 'JSON Web Key Set malformed', }) scope.get('/jwks').once().reply(200, { keys: null }) await t.throwsAsync(JWKS({ alg: 'RS256' }, {}), { code: 'ERR_JWKS_INVALID', message: 'JSON Web Key Set malformed', }) scope .get('/jwks') .once() .reply(200, { keys: [null] }) await t.throwsAsync(JWKS({ alg: 'RS256' }, {}), { code: 'ERR_JWKS_INVALID', message: 'JSON Web Key Set malformed', }) scope.get('/jwks').once().reply(404) await t.throwsAsync(JWKS({ alg: 'RS256' }, {}), { code: 'ERR_JOSE_GENERIC', message: 'Expected 200 OK from the JSON Web Key Set HTTP response', }) scope.get('/jwks').once().reply(200, '{') await t.throwsAsync(JWKS({ alg: 'RS256' }, {}), { code: 'ERR_JOSE_GENERIC', message: 'Failed to parse the JSON Web Key Set HTTP response as JSON', }) }) skipOnUndiciTestSerial('can have headers configured', async (t) => { const scope = nock('https://as.example.com', { reqheaders: { 'x-custom': 'foo', }, }) .get('/jwks') .once() .reply(200, 'null') const url = new URL('https://as.example.com/jwks') const JWKS = createRemoteJWKSet(url, { headers: { 'x-custom': 'foo' } }) await JWKS().catch(() => {}) t.true(scope.isDone()) }) skipOnUndiciTest('handles ENOTFOUND', async (t) => { nock.enableNetConnect() const url = new URL('https://op.example.com/jwks') const JWKS = createRemoteJWKSet(url) await t.throwsAsync(JWKS({ alg: 'RS256' }, {}), { code: 'ENOTFOUND', }) }) skipOnUndiciTest('handles ECONNREFUSED', async (t) => { nock.enableNetConnect() const url = new URL('http://localhost:3001/jwks') const JWKS = createRemoteJWKSet(url) await t.throwsAsync(JWKS({ alg: 'RS256' }, {}), { code: 'ECONNREFUSED', }) }) skipOnUndiciTestAndCI('handles ECONNRESET', async (t) => { nock.enableNetConnect() const url = new URL('http://localhost:3000/jwks') t.context.server.once('connection', (socket) => { socket.destroy() }) const JWKS = createRemoteJWKSet(url) await t.throwsAsync(JWKS({ alg: 'RS256' }, {}), { code: 'ECONNRESET', }) }) skipOnUndiciTestAndCI('handles a timeout', async (t) => { t.timeout(1000) nock.enableNetConnect() const url = new URL('http://localhost:3000/jwks') const JWKS = createRemoteJWKSet(url, { timeoutDuration: 500, }) await t.throwsAsync(JWKS({ alg: 'RS256' }, {}), { code: 'ERR_JWKS_TIMEOUT', }) }) jose-4.11.4/test/jws/000077500000000000000000000000001437043056600143335ustar00rootroot00000000000000jose-4.11.4/test/jws/compact.sign.test.mjs000066400000000000000000000027531437043056600204200ustar00rootroot00000000000000import test from 'ava' import { root } from '../dist.mjs' const { CompactSign } = await import(root) test.before((t) => { const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) t.context.payload = encode('It’s a dangerous business, Frodo, going out your door.') t.context.secret = new Uint8Array(32) }) test('CompactSign', async (t) => { const jws = await new CompactSign(t.context.payload) .setProtectedHeader({ alg: 'HS256' }) .sign(t.context.secret) t.is( jws, 'eyJhbGciOiJIUzI1NiJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4.UKohvCM6JaKEJlDt7ApBPgcQMW4lmp-UGXfwPmCfUaA', ) }) test('CompactSign.prototype.setProtectedHeader', (t) => { t.throws(() => new CompactSign(t.context.payload).setProtectedHeader({}).setProtectedHeader({}), { instanceOf: TypeError, message: 'setProtectedHeader can only be called once', }) }) test('CompactSign.prototype.sign must have a JOSE header', async (t) => { await t.throwsAsync(new CompactSign(t.context.payload).sign(t.context.secret), { code: 'ERR_JWS_INVALID', message: 'either setProtectedHeader or setUnprotectedHeader must be called before #sign()', }) }) test('CompactSign.prototype.sign JOSE header have an alg', async (t) => { await t.throwsAsync( new CompactSign(t.context.payload).setProtectedHeader({}).sign(t.context.secret), { code: 'ERR_JWS_INVALID', message: 'JWS "alg" (Algorithm) Header Parameter missing or invalid', }, ) }) jose-4.11.4/test/jws/compact.verify.test.mjs000066400000000000000000000021571437043056600207620ustar00rootroot00000000000000import test from 'ava' import * as crypto from 'crypto' import { root } from '../dist.mjs' const { compactVerify, CompactSign } = await import(root) test.before(async (t) => { t.context.secret = crypto.randomFillSync(new Uint8Array(32)) }) test('JWS format validation', async (t) => { { await t.notThrowsAsync(async () => { await compactVerify( await new CompactSign(new Uint8Array()) .setProtectedHeader({ alg: 'HS256' }) .sign(t.context.secret), t.context.secret, ) }) } await t.throwsAsync(compactVerify(null, new Uint8Array(0)), { message: 'Compact JWS must be a string or Uint8Array', code: 'ERR_JWS_INVALID', }) await t.throwsAsync(compactVerify('.....', new Uint8Array(0)), { message: 'Invalid Compact JWS', code: 'ERR_JWS_INVALID', }) }) test('sign empty data', async (t) => { const jws = await new CompactSign(new Uint8Array(0)) .setProtectedHeader({ alg: 'HS256' }) .sign(new Uint8Array(32)) t.is(jws.split('.')[1], '') const { payload } = await compactVerify(jws, new Uint8Array(32)) t.is(payload.byteLength, 0) }) jose-4.11.4/test/jws/crit.test.mjs000066400000000000000000000022001437043056600167570ustar00rootroot00000000000000import test from 'ava' import { root } from '../dist.mjs' const { FlattenedSign } = await import(root) const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) test('crit member checks check', async (t) => { await t.throwsAsync( new FlattenedSign(encode('foo')) .setProtectedHeader({ alg: 'HS256' }) .setUnprotectedHeader({ crit: ['b64'] }) .sign(new Uint8Array(32)), { code: 'ERR_JWS_INVALID', message: '"crit" (Critical) Header Parameter MUST be integrity protected', }, ) await t.throwsAsync( new FlattenedSign(encode('foo')) .setProtectedHeader({ alg: 'HS256', crit: [null], b64: false }) .sign(new Uint8Array(32)), { code: 'ERR_JWS_INVALID', message: '"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present', }, ) await t.throwsAsync( new FlattenedSign(encode('foo')) .setProtectedHeader({ alg: 'HS256', crit: ['nope'], nope: 'foo' }) .sign(new Uint8Array(32)), { code: 'ERR_JOSE_NOT_SUPPORTED', message: 'Extension Header Parameter "nope" is not recognized', }, ) }) jose-4.11.4/test/jws/flattened.sign.test.mjs000066400000000000000000000102221437043056600207260ustar00rootroot00000000000000import test from 'ava' import { root } from '../dist.mjs' const { FlattenedSign } = await import(root) test.before(async (t) => { const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) t.context.payload = encode('It’s a dangerous business, Frodo, going out your door.') t.context.secret = new Uint8Array(32) }) test('FlattenedSign', async (t) => { { const jws = await new FlattenedSign(t.context.payload) .setProtectedHeader({ alg: 'HS256' }) .setUnprotectedHeader({ foo: 'bar' }) .sign(t.context.secret) t.deepEqual(jws, { header: { foo: 'bar', }, payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4', protected: 'eyJhbGciOiJIUzI1NiJ9', signature: 'UKohvCM6JaKEJlDt7ApBPgcQMW4lmp-UGXfwPmCfUaA', }) } { const jws = await new FlattenedSign(t.context.payload) .setProtectedHeader({ alg: 'HS256' }) .sign(t.context.secret) t.deepEqual(jws, { protected: 'eyJhbGciOiJIUzI1NiJ9', payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4', signature: 'UKohvCM6JaKEJlDt7ApBPgcQMW4lmp-UGXfwPmCfUaA', }) } { const jws = await new FlattenedSign(t.context.payload) .setUnprotectedHeader({ alg: 'HS256' }) .sign(t.context.secret) t.deepEqual(jws, { header: { alg: 'HS256', }, payload: 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4', signature: 'O7HdMZ_6_aEQWLGGItmCKN3pf8-nZ9mHnPfT7rrPCwk', }) } { for (const value of [ undefined, null, {}, '', 'foo', 1, 0, true, false, [], new FlattenedSign(new Uint8Array()), ]) { t.throws(() => new FlattenedSign(value), { instanceOf: TypeError, message: 'payload must be an instance of Uint8Array', }) } } }) test('FlattenedSign.prototype.setProtectedHeader', (t) => { t.throws( () => new FlattenedSign(t.context.payload).setProtectedHeader({}).setProtectedHeader({}), { instanceOf: TypeError, message: 'setProtectedHeader can only be called once', }, ) }) test('FlattenedSign.prototype.setUnprotectedHeader', (t) => { t.throws( () => new FlattenedSign(t.context.payload).setUnprotectedHeader({}).setUnprotectedHeader({}), { instanceOf: TypeError, message: 'setUnprotectedHeader can only be called once', }, ) }) test('FlattenedSign.prototype.sign must have a JOSE header', async (t) => { await t.throwsAsync(new FlattenedSign(t.context.payload).sign(t.context.secret), { code: 'ERR_JWS_INVALID', message: 'either setProtectedHeader or setUnprotectedHeader must be called before #sign()', }) }) test('FlattenedSign.prototype.sign JOSE header must be disjoint', async (t) => { await t.throwsAsync( new FlattenedSign(t.context.payload) .setProtectedHeader({ alg: 'HS256' }) .setUnprotectedHeader({ alg: 'HS256' }) .sign(t.context.secret), { code: 'ERR_JWS_INVALID', message: 'JWS Protected and JWS Unprotected Header Parameter names must be disjoint', }, ) }) test('FlattenedSign.prototype.sign JOSE header have an alg', async (t) => { await t.throwsAsync( new FlattenedSign(t.context.payload) .setProtectedHeader({}) .setUnprotectedHeader({}) .sign(t.context.secret), { code: 'ERR_JWS_INVALID', message: 'JWS "alg" (Algorithm) Header Parameter missing or invalid', }, ) await t.notThrowsAsync( new FlattenedSign(t.context.payload) .setProtectedHeader({ alg: 'HS256' }) .setUnprotectedHeader({ foo: 'bar' }) .sign(t.context.secret), ) await t.notThrowsAsync( new FlattenedSign(t.context.payload) .setProtectedHeader({ alg: 'HS256' }) .sign(t.context.secret), ) await t.notThrowsAsync( new FlattenedSign(t.context.payload) .setProtectedHeader({ foo: 'bar' }) .setUnprotectedHeader({ alg: 'HS256' }) .sign(t.context.secret), ) await t.notThrowsAsync( new FlattenedSign(t.context.payload) .setUnprotectedHeader({ alg: 'HS256' }) .sign(t.context.secret), ) }) jose-4.11.4/test/jws/flattened.verify.test.mjs000066400000000000000000000100111437043056600212660ustar00rootroot00000000000000import test from 'ava' import * as crypto from 'crypto' import { root } from '../dist.mjs' const { FlattenedSign, flattenedVerify } = await import(root) test.before(async (t) => { const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) t.context.plaintext = encode('It’s a dangerous business, Frodo, going out your door.') t.context.secret = crypto.randomFillSync(new Uint8Array(32)) }) test('JWS format validation', async (t) => { const fullJws = await new FlattenedSign(t.context.plaintext) .setProtectedHeader({ bar: 'baz' }) .setUnprotectedHeader({ alg: 'HS256' }) .sign(t.context.secret) { await t.throwsAsync(flattenedVerify(null, t.context.secret), { message: 'Flattened JWS must be an object', code: 'ERR_JWS_INVALID', }) } { const jws = { ...fullJws } delete jws.protected delete jws.header await t.throwsAsync(flattenedVerify(jws, t.context.secret), { message: 'Flattened JWS must have either of the "protected" or "header" members', code: 'ERR_JWS_INVALID', }) } { await t.notThrowsAsync(async () => { await flattenedVerify( await new FlattenedSign(new Uint8Array()) .setProtectedHeader({ alg: 'HS256' }) .sign(t.context.secret), t.context.secret, ) }) } { const jws = { ...fullJws } delete jws.signature const assertion = { message: 'JWS Signature missing or incorrect type', code: 'ERR_JWS_INVALID', } await t.throwsAsync(flattenedVerify(jws, t.context.secret), assertion) jws.signature = null await t.throwsAsync(flattenedVerify(jws, t.context.secret), assertion) } { const jws = { ...fullJws } const assertion = { message: 'JWS Protected Header incorrect type', code: 'ERR_JWS_INVALID', } jws.protected = null await t.throwsAsync(flattenedVerify(jws, t.context.secret), assertion) } { const jws = { ...fullJws } const assertion = { message: 'JWS Unprotected Header incorrect type', code: 'ERR_JWS_INVALID', } jws.header = null await t.throwsAsync(flattenedVerify(jws, t.context.secret), assertion) } { const jws = { ...fullJws } const assertion = { message: 'JWS Protected Header is invalid', code: 'ERR_JWS_INVALID', } jws.protected = `1${jws.protected}` await t.throwsAsync(flattenedVerify(jws, t.context.secret), assertion) } { const jws = { ...fullJws } const assertion = { message: 'JWS Payload missing', code: 'ERR_JWS_INVALID', } delete jws.payload await t.throwsAsync(flattenedVerify(jws, t.context.secret), assertion) } { const jws = { ...fullJws } jws.header = { alg: 'HS256', bar: 'bar' } const assertion = { message: 'JWS Protected and JWS Unprotected Header Parameter names must be disjoint', code: 'ERR_JWS_INVALID', } await t.throwsAsync(flattenedVerify(jws, t.context.secret), assertion) } { const jws = { ...fullJws } delete jws.header const assertion = { message: 'JWS "alg" (Algorithm) Header Parameter missing or invalid', code: 'ERR_JWS_INVALID', } await t.throwsAsync(flattenedVerify(jws, t.context.secret), assertion) } { const jws = { ...fullJws } jws.payload = null const assertion = { message: 'JWS Payload must be a string', code: 'ERR_JWS_INVALID', } await t.throwsAsync(flattenedVerify(jws, t.context.secret), assertion) } { const jws = { ...fullJws } const assertion = { message: 'signature verification failed', code: 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED', } await t.throwsAsync(flattenedVerify(jws, crypto.randomFillSync(new Uint8Array(32))), assertion) } }) test('sign empty data', async (t) => { const jws = await new FlattenedSign(new Uint8Array(0)) .setProtectedHeader({ alg: 'HS256' }) .sign(new Uint8Array(32)) t.is(jws.payload, '') const { payload } = await flattenedVerify(jws, new Uint8Array(32)) t.is(payload.byteLength, 0) }) jose-4.11.4/test/jws/general.test.mjs000066400000000000000000000105711437043056600174450ustar00rootroot00000000000000import test from 'ava' import * as crypto from 'crypto' import { root } from '../dist.mjs' const { GeneralSign, generalVerify } = await import(root) test.before(async (t) => { const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) t.context.plaintext = encode('It’s a dangerous business, Frodo, going out your door.') t.context.secret = crypto.randomFillSync(new Uint8Array(48)) }) test('General JWS signing', async (t) => { const generalJws = await new GeneralSign(t.context.plaintext) .addSignature(t.context.secret) .setProtectedHeader({ bar: 'baz' }) .setUnprotectedHeader({ alg: 'HS256' }) .addSignature(t.context.secret) .setProtectedHeader({ bar: 'baz' }) .setUnprotectedHeader({ alg: 'HS384' }) .sign() t.is( generalJws.payload, 'SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IHlvdXIgZG9vci4', ) t.is(generalJws.signatures.length, 2) }) test('General JWS signing b64:false', async (t) => { const generalJws = await new GeneralSign(t.context.plaintext) .addSignature(t.context.secret) .setProtectedHeader({ bar: 'baz', b64: false, crit: ['b64'] }) .setUnprotectedHeader({ alg: 'HS256' }) .addSignature(t.context.secret) .setProtectedHeader({ bar: 'baz', b64: false, crit: ['b64'] }) .setUnprotectedHeader({ alg: 'HS384' }) .sign() t.is(generalJws.payload, '') t.is(generalJws.signatures.length, 2) }) test('General JWS signing validations', async (t) => { const sig = new GeneralSign(t.context.plaintext) t.throws( () => { sig .addSignature(t.context.secret) .setProtectedHeader({ bar: 'baz', crit: ['b64'], b64: false, alg: 'HS256' }) .setProtectedHeader({ bar: 'baz', crit: ['b64'], b64: false, alg: 'HS256' }) }, { instanceOf: TypeError, message: 'setProtectedHeader can only be called once' }, ) t.throws( () => { sig .addSignature(t.context.secret) .setProtectedHeader({ bar: 'baz', crit: ['b64'], b64: true, alg: 'HS384' }) .setUnprotectedHeader({ foo: 'bar' }) .setUnprotectedHeader({ foo: 'bar' }) }, { instanceOf: TypeError, message: 'setUnprotectedHeader can only be called once' }, ) await t.throwsAsync(sig.sign(), { message: 'inconsistent use of JWS Unencoded Payload Option (RFC7797)', code: 'ERR_JWS_INVALID', }) }) test('General JWS verify format validation', async (t) => { const sig = new GeneralSign(t.context.plaintext) sig .addSignature(t.context.secret) .setProtectedHeader({ bar: 'baz' }) .setUnprotectedHeader({ alg: 'HS256' }) const generalJws = await sig.sign() { await t.notThrowsAsync(async () => { await generalVerify( await new GeneralSign(new Uint8Array()) .addSignature(t.context.secret) .setProtectedHeader({ alg: 'HS256' }) .sign(), t.context.secret, ) }) } { await t.throwsAsync(generalVerify(null, t.context.secret), { message: 'General JWS must be an object', code: 'ERR_JWS_INVALID', }) } { await t.throwsAsync(generalVerify({ signatures: null }, t.context.secret), { message: 'JWS Signatures missing or incorrect type', code: 'ERR_JWS_INVALID', }) } { await t.throwsAsync(generalVerify({ signatures: [null] }, t.context.secret), { message: 'JWS Signatures missing or incorrect type', code: 'ERR_JWS_INVALID', }) } { const jws = { payload: generalJws.payload, signatures: [] } await t.throwsAsync(generalVerify(jws, t.context.secret), { message: 'signature verification failed', code: 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED', }) } { await t.notThrowsAsync(generalVerify(generalJws, t.context.secret)) } { const { payload, signatures } = generalJws const jws = { payload, signatures: [...signatures, {}] } await t.notThrowsAsync(generalVerify(jws, t.context.secret)) } { const { payload, signatures } = generalJws const jws = { payload, signatures: [{}, ...signatures] } await t.notThrowsAsync(generalVerify(jws, t.context.secret)) } }) test('sign empty data', async (t) => { const jws = await new GeneralSign(new Uint8Array(0)) .addSignature(new Uint8Array(32)) .setProtectedHeader({ alg: 'HS256' }) .sign() t.is(jws.payload, '') const { payload } = await generalVerify(jws, new Uint8Array(32)) t.is(payload.byteLength, 0) }) jose-4.11.4/test/jws/restrictions.test.mjs000066400000000000000000000147651437043056600205710ustar00rootroot00000000000000import test from 'ava' import * as crypto from 'crypto' import { conditional, root, keyRoot } from '../dist.mjs' const { FlattenedSign, flattenedVerify, FlattenedEncrypt, flattenedDecrypt, base64url } = await import(root) const { generateKeyPair, importJWK, exportPKCS8 } = await import(keyRoot) function pubjwk(jwk) { const { d, p, q, dp, dq, qi, ...publicJwk } = jwk return publicJwk } test.before((t) => { const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) t.context.payload = encode('It’s a dangerous business, Frodo, going out your door.') t.context.rsa2040 = { e: 'AQAB', n: '4waoB9XUAsGc-bhkfY-v3hKEqmLYF4nS-8nji5R5KoOOeWC2hCkvbMfd2IlKRdMU7EmGXNx2BD2FVIqN9mWyZKJlzR2125lgJ-VxCymGv1A9057LEAFIrXsCUqwjPO07hCzZNv8IAAQzq53pnlAgb3TbfrxW24tamhCtaKHb5upAwo4jhYnfzex2--vD7mPxMoTuikno-eD_hxYmA52Uh1gu3wEWy44KA6aFJBpP7m4G5StuHSCXxiOWDaqMeFsMX1jqrom7SwbGJ7j0sf3ZqWrZR4x1pB3wk5Sixi_lmDfOkXhiizYnvJJ5rzr_f0bVdXeAe2U8vpEJSQeA36T7', d: 'T7ZPm2it50XZ-yiOSDQCWSQBZt4L57_hz7ykY6b_IDlO9jlJ_H-FgllvAI-7_2ZNC2YJgmN6IKUFQpjfnas5hvIqcmnDJ9bjlz6NgZDUGipvevVfcUAyJ49wUlzUhpj5c8BXiGLliTPwfIqWs5qIuPm78_TnPnDgoAXJDVr_njr_C6CJFVfWni_6MTeT8iSApGrIJ-tovLlUWSQAyKfWT0QK8dclmREla6-B4YPFwMuBViiSI8dGFpw1O-sEn7D1aMWRepWKr-dgvukuksdL39LxBeGz-iHpI_DMdSB63t5kyjT7GPlbBkD__4ie_Vl4bG30dUZvH_Vt6nXxyXEh', p: 'D0TqaIEyAQHzW1SnC_b1AM9sehg6baMhw4mwSQHqVQreS6a2FKor2xVUdWzT3EurRJ-NThGyi81b30MsKjV_eZ1pIA2r5ulab5CgsV4pkk9LZPZYtz4Rylv9RY3ArtBxziF_BPhTbyy5LXUr5TZUpTQn-LGPOc2sjDaB80uD9XE', q: 'Dt5ET14bw-tNwsgBK-IuhuPzxeCYSi6AkiDqdJuykcN8z8Of-OyPbQSVgTNbvQSZ1anaV0-pvrkER5ilIjcaGtaBmQmCUZe0vKBynakRWXR16SE2mqJAjAmO6VD25cxdnNghdg8ue5XsdyjuQ0dnTXibsIcVyjfaIZgjbhi6mys', dp: 'BD0cWXBsAi2ZceQZD1A6CUSLl4U8Sw07JT4Gyu2WMI940EVyTGBFFmdgb8yLL59t5vnnzyFIkFisxVivXPRG8-rHsRc6fjqPWWMryLEcFzqd8mQUkqHPbH6G25UTRTQmM5PG4AlTmAwxR7Y8PkAL1WSaKAaafPBkkvPatUBkXHE', dq: 'Bv-nBfkVdr6PRu2gZ4i7P_GTMQTMirai_KYT1rnnb2emm6HI7oJj7PwoZ73GJA5DX2jphwnPrCApHI6ExLtNRW7NaD0qo7-WaufXq9EGgqYoTom8y0MuwPxK0hazcW4mborqDUmOJsxml5yjsvWscbIhDxI3No3d1sxneQ6Y4Cs', qi: 'AkpKJwYKvaB73G7IQK5yxXCOvypwSEUK1bOcbhOZSQPPNtKvov11dVsGs-pqHo0Su06IXQv0Ayyy3uxXvsY8CyZ3CbPWMXM06Z3Gr0kZWWfNu8NiFwXvkbe24P-KeXIQGFTfdqSMTfm2an1YNE9e9F36rZ0EkhdKzmwzudA7jtw', kty: 'RSA', } t.context.rsa2048 = { e: 'AQAB', n: '3egkthDOqRIif9azx83Q-HKcVNUeDALom8e5L1rjljB82EKYt5zgfKlgLW4NuJQgLDx5jA7Ez_nz-8lIcVTez-C75_M-Thv2wLhk4ZAYAZZPEmZr76zH8-lClnhxcqFnkOABqLmopr2gF1gBG_IkqEnH_h_yH486YkCd0G2ZNJAzjCOCQMR5pzBnIxC4YUAX7r_-9ilQ8Lv3MSJ0MLv6cujJTneyjWnoh_SfOXRsY6f3gkfR9APj9Q5A8PA8gvbYyN8EHr4OYb1KwNjs_0_X0Aq0e1NJx3H5eiZe6UaFleIbEVZYoNtlNJO3kmGESaxepkWTRAqBZVTfj4KnKX_9Ow', d: 'Q17sbl4x8ACyeq97i4jADf312oeNhMYJSupbHbZxbDKyZJHrfatiOFbP_VrxTX2jOurtWAlP1Xiki2fz13yV3PT095nQ67PvuVkCP70YnLq-rO5tjKmfVz0VW0ub3dqE7-YietBLFLxzc0Ljq1FbscAcuNmID-7TIetOPm5X2i3wxOuiEV2xz1nHVuys3yoO3z4rAitGFl943k71P4FKxK9mp9oTQTnDfKauP0eSOD10L2NiYLkUTg9YC8A0EQopdZatDVAz3hWitNpJg28fWe7rp7yR2YBb4nFcNuygZmzEzp7x0r87NnTt9t4Hjd1rNFbd3hdT6Dy9_pejkmdU2Q', p: '8_HZDF8wp0ujYxiyvAXOL6Xsnv08bQ80uzDOGCnHWWKeFn8n43gc49AdBiJ2ljmfQxExiK0wmetR76zdxTJBIWQdGI2ZJkb6lAIOEBhrXzrWXUSMPgc3qYbQRkmexrAAdwG1nWUymMDd36K5d_YEmL172a-gyEAXMGGW81AaeVU', q: '6N9-STJXjcrwedkJpmmjKLBpU_Nw0UfpKAkh3Xf6jpaF-A2Cvr07JqDVzExMfpYDCcki7IW8SLK5wXVfWCZqXXl4bsb5LAJLnRIglgnDxItlmRf5CWHw7lmBD6BguEIhXU3xPiNrK3XiBVS4k2yDaYHHoAPYXDfTCGpbts7SXE8', dp: 'k_OmtH43P__8BGpCXQ8YUoXL0VG9iFekn7OmC7mrEmdhgjt0sd1ziCf8sm_MhKhGE6Ml68M-qtuyQi8SAjvMjLfvfajDrhd2erYUWWa2GHfS85ZTiHtQIx2EzFxyVAcDASqkP-XUnhi7eJt06XDosMqbhxeh6FIWvl0x9DgtFlE', dq: 'UqK8VY0ftJlHLHXwDrV9yHqRZdEFP76c5jAXbFee-epAL_3bX4QW8WYxeAW7P1BMU7SkR_pNDh8d-6CC7Oz04aaxLd49nXhTDLHaDmP4rE4rB2CSZtnyfSIVwk3PBJOy80EtUjePWCTEx8-AkA_5sf7zr7ytkkvc_yd-1CggTdE', qi: 'd72eV7EbpvaSA3ZiQdGXpMMr41o0ih1WnV80Bxraugj1vMqxLlhVdDhDCVoF3LEoXVz8n2NEl1F6k2o3Gt9C5pXUDJwRGS41FwYVp8RN-aWviJM43mM0oQndJomZyDzjOKzpTzlNlAkFQQbfoagc4sbg-0JxK9rWdnMDW5AR1BU', kty: 'RSA', } }) async function testRSAsig(t, alg) { const message = `${alg} requires key modulusLength to be 2048 bits or larger` const keyBad = t.context.rsa2040 const keyOk = t.context.rsa2048 await t.throwsAsync( new FlattenedSign(t.context.payload) .setProtectedHeader({ alg }) .sign(await importJWK(keyBad, alg)), { instanceOf: TypeError, message }, ) const jws = await new FlattenedSign(t.context.payload) .setProtectedHeader({ alg }) .sign(await importJWK(keyOk, alg)) await t.throwsAsync(flattenedVerify(jws, await importJWK(pubjwk(keyBad), alg)), { instanceOf: TypeError, message, }) } testRSAsig.title = (title, alg) => `${alg} requires key modulusLength to be 2048 bits or larger` async function testRSAenc(t, alg) { const message = `${alg} requires key modulusLength to be 2048 bits or larger` const keyBad = t.context.rsa2040 const keyOk = t.context.rsa2048 await t.throwsAsync( new FlattenedEncrypt(t.context.payload) .setProtectedHeader({ alg, enc: 'A256GCM' }) .encrypt(await importJWK(pubjwk(keyBad), alg)), { instanceOf: TypeError, message }, ) const jwe = await new FlattenedEncrypt(t.context.payload) .setProtectedHeader({ alg, enc: 'A256GCM' }) .encrypt(await importJWK(pubjwk(keyOk), alg)) await t.throwsAsync(flattenedDecrypt(jwe, await importJWK(keyBad, alg)), { instanceOf: TypeError, message, }) } testRSAenc.title = (title, alg) => `${alg} requires key modulusLength to be 2048 bits or larger` async function testECDSASigEncoding(t, alg) { let { privateKey, publicKey } = await generateKeyPair(alg, { extractable: true }) const jws = await new FlattenedSign(t.context.payload) .setProtectedHeader({ alg }) .sign(privateKey) const derEncodedSignature = base64url.encode( crypto.sign(`sha${alg.slice(2, 5)}`, Buffer.from('foo'), await exportPKCS8(privateKey)), ) await t.throwsAsync(flattenedVerify({ ...jws, signature: derEncodedSignature }, publicKey), { message: 'signature verification failed', code: 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED', }) } testECDSASigEncoding.title = (title, alg) => `${alg} swallows invalid signature encoding errors` test(testRSAsig, 'RS256') test(testRSAsig, 'PS256') test(testRSAsig, 'RS384') test(testRSAsig, 'PS384') test(testRSAsig, 'RS512') test(testRSAsig, 'PS512') test(testRSAenc, 'RSA-OAEP') test(testRSAenc, 'RSA-OAEP-256') test(testRSAenc, 'RSA-OAEP-384') test(testRSAenc, 'RSA-OAEP-512') test(testECDSASigEncoding, 'ES256') test(testECDSASigEncoding, 'ES384') test(testECDSASigEncoding, 'ES512') conditional({ webcrypto: 0 })(testRSAenc, 'RSA1_5') conditional({ webcrypto: 0 })(testECDSASigEncoding, 'ES256K') jose-4.11.4/test/jws/rsa-pss.test.mjs000066400000000000000000000117611437043056600174220ustar00rootroot00000000000000import test from 'ava' import * as crypto from 'crypto' import { promisify } from 'util' const generateKeyPair = promisify(crypto.generateKeyPair) const [major, minor] = process.versions.node.split('.').map((str) => parseInt(str, 10)) const rsaPssParams = major >= 17 || (major === 16 && minor >= 9) const { FlattenedSign, flattenedVerify } = await import('#dist') if (rsaPssParams) { for (const length of [256, 384, 512]) { test(`valid RSASSA-PSS-Params PS${length}`, async (t) => { for (const options of [ { modulusLength: 2048 }, { modulusLength: 2048, hashAlgorithm: `sha${length}`, hash: `sha${length}`, mgf1HashAlgorithm: `sha${length}`, mgf1Hash: `sha${length}`, saltLength: 0, }, { modulusLength: 2048, hashAlgorithm: `sha${length}`, hash: `sha${length}`, mgf1HashAlgorithm: `sha${length}`, mgf1Hash: `sha${length}`, saltLength: length >> 3, }, ]) { const { privateKey, publicKey } = await generateKeyPair('rsa-pss', options) const jws = await new FlattenedSign(new Uint8Array(0)) .setProtectedHeader({ alg: `PS${length}` }) .sign(privateKey) await flattenedVerify(jws, publicKey) } t.pass() }) test(`invalid saltLength for PS${length}`, async (t) => { const { privateKey, publicKey } = await generateKeyPair('rsa-pss', { modulusLength: 2048, hashAlgorithm: `sha${length}`, hash: `sha${length}`, mgf1HashAlgorithm: `sha${length}`, mgf1Hash: `sha${length}`, saltLength: (length >> 3) + 1, }) await t.throwsAsync( new FlattenedSign(new Uint8Array(0)) .setProtectedHeader({ alg: `PS${length}` }) .sign(privateKey), { message: `Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" PS${length}`, instanceOf: TypeError, }, ) await t.throwsAsync( flattenedVerify({ header: { alg: `PS${length}` }, payload: '', signature: '' }, publicKey), { message: `Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" PS${length}`, instanceOf: TypeError, }, ) }) test(`invalid hashAlgorithm for PS${length}`, async (t) => { const { privateKey, publicKey } = await generateKeyPair('rsa-pss', { modulusLength: 2048, hashAlgorithm: 'sha1', hash: 'sha1', mgf1HashAlgorithm: `sha${length}`, mgf1Hash: `sha${length}`, saltLength: length >> 3, }) await t.throwsAsync( new FlattenedSign(new Uint8Array(0)) .setProtectedHeader({ alg: `PS${length}` }) .sign(privateKey), { message: `Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" PS${length}`, instanceOf: TypeError, }, ) await t.throwsAsync( flattenedVerify({ header: { alg: `PS${length}` }, payload: '', signature: '' }, publicKey), { message: `Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" PS${length}`, instanceOf: TypeError, }, ) }) test(`invalid mgf1HashAlgorithm for PS${length}`, async (t) => { const { privateKey, publicKey } = await generateKeyPair('rsa-pss', { modulusLength: 2048, hashAlgorithm: `sha${length}`, hash: `sha${length}`, mgf1HashAlgorithm: 'sha1', mgf1Hash: 'sha1', saltLength: length >> 3, }) await t.throwsAsync( new FlattenedSign(new Uint8Array(0)) .setProtectedHeader({ alg: `PS${length}` }) .sign(privateKey), { message: `Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" PS${length}`, instanceOf: TypeError, }, ) await t.throwsAsync( flattenedVerify({ header: { alg: `PS${length}` }, payload: '', signature: '' }, publicKey), { message: `Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" PS${length}`, instanceOf: TypeError, }, ) }) } } else { test('does not support rsa-pss', async (t) => { const { privateKey, publicKey } = await generateKeyPair('rsa-pss', { modulusLength: 2048 }) await t.throwsAsync( new FlattenedSign(new Uint8Array(0)).setProtectedHeader({ alg: 'PS256' }).sign(privateKey), { message: 'Invalid key for this operation, its asymmetricKeyType must be rsa', instanceOf: TypeError, }, ) await t.throwsAsync( flattenedVerify({ header: { alg: 'PS256' }, payload: '', signature: '' }, publicKey), { message: 'Invalid key for this operation, its asymmetricKeyType must be rsa', instanceOf: TypeError, }, ) }) } jose-4.11.4/test/jws/unencoded.test.mjs000066400000000000000000000032361437043056600177740ustar00rootroot00000000000000import test from 'ava' import { root } from '../dist.mjs' const { FlattenedSign, flattenedVerify } = await import(root) const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) test('JSON Web Signature (JWS) Unencoded Payload Option', async (t) => { const jws = await new FlattenedSign(encode('foo')) .setProtectedHeader({ alg: 'HS256', b64: false, crit: ['b64'] }) .sign(new Uint8Array(32)) t.deepEqual(jws, { payload: '', protected: 'eyJhbGciOiJIUzI1NiIsImI2NCI6ZmFsc2UsImNyaXQiOlsiYjY0Il19', signature: 'VklKdp4tVYD61VNPDBTqxqdEQcUL3JK-D4dGXu9NvWs', }) await t.notThrowsAsync(flattenedVerify({ ...jws, payload: 'foo' }, new Uint8Array(32))) await t.notThrowsAsync(flattenedVerify({ ...jws, payload: encode('foo') }, new Uint8Array(32))) }) test('b64 check', async (t) => { await t.throwsAsync( new FlattenedSign(encode('foo')) .setProtectedHeader({ alg: 'HS256', b64: null, crit: ['b64'] }) .sign(new Uint8Array(32)), { code: 'ERR_JWS_INVALID', message: 'The "b64" (base64url-encode payload) Header Parameter must be a boolean', }, ) await t.throwsAsync( new FlattenedSign(encode('foo')) .setProtectedHeader({ alg: 'HS256', crit: ['b64'] }) .sign(new Uint8Array(32)), { code: 'ERR_JWS_INVALID', message: 'Extension Header Parameter "b64" is missing' }, ) await t.throwsAsync( new FlattenedSign(encode('foo')) .setProtectedHeader({ alg: 'HS256', crit: ['b64'] }) .setUnprotectedHeader({ b64: false }) .sign(new Uint8Array(32)), { code: 'ERR_JWS_INVALID', message: 'Extension Header Parameter "b64" MUST be integrity protected', }, ) }) jose-4.11.4/test/jwt/000077500000000000000000000000001437043056600143345ustar00rootroot00000000000000jose-4.11.4/test/jwt/decrypt.test.mjs000066400000000000000000000273211437043056600175040ustar00rootroot00000000000000import test from 'ava' import timekeeper from 'timekeeper' import { root } from '../dist.mjs' const { EncryptJWT, jwtDecrypt, CompactEncrypt } = await import(root) const now = 1604416038 test.before(async (t) => { t.context.secret = new Uint8Array(32) t.context.payload = { 'urn:example:claim': true } timekeeper.freeze(now * 1000) }) test.after(timekeeper.reset) test('Basic JWT Claims Set verification', async (t) => { const issuer = 'urn:example:issuer' const subject = 'urn:example:subject' const audience = 'urn:example:audience' const jti = 'urn:example:jti' const nbf = now - 10 const iat = now - 20 const exp = now + 10 const typ = 'urn:example:typ' const jwt = await new EncryptJWT(t.context.payload) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM', typ }) .setIssuer(issuer) .setSubject(subject) .setAudience(audience) .setJti(jti) .setNotBefore(nbf) .setExpirationTime(exp) .setIssuedAt(iat) .encrypt(t.context.secret) t.deepEqual( await jwtDecrypt(jwt, t.context.secret, { issuer, subject, audience, jti, typ, maxTokenAge: '30s', }), { payload: { aud: 'urn:example:audience', exp: 1604416048, iat: 1604416018, iss: 'urn:example:issuer', jti: 'urn:example:jti', nbf: 1604416028, sub: 'urn:example:subject', 'urn:example:claim': true, }, protectedHeader: { alg: 'dir', enc: 'A256GCM', typ: 'urn:example:typ', }, }, ) await t.notThrowsAsync(jwtDecrypt(new TextEncoder().encode(jwt), t.context.secret)) }) test('Payload must be an object', async (t) => { const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) for (const value of [0, 1, -1, true, false, null, [], '']) { const token = await new CompactEncrypt(encode(JSON.stringify(value))) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' }) .encrypt(t.context.secret) await t.throwsAsync(jwtDecrypt(token, t.context.secret), { code: 'ERR_JWT_INVALID', message: 'JWT Claims Set must be a top-level JSON object', }) } }) test('Payload must JSON parseable', async (t) => { const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) const token = await new CompactEncrypt(encode('{')) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' }) .encrypt(t.context.secret) await t.throwsAsync(jwtDecrypt(token, t.context.secret), { code: 'ERR_JWT_INVALID', message: 'JWT Claims Set must be a top-level JSON object', }) }) test('contentEncryptionAlgorithms and keyManagementAlgorithms options', async (t) => { const jwt = await new EncryptJWT(t.context.payload) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' }) .encrypt(t.context.secret) await t.throwsAsync( jwtDecrypt(jwt, t.context.secret, { keyManagementAlgorithms: ['RSA-OAEP'], }), { code: 'ERR_JOSE_ALG_NOT_ALLOWED', message: '"alg" (Algorithm) Header Parameter not allowed', }, ) await t.throwsAsync( jwtDecrypt(jwt, t.context.secret, { keyManagementAlgorithms: [null], }), { instanceOf: TypeError, message: '"keyManagementAlgorithms" option must be an array of strings', }, ) await t.throwsAsync( jwtDecrypt(jwt, t.context.secret, { contentEncryptionAlgorithms: ['A128GCM'], }), { code: 'ERR_JOSE_ALG_NOT_ALLOWED', message: '"enc" (Encryption Algorithm) Header Parameter not allowed', }, ) await t.throwsAsync( jwtDecrypt(jwt, t.context.secret, { contentEncryptionAlgorithms: [null], }), { instanceOf: TypeError, message: '"contentEncryptionAlgorithms" option must be an array of strings', }, ) }) test('typ verification', async (t) => { { const typ = 'urn:example:typ' const jwt = await new EncryptJWT(t.context.payload) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM', typ }) .encrypt(t.context.secret) await t.notThrowsAsync( jwtDecrypt(jwt, t.context.secret, { typ: 'application/urn:example:typ', }), ) await t.throwsAsync( jwtDecrypt(jwt, t.context.secret, { typ: 'urn:example:typ:2', }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "typ" JWT header value' }, ) await t.throwsAsync( jwtDecrypt(jwt, t.context.secret, { typ: 'application/urn:example:typ:2', }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "typ" JWT header value' }, ) } { const typ = 'application/urn:example:typ' const jwt = await new EncryptJWT(t.context.payload) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM', typ }) .encrypt(t.context.secret) await t.notThrowsAsync( jwtDecrypt(jwt, t.context.secret, { typ: 'urn:example:typ', }), ) await t.throwsAsync( jwtDecrypt(jwt, t.context.secret, { typ: 'application/urn:example:typ:2', }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "typ" JWT header value' }, ) await t.throwsAsync( jwtDecrypt(jwt, t.context.secret, { typ: 'urn:example:typ:2', }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "typ" JWT header value' }, ) } }) test('Issuer[] verification', async (t) => { const issuer = 'urn:example:issuer' const jwt = await new EncryptJWT(t.context.payload) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' }) .setIssuer(issuer) .encrypt(t.context.secret) await t.notThrowsAsync( jwtDecrypt(jwt, t.context.secret, { issuer: [issuer], }), ) }) test('Issuer[] verification failed', async (t) => { const issuer = 'urn:example:issuer' const jwt = await new EncryptJWT(t.context.payload) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' }) .setIssuer(issuer) .encrypt(t.context.secret) await t.throwsAsync( jwtDecrypt(jwt, t.context.secret, { issuer: [], }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "iss" claim value' }, ) }) test('Issuer[] verification failed []', async (t) => { const issuer = 'urn:example:issuer' const jwt = await new EncryptJWT(t.context.payload) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' }) .setIssuer([issuer]) .encrypt(t.context.secret) await t.throwsAsync( jwtDecrypt(jwt, t.context.secret, { issuer: [], }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "iss" claim value' }, ) }) test('Audience[] verification', async (t) => { const audience = 'urn:example:audience' const jwt = await new EncryptJWT(t.context.payload) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' }) .setAudience(audience) .encrypt(t.context.secret) await t.notThrowsAsync( jwtDecrypt(jwt, t.context.secret, { audience: [audience], }), ) }) test('Audience[] verification failed', async (t) => { const audience = 'urn:example:audience' const jwt = await new EncryptJWT(t.context.payload) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' }) .setAudience(audience) .encrypt(t.context.secret) await t.throwsAsync( jwtDecrypt(jwt, t.context.secret, { audience: [], }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "aud" claim value' }, ) }) test('Audience[] verification failed []', async (t) => { const audience = 'urn:example:audience' const jwt = await new EncryptJWT(t.context.payload) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' }) .setAudience([audience]) .encrypt(t.context.secret) await t.throwsAsync( jwtDecrypt(jwt, t.context.secret, { audience: [], }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "aud" claim value' }, ) }) test('Subject verification failed', async (t) => { const subject = 'urn:example:subject' const jwt = await new EncryptJWT(t.context.payload) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' }) .setSubject(subject) .encrypt(t.context.secret) await t.throwsAsync( jwtDecrypt(jwt, t.context.secret, { subject: 'urn:example:subject:2', }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "sub" claim value' }, ) }) async function numericDateNumber(t, claim) { const jwt = await new EncryptJWT({ [claim]: null }) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' }) .encrypt(t.context.secret) await t.throwsAsync(jwtDecrypt(jwt, t.context.secret), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: `"${claim}" claim must be a number`, }) } numericDateNumber.title = (t, claim) => `${claim} must be a number` test('clockTolerance num', async (t) => { const jwt = await new EncryptJWT({ exp: now }) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' }) .encrypt(t.context.secret) await t.notThrowsAsync(jwtDecrypt(jwt, t.context.secret, { clockTolerance: 1 })) await t.notThrowsAsync(jwtDecrypt(jwt, t.context.secret, { clockTolerance: '1s' })) await t.throwsAsync(jwtDecrypt(jwt, t.context.secret, { clockTolerance: null }), { instanceOf: TypeError, message: 'Invalid clockTolerance option type', }) }) async function failingNumericDate(t, claims, assertion, decryptOptions) { const jwt = await new EncryptJWT({ ...claims }) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' }) .encrypt(t.context.secret) await t.throwsAsync(jwtDecrypt(jwt, t.context.secret, { ...decryptOptions }), assertion) } test( 'exp must be in the future', failingNumericDate, { exp: now }, { code: 'ERR_JWT_EXPIRED', message: '"exp" claim timestamp check failed', }, ) test( 'nbf must be at least now', failingNumericDate, { nbf: now + 1 }, { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: '"nbf" claim timestamp check failed', }, ) test( 'iat must be in the past (maxTokenAge, no exp)', failingNumericDate, { iat: now + 1 }, { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: '"iat" claim timestamp check failed (it should be in the past)', }, { maxTokenAge: 5, }, ) test( 'iat must be in the past (maxTokenAge, with exp)', failingNumericDate, { iat: now + 1, exp: now + 10 }, { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: '"iat" claim timestamp check failed (it should be in the past)', }, { maxTokenAge: 5, }, ) test( 'iat must be in the past (maxTokenAge, with exp, as a string)', failingNumericDate, { iat: now + 1, exp: now + 10 }, { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: '"iat" claim timestamp check failed (it should be in the past)', }, { maxTokenAge: '5s', }, ) test( 'maxTokenAge option', failingNumericDate, { iat: now - 31 }, { code: 'ERR_JWT_EXPIRED', message: '"iat" claim timestamp check failed (too far in the past)', }, { maxTokenAge: '30s', }, ) for (const claim of ['iat', 'nbf', 'exp']) { test(numericDateNumber, claim) } async function replicatedClaimCheck(t, claim) { { const jwt = await new EncryptJWT({ [claim]: 'urn:example' }) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM', [claim]: 'urn:example' }) .encrypt(t.context.secret) await t.notThrowsAsync(jwtDecrypt(jwt, t.context.secret)) } { const jwt = await new EncryptJWT({ [claim]: 'urn:example:mismatched' }) .setProtectedHeader({ alg: 'dir', enc: 'A256GCM', [claim]: 'urn:example' }) .encrypt(t.context.secret) await t.throwsAsync( jwtDecrypt(jwt, t.context.secret, { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: `replicated "${claim}" claim header parameter mismatch`, }), ) } } replicatedClaimCheck.title = (t, claim) => `${claim} header claim must match the payload` for (const claim of ['iss', 'sub', 'aud']) { test(replicatedClaimCheck, claim) } jose-4.11.4/test/jwt/encrypt.test.mjs000066400000000000000000000127021437043056600175130ustar00rootroot00000000000000import test from 'ava' import timekeeper from 'timekeeper' import { root } from '../dist.mjs' const { EncryptJWT, compactDecrypt, jwtDecrypt } = await import(root) const now = 1604416038 test.before(async (t) => { t.context.secret = new Uint8Array(16) t.context.initializationVector = new Uint8Array(12) t.context.payload = { 'urn:example:claim': true } timekeeper.freeze(new Date(now * 1000)) }) test.after(timekeeper.reset) test('EncryptJWT', async (t) => { const jwt = await new EncryptJWT(t.context.payload) .setInitializationVector(t.context.initializationVector) .setProtectedHeader({ alg: 'dir', enc: 'A128GCM' }) .encrypt(t.context.secret) t.is( jwt, 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..AAAAAAAAAAAAAAAA.eKqvvA6MxuqSRbLVFIidFJb8x4lzPytWkoA.aglYAurAaFCoM8sCqaXSyw', ) }) test('EncryptJWT w/crit', async (t) => { const expected = 'eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIiwiY3JpdCI6WyJodHRwOi8vb3BlbmJhbmtpbmcub3JnLnVrL2lhdCJdLCJodHRwOi8vb3BlbmJhbmtpbmcub3JnLnVrL2lhdCI6MH0..AAAAAAAAAAAAAAAA.eKqvvA6MxuqSRbLVFIidFJb8x4lzPytWkoA.Kl-auiUImwUWk4X0xpxa8A' await t.throwsAsync( new EncryptJWT(t.context.payload) .setInitializationVector(t.context.initializationVector) .setProtectedHeader({ alg: 'dir', enc: 'A128GCM', crit: ['http://openbanking.org.uk/iat'], 'http://openbanking.org.uk/iat': 0, }) .encrypt(t.context.secret), { code: 'ERR_JOSE_NOT_SUPPORTED', message: 'Extension Header Parameter "http://openbanking.org.uk/iat" is not recognized', }, ) await t.notThrowsAsync(async () => { const jwt = await new EncryptJWT(t.context.payload) .setInitializationVector(t.context.initializationVector) .setProtectedHeader({ alg: 'dir', enc: 'A128GCM', crit: ['http://openbanking.org.uk/iat'], 'http://openbanking.org.uk/iat': 0, }) .encrypt(t.context.secret, { crit: { 'http://openbanking.org.uk/iat': true } }) t.is(jwt, expected) }) await t.throwsAsync(jwtDecrypt(expected, t.context.secret), { code: 'ERR_JOSE_NOT_SUPPORTED', message: 'Extension Header Parameter "http://openbanking.org.uk/iat" is not recognized', }) await t.notThrowsAsync( jwtDecrypt(expected, t.context.secret, { crit: { 'http://openbanking.org.uk/iat': true } }), ) }) test('new EncryptJWT', (t) => { t.throws(() => new EncryptJWT(), { instanceOf: TypeError, message: 'JWT Claims Set MUST be an object', }) }) async function testJWTsetFunction(t, method, claim, value, duplicate = false, expected = value) { let enc = new EncryptJWT({}).setProtectedHeader({ alg: 'dir', enc: 'A128GCM' })[method](value) if (duplicate) { enc = enc[`replicate${method.slice(3)}AsHeader`]() } const jwt = await enc.encrypt(t.context.secret) const { plaintext, protectedHeader, key: resolvedKey, } = await compactDecrypt(jwt, async (header, token) => { t.true('alg' in header) t.true('enc' in header) t.is(header.alg, 'dir') t.is(header.enc, 'A128GCM') t.true('ciphertext' in token) t.true('iv' in token) t.true('protected' in token) t.true('tag' in token) return t.context.secret }) t.is(resolvedKey, t.context.secret) const payload = JSON.parse(new TextDecoder().decode(plaintext)) t.is(payload[claim], expected) if (duplicate) { t.true(claim in protectedHeader) t.is(protectedHeader[claim], expected) } else { t.false(claim in protectedHeader) } } testJWTsetFunction.title = (title, method, claim, value) => `EncryptJWT.prototype.${method} called with ${value}${title ? ` (${title})` : ''}` test(testJWTsetFunction, 'setIssuer', 'iss', 'urn:example:issuer') test('duplicated', testJWTsetFunction, 'setIssuer', 'iss', 'urn:example:issuer', true) test(testJWTsetFunction, 'setSubject', 'sub', 'urn:example:subject') test('duplicated', testJWTsetFunction, 'setSubject', 'sub', 'urn:example:subject', true) test(testJWTsetFunction, 'setAudience', 'aud', 'urn:example:audience') test('duplicated', testJWTsetFunction, 'setAudience', 'aud', 'urn:example:audience', true) test(testJWTsetFunction, 'setJti', 'jti', 'urn:example:jti') test(testJWTsetFunction, 'setIssuedAt', 'iat', 0) test(testJWTsetFunction, 'setIssuedAt', 'iat', undefined, undefined, now) test(testJWTsetFunction, 'setExpirationTime', 'exp', 0) test(testJWTsetFunction, 'setExpirationTime', 'exp', '10s', undefined, now + 10) test(testJWTsetFunction, 'setNotBefore', 'nbf', 0) test(testJWTsetFunction, 'setNotBefore', 'nbf', '10s', undefined, now + 10) test('EncryptJWT.prototype.setProtectedHeader', (t) => { t.throws(() => new EncryptJWT(t.context.payload).setProtectedHeader({}).setProtectedHeader({}), { instanceOf: TypeError, message: 'setProtectedHeader can only be called once', }) }) test('EncryptJWT.prototype.setContentEncryptionKey', (t) => { t.throws( () => new EncryptJWT(t.context.payload) .setContentEncryptionKey(t.context.secret) .setContentEncryptionKey(t.context.secret), { instanceOf: TypeError, message: 'setContentEncryptionKey can only be called once', }, ) }) test('EncryptJWT.prototype.setInitializationVector', (t) => { t.throws( () => new EncryptJWT(t.context.payload) .setInitializationVector(t.context.initializationVector) .setInitializationVector(t.context.initializationVector), { instanceOf: TypeError, message: 'setInitializationVector can only be called once', }, ) }) jose-4.11.4/test/jwt/sign.test.mjs000066400000000000000000000077111437043056600167730ustar00rootroot00000000000000import test from 'ava' import timekeeper from 'timekeeper' import { root } from '../dist.mjs' const { SignJWT, compactVerify, jwtVerify } = await import(root) const now = 1604416038 test.before(async (t) => { t.context.secret = new Uint8Array(32) t.context.payload = { 'urn:example:claim': true } timekeeper.freeze(now * 1000) }) test.after(timekeeper.reset) test('SignJWT', async (t) => { const jwt = await new SignJWT(t.context.payload) .setProtectedHeader({ alg: 'HS256' }) .sign(t.context.secret) t.is( jwt, 'eyJhbGciOiJIUzI1NiJ9.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6dHJ1ZX0.yPnOE--rxp3rJaYy0iZaW2Vswvus05G6_ZBdXqIdjGo', ) }) test('SignJWT w/crit', async (t) => { const expected = 'eyJhbGciOiJIUzI1NiIsImNyaXQiOlsiaHR0cDovL29wZW5iYW5raW5nLm9yZy51ay9pYXQiXSwiaHR0cDovL29wZW5iYW5raW5nLm9yZy51ay9pYXQiOjB9.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6dHJ1ZX0.YzOrPZaNql7PpCo43HAJdj-LASP8lOmtb-Bzj9OrNAk' await t.throwsAsync( new SignJWT(t.context.payload) .setProtectedHeader({ alg: 'HS256', crit: ['http://openbanking.org.uk/iat'], 'http://openbanking.org.uk/iat': 0, }) .sign(t.context.secret), { code: 'ERR_JOSE_NOT_SUPPORTED', message: 'Extension Header Parameter "http://openbanking.org.uk/iat" is not recognized', }, ) await t.notThrowsAsync(async () => { const jwt = await new SignJWT(t.context.payload) .setProtectedHeader({ alg: 'HS256', crit: ['http://openbanking.org.uk/iat'], 'http://openbanking.org.uk/iat': 0, }) .sign(t.context.secret, { crit: { 'http://openbanking.org.uk/iat': true } }) t.is(jwt, expected) }) await t.throwsAsync(jwtVerify(expected, t.context.secret), { code: 'ERR_JOSE_NOT_SUPPORTED', message: 'Extension Header Parameter "http://openbanking.org.uk/iat" is not recognized', }) await t.notThrowsAsync( jwtVerify(expected, t.context.secret, { crit: { 'http://openbanking.org.uk/iat': true } }), ) }) test('new SignJWT', (t) => { t.throws(() => new SignJWT(), { instanceOf: TypeError, message: 'JWT Claims Set MUST be an object', }) }) test('Signed JWTs cannot use unencoded payload', async (t) => { await t.throwsAsync( () => new SignJWT({}) .setProtectedHeader({ alg: 'HS256', crit: ['b64'], b64: false }) .sign(t.context.secret), { code: 'ERR_JWT_INVALID', message: 'JWTs MUST NOT use unencoded payload' }, ) await t.throwsAsync(() => new SignJWT({}).sign(t.context.secret), { code: 'ERR_JWS_INVALID', message: 'either setProtectedHeader or setUnprotectedHeader must be called before #sign()', }) }) async function testJWTsetFunction(t, method, claim, value, expected = value) { const jwt = await new SignJWT({}) .setProtectedHeader({ alg: 'HS256' }) [method](value) .sign(t.context.secret) const { payload, key: resolvedKey } = await compactVerify(jwt, async (header, token) => { t.true('alg' in header) t.is(header.alg, 'HS256') t.true('payload' in token) t.true('protected' in token) t.true('signature' in token) return t.context.secret }) t.is(resolvedKey, t.context.secret) const claims = JSON.parse(new TextDecoder().decode(payload)) t.true(claim in claims) t.is(claims[claim], expected) } testJWTsetFunction.title = (title, method, claim, value) => `SignJWT.prototype.${method} called with ${value}` test(testJWTsetFunction, 'setIssuer', 'iss', 'urn:example:issuer') test(testJWTsetFunction, 'setSubject', 'sub', 'urn:example:subject') test(testJWTsetFunction, 'setAudience', 'aud', 'urn:example:audience') test(testJWTsetFunction, 'setJti', 'jti', 'urn:example:jti') test(testJWTsetFunction, 'setIssuedAt', 'iat', 0) test(testJWTsetFunction, 'setIssuedAt', 'iat', undefined, now) test(testJWTsetFunction, 'setExpirationTime', 'exp', 0) test(testJWTsetFunction, 'setExpirationTime', 'exp', '10s', now + 10) test(testJWTsetFunction, 'setNotBefore', 'nbf', 0) test(testJWTsetFunction, 'setNotBefore', 'nbf', '10s', now + 10) jose-4.11.4/test/jwt/unsecured.test.mjs000066400000000000000000000042521437043056600200250ustar00rootroot00000000000000import test from 'ava' import timekeeper from 'timekeeper' import { root } from '../dist.mjs' const { UnsecuredJWT } = await import(root) const now = 1604416038 test.before(async (t) => { t.context.payload = { 'urn:example:claim': true } timekeeper.freeze(now * 1000) }) test.after(timekeeper.reset) test('UnsecuredJWT', async (t) => { const jwt = new UnsecuredJWT(t.context.payload).encode() t.is(jwt, 'eyJhbGciOiJub25lIn0.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6dHJ1ZX0.') }) test('UnsecuredJWT validations', (t) => { t.throws(() => UnsecuredJWT.decode(null), { code: 'ERR_JWT_INVALID', message: 'Unsecured JWT must be a string', }) t.throws(() => UnsecuredJWT.decode('....'), { code: 'ERR_JWT_INVALID', message: 'Invalid Unsecured JWT', }) t.throws(() => UnsecuredJWT.decode('..'), { code: 'ERR_JWT_INVALID', message: 'Invalid Unsecured JWT', }) t.throws(() => UnsecuredJWT.decode('..foo'), { code: 'ERR_JWT_INVALID', message: 'Invalid Unsecured JWT', }) t.throws(() => UnsecuredJWT.decode('eyJhbGciOiJIUzI1NiJ9.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6dHJ1ZX0.'), { code: 'ERR_JWT_INVALID', message: 'Invalid Unsecured JWT', }) }) test('new UnsecuredJWT', (t) => { t.throws(() => new UnsecuredJWT(), { instanceOf: TypeError, message: 'JWT Claims Set MUST be an object', }) }) async function testJWTsetFunction(t, method, claim, value, expected = value) { const jwt = new UnsecuredJWT({})[method](value).encode() const { payload: claims } = UnsecuredJWT.decode(jwt) t.true(claim in claims) t.is(claims[claim], expected) } testJWTsetFunction.title = (title, method, claim, value) => `UnsecuredJWT.prototype.${method} called with ${value}` test(testJWTsetFunction, 'setIssuer', 'iss', 'urn:example:issuer') test(testJWTsetFunction, 'setSubject', 'sub', 'urn:example:subject') test(testJWTsetFunction, 'setAudience', 'aud', 'urn:example:audience') test(testJWTsetFunction, 'setJti', 'jti', 'urn:example:jti') test(testJWTsetFunction, 'setIssuedAt', 'iat', 0) test(testJWTsetFunction, 'setIssuedAt', 'iat', undefined, now) test(testJWTsetFunction, 'setExpirationTime', 'exp', '10s', now + 10) test(testJWTsetFunction, 'setNotBefore', 'nbf', 0) jose-4.11.4/test/jwt/verify.test.mjs000066400000000000000000000257501437043056600173420ustar00rootroot00000000000000import test from 'ava' import timekeeper from 'timekeeper' import { root } from '../dist.mjs' const { SignJWT, jwtVerify, CompactSign } = await import(root) const now = 1604416038 test.before(async (t) => { t.context.secret = new Uint8Array(32) t.context.payload = { 'urn:example:claim': true } timekeeper.freeze(now * 1000) }) test.after(timekeeper.reset) test('Basic JWT Claims Set verification', async (t) => { const issuer = 'urn:example:issuer' const subject = 'urn:example:subject' const audience = 'urn:example:audience' const jti = 'urn:example:jti' const nbf = now - 10 const iat = now - 20 const exp = now + 10 const typ = 'urn:example:typ' const jwt = await new SignJWT(t.context.payload) .setProtectedHeader({ alg: 'HS256', typ }) .setIssuer(issuer) .setSubject(subject) .setAudience(audience) .setJti(jti) .setNotBefore(nbf) .setExpirationTime(exp) .setIssuedAt(iat) .sign(t.context.secret) t.deepEqual( await jwtVerify(jwt, t.context.secret, { issuer, subject, audience, jti, typ, maxTokenAge: '30s', }), { payload: { aud: 'urn:example:audience', exp: 1604416048, iat: 1604416018, iss: 'urn:example:issuer', jti: 'urn:example:jti', nbf: 1604416028, sub: 'urn:example:subject', 'urn:example:claim': true, }, protectedHeader: { alg: 'HS256', typ: 'urn:example:typ', }, }, ) await t.notThrowsAsync(jwtVerify(new TextEncoder().encode(jwt), t.context.secret)) }) test('Payload must be an object', async (t) => { const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) for (const value of [0, 1, -1, true, false, null, [], '']) { const token = await new CompactSign(encode(JSON.stringify(value))) .setProtectedHeader({ alg: 'HS256' }) .sign(t.context.secret) await t.throwsAsync(jwtVerify(token, t.context.secret), { code: 'ERR_JWT_INVALID', message: 'JWT Claims Set must be a top-level JSON object', }) } }) test('incorrect hmac signature lengths', async (t) => { const jwt = await new SignJWT(t.context.payload) .setProtectedHeader({ alg: 'HS256' }) .sign(t.context.secret) await t.throwsAsync(jwtVerify(jwt.slice(0, -3), t.context.secret), { code: 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED', message: 'signature verification failed', }) }) test('Payload must JSON parseable', async (t) => { const encode = TextEncoder.prototype.encode.bind(new TextEncoder()) const token = await new CompactSign(encode('{')) .setProtectedHeader({ alg: 'HS256' }) .sign(t.context.secret) await t.throwsAsync(jwtVerify(token, t.context.secret), { code: 'ERR_JWT_INVALID', message: 'JWT Claims Set must be a top-level JSON object', }) }) test('algorithms options', async (t) => { const jwt = await new SignJWT(t.context.payload) .setProtectedHeader({ alg: 'HS256' }) .sign(t.context.secret) await t.throwsAsync( jwtVerify(jwt, t.context.secret, { algorithms: ['PS256'], }), { code: 'ERR_JOSE_ALG_NOT_ALLOWED', message: '"alg" (Algorithm) Header Parameter not allowed', }, ) await t.throwsAsync( jwtVerify(jwt, t.context.secret, { algorithms: [null], }), { instanceOf: TypeError, message: '"algorithms" option must be an array of strings', }, ) }) test('typ verification', async (t) => { { const typ = 'urn:example:typ' const jwt = await new SignJWT(t.context.payload) .setProtectedHeader({ alg: 'HS256', typ }) .sign(t.context.secret) await t.notThrowsAsync( jwtVerify(jwt, t.context.secret, { typ: 'application/urn:example:typ', }), ) await t.throwsAsync( jwtVerify(jwt, t.context.secret, { typ: 'urn:example:typ:2', }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "typ" JWT header value' }, ) await t.throwsAsync( jwtVerify(jwt, t.context.secret, { typ: 'application/urn:example:typ:2', }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "typ" JWT header value' }, ) } { const typ = 'application/urn:example:typ' const jwt = await new SignJWT(t.context.payload) .setProtectedHeader({ alg: 'HS256', typ }) .sign(t.context.secret) await t.notThrowsAsync( jwtVerify(jwt, t.context.secret, { typ: 'urn:example:typ', }), ) await t.throwsAsync( jwtVerify(jwt, t.context.secret, { typ: 'application/urn:example:typ:2', }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "typ" JWT header value' }, ) await t.throwsAsync( jwtVerify(jwt, t.context.secret, { typ: 'urn:example:typ:2', }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "typ" JWT header value' }, ) } }) test('Issuer[] verification', async (t) => { const issuer = 'urn:example:issuer' const jwt = await new SignJWT(t.context.payload) .setProtectedHeader({ alg: 'HS256' }) .setIssuer(issuer) .sign(t.context.secret) await t.notThrowsAsync( jwtVerify(jwt, t.context.secret, { issuer: [issuer], }), ) }) test('Issuer[] verification failed', async (t) => { const issuer = 'urn:example:issuer' const jwt = await new SignJWT(t.context.payload) .setProtectedHeader({ alg: 'HS256' }) .setIssuer(issuer) .sign(t.context.secret) await t.throwsAsync( jwtVerify(jwt, t.context.secret, { issuer: [], }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "iss" claim value' }, ) }) test('Issuer[] verification failed []', async (t) => { const issuer = 'urn:example:issuer' const jwt = await new SignJWT(t.context.payload) .setProtectedHeader({ alg: 'HS256' }) .setIssuer([issuer]) .sign(t.context.secret) await t.throwsAsync( jwtVerify(jwt, t.context.secret, { issuer: [], }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "iss" claim value' }, ) }) test('Audience[] verification', async (t) => { const audience = 'urn:example:audience' const jwt = await new SignJWT(t.context.payload) .setProtectedHeader({ alg: 'HS256' }) .setAudience(audience) .sign(t.context.secret) await t.notThrowsAsync( jwtVerify(jwt, t.context.secret, { audience: [audience], }), ) }) test('Audience[] verification failed', async (t) => { const audience = 'urn:example:audience' const jwt = await new SignJWT(t.context.payload) .setProtectedHeader({ alg: 'HS256' }) .setAudience(audience) .sign(t.context.secret) await t.throwsAsync( jwtVerify(jwt, t.context.secret, { audience: [], }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "aud" claim value' }, ) }) test('Audience[] verification failed []', async (t) => { const audience = 'urn:example:audience' const jwt = await new SignJWT(t.context.payload) .setProtectedHeader({ alg: 'HS256' }) .setAudience([audience]) .sign(t.context.secret) await t.throwsAsync( jwtVerify(jwt, t.context.secret, { audience: [], }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "aud" claim value' }, ) }) test('Subject verification failed', async (t) => { const subject = 'urn:example:subject' const jwt = await new SignJWT(t.context.payload) .setProtectedHeader({ alg: 'HS256' }) .setSubject(subject) .sign(t.context.secret) await t.throwsAsync( jwtVerify(jwt, t.context.secret, { subject: 'urn:example:subject:2', }), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: 'unexpected "sub" claim value' }, ) }) async function numericDateNumber(t, claim) { const jwt = await new SignJWT({ [claim]: null }) .setProtectedHeader({ alg: 'HS256' }) .sign(t.context.secret) await t.throwsAsync(jwtVerify(jwt, t.context.secret), { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: `"${claim}" claim must be a number`, }) } numericDateNumber.title = (t, claim) => `${claim} must be a number` test('clockTolerance num', async (t) => { const jwt = await new SignJWT({ exp: now }) .setProtectedHeader({ alg: 'HS256' }) .sign(t.context.secret) await t.notThrowsAsync(jwtVerify(jwt, t.context.secret, { clockTolerance: 1 })) await t.notThrowsAsync(jwtVerify(jwt, t.context.secret, { clockTolerance: '1s' })) }) async function failingNumericDate(t, claims, assertion, verifyOptions) { const jwt = await new SignJWT({ ...claims }) .setProtectedHeader({ alg: 'HS256' }) .sign(t.context.secret) await t.throwsAsync(jwtVerify(jwt, t.context.secret, { ...verifyOptions }), assertion) } test( 'exp must be in the future', failingNumericDate, { exp: now }, { code: 'ERR_JWT_EXPIRED', message: '"exp" claim timestamp check failed', }, ) test( 'nbf must be at least now', failingNumericDate, { nbf: now + 1 }, { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: '"nbf" claim timestamp check failed', }, ) test( 'iat must be in the past (maxTokenAge, no exp)', failingNumericDate, { iat: now + 1 }, { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: '"iat" claim timestamp check failed (it should be in the past)', }, { maxTokenAge: 5, }, ) test( 'iat must be in the past (maxTokenAge, with exp)', failingNumericDate, { iat: now + 1, exp: now + 10 }, { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: '"iat" claim timestamp check failed (it should be in the past)', }, { maxTokenAge: 5, }, ) test( 'iat must be in the past (maxTokenAge, with exp, as a string)', failingNumericDate, { iat: now + 1, exp: now + 10 }, { code: 'ERR_JWT_CLAIM_VALIDATION_FAILED', message: '"iat" claim timestamp check failed (it should be in the past)', }, { maxTokenAge: '5s', }, ) test( 'maxTokenAge option', failingNumericDate, { iat: now - 31 }, { code: 'ERR_JWT_EXPIRED', message: '"iat" claim timestamp check failed (too far in the past)', }, { maxTokenAge: '30s', }, ) for (const claim of ['iat', 'nbf', 'exp']) { test(numericDateNumber, claim) } test('Signed JWTs cannot use unencoded payload', async (t) => { await t.throwsAsync( jwtVerify( 'eyJhbGciOiJIUzI1NiIsImI2NCI6ZmFsc2UsImNyaXQiOlsiYjY0Il19.foo.VklKdp4tVYD61VNPDBTqxqdEQcUL3JK-D4dGXu9NvWs', t.context.secret, ), { code: 'ERR_JWT_INVALID', message: 'JWTs MUST NOT use unencoded payload' }, ) }) test('signatures are compared before claim set', async (t) => { // https://github.com/panva/jose/discussions/447 const jwt = await new SignJWT({ exp: 0 }) .setProtectedHeader({ alg: 'HS256' }) .sign(t.context.secret) // with valid secret should throw exp failing to verify await t.throwsAsync(jwtVerify(jwt, t.context.secret), { code: 'ERR_JWT_EXPIRED' }) // with invalid secret should throw signature failing to verify await t.throwsAsync(jwtVerify(jwt, new Uint8Array([0x00, 0x01])), { code: 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED', }) }) jose-4.11.4/test/unit/000077500000000000000000000000001437043056600145075ustar00rootroot00000000000000jose-4.11.4/test/unit/buffer_utils.test.mjs000066400000000000000000000004351437043056600206730ustar00rootroot00000000000000import test from 'ava' import { root } from '../dist.mjs' const { uint32be } = await import(`${root}/lib/buffer_utils`) test('lib/buffer_utils.ts', (t) => { t.throws(() => uint32be(-1), { instanceOf: RangeError }) t.throws(() => uint32be(2 ** 32), { instanceOf: RangeError }) }) jose-4.11.4/test/unit/cek.test.mjs000066400000000000000000000004131437043056600167400ustar00rootroot00000000000000import test from 'ava' import { root } from '../dist.mjs' const { default: cek } = await import(`${root}/lib/cek`) test('lib/cek.ts', (t) => { t.throws(() => cek('foo'), { code: 'ERR_JOSE_NOT_SUPPORTED', message: 'Unsupported JWE Algorithm: foo', }) }) jose-4.11.4/test/unit/check_iv_length.test.mjs000066400000000000000000000006201437043056600213120ustar00rootroot00000000000000import test from 'ava' import { root } from '../dist.mjs' const { default: checkIvLength } = await import(`${root}/lib/check_iv_length`) test('lib/check_iv_length.ts', (t) => { t.throws(() => checkIvLength('A256GCM', new Uint8Array(13)), { code: 'ERR_JWE_INVALID', message: 'Invalid Initialization Vector length', }) t.notThrows(() => checkIvLength('A256GCM', new Uint8Array(12))) }) jose-4.11.4/test/unit/check_key_type.test.mjs000066400000000000000000000072471437043056600212000ustar00rootroot00000000000000import test from 'ava' import { root, keyRoot } from '../dist.mjs' let types = 'KeyObject or Uint8Array' let asymmetricTypes = 'KeyObject' if ('WEBCRYPTO' in process.env || 'WEBAPI' in process.env) { types = 'CryptoKey or Uint8Array' asymmetricTypes = 'CryptoKey' } else if (parseInt(process.versions.node) >= 16) { types = 'KeyObject, CryptoKey, or Uint8Array' asymmetricTypes = 'KeyObject or CryptoKey' } const { default: checkKeyType } = await import(`${root}/lib/check_key_type`) const { generateKeyPair, generateSecret } = await import(keyRoot) test('lib/check_key_type.ts', async (t) => { const expected = { instanceOf: TypeError, message: new RegExp(`^Key for the .+ algorithm must be (?:one )?of type ${types}\\.`), } t.throws(() => checkKeyType('HS256'), expected) t.throws(() => checkKeyType('HS256', undefined), expected) t.throws(() => checkKeyType('HS256', null), expected) t.throws(() => checkKeyType('HS256', 1), expected) t.throws(() => checkKeyType('HS256', 0), expected) t.throws(() => checkKeyType('HS256', true), expected) t.throws(() => checkKeyType('HS256', Boolean), expected) t.throws(() => checkKeyType('HS256', []), expected) t.throws(() => checkKeyType('HS256', ''), expected) t.throws(() => checkKeyType('HS256', 'foo'), expected) t.throws(() => checkKeyType('PS256', new Uint8Array()), { ...expected, message: new RegExp(`^Key for the .+ algorithm must be (?:one )?of type ${asymmetricTypes}\\.`), }) let secret = await generateSecret('HS256') t.throws(() => checkKeyType('PS256', secret), { ...expected, message: `${asymmetricTypes} instances for asymmetric algorithms must not be of type "secret"`, }) t.notThrows(() => checkKeyType('dir', new Uint8Array())) t.notThrows(() => checkKeyType('HS256', new Uint8Array())) t.notThrows(() => checkKeyType('PBES2-HS256+A128KW', new Uint8Array())) t.notThrows(() => checkKeyType('A256GCMKW', new Uint8Array())) t.notThrows(() => checkKeyType('A256KW', new Uint8Array())) secret = await generateSecret('A256GCMKW') t.notThrows(() => checkKeyType('dir', secret)) secret = await generateSecret('HS256') t.notThrows(() => checkKeyType('HS256', secret)) secret = await generateSecret('A256GCMKW') t.notThrows(() => checkKeyType('A256GCMKW', secret)) secret = await generateSecret('A256KW') t.notThrows(() => checkKeyType('A256KW', secret)) let keypair = await generateKeyPair('PS256') t.throws(() => checkKeyType('PS256', keypair.publicKey, 'sign'), { ...expected, message: `${asymmetricTypes} instances for asymmetric algorithm signing must be of type "private"`, }) t.throws(() => checkKeyType('HS256', keypair.privateKey), { ...expected, message: `${asymmetricTypes} instances for symmetric algorithms must be of type "secret"`, }) if (keyRoot.includes('web')) { t.throws(() => checkKeyType('PS256', keypair.privateKey, 'verify'), { ...expected, message: `${asymmetricTypes} instances for asymmetric algorithm verifying must be of type "public"`, }) } else { t.notThrows(() => checkKeyType('PS256', keypair.privateKey, 'verify')) } keypair = await generateKeyPair('ECDH-ES') t.throws(() => checkKeyType('ECDH-ES', keypair.publicKey, 'decrypt'), { ...expected, message: `${asymmetricTypes} instances for asymmetric algorithm decryption must be of type "private"`, }) if (keyRoot.includes('web')) { t.throws(() => checkKeyType('ECDH-ES', keypair.privateKey, 'encrypt'), { ...expected, message: `${asymmetricTypes} instances for asymmetric algorithm encryption must be of type "public"`, }) } else { t.notThrows(() => checkKeyType('ECDH-ES', keypair.privateKey, 'encrypt')) } }) jose-4.11.4/test/unit/check_p2s.test.mjs000066400000000000000000000007411437043056600200430ustar00rootroot00000000000000import test from 'ava' import { root } from '../dist.mjs' const { default: checkP2s } = await import(`${root}/lib/check_p2s`) test('lib/check_p2s.ts', (t) => { t.throws(() => checkP2s(null), { code: 'ERR_JWE_INVALID', message: 'PBES2 Salt Input must be 8 or more octets', }) t.throws(() => checkP2s(new Uint8Array(7)), { code: 'ERR_JWE_INVALID', message: 'PBES2 Salt Input must be 8 or more octets', }) t.notThrows(() => checkP2s(new Uint8Array(8))) }) jose-4.11.4/test/unit/iv.test.mjs000066400000000000000000000004071437043056600166170ustar00rootroot00000000000000import test from 'ava' import { root } from '../dist.mjs' const { default: iv } = await import(`${root}/lib/iv`) test('lib/iv.ts', (t) => { t.throws(() => iv('foo'), { code: 'ERR_JOSE_NOT_SUPPORTED', message: 'Unsupported JWE Algorithm: foo', }) }) jose-4.11.4/test/unit/secs.test.mjs000066400000000000000000000017331437043056600171410ustar00rootroot00000000000000import test from 'ava' import { root } from '../dist.mjs' const { default: secs } = await import(`${root}/lib/secs`) test('lib/secs.ts', (t) => { for (const v of ['sec', 'secs', 'second', 'seconds', 's']) { t.is(secs(`1${v}`), 1) t.is(secs(`1 ${v}`), 1) } for (const v of ['minute', 'minutes', 'min', 'mins', 'm']) { t.is(secs(`1${v}`), 60) t.is(secs(`1 ${v}`), 60) } for (const v of ['hour', 'hours', 'hr', 'hrs', 'h']) { t.is(secs(`1${v}`), 3600) t.is(secs(`1 ${v}`), 3600) } for (const v of ['day', 'days', 'd']) { t.is(secs(`1${v}`), 86400) t.is(secs(`1 ${v}`), 86400) } for (const v of ['week', 'weeks', 'w']) { t.is(secs(`1${v}`), 604800) t.is(secs(`1 ${v}`), 604800) } for (const v of ['years', 'year', 'yrs', 'yr', 'y']) { t.is(secs(`1${v}`), 31557600) t.is(secs(`1 ${v}`), 31557600) } t.throws(() => secs('1 fortnight'), { instanceOf: TypeError, message: 'Invalid time period format', }) }) jose-4.11.4/test/util/000077500000000000000000000000001437043056600145055ustar00rootroot00000000000000jose-4.11.4/test/util/decode_jwt.test.mjs000066400000000000000000000031541437043056600203100ustar00rootroot00000000000000import test from 'ava' import { root } from '../dist.mjs' const { decodeJwt, errors, base64url } = await import(root) test('invalid inputs', (t) => { const jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c' const parts = jwt.split('.') t.throws(() => decodeJwt(null), { instanceOf: errors.JWTInvalid, message: 'JWTs must use Compact JWS serialization, JWT must be a string', }) t.throws(() => decodeJwt('....'), { instanceOf: errors.JWTInvalid, message: 'Only JWTs using Compact JWS serialization can be decoded', }) t.throws(() => decodeJwt('.'), { instanceOf: errors.JWTInvalid, message: 'Invalid JWT', }) t.throws(() => decodeJwt([parts[0], '', parts[2]].join('.')), { instanceOf: errors.JWTInvalid, message: 'JWTs must contain a payload', }) t.throws(() => decodeJwt([parts[0], base64url.encode('null'), parts[2]].join('.')), { instanceOf: errors.JWTInvalid, message: 'Invalid JWT Claims Set', }) t.throws(() => decodeJwt([parts[0], base64url.encode('[]'), parts[2]].join('.')), { instanceOf: errors.JWTInvalid, message: 'Invalid JWT Claims Set', }) t.throws(() => decodeJwt([parts[0], base64url.encode('{"notajson'), parts[2]].join('.')), { instanceOf: errors.JWTInvalid, message: 'Failed to parse the decoded payload as JSON', }) t.deepEqual(decodeJwt([parts[0], base64url.encode('{}'), parts[2]].join('.')), {}) t.deepEqual(decodeJwt(jwt), { sub: '1234567890', name: 'John Doe', iat: 1516239022, }) }) jose-4.11.4/test/util/decode_protected_header.test.mjs000066400000000000000000000051031437043056600230010ustar00rootroot00000000000000import test from 'ava' import { root } from '../dist.mjs' const { decodeProtectedHeader } = await import(root) test('invalid inputs', (t) => { t.throws(() => decodeProtectedHeader(null), { instanceOf: TypeError, message: 'Invalid Token or Protected Header formatting', }) t.throws(() => decodeProtectedHeader('.'), { instanceOf: TypeError, message: 'Invalid Token or Protected Header formatting', }) t.throws(() => decodeProtectedHeader('ew..'), { instanceOf: TypeError, message: 'Invalid Token or Protected Header formatting', }) t.throws(() => decodeProtectedHeader('bnVsbA..'), { instanceOf: TypeError, message: 'Invalid Token or Protected Header formatting', }) t.throws(() => decodeProtectedHeader('W10..'), { instanceOf: TypeError, message: 'Invalid Token or Protected Header formatting', }) t.throws(() => decodeProtectedHeader('...'), { instanceOf: TypeError, message: 'Invalid Token or Protected Header formatting', }) t.throws(() => decodeProtectedHeader('ew....'), { instanceOf: TypeError, message: 'Invalid Token or Protected Header formatting', }) t.throws(() => decodeProtectedHeader('bnVsbA....'), { instanceOf: TypeError, message: 'Invalid Token or Protected Header formatting', }) t.throws(() => decodeProtectedHeader('W10....'), { instanceOf: TypeError, message: 'Invalid Token or Protected Header formatting', }) t.throws(() => decodeProtectedHeader('.....'), { instanceOf: TypeError, message: 'Invalid Token or Protected Header formatting', }) t.throws(() => decodeProtectedHeader({ protected: null }), { instanceOf: TypeError, message: 'Invalid Token or Protected Header formatting', }) t.throws(() => decodeProtectedHeader({ protected: 'ew' }), { instanceOf: TypeError, message: 'Invalid Token or Protected Header formatting', }) t.throws(() => decodeProtectedHeader({ protected: 'bnVsbA' }), { instanceOf: TypeError, message: 'Invalid Token or Protected Header formatting', }) t.throws(() => decodeProtectedHeader({ protected: 'W10' }), { instanceOf: TypeError, message: 'Invalid Token or Protected Header formatting', }) t.throws(() => decodeProtectedHeader({}), { instanceOf: TypeError, message: 'Token does not contain a Protected Header', }) t.deepEqual(decodeProtectedHeader('eyJhbGciOiJIUzI1NiJ9..'), { alg: 'HS256' }) t.deepEqual(decodeProtectedHeader('eyJhbGciOiJIUzI1NiJ9....'), { alg: 'HS256' }) t.deepEqual(decodeProtectedHeader({ protected: 'eyJhbGciOiJIUzI1NiJ9' }), { alg: 'HS256' }) }) jose-4.11.4/tools/000077500000000000000000000000001437043056600137115ustar00rootroot00000000000000jose-4.11.4/tools/postbump.js000077500000000000000000000031651437043056600161300ustar00rootroot00000000000000const { x } = require('tar') const { execSync } = require('child_process') const { readFileSync, writeFileSync } = require('fs') const { version } = require('../package.json') const readme = readFileSync('docs/README.md') const tagName = `v${version}` const opts = { stdio: 'inherit' } execSync('git rm -f docs/**/*.md', opts) execSync('find docs -type d | grep "docs/" | xargs rm -rf', opts) execSync('npx patch-package', opts) execSync('npm run runtime-browser', opts) execSync(`npm run docs:generate -- --gitRevision ${tagName}`, opts) writeFileSync('docs/README.md', readme) execSync('npm pack', opts) execSync('rm -rf dist', opts) x({ f: `jose-${version}.tgz`, strip: true, filter(loc) { return loc.startsWith('package/dist/') }, sync: true, }) execSync('npm run build:deno', opts) writeFileSync( 'dist/deno/README.md', readFileSync('docs/readme.md', { encoding: 'utf-8' }).replace( /\*\*[\s\S]+```/gm, `**\`example\`** Deno import \`\`\`js import * as jose from 'https://deno.land/x/jose@${tagName}/index.ts' \`\`\``, ), ) execSync('npm run build:browser-bundle', opts) execSync('npm run build:browser-bundle-min', opts) execSync('npm run build:browser-umd', opts) execSync( `sed -i '' -e 's/](/](https:\\/\\/github.com\\/panva\\/jose\\/blob\\/${tagName}\\/docs\\//g' dist/deno/README.md`, ) execSync('git add docs/**/*.md', opts) execSync('git add dist/**/* -f', opts) for (const path of ['./README.md', './docs/README.md']) { writeFileSync( path, readFileSync(path, { encoding: 'utf-8' }).replace(/jose@v\d+\.\d+\.\d+/gm, `jose@v${version}`), ) execSync(`git add ${path}`, { stdio: 'inherit' }) } jose-4.11.4/tools/publish-browser.js000077500000000000000000000010641437043056600174020ustar00rootroot00000000000000const { readFileSync, writeFileSync, unlinkSync } = require('fs') const pkg = JSON.parse(readFileSync('./package.json')) delete pkg.devDependencies delete pkg.scripts delete pkg.imports delete pkg.description delete pkg.main delete pkg.exports['.'].import delete pkg.exports['.'].require delete pkg.keywords pkg.files.push('!dist/**/package.json') pkg.files.push('!dist/node/**/*') pkg.name = 'jose-browser-runtime' pkg.type = 'module' writeFileSync('./package.json', JSON.stringify(pkg, null, 2) + '\n') unlinkSync('./CHANGELOG.md') unlinkSync('./README.md') jose-4.11.4/tools/publish-node-cjs.js000077500000000000000000000011661437043056600174240ustar00rootroot00000000000000const { readFileSync, writeFileSync, unlinkSync } = require('fs') const pkg = JSON.parse(readFileSync('./package.json')) delete pkg.devDependencies delete pkg.scripts delete pkg.imports delete pkg.description delete pkg.browser delete pkg.deno delete pkg.exports['.'].browser delete pkg.exports['.'].deno delete pkg.exports['.'].import delete pkg.keywords pkg.files.push('!dist/browser/**/*') pkg.files.push('!dist/node/esm/**/*') pkg.main = pkg.exports['.'].require pkg.name = 'jose-node-cjs-runtime' writeFileSync('./package.json', JSON.stringify(pkg, null, 2) + '\n') unlinkSync('./CHANGELOG.md') unlinkSync('./README.md') jose-4.11.4/tools/publish-node-esm.js000077500000000000000000000012621437043056600174260ustar00rootroot00000000000000const { readFileSync, writeFileSync, unlinkSync } = require('fs') const pkg = JSON.parse(readFileSync('./package.json')) delete pkg.devDependencies delete pkg.scripts delete pkg.imports delete pkg.description delete pkg.browser delete pkg.deno delete pkg.exports['.'].browser delete pkg.exports['.'].deno delete pkg.exports['.'].require delete pkg.keywords pkg.files.push('!dist/**/package.json') pkg.files.push('!dist/browser/**/*') pkg.files.push('!dist/node/cjs/**/*') pkg.main = pkg.exports['.'].import pkg.name = 'jose-node-esm-runtime' pkg.type = 'module' writeFileSync('./package.json', JSON.stringify(pkg, null, 2) + '\n') unlinkSync('./CHANGELOG.md') unlinkSync('./README.md') jose-4.11.4/tools/publish-universal.js000077500000000000000000000004361437043056600177310ustar00rootroot00000000000000const { readFileSync, writeFileSync, unlinkSync } = require('fs') const pkg = JSON.parse(readFileSync('./package.json')) delete pkg.devDependencies delete pkg.scripts delete pkg.imports writeFileSync('./package.json', JSON.stringify(pkg, null, 2) + '\n') unlinkSync('./CHANGELOG.md') jose-4.11.4/tools/release-notes.js000066400000000000000000000007571437043056600170260ustar00rootroot00000000000000const fs = require('fs') const { execSync } = require('child_process') execSync('git show HEAD -- CHANGELOG.md > CHANGELOG.diff') const tag = execSync('git tag --points-at HEAD').toString().trim() fs.writeFileSync( 'notes.md', fs .readFileSync('CHANGELOG.diff') .toString() .split('\n') .filter((line) => line.startsWith('+') && !line.startsWith('+++')) .map((line) => line.slice(1)) .slice(3) .join('\n'), ) execSync(`gh release create ${tag} -dF notes.md`) jose-4.11.4/tsconfig/000077500000000000000000000000001437043056600143655ustar00rootroot00000000000000jose-4.11.4/tsconfig/base.json000066400000000000000000000004471437043056600161770ustar00rootroot00000000000000{ "files": [ "../src/index.ts" ], "compilerOptions": { "lib": ["ES2017", "DOM"], "types": [], "strict": true, "forceConsistentCasingInFileNames": true, "noUnusedLocals": true, "noUnusedParameters": true, "sourceMap": false, "removeComments": true } } jose-4.11.4/tsconfig/browser.json000066400000000000000000000002101437043056600167340ustar00rootroot00000000000000{ "extends": "./base.json", "compilerOptions": { "target": "ES2018", "module": "ES6", "outDir": "../dist/browser" } } jose-4.11.4/tsconfig/node-cjs.json000066400000000000000000000002451437043056600167630ustar00rootroot00000000000000{ "extends": "./base.json", "compilerOptions": { "types": ["node"], "target": "ES2019", "module": "CommonJS", "outDir": "../dist/node/cjs" } } jose-4.11.4/tsconfig/node-esm.json000066400000000000000000000001701437043056600167650ustar00rootroot00000000000000{ "extends": "./node-cjs.json", "compilerOptions": { "module": "ES2020", "outDir": "../dist/node/esm" } } jose-4.11.4/tsconfig/types.json000066400000000000000000000003101437043056600164160ustar00rootroot00000000000000{ "extends": "./base.json", "compilerOptions": { "target": "ESNext", "outDir": "../dist/types", "declaration": true, "emitDeclarationOnly": true, "removeComments": false } } jose-4.11.4/typedoc.json000066400000000000000000000026741437043056600151240ustar00rootroot00000000000000{ "$schema": "https://typedoc.org/schema.json", "allReflectionsHaveOwnDocument": true, "disableSources": true, "hideBreadcrumbs": true, "entryPoints": [ "src/types.d.ts", "src/jwt/decrypt.ts", "src/jwt/encrypt.ts", "src/jwt/produce.ts", "src/jwt/sign.ts", "src/jwt/unsecured.ts", "src/jwt/verify.ts", "src/jwe/compact/encrypt.ts", "src/jwe/compact/decrypt.ts", "src/jwe/flattened/encrypt.ts", "src/jwe/flattened/decrypt.ts", "src/jwe/general/encrypt.ts", "src/jwe/general/decrypt.ts", "src/jws/compact/sign.ts", "src/jws/compact/verify.ts", "src/jws/flattened/sign.ts", "src/jws/flattened/verify.ts", "src/jws/general/sign.ts", "src/jws/general/verify.ts", "src/jwk/embedded.ts", "src/jwk/thumbprint.ts", "src/jwks/local.ts", "src/jwks/remote.ts", "src/util/base64url.ts", "src/util/decode_jwt.ts", "src/util/decode_protected_header.ts", "src/util/errors.ts", "src/key/export.ts", "src/key/generate_key_pair.ts", "src/key/generate_secret.ts", "src/key/import.ts" ], "excludeExternals": true, "excludePrivate": true, "excludeProtected": true, "gitRevision": "main", "hideGenerator": true, "out": "docs", "plugin": ["typedoc-plugin-markdown", "./.mdn_links.cjs"], "readme": "none", "tsconfig": "./tsconfig/browser.json", "sort": ["kind", "static-first", "required-first", "alphabetical"], "githubPages": false }