diff --git a/.changeset/config.json b/.changeset/config.json
index 14c1d2c02..36407468a 100644
--- a/.changeset/config.json
+++ b/.changeset/config.json
@@ -7,21 +7,14 @@
}
],
"commit": false,
- "fixed": [["@forgerock/javascript-sdk", "@forgerock/ping-protect"]],
+ "fixed": [],
"linked": [],
"access": "public",
"baseBranch": "master",
"updateInternalDependencies": "patch",
"ignore": [
- "@forgerock/device-client",
- "autoscript-apps",
- "autoscript-suites",
- "davinci-app",
- "mock-api",
- "token-vault-app",
- "@forgerock/token-vault-interceptor",
- "token-vault-proxy",
- "token-vault-suites",
- "davinci-suites"
+ "@forgerock/davinci-app",
+ "@forgerock/davinci-suites",
+ "@forgerock/mock-api-v2"
]
}
diff --git a/.eslintrc.json b/.eslintrc.json
index d56654ad3..f68d95d71 100644
--- a/.eslintrc.json
+++ b/.eslintrc.json
@@ -17,35 +17,19 @@
"depConstraints": [
{
"sourceTag": "scope:app",
- "onlyDependOnLibsWithTags": [
- "scope:sdk",
- "scope:package",
- "scope:token-vault"
- ]
+ "onlyDependOnLibsWithTags": ["scope:package"]
},
{
"sourceTag": "scope:e2e",
- "onlyDependOnLibsWithTags": ["scope:sdk, scope:app"]
- },
- {
- "sourceTag": "scope:sdk",
- "onlyDependOnLibsWithTags": []
+ "onlyDependOnLibsWithTags": ["scope:app"]
},
{
"sourceTag": "scope:package",
- "onlyDependOnLibsWithTags": ["scope:sdk"]
- },
- {
- "sourceTag": "scope:token-vault",
- "onlyDependOnLibsWithTags": [
- "scope:sdk",
- "scope:lib",
- "scope:types"
- ]
+ "onlyDependOnLibsWithTags": []
},
{
"sourceTag": "scope:types",
- "onlyDependOnLibsWithTags": ["scope:sdk"]
+ "onlyDependOnLibsWithTags": []
}
]
}
@@ -85,6 +69,13 @@
"files": "*.json",
"parser": "jsonc-eslint-parser",
"rules": {}
+ },
+ {
+ "files": ["./package.json", "./generators.json"],
+ "parser": "jsonc-eslint-parser",
+ "rules": {
+ "@nx/nx-plugin-checks": "error"
+ }
}
],
"parser": "@typescript-eslint/parser",
diff --git a/.github/labeler.yml b/.github/labeler.yml
index a9c9f5c37..4bf2813f8 100644
--- a/.github/labeler.yml
+++ b/.github/labeler.yml
@@ -13,13 +13,13 @@ NX:
root:
- '*'
-samples:
- - samples/**/*
+davinci-client:
+ - packages/davinci-client/*
-sdk:
- - packages/javascript-sdk/*
- - packages/javascript-sdk/**/*
+device-client:
+ - packages/device-client/*
+ping-protect: -packages/ping-protect/*
test:
- e2e/**/*
- jest*
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4cae4ebb8..2952ef6d4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -25,7 +25,7 @@ jobs:
# This line enables distribution
# The "--stop-agents-after" is optional, but allows idle agents to shut down once the "e2e-ci" targets have been requested
- - run: pnpm dlx nx-cloud start-ci-run --distribute-on="5 linux-medium-js" --stop-agents-after="e2e-ci" --verbose
+ - run: pnpm dlx nx-cloud start-ci-run --distribute-on=".nx/workflows/dynamic-changesets.yml" --stop-agents-after="e2e-ci" --verbose
- run: pnpm exec playwright install
@@ -46,6 +46,5 @@ jobs:
with:
name: playwright-report
path: |
- ./dist/.playwright/**
- ./dist/**
+ ./**/.playwright/**
retention-days: 30
diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml
deleted file mode 100644
index d74a063c0..000000000
--- a/.github/workflows/labeler.yml
+++ /dev/null
@@ -1,21 +0,0 @@
-name: Labeler
-on:
- pull_request:
-
-env:
- NX_CLOUD_ACCESS_TOKEN: ${{ secrets.NX_CLOUD_ACCESS_TOKEN }}
- NX_CLOUD_ENCRYPTION_KEY: ${{ secrets.NX_CLOUD_ENCRYPTION_KEY }}
-
-jobs:
- label-pr:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v3
- with:
- ref: ${{ github.event.pull_request.head.ref }}
- repository: ${{github.event.pull_request.head.repo.full_name}}
- fetch-depth: 0
- - uses: actions/labeler@v4
- with:
- repo-token: '${{ secrets.GITHUB_TOKEN }}'
- sync-labels: true
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index e1e93705a..bf27b65cd 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -37,7 +37,7 @@ jobs:
# This line enables distribution
# The "--stop-agents-after" is optional, but allows idle agents to shut down once the "e2e-ci" targets have been requested
- - run: pnpm dlx nx-cloud start-ci-run --distribute-on="5 linux-medium-js" --stop-agents-after="e2e-ci" --verbose
+ - run: pnpm dlx nx-cloud start-ci-run --distribute-on=".nx/workflows/dynamic-changesets.yml" --stop-agents-after="e2e-ci" --verbose
- run: pnpm exec playwright install
@@ -55,8 +55,7 @@ jobs:
with:
name: playwright-report
path: |
- ./dist/.playwright/**
- ./dist/**
+ ./**/.playwright/**
retention-days: 30
- run: git status
diff --git a/.gitignore b/.gitignore
index ada70396e..aa40e056d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,14 +7,9 @@
tmp/
e2e/**/dist
*/dist/*
+**/dist
dist/*
packages/*/dist/
-packages/javascript-sdk/lib-esm
-packages/javascript-sdk/lib
-packages/javascript-sdk/bundle/
-e2e/token-vault-app/public/*.js
-e2e/token-vault-app/public/*.json
-e2e/token-vault-app/public/assets/
bundles/
docs/
coverage/
diff --git a/.nx/workflows/dynamic-changesets.yml b/.nx/workflows/dynamic-changesets.yml
index d3536f3ba..ae47c2dd9 100644
--- a/.nx/workflows/dynamic-changesets.yml
+++ b/.nx/workflows/dynamic-changesets.yml
@@ -1,4 +1,5 @@
distribute-on:
- small-changeset: 3 linux-medium-js
- medium-changeset: 6 linux-medium-js
- large-changeset: 10 linux-medium-js
+ small-changeset: 3 linux-medium-js # Distribute on small if 1-25% of projects affected in PR
+ medium-changeset: 6 linux-medium-js # Distribute on medium if 26-50% of projects affected in PR
+ large-changeset: 10 linux-medium-js # Distribute on large if 51-75% of projects affected in PR
+ extra-large-changeset: 15 linux-medium-js # Distribute on extra-large if 76-100% of projects affected in PR
diff --git a/.prettierignore b/.prettierignore
index b479f21ae..a1d996fa8 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -5,4 +5,8 @@
package-lock.json
*/*/package-lock.json
.husky/*
-/.nx/workspace-data
\ No newline at end of file
+/.nx/workspace-data
+pnpm-lock.yml
+packages/*/dist
+e2e/*/dist
+*/dist
\ No newline at end of file
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bf1f4aca5..a74820bca 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,9 +1,5 @@
# ForgeRock Javascript SDK Changelogs
-[ForgeRock Javascript SDK package](./packages/javascript-sdk/CHANGELOG.md)
-
-[ForgeRock Token Vault package](./packages/token-vault/CHANGELOG.md)
-
[ForgeRock Ping Protect package](./packages/ping-protect/CHANGELOG.md)
[ForgeRock DaVinci Client package](./packages/davinci-client/CHANGELOG.md)
diff --git a/contributing_docs/creating-a-package.md b/contributing_docs/creating-a-package.md
new file mode 100644
index 000000000..3308a9fbb
--- /dev/null
+++ b/contributing_docs/creating-a-package.md
@@ -0,0 +1,31 @@
+# Creating a package
+
+We have a local plugin to create packages within the repository. This document will explain the options when creating a package.
+
+## How to generate a package
+
+There is a `pnpm` command to create a package. `pnpm create-package`.
+
+## Options
+
+You will be provided with several prompts when creating the package.
+
+The only required prompt is a `name`. This is the `package` name and the file-system name.
+
+### Optional prompts
+
+`scope`: this is the `npm` scope that will be interpolated into the `package.json` `name` field. Do not include the `@` symbol, it is added automatically.
+
+`sideEffects`: This is to ensure packages are tree shakeable. `false` sets the the value to `false`. If you intend to have `sideEffects` you can set it to `true`. however this will mark _every_ file as a side effect. It's best to edit this afterwards on your own if the value is not `false`.
+
+`description`: If you want to add a description of the package in the `package.json`, `description` field.
+
+`moduleType`: This sets the `module` type. Either `commonjs` or `module` are valid entries. Default is `module`
+
+`outputDir`: This sets up the `output` directory. by default, it is set to `dist`. This typically shouldn't need to be changed.
+
+## Notes
+
+All packages are marked as `private` by default. This is to prevent unwanted publishing. It is the developer's responsibility to mark a package as public when ready to publish. See [releases](./releases.md) for more information on releases.
+
+All packages are by default setup to used `tsc`. Other build tools can be used after the generator is run. If its requested to add a generator or option for using `vite` or something else, please reach out to @ryanbas21 or add the feature in yourself and PR it.
diff --git a/e2e/autoscript-apps/.babelrc b/e2e/autoscript-apps/.babelrc
deleted file mode 100644
index aed1b9711..000000000
--- a/e2e/autoscript-apps/.babelrc
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "presets": [["@nx/js/babel", { "useBuiltIns": "entry" }]]
-}
diff --git a/e2e/autoscript-apps/.eslintignore b/e2e/autoscript-apps/.eslintignore
deleted file mode 100644
index b7dc1d3a2..000000000
--- a/e2e/autoscript-apps/.eslintignore
+++ /dev/null
@@ -1,11 +0,0 @@
-node_modules
-*.md
-LICENSE
-.babelrc
-.env*
-.bin
-dist
-*.html
-browserslist
-.eslintignore
-.eslintrc.json
\ No newline at end of file
diff --git a/e2e/autoscript-apps/.eslintrc.json b/e2e/autoscript-apps/.eslintrc.json
deleted file mode 100644
index d4a111816..000000000
--- a/e2e/autoscript-apps/.eslintrc.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "extends": ["../../.eslintrc.json"],
- "ignorePatterns": ["**/*"]
-}
diff --git a/e2e/autoscript-apps/browserslist b/e2e/autoscript-apps/browserslist
deleted file mode 100644
index 8d6179367..000000000
--- a/e2e/autoscript-apps/browserslist
+++ /dev/null
@@ -1,13 +0,0 @@
-# This file is currently used by autoprefixer to adjust CSS to support the below specified browsers
-# For additional information regarding the format and rule options, please see:
-# https://github.com/browserslist/browserslist#queries
-#
-# If you need to support different browsers in production, you may tweak the list below.
-
-last 1 Chrome version
-last 1 Firefox version
-last 2 Edge major versions
-last 2 Safari major version
-last 2 iOS major versions
-Firefox ESR
-not IE 9-11 # For IE 9-11 support, remove 'not'.
\ No newline at end of file
diff --git a/e2e/autoscript-apps/index.html b/e2e/autoscript-apps/index.html
deleted file mode 100644
index 1a85e6f0e..000000000
--- a/e2e/autoscript-apps/index.html
+++ /dev/null
@@ -1,75 +0,0 @@
-
-
-
- E2E Test Index | ForgeRock JavaScript SDK
-
-
-
-
-
- AuthN: Basic
- AuthN: Self Service
- AuthN: Central Login
- AuthN: Central Logout Ping
- AuthN: Device Profile
- AuthN: Ping Protect
- AuthN: Email Suspend
- AuthN: Recaptcha Enterprise
- AuthN: No Session
- AuthN: OAuth
- AuthN: WellKnown
- AuthN: Platform Login
- AuthN: Second Factor
- AuthN: SAML
- AuthN: Social Login AM
- AuthN: Protect Metadata AM
- AuthN: Social Login IDM
- AuthN: WebAuthn
-
- AuthN: WebAuthN Device Registration
-
-
- AuthN: OTP Registration (QR Code)
- AuthZ: Token
-
- AuthZ: Tree-based with Basic Login and Redirect response
-
-
-
- AuthZ: Tree-based with Basic Login and JSON response
-
-
- AuthZ: Tree-based with OAuth
- AuthZ: Txn-based with Basic Login and Redirect response
-
-
- AuthZ: Txn-based with Basic Login and JSON response
-
-
- AuthZ: Txn-based with OAuth
- Config: Custom Path
- Config: Request Middleware
- Config: Token Storage
- Misc Callbacks
- Registration
- UMD Bundle Check
-
-
diff --git a/e2e/autoscript-apps/package.json b/e2e/autoscript-apps/package.json
deleted file mode 100644
index 746907575..000000000
--- a/e2e/autoscript-apps/package.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "name": "autoscript-apps",
- "version": "0.0.0",
- "private": true,
- "type": "module",
- "dependencies": {
- "@forgerock/javascript-sdk": "workspace:*",
- "@forgerock/device-client": "workspace:*",
- "@forgerock/ping-protect": "workspace:*",
- "rxjs": "^7.4.0"
- },
- "description": "apps for e2e on js sdk",
- "license": "ISC",
- "repository": {
- "type": "git",
- "url": "git+https://github.com/ForgeRock/forgerock-javascript-sdk.git"
- },
- "bugs": {
- "url": "https://github.com/ForgeRock/forgerock-javascript-sdk/issues"
- },
- "homepage": "https://github.com/ForgeRock/forgerock-javascript-sdk#readme"
-}
diff --git a/e2e/autoscript-apps/project.json b/e2e/autoscript-apps/project.json
deleted file mode 100644
index 1df806310..000000000
--- a/e2e/autoscript-apps/project.json
+++ /dev/null
@@ -1,35 +0,0 @@
-{
- "name": "autoscript-apps",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "projectType": "application",
- "sourceRoot": "e2e/autoscript-apps/src",
- "tags": ["scope:app"],
- "targets": {
- "build": {
- "inputs": ["default", "^default"],
- "outputs": ["{projectRoot}/dist"],
- "options": {
- "outDir": "./dist"
- },
- "configurations": {
- "development": {
- "mode": "development"
- }
- }
- },
- "serve": {
- "defaultConfiguration": "development",
- "configurations": {
- "development": {},
- "production": {}
- }
- },
- "preview": {
- "defaultConfiguration": "production",
- "configurations": {
- "development": {},
- "production": {}
- }
- }
- }
-}
diff --git a/e2e/autoscript-apps/src/_callback/index.html b/e2e/autoscript-apps/src/_callback/index.html
deleted file mode 100644
index f106e0a38..000000000
--- a/e2e/autoscript-apps/src/_callback/index.html
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
-
- Logged In | E2E Test | ForgeRock JavaScript SDK Samples
-
-
-
-
diff --git a/e2e/autoscript-apps/src/_polyfills/fast-text-encoder.js b/e2e/autoscript-apps/src/_polyfills/fast-text-encoder.js
deleted file mode 100644
index 2cb076e6b..000000000
--- a/e2e/autoscript-apps/src/_polyfills/fast-text-encoder.js
+++ /dev/null
@@ -1,285 +0,0 @@
-/*
- * Copyright 2017 Sam Thorogood. All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-/**
- * @fileoverview Polyfill for TextEncoder and TextDecoder.
- *
- * You probably want `text.min.js`, and not this file directly.
- */
-
-(function (scope) {
- 'use strict';
-
- // fail early
- if (scope['TextEncoder'] && scope['TextDecoder']) {
- return false;
- }
-
- // used for FastTextDecoder
- const validUtfLabels = ['utf-8', 'utf8', 'unicode-1-1-utf-8'];
-
- /**
- * @constructor
- */
- function FastTextEncoder() {
- // This does not accept an encoding, and always uses UTF-8:
- // https://www.w3.org/TR/encoding/#dom-textencoder
- }
-
- Object.defineProperty(FastTextEncoder.prototype, 'encoding', { value: 'utf-8' });
-
- /**
- * @param {string} string
- * @param {{stream: boolean}=} options
- * @return {!Uint8Array}
- */
- FastTextEncoder.prototype['encode'] = function (string, options = { stream: false }) {
- if (options.stream) {
- throw new Error(`Failed to encode: the 'stream' option is unsupported.`);
- }
-
- let pos = 0;
- const len = string.length;
-
- let at = 0; // output position
- let tlen = Math.max(32, len + (len >>> 1) + 7); // 1.5x size
- let target = new Uint8Array((tlen >>> 3) << 3); // ... but at 8 byte offset
-
- while (pos < len) {
- let value = string.charCodeAt(pos++);
- if (value >= 0xd800 && value <= 0xdbff) {
- // high surrogate
- if (pos < len) {
- const extra = string.charCodeAt(pos);
- if ((extra & 0xfc00) === 0xdc00) {
- ++pos;
- value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
- }
- }
- if (value >= 0xd800 && value <= 0xdbff) {
- continue; // drop lone surrogate
- }
- }
-
- // expand the buffer if we couldn't write 4 bytes
- if (at + 4 > target.length) {
- tlen += 8; // minimum extra
- tlen *= 1.0 + (pos / string.length) * 2; // take 2x the remaining
- tlen = (tlen >>> 3) << 3; // 8 byte offset
-
- const update = new Uint8Array(tlen);
- update.set(target);
- target = update;
- }
-
- if ((value & 0xffffff80) === 0) {
- // 1-byte
- target[at++] = value; // ASCII
- continue;
- } else if ((value & 0xfffff800) === 0) {
- // 2-byte
- target[at++] = ((value >>> 6) & 0x1f) | 0xc0;
- } else if ((value & 0xffff0000) === 0) {
- // 3-byte
- target[at++] = ((value >>> 12) & 0x0f) | 0xe0;
- target[at++] = ((value >>> 6) & 0x3f) | 0x80;
- } else if ((value & 0xffe00000) === 0) {
- // 4-byte
- target[at++] = ((value >>> 18) & 0x07) | 0xf0;
- target[at++] = ((value >>> 12) & 0x3f) | 0x80;
- target[at++] = ((value >>> 6) & 0x3f) | 0x80;
- } else {
- continue; // out of range
- }
-
- target[at++] = (value & 0x3f) | 0x80;
- }
-
- // Use subarray if slice isn't supported (IE11). This will use more memory
- // because the original array still exists.
- return target.slice ? target.slice(0, at) : target.subarray(0, at);
- };
-
- /**
- * @constructor
- * @param {string=} utfLabel
- * @param {{fatal: boolean}=} options
- */
- function FastTextDecoder(utfLabel = 'utf-8', options = { fatal: false }) {
- if (validUtfLabels.indexOf(utfLabel.toLowerCase()) === -1) {
- throw new RangeError(
- `Failed to construct 'TextDecoder': The encoding label provided ('${utfLabel}') is invalid.`,
- );
- }
- if (options.fatal) {
- throw new Error(`Failed to construct 'TextDecoder': the 'fatal' option is unsupported.`);
- }
- }
-
- Object.defineProperty(FastTextDecoder.prototype, 'encoding', { value: 'utf-8' });
-
- Object.defineProperty(FastTextDecoder.prototype, 'fatal', { value: false });
-
- Object.defineProperty(FastTextDecoder.prototype, 'ignoreBOM', { value: false });
-
- /**
- * @param {!Uint8Array} bytes
- * @return {string}
- */
- function decodeBuffer(bytes) {
- return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('utf-8');
- }
-
- /**
- * @param {!Uint8Array} bytes
- * @return {string}
- */
- function decodeSyncXHR(bytes) {
- const b = new Blob([bytes], { type: 'text/plain;charset=UTF-8' });
- const u = URL.createObjectURL(b);
-
- // This hack will fail in non-Edgium Edge because sync XHRs are disabled (and
- // possibly in other places), so ensure there's a fallback call.
- try {
- const x = new XMLHttpRequest();
- x.open('GET', u, false);
- x.send();
- return x.responseText;
- } catch (e) {
- return decodeFallback(bytes);
- } finally {
- URL.revokeObjectURL(u);
- }
- }
-
- /**
- * @param {!Uint8Array} bytes
- * @return {string}
- */
- function decodeFallback(bytes) {
- let inputIndex = 0;
-
- // Create a working buffer for UTF-16 code points, but don't generate one
- // which is too large for small input sizes. UTF-8 to UCS-16 conversion is
- // going to be at most 1:1, if all code points are ASCII. The other extreme
- // is 4-byte UTF-8, which results in two UCS-16 points, but this is still 50%
- // fewer entries in the output.
- const pendingSize = Math.min(256 * 256, bytes.length + 1);
- const pending = new Uint16Array(pendingSize);
- const chunks = [];
- let pendingIndex = 0;
-
- for (;;) {
- const more = inputIndex < bytes.length;
-
- // If there's no more data or there'd be no room for two UTF-16 values,
- // create a chunk. This isn't done at the end by simply slicing the data
- // into equal sized chunks as we might hit a surrogate pair.
- if (!more || pendingIndex >= pendingSize - 1) {
- // nb. .apply and friends are *really slow*. Low-hanging fruit is to
- // expand this to literally pass pending[0], pending[1], ... etc, but
- // the output code expands pretty fast in this case.
- chunks.push(String.fromCharCode.apply(null, pending.subarray(0, pendingIndex)));
-
- if (!more) {
- return chunks.join('');
- }
-
- // Move the buffer forward and create another chunk.
- bytes = bytes.subarray(inputIndex);
- inputIndex = 0;
- pendingIndex = 0;
- }
-
- // The native TextDecoder will generate "REPLACEMENT CHARACTER" where the
- // input data is invalid. Here, we blindly parse the data even if it's
- // wrong: e.g., if a 3-byte sequence doesn't have two valid continuations.
-
- const byte1 = bytes[inputIndex++];
- if ((byte1 & 0x80) === 0) {
- // 1-byte or null
- pending[pendingIndex++] = byte1;
- } else if ((byte1 & 0xe0) === 0xc0) {
- // 2-byte
- const byte2 = bytes[inputIndex++] & 0x3f;
- pending[pendingIndex++] = ((byte1 & 0x1f) << 6) | byte2;
- } else if ((byte1 & 0xf0) === 0xe0) {
- // 3-byte
- const byte2 = bytes[inputIndex++] & 0x3f;
- const byte3 = bytes[inputIndex++] & 0x3f;
- pending[pendingIndex++] = ((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3;
- } else if ((byte1 & 0xf8) === 0xf0) {
- // 4-byte
- const byte2 = bytes[inputIndex++] & 0x3f;
- const byte3 = bytes[inputIndex++] & 0x3f;
- const byte4 = bytes[inputIndex++] & 0x3f;
-
- // this can be > 0xffff, so possibly generate surrogates
- let codepoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
- if (codepoint > 0xffff) {
- // codepoint &= ~0x10000;
- codepoint -= 0x10000;
- pending[pendingIndex++] = ((codepoint >>> 10) & 0x3ff) | 0xd800;
- codepoint = 0xdc00 | (codepoint & 0x3ff);
- }
- pending[pendingIndex++] = codepoint;
- } else {
- // invalid initial byte
- }
- }
- }
-
- // Decoding a string is pretty slow, but use alternative options where possible.
- let decodeImpl = decodeFallback;
- if (typeof Buffer === 'function' && Buffer.from) {
- // Buffer.from was added in Node v5.10.0 (2015-11-17).
- decodeImpl = decodeBuffer;
- } else if (
- typeof Blob === 'function' &&
- typeof URL === 'function' &&
- typeof URL.createObjectURL === 'function'
- ) {
- // Blob and URL.createObjectURL are available from IE10, Safari 6, Chrome 19
- // (all released in 2012), Firefox 19 (2013), ...
- decodeImpl = decodeSyncXHR;
- }
-
- /**
- * @param {(!ArrayBuffer|!ArrayBufferView)} buffer
- * @param {{stream: boolean}=} options
- * @return {string}
- */
- FastTextDecoder.prototype['decode'] = function (buffer, options = { stream: false }) {
- if (options['stream']) {
- throw new Error(`Failed to decode: the 'stream' option is unsupported.`);
- }
-
- // Accept Uint8Array instances as-is.
- let bytes = buffer;
-
- // Look for ArrayBufferView, which isn't a real type, but basically represents
- // all the valid TypedArray types plus DataView. They all have ".buffer" as
- // an instance of ArrayBuffer.
- if (!(bytes instanceof Uint8Array) && bytes.buffer instanceof ArrayBuffer) {
- bytes = new Uint8Array(buffer.buffer);
- }
-
- return decodeImpl(/** @type {!Uint8Array} */ (bytes));
- };
-
- scope['TextEncoder'] = FastTextEncoder;
- scope['TextDecoder'] = FastTextDecoder;
-})(typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : this);
diff --git a/e2e/autoscript-apps/src/authn-basic-self-service/autoscript.ts b/e2e/autoscript-apps/src/authn-basic-self-service/autoscript.ts
deleted file mode 100644
index 06d97773d..000000000
--- a/e2e/autoscript-apps/src/authn-basic-self-service/autoscript.ts
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { deviceClient } from '@forgerock/device-client';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'https://openam-sdks.forgeblocks.com/am';
- const realmPath = url.searchParams.get('realmPath') || 'alpha';
- const un = url.searchParams.get('un') || 'demo';
- const platformHeader = url.searchParams.get('platformHeader') === 'true' ? true : false;
- const pw = url.searchParams.get('pw') || 'Demo1234!';
- const tree = url.searchParams.get('tree') || 'selfservice';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- middleware: [
- (req, action, next) => {
- switch (action.type) {
- case 'START_AUTHENTICATE':
- if (action.payload.type === 'service' && typeof action.payload.tree === 'string') {
- console.log('Starting authentication with service');
- }
- break;
- case 'AUTHENTICATE':
- if (action.payload.type === 'service' && typeof action.payload.tree === 'string') {
- console.log('Continuing authentication with service');
- }
- break;
- }
- next();
- },
- ],
- platformHeader,
- realmPath,
- tree,
- clientId: 'WebOAuthClient',
- scope: 'profile email me.read openid',
- redirectUri: `${window.location.origin}/src/_callback/index.html`,
- serverConfig: {
- baseUrl: amUrl,
- timeout: 3000,
- },
- });
-
- console.log(`${window.location.origin}/_callback/index.html`);
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- // Wrapping in setTimeout to give the test time to bind listener to console.log
- setTimeout(function () {
- from(forgerock.FRAuth.start())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap(async (step) => {
- try {
- const tokens = await forgerock.TokenManager.getTokens();
- console.log('here', tokens);
- return tokens;
- } catch (err) {
- console.log(err);
- }
- return false;
- }),
- rxDelay(delay),
- mergeMap(async () => {
- const client = deviceClient({
- realmPath,
- tree,
- clientId: 'WebOAuthClient',
- scope: 'profile email me.read openid',
- serverConfig: {
- baseUrl: amUrl,
- timeout: 3000,
- },
- });
-
- try {
- const user = await forgerock.UserManager.getCurrentUser();
-
- //const { result: deviceArr } = await client.oath.get({
- // userId: user.sub,
- // realm: 'alpha',
- //});
- //
- //console.log('retrieveOathDevices', deviceArr);
- //
- //const [{ _id: id, _rev, deviceManagementStatus, ...device }] = deviceArr;
-
- //const oathDeviceDeleted = await client.oath.delete({ userId: user.sub, id, ...device });
-
- //console.log(oathDeviceDeleted);
-
- //const { result: pushDevices } = await client.push.get({
- // userId: user.sub,
- // realm: 'alpha',
- //});
- //
- const bindingDevices = await client.boundDevices.get({
- userId: user.sub,
- realm: 'alpha',
- });
- //console.log('bindingDevices', bindingDevices);
- //
- //const webauthnDevices = await client.webauthn.get({
- // userId: user.sub,
- // realm: 'alpha',
- //});
- //console.log('webauthn devices', webauthnDevices);
- //const {
- // _id: userId,
- // _rev: ignoreThis,
- // deviceManagementStatus: ignoreDeviceManagementStatus,
- // ...rest
- //} = webauthnDevices.result[0];
- //
- //const updatedDevice = await client.webauthn.update({
- // userId: user.sub,
- // realm: 'alpha',
- // ...rest,
- // deviceName: 'RyansDeviceUpdated!!',
- //});
- //console.log('updatedDevice', updatedDevice);
- //
- const bindingDeviceNameUpdated = await client.boundDevices.update({
- userId: user.sub,
- realm: 'alpha',
- ...bindingDevices.result[0],
- deviceName: 'RyanDevice',
- });
-
- console.log('bindingDeviceNameUpdated', bindingDeviceNameUpdated);
-
- const removedDevice = await client.boundDevices.delete({
- realm: 'alpha',
- userId: user.sub,
- ...bindingDeviceNameUpdated,
- });
- //console.log('removeDevice', removedDevice);
- } catch (err) {
- console.log('failed', err);
- }
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
- }, 250);
-}
-autoscript();
-
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-basic-self-service/index.html b/e2e/autoscript-apps/src/authn-basic-self-service/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/authn-basic-self-service/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-basic/UsernamePassword.png b/e2e/autoscript-apps/src/authn-basic/UsernamePassword.png
deleted file mode 100644
index 33e10da37..000000000
Binary files a/e2e/autoscript-apps/src/authn-basic/UsernamePassword.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/authn-basic/autoscript.ts b/e2e/autoscript-apps/src/authn-basic/autoscript.ts
deleted file mode 100644
index dc986031f..000000000
--- a/e2e/autoscript-apps/src/authn-basic/autoscript.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const un = url.searchParams.get('un') || 'sdkuser';
- const platformHeader = url.searchParams.get('platformHeader') === 'true' ? true : false;
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'UsernamePassword';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- middleware: [
- (req, action, next) => {
- switch (action.type) {
- case 'START_AUTHENTICATE':
- if (action.payload.type === 'service' && typeof action.payload.tree === 'string') {
- console.log('Starting authentication with service');
- }
- break;
- case 'AUTHENTICATE':
- if (action.payload.type === 'service' && typeof action.payload.tree === 'string') {
- console.log('Continuing authentication with service');
- }
- break;
- }
- next();
- },
- ],
- platformHeader,
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- // Wrapping in setTimeout to give the test time to bind listener to console.log
- setTimeout(function () {
- from(forgerock.FRAuth.start())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- map(
- (step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Basic login successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Something went wrong.');
- }
- },
- (step) => step,
- ),
- rxDelay(delay),
- mergeMap(() => {
- return forgerock.SessionManager.logout();
- }),
- map((response) => {
- if (response.ok) {
- console.log('Logout successful');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
- }, 250);
-}
-autoscript();
-
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-basic/index.html b/e2e/autoscript-apps/src/authn-basic/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/authn-basic/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-central-login-wellknown/autoscript.ts b/e2e/autoscript-apps/src/authn-central-login-wellknown/autoscript.ts
deleted file mode 100644
index ed26ebbd0..000000000
--- a/e2e/autoscript-apps/src/authn-central-login-wellknown/autoscript.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-async function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const code = url.searchParams.get('code') || '';
- const error = url.searchParams.get('error') || '';
- const state = url.searchParams.get('state') || '';
- // in central login we use an auth query param for the return of our mock 401 request
- // this is to prevent the evaluation of the page before we have technically authenticated
- const auth = url.searchParams.get('auth') || false;
- const acr_values = url.searchParams.get('acr') || 'SpecificTree';
-
- let clientId = url.searchParams.get('clientId') || 'CentralLoginOAuthClient';
- let realmPath = url.searchParams.get('realmPath') || 'root';
- // The `revoke` scope is required for PingOne support
- let scope = url.searchParams.get('scope') || 'openid profile me.read revoke';
- let wellKnownUrl =
- url.searchParams.get('wellKnownUrl') ||
- 'http://localhost:9443/am/.well-known/oidc-configuration';
-
- console.log('Configure the SDK');
-
- if (wellKnownUrl) {
- localStorage.setItem('wellknown', wellKnownUrl);
- localStorage.setItem('clientId', clientId);
- localStorage.setItem('realmPath', realmPath);
- localStorage.setItem('scope', scope);
- } else {
- wellKnownUrl = localStorage.getItem('wellknown');
- clientId = localStorage.getItem('clientId');
- realmPath = localStorage.getItem('realmPath');
- scope = localStorage.getItem('scope');
- }
- await forgerock.Config.setAsync({
- clientId,
- realmPath,
- redirectUri: `${url.origin}/src/authn-central-login-wellknown/`,
- scope,
- serverConfig: {
- wellknown: wellKnownUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
-
- // Wrapping in setTimeout to give the test time to bind listener to console.log
- setTimeout(() => {
- from([1])
- .pipe(
- mergeMap(() => {
- let tokens;
- // detect when in iframe as to not call `/authorize` needlessly
- if (window.self !== window.top) {
- return;
- } else if (code && state) {
- tokens = forgerock.TokenManager.getTokens({
- login: 'redirect',
- query: { code, state },
- });
- } else {
- tokens = forgerock.TokenManager.getTokens({
- login: 'redirect',
- query: { acr_values },
- });
- }
- return tokens;
- }),
- map((tokens) => {
- if (tokens.accessToken) {
- console.log('OAuth authorization successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Session_Error');
- }
- }),
- rxDelay(delay),
- mergeMap(() => {
- console.log('Remove cookie');
- document.cookie = '';
- console.log('Initiate logout');
- // You have to allow specific origins to CORS for OAuth client
- return forgerock.FRUser.logout();
- }),
- )
- .subscribe({
- error: (err) => {
- /*
- * We added this because Playwright was too fast for the dom element.
- * When we make a request to central login we have to force a 401 page to mimick the real life scenario of the page being requested
- * If we do this, we append a query param of auth to make sure we don't complete the flow until we are redirected from that page
- * By saying we have !auth query param value, we are essentially mimicking the idea that we are waiting for the central login redirect
- * to complete the redirect.
- */
- if (!auth) {
- return;
- }
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- localStorage.removeItem('wellknown');
- localStorage.removeItem('clientId');
- localStorage.removeItem('realmPath');
- localStorage.removeItem('scope');
- },
- });
- }, 250);
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-central-login-wellknown/index.html b/e2e/autoscript-apps/src/authn-central-login-wellknown/index.html
deleted file mode 100644
index 77b3e405d..000000000
--- a/e2e/autoscript-apps/src/authn-central-login-wellknown/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-central-login/autoscript.ts b/e2e/autoscript-apps/src/authn-central-login/autoscript.ts
deleted file mode 100644
index 326012fe0..000000000
--- a/e2e/autoscript-apps/src/authn-central-login/autoscript.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const preAuthenticated = url.searchParams.get('preAuthenticated') || 'false';
- const code = url.searchParams.get('code') || '';
- const clientId = url.searchParams.get('clientId');
- const client_id = url.searchParams.get('client_id');
- const error = url.searchParams.get('error_description') || false;
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const scope = url.searchParams.get('scope') || 'openid profile me.read';
- const state = url.searchParams.get('state') || '';
- const acr_values = url.searchParams.get('acr') || 'SpecificTree';
- // in central login we use an auth query param for the return of our mock 401 request
- // this is to prevent the evaluation of the page before we have technically authenticated
- const auth = url.searchParams.get('auth') || false;
-
- let tokenStore = url.searchParams.get('tokenStore') || 'localStorage';
-
- // Support full redirects by setting storage, rather than rely purely on URL
- if (!localStorage.getItem('tokenStore')) {
- localStorage.setItem('tokenStore', tokenStore);
- } else {
- tokenStore = localStorage.getItem('tokenStore');
- }
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- clientId: clientId || client_id || 'CentralLoginOAuthClient',
- realmPath,
- redirectUri: `${url.origin}/src/${
- preAuthenticated === 'false' ? 'authn-central-login' : '_callback'
- }/`,
- scope,
- serverConfig: {
- baseUrl: amUrl,
- },
- tokenStore,
- });
-
- if (!code && !state) {
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
- }
-
- console.log('Initiate first step with `undefined`');
-
- // Wrapping in setTimeout to give the test time to bind listener to console.log
- setTimeout(() => {
- from([1])
- .pipe(
- map(() => {
- if (preAuthenticated === 'true') {
- console.log('Set mock cookie to represent existing session');
- document.cookie = 'iPlanetDirectoryPro=abcd1234; domain=localhost; path=/';
- if (code && state) {
- window.sessionStorage.setItem(
- `FR-SDK-${clientId}`,
- JSON.stringify({ responseType: 'code', state, verifier: '1234' }),
- );
- }
- }
- return;
- }),
- rxDelay(delay),
- mergeMap((step) => {
- let tokens;
- if (error) {
- // Do nothing
- return;
- } else if (code && state) {
- tokens = forgerock.TokenManager.getTokens({
- login: 'redirect',
- query: { code, state, acr_values },
- });
- } else {
- tokens = forgerock.TokenManager.getTokens({
- login: 'redirect',
- query: { acr_values },
- });
- }
- return tokens;
- }),
- map((tokens) => {
- if (tokens.accessToken) {
- console.log('OAuth authorization successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Session_Error');
- }
- }),
- rxDelay(delay),
- mergeMap(() => {
- console.log('Remove cookie');
- document.cookie = '';
- console.log('Initiate logout');
- return forgerock.FRUser.logout();
- }),
- )
- .subscribe({
- error: (err) => {
- /*
- * We added this because Playwright was too fast for the dom element.
- * When we make a request to central login we have to force a 401 page to mimick the real life scenario of the page being requested
- * If we do this, we append a query param of auth to make sure we don't complete the flow until we are redirected from that page
- * By saying we have !auth query param value, we are essentially mimicking the idea that we are waiting for the central login redirect
- * to complete the redirect.
- */
- if (!auth) {
- return;
- }
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- localStorage.clear();
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- history.replaceState(null, null, window.location.origin + window.location.pathname);
- localStorage.clear();
- },
- });
- }, 250);
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-central-login/index.html b/e2e/autoscript-apps/src/authn-central-login/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/authn-central-login/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-central-logout/autoscript.ts b/e2e/autoscript-apps/src/authn-central-logout/autoscript.ts
deleted file mode 100644
index e69a89cd8..000000000
--- a/e2e/autoscript-apps/src/authn-central-logout/autoscript.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import * as forgerock from '@forgerock/javascript-sdk';
-
-/*
- * @forgerock/javascript-sdk
- *
- * index.html
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-async function autoscript() {
- // Show only the view for this handler
- const showStep = (handler) => {
- document.querySelectorAll('#steps > *').forEach((x) => x.classList.remove('active'));
- const panel = document.getElementById(handler);
- if (!panel) {
- console.error(`No panel with ID "${handler}"" found`);
- return false;
- }
- document.getElementById(handler)?.classList.add('active');
- return true;
- };
-
- const showUser = (user) => {
- const query = document.querySelector('#User pre');
- if (query !== null) {
- query.innerHTML = JSON.stringify(user, null, 2);
- }
-
- const panel = document.querySelector('#User');
- if (panel) {
- const panelBtn = panel.querySelector('.btn');
- if (panelBtn !== null) {
- panelBtn.addEventListener('click', () => {
- logout();
- });
- }
- }
- showStep('User');
- };
-
- const logout = async () => {
- try {
- await forgerock.FRUser.logout({
- logoutRedirectUri: `${window.location.origin}${window.location.pathname}`,
- });
- } catch (error) {
- console.error(error);
- }
- };
-
- const authorize = async (code, state) => {
- /**
- * When the user return to this app after successfully logging in,
- * the URL will include code and state query parameters that need to
- * be passed in to complete the OAuth flow giving the user access
- */
- await forgerock.TokenManager.getTokens({ query: { code, state } });
- const user = await forgerock.UserManager.getCurrentUser();
- showUser(user);
- };
-
- document.getElementById('loginBtn')?.addEventListener('click', async () => {
- /**
- * The key-value of `login: redirect` is what allows central-login.
- * Passing no arguments or a key-value of `login: 'embedded'` means
- * the app handles authentication locally.
- */
- await forgerock.TokenManager.getTokens({ login: 'redirect' });
- const user = await forgerock.UserManager.getCurrentUser();
- showUser(user);
- });
-
- document.getElementById('forceRenewBtn')?.addEventListener('click', async () => {
- await forgerock.TokenManager.getTokens({ login: 'redirect', forceRenew: true });
- const user = await forgerock.UserManager.getCurrentUser();
- showUser(user);
- });
- await forgerock.Config.setAsync({
- clientId: '724ec718-c41c-4d51-98b0-84a583f450f9', // e.g. 'ForgeRockSDKClient'
- redirectUri: `${window.location.origin}${window.location.pathname}`, // Redirect back to your app, e.g. 'https://sdkapp.example.com:8443'
- scope: 'openid profile email name revoke', // e.g. 'openid profile email address phone me.read'
- serverConfig: {
- wellknown:
- 'https://auth.pingone.ca/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/.well-known/openid-configuration',
- },
- realmPath: '', // e.g. 'alpha' or 'root'
- });
-
- /**
- * Check URL for query parameters
- */
- const url = new URL(document.location.href);
- const params = url.searchParams;
- const authCode = params.get('code');
- const state = params.get('state');
-
- /**
- * If the URL has state and authCode as query parameters, then the user
- * returned back here after successfully logging, so call authorize with
- * the values
- */
- if (state && authCode) {
- authorize(authCode, state);
- }
-}
-autoscript();
diff --git a/e2e/autoscript-apps/src/authn-central-logout/callback.html b/e2e/autoscript-apps/src/authn-central-logout/callback.html
deleted file mode 100644
index 87c88b9b0..000000000
--- a/e2e/autoscript-apps/src/authn-central-logout/callback.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-
-
-
- Document
-
-
- Callback
-
-
diff --git a/e2e/autoscript-apps/src/authn-central-logout/index.html b/e2e/autoscript-apps/src/authn-central-logout/index.html
deleted file mode 100644
index 45f767ba1..000000000
--- a/e2e/autoscript-apps/src/authn-central-logout/index.html
+++ /dev/null
@@ -1,37 +0,0 @@
-
-
-
-
- Custom UI | ForgeRock JavaScript SDK Samples
-
-
-
-
-
-
-
-
- Login
- Force Renew
-
-
-
-
Your user information:
-
-
-
Sign Out
-
-
-
-
Something unexpected happened. Check the console for details.
-
Start over
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-device-profile/autoscript.ts b/e2e/autoscript-apps/src/authn-device-profile/autoscript.ts
deleted file mode 100644
index e53b33506..000000000
--- a/e2e/autoscript-apps/src/authn-device-profile/autoscript.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'DeviceProfileCallbackTest';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap(
- (step) => {
- const deviceCollectorCb = step.getCallbackOfType('DeviceProfileCallback');
-
- const message = deviceCollectorCb.getMessage();
- console.log(message);
- document.body.innerHTML = `${message}
`;
- const isLocationRequired = deviceCollectorCb.isLocationRequired();
- const isMetadataRequired = deviceCollectorCb.isMetadataRequired();
-
- const device = new forgerock.FRDevice();
- return device.getProfile({
- location: isLocationRequired,
- metadata: isMetadataRequired,
- });
- },
- (step, profile) => {
- console.log(profile);
- return { step, profile };
- },
- ),
- rxDelay(delay),
- mergeMap(
- ({ step, profile }) => {
- console.log('Profile collected.');
- step.getCallbackOfType('DeviceProfileCallback').setProfile(profile);
- return forgerock.FRAuth.next(step);
- },
- (step, response) => {
- if (response.type === 'LoginFailure') {
- throw new Error('No profile match.');
- } else {
- console.log('Login with profile successful.');
- document.body.innerHTML = 'Login successful
';
- return step;
- }
- },
- ),
- rxDelay(delay),
- mergeMap((step) => {
- return forgerock.SessionManager.logout();
- }),
- map((response) => {
- if (response.ok) {
- console.log('Logout successful');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- }),
- rxDelay(delay),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-device-profile/index.html b/e2e/autoscript-apps/src/authn-device-profile/index.html
deleted file mode 100644
index d88ae69ce..000000000
--- a/e2e/autoscript-apps/src/authn-device-profile/index.html
+++ /dev/null
@@ -1,51 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-email-suspend/LoginWithEmail.png b/e2e/autoscript-apps/src/authn-email-suspend/LoginWithEmail.png
deleted file mode 100644
index 10ba34067..000000000
Binary files a/e2e/autoscript-apps/src/authn-email-suspend/LoginWithEmail.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/authn-email-suspend/autoscript.ts b/e2e/autoscript-apps/src/authn-email-suspend/autoscript.ts
deleted file mode 100644
index 32166284c..000000000
--- a/e2e/autoscript-apps/src/authn-email-suspend/autoscript.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
-
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const tree = url.searchParams.get('tree') || 'LoginWithEmail';
- const un = url.searchParams.get('un') || 'sdkuser';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- // Wrapping in setTimeout to give the test time to bind listener to console.log
- setTimeout(function () {
- from(forgerock.FRAuth.next())
- .pipe(
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Set values on Platform Username callback');
- step.getCallbackOfType('ValidatedCreateUsernameCallback').setName(un);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- map((step) => {
- console.log('Get message from SuspendedTextOutputCallback callback');
- const msg = step.getCallbackOfType('SuspendedTextOutputCallback').getMessage();
- console.log(msg);
- if (msg.length) {
- return null;
- } else {
- throw new Error('SuspendedTextOutputCallback did not return message');
- }
- }),
- rxDelay(delay),
- mergeMap(() => {
- console.log('Collect Suspended ID');
- // Tester can add a predefined/mock suspendedId to the URL
- // Or, tester can add a real suspendedId from AM using the prompt element
- if (window.location.href.includes('suspendedId')) {
- return forgerock.FRAuth.resume(window.location.href, {
- realmPath: realmPath,
- });
- } else {
- const id = window.prompt('What is your suspended ID?');
- return forgerock.FRAuth.next(null, {
- query: {
- suspendedId: id,
- },
- realmPath: realmPath,
- });
- }
- }),
- rxDelay(delay),
- map(
- (step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Login with email successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Something went wrong.');
- }
- },
- (step) => step,
- ),
- rxDelay(delay),
- mergeMap((step) => {
- return forgerock.SessionManager.logout();
- }),
- map((response) => {
- if (response.ok) {
- console.log('Logout successful');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
- }, 250);
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-email-suspend/index.html b/e2e/autoscript-apps/src/authn-email-suspend/index.html
deleted file mode 100644
index e5783c98f..000000000
--- a/e2e/autoscript-apps/src/authn-email-suspend/index.html
+++ /dev/null
@@ -1,15 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-no-session/UsernamePassword.png b/e2e/autoscript-apps/src/authn-no-session/UsernamePassword.png
deleted file mode 100644
index 33e10da37..000000000
Binary files a/e2e/autoscript-apps/src/authn-no-session/UsernamePassword.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/authn-no-session/autoscript.ts b/e2e/autoscript-apps/src/authn-no-session/autoscript.ts
deleted file mode 100644
index cbeadaa8d..000000000
--- a/e2e/autoscript-apps/src/authn-no-session/autoscript.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'UsernamePassword';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- middleware: [
- (req, action, next) => {
- switch (action.type) {
- case 'START_AUTHENTICATE':
- case 'AUTHENTICATE':
- console.log('Adding "noSession" query param to URL');
- req.url.searchParams.append('noSession', 'true');
- }
- next();
- },
- ],
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- // Wrapping in setTimeout to give the test time to bind listener to console.log
- setTimeout(function () {
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- map((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.ok) {
- console.log('Basic login with "noSession" completed successfully');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Something went wrong.');
- }
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
- }, 250);
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-no-session/index.html b/e2e/autoscript-apps/src/authn-no-session/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/authn-no-session/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-oauth/UsernamePassword.png b/e2e/autoscript-apps/src/authn-oauth/UsernamePassword.png
deleted file mode 100644
index 33e10da37..000000000
Binary files a/e2e/autoscript-apps/src/authn-oauth/UsernamePassword.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/authn-oauth/autoscript.ts b/e2e/autoscript-apps/src/authn-oauth/autoscript.ts
deleted file mode 100644
index 7f51c1d5e..000000000
--- a/e2e/autoscript-apps/src/authn-oauth/autoscript.ts
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
- const tokenExpiredDelay = 2000;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const clientId = url.searchParams.get('clientId') || 'WebOAuthClient';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const scope = url.searchParams.get('scope') || 'openid profile me.read';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'UsernamePassword';
- const oauthThreshold = url.searchParams.get('oauthThreshold');
- const resourceOrigin = url.searchParams.get('resourceOrigin') || 'http://localhost:9443/resource';
- const igUrl = url.searchParams.get('igUrl'); // only use when testing against IG on different host
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- clientId,
- middleware: [
- (req, action, next) => {
- switch (action.type) {
- case 'AUTHORIZE':
- console.log('Calling authorize endpoint');
- break;
- case 'EXCHANGE_TOKEN':
- console.log('Calling access token exchange endpoint');
- break;
- }
- next();
- },
- ],
- redirectUri: `${url.origin}/_callback/`,
- realmPath,
- scope,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- oauthThreshold: oauthThreshold,
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- }
- console.log('Auth tree successfully completed');
- console.log('Get OAuth tokens');
- const tokens = forgerock.TokenManager.getTokens();
- return tokens;
- }),
- rxDelay(delay),
- map((tokens) => {
- if (tokens.accessToken) {
- console.log('OAuth login successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Session_Error');
- }
- return tokens;
- }),
- rxDelay(delay),
- mergeMap(
- (tokens) => {
- console.log('Get user info from OAuth endpoint');
- const user = forgerock.UserManager.getCurrentUser();
- return user;
- },
- (tokens, user) => {
- console.log(`User's given name: ${user.family_name}`);
- return tokens;
- },
- ),
- rxDelay(delay),
- mergeMap(
- (tokens) => {
- console.log('Force renew OAuth tokens');
- return forgerock.TokenManager.getTokens({ forceRenew: true });
- },
- (oldTokens, newTokens) => {
- if (oldTokens.accessToken !== newTokens.accessToken) {
- console.log('New OAuth tokens retrieved');
- } else {
- throw new Error('Force_Renew_Error');
- }
- return newTokens;
- },
- ),
- rxDelay(delay),
- mergeMap(() => {
- console.log('Initiate logout');
- return forgerock.FRUser.logout();
- }),
- rxDelay(delay),
- mergeMap(
- (step) => {
- return forgerock.TokenStorage.get();
- },
- (step, tokens) => {
- if (!tokens) {
- console.log('Logout successful');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- return step;
- },
- ),
- rxDelay(delay),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-oauth/index.html b/e2e/autoscript-apps/src/authn-oauth/index.html
deleted file mode 100644
index c371c9150..000000000
--- a/e2e/autoscript-apps/src/authn-oauth/index.html
+++ /dev/null
@@ -1,35 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-otp-reg/autoscript.ts b/e2e/autoscript-apps/src/authn-otp-reg/autoscript.ts
deleted file mode 100644
index 080069579..000000000
--- a/e2e/autoscript-apps/src/authn-otp-reg/autoscript.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'QRCodeTest';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- // Wrapping in setTimeout to give the test time to bind listener to console.log
- setTimeout(function () {
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks for submission');
- const unCb = step.getCallbackOfType('NameCallback');
- unCb.setName(un);
-
- const pwCb = step.getCallbackOfType('PasswordCallback');
- pwCb.setPassword(pw);
-
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Register MFA with QR Code');
- const isQRCodeStep = forgerock.FRQRCode.isQRCodeStep(step);
- if (!isQRCodeStep) {
- throw new Error('Did not get expected QR Code step');
- }
-
- const { message, use, uri } = forgerock.FRQRCode.getQRCodeData(step);
- if (!message && !use && !uri) {
- throw new Error('Was unable to retreive message, use or URI from step');
- }
-
- console.log(message);
- console.log(use);
- console.log(uri);
-
- return forgerock.FRAuth.next(step);
- }),
- map(
- (step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Basic login with OTP registration step successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Something went wrong.');
- }
- },
- (step) => step,
- ),
- rxDelay(delay),
- mergeMap((step) => {
- return forgerock.SessionManager.logout();
- }),
- map((response) => {
- if (response.ok) {
- console.log('Logout successful');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
- }, 250);
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-otp-reg/index.html b/e2e/autoscript-apps/src/authn-otp-reg/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/authn-otp-reg/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-platform/PlatformUsernamePassword.png b/e2e/autoscript-apps/src/authn-platform/PlatformUsernamePassword.png
deleted file mode 100644
index cfdcc69dc..000000000
Binary files a/e2e/autoscript-apps/src/authn-platform/PlatformUsernamePassword.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/authn-platform/autoscript.ts b/e2e/autoscript-apps/src/authn-platform/autoscript.ts
deleted file mode 100644
index 242e8f221..000000000
--- a/e2e/autoscript-apps/src/authn-platform/autoscript.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'PlatformUsernamePasswordTest';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- // Wrapping in setTimeout to give the test time to bind listener to console.log
- setTimeout(function () {
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks for validation only');
- const unCb = step.getCallbackOfType('ValidatedCreateUsernameCallback');
- // In order to pass validation (with existing username in AM),
- // the valid-username policy needs to be removed from the IDM managed user object
- unCb.setName(un);
- unCb.setValidateOnly(true);
-
- const pwCb = step.getCallbackOfType('ValidatedCreatePasswordCallback');
- pwCb.setPassword(pw);
- pwCb.setValidateOnly(true);
-
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks for submission');
- const unCb = step.getCallbackOfType('ValidatedCreateUsernameCallback');
- unCb.setName(un);
- unCb.setValidateOnly(false);
-
- const pwCb = step.getCallbackOfType('ValidatedCreatePasswordCallback');
- pwCb.setPassword(pw);
- pwCb.setValidateOnly(false);
-
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- map(
- (step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Basic login with platform nodes successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Something went wrong.');
- }
- },
- (step) => step,
- ),
- rxDelay(delay),
- mergeMap((step) => {
- return forgerock.SessionManager.logout();
- }),
- map((response) => {
- if (response.ok) {
- console.log('Logout successful');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
- }, 250);
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-platform/index.html b/e2e/autoscript-apps/src/authn-platform/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/authn-platform/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-protect-metadata/autoscript.ts b/e2e/autoscript-apps/src/authn-protect-metadata/autoscript.ts
deleted file mode 100644
index 50cbe1b7d..000000000
--- a/e2e/autoscript-apps/src/authn-protect-metadata/autoscript.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2024 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { PIProtect } from '@forgerock/ping-protect';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const pauseBehaviorData = url.searchParams.get('pauseBehaviorData') || 'true';
- const tree = url.searchParams.get('tree') || 'TEST_MetadataMarketPlace';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- // Wrapping in setTimeout to give the test time to bind listener to console.log
- setTimeout(function () {
- from(forgerock.FRAuth.start())
- .pipe(
- mergeMap(
- (step) => {
- try {
- const config = PIProtect.getNodeConfig(step);
-
- console.log('start protect');
- return PIProtect.start(config);
- } catch (err) {
- const cb = (step as forgerock.Step).getCallbackOfType(
- 'MetadataCallback',
- ) as forgerock.MetadataCallback;
- PIProtect.setNodeClientError('Error!');
- }
- },
- (step) => {
- return step;
- },
- ),
- mergeMap((step) => {
- console.log('Submitting ping protect start');
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
-
- mergeMap(async (step) => {
- try {
- const data = await PIProtect.getData();
-
- PIProtect.setNodeInputValue(step, data);
- console.log('Submitting ping protect evaluation');
- return forgerock.FRAuth.next(step);
- } catch (err) {
- return err;
- }
- }),
- map((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Basic login with Protect successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Something went wrong.');
- }
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
- }, 250);
-}
-autoscript();
-
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-protect-metadata/index.html b/e2e/autoscript-apps/src/authn-protect-metadata/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/authn-protect-metadata/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-protect/autoscript.ts b/e2e/autoscript-apps/src/authn-protect/autoscript.ts
deleted file mode 100644
index 8dfbfc497..000000000
--- a/e2e/autoscript-apps/src/authn-protect/autoscript.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2024 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { PIProtect } from '@forgerock/ping-protect';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const pauseBehaviorData = url.searchParams.get('pauseBehaviorData') || 'true';
- const tree = url.searchParams.get('tree') || 'TEST_LoginPingProtect';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- // Wrapping in setTimeout to give the test time to bind listener to console.log
- setTimeout(function () {
- from(forgerock.FRAuth.start())
- .pipe(
- mergeMap(
- (step) => {
- if (step.getCallbacksOfType('PingOneProtectInitializeCallback')) {
- const cb = step.getCallbackOfType('PingOneProtectInitializeCallback');
- const config = cb.getConfig();
-
- console.log(JSON.stringify(config));
-
- try {
- return PIProtect.start(config);
- } catch (err) {
- cb.setClientError(err.message);
- }
- }
- },
- (step) => {
- return step;
- },
- ),
- mergeMap((step) => {
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
-
- return forgerock.FRAuth.next(step);
- }),
- mergeMap(
- (step) => {
- if (step.getCallbacksOfType('PingOneProtectEvaluationCallback')) {
- const cb = step.getCallbackOfType('PingOneProtectEvaluationCallback');
-
- try {
- // Asynchronous call
- return PIProtect.getData();
- } catch (err) {
- return err;
- }
- }
- },
- (step, data) => {
- return { step, data };
- },
- ),
- mergeMap(({ step, data }) => {
- const cb = step.getCallbackOfType('PingOneProtectEvaluationCallback');
- let pauseFlag = pauseBehaviorData === 'true' ? true : false;
- let shouldPause = false;
-
- if (pauseFlag) {
- shouldPause = cb.getPauseBehavioralData();
- }
-
- console.log(`getPauseBehavioralData: ${shouldPause}`);
-
- if (shouldPause) {
- PIProtect.pauseBehavioralData();
- }
-
- if (typeof data === 'string') {
- cb.setData(data);
- } else {
- cb.setClientError(data.message);
- }
-
- return forgerock.FRAuth.next(step);
- }),
- map((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Basic login with Protect successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Something went wrong.');
- }
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
- }, 250);
-}
-autoscript();
-
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-protect/index.html b/e2e/autoscript-apps/src/authn-protect/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/authn-protect/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-recaptcha-enterprise/autoscript.ts b/e2e/autoscript-apps/src/authn-recaptcha-enterprise/autoscript.ts
deleted file mode 100644
index 61f8b6e61..000000000
--- a/e2e/autoscript-apps/src/authn-recaptcha-enterprise/autoscript.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const tree = url.searchParams.get('tree') || 'RecaptchaEnterprise'; // the specific tree for the mock api
-
- console.log('here we are');
- forgerock.Config.set({
- realmPath,
- clientId: 'WebAuth',
- serverConfig: {
- baseUrl: amUrl,
- timeout: 5000,
- },
- tree,
- });
-
- return setTimeout(function () {
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Get username password page node');
- const unCb = step.getCallbackOfType(forgerock.CallbackType.NameCallback);
- const pwCb = step.getCallbackOfType(forgerock.CallbackType.PasswordCallback);
- // In order to pass validation (with existing username in AM),
- // the valid-username policy needs to be removed from the IDM managed user object
- unCb.setName('demo');
-
- pwCb.setPassword('Password');
- //pwCb.setValidateOnly(true);
-
- console.log('submitting username step', step);
- return forgerock.FRAuth.next(step);
- }),
- mergeMap((step) => {
- console.log('we are in recaptcha step', step);
-
- const recaptchaCb = step.getCallbackOfType(
- forgerock.CallbackType.ReCaptchaEnterpriseCallback,
- ) as forgerock.ReCaptchaEnterpriseCallback;
-
- recaptchaCb.setResult('123');
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(1000),
- map(
- (step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Basic login with platform nodes successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Something went wrong.');
- }
- },
- (step) => step,
- ),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test Script Complete
`;
- },
- });
- });
-}
-
-autoscript();
diff --git a/e2e/autoscript-apps/src/authn-recaptcha-enterprise/index.html b/e2e/autoscript-apps/src/authn-recaptcha-enterprise/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/authn-recaptcha-enterprise/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-saml/autoscript.ts b/e2e/autoscript-apps/src/authn-saml/autoscript.ts
deleted file mode 100644
index d4cab3dc7..000000000
--- a/e2e/autoscript-apps/src/authn-saml/autoscript.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am/';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const tree = url.searchParams.get('tree') || 'SAMLTest'; // the specific tree for the mock api
- const responsekey = url.searchParams.get('responsekey') || '';
- const error = url.searchParams.get('error');
- const errorMessage = url.searchParams.get('errorMessage');
- const errorCode = url.searchParams.get('errorCode') ?? false;
-
- forgerock.Config.set({
- realmPath,
- serverConfig: {
- baseUrl: amUrl,
- timeout: 5000,
- },
- tree,
- });
-
- console.log('Initiate first step with `undefined`');
- // Wrapping in setTimeout to give the test time to bind listener to console.log
- setTimeout(function () {
- if (responsekey || error) {
- from(forgerock.FRAuth.resume(window.location.href))
- .pipe(
- map((step) => {
- console.log('resumed');
- if (error) {
- console.log(errorCode);
- console.log(errorMessage);
- document.body.innerHTML = 'Login Error!
';
- } else if (step.payload.ok) {
- console.log('SAML Login successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Something went wrong.');
- }
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
- } else {
- console.log('Configure the SDK');
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('init step');
- const nameCallback = step.getCallbackOfType('NameCallback');
- nameCallback.setName('samltest');
-
- return forgerock.FRAuth.next(step);
- }),
- map((step) => {
- if (!(step as any).getCallbackOfType('RedirectCallback')) {
- throw new Error('Expected callback of RedirectCallback not received');
- }
- console.log('redirecting...');
- forgerock.FRAuth.redirect(step as any);
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Redirection starting ...
`;
- },
- });
- }
- }, 250);
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-saml/index.html b/e2e/autoscript-apps/src/authn-saml/index.html
deleted file mode 100644
index c371c9150..000000000
--- a/e2e/autoscript-apps/src/authn-saml/index.html
+++ /dev/null
@@ -1,35 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-second-factor/autoscript.ts b/e2e/autoscript-apps/src/authn-second-factor/autoscript.ts
deleted file mode 100644
index 7f6c2c281..000000000
--- a/e2e/autoscript-apps/src/authn-second-factor/autoscript.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
-
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'SecondFactor';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- console.log('Initiate first step with `undefined`');
- // Wrapping in setTimeout to give the test time to bind listener to console.log
- setTimeout(function () {
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- // Second factor authentication...
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Handle ChoiceCallback');
- const cb = step.getCallbackOfType('ChoiceCallback');
-
- console.log(`Set index ${cb.getDefaultChoice()} for "email"`);
-
- cb.setChoiceIndex(0);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- const otp = window.prompt('What is your OTP?');
- console.log('Set given OTP to password callback');
- step.getCallbackOfType('PasswordCallback').setPassword(otp);
-
- return forgerock.FRAuth.next(step);
- }),
- map(
- (step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Second Factor login successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Something went wrong.');
- }
- },
- (step) => step,
- ),
- rxDelay(delay),
- mergeMap((step) => {
- return forgerock.SessionManager.logout();
- }),
- map((response) => {
- if (response.ok) {
- console.log('Logout successful');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
- }, 250);
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-second-factor/index.html b/e2e/autoscript-apps/src/authn-second-factor/index.html
deleted file mode 100644
index e642e9e3b..000000000
--- a/e2e/autoscript-apps/src/authn-second-factor/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-social-login-am/AMSocialLogin.png b/e2e/autoscript-apps/src/authn-social-login-am/AMSocialLogin.png
deleted file mode 100644
index c9b3d7d39..000000000
Binary files a/e2e/autoscript-apps/src/authn-social-login-am/AMSocialLogin.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/authn-social-login-am/autoscript.ts b/e2e/autoscript-apps/src/authn-social-login-am/autoscript.ts
deleted file mode 100644
index 702b9d456..000000000
--- a/e2e/autoscript-apps/src/authn-social-login-am/autoscript.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-social-login-idm
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost9443/am/';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const tree = url.searchParams.get('tree') || 'AMSocialLogin';
- const provider = url.searchParams.get('provider') || 'google';
- const code = url.searchParams.get('code');
- const state = url.searchParams.get('state');
-
- console.log('Initiate first step with `undefined`');
- // Wrapping in setTimeout to give the test time to bind listener to console.log
- setTimeout(function () {
- if (code && state) {
- // Below three lines are needed for automation only
- const returnParamsString = window.localStorage.getItem('returnParams');
- window.localStorage.removeItem('returnParams');
- const { amUrl, realmPath, tree } = JSON.parse(returnParamsString as string);
-
- forgerock.Config.set({
- realmPath,
- serverConfig: {
- baseUrl: amUrl,
- timeout: 5000,
- },
- tree,
- });
-
- console.log('Returning from provider');
-
- from(forgerock.FRAuth.resume(window.location.href))
- .pipe(
- map((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Social Login successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Something went wrong.');
- }
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
- } else {
- console.log('Configure the SDK');
- forgerock.Config.set({
- realmPath,
- serverConfig: {
- baseUrl: amUrl,
- timeout: 5000,
- },
- tree,
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set provider on SelectIdPCallback');
- (step as any).getCallbackOfType('ChoiceCallback' as any).setChoiceValue(provider);
- return forgerock.FRAuth.next(step as any);
- }),
- rxDelay(delay),
- map((step) => {
- if (!(step as any).getCallbackOfType('RedirectCallback')) {
- throw new Error('Expected callback of RedirectCallback not received');
- }
-
- // The returnParams are needed for just this test automation
- const returnParams = {
- amUrl,
- provider,
- realmPath,
- tree,
- };
- window.localStorage.setItem('returnParams', JSON.stringify(returnParams));
-
- console.log('Redirect to ID Provider');
- forgerock.FRAuth.redirect(step as any);
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Redirection starting ...
`;
- },
- });
- }
- }, 250);
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-social-login-am/index.html b/e2e/autoscript-apps/src/authn-social-login-am/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/authn-social-login-am/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-social-login-idm/IDMSocialLogin.png b/e2e/autoscript-apps/src/authn-social-login-idm/IDMSocialLogin.png
deleted file mode 100644
index c812249fd..000000000
Binary files a/e2e/autoscript-apps/src/authn-social-login-idm/IDMSocialLogin.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/authn-social-login-idm/autoscript.ts b/e2e/autoscript-apps/src/authn-social-login-idm/autoscript.ts
deleted file mode 100644
index 7ac2b5bd9..000000000
--- a/e2e/autoscript-apps/src/authn-social-login-idm/autoscript.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-social-login-am
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am/';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const tree = url.searchParams.get('tree') || 'IDMSocialLogin';
- const provider = url.searchParams.get('provider') || 'google';
- const code = url.searchParams.get('code');
- const state = url.searchParams.get('state');
- const form_post_entry = url.searchParams.get('form_post_entry');
-
- console.log('Initiate first step with `undefined`');
- // Wrapping in setTimeout to give the test time to bind listener to console.log
- setTimeout(function () {
- if ((code && state) || form_post_entry) {
- // Below three lines are needed for automation only
- const returnParamsString = window.localStorage.getItem('returnParams');
- window.localStorage.removeItem('returnParams');
- const { amUrl, realmPath, tree } = JSON.parse(returnParamsString as any);
-
- forgerock.Config.set({
- realmPath,
- serverConfig: {
- baseUrl: amUrl,
- timeout: 5000,
- },
- tree,
- });
-
- console.log('Returning from provider');
-
- from(forgerock.FRAuth.resume(window.location.href))
- .pipe(
- map((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Social Login successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Something went wrong.');
- }
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
- } else {
- console.log('Configure the SDK');
- forgerock.Config.set({
- realmPath,
- serverConfig: {
- baseUrl: amUrl,
- timeout: 5000,
- },
- tree,
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set provider on SelectIdPCallback');
- // TODO: setup callback handler for UI config properties
- (step as any).getCallbackOfType('SelectIdPCallback').setProvider(provider);
- return forgerock.FRAuth.next(step as any);
- }),
- rxDelay(delay),
- map((step) => {
- if (!(step as any).getCallbackOfType('RedirectCallback')) {
- throw new Error('Expected callback of RedirectCallback not received');
- }
-
- // The returnParams are needed for just this test automation
- const returnParams = {
- amUrl,
- provider,
- realmPath,
- tree,
- };
- window.localStorage.setItem('returnParams', JSON.stringify(returnParams));
-
- console.log('Redirect to ID Provider');
- forgerock.FRAuth.redirect(step as any);
- }),
- rxDelay(delay),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Redirection starting ...
`;
- },
- });
- }
- }, 250);
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-social-login-idm/index.html b/e2e/autoscript-apps/src/authn-social-login-idm/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/authn-social-login-idm/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-webauthn-device-registration/autoscript.ts b/e2e/autoscript-apps/src/authn-webauthn-device-registration/autoscript.ts
deleted file mode 100644
index 63d513982..000000000
--- a/e2e/autoscript-apps/src/authn-webauthn-device-registration/autoscript.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { fromEvent } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'PasswordlessWebAuthn';
- console.log('Configure the SDK');
- forgerock.Config.set({
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
- /***
- * Test Device Registration (Not Automated)
- * must create cert because you cannot have a TLS error with webauthn to test manually
- */
- /***
- * Test Device Registration (Not Automated)
- * must create cert because you cannot have a TLS error with webauthn to test manually
- */
- console.log('Click the device registration button!');
- const deviceRegistration = document.querySelector('.device-registration');
- fromEvent(deviceRegistration, 'click')
- .pipe(
- mergeMap(() => {
- console.log('Initiate first step with `undefined`');
- return forgerock.FRAuth.next();
- }),
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Set username on auth tree callback');
- console.log(step);
- step.getCallbackOfType('NameCallback').setName(un);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Set password on auth tree callback');
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- mergeMap(async (step) => {
- const webAuthnStep = forgerock.FRWebAuthn.getWebAuthnStepType(step);
- if (webAuthnStep === 2) {
- console.log('WebAuthn step is registration');
- } else {
- throw new Error('WebAuthn step is incorrectly identified');
- }
- console.log('Handle WebAuthn Registration');
- try {
- step = await forgerock.FRWebAuthn.register<'mydevice'>(step, 'mydevice');
- // ensure the step here has the 'mydevice' name at the end of the value. (outcome)
- const deviceValue = step.getCallbacksOfType('HiddenValueCallback')[0].getInputValue();
- if (!deviceValue.includes('mydevice')) {
- throw new Error('Device name is not correct');
- }
- } catch (err) {
- console.log(err);
- }
- return forgerock.FRAuth.next(step);
- }),
- map((step) => {
- console.log('step', step);
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Basic login successful.');
- document.body.innerHTML = 'Login successful
';
- return step;
- } else {
- throw new Error('Something went wrong.');
- }
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-webauthn-device-registration/index.html b/e2e/autoscript-apps/src/authn-webauthn-device-registration/index.html
deleted file mode 100644
index 22ac8fd6b..000000000
--- a/e2e/autoscript-apps/src/authn-webauthn-device-registration/index.html
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
- Device Registration
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-webauthn/autoscript.ts b/e2e/autoscript-apps/src/authn-webauthn/autoscript.ts
deleted file mode 100644
index 6a6a98306..000000000
--- a/e2e/autoscript-apps/src/authn-webauthn/autoscript.ts
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { fromEvent } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'PasswordlessWebAuthn';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- // Needed for testing WebAuthn on Safari due to user event needed
- console.log('Click the login button!');
- const loginBtn = document.querySelector('.login-btn');
- fromEvent(loginBtn, 'click')
- .pipe(
- mergeMap(() => {
- console.log('Initiate first step with `undefined`');
- return forgerock.FRAuth.next();
- }),
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Set username on auth tree callback');
- step.getCallbackOfType('NameCallback').setName(un);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Set password on auth tree callback');
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Choose Passwordless login');
- const cb = step.getCallbackOfType('ChoiceCallback');
- cb.setChoiceIndex(0);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap(
- async (step) => {
- const webAuthnStep = forgerock.FRWebAuthn.getWebAuthnStepType(step);
- if (webAuthnStep === 2) {
- console.log('WebAuthn step is registration');
- } else {
- throw new Error('WebAuthn step is incorrectly identified');
- }
- console.log('Handle WebAuthn Registration');
- try {
- step = await forgerock.FRWebAuthn.register(step);
- } catch (err) {
- console.log(err);
- }
- return step;
- },
- (step) => step,
- ),
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Send WebAuthn Credentials');
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Check for Display Recovery Codes step');
- const isDisplayStep = forgerock.FRRecoveryCodes.isDisplayStep(step);
- const recoveryCodes = forgerock.FRRecoveryCodes.getCodes(step);
- console.log(isDisplayStep ? 'Display recovery codes' : 'Missing recovery codes');
- console.log(recoveryCodes.length === 10 ? 'Parsed all codes' : 'Unable to parse all codes');
- return forgerock.FRAuth.next(step);
- }),
- map((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Basic login successful.');
- document.body.innerHTML = 'Login successful
';
- return step;
- } else {
- throw new Error('Something went wrong.');
- }
- }),
- rxDelay(delay),
- mergeMap((step) => {
- return forgerock.SessionManager.logout();
- }),
- map((response) => {
- if (response.ok) {
- console.log('Logout successful.');
- document.body.innerHTML =
- 'Logout successful
' +
- 'Continue ';
- } else {
- throw new Error('Logout_Error');
- }
- }),
- rxDelay(delay),
- mergeMap(() => {
- // Needed for testing WebAuthn on Safari due to user event needed
- console.log('Click the continue button!');
- const continueBtn = document.querySelector('.continue-btn');
- return rxjs.fromEvent(continueBtn, 'click');
- }),
- mergeMap(() => {
- console.log('Log back in with WebAuthn');
- return forgerock.FRAuth.next();
- }),
- rxDelay(delay),
- mergeMap((step) => {
- step.getCallbackOfType('NameCallback').setName(un);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap(
- async (step) => {
- const webAuthnStep = forgerock.FRWebAuthn.getWebAuthnStepType(step);
- if (webAuthnStep === 1) {
- console.log('WebAuthn step is authentication');
- } else {
- throw new Error('WebAuthn step is incorrectly identified');
- }
- console.log('Handle WebAuthn Authenticate');
- try {
- step = await forgerock.FRWebAuthn.authenticate(step);
- } catch (err) {
- console.log(err);
- }
- return step;
- },
- (step) => {
- return step;
- },
- ),
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Send WebAuthn Credentials');
- return forgerock.FRAuth.next(step);
- }),
- map((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Basic login successful.');
- document.body.innerHTML = 'Login successful
';
- return step;
- } else {
- throw new Error('Something went wrong.');
- }
- }),
- rxDelay(delay),
- mergeMap((step) => {
- return forgerock.SessionManager.logout();
- }),
- map((response) => {
- if (response.ok) {
- console.log('Logout successful.');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-webauthn/index.html b/e2e/autoscript-apps/src/authn-webauthn/index.html
deleted file mode 100644
index adbdc3b2e..000000000
--- a/e2e/autoscript-apps/src/authn-webauthn/index.html
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
- Login
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authn-wellknown/UsernamePassword.png b/e2e/autoscript-apps/src/authn-wellknown/UsernamePassword.png
deleted file mode 100644
index 33e10da37..000000000
Binary files a/e2e/autoscript-apps/src/authn-wellknown/UsernamePassword.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/authn-wellknown/autoscript.ts b/e2e/autoscript-apps/src/authn-wellknown/autoscript.ts
deleted file mode 100644
index d8f8bd3dd..000000000
--- a/e2e/autoscript-apps/src/authn-wellknown/autoscript.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-async function autoscript() {
- const delay = 0;
- const tokenExpiredDelay = 2000;
-
- const url = new URL(window.location.href);
- const clientId = url.searchParams.get('clientId') || 'WebOAuthClient';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const scope = url.searchParams.get('scope') || 'openid profile me.read';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'UsernamePassword';
- const oauthThreshold = url.searchParams.get('oauthThreshold');
- const resourceOrigin = url.searchParams.get('resourceOrigin') || 'http://localhost:9443/resource';
- const igUrl = url.searchParams.get('igUrl'); // only use when testing against IG on different host
- const wellKnownUrl =
- url.searchParams.get('wellKnownUrl') ||
- 'http://localhost:9443/am/.well-known/oidc-configuration';
-
- console.log('Configure the SDK');
- await forgerock.Config.setAsync({
- clientId,
- middleware: [
- (req, action, next) => {
- switch (action.type) {
- case 'AUTHORIZE':
- console.log('Calling authorize endpoint');
- break;
- case 'EXCHANGE_TOKEN':
- console.log('Calling access token exchange endpoint');
- break;
- }
- next();
- },
- ],
- redirectUri: `${url.origin}/_callback/`,
- realmPath,
- scope,
- tree,
- serverConfig: {
- wellknown: wellKnownUrl,
- },
- oauthThreshold: oauthThreshold,
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- }
- console.log('Auth tree successfully completed');
- console.log('Get OAuth tokens');
- const tokens = forgerock.TokenManager.getTokens();
- return tokens;
- }),
- rxDelay(delay),
- map((tokens) => {
- if (tokens.accessToken) {
- console.log('OAuth login successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Session_Error');
- }
- return tokens;
- }),
- rxDelay(delay),
- mergeMap(
- (tokens) => {
- console.log('Get user info from OAuth endpoint');
- const user = forgerock.UserManager.getCurrentUser();
- return user;
- },
- (tokens, user) => {
- console.log(`User's given name: ${user.family_name}`);
- return tokens;
- },
- ),
- rxDelay(delay),
- mergeMap(
- (tokens) => {
- console.log('Force renew OAuth tokens');
- return forgerock.TokenManager.getTokens({ forceRenew: true });
- },
- (oldTokens, newTokens) => {
- if (oldTokens.accessToken !== newTokens.accessToken) {
- console.log('New OAuth tokens retrieved');
- } else {
- throw new Error('Force_Renew_Error');
- }
- return newTokens;
- },
- ),
- rxDelay(delay),
- mergeMap(() => {
- console.log('Initiate logout');
- return forgerock.FRUser.logout();
- }),
- rxDelay(delay),
- mergeMap(
- (step) => {
- return forgerock.TokenStorage.get();
- },
- (step, tokens) => {
- if (!tokens) {
- console.log('Logout successful');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- return step;
- },
- ),
- rxDelay(delay),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authn-wellknown/index.html b/e2e/autoscript-apps/src/authn-wellknown/index.html
deleted file mode 100644
index e7419ea4f..000000000
--- a/e2e/autoscript-apps/src/authn-wellknown/index.html
+++ /dev/null
@@ -1,35 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authz-token/UsernamePassword.png b/e2e/autoscript-apps/src/authz-token/UsernamePassword.png
deleted file mode 100644
index 33e10da37..000000000
Binary files a/e2e/autoscript-apps/src/authz-token/UsernamePassword.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/authz-token/autoscript.ts b/e2e/autoscript-apps/src/authz-token/autoscript.ts
deleted file mode 100644
index e9e0ca0c7..000000000
--- a/e2e/autoscript-apps/src/authz-token/autoscript.ts
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
- const tokenExpiredDelay = 2000;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const clientId = url.searchParams.get('clientId') || 'WebOAuthClient';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const scope = url.searchParams.get('scope') || 'openid profile me.read';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'UsernamePassword';
- const oauthThreshold = url.searchParams.get('oauthThreshold');
- const resourceOrigin = url.searchParams.get('resourceOrigin') || 'http://localhost:9443/resource';
- const igUrl = url.searchParams.get('igUrl'); // only use when testing against IG on different host
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- clientId,
- middleware: [
- (req, action, next) => {
- switch (action.type) {
- case 'AUTHORIZE':
- console.log('Calling authorize endpoint');
- break;
- case 'EXCHANGE_TOKEN':
- console.log('Calling access token exchange endpoint');
- break;
- }
- next();
- },
- ],
- redirectUri: `${url.origin}/_callback/`,
- realmPath,
- scope,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- oauthThreshold: oauthThreshold,
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- }
- console.log('Auth tree successfully completed');
- console.log('Get OAuth tokens');
- const tokens = forgerock.TokenManager.getTokens();
- return tokens;
- }),
- rxDelay(delay),
- map((tokens) => {
- if (tokens.accessToken) {
- console.log('OAuth login successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Session_Error');
- }
- return tokens;
- }),
- rxDelay(tokenExpiredDelay),
- mergeMap(
- (tokens) => {
- console.log('Proactively refresh tokens if expiring soon');
- return forgerock.TokenManager.getTokens();
- },
- (oldTokens, newTokens) => {
- console.log('tokens', oldTokens.accessToken, newTokens.accessToken);
- if (oldTokens.accessToken === newTokens.accessToken) {
- console.log('OAuth tokens not expiring soon; not refreshed');
- } else {
- console.log('OAuth tokens expiring soon; proactively refreshed');
- }
- return newTokens;
- },
- ),
- rxDelay(delay),
- mergeMap(
- (tokens) => {
- console.log('Retrieve a resource');
- return forgerock.HttpClient.request({
- url: `${igUrl ? igUrl : resourceOrigin + '/reflect-authz-header'}`,
- init: {
- method: 'GET',
- credentials: 'include',
- },
- });
- },
- async (storedTokens, response) => {
- const authorizationHeaderValue = await response.json();
- console.log(
- 'authorizationHeaderValue',
- authorizationHeaderValue.message,
- storedTokens.accessToken,
- );
- if (authorizationHeaderValue.message.includes(storedTokens.accessToken)) {
- console.log('OAuth tokens not expiring soon; not refreshed by HttpClient call');
- } else {
- console.log('OAuth tokens expiring soon; proactively refreshed by HttpClient call');
- }
- return storedTokens;
- },
- ),
- rxDelay(delay),
- mergeMap(() => {
- console.log('Initiate logout');
- return forgerock.FRUser.logout();
- }),
- rxDelay(delay),
- mergeMap(
- (step) => {
- return forgerock.TokenStorage.get();
- },
- (step, tokens) => {
- if (!tokens) {
- console.log('Logout successful');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- return step;
- },
- ),
- rxDelay(delay),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authz-token/index.html b/e2e/autoscript-apps/src/authz-token/index.html
deleted file mode 100644
index c371c9150..000000000
--- a/e2e/autoscript-apps/src/authz-token/index.html
+++ /dev/null
@@ -1,35 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authz-tree-basic-json/UsernamePassword.png b/e2e/autoscript-apps/src/authz-tree-basic-json/UsernamePassword.png
deleted file mode 100644
index 33e10da37..000000000
Binary files a/e2e/autoscript-apps/src/authz-tree-basic-json/UsernamePassword.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/authz-tree-basic-json/autoscript.ts b/e2e/autoscript-apps/src/authz-tree-basic-json/autoscript.ts
deleted file mode 100644
index 65b0be6c1..000000000
--- a/e2e/autoscript-apps/src/authz-tree-basic-json/autoscript.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const igUrl = url.searchParams.get('igUrl'); // only use when testing against IG on different host
- const resourceOrigin = url.searchParams.get('resourceOrigin') || 'http://localhost:9443/resource';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'UsernamePassword';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- middleware: [
- (req, action, next) => {
- switch (action.type) {
- case 'START_AUTHENTICATE':
- if (
- action.payload.type === 'composite_advice' &&
- typeof action.payload.tree === 'string'
- ) {
- console.log('Starting authentication with composite advice');
- }
- break;
- case 'AUTHENTICATE':
- if (action.payload.tree === '') {
- console.log('Continuing authentication with composite advice');
- }
- break;
- }
- next();
- },
- ],
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- map((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Basic login successful.');
- document.body.innerHTML = 'Login successful
';
- return step;
- } else {
- throw new Error('Something went wrong.');
- }
- }),
- rxDelay(delay),
- mergeMap(
- (step) => {
- console.log('Retrieve the protected resource');
- return forgerock.HttpClient.request({
- url: `${igUrl ? igUrl : resourceOrigin + '/ig/authz-by-tree'}`,
- init: {
- method: 'GET',
- credentials: 'include',
- },
- authorization: {
- handleStep: async (step) => {
- console.log('IG resource requires additional authorization');
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return Promise.resolve(step);
- },
- },
- });
- },
- (step, response) => {
- if (response.ok) {
- console.log('Request to IG resource successfully responded');
- } else {
- throw new Error('IG Tree Based Authorization was not successful');
- }
- return step;
- },
- ),
- rxDelay(delay),
- mergeMap((step) => {
- return forgerock.SessionManager.logout();
- }),
- map((response) => {
- if (response.ok) {
- console.log('Logout successful.');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- }),
- rxDelay(delay),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authz-tree-basic-json/index.html b/e2e/autoscript-apps/src/authz-tree-basic-json/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/authz-tree-basic-json/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authz-tree-basic-redirect/UsernamePassword.png b/e2e/autoscript-apps/src/authz-tree-basic-redirect/UsernamePassword.png
deleted file mode 100644
index 33e10da37..000000000
Binary files a/e2e/autoscript-apps/src/authz-tree-basic-redirect/UsernamePassword.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/authz-tree-basic-redirect/autoscript.ts b/e2e/autoscript-apps/src/authz-tree-basic-redirect/autoscript.ts
deleted file mode 100644
index f35549fca..000000000
--- a/e2e/autoscript-apps/src/authz-tree-basic-redirect/autoscript.ts
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const igUrl = url.searchParams.get('igUrl'); // only use when testing against IG on different host
- const resourceOrigin = url.searchParams.get('resourceOrigin') || 'http://localhost:9443/resource';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'UsernamePassword';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- middleware: [
- (req, action, next) => {
- switch (action.type) {
- case 'START_AUTHENTICATE':
- if (
- action.payload.type === 'composite_advice' &&
- typeof action.payload.tree === 'string'
- ) {
- console.log('Starting authentication with composite advice');
- }
- break;
- case 'AUTHENTICATE':
- if (action.payload.tree === '') {
- console.log('Continuing authentication with composite advice');
- }
- break;
- }
- next();
- },
- ],
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- map((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Basic login successful.');
- document.body.innerHTML = 'Login successful
';
- return step;
- } else {
- throw new Error('Something went wrong.');
- }
- }),
- rxDelay(delay),
- mergeMap(
- (step) => {
- console.log('Retrieve the protected resource');
- return forgerock.HttpClient.request({
- url: `${igUrl ? igUrl : resourceOrigin + '/ig/authz-by-tree'}`,
- init: {
- method: 'GET',
- credentials: 'include',
- },
- authorization: {
- handleStep: async (step) => {
- console.log('IG resource requires additional authorization');
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return Promise.resolve(step);
- },
- },
- });
- },
- (step, response) => {
- if (response.ok) {
- console.log('Request to IG resource successfully responded');
- } else {
- throw new Error('IG Tree Based Authorization was not successful');
- }
- return step;
- },
- ),
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Logout before calling next resource');
- return forgerock.SessionManager.logout();
- }),
- mergeMap(() => {
- console.log('Re-authenticating to call next resource');
- return forgerock.FRAuth.next();
- }),
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap(
- (step) => {
- console.log('Retrieve the protected resource');
- return forgerock.HttpClient.request({
- url: `${resourceOrigin}/rest/authz-by-tree`,
- init: {
- method: 'GET',
- credentials: 'include',
- },
- authorization: {
- handleStep: async (step) => {
- console.log('Rest resource requires additional authorization');
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return Promise.resolve(step);
- },
- },
- });
- },
- async (step, response) => {
- const jsonResponse = await response.json();
- if (jsonResponse.message === 'Successfully retrieved resource!') {
- console.log('Request to REST resource successfully responded');
- } else {
- throw new Error('REST Tree Based Authorization was not successful');
- }
- return step;
- },
- ),
- rxDelay(delay),
- mergeMap((step) => {
- return forgerock.SessionManager.logout();
- }),
- map((response) => {
- if (response.ok) {
- console.log('Logout successful.');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- }),
- rxDelay(delay),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authz-tree-basic-redirect/index.html b/e2e/autoscript-apps/src/authz-tree-basic-redirect/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/authz-tree-basic-redirect/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authz-tree-oauth/UsernamePassword.png b/e2e/autoscript-apps/src/authz-tree-oauth/UsernamePassword.png
deleted file mode 100644
index 33e10da37..000000000
Binary files a/e2e/autoscript-apps/src/authz-tree-oauth/UsernamePassword.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/authz-tree-oauth/autoscript.ts b/e2e/autoscript-apps/src/authz-tree-oauth/autoscript.ts
deleted file mode 100644
index 7460ea184..000000000
--- a/e2e/autoscript-apps/src/authz-tree-oauth/autoscript.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl');
- const clientId = url.searchParams.get('clientId') || 'WebOAuthClient';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const igUrl = url.searchParams.get('igUrl'); // only use when testing against IG on different host
- const resourceOrigin = url.searchParams.get('resourceOrigin') || 'http://localhost:9443/resource';
- const scope = url.searchParams.get('scope') || 'openid profile me.read';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'UsernamePassword';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- clientId,
- redirectUri: `${url.origin}/_callback/`,
- realmPath,
- scope,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- map((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Basic login successful.');
- document.body.innerHTML = 'Login successful
';
- return step;
- } else {
- throw new Error('Something went wrong.');
- }
- }),
- rxDelay(delay),
- mergeMap((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- }
- console.log('Auth tree successfully completed');
- console.log('Get OAuth tokens');
- const tokens = forgerock.TokenManager.getTokens({ forceRenew: true });
- return tokens;
- }),
- rxDelay(delay),
- mergeMap(
- (tokens) => {
- console.log('Retrieve the protected resource');
- return forgerock.HttpClient.request({
- url: `${igUrl ? igUrl : restUrl}/ig/authz-by-tree`,
- init: {
- method: 'GET',
- credentials: 'include',
- },
- authorization: {
- handleStep: async (step) => {
- console.log('IG resource requires additional authorization');
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return Promise.resolve(step);
- },
- },
- });
- },
- async (step, response) => {
- const jsonResponse = await response.json();
- if (jsonResponse.message === 'Successfully retrieved resource!') {
- console.log('Request to IG resource successfully responded');
- } else {
- throw new Error('IG Transactional Authorization was not successful');
- }
- return step;
- },
- ),
- rxDelay(delay),
- mergeMap(
- (step) => {
- console.log('Retrieve the protected resource');
- return forgerock.HttpClient.request({
- url: `${resourceOrigin}/rest/authz-by-tree`,
- init: {
- method: 'GET',
- credentials: 'include',
- },
- authorization: {
- handleStep: async (step) => {
- console.log('Rest resource requires additional authorization');
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return Promise.resolve(step);
- },
- },
- });
- },
- async (step, response) => {
- const jsonResponse = await response.json();
- if (jsonResponse.message === 'Successfully retrieved resource!') {
- console.log('Request to REST resource successfully responded');
- } else {
- throw new Error('REST Transactional Authorization was not successful');
- }
- return step;
- },
- ),
- rxDelay(delay),
- mergeMap((step) => {
- return forgerock.SessionManager.logout();
- }),
- map((response) => {
- if (response.ok) {
- console.log('Logout successful.');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- }),
- rxDelay(delay),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authz-tree-oauth/index.html b/e2e/autoscript-apps/src/authz-tree-oauth/index.html
deleted file mode 100644
index c371c9150..000000000
--- a/e2e/autoscript-apps/src/authz-tree-oauth/index.html
+++ /dev/null
@@ -1,35 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authz-txn-basic-json/UsernamePassword.png b/e2e/autoscript-apps/src/authz-txn-basic-json/UsernamePassword.png
deleted file mode 100644
index 33e10da37..000000000
Binary files a/e2e/autoscript-apps/src/authz-txn-basic-json/UsernamePassword.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/authz-txn-basic-json/autoscript.ts b/e2e/autoscript-apps/src/authz-txn-basic-json/autoscript.ts
deleted file mode 100644
index b98a7b066..000000000
--- a/e2e/autoscript-apps/src/authz-txn-basic-json/autoscript.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const igUrl = url.searchParams.get('igUrl'); // only use when testing against IG on different host
- const resourceOrigin = url.searchParams.get('resourceOrigin') || 'http://localhost:9443/resource';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'UsernamePassword';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- middleware: [
- (req, action, next) => {
- switch (action.type) {
- case 'START_AUTHENTICATE':
- if (
- action.payload.type === 'composite_advice' &&
- typeof action.payload.tree === 'string'
- ) {
- console.log('Starting authentication with composite advice');
- }
- break;
- case 'AUTHENTICATE':
- if (action.payload.tree === '') {
- console.log('Continuing authentication with composite advice');
- }
- break;
- }
- next();
- },
- ],
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- map((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Basic login successful.');
- document.body.innerHTML = 'Login successful
';
- return step;
- } else {
- throw new Error('Something went wrong.');
- }
- }),
- rxDelay(delay),
- mergeMap(
- (step) => {
- console.log('Retrieve the protected resource');
- return forgerock.HttpClient.request({
- url: `${igUrl ? igUrl : resourceOrigin + '/ig/authz-by-txn'}`,
- init: {
- method: 'GET',
- credentials: 'include',
- },
- authorization: {
- handleStep: async (step) => {
- console.log('IG resource requires additional authorization');
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return step;
- },
- },
- });
- },
- async (step, response) => {
- if (response.ok) {
- console.log('Request to IG resource successfully responded');
- } else {
- throw new Error('IG Transactional Authorization was not successful');
- }
- return step;
- },
- ),
- rxDelay(delay),
- mergeMap((step) => {
- return forgerock.SessionManager.logout();
- }),
- map((response) => {
- if (response.ok) {
- console.log('Logout successful.');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- }),
- rxDelay(delay),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authz-txn-basic-json/index.html b/e2e/autoscript-apps/src/authz-txn-basic-json/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/authz-txn-basic-json/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authz-txn-basic-redirect/UsernamePassword.png b/e2e/autoscript-apps/src/authz-txn-basic-redirect/UsernamePassword.png
deleted file mode 100644
index 33e10da37..000000000
Binary files a/e2e/autoscript-apps/src/authz-txn-basic-redirect/UsernamePassword.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/authz-txn-basic-redirect/autoscript.ts b/e2e/autoscript-apps/src/authz-txn-basic-redirect/autoscript.ts
deleted file mode 100644
index bcb97952f..000000000
--- a/e2e/autoscript-apps/src/authz-txn-basic-redirect/autoscript.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const igUrl = url.searchParams.get('igUrl'); // only use when testing against IG on different host
- const resourceOrigin = url.searchParams.get('resourceOrigin') || 'http://localhost:9443/resource';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'UsernamePassword';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- middleware: [
- (req, action, next) => {
- switch (action.type) {
- case 'START_AUTHENTICATE':
- if (
- action.payload.type === 'composite_advice' &&
- typeof action.payload.tree === 'string'
- ) {
- console.log('Starting authentication with composite advice');
- }
- break;
- case 'AUTHENTICATE':
- if (action.payload.tree === '') {
- console.log('Continuing authentication with composite advice');
- }
- break;
- }
- next();
- },
- ],
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- map((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Basic login successful.');
- document.body.innerHTML = 'Login successful
';
- return step;
- } else {
- throw new Error('Something went wrong.');
- }
- }),
- rxDelay(delay),
- mergeMap(
- (step) => {
- console.log('Retrieve the protected resource');
- return forgerock.HttpClient.request({
- url: `${igUrl ? igUrl : resourceOrigin + '/ig/authz-by-txn'}`,
- init: {
- method: 'GET',
- credentials: 'include',
- },
- authorization: {
- handleStep: async (step) => {
- console.log('IG resource requires additional authorization');
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return Promise.resolve(step);
- },
- },
- });
- },
- async (step, response) => {
- if (response.ok) {
- console.log('Request to IG resource successfully responded');
- } else {
- throw new Error('IG Transactional Authorization was not successful');
- }
- return step;
- },
- ),
- rxDelay(delay),
- mergeMap(
- (step) => {
- console.log('Retrieve the protected resource');
- return forgerock.HttpClient.request({
- url: `${resourceOrigin}/rest/authz-by-txn`,
- init: {
- method: 'GET',
- credentials: 'include',
- },
- authorization: {
- handleStep: async (step) => {
- console.log('Rest resource requires additional authorization');
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return Promise.resolve(step);
- },
- },
- });
- },
- async (step, response) => {
- if (response.ok) {
- console.log('Request to REST resource successfully responded');
- } else {
- throw new Error('REST Transactional Authorization was not successful');
- }
- return step;
- },
- ),
- rxDelay(delay),
- mergeMap((step) => {
- return forgerock.SessionManager.logout();
- }),
- map((response) => {
- if (response.ok) {
- console.log('Logout successful.');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- }),
- rxDelay(delay),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authz-txn-basic-redirect/index.html b/e2e/autoscript-apps/src/authz-txn-basic-redirect/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/authz-txn-basic-redirect/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/authz-txn-oauth/UsernamePassword.png b/e2e/autoscript-apps/src/authz-txn-oauth/UsernamePassword.png
deleted file mode 100644
index 33e10da37..000000000
Binary files a/e2e/autoscript-apps/src/authz-txn-oauth/UsernamePassword.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/authz-txn-oauth/autoscript.ts b/e2e/autoscript-apps/src/authz-txn-oauth/autoscript.ts
deleted file mode 100644
index 7fe18ff59..000000000
--- a/e2e/autoscript-apps/src/authz-txn-oauth/autoscript.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const clientId = url.searchParams.get('clientId') || 'WebOAuthClient';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const igUrl = url.searchParams.get('igUrl'); // only use when testing against IG on different host
- const resourceOrigin = url.searchParams.get('resourceOrigin') || 'http://localhost:9443/resource';
- const scope = url.searchParams.get('scope') || 'openid profile me.read';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'UsernamePassword';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- clientId,
- redirectUri: `${url.origin}/_callback/`,
- realmPath,
- scope,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- map((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Basic login successful.');
- document.body.innerHTML = 'Login successful
';
- return step;
- } else {
- throw new Error('Something went wrong.');
- }
- }),
- rxDelay(delay),
- mergeMap(
- (step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- }
- console.log('Auth tree successfully completed');
- console.log('Get OAuth tokens');
- const tokens = forgerock.TokenManager.getTokens({ forceRenew: true });
- return tokens;
- },
- (step) => step,
- ),
- rxDelay(delay),
- mergeMap(
- (step) => {
- console.log('Retrieve the protected resource');
- return forgerock.HttpClient.request({
- url: `${igUrl ? igUrl : resourceOrigin + '/ig/authz-by-txn'}`,
- init: {
- method: 'GET',
- credentials: 'include',
- },
- authorization: {
- handleStep: async (step) => {
- console.log('IG resource requires additional authorization');
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return Promise.resolve(step);
- },
- },
- });
- },
- async (step, response) => {
- const jsonResponse = await response.json();
- if (jsonResponse.message === 'Successfully retrieved resource!') {
- console.log('Request to IG resource successfully responded');
- } else {
- throw new Error('IG Transactional Authorization was not successful');
- }
- return step;
- },
- ),
- rxDelay(delay),
- mergeMap(
- (step) => {
- console.log('Retrieve the protected resource');
- return forgerock.HttpClient.request({
- url: `${resourceOrigin}/rest/authz-by-txn`,
- init: {
- method: 'GET',
- credentials: 'include',
- },
- authorization: {
- handleStep: async (step) => {
- console.log('Rest resource requires additional authorization');
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return Promise.resolve(step);
- },
- },
- });
- },
- async (step, response) => {
- const jsonResponse = await response.json();
- if (jsonResponse.message === 'Successfully retrieved resource!') {
- console.log('Request to REST resource successfully responded');
- } else {
- throw new Error('REST Transactional Authorization was not successful');
- }
- return step;
- },
- ),
- rxDelay(delay),
- mergeMap((step) => {
- return forgerock.SessionManager.logout();
- }),
- map((response) => {
- if (response.ok) {
- console.log('Logout successful.');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- }),
- rxDelay(delay),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/authz-txn-oauth/index.html b/e2e/autoscript-apps/src/authz-txn-oauth/index.html
deleted file mode 100644
index c371c9150..000000000
--- a/e2e/autoscript-apps/src/authz-txn-oauth/index.html
+++ /dev/null
@@ -1,35 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/config-custom-paths/UsernamePassword.png b/e2e/autoscript-apps/src/config-custom-paths/UsernamePassword.png
deleted file mode 100644
index 33e10da37..000000000
Binary files a/e2e/autoscript-apps/src/config-custom-paths/UsernamePassword.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/config-custom-paths/autoscript.ts b/e2e/autoscript-apps/src/config-custom-paths/autoscript.ts
deleted file mode 100644
index e1bf9cd83..000000000
--- a/e2e/autoscript-apps/src/config-custom-paths/autoscript.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const clientId = url.searchParams.get('clientId') || 'WebOAuthClient';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const scope = url.searchParams.get('scope') || 'openid profile me.read';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'UsernamePassword';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- clientId,
- redirectUri: `${url.origin}/_callback/`,
- realmPath,
- scope,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- paths: {
- authenticate: 'auth/authenticate',
- authorize: 'auth/authorize',
- accessToken: 'auth/tokenExchange',
- endSession: 'auth/endSession',
- userInfo: 'auth/userInfo',
- revoke: 'auth/revoke',
- sessions: 'auth/sessions',
- },
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap(
- (step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- }
- console.log('Auth tree successfully completed');
- console.log('Get OAuth tokens');
- const tokens = forgerock.TokenManager.getTokens({ forceRenew: true });
- return tokens;
- },
- (step) => step,
- ),
- rxDelay(delay),
- map((step) => {
- if (step.getSessionToken()) {
- console.log('OAuth login successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Session_Error');
- }
- }),
- rxDelay(delay),
- mergeMap(
- (step) => {
- console.log('Get user info from OAuth endpoint');
- const user = forgerock.UserManager.getCurrentUser();
- return user;
- },
- (step, user) => {
- console.log(`User's given name: ${user.family_name}`);
- return step;
- },
- ),
- rxDelay(delay),
- mergeMap(
- (step) => {
- console.log('Initiate logout');
- return forgerock.FRUser.logout();
- },
- (step) => step,
- ),
- rxDelay(delay),
- mergeMap(
- (step) => {
- return forgerock.TokenStorage.get();
- },
- (step, tokens) => {
- if (!tokens) {
- console.log('Logout successful');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- return step;
- },
- ),
- rxDelay(delay),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/config-custom-paths/index.html b/e2e/autoscript-apps/src/config-custom-paths/index.html
deleted file mode 100644
index c371c9150..000000000
--- a/e2e/autoscript-apps/src/config-custom-paths/index.html
+++ /dev/null
@@ -1,35 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/config-request-middleware/UsernamePassword.png b/e2e/autoscript-apps/src/config-request-middleware/UsernamePassword.png
deleted file mode 100644
index 33e10da37..000000000
Binary files a/e2e/autoscript-apps/src/config-request-middleware/UsernamePassword.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/config-request-middleware/autoscript.ts b/e2e/autoscript-apps/src/config-request-middleware/autoscript.ts
deleted file mode 100644
index f6d1a9ba8..000000000
--- a/e2e/autoscript-apps/src/config-request-middleware/autoscript.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const clientId = url.searchParams.get('clientId') || 'WebOAuthClient';
- const pw = url.searchParams.get('pw') || 'password';
- const realmPath = url.searchParams.get('realmPath') || 'middleware';
- const scope = url.searchParams.get('scope') || 'openid profile me.read';
- const setMiddleware = url.searchParams.get('middleware') || 'atConfig';
- const tree = url.searchParams.get('tree') || 'UsernamePassword';
- const un = url.searchParams.get('un') || 'sdkuser';
- const support = url.searchParams.get('support') || 'legacy';
-
- const middleware = [
- (req, action, next) => {
- switch (action.type) {
- case 'START_AUTHENTICATE':
- req.url.searchParams.set('start-authenticate-middleware', 'start-authentication');
- req.init.headers.append('x-start-authenticate-middleware', 'start-authentication');
- break;
- case 'AUTHENTICATE':
- req.url.searchParams.set('authenticate-middleware', 'authentication');
- req.init.headers.append('x-authenticate-middleware', 'authentication');
- break;
- case 'AUTHORIZE':
- req.url.searchParams.set('authorize-middleware', 'authorization');
- break;
- case 'EXCHANGE_TOKEN':
- req.url.searchParams.set('exchange-token-middleware', 'exchange-token');
- req.init.headers.append('x-exchange-token-middleware', 'exchange-token');
- break;
- case 'USER_INFO':
- req.url.searchParams.set('userinfo-middleware', 'userinfo');
- req.init.headers.append('x-userinfo-middleware', 'userinfo');
- break;
- }
- next();
- },
- (req, action, next) => {
- switch (action.type) {
- case 'LOGOUT':
- req.url.searchParams.set('logout-middleware', 'logout');
- req.init.headers.append('x-logout-middleware', 'logout');
- break;
- case 'REVOKE_TOKEN':
- req.url.searchParams.set('revoke-token-middleware', 'revoke-token');
- req.init.headers.append('x-revoke-token-middleware', 'revoke-token');
- break;
- case 'END_SESSION':
- req.url.searchParams.set('end-session-middleware', 'end-session');
- req.init.headers.append('x-end-session-middleware', 'end-session');
- break;
- }
- next();
- },
- ];
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- clientId,
- middleware: setMiddleware === 'atConfig' ? middleware : null,
- // This is different because we need to handle the
- // options call that is made by the modern call.
- // The api server will respond with a 200 so that the
- // preflight and actual request successfull resolve
- redirectUri: `${url.origin}/_callback/`,
- realmPath,
- scope,
- serverConfig: {
- baseUrl: amUrl,
- },
- tree,
- });
-
- try {
- forgerock.SessionManager.logout(setMiddleware === 'atCallSite' ? { middleware } : null);
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- from(forgerock.FRAuth.next(null, setMiddleware === 'atCallSite' ? { middleware } : null))
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step, setMiddleware === 'atCallSite' ? { middleware } : null);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.status === 406) {
- throw new Error('Middleware_Error');
- } else if (step.payload.tokenId) {
- console.log('Auth tree successfully completed');
- console.log('Get OAuth tokens');
- const configObj = {
- ...(setMiddleware === 'atCallSite' ? { middleware } : null),
- };
- const tokens = forgerock.TokenManager.getTokens(configObj);
-
- return tokens;
- } else {
- throw new Error('Something went wrong');
- }
- }),
- map((tokens) => {
- if (tokens.accessToken) {
- console.log('OAuth login successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Session_Error');
- }
- return tokens;
- }),
- rxDelay(delay),
- mergeMap((tokens) => {
- console.log('Get user info from OAuth endpoint');
- const user = forgerock.UserManager.getCurrentUser(
- setMiddleware === 'atCallSite' ? { middleware } : null,
- );
- return user;
- }),
- rxDelay(delay),
- mergeMap((user) => {
- if (user) {
- console.log('User info successfully responded');
- return forgerock.FRUser.logout(setMiddleware === 'atCallSite' ? { middleware } : null);
- } else {
- throw new Error('Userinfo_Error');
- }
- }),
- rxDelay(delay),
- mergeMap(
- (step) => {
- return forgerock.TokenStorage.get();
- },
- (step, tokens) => {
- if (!tokens) {
- console.log('Logout successful');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- return step;
- },
- ),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/config-request-middleware/index.html b/e2e/autoscript-apps/src/config-request-middleware/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/config-request-middleware/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/config-token-storage/UsernamePassword.png b/e2e/autoscript-apps/src/config-token-storage/UsernamePassword.png
deleted file mode 100644
index 33e10da37..000000000
Binary files a/e2e/autoscript-apps/src/config-token-storage/UsernamePassword.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/config-token-storage/autoscript.ts b/e2e/autoscript-apps/src/config-token-storage/autoscript.ts
deleted file mode 100644
index b488e744b..000000000
--- a/e2e/autoscript-apps/src/config-token-storage/autoscript.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const clientId = url.searchParams.get('clientId') || 'WebOAuthClient';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const scope = url.searchParams.get('scope') || 'openid profile me.read';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'UsernamePassword';
- let tokenStore = url.searchParams.get('tokenStore') || 'sessionStorage';
- let inMemoryTokens;
-
- if (tokenStore === 'customStore') {
- tokenStore = {
- get(clientId) {
- console.log('Custom token getter used.');
- return Promise.resolve(inMemoryTokens);
- },
- set(clientId, tokens) {
- console.log('Custom token setter used.');
- inMemoryTokens = tokens;
- return Promise.resolve(undefined);
- },
- remove(clientId) {
- console.log('Custom token remover used.');
- inMemoryTokens = undefined;
- return Promise.resolve(undefined);
- },
- };
- }
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- clientId,
- redirectUri: `${url.origin}/_callback/`,
- realmPath,
- scope,
- serverConfig: {
- baseUrl: amUrl,
- },
- tokenStore,
- tree,
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- from(forgerock.FRAuth.next())
- .pipe(
- mergeMap((step) => {
- console.log('Set values on auth tree callbacks');
- step.getCallbackOfType('NameCallback').setName(un);
- step.getCallbackOfType('PasswordCallback').setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- }
- console.log('Auth tree successfully completed');
- console.log('Get OAuth tokens');
- const tokens = forgerock.TokenManager.getTokens();
- return tokens;
- }),
- rxDelay(delay),
- mergeMap(
- (tokens) => {
- console.log('Get stored tokens');
- return forgerock.TokenStorage.get();
- },
- (tokens, storedTokens) => {
- if (tokens.accessToken === storedTokens.accessToken) {
- console.log(`Access token is correct`);
- }
- return tokens;
- },
- ),
- rxDelay(delay),
- mergeMap(
- (step) => {
- console.log('Initiate logout');
- return forgerock.FRUser.logout();
- },
- (step) => step,
- ),
- rxDelay(delay),
- mergeMap(
- (step) => {
- return forgerock.TokenStorage.get();
- },
- (step, tokens) => {
- if (!tokens) {
- console.log('Logout successful');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- return step;
- },
- ),
- rxDelay(delay),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/config-token-storage/index.html b/e2e/autoscript-apps/src/config-token-storage/index.html
deleted file mode 100644
index c371c9150..000000000
--- a/e2e/autoscript-apps/src/config-token-storage/index.html
+++ /dev/null
@@ -1,35 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/fr-ico.png b/e2e/autoscript-apps/src/fr-ico.png
deleted file mode 100644
index 213bf84cf..000000000
Binary files a/e2e/autoscript-apps/src/fr-ico.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/index.ts b/e2e/autoscript-apps/src/index.ts
deleted file mode 100644
index be15a9f01..000000000
--- a/e2e/autoscript-apps/src/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-import 'core-js/stable';
-import 'regenerator-runtime';
diff --git a/e2e/autoscript-apps/src/misc-callbacks/MiscCallbacks.png b/e2e/autoscript-apps/src/misc-callbacks/MiscCallbacks.png
deleted file mode 100644
index f12f936ac..000000000
Binary files a/e2e/autoscript-apps/src/misc-callbacks/MiscCallbacks.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/misc-callbacks/autoscript.ts b/e2e/autoscript-apps/src/misc-callbacks/autoscript.ts
deleted file mode 100644
index 4d3793019..000000000
--- a/e2e/autoscript-apps/src/misc-callbacks/autoscript.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const un = url.searchParams.get('un') || 'sdkuser';
- const pw = url.searchParams.get('pw') || 'password';
- const tree = url.searchParams.get('tree') || 'MiscCallbacks';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- // Wrapping in setTimeout to give the test time to bind listener to console.log
- setTimeout(function () {
- from(forgerock.FRAuth.next())
- .pipe(
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Handle Username Callback');
- const cb = step.getCallbackOfType('NameCallback');
- console.log(`Prompt from NameCallback is ${cb.getPrompt()}`);
- cb.setName(un);
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Handle Text Input Callback');
- const cb = step.getCallbackOfType('TextInputCallback');
- console.log(`Prompt from TextInputCallback is ${cb.getPrompt()}`);
- cb.setInput('Text Input String');
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Handle Password Callback');
- const cb = step.getCallbackOfType('PasswordCallback');
- console.log(`Prompt from PasswordCallback is ${cb.getPrompt()}`);
- cb.setPassword(pw);
- return forgerock.FRAuth.next(step);
- }),
- mergeMap((step) => {
- console.log('Handle Choice Callback');
- const cb = step.getCallbackOfType('ChoiceCallback');
- const prompt = cb.getPrompt();
- console.log(prompt);
- const defaultChoice = cb.getDefaultChoice();
- console.log(defaultChoice);
- const choices = cb.getChoices();
- console.log(choices);
- cb.setChoiceIndex(2);
- cb.setChoiceValue('green');
- console.log('Value of "green" is set');
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Handle Confirmation Callback');
- const confirmCB = step.getCallbackOfType('ConfirmationCallback');
- const textCB = step.getCallbackOfType('TextOutputCallback');
- const message = textCB.getMessage();
- console.log(`Message for confirmation is: ${message}`);
- const options = confirmCB.getOptions();
- confirmCB.setOptionValue(options[1]);
- confirmCB.setOptionIndex(0);
- console.log('Setting value to "Yes"');
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Handle Polling Callback');
- const cb = step.getCallbackOfType('PollingWaitCallback');
- const message = cb.getMessage();
- console.log(message);
- const waitTime = cb.getWaitTime();
- console.log(`Wait time is ${waitTime} milliseconds`);
- return new Promise((resolve) => {
- setTimeout(() => {
- resolve(step);
- }, waitTime + 1000);
- });
- }),
- rxDelay(delay),
- mergeMap((step) => {
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- mergeMap((step) => {
- return forgerock.SessionManager.logout();
- }),
- map((response) => {
- if (response.ok) {
- console.log('Logout successful');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
- }, 250);
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/misc-callbacks/index.html b/e2e/autoscript-apps/src/misc-callbacks/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/misc-callbacks/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/src/register-basic/Registration.png b/e2e/autoscript-apps/src/register-basic/Registration.png
deleted file mode 100644
index c34a3a904..000000000
Binary files a/e2e/autoscript-apps/src/register-basic/Registration.png and /dev/null differ
diff --git a/e2e/autoscript-apps/src/register-basic/autoscript.ts b/e2e/autoscript-apps/src/register-basic/autoscript.ts
deleted file mode 100644
index f0f1c134d..000000000
--- a/e2e/autoscript-apps/src/register-basic/autoscript.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * autoscript.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-// @ts-nocheck
-import * as forgerock from '@forgerock/javascript-sdk';
-import { delay as rxDelay, map, mergeMap } from 'rxjs/operators';
-import { from } from 'rxjs';
-
-function autoscript() {
- const delay = 0;
-
- const url = new URL(window.location.href);
-
- const amUrl = url.searchParams.get('amUrl') || 'http://localhost:9443/am';
- const realmPath = url.searchParams.get('realmPath') || 'root';
- const tree = url.searchParams.get('tree') || 'Registration';
- const un = url.searchParams.get('un') || 'f9022889-4452-48a0-aa94-182436645551';
- const pw = url.searchParams.get('pw') || 'password';
- const email = url.searchParams.get('email') || 'sally.tester@me.com';
-
- console.log('Configure the SDK');
- forgerock.Config.set({
- realmPath,
- tree,
- serverConfig: {
- baseUrl: amUrl,
- },
- });
-
- try {
- forgerock.SessionManager.logout();
- } catch (err) {
- // Do nothing
- }
-
- console.log('Initiate first step with `undefined`');
- // Wrapping in setTimeout to give the test time to bind listener to console.log
- setTimeout(function () {
- from(forgerock.FRAuth.next())
- .pipe(
- rxDelay(delay),
- mergeMap((step) => {
- console.log('Handle ValidatedCreateUsernameCallback');
- const unCb = step.getCallbackOfType('ValidatedCreateUsernameCallback');
- console.log(`Prompt from UsernameCallback is ${unCb.getPrompt()}`);
- unCb.setName(un);
-
- console.log('Handle ValidatedCreatePasswordCallback');
- const pwCb = step.getCallbackOfType('ValidatedCreatePasswordCallback');
- console.log(`Prompt from PasswordCallback is ${pwCb.getPrompt()}`);
- pwCb.setPassword(pw);
-
- const [saCb1, saCb2, saCb3] = step.getCallbacksOfType('StringAttributeInputCallback');
-
- console.log(`Prompt 1: ${saCb1.getPrompt()}`);
- console.log(`Prompt 2: ${saCb2.getPrompt()}`);
- console.log(`Prompt 3: ${saCb3.getPrompt()}`);
-
- saCb1.setInputValue('Sally');
- saCb2.setInputValue('Tester');
- saCb3.setInputValue(email);
-
- const [baCb1, baCb2] = step.getCallbacksOfType('BooleanAttributeInputCallback');
-
- console.log(`Prompt 4: ${baCb1.getPrompt()}`);
- console.log(`Prompt 5: ${baCb2.getPrompt()}`);
-
- baCb1.setInputValue(false);
- baCb2.setInputValue(false);
-
- // const naCb = step.getCallbackOfType('NumberAttributeInputCallback');
- // console.log(`Prompt 6: ${naCb.getPrompt()}`);
-
- // naCb.setInputValue(40);
-
- console.log('Handle KbaCreateCallback');
- const [kbCb1, kbCb2] = step.getCallbacksOfType('KbaCreateCallback');
-
- console.log(`Prompt 7: ${kbCb1.getPrompt()}`);
- console.log(`Prompt 8: ${kbCb2.getPrompt()}`);
-
- const [pdq1, pdq2] = kbCb1.getPredefinedQuestions();
- console.log(`Predefined Question1: ${pdq1}`);
- console.log(`Predefined Question 2: ${pdq2}`);
-
- kbCb1.setQuestion('What is your favorite color?');
- kbCb1.setAnswer('Red');
-
- kbCb2.setQuestion('Who was your first employer?');
- kbCb2.setAnswer('AAA Engineering');
-
- console.log('Handle TermsAndConditionsCallback');
- const tcCb = step.getCallbackOfType('TermsAndConditionsCallback');
-
- console.log(`Terms version: ${tcCb.getVersion()}`);
- console.log(`Terms text: ${tcCb.getTerms()}`);
-
- tcCb.setAccepted();
-
- return forgerock.FRAuth.next(step);
- }),
- rxDelay(delay),
- map(
- (step) => {
- if (step.payload.status === 401) {
- throw new Error('Auth_Error');
- } else if (step.payload.tokenId) {
- console.log('Basic login successful');
- document.body.innerHTML = 'Login successful
';
- } else {
- throw new Error('Something went wrong.');
- }
- },
- (step) => step,
- ),
- rxDelay(delay),
- mergeMap((step) => {
- return forgerock.SessionManager.logout();
- }),
- map((response) => {
- if (response.ok) {
- console.log('Logout successful');
- document.body.innerHTML = 'Logout successful
';
- } else {
- throw new Error('Logout_Error');
- }
- }),
- )
- .subscribe({
- error: (err) => {
- console.log(`Error: ${err.message}`);
- document.body.innerHTML = `${err.message}
`;
- },
- complete: () => {
- console.log('Test script complete');
- document.body.innerHTML = `Test script complete
`;
- },
- });
- }, 250);
-}
-
-autoscript();
-export default autoscript;
diff --git a/e2e/autoscript-apps/src/register-basic/index.html b/e2e/autoscript-apps/src/register-basic/index.html
deleted file mode 100644
index 016c1758f..000000000
--- a/e2e/autoscript-apps/src/register-basic/index.html
+++ /dev/null
@@ -1,33 +0,0 @@
-
-
-
- E2E Test | ForgeRock JavaScript SDK
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/e2e/autoscript-apps/tsconfig.app.json b/e2e/autoscript-apps/tsconfig.app.json
deleted file mode 100644
index 1af188a98..000000000
--- a/e2e/autoscript-apps/tsconfig.app.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "dist",
- "composite": true,
- "moduleResolution": "Bundler",
- "target": "ES2020",
- "module": "ES2020",
- "allowUmdGlobalAccess": true
- },
- "exclude": ["**/*.spec.ts"],
- "include": ["**/*.ts"]
-}
diff --git a/e2e/autoscript-apps/tsconfig.json b/e2e/autoscript-apps/tsconfig.json
deleted file mode 100644
index 2e6faed4e..000000000
--- a/e2e/autoscript-apps/tsconfig.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "extends": "../../tsconfig.base.json",
- "files": [],
- "include": [],
- "compilerOptions": {
- "forceConsistentCasingInFileNames": true,
- "strict": false,
- "noImplicitOverride": false,
- "noPropertyAccessFromIndexSignature": false,
- "noImplicitReturns": true,
- "noFallthroughCasesInSwitch": true
- },
- "references": [
- {
- "path": "./tsconfig.app.json"
- }
- ]
-}
diff --git a/e2e/autoscript-apps/vite.config.ts b/e2e/autoscript-apps/vite.config.ts
deleted file mode 100644
index f9d0a6219..000000000
--- a/e2e/autoscript-apps/vite.config.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { defineConfig } from 'vite';
-import * as path from 'path';
-
-const pages = [
- 'authn-basic',
- 'authn-central-login',
- 'authn-central-login-wellknown',
- 'authn-device-profile',
- 'authn-protect',
- 'authn-email-suspend',
- 'authn-no-session',
- 'authn-oauth',
- 'authn-wellknown',
- 'authn-platform',
- 'authn-saml',
- 'authn-second-factor',
- 'authn-social-login-am',
- 'authn-social-login-idm',
- 'authn-webauthn',
- 'authn-webauthn-device-registration',
- 'authn-otp-reg',
- 'authz-token',
- 'authz-tree-basic-json',
- 'authz-tree-basic-redirect',
- 'authz-txn-basic-json',
- 'authz-txn-basic-redirect',
- 'authz-txn-oauth',
- 'config-custom-paths',
- 'config-request-middleware',
- 'config-token-storage',
- 'misc-callbacks',
- 'register-basic',
-];
-
-export default defineConfig({
- root: __dirname,
- cacheDir: '../../node_modules/.vite/e2e/autoscript-apps',
-
- server: {
- cors: true,
- port: 8443,
- host: 'localhost',
- headers: {
- 'Access-Control-Allow-Credentials': 'true',
- 'Access-Control-Allow-Origin': 'null',
- 'Access-Control-Allow-Headers': 'x-authorize-middleware',
- },
- },
- preview: {
- port: 8443,
- host: 'localhost',
- headers: {
- 'Access-Control-Allow-Origin': 'http://localhost:8443',
- },
- },
- build: {
- outDir: './dist',
- reportCompressedSize: true,
- rollupOptions: {
- input: {
- main: path.resolve(__dirname, 'index.html'),
- ...pages.reduce(
- (acc, page) => {
- acc[page as keyof typeof pages] = path.resolve(__dirname, `src/${page}/index.html`);
- return acc;
- },
- {} as Record,
- ),
- },
- output: {
- entryFileNames: 'src/[name]/main.js',
- },
- },
- },
-});
diff --git a/e2e/autoscript-suites/.eslintignore b/e2e/autoscript-suites/.eslintignore
deleted file mode 100644
index 7eb3b6427..000000000
--- a/e2e/autoscript-suites/.eslintignore
+++ /dev/null
@@ -1,9 +0,0 @@
-node_modules
-*.md
-LICENSE
-.babelrc
-.env*
-.bin
-dist
-.eslintignore
-*.html
\ No newline at end of file
diff --git a/e2e/autoscript-suites/.eslintrc.json b/e2e/autoscript-suites/.eslintrc.json
deleted file mode 100644
index 91a80921a..000000000
--- a/e2e/autoscript-suites/.eslintrc.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "extends": ["../../.eslintrc.json"],
- "ignorePatterns": ["!**/*"],
- "overrides": [
- {
- "files": ["*.ts", "*.spec.ts"],
- "extends": ["plugin:playwright/recommended"]
- },
- {
- "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
- "rules": {}
- }
- ]
-}
diff --git a/e2e/autoscript-suites/config.ts b/e2e/autoscript-suites/config.ts
deleted file mode 100644
index 97fcc1e94..000000000
--- a/e2e/autoscript-suites/config.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { workspaceRoot } from '@nx/devkit';
-import { PlaywrightTestConfig } from '@playwright/test';
-import { baseConfig } from './playwright.config';
-
-export const config: PlaywrightTestConfig = {
- ...baseConfig,
- reporter: process.env.CI ? 'github' : 'list',
- testIgnore: '**/authz-txn*',
- use: {
- baseURL,
- ignoreHTTPSErrors: true,
- geolocation: { latitude: 24.9884, longitude: -87.3459 },
- bypassCSP: true,
- trace: process.env.CI ? 'retry-with-trace' : 'retain-on-failure',
- },
- webServer: [
- {
- command: 'pnpm nx serve mock-api',
- url: 'http://localhost:9443/healthcheck',
- ignoreHTTPSErrors: true,
- reuseExistingServer: !process.env.CI,
- cwd: workspaceRoot,
- },
- {
- command: 'pnpm nx serve mock-api-v2',
- url: 'http://localhost:9444/healthcheck',
- ignoreHTTPSErrors: true,
- reuseExistingServer: !process.env.CI,
- cwd: workspaceRoot,
- },
- {
- command: 'pnpm nx serve autoscript-apps',
- url: 'http://localhost:8443',
- ignoreHTTPSErrors: true,
- reuseExistingServer: !process.env.CI,
- cwd: workspaceRoot,
- },
- ],
-};
diff --git a/e2e/autoscript-suites/package.json b/e2e/autoscript-suites/package.json
deleted file mode 100644
index 637a71c79..000000000
--- a/e2e/autoscript-suites/package.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "name": "autoscript-suites",
- "version": "0.0.0",
- "private": true,
- "description": "ForgeRock JavaScript SDK E2E Suites",
- "main": "index.js",
- "type": "module",
- "author": "",
- "license": "ISC",
- "repository": {
- "type": "git",
- "url": "git+https://github.com/ForgeRock/forgerock-javascript-sdk.git"
- },
- "bugs": {
- "url": "https://github.com/ForgeRock/forgerock-javascript-sdk/issues"
- },
- "homepage": "https://github.com/ForgeRock/forgerock-javascript-sdk#readme",
- "dependencies": {}
-}
diff --git a/e2e/autoscript-suites/playwright.config.ts b/e2e/autoscript-suites/playwright.config.ts
deleted file mode 100644
index 8834f9782..000000000
--- a/e2e/autoscript-suites/playwright.config.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import * as os from 'os';
-import { PlaywrightTestConfig } from '@playwright/test';
-import { nxE2EPreset } from '@nx/playwright/preset';
-import { workspaceRoot } from '@nx/devkit';
-import { fileURLToPath } from 'url';
-
-const __filename = fileURLToPath(import.meta.url);
-
-// For CI, you may want to set BASE_URL to the deployed application.
-const baseURL = process.env['BASE_URL'] || 'http://localhost:8443';
-
-const baseConfig = nxE2EPreset(__filename, {
- testDir: './src/suites',
-});
-
-const config: PlaywrightTestConfig = {
- ...baseConfig,
- reporter: process.env.CI ? 'github' : 'list',
- testIgnore: '**/authz-txn*',
- use: {
- baseURL,
- ignoreHTTPSErrors: true,
- geolocation: { latitude: 24.9884, longitude: -87.3459 },
- bypassCSP: true,
- trace: process.env.CI ? 'retry-with-trace' : 'retain-on-failure',
- },
- projects: [
- {
- name: 'Chromium',
- },
- {
- name: 'Firefox',
- },
- os.type() === 'Darwin'
- ? {
- name: 'Safari',
- }
- : undefined,
- ].filter(Boolean),
- webServer: [
- {
- command: 'pnpm nx serve mock-api',
- url: 'http://localhost:9443/healthcheck',
- ignoreHTTPSErrors: true,
- reuseExistingServer: !process.env.CI,
- cwd: workspaceRoot,
- },
- {
- command: 'pnpm nx serve mock-api-v2',
- url: 'http://localhost:9444/healthcheck',
- ignoreHTTPSErrors: true,
- reuseExistingServer: !process.env.CI,
- cwd: workspaceRoot,
- },
- {
- command: 'pnpm nx serve autoscript-apps',
- url: 'http://localhost:8443',
- ignoreHTTPSErrors: true,
- reuseExistingServer: !process.env.CI,
- cwd: workspaceRoot,
- },
- ],
-};
-
-export default config;
diff --git a/e2e/autoscript-suites/project.json b/e2e/autoscript-suites/project.json
deleted file mode 100644
index 69d7d9a46..000000000
--- a/e2e/autoscript-suites/project.json
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "name": "autoscript-suites",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "sourceRoot": "e2e/autoscript-suites/src",
- "projectType": "application",
- "tags": [],
- "implicitDependencies": ["autoscript-apps", "mock-api", "mock-api-v2"],
- "targets": {
- "e2e": {
- "options": {},
- "configurations": {
- "ui": {
- "ui": true,
- "headed": true
- }
- }
- },
- "cbt": {
- "command": "pnpm browserstack-node-sdk playwright test --config ./e2e/autoscript-suites/playwright.config.cbt.ts",
- "cwd": "e2e/autoscript-suites"
- },
- "lint": {
- "options": {
- "fix": true,
- "ignore-path": ".eslintignore",
- "args": ["**/*.ts"]
- }
- }
- }
-}
diff --git a/e2e/autoscript-suites/src/env.config.ts b/e2e/autoscript-suites/src/env.config.ts
deleted file mode 100644
index 37d025f2d..000000000
--- a/e2e/autoscript-suites/src/env.config.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * env.config.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { env } from 'process';
-
-/**
- * Configure your environment defaults below.
- */
-const oauth = {
- client: 'WebOAuthClient',
- scope: 'openid profile me.read',
-};
-
-const origins = {
- // Ensure all domains are added to the security cert creation
- app: process.env.LIVE ? 'https://sdkapp.petrov.ca' : 'http://localhost',
- forgeops: 'https://default.forgeops.petrov.ca',
- mock: 'http://localhost',
- resource: 'http://localhost',
-};
-
-const paths = {
- am: '/am',
-};
-
-const ports = {
- app: '8443',
- forgeops: '443',
- mock: '9443',
- resource: '9443',
-};
-const realm = 'root';
-const testUsers = [
- {
- // Already exists in forgeops...
- pw: 'password',
- un: 'sdkuser',
- },
-];
-
-/**
- * The below will be composed of the above values.
- * Do not edit unless you know what you're doing.
- */
-let amUrl;
-let amPort;
-
-if (env.LIVE) {
- amUrl = origins.forgeops;
- amPort = ports.forgeops;
-} else {
- amUrl = origins.mock;
- amPort = ports.mock;
-}
-
-export const APP_PORT = ports.app;
-export const AM_PORT = amPort;
-export const MOCK_PORT = ports.mock;
-
-export const AM_URL = `${amUrl}:${amPort}${paths.am}`;
-export const BASE_URL = `${origins.app}:${ports.app}`;
-export const CLIENT_ID = oauth.client;
-export const FORGEOPS = origins.forgeops;
-export const REALM_PATH = realm;
-export const RESOURCE_URL = `${origins.resource}:${ports.resource}`;
-export const SCOPE = oauth.scope;
-export const USERS = testUsers;
diff --git a/e2e/autoscript-suites/src/env.setup.ts b/e2e/autoscript-suites/src/env.setup.ts
deleted file mode 100644
index 6997f54ce..000000000
--- a/e2e/autoscript-suites/src/env.setup.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * env.setup.js
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { setup as setupDevServer } from 'jest-dev-server';
-
-const liveServers = [
- {
- command: 'pnpm run start:server:live',
- port: 9443,
- },
-];
-const mockServers = [
- {
- command: 'pnpm run start:server',
- port: 9443,
- },
-];
-const servers = process.env.LIVE === 'true' ? liveServers : mockServers;
-
-module.exports = async () => {
- await setupDevServer(servers);
-};
diff --git a/e2e/autoscript-suites/src/suites/authn-basic.lc.neg.test.ts b/e2e/autoscript-suites/src/suites/authn-basic.lc.neg.test.ts
deleted file mode 100644
index ad50871b3..000000000
--- a/e2e/autoscript-suites/src/suites/authn-basic.lc.neg.test.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-basic.lc.neg.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test bad login flow', () => {
- test(`Login UNsuccessfully`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authn-basic/', {
- pw: 'wrong_password_123!',
- });
-
- // Test assertions
- expect(messageArray.includes('Error: Auth_Error')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authn-basic.lc.test.ts b/e2e/autoscript-suites/src/suites/authn-basic.lc.test.ts
deleted file mode 100644
index d352c5599..000000000
--- a/e2e/autoscript-suites/src/suites/authn-basic.lc.test.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-basic.lc.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test Basic login flow', () => {
- test(`should login successfully and then log out`, async ({ browserName, page }) => {
- const { headerArray, messageArray } = await setupAndGo(page, browserName, 'authn-basic/');
-
- // Test assertions
- expect(messageArray.includes('Basic login successful')).toBe(true);
- expect(messageArray.includes('Logout successful')).toBe(true);
- expect(messageArray.includes('Starting authentication with service')).toBe(true);
- expect(messageArray.includes('Continuing authentication with service')).toBe(true);
-
- expect(headerArray.find((headers) => headers.get('x-requested-platform'))).toBeFalsy();
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authn-central-login-wellknown.test.ts b/e2e/autoscript-suites/src/suites/authn-central-login-wellknown.test.ts
deleted file mode 100644
index 7ff1eecdc..000000000
--- a/e2e/autoscript-suites/src/suites/authn-central-login-wellknown.test.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-central-login-wellknown.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test OAuth login flow with .wellknown config', () => {
- // eslint-disable-next-line
- test(`should use full redirect to request auth code, then token exchange`, async ({
- page,
- browserName,
- }) => {
- const { messageArray, networkArray } = await setupAndGo(
- page,
- browserName,
- 'authn-central-login-wellknown/',
- {
- clientId: 'CentralLoginOAuthClient',
- wellknown: 'http://localhost:9443/am/.well-known/oidc-configuration',
- },
- );
-
- // Test assertions
- // Test log messages
- expect(messageArray.includes('OAuth authorization successful')).toBe(true);
- expect(messageArray.includes('Test script complete')).toBe(true);
- // Test network requests
- // Authorize endpoint should use iframe, which is type "document"
- expect(networkArray.includes('/am/oauth2/realms/root/authorize, document')).toBe(true);
- expect(networkArray.includes('/am/oauth2/realms/root/access_token, fetch')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authn-central-login.test.ts b/e2e/autoscript-suites/src/suites/authn-central-login.test.ts
deleted file mode 100644
index 11c50d5b5..000000000
--- a/e2e/autoscript-suites/src/suites/authn-central-login.test.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-central-login.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test OAuth login flow', () => {
- // eslint-disable-next-line
- test(`should use full redirect to request auth code, then token exchange`, async ({
- page,
- browserName,
- }) => {
- const { messageArray, networkArray } = await setupAndGo(
- page,
- browserName,
- 'authn-central-login/',
- );
-
- // Test assertions
- // Test log messages
- expect(messageArray.includes('OAuth authorization successful')).toBe(true);
- expect(messageArray.includes('Test script complete')).toBe(true);
- // Test network requests
- // Authorize endpoint should use iframe, which is type "document"
- expect(networkArray.includes('/am/oauth2/realms/root/authorize, document')).toBe(true);
- expect(networkArray.includes('/am/oauth2/realms/root/access_token, fetch')).toBe(true);
- });
-
- test(`should use sessionStorage for OAuth tokens, then token exchange`, async ({
- page,
- browserName,
- }) => {
- const { messageArray, networkArray } = await setupAndGo(
- page,
- browserName,
- 'authn-central-login/',
- { tokenStore: 'sessionStorage' },
- );
-
- // Test assertions
- // Test log messages
- expect(messageArray.includes('OAuth authorization successful')).toBe(true);
- expect(messageArray.includes('Test script complete')).toBe(true);
- // Test network requests
- // Authorize endpoint should use iframe, which is type "document"
- expect(networkArray.includes('/am/oauth2/realms/root/authorize, document')).toBe(true);
- expect(networkArray.includes('/am/oauth2/realms/root/access_token, fetch')).toBe(true);
- });
-
- test(`should use hidden iframe to request auth code,then token exchange`, async ({
- page,
- browserName,
- }) => {
- const { messageArray, networkArray } = await setupAndGo(
- page,
- browserName,
- 'authn-central-login/',
- { preAuthenticated: 'true' },
- );
-
- // Test assertions
- // Test log messages
- expect(messageArray.includes('OAuth authorization successful')).toBe(true);
- expect(messageArray.includes('Test script complete')).toBe(true);
- // Test network requests
- // Authorize endpoint should NOT be called using document or fetch
- expect(networkArray.includes('/am/oauth2/realms/root/authorize, document')).toBe(true);
- expect(networkArray.includes('/am/oauth2/realms/root/access_token, fetch')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authn-central-logout.test.ts b/e2e/autoscript-suites/src/suites/authn-central-logout.test.ts
deleted file mode 100644
index 10037e966..000000000
--- a/e2e/autoscript-suites/src/suites/authn-central-logout.test.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { test, expect } from '@playwright/test';
-
-test('should login and logout with pingone', async ({ page }) => {
- await page.goto('http://localhost:8443/');
- await page.getByRole('link', { name: 'AuthN: Central Logout Ping' }).click();
- await expect(page).toHaveURL('http://localhost:8443/src/authn-central-logout/index.html');
- await expect(page.getByRole('button', { name: /Force Renew/ })).toBeVisible();
- const btn = page.getByRole('button', { name: /Login/ });
- await expect(btn).toBeVisible();
- await btn.click({ delay: 1000 });
- await page.waitForURL(/ping/);
- await page.getByRole('textbox', { name: 'Username' }).click();
- await page.getByPlaceholder('Username').fill('sdk.user');
- await page.getByRole('textbox', { name: 'Password' }).click();
- await page.getByRole('textbox', { name: 'Password' }).fill('XZY8gqn3gau*jmv1hwg');
- await page.getByRole('button', { name: 'Sign On' }).click();
-
- await expect(page.getByText('preferred_username')).toContainText('sdk.user');
- await page.getByRole('button', { name: 'Sign Out' }).click({ clickCount: 1, delay: 300 });
- await page.getByRole('button', { name: 'Login' }).click({ delay: 300 });
- await page.waitForRequest(/pingone/);
-});
diff --git a/e2e/autoscript-suites/src/suites/authn-device-profile.lc.test.ts b/e2e/autoscript-suites/src/suites/authn-device-profile.lc.test.ts
deleted file mode 100644
index b67778349..000000000
--- a/e2e/autoscript-suites/src/suites/authn-device-profile.lc.test.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-device-profile.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test bad login flow', () => {
- test.use({ permissions: ['geolocation'] });
- test(`Login with device profile callback`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authn-device-profile/');
-
- // Test assertions
- expect(messageArray.includes('Collecting profile ...')).toBe(true);
- expect(messageArray.includes('Profile collected.')).toBe(true);
- expect(messageArray.includes('Login with profile successful.')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authn-email-suspend.test.ts b/e2e/autoscript-suites/src/suites/authn-email-suspend.test.ts
deleted file mode 100644
index 9f5dde2c6..000000000
--- a/e2e/autoscript-suites/src/suites/authn-email-suspend.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-email-suspend.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test basic registration flow', () => {
- test(`should register user successfully and then log out`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authn-email-suspend/');
-
- // Test assertions
- expect(
- messageArray.includes(
- // eslint-disable-next-line max-len
- 'An email has been sent to the address you entered. Click the link in that email to proceed.',
- ),
- ).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authn-no-session.lc.test.ts b/e2e/autoscript-suites/src/suites/authn-no-session.lc.test.ts
deleted file mode 100644
index 55815680d..000000000
--- a/e2e/autoscript-suites/src/suites/authn-no-session.lc.test.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-no-session.lc.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test Basic login flow', () => {
- test(`should login successfully and then log out with`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authn-no-session/');
-
- // Test assertions
- expect(messageArray.includes('Adding "noSession" query param to URL')).toBe(true);
- expect(messageArray.includes('Basic login with "noSession" completed successfully')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authn-oauth.lc.test.ts b/e2e/autoscript-suites/src/suites/authn-oauth.lc.test.ts
deleted file mode 100644
index 14006141a..000000000
--- a/e2e/autoscript-suites/src/suites/authn-oauth.lc.test.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-oauth.lc.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test OAuth login flow', () => {
- test(`should login successfully and then log out with`, async ({ page, browserName }) => {
- const { messageArray, networkArray } = await setupAndGo(page, browserName, 'authn-oauth/');
-
- // Test assertions
- // Test log messages
- expect(messageArray.includes('OAuth login successful')).toBe(true);
- expect(messageArray.includes('Logout successful')).toBe(true);
- expect(messageArray.includes('Calling authorize endpoint')).toBe(true);
- expect(messageArray.includes('Calling access token exchange endpoint')).toBe(true);
- expect(messageArray.includes('Get user info from OAuth endpoint')).toBe(true);
- expect(messageArray.includes('New OAuth tokens retrieved')).toBe(true);
-
- // Test network requests
- // Make sure revoke request is made twice, one for force renew and one for logout
- const revokeRequests = networkArray.filter(
- (request) => request === '/am/oauth2/realms/root/token/revoke, fetch',
- );
- expect(revokeRequests.length).toBe(2);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authn-otp-reg.test.ts b/e2e/autoscript-suites/src/suites/authn-otp-reg.test.ts
deleted file mode 100644
index 6bfeed9fb..000000000
--- a/e2e/autoscript-suites/src/suites/authn-otp-reg.test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-otp-reg.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test QR Code flows', () => {
- test(`Login and register OTP successfully`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authn-otp-reg/');
-
- // Test assertions
- expect(
- messageArray.includes(
- 'Scan the QR code image below with the ForgeRock Authenticator app to register your device with your login.',
- ),
- ).toBe(true);
- expect(messageArray.includes('otp')).toBe(true);
- expect(
- messageArray.includes(
- 'otpauth://totp/ForgeRock:jlowery?secret=QITSTC234FRIU8DD987DW3VPICFY======&issuer=ForgeRock&period=30&digits=6&b=032b75',
- ),
- ).toBe(true);
- expect(messageArray.includes('Basic login with OTP registration step successful')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authn-ping-marketplace.test.ts b/e2e/autoscript-suites/src/suites/authn-ping-marketplace.test.ts
deleted file mode 100644
index d29322a02..000000000
--- a/e2e/autoscript-suites/src/suites/authn-ping-marketplace.test.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-otp-reg.test.ts
- *
- * Copyright (c) 2024 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Login with marketplace nodes', () => {
- test(`Ping marketplace nodes`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authn-protect-metadata/');
-
- // Test assertions
- expect(messageArray.includes('Submitting ping protect start')).toBe(true);
-
- expect(messageArray.includes('Submitting ping protect evaluation')).toBe(true);
- expect(messageArray.includes('Basic login with Protect successful')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authn-platform.lc.test.ts b/e2e/autoscript-suites/src/suites/authn-platform.lc.test.ts
deleted file mode 100644
index 45c34bd0d..000000000
--- a/e2e/autoscript-suites/src/suites/authn-platform.lc.test.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-platform.lc.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test Basic login flow', () => {
- test(`should login successfully and then log out with`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authn-platform/');
-
- // Test assertions
- expect(messageArray.includes('Basic login with platform nodes successful')).toBe(true);
- expect(messageArray.includes('Logout successful')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authn-protect.test.ts b/e2e/autoscript-suites/src/suites/authn-protect.test.ts
deleted file mode 100644
index b877f056e..000000000
--- a/e2e/autoscript-suites/src/suites/authn-protect.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-basic.lc.test.ts
- *
- * Copyright (c) 2024 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test basic login flow with Ping Protect', () => {
- test(`should send Protect data and login successfully`, async ({ browserName, page }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authn-protect/');
- const configJson = messageArray.find((message) => message.includes('envId'));
-
- let configObj;
- try {
- configObj = JSON.parse(configJson);
- } catch (err) {
- console.log('Error parsing configJson');
- configObj = {};
- }
-
- // Test assertions
- expect(configObj.envId.length).toBeGreaterThan(5);
- expect(configObj.consoleLogEnabled).toBe(true);
- expect(configObj.deviceAttributesToIgnore).toStrictEqual(['userAgent']);
- expect(configObj.customHost).toBe('http://localhost');
- expect(configObj.lazyMetadata).toBe(false);
- expect(configObj.behavioralDataCollection).toBe(true);
- expect(configObj.deviceKeyRsyncIntervals).toBe(14);
- expect(configObj.enableTrust).toBe(false);
- expect(configObj.disableTags).toBe(false);
- expect(configObj.disableHub).toBe(false);
-
- expect(messageArray.includes('[SignalsSDK] Starting Signals SDK...')).toBe(true);
- expect(messageArray.includes('[SignalsSDK] calculated device attributes.')).toBe(true);
- expect(messageArray.includes('getPauseBehavioralData: true')).toBe(true);
- expect(messageArray.includes('Basic login with Protect successful')).toBe(true);
- expect(messageArray.includes('Test script complete')).toBe(true);
- });
-
- test('should not pause behavioral data if false', async ({ browserName, page }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authn-protect/', {
- pauseBehaviorData: 'false',
- });
- expect(messageArray.includes('[SignalsSDK] Starting Signals SDK...')).toBe(true);
- expect(messageArray.includes('[SignalsSDK] calculated device attributes.')).toBe(true);
- expect(messageArray.includes('getPauseBehavioralData: false')).toBe(true);
- expect(messageArray.includes('Basic login with Protect successful')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authn-saml.test.ts b/e2e/autoscript-suites/src/suites/authn-saml.test.ts
deleted file mode 100644
index 8fae80eee..000000000
--- a/e2e/autoscript-suites/src/suites/authn-saml.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-social-login-am.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('SAML Flow', () => {
- test(`Login with SAML`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authn-saml/', {
- tree: 'SAMLTest',
- });
- // Test assertions
- expect(messageArray.includes('init step')).toBe(true);
- expect(messageArray.includes('redirecting...')).toBe(true);
- expect(messageArray.includes('resumed')).toBe(true);
- expect(messageArray.includes('SAML Login successful')).toBe(true);
- });
- test(`Error on SAML handled`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authn-saml/', {
- tree: 'SAMLTestFailure',
- });
-
- // Test assertions
- expect(messageArray.includes('init step')).toBe(true);
- expect(messageArray.includes('redirecting...')).toBe(true);
- expect(messageArray.includes('resumed')).toBe(true);
- expect(messageArray.includes('errorSaml')).toBe(true);
- expect(messageArray.includes('401')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authn-second-factor.test.ts b/e2e/autoscript-suites/src/suites/authn-second-factor.test.ts
deleted file mode 100644
index cea7aab94..000000000
--- a/e2e/autoscript-suites/src/suites/authn-second-factor.test.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-second-factor.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test Second Factor login flow', () => {
- test(`should login successfully with OTP and then log out with`, async ({
- page,
- browserName,
- }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authn-second-factor/');
-
- // Test assertions
- expect(messageArray.includes('Set given OTP to password callback')).toBe(true);
- expect(messageArray.includes('Logout successful')).toBe(true);
- expect(messageArray.includes('Second Factor login successful')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authn-social-login-am.test.ts b/e2e/autoscript-suites/src/suites/authn-social-login-am.test.ts
deleted file mode 100644
index 6479c12bd..000000000
--- a/e2e/autoscript-suites/src/suites/authn-social-login-am.test.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-social-login-am.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test Social Login flow with AM nodes', () => {
- test(`Login with identity provide`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authn-social-login-am/', {
- clientId: 'IDMSocialLogin',
- });
-
- console.log(messageArray);
- // Test assertions
- expect(messageArray.includes('Set provider on SelectIdPCallback')).toBe(true);
- expect(messageArray.includes('Redirect to ID Provider')).toBe(true);
- expect(messageArray.includes('Returning from provider')).toBe(true);
- expect(messageArray.includes('Social Login successful')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authn-social-login-idm.test.ts b/e2e/autoscript-suites/src/suites/authn-social-login-idm.test.ts
deleted file mode 100644
index baf34f338..000000000
--- a/e2e/autoscript-suites/src/suites/authn-social-login-idm.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authn-social-login-idm.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test Social Login flow with AM nodes', () => {
- test(`Login with identity provider`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authn-social-login-idm/', {
- clientId: 'IDMSocialLogin',
- });
-
- // Test assertions
- expect(messageArray.includes('Set provider on SelectIdPCallback')).toBe(true);
- expect(messageArray.includes('Redirect to ID Provider')).toBe(true);
- expect(messageArray.includes('Returning from provider')).toBe(true);
- expect(messageArray.includes('Social Login successful')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authz-token.test.ts b/e2e/autoscript-suites/src/suites/authz-token.test.ts
deleted file mode 100644
index 5d8f77a69..000000000
--- a/e2e/autoscript-suites/src/suites/authz-token.test.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authz-token.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test OAuth token management', () => {
- test(`should proactively refresh tokens if they expire within the threshold`, async ({
- page,
- browserName,
- }) => {
- // Default threshold
- const defaultThresholdResult = await setupAndGo(page, browserName, 'authz-token/', {
- realmPath: 'tokens-expiring-soon',
- });
- expect(
- defaultThresholdResult.messageArray.includes(
- 'OAuth tokens expiring soon; proactively refreshed',
- ),
- ).toBe(true);
- expect(
- defaultThresholdResult.messageArray.includes(
- 'OAuth tokens expiring soon; proactively refreshed by HttpClient call',
- ),
- ).toBe(true);
-
- // Specified threshold
- const specifiedThresholdResult = await setupAndGo(page, browserName, 'authz-token/', {
- realmPath: 'tokens-expiring-soon',
- oauthThreshold: '25000',
- });
- expect(
- specifiedThresholdResult.messageArray.includes(
- 'OAuth tokens expiring soon; proactively refreshed',
- ),
- ).toBe(true);
- expect(
- specifiedThresholdResult.messageArray.includes(
- 'OAuth tokens expiring soon; proactively refreshed by HttpClient call',
- ),
- ).toBe(true);
-
- // Expired
- const expiredResult = await setupAndGo(page, browserName, 'authz-token/', {
- realmPath: 'tokens-expired',
- });
- expect(
- expiredResult.messageArray.includes('OAuth tokens expiring soon; proactively refreshed'),
- ).toBe(true);
- expect(
- expiredResult.messageArray.includes(
- 'OAuth tokens expiring soon; proactively refreshed by HttpClient call',
- ),
- ).toBe(true);
- });
-
- test(`should not proactively refresh tokens if they expire outside the threshold`, async ({
- page,
- browserName,
- }) => {
- // Default threshold
- const defaultThresholdResult = await setupAndGo(page, browserName, 'authz-token/', {});
- expect(
- defaultThresholdResult.messageArray.includes('OAuth tokens not expiring soon; not refreshed'),
- ).toBe(true);
- expect(
- defaultThresholdResult.messageArray.includes(
- 'OAuth tokens not expiring soon; not refreshed by HttpClient call',
- ),
- ).toBe(true);
- });
- test(`should not proactively refresh tokens if they expire outside the specified threshold`, async ({
- page,
- browserName,
- }) => {
- // Specified threshold
- const specifiedThresholdResult = await setupAndGo(page, browserName, 'authz-token/', {
- realmPath: 'tokens-expiring-soon',
- oauthThreshold: '10000',
- });
- expect(
- specifiedThresholdResult.messageArray.includes(
- 'OAuth tokens not expiring soon; not refreshed',
- ),
- ).toBe(true);
- expect(
- specifiedThresholdResult.messageArray.includes(
- 'OAuth tokens not expiring soon; not refreshed by HttpClient call',
- ),
- ).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authz-tree-basic-json.test.ts b/e2e/autoscript-suites/src/suites/authz-tree-basic-json.test.ts
deleted file mode 100644
index 99dac0bf3..000000000
--- a/e2e/autoscript-suites/src/suites/authz-tree-basic-json.test.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authz-tree-basic-json.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test Tree Based Authorization flow using JSON response', () => {
- test(`Trigger Tree Based Auth appropriately`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authz-tree-basic-json/');
-
- // Test assertions
- expect(messageArray.includes('IG resource requires additional authorization')).toBe(true);
- expect(messageArray.includes('Request to IG resource successfully responded')).toBe(true);
- expect(messageArray.includes('Starting authentication with composite advice')).toBe(true);
- expect(messageArray.includes('Continuing authentication with composite advice')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authz-tree-basic-redirect.test.ts b/e2e/autoscript-suites/src/suites/authz-tree-basic-redirect.test.ts
deleted file mode 100644
index 9d19c1d64..000000000
--- a/e2e/autoscript-suites/src/suites/authz-tree-basic-redirect.test.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-// /*
-// * @forgerock/javascript-sdk
-// *
-// * authz-tree-basic-redirect.test.ts
-// *
-// * Copyright (c) 2020 ForgeRock. All rights reserved.
-// * This software may be modified and distributed under the terms
-// * of the MIT license. See the LICENSE file for details.
-// */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test Tree Based Authorization flow using Redirect response', () => {
- // eslint-disable-next-line playwright/no-skipped-test
- test.skip(`Trigger Tree Based Auth appropriately`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authz-tree-basic-redirect/');
-
- // Test assertions
- expect(messageArray.includes('IG resource requires additional authorization')).toBe(true);
- expect(messageArray.includes('Rest resource requires additional authorization')).toBe(true);
- expect(messageArray.includes('Request to IG resource successfully responded')).toBe(true);
- expect(messageArray.includes('Request to REST resource successfully responded')).toBe(true);
- expect(messageArray.includes('Starting authentication with composite advice')).toBe(true);
- expect(messageArray.includes('Continuing authentication with composite advice')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authz-txn-basic-json.test.ts b/e2e/autoscript-suites/src/suites/authz-txn-basic-json.test.ts
deleted file mode 100644
index 003be7790..000000000
--- a/e2e/autoscript-suites/src/suites/authz-txn-basic-json.test.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authz-txn-basic-json.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test Transaction Authorization flow using JSON response', () => {
- test(`Trigger Txn Auth appropriately`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authz-txn-basic-json/');
-
- // Test assertions
- expect(messageArray.includes('IG resource requires additional authorization')).toBe(true);
- expect(messageArray.includes('Request to IG resource successfully responded')).toBe(true);
- expect(messageArray.includes('Starting authentication with composite advice')).toBe(true);
- expect(messageArray.includes('Continuing authentication with composite advice')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/authz-txn-basic-redirect.test.ts b/e2e/autoscript-suites/src/suites/authz-txn-basic-redirect.test.ts
deleted file mode 100644
index 9359a36ca..000000000
--- a/e2e/autoscript-suites/src/suites/authz-txn-basic-redirect.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * authz-txn-basic-redirect.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test Transaction Authorization flow using Redirect response', () => {
- test(`Trigger Txn Auth appropriately`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'authz-txn-basic-redirect/');
-
- // Test assertions
- expect(messageArray.includes('IG resource requires additional authorization')).toBe(true);
- expect(messageArray.includes('Rest resource requires additional authorization')).toBe(true);
- expect(messageArray.includes('Request to IG resource successfully responded')).toBe(true);
- expect(messageArray.includes('Request to REST resource successfully responded')).toBe(true);
- expect(messageArray.includes('Starting authentication with composite advice')).toBe(true);
- expect(messageArray.includes('Continuing authentication with composite advice')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/config-custom-paths.test.ts b/e2e/autoscript-suites/src/suites/config-custom-paths.test.ts
deleted file mode 100644
index eb93718f1..000000000
--- a/e2e/autoscript-suites/src/suites/config-custom-paths.test.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * config-custom-paths.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test OAuth login flow with custom paths', () => {
- test(`should login successfully and then log out with`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'config-custom-paths/');
-
- // Test assertions
- expect(messageArray.includes('OAuth login successful')).toBe(true);
- expect(messageArray.includes('Logout successful')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/config-request-middleware.test.ts b/e2e/autoscript-suites/src/suites/config-request-middleware.test.ts
deleted file mode 100644
index c445c2371..000000000
--- a/e2e/autoscript-suites/src/suites/config-request-middleware.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * config-request-middleware.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test request middleware with login flow', () => {
- test(`Full login and oauth using middleware at Config`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'config-request-middleware/', {
- realmPath: 'middleware',
- middleware: 'atConfig',
- });
-
- // Test assertions
- // Test log messages
- expect(messageArray.includes('Auth tree successfully completed')).toBe(true);
- expect(messageArray.includes('OAuth login successful')).toBe(true);
- expect(messageArray.includes('User info successfully responded')).toBe(true);
- expect(messageArray.includes('Logout successful')).toBe(true);
-
- // Test for absence of error logs for FRUser.logout
- expect(messageArray.includes('Session logout was not successful')).toBe(false);
- expect(messageArray.includes('OAuth endSession was not successful')).toBe(false);
- expect(messageArray.includes('OAuth revokeToken was not successful')).toBe(false);
- });
-
- test(`Full login and oauth using middleware at Call Site`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'config-request-middleware/', {
- realmPath: 'middleware',
- middleware: 'atCallSite',
- });
-
- // Test assertions
- // Test log messages
- expect(messageArray.includes('Auth tree successfully completed')).toBe(true);
- expect(messageArray.includes('OAuth login successful')).toBe(true);
- expect(messageArray.includes('User info successfully responded')).toBe(true);
- expect(messageArray.includes('Logout successful')).toBe(true);
-
- // Test for absence of error logs for FRUser.logout
- expect(messageArray.includes('Session logout was not successful')).toBe(false);
- expect(messageArray.includes('OAuth endSession was not successful')).toBe(false);
- expect(messageArray.includes('OAuth revokeToken was not successful')).toBe(false);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/config-token-storage.test.ts b/e2e/autoscript-suites/src/suites/config-token-storage.test.ts
deleted file mode 100644
index f53090075..000000000
--- a/e2e/autoscript-suites/src/suites/config-token-storage.test.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * config-token-storage.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test oauth login flow with tokenStore configurations', () => {
- test(`store tokens in sessionStorage`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'config-token-storage/', {
- tokenStore: 'sessionStorage',
- });
-
- // Test assertions
- expect(messageArray.includes('Access token is correct')).toBe(true);
- expect(messageArray.includes('Logout successful')).toBe(true);
- });
-
- test(`store tokens in customStore`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'config-token-storage/', {
- tokenStore: 'customStore',
- });
-
- // Test assertions
- expect(messageArray.includes('Custom token setter used.')).toBe(true);
- expect(messageArray.includes('Custom token getter used.')).toBe(true);
- expect(messageArray.includes('Custom token remover used.')).toBe(true);
- expect(messageArray.includes('Access token is correct')).toBe(true);
- expect(messageArray.includes('Logout successful')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/misc-callbacks.lc.test.ts b/e2e/autoscript-suites/src/suites/misc-callbacks.lc.test.ts
deleted file mode 100644
index 8b8ff41ac..000000000
--- a/e2e/autoscript-suites/src/suites/misc-callbacks.lc.test.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * misc-callbacks.lc.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test Basic login flow', () => {
- test(`should login successfully and then log out`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'misc-callbacks/');
-
- // Test assertions
- expect(messageArray.includes('Prompt from NameCallback is User Name')).toBe(true);
- expect(
- messageArray.includes('Prompt from TextInputCallback is Provide a nickname for this account'),
- ).toBe(true);
- expect(messageArray.includes('Prompt from PasswordCallback is Password')).toBe(true);
- expect(messageArray.includes('Choose your color')).toBe(true);
- expect(messageArray.includes('Value of "green" is set')).toBe(true);
- expect(messageArray.includes('Message for confirmation is: Is it true?')).toBe(true);
- expect(messageArray.includes('Waiting for response...')).toBe(true);
- expect(messageArray.includes('Wait time is 1000 milliseconds')).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/register-basic.lc.test.ts b/e2e/autoscript-suites/src/suites/register-basic.lc.test.ts
deleted file mode 100644
index 516ec8a10..000000000
--- a/e2e/autoscript-suites/src/suites/register-basic.lc.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * register-basic.lc.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { v4 } from 'uuid';
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-test.describe('Test basic registration flow', () => {
- const un = v4();
- const email = `${un}@me.com`;
-
- test(`should register user successfully and then log ou`, async ({ page, browserName }) => {
- const { messageArray } = await setupAndGo(page, browserName, 'register-basic/', {
- un,
- email,
- });
-
- // Test assertions
- expect(messageArray.includes('Prompt from UsernameCallback is Username')).toBe(true);
- expect(messageArray.includes('Prompt from PasswordCallback is Password')).toBe(true);
- expect(messageArray.includes('Prompt 1: First Name')).toBe(true);
- expect(messageArray.includes('Prompt 2: Last Name')).toBe(true);
- expect(messageArray.includes('Prompt 3: Email Address')).toBe(true);
- expect(messageArray.includes('Prompt 4: Send me special offers and services')).toBe(true);
- expect(messageArray.includes('Prompt 5: Send me news and updates')).toBe(true);
- // expect(messageArray.includes('Prompt 6: Age')).toBe(true);
- expect(messageArray.includes('Prompt 7: Select a security question')).toBe(true);
- expect(messageArray.includes(`Predefined Question1: What's your favorite color?`)).toBe(true);
- expect(messageArray.includes('Terms version: 0.0')).toBe(true);
- expect(
- messageArray.includes(
- // eslint-disable-next-line
- 'Terms text: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
- ),
- ).toBe(true);
- });
-});
diff --git a/e2e/autoscript-suites/src/suites/send-request-header.test.ts b/e2e/autoscript-suites/src/suites/send-request-header.test.ts
deleted file mode 100644
index 38805ad0d..000000000
--- a/e2e/autoscript-suites/src/suites/send-request-header.test.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * send-request-header.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { test, expect } from '@playwright/test';
-import { setupAndGo } from '../utilities/setup-and-go';
-
-// eslint-disable-next-line
-test(`should verifies x-requested-platform header is present in the request`, async ({
- page,
- browserName,
-}) => {
- const { headerArray } = await setupAndGo(page, browserName, 'authn-basic/', {
- platformHeader: 'true',
- });
-
- expect(headerArray.find((headers) => headers.get('x-requested-platform'))).toBeTruthy();
-});
diff --git a/e2e/autoscript-suites/src/utilities/setup-and-go.ts b/e2e/autoscript-suites/src/utilities/setup-and-go.ts
deleted file mode 100644
index a451302fa..000000000
--- a/e2e/autoscript-suites/src/utilities/setup-and-go.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * setup-and-go.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { Page } from '@playwright/test';
-import { AM_URL, BASE_URL, CLIENT_ID, RESOURCE_URL, SCOPE, REALM_PATH, USERS } from '../env.config';
-
-export async function setupAndGo(
- page: Page,
- browserType: string,
- path: string,
- config?: {
- allowGeo?: boolean;
- amUrl?: string;
- pauseBehaviorData?: string; // for protect behavioral data collection
- clientId?: string;
- code?: string;
- dialogInput?: string;
- email?: string;
- middleware?: string;
- platformHeader?: string;
- preAuthenticated?: string;
- pw?: string;
- realmPath?: string;
- resourceUrl?: string;
- selector?: string;
- scope?: string;
- state?: string;
- support?: string;
- tokenStore?: string;
- tree?: string;
- un?: string;
- oauthThreshold?: string;
- wellknown?: string;
- },
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
-): Promise<{
- headerArray: Headers[];
- messageArray: string[];
- networkArray: string[];
-}> {
- const headerArray: Headers[] = [];
- const messageArray: string[] = [];
- const networkArray: string[] = [];
-
- // If anything fails, ensure we close the browser to end the process
- const url = new URL(`${BASE_URL}/src/${path}`);
-
- url.searchParams.set('amUrl', (config && config.amUrl) || AM_URL);
- url.searchParams.set('pauseBehaviorData', (config && config.pauseBehaviorData) || '');
- url.searchParams.set('clientId', (config && config.clientId) || CLIENT_ID);
- config && config.code && url.searchParams.set('code', (config && config.code) || '');
- url.searchParams.set('email', (config && config.email) || '');
- url.searchParams.set('middleware', (config && config.middleware) || '');
- url.searchParams.set('platformHeader', (config && config.platformHeader) || '');
- url.searchParams.set('preAuthenticated', (config && config.preAuthenticated) || '');
- url.searchParams.set('pw', (config && config.pw) || USERS[0].pw);
- url.searchParams.set('realmPath', (config && config.realmPath) || REALM_PATH);
- url.searchParams.set('resourceUrl', (config && config.resourceUrl) || RESOURCE_URL);
- url.searchParams.set('scope', (config && config.scope) || SCOPE);
- config && config.state && url.searchParams.set('state', (config && config.state) || '');
- url.searchParams.set('support', (config && config.support) || '');
- url.searchParams.set('tokenStore', (config && config.tokenStore) || '');
- url.searchParams.set('tree', (config && config.tree) || '');
- url.searchParams.set('un', (config && config.un) || USERS[0].un);
- url.searchParams.set('oauthThreshold', (config && config.oauthThreshold) || '');
- url.searchParams.set('wellknown', (config && config.wellknown) || '');
-
- // log out the URL used for the test, but only for chromium;
- // the other browser URLs would just be duplicates
- if (browserType === 'chromium') {
- console.log(url.toString());
- }
-
- // Listen for events on page
- page.on('console', async (msg) => {
- messageArray.push(msg.text());
- return Promise.resolve(true);
- });
-
- page.on('request', async (req) => {
- networkArray.push(`${new URL(req.url()).pathname}, ${req.resourceType()}`);
- });
-
- page.on('request', async (req) => {
- const headers = req.headers();
-
- headerArray.push(new Headers(headers));
- });
-
- page.on('dialog', async (dialog) => {
- await dialog.accept(config?.dialogInput || 'abc123');
- });
-
- await page.goto(url.toString());
-
- // Test script complete
- const locator = page.locator('.Test_Complete');
- await locator.waitFor({ state: 'visible' });
-
- page.removeListener('console', (msg) => console.log(msg.text()));
-
- return { headerArray, messageArray, networkArray };
-}
diff --git a/e2e/autoscript-suites/tsconfig.json b/e2e/autoscript-suites/tsconfig.json
deleted file mode 100644
index 1a678b631..000000000
--- a/e2e/autoscript-suites/tsconfig.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "extends": "../../tsconfig.base.json",
- "compilerOptions": {
- "sourceMap": false,
- "allowJs": true,
- "types": ["node"],
- "outDir": "dist",
- "module": "ES2020",
- "moduleResolution": "NodeNext",
- "allowUmdGlobalAccess": true,
- "target": "ES2015"
- },
- "references": [
- {
- "path": "./tsconfig.spec.json"
- }
- ]
-}
diff --git a/e2e/autoscript-suites/tsconfig.spec.json b/e2e/autoscript-suites/tsconfig.spec.json
deleted file mode 100644
index d48ccb404..000000000
--- a/e2e/autoscript-suites/tsconfig.spec.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "../../dist/e2e/javascript-sdk-app/",
- "strict": false,
- "noImplicitAny": false
- },
- "include": [
- "playwright.config.ts",
- "utilities/*",
- "suites/*",
- "**/*.test.ts",
- "**/*.spec.ts",
- "**/*.test.tsx",
- "**/*.spec.tsx",
- "**/*.test.js",
- "**/*.spec.js",
- "**/*.test.jsx",
- "**/*.spec.jsx",
- "**/*.d.ts"
- ],
- "exclude": ["dist/"]
-}
diff --git a/e2e/davinci-app/package.json b/e2e/davinci-app/package.json
index 44dcf7c8b..c253325e6 100644
--- a/e2e/davinci-app/package.json
+++ b/e2e/davinci-app/package.json
@@ -1,12 +1,19 @@
{
- "name": "davinci-app",
+ "name": "@forgerock/davinci-app",
"description": "Ping DaVinci Client Test App",
"type": "module",
"private": true,
"dependencies": {
"@forgerock/davinci-client": "workspace:*",
- "@forgerock/javascript-sdk": "workspace:*"
+ "@forgerock/javascript-sdk": "4.6.0"
},
"devDependencies": {},
- "version": "0.0.0"
+ "version": "0.0.0",
+ "scripts": {
+ "build": "vite build --watch false",
+ "dev": "vite dev",
+ "serve": "vite preview",
+ "preview": "vite preview",
+ "lint": "eslint **/*.ts --fix"
+ }
}
diff --git a/e2e/davinci-app/project.json b/e2e/davinci-app/project.json
deleted file mode 100644
index 18d0f6681..000000000
--- a/e2e/davinci-app/project.json
+++ /dev/null
@@ -1,44 +0,0 @@
-{
- "name": "davinci-app",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "projectType": "application",
- "sourceRoot": "e2e/davinci-app/src",
- "tags": ["scope:app"],
- "targets": {
- "build": {
- "outputs": [
- "{projectRoot}/{options.outDir}",
- "{workspaceRoot}/dist/e2e/davinci-app"
- ],
- "options": {
- "emptyOutDir": false,
- "outDir": "../../dist/e2e/davinci-app"
- }
- },
- "serve": {
- "defaultConfiguration": "development",
- "options": {
- "host": "localhost",
- "port": 5829
- },
- "configurations": {
- "development": {},
- "production": {}
- }
- },
- "preview": {
- "defaultConfiguration": "development",
- "configurations": {
- "development": {},
- "production": {}
- }
- },
- "lint": {
- "options": {
- "fix": true,
- "ignore-path": ".eslintignore",
- "args": ["**/*.ts"]
- }
- }
- }
-}
diff --git a/e2e/davinci-app/vite.config.ts b/e2e/davinci-app/vite.config.ts
index 8ae81651b..867c9f009 100644
--- a/e2e/davinci-app/vite.config.ts
+++ b/e2e/davinci-app/vite.config.ts
@@ -4,7 +4,7 @@ import { defineConfig } from 'vite';
export default defineConfig({
root: __dirname,
build: {
- outDir: '../../dist/e2e/davinci-app',
+ outDir: './dist',
reportCompressedSize: true,
target: 'esnext',
minify: false,
@@ -18,10 +18,10 @@ export default defineConfig({
},
},
preview: {
- port: 5823,
+ port: 5829,
},
server: {
- port: 5823,
+ port: 5829,
headers: {
'Service-Worker-Allowed': '/',
'Service-Worker': 'script',
diff --git a/e2e/davinci-suites/.eslintignore b/e2e/davinci-suites/.eslintignore
index 7787c22e4..82f30765b 100644
--- a/e2e/davinci-suites/.eslintignore
+++ b/e2e/davinci-suites/.eslintignore
@@ -1,3 +1,4 @@
+.playwright/
node_modules
*.md
LICENSE
@@ -5,4 +6,4 @@ LICENSE
.env*
.bin
dist
-.eslintignore
\ No newline at end of file
+.eslintignore
diff --git a/e2e/davinci-suites/package.json b/e2e/davinci-suites/package.json
index 770d253d1..adaa3412b 100644
--- a/e2e/davinci-suites/package.json
+++ b/e2e/davinci-suites/package.json
@@ -1,5 +1,5 @@
{
- "name": "davinci-suites",
+ "name": "@forgerock/davinci-suites",
"description": "DaVinci Client E2E Suites",
"private": true,
"type": "module",
@@ -14,5 +14,8 @@
"bugs": {
"url": "https://github.com/ForgeRock/forgerock-javascript-sdk/issues"
},
- "homepage": "https://github.com/ForgeRock/forgerock-javascript-sdk#readme"
+ "homepage": "https://github.com/ForgeRock/forgerock-javascript-sdk#readme",
+ "scripts": {
+ "e2e": "playwright test -c ./playwright.config.ts"
+ }
}
diff --git a/e2e/davinci-suites/playwright.config.ts b/e2e/davinci-suites/playwright.config.ts
index 7437f157b..7143e91b6 100644
--- a/e2e/davinci-suites/playwright.config.ts
+++ b/e2e/davinci-suites/playwright.config.ts
@@ -1,19 +1,12 @@
import { PlaywrightTestConfig } from '@playwright/test';
-import { nxE2EPreset } from '@nx/playwright/preset';
import { workspaceRoot } from '@nx/devkit';
-import { fileURLToPath } from 'url';
-
-const __filename = fileURLToPath(import.meta.url);
// For CI, you may want to set BASE_URL to the deployed application.
const baseURL = process.env['BASE_URL'] || 'http://localhost:5829';
-const baseConfig = nxE2EPreset(__filename, {
- testDir: './src',
-});
-
const config: PlaywrightTestConfig = {
- ...baseConfig,
+ outputDir: './.playwright',
+ testDir: './src',
reporter: process.env.CI ? 'github' : 'list',
timeout: 30000,
use: {
@@ -24,15 +17,8 @@ const config: PlaywrightTestConfig = {
trace: process.env.CI ? 'on-first-retry' : 'retain-on-failure',
},
webServer: [
- // {
- // command: 'pnpm nx serve mock-api-v2',
- // url: 'http://localhost:9444/healthcheck',
- // ignoreHTTPSErrors: true,
- // reuseExistingServer: !process.env.CI,
- // cwd: workspaceRoot,
- // },
{
- command: 'pnpm nx serve davinci-app',
+ command: 'pnpm nx serve @forgerock/davinci-app',
port: 5829,
ignoreHTTPSErrors: true,
reuseExistingServer: !process.env.CI,
diff --git a/e2e/davinci-suites/project.json b/e2e/davinci-suites/project.json
deleted file mode 100644
index 7231d0725..000000000
--- a/e2e/davinci-suites/project.json
+++ /dev/null
@@ -1,25 +0,0 @@
-{
- "name": "davinci-suites",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "sourceRoot": "/e2e/davinci-suites/src",
- "projectType": "application",
- "tags": ["scope:e2e"],
- "implicitDependencies": ["davinci-app"],
- "targets": {
- "e2e": {
- "options": {},
- "configurations": {
- "ui": {
- "ui": true
- }
- }
- },
- "lint": {
- "options": {
- "fix": true,
- "ignore-path": ".eslintignore",
- "args": ["**/*.ts"]
- }
- }
- }
-}
diff --git a/e2e/mock-api-v2/build.js b/e2e/mock-api-v2/build.js
new file mode 100644
index 000000000..2f9204e9d
--- /dev/null
+++ b/e2e/mock-api-v2/build.js
@@ -0,0 +1,35 @@
+// build.js
+const esbuild = require('esbuild');
+const process = require('process');
+const fs = require('fs');
+const path = require('path');
+
+const { env } = process;
+
+const production = Boolean(env?.PROD) ?? false;
+const watch = Boolean(env?.WATCH) ?? false;
+
+esbuild
+ .build({
+ entryPoints: ['src/main.ts'],
+ bundle: true,
+ platform: 'node',
+ target: 'node20', // or your preferred Node.js version
+ assetNames: 'assets',
+ format: 'esm',
+ outfile: 'dist/main.js',
+ sourcemap: true,
+ watch,
+ minify: production, // Set to true for production
+ })
+ .then(() => {
+ // Copy CSS file to dist directory
+ fs.copyFileSync(
+ path.join(__dirname, 'src', 'index.css'),
+ path.join(__dirname, 'dist', 'index.css'),
+ );
+ console.log('CSS file copied to dist directory');
+
+ console.log('Build completed successfully!');
+ })
+ .catch(() => process.exit(1));
diff --git a/e2e/mock-api-v2/package.json b/e2e/mock-api-v2/package.json
index 0a7acb646..fcf8714fc 100644
--- a/e2e/mock-api-v2/package.json
+++ b/e2e/mock-api-v2/package.json
@@ -1,13 +1,22 @@
{
- "name": "mock-api",
- "version": "0.0.0",
- "private": true,
+ "name": "@forgerock/mock-api-v2",
+ "version": "1.0.0",
"description": "",
"main": "./dist/index.js",
- "module": "./dist/index.js",
- "exports": "./dist/index.js",
- "keywords": [],
- "author": "",
- "type": "module",
- "license": "ISC"
+ "type": "commonjs",
+ "scripts": {
+ "build": "tsc --project tsconfig.app.json",
+ "build:watch": "tsc --project tsconfig.app.json --watch",
+ "serve": "node dist/e2e/mock-api-v2/src/main.js",
+ "serve:dev": "nodemon dist/e2e/mock-api-v2/src/main.js",
+ "test": "vitest run --coverage --coverage.reportsDirectory=../../coverage/mock-api-v2",
+ "test:watch": "vitest watch --coverage --coverage.reportsDirectory=../../coverage/mock-api-v2",
+ "lint": "eslint --fix --ignore-path .eslintignore \"**/*.ts\""
+ },
+ "dependencies": {
+ "@effect/platform": "^0.58.27",
+ "@effect/platform-node": "^0.53.26",
+ "effect-http": "^0.73.0",
+ "effect-http-node": "^0.16.1"
+ }
}
diff --git a/e2e/mock-api-v2/project.json b/e2e/mock-api-v2/project.json
deleted file mode 100644
index 2d8ac9a4d..000000000
--- a/e2e/mock-api-v2/project.json
+++ /dev/null
@@ -1,86 +0,0 @@
-{
- "name": "mock-api-v2",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "sourceRoot": "e2e/mock-api-v2/src",
- "projectType": "application",
- "tags": ["e2e"],
- "targets": {
- "build": {
- "executor": "@nx/esbuild:esbuild",
- "outputs": ["{projectRoot}/dist"],
- "defaultConfiguration": "production",
- "options": {
- "platform": "node",
- "outputPath": "e2e/mock-api-v2/dist",
- "format": ["esm"],
- "bundle": true,
- "main": "e2e/mock-api-v2/src/main.ts",
- "tsConfig": "e2e/mock-api-v2/tsconfig.app.json",
- "assets": ["e2e/mock-api-v2/src/assets"],
- "generatePackageJson": false,
- "esbuildOptions": {
- "sourcemap": true,
- "outExtension": {
- ".js": ".js"
- }
- }
- },
- "configurations": {
- "development": {
- "watch": true
- },
- "example-server": {
- "main": "e2e/mock-api-v2/src/example-server.ts"
- },
- "production": {
- "esbuildOptions": {
- "sourcemap": false,
- "outExtension": {
- ".js": ".js"
- }
- }
- }
- }
- },
- "serve": {
- "executor": "@nx/js:node",
- "defaultConfiguration": "development",
- "options": {
- "buildTarget": "mock-api-v2:build"
- },
- "configurations": {
- "example-server": {
- "buildTarget": "mock-api-v2:build:example-server"
- },
- "production": {
- "buildTarget": "mock-api-v2:build:production"
- }
- }
- },
- "test": {
- "inputs": [
- "default",
- "^default",
- {
- "externalDependencies": ["vitest"]
- }
- ],
- "outputs": [
- "{projectRoot}/{options.coverage.reportsDirectory}",
- "{workspaceRoot}/coverage/e2e/mock-api-v2"
- ],
- "configurations": {
- "watch": {
- "watch": true
- }
- }
- },
- "lint": {
- "options": {
- "fix": true,
- "ignore-path": ".eslintignore",
- "args": ["**/*.ts"]
- }
- }
- }
-}
diff --git a/e2e/mock-api/src/app/.gitkeep b/e2e/mock-api-v2/src/index.css
similarity index 100%
rename from e2e/mock-api/src/app/.gitkeep
rename to e2e/mock-api-v2/src/index.css
diff --git a/e2e/mock-api-v2/tsconfig.app.json b/e2e/mock-api-v2/tsconfig.app.json
index 3debf0255..3a0569246 100644
--- a/e2e/mock-api-v2/tsconfig.app.json
+++ b/e2e/mock-api-v2/tsconfig.app.json
@@ -1,11 +1,11 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
- "outDir": "../../dist/out-tsc",
+ "outDir": "./dist",
"module": "Node16",
- "target": "ES2020",
- "declaration": true,
- "declarationMap": true,
+ "moduleResolution": "Node16",
+ "declaration": false,
+ "declarationMap": false,
"types": ["node"],
"exactOptionalPropertyTypes": true,
"strictNullChecks": true,
diff --git a/e2e/mock-api/.babelrc b/e2e/mock-api/.babelrc
deleted file mode 100644
index aed1b9711..000000000
--- a/e2e/mock-api/.babelrc
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "presets": [["@nx/js/babel", { "useBuiltIns": "entry" }]]
-}
diff --git a/e2e/mock-api/.eslintignore b/e2e/mock-api/.eslintignore
deleted file mode 100644
index 7787c22e4..000000000
--- a/e2e/mock-api/.eslintignore
+++ /dev/null
@@ -1,8 +0,0 @@
-node_modules
-*.md
-LICENSE
-.babelrc
-.env*
-.bin
-dist
-.eslintignore
\ No newline at end of file
diff --git a/e2e/mock-api/.eslintrc.json b/e2e/mock-api/.eslintrc.json
deleted file mode 100644
index 9d9c0db55..000000000
--- a/e2e/mock-api/.eslintrc.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "extends": ["../../.eslintrc.json"],
- "ignorePatterns": ["!**/*"],
- "overrides": [
- {
- "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
- "rules": {}
- },
- {
- "files": ["*.ts", "*.tsx"],
- "rules": {}
- },
- {
- "files": ["*.js", "*.jsx"],
- "rules": {}
- }
- ]
-}
diff --git a/e2e/mock-api/package.json b/e2e/mock-api/package.json
deleted file mode 100644
index 8180b1ce5..000000000
--- a/e2e/mock-api/package.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "name": "mock-api",
- "version": "0.0.0",
- "private": true,
- "description": "",
- "main": "./index.js",
- "keywords": [],
- "author": "",
- "type": "commonjs",
- "license": "ISC"
-}
diff --git a/e2e/mock-api/project.json b/e2e/mock-api/project.json
deleted file mode 100644
index c82029329..000000000
--- a/e2e/mock-api/project.json
+++ /dev/null
@@ -1,50 +0,0 @@
-{
- "name": "mock-api",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "sourceRoot": "e2e/mock-api/src",
- "projectType": "application",
- "tags": ["scope:e2e"],
- "targets": {
- "build": {
- "executor": "@nx/js:tsc",
- "outputs": ["{projectRoot}/dist"],
- "options": {
- "outputPath": "e2e/mock-api/dist",
- "main": "e2e/mock-api/src/index.js",
- "clean": true,
- "tsConfig": "e2e/mock-api/tsconfig.app.json",
- "assets": ["e2e/mock-api/src/assets", "e2e/mock-api/package.json"]
- },
- "configurations": {
- "development": {
- "watch": true
- },
- "production": {
- "optimization": true,
- "extractLicenses": true,
- "inspect": false,
- "fileReplacements": [
- {
- "replace": "e2e/mock-api/src/environments/environment.ts",
- "with": "e2e/mock-api/src/environments/environment.prod.ts"
- }
- ]
- }
- }
- },
- "serve": {
- "executor": "@nx/js:node",
- "outputs": ["{projectRoot}/dist"],
- "options": {
- "buildTarget": "mock-api:build"
- }
- },
- "lint": {
- "options": {
- "fix": true,
- "ignore-path": ".eslintignore",
- "args": ["**/*.ts"]
- }
- }
- }
-}
diff --git a/e2e/mock-api/src/app/app.auth.js b/e2e/mock-api/src/app/app.auth.js
deleted file mode 100644
index 45f75e3f5..000000000
--- a/e2e/mock-api/src/app/app.auth.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * app.auth.js
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import request from 'superagent';
-import { AM_URL, REALM_PATH } from './env.config.js';
-
-export let session;
-
-export async function authorizeApp({ un, pw }) {
- try {
- const response = await request
- .post(`${AM_URL}/json/realms/${REALM_PATH}/authenticate`)
- .set('Content-Type', 'application/json')
- .set('Accept-API-Version', 'resource=2.0, protocol=1.0')
- .set('X-OpenAM-Username', un)
- .set('X-OpenAM-Password', pw)
- .send({});
-
- session = response.body;
-
- console.log(`REST app identity token: ${session.tokenId}`);
-
- return session;
- } catch (error) {
- console.warn('\n###################################################');
- console.warn('WARNING: REST app user for Step Up/Txn Auth missing');
- console.warn('###################################################\n');
- }
-}
diff --git a/e2e/mock-api/src/app/constants.js b/e2e/mock-api/src/app/constants.js
deleted file mode 100644
index e9bba07ed..000000000
--- a/e2e/mock-api/src/app/constants.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * constants.js
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-export const authPaths = {
- tokenExchange: [
- '/am/auth/tokenExchange',
- '/am/oauth2/realms/root/access_token',
- '/am/oauth2/realms/root/realms/middleware/access_token',
- '/am/oauth2/realms/root/realms/middleware-modern/access_token',
- '/am/oauth2/realms/root/realms/tokens-expiring-soon/access_token',
- '/am/oauth2/realms/root/realms/tokens-expired/access_token',
- ],
- authenticate: [
- '/am/auth/authenticate',
- '/am/json/realms/root/authenticate',
- '/am/json/realms/root/realms/middleware/authenticate',
- '/am/json/realms/root/realms/tokens-expiring-soon/authenticate',
- '/am/json/realms/root/realms/tokens-expired/authenticate',
- ],
- htmlAuthenticate: ['/am/'],
- authorize: [
- '/am/auth/authorize',
- '/am/oauth2/realms/root/authorize',
- '/am/oauth2/realms/root/realms/middleware/authorize',
- '/am/oauth2/realms/root/realms/middleware-modern/authorize',
- '/am/oauth2/realms/root/realms/tokens-expiring-soon/authorize',
- '/am/oauth2/realms/root/realms/tokens-expired/authorize',
- ],
- endSession: [
- '/am/auth/endSession',
- '/am/oauth2/realms/root/connect/endSession',
- '/am/oauth2/realms/root/realms/middleware/connect/endSession',
- '/am/oauth2/realms/root/realms/tokens-expiring-soon/connect/endSession',
- '/am/oauth2/realms/root/realms/tokens-expired/connect/endSession',
- ],
- userInfo: [
- '/am/auth/userInfo',
- '/am/oauth2/realms/root/userinfo',
- '/am/oauth2/realms/root/realms/middleware/userinfo',
- '/am/oauth2/realms/root/realms/tokens-expiring-soon/userinfo',
- '/am/oauth2/realms/root/realms/tokens-expired/userinfo',
- ],
- revoke: [
- '/am/auth/revoke',
- '/am/oauth2/realms/root/token/revoke',
- '/am/oauth2/realms/root/realms/middleware/token/revoke',
- '/am/oauth2/realms/root/realms/tokens-expiring-soon/token/revoke',
- '/am/oauth2/realms/root/realms/tokens-expired/token/revoke',
- ],
- sessions: [
- '/am/auth/sessions',
- '/am/json/realms/root/sessions',
- '/am/json/realms/root/realms/middleware/sessions',
- '/am/json/realms/root/realms/tokens-expiring-soon/sessions',
- '/am/json/realms/root/realms/tokens-expired/sessions',
- ],
- accounts: ['/o/oauth2/v2/auth', '/SAMLFailure', '/SAMLTest'],
-};
diff --git a/e2e/mock-api/src/app/env.config.js b/e2e/mock-api/src/app/env.config.js
deleted file mode 100644
index c34d7c8de..000000000
--- a/e2e/mock-api/src/app/env.config.js
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * env.config.js
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { env } from 'process';
-
-/**
- * Configure your environment defaults below.
- */
-const oauth = {
- client: 'WebOAuthClient',
- scope: 'openid profile me.read',
-};
-const origins = {
- // Ensure all domains are added to the security cert creation
- app: process.env.NODE_ENV === 'LIVE' ? 'https://sdkapp.petrov.ca' : 'http://localhost',
- forgeops: 'https://default.forgeops.petrov.ca',
- mock: 'http://localhost',
- resource: 'http://localhost',
-};
-const paths = {
- am: '/am',
-};
-const ports = {
- app: '8443',
- forgeops: '443',
- mock: '9443',
- resource: '9443',
-};
-const realm = 'root';
-const testUsers = [
- {
- // Already exists in forgeops...
- pw: 'password',
- un: 'sdkuser',
- },
-];
-
-/**
- * The below will be composed of the above values.
- * Do not edit unless you know what you're doing.
- */
-let amUrl;
-let amPort;
-
-if (env.LIVE) {
- amUrl = origins.forgeops;
- amPort = ports.forgeops;
-} else {
- amUrl = origins.mock;
- amPort = ports.mock;
-}
-
-export const APP_PORT = ports.app;
-export const AM_PORT = amPort;
-export const MOCK_PORT = process.env.PORT || ports.mock;
-
-export const AM_URL = `${amUrl}:${amPort}${paths.am}`;
-export const BASE_URL = `${origins.app}:${ports.app}`;
-export const CLIENT_ID = oauth.client;
-export const FORGEOPS = origins.forgeops;
-export const REALM_PATH = realm;
-export const RESOURCE_URL = `${origins.resource}:${ports.resource}`;
-export const SCOPE = oauth.scope;
-export const USERS = testUsers;
diff --git a/e2e/mock-api/src/app/response.registration.js b/e2e/mock-api/src/app/response.registration.js
deleted file mode 100644
index 3ec70f2f9..000000000
--- a/e2e/mock-api/src/app/response.registration.js
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * response.registration.js
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-export default {
- authId: 'foo',
- callbacks: [
- {
- type: 'ValidatedCreateUsernameCallback',
- output: [
- {
- name: 'policies',
- value: [
- { policyId: 'unique' },
- { policyId: 'no-internal-user-conflict' },
- { policyId: 'cannot-contain-characters', params: { forbiddenChars: ['/'] } },
- ],
- },
- { name: 'failedPolicies', value: [] },
- { name: 'validateOnly', value: false },
- { name: 'prompt', value: 'Username' },
- ],
- input: [
- { name: 'IDToken1', value: '' },
- { name: 'IDToken1validateOnly', value: false },
- ],
- _id: 0,
- },
- {
- type: 'StringAttributeInputCallback',
- output: [
- { name: 'name', value: 'givenName' },
- { name: 'prompt', value: 'First Name' },
- { name: 'required', value: true },
- { name: 'policies', value: [] },
- { name: 'failedPolicies', value: [] },
- { name: 'validateOnly', value: false },
- { name: 'value', value: '' },
- ],
- input: [
- { name: 'IDToken2', value: '' },
- { name: 'IDToken2validateOnly', value: false },
- ],
- _id: 1,
- },
- {
- type: 'StringAttributeInputCallback',
- output: [
- { name: 'name', value: 'sn' },
- { name: 'prompt', value: 'Last Name' },
- { name: 'required', value: true },
- { name: 'policies', value: [] },
- { name: 'failedPolicies', value: [] },
- { name: 'validateOnly', value: false },
- { name: 'value', value: '' },
- ],
- input: [
- { name: 'IDToken3', value: '' },
- { name: 'IDToken3validateOnly', value: false },
- ],
- _id: 2,
- },
- // {
- // type: 'NumberAttributeInputCallback',
- // input: [
- // { name: 'IDToken4', value: null },
- // { name: 'IDToken4validateOnly', value: false },
- // ],
- // output: [
- // { name: 'name', value: 'age' },
- // { name: 'prompt', value: 'Age' },
- // { name: 'required', value: true },
- // {
- // name: 'policies',
- // value: {
- // policyRequirements: ['VALID_TYPE'],
- // fallbackPolicies: null,
- // name: 'age',
- // policies: [
- // {
- // policyRequirements: ['VALID_TYPE'],
- // policyId: 'valid-type',
- // params: { types: ['number'] },
- // },
- // ],
- // conditionalPolicies: null,
- // },
- // },
- // { name: 'failedPolicies', value: [] },
- // { name: 'validateOnly', value: false },
- // { name: 'value', value: null },
- // ],
- // },
- {
- type: 'StringAttributeInputCallback',
- output: [
- { name: 'name', value: 'mail' },
- { name: 'prompt', value: 'Email Address' },
- { name: 'required', value: true },
- { name: 'policies', value: [{ policyId: 'valid-email-address-format' }] },
- { name: 'failedPolicies', value: [] },
- { name: 'validateOnly', value: false },
- { name: 'value', value: '' },
- ],
- input: [
- { name: 'IDToken4', value: '' },
- { name: 'IDToken4validateOnly', value: false },
- ],
- _id: 3,
- },
- {
- type: 'BooleanAttributeInputCallback',
- output: [
- { name: 'name', value: 'preferences/marketing' },
- { name: 'prompt', value: 'Send me special offers and services' },
- { name: 'required', value: true },
- { name: 'policies', value: [] },
- { name: 'failedPolicies', value: [] },
- { name: 'validateOnly', value: false },
- { name: 'value', value: false },
- ],
- input: [
- { name: 'IDToken5', value: false },
- { name: 'IDToken5validateOnly', value: false },
- ],
- _id: 4,
- },
- {
- type: 'BooleanAttributeInputCallback',
- output: [
- { name: 'name', value: 'preferences/updates' },
- { name: 'prompt', value: 'Send me news and updates' },
- { name: 'required', value: true },
- { name: 'policies', value: [] },
- { name: 'failedPolicies', value: [] },
- { name: 'validateOnly', value: false },
- { name: 'value', value: false },
- ],
- input: [
- { name: 'IDToken6', value: false },
- { name: 'IDToken6validateOnly', value: false },
- ],
- _id: 5,
- },
- {
- type: 'ValidatedCreatePasswordCallback',
- output: [
- { name: 'echoOn', value: false },
- {
- name: 'policies',
- value: [
- { policyId: 'at-least-X-capitals', params: { numCaps: 1 } },
- { policyId: 'at-least-X-numbers', params: { numNums: 1 } },
- {
- policyId: 'cannot-contain-others',
- params: { disallowedFields: ['userName', 'givenName', 'sn'] },
- },
- ],
- },
- { name: 'failedPolicies', value: [] },
- { name: 'validateOnly', value: false },
- { name: 'prompt', value: 'Password' },
- ],
- input: [
- { name: 'IDToken7', value: '' },
- { name: 'IDToken7validateOnly', value: false },
- ],
- _id: 6,
- },
- {
- type: 'KbaCreateCallback',
- output: [
- { name: 'prompt', value: 'Select a security question' },
- {
- name: 'predefinedQuestions',
- value: [`What's your favorite color?`, 'Who was your first employer?'],
- },
- ],
- input: [
- { name: 'IDToken8question', value: '' },
- { name: 'IDToken8answer', value: '' },
- ],
- _id: 7,
- },
- {
- type: 'KbaCreateCallback',
- output: [
- { name: 'prompt', value: 'Select a security question' },
- {
- name: 'predefinedQuestions',
- value: [`What's your favorite color?`, 'Who was your first employer?'],
- },
- ],
- input: [
- { name: 'IDToken9question', value: '' },
- { name: 'IDToken9answer', value: '' },
- ],
- _id: 8,
- },
- {
- type: 'TermsAndConditionsCallback',
- output: [
- { name: 'version', value: '0.0' },
- {
- name: 'terms',
- // eslint-disable-next-line
- value:
- 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
- },
- { name: 'createDate', value: '2019-10-28T04:20:11.320Z' },
- ],
- input: [{ name: 'IDToken10', value: false }],
- _id: 9,
- },
- ],
- header: 'Sign Up',
- description: 'Already have an account? Sign In ',
-};
diff --git a/e2e/mock-api/src/app/responses.js b/e2e/mock-api/src/app/responses.js
deleted file mode 100644
index 12cc6173d..000000000
--- a/e2e/mock-api/src/app/responses.js
+++ /dev/null
@@ -1,1267 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * responses.js
- *
- * Copyright (c) 2020-2024 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { AM_URL, RESOURCE_URL } from './env.config.js';
-
-export const oauthTokens = {
- access_token: 'baz',
- refresh_token: 'qux',
- scope: 'openid profile me.read',
- id_token: 'mox',
- token_type: 'Bearer',
- expires_in: 3598,
-};
-
-export const oauthTokensExpiringSoon = {
- access_token: 'baz',
- refresh_token: 'qux',
- scope: 'openid profile me.read',
- id_token: 'mox',
- token_type: 'Bearer',
- expires_in: 20,
-};
-
-export const oauthTokensExpired = {
- access_token: 'baz',
- refresh_token: 'qux',
- scope: 'openid profile me.read',
- id_token: 'mox',
- token_type: 'Bearer',
- expires_in: 1,
-};
-
-export const authFail = {
- code: 401,
- message: 'Authentication Failed For Given Credentials',
-};
-
-export const authSuccess = {
- tokenId: 'bar',
- successUrl: '/console',
- realm: '/',
-};
-
-export const createTxnStepUpUrl = (url) => {
- console.log(url);
- // Grab the client's desired AM URL
- const referer = new URL(url);
- const amUrl = referer.searchParams.get('amUrl');
- // Create the redirect URL
- const redirectUrl = new URL(amUrl || AM_URL);
- redirectUrl.searchParams.set('goto', `${RESOURCE_URL}/ig`);
- redirectUrl.searchParams.set('realm', '/');
- redirectUrl.searchParams.set('authIndexType', 'composite_advice');
- redirectUrl.searchParams.set(
- 'authIndexValue',
- // eslint-disable-next-line max-len
- '%3CAdvices%3E%3CAttributeValuePair%3E%3CAttribute%20name%3D%22TransactionConditionAdvice%22/%3E%3CValue%3E39dfdd15-59a3-473c-a7fc-ecda3bbc3bc8%3C/Value%3E%3C/AttributeValuePair%3E%3C/Advices%3E',
- );
-
- return redirectUrl.toString();
-};
-
-export const createTreeStepUpUrl = (url) => {
- // Grab the client's desired AM URL
- const referer = new URL(url);
- const amUrl = referer.searchParams.get('amUrl');
- // Create the redirect URL
- const redirectUrl = new URL(amUrl || AM_URL);
- redirectUrl.searchParams.set('goto', `${RESOURCE_URL}/ig`);
- redirectUrl.searchParams.set('realm', '/');
- redirectUrl.searchParams.set('authIndexType', 'composite_advice');
- redirectUrl.searchParams.set(
- 'authIndexValue',
- // eslint-disable-next-line max-len
- '%3CAdvices%3E%3CAttributeValuePair%3E%3CAttribute%20name=%22AuthenticateToServiceConditionAdvice%22/%3E%3CValue%3E/sdk:ConfirmPassword%3C/Value%3E%3C/AttributeValuePair%3E%3C/Advices%3E',
- );
-
- return redirectUrl.toString();
-};
-
-export const createTxnStepUpHeader = (url) => {
- // Grab the client's desired AM URL
- const referer = new URL(url);
- const amUrl = referer.searchParams.get('amUrl') || AM_URL;
-
- // Base 64 of {"TransactionConditionAdvice":["39dfdd15-59a3-473c-a7fc-ecda3bbc3bc8"]}
- const advices =
- 'eyJUcmFuc2FjdGlvbkNvbmRpdGlvbkFkdmljZSI6WyIzOWRmZGQxNS01OWEzLTQ3M2MtYTdmYy1lY2RhM2JiYzNiYzgiXX0=';
- const realm = '/';
- const headerValue = `SSOADVICE realm="${realm}",advices="${advices}",am_uri="${amUrl}"`;
- return headerValue;
-};
-
-export const createTreeStepUpHeader = (url) => {
- // Grab the client's desired AM URL
- const referer = new URL(url);
- const amUrl = referer.searchParams.get('amUrl') || AM_URL;
-
- // Base 64 of {"AuthenticateToServiceConditionAdvice":["/sdk:ConfirmPassword"]}
- const advices =
- 'eyJBdXRoZW50aWNhdGVUb1NlcnZpY2VDb25kaXRpb25BZHZpY2UiOlsiL3NkazpDb25maXJtUGFzc3dvcmQiXX0=';
- const realm = '/';
- const headerValue = `SSOADVICE realm="${realm}",advices="${advices}",am_uri="${amUrl}"`;
- return headerValue;
-};
-
-export const authByTreeResponse = {
- resource: '',
- actions: {},
- attributes: {},
- advices: {
- AuthenticateToServiceConditionAdvice: ['/sdk:ConfirmPassword'],
- },
- ttl: 0,
-};
-
-export const authByTxnResponse = {
- resource: '',
- actions: {},
- attributes: {},
- advices: {
- TransactionConditionAdvice: ['39dfdd15-59a3-473c-a7fc-ecda3bbc3bc8'],
- },
- ttl: 0,
-};
-
-export const emailSuspend = {
- authId: 'foo',
- callbacks: [
- {
- type: 'SuspendedTextOutputCallback',
- output: [
- {
- name: 'message',
- value:
- // eslint-disable-next-line max-len
- 'An email has been sent to the address you entered. Click the link in that email to proceed.',
- },
- { name: 'messageType', value: '0' },
- ],
- },
- ],
-};
-
-export const idpChoiceCallback = {
- authId: 'foo',
- callbacks: [
- {
- type: 'ChoiceCallback',
- output: [
- { name: 'prompt', value: 'Select Provider' },
- { name: 'choices', value: ['google', 'facebook'] },
- { name: 'defaultChoice', value: 0 },
- ],
- input: [{ name: 'IDToken1', value: 0 }],
- },
- ],
-};
-export const nameCallback = {
- authId: 'foo',
- callbacks: [
- {
- type: 'NameCallback',
- output: [{ name: 'prompt', value: 'User Name' }],
- input: [{ name: 'IDToken1', value: '' }],
- _id: 0,
- },
- ],
-};
-export const textInputCallback = {
- authId: 'foo',
- callbacks: [
- {
- type: 'TextInputCallback',
- output: [
- {
- name: 'prompt',
- value: 'Provide a nickname for this account',
- },
- ],
- input: [
- {
- name: 'IDToken1',
- value: '',
- },
- ],
- },
- ],
-};
-
-export const initialBasicLogin = {
- authId: 'foo',
- callbacks: [
- {
- type: 'NameCallback',
- output: [{ name: 'prompt', value: 'User Name' }],
- input: [{ name: 'IDToken1', value: '' }],
- _id: 0,
- },
- {
- type: 'PasswordCallback',
- output: [{ name: 'prompt', value: 'Password' }],
- input: [{ name: 'IDToken2', value: '' }],
- _id: 1,
- },
- ],
- stage: 'UsernamePassword',
-};
-
-export const initialLoginWithEmailResponse = {
- authId: 'foo',
- callbacks: [
- {
- type: 'ValidatedCreateUsernameCallback',
- output: [
- { name: 'policies', value: {} },
- { name: 'failedPolicies', value: [] },
- { name: 'validateOnly', value: false },
- { name: 'prompt', value: 'Username' },
- ],
- input: [
- { name: 'IDToken1', value: '' },
- { name: 'IDToken1validateOnly', value: false },
- ],
- },
- ],
-};
-
-export const initialPlatformLogin = {
- authId: 'foo',
- callbacks: [
- {
- type: 'ValidatedCreateUsernameCallback',
- input: [
- { name: 'IDToken1', value: '' },
- { name: 'IDToken1validateOnly', value: false },
- ],
- output: [
- { name: 'policies', value: [] },
- { name: 'failedPolicies', value: [] },
- { name: 'validateOnly', value: false },
- { name: 'prompt', value: 'Username' },
- ],
- _id: 0,
- },
- {
- type: 'ValidatedCreatePasswordCallback',
- output: [{ name: 'prompt', value: 'Password' }],
- input: [
- { name: 'IDToken2', value: '' },
- { name: 'IDToken2validateOnly', value: false },
- ],
- _id: 1,
- },
- ],
- stage: 'UsernamePassword',
-};
-
-export const initialMiscCallbacks = {
- authId: 'foo',
- callbacks: [
- {
- type: 'NameCallback',
- output: [{ name: 'prompt', value: 'User Name' }],
- input: [{ name: 'IDToken1', value: '' }],
- },
- ],
-};
-
-export const passwordCallback = {
- authId: 'foo',
- callbacks: [
- {
- type: 'PasswordCallback',
- output: [{ name: 'prompt', value: 'Password' }],
- input: [{ name: 'IDToken1', value: '' }],
- },
- ],
-};
-
-export const pingProtectEvaluate = {
- authId: 'foo',
- callbacks: [
- {
- type: 'PingOneProtectEvaluationCallback',
- output: [
- {
- name: 'pauseBehavioralData',
- value: true,
- },
- ],
- input: [
- {
- name: 'IDToken1signals',
- value: '',
- },
- {
- name: 'IDToken1clientError',
- value: '',
- },
- ],
- },
- ],
-};
-
-export const pingProtectInitialize = {
- authId: 'foo',
- callbacks: [
- {
- type: 'PingOneProtectInitializeCallback',
- output: [
- {
- name: 'envId',
- value: '02fb1243-189a-4bc7-9d6c-a919edf6447',
- },
- {
- name: 'consoleLogEnabled',
- value: true,
- },
- {
- name: 'deviceAttributesToIgnore',
- value: ['userAgent'],
- },
- {
- name: 'customHost',
- value: 'http://localhost',
- },
- {
- name: 'lazyMetadata',
- value: false,
- },
- {
- name: 'behavioralDataCollection',
- value: true,
- },
- {
- name: 'deviceKeyRsyncIntervals',
- value: 14,
- },
- {
- name: 'enableTrust',
- value: false,
- },
- {
- name: 'disableTags',
- value: false,
- },
- {
- name: 'disableHub',
- value: false,
- },
- ],
- input: [
- {
- name: 'IDToken1clientError',
- value: '',
- },
- ],
- },
- ],
-};
-
-export const choiceCallback = {
- authId: 'foo',
- callbacks: [
- {
- type: 'ChoiceCallback',
- output: [
- { name: 'prompt', value: 'Choose your color' },
- { name: 'choices', value: ['red', 'green', 'blue'] },
- { name: 'defaultChoice', value: 0 },
- ],
- input: [{ name: 'IDToken1', value: 0 }],
- },
- ],
-};
-
-export const secondFactorChoiceCallback = {
- authId: 'foo',
- callbacks: [
- {
- type: 'ChoiceCallback',
- output: [
- { name: 'prompt', value: 'Choose Second Factor' },
- { name: 'choices', value: ['Email', 'SMS'] },
- { name: 'defaultChoice', value: 0 },
- ],
- input: [{ name: 'IDToken1', value: 0 }],
- },
- ],
-};
-
-export const messageCallback = {
- authId: 'foo',
- callbacks: [
- {
- type: 'TextOutputCallback',
- output: [
- { name: 'message', value: 'Is it true?' },
- { name: 'messageType', value: '0' },
- ],
- },
- {
- type: 'ConfirmationCallback',
- output: [
- { name: 'prompt', value: '' },
- { name: 'messageType', value: 0 },
- { name: 'options', value: ['Yes', 'No'] },
- { name: 'optionType', value: -1 },
- { name: 'defaultOption', value: 1 },
- ],
- input: [{ name: 'IDToken2', value: 0 }],
- },
- ],
-};
-
-export const noSessionSuccess = { successUrl: '/am/console', realm: '/' };
-
-export const pollingCallback = {
- authId: 'foo',
- callbacks: [
- {
- type: 'PollingWaitCallback',
- output: [
- { name: 'waitTime', value: '1000' },
- { name: 'message', value: 'Waiting for response...' },
- ],
- },
- ],
-};
-
-export const selectIdPCallback = {
- authId: 'foo',
- callbacks: [
- {
- type: 'SelectIdPCallback',
- output: [
- {
- name: 'providers',
- value: [
- {
- provider: 'google',
- uiConfig: {
- buttonImage: 'images/g-logo.png',
- buttonCustomStyle: 'background-color: #fff; color: #757575; border-color: #ddd;',
- buttonClass: '',
- buttonCustomStyleHover:
- 'color: #6d6d6d; background-color: #eee; border-color: #ccc;',
- buttonDisplayName: 'Google',
- iconFontColor: 'white',
- iconClass: 'fa-google',
- iconBackground: '#4184f3',
- },
- },
- {
- provider: 'facebook',
- uiConfig: {
- buttonImage: '',
- buttonCustomStyle: 'background-color: #3b5998;border-color: #3b5998; color: white;',
- buttonClass: 'fa-facebook-official',
- buttonCustomStyleHover:
- 'background-color: #334b7d;border-color: #334b7d; color: white;',
- buttonDisplayName: 'Facebook',
- iconFontColor: 'white',
- iconClass: 'fa-facebook',
- iconBackground: '#3b5998',
- },
- },
- { provider: 'localAuthentication' },
- ],
- },
- { name: 'value', value: '' },
- ],
- input: [{ name: 'IDToken1', value: '' }],
- _id: 0,
- },
- ],
-};
-
-export const secondFactorCallback = {
- authId: 'foo',
- callbacks: [
- {
- type: 'PasswordCallback',
- output: [{ name: 'prompt', value: 'One Time Password' }],
- input: [{ name: 'IDToken1', value: '' }],
- _id: 0,
- },
- ],
- stage: 'OneTimePasswordEmail',
-};
-
-export const otpQRCodeCallbacks = {
- authId: 'foo',
- callbacks: [
- {
- type: 'TextOutputCallback',
- output: [
- {
- name: 'message',
- value:
- 'Scan the QR code image below with the ForgeRock Authenticator app to register your device with your login.',
- },
- {
- name: 'messageType',
- value: '0',
- },
- ],
- },
- {
- type: 'TextOutputCallback',
- output: [
- {
- name: 'message',
- value:
- // eslint-disable-next-line quotes
- "window.QRCodeReader.createCode({\n id: 'callback_0',\n text: 'otpauth\\x3A\\x2F\\x2Ftotp\\x2FForgeRock\\x3Ajlowery\\x3Fperiod\\x3D30\\x26b\\x3D032b75\\x26digits\\x3D6\\x26secret\\QITSTC234FRIU8DD987DW3VPICFY\\x3D\\x3D\\x3D\\x3D\\x3D\\x3D\\x26issuer\\x3DForgeRock',\n version: '20',\n code: 'L'\n});",
- },
- {
- name: 'messageType',
- value: '4',
- },
- ],
- },
- {
- type: 'HiddenValueCallback',
- output: [
- {
- name: 'value',
- value:
- 'otpauth://totp/ForgeRock:jlowery?secret=QITSTC234FRIU8DD987DW3VPICFY======&issuer=ForgeRock&period=30&digits=6&b=032b75',
- },
- {
- name: 'id',
- value: 'mfaDeviceRegistration',
- },
- ],
- input: [
- {
- name: 'IDToken3',
- value: 'mfaDeviceRegistration',
- },
- ],
- },
- {
- type: 'ConfirmationCallback',
- output: [
- {
- name: 'prompt',
- value: '',
- },
- {
- name: 'messageType',
- value: 0,
- },
- {
- name: 'options',
- value: ['Next'],
- },
- {
- name: 'optionType',
- value: -1,
- },
- {
- name: 'defaultOption',
- value: 0,
- },
- ],
- input: [
- {
- name: 'IDToken4',
- value: 0,
- },
- ],
- },
- ],
-};
-
-export const redirectCallback = {
- authId: 'foo',
- callbacks: [
- {
- type: 'RedirectCallback',
- output: [
- {
- name: 'redirectUrl',
- value:
- // eslint-disable-next-line max-len
- 'http://localhost:9443/o/oauth2/v2/auth?nonce=ko7fdf2v3b6yctgq35bdpndel0p9qiq&response_type=code&client_id=546064052569-ke17g9ufsmvda3kgg7s5kp2hpf3gnqi8.apps.googleusercontent.com&scope=openid%20profile%20email&code_challenge=Bh_6aMiI04KGI1wVILtEamByklmXnQY9JKhKhlwsIxk&code_challenge_method=S256&state=rtu8pz65dbg6baw985d532myfbbnf5v',
- },
- { name: 'redirectMethod', value: 'GET' },
- { name: 'trackingCookie', value: true },
- ],
- },
- ],
-};
-export const redirectCallbackSaml = {
- authId: 'foo',
- callbacks: [
- {
- type: 'RedirectCallback',
- output: [
- {
- name: 'redirectUrl',
- value:
- // eslint-disable-next-line max-len
- 'http://localhost:9443/SAMLTest/',
- },
- { name: 'redirectMethod', value: 'GET' },
- { name: 'trackingCookie', value: true },
- ],
- },
- ],
-};
-export const redirectCallbackFailureSaml = {
- authId: 'foo',
- callbacks: [
- {
- type: 'RedirectCallback',
- output: [
- {
- name: 'redirectUrl',
- value:
- // eslint-disable-next-line max-len
- 'http://localhost:9443/SAMLFailure',
- },
- { name: 'redirectMethod', value: 'GET' },
- { name: 'trackingCookie', value: true },
- ],
- },
- ],
-};
-export const txnAuthz = {
- authId: 'bar',
- callbacks: [
- {
- type: 'PasswordCallback',
- output: [{ name: 'prompt', value: 'Password' }],
- input: [{ name: 'IDToken2', value: '' }],
- _id: 1,
- },
- ],
- stage: 'TransactionAuthorization',
-};
-export const treeAuthz = {
- authId: 'bar',
- callbacks: [
- {
- type: 'PasswordCallback',
- output: [{ name: 'prompt', value: 'Password' }],
- input: [{ name: 'IDToken2', value: '' }],
- _id: 1,
- },
- ],
- stage: 'TreeBasedAuthorization',
-};
-
-export const userInfo = {
- family_name: 'Tester',
- given_name: 'Bob',
- name: 'Bob Tester',
- updated_at: 1575671644,
- sub: 'thetester',
-};
-
-export const requestDeviceProfile = {
- authId: 'foo',
- callbacks: [
- {
- type: 'DeviceProfileCallback',
- output: [
- {
- name: 'metadata',
- value: true,
- },
- {
- name: 'location',
- value: true,
- },
- {
- name: 'message',
- value: 'Collecting profile ...',
- },
- ],
- input: [
- {
- name: 'IDToken1',
- value: '',
- },
- ],
- },
- ],
-};
-
-export const wellKnownForgeRock = {
- request_parameter_supported: true,
- pushed_authorization_request_endpoint: 'http://localhost:9443/am/oauth2/realms/root/par',
- introspection_encryption_alg_values_supported: [
- 'ECDH-ES+A256KW',
- 'ECDH-ES+A192KW',
- 'RSA-OAEP',
- 'ECDH-ES+A128KW',
- 'RSA-OAEP-256',
- 'A128KW',
- 'A256KW',
- 'ECDH-ES',
- 'dir',
- 'A192KW',
- ],
- claims_parameter_supported: false,
- introspection_endpoint: 'http://localhost:9443/am/oauth2/realms/root/introspect',
- issuer: 'http://localhost:9443/am/oauth2/realms/root',
- id_token_encryption_enc_values_supported: [
- 'A256GCM',
- 'A192GCM',
- 'A128GCM',
- 'A128CBC-HS256',
- 'A192CBC-HS384',
- 'A256CBC-HS512',
- ],
- userinfo_encryption_enc_values_supported: [
- 'A256GCM',
- 'A192GCM',
- 'A128GCM',
- 'A128CBC-HS256',
- 'A192CBC-HS384',
- 'A256CBC-HS512',
- ],
- authorization_endpoint: 'http://localhost:9443/am/oauth2/realms/root/authorize',
- authorization_encryption_alg_values_supported: [
- 'ECDH-ES+A256KW',
- 'ECDH-ES+A192KW',
- 'RSA-OAEP',
- 'ECDH-ES+A128KW',
- 'RSA-OAEP-256',
- 'A128KW',
- 'A256KW',
- 'ECDH-ES',
- 'dir',
- 'A192KW',
- ],
- introspection_encryption_enc_values_supported: [
- 'A256GCM',
- 'A192GCM',
- 'A128GCM',
- 'A128CBC-HS256',
- 'A192CBC-HS384',
- 'A256CBC-HS512',
- ],
- claims_supported: [],
- rcs_request_signing_alg_values_supported: [
- 'PS384',
- 'ES384',
- 'RS384',
- 'HS256',
- 'HS512',
- 'ES256',
- 'RS256',
- 'HS384',
- 'ES512',
- 'PS256',
- 'PS512',
- 'RS512',
- ],
- token_endpoint_auth_methods_supported: [
- 'client_secret_post',
- 'private_key_jwt',
- 'self_signed_tls_client_auth',
- 'tls_client_auth',
- 'none',
- 'client_secret_basic',
- ],
- tls_client_certificate_bound_access_tokens: true,
- response_modes_supported: [
- 'fragment.jwt',
- 'form_post',
- 'form_post.jwt',
- 'jwt',
- 'fragment',
- 'query.jwt',
- 'query',
- ],
- backchannel_logout_session_supported: true,
- token_endpoint: 'http://localhost:9443/am/oauth2/realms/root/access_token',
- response_types_supported: [
- 'code token id_token',
- 'code',
- 'code id_token',
- 'device_code',
- 'id_token',
- 'code token',
- 'token',
- 'token id_token',
- ],
- authorization_encryption_enc_values_supported: [
- 'A256GCM',
- 'A192GCM',
- 'A128GCM',
- 'A128CBC-HS256',
- 'A192CBC-HS384',
- 'A256CBC-HS512',
- ],
- revocation_endpoint_auth_methods_supported: [
- 'client_secret_post',
- 'private_key_jwt',
- 'self_signed_tls_client_auth',
- 'tls_client_auth',
- 'none',
- 'client_secret_basic',
- ],
- request_uri_parameter_supported: true,
- grant_types_supported: [
- 'implicit',
- 'urn:ietf:params:oauth:grant-type:saml2-bearer',
- 'refresh_token',
- 'password',
- 'client_credentials',
- 'urn:ietf:params:oauth:grant-type:device_code',
- 'authorization_code',
- 'urn:openid:params:grant-type:ciba',
- 'urn:ietf:params:oauth:grant-type:uma-ticket',
- 'urn:ietf:params:oauth:grant-type:jwt-bearer',
- ],
- version: '3.0',
- prompt_values_supported: ['none', 'login', 'consent'],
- userinfo_endpoint: 'http://localhost:9443/am/oauth2/realms/root/userinfo',
- require_request_uri_registration: true,
- code_challenge_methods_supported: ['plain', 'S256'],
- id_token_encryption_alg_values_supported: [
- 'ECDH-ES+A256KW',
- 'ECDH-ES+A192KW',
- 'RSA-OAEP',
- 'ECDH-ES+A128KW',
- 'RSA-OAEP-256',
- 'A128KW',
- 'A256KW',
- 'ECDH-ES',
- 'dir',
- 'A192KW',
- ],
- authorization_signing_alg_values_supported: [
- 'PS384',
- 'RS384',
- 'EdDSA',
- 'ES384',
- 'HS256',
- 'HS512',
- 'ES256',
- 'RS256',
- 'HS384',
- 'ES512',
- 'PS256',
- 'PS512',
- 'RS512',
- ],
- request_object_signing_alg_values_supported: [
- 'PS384',
- 'ES384',
- 'RS384',
- 'HS256',
- 'HS512',
- 'ES256',
- 'RS256',
- 'HS384',
- 'ES512',
- 'PS256',
- 'PS512',
- 'RS512',
- ],
- request_object_encryption_alg_values_supported: [
- 'ECDH-ES+A256KW',
- 'ECDH-ES+A192KW',
- 'ECDH-ES+A128KW',
- 'RSA-OAEP',
- 'RSA-OAEP-256',
- 'A128KW',
- 'A256KW',
- 'ECDH-ES',
- 'dir',
- 'A192KW',
- ],
- rcs_response_signing_alg_values_supported: [
- 'PS384',
- 'ES384',
- 'RS384',
- 'HS256',
- 'HS512',
- 'ES256',
- 'RS256',
- 'HS384',
- 'ES512',
- 'PS256',
- 'PS512',
- 'RS512',
- ],
- introspection_signing_alg_values_supported: [
- 'PS384',
- 'RS384',
- 'EdDSA',
- 'ES384',
- 'HS256',
- 'HS512',
- 'ES256',
- 'RS256',
- 'HS384',
- 'ES512',
- 'PS256',
- 'PS512',
- 'RS512',
- ],
- check_session_iframe: 'http://localhost:9443/am/oauth2/realms/root/connect/checkSession',
- scopes_supported: [
- 'address',
- 'phone',
- 'openid',
- 'profile',
- 'fr:idm:*',
- 'am-introspect-all-tokens',
- 'email',
- ],
- backchannel_logout_supported: true,
- acr_values_supported: [],
- request_object_encryption_enc_values_supported: [
- 'A256GCM',
- 'A192GCM',
- 'A128GCM',
- 'A128CBC-HS256',
- 'A192CBC-HS384',
- 'A256CBC-HS512',
- ],
- rcs_request_encryption_alg_values_supported: [
- 'ECDH-ES+A256KW',
- 'ECDH-ES+A192KW',
- 'RSA-OAEP',
- 'ECDH-ES+A128KW',
- 'RSA-OAEP-256',
- 'A128KW',
- 'A256KW',
- 'ECDH-ES',
- 'dir',
- 'A192KW',
- ],
- userinfo_signing_alg_values_supported: [
- 'ES384',
- 'HS256',
- 'HS512',
- 'ES256',
- 'RS256',
- 'HS384',
- 'ES512',
- ],
- require_pushed_authorization_requests: false,
- rcs_response_encryption_enc_values_supported: [
- 'A256GCM',
- 'A192GCM',
- 'A128GCM',
- 'A128CBC-HS256',
- 'A192CBC-HS384',
- 'A256CBC-HS512',
- ],
- userinfo_encryption_alg_values_supported: [
- 'ECDH-ES+A256KW',
- 'ECDH-ES+A192KW',
- 'RSA-OAEP',
- 'ECDH-ES+A128KW',
- 'RSA-OAEP-256',
- 'A128KW',
- 'A256KW',
- 'ECDH-ES',
- 'dir',
- 'A192KW',
- ],
- end_session_endpoint: 'http://localhost:9443/am/oauth2/realms/root/connect/endSession',
- rcs_request_encryption_enc_values_supported: [
- 'A256GCM',
- 'A192GCM',
- 'A128GCM',
- 'A128CBC-HS256',
- 'A192CBC-HS384',
- 'A256CBC-HS512',
- ],
- revocation_endpoint: 'http://localhost:9443/am/oauth2/realms/root/token/revoke',
- rcs_response_encryption_alg_values_supported: [
- 'ECDH-ES+A256KW',
- 'ECDH-ES+A192KW',
- 'ECDH-ES+A128KW',
- 'RSA-OAEP',
- 'RSA-OAEP-256',
- 'A128KW',
- 'A256KW',
- 'ECDH-ES',
- 'dir',
- 'A192KW',
- ],
- token_endpoint_auth_signing_alg_values_supported: [
- 'PS384',
- 'ES384',
- 'RS384',
- 'HS256',
- 'HS512',
- 'ES256',
- 'RS256',
- 'HS384',
- 'ES512',
- 'PS256',
- 'PS512',
- 'RS512',
- ],
- jwks_uri: 'http://localhost:9443/am/oauth2/realms/root/connect/jwk_uri',
- subject_types_supported: ['public', 'pairwise'],
- id_token_signing_alg_values_supported: [
- 'PS384',
- 'ES384',
- 'RS384',
- 'HS256',
- 'HS512',
- 'ES256',
- 'RS256',
- 'HS384',
- 'ES512',
- 'PS256',
- 'PS512',
- 'RS512',
- ],
- registration_endpoint: 'http://localhost:9443/am/oauth2/realms/root/register',
-};
-
-export const wellKnownPing = {
- issuer: 'https://ping.example.com:9443/02fb4743-189a-4bc7-9d6c-a919edfe6447/as',
- authorization_endpoint:
- 'https://ping.example.com:9443/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/authorize',
- pushed_authorization_request_endpoint:
- 'https://ping.example.com:9443/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/par',
- token_endpoint: 'https://ping.example.com:9443/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/token',
- userinfo_endpoint:
- 'https://ping.example.com:9443/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/userinfo',
- jwks_uri: 'https://ping.example.com:9443/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/jwks',
- end_session_endpoint:
- 'https://ping.example.com:9443/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/signoff',
- introspection_endpoint:
- 'https://ping.example.com:9443/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/introspect',
- revocation_endpoint:
- 'https://ping.example.com:9443/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/revoke',
- device_authorization_endpoint:
- 'https://ping.example.com:9443/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/device_authorization',
- claims_parameter_supported: false,
- request_parameter_supported: true,
- request_uri_parameter_supported: false,
- require_pushed_authorization_requests: false,
- scopes_supported: ['openid', 'profile', 'email', 'address', 'phone'],
- response_types_supported: [
- 'code',
- 'id_token',
- 'token id_token',
- 'code id_token',
- 'code token',
- 'code token id_token',
- ],
- response_modes_supported: ['pi.flow', 'query', 'fragment', 'form_post'],
- grant_types_supported: [
- 'authorization_code',
- 'implicit',
- 'client_credentials',
- 'refresh_token',
- 'urn:ietf:params:oauth:grant-type:device_code',
- ],
- subject_types_supported: ['public'],
- id_token_signing_alg_values_supported: ['RS256'],
- userinfo_signing_alg_values_supported: ['none'],
- request_object_signing_alg_values_supported: [
- 'none',
- 'HS256',
- 'HS384',
- 'HS512',
- 'RS256',
- 'RS384',
- 'RS512',
- ],
- token_endpoint_auth_methods_supported: [
- 'client_secret_basic',
- 'client_secret_post',
- 'client_secret_jwt',
- 'private_key_jwt',
- ],
- token_endpoint_auth_signing_alg_values_supported: [
- 'HS256',
- 'HS384',
- 'HS512',
- 'RS256',
- 'RS384',
- 'RS512',
- ],
- claim_types_supported: ['normal'],
- claims_supported: [
- 'sub',
- 'iss',
- 'auth_time',
- 'acr',
- 'name',
- 'given_name',
- 'family_name',
- 'middle_name',
- 'preferred_username',
- 'profile',
- 'picture',
- 'zoneinfo',
- 'phone_number',
- 'updated_at',
- 'address',
- 'email',
- 'locale',
- ],
- code_challenge_methods_supported: ['plain', 'S256'],
-};
-
-export const MetadataMarketPlaceInitialize = {
- authId: 'foo',
- callbacks: [
- {
- type: 'MetadataCallback',
- output: [
- {
- name: 'data',
- value: {
- _type: 'PingOneProtect',
- _action: 'protect_initialize',
- envId: 'some_id',
- consoleLogEnabled: true,
- deviceAttributesToIgnore: [],
- customHost: '',
- lazyMetadata: true,
- behavioralDataCollection: true,
- disableHub: true,
- deviceKeyRsyncIntervals: 10,
- enableTrust: true,
- disableTags: true,
- },
- },
- ],
- },
- {
- type: 'HiddenValueCallback',
- output: [
- {
- name: 'value',
- value: '',
- },
- {
- name: 'id',
- value: 'clientError',
- },
- ],
- input: [
- {
- name: 'IDToken1',
- value: '',
- },
- ],
- },
- ],
-};
-
-export const MetadataMarketPlacePingOneEvaluation = {
- authId: 'foo',
- callbacks: [
- {
- type: 'MetadataCallback',
- output: [
- {
- name: 'data',
- value: {
- _type: 'PingOneProtect',
- _action: 'protect_risk_evaluation',
- envId: 'some_id',
- pauseBehavioralData: true,
- },
- },
- ],
- },
- {
- type: 'HiddenValueCallback',
- output: [
- {
- name: 'value',
- value: '',
- },
- {
- name: 'id',
- value: 'pingone_risk_evaluation_signals',
- },
- ],
- input: [
- {
- name: 'IDToken1',
- value: 'pingone_risk_evaluation_signals',
- },
- ],
- },
- {
- type: 'HiddenValueCallback',
- output: [
- {
- name: 'value',
- value: '',
- },
- {
- name: 'id',
- value: 'clientError',
- },
- ],
- input: [
- {
- name: 'IDToken1',
- value: '',
- },
- ],
- },
- ],
-};
-
-export const recaptchaEnterpriseCallback = {
- authId: 'foo',
- callbacks: [
- {
- type: 'ReCaptchaEnterpriseCallback',
- output: [
- {
- name: 'recaptchaSiteKey',
- value: '6LdSu_spAAAAAKz3UhIy4JYQld2lm_WRt7dEhf9T',
- },
- {
- name: 'captchaApiUri',
- value: 'https://www.google.com/recaptcha/enterprise.js',
- },
- {
- name: 'captchaDivClass',
- value: 'g-recaptcha',
- },
- ],
- input: [
- {
- name: 'IDToken1token',
- value: '',
- },
- {
- name: 'IDToken1action',
- value: '',
- },
- {
- name: 'IDToken1clientError',
- value: '',
- },
- {
- name: 'IDToken1payload',
- value: '',
- },
- ],
- },
- ],
-};
diff --git a/e2e/mock-api/src/app/routes.auth.js b/e2e/mock-api/src/app/routes.auth.js
deleted file mode 100644
index 95768433d..000000000
--- a/e2e/mock-api/src/app/routes.auth.js
+++ /dev/null
@@ -1,641 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * routes.auth.js
- *
- * Copyright (c) 2020-2024 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { v4 } from 'uuid';
-import { authPaths } from './constants.js';
-import { AM_URL, USERS } from './env.config.js';
-import {
- oauthTokens,
- authFail,
- authSuccess,
- emailSuspend,
- idpChoiceCallback,
- initialBasicLogin,
- initialLoginWithEmailResponse,
- initialMiscCallbacks,
- initialPlatformLogin,
- passwordCallback,
- choiceCallback,
- messageCallback,
- noSessionSuccess,
- pollingCallback,
- pingProtectEvaluate,
- pingProtectInitialize,
- redirectCallback,
- redirectCallbackSaml,
- requestDeviceProfile,
- secondFactorCallback,
- secondFactorChoiceCallback,
- selectIdPCallback,
- userInfo,
- oauthTokensExpiringSoon,
- oauthTokensExpired,
- nameCallback,
- redirectCallbackFailureSaml,
- textInputCallback,
- treeAuthz,
- txnAuthz,
- otpQRCodeCallbacks,
- wellKnownForgeRock,
- wellKnownPing,
- recaptchaEnterpriseCallback,
- MetadataMarketPlaceInitialize,
- MetadataMarketPlacePingOneEvaluation,
-} from './responses.js';
-import initialRegResponse from './response.registration.js';
-import wait from './wait.js';
-
-console.log(`Your user password from 'env.config' file: ${USERS[0].pw}`);
-
-export const baz = {
- canWithdraw: false,
-};
-
-export default function (app) {
- app.post(authPaths.authenticate, wait, async (req, res) => {
- if (!req.body.callbacks) {
- if (req.query.authIndexType === 'composite_advice') {
- if (req.query.authIndexValue.includes('TransactionConditionAdvice')) {
- res.json(txnAuthz);
- } else if (req.query.authIndexValue.includes('AuthenticateToServiceConditionAdvice')) {
- res.json(treeAuthz);
- }
- } else if (req.query.authIndexValue === 'MiscCallbacks') {
- res.json(initialMiscCallbacks);
- } else if (req.query.authIndexValue === 'PlatformUsernamePasswordTest') {
- res.json(initialPlatformLogin);
- } else if (req.query.authIndexValue === 'Registration') {
- res.json(initialRegResponse);
- } else if (req.query.authIndexValue === 'LoginWithEmail') {
- if (typeof req.query.suspendedId === 'string' && req.query.suspendedId.length) {
- res.cookie('iPlanetDirectoryPro', 'abcd1234', { domain: 'localhost' });
- res.json(authSuccess);
- } else {
- res.json(initialLoginWithEmailResponse);
- }
- } else if (
- req.query.authIndexValue === 'SAMLTest' ||
- req.query.authIndexValue === 'SAMLFailure'
- ) {
- res.json(nameCallback);
- } else if (req.query.authIndexValue === 'TEST_LoginPingProtect') {
- res.json(pingProtectInitialize);
- } else if (req.query.authIndexValue === 'IDMSocialLogin') {
- res.json(selectIdPCallback);
- } else if (req.query.authIndexValue === 'TEST_MetadataMarketPlace') {
- res.json(MetadataMarketPlaceInitialize);
- } else if (req.query.authIndexValue === 'AMSocialLogin') {
- res.json(idpChoiceCallback);
- } else if (req.query.authIndexValue === 'RecaptchaEnterprise') {
- res.json(initialBasicLogin);
- } else {
- if (req.path.includes('middleware')) {
- if (
- req.query['start-authenticate-middleware'] === 'start-authentication' &&
- req.headers['x-start-authenticate-middleware'] === 'start-authentication' &&
- !req.headers['x-logout-middleware'] &&
- !req.query['logout-middleware']
- ) {
- res.json(initialBasicLogin);
- } else {
- res.status(406).send('Middleware additions are missing.');
- }
- } else {
- res.json(initialBasicLogin);
- }
- }
- } else if (req.query.authIndexValue === 'LoginWithEmail') {
- res.json(emailSuspend);
- } else if (req.query.authIndexValue === 'RecaptchaEnterprise') {
- console.log(req.body.callbacks);
- if (req.body.callbacks[0].type === 'NameCallback') {
- const [username, password] = req.body.callbacks;
- if (username && username.type === 'NameCallback' && username.input[0].value === 'demo') {
- if (
- password &&
- password.type === 'PasswordCallback' &&
- password.input[0].value === 'Password'
- ) {
- res.json(recaptchaEnterpriseCallback);
- }
- }
- } else {
- const [captcha] = req.body.callbacks;
- if (captcha && captcha.input[0].value === '123') {
- res.json(authSuccess);
- }
- }
- } else if (req.query.authIndexValue === 'TEST_MetadataMarketPlace') {
- if (req.body.callbacks.find((cb) => cb.type === 'MetadataCallback')) {
- const metadataCb = req.body.callbacks.find((cb) => cb.type === 'MetadataCallback');
- const action = metadataCb.output[0].value._action;
- console.log('the action', action);
- if (action === 'protect_initialize') {
- if (req.body.callbacks.find((cb) => cb.type === 'HiddenValueCallback')) {
- const hiddenCb = req.body.callbacks.find((cb) => cb.type === 'HiddenValueCallback');
- if (hiddenCb.input[0].value === 'we had an error') {
- return res.json(authFail);
- }
- return res.json(MetadataMarketPlacePingOneEvaluation);
- }
- }
- if (action === 'protect_risk_evaluation') {
- if (req.body.callbacks.find((cb) => cb.type === 'HiddenValueCallback')) {
- const hiddenCb = req.body.callbacks.find((cb) => cb.type === 'HiddenValueCallback');
- if (hiddenCb.input[0].value === 'we had an error') {
- return res.json(authFail);
- }
- return res.json(authSuccess);
- }
- }
- } else {
- if (req.body.callbacks.find((cb) => cb.type === 'PingOneEvaluationCallback')) {
- const cb = req.body.callbacks.find((cb) => cb.type === 'PingOneEvaluationCallback');
- if (cb.input[0].value === 'the value to set') {
- return res.json(authSuccess);
- } else {
- return res.json(authFail);
- }
- }
- }
- return res.json(MetadataMarketPlacePingOneEvaluation);
- } else if (req.query.authIndexValue === 'QRCodeTest') {
- // If QR Code callbacks are being returned, return success
- if (req.body.callbacks.find((cb) => cb.type === 'HiddenValueCallback')) {
- return res.json(authSuccess);
- }
- // Client is returning callbacks from username password, so return QR Code callbacks
- res.json(otpQRCodeCallbacks);
- } else if (req.query.authIndexValue === 'SAMLTestFailure') {
- if (req.body.callbacks.find((cb) => cb.type === 'RedirectCallback')) {
- if (
- req.query.error === 'true' &&
- req.query.errorCode === '401' &&
- req.body.errorMessage === 'errorSaml'
- ) {
- res.json(authFail);
- } else {
- res.json(authSuccess);
- }
- } else {
- res.json(redirectCallbackFailureSaml);
- }
- } else if (req.query.authIndexValue === 'SAMLTest') {
- if (req.body.callbacks.find((cb) => cb.type === 'RedirectCallback')) {
- if (
- req.query.RelayState === 'https://forgerock.com' &&
- req.query.responsekey === '885cae87-f88b-4d75-a0fd-0ae1400b766f' &&
- req.body.authId === 'foo'
- ) {
- res.json(authSuccess);
- } else {
- res.json(authFail);
- }
- } else {
- res.json(redirectCallbackSaml);
- }
- } else if (req.query.authIndexValue === 'MiscCallbacks') {
- if (req.body.callbacks.find((cb) => cb.type === 'NameCallback')) {
- const cb = req.body.callbacks.find((cb) => cb.type === 'NameCallback');
- if (cb.input[0].value !== USERS[0].un) {
- res.json(authFail);
- } else {
- res.json(textInputCallback);
- }
- } else if (req.body.callbacks.find((cb) => cb.type === 'TextInputCallback')) {
- const cb = req.body.callbacks.find((cb) => cb.type === 'TextInputCallback');
- if (cb.input[0].value !== 'Text Input String') {
- res.json(authFail);
- } else {
- res.json(passwordCallback);
- }
- } else if (req.body.callbacks.find((cb) => cb.type === 'PasswordCallback')) {
- const cb = req.body.callbacks.find((cb) => cb.type === 'PasswordCallback');
- if (cb.input[0].value !== USERS[0].pw) {
- res.json(authFail);
- } else {
- res.json(choiceCallback);
- }
- } else if (req.body.callbacks.find((cb) => cb.type === 'ChoiceCallback')) {
- const cb = req.body.callbacks.find((cb) => cb.type === 'ChoiceCallback');
- if (cb.input[0].value !== 1) {
- res.json(authFail);
- } else {
- res.json(messageCallback);
- }
- } else if (req.body.callbacks.find((cb) => cb.type === 'ConfirmationCallback')) {
- const cb = req.body.callbacks.find((cb) => cb.type === 'ConfirmationCallback');
- if (cb.input[0].value !== 0) {
- res.json(authFail);
- } else {
- res.json(pollingCallback);
- }
- } else if (req.body.callbacks.find((cb) => cb.type === 'PollingCallback')) {
- res.cookie('iPlanetDirectoryPro', 'abcd1234', { domain: 'localhost' });
- res.json(authSuccess);
- } else {
- res.json(authFail);
- }
- } else if (req.query.authIndexValue === 'PlatformUsernamePasswordTest') {
- const pwCb = req.body.callbacks.find((cb) => cb.type === 'ValidatedCreatePasswordCallback');
- // If validate only, return callbacks
- if (pwCb.input[1].value) {
- res.json(initialPlatformLogin);
- } else if (pwCb.input[0].value !== USERS[0].pw) {
- res.status(401).json(authFail);
- } else {
- res.cookie('iPlanetDirectoryPro', 'abcd1234', { domain: 'localhost' });
- res.json(authSuccess);
- }
- } else if (req.query.authIndexValue === 'Registration') {
- const un = req.body.callbacks.find((cb) => cb.type === 'ValidatedCreateUsernameCallback');
- const [fn, ln, em] = req.body.callbacks.filter(
- (cb) => cb.type === 'StringAttributeInputCallback',
- );
- // const age = req.body.callbacks.find((cb) => cb.type === 'NumberAttributeInputCallback');
- const [mktg, update] = req.body.callbacks.filter(
- (cb) => cb.type === 'BooleanAttributeInputCallback',
- );
- const pw = req.body.callbacks.find((cb) => cb.type === 'ValidatedCreatePasswordCallback');
- const [kba1, kba2] = req.body.callbacks.filter((cb) => cb.type === 'KbaCreateCallback');
- const terms = req.body.callbacks.find((cb) => cb.type === 'TermsAndConditionsCallback');
- if (
- un.input[0].value.length &&
- fn.input[0].value === 'Sally' &&
- ln.input[0].value === 'Tester' &&
- // age.input[0].value === 40 &&
- em.input[0].value.length &&
- mktg.input[0].value === false &&
- update.input[0].value === false &&
- pw.input[0].value === USERS[0].pw &&
- kba1.input[0].value === 'What is your favorite color?' &&
- kba1.input[1].value === 'Red' &&
- kba2.input[0].value === 'Who was your first employer?' &&
- kba2.input[1].value === 'AAA Engineering' &&
- terms.input[0].value === true
- ) {
- res.cookie('iPlanetDirectoryPro', 'abcd1234', { domain: 'localhost' });
- res.json(authSuccess);
- } else {
- res.status(401).json(authFail);
- }
- } else if (req.query.authIndexValue === 'SecondFactor') {
- if (req.body.callbacks.find((cb) => cb.type === 'NameCallback')) {
- res.json(secondFactorChoiceCallback);
- } else if (req.body.callbacks.find((cb) => cb.type === 'ChoiceCallback')) {
- res.json(secondFactorCallback);
- } else if (req.body.callbacks.find((cb) => cb.type === 'PasswordCallback')) {
- const pwCb = req.body.callbacks.find((cb) => cb.type === 'PasswordCallback');
- if (pwCb.input[0].value !== 'abc123') {
- res.status(401).json(authFail);
- } else {
- res.cookie('iPlanetDirectoryPro', 'abcd1234', { domain: 'localhost' });
- res.json(authSuccess);
- }
- }
- } else if (req.query.authIndexValue === 'IDMSocialLogin') {
- if (req.body.callbacks.find((cb) => cb.type === 'SelectIdPCallback')) {
- const idPCb = req.body.callbacks.find((cb) => cb.type === 'SelectIdPCallback');
- if (idPCb.input[0].value !== 'google') {
- res.status(401).json(authFail);
- } else {
- res.json(redirectCallback);
- }
- } else if (req.body.callbacks.find((cb) => cb.type === 'RedirectCallback')) {
- if (req.body.authId && req.query.code && req.query.state) {
- res.cookie('iPlanetDirectoryPro', 'abcd1234', { domain: 'localhost' });
- res.json(authSuccess);
- } else {
- res.status(401).json(authFail);
- }
- }
- } else if (req.query.authIndexValue === 'AMSocialLogin') {
- if (req.body.callbacks.find((cb) => cb.type === 'ChoiceCallback')) {
- const idPCb = req.body.callbacks.find((cb) => cb.type === 'ChoiceCallback');
- if (idPCb.input[0].value !== 0) {
- res.status(401).json(authFail);
- } else {
- res.json(redirectCallback);
- }
- } else if (req.body.callbacks.find((cb) => cb.type === 'RedirectCallback')) {
- if (req.body.authId && req.query.code && req.query.state) {
- res.cookie('iPlanetDirectoryPro', 'abcd1234', { domain: 'localhost' });
- res.json(authSuccess);
- } else {
- res.status(401).json(authFail);
- }
- }
- } else if (req.query.authIndexValue === 'TEST_LoginPingProtect') {
- const protectInitCb = req.body.callbacks.find(
- (cb) => cb.type === 'PingOneProtectInitializeCallback',
- );
- const usernameCb = req.body.callbacks.find((cb) => cb.type === 'NameCallback');
- const protectEvalCb = req.body.callbacks.find(
- (cb) => cb.type === 'PingOneProtectEvaluationCallback',
- );
- if (protectInitCb) {
- res.json(initialBasicLogin);
- } else if (usernameCb && usernameCb.input[0].value) {
- res.json(pingProtectEvaluate);
- } else if (protectEvalCb && protectEvalCb.input[0].value) {
- res.json(authSuccess);
- } else {
- res.status(401).json(authFail);
- }
- } else if (req.body.callbacks.find((cb) => cb.type === 'PasswordCallback')) {
- const pwCb = req.body.callbacks.find((cb) => cb.type === 'PasswordCallback');
- if (pwCb.input[0].value !== USERS[0].pw) {
- res.status(401).json(authFail);
- } else {
- if (req.query.authIndexValue === 'DeviceProfileCallbackTest') {
- res.json(requestDeviceProfile);
- } else {
- if (
- req.body.stage === 'TransactionAuthorization' ||
- req.body.stage === 'TreeBasedAuthorization'
- ) {
- baz.canWithdraw = true;
- }
- if (req.path.includes('middleware')) {
- if (
- req.query['authenticate-middleware'] === 'authentication' &&
- req.headers['x-authenticate-middleware'] === 'authentication' &&
- !req.headers['x-logout-middleware'] &&
- !req.query['logout-middleware']
- ) {
- res.cookie('iPlanetDirectoryPro', 'abcd1234', { domain: 'localhost' });
- res.json(authSuccess);
- } else {
- res.status(406).send('Middleware additions are missing.');
- }
- } else {
- res.cookie('iPlanetDirectoryPro', 'abcd1234', { domain: 'localhost' });
- res.json(req.query.noSession === 'true' ? noSessionSuccess : authSuccess);
- }
- }
- }
- } else if (req.body.callbacks.find((cb) => cb.type === 'DeviceProfileCallback')) {
- const deviceCb = req.body.callbacks.find((cb) => cb.type === 'DeviceProfileCallback') || {};
- const inputArr = deviceCb.input || [];
- const input = inputArr[0] || {};
- const value = JSON.parse(input.value);
- const location = value.location || {};
- const metadata = value.metadata || {};
- // location is not allowed in some browser automation
- // const location = value.location || {};
-
- // We just need property existence to ensure profile is generated
- // We don't care about values since they are unique per browser
- if (
- location &&
- location.latitude &&
- location.longitude &&
- metadata.browser &&
- metadata.browser.userAgent &&
- metadata.platform &&
- metadata.platform.deviceName &&
- metadata.platform.fonts &&
- metadata.platform.fonts.length > 0 &&
- metadata.platform.timezone &&
- value.identifier &&
- value.identifier.length > 0
- ) {
- res.cookie('iPlanetDirectoryPro', 'abcd1234', { domain: 'localhost' });
- res.json(authSuccess);
- } else {
- // Just failing the auth for testing, but in reality,
- // an additional auth callback would be sent, like OTP
- res.json(authFail);
- }
- }
- });
-
- app.post(authPaths.tokenExchange, wait, async (req, res) => {
- // eslint-disable-next-line
- const access_token = v4();
- const refresh_token = v4();
- // eslint-disable-next-line
- const tokens = { ...oauthTokens, access_token, refresh_token };
-
- if (req.path.includes('middleware')) {
- if (
- req.query['exchange-token-middleware'] === 'exchange-token' &&
- req.headers['x-exchange-token-middleware'] === 'exchange-token' &&
- !req.headers['x-logout-middleware'] &&
- !req.query['logout-middleware']
- ) {
- res.json(tokens);
- } else {
- res.status(406).send('Middleware header is missing.');
- }
- } else if (req.path.includes('tokens-expiring-soon')) {
- const tokensExpiringSoon = { ...oauthTokensExpiringSoon, access_token, refresh_token };
- res.json(tokensExpiringSoon);
- } else if (req.path.includes('tokens-expired')) {
- const tokensExpired = { ...oauthTokensExpired, access_token, refresh_token };
- res.json(tokensExpired);
- } else {
- res.json(tokens);
- }
- });
-
- app.get(authPaths.accounts, wait, async (req, res) => {
- if (req.url.includes('SAMLFailure')) {
- const referrer = new URL(req.get('Referer'));
- const additionalQueryParams = 'error=true&errorCode=401&errorMessage=errorSaml';
- const redirectUrl = `${referrer.href}${
- referrer.href.includes('?') ? '&' : '?'
- }${additionalQueryParams}`;
- return res.redirect(redirectUrl);
- } else if (req.url.includes('SAMLTest')) {
- const referrer = new URL(req.get('Referer'));
- const additionalQueryParams =
- 'responsekey=885cae87-f88b-4d75-a0fd-0ae1400b766f&RelayState=https://forgerock.com';
- const redirectUrl = `${referrer.href}${
- referrer.href.includes('?') ? '&' : '?'
- }${additionalQueryParams}`;
- return res.redirect(redirectUrl);
- } else {
- const referrer = new URL(req.get('Referer'));
- const additionalQueryParams =
- // eslint-disable-next-line max-len
- 'state=rtu8pz65dbg6baw985d532myfbbnf5v&code=4%2F0AY0e-g5vHGhzfggdAuIofxnblW-iR1Y30G5lN5RvbrU8Zv5ZmtUVheTzSX7YMJF_usbzUA&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&authuser=0&hd=forgerock.com&prompt=none';
- const redirectUrl = `${referrer.href}${
- referrer.href.includes('?') ? '&' : '?'
- }${additionalQueryParams}`;
- res.redirect(redirectUrl);
- }
- });
-
- app.get(authPaths.authorize, wait, async (req, res) => {
- const loginUrl = new URL(`${req.protocol}://${req.headers.host}/login`);
- loginUrl.searchParams.set('client_id', req.query.client_id);
- loginUrl.searchParams.set('acr_values', req.query.acr_values);
- loginUrl.searchParams.set('redirect_uri', req.query.redirect_uri);
- loginUrl.searchParams.set('state', req.query.state);
-
- // Detect if Central Login to enforce ACR value presence
- if (
- req.query.client_id === 'CentralLoginOAuthClient' &&
- req.query.acr_values !== 'SpecificTree'
- ) {
- return res.status(400).json({ message: 'acr_values did not match "SpecificTree"' });
- }
- if (req.path.includes('middleware-modern')) {
- if (
- req.query['authorize-middleware'] === 'authorization' &&
- req.headers['x-authorize-middleware'] === 'authorization' &&
- !req.query['logout-middleware'] &&
- !req.headers['x-logout-middleware']
- ) {
- res.redirect(loginUrl);
- } else {
- res.status(406).send('Middleware additions are missing.');
- }
- } else if (req.path.includes('middleware')) {
- if (
- req.query['authorize-middleware'] === 'authorization' &&
- !req.query['logout-middleware']
- ) {
- res.redirect(loginUrl);
- } else {
- res.status(406).send('Middleware additions are missing.');
- }
- } else {
- if (req.cookies.iPlanetDirectoryPro) {
- const redirectUrl = new URL(`${req.query.redirect_uri}`);
-
- console.log(`Request URL: ${req.query.client_id}`);
-
- redirectUrl.searchParams.set('client_id', req.query.client_id);
- redirectUrl.searchParams.set('code', 'foo');
- redirectUrl.searchParams.set('iss', `${AM_URL}/oauth2`);
- redirectUrl.searchParams.set('state', req.query.state);
-
- res.redirect(redirectUrl);
- } else if (req.cookies.redirected === 'true') {
- res.redirect(loginUrl);
- } else {
- res.cookie('redirected', 'true');
-
- const interactionNeeded = 'The request requires some interaction that is not allowed.';
- const redirectErrorUrl = new URL(
- `${req.query.redirect_uri}?error_description=${interactionNeeded}`,
- );
-
- res.redirect(redirectErrorUrl);
- }
- }
- });
-
- app.get('/login', async (req, res) => {
- const domain = req.url.includes('localhost') ? 'localhost' : 'example.com';
-
- res.clearCookie('redirected');
- res.cookie('iPlanetDirectoryPro', 'abcd1234', { domain, sameSite: 'none', secure: true });
-
- const url = new URL(`${req.protocol}://${req.headers.host}${authPaths.authorize[1]}`);
- url.searchParams.set('client_id', req.query.client_id);
- url.searchParams.set('acr_values', req.query.acr_values);
- url.searchParams.set('redirect_uri', req.query.redirect_uri);
- url.searchParams.set('state', req.query.state);
-
- res.redirect(url);
- });
-
- app.get(authPaths.userInfo, wait, async (req, res) => {
- if (req.headers['authorization'] && req.path.includes('middleware')) {
- if (
- req.query['userinfo-middleware'] === 'userinfo' &&
- req.headers['x-userinfo-middleware'] === 'userinfo' &&
- !req.headers['x-logout-middleware'] &&
- !req.query['logout-middleware']
- ) {
- res.json(userInfo);
- } else {
- res.status(406).send('Middleware additions are missing.');
- }
- } else if (req.headers['authorization']) {
- res.json(userInfo);
- } else {
- res.status(401).send('Unauthorized');
- }
- });
-
- app.get(authPaths.endSession, wait, async (req, res) => {
- if (req.path.includes('middleware')) {
- if (
- req.query['end-session-middleware'] === 'end-session' &&
- req.headers['x-end-session-middleware'] === 'end-session' &&
- !req.headers['x-logout-middleware'] &&
- !req.query['logout-middleware']
- ) {
- res.status(204).send();
- } else {
- res.status(406).send('Middleware additions are missing missing.');
- }
- } else {
- res.status(204).send();
- }
- });
-
- app.post(authPaths.revoke, wait, async (req, res) => {
- if (req.path.includes('middleware')) {
- if (
- req.query['revoke-token-middleware'] === 'revoke-token' &&
- req.headers['x-revoke-token-middleware'] === 'revoke-token' &&
- !req.headers['x-logout-middleware'] &&
- !req.query['logout-middleware']
- ) {
- res.status(200).send();
- } else {
- res.status(406).send('Middleware header is missing.');
- }
- } else {
- res.status(200).send();
- }
- });
-
- app.all(authPaths.htmlAuthenticate, wait, async (req, res) => {
- res.type('html');
- res.status(200).send('');
- });
-
- app.post(authPaths.sessions, wait, async (req, res) => {
- if (req.query._action === 'logout') {
- if (req.path.includes('middleware')) {
- if (
- req.query['logout-middleware'] === 'logout' &&
- req.headers['x-logout-middleware'] === 'logout' &&
- !req.headers['x-auth-middleware'] &&
- !req.query['auth-middleware']
- ) {
- res.clearCookie('iPlanetDirectoryPro', { domain: 'localhost', path: '/' });
- res.status(204).send();
- } else {
- res.status(406).send('Middleware header is missing.');
- }
- } else {
- res.clearCookie('iPlanetDirectoryPro', { domain: 'localhost', path: '/' });
- res.status(204).send();
- }
- }
- });
-
- app.get('/callback', (req, res) => res.status(200).send('ok'));
-
- app.get('/am/.well-known/oidc-configuration', (req, res) => {
- res.send(wellKnownForgeRock);
- });
-
- app.get('/as/.well-known/oidc-configuration', (req, res) => {
- res.send(wellKnownPing);
- });
-}
diff --git a/e2e/mock-api/src/app/routes.resource.js b/e2e/mock-api/src/app/routes.resource.js
deleted file mode 100644
index e6c9313ed..000000000
--- a/e2e/mock-api/src/app/routes.resource.js
+++ /dev/null
@@ -1,191 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * routes.resource.js
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { env } from 'process';
-import request from 'superagent';
-import { session } from './app.auth.js';
-import { AM_URL, AM_PORT, FORGEOPS, REALM_PATH } from './env.config.js';
-import {
- authByTreeResponse,
- authByTxnResponse,
- createTxnStepUpHeader,
- createTreeStepUpHeader,
- createTxnStepUpUrl,
- createTreeStepUpUrl,
-} from './responses.js';
-import { baz } from './routes.auth.js';
-import wait from './wait.js';
-
-async function authorization(req, res, next) {
- if (env.NODE_ENV === 'LIVE' && req.hostname !== FORGEOPS) {
- const fullURL = `${req.protocol}://${req.host}:${AM_PORT}${req.url}`;
- let realms;
- const body = {
- application: req.path.includes('authz-by-txn') ? 'TxnBasedPolicy' : 'TreeBasedPolicy',
- resources: [fullURL],
- subject: {
- ssoToken: req.headers['x-idtoken'] || req.cookies.iPlanetDirectoryPro,
- },
- };
- if (req.headers['x-txid']) {
- body.environment = {
- TxId: [req.headers['x-txid']],
- };
- }
- if (REALM_PATH !== 'root') {
- realms = `realms/root/realms/${REALM_PATH}`;
- } else {
- realms = 'realms/root';
- }
- const response = await request
- // eslint-disable-next-line
- .post(`${AM_URL}/json/${realms}/policies/?_action=evaluate`)
- // .key(key)
- // .cert(cert)
- .set('Content-Type', 'application/json')
- .set('Accept-API-Version', 'resource=2.1')
- .set('iPlanetDirectoryPro', session.tokenId)
- .send(body);
-
- req.access = response.body[0] || {};
- next();
- } else {
- next();
- }
-}
-
-export default function (app) {
- // Passthrough route that enforces authentication
- app.all('/resource/*', async (req, res, next) => {
- if (env.NODE_ENV === 'LIVE' && req.hostname === FORGEOPS) {
- // Only enforce authentication if IG is not used
- // In other words, the call comes directly from app
- let response;
- if (req.headers.authorization) {
- // Using OAuth
- const authHeaderArr = req.headers.authorization.split(' ');
- response = await request
- .post(`${AM_URL}/oauth2/introspect`)
- .set('Content-Type', 'application/json')
- .set('iPlanetDirectoryPro', session.tokenId)
- .set('Accept-API-Version', 'resource=1.2')
- .send({ token: authHeaderArr[1] });
- } else {
- // Using SSO
- response = await request
- .post(`${AM_URL}/json/sessions/?_action=validate`)
- .set('Content-Type', 'application/json')
- .set('iPlanetDirectoryPro', session.tokenId)
- .set('Accept-API-Version', 'resource=2.1, protocol=1.0')
- .send({ tokenId: req.cookies.iPlanetDirectoryPro });
- }
-
- if (response.body.active || response.body.valid) {
- next();
- } else {
- res.status(401).send();
- }
- } else {
- // Call came from a proxy, so proxy (e.g. IG) will enforce auth
- next();
- }
- });
-
- app.get('/resource/reflect-authz-header', wait, authorization, async (req, res) => {
- // Respond with the value of the authorization header to assist in testing http client
- res.json({ message: req.headers['authorization'] });
- });
-
- app.get('/resource/ig/authz-by-txn', wait, authorization, async (req, res) => {
- if (req.hostname === FORGEOPS) {
- // Calls are coming from IG, so Auth is already enforced
- res.json({ message: 'Successfully retrieved resource!' });
- } else {
- // Calls are coming directly from app, so let's mocks IG's behavior
- if (
- req.cookies.iPlanetDirectoryPro === 'abcd1234' &&
- baz.canWithdraw &&
- req.query._txid === authByTxnResponse.advices.TransactionConditionAdvice[0]
- ) {
- baz.canWithdraw = false;
- res.json({ message: 'Successfully retrieved resource!' });
- } else {
- console.log(req.headers['x-authenticate-response']);
- if (
- req.headers['x-authenticate-response'] &&
- req.headers['x-authenticate-response'] === 'header' &&
- req.headers.referer.includes('json')
- ) {
- res.setHeader('WWW-Authenticate', createTxnStepUpHeader(req.headers.referer));
- res.send(401, null);
- } else {
- res.redirect(307, createTxnStepUpUrl(req.headers.referer));
- }
- }
- }
- });
-
- app.get('/resource/ig/authz-by-tree', wait, authorization, async (req, res) => {
- if (req.hostname === FORGEOPS) {
- // Calls are coming from IG, so Auth is already enforced
- res.json({ message: 'Successfully retrieved resource!' });
- } else {
- // Calls are coming directly from app, so let's mocks IG's behavior
- if (req.cookies.iPlanetDirectoryPro === 'abcd1234' && baz.canWithdraw) {
- baz.canWithdraw = false;
- res.json({ message: 'Successfully retrieved resource!' });
- } else {
- if (
- req.headers['x-authenticate-response'] &&
- req.headers['x-authenticate-response'] === 'header' &&
- req.headers.referer.includes('json')
- ) {
- res.setHeader('WWW-Authenticate', createTreeStepUpHeader(req.headers.referer));
- res.send(401, null);
- } else {
- res.redirect(307, createTreeStepUpUrl(req.headers.referer));
- }
- }
- }
- });
-
- app.get('/resource/rest/*', wait, authorization, async (req, res) => {
- if (env.NODE_ENV === 'live') {
- if (req.access.actions && req.access.actions.GET) {
- res.json({ message: 'Successfully retrieved resource!' });
- } else if (
- req.access.advices &&
- (req.access.advices.TransactionConditionAdvice ||
- req.access.advices.AuthenticateToServiceConditionAdvice)
- ) {
- res.json(req.access);
- } else {
- res.status(401).send();
- }
- } else {
- if (
- req.cookies.iPlanetDirectoryPro === 'abcd1234' &&
- baz.canWithdraw &&
- (req.headers['x-txid'] === authByTxnResponse.advices.TransactionConditionAdvice[0] ||
- req.headers['x-tree'] ===
- authByTreeResponse.advices.AuthenticateToServiceConditionAdvice[0])
- ) {
- baz.canWithdraw = false;
- res.json({ message: 'Successfully retrieved resource!' });
- } else {
- if (req.path.includes('authz-by-txn')) {
- res.json(authByTxnResponse);
- } else if (req.path.includes('authz-by-tree')) {
- res.json(authByTreeResponse);
- }
- }
- }
- });
-}
diff --git a/e2e/mock-api/src/app/wait.js b/e2e/mock-api/src/app/wait.js
deleted file mode 100644
index be41fb7cc..000000000
--- a/e2e/mock-api/src/app/wait.js
+++ /dev/null
@@ -1,15 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * wait.js
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-const delay = 0;
-
-export default function wait(req, res, next) {
- setTimeout(() => next(), delay);
-}
diff --git a/e2e/mock-api/src/environments/environment.prod.ts b/e2e/mock-api/src/environments/environment.prod.ts
deleted file mode 100644
index c9669790b..000000000
--- a/e2e/mock-api/src/environments/environment.prod.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export const environment = {
- production: true,
-};
diff --git a/e2e/mock-api/src/environments/environment.ts b/e2e/mock-api/src/environments/environment.ts
deleted file mode 100644
index a24f6ba2c..000000000
--- a/e2e/mock-api/src/environments/environment.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-export const environment = {
- AM_URL: 'https://openam-crbrl-01.forgeblocks.com/am/',
- REALM_PATH: 'alpha',
- WEB_OAUTH_CLIENT: 'WebOAuthClient',
- JOURNEY_LOGIN: 'UsernamelessWebAuthn',
- JOURNEY_REGISTER: 'Registration',
- API_URL: 'http://localhost:9443',
- production: 'development',
-};
diff --git a/e2e/mock-api/src/index.js b/e2e/mock-api/src/index.js
deleted file mode 100644
index 7d80a924c..000000000
--- a/e2e/mock-api/src/index.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.js
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-import * as dns from 'dns';
-import cors from 'cors';
-import express from 'express';
-import cookieParser from 'cookie-parser';
-import { createServer } from 'http';
-import { env } from 'process';
-import path from 'path';
-import { authorizeApp } from './app/app.auth.js';
-import { MOCK_PORT } from './app/env.config.js';
-import authRoutes from './app/routes.auth.js';
-import resourceRoutes from './app/routes.resource.js';
-
-dns.setDefaultResultOrder('ipv4first');
-
-const app = express();
-
-app.use(express.json());
-app.use('/am/XUI/images', express.static(path.join(__dirname, 'public')));
-app.use(cookieParser());
-app.use(
- cors({
- exposedHeaders: ['www-authenticate'],
- credentials: true,
- origin: function (origin, callback) {
- return callback(null, true);
- },
- }),
-);
-app.use((req, res, next) => {
- console.log(`${req.method} ${req.path}`);
- next();
-});
-
-if (env.NODE_ENV === 'LIVE') {
- authorizeApp({
- un: '9190fcce-d6d7-4473-9449-412f281f9bc6',
- pw: '7fh9sj7*NP$%F6978',
- });
-}
-
-authRoutes(app);
-resourceRoutes(app);
-
-app.get('/healthcheck', (req, res) => res.status(200).send('ok'));
-
-env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;
-createServer(app).listen(MOCK_PORT);
-console.log(`Listening to HTTP on secure port: ${MOCK_PORT}`);
diff --git a/e2e/mock-api/tsconfig.app.json b/e2e/mock-api/tsconfig.app.json
deleted file mode 100644
index 5140abd9d..000000000
--- a/e2e/mock-api/tsconfig.app.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "../../dist/out-tsc",
- "module": "Node16",
- "moduleResolution": "Node16",
- "target": "ES6",
- "composite": true,
- "allowJs": true,
- "types": ["node", "express"]
- },
- "exclude": ["**/*.spec.ts", "**/*.test.ts", "dist"],
- "include": ["**/*.ts", "**/*.js"]
-}
diff --git a/e2e/mock-api/tsconfig.json b/e2e/mock-api/tsconfig.json
deleted file mode 100644
index 63dbe35fb..000000000
--- a/e2e/mock-api/tsconfig.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "extends": "../../tsconfig.base.json",
- "files": [],
- "include": [],
- "references": [
- {
- "path": "./tsconfig.app.json"
- },
- {
- "path": "./tsconfig.spec.json"
- }
- ]
-}
diff --git a/e2e/token-vault-app/.babelrc b/e2e/token-vault-app/.babelrc
deleted file mode 100644
index f2f380674..000000000
--- a/e2e/token-vault-app/.babelrc
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "presets": ["@nx/js/babel"]
-}
diff --git a/e2e/token-vault-app/.env.preview b/e2e/token-vault-app/.env.preview
deleted file mode 100644
index 9189bc43c..000000000
--- a/e2e/token-vault-app/.env.preview
+++ /dev/null
@@ -1,2 +0,0 @@
-VITE_AM_URL=http://localhost:9443/am
-VITE_AM_REALM=root
\ No newline at end of file
diff --git a/e2e/token-vault-app/.eslintignore b/e2e/token-vault-app/.eslintignore
deleted file mode 100644
index 7eb3b6427..000000000
--- a/e2e/token-vault-app/.eslintignore
+++ /dev/null
@@ -1,9 +0,0 @@
-node_modules
-*.md
-LICENSE
-.babelrc
-.env*
-.bin
-dist
-.eslintignore
-*.html
\ No newline at end of file
diff --git a/e2e/token-vault-app/.eslintrc.json b/e2e/token-vault-app/.eslintrc.json
deleted file mode 100644
index ba8f68df1..000000000
--- a/e2e/token-vault-app/.eslintrc.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "extends": ["../../.eslintrc.json"],
- "ignorePatterns": ["!**/*", "public"],
- "overrides": [
- {
- "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
- "rules": {}
- },
- {
- "files": ["*.ts", "*.tsx"],
- "rules": {}
- },
- {
- "files": ["*.js", "*.jsx"],
- "rules": {}
- }
- ]
-}
diff --git a/e2e/token-vault-app/index.html b/e2e/token-vault-app/index.html
deleted file mode 100644
index 322bbfb61..000000000
--- a/e2e/token-vault-app/index.html
+++ /dev/null
@@ -1,69 +0,0 @@
-
-
-
-
- Token Vault App
-
-
-
-
-
-
-
-
- Login
- Fetch Protected Mock Todos
- Fetch Unprotected Mock Data
- Fetch Real User
- Check for Tokens
- Refresh Tokens
- Logout
- Unregister Interceptor
- Destroy Proxy
- Hacker!
-
-
- User Logged In:
- false
- User info:
- n/a
- User has tokens:
- false
- Tokens refreshed:
- false
-
-
-
-
-
-
diff --git a/e2e/token-vault-app/package.json b/e2e/token-vault-app/package.json
deleted file mode 100644
index a95e4ca36..000000000
--- a/e2e/token-vault-app/package.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "name": "token-vault-app",
- "description": "ForgeRock Token Vault Test App",
- "private": true,
- "type": "module",
- "dependencies": {
- "@forgerock/javascript-sdk": "workspace:*",
- "@forgerock/token-vault": "workspace:*",
- "@forgerock/token-vault-interceptor": "workspace:*"
- },
- "version": "0.0.0"
-}
diff --git a/e2e/token-vault-app/project.json b/e2e/token-vault-app/project.json
deleted file mode 100644
index 7193a7eae..000000000
--- a/e2e/token-vault-app/project.json
+++ /dev/null
@@ -1,46 +0,0 @@
-{
- "name": "token-vault-app",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "projectType": "application",
- "sourceRoot": "e2e/token-vault-app/src",
- "tags": ["scope:app"],
- "targets": {
- "build": {
- "inputs": ["default", "^default"],
- "outputs": ["{projectRoot}/dist"],
- "options": {
- "emptyOutDir": false
- },
- "configurations": {
- "development": {
- "mode": "development"
- }
- }
- },
- "serve": {
- "defaultConfiguration": "development",
- "options": {
- "host": "localhost",
- "port": 5823
- },
- "configurations": {
- "development": {},
- "production": {}
- }
- },
- "preview": {
- "defaultConfiguration": "development",
- "configurations": {
- "development": {},
- "production": {}
- }
- },
- "lint": {
- "options": {
- "fix": true,
- "ignore-path": ".eslintignore",
- "args": ["**/*.ts"]
- }
- }
- }
-}
diff --git a/e2e/token-vault-app/public/favicon.ico b/e2e/token-vault-app/public/favicon.ico
deleted file mode 100644
index 317ebcb23..000000000
Binary files a/e2e/token-vault-app/public/favicon.ico and /dev/null differ
diff --git a/e2e/token-vault-app/src/main.ts b/e2e/token-vault-app/src/main.ts
deleted file mode 100644
index 4fc0aa793..000000000
--- a/e2e/token-vault-app/src/main.ts
+++ /dev/null
@@ -1,209 +0,0 @@
-/* eslint-disable @typescript-eslint/no-unused-vars */
-import { Config, FRUser, TokenManager, UserManager } from '@forgerock/javascript-sdk';
-import { client } from '@forgerock/token-vault';
-
-/** ****************************************************
- * START: CONFIGURE THE TOKEN VAULT
- **************************************************** */
-
-// Initialize the Token Vault Client
-const register = client({
- app: {
- origin: 'http://localhost:5823',
- },
- interceptor: {
- file: new URL('@forgerock/token-vault-interceptor', import.meta.url).pathname,
- scope: '/',
- },
- proxy: {
- origin: 'http://localhost:5833',
- urls: ['https://jsonplaceholder.typicode.com/*'],
- },
-});
-
-// Register the Token Vault Interceptor
-const interceptor = await register.interceptor();
-
-// Register the Token Vault Proxy
-const proxy = await register.proxy(document.getElementById('token-vault') as HTMLElement);
-
-// Register the Token Vault Store
-const tokenStore = register.store();
-
-/** ****************************************************
- * END: CONFIGURE THE TOKEN VAULT
- **************************************************** */
-
-//
-// ----------------------------------------------------
-//
-
-/** ****************************************************
- * START: SDK CONFIGURATION
- **************************************************** */
-console.log(`AM URL: ${import.meta.env.VITE_AM_URL}`);
-
-Config.set({
- clientId: 'CentralLoginOAuthClient',
- redirectUri: `${window.location.origin}`,
- scope: 'openid profile me.read',
- serverConfig: {
- baseUrl: import.meta.env.VITE_AM_URL || 'http://localhost:9443/am',
- timeout: 5000,
- },
- realmPath: import.meta.env.VITE_AM_REALM || 'root',
- tokenStore: {
- get: tokenStore.get,
- set: tokenStore.set,
- remove: tokenStore.remove,
- },
-});
-
-/** ****************************************************
- * END: SDK CONFIGURATION
- **************************************************** */
-
-//
-// ----------------------------------------------------
-//
-
-/** ****************************************************
- * START: APPLICATION LOGIC
- ***************************************************** */
-
-/**
- * Check URL for query parameters
- */
-const url = new URL(document.location.href);
-const params = url.searchParams;
-const code = params.get('code');
-const state = params.get('state');
-console.log('page loaded');
-/**
- * Get the elements we need to update
- */
-function getById(id: string) {
- return document.getElementById(id) as HTMLElement;
-}
-// Buttons
-const fetchProtectedMockBtn = getById('fetchProtectedMockBtn');
-const fetchUnprotectedMockBtn = getById('fetchUnprotectedMockBtn');
-const fetchUserBtn = getById('fetchUserBtn');
-const hasTokensBtn = getById('hasTokensBtn');
-const refreshTokensBtn = getById('refreshTokensBtn');
-const loginBtn = getById('loginBtn');
-const logoutBtn = getById('logoutBtn');
-const unregisterInterceptorBtn = getById('unregisterInterceptorBtn');
-const destroyProxyBtn = getById('destroyProxyBtn');
-
-// Definition elements
-const loggedInEl = getById('loggedInDef');
-const userInfoEl = getById('userInfoDef');
-const hasTokensEl = getById('hasTokensDef');
-const refreshTokensEl = getById('refreshTokensDef');
-const hackerEl = getById('hacker');
-
-/**
- * If the URL has state and code as query parameters, then the user
- * returned back here after successfully logging in, so call authorize
- * with the values
- */
-if (state && code) {
- await TokenManager.getTokens({ query: { code, state } });
- location.replace('http://localhost:5823');
-}
-
-/**
- * Let's make an initial check for tokens to see if the user is logged in
- */
-const res = await (async () => {
- return await tokenStore.has();
-})();
-if (res.hasTokens) {
- loggedInEl.innerText = 'true';
-}
-
-/** ****************************************************
- * ATTACH USER EVENT LISTENERS
- */
-fetchProtectedMockBtn.addEventListener('click', async (event) => {
- await fetch('https://jsonplaceholder.typicode.com/todos');
-});
-
-fetchUnprotectedMockBtn.addEventListener('click', async (event) => {
- await fetch('https://thecocktaildb.com/api/json/v1/1/search.php?s=margarita');
-});
-
-fetchUserBtn.addEventListener('click', async (event) => {
- const user = (await UserManager.getCurrentUser()) as any;
-
- userInfoEl.innerText = user?.name;
- console.log(user);
-});
-
-hasTokensBtn.addEventListener('click', async (event) => {
- const res = await tokenStore.has();
-
- hasTokensEl.innerText = String(res.hasTokens);
- console.log(res);
-});
-
-refreshTokensBtn.addEventListener('click', async (event) => {
- const res = await tokenStore.refresh();
-
- refreshTokensEl.innerText = String(res.refreshTokens);
- console.log(res);
-});
-
-hackerEl.addEventListener('click', async () => {
- console.log('in hacker function!');
- const proxyChannel = new MessageChannel();
- const proxyOrigin = 'http://localhost:5833';
-
- // Create a request to a URL that is not allow-listed
- const request = { url: 'https://reqres.in/api/users/2' };
-
- const type = 'TVP_FETCH_RESOURCE';
-
- // Grab the Proxy's iframe and post message to it
- (document?.getElementById('token-vault-iframe') as HTMLIFrameElement)?.contentWindow?.postMessage(
- { type, request },
- proxyOrigin,
- [proxyChannel.port2],
- );
-
- // This is how you listen for the response from the Proxy
- proxyChannel.port1.onmessage = (event) => {
- console.log(event.data); // This should return error
- };
-});
-
-loginBtn.addEventListener('click', async (event) => {
- console.log('Logging in...');
- await TokenManager.getTokens({
- login: 'redirect',
- forceRenew: true,
- query: { acr_values: 'SpecificTree' },
- });
-});
-
-logoutBtn.addEventListener('click', async (event) => {
- // Not all endpoints are supported and will fail
- await FRUser.logout();
-
- loggedInEl.innerText = 'false';
- hasTokensEl.innerText = 'false';
- refreshTokensEl.innerText = 'false';
- userInfoEl.innerText = 'n/a';
- console.log('Logged out');
-});
-
-unregisterInterceptorBtn.addEventListener('click', async (event) => {
- await interceptor?.unregister();
- console.log('Interceptor unregistered');
-});
-
-destroyProxyBtn.addEventListener('click', async (event) => {
- (document.getElementById('token-vault') as HTMLDivElement).removeChild(proxy as Node);
- console.log('Proxy destroyed');
-});
diff --git a/e2e/token-vault-app/tsconfig.app.json b/e2e/token-vault-app/tsconfig.app.json
deleted file mode 100644
index b52b97526..000000000
--- a/e2e/token-vault-app/tsconfig.app.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "dist",
- "composite": true,
- "moduleResolution": "Bundler",
- "target": "ESNext",
- "module": "ESNext",
- "moduleDetection": "force"
- },
- "exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"],
- "include": ["src/**/*.ts"]
-}
diff --git a/e2e/token-vault-app/tsconfig.json b/e2e/token-vault-app/tsconfig.json
deleted file mode 100644
index 856153538..000000000
--- a/e2e/token-vault-app/tsconfig.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "extends": "../../tsconfig.base.json",
- "files": [],
- "compilerOptions": {
- "useDefineForClassFields": true,
- "lib": ["ESNext", "DOM", "WebWorker", "Webworker.Iterable"],
- "resolveJsonModule": true,
- "isolatedModules": true,
- "noUnusedLocals": true,
- "noUnusedParameters": false,
- "noImplicitReturns": true,
- "skipLibCheck": true
- },
- "references": [
- {
- "path": "./tsconfig.spec.json"
- },
- {
- "path": "./tsconfig.app.json"
- }
- ]
-}
diff --git a/e2e/token-vault-app/vite.config.ts b/e2e/token-vault-app/vite.config.ts
deleted file mode 100644
index d0da4a164..000000000
--- a/e2e/token-vault-app/vite.config.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import * as path from 'path';
-import { defineConfig } from 'vite';
-
-export default defineConfig({
- root: __dirname,
- cacheDir: '../../node_modules/.vite/e2e/token-vault-app',
- build: {
- outDir: './dist',
- reportCompressedSize: true,
- target: 'esnext',
- rollupOptions: {
- input: {
- main: path.resolve(__dirname, 'index.html'),
- },
- output: {
- entryFileNames: 'main.js',
- },
- },
- },
- preview: {
- port: 5823,
- },
- server: {
- port: 5823,
- headers: {
- 'Service-Worker-Allowed': '/',
- 'Service-Worker': 'script',
- },
- strictPort: true,
- },
-});
diff --git a/e2e/token-vault-app/vite.interceptor.config.ts b/e2e/token-vault-app/vite.interceptor.config.ts
deleted file mode 100644
index 52c6638e4..000000000
--- a/e2e/token-vault-app/vite.interceptor.config.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { defineConfig } from 'vite';
-
-export default defineConfig({
- root: __dirname,
- build: {
- outDir: './public',
- reportCompressedSize: true,
- minify: false,
- emptyOutDir: false,
- rollupOptions: {
- input: './src/interceptor.ts',
- output: {
- entryFileNames: 'interceptor.js',
- format: 'iife',
- esModule: false,
- },
- },
- },
-});
diff --git a/e2e/token-vault-interceptor/README.md b/e2e/token-vault-interceptor/README.md
deleted file mode 100644
index 61c5d239f..000000000
--- a/e2e/token-vault-interceptor/README.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# token-vault-interceptor
-
-This library was generated with [Nx](https://nx.dev).
-
-## Building
-
-Run `nx build token-vault-interceptor` to build the library.
-
-## Running unit tests
-
-Run `nx test token-vault-interceptor` to execute the unit tests via [Vitest](https://vitest.dev/).
diff --git a/e2e/token-vault-interceptor/package.json b/e2e/token-vault-interceptor/package.json
deleted file mode 100644
index 0b7d8a019..000000000
--- a/e2e/token-vault-interceptor/package.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "name": "@forgerock/token-vault-interceptor",
- "version": "0.0.1",
- "dependencies": {
- "@forgerock/token-vault": "workspace:*"
- },
- "main": "./dist/index.iife.js",
- "module": "./dist/index.iife.js",
- "exports": "./dist/index.iife.js",
- "typings": "./dist/index.d.ts",
- "private": true
-}
diff --git a/e2e/token-vault-interceptor/project.json b/e2e/token-vault-interceptor/project.json
deleted file mode 100644
index e1ecf6887..000000000
--- a/e2e/token-vault-interceptor/project.json
+++ /dev/null
@@ -1,32 +0,0 @@
-{
- "name": "@forgerock/token-vault-interceptor",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "sourceRoot": "e2e/token-vault-interceptor/src",
- "projectType": "library",
- "tags": ["scope:app"],
- "targets": {
- "build": {
- "inputs": ["default", "^default"],
- "outputs": ["{projectRoot}/dist"],
- "defaultConfiguration": "production",
- "options": {
- "emptyOutDir": false
- },
- "configurations": {
- "development": {
- "mode": "development"
- },
- "production": {
- "mode": "production"
- }
- }
- },
- "lint": {
- "options": {
- "fix": true,
- "ignore-path": ".eslintignore",
- "args": ["**/*.ts"]
- }
- }
- }
-}
diff --git a/e2e/token-vault-interceptor/src/interceptor.ts b/e2e/token-vault-interceptor/src/interceptor.ts
deleted file mode 100644
index 4f18458b1..000000000
--- a/e2e/token-vault-interceptor/src/interceptor.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { interceptor } from '@forgerock/token-vault';
-
-// Initialize the token vault interceptor
-interceptor({
- interceptor: {
- urls: ['https://jsonplaceholder.typicode.com/*'],
- },
- forgerock: {
- serverConfig: {
- baseUrl: import.meta.env.VITE_AM_URL || 'http://localhost:9443/am',
- timeout: 5000,
- },
- realmPath: import.meta.env.VITE_AM_REALM || 'root',
- },
-});
diff --git a/e2e/token-vault-interceptor/vite.config.ts b/e2e/token-vault-interceptor/vite.config.ts
deleted file mode 100644
index 1bdee6d2a..000000000
--- a/e2e/token-vault-interceptor/vite.config.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-///
-import { defineConfig } from 'vite';
-import dts from 'vite-plugin-dts';
-
-export default defineConfig({
- root: __dirname,
- cacheDir: '../../node_modules/.vite/e2e/token-vault-interceptor',
-
- build: {
- outDir: './dist',
- emptyOutDir: true,
- reportCompressedSize: true,
- lib: {
- entry: 'src/interceptor.ts',
- name: 'tokenvaultinterceptor',
- fileName: 'index',
- formats: ['iife'],
- },
- },
- plugins: [
- dts({
- declarationOnly: false,
- rollupTypes: true,
- entryRoot: 'src',
- tsconfigPath: './tsconfig.lib.json',
- }),
- ],
-
- test: {
- watch: false,
- globals: true,
- environment: 'node',
- passWithNoTests: true,
- include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
-
- reporters: ['default', 'json', 'html'],
- coverage: {
- reportsDirectory: './coverage',
- provider: 'v8',
- },
- },
-});
diff --git a/e2e/token-vault-proxy/.babelrc b/e2e/token-vault-proxy/.babelrc
deleted file mode 100644
index f2f380674..000000000
--- a/e2e/token-vault-proxy/.babelrc
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "presets": ["@nx/js/babel"]
-}
diff --git a/e2e/token-vault-proxy/.env.build-interceptor b/e2e/token-vault-proxy/.env.build-interceptor
deleted file mode 100644
index 9189bc43c..000000000
--- a/e2e/token-vault-proxy/.env.build-interceptor
+++ /dev/null
@@ -1,2 +0,0 @@
-VITE_AM_URL=http://localhost:9443/am
-VITE_AM_REALM=root
\ No newline at end of file
diff --git a/e2e/token-vault-proxy/.env.preview b/e2e/token-vault-proxy/.env.preview
deleted file mode 100644
index 9189bc43c..000000000
--- a/e2e/token-vault-proxy/.env.preview
+++ /dev/null
@@ -1,2 +0,0 @@
-VITE_AM_URL=http://localhost:9443/am
-VITE_AM_REALM=root
\ No newline at end of file
diff --git a/e2e/token-vault-proxy/.eslintignore b/e2e/token-vault-proxy/.eslintignore
deleted file mode 100644
index 25b05a282..000000000
--- a/e2e/token-vault-proxy/.eslintignore
+++ /dev/null
@@ -1,10 +0,0 @@
-node_modules
-*.md
-LICENSE
-.babelrc
-.env*
-.bin
-dist
-favicon.ico
-*.html
-.eslintignore
\ No newline at end of file
diff --git a/e2e/token-vault-proxy/.eslintrc.json b/e2e/token-vault-proxy/.eslintrc.json
deleted file mode 100644
index 9d9c0db55..000000000
--- a/e2e/token-vault-proxy/.eslintrc.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "extends": ["../../.eslintrc.json"],
- "ignorePatterns": ["!**/*"],
- "overrides": [
- {
- "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
- "rules": {}
- },
- {
- "files": ["*.ts", "*.tsx"],
- "rules": {}
- },
- {
- "files": ["*.js", "*.jsx"],
- "rules": {}
- }
- ]
-}
diff --git a/e2e/token-vault-proxy/favicon.ico b/e2e/token-vault-proxy/favicon.ico
deleted file mode 100644
index 305b5bd2b..000000000
Binary files a/e2e/token-vault-proxy/favicon.ico and /dev/null differ
diff --git a/e2e/token-vault-proxy/index.html b/e2e/token-vault-proxy/index.html
deleted file mode 100644
index 9cda3c741..000000000
--- a/e2e/token-vault-proxy/index.html
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
-
-
- Token Vault Proxy
-
-
-
-
-
-
-
-
-
diff --git a/e2e/token-vault-proxy/package.json b/e2e/token-vault-proxy/package.json
deleted file mode 100644
index a7bf9c53b..000000000
--- a/e2e/token-vault-proxy/package.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "name": "token-vault-proxy",
- "version": "0.0.0",
- "description": "ForgeRock Token Vault Test Proxy",
- "private": true,
- "type": "module",
- "dependencies": {
- "@forgerock/javascript-sdk": "workspace:*",
- "@forgerock/token-vault": "workspace:*"
- },
- "devDependencies": {}
-}
diff --git a/e2e/token-vault-proxy/project.json b/e2e/token-vault-proxy/project.json
deleted file mode 100644
index 67f6bc307..000000000
--- a/e2e/token-vault-proxy/project.json
+++ /dev/null
@@ -1,47 +0,0 @@
-{
- "name": "token-vault-proxy",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "projectType": "application",
- "sourceRoot": "e2e/token-vault-proxy/src",
- "tags": ["scope:app"],
- "targets": {
- "build": {
- "inputs": ["default", "^default"],
- "outputs": ["{projectRoot}/dist"],
- "defaultConfiguration": "production",
- "configurations": {
- "development": {
- "mode": "development"
- },
- "production": {
- "mode": "production"
- }
- }
- },
- "serve": {
- "defaultConfiguration": "development",
- "options": {
- "host": "localhost",
- "port": 5833
- },
- "configurations": {
- "development": {},
- "production": {}
- }
- },
- "preview": {
- "defaultConfiguration": "development",
- "configurations": {
- "development": {},
- "production": {}
- }
- },
- "lint": {
- "options": {
- "fix": true,
- "ignore-path": ".eslintignore",
- "args": ["**/*.ts"]
- }
- }
- }
-}
diff --git a/e2e/token-vault-proxy/public/favicon.ico b/e2e/token-vault-proxy/public/favicon.ico
deleted file mode 100644
index 317ebcb23..000000000
Binary files a/e2e/token-vault-proxy/public/favicon.ico and /dev/null differ
diff --git a/e2e/token-vault-proxy/src/main.ts b/e2e/token-vault-proxy/src/main.ts
deleted file mode 100644
index 44a260108..000000000
--- a/e2e/token-vault-proxy/src/main.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { proxy } from '@forgerock/token-vault';
-
-// Initialize the token vault proxy
-proxy({
- app: {
- origin: 'http://localhost:5823',
- },
- forgerock: {
- clientId: 'CentralLoginOAuthClient',
- oauthThreshold: 5000,
- scope: 'openid profile me.read',
- serverConfig: {
- baseUrl: import.meta.env.VITE_AM_URL || 'http://localhost:9443/am',
- timeout: 5000,
- },
- realmPath: import.meta.env.VITE_AM_REALM || 'root',
- },
- proxy: {
- origin: 'http://localhost:5823',
- urls: ['https://jsonplaceholder.typicode.com/*'],
- },
-});
diff --git a/e2e/token-vault-proxy/tsconfig.app.json b/e2e/token-vault-proxy/tsconfig.app.json
deleted file mode 100644
index 7a9d3d744..000000000
--- a/e2e/token-vault-proxy/tsconfig.app.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "../../dist/out-tsc",
- "types": ["vite/client", "node"],
- "composite": true
- },
- "exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"],
- "include": ["src/**/*.ts"]
-}
diff --git a/e2e/token-vault-proxy/tsconfig.json b/e2e/token-vault-proxy/tsconfig.json
deleted file mode 100644
index 33ec93db4..000000000
--- a/e2e/token-vault-proxy/tsconfig.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "extends": "../../tsconfig.base.json",
- "files": [],
- "compilerOptions": {
- "target": "ESNext",
- "useDefineForClassFields": true,
- "module": "ESNext",
- "lib": ["ESNext", "DOM", "WebWorker", "Webworker.Iterable"],
- "moduleResolution": "Bundler",
- "strict": true,
- "resolveJsonModule": true,
- "isolatedModules": true,
- "esModuleInterop": true,
- "noUnusedLocals": true,
- "noUnusedParameters": true,
- "noImplicitReturns": true,
- "skipLibCheck": true,
- "types": ["vite/client", "vitest"]
- },
- "references": [
- {
- "path": "./tsconfig.spec.json"
- },
- {
- "path": "./tsconfig.app.json"
- }
- ]
-}
diff --git a/e2e/token-vault-proxy/tsconfig.spec.json b/e2e/token-vault-proxy/tsconfig.spec.json
deleted file mode 100644
index 8ac2473c6..000000000
--- a/e2e/token-vault-proxy/tsconfig.spec.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "../../dist/out-tsc",
- "declaration": true
- },
- "include": [
- "vite.config.ts",
- "src/**/*.test.ts",
- "src/**/*.spec.ts",
- "src/**/*.test.tsx",
- "src/**/*.spec.tsx",
- "src/**/*.test.js",
- "src/**/*.spec.js",
- "src/**/*.test.jsx",
- "src/**/*.spec.jsx",
- "src/**/*.d.ts"
- ]
-}
diff --git a/e2e/token-vault-proxy/vite.config.ts b/e2e/token-vault-proxy/vite.config.ts
deleted file mode 100644
index d52bcf524..000000000
--- a/e2e/token-vault-proxy/vite.config.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { defineConfig } from 'vite';
-
-export default defineConfig({
- root: __dirname,
- build: {
- outDir: './dist',
- reportCompressedSize: true,
- },
- server: {
- port: 5833,
- strictPort: true,
- },
-});
diff --git a/e2e/token-vault-suites/.env.e2e b/e2e/token-vault-suites/.env.e2e
deleted file mode 100644
index 9189bc43c..000000000
--- a/e2e/token-vault-suites/.env.e2e
+++ /dev/null
@@ -1,2 +0,0 @@
-VITE_AM_URL=http://localhost:9443/am
-VITE_AM_REALM=root
\ No newline at end of file
diff --git a/e2e/token-vault-suites/.eslintignore b/e2e/token-vault-suites/.eslintignore
deleted file mode 100644
index 7787c22e4..000000000
--- a/e2e/token-vault-suites/.eslintignore
+++ /dev/null
@@ -1,8 +0,0 @@
-node_modules
-*.md
-LICENSE
-.babelrc
-.env*
-.bin
-dist
-.eslintignore
\ No newline at end of file
diff --git a/e2e/token-vault-suites/.eslintrc.json b/e2e/token-vault-suites/.eslintrc.json
deleted file mode 100644
index 9d9c0db55..000000000
--- a/e2e/token-vault-suites/.eslintrc.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "extends": ["../../.eslintrc.json"],
- "ignorePatterns": ["!**/*"],
- "overrides": [
- {
- "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
- "rules": {}
- },
- {
- "files": ["*.ts", "*.tsx"],
- "rules": {}
- },
- {
- "files": ["*.js", "*.jsx"],
- "rules": {}
- }
- ]
-}
diff --git a/e2e/token-vault-suites/package.json b/e2e/token-vault-suites/package.json
deleted file mode 100644
index 8c7b059b7..000000000
--- a/e2e/token-vault-suites/package.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "name": "token-vault-suites",
- "description": "ForgeRock Token Vault E2E Suites",
- "private": true,
- "type": "module",
- "version": "0.0.0",
- "main": "src/index.js",
- "author": "",
- "license": "ISC",
- "repository": {
- "type": "git",
- "url": "git+https://github.com/ForgeRock/forgerock-javascript-sdk.git"
- },
- "bugs": {
- "url": "https://github.com/ForgeRock/forgerock-javascript-sdk/issues"
- },
- "homepage": "https://github.com/ForgeRock/forgerock-javascript-sdk#readme"
-}
diff --git a/e2e/token-vault-suites/playwright.config.ts b/e2e/token-vault-suites/playwright.config.ts
deleted file mode 100644
index c60fb1315..000000000
--- a/e2e/token-vault-suites/playwright.config.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { PlaywrightTestConfig } from '@playwright/test';
-import { nxE2EPreset } from '@nx/playwright/preset';
-import { workspaceRoot } from '@nx/devkit';
-import { fileURLToPath } from 'url';
-
-const __filename = fileURLToPath(import.meta.url);
-
-// For CI, you may want to set BASE_URL to the deployed application.
-const baseURL = process.env['BASE_URL'] || 'http://localhost:5823';
-
-const baseConfig = nxE2EPreset(__filename, {
- testDir: './src',
-});
-
-const config: PlaywrightTestConfig = {
- ...baseConfig,
- reporter: process.env.CI ? 'github' : 'list',
- timeout: 30000,
- use: {
- baseURL,
- ignoreHTTPSErrors: true,
- geolocation: { latitude: 24.9884, longitude: -87.3459 },
- bypassCSP: true,
- trace: process.env.CI ? 'on-first-retry' : 'retain-on-failure',
- },
- webServer: [
- {
- command: 'pnpm nx serve mock-api',
- url: 'http://localhost:9443/healthcheck',
- ignoreHTTPSErrors: true,
- reuseExistingServer: !process.env.CI,
- cwd: workspaceRoot,
- },
- {
- command: 'pnpm nx serve token-vault-proxy',
- port: 5833,
- ignoreHTTPSErrors: true,
- reuseExistingServer: !process.env.CI,
- cwd: workspaceRoot,
- },
- {
- command: 'pnpm nx serve token-vault-app',
- port: 5823,
- ignoreHTTPSErrors: true,
- reuseExistingServer: !process.env.CI,
- cwd: workspaceRoot,
- },
- ],
-};
-
-export default config;
diff --git a/e2e/token-vault-suites/project.json b/e2e/token-vault-suites/project.json
deleted file mode 100644
index 733a05908..000000000
--- a/e2e/token-vault-suites/project.json
+++ /dev/null
@@ -1,25 +0,0 @@
-{
- "name": "token-vault-suites",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "sourceRoot": "/e2e/token-vault-suites/src",
- "projectType": "application",
- "tags": ["scope:e2e"],
- "implicitDependencies": ["token-vault-app", "token-vault-proxy"],
- "targets": {
- "e2e": {
- "options": {},
- "configurations": {
- "ui": {
- "ui": true
- }
- }
- },
- "lint": {
- "options": {
- "fix": true,
- "ignore-path": ".eslintignore",
- "args": ["**/*.ts"]
- }
- }
- }
-}
diff --git a/e2e/token-vault-suites/src/basic.test.ts b/e2e/token-vault-suites/src/basic.test.ts
deleted file mode 100644
index de98d126e..000000000
--- a/e2e/token-vault-suites/src/basic.test.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { expect, test } from '@playwright/test';
-import { asyncEvents } from './utils/async-events';
-
-test('Test happy paths on test page', async ({ page }) => {
- const { clickButton, getTokens, navigate } = asyncEvents(page);
- await navigate('/');
-
- expect(page.url()).toBe('http://localhost:5823/');
-
- const userLoggedIn = await page.$('#loggedInDef');
- expect(await userLoggedIn.innerText()).toBe('false');
-
- // Click the login button, but wait for a FULL page load of the app
- // That's why we aren't using the `navigate` function from 'async-events.ts'
- await Promise.all([
- page.waitForURL('http://localhost:5823'),
- page.getByRole('button', { name: 'Login' }).click(),
- ]);
-
- // The app should have reloaded and tokens should be present
- // But, it takes a bit for the app to make the call to the iframe to check
- await page.waitForSelector('#loggedInDef:has-text("true")');
- const loggedInDef = await page.$('#loggedInDef');
- expect(await loggedInDef.innerText()).toBe('true');
-
- // Check if tokens are stored in the main app's local storage
- // There should be no tokens as they are in the proxy app's local storage
- const mainAppTokens = await getTokens('http://localhost:5823', 'CentralLoginOAuthClient');
- expect(mainAppTokens).toBeFalsy();
-
- // Check if tokens are stored in the proxy app's local storage
- // They should be present here
- const proxyAppTokens = await getTokens('http://localhost:5833', 'CentralLoginOAuthClient');
- expect(proxyAppTokens.accessToken).toBeTruthy();
-
- // Before we click the "Check for Tokens" button, the app should say "false"
- const hasTokensDef = await page.$('#hasTokensDef');
- expect(await hasTokensDef.innerText()).toBe('false');
-
- // Click the "Check for Tokens" button and wait a bit for the proxy to respond
- // Unfortunately, I don't know how to wait for an iframe to respond on a MessageChannel
- await page.getByRole('button', { name: 'Check for Tokens' }).click();
- await page.waitForTimeout(500);
-
- expect(await hasTokensDef.innerText()).toBe('true');
-
- await clickButton('Refresh Tokens', '/access_token');
-
- // Grab tokens from the proxy app
- const refreshedTokens = await getTokens('http://localhost:5833', 'CentralLoginOAuthClient');
-
- // The refreshed Access Token should be different from the original Access Token
- expect(refreshedTokens.accessToken).not.toBe(proxyAppTokens.accessToken);
-
- await clickButton('Fetch Real User', '/userinfo');
-
- const userInfoDef = await page.$('#userInfoDef');
- expect(await userInfoDef.innerText()).toBe('Bob Tester');
-
- let authorizationHeader = '';
- page.on('request', (request) => {
- if (request.url().includes('jsonplaceholder.typicode.com')) {
- authorizationHeader = request.headers()['authorization'];
- } else if (request.url().includes('thecocktaildb.com')) {
- authorizationHeader = request.headers()['authorization'];
- }
- });
-
- await clickButton('Fetch Protected Mock Todos', '/todos');
-
- // The authorization header should be present and have the refreshed Access Token
- expect(authorizationHeader).toBe(`Bearer ${refreshedTokens.accessToken}`);
-
- // Make unprotected request to cocktail API that is not in urls allowed list
- await clickButton('Fetch Unprotected Mock Data', '/api/json/v1/1/search.php');
-
- // The authorization header should be empty
- expect(authorizationHeader).toBeFalsy();
-
- // Since logout requires multiple requests to complete, we use Promise.all
- await Promise.all([
- page.waitForResponse((response) => response.url().includes('/sessions')),
- page.waitForResponse((response) => response.url().includes('/endSession')),
- page.waitForResponse((response) => response.url().includes('/revoke')),
- page.getByRole('button', { name: 'Logout' }).click(),
- ]);
-
- // Make sure tokens stored on proxy are removed
- const revokedTokens = await getTokens('http://localhost:5833', 'CentralLoginOAuthClient');
- expect(revokedTokens).toBeFalsy();
-});
-/*
- * ensure the proxy is not called when the url is not in the allow list
- * and that the proxy responds with an error
- */
-test('Ensure someone cannot try to call their own url!', async ({ page }) => {
- const { navigate } = asyncEvents(page);
- await navigate('/');
-
- expect(page.url()).toBe('http://localhost:5823/');
-
- const messageArray = [];
- page.on('console', (message) => messageArray.push(message.text()));
-
- await page.click('#hacker');
- expect(
- messageArray.includes('Received TVP_FETCH_RESOURCE event from http://localhost:5823'),
- ).toBe(true);
- expect(messageArray.includes('Proxying https://reqres.in/api/users/2')).toBe(true);
- expect(
- messageArray.includes(
- '{error: unrecognized_origin, message: Unrecognized origin: https://reqres.in. Please configure URLs in Proxy.}',
- ),
- ).toBe(true);
-});
diff --git a/e2e/token-vault-suites/src/utils/async-events.ts b/e2e/token-vault-suites/src/utils/async-events.ts
deleted file mode 100644
index d601fcea9..000000000
--- a/e2e/token-vault-suites/src/utils/async-events.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-export function asyncEvents(page) {
- return {
- async clickButton(text, endpoint) {
- if (!endpoint)
- throw new Error('Must provide endpoint argument, type string, e.g. "/authenticate"');
- await Promise.all([
- page.waitForResponse((response) => response.url().includes(endpoint)),
- page.getByRole('button', { name: text }).click(),
- ]);
- },
- async clickLink(text, endpoint) {
- if (!endpoint)
- throw new Error('Must provide endpoint argument, type string, e.g. "/authenticate"');
- await Promise.all([
- page.waitForResponse((response) => response.url().includes(endpoint)),
- page.getByRole('link', { name: text }).click(),
- ]);
- },
- async getTokens(origin, clientId) {
- const webStorage = await page.context().storageState();
-
- const originStorage = webStorage.origins.find((item) => item.origin === origin);
- // Storage may not have any items
- if (!originStorage) {
- return null;
- }
- const clientIdStorage = originStorage?.localStorage.find((item) => item.name === clientId);
-
- if (clientIdStorage && typeof clientIdStorage.value !== 'string' && !clientIdStorage.value) {
- return null;
- }
- try {
- return JSON.parse(clientIdStorage.value);
- } catch (e) {
- return null;
- }
- },
- async navigate(route) {
- await page.goto(route, { waitUntil: 'networkidle' });
- },
- async pressEnter(endpoint) {
- if (!endpoint)
- throw new Error('Must provide endpoint argument, type string, e.g. "/authenticate"');
- await Promise.all([
- page.waitForResponse((response) => response.url().includes(endpoint)),
- page.keyboard.press('Enter'),
- ]);
- },
- async pressSpacebar(endpoint) {
- if (!endpoint)
- throw new Error('Must provide endpoint argument, type string, e.g. "/authenticate"');
- await Promise.all([
- page.waitForResponse((response) => response.url().includes(endpoint)),
- page.keyboard.press(' '),
- ]);
- },
- };
-}
-
-export async function verifyUserInfo(page, expect, type) {
- const emailString = type === 'register' ? 'Email: test@auto.com' : 'Email: demo@user.com';
- const nameString = 'Full name: Demo User';
-
- const name = page.getByText(nameString);
- const email = page.getByText(emailString);
-
- // Just wait for one of them to be visible
- await name.waitFor();
-
- expect(await name.textContent()).toBe(nameString);
- expect(await email.textContent()).toBe(emailString);
-}
diff --git a/e2e/token-vault-suites/teardown.ts b/e2e/token-vault-suites/teardown.ts
deleted file mode 100644
index 09b49e70b..000000000
--- a/e2e/token-vault-suites/teardown.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export default () => {
- console.log('tests finished');
-};
diff --git a/e2e/token-vault-suites/tsconfig.e2e.json b/e2e/token-vault-suites/tsconfig.e2e.json
deleted file mode 100644
index cf968ee5a..000000000
--- a/e2e/token-vault-suites/tsconfig.e2e.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "composite": true,
- "sourceMap": false,
- "outDir": "../../dist/out-tsc",
- "allowJs": true,
- "module": "Node16"
- },
- "include": ["**/*.ts", "**/*.js"]
-}
diff --git a/e2e/token-vault-suites/tsconfig.json b/e2e/token-vault-suites/tsconfig.json
deleted file mode 100644
index 08841a7f5..000000000
--- a/e2e/token-vault-suites/tsconfig.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "extends": "../../tsconfig.base.json",
- "files": [],
- "include": [],
- "references": [
- {
- "path": "./tsconfig.e2e.json"
- }
- ]
-}
diff --git a/generators.json b/generators.json
new file mode 100644
index 000000000..4e742ad23
--- /dev/null
+++ b/generators.json
@@ -0,0 +1,9 @@
+{
+ "generators": {
+ "create-package-generator": {
+ "factory": "./tools/create-package/src/generators/create-package-generator",
+ "schema": "./tools/create-package/src/generators/schema.json",
+ "description": "create-package-generator generator"
+ }
+ }
+}
diff --git a/nx.json b/nx.json
index e6f043f2c..7d4d99790 100644
--- a/nx.json
+++ b/nx.json
@@ -12,11 +12,6 @@
"noMarkdown": ["!{projectRoot}/**/*.md"]
},
"targetDefaults": {
- "nx-release-publish": {
- "options": {
- "packageRoot": "packages/{projectName}"
- }
- },
"docs": {
"dependsOn": ["build", "^build", "^docs"],
"cache": true,
@@ -24,56 +19,41 @@
},
"serve": {
"cache": false,
- "dependsOn": ["^build"]
+ "dependsOn": ["build"]
},
"e2e": {
"dependsOn": ["^build"],
"inputs": ["noMarkdown", "^noMarkdown"],
+ "outputs": ["{projectRoot}/.playwright"],
"cache": true
},
- "build": {
- "dependsOn": ["^build"],
- "inputs": ["noMarkdown", "^noMarkdown"],
- "cache": true,
- "outputs": ["{projectRoot}/dist"]
- },
- "@nx/vite:test": {
- "dependsOn": ["^test"],
+ "lint": {
+ "dependsOn": ["^lint"],
"inputs": ["noMarkdown", "^noMarkdown"],
- "outputs": ["{projectRoot}/coverage"],
"cache": true
},
- "@nx/eslint:lint": {
- "dependsOn": ["^build", "^lint"],
+ "test": {
+ "dependsOn": ["^build", "^test"],
"inputs": ["noMarkdown", "^noMarkdown"],
+ "outputs": ["{projectRoot}/coverage"],
"cache": true
},
- "@nx/vite:build": {
- "dependsOn": ["^build"],
- "cache": true,
- "inputs": ["noMarkdown", "^noMarkdown"],
- "outputs": ["{projectRoot}/dist"]
- },
- "@nx/playwright:run": {
+ "build": {
"dependsOn": ["^build"],
"inputs": ["noMarkdown", "^noMarkdown"],
- "cache": true
- },
- "@nx/esbuild:esbuild": {
- "dependsOn": ["^build"],
"cache": true,
- "inputs": ["noMarkdown", "^noMarkdown"]
+ "outputs": ["{projectRoot}/dist"]
},
"e2e-ci--**/*": {
"dependsOn": ["^build"],
"inputs": ["noMarkdown", "^noMarkdown"],
+ "outputs": ["{projectRoot}/.playwright"],
"cache": true
},
"@nx/js:tsc": {
"cache": true,
"dependsOn": ["^build"],
- "inputs": ["production", "^production"],
- "outputs": ["{projectRoot}/dist"]
+ "inputs": ["production", "^production"]
}
},
"parallel": 1,
@@ -81,78 +61,6 @@
"appsDir": "",
"libsDir": ""
},
- "release": {
- "projects": ["packages/*"],
- "releaseTagPattern": "v{version}",
- "version": {
- "preVersionCommand": "npx nx run-many -t build",
- "generatorOptions": {
- "currentVersionResolver": "git-tag",
- "specifierSource": "conventional-commits"
- }
- },
- "changelog": {
- "git": {
- "commit": true,
- "tag": true
- },
- "workspaceChangelog": {
- "createRelease": "github"
- },
- "projectChangelogs": true
- }
- },
- "plugins": [
- {
- "plugin": "@nx/playwright/plugin",
- "options": {
- "ciTargetName": "e2e-ci",
- "targetName": "e2e"
- }
- },
- {
- "plugin": "@nx/eslint/plugin",
- "options": {
- "targetName": "lint"
- }
- },
- {
- "plugin": "@nx/vite/plugin",
- "options": {
- "buildTargetName": "build",
- "serveTargetName": "serve",
- "previewTargetName": "preview",
- "testTargetName": "test",
- "serveStaticTargetName": "serve-static",
- "typecheckTargetName": "typecheck"
- },
- "include": ["e2e/**/*", "packages/**/*"]
- },
- {
- "plugin": "@nx/vite/plugin",
- "options": {
- "buildTargetName": "build-interceptor",
- "serveTargetName": "serve",
- "previewTargetName": "preview",
- "testTargetName": "test",
- "serveStaticTargetName": "serve-static",
- "typecheckTargetName": "typecheck"
- },
- "include": ["e2e/token-vault-app/**/*"]
- },
- {
- "plugin": "@nx/vite/plugin",
- "options": {
- "buildTargetName": "vite:build",
- "testTargetName": "vite:test",
- "serveTargetName": "vite:serve",
- "previewTargetName": "vite:preview",
- "serveStaticTargetName": "vite:serve-static",
- "typecheckTargetName": "vite:typecheck"
- }
- }
- ],
- "defaultProject": "javascript-sdk",
"useDaemonProcess": true,
"useInferencePlugins": true,
"defaultBase": "develop",
diff --git a/package.json b/package.json
index d2ebab5a5..11b662888 100644
--- a/package.json
+++ b/package.json
@@ -13,6 +13,7 @@
"ci:version": "changeset version && pnpm install --no-frozen-lockfile && pnpm nx format:write",
"changeset": "changeset",
"commit": "git cz",
+ "create-package": "nx build @forgerock/create-package && nx g @forgerock/create-package:create",
"docs": "nx affected --target=typedoc",
"e2e": "CI=true nx affected:e2e",
"format:staged": "pretty-quick --staged",
@@ -22,7 +23,6 @@
"prepare": "node .husky/install.mjs",
"publish:local": "node ./tools/release/local.mjs",
"publish:dev": "node ./tools/release/dev.mjs",
- "start:token-vault": "nx run-many --target=serve --projects=token-vault-app,token-vault-proxy,mock-api",
"test": "CI=true nx affected:test",
"verdaccio": "nx local-registry",
"commitlint": "commitlint --edit"
@@ -45,19 +45,17 @@
"@effect/platform-node": "^0.53.26",
"@effect/schema": "^0.68.23",
"@effect/vitest": "^0.6.7",
+ "@forgerock/create-package": "workspace:*",
"@nx/devkit": "20.2.2",
- "@nx/esbuild": "20.2.2",
"@nx/eslint": "20.2.2",
"@nx/eslint-plugin": "20.2.2",
- "@nx/express": "20.2.2",
+ "@nx/jest": "20.2.2",
"@nx/js": "20.2.2",
- "@nx/node": "20.2.2",
- "@nx/playwright": "20.2.2",
- "@nx/vite": "20.2.2",
- "@nx/web": "20.2.2",
+ "@nx/plugin": "20.2.2",
"@nx/workspace": "20.2.2",
"@playwright/test": "^1.47.2",
"@swc-node/register": "1.9.2",
+ "@swc/cli": "~0.3.12",
"@swc/core": "1.5.7",
"@swc/helpers": "0.5.12",
"@types/estree": "^1.0.1",
@@ -67,18 +65,14 @@
"@typescript-eslint/parser": "7.16.1",
"@typescript-eslint/typescript-estree": "5.59.5",
"@typescript-eslint/utils": "^8.13.0",
- "@vitejs/plugin-basic-ssl": "1.1.0",
"@vitest/coverage-v8": "^1.5.0",
"@vitest/ui": "^1.4.0",
"conventional-changelog-conventionalcommits": "^7.0.2",
- "cookie-parser": "^1.4.6",
- "cors": "^2.8.5",
"cz-conventional-changelog": "^3.3.0",
"cz-git": "^1.6.1",
"effect": "^3.5.3",
"effect-http": "^0.73.0",
"effect-http-node": "^0.16.1",
- "esbuild": "^0.19.2",
"eslint": "8.57.0",
"eslint-config-prettier": "9.1.0",
"eslint-plugin-import": "2.27.5",
@@ -90,15 +84,12 @@
"jsdom": "22.1.0",
"jsonc-eslint-parser": "^2.1.0",
"lint-staged": "^13.2.2",
- "mkcert": "^3.2.0",
"npm-cli-login": "^1.0.0",
"nx": "20.2.2",
"playwright": "^1.47.2",
"prettier": "^3.2.5",
"pretty-quick": "^4.0.0",
- "sass": "^1.71.1",
"shx": "^0.3.4",
- "superagent": "^8.1.2",
"swc-loader": "0.1.15",
"ts-node": "10.9.1",
"tslib": "^2.5.0",
@@ -106,7 +97,6 @@
"typedoc-github-theme": "0.2.0",
"typedoc-plugin-rename-defaults": "^0.7.2",
"typescript": "5.6.3",
- "uuid": "^9.0.1",
"verdaccio": "^5.29.2",
"vite": "^5.4.8",
"vite-plugin-dts": "^4.2.2",
@@ -126,6 +116,7 @@
},
"packageManager": "pnpm@9.15.0+sha256.09a8fe31a34fda706354680619f4002f4ccef6dadff93240d24ef6c831f0fd28",
"dependencies": {
+ "@nx/devkit": "20.2.2",
"@changesets/changelog-github": "^0.5.0",
"@changesets/cli": "^2.27.9",
"browserstack-node-sdk": "1.34.17",
@@ -147,5 +138,6 @@
"path-to-regexp@<0.1.10": ">=0.1.10",
"rollup@<2.79.2": ">=2.79.2"
}
- }
+ },
+ "generators": "./generators.json"
}
diff --git a/packages/davinci-client/package.json b/packages/davinci-client/package.json
index 5ca2ec646..51edf55dc 100644
--- a/packages/davinci-client/package.json
+++ b/packages/davinci-client/package.json
@@ -15,9 +15,11 @@
"access": "public"
},
"dependencies": {
- "@forgerock/javascript-sdk": "workspace:*",
+ "@forgerock/javascript-sdk": "4.6.0",
"@reduxjs/toolkit": "2.3.0",
- "immer": "10.1.1",
+ "immer": "10.1.1"
+ },
+ "devDependencies": {
"vitest": "^1.4.0"
},
"exports": {
@@ -26,5 +28,12 @@
"require": "./dist/index.js"
},
"./types": "./dist/types.d.ts"
+ },
+ "scripts": {
+ "build": "vite build",
+ "test": "vitest",
+ "test:watch": "vitest --watch",
+ "test:coverage": "vitest --coverage",
+ "lint": "eslint **/*.ts --fix"
}
}
diff --git a/packages/davinci-client/project.json b/packages/davinci-client/project.json
deleted file mode 100644
index 7369a18a1..000000000
--- a/packages/davinci-client/project.json
+++ /dev/null
@@ -1,44 +0,0 @@
-{
- "name": "davinci-client",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "sourceRoot": "packages/davinci-client/src",
- "projectType": "library",
- "tags": ["scope:package"],
- "targets": {
- "docs": {
- "command": "pnpm typedoc --options {projectRoot}/typedoc.json"
- },
- "build": {
- "inputs": [
- "default",
- "^default",
- {
- "externalDependencies": ["vite"]
- }
- ],
- "outputs": ["{projectRoot}/dist"]
- },
- "test": {
- "inputs": [
- "noMarkdown",
- "^noMarkdown",
- {
- "externalDependencies": ["vitest"]
- }
- ]
- },
- "lint": {
- "inputs": [
- "noMarkdown",
- "^noMarkdown",
- {
- "externalDependencies": ["eslint"]
- }
- ],
- "options": {
- "fix": true,
- "args": ["**/*.ts"]
- }
- }
- }
-}
diff --git a/packages/device-client/package.json b/packages/device-client/package.json
index 312567fc0..1a80a74c7 100644
--- a/packages/device-client/package.json
+++ b/packages/device-client/package.json
@@ -15,10 +15,18 @@
"files": ["./dist"],
"dependencies": {
"@reduxjs/toolkit": "2.3.0",
- "@forgerock/javascript-sdk": "4.6.0"
+ "@forgerock/javascript-sdk": "4.6.0",
+ "immer": "10.1.1"
},
"devDependencies": {
"msw": "^2.5.1",
"vitest": "^1.4.0"
+ },
+ "scripts": {
+ "build": "vite build",
+ "test": "vitest",
+ "test:watch": "vitest --watch",
+ "test:coverage": "vitest --coverage",
+ "lint": "eslint **/*.ts --fix"
}
}
diff --git a/packages/device-client/project.json b/packages/device-client/project.json
deleted file mode 100644
index f6337495b..000000000
--- a/packages/device-client/project.json
+++ /dev/null
@@ -1,43 +0,0 @@
-{
- "name": "device-client",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "sourceRoot": "packages/self-service/src",
- "projectType": "library",
- "tags": ["scope:package"],
- "targets": {
- "docs": {
- "command": "pnpm typedoc --options {projectRoot}/typedoc.json"
- },
- "build": {
- "outputs": ["{projectRoot}/{options.outDir}", "{projectRoot}/dist"],
- "options": {
- "assets": ["packages/self-service/*.md"]
- }
- },
- "lint": {
- "options": {
- "fix": true,
- "ignore-path": ".eslintignore",
- "args": ["**/*.ts"]
- }
- },
- "test": {
- "inputs": [
- "default",
- "^default",
- {
- "externalDependencies": ["vitest"]
- }
- ],
- "options": {
- "testPathPattern": ["packages/javascript-sdk/src"]
- },
- "configurations": {
- "watch": {
- "watch": true,
- "mode": "ui"
- }
- }
- }
- }
-}
diff --git a/packages/javascript-sdk/.babelrc b/packages/javascript-sdk/.babelrc
deleted file mode 100644
index 1c3a3a742..000000000
--- a/packages/javascript-sdk/.babelrc
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "presets": [["@nx/js/babel", { "useBuiltIns": false }]]
-}
diff --git a/packages/javascript-sdk/.eslintignore b/packages/javascript-sdk/.eslintignore
deleted file mode 100644
index 6dee592cf..000000000
--- a/packages/javascript-sdk/.eslintignore
+++ /dev/null
@@ -1,10 +0,0 @@
-node_modules
-*.md
-LICENSE
-.babelrc
-.env*
-.bin
-dist
-docs
-coverage
-vite.config.*.timestamp*
diff --git a/packages/javascript-sdk/.eslintrc.json b/packages/javascript-sdk/.eslintrc.json
deleted file mode 100644
index d0f41df6d..000000000
--- a/packages/javascript-sdk/.eslintrc.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "extends": ["../../.eslintrc.json"],
- "overrides": [
- {
- "files": ["*.ts", "*.js"]
- }
- ]
-}
diff --git a/packages/javascript-sdk/CHANGELOG.md b/packages/javascript-sdk/CHANGELOG.md
deleted file mode 100644
index 3112e22ae..000000000
--- a/packages/javascript-sdk/CHANGELOG.md
+++ /dev/null
@@ -1,327 +0,0 @@
-# Changelog
-
-## [4.6.0] - 2024-08-15
-
-### 🚀 Features
-
-- ping-fed-central-login ([57e7c80](https://github.com/ForgeRock/forgerock-javascript-sdk/commit/57e7c80))
-
-- recaptcha-enterprise-callback ([006cec9](https://github.com/ForgeRock/forgerock-javascript-sdk/commit/006cec9))
-
-- support-metadata-marketplace-protect ([a3494b9](https://github.com/ForgeRock/forgerock-javascript-sdk/commit/a3494b9))
-
-- **javascript-sdk:** refactor authorize URL utilities for DaVinci ([b34e458](https://github.com/ForgeRock/forgerock-javascript-sdk/commit/b34e458))
-
-- **javascript-sdk:** recaptcha-enterprise ([8b4656c](https://github.com/ForgeRock/forgerock-javascript-sdk/commit/8b4656c))
-
-### 🩹 Fixes
-
-- **javascript-sdk:** allowed-error-messages ([88ece3f](https://github.com/ForgeRock/forgerock-javascript-sdk/commit/88ece3f))
-
-- **javascript-sdk:** change pkce utility to return storage function ([b4e0fbe](https://github.com/ForgeRock/forgerock-javascript-sdk/commit/b4e0fbe))
-
-### ❤️ Thank You
-
-- Justin Lowery
-- ryanbas21
-
-## [4.4.2] - 2024-05-15
-
-Features:
-feat: new request header by @juangarmendia05 in #432
-
-Fixes:
-fix(javascript-sdk): fix-exports-update-protect by @ryanbas21 in #433
-fix(javascript-sdk): circular-dep by @ryanbas21 in #435
-fix(javascript-sdk): change x-requested-platform to opt-in by @cerebrl in #438
-fix(javascript-sdk): add logout redirect for pingone by @cerebrl in #443
-
-## [4.4.1] - 2024-03-27
-
-Fixes:
-fix(javascript-sdk): Export the classes of ping-protect callbacks from index
-
-## [4.4.0] - 2024-03-12
-
-Features:
-
-feat(javascript-sdk): add config.setAsync for wellknown endpoint support
-feat(javascript-sdk): handle-device-name-in-response
-
-Fixes
-fix(javascript-sdk): add PingOne login error to allowed errors
-fix(javascript-sdk): sessionStorage conflict
-fix(javascript-sdk): circular-dependency
-
-## [4.3.0] - 2024-01-04
-
-Features
-
-- Make a prefix to the storage keys configurable via the Config class
-- Added a QR Code utility class to determine if a step has a QR Code and handle QR Codes in SDK
-
-Fixes
-
-- Fix main and module fields in package.json being undefined
-
-## [4.2.0] - 2023-09-11
-
-Features:
-
-- Added ability for SDK to accept a logLevel and customLogger option in the config. The default to the logger is `none` which means the SDK will no longer output to the console messages/warnings/console.error calls.
-
-## [4.1.2] - 2023-07-20
-
-Features:
-
-- Minor changes to prepare for an upcoming Token Vault release
-
-Fixes:
-
-- fix(javascript-sdk): get-tokens-default-destructure (360df9968d)
-
-## [4.1.1] - 2023-06-29
-
-Features:
-
-- Transaction Authorization advices information adds support for JSON, HTTPClient modified to support this change
-
-Fixes:
-
-- Improved types when in strict mode of Typescript
-
-## [4.0.0] - 2023-05-23
-
-Breaking Changes:
-
-- Dropped UMD bundle support, if you would like to use a UMD bundle it's available in 3.4 or you can produce your own by git cloning the repo and setting up the ability to do so.
-- Removed Event and FRUI modules
-
-Deprecated:
-
-- JavaScript support configuration property deprecated.
-
-Features:
-
-- Updated the esmodule bundle
-- Added interface to register a name to a webauthn device
-
-Fixes:
-
-- Fixed Policy Types so that a PolicyRequirement array is outputted from `failedPolicies`
-
-Infrastructure:
-
-- Updated tags in github to be prefixed with package name
-
-# Changelog
-
-## [3.4.0] - 2022-10-18
-
-- Fixed HTTP headers by capitalizing all header names
-- Add support for TextInput Callback
-- Fix object checks for device profile callback and use globalThis instead of window
-
-## [3.3.1] - 2022-05-18
-
-- Fixed issue where UMD bundle namespace changed
-
-## [3.3.0] - 2022-04-25
-
-### Added:
-
-- OAuth token threshold config property and proactive refresh of tokens expiring soon
-- Add Angular sample app to the repo
-
-## [3.2.2] - 2022-1-31
-
-### Fixed
-
-- Fixed typescript transpilation bug in esmodule config
-
-## [3.2.1] - 2022-1-31
-
-### Fixed
-
-- Updated readme
-
-## [3.2.0] - 2022-1-31
-
-### Fixed
-
-- `/authorize` call not honoring middleware overwrites
-- expand middleware passing to call-site so that it overwrites middleware set in `config`
-
-### Added:
-
-- Refactor of end-to-end test suite to use playwright test runner instead of jest
-- Upgrade rxjs version from 6 to 7 in `autoscript` files for e2e tests
-- Remove SSL certificate dependency in CI
-- Move to using Github Actions for CI
-- Convert to monorepo using `nx`
-- Add react sample app to the repo
-- Remove certificate dependency across all sample apps
-- Replaced development bundle with a rollup production bundle in javascript-sdk package
-- Update Readme's in all packages / samples
-- Added a CONTRIBUTING.MD file
-- Added a pull request template for contributors
-
-## [3.0.0] - 2021-6-24
-
-### Added
-
-- "Native" Social Login callbacks for both the original AM nodes in 6.5 and the new IDM nodes in 7.0
-- SDK Social Login feature officially supports Apple, Facebook and Google
-- New `FRAuth` methods for handing redirection to provider and resuming an authentication journey
- - `FRAuth.redirect` for redirecting to an Identity Provider for authentication
- - `FRAuth.resume` supports both return from an IdP and returning from Email Suspend node
-- New `FRAuth.start` method that aliases `FRAuth.next` to align native mobile SDKs
-- E2E test pages will now follow your OS's dark mode setting
-
-### Fixed
-
-- Arbitrary query parameters are now passed along through to the `/authorize` endpoint supporting the use of ACR values for tree specificity
-- Fixed build issue when using Windows PowerShell
-- WebAuthn error handling is now standardized according to the WebAuthn spec
-- When WebAuthn encounters an error, the SDK now formats the error appropriately for AM and sets it into the hiddenValueCallback; this allows the developer to just send it to AM "as is" or handle it specially when catching the thrown error
-- Changed the default behavior in case of unidentified storage, to be the localStorage option
-- Increased timeout (20 to 60 seconds) for E2E tests to avoid pure timeout failures
-
-### Breaking
-
-- WebAuthn's thrown error message text has been changed to align with spec, so check all conditionals comparing error message strings
-- Renamed `getAuthorizeUrl` method to `getAuthCodeByIframe`
-- Removed the single parameter from `createVerifier` function
-- Removal of `nonce` function
-
-## [2.2.0] - 2020-12-18
-
-### Added
-
-- Centralized login support has been added
-- OAuth authorize endpoint now supports both iframe and fetch through the new `support` property in the config
-- Support for TypeScript 4.0
-
-### Fixed
-
-- `step.getStage()` is no longer used in sample app; `getStage(step)` is now used for better compatibility with AM 6.5
-- `FRUser.logout` now uses a try-catch around each endpoint call, rather than a single try-catch, ensuring an error in one doesn't interrupt other endpoints being called
-- Paths for sample app now point to correct favicon image
-- Improved automation testing
-- Compatibility with AM 6.5.3 WebAuthn nodes
-- Step detection with `getWebAuthnStepType` and "usernameless" configuration
-- `getTokens` method with `forceRenew` now revokes existing tokens, if present, before requesting new ones
-
-## [2.1.0] - 2020-08-25
-
-### Added
-
-- Support for "usernameless" login (storing username on WebAuthn capable tech)
-- Support for the recovery code display node and the parsing of the codes from the TextOutputCallback
-- Support for user verification property for WebAuthn
-- Updated support for new IDM nodes for registration and self-service: BooleanAttributeInputCallback and NumberAttributeInputCallback support
-- Added SuspendedTextOutputCallback support for the new Email Suspended Node
-- Added SessionManager.logout() call back to FRUser.logout()
-
-### Fixed
-
-- Conditionally set user verification, relying party and allow credentials to WebAuthn key options
-- Added exclude credentials to script parsing for WebAuthn key options
-- Ensure display name and username are correctly parsed and added to WebAuthn key options
-- Add authenticator attachment to WebAuthn and other WebAuthn fixes for custom configuration
-- Increased entropy for cryptographic functions related to PKCE for both state and verifier
-- Improved instructions for cert creation for sample app
-
-### Deprecated
-
-- Name change for `getAuthorizeUrl`: method's name will change to better reflect its behavior in v3
-- Removal of `nonce`: this utility is no longer used in the SDK, and therefore will be removed in v3
-- Function signature change for `createVerifier`: the parameter will be removed in v3.
-
-## [2.0.0] - 2020-06-22
-
-### Added
-
-- Support for authorization by transaction
-- Support for authorization by tree
-- Support for device profile collection callback
-- Allow server paths to be configurable
-- Allow OAuth token storage to be configurable
-- Support for request "middleware" for modifying request from SDK
-- "Containerize" code base for easier development
-- End-to-end tests now use Playwright and mock Node.js server
-- Support for WebAuthn script-based authentication
-
-### Fixed
-
-- Increased default timeout to accommodate development/debugging
-- Provide alternative token store for Firefox Private IndexedDB bug
-- Aligned json-based WebAuthn with 7.0 release of AM
-
-## [1.0.5] - 2020-01-16
-
-### Added
-
-- Support for additional querystring parameters (e.g. `suspendedId`) when invoking authentication trees
-
-## [1.0.4] - 2020-01-06
-
-### Fixed
-
-- Renamed `getWebAuthStepType` to `getWebAuthnStepType` in `FRWebAuthn` module
-
-## [1.0.3] - 2020-01-06
-
-### Added
-
-- Replaced `url` and `querystring` dependencies to avoid build issues in some environments
-
-## [1.0.2] - 2019-12-20
-
-### Added
-
-- Exported `Deferred` and `nonce`
-
-## [1.0.1] - 2019-12-19
-
-### Added
-
-- Server mocking with Mirage JS for E2E tests
-- Version header to all OpenAM calls to avoid CSRF problems
-- Updated callback interface to reflect that some properties are optional
-
-## [1.0.0] - 2019-12-09
-
-### Added
-
-- WebAuthn module that can be used in custom UIs
-- Improvements to `FRCallback`
-- Addressed all linter warnings
-
-## [0.9.3] - 2019-11-13
-
-### Fixed
-
-- Non-relative import in FRAuth module
-
-## [0.9.2] - 2019-11-06
-
-### Added
-
-- OAuth2Client obeys `realmPath` configuration setting
-
-## [0.9.1] - 2019-10-28
-
-### Added
-
-- FRPolicy module allows easy consumption and customization of policy-related errors
-- Export `SessionManager` module
-- `FRStep.type` property to simplify conditional handling of tree responses
-- Overhaul and expansion of tests to include unit, integration, and e2e testing
-
-## [0.9.0] - 2019-10-17
-
-### Added
-
-- Initial release for SDK
-- Initial npm deployment for beta version
diff --git a/packages/javascript-sdk/LICENSE b/packages/javascript-sdk/LICENSE
deleted file mode 100644
index e5396cc66..000000000
--- a/packages/javascript-sdk/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2019 ForgeRock
-
-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.
diff --git a/packages/javascript-sdk/README.md b/packages/javascript-sdk/README.md
deleted file mode 100644
index 67ca80f5d..000000000
--- a/packages/javascript-sdk/README.md
+++ /dev/null
@@ -1,177 +0,0 @@
-[](CHANGELOG.md)
-[](https://github.com/ForgeRock/forgerock-javascript-sdk/actions/workflows/ci.yml)
-
-
-
-
-
-
ForgeRock SDK for JavaScript
-
- Change Log
- ·
- Support
- ·
- Docs
-
-
-
-The ForgeRock JavaScript SDK enables you to quickly integrate the [ForgeRock Identity Platform](https://www.forgerock.com/digital-identity-and-access-management-platform) into your client-side JavaScript apps.
-
-Use the SDKs to leverage _[Intelligent Authentication](https://www.forgerock.com/platform/access-management/intelligent-authentication)_ in [ForgeRock's Access Management (AM)](https://www.forgerock.com/platform/access-management) product, to easily step through each stage of an authentication tree by using callbacks.
-
-
-
-
-## Requirements
-
-- ForgeRock Identity Platform
-
- - Access Management (AM) 6.5.2+
-
-- Browsers:
- - Chrome 87
- - Firefox 84
- - Safari 14
- - Edge 87 (Chromium)
- - Edge 44 (Legacy): requires one polyfill for TextEncoder, [`fast-text-encoding` is recommended](https://www.npmjs.com/package/fast-text-encoding)
-
-> **Tip**: Older browsers (like IE11) may require multiple [polyfills, which can be found in our documentation](https://sdks.forgerock.com/javascript/polyfills/).
-
-
-
-
-## Installation
-
-```
-npm install @forgerock/javascript-sdk
-```
-
-
-
-
-## Getting Started
-
-To try out the ForgeRock JavaScript SDK, perform these steps:
-
-1. Setup CORS support in an Access Management (AM) instance.
-
- See [Enabling CORS Support](https://sdks.forgerock.com/js/01_prepare-am/#enabling-cors-support) in the Documentation.
-
-2. Create an authentication tree in AM.
-
- See [Creating a User Authentication Tree](https://sdks.forgerock.com/js/01_prepare-am/#creating-a-user-authentication-tree) in the Documentation.
-
-3. Clone this repo:
-
- ```
- git clone https://github.com/ForgeRock/forgerock-javascript-sdk.git
- ```
-
-4. In the root folder of the repo, use NPM to install dependencies:
-
- ```
- npm install
- ```
-
-5. Build the ForgeRock JavaScript SDK:
-
- ```
- pnpm run build
- ```
-
-6. Open `samples/embedded-login/index.html` and edit the configuration values to match your AM instance.
-
-7. Serve the `samples` directory by using a simple HTTP server.
-
- - Run `pnpm run start:samples`
-
-8. Edit your `/etc/hosts` file to point your localhost (e.g. `127.0.0.1`) to `sdkapp.example.com`
-
-9. In a [supported web browser](#requirements), navigate to `https://sdkapp.example.com:8443`, and then click **Embedded Login**.
-
-
-
-
-## Samples
-
-ForgeRock provides these samples to help demonstrate SDK functionality/implementation. They are provided "as is" and are not official products of ForgeRock and are not officially supported.
-
-- **Embedded login - `/samples/embedded-login`**
-
- In most real-world scenarios, you will want to have full control over the UI. In these cases, you can use `FRAuth` to obtain typed callback instances from authentication trees and render the UI in whatever way makes sense for your application.
-
- You can run this sample app with the `pnpm run start:samples` command. Please [see the Getting Started instructions](#getting-started) for more details.
-
-- **Central login - `/samples/central-login`**
-
- In cases in which a centralized login application is desired, in contrast to an embedded login form, the SDK provides a method for leveraging an OAuth flow known as Authorization Code Flow (with PKCE). By using an option (login of "redirect") provided by `TokenManager` to request OAuth/OIDC tokens, when the user is not authenticated, the SDK will redirect the user to the configured login application with the ForgeRock platform. Once authenticated, the user will be redirected back to the original application to attain OAuth/OIDC tokens to complete the user flow.
-
- You can run this sample app with the `pnpm run start:samples` command. Please [see the Getting Started instructions](#getting-started) for more details.
-
-- **React todos - `/samples/reactjs-todos`**
-
- A sample React JS application is provided to demonstrate how the JavaScript SDK can be implemented within a React context. You can read more about this application by [visiting its README.md file](samples/reactjs-todo/README.md).
-
- Since this sample app uses npm's workspaces feature, npm 7 or higher is required. When on npm 7+, dependencies are already installed when running `npm install`. You can run this sample app with: `npx nx run reactjs-todo:serve`.
-
-
-
-
-## Documentation
-
-Documentation for the SDKs is provided at ****, and includes topics such as:
-
-- Introducing the SDK Features
-- Preparing AM for use with the SDKS
-- API Reference documentation
-
-
-
-
-## Support
-
-If you encounter any issues, be sure to check our **[Troubleshooting](https://backstage.forgerock.com/knowledge/kb/article/a83789945)** pages.
-
-Support tickets can be raised whenever you need our assistance; here are some examples of when it is appropriate to open a ticket (but not limited to):
-
-- Suspected bugs or problems with ForgeRock software.
-- Requests for assistance - please look at the **[Documentation](https://sdks.forgerock.com)** and **[Knowledge Base](https://backstage.forgerock.com/knowledge/kb/home/g32324668)** first.
-
-You can raise a ticket using **[BackStage](https://backstage.forgerock.com/support/tickets)**, our customer support portal that provides one stop access to ForgeRock services.
-
-BackStage shows all currently open support tickets and allows you to raise a new one by clicking **New Ticket**.
-
-## Version History
-
-[Our version history can be viewed by visiting our CHANGELOG.md](https://github.com/ForgeRock/forgerock-javascript-sdk/blob/master/CHANGELOG.md).
-
-
-
-
-## Contributing
-
-If you would like to contribute to this project you can fork the repository, clone it to your machine and get started.
-
-
-
-Be sure to check out our [Coding Style and Guidelines](https://wikis.forgerock.org/confluence/display/devcom/Coding+Style+and+Guidelines) page.
-
-
-
-
-## Disclaimer
-
-> **This code is provided by ForgeRock on an “as is” basis, without warranty of any kind, to the fullest extent permitted by law. ForgeRock does not represent or warrant or make any guarantee regarding the use of this code or the accuracy, timeliness or completeness of any data or information relating to this code, and ForgeRock hereby disclaims all warranties whether express, or implied or statutory, including without limitation the implied warranties of merchantability, fitness for a particular purpose, and any warranty of non-infringement. ForgeRock shall not have any liability arising out of or related to any use, implementation or configuration of this code, including but not limited to use for any commercial purpose. Any action or suit relating to the use of the code may be brought only in the courts of a jurisdiction wherein ForgeRock resides or in which ForgeRock conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions.**
-
-
-
-
-## License
-
-This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details
-
----
-
-© Copyright 2020 ForgeRock AS. All Rights Reserved.
-
-[forgerock-logo]: https://www.forgerock.com/themes/custom/forgerock/images/fr-logo-horz-color.svg 'ForgeRock Logo'
diff --git a/packages/javascript-sdk/package.json b/packages/javascript-sdk/package.json
deleted file mode 100644
index ad8ece6c5..000000000
--- a/packages/javascript-sdk/package.json
+++ /dev/null
@@ -1,54 +0,0 @@
-{
- "name": "@forgerock/javascript-sdk",
- "version": "4.6.0",
- "description": "ForgeRock JavaScript SDK",
- "author": "ForgeRock",
- "license": "MIT",
- "files": ["dist/*"],
- "repository": {
- "type": "git",
- "url": "git+https://github.com:ForgeRock/forgerock-javascript-sdk.git",
- "directory": "packages/javascript-sdk"
- },
- "bugs": {
- "url": "https://github.com/ForgeRock/forgerock-javascript-sdk/issues"
- },
- "homepage": "https://github.com/ForgeRock/forgerock-javascript-sdk#readme",
- "main": "./dist/index.cjs",
- "module": "./dist/index.js",
- "sideEffects": false,
- "types": "./dist/index.d.ts",
- "exports": {
- ".": {
- "import": {
- "types": "./dist/index.d.ts",
- "default": "./dist/index.js"
- },
- "require": {
- "types": "./dist/index.d.cts",
- "default": "./dist/index.cjs"
- }
- },
- "./src/*": {
- "import": {
- "types": "./dist/*.d.ts",
- "default": "./dist/*.js"
- },
- "require": {
- "types": "./dist/*.d.cts",
- "default": "./dist/*.cjs"
- }
- },
- "./src/": {
- "import": {
- "types": "./dist/*.d.ts",
- "default": "./dist/*.js"
- },
- "require": {
- "types": "./dist/*.d.cts",
- "default": "./dist/*.cjs"
- }
- }
- },
- "type": "module"
-}
diff --git a/packages/javascript-sdk/project.json b/packages/javascript-sdk/project.json
deleted file mode 100644
index 3f07bf934..000000000
--- a/packages/javascript-sdk/project.json
+++ /dev/null
@@ -1,47 +0,0 @@
-{
- "name": "javascript-sdk",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "sourceRoot": "packages/javascript-sdk/src",
- "projectType": "library",
- "tags": ["scope:sdk"],
- "targets": {
- "docs": {
- "command": "pnpm typedoc --options {projectRoot}/typedoc.json"
- },
- "build": {
- "inputs": [
- "default",
- "^default",
- {
- "externalDependencies": ["vite"]
- }
- ],
- "outputs": ["{projectRoot}/dist"]
- },
- "lint": {
- "options": {
- "fix": true,
- "ignore-path": ".eslintignore",
- "args": ["**/*.ts"]
- }
- },
- "test": {
- "inputs": [
- "default",
- "^default",
- {
- "externalDependencies": ["vitest"]
- }
- ],
- "options": {
- "testPathPattern": ["packages/javascript-sdk/src"]
- },
- "configurations": {
- "watch": {
- "watch": true,
- "mode": "ui"
- }
- }
- }
- }
-}
diff --git a/packages/javascript-sdk/src/auth/enums.ts b/packages/javascript-sdk/src/auth/enums.ts
deleted file mode 100644
index 435769fe3..000000000
--- a/packages/javascript-sdk/src/auth/enums.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * enums.ts
- *
- * Copyright (c) 2020-2024 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/**
- * Known errors that can occur during authentication.
- */
-enum ErrorCode {
- BadRequest = 'BAD_REQUEST',
- Timeout = 'TIMEOUT',
- Unauthorized = 'UNAUTHORIZED',
- Unknown = 'UNKNOWN',
-}
-
-/**
- * Types of callbacks directly supported by the SDK.
- */
-enum CallbackType {
- BooleanAttributeInputCallback = 'BooleanAttributeInputCallback',
- ChoiceCallback = 'ChoiceCallback',
- ConfirmationCallback = 'ConfirmationCallback',
- DeviceProfileCallback = 'DeviceProfileCallback',
- HiddenValueCallback = 'HiddenValueCallback',
- KbaCreateCallback = 'KbaCreateCallback',
- MetadataCallback = 'MetadataCallback',
- NameCallback = 'NameCallback',
- NumberAttributeInputCallback = 'NumberAttributeInputCallback',
- PasswordCallback = 'PasswordCallback',
- PingOneProtectEvaluationCallback = 'PingOneProtectEvaluationCallback',
- PingOneProtectInitializeCallback = 'PingOneProtectInitializeCallback',
- PollingWaitCallback = 'PollingWaitCallback',
- ReCaptchaCallback = 'ReCaptchaCallback',
- ReCaptchaEnterpriseCallback = 'ReCaptchaEnterpriseCallback',
- RedirectCallback = 'RedirectCallback',
- SelectIdPCallback = 'SelectIdPCallback',
- StringAttributeInputCallback = 'StringAttributeInputCallback',
- SuspendedTextOutputCallback = 'SuspendedTextOutputCallback',
- TermsAndConditionsCallback = 'TermsAndConditionsCallback',
- TextInputCallback = 'TextInputCallback',
- TextOutputCallback = 'TextOutputCallback',
- ValidatedCreatePasswordCallback = 'ValidatedCreatePasswordCallback',
- ValidatedCreateUsernameCallback = 'ValidatedCreateUsernameCallback',
-}
-
-export { CallbackType, ErrorCode };
diff --git a/packages/javascript-sdk/src/auth/index.ts b/packages/javascript-sdk/src/auth/index.ts
deleted file mode 100644
index 682f06b55..000000000
--- a/packages/javascript-sdk/src/auth/index.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { ServerConfig, StepOptions } from '../config';
-import Config from '../config';
-import { ActionTypes } from '../config/enums';
-import { REQUESTED_WITH, X_REQUESTED_PLATFORM } from '../shared/constants';
-import type { StringDict } from '../shared/interfaces';
-import { withTimeout } from '../util/timeout';
-import { getEndpointPath, resolve, stringify } from '../util/url';
-import type { Step } from './interfaces';
-import middlewareWrapper from '../util/middleware';
-
-/**
- * Provides direct access to the OpenAM authentication tree API.
- */
-abstract class Auth {
- /**
- * Gets the next step in the authentication tree.
- *
- * @param {Step} previousStep The previous step, including any required input.
- * @param {StepOptions} options Configuration default overrides.
- * @return {Step} The next step in the authentication tree.
- */
- public static async next(previousStep?: Step, options?: StepOptions): Promise {
- const { middleware, platformHeader, realmPath, serverConfig, tree, type } = Config.get(options);
- const query = options ? options.query : {};
- const url = this.constructUrl(serverConfig, realmPath, tree, query);
- const runMiddleware = middlewareWrapper(
- {
- url: new URL(url),
- init: this.configureRequest(previousStep),
- },
- {
- type: previousStep ? ActionTypes.Authenticate : ActionTypes.StartAuthenticate,
- payload: {
- tree,
- type: type ? type : 'service',
- },
- },
- );
- const req = runMiddleware(middleware);
-
- /**
- * Run after as to now allow mutation by user
- * Since the init headers can be an array, object or Headers class,
- * we need to handle all types.
- */
- if (platformHeader) {
- if (req.init.headers instanceof Headers) {
- req.init.headers.set('X-Requested-Platform', X_REQUESTED_PLATFORM);
- } else if (Array.isArray(req.init.headers)) {
- req.init.headers.push(['X-Requested-Platform', X_REQUESTED_PLATFORM]);
- } else if (req.init.headers) {
- req.init.headers['X-Requested-Platform'] = X_REQUESTED_PLATFORM;
- } else {
- req.init.headers = {
- 'X-Requested-Platform': X_REQUESTED_PLATFORM,
- };
- }
- }
- const res = await withTimeout(fetch(req.url.toString(), req.init), serverConfig.timeout);
- const json = await this.getResponseJson(res);
- return json;
- }
-
- private static constructUrl(
- serverConfig: ServerConfig,
- realmPath?: string,
- tree?: string,
- query?: StringDict,
- ): string {
- const treeParams = tree ? { authIndexType: 'service', authIndexValue: tree } : undefined;
- const params: StringDict = { ...query, ...treeParams };
- const queryString = Object.keys(params).length > 0 ? `?${stringify(params)}` : '';
- const path = getEndpointPath('authenticate', realmPath, serverConfig.paths);
- const url = resolve(serverConfig.baseUrl, `${path}${queryString}`);
- return url;
- }
-
- private static configureRequest(step?: Step): RequestInit {
- const init: RequestInit = {
- body: step ? JSON.stringify(step) : undefined,
- credentials: 'include',
- headers: new Headers({
- Accept: 'application/json',
- 'Accept-API-Version': 'protocol=1.0,resource=2.1',
- 'Content-Type': 'application/json',
- 'X-Requested-With': REQUESTED_WITH,
- }),
- method: 'POST',
- };
-
- return init;
- }
-
- private static async getResponseJson(res: Response): Promise {
- const contentType = res.headers.get('content-type');
- const isJson = contentType && contentType.indexOf('application/json') > -1;
- const json = isJson ? await res.json() : {};
- json.status = res.status;
- json.ok = res.ok;
- return json;
- }
-}
-
-export default Auth;
diff --git a/packages/javascript-sdk/src/auth/interfaces.ts b/packages/javascript-sdk/src/auth/interfaces.ts
deleted file mode 100644
index e022d2a56..000000000
--- a/packages/javascript-sdk/src/auth/interfaces.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * interfaces.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { CallbackType } from './enums';
-
-/**
- * Represents the authentication tree API payload schema.
- */
-interface Step {
- authId?: string;
- callbacks?: Callback[];
- code?: number;
- description?: string;
- detail?: StepDetail;
- header?: string;
- message?: string;
- ok?: string;
- realm?: string;
- reason?: string;
- stage?: string;
- status?: number;
- successUrl?: string;
- tokenId?: string;
-}
-
-/**
- * Represents details of a failure in an authentication step.
- */
-interface StepDetail {
- failedPolicyRequirements?: FailedPolicyRequirement[];
- failureUrl?: string;
- result?: boolean;
-}
-
-/**
- * Represents failed policies for a matching property.
- */
-interface FailedPolicyRequirement {
- policyRequirements: PolicyRequirement[];
- property: string;
-}
-
-/**
- * Represents a failed policy policy and failed policy params.
- */
-interface PolicyRequirement {
- params?: Partial;
- policyRequirement: string;
-}
-
-interface PolicyParams {
- [key: string]: unknown;
- disallowedFields: string;
- duplicateValue: string;
- forbiddenChars: string;
- maxLength: number;
- minLength: number;
- numCaps: number;
- numNums: number;
-}
-
-/**
- * Represents the authentication tree API callback schema.
- */
-interface Callback {
- _id?: number;
- input?: NameValue[];
- output: NameValue[];
- type: CallbackType;
-}
-
-/**
- * Represents a name/value pair found in an authentication tree callback.
- */
-interface NameValue {
- name: string;
- value: unknown;
-}
-
-export type {
- Callback,
- FailedPolicyRequirement,
- NameValue,
- PolicyParams,
- PolicyRequirement,
- Step,
- StepDetail,
-};
diff --git a/packages/javascript-sdk/src/config/constants.ts b/packages/javascript-sdk/src/config/constants.ts
deleted file mode 100644
index 1a301ecc5..000000000
--- a/packages/javascript-sdk/src/config/constants.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * constants.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/** @hidden */
-const DEFAULT_TIMEOUT = 5 * 1000;
-const DEFAULT_OAUTH_THRESHOLD = 30 * 1000;
-const PREFIX = 'FR-SDK';
-
-export { DEFAULT_TIMEOUT, DEFAULT_OAUTH_THRESHOLD, PREFIX };
diff --git a/packages/javascript-sdk/src/config/enums.ts b/packages/javascript-sdk/src/config/enums.ts
deleted file mode 100644
index 75ba147a8..000000000
--- a/packages/javascript-sdk/src/config/enums.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * enums.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-export enum ActionTypes {
- Authenticate = 'AUTHENTICATE',
- Authorize = 'AUTHORIZE',
- EndSession = 'END_SESSION',
- Logout = 'LOGOUT',
- ExchangeToken = 'EXCHANGE_TOKEN',
- RefreshToken = 'REFRESH_TOKEN',
- ResumeAuthenticate = 'RESUME_AUTHENTICATE',
- RevokeToken = 'REVOKE_TOKEN',
- StartAuthenticate = 'START_AUTHENTICATE',
- UserInfo = 'USER_INFO',
- WellKnown = 'WELL_KNOWN',
-}
diff --git a/packages/javascript-sdk/src/config/helpers.test.ts b/packages/javascript-sdk/src/config/helpers.test.ts
deleted file mode 100644
index c1b2ca168..000000000
--- a/packages/javascript-sdk/src/config/helpers.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { convertWellKnown } from './helpers';
-import { frWellKnown, piWellKnown } from './well-known.mock';
-
-describe('Test config helpers', () => {
- it('should test wellknown response conversion ForgeRock', () => {
- const result = convertWellKnown(frWellKnown);
- const expected = {
- baseUrl: 'https://openam-spetrov.forgeblocks.com',
- paths: {
- accessToken: '/am/oauth2/alpha/access_token',
- authenticate: '/am/json/alpha/authenticate',
- authorize: '/am/oauth2/alpha/authorize',
- endSession: '/am/oauth2/alpha/connect/endSession',
- revoke: '/am/oauth2/alpha/token/revoke',
- sessions: '/am/json/alpha/sessions',
- userInfo: '/am/oauth2/alpha/userinfo',
- },
- };
- expect(result).toStrictEqual(expected);
- });
-
- it('should test wellknown response conversion from Ping', () => {
- const result = convertWellKnown(piWellKnown);
- const expected = {
- baseUrl: 'https://auth.pingone.ca',
- paths: {
- accessToken: '/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/token',
- authorize: '/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/authorize',
- endSession: '/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/signoff',
- revoke: '/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/revoke',
- userInfo: '/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/userinfo',
- },
- };
- expect(result).toStrictEqual(expected);
- });
-});
diff --git a/packages/javascript-sdk/src/config/helpers.ts b/packages/javascript-sdk/src/config/helpers.ts
deleted file mode 100644
index 5f1c56208..000000000
--- a/packages/javascript-sdk/src/config/helpers.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * helpers.ts
- *
- * Copyright (c) 2024 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import middlewareWrapper from '../util/middleware';
-import { withTimeout } from '../util/timeout';
-import { ActionTypes } from './enums';
-import type { AsyncConfigOptions, ServerConfig, WellKnownResponse } from './interfaces';
-
-/**
- * @function convertWellKnown - Convert the response from welknown into SDK config
- * @param {WellKnownResponse} data - response from wellknown endpoint
- * @returns {ServerConfig}
- */
-export function convertWellKnown(data: WellKnownResponse, options?: ServerConfig): ServerConfig {
- if (!data.authorization_endpoint) {
- throw new Error('Wellknown endpoint did not return `authorization_endpoint`');
- }
-
- const fullUrl = new URL(data.authorization_endpoint);
- const baseUrl = fullUrl.origin;
-
- let authenticateUrl: string | undefined;
- let sessionsUrl: string | undefined;
-
- if (options?.paths) {
- // Prioritize user provided URLs for authenticate and session as they are NOT provided in wellknown response
- authenticateUrl = options?.paths?.authenticate;
- sessionsUrl = options?.paths?.sessions;
- } else if (data.issuer.includes('/am/')) {
- // If no authentiate and session URL provided, detect AM and use standard `/authenticate`
- authenticateUrl = `${data.issuer.replace('oauth2', 'json')}/authenticate`;
- // Use standard AM `/sessions`
- sessionsUrl = `${data.issuer.replace('oauth2', 'json')}/sessions`;
- } else if (data.issuer.includes('/as/')) {
- // URLs for PingOne's authenticate and sessions, once supported
- }
-
- const paths = {
- ...(authenticateUrl ? { authenticate: new URL(authenticateUrl).pathname } : {}),
- authorize: new URL(data.authorization_endpoint).pathname,
- accessToken: new URL(data.token_endpoint).pathname,
- endSession: new URL(data.end_session_endpoint).pathname,
- userInfo: new URL(data.userinfo_endpoint).pathname,
- revoke: new URL(data.revocation_endpoint).pathname,
- ...(sessionsUrl ? { sessions: new URL(sessionsUrl).pathname } : {}),
- };
-
- return {
- baseUrl,
- paths,
- };
-}
-
-/**
- * @function fetchWellKnown - Fetch the wellknown endpoint for OAuth/OIDC URLs
- */
-export async function fetchWellKnown(options: AsyncConfigOptions): Promise {
- if (!options.serverConfig.wellknown) {
- throw new Error('wellknown URL is missing in options');
- }
-
- const runMiddleware = middlewareWrapper(
- {
- url: new URL(options.serverConfig?.wellknown),
- init: { method: 'GET' },
- },
- {
- type: ActionTypes.WellKnown,
- payload: {},
- },
- );
- const req = runMiddleware(options.middleware);
- const res = await withTimeout(fetch(req.url.toString(), req.init), options.serverConfig.timeout);
-
- const json = await res.json();
- return json;
-}
diff --git a/packages/javascript-sdk/src/config/index.ts b/packages/javascript-sdk/src/config/index.ts
deleted file mode 100644
index 020aff13f..000000000
--- a/packages/javascript-sdk/src/config/index.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.ts
- *
- * Copyright (c) 2020-2024 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { DEFAULT_TIMEOUT, DEFAULT_OAUTH_THRESHOLD, PREFIX } from './constants';
-import { convertWellKnown, fetchWellKnown } from './helpers';
-import type {
- AsyncConfigOptions,
- ConfigOptions,
- ServerConfig,
- StepOptions,
- ValidConfigOptions,
-} from './interfaces';
-
-/**
- * Sets defaults for options that are required but have no supplied value
- * @param options The options to set defaults for
- * @returns options The options with defaults
- */
-function setDefaults(options: ConfigOptions): ConfigOptions {
- return {
- ...options,
- oauthThreshold: options.oauthThreshold || DEFAULT_OAUTH_THRESHOLD,
- logLevel: options.logLevel || 'none',
- platformHeader: options.platformHeader || false,
- prefix: options.prefix || PREFIX,
- };
-}
-
-/**
- * Utility for merging configuration defaults with one-off options.
- *
- * Example:
- *
- * ```js
- * // Establish configuration defaults
- * Config.set({
- * clientId: 'myApp',
- * serverConfig: { baseUrl: 'https://openam-domain.com/am' },
- * tree: 'UsernamePassword'
- * });
- *
- * // Specify overrides as needed
- * const configOverrides = { tree: 'PasswordlessWebAuthn' };
- * const step = await FRAuth.next(undefined, configOverrides);
- */
-abstract class Config {
- private static options: ConfigOptions;
-
- /**
- * Sets the default options.
- *
- * @param options The options to use as defaults
- */
- public static set(options: ConfigOptions): void {
- if (!this.isValid(options)) {
- throw new Error('Configuration is invalid');
- }
- if (options.serverConfig) {
- this.validateServerConfig(options.serverConfig);
- }
- this.options = { ...setDefaults(options) };
- }
-
- /**
- * @method setAsync - Asynchronously calls the WellKnown endpoint to collect the APIs for OAuth
- * @param {AsyncConfigOptions} options - config options with wellknown endpoint URL
- * @returns {Promise} - Returns a success or failure message object
- */
- public static async setAsync(options: AsyncConfigOptions): Promise {
- if (!options.serverConfig.wellknown) {
- throw new Error(
- 'Missing well-known property. Use `Config.set` method if not using well-known endpoint.',
- );
- }
- // @ts-expect-error safety against runtimes without typescript
- if (options.serverConfig.baseUrl) {
- console.warn(
- 'The baseUrl property passed in will be ignored, and replaced with well-known origin.',
- );
- }
-
- // Fetch wellknown endpoint for OAuth/OIDC API URLs
- const json = await fetchWellKnown(options);
- // Use wellknown object and convert to custom paths
- const serverConfig = convertWellKnown(json);
-
- // Remove wellknown property as it's no longer needed
- delete options.serverConfig.wellknown;
- // Assign to a new config object with the "sync" config type
- const newConfig = options as ConfigOptions;
- newConfig.serverConfig = serverConfig;
-
- // Set the config as usual
- this.set(newConfig);
- }
-
- /**
- * Merges the provided options with the default options. Ensures a server configuration exists.
- *
- * @param options The options to merge with defaults
- */
- public static get(options?: ConfigOptions): ValidConfigOptions {
- if (!this.options && !options) {
- throw new Error('Configuration has not been set');
- }
-
- const merged = { ...this.options, ...options };
- if (!merged.serverConfig || !merged.serverConfig.baseUrl) {
- throw new Error('Server configuration has not been set');
- }
-
- return merged as ValidConfigOptions;
- }
-
- private static isValid(options: ConfigOptions): boolean {
- return !!(options && options.serverConfig);
- }
-
- private static validateServerConfig(serverConfig: ServerConfig): void {
- if (!serverConfig.timeout) {
- serverConfig.timeout = DEFAULT_TIMEOUT;
- }
-
- const url = serverConfig.baseUrl;
- if (url && url.charAt(url.length - 1) !== '/') {
- serverConfig.baseUrl = url + '/';
- }
- }
-}
-
-export default Config;
-export type { ConfigOptions, ServerConfig, ValidConfigOptions, StepOptions };
diff --git a/packages/javascript-sdk/src/config/interfaces.ts b/packages/javascript-sdk/src/config/interfaces.ts
deleted file mode 100644
index 7d183d373..000000000
--- a/packages/javascript-sdk/src/config/interfaces.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * interfaces.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { ActionTypes } from './enums';
-import type { FRCallbackFactory } from '../fr-auth/callbacks/factory';
-import type { StringDict, Tokens } from '../shared/interfaces';
-
-type LogLevel = 'none' | 'info' | 'warn' | 'error' | 'debug';
-
-interface Action {
- type: ActionTypes;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- payload: any;
-}
-
-/**
- * Custom Logger for logger
- */
-interface LoggerFunctions<
- W = (...msgs: unknown[]) => void,
- E = (...msgs: unknown[]) => void,
- L = (...msgs: unknown[]) => void,
- I = (...msgs: unknown[]) => void,
-> {
- warn?: W;
- error?: E;
- log?: L;
- info?: I;
-}
-/**
- * Configuration options.
- */
-interface ConfigOptions {
- callbackFactory?: FRCallbackFactory;
- clientId?: string;
- middleware?: RequestMiddleware[];
- realmPath?: string;
- redirectUri?: string;
- scope?: string;
- serverConfig?: ServerConfig;
- tokenStore?: TokenStoreObject | 'sessionStorage' | 'localStorage';
- tree?: string;
- type?: string;
- oauthThreshold?: number;
- logLevel?: LogLevel;
- logger?: LoggerFunctions;
- platformHeader?: boolean;
- prefix?: string;
-}
-
-/**
- * Async ConfigOptions for well-known endpoint usage
- */
-interface AsyncConfigOptions extends Omit {
- serverConfig: AsyncServerConfig;
-}
-
-type ConfigurablePaths = keyof CustomPathConfig;
-/**
- * Optional configuration for custom paths for actions
- */
-interface CustomPathConfig {
- authenticate?: string;
- authorize?: string;
- accessToken?: string;
- endSession?: string;
- userInfo?: string;
- revoke?: string;
- sessions?: string;
-}
-
-type RequestMiddleware = (req: RequestObj, action: Action, next: () => RequestObj) => void;
-
-interface RequestObj {
- url: URL;
- init: RequestInit;
-}
-
-/**
- * Configuration settings for connecting to a server.
- */
-interface ServerConfig {
- baseUrl: string;
- paths?: CustomPathConfig;
- timeout?: number;
-}
-
-/**
- * Configuration settings for async config with well-known
- */
-interface AsyncServerConfig extends Omit {
- wellknown?: string;
-}
-
-/**
- * API for implementing a custom token store
- */
-interface TokenStoreObject {
- get: (clientId: string) => Promise;
- set: (clientId: string, token: Tokens) => Promise;
- remove: (clientId: string) => Promise;
-}
-
-/**
- * Configuration options with a server configuration specified.
- */
-interface ValidConfigOptions extends ConfigOptions {
- serverConfig: ServerConfig;
- logLevel: LogLevel;
-}
-
-/**
- * Represents configuration overrides used when requesting the next
- * step in an authentication tree.
- */
-interface StepOptions extends ConfigOptions {
- query?: StringDict;
-}
-
-interface WellKnownResponse {
- issuer: string;
- authorization_endpoint: string;
- pushed_authorization_request_endpoint?: string;
- token_endpoint: string;
- userinfo_endpoint: string;
- end_session_endpoint: string;
- introspection_endpoint: string;
- revocation_endpoint: string;
- jwks_uri?: string;
- device_authorization_endpoint?: string;
- claims_parameter_supported?: boolean;
- request_parameter_supported?: boolean;
- request_uri_parameter_supported?: boolean;
- require_pushed_authorization_requests?: boolean;
- scopes_supported?: string[];
- response_types_supported?: string[];
- response_modes_supported?: string[];
- grant_types_supported?: string[];
- subject_types_supported?: string[];
- id_token_signing_alg_values_supported?: string[];
- userinfo_signing_alg_values_supported?: string[];
- request_object_signing_alg_values_supported?: string[];
- token_endpoint_auth_methods_supported?: string[];
- token_endpoint_auth_signing_alg_values_supported?: string[];
- claim_types_supported?: string[];
- claims_supported?: string[];
- code_challenge_methods_supported?: string[];
-}
-
-export type {
- Action,
- AsyncConfigOptions,
- AsyncServerConfig,
- ConfigOptions,
- ConfigurablePaths,
- CustomPathConfig,
- LogLevel,
- LoggerFunctions,
- RequestMiddleware,
- RequestObj,
- ServerConfig,
- TokenStoreObject,
- ValidConfigOptions,
- StepOptions,
- WellKnownResponse,
-};
diff --git a/packages/javascript-sdk/src/config/well-known.mock.ts b/packages/javascript-sdk/src/config/well-known.mock.ts
deleted file mode 100644
index 2a4d955ab..000000000
--- a/packages/javascript-sdk/src/config/well-known.mock.ts
+++ /dev/null
@@ -1,420 +0,0 @@
-export const frWellKnown = {
- request_parameter_supported: true,
- pushed_authorization_request_endpoint:
- 'https://openam-spetrov.forgeblocks.com:443/am/oauth2/alpha/par',
- introspection_encryption_alg_values_supported: [
- 'ECDH-ES+A256KW',
- 'ECDH-ES+A192KW',
- 'RSA-OAEP',
- 'ECDH-ES+A128KW',
- 'RSA-OAEP-256',
- 'A128KW',
- 'A256KW',
- 'ECDH-ES',
- 'dir',
- 'A192KW',
- ],
- claims_parameter_supported: false,
- introspection_endpoint: 'https://openam-spetrov.forgeblocks.com:443/am/oauth2/alpha/introspect',
- issuer: 'https://openam-spetrov.forgeblocks.com:443/am/oauth2/alpha',
- id_token_encryption_enc_values_supported: [
- 'A256GCM',
- 'A192GCM',
- 'A128GCM',
- 'A128CBC-HS256',
- 'A192CBC-HS384',
- 'A256CBC-HS512',
- ],
- userinfo_encryption_enc_values_supported: [
- 'A256GCM',
- 'A192GCM',
- 'A128GCM',
- 'A128CBC-HS256',
- 'A192CBC-HS384',
- 'A256CBC-HS512',
- ],
- authorization_endpoint: 'https://openam-spetrov.forgeblocks.com:443/am/oauth2/alpha/authorize',
- authorization_encryption_alg_values_supported: [
- 'ECDH-ES+A256KW',
- 'ECDH-ES+A192KW',
- 'RSA-OAEP',
- 'ECDH-ES+A128KW',
- 'RSA-OAEP-256',
- 'A128KW',
- 'A256KW',
- 'ECDH-ES',
- 'dir',
- 'A192KW',
- ],
- introspection_encryption_enc_values_supported: [
- 'A256GCM',
- 'A192GCM',
- 'A128GCM',
- 'A128CBC-HS256',
- 'A192CBC-HS384',
- 'A256CBC-HS512',
- ],
- claims_supported: [],
- rcs_request_signing_alg_values_supported: [
- 'PS384',
- 'ES384',
- 'RS384',
- 'HS256',
- 'HS512',
- 'ES256',
- 'RS256',
- 'HS384',
- 'ES512',
- 'PS256',
- 'PS512',
- 'RS512',
- ],
- token_endpoint_auth_methods_supported: [
- 'client_secret_post',
- 'private_key_jwt',
- 'self_signed_tls_client_auth',
- 'tls_client_auth',
- 'none',
- 'client_secret_basic',
- ],
- tls_client_certificate_bound_access_tokens: true,
- response_modes_supported: [
- 'fragment.jwt',
- 'form_post',
- 'form_post.jwt',
- 'jwt',
- 'fragment',
- 'query.jwt',
- 'query',
- ],
- backchannel_logout_session_supported: true,
- token_endpoint: 'https://openam-spetrov.forgeblocks.com:443/am/oauth2/alpha/access_token',
- response_types_supported: [
- 'code token id_token',
- 'code',
- 'code id_token',
- 'device_code',
- 'id_token',
- 'code token',
- 'token',
- 'token id_token',
- ],
- authorization_encryption_enc_values_supported: [
- 'A256GCM',
- 'A192GCM',
- 'A128GCM',
- 'A128CBC-HS256',
- 'A192CBC-HS384',
- 'A256CBC-HS512',
- ],
- revocation_endpoint_auth_methods_supported: [
- 'client_secret_post',
- 'private_key_jwt',
- 'self_signed_tls_client_auth',
- 'tls_client_auth',
- 'none',
- 'client_secret_basic',
- ],
- request_uri_parameter_supported: true,
- grant_types_supported: [
- 'implicit',
- 'urn:ietf:params:oauth:grant-type:saml2-bearer',
- 'refresh_token',
- 'password',
- 'client_credentials',
- 'urn:ietf:params:oauth:grant-type:device_code',
- 'authorization_code',
- 'urn:openid:params:grant-type:ciba',
- 'urn:ietf:params:oauth:grant-type:uma-ticket',
- 'urn:ietf:params:oauth:grant-type:jwt-bearer',
- ],
- version: '3.0',
- prompt_values_supported: ['none', 'login', 'consent'],
- userinfo_endpoint: 'https://openam-spetrov.forgeblocks.com:443/am/oauth2/alpha/userinfo',
- require_request_uri_registration: true,
- code_challenge_methods_supported: ['plain', 'S256'],
- id_token_encryption_alg_values_supported: [
- 'ECDH-ES+A256KW',
- 'ECDH-ES+A192KW',
- 'RSA-OAEP',
- 'ECDH-ES+A128KW',
- 'RSA-OAEP-256',
- 'A128KW',
- 'A256KW',
- 'ECDH-ES',
- 'dir',
- 'A192KW',
- ],
- authorization_signing_alg_values_supported: [
- 'PS384',
- 'RS384',
- 'EdDSA',
- 'ES384',
- 'HS256',
- 'HS512',
- 'ES256',
- 'RS256',
- 'HS384',
- 'ES512',
- 'PS256',
- 'PS512',
- 'RS512',
- ],
- request_object_signing_alg_values_supported: [
- 'PS384',
- 'ES384',
- 'RS384',
- 'HS256',
- 'HS512',
- 'ES256',
- 'RS256',
- 'HS384',
- 'ES512',
- 'PS256',
- 'PS512',
- 'RS512',
- ],
- request_object_encryption_alg_values_supported: [
- 'ECDH-ES+A256KW',
- 'ECDH-ES+A192KW',
- 'ECDH-ES+A128KW',
- 'RSA-OAEP',
- 'RSA-OAEP-256',
- 'A128KW',
- 'A256KW',
- 'ECDH-ES',
- 'dir',
- 'A192KW',
- ],
- rcs_response_signing_alg_values_supported: [
- 'PS384',
- 'ES384',
- 'RS384',
- 'HS256',
- 'HS512',
- 'ES256',
- 'RS256',
- 'HS384',
- 'ES512',
- 'PS256',
- 'PS512',
- 'RS512',
- ],
- introspection_signing_alg_values_supported: [
- 'PS384',
- 'RS384',
- 'EdDSA',
- 'ES384',
- 'HS256',
- 'HS512',
- 'ES256',
- 'RS256',
- 'HS384',
- 'ES512',
- 'PS256',
- 'PS512',
- 'RS512',
- ],
- check_session_iframe:
- 'https://openam-spetrov.forgeblocks.com:443/am/oauth2/alpha/connect/checkSession',
- scopes_supported: [
- 'address',
- 'phone',
- 'openid',
- 'profile',
- 'fr:idm:*',
- 'am-introspect-all-tokens',
- 'email',
- ],
- backchannel_logout_supported: true,
- acr_values_supported: [],
- request_object_encryption_enc_values_supported: [
- 'A256GCM',
- 'A192GCM',
- 'A128GCM',
- 'A128CBC-HS256',
- 'A192CBC-HS384',
- 'A256CBC-HS512',
- ],
- rcs_request_encryption_alg_values_supported: [
- 'ECDH-ES+A256KW',
- 'ECDH-ES+A192KW',
- 'RSA-OAEP',
- 'ECDH-ES+A128KW',
- 'RSA-OAEP-256',
- 'A128KW',
- 'A256KW',
- 'ECDH-ES',
- 'dir',
- 'A192KW',
- ],
- userinfo_signing_alg_values_supported: [
- 'ES384',
- 'HS256',
- 'HS512',
- 'ES256',
- 'RS256',
- 'HS384',
- 'ES512',
- ],
- require_pushed_authorization_requests: false,
- rcs_response_encryption_enc_values_supported: [
- 'A256GCM',
- 'A192GCM',
- 'A128GCM',
- 'A128CBC-HS256',
- 'A192CBC-HS384',
- 'A256CBC-HS512',
- ],
- userinfo_encryption_alg_values_supported: [
- 'ECDH-ES+A256KW',
- 'ECDH-ES+A192KW',
- 'RSA-OAEP',
- 'ECDH-ES+A128KW',
- 'RSA-OAEP-256',
- 'A128KW',
- 'A256KW',
- 'ECDH-ES',
- 'dir',
- 'A192KW',
- ],
- end_session_endpoint:
- 'https://openam-spetrov.forgeblocks.com:443/am/oauth2/alpha/connect/endSession',
- rcs_request_encryption_enc_values_supported: [
- 'A256GCM',
- 'A192GCM',
- 'A128GCM',
- 'A128CBC-HS256',
- 'A192CBC-HS384',
- 'A256CBC-HS512',
- ],
- revocation_endpoint: 'https://openam-spetrov.forgeblocks.com:443/am/oauth2/alpha/token/revoke',
- rcs_response_encryption_alg_values_supported: [
- 'ECDH-ES+A256KW',
- 'ECDH-ES+A192KW',
- 'ECDH-ES+A128KW',
- 'RSA-OAEP',
- 'RSA-OAEP-256',
- 'A128KW',
- 'A256KW',
- 'ECDH-ES',
- 'dir',
- 'A192KW',
- ],
- token_endpoint_auth_signing_alg_values_supported: [
- 'PS384',
- 'ES384',
- 'RS384',
- 'HS256',
- 'HS512',
- 'ES256',
- 'RS256',
- 'HS384',
- 'ES512',
- 'PS256',
- 'PS512',
- 'RS512',
- ],
- jwks_uri: 'https://openam-spetrov.forgeblocks.com:443/am/oauth2/alpha/connect/jwk_uri',
- subject_types_supported: ['public', 'pairwise'],
- id_token_signing_alg_values_supported: [
- 'PS384',
- 'ES384',
- 'RS384',
- 'HS256',
- 'HS512',
- 'ES256',
- 'RS256',
- 'HS384',
- 'ES512',
- 'PS256',
- 'PS512',
- 'RS512',
- ],
- registration_endpoint: 'https://openam-spetrov.forgeblocks.com:443/am/oauth2/alpha/register',
-};
-
-export const piWellKnown = {
- issuer: 'https://auth.pingone.ca/02fb4743-189a-4bc7-9d6c-a919edfe6447/as',
- authorization_endpoint:
- 'https://auth.pingone.ca/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/authorize',
- pushed_authorization_request_endpoint:
- 'https://auth.pingone.ca/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/par',
- token_endpoint: 'https://auth.pingone.ca/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/token',
- userinfo_endpoint: 'https://auth.pingone.ca/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/userinfo',
- jwks_uri: 'https://auth.pingone.ca/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/jwks',
- end_session_endpoint: 'https://auth.pingone.ca/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/signoff',
- introspection_endpoint:
- 'https://auth.pingone.ca/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/introspect',
- revocation_endpoint: 'https://auth.pingone.ca/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/revoke',
- device_authorization_endpoint:
- 'https://auth.pingone.ca/02fb4743-189a-4bc7-9d6c-a919edfe6447/as/device_authorization',
- claims_parameter_supported: false,
- request_parameter_supported: true,
- request_uri_parameter_supported: false,
- require_pushed_authorization_requests: false,
- scopes_supported: ['openid', 'profile', 'email', 'address', 'phone'],
- response_types_supported: [
- 'code',
- 'id_token',
- 'token id_token',
- 'code id_token',
- 'code token',
- 'code token id_token',
- ],
- response_modes_supported: ['pi.flow', 'query', 'fragment', 'form_post'],
- grant_types_supported: [
- 'authorization_code',
- 'implicit',
- 'client_credentials',
- 'refresh_token',
- 'urn:ietf:params:oauth:grant-type:device_code',
- ],
- subject_types_supported: ['public'],
- id_token_signing_alg_values_supported: ['RS256'],
- userinfo_signing_alg_values_supported: ['none'],
- request_object_signing_alg_values_supported: [
- 'none',
- 'HS256',
- 'HS384',
- 'HS512',
- 'RS256',
- 'RS384',
- 'RS512',
- ],
- token_endpoint_auth_methods_supported: [
- 'client_secret_basic',
- 'client_secret_post',
- 'client_secret_jwt',
- 'private_key_jwt',
- ],
- token_endpoint_auth_signing_alg_values_supported: [
- 'HS256',
- 'HS384',
- 'HS512',
- 'RS256',
- 'RS384',
- 'RS512',
- ],
- claim_types_supported: ['normal'],
- claims_supported: [
- 'sub',
- 'iss',
- 'auth_time',
- 'acr',
- 'name',
- 'given_name',
- 'family_name',
- 'middle_name',
- 'preferred_username',
- 'profile',
- 'picture',
- 'zoneinfo',
- 'phone_number',
- 'updated_at',
- 'address',
- 'email',
- 'locale',
- ],
- code_challenge_methods_supported: ['plain', 'S256'],
-};
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/attribute-input-callback.test.ts b/packages/javascript-sdk/src/fr-auth/callbacks/attribute-input-callback.test.ts
deleted file mode 100644
index ab0841164..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/attribute-input-callback.test.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * attribute-input-callback.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { CallbackType } from '../../auth/enums';
-import type { Callback } from '../../auth/interfaces';
-import AttributeInputCallback from './attribute-input-callback';
-
-describe('AttributeInputCallback', () => {
- const payload: Callback = {
- _id: 0,
- input: [
- {
- name: 'IDToken0',
- value: '',
- },
- {
- name: 'IDToken0validateOnly',
- value: false,
- },
- ],
- output: [
- {
- name: 'name',
- value: 'givenName',
- },
- {
- name: 'prompt',
- value: 'First Name:',
- },
- {
- name: 'required',
- value: true,
- },
- {
- name: 'policies',
- value: {
- policyRequirements: ['a', 'b'],
- name: 'givenName',
- policies: [],
- },
- },
- {
- name: 'failedPolicies',
- value: [JSON.stringify({ failedPolicies: { c: 'c', d: 'd' } })],
- },
- {
- name: 'validateOnly',
- value: false,
- },
- ],
- type: CallbackType.StringAttributeInputCallback,
- };
-
- it('reads/writes basic properties with "validate only"', () => {
- const cb = new AttributeInputCallback(payload);
- cb.setValue('Clark');
- cb.setValidateOnly(true);
-
- expect(cb.getType()).toBe('StringAttributeInputCallback');
- expect(cb.getName()).toBe('givenName');
- expect(cb.getPrompt()).toBe('First Name:');
- expect(cb.isRequired()).toBe(true);
- expect(cb.getPolicies().policyRequirements).toStrictEqual(['a', 'b']);
- expect(cb.getFailedPolicies()).toStrictEqual([{ failedPolicies: { c: 'c', d: 'd' } }]);
- expect(cb.getInputValue()).toBe('Clark');
- expect(cb.payload.input[1].value).toBe(true);
- });
-
- it('writes validate only to `false` for submission', () => {
- const cb = new AttributeInputCallback(payload);
- cb.setValidateOnly(false);
- expect(cb.payload.input[1].value).toBe(false);
- });
-});
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/attribute-input-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/attribute-input-callback.ts
deleted file mode 100644
index df11c7486..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/attribute-input-callback.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * attribute-input-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback, PolicyRequirement } from '../../auth/interfaces';
-import type { StringDict } from '../../shared/interfaces';
-
-/**
- * Represents a callback used to collect attributes.
- *
- * @typeparam T Maps to StringAttributeInputCallback, NumberAttributeInputCallback and
- * BooleanAttributeInputCallback, respectively
- */
-class AttributeInputCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the attribute name.
- */
- public getName(): string {
- return this.getOutputByName('name', '');
- }
-
- /**
- * Gets the attribute prompt.
- */
- public getPrompt(): string {
- return this.getOutputByName('prompt', '');
- }
-
- /**
- * Gets whether the attribute is required.
- */
- public isRequired(): boolean {
- return this.getOutputByName('required', false);
- }
-
- /**
- * Gets the callback's failed policies.
- */
- public getFailedPolicies(): PolicyRequirement[] {
- const failedPolicies = this.getOutputByName(
- 'failedPolicies',
- [],
- ) as unknown as string[];
- try {
- return failedPolicies.map((v) => JSON.parse(v)) as PolicyRequirement[];
- } catch (err) {
- throw new Error(
- 'Unable to parse "failed policies" from the ForgeRock server. The JSON within `AttributeInputCallback` was either malformed or missing.',
- );
- }
- }
-
- /**
- * Gets the callback's applicable policies.
- */
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- public getPolicies(): StringDict {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return this.getOutputByName>('policies', {});
- }
-
- /**
- * Set if validating value only.
- */
- public setValidateOnly(value: boolean): void {
- this.setInputValue(value, /validateOnly/);
- }
-
- /**
- * Sets the attribute's value.
- */
- public setValue(value: T): void {
- this.setInputValue(value);
- }
-}
-
-export default AttributeInputCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/choice-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/choice-callback.ts
deleted file mode 100644
index 1eceb731a..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/choice-callback.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * choice-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-
-/**
- * Represents a callback used to collect an answer to a choice.
- */
-class ChoiceCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the choice's prompt.
- */
- public getPrompt(): string {
- return this.getOutputByName('prompt', '');
- }
-
- /**
- * Gets the choice's default answer.
- */
- public getDefaultChoice(): number {
- return this.getOutputByName('defaultChoice', 0);
- }
-
- /**
- * Gets the choice's possible answers.
- */
- public getChoices(): string[] {
- return this.getOutputByName('choices', []);
- }
-
- /**
- * Sets the choice's answer by index position.
- */
- public setChoiceIndex(index: number): void {
- const length = this.getChoices().length;
- if (index < 0 || index > length - 1) {
- throw new Error(`${index} is out of bounds`);
- }
- this.setInputValue(index);
- }
-
- /**
- * Sets the choice's answer by value.
- */
- public setChoiceValue(value: string): void {
- const index = this.getChoices().indexOf(value);
- if (index === -1) {
- throw new Error(`"${value}" is not a valid choice`);
- }
- this.setInputValue(index);
- }
-}
-
-export default ChoiceCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/confirmation-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/confirmation-callback.ts
deleted file mode 100644
index 50f3fba18..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/confirmation-callback.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * confirmation-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-
-/**
- * Represents a callback used to collect a confirmation to a message.
- */
-class ConfirmationCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the index position of the confirmation's default answer.
- */
- public getDefaultOption(): number {
- return Number(this.getOutputByName('defaultOption', 0));
- }
-
- /**
- * Gets the confirmation's message type.
- */
- public getMessageType(): number {
- return Number(this.getOutputByName('messageType', 0));
- }
-
- /**
- * Gets the confirmation's possible answers.
- */
- public getOptions(): string[] {
- return this.getOutputByName('options', []);
- }
-
- /**
- * Gets the confirmation's option type.
- */
- public getOptionType(): number {
- return Number(this.getOutputByName('optionType', 0));
- }
-
- /**
- * Gets the confirmation's prompt.
- */
- public getPrompt(): string {
- return this.getOutputByName('prompt', '');
- }
-
- /**
- * Set option index.
- */
- public setOptionIndex(index: number): void {
- if (index !== 0 && index !== 1) {
- throw new Error(`"${index}" is not a valid choice`);
- }
- this.setInputValue(index);
- }
-
- /**
- * Set option value.
- */
- public setOptionValue(value: string): void {
- const index = this.getOptions().indexOf(value);
- if (index === -1) {
- throw new Error(`"${value}" is not a valid choice`);
- }
- this.setInputValue(index);
- }
-}
-
-export default ConfirmationCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/device-profile-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/device-profile-callback.ts
deleted file mode 100644
index 577c0fcd0..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/device-profile-callback.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * device-profile-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-import type { DeviceProfileData } from '../../fr-device/interfaces';
-
-/**
- * Represents a callback used to collect device profile data.
- */
-class DeviceProfileCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the callback's data.
- */
- public getMessage(): string {
- return this.getOutputByName('message', '');
- }
-
- /**
- * Does callback require metadata?
- */
- public isMetadataRequired(): boolean {
- return this.getOutputByName('metadata', false);
- }
-
- /**
- * Does callback require location data?
- */
- public isLocationRequired(): boolean {
- return this.getOutputByName('location', false);
- }
-
- /**
- * Sets the profile.
- */
- public setProfile(profile: DeviceProfileData): void {
- this.setInputValue(JSON.stringify(profile));
- }
-}
-
-export default DeviceProfileCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/factory.ts b/packages/javascript-sdk/src/fr-auth/callbacks/factory.ts
deleted file mode 100644
index 854b0baff..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/factory.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * factory.ts
- *
- * Copyright (c) 2020-2024 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import { CallbackType } from '../../auth/enums';
-import type { Callback } from '../../auth/interfaces';
-import AttributeInputCallback from './attribute-input-callback';
-import ChoiceCallback from './choice-callback';
-import ConfirmationCallback from './confirmation-callback';
-import DeviceProfileCallback from './device-profile-callback';
-import HiddenValueCallback from './hidden-value-callback';
-import KbaCreateCallback from './kba-create-callback';
-import MetadataCallback from './metadata-callback';
-import NameCallback from './name-callback';
-import PasswordCallback from './password-callback';
-import PingOneProtectEvaluationCallback from './ping-protect-evaluation-callback';
-import PingOneProtectInitializeCallback from './ping-protect-initialize-callback';
-import PollingWaitCallback from './polling-wait-callback';
-import ReCaptchaCallback from './recaptcha-callback';
-import ReCaptchaEnterpriseCallback from './recaptcha-enterprise-callback';
-import RedirectCallback from './redirect-callback';
-import SelectIdPCallback from './select-idp-callback';
-import SuspendedTextOutputCallback from './suspended-text-output-callback';
-import TermsAndConditionsCallback from './terms-and-conditions-callback';
-import TextInputCallback from './text-input-callback';
-import TextOutputCallback from './text-output-callback';
-import ValidatedCreatePasswordCallback from './validated-create-password-callback';
-import ValidatedCreateUsernameCallback from './validated-create-username-callback';
-
-type FRCallbackFactory = (callback: Callback) => FRCallback;
-
-/**
- * @hidden
- */
-function createCallback(callback: Callback): FRCallback {
- switch (callback.type) {
- case CallbackType.BooleanAttributeInputCallback:
- return new AttributeInputCallback(callback);
- case CallbackType.ChoiceCallback:
- return new ChoiceCallback(callback);
- case CallbackType.ConfirmationCallback:
- return new ConfirmationCallback(callback);
- case CallbackType.DeviceProfileCallback:
- return new DeviceProfileCallback(callback);
- case CallbackType.HiddenValueCallback:
- return new HiddenValueCallback(callback);
- case CallbackType.KbaCreateCallback:
- return new KbaCreateCallback(callback);
- case CallbackType.MetadataCallback:
- return new MetadataCallback(callback);
- case CallbackType.NameCallback:
- return new NameCallback(callback);
- case CallbackType.NumberAttributeInputCallback:
- return new AttributeInputCallback(callback);
- case CallbackType.PasswordCallback:
- return new PasswordCallback(callback);
- case CallbackType.PingOneProtectEvaluationCallback:
- return new PingOneProtectEvaluationCallback(callback);
- case CallbackType.PingOneProtectInitializeCallback:
- return new PingOneProtectInitializeCallback(callback);
- case CallbackType.PollingWaitCallback:
- return new PollingWaitCallback(callback);
- case CallbackType.ReCaptchaCallback:
- return new ReCaptchaCallback(callback);
- case CallbackType.ReCaptchaEnterpriseCallback:
- return new ReCaptchaEnterpriseCallback(callback);
- case CallbackType.RedirectCallback:
- return new RedirectCallback(callback);
- case CallbackType.SelectIdPCallback:
- return new SelectIdPCallback(callback);
- case CallbackType.StringAttributeInputCallback:
- return new AttributeInputCallback(callback);
- case CallbackType.SuspendedTextOutputCallback:
- return new SuspendedTextOutputCallback(callback);
- case CallbackType.TermsAndConditionsCallback:
- return new TermsAndConditionsCallback(callback);
- case CallbackType.TextInputCallback:
- return new TextInputCallback(callback);
- case CallbackType.TextOutputCallback:
- return new TextOutputCallback(callback);
- case CallbackType.ValidatedCreatePasswordCallback:
- return new ValidatedCreatePasswordCallback(callback);
- case CallbackType.ValidatedCreateUsernameCallback:
- return new ValidatedCreateUsernameCallback(callback);
- default:
- return new FRCallback(callback);
- }
-}
-
-export default createCallback;
-export type { FRCallbackFactory };
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/fr-auth-callback.test.ts b/packages/javascript-sdk/src/fr-auth/callbacks/fr-auth-callback.test.ts
deleted file mode 100644
index 38c33c854..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/fr-auth-callback.test.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * fr-auth-callback.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import { CallbackType } from '../../auth/enums';
-import type { Callback } from '../../auth/interfaces';
-
-describe('FRCallback', () => {
- it('reads/writes basic properties', () => {
- const payload: Callback = {
- _id: 0,
- input: [
- {
- name: 'userName',
- value: '',
- },
- ],
- output: [
- {
- name: 'prompt',
- value: 'Username:',
- },
- ],
- type: CallbackType.NameCallback,
- };
- const cb = new FRCallback(payload);
- cb.setInputValue('superman');
-
- expect(cb.getType()).toBe('NameCallback');
- expect(cb.getOutputValue('prompt')).toBe('Username:');
- expect(cb.getInputValue()).toBe('superman');
- });
-});
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/hidden-value-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/hidden-value-callback.ts
deleted file mode 100644
index 9967fd3f3..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/hidden-value-callback.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * hidden-value-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-
-/**
- * Represents a callback used to collect information indirectly from the user.
- */
-class HiddenValueCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-}
-
-export default HiddenValueCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/index.ts b/packages/javascript-sdk/src/fr-auth/callbacks/index.ts
deleted file mode 100644
index 392f01bcf..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/index.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { CallbackType } from '../../auth/enums';
-import type { Callback, NameValue } from '../../auth/interfaces';
-
-/**
- * Base class for authentication tree callback wrappers.
- */
-class FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {}
-
- /**
- * Gets the name of this callback type.
- */
- public getType(): CallbackType {
- return this.payload.type;
- }
-
- /**
- * Gets the value of the specified input element, or the first element if `selector` is not
- * provided.
- *
- * @param selector The index position or name of the desired element
- */
- public getInputValue(selector: number | string = 0): unknown {
- return this.getArrayElement(this.payload.input, selector).value;
- }
-
- /**
- * Sets the value of the specified input element, or the first element if `selector` is not
- * provided.
- *
- * @param selector The index position or name of the desired element
- */
- public setInputValue(value: unknown, selector: number | string | RegExp = 0): void {
- this.getArrayElement(this.payload.input, selector).value = value;
- }
-
- /**
- * Gets the value of the specified output element, or the first element if `selector`
- * is not provided.
- *
- * @param selector The index position or name of the desired element
- */
- public getOutputValue(selector: number | string = 0): unknown {
- return this.getArrayElement(this.payload.output, selector).value;
- }
-
- /**
- * Gets the value of the first output element with the specified name or the
- * specified default value.
- *
- * @param name The name of the desired element
- */
- public getOutputByName(name: string, defaultValue: T): T {
- const output = this.payload.output.find((x) => x.name === name);
- return output ? (output.value as T) : defaultValue;
- }
-
- private getArrayElement(
- array: NameValue[] | undefined,
- selector: number | string | RegExp = 0,
- ): NameValue {
- if (array === undefined) {
- throw new Error(`No NameValue array was provided to search (selector ${selector})`);
- }
-
- if (typeof selector === 'number') {
- if (selector < 0 || selector > array.length - 1) {
- throw new Error(`Selector index ${selector} is out of range`);
- }
- return array[selector];
- }
-
- if (typeof selector === 'string') {
- const input = array.find((x) => x.name === selector);
- if (!input) {
- throw new Error(`Missing callback input entry "${selector}"`);
- }
- return input;
- }
-
- // Duck typing for RegEx
- if (typeof selector === 'object' && selector.test && Boolean(selector.exec)) {
- const input = array.find((x) => selector.test(x.name));
- if (!input) {
- throw new Error(`Missing callback input entry "${selector}"`);
- }
- return input;
- }
-
- throw new Error('Invalid selector value type');
- }
-}
-
-export default FRCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/kba-create-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/kba-create-callback.ts
deleted file mode 100644
index 5469b38e5..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/kba-create-callback.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * kba-create-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-
-/**
- * Represents a callback used to collect KBA-style security questions and answers.
- */
-class KbaCreateCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the callback prompt.
- */
- public getPrompt(): string {
- return this.getOutputByName('prompt', '');
- }
-
- /**
- * Gets the callback's list of pre-defined security questions.
- */
- public getPredefinedQuestions(): string[] {
- return this.getOutputByName('predefinedQuestions', []);
- }
-
- /**
- * Sets the callback's security question.
- */
- public setQuestion(question: string): void {
- this.setValue('question', question);
- }
-
- /**
- * Sets the callback's security question answer.
- */
- public setAnswer(answer: string): void {
- this.setValue('answer', answer);
- }
-
- private setValue(type: 'question' | 'answer', value: string): void {
- if (!this.payload.input) {
- throw new Error('KBA payload is missing input');
- }
-
- const input = this.payload.input.find((x) => x.name.endsWith(type));
- if (!input) {
- throw new Error(`No input has name ending in "${type}"`);
- }
- input.value = value;
- }
-}
-
-export default KbaCreateCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/metadata-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/metadata-callback.ts
deleted file mode 100644
index 56f5418fa..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/metadata-callback.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * metadata-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-
-/**
- * Represents a callback used to deliver and collect miscellaneous data.
- */
-class MetadataCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the callback's data.
- */
- public getData(): T {
- return this.getOutputByName('data', {} as T);
- }
-}
-
-export default MetadataCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/name-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/name-callback.ts
deleted file mode 100644
index 17ef43875..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/name-callback.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * name-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-
-/**
- * Represents a callback used to collect a username.
- */
-class NameCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the callback's prompt.
- */
- public getPrompt(): string {
- return this.getOutputByName('prompt', '');
- }
-
- /**
- * Sets the username.
- */
- public setName(name: string): void {
- this.setInputValue(name);
- }
-}
-
-export default NameCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/password-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/password-callback.ts
deleted file mode 100644
index 5ac558acf..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/password-callback.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * password-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback, PolicyRequirement } from '../../auth/interfaces';
-
-/**
- * Represents a callback used to collect a password.
- */
-class PasswordCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the callback's failed policies.
- */
- public getFailedPolicies(): PolicyRequirement[] {
- return this.getOutputByName('failedPolicies', []);
- }
-
- /**
- * Gets the callback's applicable policies.
- */
- public getPolicies(): string[] {
- return this.getOutputByName('policies', []);
- }
-
- /**
- * Gets the callback's prompt.
- */
- public getPrompt(): string {
- return this.getOutputByName('prompt', '');
- }
-
- /**
- * Sets the password.
- */
- public setPassword(password: string): void {
- this.setInputValue(password);
- }
-}
-
-export default PasswordCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/ping-protect-evaluation-callback.test.ts b/packages/javascript-sdk/src/fr-auth/callbacks/ping-protect-evaluation-callback.test.ts
deleted file mode 100644
index a7c719ea8..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/ping-protect-evaluation-callback.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { vi, describe, it, expect } from 'vitest';
-import { CallbackType } from '../../auth/enums';
-import PingOneProtectEvaluationCallback from './ping-protect-evaluation-callback';
-
-describe('PingOneProtectEvaluationCallback', () => {
- it('should be defined', () => {
- expect(PingOneProtectEvaluationCallback).toBeDefined();
- });
- it('should test that the pauseBehavior method can be called', () => {
- const callback = new PingOneProtectEvaluationCallback({
- type: 'PingOneProtectEvaluationCallback' as CallbackType.PingOneProtectEvaluationCallback,
- output: [{ name: 'pauseBehavioralData', value: true }],
- });
- const mock = vi.spyOn(callback, 'getPauseBehavioralData');
- callback.getPauseBehavioralData();
- expect(mock).toHaveBeenCalled();
- });
- it('should test setData method', () => {
- const callback = new PingOneProtectEvaluationCallback({
- type: 'PingOneProtectEvaluationCallback' as CallbackType.PingOneProtectEvaluationCallback,
- output: [{ name: 'signals', value: '' }],
- input: [
- {
- name: 'IDToken1signals',
- value: '',
- },
- {
- name: 'IDToken1clientError',
- value: '',
- },
- ],
- });
- const mock = vi.spyOn(callback, 'setData');
- callback.setData('data');
- expect(mock).toHaveBeenCalledWith('data');
- expect(callback.getInputValue('IDToken1signals')).toBe('data');
- });
- it('should test setClientError method', () => {
- const callback = new PingOneProtectEvaluationCallback({
- type: 'PingOneProtectEvaluationCallback' as CallbackType.PingOneProtectEvaluationCallback,
- output: [{ name: 'signals', value: '' }],
- input: [
- {
- name: 'IDToken1signals',
- value: '',
- },
- {
- name: 'IDToken1clientError',
- value: '',
- },
- ],
- });
- const mock = vi.spyOn(callback, 'setClientError');
- callback.setClientError('error i just set');
- expect(mock).toHaveBeenCalledWith('error i just set');
- expect(callback.getInputValue('IDToken1clientError')).toBe('error i just set');
- });
-});
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/ping-protect-evaluation-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/ping-protect-evaluation-callback.ts
deleted file mode 100644
index e50cf13d7..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/ping-protect-evaluation-callback.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * ping-protect-evaluation-callback.ts
- *
- * Copyright (c) 2024 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-
-/**
- * @class - Represents a callback used to complete and package up device and behavioral data.
- */
-class PingOneProtectEvaluationCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the callback's pauseBehavioralData value.
- * @returns {boolean}
- */
- public getPauseBehavioralData(): boolean {
- return this.getOutputByName('pauseBehavioralData', false);
- }
-
- /**
- * @method setData - Set the result of data collection
- * @param {string} data - Data from calling pingProtect.get()
- * @returns {void}
- */
- public setData(data: string): void {
- this.setInputValue(data, /signals/);
- }
-
- /**
- * @method setClientError - Set the client error message
- * @param {string} errorMessage - Error message
- * @returns {void}
- */
- public setClientError(errorMessage: string): void {
- this.setInputValue(errorMessage, /clientError/);
- }
-}
-
-export default PingOneProtectEvaluationCallback;
-
-/**
- * Example of callback:
-{
- "type": "PingOneProtectEvaluationCallback",
- "output": [
- {
- "name": "pauseBehavioralData",
- "value": true
- }
- ],
- "input": [
- {
- "name": "IDToken1signals",
- "value": ""
- },
- {
- "name": "IDToken1clientError",
- "value": ""
- }
- ]
-}
-*/
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/ping-protect-initialize-callback.test.ts b/packages/javascript-sdk/src/fr-auth/callbacks/ping-protect-initialize-callback.test.ts
deleted file mode 100644
index a8030f5c9..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/ping-protect-initialize-callback.test.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-import { vi, describe, expect, it } from 'vitest';
-import { CallbackType } from '../../auth/enums';
-import PingOneProtectInitializeCallback from './ping-protect-initialize-callback';
-
-describe('PingOneProtectInitializeCallback', () => {
- it('should exist', () => {
- expect(PingOneProtectInitializeCallback).toBeDefined();
- });
- it('should test the getConfig method', () => {
- const callback = new PingOneProtectInitializeCallback({
- type: 'PingOneProtectInitializeCallback' as CallbackType,
- input: [
- {
- name: 'IDToken1signals',
- value: '',
- },
- {
- name: 'IDToken1clientError',
- value: '',
- },
- ],
- output: [
- {
- name: 'envId',
- value: '02fb4743-189a-4bc7-9d6c-a919edfe6447',
- },
- {
- name: 'consoleLogEnabled',
- value: false,
- },
- {
- name: 'deviceAttributesToIgnore',
- value: [],
- },
- {
- name: 'customHost',
- value: '',
- },
- {
- name: 'lazyMetadata',
- value: false,
- },
- {
- name: 'behavioralDataCollection',
- value: true,
- },
- {
- name: 'deviceKeyRsyncIntervals',
- value: 14,
- },
- {
- name: 'enableTrust',
- value: false,
- },
- {
- name: 'disableTags',
- value: false,
- },
- {
- name: 'disableHub',
- value: false,
- },
- ],
- });
- const mock = vi.spyOn(callback, 'getConfig');
- const config = callback.getConfig();
- expect(mock).toHaveBeenCalled();
- expect(config).toMatchObject({
- envId: '02fb4743-189a-4bc7-9d6c-a919edfe6447',
- consoleLogEnabled: false,
- deviceAttributesToIgnore: [],
- customHost: '',
- lazyMetadata: false,
- behavioralDataCollection: true,
- deviceKeyRsyncIntervals: 14,
- enableTrust: false,
- disableTags: false,
- disableHub: false,
- });
- });
- it('should test the setClientError method', () => {
- const callback = new PingOneProtectInitializeCallback({
- type: 'PingOneProtectInitializeCallback' as CallbackType,
- input: [
- {
- name: 'IDToken1signals',
- value: '',
- },
- {
- name: 'IDToken1clientError',
- value: '',
- },
- ],
- output: [
- {
- name: 'envId',
- value: '02fb4743-189a-4bc7-9d6c-a919edfe6447',
- },
- {
- name: 'consoleLogEnabled',
- value: false,
- },
- {
- name: 'deviceAttributesToIgnore',
- value: [],
- },
- {
- name: 'customHost',
- value: '',
- },
- {
- name: 'lazyMetadata',
- value: false,
- },
- {
- name: 'behavioralDataCollection',
- value: true,
- },
- {
- name: 'deviceKeyRsyncIntervals',
- value: 14,
- },
- {
- name: 'enableTrust',
- value: false,
- },
- {
- name: 'disableTags',
- value: false,
- },
- {
- name: 'disableHub',
- value: false,
- },
- ],
- });
- const mock = vi.spyOn(callback, 'setClientError');
- callback.setClientError('error i just set');
- expect(mock).toHaveBeenCalled();
- expect(callback.getInputValue('IDToken1clientError')).toBe('error i just set');
- });
-});
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/ping-protect-initialize-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/ping-protect-initialize-callback.ts
deleted file mode 100644
index 7f96bc6d6..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/ping-protect-initialize-callback.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * ping-protect-initialize-callback.ts
- *
- * Copyright (c) 2024 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-
-/**
- * @class - Represents a callback used to initialize and start device and behavioral data collection.
- */
-class PingOneProtectInitializeCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Get callback's initialization config settings
- */
- public getConfig() {
- const config = {
- envId: this.getOutputByName('envId', ''),
- consoleLogEnabled: this.getOutputByName('consoleLogEnabled', false),
- deviceAttributesToIgnore: this.getOutputByName('deviceAttributesToIgnore', []),
- customHost: this.getOutputByName('customHost', ''),
- lazyMetadata: this.getOutputByName('lazyMetadata', false),
- behavioralDataCollection: this.getOutputByName('behavioralDataCollection', true),
- deviceKeyRsyncIntervals: this.getOutputByName('deviceKeyRsyncIntervals', 14),
- enableTrust: this.getOutputByName('enableTrust', false),
- disableTags: this.getOutputByName('disableTags', false),
- disableHub: this.getOutputByName('disableHub', false),
- };
- return config;
- }
-
- public setClientError(errorMessage: string): void {
- this.setInputValue(errorMessage, /clientError/);
- }
-}
-
-export default PingOneProtectInitializeCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/polling-wait-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/polling-wait-callback.ts
deleted file mode 100644
index 3441be154..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/polling-wait-callback.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * polling-wait-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-
-/**
- * Represents a callback used to instruct the system to poll while a backend process completes.
- */
-class PollingWaitCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the message to display while polling.
- */
- public getMessage(): string {
- return this.getOutputByName('message', '');
- }
-
- /**
- * Gets the polling interval in milliseconds.
- */
- public getWaitTime(): number {
- return Number(this.getOutputByName('waitTime', 0));
- }
-}
-
-export default PollingWaitCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/recaptcha-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/recaptcha-callback.ts
deleted file mode 100644
index 498f4f269..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/recaptcha-callback.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * recaptcha-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-
-/**
- * Represents a callback used to integrate reCAPTCHA.
- */
-class ReCaptchaCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the reCAPTCHA site key.
- */
- public getSiteKey(): string {
- return this.getOutputByName('recaptchaSiteKey', '');
- }
-
- /**
- * Sets the reCAPTCHA result.
- */
- public setResult(result: string): void {
- this.setInputValue(result);
- }
-}
-
-export default ReCaptchaCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/recaptcha-enterprise-callback.test.ts b/packages/javascript-sdk/src/fr-auth/callbacks/recaptcha-enterprise-callback.test.ts
deleted file mode 100644
index c9080fa41..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/recaptcha-enterprise-callback.test.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { describe, expect, it, beforeAll } from 'vitest';
-import ReCaptchaEnterpriseCallback from './recaptcha-enterprise-callback';
-import { CallbackType } from '../../auth/enums';
-import { Callback } from '../../auth/interfaces';
-
-const recaptchaCallback: Callback = {
- type: 'ReCaptchaEnterpriseCallback' as CallbackType.ReCaptchaEnterpriseCallback,
- output: [
- {
- name: 'recaptchaSiteKey',
- value: '6LdSu_spAAAAAKz3UhIy4JYQld2lm_WRt7dEhf9T',
- },
- {
- name: 'captchaApiUri',
- value: 'https://www.google.com/recaptcha/enterprise.js',
- },
- {
- name: 'captchaDivClass',
- value: 'g-recaptcha',
- },
- ],
- input: [
- {
- name: 'IDToken1token',
- value: '',
- },
- {
- name: 'IDToken1action',
- value: '',
- },
- {
- name: 'IDToken1clientError',
- value: '',
- },
- {
- name: 'IDToken1payload',
- value: '',
- },
- ],
-};
-describe('enterprise recaptcha', () => {
- let callback: ReCaptchaEnterpriseCallback;
- beforeAll(() => {
- callback = new ReCaptchaEnterpriseCallback(recaptchaCallback);
- });
- it('should get the site key', () => {
- const siteKey = callback.getSiteKey();
- expect(siteKey).toEqual('6LdSu_spAAAAAKz3UhIy4JYQld2lm_WRt7dEhf9T');
- });
- it('should get captchaApiUri', () => {
- const url = callback.getApiUrl();
- expect(url).toEqual('https://www.google.com/recaptcha/enterprise.js');
- });
- it('should set the action', () => {
- callback.setAction('my_action');
- expect(callback.getInputValue('IDToken1action')).toEqual('my_action');
- });
- it('should set the client error', () => {
- callback.setClientError('error here');
- expect(callback.getInputValue('IDToken1clientError')).toEqual('error here');
- });
- it('should set the payload', () => {
- callback.setPayload({ test: 'here' });
- expect(callback.getInputValue('IDToken1payload')).toEqual({ test: 'here' });
- });
- it('should set the token', () => {
- callback.setResult('12345');
- expect(callback.getInputValue('IDToken1token')).toEqual('12345');
- });
- it('should get the class', () => {
- const className = callback.getElementClass();
- expect(className).toBe('g-recaptcha');
- });
-});
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/recaptcha-enterprise-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/recaptcha-enterprise-callback.ts
deleted file mode 100644
index fb3f4e7aa..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/recaptcha-enterprise-callback.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * recaptcha-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-//"input": [
-// {
-// "name": "IDToken1token",
-// "value": ""
-// },
-// {
-// "name": "IDToken1action",
-// "value": ""
-// },
-// {
-// "name": "IDToken1clientError",
-// "value": ""
-// },
-// {
-// "name": "IDToken1payload",
-// "value": ""
-// }
-
-/**
- * Represents a callback used to integrate reCAPTCHA.
- */
-class ReCaptchaEnterpriseCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the reCAPTCHA site key.
- */
- public getSiteKey(): string {
- return this.getOutputByName('recaptchaSiteKey', '');
- }
-
- /**
- * Get the api url
- */
- public getApiUrl(): string {
- return this.getOutputByName('captchaApiUri', '');
- }
- /**
- * Get the class name
- */
- public getElementClass(): string {
- return this.getOutputByName('captchaDivClass', '');
- }
- /**
- * Sets the reCAPTCHA result.
- */
- public setResult(result: string): void {
- this.setInputValue(result);
- }
-
- /**
- * Set client client error
- */
- public setClientError(error: string) {
- this.setInputValue(error, 'IDToken1clientError');
- }
-
- /**
- * Set the recaptcha payload
- */
- public setPayload(payload: unknown) {
- this.setInputValue(payload, 'IDToken1payload');
- }
-
- /**
- * Set the recaptcha action
- */
- public setAction(action: string) {
- this.setInputValue(action, 'IDToken1action');
- }
-}
-
-export default ReCaptchaEnterpriseCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/redirect-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/redirect-callback.ts
deleted file mode 100644
index c4851382c..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/redirect-callback.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * redirect-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-
-/**
- * Represents a callback used to collect an answer to a choice.
- */
-class RedirectCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the redirect URL.
- */
- public getRedirectUrl(): string {
- return this.getOutputByName('redirectUrl', '');
- }
-}
-
-export default RedirectCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/select-idp-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/select-idp-callback.ts
deleted file mode 100644
index a67823b14..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/select-idp-callback.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * select-idp-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-
-interface IdPValue {
- provider: string;
- uiConfig: {
- [key: string]: string;
- };
-}
-
-/**
- * Represents a callback used to collect an answer to a choice.
- */
-class SelectIdPCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the available providers.
- */
- public getProviders(): IdPValue[] {
- return this.getOutputByName('providers', []);
- }
-
- /**
- * Sets the provider by name.
- */
- public setProvider(value: string): void {
- const item = this.getProviders().find((item) => item.provider === value);
- if (!item) {
- throw new Error(`"${value}" is not a valid choice`);
- }
- this.setInputValue(item.provider);
- }
-}
-
-export default SelectIdPCallback;
-
-export type { IdPValue };
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/suspended-text-output-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/suspended-text-output-callback.ts
deleted file mode 100644
index 55ec03b92..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/suspended-text-output-callback.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * suspended-text-output-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import TextOutputCallback from './text-output-callback';
-import type { Callback } from '../../auth/interfaces';
-
-/**
- * Represents a callback used to display a message.
- */
-class SuspendedTextOutputCallback extends TextOutputCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-}
-
-export default SuspendedTextOutputCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/terms-and-conditions-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/terms-and-conditions-callback.ts
deleted file mode 100644
index 2b4fc4d4f..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/terms-and-conditions-callback.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * terms-and-conditions-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-
-/**
- * Represents a callback used to collect acceptance of terms and conditions.
- */
-class TermsAndConditionsCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the terms and conditions content.
- */
- public getTerms(): string {
- return this.getOutputByName('terms', '');
- }
-
- /**
- * Gets the version of the terms and conditions.
- */
- public getVersion(): string {
- return this.getOutputByName('version', '');
- }
-
- /**
- * Gets the date of the terms and conditions.
- */
- public getCreateDate(): Date {
- const date = this.getOutputByName('createDate', '');
- return new Date(date);
- }
-
- /**
- * Sets the callback's acceptance.
- */
- public setAccepted(accepted = true): void {
- this.setInputValue(accepted);
- }
-}
-
-export default TermsAndConditionsCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/text-input-callback.test.ts b/packages/javascript-sdk/src/fr-auth/callbacks/text-input-callback.test.ts
deleted file mode 100644
index 18b0679df..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/text-input-callback.test.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * attribute-input-callback.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { CallbackType } from '../../auth/enums';
-import type { Callback } from '../../auth/interfaces';
-import TextInputCallback from './text-input-callback';
-
-describe('TextInputCallback', () => {
- const payload: Callback = {
- type: CallbackType.TextInputCallback,
- output: [
- {
- name: 'prompt',
- value: 'Provide a nickname for this account',
- },
- ],
- input: [
- {
- name: 'IDToken1',
- value: '',
- },
- ],
- };
-
- it('reads/writes basic properties', () => {
- const cb = new TextInputCallback(payload);
-
- expect(cb.getPrompt()).toBe('Provide a nickname for this account');
-
- cb.setInput('Test setting input');
-
- expect(cb.getInputValue()).toBe('Test setting input');
- });
-});
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/text-input-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/text-input-callback.ts
deleted file mode 100644
index 4b9c4dfc9..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/text-input-callback.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * text-input-callback.ts
- *
- * Copyright (c) 2022 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-
-/**
- * Represents a callback used to retrieve input from the user.
- */
-class TextInputCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the callback's prompt.
- */
- public getPrompt(): string {
- return this.getOutputByName('prompt', '');
- }
-
- /**
- * Sets the callback's input value.
- */
- public setInput(input: string): void {
- this.setInputValue(input);
- }
-}
-
-export default TextInputCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/text-output-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/text-output-callback.ts
deleted file mode 100644
index 025f7a9a3..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/text-output-callback.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * text-output-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback } from '../../auth/interfaces';
-
-/**
- * Represents a callback used to display a message.
- */
-class TextOutputCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the message content.
- */
- public getMessage(): string {
- return this.getOutputByName('message', '');
- }
-
- /**
- * Gets the message type.
- */
- public getMessageType(): string {
- return this.getOutputByName('messageType', '');
- }
-}
-
-export default TextOutputCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/validated-create-password-callback.test.ts b/packages/javascript-sdk/src/fr-auth/callbacks/validated-create-password-callback.test.ts
deleted file mode 100644
index ccfe67cd6..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/validated-create-password-callback.test.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * validated-create-password-callback.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { CallbackType } from '../../auth/enums';
-import type { Callback } from '../../auth/interfaces';
-import ValidatedCreatePasswordCallback from './validated-create-password-callback';
-
-describe('ValidatedCreatePasswordCallback', () => {
- const payload: Callback = {
- type: CallbackType.ValidatedCreatePasswordCallback,
- output: [
- {
- name: 'echoOn',
- value: false,
- },
- {
- name: 'required',
- value: true,
- },
- {
- name: 'policies',
- value: {
- policyRequirements: ['a', 'b'],
- name: 'password',
- policies: [],
- },
- },
- {
- name: 'failedPolicies',
- value: [JSON.stringify({ failedPolicies: { c: 'c', d: 'd' } })],
- },
- {
- name: 'validateOnly',
- value: false,
- },
- {
- name: 'prompt',
- value: 'Password',
- },
- ],
- input: [
- {
- name: 'IDToken2',
- value: '',
- },
- {
- name: 'IDToken2validateOnly',
- value: false,
- },
- ],
- _id: 1,
- };
-
- it('reads/writes basic properties with "validate only"', () => {
- const cb = new ValidatedCreatePasswordCallback(payload);
- cb.setPassword('abcd123');
- cb.setValidateOnly(true);
-
- expect(cb.getType()).toBe('ValidatedCreatePasswordCallback');
- expect(cb.getPrompt()).toBe('Password');
- expect(cb.isRequired()).toBe(true);
- expect(cb.getPolicies().policyRequirements).toStrictEqual(['a', 'b']);
- expect(cb.getFailedPolicies()).toStrictEqual([{ failedPolicies: { c: 'c', d: 'd' } }]);
- expect(cb.payload.input[0].value).toBe('abcd123');
- expect(cb.payload.input[1].value).toBe(true);
- });
-
- it('writes validate only to `false` for submission', () => {
- const cb = new ValidatedCreatePasswordCallback(payload);
- cb.setValidateOnly(false);
- expect(cb.payload.input[1].value).toBe(false);
- });
-});
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/validated-create-password-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/validated-create-password-callback.ts
deleted file mode 100644
index f36d1395f..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/validated-create-password-callback.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * validated-create-password-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback, PolicyRequirement } from '../../auth/interfaces';
-import type { StringDict } from '../../shared/interfaces';
-
-/**
- * Represents a callback used to collect a valid platform password.
- */
-class ValidatedCreatePasswordCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the callback's failed policies.
- */
- public getFailedPolicies(): PolicyRequirement[] {
- const failedPolicies = this.getOutputByName(
- 'failedPolicies',
- [],
- ) as unknown as string[];
- try {
- return failedPolicies.map((v) => JSON.parse(v)) as PolicyRequirement[];
- } catch (err) {
- throw new Error(
- 'Unable to parse "failed policies" from the ForgeRock server. The JSON within `ValidatedCreatePasswordCallback` was either malformed or missing.',
- );
- }
- }
-
- /**
- * Gets the callback's applicable policies.
- */
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- public getPolicies(): StringDict {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return this.getOutputByName>('policies', {});
- }
-
- /**
- * Gets the callback's prompt.
- */
- public getPrompt(): string {
- return this.getOutputByName('prompt', '');
- }
-
- /**
- * Gets whether the password is required.
- */
- public isRequired(): boolean {
- return this.getOutputByName('required', false);
- }
-
- /**
- * Sets the callback's password.
- */
- public setPassword(password: string): void {
- this.setInputValue(password);
- }
-
- /**
- * Set if validating value only.
- */
- public setValidateOnly(value: boolean): void {
- this.setInputValue(value, /validateOnly/);
- }
-}
-
-export default ValidatedCreatePasswordCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/validated-create-username-callback.test.ts b/packages/javascript-sdk/src/fr-auth/callbacks/validated-create-username-callback.test.ts
deleted file mode 100644
index 5eed99631..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/validated-create-username-callback.test.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * validated-create-username-callback.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { CallbackType } from '../../auth/enums';
-import type { Callback } from '../../auth/interfaces';
-import ValidatedCreateUsernameCallback from './validated-create-username-callback';
-
-describe('ValidatedCreateUsernameCallback', () => {
- const payload: Callback = {
- type: CallbackType.ValidatedCreateUsernameCallback,
- output: [
- {
- name: 'echoOn',
- value: false,
- },
- {
- name: 'required',
- value: true,
- },
- {
- name: 'policies',
- value: {
- policyRequirements: ['a', 'b'],
- name: 'username',
- policies: [],
- },
- },
- {
- name: 'failedPolicies',
- value: [JSON.stringify({ failedPolicies: { c: 'c', d: 'd' } })],
- },
- {
- name: 'validateOnly',
- value: false,
- },
- {
- name: 'prompt',
- value: 'Username',
- },
- ],
- input: [
- {
- name: 'IDToken2',
- value: '',
- },
- {
- name: 'IDToken2validateOnly',
- value: false,
- },
- ],
- _id: 1,
- };
-
- it('reads/writes basic properties with "validate only"', () => {
- const cb = new ValidatedCreateUsernameCallback(payload);
- cb.setName('abcd123');
- cb.setValidateOnly(true);
-
- expect(cb.getType()).toBe('ValidatedCreateUsernameCallback');
- expect(cb.getPrompt()).toBe('Username');
- expect(cb.isRequired()).toBe(true);
- expect(cb.getPolicies().policyRequirements).toStrictEqual(['a', 'b']);
- expect(cb.getFailedPolicies()).toStrictEqual([{ failedPolicies: { c: 'c', d: 'd' } }]);
- expect(cb.payload.input[0].value).toBe('abcd123');
- expect(cb.payload.input[1].value).toBe(true);
- });
-
- it('writes validate only to `false` for submission', () => {
- const cb = new ValidatedCreateUsernameCallback(payload);
- cb.setValidateOnly(false);
- expect(cb.payload.input[1].value).toBe(false);
- });
-});
diff --git a/packages/javascript-sdk/src/fr-auth/callbacks/validated-create-username-callback.ts b/packages/javascript-sdk/src/fr-auth/callbacks/validated-create-username-callback.ts
deleted file mode 100644
index 7e8f8fa1a..000000000
--- a/packages/javascript-sdk/src/fr-auth/callbacks/validated-create-username-callback.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * validated-create-username-callback.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRCallback from '.';
-import type { Callback, PolicyRequirement } from '../../auth/interfaces';
-import type { StringDict } from '../../shared/interfaces';
-
-/**
- * Represents a callback used to collect a valid platform username.
- */
-class ValidatedCreateUsernameCallback extends FRCallback {
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Callback) {
- super(payload);
- }
-
- /**
- * Gets the callback's prompt.
- */
- public getPrompt(): string {
- return this.getOutputByName('prompt', '');
- }
-
- /**
- * Gets the callback's failed policies.
- */
- public getFailedPolicies(): PolicyRequirement[] {
- const failedPolicies = this.getOutputByName(
- 'failedPolicies',
- [],
- ) as unknown as string[];
- try {
- return failedPolicies.map((v) => JSON.parse(v)) as PolicyRequirement[];
- } catch (err) {
- throw new Error(
- 'Unable to parse "failed policies" from the ForgeRock server. The JSON within `ValidatedCreateUsernameCallback` was either malformed or missing.',
- );
- }
- }
-
- /**
- * Gets the callback's applicable policies.
- */
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- public getPolicies(): StringDict {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return this.getOutputByName>('policies', {});
- }
-
- /**
- * Gets whether the username is required.
- */
- public isRequired(): boolean {
- return this.getOutputByName('required', false);
- }
-
- /**
- * Sets the callback's username.
- */
- public setName(name: string): void {
- this.setInputValue(name);
- }
-
- /**
- * Set if validating value only.
- */
- public setValidateOnly(value: boolean): void {
- this.setInputValue(value, /validateOnly/);
- }
-}
-
-export default ValidatedCreateUsernameCallback;
diff --git a/packages/javascript-sdk/src/fr-auth/enums.ts b/packages/javascript-sdk/src/fr-auth/enums.ts
deleted file mode 100644
index b031a864e..000000000
--- a/packages/javascript-sdk/src/fr-auth/enums.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * enums.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/**
- * Types of steps returned by the authentication tree.
- */
-enum StepType {
- LoginFailure = 'LoginFailure',
- LoginSuccess = 'LoginSuccess',
- Step = 'Step',
-}
-
-export { StepType };
diff --git a/packages/javascript-sdk/src/fr-auth/fr-login-failure.ts b/packages/javascript-sdk/src/fr-auth/fr-login-failure.ts
deleted file mode 100644
index 76d353a4c..000000000
--- a/packages/javascript-sdk/src/fr-auth/fr-login-failure.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * fr-login-failure.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRPolicy from '../fr-policy';
-import type { MessageCreator, ProcessedPropertyError } from '../fr-policy/interfaces';
-import type { Step } from '../auth/interfaces';
-import { StepType } from './enums';
-import type { AuthResponse, FailureDetail } from './interfaces';
-
-class FRLoginFailure implements AuthResponse {
- /**
- * The type of step.
- */
- public readonly type = StepType.LoginFailure;
-
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Step) {}
-
- /**
- * Gets the error code.
- */
- public getCode(): number {
- return Number(this.payload.code);
- }
-
- /**
- * Gets the failure details.
- */
- public getDetail(): FailureDetail | undefined {
- return this.payload.detail;
- }
-
- /**
- * Gets the failure message.
- */
- public getMessage(): string | undefined {
- return this.payload.message;
- }
-
- /**
- * Gets processed failure message.
- */
- public getProcessedMessage(messageCreator?: MessageCreator): ProcessedPropertyError[] {
- return FRPolicy.parseErrors(this.payload, messageCreator);
- }
-
- /**
- * Gets the failure reason.
- */
- public getReason(): string | undefined {
- return this.payload.reason;
- }
-}
-
-export default FRLoginFailure;
diff --git a/packages/javascript-sdk/src/fr-auth/fr-login-success.ts b/packages/javascript-sdk/src/fr-auth/fr-login-success.ts
deleted file mode 100644
index 88acd639e..000000000
--- a/packages/javascript-sdk/src/fr-auth/fr-login-success.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * fr-login-success.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { Step } from '../auth/interfaces';
-import { StepType } from './enums';
-import type { AuthResponse } from './interfaces';
-
-class FRLoginSuccess implements AuthResponse {
- /**
- * The type of step.
- */
- public readonly type = StepType.LoginSuccess;
-
- /**
- * @param payload The raw payload returned by OpenAM
- */
- constructor(public payload: Step) {}
-
- /**
- * Gets the step's realm.
- */
- public getRealm(): string | undefined {
- return this.payload.realm;
- }
-
- /**
- * Gets the step's session token.
- */
- public getSessionToken(): string | undefined {
- return this.payload.tokenId;
- }
-
- /**
- * Gets the step's success URL.
- */
- public getSuccessUrl(): string | undefined {
- return this.payload.successUrl;
- }
-}
-
-export default FRLoginSuccess;
diff --git a/packages/javascript-sdk/src/fr-auth/fr-step.ts b/packages/javascript-sdk/src/fr-auth/fr-step.ts
deleted file mode 100644
index ba987f22f..000000000
--- a/packages/javascript-sdk/src/fr-auth/fr-step.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * fr-step.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { CallbackType } from '../auth/enums';
-import type { Callback, Step } from '../auth/interfaces';
-import type FRCallback from './callbacks';
-import type { FRCallbackFactory } from './callbacks/factory';
-import createCallback from './callbacks/factory';
-import { StepType } from './enums';
-import type { AuthResponse } from './interfaces';
-
-/**
- * Represents a single step of an authentication tree.
- */
-class FRStep implements AuthResponse {
- /**
- * The type of step.
- */
- public readonly type = StepType.Step;
-
- /**
- * The callbacks contained in this step.
- */
- public callbacks: FRCallback[] = [];
-
- /**
- * @param payload The raw payload returned by OpenAM
- * @param callbackFactory A function that returns am implementation of FRCallback
- */
- constructor(
- public payload: Step,
- callbackFactory?: FRCallbackFactory,
- ) {
- if (payload.callbacks) {
- this.callbacks = this.convertCallbacks(payload.callbacks, callbackFactory);
- }
- }
-
- /**
- * Gets the first callback of the specified type in this step.
- *
- * @param type The type of callback to find.
- */
- public getCallbackOfType(type: CallbackType): T {
- const callbacks = this.getCallbacksOfType(type);
- if (callbacks.length !== 1) {
- throw new Error(`Expected 1 callback of type "${type}", but found ${callbacks.length}`);
- }
- return callbacks[0];
- }
-
- /**
- * Gets all callbacks of the specified type in this step.
- *
- * @param type The type of callback to find.
- */
- public getCallbacksOfType(type: CallbackType): T[] {
- return this.callbacks.filter((x) => x.getType() === type) as T[];
- }
-
- /**
- * Sets the value of the first callback of the specified type in this step.
- *
- * @param type The type of callback to find.
- * @param value The value to set for the callback.
- */
- public setCallbackValue(type: CallbackType, value: unknown): void {
- const callbacks = this.getCallbacksOfType(type);
- if (callbacks.length !== 1) {
- throw new Error(`Expected 1 callback of type "${type}", but found ${callbacks.length}`);
- }
- callbacks[0].setInputValue(value);
- }
-
- /**
- * Gets the step's description.
- */
- public getDescription(): string | undefined {
- return this.payload.description;
- }
-
- /**
- * Gets the step's header.
- */
- public getHeader(): string | undefined {
- return this.payload.header;
- }
-
- /**
- * Gets the step's stage.
- */
- public getStage(): string | undefined {
- return this.payload.stage;
- }
-
- private convertCallbacks(
- callbacks: Callback[],
- callbackFactory?: FRCallbackFactory,
- ): FRCallback[] {
- const converted = callbacks.map((x: Callback) => {
- // This gives preference to the provided factory and falls back to our default implementation
- return (callbackFactory || createCallback)(x) || createCallback(x);
- });
- return converted;
- }
-}
-
-/**
- * A function that can populate the provided authentication tree step.
- */
-type FRStepHandler = (step: FRStep) => void;
-
-export default FRStep;
-export type { FRStepHandler };
diff --git a/packages/javascript-sdk/src/fr-auth/index.ts b/packages/javascript-sdk/src/fr-auth/index.ts
deleted file mode 100644
index 5d783edf5..000000000
--- a/packages/javascript-sdk/src/fr-auth/index.ts
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import Config, { StepOptions } from '../config';
-import Auth from '../auth/index';
-import { CallbackType } from '../auth/enums';
-import type RedirectCallback from '../fr-auth/callbacks/redirect-callback';
-import FRLoginFailure from './fr-login-failure';
-import FRLoginSuccess from './fr-login-success';
-import FRStep from './fr-step';
-
-/**
- * Provides access to the OpenAM authentication tree API.
- */
-abstract class FRAuth {
- public static get previousStepKey() {
- return `${Config.get().prefix}-PreviousStep`;
- }
-
- /**
- * Requests the next step in the authentication tree.
- *
- * Call `FRAuth.next()` recursively. At each step, check for session token or error, otherwise
- * populate the step's callbacks and call `next()` again.
- *
- * Example:
- *
- * ```js
- * async function nextStep(previousStep) {
- * const thisStep = await FRAuth.next(previousStep);
- *
- * switch (thisStep.type) {
- * case StepType.LoginSuccess:
- * const token = thisStep.getSessionToken();
- * break;
- * case StepType.LoginFailure:
- * const detail = thisStep.getDetail();
- * break;
- * case StepType.Step:
- * // Populate `thisStep` callbacks here, and then continue
- * thisStep.setInputValue('foo');
- * nextStep(thisStep);
- * break;
- * }
- * }
- * ```
- *
- * @param previousStep The previous step with its callback values populated
- * @param options Configuration overrides
- * @return The next step in the authentication tree
- */
- public static async next(
- previousStep?: FRStep,
- options?: StepOptions,
- ): Promise {
- const nextPayload = await Auth.next(previousStep ? previousStep.payload : undefined, options);
-
- if (nextPayload.authId) {
- // If there's an authId, tree has not been completed
- const callbackFactory = options ? options.callbackFactory : undefined;
- return new FRStep(nextPayload, callbackFactory);
- }
-
- if (!nextPayload.authId && nextPayload.ok) {
- // If there's no authId, and the response is OK, tree is complete
- return new FRLoginSuccess(nextPayload);
- }
-
- // If there's no authId, and the response is not OK, tree has failure
- return new FRLoginFailure(nextPayload);
- }
-
- /**
- * Redirects to the URL identified in the RedirectCallback and saves the full
- * step information to localStorage for retrieval when user returns from login.
- *
- * Example:
- * ```js
- * forgerock.FRAuth.redirect(step);
- * ```
- */
- public static redirect(step: FRStep): void {
- const cb = step.getCallbackOfType(CallbackType.RedirectCallback) as RedirectCallback;
- const redirectUrl = cb.getRedirectUrl();
-
- localStorage.setItem(this.previousStepKey, JSON.stringify(step));
- location.assign(redirectUrl);
- }
-
- /**
- * Resumes a tree after returning from an external client or provider.
- * Requires the full URL of the current window. It will parse URL for
- * key-value pairs as well as, if required, retrieves previous step.
- *
- * Example;
- * ```js
- * forgerock.FRAuth.resume(window.location.href)
- * ```
- */
- public static async resume(
- url: string,
- options?: StepOptions,
- ): Promise {
- const parsedUrl = new URL(url);
- const code = parsedUrl.searchParams.get('code');
- const error = parsedUrl.searchParams.get('error');
- const errorCode = parsedUrl.searchParams.get('errorCode');
- const errorMessage = parsedUrl.searchParams.get('errorMessage');
- const form_post_entry = parsedUrl.searchParams.get('form_post_entry');
- const nonce = parsedUrl.searchParams.get('nonce');
- const RelayState = parsedUrl.searchParams.get('RelayState');
- const responsekey = parsedUrl.searchParams.get('responsekey');
- const scope = parsedUrl.searchParams.get('scope');
- const state = parsedUrl.searchParams.get('state');
- const suspendedId = parsedUrl.searchParams.get('suspendedId');
- const authIndexValue = parsedUrl.searchParams.get('authIndexValue') ?? undefined;
-
- let previousStep;
-
- function requiresPreviousStep() {
- return (code && state) || form_post_entry || responsekey;
- }
-
- /**
- * If we are returning back from a provider, the previous redirect step data is required.
- * Retrieve the previous step from localStorage, and then delete it to remove stale data.
- * If suspendedId is present, no previous step data is needed, so skip below conditional.
- */
- if (requiresPreviousStep()) {
- const redirectStepString = localStorage.getItem(this.previousStepKey);
-
- if (!redirectStepString) {
- throw new Error('Error: could not retrieve original redirect information.');
- }
-
- try {
- previousStep = JSON.parse(redirectStepString);
- } catch (err) {
- throw new Error('Error: could not parse redirect params or step information');
- }
-
- localStorage.removeItem(this.previousStepKey);
- }
-
- /**
- * Construct options object from the options parameter and key-value pairs from URL.
- * Ensure query parameters from current URL are the last properties spread in the object.
- */
- const nextOptions = {
- ...options,
- query: {
- // Conditionally spread properties into object. Don't spread props with undefined/null.
- ...(code && { code }),
- ...(error && { error }),
- ...(errorCode && { errorCode }),
- ...(errorMessage && { errorMessage }),
- ...(form_post_entry && { form_post_entry }),
- ...(nonce && { nonce }),
- ...(RelayState && { RelayState }),
- ...(responsekey && { responsekey }),
- ...(scope && { scope }),
- ...(state && { state }),
- ...(suspendedId && { suspendedId }),
- // Allow developer to add or override params with their own.
- ...(options && options.query),
- },
- ...((options?.tree ?? authIndexValue) && {
- tree: options?.tree ?? authIndexValue,
- }),
- };
-
- return await this.next(previousStep, nextOptions);
- }
-
- /**
- * Requests the first step in the authentication tree.
- * This is essentially an alias to calling FRAuth.next without a previous step.
- *
- * @param options Configuration overrides
- * @return The next step in the authentication tree
- */
- public static async start(
- options?: StepOptions,
- ): Promise {
- return await FRAuth.next(undefined, options);
- }
-}
-
-export default FRAuth;
diff --git a/packages/javascript-sdk/src/fr-auth/interfaces.ts b/packages/javascript-sdk/src/fr-auth/interfaces.ts
deleted file mode 100644
index 2de0f3ff8..000000000
--- a/packages/javascript-sdk/src/fr-auth/interfaces.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * interfaces.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { StepType } from './enums';
-
-/**
- * Base interface for all types of authentication step responses.
- */
-interface AuthResponse {
- type: StepType;
-}
-
-/**
- * Represents details of a failure in an authentication step.
- */
-interface FailureDetail {
- failureUrl?: string;
-}
-
-export type { AuthResponse, FailureDetail };
diff --git a/packages/javascript-sdk/src/fr-device/collector.ts b/packages/javascript-sdk/src/fr-device/collector.ts
deleted file mode 100644
index 7e37f037f..000000000
--- a/packages/javascript-sdk/src/fr-device/collector.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * collector.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { StringDict } from '../shared/interfaces';
-
-/**
- * @class Collector - base class for FRDevice
- * Generic collector functions for collecting a device profile attributes
- */
-class Collector {
- /**
- * @method reduceToObject - goes one to two levels into source to collect attribute
- * @param props - array of strings; can use dot notation for two level lookup
- * @param src - source of attributes to check
- */
- // eslint-disable-next-line
- reduceToObject(props: string[], src: StringDict): StringDict {
- return props.reduce((prev, curr) => {
- if (curr.includes('.')) {
- const propArr = curr.split('.');
- const prop1 = propArr[0];
- const prop2 = propArr[1];
- const prop = src[prop1] && src[prop1][prop2];
- prev[prop2] = prop != undefined ? prop : '';
- } else {
- prev[curr] = src[curr] != undefined ? src[curr] : null;
- }
- return prev;
- }, {} as StringDict);
- }
-
- /**
- * @method reduceToString - goes one level into source to collect attribute
- * @param props - array of strings
- * @param src - source of attributes to check
- */
- // eslint-disable-next-line
- reduceToString(props: string[], src: any): string {
- return props.reduce((prev, curr) => {
- prev = `${prev}${src[curr].filename};`;
- return prev;
- }, '');
- }
-}
-
-export default Collector;
diff --git a/packages/javascript-sdk/src/fr-device/defaults.ts b/packages/javascript-sdk/src/fr-device/defaults.ts
deleted file mode 100644
index 9b6d6a027..000000000
--- a/packages/javascript-sdk/src/fr-device/defaults.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * defaults.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-const browserProps = [
- 'userAgent',
- 'appName',
- 'appCodeName',
- 'appVersion',
- 'appMinorVersion',
- 'buildID',
- 'product',
- 'productSub',
- 'vendor',
- 'vendorSub',
- 'browserLanguage',
-];
-const configurableCategories = [
- 'fontNames',
- 'displayProps',
- 'browserProps',
- 'hardwareProps',
- 'platformProps',
-];
-const delay = 30 * 1000;
-const devicePlatforms = {
- mac: ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
- windows: ['Win32', 'Win64', 'Windows', 'WinCE'],
- ios: ['iPhone', 'iPad', 'iPod'],
-};
-const displayProps = ['width', 'height', 'pixelDepth', 'orientation.angle'];
-const fontNames = [
- 'cursive',
- 'monospace',
- 'serif',
- 'sans-serif',
- 'fantasy',
- 'Arial',
- 'Arial Black',
- 'Arial Narrow',
- 'Arial Rounded MT Bold',
- 'Bookman Old Style',
- 'Bradley Hand ITC',
- 'Century',
- 'Century Gothic',
- 'Comic Sans MS',
- 'Courier',
- 'Courier New',
- 'Georgia',
- 'Gentium',
- 'Impact',
- 'King',
- 'Lucida Console',
- 'Lalit',
- 'Modena',
- 'Monotype Corsiva',
- 'Papyrus',
- 'Tahoma',
- 'TeX',
- 'Times',
- 'Times New Roman',
- 'Trebuchet MS',
- 'Verdana',
- 'Verona',
-];
-const hardwareProps = [
- 'cpuClass',
- 'deviceMemory',
- 'hardwareConcurrency',
- 'maxTouchPoints',
- 'oscpu',
-];
-const platformProps = ['language', 'platform', 'userLanguage', 'systemLanguage'];
-
-export {
- browserProps,
- configurableCategories,
- delay,
- devicePlatforms,
- displayProps,
- fontNames,
- hardwareProps,
- platformProps,
-};
diff --git a/packages/javascript-sdk/src/fr-device/device-profile.mock.data.ts b/packages/javascript-sdk/src/fr-device/device-profile.mock.data.ts
deleted file mode 100644
index 7227fe0dc..000000000
--- a/packages/javascript-sdk/src/fr-device/device-profile.mock.data.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * device-profile.mock.data.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-const expectedJsdom = {
- identifier: '',
- metadata: {
- hardware: {
- display: {
- width: 0,
- height: 0,
- pixelDepth: 24,
- angle: '',
- },
- cpuClass: null,
- deviceMemory: null,
- hardwareConcurrency: 16,
- maxTouchPoints: null,
- oscpu: null,
- },
- browser: {
- appName: 'Netscape',
- userAgent: 'Mozilla/5.0 (darwin) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/16.2.2',
- appCodeName: 'Mozilla',
- appVersion: '4.0',
- appMinorVersion: null,
- buildID: null,
- product: 'Gecko',
- productSub: '20030107',
- vendor: 'Apple Computer, Inc.',
- vendorSub: '',
- browserLanguage: null,
- plugins: '',
- },
- platform: {
- deviceName: 'Unknown (Browser)',
- fonts: '',
- language: 'en-US',
- platform: '',
- userLanguage: null,
- systemLanguage: null,
- timezone: 300,
- },
- },
-};
-
-const expectedJsdomWithoutDisplay = {
- identifier: '',
- metadata: {
- hardware: {
- display: {},
- cpuClass: null,
- deviceMemory: null,
- hardwareConcurrency: 16,
- maxTouchPoints: null,
- oscpu: null,
- },
- browser: {
- appName: 'Netscape',
- userAgent: 'Mozilla/5.0 (darwin) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/16.2.2',
- appCodeName: 'Mozilla',
- appVersion: '4.0',
- appMinorVersion: null,
- buildID: null,
- product: 'Gecko',
- productSub: '20030107',
- vendor: 'Apple Computer, Inc.',
- vendorSub: '',
- browserLanguage: null,
- plugins: '',
- },
- platform: {
- deviceName: 'Unknown (Browser)',
- fonts: '',
- language: 'en-US',
- platform: '',
- userLanguage: null,
- systemLanguage: null,
- timezone: 300,
- },
- },
-};
-
-const expectedJsdomWithNarrowedBrowserProps = {
- identifier: '',
- metadata: {
- hardware: {
- display: {
- width: 0,
- height: 0,
- pixelDepth: 24,
- angle: '',
- },
- cpuClass: null,
- deviceMemory: null,
- hardwareConcurrency: 16,
- maxTouchPoints: null,
- oscpu: null,
- },
- browser: {
- userAgent: 'Mozilla/5.0 (darwin) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/16.2.2',
- plugins: '',
- },
- platform: {
- deviceName: 'Unknown (Browser)',
- fonts: '',
- language: 'en-US',
- platform: '',
- userLanguage: null,
- systemLanguage: null,
- timezone: 300,
- },
- },
-};
-
-export { expectedJsdom, expectedJsdomWithoutDisplay, expectedJsdomWithNarrowedBrowserProps };
diff --git a/packages/javascript-sdk/src/fr-device/device-profile.test.ts b/packages/javascript-sdk/src/fr-device/device-profile.test.ts
deleted file mode 100644
index 93128bbfe..000000000
--- a/packages/javascript-sdk/src/fr-device/device-profile.test.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * device-profile.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-import { vi, expect, describe, it, beforeAll } from 'vitest';
-import Config from '../config';
-import FRDevice from './index';
-
-Object.defineProperty(window, 'crypto', {
- writable: true,
- value: {
- getRandomValues: vi.fn().mockImplementation(() => ['714524572', '2799534390', '3707617532']),
- },
-});
-
-beforeAll(() => {
- Config.set({
- serverConfig: {
- baseUrl: 'http://am.example.com:8443',
- timeout: 3000,
- },
- });
-});
-describe('Test DeviceProfile', () => {
- it('should return basic metadata', async () => {
- const device = new FRDevice();
- const profile = await device.getProfile({
- location: false,
- metadata: true,
- });
- const userAgent = profile.metadata.browser.userAgent as string;
- const appName = profile.metadata.browser.appName as string;
- const appVersion = profile.metadata.browser.appVersion as string;
- const vendor = profile.metadata.browser.vendor as string;
- const display = profile.metadata.hardware.display;
- const deviceName = profile.metadata.platform.deviceName as string;
- expect(userAgent.includes('jsdom')).toBeTruthy();
- expect(appName).toBe('Netscape');
- expect(appVersion).toBe('4.0');
- expect(vendor).toBe('Apple Computer, Inc.');
- expect(display).toHaveProperty('width');
- expect(display).toHaveProperty('height');
- expect(deviceName.length).toBeGreaterThan(1);
- });
-
- it('should return metadata without any display props', async () => {
- const device = new FRDevice({ displayProps: [] });
- const profile = await device.getProfile({
- location: false,
- metadata: true,
- });
- const userAgent = profile.metadata.browser.userAgent as string;
- const display = profile.metadata.hardware.display;
- const deviceName = profile.metadata.platform.deviceName as string;
- expect(userAgent.length).toBeGreaterThan(1);
- expect(display.width).toBeFalsy();
- expect(display.height).toBeFalsy();
- expect(deviceName.length).toBeGreaterThan(1);
- });
-
- it('should return metadata according to narrowed browser props', async () => {
- const device = new FRDevice({ browserProps: ['userAgent'] });
- const profile = await device.getProfile({
- location: false,
- metadata: true,
- });
- const userAgent = profile.metadata.browser.userAgent as string;
- const appName = profile.metadata.browser.appName as string;
- const appVersion = profile.metadata.browser.appVersion as string;
- const vendor = profile.metadata.browser.vendor as string;
- const display = profile.metadata.hardware.display;
- const deviceName = profile.metadata.platform.deviceName as string;
- expect(userAgent.includes('jsdom')).toBeTruthy();
- expect(appName).toBeFalsy();
- expect(appVersion).toBeFalsy();
- expect(vendor).toBeFalsy();
- expect(display).toHaveProperty('width');
- expect(display).toHaveProperty('height');
- expect(deviceName.length).toBeGreaterThan(1);
- });
-});
diff --git a/packages/javascript-sdk/src/fr-device/index.ts b/packages/javascript-sdk/src/fr-device/index.ts
deleted file mode 100644
index a67b2d437..000000000
--- a/packages/javascript-sdk/src/fr-device/index.ts
+++ /dev/null
@@ -1,264 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import {
- browserProps,
- configurableCategories,
- delay,
- devicePlatforms,
- displayProps,
- fontNames,
- hardwareProps,
- platformProps,
-} from './defaults';
-import type {
- BaseProfileConfig,
- Category,
- CollectParameters,
- DeviceProfileData,
- Geolocation,
- ProfileConfigOptions,
-} from './interfaces';
-import Collector from './collector';
-import { FRLogger } from '../util/logger';
-import Config from '../config';
-
-/**
- * @class FRDevice - Collects user device metadata
- *
- * Example:
- *
- * ```js
- * // Instantiate new device object (w/optional config, if needed)
- * const device = new forgerock.FRDevice(
- * // optional configuration
- * );
- * // override any instance methods, if needed
- * // e.g.: device.getDisplayMeta = () => {};
- *
- * // Call getProfile with required argument obj of boolean properties
- * // of location and metadata
- * const profile = await device.getProfile({
- * location: isLocationRequired,
- * metadata: isMetadataRequired,
- * });
- * ```
- */
-class FRDevice extends Collector {
- config: BaseProfileConfig = {
- fontNames,
- devicePlatforms,
- displayProps,
- browserProps,
- hardwareProps,
- platformProps,
- };
-
- constructor(config?: ProfileConfigOptions) {
- super();
- if (config) {
- Object.keys(config).forEach((key: string) => {
- if (!configurableCategories.includes(key)) {
- throw new Error('Device profile configuration category does not exist.');
- }
- this.config[key as Category] = config[key as Category];
- });
- }
- }
-
- getBrowserMeta(): { [key: string]: string } {
- if (typeof navigator === 'undefined') {
- FRLogger.warn('Cannot collect browser metadata. navigator is not defined.');
- return {};
- }
- return this.reduceToObject(this.config.browserProps, navigator);
- }
-
- getBrowserPluginsNames(): string {
- if (!(typeof navigator !== 'undefined' && navigator.plugins)) {
- FRLogger.warn('Cannot collect browser plugin information. navigator.plugins is not defined.');
- return '';
- }
- return this.reduceToString(Object.keys(navigator.plugins), navigator.plugins);
- }
-
- getDeviceName(): string {
- if (typeof navigator === 'undefined') {
- FRLogger.warn('Cannot collect device name. navigator is not defined.');
- return '';
- }
- const userAgent = navigator.userAgent;
- const platform = navigator.platform;
-
- switch (true) {
- case this.config.devicePlatforms.mac.includes(platform):
- return 'Mac (Browser)';
- case this.config.devicePlatforms.ios.includes(platform):
- return `${platform} (Browser)`;
- case this.config.devicePlatforms.windows.includes(platform):
- return 'Windows (Browser)';
- case /Android/.test(platform) || /Android/.test(userAgent):
- return 'Android (Browser)';
- case /CrOS/.test(userAgent) || /Chromebook/.test(userAgent):
- return 'Chrome OS (Browser)';
- case /Linux/.test(platform):
- return 'Linux (Browser)';
- default:
- return `${platform || 'Unknown'} (Browser)`;
- }
- }
-
- getDisplayMeta(): { [key: string]: string | number | null } {
- if (typeof screen === 'undefined') {
- FRLogger.warn('Cannot collect screen information. screen is not defined.');
- return {};
- }
- return this.reduceToObject(this.config.displayProps, screen);
- }
-
- getHardwareMeta(): { [key: string]: string } {
- if (typeof navigator === 'undefined') {
- FRLogger.warn('Cannot collect OS metadata. Navigator is not defined.');
- return {};
- }
- return this.reduceToObject(this.config.hardwareProps, navigator);
- }
-
- getIdentifier(): string {
- const storageKey = `${Config.get().prefix}-DeviceID`;
-
- if (!(typeof globalThis.crypto !== 'undefined' && globalThis.crypto.getRandomValues)) {
- FRLogger.warn('Cannot generate profile ID. Crypto and/or getRandomValues is not supported.');
- return '';
- }
- if (!localStorage) {
- FRLogger.warn('Cannot store profile ID. localStorage is not supported.');
- return '';
- }
- let id = localStorage.getItem(storageKey);
- if (!id) {
- // generate ID, 3 sections of random numbers: "714524572-2799534390-3707617532"
- id = globalThis.crypto.getRandomValues(new Uint32Array(3)).join('-');
- localStorage.setItem(storageKey, id);
- }
- return id;
- }
-
- getInstalledFonts(): string {
- if (typeof document === 'undefined') {
- FRLogger.warn('Cannot collect font data. Global document object is undefined.');
- return '';
- }
- const canvas = document.createElement('canvas');
- if (!canvas) {
- FRLogger.warn('Cannot collect font data. Browser does not support canvas element');
- return '';
- }
- const context = canvas.getContext && canvas.getContext('2d');
-
- if (!context) {
- FRLogger.warn('Cannot collect font data. Browser does not support 2d canvas context');
- return '';
- }
- const text = 'abcdefghi0123456789';
- context.font = '72px Comic Sans';
- const baseWidth = context.measureText(text).width;
-
- const installedFonts = this.config.fontNames.reduce((prev, curr) => {
- context.font = `72px ${curr}, Comic Sans`;
- const newWidth = context.measureText(text).width;
-
- if (newWidth !== baseWidth) {
- prev = `${prev}${curr};`;
- }
- return prev;
- }, '');
-
- return installedFonts;
- }
-
- async getLocationCoordinates(): Promise> {
- if (!(typeof navigator !== 'undefined' && navigator.geolocation)) {
- FRLogger.warn(
- 'Cannot collect geolocation information. navigator.geolocation is not defined.',
- );
- return Promise.resolve({});
- }
- // eslint-disable-next-line no-async-promise-executor
- return new Promise(async (resolve) => {
- navigator.geolocation.getCurrentPosition(
- (position) =>
- resolve({
- latitude: position.coords.latitude,
- longitude: position.coords.longitude,
- }),
- (error) => {
- FRLogger.warn(
- 'Cannot collect geolocation information. ' + error.code + ': ' + error.message,
- );
- resolve({});
- },
- {
- enableHighAccuracy: true,
- timeout: delay,
- maximumAge: 0,
- },
- );
- });
- }
-
- getOSMeta(): { [key: string]: string } {
- if (typeof navigator === 'undefined') {
- FRLogger.warn('Cannot collect OS metadata. navigator is not defined.');
- return {};
- }
- return this.reduceToObject(this.config.platformProps, navigator);
- }
-
- async getProfile({ location, metadata }: CollectParameters): Promise {
- const profile: DeviceProfileData = {
- identifier: this.getIdentifier(),
- };
-
- if (metadata) {
- profile.metadata = {
- hardware: {
- ...this.getHardwareMeta(),
- display: this.getDisplayMeta(),
- },
- browser: {
- ...this.getBrowserMeta(),
- plugins: this.getBrowserPluginsNames(),
- },
- platform: {
- ...this.getOSMeta(),
- deviceName: this.getDeviceName(),
- fonts: this.getInstalledFonts(),
- timezone: this.getTimezoneOffset(),
- },
- };
- }
- if (location) {
- profile.location = await this.getLocationCoordinates();
- }
- return profile;
- }
-
- getTimezoneOffset(): number | null {
- try {
- return new Date().getTimezoneOffset();
- } catch (err) {
- FRLogger.warn('Cannot collect timezone information. getTimezoneOffset is not defined.');
- return null;
- }
- }
-}
-
-export default FRDevice;
diff --git a/packages/javascript-sdk/src/fr-device/interfaces.ts b/packages/javascript-sdk/src/fr-device/interfaces.ts
deleted file mode 100644
index dbb2e0003..000000000
--- a/packages/javascript-sdk/src/fr-device/interfaces.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * interfaces.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-type Category = 'fontNames' | 'displayProps' | 'browserProps' | 'hardwareProps' | 'platformProps';
-
-interface CollectParameters {
- location: boolean;
- metadata: boolean;
-}
-
-interface DeviceProfileData {
- identifier: string;
- metadata?: {
- hardware: {
- display: {
- [key: string]: string | number | null;
- };
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- [key: string]: any;
- };
- browser: {
- [key: string]: string | number | null;
- };
- platform: {
- [key: string]: string | number | null;
- };
- };
- location?: Geolocation | Record;
-}
-
-interface Geolocation {
- latitude: number;
- longitude: number;
-}
-
-interface BaseProfileConfig {
- fontNames: string[];
- devicePlatforms: {
- mac: string[];
- windows: string[];
- ios: string[];
- };
- displayProps: string[];
- browserProps: string[];
- hardwareProps: string[];
- platformProps: string[];
-}
-
-interface ProfileConfigOptions {
- [key: string]: string[];
-}
-
-export type {
- BaseProfileConfig,
- Category,
- CollectParameters,
- DeviceProfileData,
- Geolocation,
- ProfileConfigOptions,
-};
diff --git a/packages/javascript-sdk/src/fr-device/sample-profile.json b/packages/javascript-sdk/src/fr-device/sample-profile.json
deleted file mode 100644
index 1b0375352..000000000
--- a/packages/javascript-sdk/src/fr-device/sample-profile.json
+++ /dev/null
@@ -1,45 +0,0 @@
-{
- "indentifier": "714524572-2799534390-3707617532",
- "metadata": {
- "hardware": {
- "cpuClass": null,
- "deviceMemory": 8,
- "hardwareConcurrency": 16,
- "maxTouchPoints": 0,
- "oscpu": null,
- "display": {
- "width": 1080,
- "height": 1920,
- "pixelDepth": 24,
- "angle": 270
- }
- },
- "browser": {
- "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36 Edg/80.0.361.111",
- "appName": "Netscape",
- "appCodeName": "Mozilla",
- "appVersion": "5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36 Edg/80.0.361.111",
- "appMinorVersion": null,
- "buildID": null,
- "product": "Gecko",
- "productSub": "20030107",
- "vendor": "Google Inc.",
- "vendorSub": "",
- "browserLanguage": null,
- "plugins": "internal-pdf-viewer;mhjfbmdgcfjbbpaeojofohoefgiehjai;internal-nacl-plugin;"
- },
- "platform": {
- "deviceName": "Mac (Browser)",
- "language": "en-US",
- "platform": "MacIntel",
- "userLanguage": null,
- "systemLanguage": null,
- "fonts": "cursive;monospace;sans-serif;fantasy;Arial;Arial Black;Arial Narrow;Arial Rounded MT Bold;Comic Sans MS;Courier;Courier New;Georgia;Impact;Papyrus;Tahoma;Trebuchet MS;Verdana;",
- "timezone": 300
- }
- },
- "location": {
- "latitude": 27.766237,
- "longitude": -94.889905
- }
-}
diff --git a/packages/javascript-sdk/src/fr-policy/enums.ts b/packages/javascript-sdk/src/fr-policy/enums.ts
deleted file mode 100644
index d12489ed2..000000000
--- a/packages/javascript-sdk/src/fr-policy/enums.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * enums.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-enum PolicyKey {
- CannotContainCharacters = 'CANNOT_CONTAIN_CHARACTERS',
- CannotContainDuplicates = 'CANNOT_CONTAIN_DUPLICATES',
- CannotContainOthers = 'CANNOT_CONTAIN_OTHERS',
- LeastCapitalLetters = 'AT_LEAST_X_CAPITAL_LETTERS',
- LeastNumbers = 'AT_LEAST_X_NUMBERS',
- MatchRegexp = 'MATCH_REGEXP',
- MaximumLength = 'MAX_LENGTH',
- MaximumNumber = 'MAXIMUM_NUMBER_VALUE',
- MinimumLength = 'MIN_LENGTH',
- MinimumNumber = 'MINIMUM_NUMBER_VALUE',
- Required = 'REQUIRED',
- Unique = 'UNIQUE',
- UnknownPolicy = 'UNKNOWN_POLICY',
- ValidArrayItems = 'VALID_ARRAY_ITEMS',
- ValidDate = 'VALID_DATE',
- ValidEmailAddress = 'VALID_EMAIL_ADDRESS_FORMAT',
- ValidNameFormat = 'VALID_NAME_FORMAT',
- ValidNumber = 'VALID_NUMBER',
- ValidPhoneFormat = 'VALID_PHONE_FORMAT',
- ValidQueryFilter = 'VALID_QUERY_FILTER',
- ValidType = 'VALID_TYPE',
-}
-
-export { PolicyKey };
diff --git a/packages/javascript-sdk/src/fr-policy/fr-policy.test.ts b/packages/javascript-sdk/src/fr-policy/fr-policy.test.ts
deleted file mode 100644
index ea66db6ea..000000000
--- a/packages/javascript-sdk/src/fr-policy/fr-policy.test.ts
+++ /dev/null
@@ -1,197 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * fr-policy.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRPolicy from '.';
-import { PolicyKey } from './enums';
-
-describe('The IDM error handling', () => {
- const property = 'userName';
-
- it('returns a human readable error message', () => {
- const test = {
- expectedString: `${property} must be unique`,
- policy: {
- policyRequirement: 'UNIQUE',
- },
- };
- const message = FRPolicy.parsePolicyRequirement(property, test.policy);
- expect(message).toBe(test.expectedString);
- });
-
- it('returns a human readable error message with param data', () => {
- const test = {
- expectedString: `${property} must be at least 6 characters`,
- policy: {
- params: {
- minLength: 6,
- },
- policyRequirement: 'MIN_LENGTH',
- },
- };
- const message = FRPolicy.parsePolicyRequirement(property, test.policy);
- expect(message).toBe(test.expectedString);
- });
-
- it('returns a human readable generic message for unknown error', () => {
- const test = {
- expectedString: `${property}: Unknown policy requirement "SOME_UNKNOWN_POLICY"`,
- policy: {
- params: {
- unknownParam: 6,
- },
- policyRequirement: 'SOME_UNKNOWN_POLICY',
- },
- };
- const message = FRPolicy.parsePolicyRequirement(property, test.policy);
- expect(message).toBe(test.expectedString);
- });
-
- it('error handling is extensible by customer', () => {
- const test = {
- customMessage: {
- CUSTOM_POLICY: (property: string, params: { policyRequirement: string }): string =>
- `this is a custom message for "${params.policyRequirement}" policy of ${property}`,
- },
- expectedString: `this is a custom message for "CUSTOM_POLICY" policy of ${property}`,
- policy: {
- policyRequirement: 'CUSTOM_POLICY',
- },
- };
- const message = FRPolicy.parsePolicyRequirement(property, test.policy, test.customMessage);
- expect(message).toBe(test.expectedString);
- });
-
- it('error handling is overwritable by customer', () => {
- const test = {
- customMessage: {
- [PolicyKey.Unique]: (property: string): string =>
- `this is a custom message for "UNIQUE" policy of ${property}`,
- },
- expectedString: `this is a custom message for "UNIQUE" policy of ${property}`,
- policy: {
- policyRequirement: 'UNIQUE',
- },
- };
- const message = FRPolicy.parsePolicyRequirement(property, test.policy, test.customMessage);
- expect(message).toBe(test.expectedString);
- });
-
- it('groups failed policies for one property', () => {
- const policy = {
- policyRequirements: [
- {
- policyRequirement: 'UNIQUE',
- },
- {
- params: {
- minLength: 6,
- },
- policyRequirement: 'MIN_LENGTH',
- },
- ],
- property: 'userName',
- };
-
- const messageArray = FRPolicy.parseFailedPolicyRequirement(policy);
- expect(messageArray).toEqual([
- 'userName must be unique',
- 'userName must be at least 6 characters',
- ]);
- });
-
- it('returns an object array with a human readable error and the server error', () => {
- const errorResponse = {
- code: 403,
- reason: 'Forbidden',
- message: 'Policy validation failed',
- detail: {
- failedPolicyRequirements: [
- {
- policyRequirements: [
- {
- policyRequirement: 'UNIQUE',
- },
- {
- params: {
- minLength: 6,
- },
- policyRequirement: 'MIN_LENGTH',
- },
- {
- policyRequirement: 'CUSTOM_POLICY',
- },
- ],
- property: 'userName',
- },
- {
- policyRequirements: [
- {
- params: {
- numCaps: 1,
- },
- policyRequirement: 'AT_LEAST_X_CAPITAL_LETTERS',
- },
- {
- params: {
- minLength: 6,
- },
- policyRequirement: 'MIN_LENGTH',
- },
- ],
- property: 'password',
- },
- ],
- result: false,
- },
- };
- const customMessage = {
- [PolicyKey.Unique]: (property: string): string =>
- `this is a custom message for "UNIQUE" policy of ${property}`,
- CUSTOM_POLICY: (property: string, params: { policyRequirement: string }): string =>
- `this is a custom message for "${params.policyRequirement}" policy of ${property}`,
- };
- const expected = [
- {
- messages: [
- 'this is a custom message for "UNIQUE" policy of userName',
- 'userName must be at least 6 characters',
- 'this is a custom message for "CUSTOM_POLICY" policy of userName',
- ],
- detail: {
- policyRequirements: [
- { policyRequirement: 'UNIQUE' },
- { params: { minLength: 6 }, policyRequirement: 'MIN_LENGTH' },
- { policyRequirement: 'CUSTOM_POLICY' },
- ],
- property: 'userName',
- },
- },
- {
- messages: [
- 'password must contain at least 1 capital letter',
- 'password must be at least 6 characters',
- ],
- detail: {
- policyRequirements: [
- {
- params: { numCaps: 1 },
- policyRequirement: 'AT_LEAST_X_CAPITAL_LETTERS',
- },
- { params: { minLength: 6 }, policyRequirement: 'MIN_LENGTH' },
- ],
- property: 'password',
- },
- },
- ];
-
- const errorObjArr = FRPolicy.parseErrors(errorResponse, customMessage);
- expect(errorObjArr).toEqual(expected);
- });
-});
diff --git a/packages/javascript-sdk/src/fr-policy/helpers.ts b/packages/javascript-sdk/src/fr-policy/helpers.ts
deleted file mode 100644
index 6803f8534..000000000
--- a/packages/javascript-sdk/src/fr-policy/helpers.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * helpers.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-function getProp(obj: { [key: string]: unknown } | undefined, prop: string, defaultValue: T): T {
- if (!obj || obj[prop] === undefined) {
- return defaultValue;
- }
- return obj[prop] as T;
-}
-
-export { getProp };
diff --git a/packages/javascript-sdk/src/fr-policy/index.ts b/packages/javascript-sdk/src/fr-policy/index.ts
deleted file mode 100644
index c773c583e..000000000
--- a/packages/javascript-sdk/src/fr-policy/index.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { FailedPolicyRequirement, PolicyRequirement, Step } from '../auth/interfaces';
-import { PolicyKey } from './enums';
-import type { MessageCreator, ProcessedPropertyError } from './interfaces';
-import defaultMessageCreator from './message-creator';
-
-/**
- * Utility for processing policy failures into human readable messages.
- *
- * Example:
- *
- * ```js
- * // Create message overrides and extensions as needed
- * const messageCreator = {
- * [PolicyKey.unique]: (property: string) => (
- * `this is a custom message for "UNIQUE" policy of ${property}`
- * ),
- * CUSTOM_POLICY: (property: string, params: any) => (
- * `this is a custom message for "${params.policyRequirement}" policy of ${property}`
- * ),
- * };
- *
- * const thisStep = await FRAuth.next(previousStep);
- *
- * if (thisStep.type === StepType.LoginFailure) {
- * const messagesStepMethod = thisStep.getProcessedMessage(messageCreator);
- * const messagesClassMethod = FRPolicy.parseErrors(thisStep, messageCreator)
- * }
- */
-abstract class FRPolicy {
- /**
- * Parses policy errors and generates human readable error messages.
- *
- * @param {Step} err The step containing the error.
- * @param {MessageCreator} messageCreator
- * Extensible and overridable custom error messages for policy failures.
- * @return {ProcessedPropertyError[]} Array of objects containing all processed policy errors.
- */
- public static parseErrors(
- err: Partial,
- messageCreator?: MessageCreator,
- ): ProcessedPropertyError[] {
- const errors: ProcessedPropertyError[] = [];
- if (err.detail && err.detail.failedPolicyRequirements) {
- err.detail.failedPolicyRequirements.map((x) => {
- errors.push.apply(errors, [
- {
- detail: x,
- messages: this.parseFailedPolicyRequirement(x, messageCreator),
- },
- ]);
- });
- }
- return errors;
- }
-
- /**
- * Parses a failed policy and returns a string array of error messages.
- *
- * @param {FailedPolicyRequirement} failedPolicy The detail data of the failed policy.
- * @param {MessageCreator} customMessage
- * Extensible and overridable custom error messages for policy failures.
- * @return {string[]} Array of strings with all processed policy errors.
- */
- public static parseFailedPolicyRequirement(
- failedPolicy: FailedPolicyRequirement,
- messageCreator?: MessageCreator,
- ): string[] {
- const errors: string[] = [];
- failedPolicy.policyRequirements.map((policyRequirement) => {
- errors.push(
- this.parsePolicyRequirement(failedPolicy.property, policyRequirement, messageCreator),
- );
- });
- return errors;
- }
-
- /**
- * Parses a policy error into a human readable error message.
- *
- * @param {string} property The property with the policy failure.
- * @param {PolicyRequirement} policy The policy failure data.
- * @param {MessageCreator} customMessage
- * Extensible and overridable custom error messages for policy failures.
- * @return {string} Human readable error message.
- */
- public static parsePolicyRequirement(
- property: string,
- policy: PolicyRequirement,
- messageCreator: MessageCreator = {},
- ): string {
- // AM is returning policy requirement failures as JSON strings
- const policyObject = typeof policy === 'string' ? JSON.parse(policy) : { ...policy };
-
- const policyRequirement = policyObject.policyRequirement;
-
- // Determine which message creator function to use
- const effectiveMessageCreator =
- messageCreator[policyRequirement] ||
- defaultMessageCreator[policyRequirement] ||
- defaultMessageCreator[PolicyKey.UnknownPolicy];
-
- // Flatten the parameters and create the message
- const params = policyObject.params
- ? { ...policyObject.params, policyRequirement }
- : { policyRequirement };
- const message = effectiveMessageCreator(property, params);
-
- return message;
- }
-}
-
-export default FRPolicy;
-export type { MessageCreator, ProcessedPropertyError };
-export { PolicyKey };
diff --git a/packages/javascript-sdk/src/fr-policy/interfaces.ts b/packages/javascript-sdk/src/fr-policy/interfaces.ts
deleted file mode 100644
index 6d1bf868f..000000000
--- a/packages/javascript-sdk/src/fr-policy/interfaces.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * interfaces.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { FailedPolicyRequirement } from '../auth/interfaces';
-
-interface MessageCreator {
- [key: string]: (propertyName: string, params?: { [key: string]: unknown }) => string;
-}
-
-interface ProcessedPropertyError {
- detail: FailedPolicyRequirement;
- messages: string[];
-}
-
-export type { MessageCreator, ProcessedPropertyError };
diff --git a/packages/javascript-sdk/src/fr-policy/message-creator.ts b/packages/javascript-sdk/src/fr-policy/message-creator.ts
deleted file mode 100644
index b8315f8c0..000000000
--- a/packages/javascript-sdk/src/fr-policy/message-creator.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * message-creator.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { plural } from '../util/strings';
-import { PolicyKey } from './enums';
-import { getProp } from './helpers';
-import type { MessageCreator } from './interfaces';
-
-const defaultMessageCreator: MessageCreator = {
- [PolicyKey.CannotContainCharacters]: (property: string, params?: { forbiddenChars?: string }) => {
- const forbiddenChars = getProp(params, 'forbiddenChars', '');
- return `${property} must not contain following characters: "${forbiddenChars}"`;
- },
- [PolicyKey.CannotContainDuplicates]: (property: string, params?: { duplicateValue?: string }) => {
- const duplicateValue = getProp(params, 'duplicateValue', '');
- return `${property} must not contain duplicates: "${duplicateValue}"`;
- },
- [PolicyKey.CannotContainOthers]: (property: string, params?: { disallowedFields?: string }) => {
- const disallowedFields = getProp(params, 'disallowedFields', '');
- return `${property} must not contain: "${disallowedFields}"`;
- },
- [PolicyKey.LeastCapitalLetters]: (property: string, params?: { numCaps?: number }) => {
- const numCaps = getProp(params, 'numCaps', 0);
- return `${property} must contain at least ${numCaps} capital ${plural(numCaps, 'letter')}`;
- },
- [PolicyKey.LeastNumbers]: (property: string, params?: { numNums?: number }) => {
- const numNums = getProp(params, 'numNums', 0);
- return `${property} must contain at least ${numNums} numeric ${plural(numNums, 'value')}`;
- },
- [PolicyKey.MatchRegexp]: (property: string) => `${property} has failed the "MATCH_REGEXP" policy`,
- [PolicyKey.MaximumLength]: (property: string, params?: { maxLength?: number }) => {
- const maxLength = getProp(params, 'maxLength', 0);
- return `${property} must be at most ${maxLength} ${plural(maxLength, 'character')}`;
- },
- [PolicyKey.MaximumNumber]: (property: string) =>
- `${property} has failed the "MAXIMUM_NUMBER_VALUE" policy`,
- [PolicyKey.MinimumLength]: (property: string, params?: { minLength?: number }) => {
- const minLength = getProp(params, 'minLength', 0);
- return `${property} must be at least ${minLength} ${plural(minLength, 'character')}`;
- },
- [PolicyKey.MinimumNumber]: (property: string) =>
- `${property} has failed the "MINIMUM_NUMBER_VALUE" policy`,
- [PolicyKey.Required]: (property: string) => `${property} is required`,
- [PolicyKey.Unique]: (property: string) => `${property} must be unique`,
- [PolicyKey.UnknownPolicy]: (property: string, params?: { policyRequirement?: string }) => {
- const policyRequirement = getProp(params, 'policyRequirement', 'Unknown');
- return `${property}: Unknown policy requirement "${policyRequirement}"`;
- },
- [PolicyKey.ValidArrayItems]: (property: string) =>
- `${property} has failed the "VALID_ARRAY_ITEMS" policy`,
- [PolicyKey.ValidDate]: (property: string) => `${property} has an invalid date`,
- [PolicyKey.ValidEmailAddress]: (property: string) => `${property} has an invalid email address`,
- [PolicyKey.ValidNameFormat]: (property: string) => `${property} has an invalid name format`,
- [PolicyKey.ValidNumber]: (property: string) => `${property} has an invalid number`,
- [PolicyKey.ValidPhoneFormat]: (property: string) => `${property} has an invalid phone number`,
- [PolicyKey.ValidQueryFilter]: (property: string) =>
- `${property} has failed the "VALID_QUERY_FILTER" policy`,
- [PolicyKey.ValidType]: (property: string) => `${property} has failed the "VALID_TYPE" policy`,
-};
-
-export default defaultMessageCreator;
diff --git a/packages/javascript-sdk/src/fr-qr-code/index.mock.data.ts b/packages/javascript-sdk/src/fr-qr-code/index.mock.data.ts
deleted file mode 100644
index f1c9db7e0..000000000
--- a/packages/javascript-sdk/src/fr-qr-code/index.mock.data.ts
+++ /dev/null
@@ -1,174 +0,0 @@
-import { CallbackType } from '../auth/enums';
-
-export const otpQRCodeStep = {
- authId: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9',
- callbacks: [
- {
- type: CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- 'Scan the QR code image below with the ForgeRock Authenticator app to register your ' +
- 'device with your login.',
- },
- {
- name: 'messageType',
- value: '0',
- },
- ],
- },
- {
- type: CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- `window.QRCodeReader.createCode({\n id: 'callback_0',\n text: 'otpauth\\x3A\\x` +
- `2F\\x2Ftotp\\x2FForgeRock\\x3Ajlowery\\x3Fperiod\\x3D30\\x26b\\x3D032b75\\x26` +
- `digits\\x3D6\\x26secret\\QITSTC234FRIU8DD987DW3VPICFY\\x3D\\x3D\\x3D\\x3D\\x3` +
- `D\\x',\n 3D\\x26issuer\\x3DForgeRock version: '20',\n code: 'L'\n});`,
- },
- {
- name: 'messageType',
- value: '4',
- },
- ],
- },
- {
- type: CallbackType.HiddenValueCallback,
- output: [
- {
- name: 'value',
- value:
- 'otpauth://totp/ForgeRock:jlowery?secret=QITSTC234FRIU8DD987DW3VPICFY======&issue' +
- 'r=ForgeRock&period=30&digits=6&b=032b75',
- },
- {
- name: 'id',
- value: 'mfaDeviceRegistration',
- },
- ],
- input: [
- {
- name: 'IDToken3',
- value: 'mfaDeviceRegistration',
- },
- ],
- },
- {
- type: CallbackType.ConfirmationCallback,
- output: [
- {
- name: 'prompt',
- value: '',
- },
- {
- name: 'messageType',
- value: 0,
- },
- {
- name: 'options',
- value: ['Next'],
- },
- {
- name: 'optionType',
- value: -1,
- },
- {
- name: 'defaultOption',
- value: 0,
- },
- ],
- input: [
- {
- name: 'IDToken4',
- value: 0,
- },
- ],
- },
- ],
-};
-
-export const pushQRCodeStep = {
- authId: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9',
- callbacks: [
- {
- type: CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- 'Scan the QR code image below with the ForgeRock Authenticator app to register ' +
- 'your device with your login.',
- },
- {
- name: 'messageType',
- value: '0',
- },
- ],
- },
- {
- type: CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- `window.QRCodeReader.createCode({\n id: 'callback_0',\n text: 'pushauth\\x` +
- `3A\\x2F\\x2Fpush\\x2Fforgerock\\x3AJustin\\x2520Lowery\\x3Fa\\x3DaHR0cHM6Ly9vc` +
- `GVuYW0tZm9yZ2Vycm9jay1zZGtzLmZvcmdlYmxvY2tzLmNvbTo0NDMvYW0vanNvbi9hbHBoYS9wdXN` +
- `oL3Nucy9tZXNzYWdlP19hY3Rpb249YXV0aGVudGljYXRl\\x26r\\x3DaHR0cHM6Ly9vcGVuYW0tZm` +
- `9yZ2Vycm9jay1zZGtzLmZvcmdlYmxvY2tzLmNvbTo0NDMvYW0vanNvbi9hbHBoYS9wdXNoL3Nucy9t` +
- `ZXNzYWdlP19hY3Rpb249cmVnaXN0ZXI\\x26b\\x3D032b75\\x26s\\x3DFoxEr5uAzrys1yBmuyg` +
- `PbxrVjysElmzsmqifi6eO_AI\\x26c\\x3DXD\\x2DMxsK2sRGa7sUw7kinSKoUDf_eNYMZUV2f0z5` +
- `kjgw\\x26l\\x3DYW1sYmNvb2tpZT0wMQ\\x26m\\x3DREGISTER\\x3A53b85112\\x2D8ba9\\x2` +
- `D4b7e\\x2D9107\\x2Decbca2d65f7b1695151603616\\x26issuer\\x3DRm9yZ2VSb2Nr',\n ` +
- ` version: '20',\n code: 'L'\n});`,
- },
- {
- name: 'messageType',
- value: '4',
- },
- ],
- },
- {
- type: CallbackType.HiddenValueCallback,
- output: [
- {
- name: 'value',
- value:
- 'pushauth://push/forgerock:Justin%20Lowery?l=YW1sYmNvb2tpZT0wMQ&issuer=Rm9yZ2VSb' +
- '2Nr&m=REGISTER:53b85112-8ba9-4b7e-9107-ecbca2d65f7b1695151603616&s=FoxEr5uAzrys' +
- '1yBmuygPbxrVjysElmzsmqifi6eO_AI&c=XD-MxsK2sRGa7sUw7kinSKoUDf_eNYMZUV2f0z5kjgw&r' +
- '=aHR0cHM6Ly9vcGVuYW0tZm9yZ2Vycm9jay1zZGtzLmZvcmdlYmxvY2tzLmNvbTo0NDMvYW0vanNvbi' +
- '9hbHBoYS9wdXNoL3Nucy9tZXNzYWdlP19hY3Rpb249cmVnaXN0ZXI&a=aHR0cHM6Ly9vcGVuYW0tZm9' +
- 'yZ2Vycm9jay1zZGtzLmZvcmdlYmxvY2tzLmNvbTo0NDMvYW0vanNvbi9hbHBoYS9wdXNoL3Nucy9tZ' +
- 'XNzYWdlP19hY3Rpb249YXV0aGVudGljYXRl&b=032b75',
- },
- {
- name: 'id',
- value: 'mfaDeviceRegistration',
- },
- ],
- input: [
- {
- name: 'IDToken3',
- value: 'mfaDeviceRegistration',
- },
- ],
- },
- {
- type: CallbackType.PollingWaitCallback,
- output: [
- {
- name: 'waitTime',
- value: '5000',
- },
- {
- name: 'message',
- value: 'Waiting for response...',
- },
- ],
- },
- ],
-};
diff --git a/packages/javascript-sdk/src/fr-qr-code/index.test.ts b/packages/javascript-sdk/src/fr-qr-code/index.test.ts
deleted file mode 100644
index a2ce2728f..000000000
--- a/packages/javascript-sdk/src/fr-qr-code/index.test.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import FRStep from '../fr-auth/fr-step';
-import FRQRCode from './index';
-import { otpQRCodeStep, pushQRCodeStep } from './index.mock.data';
-// import WebAuthn step as it's similar in structure for testing non-QR Code steps
-import { webAuthnRegJSCallback70 } from '../fr-webauthn/fr-webauthn.mock.data';
-
-describe('Class for managing QR Codes', () => {
- it('should return true for step containing OTP QR Code callbacks', () => {
- const expected = true;
- const step = new FRStep(otpQRCodeStep);
- const result = FRQRCode.isQRCodeStep(step);
-
- expect(result).toBe(expected);
- });
-
- it('should return true for step containing Push QR Code callbacks', () => {
- const expected = true;
- const step = new FRStep(pushQRCodeStep);
- const result = FRQRCode.isQRCodeStep(step);
-
- expect(result).toBe(expected);
- });
-
- it('should return false for step containing WebAuthn step', () => {
- const expected = false;
- const step = new FRStep(webAuthnRegJSCallback70);
- const result = FRQRCode.isQRCodeStep(step);
-
- expect(result).toBe(expected);
- });
-
- it('should return an object with OTP QR Code data', () => {
- const expected = {
- message:
- 'Scan the QR code image below with the ForgeRock Authenticator app to register your ' +
- 'device with your login.',
- use: 'otp',
- uri:
- 'otpauth://totp/ForgeRock:jlowery?secret=QITSTC234FRIU8DD987DW3VPICFY======&issue' +
- 'r=ForgeRock&period=30&digits=6&b=032b75',
- };
- const step = new FRStep(otpQRCodeStep);
- const result = FRQRCode.getQRCodeData(step);
-
- expect(result).toStrictEqual(expected);
- });
-
- it('should return an object with Push QR Code data', () => {
- const expected = {
- message:
- 'Scan the QR code image below with the ForgeRock Authenticator app to register ' +
- 'your device with your login.',
- use: 'push',
- uri:
- 'pushauth://push/forgerock:Justin%20Lowery?l=YW1sYmNvb2tpZT0wMQ&issuer=Rm9yZ2VSb' +
- '2Nr&m=REGISTER:53b85112-8ba9-4b7e-9107-ecbca2d65f7b1695151603616&s=FoxEr5uAzrys' +
- '1yBmuygPbxrVjysElmzsmqifi6eO_AI&c=XD-MxsK2sRGa7sUw7kinSKoUDf_eNYMZUV2f0z5kjgw&r' +
- '=aHR0cHM6Ly9vcGVuYW0tZm9yZ2Vycm9jay1zZGtzLmZvcmdlYmxvY2tzLmNvbTo0NDMvYW0vanNvbi' +
- '9hbHBoYS9wdXNoL3Nucy9tZXNzYWdlP19hY3Rpb249cmVnaXN0ZXI&a=aHR0cHM6Ly9vcGVuYW0tZm9' +
- 'yZ2Vycm9jay1zZGtzLmZvcmdlYmxvY2tzLmNvbTo0NDMvYW0vanNvbi9hbHBoYS9wdXNoL3Nucy9tZ' +
- 'XNzYWdlP19hY3Rpb249YXV0aGVudGljYXRl&b=032b75',
- };
- const step = new FRStep(pushQRCodeStep);
- const result = FRQRCode.getQRCodeData(step);
-
- expect(result).toStrictEqual(expected);
- });
-});
diff --git a/packages/javascript-sdk/src/fr-qr-code/index.ts b/packages/javascript-sdk/src/fr-qr-code/index.ts
deleted file mode 100644
index b14f0ee3a..000000000
--- a/packages/javascript-sdk/src/fr-qr-code/index.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { CallbackType } from '../auth/enums';
-import HiddenValueCallback from '../fr-auth/callbacks/hidden-value-callback';
-import TextOutputCallback from '../fr-auth/callbacks/text-output-callback';
-import FRStep from '../fr-auth/fr-step';
-
-export type QRCodeData = {
- message: string;
- use: string;
- uri: string;
-};
-
-/**
- * @class FRQRCode - A utility class for handling QR Code steps
- *
- * Example:
- *
- * ```js
- * const isQRCodeStep = FRQRCode.isQRCodeStep(step);
- * let qrCodeData;
- * if (isQRCodeStep) {
- * qrCodeData = FRQRCode.getQRCodeData(step);
- * }
- * ```
- */
-abstract class FRQRCode {
- /**
- * @method isQRCodeStep - determines if step contains QR Code callbacks
- * @param {FRStep} step - step object from AM response
- * @returns {boolean}
- */
- public static isQRCodeStep(step: FRStep): boolean {
- const hiddenValueCb = step.getCallbacksOfType(CallbackType.HiddenValueCallback);
-
- // QR Codes step should have at least one HiddenValueCallback
- if (hiddenValueCb.length === 0) {
- return false;
- }
- return !!this.getQRCodeURICb(hiddenValueCb);
- }
-
- /**
- * @method getQRCodeData - gets the necessary information from the QR Code callbacks
- * @param {FRStep} step - step object from AM response
- * @returns {QRCodeData}
- */
- public static getQRCodeData(step: FRStep): QRCodeData {
- const hiddenValueCb = step.getCallbacksOfType(CallbackType.HiddenValueCallback);
-
- // QR Codes step should have at least one HiddenValueCallback
- if (hiddenValueCb.length === 0) {
- throw new Error(
- 'QR Code step must contain a HiddenValueCallback. Use `FRQRCode.isQRCodeStep` to guard.',
- );
- }
- const qrCodeURICb = this.getQRCodeURICb(hiddenValueCb) as HiddenValueCallback;
- const outputValue = qrCodeURICb ? qrCodeURICb.getOutputValue('value') : '';
- const qrCodeUse =
- typeof outputValue === 'string' && outputValue.includes('otpauth://') ? 'otp' : 'push';
-
- const messageCbs = step.getCallbacksOfType(CallbackType.TextOutputCallback);
- const displayMessageCb = messageCbs.find((cb) => {
- const textOutputCallback = cb as TextOutputCallback;
- return textOutputCallback.getMessageType() !== '4';
- }) as TextOutputCallback | null;
-
- return {
- message: displayMessageCb ? displayMessageCb.getMessage() : '',
- use: qrCodeUse,
- uri: typeof outputValue === 'string' ? outputValue : '',
- };
- }
-
- private static getQRCodeURICb(hiddenValueCbs: HiddenValueCallback[]) {
- // Look for a HiddenValueCallback with an OTP URI
- return hiddenValueCbs.find((cb) => {
- const outputValue = cb.getOutputValue('value');
-
- if (typeof outputValue === 'string') {
- return outputValue?.includes('otpauth://') || outputValue?.includes('pushauth://');
- }
- return false;
- });
- }
-}
-
-export default FRQRCode;
diff --git a/packages/javascript-sdk/src/fr-recovery-codes/index.ts b/packages/javascript-sdk/src/fr-recovery-codes/index.ts
deleted file mode 100644
index 7b67ea8a5..000000000
--- a/packages/javascript-sdk/src/fr-recovery-codes/index.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { CallbackType } from '../auth/enums';
-import type TextOutputCallback from '../fr-auth/callbacks/text-output-callback';
-import type FRStep from '../fr-auth/fr-step';
-import { parseDeviceNameText, parseDisplayRecoveryCodesText } from './script-parser';
-
-/**
- * Utility for handling recovery code nodes.
- *
- * Example:
- *
- * ```js
- * // Determine if step is Display Recovery Codes step
- * const isDisplayRecoveryCodesStep = FRRecoveryCodes.isDisplayStep(step);
- * if (isDisplayRecoveryCodesStep) {
- * const recoveryCodes = FRRecoveryCodes.getCodes(step);
- * // Do the UI needful
- * }
- * ```
- */
-abstract class FRRecoveryCodes {
- public static getDeviceName(step: FRStep): string {
- const text = this.getDisplayCallback(step)?.getOutputByName('message', '') ?? '';
- return parseDeviceNameText(text);
- }
- /**
- * Retrieves the recovery codes by parsing the JavaScript message text in callback.
- *
- * @param step The step to evaluate
- * @return Recovery Code values in array
- */
- public static getCodes(step: FRStep): string[] {
- const text = this.getDisplayCallback(step)?.getOutputByName('message', '');
- return parseDisplayRecoveryCodesText(text || '');
- }
-
- /**
- * Determines if the given step is a Display Recovery Codes step.
- *
- * @param step The step to evaluate
- * @return Is this step a Display Recovery Codes step
- */
- public static isDisplayStep(step: FRStep): boolean {
- return !!this.getDisplayCallback(step);
- }
-
- /**
- * Gets the recovery codes step.
- *
- * @param step The step to evaluate
- * @return gets the Display Recovery Codes' callback
- */
- private static getDisplayCallback(step: FRStep): TextOutputCallback | undefined {
- return step
- .getCallbacksOfType(CallbackType.TextOutputCallback)
- .find((x) => {
- const cb = x.getOutputByName('message', undefined);
- return cb && (cb.includes('Recovery Codes') || cb.includes('recovery codes'));
- });
- }
-}
-
-export default FRRecoveryCodes;
diff --git a/packages/javascript-sdk/src/fr-recovery-codes/recovery-codes.test.ts b/packages/javascript-sdk/src/fr-recovery-codes/recovery-codes.test.ts
deleted file mode 100644
index ab59402be..000000000
--- a/packages/javascript-sdk/src/fr-recovery-codes/recovery-codes.test.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * recovery-codes.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import FRStep from '../fr-auth/fr-step';
-import FRRecoveryCodes from './index';
-import {
- displayRecoveryCodesResponse,
- expectedDeviceName,
- expectedRecoveryCodes,
- otherResponse,
-} from './script-text.mock.data';
-
-describe('Class for managing the Display Recovery Codes node', () => {
- it('should return true if Display Recovery Codes step', () => {
- const step = new FRStep(displayRecoveryCodesResponse);
- const isDisplayStep = FRRecoveryCodes.isDisplayStep(step);
- expect(isDisplayStep).toBe(true);
- });
-
- it('should return false if not Display Recovery Codes step', () => {
- const step = new FRStep(otherResponse);
- const isDisplayStep = FRRecoveryCodes.isDisplayStep(step);
- expect(isDisplayStep).toBe(false);
- });
-
- it('should return the Recovery Codes as array of strings', () => {
- const step = new FRStep(displayRecoveryCodesResponse);
- const recoveryCodes = FRRecoveryCodes.getCodes(step);
- expect(recoveryCodes).toStrictEqual(expectedRecoveryCodes);
- });
- it('should return a display name from the getDisplayName method', () => {
- const step = new FRStep(displayRecoveryCodesResponse);
- const displayName = FRRecoveryCodes.getDeviceName(step);
- expect(displayName).toStrictEqual(expectedDeviceName);
- });
-});
diff --git a/packages/javascript-sdk/src/fr-recovery-codes/script-parser.test.ts b/packages/javascript-sdk/src/fr-recovery-codes/script-parser.test.ts
deleted file mode 100644
index f3bcc5bac..000000000
--- a/packages/javascript-sdk/src/fr-recovery-codes/script-parser.test.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * script-parser.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { parseDeviceNameText, parseDisplayRecoveryCodesText } from './script-parser';
-import {
- displayRecoveryCodes,
- expectedRecoveryCodes,
- securityKeyCustomNameResponse,
- securityKeyResponse,
-} from './script-text.mock.data';
-
-describe('Parsing of the Display Recovery Codes script text', () => {
- it('should parse the Display Recovery Codes Text', () => {
- const result = parseDisplayRecoveryCodesText(displayRecoveryCodes);
- expect(result).toStrictEqual(expectedRecoveryCodes);
- });
- it('should parse the display name from recovery codes script', () => {
- const text = securityKeyResponse;
- const result = parseDeviceNameText(text);
- expect(result).toStrictEqual('New Security Key');
- });
- it('should parse a custom name out of the recovery text', () => {
- const text = securityKeyCustomNameResponse;
- const result = parseDeviceNameText(text);
- expect(result).toStrictEqual('My Custom Device Name');
- });
-});
diff --git a/packages/javascript-sdk/src/fr-recovery-codes/script-parser.ts b/packages/javascript-sdk/src/fr-recovery-codes/script-parser.ts
deleted file mode 100644
index 92ef8fbd3..000000000
--- a/packages/javascript-sdk/src/fr-recovery-codes/script-parser.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * script-parser.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-function parseDisplayRecoveryCodesText(text: string): string[] {
- /**
- * e.g. ` ...
- * "\n" +
- * "iZmEtxvQ00\n" +
- * "
\n" +
- * ... `
- */
-
- const recoveryCodesMatches = text.match(/\s[\w\W]"([\w]*)\\/g);
- const recoveryCodes =
- Array.isArray(recoveryCodesMatches) &&
- recoveryCodesMatches.map((substr: string) => {
- // e.g. `"iZmEtxvQ00\`
- const arr = substr.match(/"([\w]*)\\/);
- return Array.isArray(arr) ? arr[1] : '';
- });
- return recoveryCodes || [];
-}
-
-/**
- *
- * @param text
- * @returns string
- */
-function parseDeviceNameText(text: string): string {
- /**
- * We default the device name to 'New Security Key'
- * If the user has a device name, it will be wrapped in tags
- * e.g. ` ... My Security Key ... `
- * We want to remove the tags and just return the device name
- * e.g. ` ... My Security Key ... `
- */
- const displayName =
- text
- ?.match(/\s*.*<\/em>/g)?.[0]
- ?.replace('', '')
- ?.replace(' ', '') ?? 'New Security Key';
- return displayName;
-}
-export { parseDeviceNameText, parseDisplayRecoveryCodesText };
diff --git a/packages/javascript-sdk/src/fr-recovery-codes/script-text.mock.data.ts b/packages/javascript-sdk/src/fr-recovery-codes/script-text.mock.data.ts
deleted file mode 100644
index 89b953020..000000000
--- a/packages/javascript-sdk/src/fr-recovery-codes/script-text.mock.data.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-/* eslint-disable no-useless-escape */
-/*
- * @forgerock/javascript-sdk
- *
- * script-text.mock.data.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { CallbackType } from '../auth/enums';
-
-/* eslint-disable max-len */
-const displayRecoveryCodes = `/*
-* Copyright 2018 ForgeRock AS. All Rights Reserved
-*
-* Use of this code requires a commercial software license with ForgeRock AS.
-* or with one of its affiliates. All use shall be exclusively subject
-* to such license between the licensee and ForgeRock AS.
-*/\n\nvar newLocation = document.getElementById(\"wrapper\");\nvar oldHtml = newLocation.getElementsByTagName(\"fieldset\")[0].innerHTML;\nnewLocation.getElementsByTagName(\"fieldset\")[0].innerHTML = \"\\n\" +
- \"
\\n\" +
- \"
Your Recovery Codes \\n\" +
- \" You must make a copy of these WebAuthn authenticator recovery codes. They cannot be displayed again. \\n\" +
- \" \\n\" +
- \"
\\n\" +
- \"iZmEtxvQ00\\n\" +
- \"
\\n\" +
- \"
\\n\" +
- \"Eqw3GFVamY\\n\" +
- \"
\\n\" +
- \"
\\n\" +
- \"nNPqIEtIpS\\n\" +
- \"
\\n\" +
- \"
\\n\" +
- \"vGhNQpDjP8\\n\" +
- \"
\\n\" +
- \"
\\n\" +
- \"ItA4W3iBaA\\n\" +
- \"
\\n\" +
- \"
\\n\" +
- \"JmLQP6XyIo\\n\" +
- \"
\\n\" +
- \"
\\n\" +
- \"G2e6foNKke\\n\" +
- \"
\\n\" +
- \"
\\n\" +
- \"h2SqAqvT21\\n\" +
- \"
\\n\" +
- \"
\\n\" +
- \"q6VX1ojNbI\\n\" +
- \"
\\n\" +
- \"
\\n\" +
- \"IZKIQXAfY2\\n\" +
- \"
\\n\" +
- \"
\\n\" +
- \"
Use one of these codes to authenticate if you lose your device, which has been named: New Security Key
\\n\" +
- \"
\\n\" +
- \"
\" + oldHtml;\ndocument.body.appendChild(newLocation);\n\n\n
-`;
-
-const displayRecoveryCodesResponse = {
- authId: 'foo',
- callbacks: [
- {
- type: 'TextOutputCallback' as CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- '/*\n * Copyright 2018 ForgeRock AS. All Rights Reserved\n *\n * Use of this code requires a commercial software license with ForgeRock AS.\n * or with one of its affiliates. All use shall be exclusively subject\n * to such license between the licensee and ForgeRock AS.\n */\n\nvar newLocation = document.getElementById("wrapper");\nvar oldHtml = newLocation.getElementsByTagName("fieldset")[0].innerHTML;\nnewLocation.getElementsByTagName("fieldset")[0].innerHTML = "\\n" +\n "
\\n" +\n "
Your Recovery Codes \\n" +\n " You must make a copy of these WebAuthn authenticator recovery codes. They cannot be displayed again. \\n" +\n " \\n" +\n "
\\n" +\n "iZmEtxvQ00\\n" +\n "
\\n" +\n "
\\n" +\n "Eqw3GFVamY\\n" +\n "
\\n" +\n "
\\n" +\n "nNPqIEtIpS\\n" +\n "
\\n" +\n "
\\n" +\n "vGhNQpDjP8\\n" +\n "
\\n" +\n "
\\n" +\n "ItA4W3iBaA\\n" +\n "
\\n" +\n "
\\n" +\n "JmLQP6XyIo\\n" +\n "
\\n" +\n "
\\n" +\n "G2e6foNKke\\n" +\n "
\\n" +\n "
\\n" +\n "h2SqAqvT21\\n" +\n "
\\n" +\n "
\\n" +\n "q6VX1ojNbI\\n" +\n "
\\n" +\n "
\\n" +\n "IZKIQXAfY2\\n" +\n "
\\n" +\n "
\\n" +\n "
Use one of these codes to authenticate if you lose your device, which has been named: New Security Key
\\n" +\n "
\\n" +\n "
" + oldHtml;\ndocument.body.appendChild(newLocation);\n\n\n',
- },
- { name: 'messageType', value: '4' },
- ],
- },
- ],
-};
-const expectedDeviceName = 'New Security Key';
-
-const expectedRecoveryCodes = [
- 'iZmEtxvQ00',
- 'Eqw3GFVamY',
- 'nNPqIEtIpS',
- 'vGhNQpDjP8',
- 'ItA4W3iBaA',
- 'JmLQP6XyIo',
- 'G2e6foNKke',
- 'h2SqAqvT21',
- 'q6VX1ojNbI',
- 'IZKIQXAfY2',
-];
-
-const otherResponse = {
- authId: 'foo',
- callbacks: [
- {
- type: 'TextOutputCallback' as CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- '/*\n * Copyright 2018 ForgeRock AS. All Rights Reserved\n *\n * Use of this code requires a commercial software license with ForgeRock AS.\n * or with one of its affiliates. All use shall be exclusively subject\n * to such license between the licensee and ForgeRock AS.\n */\n\nvar new Location = foo;',
- },
- { name: 'messageType', value: '4' },
- ],
- },
- ],
-};
-
-const securityKeyResponse = `/* * Copyright 2018 ForgeRock AS. All Rights Reserved * * Use of this code requires a commercial software license with ForgeRock AS. * or with one of its affiliates. All use shall be exclusively subject * to such license between the licensee and ForgeRock AS. */ var newLocation = document.getElementById("wrapper"); var oldHtml = newLocation.getElementsByTagName("fieldset")[0].innerHTML; newLocation.getElementsByTagName("fieldset")[0].innerHTML = "\n" + "
\n" + "
Your Recovery Codes \n" + " You must make a copy of these recovery codes. They cannot be displayed again. \n" + " \n" + "
\n" + "kw50qtmm32\n" + "
\n" + "
\n" + "Rt2Td8AK2s\n" + "
\n" + "
\n" + "6vZrIRCBJB\n" + "
\n" + "
\n" + "HCmL01Yiyv\n" + "
\n" + "
\n" + "BvDsSpazA2\n" + "
\n" + "
\n" + "T6pbKLyW2l\n" + "
\n" + "
\n" + "gZR0u6XubS\n" + "
\n" + "
\n" + "VZ1bH94IfO\n" + "
\n" + "
\n" + "O9BZ4bLefQ\n" + "
\n" + "
\n" + "NKNrBxlHCt\n" + "
\n" + "
\n" + "
Use one of these codes to authenticate if you lose your device, which has been named: New Security Key
\n" + "
\n" + "
" + oldHtml; document.body.appendChild(newLocation);`;
-const securityKeyCustomNameResponse = `/* * Copyright 2018 ForgeRock AS. All Rights Reserved * * Use of this code requires a commercial software license with ForgeRock AS. * or with one of its affiliates. All use shall be exclusively subject * to such license between the licensee and ForgeRock AS. */ var newLocation = document.getElementById("wrapper"); var oldHtml = newLocation.getElementsByTagName("fieldset")[0].innerHTML; newLocation.getElementsByTagName("fieldset")[0].innerHTML = "\n" + "
\n" + "
Your Recovery Codes \n" + " You must make a copy of these recovery codes. They cannot be displayed again. \n" + " \n" + "
\n" + "kw50qtmm32\n" + "
\n" + "
\n" + "Rt2Td8AK2s\n" + "
\n" + "
\n" + "6vZrIRCBJB\n" + "
\n" + "
\n" + "HCmL01Yiyv\n" + "
\n" + "
\n" + "BvDsSpazA2\n" + "
\n" + "
\n" + "T6pbKLyW2l\n" + "
\n" + "
\n" + "gZR0u6XubS\n" + "
\n" + "
\n" + "VZ1bH94IfO\n" + "
\n" + "
\n" + "O9BZ4bLefQ\n" + "
\n" + "
\n" + "NKNrBxlHCt\n" + "
\n" + "
\n" + "
Use one of these codes to authenticate if you lose your device, which has been named: My Custom Device Name
\n" + "
\n" + "
" + oldHtml; document.body.appendChild(newLocation);`;
-
-export {
- displayRecoveryCodes,
- displayRecoveryCodesResponse,
- expectedDeviceName,
- expectedRecoveryCodes,
- otherResponse,
- securityKeyCustomNameResponse,
- securityKeyResponse,
-};
diff --git a/packages/javascript-sdk/src/fr-user/index.ts b/packages/javascript-sdk/src/fr-user/index.ts
deleted file mode 100644
index c69054aa6..000000000
--- a/packages/javascript-sdk/src/fr-user/index.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { ConfigOptions } from '../config';
-import type { FRStepHandler } from '../fr-auth/fr-step';
-import type FRStep from '../fr-auth/fr-step';
-import { FRLogger } from '../util/logger';
-import OAuth2Client from '../oauth2-client';
-import SessionManager from '../session-manager';
-import TokenManager from '../token-manager';
-import type { LogoutOptions } from '../oauth2-client/interfaces';
-import TokenStorage from '../token-storage';
-
-/**
- * High-level API for logging a user in/out and getting profile information.
- */
-abstract class FRUser {
- /**
- * Logs the user in with the specified step handler, acquires OAuth tokens, and retrieves
- * user profile. **Currently not implemented.**
- *
- * @typeparam T The type of user object expected
- * @param handler The function to invoke when handling authentication steps
- * @param options Configuration overrides
- */
- public static async login(
- handler: FRStepHandler,
- options?: ConfigOptions,
- ): Promise {
- FRLogger.info(handler, options); // Avoid lint errors
- throw new Error('FRUser.login() not implemented');
- }
-
- /**
- * Ends the user's session and revokes OAuth tokens.
- *
- * @param options Configuration overrides
- */
- public static async logout(options?: LogoutOptions): Promise {
- // Shallow copy options to delete redirect prop
- const configOptions = { ...options };
- delete configOptions.redirect;
-
- // Just log any exceptions that are thrown, but don't abandon the flow
- try {
- // Both invalidates the session on the server AND removes browser cookie
- await SessionManager.logout(configOptions);
- } catch (error) {
- FRLogger.warn('Session logout was not successful');
- }
-
- try {
- await OAuth2Client.revokeToken(configOptions);
- } catch (error) {
- FRLogger.warn('OAuth revokeToken was not successful');
- }
-
- // Grab tokens and keep in closure
- const storedTokens = await TokenStorage.get();
- const { idToken = '' } = storedTokens || {};
-
- // Remove tokens locally
- await TokenManager.deleteTokens();
-
- // Do this last as it can result in a redirect if using PingOne
- try {
- // Invalidates session on the server tied to the ID Token
- // Needed for Express environment as session logout is unavailable
- // Pass in the original `options` as it's needed for redirect control
- await OAuth2Client.endSession({ ...options, idToken });
- } catch (error) {
- FRLogger.warn('OAuth endSession was not successful');
- }
- }
-}
-
-export default FRUser;
diff --git a/packages/javascript-sdk/src/fr-webauthn/enums.ts b/packages/javascript-sdk/src/fr-webauthn/enums.ts
deleted file mode 100644
index 41afa8d57..000000000
--- a/packages/javascript-sdk/src/fr-webauthn/enums.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * enums.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-enum WebAuthnOutcome {
- Error = 'ERROR',
- Unsupported = 'unsupported',
-}
-
-enum WebAuthnOutcomeType {
- AbortError = 'AbortError',
- DataError = 'DataError',
- ConstraintError = 'ConstraintError',
- EncodingError = 'EncodingError',
- InvalidError = 'InvalidError',
- NetworkError = 'NetworkError',
- NotAllowedError = 'NotAllowedError',
- NotSupportedError = 'NotSupportedError',
- SecurityError = 'SecurityError',
- TimeoutError = 'TimeoutError',
- UnknownError = 'UnknownError',
-}
-
-enum WebAuthnStepType {
- None = 0,
- Authentication = 1,
- Registration = 2,
-}
-
-export { WebAuthnOutcome, WebAuthnOutcomeType, WebAuthnStepType };
diff --git a/packages/javascript-sdk/src/fr-webauthn/fr-webauthn.mock.data.ts b/packages/javascript-sdk/src/fr-webauthn/fr-webauthn.mock.data.ts
deleted file mode 100644
index 72e7c2794..000000000
--- a/packages/javascript-sdk/src/fr-webauthn/fr-webauthn.mock.data.ts
+++ /dev/null
@@ -1,375 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * fr-webauthn.mock.data.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { CallbackType } from '../auth/enums';
-
-export const webAuthnRegJSCallback653 = {
- authId: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 ... ',
- callbacks: [
- {
- type: CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- // eslint-disable-next-line
- '/*\n * Copyright 2018-2020 ForgeRock AS. All Rights Reserved\n *\n * Use of this code requires a commercial software license with ForgeRock AS.\n * or with one of its affiliates. All use shall be exclusively subject\n * to such license between the licensee and ForgeRock AS.\n */\n\nif (!window.PublicKeyCredential) {\n document.getElementById(\'webAuthnOutcome\').value = "unsupported";\n document.getElementById("loginButton_0").click();\n}\n\nvar publicKey = {\n challenge: new Int8Array([63, -71, 8, -32, 51, 11, 35, -85, -19, -93, -17, 9, -10, 104, 96, -5, -43, -94, 126, 123, 18, 44, -53, 27, 69, -59, -45, -113, 4, -120, -12, -17]).buffer,\n // Relying Party:\n rp: {\n \n name: "ForgeRock"\n },\n // User:\n user: {\n id: Uint8Array.from("sgsP5DNBy2TvEhwnWHu1BFRw2_LQepAdjkOfC1z6nxU", function (c) { return c.charCodeAt(0) }),\n name: "57a5b4e4-6999-4b45-bf86-a4f2e5d4b629",\n displayName: "57a5b4e4-6999-4b45-bf86-a4f2e5d4b629"\n },\n pubKeyCredParams: [ { "type": "public-key", "alg": -7 }, { "type": "public-key", "alg": -257 } ],\n attestation: "none",\n timeout: 60000,\n excludeCredentials: [],\n authenticatorSelection: {"userVerification":"discouraged"}\n};\n\nnavigator.credentials.create({publicKey: publicKey})\n .then(function (newCredentialInfo) {\n var rawId = newCredentialInfo.id;\n var clientData = String.fromCharCode.apply(null, new Uint8Array(newCredentialInfo.response.clientDataJSON));\n var keyData = new Int8Array(newCredentialInfo.response.attestationObject).toString();\n document.getElementById(\'webAuthnOutcome\').value = clientData + "::" + keyData + "::" + rawId;\n document.getElementById("loginButton_0").click();\n }).catch(function (err) {\n document.getElementById(\'webAuthnOutcome\').value = "ERROR" + "::" + err;\n document.getElementById("loginButton_0").click();\n });\n',
- },
- { name: 'messageType', value: '4' },
- ],
- },
- {
- type: CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- // eslint-disable-next-line
- '/*\n * Copyright 2018 ForgeRock AS. All Rights Reserved\n *\n * Use of this code requires a commercial software license with ForgeRock AS.\n * or with one of its affiliates. All use shall be exclusively subject\n * to such license between the licensee and ForgeRock AS.\n *\n */\n\n/*\n * Note:\n *\n * When a ConfirmationCallback is used (e.g. during recovery code use), the XUI does not render a loginButton. However\n * the webAuthn script needs to call loginButton.click() to execute the appropriate data reformatting prior to sending\n * the request into AM. Here we query whether the loginButton exists and add it to the DOM if it doesn\'t.\n */\n\nvar newLocation = document.getElementById("wrapper");\n\nvar script = "";\n\nnewLocation.getElementsByTagName("fieldset")[0].innerHTML += script;\ndocument.body.appendChild(newLocation);',
- },
- { name: 'messageType', value: '4' },
- ],
- },
- {
- type: CallbackType.HiddenValueCallback,
- output: [
- { name: 'value', value: 'false' },
- { name: 'id', value: 'webAuthnOutcome' },
- ],
- input: [{ name: 'IDToken3', value: 'webAuthnOutcome' }],
- },
- ],
-};
-
-export const webAuthnAuthJSCallback653 = {
- authId: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 ... ',
- callbacks: [
- {
- type: CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- // eslint-disable-next-line
- '/*\n * Copyright 2018-2020 ForgeRock AS. All Rights Reserved\n *\n * Use of this code requires a commercial software license with ForgeRock AS.\n * or with one of its affiliates. All use shall be exclusively subject\n * to such license between the licensee and ForgeRock AS.\n */\n\nif (!window.PublicKeyCredential) {\n document.getElementById(\'webAuthnOutcome\').value = "unsupported";\n document.getElementById("loginButton_0").click();\n}\n\nvar acceptableCredentials = [\n { "type": "public-key", "id": new Int8Array([1, 97, 2, 123, -105, -19, -106, 10, -86, 82, -23, 5, 52, 63, 103, 110, -71, 53, 107, 104, 76, -42, -49, 96, 67, -114, -97, 19, -59, 89, -102, -115, -110, -101, -6, -98, 39, -75, 2, 74, 23, -105, 67, 6, -112, 21, -3, 36, -114, 52, 35, 75, 74, 82, -8, 115, -128, -34, -105, 110, 124, 41, -79, -53, -90, 81, -11, -7, 91, -45, -67, -82, 106, 74, 30, 112, 100, -47, 54, -12, 95, 81, 97, 36, 123, -15, -91, 87, -82, 87, -45, -103, -80, 109, -111, 82, 109, 58, 50, 19, -21, -102, 54, -108, -68, 12, -101, -53, -65, 11, -94, -36, 112, -101, -95, -90, -118, 68, 13, 8, -49, -77, -28, -82, -97, 126, -71, 33, -58, 19, 58, -118, 36, -28, 22, -55, 64, -72, -80, -9, -48, -50, 58, -52, 64, -64, -27, -5, -12, 110, -95, -17]).buffer }\n];\n\nvar options = {\n \n challenge: new Int8Array([109, 14, 35, -101, 97, -69, -105, -89, -58, 14, 108, 59, 45, 87, 109, -78, -51, 64, 90, 124, -97, 43, -84, -108, -69, -117, 101, -4, -36, -69, -106, 103]).buffer,\n timeout: 60000,\n userVerification: "discouraged",\n allowCredentials: acceptableCredentials\n};\n\nnavigator.credentials.get({ "publicKey" : options })\n .then(function (assertion) {\n var clientData = String.fromCharCode.apply(null, new Uint8Array(assertion.response.clientDataJSON));\n var authenticatorData = new Int8Array(assertion.response.authenticatorData).toString();\n var signature = new Int8Array(assertion.response.signature).toString();\n var rawId = assertion.id;\n document.getElementById(\'webAuthnOutcome\').value = clientData + "::" + authenticatorData + "::" + signature + "::" + rawId;\n document.getElementById("loginButton_0").click();\n }).catch(function (err) {\n document.getElementById(\'webAuthnOutcome\').value = "ERROR" + "::" + err;\n document.getElementById("loginButton_0").click();\n });\n',
- },
- { name: 'messageType', value: '4' },
- ],
- },
- {
- type: CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- // eslint-disable-next-line
- '/*\n * Copyright 2018 ForgeRock AS. All Rights Reserved\n *\n * Use of this code requires a commercial software license with ForgeRock AS.\n * or with one of its affiliates. All use shall be exclusively subject\n * to such license between the licensee and ForgeRock AS.\n *\n */\n\n/*\n * Note:\n *\n * When a ConfirmationCallback is used (e.g. during recovery code use), the XUI does not render a loginButton. However\n * the webAuthn script needs to call loginButton.click() to execute the appropriate data reformatting prior to sending\n * the request into AM. Here we query whether the loginButton exists and add it to the DOM if it doesn\'t.\n */\n\nvar newLocation = document.getElementById("wrapper");\n\nvar script = "";\n\nnewLocation.getElementsByTagName("fieldset")[0].innerHTML += script;\ndocument.body.appendChild(newLocation);',
- },
- { name: 'messageType', value: '4' },
- ],
- },
- {
- type: CallbackType.HiddenValueCallback,
- output: [
- { name: 'value', value: 'false' },
- { name: 'id', value: 'webAuthnOutcome' },
- ],
- input: [{ name: 'IDToken3', value: 'webAuthnOutcome' }],
- },
- ],
-};
-
-export const webAuthnRegJSCallback70 = {
- authId: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 ... ',
- callbacks: [
- {
- type: CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- // eslint-disable-next-line
- '/*\n * Copyright 2018-2020 ForgeRock AS. All Rights Reserved\n *\n * Use of this code requires a commercial software license with ForgeRock AS.\n * or with one of its affiliates. All use shall be exclusively subject\n * to such license between the licensee and ForgeRock AS.\n */\n\nif (!window.PublicKeyCredential) {\n document.getElementById(\'webAuthnOutcome\').value = "unsupported";\n document.getElementById("loginButton_0").click();\n}\n\nvar publicKey = {\n challenge: new Int8Array([87, -95, 18, -17, -59, -3, -72, -9, -109, 77, -66, 67, 101, -59, -29, -92, -31, -58, 117, -14, 3, -123, 1, -54, -69, -122, 44, 111, 30, 49, 12, 81]).buffer,\n // Relying Party:\n rp: {\n id: "https://user.example.com:3002",\n name: "ForgeRock"\n },\n // User:\n user: {\n id: Uint8Array.from("NTdhNWI0ZTQtNjk5OS00YjQ1LWJmODYtYTRmMmU1ZDRiNjI5", function (c) { return c.charCodeAt(0) }),\n name: "57a5b4e4-6999-4b45-bf86-a4f2e5d4b629",\n displayName: "57a5b4e4-6999-4b45-bf86-a4f2e5d4b629"\n },\n pubKeyCredParams: [ { "type": "public-key", "alg": -257 }, { "type": "public-key", "alg": -7 } ],\n attestation: "none",\n timeout: 60000,\n excludeCredentials: [{ "type": "public-key", "id": new Int8Array([49, -96, -107, 113, 106, 5, 115, 22, 68, 121, -85, -27, 8, -58, -113, 127, -105, -37, -10, -12, -58, -25, 29, -82, -18, 69, -99, 125, 33, 82, 38, -66, -27, -128, -91, -86, 87, 68, 94, 0, -78, 70, -11, -70, -14, -53, 38, -60, 46, 27, 66, 46, 21, -125, -70, 123, -46, -124, 86, -2, 102, 70, -52, 54]).buffer },{ "type": "public-key", "id": new Int8Array([64, 17, -15, -123, -21, 127, 76, -120, 90, -112, -5, 54, 105, 93, 82, -104, -79, 107, -69, -3, -113, -94, -59, -4, 126, -33, 117, 32, -44, 122, -97, 8, -112, 105, -96, 96, 90, 44, -128, -121, 107, 79, -98, -68, -93, 11, -105, -47, 102, 13, 110, 84, 59, -91, -30, 37, -3, -22, 39, 111, -10, 87, -50, -35]).buffer }],\n authenticatorSelection: {"userVerification":"preferred"}\n};\n\nnavigator.credentials.create({publicKey: publicKey})\n .then(function (newCredentialInfo) {\n var rawId = newCredentialInfo.id;\n var clientData = String.fromCharCode.apply(null, new Uint8Array(newCredentialInfo.response.clientDataJSON));\n var keyData = new Int8Array(newCredentialInfo.response.attestationObject).toString();\n document.getElementById(\'webAuthnOutcome\').value = clientData + "::" + keyData + "::" + rawId;\n document.getElementById("loginButton_0").click();\n }).catch(function (err) {\n document.getElementById(\'webAuthnOutcome\').value = "ERROR" + "::" + err;\n document.getElementById("loginButton_0").click();\n });',
- },
- { name: 'messageType', value: '4' },
- ],
- },
- {
- type: CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- // eslint-disable-next-line
- '/*\n * Copyright 2018 ForgeRock AS. All Rights Reserved\n *\n * Use of this code requires a commercial software license with ForgeRock AS.\n * or with one of its affiliates. All use shall be exclusively subject\n * to such license between the licensee and ForgeRock AS.\n *\n */\n\n/*\n * Note:\n *\n * When a ConfirmationCallback is used (e.g. during recovery code use), the XUI does not render a loginButton. However\n * the webAuthn script needs to call loginButton.click() to execute the appropriate data reformatting prior to sending\n * the request into AM. Here we query whether the loginButton exists and add it to the DOM if it doesn\'t.\n */\n\nvar newLocation = document.getElementById("wrapper");\n\nvar script = "";\n\nnewLocation.getElementsByTagName("fieldset")[0].innerHTML += script;\ndocument.body.appendChild(newLocation);',
- },
- { name: 'messageType', value: '4' },
- ],
- },
- {
- type: CallbackType.HiddenValueCallback,
- output: [
- { name: 'value', value: 'false' },
- { name: 'id', value: 'webAuthnOutcome' },
- ],
- input: [{ name: 'IDToken3', value: 'webAuthnOutcome' }],
- },
- ],
-};
-
-export const webAuthnAuthJSCallback70 = {
- authId: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 ... ',
- callbacks: [
- {
- type: CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- // eslint-disable-next-line
- '/*\n * Copyright 2018-2020 ForgeRock AS. All Rights Reserved\n *\n * Use of this code requires a commercial software license with ForgeRock AS.\n * or with one of its affiliates. All use shall be exclusively subject\n * to such license between the licensee and ForgeRock AS.\n */\n\nif (!window.PublicKeyCredential) {\n document.getElementById(\'webAuthnOutcome\').value = "unsupported";\n document.getElementById("loginButton_0").click();\n}\n\nvar options = {\n \n challenge: new Int8Array([-2, 85, 78, -80, -124, -6, -118, 15, 77, -30, -76, -27, -43, -19, -51, -68, 60, -80, -64, -102, 73, -103, 76, -77, -96, -28, 5, -23, -59, -36, 1, -1]).buffer,\n timeout: 60000,\n allowCredentials: [{ "type": "public-key", "id": new Int8Array([-107, 93, 68, -67, -5, 107, 18, 16, -25, -30, 80, 103, -75, -53, -2, -95, 102, 42, 47, 126, -1, 85, 93, 45, -85, 8, -108, 107, 47, -25, 66, 12, -96, 81, 104, -127, 26, -59, -69, -23, 75, 89, 58, 124, -93, 4, 28, -128, 121, 35, 39, 103, -86, -86, 123, -67, -7, -4, 79, -49, 127, -19, 7, 4]).buffer }]\n};\n\nnavigator.credentials.get({ "publicKey" : options })\n .then(function (assertion) {\n var clientData = String.fromCharCode.apply(null, new Uint8Array(assertion.response.clientDataJSON));\n var authenticatorData = new Int8Array(assertion.response.authenticatorData).toString();\n var signature = new Int8Array(assertion.response.signature).toString();\n var rawId = assertion.id;\n var userHandle = String.fromCharCode.apply(null, new Uint8Array(assertion.response.userHandle));\n document.getElementById(\'webAuthnOutcome\').value = clientData + "::" + authenticatorData + "::" + signature + "::" + rawId + "::" + userHandle;\n document.getElementById("loginButton_0").click();\n }).catch(function (err) {\n document.getElementById(\'webAuthnOutcome\').value = "ERROR" + "::" + err;\n document.getElementById("loginButton_0").click();\n });\n',
- },
- { name: 'messageType', value: '4' },
- ],
- },
- {
- type: CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- // eslint-disable-next-line
- '/*\n * Copyright 2018 ForgeRock AS. All Rights Reserved\n *\n * Use of this code requires a commercial software license with ForgeRock AS.\n * or with one of its affiliates. All use shall be exclusively subject\n * to such license between the licensee and ForgeRock AS.\n *\n */\n\n/*\n * Note:\n *\n * When a ConfirmationCallback is used (e.g. during recovery code use), the XUI does not render a loginButton. However\n * the webAuthn script needs to call loginButton.click() to execute the appropriate data reformatting prior to sending\n * the request into AM. Here we query whether the loginButton exists and add it to the DOM if it doesn\'t.\n */\n\nvar newLocation = document.getElementById("wrapper");\n\nvar script = "";\n\nnewLocation.getElementsByTagName("fieldset")[0].innerHTML += script;\ndocument.body.appendChild(newLocation);',
- },
- { name: 'messageType', value: '4' },
- ],
- },
- {
- type: CallbackType.HiddenValueCallback,
- output: [
- { name: 'value', value: 'false' },
- { name: 'id', value: 'webAuthnOutcome' },
- ],
- input: [{ name: 'IDToken3', value: 'webAuthnOutcome' }],
- },
- ],
-};
-
-export const webAuthnRegJSCallback70StoredUsername = {
- authId: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 ... ',
- callbacks: [
- {
- type: CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- // eslint-disable-next-line
- '/*\n * Copyright 2018-2020 ForgeRock AS. All Rights Reserved\n *\n * Use of this code requires a commercial software license with ForgeRock AS.\n * or with one of its affiliates. All use shall be exclusively subject\n * to such license between the licensee and ForgeRock AS.\n */\n\nif (!window.PublicKeyCredential) {\n document.getElementById(\'webAuthnOutcome\').value = "unsupported";\n document.getElementById("loginButton_0").click();\n}\n\nvar publicKey = {\n challenge: new Int8Array([-90, -30, 14, -111, 43, -115, -125, 43, -96, 124, -109, -1, -100, -64, -52, -56, -15, -9, 41, 22, -111, -116, -65, -88, 108, -60, -58, 53, 62, -66, -34, 104]).buffer,\n // Relying Party:\n rp: {\n \n name: "ForgeRock"\n },\n // User:\n user: {\n id: Uint8Array.from("NTdhNWI0ZTQtNjk5OS00YjQ1LWJmODYtYTRmMmU1ZDRiNjI5", function (c) { return c.charCodeAt(0) }),\n name: "57a5b4e4-6999-4b45-bf86-a4f2e5d4b629",\n displayName: "57a5b4e4-6999-4b45-bf86-a4f2e5d4b629"\n },\n pubKeyCredParams: [ { "type": "public-key", "alg": -257 }, { "type": "public-key", "alg": -7 } ],\n attestation: "none",\n timeout: 60000,\n excludeCredentials: [],\n authenticatorSelection: {"userVerification":"preferred","requireResidentKey":true}\n};\n\nnavigator.credentials.create({publicKey: publicKey})\n .then(function (newCredentialInfo) {\n var rawId = newCredentialInfo.id;\n var clientData = String.fromCharCode.apply(null, new Uint8Array(newCredentialInfo.response.clientDataJSON));\n var keyData = new Int8Array(newCredentialInfo.response.attestationObject).toString();\n document.getElementById(\'webAuthnOutcome\').value = clientData + "::" + keyData + "::" + rawId;\n document.getElementById("loginButton_0").click();\n }).catch(function (err) {\n document.getElementById(\'webAuthnOutcome\').value = "ERROR" + "::" + err;\n document.getElementById("loginButton_0").click();\n });',
- },
- { name: 'messageType', value: '4' },
- ],
- },
- {
- type: CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- // eslint-disable-next-line
- '/*\n * Copyright 2018 ForgeRock AS. All Rights Reserved\n *\n * Use of this code requires a commercial software license with ForgeRock AS.\n * or with one of its affiliates. All use shall be exclusively subject\n * to such license between the licensee and ForgeRock AS.\n *\n */\n\n/*\n * Note:\n *\n * When a ConfirmationCallback is used (e.g. during recovery code use), the XUI does not render a loginButton. However\n * the webAuthn script needs to call loginButton.click() to execute the appropriate data reformatting prior to sending\n * the request into AM. Here we query whether the loginButton exists and add it to the DOM if it doesn\'t.\n */\n\nvar newLocation = document.getElementById("wrapper");\n\nvar script = "";\n\nnewLocation.getElementsByTagName("fieldset")[0].innerHTML += script;\ndocument.body.appendChild(newLocation);',
- },
- { name: 'messageType', value: '4' },
- ],
- },
- {
- type: CallbackType.HiddenValueCallback,
- output: [
- { name: 'value', value: 'false' },
- { name: 'id', value: 'webAuthnOutcome' },
- ],
- input: [{ name: 'IDToken3', value: 'webAuthnOutcome' }],
- },
- ],
-};
-
-export const webAuthnAuthJSCallback70StoredUsername = {
- authId: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 ... ',
- callbacks: [
- {
- type: CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- // eslint-disable-next-line
- '/*\n * Copyright 2018-2020 ForgeRock AS. All Rights Reserved\n *\n * Use of this code requires a commercial software license with ForgeRock AS.\n * or with one of its affiliates. All use shall be exclusively subject\n * to such license between the licensee and ForgeRock AS.\n */\n\nif (!window.PublicKeyCredential) {\n document.getElementById(\'webAuthnOutcome\').value = "unsupported";\n document.getElementById("loginButton_0").click();\n}\n\nvar options = {\n \n challenge: new Int8Array([50, -11, 63, -112, 37, -61, 57, 126, 83, -127, 122, -42, -102, -82, 26, -95, -75, -37, 16, 52, 27, 54, -101, 124, -16, 99, 33, 92, 63, 10, -110, 102]).buffer,\n timeout: 60000,\n userVerification: "preferred",\n \n};\n\nnavigator.credentials.get({ "publicKey" : options })\n .then(function (assertion) {\n var clientData = String.fromCharCode.apply(null, new Uint8Array(assertion.response.clientDataJSON));\n var authenticatorData = new Int8Array(assertion.response.authenticatorData).toString();\n var signature = new Int8Array(assertion.response.signature).toString();\n var rawId = assertion.id;\n var userHandle = String.fromCharCode.apply(null, new Uint8Array(assertion.response.userHandle));\n document.getElementById(\'webAuthnOutcome\').value = clientData + "::" + authenticatorData + "::" + signature + "::" + rawId + "::" + userHandle;\n document.getElementById("loginButton_0").click();\n }).catch(function (err) {\n document.getElementById(\'webAuthnOutcome\').value = "ERROR" + "::" + err;\n document.getElementById("loginButton_0").click();\n });\n',
- },
- { name: 'messageType', value: '4' },
- ],
- },
- {
- type: CallbackType.TextOutputCallback,
- output: [
- {
- name: 'message',
- value:
- // eslint-disable-next-line
- '/*\n * Copyright 2018 ForgeRock AS. All Rights Reserved\n *\n * Use of this code requires a commercial software license with ForgeRock AS.\n * or with one of its affiliates. All use shall be exclusively subject\n * to such license between the licensee and ForgeRock AS.\n *\n */\n\n/*\n * Note:\n *\n * When a ConfirmationCallback is used (e.g. during recovery code use), the XUI does not render a loginButton. However\n * the webAuthn script needs to call loginButton.click() to execute the appropriate data reformatting prior to sending\n * the request into AM. Here we query whether the loginButton exists and add it to the DOM if it doesn\'t.\n */\n\nvar newLocation = document.getElementById("wrapper");\n\nvar script = "";\n\nnewLocation.getElementsByTagName("fieldset")[0].innerHTML += script;\ndocument.body.appendChild(newLocation);',
- },
- { name: 'messageType', value: '4' },
- ],
- },
- {
- type: CallbackType.HiddenValueCallback,
- output: [
- { name: 'value', value: 'false' },
- { name: 'id', value: 'webAuthnOutcome' },
- ],
- input: [{ name: 'IDToken3', value: 'webAuthnOutcome' }],
- },
- ],
-};
-
-export const webAuthnRegMetaCallback70 = {
- authId: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 ... ',
- callbacks: [
- {
- type: CallbackType.MetadataCallback,
- output: [
- {
- name: 'data',
- value: {
- relyingPartyName: 'ForgeRock',
- attestationPreference: 'none',
- displayName: '57a5b4e4-6999-4b45-bf86-a4f2e5d4b629',
- _type: 'WebAuthn',
- relyingPartyId: '',
- userName: '57a5b4e4-6999-4b45-bf86-a4f2e5d4b629',
- authenticatorSelection: '{"userVerification":"preferred"}',
- userId: 'NTdhNWI0ZTQtNjk5OS00YjQ1LWJmODYtYTRmMmU1ZDRiNjI5',
- timeout: '60000',
- excludeCredentials: '',
- pubKeyCredParams:
- '[ { "type": "public-key", "alg": -257 }, { "type": "public-key", "alg": -7 } ]',
- challenge: 'PiIwSUMSo5qN7ahxaBVzWCHnpIxiWZPBix3PDI4/O8k=',
- },
- },
- ],
- },
- {
- type: CallbackType.HiddenValueCallback,
- output: [
- { name: 'value', value: 'false' },
- { name: 'id', value: 'webAuthnOutcome' },
- ],
- input: [{ name: 'IDToken2', value: 'webAuthnOutcome' }],
- },
- ],
-};
-
-export const webAuthnAuthMetaCallback70 = {
- authId: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 ... ',
- callbacks: [
- {
- type: CallbackType.MetadataCallback,
- output: [
- {
- name: 'data',
- value: {
- userVerification: 'preferred',
- _type: 'WebAuthn',
- challenge: 'J7kVW1EpFY3thLYVMAAJuR9dswysFhqgrBT6vvSuidE=',
- relyingPartyId: '',
- allowCredentials:
- // eslint-disable-next-line
- 'allowCredentials: [{ "type": "public-key", "id": new Int8Array([1, 122, 110, -32, -105, -95, -90, 81, 20, -122, -96, -115, -115, 38, -7, 15, -127, 48, 48, 97, 94, -23, -54, 74, 3, -41, -118, -124, 112, 5, -77, 87, -11, 102, -86, 93, 27, 112, -128, 103, -58, -75, 68, -62, -62, 72, -27, 108, -59, 0, -124, -117, -121, -52, -97, -88, -112, 22, 122, 109, 104, -89, -10, 46, -95, 62, 64, 43, -42, 127, -53, -98, 88, -126, -68, -94, -5, 81, -71, -52, -54, -12, -55, 127, -125, 125, 53, -61, 61, 47, -66, -12, 25, 115, -24, -56, 95, 8, -20, -6, 4, 72, -45, -103, -52, 39, 123, 13, 9, -79, 99, -62, 84, -2, -41, 55, 125, 17, 126, -38, -80, -83, -28, 99, -26, -30, -18, 122, 92, -91, -128, -27, 4, 27, -39, 36, 117, 4, 120, 9, -24, -72, 84, 124, 25, 100, -40, 32, 63, -97, 119, 10, 73, 8, -46, 61, 56]).buffer },{ "type": "public-key", "id": new Int8Array([1, 15, 3, 3, 70, 54, 31, -27, -121, 121, 41, 83, -28, -49, 9, -113, -58, 117, -97, 18, 1, 100, -29, 6, -116, -93, 90, -91, 75, -120, -127, 50, 99, -37, -56, -41, 105, 42, 8, -87, -21, 37, -7, 96, -121, -125, -33, 79, 2, -10, 127, -117, 23, 46, 42, 29, 125, 91, 47, -101, 126, 44, 70, -84, -124, -94, -119, -87, 63, -116, 11, -28, 127, 76, -67, 36, -62, 62, -125, -82, 99, 71, 24, 32, -87, 93, 53, 97, -44, 18, -14, 77, 80, 77, 110, -80, -52, 18, 69, 127, 82, -27, -116, 42, -66, -53, -26, -29, 74, 75, 34, -88, -119, 118, -50, -70, -110, -68, -91, -15, 100, 113, 24, 13, -127, 39, -1, -85, 114, -125, 89, 89, -101, 94, -37, 82, -61, 15, -2, 3, -4, 9, 28, -75, -84, 96, 60, 85, -44, -98, -27, -29, 107, -115, -111, -3, -102]).buffer }]',
- timeout: '60000',
- },
- },
- ],
- },
- {
- type: CallbackType.HiddenValueCallback,
- output: [
- { name: 'value', value: 'false' },
- { name: 'id', value: 'webAuthnOutcome' },
- ],
- input: [{ name: 'IDToken2', value: 'webAuthnOutcome' }],
- },
- ],
-};
-
-export const webAuthnRegMetaCallback70StoredUsername = {
- authId: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 ... ',
- callbacks: [
- {
- type: CallbackType.MetadataCallback,
- output: [
- {
- name: 'data',
- value: {
- relyingPartyName: 'ForgeRock',
- attestationPreference: 'none',
- displayName: '57a5b4e4-6999-4b45-bf86-a4f2e5d4b629',
- _type: 'WebAuthn',
- relyingPartyId: '',
- userName: '57a5b4e4-6999-4b45-bf86-a4f2e5d4b629',
- authenticatorSelection: '{"userVerification":"preferred","requireResidentKey":true}',
- userId: 'NTdhNWI0ZTQtNjk5OS00YjQ1LWJmODYtYTRmMmU1ZDRiNjI5',
- timeout: '60000',
- excludeCredentials: '',
- pubKeyCredParams:
- '[ { "type": "public-key", "alg": -257 }, { "type": "public-key", "alg": -7 } ]',
- challenge: 'DfZ7CvBgBaApXZgcqSb+7/yA5ih/yRHhpDzrrWLMtZc=',
- },
- },
- ],
- },
- {
- type: CallbackType.HiddenValueCallback,
- output: [
- { name: 'value', value: 'false' },
- { name: 'id', value: 'webAuthnOutcome' },
- ],
- input: [{ name: 'IDToken2', value: 'webAuthnOutcome' }],
- },
- ],
-};
-
-export const webAuthnAuthMetaCallback70StoredUsername = {
- authId: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 ... ',
- callbacks: [
- {
- type: CallbackType.MetadataCallback,
- output: [
- {
- name: 'data',
- value: {
- userVerification: 'preferred',
- _type: 'WebAuthn',
- challenge: 'OHmmFKfBhrUZKkuZJ84lf9N8TaRmQSjRdZyueeSIXAo=',
- relyingPartyId: '',
- allowCredentials: '',
- timeout: '60000',
- },
- },
- ],
- },
- {
- type: CallbackType.HiddenValueCallback,
- output: [
- { name: 'value', value: 'false' },
- { name: 'id', value: 'webAuthnOutcome' },
- ],
- input: [{ name: 'IDToken2', value: 'webAuthnOutcome' }],
- },
- ],
-};
diff --git a/packages/javascript-sdk/src/fr-webauthn/fr-webauthn.test.ts b/packages/javascript-sdk/src/fr-webauthn/fr-webauthn.test.ts
deleted file mode 100644
index b3ec84116..000000000
--- a/packages/javascript-sdk/src/fr-webauthn/fr-webauthn.test.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * fr-webauthn.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { WebAuthnStepType } from './enums';
-import FRWebAuthn from './index';
-import {
- webAuthnRegJSCallback653,
- webAuthnAuthJSCallback653,
- webAuthnRegJSCallback70,
- webAuthnAuthJSCallback70,
- webAuthnRegMetaCallback70,
- webAuthnAuthMetaCallback70,
- webAuthnRegJSCallback70StoredUsername,
- webAuthnAuthJSCallback70StoredUsername,
- webAuthnRegMetaCallback70StoredUsername,
- webAuthnAuthMetaCallback70StoredUsername,
-} from './fr-webauthn.mock.data';
-import FRStep from '../fr-auth/fr-step';
-
-describe('Test FRWebAuthn class with 6.5.3 "Passwordless"', () => {
- it('should return Registration type with register text-output callbacks', () => {
- // eslint-disable-next-line
- const step = new FRStep(webAuthnRegJSCallback653 as any);
- const stepType = FRWebAuthn.getWebAuthnStepType(step);
- expect(stepType).toBe(WebAuthnStepType.Registration);
- });
- it('should return Authentication type with authenticate text-output callbacks', () => {
- // eslint-disable-next-line
- const step = new FRStep(webAuthnAuthJSCallback653 as any);
- const stepType = FRWebAuthn.getWebAuthnStepType(step);
- expect(stepType).toBe(WebAuthnStepType.Authentication);
- });
- // it('should return Registration type with register metadata callbacks', () => {
- // // eslint-disable-next-line
- // const step = new FRStep(webAuthnRegMetaCallback653 as any);
- // const stepType = FRWebAuthn.getWebAuthnStepType(step);
- // expect(stepType).toBe(WebAuthnStepType.Registration);
- // });
- // it('should return Authentication type with authenticate metadata callbacks', () => {
- // // eslint-disable-next-line
- // const step = new FRStep(webAuthnAuthMetaCallback653 as any);
- // const stepType = FRWebAuthn.getWebAuthnStepType(step);
- // expect(stepType).toBe(WebAuthnStepType.Authentication);
- // });
-});
-
-describe('Test FRWebAuthn class with 7.0 "Passwordless"', () => {
- it('should return Registration type with register text-output callbacks', () => {
- // eslint-disable-next-line
- const step = new FRStep(webAuthnRegJSCallback70 as any);
- const stepType = FRWebAuthn.getWebAuthnStepType(step);
- expect(stepType).toBe(WebAuthnStepType.Registration);
- });
- it('should return Authentication type with authenticate text-output callbacks', () => {
- // eslint-disable-next-line
- const step = new FRStep(webAuthnAuthJSCallback70 as any);
- const stepType = FRWebAuthn.getWebAuthnStepType(step);
- expect(stepType).toBe(WebAuthnStepType.Authentication);
- });
- it('should return Registration type with register metadata callbacks', () => {
- // eslint-disable-next-line
- const step = new FRStep(webAuthnRegMetaCallback70 as any);
- const stepType = FRWebAuthn.getWebAuthnStepType(step);
- expect(stepType).toBe(WebAuthnStepType.Registration);
- });
- it('should return Authentication type with authenticate metadata callbacks', () => {
- // eslint-disable-next-line
- const step = new FRStep(webAuthnAuthMetaCallback70 as any);
- const stepType = FRWebAuthn.getWebAuthnStepType(step);
- expect(stepType).toBe(WebAuthnStepType.Authentication);
- });
-});
-
-describe('Test FRWebAuthn class with 7.0 "Usernameless"', () => {
- it('should return Registration type with register text-output callbacks', () => {
- // eslint-disable-next-line
- const step = new FRStep(webAuthnRegJSCallback70StoredUsername as any);
- const stepType = FRWebAuthn.getWebAuthnStepType(step);
- expect(stepType).toBe(WebAuthnStepType.Registration);
- });
- it('should return Authentication type with authenticate text-output callbacks', () => {
- // eslint-disable-next-line
- const step = new FRStep(webAuthnAuthJSCallback70StoredUsername as any);
- const stepType = FRWebAuthn.getWebAuthnStepType(step);
- expect(stepType).toBe(WebAuthnStepType.Authentication);
- });
- it('should return Registration type with register metadata callbacks', () => {
- // eslint-disable-next-line
- const step = new FRStep(webAuthnRegMetaCallback70StoredUsername as any);
- const stepType = FRWebAuthn.getWebAuthnStepType(step);
- expect(stepType).toBe(WebAuthnStepType.Registration);
- });
- it('should return Authentication type with authenticate metadata callbacks', () => {
- // eslint-disable-next-line
- const step = new FRStep(webAuthnAuthMetaCallback70StoredUsername as any);
- const stepType = FRWebAuthn.getWebAuthnStepType(step);
- expect(stepType).toBe(WebAuthnStepType.Authentication);
- });
-});
diff --git a/packages/javascript-sdk/src/fr-webauthn/helpers.mock.data.ts b/packages/javascript-sdk/src/fr-webauthn/helpers.mock.data.ts
deleted file mode 100644
index d8526f0ea..000000000
--- a/packages/javascript-sdk/src/fr-webauthn/helpers.mock.data.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * helpers.mock.data.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-// eslint-disable-next-line
-export const allowCredentials70 = 'allowCredentials: [{ "type": "public-key", "id": new Int8Array([1, -16, 9, 79, 6, -2, -82, 51, 124, -94, 95, 23, -86, 70, -43, 89, 91, -9, 45, -22, 91, -51, 84, 93, 24, -64, 38, 101, 126, -53, 87, 70, -49, -88, -105, 116, 33, 75, -39, -92, -5, 115, 12, 52, 124, -100, 85, 104, -15, 5, -13, 25, -74, 101, 71, -115, -102, 16, 10, -9, -19, -110, 65, 118, -28, 89, -15, -115, -81, 22, -104, 123, 17, -92, 49, 109, -38, -51, 100, 96, -65, 25, -48, 28, 106, -45, 17, -45, -37, 46, -5, -6, -26, -23, -108, 13, -66, -55, -117, -107, 119, 7, -32, 34, 46, 0, -29, -111, -32, 45, -15, -113, 110, 123, -44, 6, 10, 65, 99, 25, 105, 69, -127, 76, 127, -33, -89, -56, 74, 25, 43, -43, -56, 9, 87, 80, 124, -32, -39, 115, 17, 18, 78, 121, 69, -36, -44, -28, -109, -126, 58, 64, 80, -4, 21, 63, -19]).buffer }]';
-// eslint-disable-next-line
-export const allowMultipleCredentials70 = 'allowCredentials: [{ "type": "public-key", "id": new Int8Array([-33, 120, 18, 124, 16, 5, -127, -51, 68, 85, 76, -92, -3, 25, 116, 91, 71, 53, 106, -114, -86, 9, -81, -96, -32, -110, 66, -23, -5, 104, 96, 46, 43, -66, -110, 8, -70, 11, 51, -93, 19, 124, 81, 78, 58, -97, 89, -87, -26, -112, 95, -83, 118, -25, 118, 3, 35, -96, 120, -76, -87, 83, -101, 82]).buffer },{ "type": "public-key", "id": new Int8Array([1, 73, 82, 23, 76, -5, -53, -48, -104, -17, -42, 45, 7, 35, 35, -72, -7, 37, 9, 37, 117, 42, 66, 116, 58, 25, -68, 53, 113, -10, 102, 3, -60, -81, -74, 96, -5, 111, -56, 110, -101, -54, -31, -123, -100, 3, 37, -69, -114, -19, -25, -62, 18, 122, 39, 11, 83, 60, -58, 3, 116, 10, -80, -35, 6, -128, -51, -92, 100, -115, -22, -122, 21, -65, 97, 67, -49, 26, 42, -11, 90, 121, -63, 112, -16, 118, -99, -73, -89, -67, 72, -80, 18, -72, 109, 4, -14, 1, -93, 17, -17, -70, -2, -5, -116, 111, -128, 7, 62, -34, -43, 110, 89, 113, -65, -95, 113, -5, -104, -100, -73, 42, 2, 112, -21, 41, 41, 91, 108, -102, 47, -77, -52, 70, 107, -4, 25, -120, 114, 30, 23, 103, 120, 17, 55, 91, -110, -58, -110, 13, -56, 57, -126, 36, 40, 89, -9]).buffer }]'
-// eslint-disable-next-line
-export const acceptableCredentials653 = '{ "type": "public-key", "id": new Int8Array([53, -21, 26, -99, 5, 4, -112, -76, -126, 90, -35, -7, -31, -92, 19, -71, -39, 73, 52, -10, -14, -7, -59, -7, -36, -111, 64, 101, 29, 89, 90, -56, 108, 42, 32, -19, -113, 118, -114, 49, 109, -70, 68, -89, 36, -36, -103, -128, 34, -24, -40, -71, -125, -120, -80, 63, 25, -33, 2, 26, 111, -52, -15, -52]).buffer }';
-// eslint-disable-next-line
-export const acceptableMultipleCredentials653 = '{ "type": "public-key", "id": new Int8Array([17, 88, -12, 26, -50, -48, -38, 36, -69, -105, -68, -38, 66, -53, -37, -50, -109, -126, 122, 26, 25, -45, 96, 37, -124, 102, 124, 94, -98, -59, 113, 94, 115, -111, -69, 45, 37, -83, 118, -115, -4, -49, 34, 115, -24, -49, -37, -17, -127, -15, 62, 18, 93, 122, -109, 53, -52, 44, -63, -74, 109, 2, -110, 45]).buffer },{ "type": "public-key", "id": new Int8Array([1, 83, -98, 32, 110, -62, 78, 53, -63, -118, 12, 122, -72, -15, 85, 48, -39, -97, -73, 108, -122, -60, 56, -112, -89, -118, 111, 0, -4, 13, -50, -43, -53, 28, 114, 82, 22, -76, 15, 51, -95, 26, -90, -93, -51, 115, -28, 85, -105, -27, 111, 70, 106, -28, 45, 126, 44, 63, -16, 97, -55, 31, -24, 57, -92, 48, 26, 127, -39, 75, 12, 13, 100, -77, 13, -48, 49, 52, 31, 85, 9, 63, -122, -90, -54, -87, -110, -1, 115, -122, -69, -15, 83, 57, 95, -31, -92, -116, 89, -109, -98, 21, 24, -80, -28, 103, -28, -82, -39, 114, -29, -46, -76, 123, -69, -44, 124, 10, 53, -103, 19, -43, -12, 62, -83, -86, 95, -78, 70, -105, 116, -25, 106, 54, -72, -119, 91, 91, -71, -49, 22, 25, -108, 112, -14, 55, 9, 75, 89, -91, -59, 45]).buffer }';
-// eslint-disable-next-line
-export const pubKeyCredParamsStr = '[ { "type": "public-key", "alg": -257 }, { "type": "public-key", "alg": -7 } ]';
diff --git a/packages/javascript-sdk/src/fr-webauthn/helpers.test.ts b/packages/javascript-sdk/src/fr-webauthn/helpers.test.ts
deleted file mode 100644
index d31dd7204..000000000
--- a/packages/javascript-sdk/src/fr-webauthn/helpers.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * helpers.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { parseCredentials, parsePubKeyArray } from './helpers';
-import {
- allowCredentials70,
- allowMultipleCredentials70,
- acceptableCredentials653,
- acceptableMultipleCredentials653,
- pubKeyCredParamsStr,
-} from './helpers.mock.data';
-
-describe('Test WebAuthn helper functions', () => {
- it('should parse the one credential in the MetadataCallback 7.0', () => {
- const credentials = parseCredentials(allowCredentials70);
- expect(credentials[0].id.toString()).toBe('[object ArrayBuffer]');
- expect(credentials[0].type).toBe('public-key');
- });
-
- it('should parse the two credentials in the MetadataCallback 7.0', () => {
- const credentials = parseCredentials(allowMultipleCredentials70);
- expect(credentials[0].id.toString()).toBe('[object ArrayBuffer]');
- expect(credentials[0].type).toBe('public-key');
- expect(credentials[1].id.toString()).toBe('[object ArrayBuffer]');
- expect(credentials[1].type).toBe('public-key');
- });
-
- it('should parse the one credential in the MetadataCallback 6.5', () => {
- const credentials = parseCredentials(acceptableCredentials653);
- expect(credentials[0].id.toString()).toBe('[object ArrayBuffer]');
- expect(credentials[0].type).toBe('public-key');
- });
-
- it('should parse the two credentials in the MetadataCallback 6.5', () => {
- const credentials = parseCredentials(acceptableMultipleCredentials653);
- expect(credentials[0].id.toString()).toBe('[object ArrayBuffer]');
- expect(credentials[0].type).toBe('public-key');
- expect(credentials[1].id.toString()).toBe('[object ArrayBuffer]');
- expect(credentials[1].type).toBe('public-key');
- });
-
- it('should parse the pubKeyCredParams in the MetadataCallback 7.0 & 6.5.3', () => {
- const pubKeyCredParams = parsePubKeyArray(pubKeyCredParamsStr);
- expect(pubKeyCredParams).toContainEqual({ type: 'public-key', alg: -7 });
- expect(pubKeyCredParams).toContainEqual({ type: 'public-key', alg: -257 });
- });
-});
diff --git a/packages/javascript-sdk/src/fr-webauthn/helpers.ts b/packages/javascript-sdk/src/fr-webauthn/helpers.ts
deleted file mode 100644
index 428441ee7..000000000
--- a/packages/javascript-sdk/src/fr-webauthn/helpers.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * helpers.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/**
- * @module
- * @ignore
- * These are private utility functions for HttpClient
- */
-import { WebAuthnOutcomeType } from './enums';
-import type { ParsedCredential } from './interfaces';
-
-function ensureArray(arr: RegExpMatchArray | null): string[] {
- return arr || [];
-}
-
-function arrayBufferToString(arrayBuffer: ArrayBuffer): string {
- // https://goo.gl/yabPex - To future-proof, we'll pass along whatever the browser
- // gives us and let AM disregard randomly-injected properties
- const uint8Array = new Uint8Array(arrayBuffer);
- const txtDecoder = new TextDecoder();
-
- const json = txtDecoder.decode(uint8Array);
- return json;
-}
-
-function getIndexOne(arr: RegExpMatchArray | null): string {
- return arr ? arr[1] : '';
-}
-
-// TODO: Remove this once AM is providing fully-serialized JSON
-function parseCredentials(value: string): ParsedCredential[] {
- try {
- const creds = value
- .split('}')
- .filter((x) => !!x && x !== ']')
- .map((x) => {
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
- const idArray = parseNumberArray(x);
- return {
- id: new Int8Array(idArray).buffer,
- type: 'public-key' as PublicKeyCredentialType,
- };
- });
- return creds;
- } catch (error) {
- const e = new Error('Transforming credential object to string failed');
- e.name = WebAuthnOutcomeType.EncodingError;
- throw e;
- }
-}
-
-function parseNumberArray(value: string): number[] {
- const matches = /new Int8Array\((.+)\)/.exec(value);
- if (matches === null || matches.length < 2) {
- return [];
- }
- return JSON.parse(matches[1]);
-}
-
-function parsePubKeyArray(value: string | unknown[]): PublicKeyCredentialParameters[] | undefined {
- if (Array.isArray(value)) {
- return value as PublicKeyCredentialParameters[];
- }
- if (typeof value !== 'string') {
- return undefined;
- }
- if (value && value[0] === '[') {
- return JSON.parse(value);
- }
- value = value.replace(/(\w+):/g, '"$1":');
- return JSON.parse(`[${value}]`);
-}
-
-function parseAllowCredentialsArray(
- value: string | unknown[],
-): PublicKeyCredentialDescriptor[] | undefined {
- if (!value) {
- return undefined;
- }
- if (Array.isArray(value)) {
- return value as PublicKeyCredentialDescriptor[];
- }
- if (typeof value !== 'string') {
- return undefined;
- }
- if (value && value[0] === '[') {
- return JSON.parse(value);
- }
- value = value.replace(/(\w+):/g, '"$1":');
- return JSON.parse(`[${value}]`);
-}
-
-/**
- * AM is currently serializing RP as one of the following formats, depending on
- * whether RP ID has been configured:
- * "relyingPartyId":""
- * "relyingPartyId":"rpId: \"foo\","
- * This regex handles both formats, but should be removed once AM is fixed.
- */
-function parseRelyingPartyId(relyingPartyId: string): string {
- if (relyingPartyId.includes('rpId')) {
- return relyingPartyId.replace(/rpId: "(.+)",/, '$1');
- } else {
- return relyingPartyId.replace(/id: "(.+)",/, '$1');
- }
-}
-
-export {
- ensureArray,
- arrayBufferToString,
- getIndexOne,
- parseCredentials,
- parseNumberArray,
- parseAllowCredentialsArray,
- parsePubKeyArray,
- parseRelyingPartyId,
-};
diff --git a/packages/javascript-sdk/src/fr-webauthn/index.ts b/packages/javascript-sdk/src/fr-webauthn/index.ts
deleted file mode 100644
index 4cd1b5c4b..000000000
--- a/packages/javascript-sdk/src/fr-webauthn/index.ts
+++ /dev/null
@@ -1,477 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { CallbackType } from '../auth/enums';
-import type HiddenValueCallback from '../fr-auth/callbacks/hidden-value-callback';
-import type MetadataCallback from '../fr-auth/callbacks/metadata-callback';
-import type FRStep from '../fr-auth/fr-step';
-import { WebAuthnOutcome, WebAuthnOutcomeType, WebAuthnStepType } from './enums';
-import {
- arrayBufferToString,
- parseCredentials,
- parsePubKeyArray,
- parseRelyingPartyId,
-} from './helpers';
-import type {
- AttestationType,
- RelyingParty,
- WebAuthnAuthenticationMetadata,
- WebAuthnCallbacks,
- WebAuthnRegistrationMetadata,
- WebAuthnTextOutputRegistration,
-} from './interfaces';
-import type TextOutputCallback from '../fr-auth/callbacks/text-output-callback';
-import { parseWebAuthnAuthenticateText, parseWebAuthnRegisterText } from './script-parser';
-
-// ::::::
-type OutcomeWithName<
- ClientId extends string,
- Attestation extends AttestationType,
- PubKeyCred extends PublicKeyCredential,
- Name = '',
-> = Name extends infer P extends string
- ? `${ClientId}::${Attestation}::${PubKeyCred['id']}${P extends '' ? '' : `::${P}`}`
- : never;
-// JSON-based WebAuthn
-type WebAuthnMetadata = WebAuthnAuthenticationMetadata | WebAuthnRegistrationMetadata;
-// Script-based WebAuthn
-type WebAuthnTextOutput = WebAuthnTextOutputRegistration;
-/**
- * Utility for integrating a web browser's WebAuthn API.
- *
- * Example:
- *
- * ```js
- * // Determine if a step is a WebAuthn step
- * const stepType = FRWebAuthn.getWebAuthnStepType(step);
- * if (stepType === WebAuthnStepType.Registration) {
- * // Register a new device
- * await FRWebAuthn.register(step);
- * } else if (stepType === WebAuthnStepType.Authentication) {
- * // Authenticate with a registered device
- * await FRWebAuthn.authenticate(step);
- * }
- * ```
- */
-abstract class FRWebAuthn {
- /**
- * Determines if the given step is a WebAuthn step.
- *
- * @param step The step to evaluate
- * @return A WebAuthnStepType value
- */
- public static getWebAuthnStepType(step: FRStep): WebAuthnStepType {
- const outcomeCallback = this.getOutcomeCallback(step);
- const metadataCallback = this.getMetadataCallback(step);
- const textOutputCallback = this.getTextOutputCallback(step);
-
- if (outcomeCallback && metadataCallback) {
- const metadata = metadataCallback.getOutputValue('data') as {
- pubKeyCredParams?: [];
- };
- if (metadata?.pubKeyCredParams) {
- return WebAuthnStepType.Registration;
- }
-
- return WebAuthnStepType.Authentication;
- } else if (outcomeCallback && textOutputCallback) {
- const message = textOutputCallback.getMessage();
- if (message.includes('pubKeyCredParams')) {
- return WebAuthnStepType.Registration;
- }
-
- return WebAuthnStepType.Authentication;
- } else {
- return WebAuthnStepType.None;
- }
- }
-
- /**
- * Populates the step with the necessary authentication outcome.
- *
- * @param step The step that contains WebAuthn authentication data
- * @return The populated step
- */
- public static async authenticate(step: FRStep): Promise {
- const { hiddenCallback, metadataCallback, textOutputCallback } = this.getCallbacks(step);
- if (hiddenCallback && (metadataCallback || textOutputCallback)) {
- let outcome: ReturnType;
-
- try {
- let publicKey: PublicKeyCredentialRequestOptions;
- if (metadataCallback) {
- const meta = metadataCallback.getOutputValue('data') as WebAuthnAuthenticationMetadata;
- publicKey = this.createAuthenticationPublicKey(meta);
- } else if (textOutputCallback) {
- publicKey = parseWebAuthnAuthenticateText(textOutputCallback.getMessage());
- }
- // TypeScript doesn't like `publicKey` being assigned in conditionals above
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore
- const credential = await this.getAuthenticationCredential(publicKey);
- outcome = this.getAuthenticationOutcome(credential);
- } catch (error) {
- if (!(error instanceof Error)) throw error;
- // NotSupportedError is a special case
- if (error.name === WebAuthnOutcomeType.NotSupportedError) {
- hiddenCallback.setInputValue(WebAuthnOutcome.Unsupported);
- throw error;
- }
- hiddenCallback.setInputValue(`${WebAuthnOutcome.Error}::${error.name}:${error.message}`);
- throw error;
- }
-
- hiddenCallback.setInputValue(outcome);
- return step;
- } else {
- const e = new Error('Incorrect callbacks for WebAuthn authentication');
- e.name = WebAuthnOutcomeType.DataError;
- hiddenCallback?.setInputValue(`${WebAuthnOutcome.Error}::${e.name}:${e.message}`);
- throw e;
- }
- }
- /**
- * Populates the step with the necessary registration outcome.
- *
- * @param step The step that contains WebAuthn registration data
- * @return The populated step
- */
- // Can make this generic const in Typescript 5.0 > and the name itself will
- // be inferred from the type so `typeof deviceName` will not just return string
- // but the actual name of the deviceName passed in as a generic.
- public static async register(
- step: FRStep,
- deviceName?: T,
- ): Promise {
- const { hiddenCallback, metadataCallback, textOutputCallback } = this.getCallbacks(step);
- if (hiddenCallback && (metadataCallback || textOutputCallback)) {
- let outcome: OutcomeWithName;
-
- try {
- let publicKey: PublicKeyCredentialRequestOptions;
- if (metadataCallback) {
- const meta = metadataCallback.getOutputValue('data') as WebAuthnRegistrationMetadata;
- publicKey = this.createRegistrationPublicKey(meta);
- const credential = await this.getRegistrationCredential(
- publicKey as PublicKeyCredentialCreationOptions,
- );
- outcome = this.getRegistrationOutcome(credential);
- } else if (textOutputCallback) {
- publicKey = parseWebAuthnRegisterText(textOutputCallback.getMessage());
- const credential = await this.getRegistrationCredential(
- publicKey as PublicKeyCredentialCreationOptions,
- );
- outcome = this.getRegistrationOutcome(credential);
- } else {
- throw new Error('No Credential found from Public Key');
- }
- } catch (error) {
- if (!(error instanceof Error)) throw error;
- // NotSupportedError is a special case
- if (error.name === WebAuthnOutcomeType.NotSupportedError) {
- hiddenCallback.setInputValue(WebAuthnOutcome.Unsupported);
- throw error;
- }
- hiddenCallback.setInputValue(`${WebAuthnOutcome.Error}::${error.name}:${error.message}`);
- throw error;
- }
- hiddenCallback.setInputValue(
- deviceName && deviceName.length > 0 ? `${outcome}::${deviceName}` : outcome,
- );
- return step;
- } else {
- const e = new Error('Incorrect callbacks for WebAuthn registration');
- e.name = WebAuthnOutcomeType.DataError;
- hiddenCallback?.setInputValue(`${WebAuthnOutcome.Error}::${e.name}:${e.message}`);
- throw e;
- }
- }
-
- /**
- * Returns an object containing the two WebAuthn callbacks.
- *
- * @param step The step that contains WebAuthn callbacks
- * @return The WebAuthn callbacks
- */
- public static getCallbacks(step: FRStep): WebAuthnCallbacks {
- const hiddenCallback = this.getOutcomeCallback(step);
- const metadataCallback = this.getMetadataCallback(step);
- const textOutputCallback = this.getTextOutputCallback(step);
-
- const returnObj: WebAuthnCallbacks = {
- hiddenCallback,
- };
- if (metadataCallback) {
- returnObj.metadataCallback = metadataCallback;
- } else if (textOutputCallback) {
- returnObj.textOutputCallback = textOutputCallback;
- }
- return returnObj;
- }
-
- /**
- * Returns the WebAuthn metadata callback containing data to pass to the browser
- * Web Authentication API.
- *
- * @param step The step that contains WebAuthn callbacks
- * @return The metadata callback
- */
- public static getMetadataCallback(step: FRStep): MetadataCallback | undefined {
- return step.getCallbacksOfType(CallbackType.MetadataCallback).find((x) => {
- const cb = x.getOutputByName('data', undefined);
- // eslint-disable-next-line no-prototype-builtins
- return cb && cb.hasOwnProperty('relyingPartyId');
- });
- }
-
- /**
- * Returns the WebAuthn hidden value callback where the outcome should be populated.
- *
- * @param step The step that contains WebAuthn callbacks
- * @return The hidden value callback
- */
- public static getOutcomeCallback(step: FRStep): HiddenValueCallback | undefined {
- return step
- .getCallbacksOfType(CallbackType.HiddenValueCallback)
- .find((x) => x.getOutputByName('id', '') === 'webAuthnOutcome');
- }
-
- /**
- * Returns the WebAuthn metadata callback containing data to pass to the browser
- * Web Authentication API.
- *
- * @param step The step that contains WebAuthn callbacks
- * @return The metadata callback
- */
- public static getTextOutputCallback(step: FRStep): TextOutputCallback | undefined {
- return step
- .getCallbacksOfType(CallbackType.TextOutputCallback)
- .find((x) => {
- const cb = x.getOutputByName('message', undefined);
- return cb && cb.includes('webAuthnOutcome');
- });
- }
-
- /**
- * Retrieves the credential from the browser Web Authentication API.
- *
- * @param options The public key options associated with the request
- * @return The credential
- */
- public static async getAuthenticationCredential(
- options: PublicKeyCredentialRequestOptions,
- ): Promise {
- // Feature check before we attempt registering a device
- if (!window.PublicKeyCredential) {
- const e = new Error('PublicKeyCredential not supported by this browser');
- e.name = WebAuthnOutcomeType.NotSupportedError;
- throw e;
- }
- const credential = await navigator.credentials.get({ publicKey: options });
- return credential as PublicKeyCredential;
- }
-
- /**
- * Converts an authentication credential into the outcome expected by OpenAM.
- *
- * @param credential The credential to convert
- * @return The outcome string
- */
- public static getAuthenticationOutcome(
- credential: PublicKeyCredential | null,
- ):
- | OutcomeWithName
- | OutcomeWithName {
- if (credential === null) {
- const e = new Error('No credential generated from authentication');
- e.name = WebAuthnOutcomeType.UnknownError;
- throw e;
- }
-
- try {
- const clientDataJSON = arrayBufferToString(credential.response.clientDataJSON);
- const assertionResponse = credential.response as AuthenticatorAssertionResponse;
- const authenticatorData = new Int8Array(
- assertionResponse.authenticatorData,
- ).toString() as AttestationType;
- const signature = new Int8Array(assertionResponse.signature).toString();
-
- // Current native typing for PublicKeyCredential does not include `userHandle`
- // eslint-disable-next-line
- // @ts-ignore
- const userHandle = arrayBufferToString(credential.response.userHandle);
-
- let stringOutput =
- `${clientDataJSON}::${authenticatorData}::${signature}::${credential.id}` as OutcomeWithName<
- string,
- AttestationType,
- PublicKeyCredential
- >;
- // Check if Username is stored on device
- if (userHandle) {
- stringOutput = `${stringOutput}::${userHandle}`;
- return stringOutput as OutcomeWithName<
- string,
- AttestationType,
- PublicKeyCredential,
- string
- >;
- }
-
- return stringOutput;
- } catch (error) {
- const e = new Error('Transforming credential object to string failed');
- e.name = WebAuthnOutcomeType.EncodingError;
- throw e;
- }
- }
-
- /**
- * Retrieves the credential from the browser Web Authentication API.
- *
- * @param options The public key options associated with the request
- * @return The credential
- */
- public static async getRegistrationCredential(
- options: PublicKeyCredentialCreationOptions,
- ): Promise {
- // Feature check before we attempt registering a device
- if (!window.PublicKeyCredential) {
- const e = new Error('PublicKeyCredential not supported by this browser');
- e.name = WebAuthnOutcomeType.NotSupportedError;
- throw e;
- }
- const credential = await navigator.credentials.create({
- publicKey: options,
- });
- return credential as PublicKeyCredential;
- }
-
- /**
- * Converts a registration credential into the outcome expected by OpenAM.
- *
- * @param credential The credential to convert
- * @return The outcome string
- */
- public static getRegistrationOutcome(
- credential: PublicKeyCredential | null,
- ): OutcomeWithName {
- if (credential === null) {
- const e = new Error('No credential generated from registration');
- e.name = WebAuthnOutcomeType.UnknownError;
- throw e;
- }
-
- try {
- const clientDataJSON = arrayBufferToString(credential.response.clientDataJSON);
- const attestationResponse = credential.response as AuthenticatorAttestationResponse;
- const attestationObject = new Int8Array(
- attestationResponse.attestationObject,
- ).toString() as AttestationType.Direct;
- return `${clientDataJSON}::${attestationObject}::${credential.id}`;
- } catch (error) {
- const e = new Error('Transforming credential object to string failed');
- e.name = WebAuthnOutcomeType.EncodingError;
- throw e;
- }
- }
-
- /**
- * Converts authentication tree metadata into options required by the browser
- * Web Authentication API.
- *
- * @param metadata The metadata provided in the authentication tree MetadataCallback
- * @return The Web Authentication API request options
- */
- public static createAuthenticationPublicKey(
- metadata: WebAuthnAuthenticationMetadata,
- ): PublicKeyCredentialRequestOptions {
- const {
- acceptableCredentials,
- allowCredentials,
- challenge,
- relyingPartyId,
- timeout,
- userVerification,
- } = metadata;
- const rpId = parseRelyingPartyId(relyingPartyId);
- const allowCredentialsValue = parseCredentials(allowCredentials || acceptableCredentials || '');
-
- return {
- challenge: Uint8Array.from(atob(challenge), (c) => c.charCodeAt(0)).buffer,
- timeout,
- // only add key-value pair if proper value is provided
- ...(allowCredentialsValue && { allowCredentials: allowCredentialsValue }),
- ...(userVerification && { userVerification }),
- ...(rpId && { rpId }),
- };
- }
-
- /**
- * Converts authentication tree metadata into options required by the browser
- * Web Authentication API.
- *
- * @param metadata The metadata provided in the authentication tree MetadataCallback
- * @return The Web Authentication API request options
- */
- public static createRegistrationPublicKey(
- metadata: WebAuthnRegistrationMetadata,
- ): PublicKeyCredentialCreationOptions {
- const { pubKeyCredParams: pubKeyCredParamsString } = metadata;
- const pubKeyCredParams = parsePubKeyArray(pubKeyCredParamsString);
- if (!pubKeyCredParams) {
- const e = new Error('Missing pubKeyCredParams property from registration options');
- e.name = WebAuthnOutcomeType.DataError;
- throw e;
- }
- const excludeCredentials = parseCredentials(metadata.excludeCredentials);
-
- const {
- attestationPreference,
- authenticatorSelection,
- challenge,
- relyingPartyId,
- relyingPartyName,
- timeout,
- userId,
- userName,
- displayName,
- } = metadata;
- const rpId = parseRelyingPartyId(relyingPartyId);
- const rp: RelyingParty = {
- name: relyingPartyName,
- ...(rpId && { id: rpId }),
- };
-
- return {
- attestation: attestationPreference,
- authenticatorSelection: JSON.parse(authenticatorSelection),
- challenge: Uint8Array.from(atob(challenge), (c) => c.charCodeAt(0)).buffer,
- ...(excludeCredentials.length && { excludeCredentials }),
- pubKeyCredParams,
- rp,
- timeout,
- user: {
- displayName: displayName || userName,
- id: Int8Array.from(userId.split('').map((c: string) => c.charCodeAt(0))),
- name: userName,
- },
- };
- }
-}
-
-export default FRWebAuthn;
-export type {
- RelyingParty,
- WebAuthnAuthenticationMetadata,
- WebAuthnCallbacks,
- WebAuthnRegistrationMetadata,
-};
-export { WebAuthnOutcome, WebAuthnStepType };
diff --git a/packages/javascript-sdk/src/fr-webauthn/interfaces.ts b/packages/javascript-sdk/src/fr-webauthn/interfaces.ts
deleted file mode 100644
index de57c7a6d..000000000
--- a/packages/javascript-sdk/src/fr-webauthn/interfaces.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * interfaces.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type HiddenValueCallback from '../fr-auth/callbacks/hidden-value-callback';
-import type MetadataCallback from '../fr-auth/callbacks/metadata-callback';
-import type TextOutputCallback from '../fr-auth/callbacks/text-output-callback';
-
-enum AttestationType {
- Direct = 'direct',
- Indirect = 'indirect',
- None = 'none',
-}
-
-interface DeviceStepState extends StepState {
- value1: number;
- value2: number;
-}
-
-enum UserVerificationType {
- Discouraged = 'discouraged',
- Preferred = 'preferred',
- Required = 'required',
-}
-
-interface RelyingParty {
- name: string;
- id?: string;
-}
-
-interface ResponseCredential {
- response: { clientDataJSON: ArrayBuffer };
-}
-
-interface Step {
- data?: TData;
- state: TState;
- type: StepType;
-}
-
-interface StepState {
- authId: string;
-}
-
-enum StepType {
- DeviceAuthentication = 'DeviceAuthentication',
- DeviceRegistration = 'DeviceRegistration',
- DeviceRegistrationChoice = 'DeviceRegistrationChoice',
- LoginFailure = 'LoginFailure',
- LoginSuccess = 'LoginSuccess',
- OneTimePassword = 'OneTimePassword',
- SecondFactorChoice = 'SecondFactorChoice',
- Username = 'Username',
- UsernamePassword = 'UsernamePassword',
- UserPassword = 'UserPassword',
-}
-
-interface WebAuthnRegistrationMetadata {
- attestationPreference: 'none' | 'indirect' | 'direct';
- authenticatorSelection: string;
- challenge: string;
- excludeCredentials: string;
- pubKeyCredParams: string;
- relyingPartyId: string;
- relyingPartyName: string;
- timeout: number;
- userId: string;
- userName: string;
- displayName?: string;
-}
-
-interface WebAuthnAuthenticationMetadata {
- acceptableCredentials?: string;
- allowCredentials?: string;
- challenge: string;
- relyingPartyId: string;
- timeout: number;
- userVerification: UserVerificationType;
-}
-
-interface WebAuthnCallbacks {
- hiddenCallback?: HiddenValueCallback;
- metadataCallback?: MetadataCallback;
- textOutputCallback?: TextOutputCallback;
-}
-
-type WebAuthnTextOutputRegistration = string;
-
-interface ParsedCredential {
- id: ArrayBuffer | SharedArrayBuffer;
- type: 'public-key';
-}
-
-export type {
- DeviceStepState,
- ParsedCredential,
- RelyingParty,
- ResponseCredential,
- Step,
- WebAuthnCallbacks,
- WebAuthnAuthenticationMetadata,
- WebAuthnRegistrationMetadata,
- WebAuthnTextOutputRegistration,
-};
-export { AttestationType, StepType, UserVerificationType };
diff --git a/packages/javascript-sdk/src/fr-webauthn/script-parser.test.ts b/packages/javascript-sdk/src/fr-webauthn/script-parser.test.ts
deleted file mode 100644
index 617e26f27..000000000
--- a/packages/javascript-sdk/src/fr-webauthn/script-parser.test.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * script-parser.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { parseWebAuthnAuthenticateText, parseWebAuthnRegisterText } from './script-parser';
-import {
- authenticateInputWithRpidAndAllowCredentials,
- authenticateInputWithRpidAndAllowCredentialsAndAllowRecoveryCode,
- authenticateInputWithRpidAllowCredentialsAndQuotes,
- authenticateInputWithoutRpidAndAllowCredentials,
- authenticateInputWithAcceptableCredentialsWithoutRpid,
- registerInputWithRpid,
- registerInputWithRpidAndQuotes,
- registerOutputWithRpid,
- registerInputWithoutRpid,
- registerOutputWithoutRpid,
- registerInputWithExcludeCreds,
-} from './script-text.mock.data';
-
-describe('Parsing of the WebAuthn script type text', () => {
- it('should parse the WebAuthn authenticate block of text with rpid and allow credentials', () => {
- const obj = parseWebAuthnAuthenticateText(authenticateInputWithRpidAndAllowCredentials);
- expect(obj.allowCredentials[0].type).toBe('public-key');
- expect(obj.allowCredentials[0].id.byteLength > 0).toBe(true);
- expect(obj.challenge.byteLength > 0).toBe(true);
- expect(obj.timeout).toBe(60000);
- expect(obj.rpId).toBe('example.com');
- });
- it('should parse the WebAuthn authenticate block of text with rpid and allow credentials & Allow recovery code', () => {
- const obj = parseWebAuthnAuthenticateText(
- authenticateInputWithRpidAndAllowCredentialsAndAllowRecoveryCode,
- );
- expect(obj.allowCredentials[0].type).toBe('public-key');
- expect(obj.allowCredentials[0].id.byteLength > 0).toBe(true);
- expect(obj.challenge.byteLength > 0).toBe(true);
- expect(obj.timeout).toBe(60000);
- expect(obj.userVerification).toBe('preferred');
- });
- it('should parse the WebAuthn authenticate block of text with quoted keys', () => {
- const obj = parseWebAuthnAuthenticateText(authenticateInputWithRpidAllowCredentialsAndQuotes);
- expect(obj.allowCredentials[0].type).toBe('public-key');
- expect(obj.allowCredentials[0].id.byteLength > 0).toBe(true);
- expect(obj.challenge.byteLength > 0).toBe(true);
- expect(obj.timeout).toBe(60000);
- expect(obj.rpId).toBe('example.com');
- });
-
- it('should parse the WebAuthn authenticate block from 6.5.3 text', () => {
- const obj = parseWebAuthnAuthenticateText(
- authenticateInputWithAcceptableCredentialsWithoutRpid,
- );
- expect(obj.allowCredentials[0].type).toBe('public-key');
- expect(obj.allowCredentials[0].id.byteLength > 0).toBe(true);
- expect(obj.challenge.byteLength > 0).toBe(true);
- expect(obj.timeout).toBe(60000);
- });
-
- it('should parse the WebAuthn authenticate block of text', () => {
- const obj = parseWebAuthnAuthenticateText(authenticateInputWithoutRpidAndAllowCredentials);
- expect(obj.allowCredentials).toBe(undefined);
- expect(obj.rpId).toBe(undefined);
- });
-
- it('should parse the WebAuthn register block of text with rpid', () => {
- const obj = parseWebAuthnRegisterText(registerInputWithRpid);
- expect(obj.attestation).toBe(registerOutputWithRpid.attestation);
- expect(obj.authenticatorSelection).toStrictEqual(registerOutputWithRpid.authenticatorSelection);
- expect(obj.challenge.byteLength > 0).toBe(true);
- expect(obj.pubKeyCredParams).toContainEqual(registerOutputWithRpid.pubKeyCredParams[0]);
- expect(obj.pubKeyCredParams).toContainEqual(registerOutputWithRpid.pubKeyCredParams[1]);
- expect(obj.rp).toStrictEqual(registerOutputWithRpid.rp);
- expect(obj.timeout).toBe(registerOutputWithRpid.timeout);
- expect(obj.user.displayName).toStrictEqual(registerOutputWithRpid.user.displayName);
- expect(obj.user.name).toBe(registerOutputWithRpid.user.name);
- expect(obj.user.id.byteLength > 0).toBe(true);
- });
-
- it('should parse the WebAuthn register block of text with rpid and quoted keys', () => {
- const obj = parseWebAuthnRegisterText(registerInputWithRpidAndQuotes);
- expect(obj.attestation).toBe(registerOutputWithRpid.attestation);
- expect(obj.authenticatorSelection).toStrictEqual(registerOutputWithRpid.authenticatorSelection);
- expect(obj.challenge.byteLength > 0).toBe(true);
- expect(obj.pubKeyCredParams).toContainEqual(registerOutputWithRpid.pubKeyCredParams[0]);
- expect(obj.pubKeyCredParams).toContainEqual(registerOutputWithRpid.pubKeyCredParams[1]);
- expect(obj.rp).toStrictEqual(registerOutputWithRpid.rp);
- expect(obj.timeout).toBe(registerOutputWithRpid.timeout);
- expect(obj.user.displayName).toStrictEqual(registerOutputWithRpid.user.displayName);
- expect(obj.user.name).toBe(registerOutputWithRpid.user.name);
- expect(obj.user.id.byteLength > 0).toBe(true);
- });
-
- it('should parse the WebAuthn register block of text withOUT rpid', () => {
- const obj = parseWebAuthnRegisterText(registerInputWithoutRpid);
- expect(obj.rp).toStrictEqual(registerOutputWithoutRpid.rp);
- });
-
- it('should parse the WebAuthn register block of text with exclude creds', () => {
- const obj = parseWebAuthnRegisterText(registerInputWithExcludeCreds);
- expect(obj.excludeCredentials.length).toBe(2);
- expect(obj.excludeCredentials[0].type).toBe('public-key');
- });
-});
diff --git a/packages/javascript-sdk/src/fr-webauthn/script-parser.ts b/packages/javascript-sdk/src/fr-webauthn/script-parser.ts
deleted file mode 100644
index 0c07410f8..000000000
--- a/packages/javascript-sdk/src/fr-webauthn/script-parser.ts
+++ /dev/null
@@ -1,192 +0,0 @@
-/* eslint-disable no-useless-escape */
-/*
- * @forgerock/javascript-sdk
- *
- * script-parser.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { WebAuthnOutcomeType } from './enums';
-import { ensureArray, getIndexOne, parsePubKeyArray, parseCredentials } from './helpers';
-import type { AttestationType, UserVerificationType } from './interfaces';
-
-function parseWebAuthnRegisterText(text: string): PublicKeyCredentialCreationOptions {
- const txtEncoder = new TextEncoder();
-
- // TODO: Incrementally move to `*` instead of `{0,}`
- // e.g. `attestation: "none"`
- const attestation = getIndexOne(text.match(/attestation"{0,}:\s{0,}"(\w+)"/)) as AttestationType;
- // e.g. `timeout: 60000`
- const timeout = Number(getIndexOne(text.match(/timeout"{0,}:\s{0,}(\d+)/)));
- // e.g. from 7.0: `"userVerification":"preferred"`
- // e.g. from 6.5: `userVerification: "preferred"`
- const userVerification = getIndexOne(
- text.match(/userVerification"{0,}:\s{0,}"(\w+)"/),
- ) as UserVerificationType;
- // e.g. `"requireResidentKey":true`
- const requireResidentKey = getIndexOne(
- text.match(/requireResidentKey"{0,}:\s{0,}(\w+)/),
- ) as string;
- // e.g. `"authenticatorAttachment":"cross-platform"`
- const authenticatorAttachment = getIndexOne(
- text.match(/authenticatorAttachment"{0,}:\s{0,}"([\w-]+)/),
- ) as AuthenticatorAttachment;
-
- // e.g. `rp: {\n id: \"https://user.example.com:3002\",\n name: \"ForgeRock\"\n }`
- const rp = getIndexOne(text.match(/rp"{0,}:\s{0,}{([^}]+)}/)).trim();
- // e.g. `id: \"example.com\"
- const rpId = getIndexOne(rp.match(/id"{0,}:\s{0,}"([^"]*)"/));
- // e.g. `name: \"ForgeRock\"`
- const rpName = getIndexOne(rp.match(/name"{0,}:\s{0,}"([^"]*)"/));
-
- // e.g. `user: {\n id: Uint8Array.from(\"NTdhN...RiNjI5\",
- // function (c) { return c.charCodeAt(0) }),\n
- // name: \"57a5b4e4-...-a4f2e5d4b629\",\n
- // displayName: \"57a5b4e4-...-a4f2e5d4b629\"\n }`
- const user = getIndexOne(text.match(/user"{0,}:\s{0,}{([^]{0,})},/)).trim();
- // e.g `id: Uint8Array.from(\"NTdhN...RiNjI5\",`
- const userId = getIndexOne(user.match(/id"{0,}:\s{0,}Uint8Array.from\("([^"]+)"/));
- // e.g. `name: \"57a5b4e4-...-a4f2e5d4b629\",`
- const userName = getIndexOne(user.match(/name"{0,}:\s{0,}"([\d\w._-]+)"/));
- // e.g. `displayName: \"57a5b4e4-...-a4f2e5d4b629\"`
- const userDisplayName = getIndexOne(user.match(/displayName"{0,}:\s{0,}"([\d\w\s.@_-]+)"/));
-
- // e.g. `pubKeyCredParams: [
- // { \"type\": \"public-key\", \"alg\": -257 }, { \"type\": \"public-key\", \"alg\": -7 }
- // ]`
- const pubKeyCredParamsString = getIndexOne(
- // Capture the `pubKeyCredParams` without also matching `excludeCredentials` as well.
- // `excludeCredentials` values are very similar to this property, so we need to make sure
- // our last value doesn't end with "buffer", so we are only capturing objects that
- // end in a digit and possibly a space.
- text.match(/pubKeyCredParams"*:\s*\[([^]+\d\s*})\s*]/),
- ).trim();
- // e.g. `{ \"type\": \"public-key\", \"alg\": -257 }, { \"type\": \"public-key\", \"alg\": -7 }`
- const pubKeyCredParams = parsePubKeyArray(pubKeyCredParamsString);
- if (!pubKeyCredParams) {
- const e = new Error('Missing pubKeyCredParams property from registration options');
- e.name = WebAuthnOutcomeType.DataError;
- throw e;
- }
-
- // e.g. `excludeCredentials: [{
- // \"type\": \"public-key\", \"id\": new Int8Array([-18, 69, -99, 82, 38, -66]).buffer },
- // { \"type\": \"public-key\", \"id\": new Int8Array([64, 17, -15, 56, -32, 91]).buffer }],\n`
- const excludeCredentialsString = getIndexOne(
- text.match(/excludeCredentials"{0,}:\s{0,}\[([^]+)\s{0,}]/),
- ).trim();
- // e.g. `{ \"type\": \"public-key\", \"id\": new Int8Array([-18, 69, -99, 82, 38, -66]).buffer },
- // { \"type\": \"public-key\", \"id\": new Int8Array([64, 17, -15, 56, -32, 91]).buffer }`
- const excludeCredentials = parseCredentials(excludeCredentialsString);
-
- // e.g. `challenge: new Int8Array([87, -95, 18, ... -3, 49, 12, 81]).buffer,`
- const challengeArr: string[] = ensureArray(
- text.match(/challenge"{0,}:\s{0,}new\s{0,}(Uint|Int)8Array\(([^\)]+)/),
- );
- // e.g. `[87, -95, 18, ... -3, 49, 12, 81]`
- const challengeJSON = JSON.parse(challengeArr[2]);
- // e.g. [87, -95, 18, ... -3, 49, 12, 81]
- const challenge = new Int8Array(challengeJSON).buffer;
-
- return {
- attestation,
- authenticatorSelection: {
- userVerification,
- // Only include authenticatorAttachment prop if the value is truthy
- ...(authenticatorAttachment && { authenticatorAttachment }),
- // Only include requireResidentKey prop if the value is of string "true"
- ...(requireResidentKey === 'true' && {
- requireResidentKey: !!requireResidentKey,
- }),
- },
- challenge,
- ...(excludeCredentials.length && { excludeCredentials }),
- pubKeyCredParams,
- rp: {
- name: rpName,
- // only add key-value pair if truthy value is provided
- ...(rpId && { id: rpId }),
- },
- timeout,
- user: {
- displayName: userDisplayName,
- id: txtEncoder.encode(userId),
- name: userName,
- },
- };
-}
-
-function parseWebAuthnAuthenticateText(text: string): PublicKeyCredentialRequestOptions {
- let allowCredentials;
- let allowCredentialsText;
-
- if (text.includes('acceptableCredentials')) {
- // e.g. `var acceptableCredentials = [
- // { "type": "public-key", "id": new Int8Array([1, 97, 2, 123, ... -17]).buffer }
- // ];`
- allowCredentialsText = getIndexOne(
- text.match(/acceptableCredentials"*\s*=\s*\[([^]+)\s*]/),
- ).trim();
- } else {
- // e.g. `allowCredentials: [
- // { \"type\": \"public-key\",
- // \"id\": new Int8Array([-107, 93, 68, -67, ... -19, 7, 4]).buffer }
- // ]`
- allowCredentialsText = getIndexOne(
- text.match(/allowCredentials"{0,}:\s{0,}\[([^]+)\s{0,}]/),
- ).trim();
- }
- // e.g. `"userVerification":"preferred"`
- const userVerification = getIndexOne(
- text.match(/userVerification"{0,}:\s{0,}"(\w+)"/),
- ) as UserVerificationType;
-
- if (allowCredentialsText) {
- // Splitting objects in array in case the user has multiple keys
- const allowCredentialArr = allowCredentialsText.split('},') || [allowCredentialsText];
- // Iterating over array of substrings
- allowCredentials = allowCredentialArr.map((str) => {
- // e.g. `{ \"type\": \"public-key\",
- const type = getIndexOne(str.match(/type"{0,}:\s{0,}"([\w-]+)"/)) as 'public-key';
- // e.g. \"id\": new Int8Array([-107, 93, 68, -67, ... -19, 7, 4]).buffer
- const idArr = ensureArray(str.match(/id"{0,}:\s{0,}new\s{0,}(Uint|Int)8Array\(([^\)]+)/));
- // e.g. `[-107, 93, 68, -67, ... -19, 7, 4]`
- const idJSON = JSON.parse(idArr[2]);
- // e.g. [-107, 93, 68, -67, ... -19, 7, 4]
- const id = new Int8Array(idJSON).buffer;
-
- return {
- type,
- id,
- };
- });
- }
-
- // e.g. `timeout: 60000`
- const timeout = Number(getIndexOne(text.match(/timeout"{0,}:\s{0,}(\d+)/)));
-
- // e.g. `challenge: new Int8Array([87, -95, 18, ... -3, 49, 12, 81]).buffer,`
- const challengeArr: string[] = ensureArray(
- text.match(/challenge"{0,}:\s{0,}new\s{0,}(Uint|Int)8Array\(([^\)]+)/),
- );
- // e.g. `[87, -95, 18, ... -3, 49, 12, 81]`
- const challengeJSON = JSON.parse(challengeArr[2]);
- // e.g. [87, -95, 18, ... -3, 49, 12, 81]
- const challenge = new Int8Array(challengeJSON).buffer;
- // e.g. `rpId: \"example.com\"`
- const rpId = getIndexOne(text.match(/rpId"{0,}:\s{0,}\\{0,}"([^"\\]*)/));
-
- return {
- challenge,
- timeout,
- // only add key-value pairs if the truthy values are provided
- ...(allowCredentials && { allowCredentials }),
- ...(userVerification && { userVerification }),
- ...(rpId && { rpId }),
- };
-}
-
-export { parseWebAuthnAuthenticateText, parseWebAuthnRegisterText };
diff --git a/packages/javascript-sdk/src/fr-webauthn/script-text.mock.data.ts b/packages/javascript-sdk/src/fr-webauthn/script-text.mock.data.ts
deleted file mode 100644
index 3cc85e5fd..000000000
--- a/packages/javascript-sdk/src/fr-webauthn/script-text.mock.data.ts
+++ /dev/null
@@ -1,464 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * script-text.mock.data.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/* eslint-disable max-len */
-export const authenticateInputWithRpidAndAllowCredentials = `/*
-* Copyright 2018-2020 ForgeRock AS. All Rights Reserved
-*
-* Use of this code requires a commercial software license with ForgeRock AS.
-* or with one of its affiliates. All use shall be exclusively subject
-* to such license between the licensee and ForgeRock AS.
-*/
-
-if (!window.PublicKeyCredential) {
- document.getElementById('webAuthnOutcome').value = "unsupported";
- document.getElementById("loginButton_0").click();
-}
-
-var options = {
- rpId: "example.com",
- challenge: new Int8Array([14, 126, -110, -74, 64, -66, 20, -56, -40, -28, 116, -61, -128, -20, 72, 24, 42, 79, -105, 94, -84, -12, -17, -97, 105, -31, -30, 92, 55, 67, -83, 65]).buffer,
- timeout: 60000,
- allowCredentials: [{ type: "public-key", id: new Int8Array([-107, 93, 68, -67, -5, 107, 18, 16, -25, -30, 80, 103, -75, -53, -2, -95, 102, 42, 47, 126, -1, 85, 93, 45, -85, 8, -108, 107, 47, -25, 66, 12, -96, 81, 104, -127, 26, -59, -69, -23, 75, 89, 58, 124, -93, 4, 28, -128, 121, 35, 39, 103, -86, -86, 123, -67, -7, -4, 79, -49, 127, -19, 7, 4]).buffer }]
-};
-
-navigator.credentials.get({ "publicKey" : options })
- .then(function (assertion) {
- var clientData = String.fromCharCode.apply(null, new Uint8Array(assertion.response.clientDataJSON));
- var authenticatorData = new Int8Array(assertion.response.authenticatorData).toString();
- var signature = new Int8Array(assertion.response.signature).toString();
- var rawId = assertion.id;
- var userHandle = String.fromCharCode.apply(null, new Uint8Array(assertion.response.userHandle));
- document.getElementById('webAuthnOutcome').value = clientData + "::" + authenticatorData + "::" + signature + "::" + rawId + "::" + userHandle;
- document.getElementById("loginButton_0").click();
- }).catch(function (err) {
- document.getElementById('webAuthnOutcome').value = "ERROR" + "::" + err;
- document.getElementById("loginButton_0").click();
- });`;
-
-export const authenticateInputWithRpidAllowCredentialsAndQuotes = `/*
-* Copyright 2018-2020 ForgeRock AS. All Rights Reserved
-*
-* Use of this code requires a commercial software license with ForgeRock AS.
-* or with one of its affiliates. All use shall be exclusively subject
-* to such license between the licensee and ForgeRock AS.
-*/
-
-if (!window.PublicKeyCredential) {
- document.getElementById('webAuthnOutcome').value = "unsupported";
- document.getElementById("loginButton_0").click();
-}
-
-var options = {
- "rpId": "example.com",
- "challenge": new Int8Array([14, 126, -110, -74, 64, -66, 20, -56, -40, -28, 116, -61, -128, -20, 72, 24, 42, 79, -105, 94, -84, -12, -17, -97, 105, -31, -30, 92, 55, 67, -83, 65]).buffer,
- "timeout": 60000,
- "allowCredentials": [{ "type": "public-key", "id": new Int8Array([-107, 93, 68, -67, -5, 107, 18, 16, -25, -30, 80, 103, -75, -53, -2, -95, 102, 42, 47, 126, -1, 85, 93, 45, -85, 8, -108, 107, 47, -25, 66, 12, -96, 81, 104, -127, 26, -59, -69, -23, 75, 89, 58, 124, -93, 4, 28, -128, 121, 35, 39, 103, -86, -86, 123, -67, -7, -4, 79, -49, 127, -19, 7, 4]).buffer }]
-};
-
-navigator.credentials.get({ "publicKey" : options })
- .then(function (assertion) {
- var clientData = String.fromCharCode.apply(null, new Uint8Array(assertion.response.clientDataJSON));
- var authenticatorData = new Int8Array(assertion.response.authenticatorData).toString();
- var signature = new Int8Array(assertion.response.signature).toString();
- var rawId = assertion.id;
- var userHandle = String.fromCharCode.apply(null, new Uint8Array(assertion.response.userHandle));
- document.getElementById('webAuthnOutcome').value = clientData + "::" + authenticatorData + "::" + signature + "::" + rawId + "::" + userHandle;
- document.getElementById("loginButton_0").click();
- }).catch(function (err) {
- document.getElementById('webAuthnOutcome').value = "ERROR" + "::" + err;
- document.getElementById("loginButton_0").click();
- });`;
-
-export const authenticateInputWithoutRpidAndAllowCredentials = `/*
-* Copyright 2018-2020 ForgeRock AS. All Rights Reserved
-*
-* Use of this code requires a commercial software license with ForgeRock AS.
-* or with one of its affiliates. All use shall be exclusively subject
-* to such license between the licensee and ForgeRock AS.
-*/
-
-if (!window.PublicKeyCredential) {
- document.getElementById('webAuthnOutcome').value = "unsupported";
- document.getElementById("loginButton_0").click();
-}
-
-var options = {
- challenge: new Int8Array([14, 126, -110, -74, 64, -66, 20, -56, -40, -28, 116, -61, -128, -20, 72, 24, 42, 79, -105, 94, -84, -12, -17, -97, 105, -31, -30, 92, 55, 67, -83, 65]).buffer,
- timeout: 60000,
-};
-
-navigator.credentials.get({ "publicKey" : options })
- .then(function (assertion) {
- var clientData = String.fromCharCode.apply(null, new Uint8Array(assertion.response.clientDataJSON));
- var authenticatorData = new Int8Array(assertion.response.authenticatorData).toString();
- var signature = new Int8Array(assertion.response.signature).toString();
- var rawId = assertion.id;
- var userHandle = String.fromCharCode.apply(null, new Uint8Array(assertion.response.userHandle));
- document.getElementById('webAuthnOutcome').value = clientData + "::" + authenticatorData + "::" + signature + "::" + rawId + "::" + userHandle;
- document.getElementById("loginButton_0").click();
- }).catch(function (err) {
- document.getElementById('webAuthnOutcome').value = "ERROR" + "::" + err;
- document.getElementById("loginButton_0").click();
- });`;
-
-// AM 6.5.3 variant of JS text string
-export const authenticateInputWithAcceptableCredentialsWithoutRpid = `/*
-* Copyright 2018-2020 ForgeRock AS. All Rights Reserved
-*
-* Use of this code requires a commercial software license with ForgeRock AS.
-* or with one of its affiliates. All use shall be exclusively subject
-* to such license between the licensee and ForgeRock AS.
-*/
-
-if (!window.PublicKeyCredential) {
- document.getElementById('webAuthnOutcome').value = "unsupported";
- document.getElementById("loginButton_0").click();
-}
-
-var acceptableCredentials = [
- { "type": "public-key", "id": new Int8Array([1, 97, 2, 123, -105, -19, -106, 10, -86, 82, -23, 5, 52, 63, 103, 110, -71, 53, 107, 104, 76, -42, -49, 96, 67, -114, -97, 19, -59, 89, -102, -115, -110, -101, -6, -98, 39, -75, 2, 74, 23, -105, 67, 6, -112, 21, -3, 36, -114, 52, 35, 75, 74, 82, -8, 115, -128, -34, -105, 110, 124, 41, -79, -53, -90, 81, -11, -7, 91, -45, -67, -82, 106, 74, 30, 112, 100, -47, 54, -12, 95, 81, 97, 36, 123, -15, -91, 87, -82, 87, -45, -103, -80, 109, -111, 82, 109, 58, 50, 19, -21, -102, 54, -108, -68, 12, -101, -53, -65, 11, -94, -36, 112, -101, -95, -90, -118, 68, 13, 8, -49, -77, -28, -82, -97, 126, -71, 33, -58, 19, 58, -118, 36, -28, 22, -55, 64, -72, -80, -9, -48, -50, 58, -52, 64, -64, -27, -5, -12, 110, -95, -17]).buffer }
-];
-
-var options = {
-
- challenge: new Int8Array([-42, -21, -101, -22, -35, 94, 14, 33, -75, -12, -113, 86, 109, -51, 62, 89, 29, 119, 48, -92, 33, -64, 102, -18, 18, -122, 73, 13, -17, -50, -22, -74]).buffer,
- timeout: 60000,
- userVerification: "preferred",
- allowCredentials: acceptableCredentials
-};
-
-navigator.credentials.get({ "publicKey" : options })
- .then(function (assertion) {
- var clientData = String.fromCharCode.apply(null, new Uint8Array(assertion.response.clientDataJSON));
- var authenticatorData = new Int8Array(assertion.response.authenticatorData).toString();
- var signature = new Int8Array(assertion.response.signature).toString();
- var rawId = assertion.id;
- document.getElementById('webAuthnOutcome').value = clientData + "::" + authenticatorData + "::" + signature + "::" + rawId;
- document.getElementById("loginButton_0").click();
- }).catch(function (err) {
- document.getElementById('webAuthnOutcome').value = "ERROR" + "::" + err;
- document.getElementById("loginButton_0").click();
- });`;
-
-export const registerInputWithRpid = `/*
- * Copyright 2018-2020 ForgeRock AS. All Rights Reserved
- *
- * Use of this code requires a commercial software license with ForgeRock AS.
- * or with one of its affiliates. All use shall be exclusively subject
- * to such license between the licensee and ForgeRock AS.
- */
-
-if (!window.PublicKeyCredential) {
- document.getElementById('webAuthnOutcome').value = "unsupported";
- document.getElementById("loginButton_0").click();
-}
-
-var publicKey = {
- challenge: new Int8Array([102, -15, -36, -101, -95, 10, -20, 39, 29, 70, 122, 25, 53, 83, 72, -38, 83, -92, 31, -30, 26, -94, 92, -94, -83, 7, 82, -66, -125, -95, -4, -75]).buffer,
- // Relying Party:
- rp: {
- id: "example.com",
- name: "ForgeRock"
- },
- // User:
- user: {
- id: Uint8Array.from("NTdhNWI0ZTQtNjk5OS00YjQ1LWJmODYtYTRmMmU1ZDRiNjI5", function (c) { return c.charCodeAt(0) }),
- name: "57a5b4e4-6999-4b45-bf86-a4f2e5d4b629",
- displayName: "bob_lee-tester@me.co.uk"
- },
- // Below pubKeyCredParams format represents AM 6.5
- pubKeyCredParams: [
- {
- type: "public-key",
- alg: -7
- }
- ,{
- type: "public-key",
- alg: -257
- }
- ],
- attestation: "none",
- timeout: 60000,
- excludeCredentials: [],
- authenticatorSelection: {
- userVerification: "preferred"
- authenticatorAttachment:"cross-platform"
- }
-};
-
-navigator.credentials.create({publicKey: publicKey})
- .then(function (newCredentialInfo) {
- var rawId = newCredentialInfo.id;
- var clientData = String.fromCharCode.apply(null, new Uint8Array(newCredentialInfo.response.clientDataJSON));
- var keyData = new Int8Array(newCredentialInfo.response.attestationObject).toString();
- document.getElementById('webAuthnOutcome').value = clientData + "::" + keyData + "::" + rawId;
- document.getElementById("loginButton_0").click();
- }).catch(function (err) {
- document.getElementById('webAuthnOutcome').value = "ERROR" + "::" + err;
- document.getElementById("loginButton_0").click();
- });`;
-
-export const registerInputWithRpidAndQuotes = `/*
- * Copyright 2018-2020 ForgeRock AS. All Rights Reserved
- *
- * Use of this code requires a commercial software license with ForgeRock AS.
- * or with one of its affiliates. All use shall be exclusively subject
- * to such license between the licensee and ForgeRock AS.
- */
-
- if (!window.PublicKeyCredential) {
- document.getElementById('webAuthnOutcome').value = "unsupported";
- document.getElementById("loginButton_0").click();
- }
-
- var publicKey = {
- "challenge": new Int8Array([102, -15, -36, -101, -95, 10, -20, 39, 29, 70, 122, 25, 53, 83, 72, -38, 83, -92, 31, -30, 26, -94, 92, -94, -83, 7, 82, -66, -125, -95, -4, -75]).buffer,
- // Relying Party:
- "rp": {
- "id": "example.com",
- "name": "ForgeRock"
- },
- // User:
- "user": {
- "id": Uint8Array.from("NTdhNWI0ZTQtNjk5OS00YjQ1LWJmODYtYTRmMmU1ZDRiNjI5", function (c) { return c.charCodeAt(0) }),
- "name": "57a5b4e4-6999-4b45-bf86-a4f2e5d4b629",
- "displayName": "bob_lee-tester@me.co.uk"
- },
- "pubKeyCredParams": [ { "type": "public-key", "alg": -257 }, { "type": "public-key", "alg": -7 } ],
- "attestation": "none",
- "timeout": 60000,
- "excludeCredentials": [],
- "authenticatorSelection": {"userVerification":"preferred","authenticatorAttachment":"cross-platform"}
- };
-
- navigator.credentials.create({publicKey: publicKey})
- .then(function (newCredentialInfo) {
- var rawId = newCredentialInfo.id;
- var clientData = String.fromCharCode.apply(null, new Uint8Array(newCredentialInfo.response.clientDataJSON));
- var keyData = new Int8Array(newCredentialInfo.response.attestationObject).toString();
- document.getElementById('webAuthnOutcome').value = clientData + "::" + keyData + "::" + rawId;
- document.getElementById("loginButton_0").click();
- }).catch(function (err) {
- document.getElementById('webAuthnOutcome').value = "ERROR" + "::" + err;
- document.getElementById("loginButton_0").click();
- });`;
-
-export const registerOutputWithRpid = {
- attestation: 'none',
- authenticatorSelection: {
- userVerification: 'preferred',
- authenticatorAttachment: 'cross-platform',
- },
- challenge: [
- /* don't directly test */
- ],
- pubKeyCredParams: [
- { type: 'public-key', alg: -257 },
- { type: 'public-key', alg: -7 },
- ],
- rp: { id: 'example.com', name: 'ForgeRock' },
- timeout: 60000,
- user: {
- displayName: 'bob_lee-tester@me.co.uk',
- id: [
- /* don't directly test */
- ],
- name: '57a5b4e4-6999-4b45-bf86-a4f2e5d4b629',
- },
-};
-
-export const registerInputWithoutRpid = `/*
- * Copyright 2018-2020 ForgeRock AS. All Rights Reserved
- *
- * Use of this code requires a commercial software license with ForgeRock AS.
- * or with one of its affiliates. All use shall be exclusively subject
- * to such license between the licensee and ForgeRock AS.
- */
-
-if (!window.PublicKeyCredential) {
- document.getElementById('webAuthnOutcome').value = "unsupported";
- document.getElementById("loginButton_0").click();
-}
-
-var publicKey = {
- challenge: new Int8Array([102, -15, -36, -101, -95, 10, -20, 39, 29, 70, 122, 25, 53, 83, 72, -38, 83, -92, 31, -30, 26, -94, 92, -94, -83, 7, 82, -66, -125, -95, -4, -75]).buffer,
- // Relying Party:
- rp: {
- name: "ForgeRock"
- },
- // User:
- user: {
- id: Uint8Array.from("NTdhNWI0ZTQtNjk5OS00YjQ1LWJmODYtYTRmMmU1ZDRiNjI5", function (c) { return c.charCodeAt(0) }),
- name: "57a5b4e4-6999-4b45-bf86-a4f2e5d4b629",
- displayName: "Bob Tester"
- },
- pubKeyCredParams: [ { "type": "public-key", "alg": -257 }, { "type": "public-key", "alg": -7 } ],
- attestation: "none",
- timeout: 60000,
- excludeCredentials: [],
- authenticatorSelection: {"userVerification":"preferred"}
-};
-
-navigator.credentials.create({publicKey: publicKey})
- .then(function (newCredentialInfo) {
- var rawId = newCredentialInfo.id;
- var clientData = String.fromCharCode.apply(null, new Uint8Array(newCredentialInfo.response.clientDataJSON));
- var keyData = new Int8Array(newCredentialInfo.response.attestationObject).toString();
- document.getElementById('webAuthnOutcome').value = clientData + "::" + keyData + "::" + rawId;
- document.getElementById("loginButton_0").click();
- }).catch(function (err) {
- document.getElementById('webAuthnOutcome').value = "ERROR" + "::" + err;
- document.getElementById("loginButton_0").click();
- });`;
-
-export const registerOutputWithoutRpid = {
- attestation: 'none',
- authenticatorSelection: { userVerification: 'preferred' },
- challenge: [
- /* don't directly test */
- ],
- pubKeyCredParams: [
- { type: 'public-key', alg: -257 },
- { type: 'public-key', alg: -7 },
- ],
- rp: { name: 'ForgeRock' },
- timeout: 60000,
- user: {
- displayName: 'Bob Tester',
- id: [
- /* don't directly test */
- ],
- name: '57a5b4e4-6999-4b45-bf86-a4f2e5d4b629',
- },
-};
-
-export const registerInputWithExcludeCreds = `/*
- * Copyright 2018-2020 ForgeRock AS. All Rights Reserved
- *
- * Use of this code requires a commercial software license with ForgeRock AS.
- * or with one of its affiliates. All use shall be exclusively subject
- * to such license between the licensee and ForgeRock AS.
- */
-
-if (!window.PublicKeyCredential) {
- document.getElementById('webAuthnOutcome').value = "unsupported";
- document.getElementById("loginButton_0").click();
-}
-
-var publicKey = {
- challenge: new Int8Array([102, -15, -36, -101, -95, 10, -20, 39, 29, 70, 122, 25, 53, 83, 72, -38, 83, -92, 31, -30, 26, -94, 92, -94, -83, 7, 82, -66, -125, -95, -4, -75]).buffer,
- // Relying Party:
- rp: {
- name: "ForgeRock"
- },
- // User:
- user: {
- id: Uint8Array.from("NTdhNWI0ZTQtNjk5OS00YjQ1LWJmODYtYTRmMmU1ZDRiNjI5", function (c) { return c.charCodeAt(0) }),
- name: "57a5b4e4-6999-4b45-bf86-a4f2e5d4b629",
- displayName: "Bob Tester"
- },
- pubKeyCredParams: [ { "type": "public-key", "alg": -257 }, { "type": "public-key", "alg": -7 } ],
- attestation: "none",
- timeout: 60000,
- excludeCredentials: [{ "type": "public-key", "id": new Int8Array([49, -96, -107, 113, 106, 5, 115, 22, 68, 121, -85, -27, 8, -58, -113, 127, -105, -37, -10, -12, -58, -25, 29, -82, -18, 69, -99, 125, 33, 82, 38, -66, -27, -128, -91, -86, 87, 68, 94, 0, -78, 70, -11, -70, -14, -53, 38, -60, 46, 27, 66, 46, 21, -125, -70, 123, -46, -124, 86, -2, 102, 70, -52, 54]).buffer },{ "type": "public-key", "id": new Int8Array([64, 17, -15, -123, -21, 127, 76, -120, 90, -112, -5, 54, 105, 93, 82, -104, -79, 107, -69, -3, -113, -94, -59, -4, 126, -33, 117, 32, -44, 122, -97, 8, -112, 105, -96, 96, 90, 44, -128, -121, 107, 79, -98, -68, -93, 11, -105, -47, 102, 13, 110, 84, 59, -91, -30, 37, -3, -22, 39, 111, -10, 87, -50, -35]).buffer }],
- authenticatorSelection: {"userVerification":"preferred"}
-};
-
-navigator.credentials.create({publicKey: publicKey})
- .then(function (newCredentialInfo) {
- var rawId = newCredentialInfo.id;
- var clientData = String.fromCharCode.apply(null, new Uint8Array(newCredentialInfo.response.clientDataJSON));
- var keyData = new Int8Array(newCredentialInfo.response.attestationObject).toString();
- document.getElementById('webAuthnOutcome').value = clientData + "::" + keyData + "::" + rawId;
- document.getElementById("loginButton_0").click();
- }).catch(function (err) {
- document.getElementById('webAuthnOutcome').value = "ERROR" + "::" + err;
- document.getElementById("loginButton_0").click();
- });`;
-
-export const registerOutputWithExcludeCreds = {
- attestation: 'none',
- authenticatorSelection: { userVerification: 'preferred' },
- challenge: [
- /* don't directly test */
- ],
- excludeCredentials: [
- {
- type: 'public-key',
- id: 'Do not directly test',
- },
- {
- type: 'public-key',
- id: 'Do not directly test',
- },
- ],
- pubKeyCredParams: [
- { type: 'public-key', alg: -257 },
- { type: 'public-key', alg: -7 },
- ],
- rp: { name: 'ForgeRock' },
- timeout: 60000,
- user: {
- displayName: 'Bob Tester',
- id: [
- /* don't directly test */
- ],
- name: '57a5b4e4-6999-4b45-bf86-a4f2e5d4b629',
- },
-};
-
-export const authenticateInputWithRpidAndAllowCredentialsAndAllowRecoveryCode = `/*
- * Copyright 2018-2022 ForgeRock AS. All Rights Reserved
- *
- * Use of this code requires a commercial software license with ForgeRock AS.
- * or with one of its affiliates. All use shall be exclusively subject
- * to such license between the licensee and ForgeRock AS.
- */
-
-if (!window.PublicKeyCredential) {
- document.getElementById('webAuthnOutcome').value = "unsupported";
- document.getElementById("loginButton_0").click();
-}
-
-var options = {
-
- challenge: new Int8Array([-17, -117, -10, 120, -90, 127, 70, -73, 114, -37, -94, 126, -96, -111, -65, 78, -84, 53, 74, -18, 93, 102, 24, -77, -97, -6, -106, -10, -101, -29, 36, -33]).buffer,
- timeout: 60000,
- userVerification: "preferred",
- allowCredentials: [{ "type": "public-key", "id": new Int8Array([-33, 59, -68, 121, 57, -27, -33, -40, 55, 8, -65, -15, -40, -103, 73, 61, 49, 56, 65, -84, -27, -86, -103, -115, 15, 43, -64, -60, -105, 81, -111, 115, 105, 111, -105, 64, 73, 55, -35, 35, 38, 59, -91, 95, 64, 30, -10, -6, -91, -59, 26, 19, -3, 2, -39, 71, 112, 124, -66, -89, -10, -35, 122, 103]).buffer }]
-};
-
-navigator.credentials.get({ "publicKey" : options })
- .then(function (assertion) {
- var clientData = String.fromCharCode.apply(null, new Uint8Array(assertion.response.clientDataJSON));
- var authenticatorData = new Int8Array(assertion.response.authenticatorData).toString();
- var signature = new Int8Array(assertion.response.signature).toString();
- var rawId = assertion.id;
- var userHandle = String.fromCharCode.apply(null, new Uint8Array(assertion.response.userHandle));
- document.getElementById('webAuthnOutcome').value = clientData + "::" + authenticatorData + "::" + signature + "::" + rawId + "::" + userHandle;
- document.getElementById("loginButton_0").click();
- }).catch(function (err) {
- document.getElementById('webAuthnOutcome').value = "ERROR" + "::" + err;
- var allowRecoveryCode = 'true' === "true";
- if (allowRecoveryCode) {
- var loginButton = document.getElementById("loginButton_0");
- if (loginButton) {
- var prev = loginButton.previousElementSibling;
- if (prev && prev.nodeName == "DIV") {
- prev.getElementsByTagName("div")[0].innerHTML = " "
- + err + " ";
- }
- }
- } else {
- document.getElementById("loginButton_0").click();
- }
- });
-`;
diff --git a/packages/javascript-sdk/src/http-client/helpers.test.ts b/packages/javascript-sdk/src/http-client/helpers.test.ts
deleted file mode 100644
index df0b22fb3..000000000
--- a/packages/javascript-sdk/src/http-client/helpers.test.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * helpers.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import {
- buildAuthzOptions,
- examineForIGAuthz,
- examineForIGAuthzHeader,
- examineForRESTAuthz,
- normalizeIGJSONResponseToAdviceJSON,
- normalizeIGRedirectResponseToAdviceJSON,
-} from './helpers';
-import {
- authzByTxnResFromIG,
- authzByTxnResFromIGHeader,
- authzByTxnResFromREST,
- authzByTreeResFromIG,
- authzByTreeResFromIGHeader,
- authzByTreeResFromREST,
- authzTreeJSON,
- authzTxnJSON,
-} from './http-client.mock.data';
-
-describe('Test HttpClient utils', () => {
- it('build auth by tree req options', () => {
- const txnAuthObj = authzTreeJSON;
- const expectedUrl =
- // eslint-disable-next-line max-len, prettier/prettier
- 'https://openam.example.com/am/json/realms/root/authenticate?authIndexType=composite_advice&authIndexValue=%3CAdvices%3E%3CAttributeValuePair%3E%3CAttribute%20name%3D%22AuthenticateToServiceConditionAdvice%22%2F%3E%3CValue%3Eabc%3C%2FValue%3E%3C%2FAttributeValuePair%3E%3C%2FAdvices%3E';
-
- const output = buildAuthzOptions(txnAuthObj, 'https://openam.example.com/am/', 0);
- expect(output.url).toStrictEqual(expectedUrl);
- });
-
- it('build auth by txn req options', () => {
- const txnAuthObj = authzTxnJSON;
- const expectedUrl =
- // eslint-disable-next-line max-len, prettier/prettier
- 'https://openam.example.com/am/json/realms/root/authenticate?authIndexType=composite_advice&authIndexValue=%3CAdvices%3E%3CAttributeValuePair%3E%3CAttribute%20name%3D%22TransactionConditionAdvice%22%2F%3E%3CValue%3Eabc%3C%2FValue%3E%3C%2FAttributeValuePair%3E%3C%2FAdvices%3E';
- const output = buildAuthzOptions(txnAuthObj, 'https://openam.example.com/am/', 0);
- expect(output.url).toStrictEqual(expectedUrl);
- });
-
- it('examines response for IG auth by tree', async () => {
- const output = await examineForIGAuthz(authzByTreeResFromIG);
- expect(output).toBe(true);
- });
-
- it('examines response for IG auth by tree using header', async () => {
- const output = await examineForIGAuthzHeader(authzByTreeResFromIGHeader);
- expect(output).toBe(true);
- });
-
- it('examines response for REST auth by tree', async () => {
- const output = await examineForRESTAuthz(authzByTreeResFromREST);
- expect(output).toBe(true);
- });
-
- it('examines response for IG auth by txn', async () => {
- const output = await examineForIGAuthz(authzByTxnResFromIG);
- expect(output).toBe(true);
- });
-
- it('examines response for IG auth by txn using header', async () => {
- const output = await examineForIGAuthzHeader(authzByTxnResFromIGHeader);
- expect(output).toBe(true);
- });
-
- it('examines response for REST auth by txn', async () => {
- const output = await examineForRESTAuthz(authzByTxnResFromREST);
- expect(output).toBe(true);
- });
-
- it('normalizes authz by tree from IG redirect to JSON', async () => {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const res: any = {
- // eslint-disable-next-line max-len, prettier/prettier
- url: 'https://openam.example.com/am/json/realms/root/authenticate?authIndexType=composite_advice&authIndexValue=%3CAdvices%3E%3CAttributeValuePair%3E%3CAttribute+name%3D%22AuthenticateToServiceConditionAdvice%22%2F%3E%3CValue%3Eabc%3C%2FValue%3E%3C%2FAttributeValuePair%3E%3C%2FAdvices%3E',
- };
- const expected = authzTreeJSON;
- const output = await normalizeIGRedirectResponseToAdviceJSON(res);
- expect(output).toStrictEqual(expected);
- });
-
- it('normalizes IG redirect to advice JSON', async () => {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const res: any = {
- // eslint-disable-next-line max-len, prettier/prettier
- url: 'https://openam.example.com/am/json/realms/root/authenticate?authIndexType=composite_advice&authIndexValue=%3CAdvices%3E%3CAttributeValuePair%3E%3CAttribute+name%3D%22TransactionConditionAdvice%22%2F%3E%3CValue%3Eabc%3C%2FValue%3E%3C%2FAttributeValuePair%3E%3C%2FAdvices%3E',
- };
- const expected = authzTxnJSON;
- const output = await normalizeIGRedirectResponseToAdviceJSON(res);
- expect(output).toStrictEqual(expected);
- });
-
- it('normalizes IG JSON to advice JSON', async () => {
- const advices = btoa('{"TransactionConditionAdvice":["abc"]}');
- const headers = new Headers();
- headers.append(
- 'WWW-Authenticate',
- `SSOADVICE realm="/",advices="${advices}",am_uri="https://openam.example.com/am"`,
- );
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const res: any = {
- headers: headers,
- };
- const expected = authzTxnJSON;
- const output = await normalizeIGJSONResponseToAdviceJSON(res);
- expect(output).toStrictEqual(expected);
- });
-});
diff --git a/packages/javascript-sdk/src/http-client/helpers.ts b/packages/javascript-sdk/src/http-client/helpers.ts
deleted file mode 100644
index 73ccaf200..000000000
--- a/packages/javascript-sdk/src/http-client/helpers.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * helpers.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/**
- * @module
- * @ignore
- * These are private utility functions for HttpClient
- */
-import type { CustomPathConfig } from '../config/interfaces';
-import type {
- Advices,
- HttpClientRequestOptions,
- RequiresNewTokenFn,
- AuthorizationJSON,
-} from './interfaces';
-import type { Tokens } from '../shared/interfaces';
-import { getEndpointPath, resolve, stringify } from '../util/url';
-import { FRLogger } from '../util/logger';
-
-export function addAuthzInfoToHeaders(
- init: RequestInit,
- advices: Advices,
- tokens?: Tokens | void,
-): Headers {
- const headers = new Headers(init.headers);
-
- if (advices.AuthenticateToServiceConditionAdvice) {
- headers.set('X-Tree', advices.AuthenticateToServiceConditionAdvice[0]);
- } else if (advices.TransactionConditionAdvice) {
- headers.set('X-TxID', advices.TransactionConditionAdvice[0]);
- }
-
- if (tokens && tokens.idToken) {
- headers.set('X-IdToken', tokens.idToken);
- }
- return headers;
-}
-
-export function addAuthzInfoToURL(url: string, advices: Advices, tokens?: Tokens | void): string {
- const updatedURL = new URL(url);
-
- // Only modify URL for Transactional Authorization
- if (advices.TransactionConditionAdvice) {
- const txId = advices.TransactionConditionAdvice[0];
- // Add Txn ID to *original* request options as URL param
- updatedURL.searchParams.append('_txid', txId);
- }
-
- // If tokens are used, send idToken (OIDC)
- if (tokens && tokens.idToken) {
- updatedURL.searchParams.append('_idtoken', tokens.idToken);
- }
-
- // FYI: in certain circumstances, the URL may be returned unchanged
- return updatedURL.toString();
-}
-
-export function buildAuthzOptions(
- authzObj: AuthorizationJSON,
- baseURL: string,
- timeout: number,
- realmPath?: string,
- customPaths?: CustomPathConfig,
-): HttpClientRequestOptions {
- const treeAuthAdvices = authzObj.advices && authzObj.advices.AuthenticateToServiceConditionAdvice;
- const txnAuthAdvices = authzObj.advices && authzObj.advices.TransactionConditionAdvice;
- let attributeValue = '';
- let attributeName = '';
-
- if (treeAuthAdvices) {
- attributeValue = treeAuthAdvices.reduce((prev: string, curr: string) => {
- const prevWithSpace = prev ? ` ${prev}` : prev;
- prev = `${curr}${prevWithSpace}`;
- return prev;
- }, '');
- attributeName = 'AuthenticateToServiceConditionAdvice';
- } else if (txnAuthAdvices) {
- attributeValue = txnAuthAdvices.reduce((prev: string, curr: string) => {
- const prevWithSpace = prev ? ` ${prev}` : prev;
- prev = `${curr}${prevWithSpace}`;
- return prev;
- }, '');
- attributeName = 'TransactionConditionAdvice';
- }
-
- const openTags = ``;
- const nameTag = ` `;
- const valueTag = `${attributeValue} `;
- const endTags = ` `;
- const fullXML = `${openTags}${nameTag}${valueTag}${endTags}`;
-
- const path = getEndpointPath('authenticate', realmPath, customPaths);
- const queryParams = {
- authIndexType: 'composite_advice',
- authIndexValue: fullXML,
- };
-
- const options = {
- init: {
- method: 'POST',
- credentials: 'include' as const,
- headers: new Headers({
- 'Accept-API-Version': 'resource=2.0, protocol=1.0',
- }),
- },
- timeout,
- url: resolve(baseURL, `${path}?${stringify(queryParams)}`),
- };
- return options;
-}
-
-export function examineForIGAuthz(res: Response): boolean {
- const type = res.headers.get('Content-Type') || '';
- return type.includes('html') && res.url.includes('composite_advice');
-}
-
-export function examineForIGAuthzHeader(headers: Headers): boolean {
- const authnHeader = headers.get('WWW-Authenticate') || '';
- return authnHeader.includes('advices');
-}
-
-export async function examineForRESTAuthz(res: Response): Promise {
- const clone = res.clone();
- const json = await clone.json();
- return !!json.advices;
-}
-
-function getXMLValueFromURL(urlString: string): string {
- const url = new URL(urlString);
- const value = url.searchParams.get('authIndexValue') || '';
- const parser = new DOMParser();
- const decodedValue = decodeURIComponent(value);
- const doc = parser.parseFromString(decodedValue, 'application/xml');
- const el = doc.querySelector('Value');
- return el ? el.innerHTML : '';
-}
-
-export function getAdvicesFromHeader(header: string): Advices {
- const headerArr = header.split(',') || [];
- const advicesSubstr = headerArr.find((substr) => substr.includes('advices')) || '';
- let advicesValueParsed: Advices;
- try {
- const advicesValueArray = advicesSubstr.match(/"(\S+)"/);
- const advicesValue = advicesValueArray ? advicesValueArray[1] : '';
- const advicesValueDecoded = atob(advicesValue);
- advicesValueParsed = JSON.parse(advicesValueDecoded);
- return advicesValueParsed;
- } catch (err) {
- FRLogger.error('Could not parse advices value from WWW-Authenticate header');
- }
- return {};
-}
-
-export function hasAuthzAdvice(json: AuthorizationJSON): boolean {
- if (json.advices && json.advices.AuthenticateToServiceConditionAdvice) {
- return (
- Array.isArray(json.advices.AuthenticateToServiceConditionAdvice) &&
- json.advices.AuthenticateToServiceConditionAdvice.length > 0
- );
- } else if (json.advices && json.advices.TransactionConditionAdvice) {
- return (
- Array.isArray(json.advices.TransactionConditionAdvice) &&
- json.advices.TransactionConditionAdvice.length > 0
- );
- } else {
- return false;
- }
-}
-
-export async function isAuthzStep(res: Response): Promise {
- // TODO: add comment
- const clone = res.clone();
- const json = await clone.json();
- return !!json.callbacks;
-}
-
-export function newTokenRequired(res: Response, requiresNewToken?: RequiresNewTokenFn): boolean {
- if (typeof requiresNewToken === 'function') {
- return requiresNewToken(res);
- }
- return res.status === 401;
-}
-
-export function normalizeIGRedirectResponseToAdviceJSON(res: Response): AuthorizationJSON {
- const advices: Advices = {};
- if (res.url.includes('AuthenticateToServiceConditionAdvice')) {
- advices.AuthenticateToServiceConditionAdvice = [getXMLValueFromURL(res.url)];
- } else {
- advices.TransactionConditionAdvice = [getXMLValueFromURL(res.url)];
- }
- return {
- resource: '',
- actions: {},
- attributes: {},
- advices,
- ttl: 0,
- };
-}
-
-export function normalizeIGJSONResponseToAdviceJSON(res: Response): AuthorizationJSON {
- const authHeader = res.headers.get('WWW-Authenticate') || '';
- const advicesObject = getAdvicesFromHeader(authHeader);
-
- return {
- resource: '',
- actions: {},
- attributes: {},
- advices: advicesObject,
- ttl: 0,
- };
-}
-
-export async function normalizeRESTJSON(res: Response): Promise {
- return await res.json();
-}
diff --git a/packages/javascript-sdk/src/http-client/http-client.mock.data.ts b/packages/javascript-sdk/src/http-client/http-client.mock.data.ts
deleted file mode 100644
index d739c8b6e..000000000
--- a/packages/javascript-sdk/src/http-client/http-client.mock.data.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * http-client.mock.data.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-export const authzByTreeResFromIG = {
- headers: {
- get(): string {
- return 'text/html; charset=utf-8';
- },
- },
- redirected: true,
- // eslint-disable-next-line max-len, prettier/prettier
- url: 'https://openam.example.com/am/json/realms/root/authenticate?authIndexType=composite_advice&authIndexValue=%3CAdvices%3E%3CAttributeValuePair%3E%3CAttribute%20name%3D%22AuthenticateToServiceConditionAdvice%22%2F%3E%3CValue%3Eabc%3C%2FValue%3E%3C%2FAttributeValuePair%3E%3C%2FAdvices%3E',
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
-} as any;
-
-export const authzByTreeResFromIGHeader = {
- get(name: string): string {
- const headerValue =
- 'SSOADVICE realm="/",advices="eyJBdXRoZW50aWNhdGVUb1NlcnZpY2VDb25kaXRpb25BZHZpY2UiOlsiL3NkazpDb25maXJtUGFzc3dvcmQiXX0=",am_uri="https://openam.example.com/am",';
- switch (name) {
- case 'WWW-Authenticate':
- return headerValue;
- default:
- return headerValue;
- }
- },
-} as any;
-
-export const authzByTxnResFromIG = {
- headers: {
- get(): string {
- return 'text/html; charset=utf-8';
- },
- },
- redirected: true,
- // eslint-disable-next-line max-len, prettier/prettier
- url: 'https://openam.example.com/am/json/realms/root/authenticate?authIndexType=composite_advice&authIndexValue=%3CAdvices%3E%3CAttributeValuePair%3E%3CAttribute%20name%3D%22TransactionConditionAdvice%22%2F%3E%3CValue%3Eabc%3C%2FValue%3E%3C%2FAttributeValuePair%3E%3C%2FAdvices%3E',
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
-} as any;
-
-export const authzByTxnResFromIGHeader = {
- get(name: string): string {
- const headerValue =
- 'SSOADVICE realm="/",advices="eyJUcmFuc2FjdGlvbkNvbmRpdGlvbkFkdmljZSI6WyIzOWRmZGQxNS01OWEzLTQ3M2MtYTdmYy1lY2RhM2JiYzNiYzgiXX0=",am_uri="https://openam.example.com/am"';
- switch (name) {
- case 'WWW-Authenticate':
- return headerValue;
- default:
- return headerValue;
- }
- },
-} as any;
-
-export const authzTreeJSON = {
- resource: '',
- actions: {},
- attributes: {},
- advices: {
- AuthenticateToServiceConditionAdvice: ['abc'],
- },
- ttl: 0,
-};
-
-export const authzTxnJSON = {
- resource: '',
- actions: {},
- attributes: {},
- advices: {
- TransactionConditionAdvice: ['abc'],
- },
- ttl: 0,
-};
-
-export const authzByTreeResFromREST = {
- clone() {
- return {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- json(): any {
- return Promise.resolve(authzTreeJSON);
- },
- };
- },
- json() {
- return Promise.resolve(authzTreeJSON);
- },
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
-} as any;
-
-export const authzByTxnResFromREST = {
- clone() {
- return {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- json(): any {
- return Promise.resolve(authzTxnJSON);
- },
- };
- },
- json() {
- return Promise.resolve(authzTxnJSON);
- },
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
-} as any;
diff --git a/packages/javascript-sdk/src/http-client/index.ts b/packages/javascript-sdk/src/http-client/index.ts
deleted file mode 100644
index ee67ea840..000000000
--- a/packages/javascript-sdk/src/http-client/index.ts
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import Config from '../config';
-import { ActionTypes } from '../config/enums';
-import FRAuth from '../fr-auth';
-import { StepType } from '../fr-auth/enums';
-import FRStep from '../fr-auth/fr-step';
-import type {
- HandleStep,
- HttpClientRequestOptions,
- RequiresNewTokenFn,
- AuthorizationJSON,
-} from './interfaces';
-import TokenManager from '../token-manager';
-import TokenStorage from '../token-storage';
-import { withTimeout } from '../util/timeout';
-import {
- addAuthzInfoToHeaders,
- addAuthzInfoToURL,
- buildAuthzOptions,
- examineForIGAuthz,
- examineForIGAuthzHeader,
- examineForRESTAuthz,
- hasAuthzAdvice,
- isAuthzStep,
- newTokenRequired,
- normalizeIGRedirectResponseToAdviceJSON,
- normalizeIGJSONResponseToAdviceJSON,
- normalizeRESTJSON,
-} from './helpers';
-import middlewareWrapper from '../util/middleware';
-
-/**
- * HTTP client that includes bearer token injection and refresh.
- * This module also supports authorization for policy protected endpoints.
- *
- * Example:
- *
- * ```js
- * return forgerock.HttpClient.request({
- * url: `https://example.com/protected/resource`,
- * init: {
- * method: 'GET',
- * credentials: 'include',
- * },
- * authorization: {
- * handleStep: async (step) => {
- * step.getCallbackOfType('PasswordCallback').setPassword(pw);
- * return Promise.resolve(step);
- * },
- * },
- * });
- * ```
- */
-abstract class HttpClient {
- /**
- * Makes a request using the specified options.
- *
- * @param options The options to use when making the request
- */
- public static async request(options: HttpClientRequestOptions): Promise {
- let res = await this._request(options, false);
- let authorizationJSON: AuthorizationJSON | undefined;
- let hasIG = false;
-
- if (newTokenRequired(res, options.requiresNewToken)) {
- res = await this._request(options, true);
- }
-
- if (options.authorization && options.authorization.handleStep) {
- if (res.status === 401 && examineForIGAuthzHeader(res.headers)) {
- hasIG = true;
- authorizationJSON = normalizeIGJSONResponseToAdviceJSON(res);
- } else if (res.redirected && examineForIGAuthz(res)) {
- hasIG = true;
- authorizationJSON = normalizeIGRedirectResponseToAdviceJSON(res);
- } else if (await examineForRESTAuthz(res)) {
- authorizationJSON = await normalizeRESTJSON(res);
- }
-
- if (authorizationJSON && authorizationJSON.advices) {
- const { middleware, realmPath, serverConfig } = Config.get(options.authorization.config);
- const authzOptions = buildAuthzOptions(
- authorizationJSON,
- serverConfig.baseUrl,
- options.timeout,
- realmPath,
- serverConfig.paths,
- );
-
- const url = new URL(authzOptions.url);
- const type = url.searchParams.get('authIndexType') as string;
- const tree = url.searchParams.get('authIndexValue') as string;
- const runMiddleware = middlewareWrapper(
- {
- url: new URL(authzOptions.url),
- init: authzOptions.init,
- },
- {
- type: ActionTypes.StartAuthenticate,
- payload: { type, tree },
- },
- );
- const { url: authUrl, init: authInit } = runMiddleware(middleware);
- authzOptions.url = authUrl.toString();
- authzOptions.init = authInit;
- const initialStep = await this._request(authzOptions, false);
-
- if (!(await isAuthzStep(initialStep))) {
- throw new Error('Error: Initial response from auth server not a "step".');
- }
- if (!hasAuthzAdvice(authorizationJSON)) {
- throw new Error(`Error: Transactional or Service Advice is empty.`);
- }
-
- // Walk through auth tree
- await this.stepIterator(initialStep, options.authorization.handleStep);
- // See if OAuth tokens are being used
- const tokens = await TokenStorage.get();
-
- if (hasIG) {
- // Update URL with IDs and tokens for IG
- options.url = addAuthzInfoToURL(options.url, authorizationJSON.advices, tokens);
- } else {
- // Update headers with IDs and tokens for REST API
- options.init.headers = addAuthzInfoToHeaders(
- options.init,
- authorizationJSON.advices,
- tokens,
- );
- }
- // Retry original resource request
- res = await this._request(options, false);
- } else {
- throw new Error(`Error: Unable to process advice`);
- }
- }
-
- return res;
- }
-
- private static async setAuthHeaders(headers: Headers, forceRenew: boolean): Promise {
- let tokens = await TokenStorage.get();
-
- /**
- * Condition to see if Auth is session based or OAuth token based
- */
- if (tokens && tokens.accessToken) {
- // Access tokens are an OAuth artifact
- tokens = await TokenManager.getTokens({ forceRenew });
- // TODO: Temp fix; refactor this in next txn auth story
- if (tokens && tokens.accessToken) {
- headers.set('Authorization', `Bearer ${tokens.accessToken}`);
- }
- }
- return headers;
- }
-
- private static async stepIterator(res: Response, handleStep: HandleStep): Promise {
- const jsonRes = await res.json();
- const initialStep = new FRStep(jsonRes);
-
- // eslint-disable-next-line no-async-promise-executor
- return new Promise(async (resolve, reject) => {
- async function handleNext(step: FRStep): Promise {
- const input = await handleStep(step);
- const output = await FRAuth.next(input, { tree: '', type: '' });
-
- if (output.type === StepType.LoginSuccess) {
- resolve();
- } else if (output.type === StepType.LoginFailure) {
- reject('Authentication tree failure.');
- } else {
- handleNext(output);
- }
- }
-
- handleNext(initialStep);
- });
- }
-
- private static async _request(
- options: HttpClientRequestOptions,
- forceRenew: boolean,
- ): Promise {
- const { url, init, timeout } = options;
- let headers = new Headers(init.headers || {});
-
- if (options.authorization) {
- headers.set('x-authenticate-response', 'header');
- }
-
- if (!options.bypassAuthentication) {
- headers = await this.setAuthHeaders(headers, forceRenew);
- }
- init.headers = headers;
-
- return withTimeout(fetch(url, init), timeout);
- }
-}
-
-export default HttpClient;
-export type { HttpClientRequestOptions, RequiresNewTokenFn };
diff --git a/packages/javascript-sdk/src/http-client/interfaces.ts b/packages/javascript-sdk/src/http-client/interfaces.ts
deleted file mode 100644
index 68ea767a5..000000000
--- a/packages/javascript-sdk/src/http-client/interfaces.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * interfaces.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { ConfigOptions } from '../config/interfaces';
-import type FRStep from '../fr-auth/fr-step';
-
-export interface Advices {
- AuthenticateToServiceConditionAdvice?: string[];
- TransactionConditionAdvice?: string[];
-}
-
-export declare type HandleStep = (step: FRStep) => Promise;
-
-/**
- * Options to use when making an HTTP call.
- */
-export interface HttpClientRequestOptions {
- bypassAuthentication?: boolean;
- authorization?: {
- config?: ConfigOptions;
- handleStep: HandleStep;
- idToken?: string;
- txnID?: string;
- };
- init: RequestInit;
- requiresNewToken?: RequiresNewTokenFn;
- timeout: number;
- url: string;
-}
-
-/**
- * A function that determines whether a new token is required based on a HTTP response.
- */
-export type RequiresNewTokenFn = (res: Response) => boolean;
-
-export interface AuthorizationJSON {
- resource: string;
- actions: { [key: string]: string };
- attributes: { [key: string]: string };
- advices: Advices | null;
- ttl: number;
-}
diff --git a/packages/javascript-sdk/src/index.test.ts b/packages/javascript-sdk/src/index.test.ts
deleted file mode 100644
index 39bc2e74f..000000000
--- a/packages/javascript-sdk/src/index.test.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import * as sdk from './';
-import Auth from './auth';
-import { CallbackType, ErrorCode } from './auth/enums';
-import Config from './config';
-import FRAuth from './fr-auth';
-import FRCallback from './fr-auth/callbacks';
-import AttributeInputCallback from './fr-auth/callbacks/attribute-input-callback';
-import ChoiceCallback from './fr-auth/callbacks/choice-callback';
-import ConfirmationCallback from './fr-auth/callbacks/confirmation-callback';
-import DeviceProfileCallback from './fr-auth/callbacks/device-profile-callback';
-import HiddenValueCallback from './fr-auth/callbacks/hidden-value-callback';
-import KbaCreateCallback from './fr-auth/callbacks/kba-create-callback';
-import MetadataCallback from './fr-auth/callbacks/metadata-callback';
-import NameCallback from './fr-auth/callbacks/name-callback';
-import PasswordCallback from './fr-auth/callbacks/password-callback';
-import PollingWaitCallback from './fr-auth/callbacks/polling-wait-callback';
-import PingOneProtectEvaluationCallback from './fr-auth/callbacks/ping-protect-evaluation-callback';
-import PingOneProtectInitializeCallback from './fr-auth/callbacks/ping-protect-initialize-callback';
-import ReCaptchaCallback from './fr-auth/callbacks/recaptcha-callback';
-import RedirectCallback from './fr-auth/callbacks/redirect-callback';
-import SelectIdPCallback from './fr-auth/callbacks/select-idp-callback';
-import SuspendedTextOutputCallback from './fr-auth/callbacks/suspended-text-output-callback';
-import TermsAndConditionsCallback from './fr-auth/callbacks/terms-and-conditions-callback';
-import TextInputCallback from './fr-auth/callbacks/text-input-callback';
-import TextOutputCallback from './fr-auth/callbacks/text-output-callback';
-// eslint-disable-next-line max-len
-import ValidatedCreatePasswordCallback from './fr-auth/callbacks/validated-create-password-callback';
-// eslint-disable-next-line max-len
-import ValidatedCreateUsernameCallback from './fr-auth/callbacks/validated-create-username-callback';
-import { StepType } from './fr-auth/enums';
-import FRLoginFailure from './fr-auth/fr-login-failure';
-import FRLoginSuccess from './fr-auth/fr-login-success';
-import FRStep from './fr-auth/fr-step';
-import FRDevice from './fr-device';
-import FRPolicy, { PolicyKey } from './fr-policy';
-import FRQRCode from './fr-qr-code';
-import defaultMessageCreator from './fr-policy/message-creator';
-import FRRecoveryCodes from './fr-recovery-codes';
-import FRUser from './fr-user';
-import FRWebAuthn, { WebAuthnOutcome, WebAuthnStepType } from './fr-webauthn';
-import HttpClient from './http-client';
-import OAuth2Client, { ResponseType } from './oauth2-client';
-import SessionManager from './session-manager';
-import TokenManager from './token-manager';
-import TokenStorage from './token-storage';
-import UserManager from './user-manager';
-import Deferred from './util/deferred';
-import PKCE from './util/pkce';
-import LocalStorage from './util/storage';
-
-test('ensure the sdk exports are exported from the index', () => {
- expect(sdk).toBeDefined();
- expect(sdk).toMatchObject({
- defaultMessageCreator,
- AttributeInputCallback,
- Auth,
- CallbackType,
- ChoiceCallback,
- Config,
- ConfirmationCallback,
- Deferred,
- DeviceProfileCallback,
- ErrorCode,
- FRAuth,
- FRCallback,
- FRDevice,
- FRLoginFailure,
- FRLoginSuccess,
- FRPolicy,
- FRQRCode,
- FRRecoveryCodes,
- FRStep,
- FRUser,
- FRWebAuthn,
- HiddenValueCallback,
- HttpClient,
- KbaCreateCallback,
- LocalStorage,
- MetadataCallback,
- NameCallback,
- OAuth2Client,
- PasswordCallback,
- PKCE,
- PingOneProtectEvaluationCallback,
- PingOneProtectInitializeCallback,
- PolicyKey,
- PollingWaitCallback,
- ReCaptchaCallback,
- RedirectCallback,
- ResponseType,
- SelectIdPCallback,
- SessionManager,
- StepType,
- SuspendedTextOutputCallback,
- TermsAndConditionsCallback,
- TextInputCallback,
- TextOutputCallback,
- TokenManager,
- TokenStorage,
- UserManager,
- ValidatedCreatePasswordCallback,
- ValidatedCreateUsernameCallback,
- WebAuthnOutcome,
- WebAuthnStepType,
- });
-});
diff --git a/packages/javascript-sdk/src/index.ts b/packages/javascript-sdk/src/index.ts
deleted file mode 100644
index 6944a4ace..000000000
--- a/packages/javascript-sdk/src/index.ts
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.ts
- *
- * Copyright (c) 2020-2021 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import Auth from './auth';
-import { CallbackType, ErrorCode } from './auth/enums';
-import type { Callback, NameValue, PolicyRequirement, Step, StepDetail } from './auth/interfaces';
-import Config from './config';
-import type { ConfigOptions, ValidConfigOptions } from './config';
-import FRAuth from './fr-auth';
-import FRCallback from './fr-auth/callbacks';
-import AttributeInputCallback from './fr-auth/callbacks/attribute-input-callback';
-import ChoiceCallback from './fr-auth/callbacks/choice-callback';
-import ConfirmationCallback from './fr-auth/callbacks/confirmation-callback';
-import DeviceProfileCallback from './fr-auth/callbacks/device-profile-callback';
-import type { FRCallbackFactory } from './fr-auth/callbacks/factory';
-import HiddenValueCallback from './fr-auth/callbacks/hidden-value-callback';
-import KbaCreateCallback from './fr-auth/callbacks/kba-create-callback';
-import MetadataCallback from './fr-auth/callbacks/metadata-callback';
-import NameCallback from './fr-auth/callbacks/name-callback';
-import PasswordCallback from './fr-auth/callbacks/password-callback';
-import PollingWaitCallback from './fr-auth/callbacks/polling-wait-callback';
-import ReCaptchaCallback from './fr-auth/callbacks/recaptcha-callback';
-import RedirectCallback from './fr-auth/callbacks/redirect-callback';
-import type { IdPValue } from './fr-auth/callbacks/select-idp-callback';
-import SelectIdPCallback from './fr-auth/callbacks/select-idp-callback';
-import SuspendedTextOutputCallback from './fr-auth/callbacks/suspended-text-output-callback';
-import TermsAndConditionsCallback from './fr-auth/callbacks/terms-and-conditions-callback';
-import TextInputCallback from './fr-auth/callbacks/text-input-callback';
-import TextOutputCallback from './fr-auth/callbacks/text-output-callback';
-// eslint-disable-next-line max-len
-import ValidatedCreatePasswordCallback from './fr-auth/callbacks/validated-create-password-callback';
-// eslint-disable-next-line max-len
-import ValidatedCreateUsernameCallback from './fr-auth/callbacks/validated-create-username-callback';
-import { StepType } from './fr-auth/enums';
-import FRLoginFailure from './fr-auth/fr-login-failure';
-import PingOneProtectEvaluationCallback from './fr-auth/callbacks/ping-protect-evaluation-callback';
-import PingOneProtectInitializeCallback from './fr-auth/callbacks/ping-protect-initialize-callback';
-import ReCaptchaEnterpriseCallback from './fr-auth/callbacks/recaptcha-enterprise-callback';
-import FRLoginSuccess from './fr-auth/fr-login-success';
-import type { FRStepHandler } from './fr-auth/fr-step';
-import FRStep from './fr-auth/fr-step';
-import type { AuthResponse, FailureDetail } from './fr-auth/interfaces';
-import FRDevice from './fr-device';
-import type { MessageCreator, ProcessedPropertyError } from './fr-policy';
-import FRPolicy, { PolicyKey } from './fr-policy';
-import FRQRCode from './fr-qr-code';
-import defaultMessageCreator from './fr-policy/message-creator';
-import FRRecoveryCodes from './fr-recovery-codes';
-import FRUser from './fr-user';
-import type {
- RelyingParty,
- WebAuthnAuthenticationMetadata,
- WebAuthnCallbacks,
- WebAuthnRegistrationMetadata,
-} from './fr-webauthn';
-import FRWebAuthn, { WebAuthnOutcome, WebAuthnStepType } from './fr-webauthn';
-import HttpClient from './http-client';
-import type {
- GetAuthorizationUrlOptions,
- GetOAuth2TokensOptions,
- OAuth2Tokens,
-} from './oauth2-client';
-import OAuth2Client, { ResponseType } from './oauth2-client';
-import SessionManager from './session-manager';
-import type { Tokens } from './shared/interfaces';
-import type { GetTokensOptions } from './token-manager';
-import TokenManager from './token-manager';
-import TokenStorage from './token-storage';
-import UserManager from './user-manager';
-import Deferred from './util/deferred';
-import PKCE from './util/pkce';
-import LocalStorage from './util/storage';
-import type { LoggerFunctions, StepOptions } from './config/interfaces';
-
-export type {
- AuthResponse,
- Callback,
- ConfigOptions,
- FailureDetail,
- FRCallbackFactory,
- FRStepHandler,
- GetAuthorizationUrlOptions,
- GetOAuth2TokensOptions,
- GetTokensOptions,
- IdPValue,
- LoggerFunctions,
- MessageCreator,
- NameValue,
- OAuth2Tokens,
- PolicyRequirement,
- ProcessedPropertyError,
- RelyingParty,
- Step,
- StepDetail,
- Tokens,
- ValidConfigOptions,
- WebAuthnAuthenticationMetadata,
- WebAuthnCallbacks,
- WebAuthnRegistrationMetadata,
-};
-export {
- defaultMessageCreator,
- AttributeInputCallback,
- Auth,
- CallbackType,
- ChoiceCallback,
- Config,
- ConfirmationCallback,
- Deferred,
- DeviceProfileCallback,
- ErrorCode,
- FRAuth,
- FRCallback,
- FRDevice,
- FRLoginFailure,
- FRLoginSuccess,
- FRPolicy,
- FRQRCode,
- FRRecoveryCodes,
- FRStep,
- FRUser,
- FRWebAuthn,
- HiddenValueCallback,
- HttpClient,
- KbaCreateCallback,
- LocalStorage,
- MetadataCallback,
- NameCallback,
- OAuth2Client,
- PasswordCallback,
- PingOneProtectEvaluationCallback,
- PingOneProtectInitializeCallback,
- PKCE,
- PolicyKey,
- PollingWaitCallback,
- ReCaptchaCallback,
- ReCaptchaEnterpriseCallback,
- RedirectCallback,
- ResponseType,
- SelectIdPCallback,
- SessionManager,
- StepOptions,
- StepType,
- SuspendedTextOutputCallback,
- TermsAndConditionsCallback,
- TextInputCallback,
- TextOutputCallback,
- TokenManager,
- TokenStorage,
- UserManager,
- ValidatedCreatePasswordCallback,
- ValidatedCreateUsernameCallback,
- WebAuthnOutcome,
- WebAuthnStepType,
-};
diff --git a/packages/javascript-sdk/src/oauth2-client/enums.ts b/packages/javascript-sdk/src/oauth2-client/enums.ts
deleted file mode 100644
index 25657ec32..000000000
--- a/packages/javascript-sdk/src/oauth2-client/enums.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * enums.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/**
- * Specifies the type of OAuth flow to invoke.
- */
-enum ResponseType {
- Code = 'code',
- Token = 'token',
-}
-
-export { ResponseType };
diff --git a/packages/javascript-sdk/src/oauth2-client/index.ts b/packages/javascript-sdk/src/oauth2-client/index.ts
deleted file mode 100644
index e6c705e40..000000000
--- a/packages/javascript-sdk/src/oauth2-client/index.ts
+++ /dev/null
@@ -1,401 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.ts
- *
- * Copyright (c) 2020-2021 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { ActionTypes } from '../config/enums';
-import type { ConfigOptions } from '../config/index';
-import Config from '../config/index';
-import type { ConfigurablePaths } from '../config/interfaces';
-import type { StringDict } from '../shared/interfaces';
-import type { Noop } from '../shared/types';
-import TokenStorage from '../token-storage';
-import { isOkOr4xx } from '../util/http';
-import PKCE from '../util/pkce';
-import { withTimeout } from '../util/timeout';
-import { getEndpointPath, resolve, stringify } from '../util/url';
-import { ResponseType } from './enums';
-import type {
- AccessTokenResponse,
- LogoutOptions,
- GetAuthorizationUrlOptions,
- GetOAuth2TokensOptions,
- OAuth2Tokens,
- EndSessionOptions,
-} from './interfaces';
-import middlewareWrapper from '../util/middleware';
-
-const allowedErrors = {
- // AM error for consent requirement
- AuthenticationConsentRequired: 'Authentication or consent required',
-
- // Ping federate consent requirement
- AuthenticationIsRequired: 'Authentication is required.',
-
- // Manual iframe error
- AuthorizationTimeout: 'Authorization timed out',
-
- // Chromium browser error
- FailedToFetch: 'Failed to fetch',
-
- // Mozilla browser error
- NetworkError: 'NetworkError when attempting to fetch resource.',
-
- // Webkit browser error
- CORSError: 'Cross-origin redirection',
-
- // prompt=none errors
- InteractionNotAllowed: 'The request requires some interaction that is not allowed.',
-
- // PingOne login error
- LoginRequired: 'User authentication is required',
-
- RequestRequiresConsent: 'The request requires consent.',
-};
-
-/**
- * OAuth 2.0 client.
- */
-abstract class OAuth2Client {
- public static async createAuthorizeUrl(options: GetAuthorizationUrlOptions): Promise {
- const { clientId, middleware, redirectUri, scope } = Config.get(options);
- const requestParams: StringDict = {
- ...options.query,
- client_id: clientId,
- redirect_uri: redirectUri,
- response_type: options.responseType,
- scope,
- state: options.state,
- ...(options.prompt ? { prompt: options.prompt } : {}),
- };
-
- if (options.verifier) {
- const challenge = await PKCE.createChallenge(options.verifier);
- requestParams.code_challenge = challenge;
- requestParams.code_challenge_method = 'S256';
- }
-
- const runMiddleware = middlewareWrapper(
- {
- url: new URL(this.getUrl('authorize', requestParams, options)),
- init: {},
- },
- { type: ActionTypes.Authorize },
- );
- const { url } = runMiddleware(middleware);
- return url.toString();
- }
-
- /**
- * Calls the authorize URL with an iframe. If successful,
- * it returns the callback URL with authentication code,
- * optionally using PKCE.
- * Method renamed in v3.
- * Original Name: getAuthorizeUrl
- * New Name: getAuthCodeByIframe
- */
- public static async getAuthCodeByIframe(options: GetAuthorizationUrlOptions): Promise {
- const url = await this.createAuthorizeUrl({ ...options, prompt: 'none' });
-
- const { serverConfig } = Config.get(options);
-
- return new Promise((resolve, reject) => {
- const iframe = document.createElement('iframe');
-
- // Define these here to avoid linter warnings
- const noop: Noop = () => {
- return;
- };
- let onLoad: Noop = noop;
- let cleanUp: Noop = noop;
- let timeout: number | ReturnType = 0;
-
- cleanUp = (): void => {
- clearTimeout(timeout);
- iframe.removeEventListener('load', onLoad);
- iframe.remove();
- };
-
- onLoad = (): void => {
- if (iframe.contentWindow) {
- const newHref = iframe.contentWindow.location.href;
- if (this.containsAuthCode(newHref)) {
- cleanUp();
- resolve(newHref);
- } else if (this.containsAuthError(newHref)) {
- cleanUp();
- resolve(newHref);
- }
- }
- };
-
- timeout = setTimeout(() => {
- cleanUp();
- reject(new Error(allowedErrors.AuthorizationTimeout));
- }, serverConfig.timeout);
-
- iframe.style.display = 'none';
- iframe.addEventListener('load', onLoad);
- document.body.appendChild(iframe);
- iframe.src = url;
- });
- }
-
- /**
- * Exchanges an authorization code for OAuth tokens.
- */
- public static async getOAuth2Tokens(options: GetOAuth2TokensOptions): Promise {
- const { clientId, redirectUri } = Config.get(options);
-
- const requestParams: StringDict = {
- client_id: clientId,
- code: options.authorizationCode,
- grant_type: 'authorization_code',
- redirect_uri: redirectUri,
- };
-
- if (options.verifier) {
- requestParams.code_verifier = options.verifier;
- }
-
- const body = stringify(requestParams);
- const init = {
- body,
- headers: new Headers({
- 'Content-Length': body.length.toString(),
- 'Content-Type': 'application/x-www-form-urlencoded',
- }),
- method: 'POST',
- };
-
- const response = await this.request('accessToken', undefined, false, init, options);
- const responseBody = await this.getBody(response);
-
- if (response.status !== 200) {
- const message =
- typeof responseBody === 'string'
- ? `Expected 200, received ${response.status}`
- : this.parseError(responseBody as StringDict);
- throw new Error(message);
- }
-
- const responseObject = responseBody as AccessTokenResponse;
- if (!responseObject.access_token) {
- throw new Error('Access token not found in response');
- }
-
- let tokenExpiry: number | undefined = undefined;
- if (responseObject.expires_in) {
- tokenExpiry = Date.now() + responseObject.expires_in * 1000;
- }
-
- return {
- accessToken: responseObject.access_token,
- idToken: responseObject.id_token,
- refreshToken: responseObject.refresh_token,
- tokenExpiry: tokenExpiry,
- };
- }
-
- /**
- * Gets OIDC user information.
- */
- public static async getUserInfo(options?: ConfigOptions): Promise {
- const response = await this.request('userInfo', undefined, true, undefined, options);
- if (response.status !== 200) {
- throw new Error(`Failed to get user info; received ${response.status}`);
- }
-
- const json = await response.json();
- return json;
- }
-
- /**
- * Invokes the OIDC end session endpoint.
- * Can result in a redirect to `/signoff` if using PingOne
- * It's best to explicitly provide the logout redirect URL in options
- *
- * @function endSession - call authorization server to end associated session
- * @param options {LogoutOptions} - an extension of ConfigOptions, but with two additional props
- * @param options.logoutRedirectUri {string} - the URL you want the AS to redirect to after signout
- * @param options.redirect {boolean} - to explicitly deactivate redirect, pass `false`
- */
- public static async endSession(
- options?: LogoutOptions | EndSessionOptions,
- ): Promise {
- // Shallow copy options to delete redirect props
- const configOptions: LogoutOptions | EndSessionOptions = { ...options };
-
- delete configOptions.redirect;
-
- delete configOptions.logoutRedirectUri;
-
- const query: StringDict = {};
-
- const tokens = await TokenStorage.get();
- query.id_token_hint =
- (tokens && tokens.idToken) || (options && 'idToken' in options ? options.idToken : '');
-
- const response = await this.request('endSession', query, true, undefined, configOptions, {
- redirect: options?.redirect,
- logoutRedirectUri: options?.logoutRedirectUri,
- });
- if (!isOkOr4xx(response)) {
- throw new Error(`Failed to end session; received ${response.status}`);
- }
- return response;
- }
-
- /**
- * Immediately revokes the stored access token.
- */
- public static async revokeToken(options?: ConfigOptions): Promise {
- const { clientId } = Config.get(options);
- const tokens = await TokenStorage.get();
- const accessToken = tokens && tokens.accessToken;
-
- const body: StringDict = {
- client_id: clientId,
- };
- // This is needed to support Token Vault; the SDK may not have the token locally
- if (accessToken) {
- body.token = accessToken;
- }
- const init: RequestInit = {
- body: stringify(body),
- credentials: 'include',
- headers: new Headers({
- 'Content-Type': 'application/x-www-form-urlencoded',
- }),
- method: 'POST',
- };
- const response = await this.request('revoke', undefined, false, init, options);
- if (!isOkOr4xx(response)) {
- throw new Error(`Failed to revoke token; received ${response.status}`);
- }
- return response;
- }
-
- private static async request(
- endpoint: ConfigurablePaths,
- query?: StringDict,
- includeToken?: boolean,
- init?: RequestInit,
- options?: ConfigOptions,
- logoutOptions?: { redirect?: boolean; logoutRedirectUri?: string },
- ): Promise {
- const { redirectUri, middleware, serverConfig } = Config.get(options);
- const endSessionRedirectUrl = logoutOptions?.logoutRedirectUri
- ? logoutOptions.logoutRedirectUri
- : redirectUri;
- const url = this.getUrl(endpoint, query, options);
-
- const getActionType = (endpoint: ConfigurablePaths): ActionTypes => {
- switch (endpoint) {
- case 'accessToken':
- return ActionTypes.ExchangeToken;
- case 'endSession':
- return ActionTypes.EndSession;
- case 'revoke':
- return ActionTypes.RevokeToken;
- default:
- return ActionTypes.UserInfo;
- }
- };
-
- init = init || ({} as RequestInit);
-
- if (includeToken) {
- const tokens = await TokenStorage.get();
- const accessToken = tokens && tokens.accessToken;
- init.credentials = 'include';
- init.headers = (init.headers || new Headers()) as Headers;
- init.headers.set('Authorization', `Bearer ${accessToken}`);
- }
- const runMiddleware = middlewareWrapper(
- { url: new URL(url), init },
- { type: getActionType(endpoint) },
- );
- const req = runMiddleware(middleware);
-
- /*
- * Check for PingOne related end session redirection requirement for third-party cookie support
- */
- if (
- getActionType(endpoint) === ActionTypes.EndSession && // endSession action only
- logoutOptions?.redirect === true // If redirect is explicitly `true`, do it!
- ) {
- // Add PingOne's redirect URL for signout before redirecting
- // Intentionally NOT using `window.location.href` for security just using empty string for fallback.
- req.url.searchParams.append('post_logout_redirect_uri', endSessionRedirectUrl || '');
- window.location.assign(req.url.toString());
-
- return new Response(); // Just return an empty response to keep the types the same.
- } else if (
- getActionType(endpoint) === ActionTypes.EndSession && // endSession action only
- logoutOptions?.redirect !== false && // Only `false` explicitly disables this behavior for rare edge cases
- // If we explicitly get a logout redirect URL, then that's enough of a hint to redirect
- // If we don't have that, let's see if they are calling the typical PingOne `/signoff` endpoint
- (logoutOptions?.logoutRedirectUri || this.getUrl('endSession').includes('/as/signoff'))
- ) {
- // Same as above
- req.url.searchParams.append('post_logout_redirect_uri', endSessionRedirectUrl || '');
- window.location.assign(req.url.toString());
-
- return new Response(); // Just return an empty response to keep the types the same.
- } else {
- return await withTimeout(fetch(req.url.toString(), req.init), serverConfig.timeout);
- }
- }
-
- private static containsAuthCode(url: string | null): boolean {
- return !!url && /code=([^&]+)/.test(url);
- }
-
- private static containsAuthError(url: string | null): boolean {
- return !!url && /error=([^&]+)/.test(url);
- }
-
- private static async getBody(response: Response): Promise {
- const contentType = response.headers.get('Content-Type');
- if (contentType && contentType.indexOf('application/json') > -1) {
- return await response.json();
- }
- return await response.text();
- }
-
- private static parseError(json: StringDict): string | undefined {
- if (json) {
- if (json.error && json.error_description) {
- return `${json.error}: ${json.error_description}`;
- }
- if (json.code && json.message) {
- return `${json.code}: ${json.message}`;
- }
- }
- return undefined;
- }
-
- private static getUrl(
- endpoint: ConfigurablePaths,
- query?: StringDict,
- options?: ConfigOptions,
- ): string {
- const { realmPath, serverConfig } = Config.get(options);
- const path = getEndpointPath(endpoint, realmPath, serverConfig.paths);
- let url = resolve(serverConfig.baseUrl, path);
- if (query) {
- url += `?${stringify(query)}`;
- }
- return url;
- }
-}
-
-export default OAuth2Client;
-export type { GetAuthorizationUrlOptions, GetOAuth2TokensOptions, OAuth2Tokens };
-export { allowedErrors, ResponseType };
diff --git a/packages/javascript-sdk/src/oauth2-client/interfaces.ts b/packages/javascript-sdk/src/oauth2-client/interfaces.ts
deleted file mode 100644
index 7f080a4fb..000000000
--- a/packages/javascript-sdk/src/oauth2-client/interfaces.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * interfaces.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { StringDict } from '../shared/interfaces';
-import type { ConfigOptions } from '../config';
-import type { ResponseType } from './enums';
-
-/**
- * Tokens returned after successful authentication.
- */
-interface OAuth2Tokens {
- accessToken: string;
- idToken?: string;
- refreshToken?: string;
- tokenExpiry?: number;
-}
-
-/**
- * Response from access_token endpoint.
- */
-interface AccessTokenResponse {
- access_token: string;
- id_token: string;
- refresh_token: string;
- expires_in: number;
-}
-
-/**
- * Options used when requesting the authorization URL.
- */
-interface GetAuthorizationUrlOptions extends ConfigOptions {
- responseType: ResponseType;
- state?: string;
- verifier?: string;
- query?: StringDict;
- prompt?: 'none' | 'login' | 'consent';
-}
-
-/**
- * Options used when requesting OAuth tokens.
- */
-interface GetOAuth2TokensOptions extends ConfigOptions {
- authorizationCode: string;
- verifier?: string;
-}
-
-interface LogoutOptions extends ConfigOptions {
- redirect?: boolean;
- logoutRedirectUri?: string;
-}
-
-interface EndSessionOptions extends LogoutOptions {
- idToken: string;
-}
-export type {
- AccessTokenResponse,
- EndSessionOptions,
- GetAuthorizationUrlOptions,
- GetOAuth2TokensOptions,
- LogoutOptions,
- OAuth2Tokens,
-};
diff --git a/packages/javascript-sdk/src/oauth2-client/state-pkce.ts b/packages/javascript-sdk/src/oauth2-client/state-pkce.ts
deleted file mode 100644
index bbb681047..000000000
--- a/packages/javascript-sdk/src/oauth2-client/state-pkce.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import PKCE from '../util/pkce';
-import { GetAuthorizationUrlOptions } from './interfaces';
-
-function getStorageKey(clientId: string, prefix?: string) {
- return `${prefix || 'FR-SDK'}-authflow-${clientId}`;
-}
-
-/**
- * Generate and store PKCE values for later use
- * @param { string } storageKey - Key to store authorization options in sessionStorage
- * @param {GenerateAndStoreAuthUrlValues} options - Options for generating PKCE values
- * @returns { state: string, verifier: string, GetAuthorizationUrlOptions }
- */
-interface GenerateAndStoreAuthUrlValues extends GetAuthorizationUrlOptions {
- clientId: string;
- login?: 'redirect' | 'embedded';
- prefix?: string;
-}
-
-export function generateAndStoreAuthUrlValues(options: GenerateAndStoreAuthUrlValues) {
- const verifier = PKCE.createVerifier();
- const state = PKCE.createState();
- const storageKey = getStorageKey(options.clientId, options.prefix);
-
- const authorizeUrlOptions = {
- ...options,
- state,
- verifier,
- };
-
- return [
- authorizeUrlOptions,
- () => sessionStorage.setItem(storageKey, JSON.stringify(authorizeUrlOptions)),
- ] as const;
-}
-
-/**
- * @function getStoredAuthUrlValues - Retrieve stored authorization options from sessionStorage
- * @param { string } storageKey - Key to retrieve stored values from sessionStorage
- * @returns { GetAuthorizationUrlOptions }
- */
-export function getStoredAuthUrlValues(
- clientId: string,
- prefix?: string,
-): GetAuthorizationUrlOptions {
- const storageKey = getStorageKey(clientId, prefix);
- const storedString = sessionStorage.getItem(storageKey);
- sessionStorage.removeItem(storageKey);
-
- try {
- return JSON.parse(storedString as string);
- } catch (error) {
- throw new Error('Stored values for Auth URL could not be parsed');
- }
-}
diff --git a/packages/javascript-sdk/src/session-manager/index.ts b/packages/javascript-sdk/src/session-manager/index.ts
deleted file mode 100644
index 8a65903a7..000000000
--- a/packages/javascript-sdk/src/session-manager/index.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { ConfigOptions } from '../config/index';
-import Config from '../config/index';
-import { REQUESTED_WITH, X_REQUESTED_PLATFORM } from '../shared/constants';
-import { isOkOr4xx } from '../util/http';
-import { withTimeout } from '../util/timeout';
-import { ActionTypes } from '../config/enums';
-import middlewareWrapper from '../util/middleware';
-import { getEndpointPath, resolve } from '../util/url';
-
-/**
- * Provides access to the session management API.
- */
-abstract class SessionManager {
- /**
- * Ends the current session.
- */
- public static async logout(options?: ConfigOptions): Promise {
- const { middleware, platformHeader, realmPath, serverConfig } = Config.get(options);
- const init: RequestInit = {
- credentials: 'include',
- headers: new Headers({
- 'Accept-API-Version': 'protocol=1.0,resource=2.0',
- 'X-Requested-With': REQUESTED_WITH,
- }),
- method: 'POST',
- };
-
- const path = `${getEndpointPath('sessions', realmPath, serverConfig.paths)}?_action=logout`;
- const url = resolve(serverConfig.baseUrl, path);
-
- const runMiddleware = middlewareWrapper(
- { url: new URL(url), init },
- { type: ActionTypes.Logout },
- );
- const req = runMiddleware(middleware);
-
- /**
- * Run after as to now allow mutation by user
- * Since the init headers can be an array, object or Headers class,
- * we need to handle all types.
- */
- if (platformHeader) {
- if (req.init.headers instanceof Headers) {
- req.init.headers.set('X-Requested-Platform', X_REQUESTED_PLATFORM);
- } else if (Array.isArray(req.init.headers)) {
- req.init.headers.push(['X-Requested-Platform', X_REQUESTED_PLATFORM]);
- } else if (req.init.headers) {
- req.init.headers['X-Requested-Platform'] = X_REQUESTED_PLATFORM;
- } else {
- req.init.headers = {
- 'X-Requested-Platform': X_REQUESTED_PLATFORM,
- };
- }
- }
-
- const response = await withTimeout(fetch(req.url.toString(), req.init), serverConfig.timeout);
- if (!isOkOr4xx(response)) {
- throw new Error(`Failed to log out; received ${response.status}`);
- }
- return response;
- }
-}
-
-export default SessionManager;
diff --git a/packages/javascript-sdk/src/shared/constants.ts b/packages/javascript-sdk/src/shared/constants.ts
deleted file mode 100644
index e0d617f1e..000000000
--- a/packages/javascript-sdk/src/shared/constants.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * constants.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/**
- * @module
- * @ignore
- * These are private constants
- */
-const REQUESTED_WITH = 'forgerock-sdk';
-const X_REQUESTED_PLATFORM = 'javascript';
-
-export { REQUESTED_WITH, X_REQUESTED_PLATFORM };
diff --git a/packages/javascript-sdk/src/shared/interfaces.ts b/packages/javascript-sdk/src/shared/interfaces.ts
deleted file mode 100644
index d8a5e8139..000000000
--- a/packages/javascript-sdk/src/shared/interfaces.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * interfaces.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-interface StringDict {
- [name: string]: T;
-}
-
-interface Tokens {
- accessToken: string;
- idToken?: string;
- refreshToken?: string;
- tokenExpiry?: number;
-}
-
-export type { StringDict, Tokens };
diff --git a/packages/javascript-sdk/src/shared/types.ts b/packages/javascript-sdk/src/shared/types.ts
deleted file mode 100644
index 2728a5353..000000000
--- a/packages/javascript-sdk/src/shared/types.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * types.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/**
- * @module
- * @ignore
- * These are private utility functions
- */
-type Noop = () => void;
-
-export type { Noop };
diff --git a/packages/javascript-sdk/src/token-manager/helpers.test.ts b/packages/javascript-sdk/src/token-manager/helpers.test.ts
deleted file mode 100644
index e09c21b92..000000000
--- a/packages/javascript-sdk/src/token-manager/helpers.test.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * helpers.test.ts
- *
- * Copyright (c) 2022 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-import { vi, afterAll, expect, describe, it, beforeAll } from 'vitest';
-import { tokensWillExpireWithinThreshold } from './helpers';
-import {
- oauthThreshold,
- tokenExpiryWithinThreshold,
- tokenExpiryOutsideThreshold,
- tokenExpiryNotSet,
-} from './token-manager.mock.data';
-
-describe('Test Token Manager utils', () => {
- // We want to avoid race conditions between expected and actual date values
- beforeAll(() => {
- // Override date functions to return a static date temporarily
- vi.useFakeTimers();
- vi.setSystemTime(new Date('25 Mar 2022 16:50:00 GMT').getTime());
- });
-
- it('Should return true if tokens expire within configured threshold', () => {
- const expiresSoon = tokensWillExpireWithinThreshold(
- oauthThreshold,
- Date.now() + tokenExpiryWithinThreshold,
- );
- expect(expiresSoon).toBe(true);
- });
-
- it('Should return false if tokens expire outside configured threshold', () => {
- const expiresSoon = tokensWillExpireWithinThreshold(
- oauthThreshold,
- Date.now() + tokenExpiryOutsideThreshold,
- );
- expect(expiresSoon).toBe(false);
- });
-
- it('Should return false if token expiry is not set', () => {
- const expiresSoon = tokensWillExpireWithinThreshold(
- oauthThreshold,
- Date.now() + tokenExpiryNotSet,
- );
- expect(expiresSoon).toBe(false);
- });
-
- afterAll(() => {
- // Reset timers
- vi.useRealTimers();
- });
-});
diff --git a/packages/javascript-sdk/src/token-manager/helpers.ts b/packages/javascript-sdk/src/token-manager/helpers.ts
deleted file mode 100644
index 1756d5ac9..000000000
--- a/packages/javascript-sdk/src/token-manager/helpers.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * helpers.ts
- *
- * Copyright (c) 2022 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/**
- * @module
- * @ignore
- * These are private utility functions for Token Manager
- */
-
-export function tokensWillExpireWithinThreshold(
- oauthThreshold?: number,
- tokenExpiry?: number,
-): boolean {
- if (oauthThreshold && tokenExpiry) {
- return tokenExpiry - oauthThreshold < Date.now();
- }
- return false;
-}
diff --git a/packages/javascript-sdk/src/token-manager/index.test.ts b/packages/javascript-sdk/src/token-manager/index.test.ts
deleted file mode 100644
index 0e8595339..000000000
--- a/packages/javascript-sdk/src/token-manager/index.test.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { vi, describe, it, expect } from 'vitest';
-import TokenManager from '.';
-import Config from '../config';
-import OAuth2Client from '../oauth2-client';
-
-vi.spyOn(OAuth2Client, 'getAuthCodeByIframe').mockImplementation(() => {
- return Promise.resolve('http://myapi.com?code=123&state=123');
-});
-// TokenManager.tokenExchange is private
-// so cast as any so typescript lets us spy.
-vi.spyOn(TokenManager as any, 'tokenExchange').mockImplementation(() => {
- return Promise.resolve('abctoken');
-});
-describe('TokenManager', () => {
- describe('getTokens', () => {
- it('should ensure if no options are passed in, tokens call can proceed', async () => {
- Config.set({
- clientId: '123',
- redirectUri: 'http://localhost:3000',
- scope: 'openid',
- serverConfig: {
- baseUrl: 'http://localhost:8080/am',
- timeout: 5000,
- },
- });
- const tokens = await TokenManager.getTokens();
- expect(tokens).toBe('abctoken');
- });
- });
-});
diff --git a/packages/javascript-sdk/src/token-manager/index.ts b/packages/javascript-sdk/src/token-manager/index.ts
deleted file mode 100644
index 3d553b78f..000000000
--- a/packages/javascript-sdk/src/token-manager/index.ts
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.ts
- *
- * Copyright (c) 2020-2021 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { ConfigOptions } from '../config';
-import Config from '../config';
-import { FRLogger } from '../util/logger';
-import type { OAuth2Tokens } from '../oauth2-client';
-import OAuth2Client, { allowedErrors, ResponseType } from '../oauth2-client';
-import type { StringDict, Tokens } from '../shared/interfaces';
-import TokenStorage from '../token-storage';
-import { generateAndStoreAuthUrlValues, getStoredAuthUrlValues } from '../oauth2-client/state-pkce';
-import { parseQuery } from '../util/url';
-import { tokensWillExpireWithinThreshold } from './helpers';
-
-interface GetTokensOptions extends ConfigOptions {
- forceRenew?: boolean;
- login?: 'embedded' | 'redirect' | undefined;
- query?: StringDict;
-}
-
-abstract class TokenManager {
- /**
- * Token Manager class that provides high-level abstraction for Authorization Code flow,
- * PKCE value generation, token exchange and token storage.
- *
- * Supports both embedded authentication as well as external authentication via redirects
- *
- Example 1:
-
- ```js
- const tokens = forgerock.TokenManager.getTokens({
- forceRenew: true, // If you want to get new tokens, despite existing ones
- login: 'embedded', // If user authentication is handled in-app
- serverConfig: {
- timeout: 5000,
- },
- });
- ```
-
- Example 2:
-
- ```js
- const tokens = forgerock.TokenManager.getTokens({
- forceRenew: false, // Will immediately return stored tokens, if they exist
- login: 'redirect', // If user authentication is handled in external Web app
- });
- ```
-
- Example 3:
-
- ```js
- const tokens = forgerock.TokenManager.getTokens({
- query: {
- code: 'lFJQYdoQG1u7nUm8 ... ', // Authorization code from redirect URL
- state: 'MTY2NDkxNTQ2Nde3D ... ', // State from redirect URL
- },
- });
- ```
- */
- public static async getTokens(options?: GetTokensOptions): Promise {
- const { clientId, oauthThreshold, prefix } = Config.get(options as ConfigOptions);
-
- if (!clientId) {
- throw new Error('Client ID is required');
- }
-
- /**
- * First, let's see if tokens exist locally
- */
- const tokens = await TokenStorage.get();
-
- /**
- * If tokens are stored, no option for `forceRenew` or `query` object with `code`, and do not expire within the configured threshold,
- * immediately return the stored tokens
- */
- if (
- tokens &&
- !options?.forceRenew &&
- !options?.query?.code &&
- !tokensWillExpireWithinThreshold(oauthThreshold, tokens.tokenExpiry)
- ) {
- return tokens;
- }
-
- /**
- * If we are still here because of forceRenew or we have an authorization code, or the tokens expire within the configured threshold,
- * revoke and delete existing tokens to prepare for the new ones
- */
- if (tokens) {
- try {
- await OAuth2Client.revokeToken(options);
- await TokenManager.deleteTokens();
- } catch (error) {
- FRLogger.warn('Existing tokens could not be revoked or deleted', error);
- }
- }
-
- /**
- * If authorization code and state are passed in, call token exchange
- * and return acquired tokens
- */
- if (options?.query?.code && options?.query?.state) {
- const { state, verifier } = getStoredAuthUrlValues(clientId, prefix);
-
- if (state === undefined || verifier === undefined) {
- throw new Error(
- '`state` and/or `verifier` not found in sessionStorage. Debugging: sessionStorage is not accessible in separate tabs.',
- );
- }
- return await this.tokenExchange(options, { state, verifier });
- }
-
- // so to not change the type of the above function
- // we assign it here if its undefined or null.
- const config = Object.assign({}, options);
- delete config.forceRenew;
-
- /**
- * Generate state and verifier for PKCE
- */
- const [pkceValues, storePkceValues] = generateAndStoreAuthUrlValues({
- ...config,
- clientId,
- prefix,
- responseType: ResponseType.Code,
- });
-
- /**
- * Attempt to call the authorize URL to retrieve authorization code
- */
- try {
- // Check expected browser support
- // To support legacy browsers, iframe works best with short timeout
- const parsedUrl = new URL(await OAuth2Client.getAuthCodeByIframe(pkceValues));
-
- // Throw if we have an error param or have no authorization code
- if (parsedUrl.searchParams.get('error')) {
- throw Error(`${parsedUrl.searchParams.get('error_description')}`);
- } else if (!parsedUrl.searchParams.get('code')) {
- throw Error(allowedErrors.AuthenticationConsentRequired);
- }
-
- const parsedQuery = parseQuery(parsedUrl.toString());
-
- if (!options) {
- options = {};
- }
- options.query = parsedQuery;
- } catch (err) {
- // If authorize request fails, handle according to `login` type
- if (!(err instanceof Error) || options?.login !== 'redirect') {
- // Throw for any error if login is NOT of type "redirect"
- throw err;
- }
-
- // Check if error is not one of our allowed errors
- if (
- allowedErrors.AuthenticationIsRequired !== err.message &&
- allowedErrors.AuthenticationConsentRequired !== err.message &&
- allowedErrors.AuthorizationTimeout !== err.message &&
- allowedErrors.FailedToFetch !== err.message &&
- allowedErrors.NetworkError !== err.message &&
- allowedErrors.InteractionNotAllowed !== err.message &&
- allowedErrors.RequestRequiresConsent !== err.message &&
- // Check for Ping Identity Login Required error
- // Long message, so just check substring
- !err.message.includes(allowedErrors.LoginRequired) &&
- // Safari has a very long error message, so we check for a substring
- !err.message.includes(allowedErrors.CORSError)
- ) {
- // Throw if the error is NOT an explicitly allowed error along with redirect of true
- // as that is a normal response and just requires a redirect
- throw err;
- }
-
- const authorizeUrl = await OAuth2Client.createAuthorizeUrl(pkceValues);
-
- // Before redirecting, store PKCE values
- storePkceValues();
-
- return location.assign(authorizeUrl);
- }
- /**
- * Exchange authorization code for tokens
- */
- return await this.tokenExchange(options, {
- state: pkceValues.state,
- verifier: pkceValues.verifier,
- });
- }
-
- public static async deleteTokens(): Promise {
- await TokenStorage.remove();
- }
-
- private static async tokenExchange(
- options: GetTokensOptions,
- stored: { state: string; verifier: string },
- ): Promise {
- /**
- * Ensure incoming state and stored state are equal and authorization code exists
- */
- if (options.query?.state !== stored.state) {
- throw new Error('State mismatch');
- }
- if (!options.query?.code || Array.isArray(options.query?.code)) {
- throw new Error('Failed to acquire authorization code');
- }
-
- /**
- * Generate token exchange options
- */
- const authorizationCode = options.query?.code;
- const verifier = stored.verifier;
- const getTokensOptions = { ...options, authorizationCode, verifier };
- const tokens = await OAuth2Client.getOAuth2Tokens(getTokensOptions);
-
- if (!tokens || !tokens.accessToken) {
- throw new Error('Unable to exchange authorization for tokens');
- }
-
- try {
- await TokenStorage.set(tokens);
- } catch (error) {
- FRLogger.error('Failed to store tokens', error);
- }
-
- return tokens;
- }
-}
-
-export default TokenManager;
-export type { GetTokensOptions };
diff --git a/packages/javascript-sdk/src/token-manager/token-manager.mock.data.ts b/packages/javascript-sdk/src/token-manager/token-manager.mock.data.ts
deleted file mode 100644
index d0814e9f2..000000000
--- a/packages/javascript-sdk/src/token-manager/token-manager.mock.data.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * token-manager.mock.data.ts
- *
- * Copyright (c) 2022 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-export const oauthThreshold = 120000;
-export const tokenExpiryWithinThreshold = 60000;
-export const tokenExpiryOutsideThreshold = 180000;
-export const tokenExpiryNotSet = undefined;
diff --git a/packages/javascript-sdk/src/token-storage/constants.ts b/packages/javascript-sdk/src/token-storage/constants.ts
deleted file mode 100644
index 7a8000740..000000000
--- a/packages/javascript-sdk/src/token-storage/constants.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * constants.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/**
- * @module
- * @ignore
- * These are private constants for TokenStorage
- */
-
-/** @hidden */
-const TOKEN_KEY = 'tokens';
-
-export { TOKEN_KEY };
diff --git a/packages/javascript-sdk/src/token-storage/index.ts b/packages/javascript-sdk/src/token-storage/index.ts
deleted file mode 100644
index e9f085724..000000000
--- a/packages/javascript-sdk/src/token-storage/index.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.ts
- *
- * Copyright (c) 2020-2021 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import Config from '../config/index';
-import { FRLogger } from '../util/logger';
-import type { TokenStoreObject } from '../config/interfaces';
-import LocalStorageWrapper from './local-storage';
-import SessionStorageWrapper from './session-storage';
-import type { Tokens } from '../shared/interfaces';
-
-/**
- * Provides access to the token storage API.
- * The type of storage (localStorage, sessionStorage, etc) can be configured
- * through `tokenStore` object on the SDK configuration.
- */
-abstract class TokenStorage {
- /**
- * Gets stored tokens.
- */
- public static async get(): Promise {
- const { clientId, tokenStore } = this.getClientConfig();
-
- if (tokenStore === 'sessionStorage') {
- return await SessionStorageWrapper.get(clientId);
- } else if (tokenStore === 'localStorage') {
- return await LocalStorageWrapper.get(clientId);
-
- // Preserving this condition for communicating its removal
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore
- } else if (tokenStore === 'indexedDB') {
- FRLogger.warn('IndexedDB is not supported in this version.');
- } else if (tokenStore && tokenStore.get) {
- // User supplied token store
- return await tokenStore.get(clientId);
- }
- return await LocalStorageWrapper.get(clientId);
- }
-
- /**
- * Saves tokens.
- */
- public static async set(tokens: Tokens): Promise {
- const { clientId, tokenStore } = this.getClientConfig();
-
- if (tokenStore === 'sessionStorage') {
- return await SessionStorageWrapper.set(clientId, tokens);
- } else if (tokenStore === 'localStorage') {
- return await LocalStorageWrapper.set(clientId, tokens);
-
- // Preserving this condition for communicating its removal
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore
- } else if (tokenStore === 'indexedDB') {
- FRLogger.warn('IndexedDB is not supported in this version.');
- } else if (tokenStore && tokenStore.set) {
- // User supplied token store
- return await tokenStore.set(clientId, tokens);
- }
- return await LocalStorageWrapper.set(clientId, tokens);
- }
-
- /**
- * Removes stored tokens.
- */
- public static async remove(): Promise {
- const { clientId, tokenStore } = this.getClientConfig();
-
- if (tokenStore === 'sessionStorage') {
- return await SessionStorageWrapper.remove(clientId);
- } else if (tokenStore === 'localStorage') {
- return await LocalStorageWrapper.remove(clientId);
-
- // Preserving this condition for communicating its removal
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore
- } else if (tokenStore === 'indexedDB') {
- FRLogger.warn('IndexedDB is not supported in this version.');
- } else if (tokenStore && tokenStore.remove) {
- // User supplied token store
- return await tokenStore.remove(clientId);
- }
- return await LocalStorageWrapper.remove(clientId);
- }
-
- private static getClientConfig(): {
- clientId: string;
- tokenStore: TokenStoreObject | 'sessionStorage' | 'localStorage' | undefined;
- } {
- const { clientId = 'unconfiguredClient', tokenStore = 'localStorage' } = Config.get();
-
- return { clientId, tokenStore };
- }
-}
-
-export default TokenStorage;
diff --git a/packages/javascript-sdk/src/token-storage/interfaces.ts b/packages/javascript-sdk/src/token-storage/interfaces.ts
deleted file mode 100644
index 0a69cff8d..000000000
--- a/packages/javascript-sdk/src/token-storage/interfaces.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * interfaces.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { Tokens } from '../shared/interfaces';
-
-/** @hidden */
-interface TokenDbEventTarget extends EventTarget {
- result?: Tokens;
-}
-
-/** @hidden */
-interface TokenDbEvent extends Event {
- target: TokenDbEventTarget | null;
-}
-
-export type { TokenDbEvent, TokenDbEventTarget };
diff --git a/packages/javascript-sdk/src/token-storage/local-storage.ts b/packages/javascript-sdk/src/token-storage/local-storage.ts
deleted file mode 100644
index 4c8106ace..000000000
--- a/packages/javascript-sdk/src/token-storage/local-storage.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * local-storage.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { Tokens } from '../shared/interfaces';
-import Config from '../config';
-
-/**
- * Provides wrapper for tokens with localStorage.
- */
-abstract class LocalStorageWrapper {
- /**
- * Retrieve tokens.
- */
- public static async get(clientId: string): Promise {
- const tokenString = localStorage.getItem(`${Config.get().prefix}-${clientId}`);
-
- // If there is no stored token, or the token is not an object, return null
- if (!tokenString) {
- // This is a normal state, so resolve with undefined
- return;
- }
-
- try {
- return JSON.parse(tokenString || '');
- } catch (err) {
- // This is an error state, so reject
- throw new Error('Could not parse token object from localStorage');
- }
- }
-
- /**
- * Saves tokens.
- */
- public static async set(clientId: string, tokens: Tokens): Promise {
- const tokenString = JSON.stringify(tokens);
- localStorage.setItem(`${Config.get().prefix}-${clientId}`, tokenString);
- }
-
- /**
- * Removes stored tokens.
- */
- public static async remove(clientId: string): Promise {
- localStorage.removeItem(`${Config.get().prefix}-${clientId}`);
- }
-}
-
-export default LocalStorageWrapper;
diff --git a/packages/javascript-sdk/src/token-storage/session-storage.ts b/packages/javascript-sdk/src/token-storage/session-storage.ts
deleted file mode 100644
index f6417d002..000000000
--- a/packages/javascript-sdk/src/token-storage/session-storage.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * session-storage.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { Tokens } from '../shared/interfaces';
-import Config from '../config';
-
-/**
- * Provides wrapper for tokens with sessionStorage.
- */
-abstract class SessionStorageWrapper {
- /**
- * Retrieve tokens.
- */
- public static async get(clientId: string): Promise {
- const tokenString = sessionStorage.getItem(`${Config.get().prefix}-${clientId}`);
-
- // If there is no stored token, or the token is not an object, return null
- if (!tokenString) {
- // This is a normal state, so resolve with undefined
- return;
- }
-
- try {
- return JSON.parse(tokenString || '');
- } catch (err) {
- // This is an error state, so reject
- throw new Error('Could not parse token from sessionStorage');
- }
- }
-
- /**
- * Saves tokens.
- */
- public static async set(clientId: string, tokens: Tokens): Promise {
- const tokenString = JSON.stringify(tokens);
- sessionStorage.setItem(`${Config.get().prefix}-${clientId}`, tokenString);
- }
-
- /**
- * Removes stored tokens.
- */
- public static async remove(clientId: string): Promise {
- sessionStorage.removeItem(`${Config.get().prefix}-${clientId}`);
- }
-}
-
-export default SessionStorageWrapper;
diff --git a/packages/javascript-sdk/src/typings.d.ts b/packages/javascript-sdk/src/typings.d.ts
deleted file mode 100644
index b0daa25c8..000000000
--- a/packages/javascript-sdk/src/typings.d.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * typings.d.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-interface Window {
- PublicKeyCredential: unknown;
-}
diff --git a/packages/javascript-sdk/src/typings.test.d.ts b/packages/javascript-sdk/src/typings.test.d.ts
deleted file mode 100644
index bd6f546bc..000000000
--- a/packages/javascript-sdk/src/typings.test.d.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * typings.test.d.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-declare module 'fake-indexeddb/auto';
diff --git a/packages/javascript-sdk/src/user-manager/index.ts b/packages/javascript-sdk/src/user-manager/index.ts
deleted file mode 100644
index 79b8b98fb..000000000
--- a/packages/javascript-sdk/src/user-manager/index.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * index.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { ConfigOptions } from '../config/interfaces';
-import OAuth2Client from '../oauth2-client';
-
-/**
- * Provides access to the current user's profile.
- */
-abstract class UserManager {
- /**
- * Gets the current user's profile.
- */
- public static getCurrentUser(options?: ConfigOptions): Promise {
- return OAuth2Client.getUserInfo(options);
- }
-}
-
-export default UserManager;
diff --git a/packages/javascript-sdk/src/util/deferred.ts b/packages/javascript-sdk/src/util/deferred.ts
deleted file mode 100644
index d5f7201fe..000000000
--- a/packages/javascript-sdk/src/util/deferred.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * deferred.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/**
- * Implementation of the Deferred API to simplify handling of Promises.
- */
-class Deferred {
- public promise: Promise;
- public resolve!: (value: T) => void;
- public reject!: (reason: unknown) => void;
-
- constructor() {
- this.promise = new Promise((resolve, reject) => {
- this.reject = reject;
- this.resolve = resolve;
- });
- }
-}
-
-export default Deferred;
diff --git a/packages/javascript-sdk/src/util/http.ts b/packages/javascript-sdk/src/util/http.ts
deleted file mode 100644
index 8e437111e..000000000
--- a/packages/javascript-sdk/src/util/http.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * http.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/**
- * @module
- * @ignore
- * These are private utility functions
- */
-function isOkOr4xx(response: Response): boolean {
- return response.ok || Math.floor(response.status / 100) === 4;
-}
-
-export { isOkOr4xx };
diff --git a/packages/javascript-sdk/src/util/logger.test.ts b/packages/javascript-sdk/src/util/logger.test.ts
deleted file mode 100644
index 4844984f3..000000000
--- a/packages/javascript-sdk/src/util/logger.test.ts
+++ /dev/null
@@ -1,322 +0,0 @@
-import { vi, describe, it, expect } from 'vitest';
-import { FRLogger } from './logger';
-import Config from '../config';
-import { LoggerFunctions } from '../config/interfaces';
-
-describe('Logger Class', () => {
- it('should instantiate with default log level when one is not passed in', () => {
- Config.set({
- serverConfig: {
- baseUrl: 'http://localhost:8080',
- },
- clientId: 'test',
- realmPath: 'alpha',
- });
- expect(FRLogger.enabled()).toEqual(0);
- });
- it('should instantiate with the log level that is passed in and verify if it should log', () => {
- Config.set({
- serverConfig: {
- baseUrl: 'http://localhost:8080',
- },
- clientId: 'test',
- realmPath: 'alpha',
- logLevel: 'info',
- });
- expect(FRLogger.enabled()).toEqual(75);
- });
- it('should call error method if logLevel allows it', () => {
- Config.set({
- serverConfig: {
- baseUrl: 'http://localhost:8080',
- },
- clientId: 'test',
- realmPath: 'alpha',
- logLevel: 'info',
- });
- const spy = vi.spyOn(FRLogger, 'error').mockImplementation();
- FRLogger.error('test');
- expect(spy).toHaveBeenCalled();
- spy.mockRestore();
- });
- it('should call warn if logLevel allows it', () => {
- Config.set({
- serverConfig: {
- baseUrl: 'http://localhost:8080',
- },
- clientId: 'test',
- realmPath: 'alpha',
- logLevel: 'info',
- });
- const spy = vi.spyOn(FRLogger, 'warn').mockImplementation();
- FRLogger.warn('test');
- expect(spy).toHaveBeenCalled();
- spy.mockRestore();
- });
- it('should call log if logLevel allows it', () => {
- Config.set({
- serverConfig: {
- baseUrl: 'http://localhost:8080',
- },
- clientId: 'test',
- realmPath: 'alpha',
- logLevel: 'info',
- });
- const spy = vi.spyOn(FRLogger, 'log').mockImplementation();
- FRLogger.log('test');
- expect(spy).toHaveBeenCalled();
- spy.mockRestore();
- });
- it('should not call error if logLevel does not allow it', () => {
- Config.set({
- serverConfig: {
- baseUrl: 'http://localhost:8080',
- },
- clientId: 'test',
- realmPath: 'alpha',
- logLevel: 'none',
- });
- const spy = vi.spyOn(console, 'error').mockImplementation();
- FRLogger.error('test');
- expect(spy).not.toHaveBeenCalled();
- spy.mockRestore();
- });
- it('should only call error when set to error', () => {
- Config.set({
- serverConfig: {
- baseUrl: 'http://localhost:8080',
- },
- clientId: 'test',
- realmPath: 'alpha',
- logLevel: 'error',
- });
- const spyError = vi.spyOn(console, 'error').mockImplementation();
- const spyWarn = vi.spyOn(console, 'warn').mockImplementation();
- const spyInfo = vi.spyOn(console, 'info').mockImplementation();
- FRLogger.log('info');
- expect(spyInfo).not.toHaveBeenCalled();
- FRLogger.warn('test');
- FRLogger.error('error');
- expect(spyWarn).not.toHaveBeenCalled();
- expect(spyError).toHaveBeenCalled();
- spyInfo.mockRestore();
- spyError.mockRestore();
- spyWarn.mockRestore();
- });
- it('should not call warn if logLevel does not allow it', () => {
- Config.set({
- serverConfig: {
- baseUrl: 'http://localhost:8080',
- },
- clientId: 'test',
- realmPath: 'alpha',
- logLevel: 'none',
- });
- const spy = vi.spyOn(console, 'warn').mockImplementation();
- FRLogger.warn('test');
- expect(spy).not.toHaveBeenCalled();
- spy.mockRestore();
- });
- it('should not call log if logLevel does not allow it', () => {
- Config.set({
- serverConfig: {
- baseUrl: 'http://localhost:8080',
- },
- clientId: 'test',
- realmPath: 'alpha',
- logLevel: 'none',
- });
- const spy = vi.spyOn(console, 'log').mockImplementation();
- FRLogger.log('test');
-
- expect(spy).not.toHaveBeenCalled();
- spy.mockRestore();
- });
- it('should allow a custom logger', () => {
- const myloggerFn: LoggerFunctions = {
- warn: vi.fn(),
- error: vi.fn(),
- log: vi.fn(),
- };
-
- Config.set({
- serverConfig: {
- baseUrl: 'http://localhost:8080',
- },
- clientId: 'test',
- realmPath: 'alpha',
- logLevel: 'debug',
- logger: myloggerFn,
- });
-
- FRLogger.warn('test');
- expect(myloggerFn.warn).toHaveBeenCalled();
-
- FRLogger.log('test');
- expect(myloggerFn.log).toHaveBeenCalled();
-
- FRLogger.error('test');
- expect(myloggerFn.error).toHaveBeenCalled();
- });
- it('should allow a custom logger but not call methods that arent allowed', () => {
- const myloggerFn: LoggerFunctions = {
- warn: vi.fn(),
- error: vi.fn(),
- log: vi.fn(),
- };
-
- Config.set({
- serverConfig: {
- baseUrl: 'http://localhost:8080',
- },
- clientId: 'test',
- realmPath: 'alpha',
- logLevel: 'error',
- logger: myloggerFn,
- });
-
- FRLogger.warn('test');
- expect(myloggerFn.warn).not.toHaveBeenCalled();
-
- FRLogger.log('test');
- expect(myloggerFn.log).not.toHaveBeenCalled();
-
- FRLogger.error('test');
- expect(myloggerFn.error).toHaveBeenCalled();
- });
- it('should use the hierarchy of log levels appropriately for warn', () => {
- Config.set({
- serverConfig: {
- baseUrl: 'http://localhost:8080',
- },
- clientId: 'test',
- realmPath: 'alpha',
- logLevel: 'warn',
- });
- const spyWarn = vi.spyOn(console, 'warn').mockImplementation();
- const spyError = vi.spyOn(console, 'error').mockImplementation();
- const spyLog = vi.spyOn(console, 'log').mockImplementation();
-
- FRLogger.warn('test');
- expect(console.warn).toHaveBeenCalled();
-
- FRLogger.log('test');
- expect(console.log).not.toHaveBeenCalled();
-
- FRLogger.error('test');
- expect(console.error).toHaveBeenCalled();
-
- spyWarn.mockReset();
- spyError.mockReset();
- spyLog.mockReset();
- });
- it('should use the hierarchy of log levels appropriately for info', () => {
- Config.set({
- serverConfig: {
- baseUrl: 'http://localhost:8080',
- },
- clientId: 'test',
- realmPath: 'alpha',
- logLevel: 'info',
- });
- const spyWarn = vi.spyOn(console, 'warn').mockImplementation();
- const spyError = vi.spyOn(console, 'error').mockImplementation();
- const spyLog = vi.spyOn(console, 'log').mockImplementation();
-
- FRLogger.warn('test');
- expect(console.warn).toHaveBeenCalled();
-
- FRLogger.log('test');
- expect(console.log).toHaveBeenCalled();
-
- FRLogger.error('test');
- expect(console.error).toHaveBeenCalled();
-
- spyWarn.mockReset();
- spyError.mockReset();
- spyLog.mockReset();
- });
- it('should use the hierarchy of log levels appropriately for debug', () => {
- Config.set({
- serverConfig: {
- baseUrl: 'http://localhost:8080',
- },
- clientId: 'test',
- realmPath: 'alpha',
- logLevel: 'debug',
- });
- const spyWarn = vi.spyOn(console, 'warn').mockImplementation();
- const spyError = vi.spyOn(console, 'error').mockImplementation();
- const spyLog = vi.spyOn(console, 'log').mockImplementation();
-
- FRLogger.warn('test');
- expect(console.warn).toHaveBeenCalled();
-
- FRLogger.log('test');
- expect(console.log).toHaveBeenCalled();
-
- FRLogger.error('test');
- expect(console.error).toHaveBeenCalled();
-
- spyWarn.mockReset();
- spyError.mockReset();
- spyLog.mockReset();
- });
- it('should use the hierarchy of log levels appropriately for error', () => {
- Config.set({
- serverConfig: {
- baseUrl: 'http://localhost:8080',
- },
- clientId: 'test',
- realmPath: 'alpha',
- logLevel: 'error',
- });
- const spyWarn = vi.spyOn(console, 'warn').mockImplementation();
- const spyError = vi.spyOn(console, 'error').mockImplementation();
- const spyLog = vi.spyOn(console, 'log').mockImplementation();
-
- FRLogger.warn('test');
- expect(console.warn).not.toHaveBeenCalled();
-
- FRLogger.log('test');
- expect(console.log).not.toHaveBeenCalled();
-
- FRLogger.error('test');
- expect(console.error).toHaveBeenCalled();
-
- spyWarn.mockReset();
- spyError.mockReset();
- spyLog.mockReset();
- });
- it('should use the hierarchy of log levels appropriately for info', () => {
- Config.set({
- serverConfig: {
- baseUrl: 'http://localhost:8080',
- },
- clientId: 'test',
- realmPath: 'alpha',
- logLevel: 'info',
- });
- const spyWarn = vi.spyOn(console, 'warn').mockImplementation();
- const spyError = vi.spyOn(console, 'error').mockImplementation();
- const spyLog = vi.spyOn(console, 'log').mockImplementation();
- const spyInfo = vi.spyOn(console, 'info').mockImplementation();
-
- FRLogger.warn('test');
- expect(console.warn).toHaveBeenCalled();
-
- FRLogger.log('test');
- expect(console.log).toHaveBeenCalled();
-
- FRLogger.info('info');
- expect(console.info).toHaveBeenCalled();
-
- FRLogger.error('test');
- expect(console.error).toHaveBeenCalled();
-
- spyInfo.mockReset();
- spyWarn.mockReset();
- spyError.mockReset();
- spyLog.mockReset();
- });
-});
diff --git a/packages/javascript-sdk/src/util/logger.ts b/packages/javascript-sdk/src/util/logger.ts
deleted file mode 100644
index a837d9402..000000000
--- a/packages/javascript-sdk/src/util/logger.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import Config from '../config/index';
-import { LogLevel } from '../config/interfaces';
-
-/*
- * Log “levels” are inclusive of its level and the level above.
- * error will log only error()
- * warn will log warn(), plus everything in error level
- * info will log info(), plus everything from warn level
- * debug will log everything
- * none will log nothing
- */
-type LogLevelRating = {
- ['none']: 0;
- ['error']: 25;
- ['warn']: 50;
- ['info']: 75;
- ['debug']: 100;
-};
-
-abstract class FRLogger {
- public static enabled(): LogLevelRating[LogLevel] {
- const { logLevel } = Config.get();
- /*
- * Return an object
- * which satisfies the LogLevelRating type
- * and has a key of the current log level
- * and a value of the log level rating
- */
- const logLevels = {
- none: 0,
- error: 25,
- warn: 50,
- info: 75,
- debug: 100,
- } satisfies LogLevelRating;
-
- return logLevels[logLevel];
- }
- static info(...msgs: unknown[]) {
- const { logger } = Config.get();
- if (this.enabled() >= 50) {
- if (logger && logger.info) {
- logger.info(...msgs);
- } else {
- console.info(...msgs);
- }
- }
- }
- static warn(...msgs: unknown[]) {
- const { logger } = Config.get();
- if (this.enabled() >= 50) {
- if (logger && logger.warn) {
- logger.warn(...msgs);
- } else {
- console.warn(...msgs);
- }
- }
- }
- static error(...msgs: unknown[]) {
- const { logger } = Config.get();
- if (this.enabled() >= 25) {
- if (logger && logger.error) {
- logger.error(...msgs);
- } else {
- console.error(...msgs);
- }
- }
- }
- static log(...msgs: unknown[]) {
- const { logger } = Config.get();
- if (this.enabled() >= 75) {
- if (logger && logger.log) {
- logger.log(...msgs);
- } else {
- console.log(...msgs);
- }
- }
- }
-}
-
-export { FRLogger };
diff --git a/packages/javascript-sdk/src/util/middleware.mock.data.ts b/packages/javascript-sdk/src/util/middleware.mock.data.ts
deleted file mode 100644
index 47aabd816..000000000
--- a/packages/javascript-sdk/src/util/middleware.mock.data.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * middleware.mock.data.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { Action, RequestMiddleware, RequestObj } from '../config/interfaces';
-import type { ActionTypes } from '../config/enums';
-
-type NextFn = () => RequestObj;
-
-const a = 'a' as ActionTypes;
-const b = 'b' as ActionTypes;
-const one = '1' as ActionTypes;
-const two = '2' as ActionTypes;
-const add = 'ADD' as ActionTypes;
-const reassignment = 'REASSIGNMENT' as ActionTypes;
-const mutateAction = 'MUTATE-ACTION' as ActionTypes;
-
-const middleware: RequestMiddleware[] = [
- (req: RequestObj, action: Action, next: NextFn): void => {
- switch (action.type) {
- case a:
- case b:
- req.url.searchParams.set('letter', 'true');
- req.init.headers = { ...{ 'x-letter': 'true' }, ...req.init.headers };
- break;
- case one:
- case two:
- req.url.searchParams.set('letter', 'false');
- req.init.headers = { ...{ 'x-letter': 'false' }, ...req.init.headers };
- break;
- }
- next();
- },
- (req: RequestObj, action: Action, next: NextFn): void => {
- switch (action.type) {
- case a:
- req.url.searchParams.set('char', 'a');
- req.init.headers = { ...{ 'x-char': 'a' }, ...req.init.headers };
- break;
- case b:
- req.url.searchParams.set('char', 'b');
- req.init.headers = { ...{ 'x-char': 'b' }, ...req.init.headers };
- break;
- }
- next();
- },
- (req: RequestObj, action: Action, next: NextFn): void => {
- switch (action.type) {
- case one:
- req.url.searchParams.set('char', '1');
- req.init.headers = { ...{ 'x-char': '1' }, ...req.init.headers };
- break;
- case two:
- req.url.searchParams.set('char', '2');
- req.init.headers = { ...{ 'x-char': '2' }, ...req.init.headers };
- break;
- }
- next();
- },
- (req: RequestObj, action: Action, next: NextFn): void => {
- switch (action.type) {
- case add:
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore
- req.init.headers = {
- ...{ 'x-char': 'a,' + action.payload },
- ...req.init.headers,
- };
- break;
- }
- next();
- },
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore
- (req: RequestObj, action: Action, next: NextFn): void => {
- switch (action.type) {
- case reassignment:
- req = {
- url: new URL('https://bad.com'),
- init: { headers: { 'x-bad': 'true' } },
- };
- break;
- }
- next();
- },
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore
- (req: RequestObj, action: Action, next: NextFn): void => {
- switch (action.type) {
- case mutateAction:
- action.type = 'hello' as ActionTypes;
- break;
- }
- next();
- },
-];
-
-export default middleware;
diff --git a/packages/javascript-sdk/src/util/middleware.test.ts b/packages/javascript-sdk/src/util/middleware.test.ts
deleted file mode 100644
index 41d6511e3..000000000
--- a/packages/javascript-sdk/src/util/middleware.test.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * middleware.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import middlewareWrapper from './middleware';
-import middleware from './middleware.mock.data';
-import type { ActionTypes } from '../config/enums';
-
-describe('Middleware should be called with an action', () => {
- it('should run all middleware testing action for letter and "a"', () => {
- const runMiddleware = middlewareWrapper(
- { url: new URL('https://www.example.com'), init: {} },
- {
- type: 'a' as ActionTypes,
- },
- );
- const newReq = runMiddleware(middleware);
- expect(newReq.init).toStrictEqual({
- headers: { 'x-letter': 'true', 'x-char': 'a' },
- });
- expect(newReq.url.toString()).toBe('https://www.example.com/?letter=true&char=a');
- });
- it('should run all middleware testing action for number and "1"', () => {
- const runMiddleware = middlewareWrapper(
- { url: new URL('https://www.example.com'), init: {} },
- {
- type: '1' as ActionTypes,
- },
- );
- const newReq = runMiddleware(middleware);
- expect(newReq.init).toStrictEqual({
- headers: { 'x-letter': 'false', 'x-char': '1' },
- });
- expect(newReq.url.toString()).toBe('https://www.example.com/?letter=false&char=1');
- });
- it('should run all middleware testing action for no match', () => {
- const runMiddleware = middlewareWrapper(
- { url: new URL('https://www.example.com'), init: {} },
- {
- type: 'z' as ActionTypes,
- },
- );
- const newReq = runMiddleware(middleware);
- expect(newReq.init).toStrictEqual({});
- expect(newReq.url.toString()).toBe('https://www.example.com/');
- });
- it('should run all middleware testing add action with payload', () => {
- const runMiddleware = middlewareWrapper(
- {
- url: new URL('https://www.example.com'),
- init: { headers: { 'x-number': '3' } },
- },
- {
- type: 'ADD' as ActionTypes,
- payload: 'b',
- },
- );
- const newReq = runMiddleware(middleware);
- expect(newReq.init).toStrictEqual({
- headers: { 'x-number': '3', 'x-char': 'a,b' },
- });
- });
- it('should not allow middleware to reassign `req`', () => {
- const runMiddleware = middlewareWrapper(
- { url: new URL('https://www.example.com'), init: {} },
- {
- type: 'REASSIGNMENT' as ActionTypes,
- },
- );
- const newReq = runMiddleware(middleware);
- expect(newReq.init).toStrictEqual({});
- expect(newReq.url.toString()).toBe('https://www.example.com/');
- });
- it('should not allow middleware to mutate `action`', () => {
- try {
- const runMiddleware = middlewareWrapper(
- { url: new URL('https://www.example.com'), init: {} },
- {
- type: 'MUTATE-ACTION' as ActionTypes,
- },
- );
- runMiddleware(middleware);
- } catch (err) {
- expect(err.message).toBe(`Cannot assign to read only property 'type' of object '#'`);
- }
- });
-});
diff --git a/packages/javascript-sdk/src/util/middleware.ts b/packages/javascript-sdk/src/util/middleware.ts
deleted file mode 100644
index 9d5f1686c..000000000
--- a/packages/javascript-sdk/src/util/middleware.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * middleware.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { RequestMiddleware, RequestObj } from '../config/interfaces';
-import type { ActionTypes } from '../config/enums';
-
-/**
- * @function middlewareWrapper - A "Node" and "Redux" style middleware that is called just before
- * the request is made from the SDK. This allows you access to the request for modification.
- * @param request - A request object container of the URL and the Request Init object
- * @param action - The action object that is passed into the middleware communicating intent
- * @param action.type - A "Redux" style type that contains the serialized action
- * @param action.payload - The payload of the action that can contain metadata
- * @returns {function} - Function that takes middleware parameter & runs middleware against request
- */
-function middlewareWrapper(
- request: RequestObj,
- // eslint-disable-next-line
- { type, payload }: { type: ActionTypes; payload?: any },
-): (middleware: RequestMiddleware[] | undefined) => RequestObj {
- // no mutation and no reassignment
- const actionCopy = Object.freeze({ type, payload });
-
- return (middleware: RequestMiddleware[] | undefined) => {
- if (!Array.isArray(middleware)) {
- return request;
- }
-
- // Copy middleware so the `shift` below doesn't mutate source
- const mwareCopy = middleware.map((fn) => fn);
-
- function iterator(): RequestObj {
- const nextMiddlewareToBeCalled = mwareCopy.shift();
- nextMiddlewareToBeCalled && nextMiddlewareToBeCalled(request, actionCopy, iterator);
- return request;
- }
-
- return iterator();
- };
-}
-
-export default middlewareWrapper;
diff --git a/packages/javascript-sdk/src/util/pkce.test.ts b/packages/javascript-sdk/src/util/pkce.test.ts
deleted file mode 100644
index 4a1ffbc92..000000000
--- a/packages/javascript-sdk/src/util/pkce.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * pkce.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/**
- * @jest-environment jsdom
- */
-import { expect, describe, it } from 'vitest';
-import * as crypto from 'crypto';
-import { TextEncoder } from 'util';
-import PKCE from './pkce';
-
-declare let window: unknown;
-
-Object.defineProperty(window, 'crypto', {
- value: {
- getRandomValues: (array: Buffer): Buffer => crypto.randomFillSync(array),
- subtle: {
- digest: (alg: string, array: Uint8Array): Buffer => {
- if (alg === 'SHA-256') {
- return crypto.createHash('sha256').update(array).digest();
- }
- throw new Error(`Unsupported algorithm "${alg}"`);
- },
- },
- },
-});
-
-Object.defineProperty(global, 'TextEncoder', {
- value: TextEncoder,
-});
-
-describe('The PKCE module', () => {
- it('creates verifiers and challenges in the correct format', async () => {
- const validChars = /[a-z0-9-_]/i;
- for (let i = 0; i < 100; i++) {
- const verifier = PKCE.createVerifier();
- expect(verifier).toMatch(validChars);
- expect(verifier.length).toBeGreaterThan(89);
-
- const challenge = await PKCE.createChallenge(verifier);
- expect(challenge).toMatch(validChars);
- }
- });
-});
diff --git a/packages/javascript-sdk/src/util/pkce.ts b/packages/javascript-sdk/src/util/pkce.ts
deleted file mode 100644
index c0b6f50de..000000000
--- a/packages/javascript-sdk/src/util/pkce.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * pkce.ts
- *
- * Copyright (c) 2020-2021 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/**
- * Helper class for generating verifier, challenge and state strings used for
- * Proof Key for Code Exchange (PKCE).
- */
-abstract class PKCE {
- /**
- * Creates a random state.
- */
- public static createState(): string {
- return this.createRandomString(16);
- }
-
- /**
- * Creates a random verifier.
- */
- public static createVerifier(): string {
- return this.createRandomString(32);
- }
-
- /**
- * Creates a SHA-256 hash of the verifier.
- *
- * @param verifier The verifier to hash
- */
- public static async createChallenge(verifier: string): Promise {
- const sha256 = await this.sha256(verifier);
- const challenge = this.base64UrlEncode(sha256);
- return challenge;
- }
-
- /**
- * Creates a base64 encoded, URL-friendly version of the specified array.
- *
- * @param array The array of numbers to encode
- */
- public static base64UrlEncode(array: Uint8Array): string {
- const numbers = Array.prototype.slice.call(array);
- const ascii = btoa(String.fromCharCode.apply(null, numbers));
- const urlEncoded = ascii.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
- return urlEncoded;
- }
-
- /**
- * Creates a SHA-256 hash of the specified string.
- *
- * @param value The string to hash
- */
- public static async sha256(value: string): Promise {
- const uint8Array = new TextEncoder().encode(value);
- const hashBuffer = await crypto.subtle.digest('SHA-256', uint8Array);
- const hashArray = new Uint8Array(hashBuffer);
- return hashArray;
- }
- /**
- * Creates a random string.
- *
- * @param size The number for entropy (default: 32)
- */
- private static createRandomString(num = 32): string {
- const random = new Uint8Array(num);
- crypto.getRandomValues(random);
- return btoa(random.join('')).replace(/[^a-zA-Z0-9]+/, '');
- }
-}
-
-export default PKCE;
diff --git a/packages/javascript-sdk/src/util/realm.test.ts b/packages/javascript-sdk/src/util/realm.test.ts
deleted file mode 100644
index 288925159..000000000
--- a/packages/javascript-sdk/src/util/realm.test.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * realm.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { getRealmUrlPath } from './realm';
-import { describe, it, expect } from 'vitest';
-
-describe('The realm utility', () => {
- it('creates the correct paths', () => {
- const tests = [
- [undefined, 'realms/root'],
- ['', 'realms/root'],
- ['root', 'realms/root'],
- ['foo', 'realms/root/realms/foo'],
- ['root/foo', 'realms/root/realms/foo'],
- ['foo/bar', 'realms/root/realms/foo/realms/bar'],
- ['foo/Bar', 'realms/root/realms/foo/realms/Bar'],
- ['/foo/baz/', 'realms/root/realms/foo/realms/baz'],
- [' /foo/baz ', 'realms/root/realms/foo/realms/baz'],
- [' foo / baz ', 'realms/root/realms/foo/realms/baz'],
- [' / foo / baz / ', 'realms/root/realms/foo/realms/baz'],
- ];
-
- tests.forEach((x) => {
- const urlPath = getRealmUrlPath(x[0]);
- expect(urlPath).toBe(x[1]);
- });
- });
-});
diff --git a/packages/javascript-sdk/src/util/realm.ts b/packages/javascript-sdk/src/util/realm.ts
deleted file mode 100644
index fbc128cb2..000000000
--- a/packages/javascript-sdk/src/util/realm.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * realm.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/** @hidden */
-function getRealmUrlPath(realmPath?: string): string {
- // Split the path and scrub segments
- const names = (realmPath || '')
- .split('/')
- .map((x) => x.trim())
- .filter((x) => x !== '');
-
- // Ensure 'root' is the first realm
- if (names[0] !== 'root') {
- names.unshift('root');
- }
-
- // Concatenate into a URL path
- const urlPath = names.map((x) => `realms/${x}`).join('/');
- return urlPath;
-}
-
-export { getRealmUrlPath };
diff --git a/packages/javascript-sdk/src/util/storage.ts b/packages/javascript-sdk/src/util/storage.ts
deleted file mode 100644
index a91f868ff..000000000
--- a/packages/javascript-sdk/src/util/storage.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * storage.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/** @hidden */
-class LocalStorage {
- private storage: Storage;
- constructor(persist = false) {
- this.storage = persist ? localStorage : sessionStorage;
- }
-
- public get(key: string): T | undefined {
- const value = this.storage.getItem(key);
- if (!value) {
- return undefined;
- }
-
- return JSON.parse(value);
- }
-
- public set(key: string, value: T): void {
- this.storage.setItem(key, JSON.stringify(value));
- }
-
- public remove(key: string): void {
- this.storage.removeItem(key);
- }
-}
-
-export default LocalStorage;
diff --git a/packages/javascript-sdk/src/util/strings.ts b/packages/javascript-sdk/src/util/strings.ts
deleted file mode 100644
index 045f8b0b6..000000000
--- a/packages/javascript-sdk/src/util/strings.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * strings.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-/**
- * @module
- * @ignore
- * These are private utility functions
- */
-export function plural(n: number, singularText: string, pluralText?: string): string {
- if (n === 1) {
- return singularText;
- }
- return pluralText !== undefined ? pluralText : singularText + 's';
-}
diff --git a/packages/javascript-sdk/src/util/timeout.test.ts b/packages/javascript-sdk/src/util/timeout.test.ts
deleted file mode 100644
index 4b2b503ea..000000000
--- a/packages/javascript-sdk/src/util/timeout.test.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * timeout.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { withTimeout } from './timeout';
-
-describe('withTimeout function', () => {
- it('should return the promise passed', async () => {
- const promise = new Promise((res) => res('ok'));
- const result = await withTimeout(promise, 500);
- expect(result).toBe('ok');
- });
- it('should return the promise passed if it rejects', async () => {
- const promise = new Promise((_, rej) => rej('rejected'));
- expect(withTimeout(promise, 500)).rejects.toBe('rejected');
- });
- it('should return the window timeout', async () => {
- const promise = new Promise(() => 'ok');
- await withTimeout(promise, 1).catch((res) => expect(res).toEqual(new Error('Timeout')));
- });
-});
diff --git a/packages/javascript-sdk/src/util/timeout.ts b/packages/javascript-sdk/src/util/timeout.ts
deleted file mode 100644
index 60871cfc8..000000000
--- a/packages/javascript-sdk/src/util/timeout.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * timeout.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { DEFAULT_TIMEOUT } from '../config/constants';
-
-/**
- * @module
- * @ignore
- * These are private utility functions
- */
-function withTimeout(promise: Promise, timeout: number = DEFAULT_TIMEOUT): Promise {
- const effectiveTimeout = timeout || DEFAULT_TIMEOUT;
- const timeoutP = new Promise((_, reject) =>
- setTimeout(() => reject(new Error('Timeout')), effectiveTimeout),
- );
-
- return Promise.race([promise, timeoutP]);
-}
-
-export { withTimeout };
diff --git a/packages/javascript-sdk/src/util/url.test.ts b/packages/javascript-sdk/src/util/url.test.ts
deleted file mode 100644
index 039ea2395..000000000
--- a/packages/javascript-sdk/src/util/url.test.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * url.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { getBaseUrl, parseQuery, resolve, stringify } from './url';
-
-describe('The URL utility', () => {
- const querystrings = {
- '': {},
- 'foo=bar': { foo: 'bar' },
- 'foo=bar&goo=baz': { foo: 'bar', goo: 'baz' },
- 'foo=b%20r': { foo: 'b r' },
- };
-
- it('correctly determines base URL', () => {
- const tests = [
- ['http://domain.com', 'http://domain.com'],
- ['http://domain.com/', 'http://domain.com'],
- ['http://domain.com:80', 'http://domain.com'],
- ['http://domain.com:80/', 'http://domain.com'],
- ['http://domain.com:81', 'http://domain.com:81'],
- ['http://domain.com:81/', 'http://domain.com:81'],
- ['https://domain.com', 'https://domain.com'],
- ['https://domain.com/', 'https://domain.com'],
- ['https://domain.com:443', 'https://domain.com'],
- ['https://domain.com:443/', 'https://domain.com'],
- ['https://domain.com:8443', 'https://domain.com:8443'],
- ['https://domain.com:8443/', 'https://domain.com:8443'],
- ];
-
- tests.forEach((x) => {
- const url = new URL(x[0]);
- const actual = getBaseUrl(url);
- expect(actual).toBe(x[1]);
- });
- });
-
- it('correctly resolves paths', () => {
- const baseUrls = [
- 'http://domain.com',
- 'http://domain.com/',
- 'https://domain.com:8443',
- 'https://domain.com:8443/',
- ];
- const basePath = '/a/b/c';
-
- baseUrls.forEach((baseUrl) => {
- const baseUrlWithoutSlash = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
-
- const tests = [
- ['', `${baseUrlWithoutSlash}/a/b`],
- ['foo', `${baseUrlWithoutSlash}/a/b/foo`],
- ['/foo', `${baseUrlWithoutSlash}/foo`],
- ['foo/baz', `${baseUrlWithoutSlash}/a/b/foo/baz`],
- ['/foo/baz', `${baseUrlWithoutSlash}/foo/baz`],
- ];
-
- tests.forEach((x) => {
- const actual = resolve(baseUrlWithoutSlash + basePath, x[0]);
- expect(actual).toBe(x[1]);
- });
- });
- });
-
- it('correctly parses a querystring', () => {
- const baseUrl = 'http://domain.com?';
- for (const t in querystrings) {
- const actual = parseQuery(baseUrl + t);
- expect(actual).toStrictEqual(querystrings[t]);
- }
- });
-
- it('correctly serializes a querystring', () => {
- for (const t in querystrings) {
- const actual = stringify(querystrings[t]);
- expect(actual).toStrictEqual(t);
- }
- });
-});
diff --git a/packages/javascript-sdk/src/util/url.ts b/packages/javascript-sdk/src/util/url.ts
deleted file mode 100644
index d70896ffb..000000000
--- a/packages/javascript-sdk/src/util/url.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * url.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { ConfigurablePaths, CustomPathConfig } from '../config/interfaces';
-import type { StringDict } from '../shared/interfaces';
-import { getRealmUrlPath } from '../util/realm';
-
-/**
- * Returns the base URL including protocol, hostname and any non-standard port.
- * The returned URL does not include a trailing slash.
- */
-function getBaseUrl(url: URL): string {
- const isNonStandardPort =
- (url.protocol === 'http:' && ['', '80'].indexOf(url.port) === -1) ||
- (url.protocol === 'https:' && ['', '443'].indexOf(url.port) === -1);
- const port = isNonStandardPort ? `:${url.port}` : '';
- const baseUrl = `${url.protocol}//${url.hostname}${port}`;
- return baseUrl;
-}
-
-function getEndpointPath(
- endpoint: ConfigurablePaths,
- realmPath?: string,
- customPaths?: CustomPathConfig,
-): string {
- const realmUrlPath = getRealmUrlPath(realmPath);
- const defaultPaths = {
- authenticate: `json/${realmUrlPath}/authenticate`,
- authorize: `oauth2/${realmUrlPath}/authorize`,
- accessToken: `oauth2/${realmUrlPath}/access_token`,
- endSession: `oauth2/${realmUrlPath}/connect/endSession`,
- userInfo: `oauth2/${realmUrlPath}/userinfo`,
- revoke: `oauth2/${realmUrlPath}/token/revoke`,
- sessions: `json/${realmUrlPath}/sessions/`,
- };
- if (customPaths && customPaths[endpoint]) {
- // TypeScript is not correctly reading the condition above
- // It's thinking that customPaths[endpoint] may result in undefined
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore
- return customPaths[endpoint];
- } else {
- return defaultPaths[endpoint];
- }
-}
-
-function resolve(baseUrl: string, path: string): string {
- const url = new URL(baseUrl);
-
- if (path.startsWith('/')) {
- return `${getBaseUrl(url)}${path}`;
- }
-
- const basePath = url.pathname.split('/');
- const destPath = path.split('/').filter((x) => !!x);
- const newPath = [...basePath.slice(0, -1), ...destPath].join('/');
-
- return `${getBaseUrl(url)}${newPath}`;
-}
-
-function parseQuery(fullUrl: string): StringDict {
- const url = new URL(fullUrl);
- const query: StringDict = {};
- url.searchParams.forEach((v, k) => (query[k] = v));
- return query;
-}
-
-function stringify(data: StringDict): string {
- const pairs: string[] = [];
- for (const k in data) {
- if (data[k]) {
- pairs.push(k + '=' + encodeURIComponent(data[k] as string));
- }
- }
- return pairs.join('&');
-}
-
-export { getBaseUrl, getEndpointPath, parseQuery, resolve, stringify };
diff --git a/packages/javascript-sdk/tests/integration/fr-auth.mock.data.ts b/packages/javascript-sdk/tests/integration/fr-auth.mock.data.ts
deleted file mode 100644
index 8e2065aa3..000000000
--- a/packages/javascript-sdk/tests/integration/fr-auth.mock.data.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * fr-auth.mock.data.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { CallbackType } from '../../src/auth/enums';
-import type { Step } from '../../src/auth/interfaces';
-
-export const jsonResponse: Step = {
- authId: 'unused',
- callbacks: [
- {
- type: CallbackType.NameCallback,
- output: [{ name: 'prompt', value: 'User Name' }],
- input: [{ name: 'IDToken1', value: '' }],
- _id: 0,
- },
- {
- type: CallbackType.PasswordCallback,
- output: [{ name: 'prompt', value: 'Password' }],
- input: [{ name: 'IDToken2', value: '' }],
- _id: 1,
- },
- ],
- stage: 'UsernamePassword',
-};
-
-export const rawResponse = {
- body: {},
- bodyUsed: true,
- headers: {
- get(): string {
- return 'application/json';
- },
- },
- json(): Step {
- return jsonResponse;
- },
- ok: true,
- redirected: false,
- status: 200,
- statusText: '',
- type: 'cors',
- url:
- // eslint-disable-next-line max-len
- 'https://openam-devjustin2.forgeblocks.com/am/json/realms/root/authenticate?authIndexType=service&authIndexValue=UsernamePassword',
-};
-
-export const loginSubmission = {
- payload: {
- authId: 'unused',
- callbacks: [
- {
- type: 'NameCallback',
- output: [{ name: 'prompt', value: 'User Name' }],
- input: [{ name: 'IDToken1', value: 'jsmith' }],
- _id: 0,
- },
- {
- type: 'PasswordCallback',
- output: [{ name: 'prompt', value: 'Password' }],
- input: [{ name: 'IDToken2', value: 'Password1!' }],
- _id: 1,
- },
- ],
- stage: 'UsernamePassword',
- },
- callbacks: [
- {
- payload: {
- type: 'NameCallback',
- output: [{ name: 'prompt', value: 'User Name' }],
- input: [{ name: 'IDToken1', value: 'jsmith' }],
- _id: 0,
- },
- },
- {
- payload: {
- type: 'PasswordCallback',
- output: [{ name: 'prompt', value: 'Password' }],
- input: [{ name: 'IDToken2', value: 'Password1!' }],
- _id: 1,
- },
- },
- ],
-};
diff --git a/packages/javascript-sdk/tests/integration/fr-auth.test.ts b/packages/javascript-sdk/tests/integration/fr-auth.test.ts
deleted file mode 100644
index 5ff76d65d..000000000
--- a/packages/javascript-sdk/tests/integration/fr-auth.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * fr-auth.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import { vi, expect, describe, it, afterAll } from 'vitest';
-import type PasswordCallback from '../../src/fr-auth/callbacks/password-callback';
-import { CallbackType } from '../../src/auth/enums';
-import Config from '../../src/config/index';
-import FRAuth from '../../src/fr-auth/index';
-import type NameCallback from '../../src/fr-auth/callbacks/name-callback';
-import type FRStep from '../../src/fr-auth/fr-step';
-import { rawResponse } from './fr-auth.mock.data';
-
-vi.mock('../../src/config/index', () => {
- return {
- default: {
- set: (conf) => conf,
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
- get() {
- return {
- serverConfig: {
- baseUrl: 'https://openam.example.com/am/',
- timeout: 0,
- },
- };
- },
- },
- };
-});
-
-afterAll(() => {
- vi.clearAllMocks();
- vi.resetModules();
-});
-describe('Test FRAuth.next functionality', () => {
- it('should be able to make initial next step', async () => {
- global.fetch = vi.fn().mockImplementation(() => rawResponse);
- console.log(JSON.stringify(Config.set));
- Config.set({
- serverConfig: {
- baseUrl: 'http://am.example.com',
- timeout: 3000,
- },
- });
-
- const step = await FRAuth.next();
- const stage = (step as FRStep).getStage();
- ((step as FRStep).getCallbackOfType(CallbackType.NameCallback) as NameCallback).setName(
- 'jsmith',
- );
- (
- (step as FRStep).getCallbackOfType(CallbackType.PasswordCallback) as PasswordCallback
- ).setPassword('Password1!');
-
- expect(stage).toBe('UsernamePassword');
- expect(step.payload.callbacks![0].input![0].name).toBe('IDToken1');
- expect(step.payload.callbacks![0].input![0].value).toBe('jsmith');
- expect(step.payload.callbacks![1].input![0].name).toBe('IDToken2');
- expect(step.payload.callbacks![1].input![0].value).toBe('Password1!');
- });
-});
diff --git a/packages/javascript-sdk/tests/integration/http-client.mock.data.ts b/packages/javascript-sdk/tests/integration/http-client.mock.data.ts
deleted file mode 100644
index ad41883b7..000000000
--- a/packages/javascript-sdk/tests/integration/http-client.mock.data.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * http-client.mock.data.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-
-import type { HandleStep } from '../../src/http-client/interfaces';
-
-export const authzByTreeReqOptionsForIG = {
- init: {
- credentials: 'include' as const,
- method: 'POST',
- },
- authorization: {
- handleStep: {} as HandleStep,
- config: {
- serverConfig: {
- baseUrl: 'https://openam.example.com/am/',
- timeout: 0,
- },
- },
- },
- timeout: 0,
- url: 'https://request-auth-by-txn.com/ig',
-};
-
-export const authzByTreeReqOptionsForREST = {
- init: {
- credentials: 'include' as const,
- method: 'POST',
- },
- authorization: {
- handleStep: {} as HandleStep,
- config: {
- serverConfig: {
- baseUrl: 'https://openam.example.com/am/',
- timeout: 0,
- },
- },
- },
- timeout: 0,
- url: 'https://request-auth-by-txn.com/rest',
-};
-
-export const authzByTxnReqOptionsForIG = {
- init: {
- credentials: 'include' as const,
- method: 'POST',
- },
- authorization: {
- handleStep: {} as HandleStep,
- config: {
- serverConfig: {
- baseUrl: 'https://openam.example.com/am/',
- timeout: 0,
- },
- },
- },
- timeout: 0,
- url: 'https://request-auth-by-txn.com/ig',
-};
-
-export const authzByTxnReqOptionsForREST = {
- init: {
- credentials: 'include' as const,
- method: 'POST',
- },
- authorization: {
- handleStep: {} as HandleStep,
- config: {
- serverConfig: {
- baseUrl: 'https://openam.example.com/am/',
- timeout: 0,
- },
- },
- },
- timeout: 0,
- url: 'https://request-auth-by-txn.com/rest',
-};
-
-export const responseFromAM = {
- clone() {
- return {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- json(): any {
- return Promise.resolve({
- callbacks: {},
- });
- },
- };
- },
- json() {
- return Promise.resolve({
- callbacks: {},
- });
- },
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
-} as any;
diff --git a/packages/javascript-sdk/tests/integration/http-client.test.ts b/packages/javascript-sdk/tests/integration/http-client.test.ts
deleted file mode 100644
index f09c5957f..000000000
--- a/packages/javascript-sdk/tests/integration/http-client.test.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * @forgerock/javascript-sdk
- *
- * http-client.test.ts
- *
- * Copyright (c) 2020 ForgeRock. All rights reserved.
- * This software may be modified and distributed under the terms
- * of the MIT license. See the LICENSE file for details.
- */
-import { vi, expect, describe, it, afterAll, beforeEach } from 'vitest';
-import HttpClient from '../../src/http-client/index';
-import TokenStorage from '../../src/token-storage/index';
-import {
- authzByTreeReqOptionsForREST,
- authzByTreeReqOptionsForIG,
- authzByTxnReqOptionsForREST,
- authzByTxnReqOptionsForIG,
- responseFromAM as mockResponseFromAM,
-} from './http-client.mock.data';
-import {
- /* jest requires mock variables guaranteed to be initialized out of scope of the mock
- * to be prefixed with mock
- * see: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
- * Note: This is a precaution to guard against uninitialized mock variables.
- * If it is ensured that the mock is required lazily, variable names prefixed with `mock`(case insensitive) are permitted.
- */
- authzByTreeResFromIG as mockAuthzByTreeResFromIG,
- authzByTreeResFromREST as mockAuthzByTreeResFromREST,
- authzByTxnResFromIG as mockAuthzByTxnResFromIG,
- authzByTxnResFromREST as mockAuthzByTxnResFromREST,
-} from '../../src/http-client/http-client.mock.data';
-
-// TODO: figure out how to move these mock functions in separate file
-// Because Jest hoists mocks above the imports, importing doesn't work :(
-vi.mock('../../src/token-storage/index');
-vi.mock('../../src/config/index', () => {
- return {
- default: {
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
- get() {
- return {
- serverConfig: {
- baseUrl: 'https://openam.example.com/am/',
- timeout: 0,
- },
- };
- },
- },
- };
-});
-
-vi.mock('../../src/http-client/index', async () => {
- const originalHttpClient = await vi.importActual('../../src/http-client/index');
- const mockResponse = vi.fn(function (options: any): Promise {
- if (options.url === 'https://request-auth-by-tree.com/ig') {
- return Promise.resolve(mockAuthzByTreeResFromIG);
- } else if (options.url === 'https://request-auth-by-tree.com/rest') {
- return Promise.resolve(mockAuthzByTreeResFromREST);
- } else if (options.url === 'https://request-auth-by-txn.com/ig') {
- return Promise.resolve(mockAuthzByTxnResFromIG);
- } else if (options.url === 'https://request-auth-by-txn.com/rest') {
- return Promise.resolve(mockAuthzByTxnResFromREST);
- }
- {
- return Promise.resolve(mockResponseFromAM);
- }
- });
- return {
- default: {
- request: (originalHttpClient.default as typeof HttpClient).request,
- stepIterator: vi.fn().mockResolvedValue({}),
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- _request: mockResponse,
- },
- };
-});
-
-describe('Test HttpClient request for txn auth', () => {
- const expectedTxnReq = {
- init: {
- credentials: 'include' as const,
- headers: {
- 'Accept-API-Version': 'resource=2.0, protocol=1.0',
- },
- method: 'POST',
- },
- timeout: 0,
- // eslint-disable-next-line max-len, prettier/prettier
- url: 'https://openam.example.com/am/json/realms/root/authenticate?authIndexType=composite_advice&authIndexValue=%3CAdvices%3E%3CAttributeValuePair%3E%3CAttribute%20name%3D%22TransactionConditionAdvice%22%2F%3E%3CValue%3Eabc%3C%2FValue%3E%3C%2FAttributeValuePair%3E%3C%2FAdvices%3E',
- };
-
- afterAll(() => {
- vi.clearAllMocks();
- });
- beforeEach(() => {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const mockedHttpClientRequest = HttpClient['_request'] as any;
- mockedHttpClientRequest.mockClear();
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore
- TokenStorage.get.mockResolvedValue({
- accessToken: 'abcd',
- idToken: '1234',
- refreshToken: 'xyz',
- });
- });
-
- it('should construct proper authz by tree request from IG response', async () => {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const mockedHttpClientRequest = HttpClient['_request'] as any;
- await HttpClient.request(authzByTreeReqOptionsForIG);
- expect(mockedHttpClientRequest).toBeCalledTimes(3);
- expect(mockedHttpClientRequest.mock.calls[1][0].url).toStrictEqual(expectedTxnReq.url);
- });
-
- it('should construct proper authz by tree request from REST response', async () => {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const mockedHttpClientRequest = HttpClient['_request'] as any;
- await HttpClient.request(authzByTreeReqOptionsForREST);
- expect(mockedHttpClientRequest).toBeCalledTimes(3);
- expect(mockedHttpClientRequest.mock.calls[1][0].url).toStrictEqual(expectedTxnReq.url);
- });
-
- it('should construct proper authz by txn request from IG response', async () => {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const mockedHttpClientRequest = HttpClient['_request'] as any;
- await HttpClient.request(authzByTxnReqOptionsForIG);
- expect(mockedHttpClientRequest).toBeCalledTimes(3);
- expect(mockedHttpClientRequest.mock.calls[1][0].url).toStrictEqual(expectedTxnReq.url);
- });
-
- it('should construct proper authz by txn request from REST response', async () => {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const mockedHttpClientRequest = HttpClient['_request'] as any;
- await HttpClient.request(authzByTxnReqOptionsForREST);
- expect(mockedHttpClientRequest).toBeCalledTimes(3);
- expect(mockedHttpClientRequest.mock.calls[1][0].url).toStrictEqual(expectedTxnReq.url);
- });
-});
diff --git a/packages/javascript-sdk/tests/integration/oauth2-client.test.ts b/packages/javascript-sdk/tests/integration/oauth2-client.test.ts
deleted file mode 100644
index 18c1c14be..000000000
--- a/packages/javascript-sdk/tests/integration/oauth2-client.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { vi, afterAll, describe, it, expect } from 'vitest';
-import OAuth2Client from '../../src/oauth2-client/index';
-import PKCE from '../../src/util/pkce';
-import { ResponseType } from '../../src/oauth2-client/index';
-import { FRLogger } from '../../src/util/logger';
-
-vi.mock('../../src/config/index', () => {
- return {
- default: {
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
- get() {
- return {
- redirectUrl: 'https://sdkapp.example.com/',
- clientId: 'OAuth2ClientID',
- scope: 'openid email profile',
- serverConfig: {
- baseUrl: 'https://openam.example.com/am/',
- timeout: '3000',
- },
- realmPath: '/alpha',
- };
- },
- },
- };
-});
-
-vi.mock('../../src/util/pkce', () => {
- return {
- default: {
- createVerifier(): string {
- return 'abcd';
- },
- createState(): string {
- return '1234';
- },
- createChallenge(): string {
- return 'wxyz';
- },
- },
- };
-});
-
-afterAll(() => {
- vi.clearAllMocks();
-});
-
-describe('Test OAuth2Client methods', () => {
- it('should construct proper authorization URL', async () => {
- const verifier = PKCE.createVerifier();
- const state = PKCE.createState();
- const authorizeUrlOptions = {
- responseType: ResponseType.Code,
- state,
- verifier,
- };
- const authorizeUrl = await OAuth2Client.createAuthorizeUrl(authorizeUrlOptions);
- FRLogger.log(authorizeUrl);
- // eslint-disable-next-line
- expect(authorizeUrl).toBe(
- 'https://openam.example.com/am/oauth2/realms/root/realms/alpha/authorize?client_id=OAuth2ClientID&response_type=code&scope=openid%20email%20profile&state=1234&code_challenge=wxyz&code_challenge_method=S256',
- );
- });
-});
diff --git a/packages/javascript-sdk/tsconfig.json b/packages/javascript-sdk/tsconfig.json
deleted file mode 100644
index 51449353a..000000000
--- a/packages/javascript-sdk/tsconfig.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "extends": "../../tsconfig.base.json",
- "compilerOptions": {
- "module": "ES2020",
- "forceConsistentCasingInFileNames": true,
- "strict": true,
- "noImplicitOverride": false,
- "noPropertyAccessFromIndexSignature": false,
- "skipLibCheck": true,
- "noImplicitReturns": true,
- "noFallthroughCasesInSwitch": true
- },
- "references": [
- {
- "path": "./tsconfig.spec.json"
- },
- {
- "path": "./tsconfig.lib.json"
- }
- ]
-}
diff --git a/packages/javascript-sdk/tsconfig.lib.json b/packages/javascript-sdk/tsconfig.lib.json
deleted file mode 100644
index e4307b479..000000000
--- a/packages/javascript-sdk/tsconfig.lib.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "./dist",
- "sourceMap": true,
- "noPropertyAccessFromIndexSignature": false,
- "lib": ["DOM", "DOM.Iterable", "es2023"],
- "module": "ES2020",
- "target": "ES2020",
- "composite": true,
- "declaration": true,
- "declarationMap": true,
- "strict": true,
- "esModuleInterop": true,
- "skipLibCheck": true,
- "moduleResolution": "Bundler"
- },
- "include": ["src/**/*.ts", "typedoc.json"],
- "exclude": [
- "**/*.spec.ts",
- "**/*.test.ts",
- "**/*.mock.ts",
- "tests/*",
- "**/*.mock.data.ts"
- ]
-}
diff --git a/packages/javascript-sdk/tsconfig.spec.json b/packages/javascript-sdk/tsconfig.spec.json
deleted file mode 100644
index dfd5c8d0a..000000000
--- a/packages/javascript-sdk/tsconfig.spec.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "../../dist/out-tsc",
- "target": "ES2020",
- "composite": true,
- "esModuleInterop": true,
- "moduleResolution": "Bundler",
- "lib": ["DOM", "DOM.Iterable", "es2023"]
- },
- "include": [
- "vite.config.ts",
- "vitest.config.ts",
- "src/**/*.test.ts",
- "src/**/*.spec.ts",
- "src/**/*.test.tsx",
- "src/**/*.spec.tsx",
- "src/**/*.test.js",
- "src/**/*.spec.js",
- "src/**/*.test.jsx",
- "src/**/*.spec.jsx",
- "src/**/*.d.ts",
- "src/**/*.mock.*",
- "tests/**/*.test.ts",
- "tests/**/*.spec.ts",
- "tests/**/*.mock*.ts"
- ]
-}
diff --git a/packages/javascript-sdk/typedoc.json b/packages/javascript-sdk/typedoc.json
deleted file mode 100644
index 9aaab9e85..000000000
--- a/packages/javascript-sdk/typedoc.json
+++ /dev/null
@@ -1,68 +0,0 @@
-{
- "entryPointStrategy": "expand",
- "entryPoints": ["./src/"],
- "tsconfig": "tsconfig.lib.json",
- "compilerOptions": {},
- "exclude": [
- "**/*.(spec|test|e2e).ts",
- "**/*.mock.*",
- "**/*.data.*",
- "docs/**",
- "tests/**",
- "specs/**",
- "spec/**",
- "test/**"
- ],
- "externalPattern": ["**/node_modules/**"],
- "excludeExternals": true,
- "excludeInternal": false,
- "excludePrivate": false,
- "excludeProtected": false,
- "excludeNotDocumented": false,
- "externalSymbolLinkMappings": {},
- "out": "./docs",
- "emit": "docs",
- "theme": "typedoc-github-theme",
- "name": "javascript-sdk",
- "includeVersion": true,
- "readme": "./README.md",
- "disableSources": false,
- "excludeTags": [],
- "cname": "",
- "sourceLinkTemplate": "",
- "gitRevision": "master",
- "gitRemote": "origin",
- "lang": "en",
- "githubPages": true,
- "hideGenerator": true,
- "searchInComments": false,
- "cleanOutputDir": true,
- "titleLink": "",
- "navigationLinks": {},
- "sidebarLinks": {},
- "commentStyle": "all",
- "categorizeByGroup": true,
- "defaultCategory": "Other",
- "categoryOrder": [],
- "sort": ["visibility", "required-first", "source-order"],
- "visibilityFilters": {
- "protected": true,
- "private": true,
- "inherited": true,
- "external": true
- },
- "searchCategoryBoosts": {},
- "searchGroupBoosts": {},
- "preserveWatchOutput": false,
- "skipErrorChecking": false,
- "validation": {
- "notExported": true,
- "invalidLink": true,
- "notDocumented": true
- },
- "requiredToBeDocumented": [],
- "treatWarningsAsErrors": false,
- "intentionallyNotExported": [],
- "logLevel": "Verbose",
- "plugin": ["typedoc-plugin-rename-defaults", "typedoc-github-theme"]
-}
diff --git a/packages/javascript-sdk/vite.config.ts b/packages/javascript-sdk/vite.config.ts
deleted file mode 100644
index e0aedebcb..000000000
--- a/packages/javascript-sdk/vite.config.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { defineConfig } from 'vite';
-import dts from 'vite-plugin-dts';
-import { copyFileSync } from 'fs';
-
-export default defineConfig({
- root: __dirname,
- cacheDir: '../../node_modules/.vite/',
- build: {
- outDir: './dist',
- target: ['esnext', 'es2020'],
- lib: {
- entry: 'src/index.ts',
- name: 'javascript-sdk',
- formats: ['es', 'cjs'],
- fileName: (format, fileName) => {
- const extension = format === 'es' ? 'js' : 'cjs';
- return `${fileName}.${extension}`;
- },
- },
- rollupOptions: {
- output: {
- dir: './dist',
- preserveModulesRoot: './src',
- preserveModules: true,
- },
- },
- },
- plugins: [
- dts({
- declarationOnly: false,
- entryRoot: 'src',
- rollupTypes: false,
- insertTypesEntry: true,
- tsconfigPath: './tsconfig.lib.json',
- afterBuild: (file) => {
- file.forEach((v, k) => {
- copyFileSync(k, k.replace('.d.ts', '.d.cts'));
- });
- },
- }),
- ],
- test: {
- globals: true,
- environment: 'jsdom',
- include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}', 'tests/**/*.test.ts'],
- watch: !process.env['CI'],
- reporters: ['default'],
- setupFiles: ['./vitest.setup.ts'],
- coverage: {
- enabled: Boolean(process.env['CI']),
- reporter: ['text', 'json', 'html'],
- reportsDirectory: './coverage',
- provider: 'v8',
- },
- deps: {
- optimizer: {
- web: {
- include: ['vitest-canvas-mock'],
- },
- },
- },
- },
-});
diff --git a/packages/javascript-sdk/vitest.setup.ts b/packages/javascript-sdk/vitest.setup.ts
deleted file mode 100644
index 644736e02..000000000
--- a/packages/javascript-sdk/vitest.setup.ts
+++ /dev/null
@@ -1 +0,0 @@
-import 'vitest-canvas-mock';
diff --git a/packages/ping-protect/.eslintignore b/packages/ping-protect/.eslintignore
deleted file mode 100644
index a1d4b2ec4..000000000
--- a/packages/ping-protect/.eslintignore
+++ /dev/null
@@ -1,12 +0,0 @@
-node_modules
-*.md
-LICENSE
-.babelrc
-.env*
-.bin
-dist
-src/lib/ping-signals-sdk.js
-.eslintignore
-docs
-coverage
-vite.config.*.timestamp*
diff --git a/packages/ping-protect/.eslintrc.json b/packages/ping-protect/.eslintrc.json
deleted file mode 100644
index 9d9c0db55..000000000
--- a/packages/ping-protect/.eslintrc.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "extends": ["../../.eslintrc.json"],
- "ignorePatterns": ["!**/*"],
- "overrides": [
- {
- "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
- "rules": {}
- },
- {
- "files": ["*.ts", "*.tsx"],
- "rules": {}
- },
- {
- "files": ["*.js", "*.jsx"],
- "rules": {}
- }
- ]
-}
diff --git a/packages/ping-protect/CHANGELOG.md b/packages/ping-protect/CHANGELOG.md
deleted file mode 100644
index a2a146b61..000000000
--- a/packages/ping-protect/CHANGELOG.md
+++ /dev/null
@@ -1,23 +0,0 @@
-# Changelog
-
-## v4.6.0 (2024-08-15)
-
-### 🚀 Features
-
-- support-metadata-marketplace-protect ([a3494b9](https://github.com/ForgeRock/forgerock-javascript-sdk/commit/a3494b9))
-
-### ❤️ Thank You
-
-- ryanbas21
-
-## [4.4.2] - 2024-05-15
-
-fix(ping-protect): update-module-type by @ryanbas21 in #434
-fix(ping-protect): update-signals-sdk by @ryanbas21 in #437
-fix(ping-protect): bundling by @ryanbas21 in #440
-fix(ping-protect): update-ping-protect-signals-sdk by @ryanbas21 in #441
-fix(ping-protect): dynamically load ping protect in start and transpile as esmodule
-
-## [4.4.0] - 2024-03-12
-
-feat(ping-protect): Add a new module for Ping Protect and allow for use of .wellknown endpoint for configuration of PingOne as an oauth server
diff --git a/packages/ping-protect/README.md b/packages/ping-protect/README.md
deleted file mode 100644
index 2577ec8d5..000000000
--- a/packages/ping-protect/README.md
+++ /dev/null
@@ -1,138 +0,0 @@
-# Ping Protect
-
-The Ping Protect module is intended to be used along with the ForgeRock JavaScript SDK to provide the Ping Protect feature to our existing ForgeRock SDK customers.
-
-## Overall Design
-
-There are two components on the server side and two components on the client side to enable this feature. You'll need to have the following:
-
-1. ForgeRock Identity Cloud (aka ID Cloud) platform or an up-to-date ForgeRock Access Management (aka AM)
-2. PingOne tenant with Protect enabled
-3. A Ping Protect Service configured in ID Cloud or AM
-4. A journey/tree with the appropriate Protect Nodes
-5. A client application with the `@forgerock/javascript-sdk` and `@forgerock/ping-protect` modules installed
-
-## Quick Start for Client Application
-
-Install both modules and their latest versions:
-
-```sh
-npm install @forgerock/javascript-sdk @forgerock/ping-protect
-```
-
-The two main responsibilities of the Ping Protect module is the initialization of the profiling and data collection and the completion and preparation of the collected data for the server. You can find the two methods on the `PIProtect` module found within the `@forgerock/ping-protect` module.
-
-- `PIProtect.start()`
-- `PIProtect.getData()`
-
-The `start` method can be called at application startup, or when you receive the `PingOneProtectInitializeCallback` callback from the server. We recommend you call `start` as soon as you can to collect as much data as possible for higher accuracy.
-
-When calling `start`, you have many different options to configure what and how the data is collected. The most important and required of these settings is the `envId`. All other settings are optional.
-
-```js
-import { PIProtect } from '@forgerock/ping-protect';
-
-// Call early in your application startup
-PIProtect.start({ envId: '02fb1243-189a-4bc7-9d6c-a919edf6447' });
-```
-
-Alternatively, you can delay the initialization until you receive the instruction from the server by way of the special callback: `PingOneProtectInitializeCallback`. To do this, you would call the `start` method when the callback is present in the journey.
-
-```js
-import { PIProtect } from '@forgerock/ping-protect';
-
-if (step.getCallbacksOfType('PingOneProtectInitializeCallback')) {
- try {
- // Asynchronous call
- await PIProtect.start({ envId: '02fb1243-189a-4bc7-9d6c-a919edf6447' });
- } catch (err) {
- // handle error
- }
-}
-```
-
-You then call the `FRAuth.next` method after initialization to move the user forward in the journey.
-
-```js
-FRAuth.next(step);
-```
-
-At some point in the journey, and as late as possible in order to collect as much data as you can, you will come across the `PingOneProtectEvaluationCallback`. This is when you call the `getData` method to package what's been collected for the server to evaluate.
-
-```js
-import { PIProtect } from '@forgerock/ping-protect';
-
-let data;
-
-if (step.getCallbacksOfType('PingOneProtectEvaluationCallback')) {
- try {
- // Asynchronous call
- data = await PIProtect.getData();
- } catch (err) {
- // handle error
- }
-}
-```
-
-Now that we have the data, set it on the callback in order to send it to the server when we call `next`.
-
-```js
-callback.setData(data);
-
-FRAuth.next(step);
-```
-
-## Error Handling
-
-When you encounter an error during initialization or evaluation, set the error message on the callback using the `setClientError` method. Setting the message on the callback is how it gets sent to the server on the `FRAuth.next` method call.
-
-```js
-if (step.getCallbacksOfType('PingOneProtectInitializeCallback')) {
- const callback = step.getCallbackOfType('PingOneProtectInitializeCallback');
- try {
- // Asynchronous call
- await PIProtect.start({ envId: '02fb1243-189a-4bc7-9d6c-a919edf6447' });
- } catch (err) {
- callback.setClientError(err.message);
- }
-}
-```
-
-A similar process is used for the evaluation step.
-
-```js
-let data;
-
-if (step.getCallbacksOfType('PingOneProtectEvaluationCallback')) {
- const callback = step.getCallbackOfType('PingOneProtectEvaluationCallback');
- try {
- // Asynchronous call
- data = await PIProtect.getData();
- } catch (err) {
- callback.setClientError(err.message);
- }
-}
-```
-
-## Full API
-
-```js
-// PIProtect class methods
-PIProtect.start();
-PIProtect.getData();
-PIProtect.pauseBehavioralData();
-PIProtect.resumeBehavioralData();
-```
-
-```js
-// PingOneProtectInitializeCallback class methods
-callback.getConfig();
-callback.setClientError();
-```
-
-```js
-// PingOneProtectEvaluationCallback class methods
-callback.setData();
-callback.setClientError();
-callback.getPauseBehavioralData();
-```
diff --git a/packages/ping-protect/package.json b/packages/ping-protect/package.json
deleted file mode 100644
index d51172cd1..000000000
--- a/packages/ping-protect/package.json
+++ /dev/null
@@ -1,25 +0,0 @@
-{
- "name": "@forgerock/ping-protect",
- "version": "4.6.0",
- "private": false,
- "type": "module",
- "files": ["dist"],
- "module": "./dist/index.js",
- "main": "./dist/index.js",
- "repository": {
- "type": "git",
- "url": "git+https://github.com:ForgeRock/forgerock-javascript-sdk.git",
- "directory": "packages/ping-protect"
- },
- "sideEffects": ["./dist/lib/ping-signals-sdk.js"],
- "exports": {
- ".": {
- "types": "./dist/index.ts.d.ts",
- "default": "./dist/index.js"
- }
- },
- "types": "./dist/index.ts.d.ts",
- "dependencies": {
- "@forgerock/javascript-sdk": "workspace:*"
- }
-}
diff --git a/packages/ping-protect/project.json b/packages/ping-protect/project.json
deleted file mode 100644
index f97897cdd..000000000
--- a/packages/ping-protect/project.json
+++ /dev/null
@@ -1,44 +0,0 @@
-{
- "name": "ping-protect",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "sourceRoot": "packages/ping-protect/src",
- "projectType": "library",
- "tags": ["scope:package"],
- "targets": {
- "docs": {
- "command": "pnpm typedoc --options {projectRoot}/typedoc.json"
- },
- "build": {
- "inputs": [
- "default",
- "^default",
- {
- "externalDependencies": ["vite"]
- }
- ],
- "outputs": ["{projectRoot}/dist"]
- },
- "lint": {
- "options": {
- "args": ["**/*.ts"]
- }
- },
- "test": {
- "inputs": [
- "default",
- "^default",
- {
- "externalDependencies": ["vitest"]
- }
- ],
- "options": {
- "config": "./vite.config.ts"
- },
- "configurations": {
- "watch": {
- "watch": true
- }
- }
- }
- }
-}
diff --git a/packages/ping-protect/src/index.test.ts b/packages/ping-protect/src/index.test.ts
deleted file mode 100644
index 5a79bdfc9..000000000
--- a/packages/ping-protect/src/index.test.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import * as module from './index.js';
-
-describe('PIProtect', () => {
- it('should be defined', () => {
- expect(module.PIProtect).toBeDefined();
- });
-});
diff --git a/packages/ping-protect/src/index.ts b/packages/ping-protect/src/index.ts
deleted file mode 100644
index e3ec0887a..000000000
--- a/packages/ping-protect/src/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from './lib/ping-protect.js';
diff --git a/packages/ping-protect/src/lib/ping-protect.mock.data.ts b/packages/ping-protect/src/lib/ping-protect.mock.data.ts
deleted file mode 100644
index d02a18aae..000000000
--- a/packages/ping-protect/src/lib/ping-protect.mock.data.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-import { CallbackType, FRStep } from '@forgerock/javascript-sdk';
-
-export const standardPingProtectInitializeStep = new FRStep({
- authId: 'foo',
- callbacks: [
- {
- type: 'MetadataCallback' as CallbackType.MetadataCallback,
- output: [
- {
- name: 'data',
- value: {
- _type: 'PingOneProtect',
- _action: 'protect_initialize',
- envId: 'some_id',
- consoleLogEnabled: true,
- deviceAttributesToIgnore: [],
- customHost: '',
- lazyMetadata: true,
- behavioralDataCollection: true,
- disableHub: true,
- deviceKeyRsyncIntervals: 10,
- enableTrust: true,
- disableTags: true,
- },
- },
- ],
- },
- {
- type: 'HiddenValueCallback' as CallbackType.HiddenValueCallback,
- output: [
- {
- name: 'value',
- value: '',
- },
- {
- name: 'id',
- value: 'clientError',
- },
- ],
- input: [
- {
- name: 'IDToken1',
- value: 'clientError',
- },
- ],
- },
- ],
-});
-
-export const standardPingProtectEvaluationStep = new FRStep({
- authId: 'foo',
- callbacks: [
- {
- type: 'MetadataCallback' as CallbackType.MetadataCallback,
- output: [
- {
- name: 'data',
- value: {
- _type: 'PingOneProtect',
- _action: 'protect_risk_evaluation',
- envId: 'some_id',
- pauseBehavioralData: true,
- },
- },
- ],
- },
- {
- type: 'HiddenValueCallback' as CallbackType.HiddenValueCallback,
- output: [
- {
- name: 'value',
- value: '',
- },
- {
- name: 'id',
- value: 'pingone_risk_evaluation_signals',
- },
- ],
- input: [
- {
- name: 'IDToken1',
- value: 'pingone_risk_evaluation_signals',
- },
- ],
- },
- {
- type: 'HiddenValueCallback' as CallbackType.HiddenValueCallback,
- output: [
- {
- name: 'value',
- value: '',
- },
- {
- name: 'id',
- value: 'clientError',
- },
- ],
- input: [
- {
- name: 'IDToken1',
- value: 'clientError',
- },
- ],
- },
- ],
-});
-
-export const noProtectType = new FRStep({
- authId: 'foo',
- callbacks: [
- {
- type: 'HiddenValueCallback' as CallbackType.HiddenValueCallback,
- output: [
- {
- name: 'value',
- value: '',
- },
- {
- name: 'id',
- value: 'pingone_risk_evaluation_signals',
- },
- ],
- input: [
- {
- name: 'IDToken1',
- value: 'pingone_risk_evaluation_signals',
- },
- ],
- },
- {
- type: 'HiddenValueCallback' as CallbackType.HiddenValueCallback,
- output: [
- {
- name: 'value',
- value: '',
- },
- {
- name: 'id',
- value: 'clientError',
- },
- ],
- input: [
- {
- name: 'IDToken1',
- value: 'clientError',
- },
- ],
- },
- ],
-});
diff --git a/packages/ping-protect/src/lib/ping-protect.test.ts b/packages/ping-protect/src/lib/ping-protect.test.ts
deleted file mode 100644
index a34fac396..000000000
--- a/packages/ping-protect/src/lib/ping-protect.test.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import { vi, expect, describe, it } from 'vitest';
-import { PIProtect } from './ping-protect.js';
-import {
- noProtectType,
- standardPingProtectEvaluationStep,
- standardPingProtectInitializeStep,
-} from './ping-protect.mock.data.js';
-import { CallbackType, HiddenValueCallback } from '@forgerock/javascript-sdk';
-
-describe('PIProtect', () => {
- it('should be defined', () => {
- expect(PIProtect).toBeDefined();
- expect(PIProtect.start).toBeDefined();
- expect(PIProtect.getData).toBeDefined();
- expect(PIProtect.pauseBehavioralData).toBeDefined();
- expect(PIProtect.resumeBehavioralData).toBeDefined();
- });
- it('should call start', async () => {
- const protectMock = vi.spyOn(PIProtect, 'start');
- const config = {
- envId: '12345',
- consoleLogEnabled: true,
- deviceAttributesToIgnore: ['userAgent'],
- customHost: 'https://example.com',
- lazyMetadata: false,
- behavioralDataCollection: true,
- deviceKeyRsyncIntervals: 14,
- enableTrust: false,
- disableTags: false,
- disableHub: false,
- };
- await PIProtect.start(config);
- expect(protectMock).toHaveBeenCalledWith(config);
- });
- it('should call pause behavioralData', () => {
- const protectMock = vi.spyOn(PIProtect, 'pauseBehavioralData');
- PIProtect.pauseBehavioralData();
- expect(protectMock).toHaveBeenCalled();
- });
- it('should call resume behavioralData', () => {
- const protectMock = vi.spyOn(PIProtect, 'resumeBehavioralData');
- PIProtect.resumeBehavioralData();
- expect(protectMock).toHaveBeenCalled();
- });
-
- describe('should test the marketplace node setup', () => {
- it('should test getPauseBehavioralData with marketplace data', () => {
- const result = PIProtect.getPauseBehavioralData(standardPingProtectEvaluationStep);
-
- expect(result).toEqual(false);
-
- const secondResult = PIProtect.getPauseBehavioralData(standardPingProtectInitializeStep);
-
- expect(secondResult).toEqual(true);
- });
- it('should test the getPingProtectType method', () => {
- const result = PIProtect.getPingProtectType(standardPingProtectInitializeStep);
-
- expect(result).toEqual('initialize');
-
- const result2 = PIProtect.getPingProtectType(standardPingProtectEvaluationStep);
-
- expect(result2).toEqual('evaluate');
-
- const result3 = PIProtect.getPingProtectType(noProtectType);
- expect(result3).toEqual('none');
- });
- it('should setNodeInputValue', () => {
- const step = standardPingProtectEvaluationStep;
-
- PIProtect.setNodeInputValue(step, 'the value');
- const [hc] = step.getCallbacksOfType(CallbackType.HiddenValueCallback);
-
- expect(hc.getInputValue()).toEqual('the value');
- });
- });
-
- it('should get the node config', () => {
- const result = PIProtect.getNodeConfig(standardPingProtectInitializeStep);
- expect(result).toEqual(
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
- standardPingProtectInitializeStep!.payload.callbacks![0].output[0].value,
- );
-
- const result2 = PIProtect.getNodeConfig(noProtectType);
- expect(result2).toBeUndefined();
- });
- it('should set an error with marketplace nodes', () => {
- PIProtect.setNodeClientError(standardPingProtectEvaluationStep, 'we errored!');
-
- const [, err] = standardPingProtectEvaluationStep.getCallbacksOfType(
- CallbackType.HiddenValueCallback,
- );
-
- expect(err.getInputValue()).toBe('we errored!');
- });
-});
diff --git a/packages/ping-protect/src/lib/ping-protect.ts b/packages/ping-protect/src/lib/ping-protect.ts
deleted file mode 100644
index 2a6bf90df..000000000
--- a/packages/ping-protect/src/lib/ping-protect.ts
+++ /dev/null
@@ -1,270 +0,0 @@
-import {
- CallbackType,
- FRStep,
- HiddenValueCallback,
- MetadataCallback,
- PingOneProtectEvaluationCallback,
- PingOneProtectInitializeCallback,
-} from '@forgerock/javascript-sdk';
-import { ProtectEvaluationConfig, ProtectInitializeConfig } from './ping-protect.types';
-
-export interface Identifiers {
- [key: string]: string;
-}
-
-/**
- * InitParams - Interface for the init method parameters
- * envId: string - Required; the environment id from your PingOne tenant
- * * - All other parameters are optional
- */
-export interface InitParams {
- envId: string; // environment id
- consoleLogEnabled?: boolean; // true to enable SDK logs in the developer console. default is false
- waitForWindowLoad?: boolean; // true to init the SDK on load event, instead of DOMContentLoaded event. default is true
- hubUrl?: string; // iframe url for cross-storage device ID
- disableHub?: boolean; // when true, the SDK store the deviceId to the localStorage only and won't use an iframe (hub). default is false
- deviceAttributesToIgnore?: string[]; // metadata blacklist
- lazyMetadata?: boolean; // true to calculate the metadata only on getData invocation, otherwise do it automatically on init. default is false
- behavioralDataCollection?: boolean; // true to collect behavioral data. default is true
- disableTags?: boolean; // true to skip tag collection. default is false,
- externalIdentifiers?: Identifiers; // optional customer external identifiers that should be reflected on a device entity
- deviceKeyRsyncIntervals?: number; // number of days used to window the next time the device attestation should use the device fallback key. default is 14 days
- enableTrust?: boolean; // tie the device payload to a non-extractable crypto key stored on the browser for content authenticity verification
-}
-
-// Add Signals SDK namespace to the window object
-declare global {
- interface Window {
- _pingOneSignals: {
- init: (initParams?: InitParams) => Promise;
- getData: () => Promise;
- pauseBehavioralData: () => void;
- resumeBehavioralData: () => void;
- };
- }
-}
-
-/**
- * @class PIProtect - Class to interact with the underlying PingOne Signals SDK
- */
-export abstract class PIProtect {
- /** ***********************************************************************************************
- * The following methods are methods for the interacting with PingOne Signals SDK
- */
-
- /**
- * @method getData - Method to get the device data
- * @returns {Promise} - Returns the device data
- */
- public static async getData(): Promise {
- return await window._pingOneSignals.getData();
- }
-
- /**
- * @method start - Method to initialize and start the PingOne Signals SDK
- * @param {InitParams} options - The init parameters
- * @returns {Promise} - Returns a promise
- */
- public static async start(options: InitParams): Promise {
- try {
- /*
- * Load the Ping Signals SDK
- * this automatically pollutes the window
- * there are no exports of this module
- */
- await import('./ping-signals-sdk.js' as string);
- } catch (err) {
- console.error('error loading ping signals', err);
- }
- await window._pingOneSignals.init(options);
-
- if (options.behavioralDataCollection === true) {
- window._pingOneSignals.resumeBehavioralData();
- }
- }
-
- /**
- * @method pauseBehavioralData - Method to pause the behavioral data collection
- * @returns {void}
- * @description Pause the behavioral data collection only; device profile data will still be collected
- */
- public static pauseBehavioralData(): void {
- window._pingOneSignals.pauseBehavioralData();
- }
-
- /**
- * @method resumeBehavioralData - Method to resume the behavioral data collection
- * @returns {void}
- * @description Resume the behavioral data collection
- */
- public static resumeBehavioralData(): void {
- window._pingOneSignals.resumeBehavioralData();
- }
-
- /** ***********************************************************************************************
- * Required when using the Ping Protect Marketplace nodes, which has generic callbacks
- * But, can be used for native nodes and/or either callback type
- */
-
- public static getPauseBehavioralData(step: FRStep): boolean {
- // Check for native callback first
- try {
- const nativeCallback = step.getCallbackOfType(
- CallbackType.PingOneProtectEvaluationCallback,
- );
-
- const shouldPause = nativeCallback?.getPauseBehavioralData();
- return shouldPause || false;
- } catch (err) {
- // Do nothing
- }
-
- // If we are here, we are dealing with Marketplace nodes
- const cbs = step.getCallbacksOfType(CallbackType.MetadataCallback);
-
- if (!cbs.length) {
- return false;
- }
-
- const protectMetadataCb = cbs.find((metadataCallback) => {
- const data = metadataCallback.getData() as { _type: string; _action: string };
- return data._type === 'PingOneProtect';
- });
-
- if (!protectMetadataCb) {
- return false;
- }
-
- const data: ProtectInitializeConfig | ProtectEvaluationConfig = (
- protectMetadataCb as MetadataCallback
- ).getData();
-
- if (data._action === 'protect_risk_evaluation') {
- return false;
- } else {
- return !!(data as ProtectInitializeConfig).behavioralDataCollection;
- }
- }
-
- public static getNodeConfig(step: FRStep): ProtectInitializeConfig | undefined {
- // Check for native callback first
- try {
- const nativeCallback = step.getCallbackOfType(
- CallbackType.PingOneProtectInitializeCallback,
- );
-
- const config = nativeCallback?.getConfig() as ProtectInitializeConfig;
- return config;
- } catch (err) {
- // Do nothing
- }
-
- const cbs = step.getCallbacksOfType(CallbackType.MetadataCallback);
-
- if (!cbs.length) {
- return undefined;
- }
-
- const protectMetadataCb = cbs.find((metadataCallback) => {
- const data = metadataCallback.getData() as { _type: string; _action: string };
- return data._action === 'protect_initialize';
- });
-
- if (!protectMetadataCb) {
- return undefined;
- }
-
- const data = (protectMetadataCb as MetadataCallback).getData() as ProtectInitializeConfig;
-
- return data;
- }
-
- public static getPingProtectType(step: FRStep): 'initialize' | 'evaluate' | 'none' {
- const cbs = step.getCallbacksOfType(CallbackType.MetadataCallback);
-
- if (!cbs.length) {
- return 'none';
- }
-
- const protectMetadataCb = cbs.find((cb) => {
- const metadataCallback = cb as MetadataCallback;
- const data = metadataCallback.getData() as { _type: string; _action: string };
- return data._type === 'PingOneProtect';
- });
-
- if (!protectMetadataCb) {
- return 'none';
- }
-
- const data = (protectMetadataCb as MetadataCallback).getData() as ProtectInitializeConfig;
-
- return data._action === 'protect_initialize' ? 'initialize' : 'evaluate';
- }
-
- public static setNodeClientError(step: FRStep, value: string): void {
- // Check for native callback first
- const nativeEvaluationCallback = step.getCallbacksOfType(
- CallbackType.PingOneProtectEvaluationCallback,
- );
- const nativeInitializeCallback = step.getCallbacksOfType(
- CallbackType.PingOneProtectInitializeCallback,
- );
- const arr = [...nativeEvaluationCallback, ...nativeInitializeCallback];
-
- if (arr.length) {
- const cb = arr[0];
- cb.setClientError(value);
- return;
- }
-
- // If we are here, we are dealing with Marketplace nodes
- const cbs = step.getCallbacksOfType(CallbackType.HiddenValueCallback);
-
- if (!cbs.length) {
- return;
- }
-
- const clientErrorCb = cbs.find((hiddenValueCallback) => {
- const output = hiddenValueCallback.getOutputByName('id', '');
- return output === 'clientError';
- });
-
- if (!clientErrorCb) {
- return;
- }
-
- clientErrorCb.setInputValue(value);
- }
-
- public static setNodeInputValue(step: FRStep, value: string): void {
- // Check for native callback first
- try {
- const nativeCallback = step.getCallbackOfType(
- CallbackType.PingOneProtectEvaluationCallback,
- );
-
- nativeCallback?.setData(value);
- return;
- } catch (err) {
- // Do nothing
- }
-
- // If we are here, we are dealing with Marketplace nodes
- const cbs = step.getCallbacksOfType(CallbackType.HiddenValueCallback);
-
- if (!cbs.length) {
- return;
- }
-
- const inputCb = cbs.find((hiddenValueCallback) => {
- const output = hiddenValueCallback.getOutputByName('id', '');
- return output === 'pingone_risk_evaluation_signals';
- });
-
- if (!inputCb) {
- return;
- }
-
- inputCb.setInputValue(value);
- }
-}
diff --git a/packages/ping-protect/src/lib/ping-protect.types.ts b/packages/ping-protect/src/lib/ping-protect.types.ts
deleted file mode 100644
index 1df9a6963..000000000
--- a/packages/ping-protect/src/lib/ping-protect.types.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-export interface ProtectInitializeConfig {
- _type: 'PingOneProtect';
- _action: 'protect_initialize';
- envId?: string;
- consoleLogEnabled?: boolean;
- deviceAttributesToIgnore?: string[];
- customHost?: string;
- lazyMetadata?: boolean;
- behavioralDataCollection?: boolean;
- deviceKeyRsyncIntervals?: number;
- enableTrust?: boolean;
- disableTags?: boolean;
- disableHub?: boolean;
-}
-
-export interface ProtectEvaluationConfig {
- _type: 'PingOneProtect';
- _action: 'protect_risk_evaluation';
- envId: string;
- pauseBehavioralData: boolean;
-}
diff --git a/packages/ping-protect/src/lib/ping-signals-sdk.js b/packages/ping-protect/src/lib/ping-signals-sdk.js
deleted file mode 100644
index d05857e05..000000000
--- a/packages/ping-protect/src/lib/ping-signals-sdk.js
+++ /dev/null
@@ -1,14434 +0,0 @@
-if (typeof window !== 'undefined') {
- var _POSignalsEntities;
- !(function (t, e) {
- 'use strict';
- 'function' != typeof t.CustomEvent &&
- (t.CustomEvent = (function () {
- return function (t, e) {
- e = e || { bubbles: !1, cancelable: !1, detail: null };
- var n = document.createEvent('CustomEvent');
- return n.initCustomEvent(t, e.bubbles, e.cancelable, e.detail), n;
- };
- })());
- })(window),
- (function () {
- 'use strict';
- var t = 'st-ping-div';
- function e(t) {
- 'loading' !== document.readyState ? t() : document.addEventListener('DOMContentLoaded', t);
- }
- function n(n) {
- e(function () {
- if (n) {
- var e =
- (i = document.getElementById(t)) ||
- (((i = document.createElement('div')).style.border = 'none'),
- (i.style.position = 'absolute'),
- (i.style.top = '-999px'),
- (i.style.left = '-999px'),
- (i.style.width = '0'),
- (i.style.height = '0'),
- (i.style.visibility = 'hidden'),
- (i.style.overflow = 'hidden'),
- (i.id = t),
- document.body.appendChild(i),
- i);
- (window._pingOneSignalsToken = getComputedStyle(e, '::after').content.replace(
- /['"]+/g,
- '',
- )),
- document.dispatchEvent(new CustomEvent('PingOneSignalsTokenReadyEvent'));
- }
- var i, r;
- (r = 'Finished - ' + (n ? 'success' : 'failure')),
- window['enable-logs-pingOneSignals'] && console.log(r);
- });
- }
- var i,
- r,
- a,
- o,
- s = document.querySelector('script[data-pingOneSignalsSkipToken]');
- if (s && 'true' === s.getAttribute('data-pingOneSignalsSkipToken'))
- return (
- (window._pingOneSignalsToken = 'skipped_token_' + new Date().getTime()),
- e(function () {
- document.dispatchEvent(new CustomEvent('PingOneSignalsTokenSkippedEvent'));
- })
- );
- window._pingOneSignalsToken ||
- (window._pingOneSignalsToken = 'uninitialized_token_' + new Date().getTime()),
- (i = window._pingOneSignalsCustomHost || 'apps.pingone.com'),
- (r = { sdkVersion: '5.3.5w', platform: navigator.platform || '' }),
- (a = encodeURIComponent(
- (function (t) {
- var e,
- n,
- i,
- r,
- a,
- o,
- s,
- u = '',
- c = 0,
- l = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
- for (
- t = (function (t) {
- t = t.replace(/\r\n/g, '\n');
- for (var e = '', n = 0; n < t.length; n++) {
- var i = t.charCodeAt(n);
- i < 128
- ? (e += String.fromCharCode(i))
- : (127 < i && i < 2048
- ? (e += String.fromCharCode((i >> 6) | 192))
- : ((e += String.fromCharCode((i >> 12) | 224)),
- (e += String.fromCharCode(((i >> 6) & 63) | 128))),
- (e += String.fromCharCode((63 & i) | 128)));
- }
- return e;
- })(t);
- c < t.length;
-
- )
- (r = (e = t.charCodeAt(c++)) >> 2),
- (a = ((3 & e) << 4) | ((n = t.charCodeAt(c++)) >> 4)),
- (o = ((15 & n) << 2) | ((i = t.charCodeAt(c++)) >> 6)),
- (s = 63 & i),
- isNaN(n) ? (o = s = 64) : isNaN(i) && (s = 64),
- (u = u + l.charAt(r) + l.charAt(a) + l.charAt(o) + l.charAt(s));
- return u;
- })(
- (function (t, e) {
- for (var n = [], i = 0; i < t.length; i++) {
- var r = t.charCodeAt(i) ^ e.charCodeAt(i % e.length);
- n.push(String.fromCharCode(r));
- }
- return n.join('');
- })(JSON.stringify(r), 'dkiBm42'),
- ),
- )),
- ((o = document.createElement('link')).type = 'text/css'),
- (o.rel = 'stylesheet'),
- (o.href = 'https://' + i + '/signals/sdk/pong.css?body=' + a + '&e=2'),
- (document.head || document.getElementsByTagName('head')[0]).appendChild(o),
- (o.onload = function () {
- n(!0);
- }),
- (o.onerror = function () {
- n(!1);
- });
- })(),
- (function (t) {
- t._POSignalsEntities || (t._POSignalsEntities = {}),
- t._pingOneSignals && console.warn('PingOne Signals script was imported multiple times');
- })(window),
- (function (t) {
- 'use strict';
- function e(t) {
- var e = this.constructor;
- return this.then(
- function (n) {
- return e.resolve(t()).then(function () {
- return n;
- });
- },
- function (n) {
- return e.resolve(t()).then(function () {
- return e.reject(n);
- });
- },
- );
- }
- var n = setTimeout;
- function i(t) {
- return Boolean(t && void 0 !== t.length);
- }
- function r() {}
- function a(t) {
- if (!(this instanceof a)) throw new TypeError('Promises must be constructed via new');
- if ('function' != typeof t) throw new TypeError('not a function');
- (this._state = 0),
- (this._handled = !1),
- (this._value = void 0),
- (this._deferreds = []),
- l(t, this);
- }
- function o(t, e) {
- for (; 3 === t._state; ) t = t._value;
- 0 !== t._state
- ? ((t._handled = !0),
- a._immediateFn(function () {
- var n = 1 === t._state ? e.onFulfilled : e.onRejected;
- if (null !== n) {
- var i;
- try {
- i = n(t._value);
- } catch (t) {
- return void u(e.promise, t);
- }
- s(e.promise, i);
- } else (1 === t._state ? s : u)(e.promise, t._value);
- }))
- : t._deferreds.push(e);
- }
- function s(t, e) {
- try {
- if (e === t) throw new TypeError('A promise cannot be resolved with itself.');
- if (e && ('object' == typeof e || 'function' == typeof e)) {
- var n = e.then;
- if (e instanceof a) return (t._state = 3), (t._value = e), void c(t);
- if ('function' == typeof n)
- return void l(
- ((i = n),
- (r = e),
- function () {
- i.apply(r, arguments);
- }),
- t,
- );
- }
- (t._state = 1), (t._value = e), c(t);
- } catch (e) {
- u(t, e);
- }
- var i, r;
- }
- function u(t, e) {
- (t._state = 2), (t._value = e), c(t);
- }
- function c(t) {
- 2 === t._state &&
- 0 === t._deferreds.length &&
- a._immediateFn(function () {
- t._handled || a._unhandledRejectionFn(t._value);
- });
- for (var e = 0, n = t._deferreds.length; e < n; e++) o(t, t._deferreds[e]);
- t._deferreds = null;
- }
- function l(t, e) {
- var n = !1;
- try {
- t(
- function (t) {
- n || ((n = !0), s(e, t));
- },
- function (t) {
- n || ((n = !0), u(e, t));
- },
- );
- } catch (t) {
- if (n) return;
- (n = !0), u(e, t);
- }
- }
- (a.prototype.catch = function (t) {
- return this.then(null, t);
- }),
- (a.prototype.then = function (t, e) {
- var n = new this.constructor(r);
- return (
- o(
- this,
- new (function (t, e, n) {
- (this.onFulfilled = 'function' == typeof t ? t : null),
- (this.onRejected = 'function' == typeof e ? e : null),
- (this.promise = n);
- })(t, e, n),
- ),
- n
- );
- }),
- (a.prototype.finally = e),
- (a.all = function (t) {
- return new a(function (e, n) {
- if (!i(t)) return n(new TypeError('Promise.all accepts an array'));
- var r = Array.prototype.slice.call(t);
- if (0 === r.length) return e([]);
- var a = r.length;
- function o(t, i) {
- try {
- if (i && ('object' == typeof i || 'function' == typeof i)) {
- var s = i.then;
- if ('function' == typeof s)
- return void s.call(
- i,
- function (e) {
- o(t, e);
- },
- n,
- );
- }
- (r[t] = i), 0 == --a && e(r);
- } catch (t) {
- n(t);
- }
- }
- for (var s = 0; s < r.length; s++) o(s, r[s]);
- });
- }),
- (a.resolve = function (t) {
- return t && 'object' == typeof t && t.constructor === a
- ? t
- : new a(function (e) {
- e(t);
- });
- }),
- (a.reject = function (t) {
- return new a(function (e, n) {
- n(t);
- });
- }),
- (a.race = function (t) {
- return new a(function (e, n) {
- if (!i(t)) return n(new TypeError('Promise.race accepts an array'));
- for (var r = 0, o = t.length; r < o; r++) a.resolve(t[r]).then(e, n);
- });
- }),
- (a._immediateFn =
- ('function' == typeof setImmediate &&
- function (t) {
- setImmediate(t);
- }) ||
- function (t) {
- n(t, 0);
- }),
- (a._unhandledRejectionFn = function (t) {
- 'undefined' != typeof console &&
- console &&
- console.warn('Possible Unhandled Promise Rejection:', t);
- }),
- 'function' != typeof t.Promise
- ? (t.Promise = a)
- : t.Promise.prototype.finally || (t.Promise.prototype.finally = e);
- })(window),
- (function (t, e) {
- 'use strict';
- (_POSignalsEntities || (_POSignalsEntities = {})).PromiseQueue = (function () {
- var t = function () {};
- function e(t, e, n) {
- (this.options = n = n || {}),
- (this.pendingPromises = 0),
- (this.maxPendingPromises = void 0 !== t ? t : 1 / 0),
- (this.maxQueuedPromises = void 0 !== e ? e : 1 / 0),
- (this.queue = []);
- }
- return (
- (e.prototype.add = function (e) {
- var n = this;
- return new Promise(function (i, r, a) {
- n.queue.length >= n.maxQueuedPromises
- ? r(new Error('Queue limit reached'))
- : (n.queue.push({ promiseGenerator: e, resolve: i, reject: r, notify: a || t }),
- n._dequeue());
- });
- }),
- (e.prototype.getPendingLength = function () {
- return this.pendingPromises;
- }),
- (e.prototype.getQueueLength = function () {
- return this.queue.length;
- }),
- (e.prototype._dequeue = function () {
- var t = this;
- if (this.pendingPromises >= this.maxPendingPromises) return !1;
- var e,
- n = this.queue.shift();
- if (!n) return this.options.onEmpty && this.options.onEmpty(), !1;
- try {
- this.pendingPromises++,
- ((e = n.promiseGenerator()),
- e && 'function' == typeof e.then
- ? e
- : new Promise(function (t) {
- t(e);
- })).then(
- function (e) {
- t.pendingPromises--, n.resolve(e), t._dequeue();
- },
- function (e) {
- t.pendingPromises--, n.reject(e), t._dequeue();
- },
- function (t) {
- n.notify(t);
- },
- );
- } catch (e) {
- t.pendingPromises--, n.reject(e), t._dequeue();
- }
- return !0;
- }),
- e
- );
- })();
- })(),
- (function (t) {
- 'use strict';
- var e = 'input is invalid type',
- n = !t.JS_SHA256_NO_ARRAY_BUFFER && 'undefined' != typeof ArrayBuffer,
- i = '0123456789abcdef'.split(''),
- r = [-2147483648, 8388608, 32768, 128],
- a = [24, 16, 8, 0],
- o = [
- 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748,
- 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206,
- 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983,
- 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671,
- 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372,
- 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411,
- 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734,
- 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779,
- 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479,
- 3329325298,
- ],
- s = ['hex', 'array', 'digest', 'arrayBuffer'],
- u = [];
- (!t.JS_SHA256_NO_NODE_JS && Array.isArray) ||
- (Array.isArray = function (t) {
- return '[object Array]' === Object.prototype.toString.call(t);
- }),
- !n ||
- (!t.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW && ArrayBuffer.isView) ||
- (ArrayBuffer.isView = function (t) {
- return 'object' == typeof t && t.buffer && t.buffer.constructor === ArrayBuffer;
- });
- var c = function (t, e) {
- return function (n) {
- return new f(e, !0).update(n)[t]();
- };
- },
- l = function (t) {
- var e = c('hex', t);
- (e.create = function () {
- return new f(t);
- }),
- (e.update = function (t) {
- return e.create().update(t);
- });
- for (var n = 0; n < s.length; ++n) {
- var i = s[n];
- e[i] = c(i, t);
- }
- return e;
- },
- d = function (t, e) {
- return function (n, i) {
- return new g(n, e, !0).update(i)[t]();
- };
- },
- h = function (t) {
- var e = d('hex', t);
- (e.create = function (e) {
- return new g(e, t);
- }),
- (e.update = function (t, n) {
- return e.create(t).update(n);
- });
- for (var n = 0; n < s.length; ++n) {
- var i = s[n];
- e[i] = d(i, t);
- }
- return e;
- };
- function f(t, e) {
- e
- ? ((u[0] =
- u[16] =
- u[1] =
- u[2] =
- u[3] =
- u[4] =
- u[5] =
- u[6] =
- u[7] =
- u[8] =
- u[9] =
- u[10] =
- u[11] =
- u[12] =
- u[13] =
- u[14] =
- u[15] =
- 0),
- (this.blocks = u))
- : (this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
- t
- ? ((this.h0 = 3238371032),
- (this.h1 = 914150663),
- (this.h2 = 812702999),
- (this.h3 = 4144912697),
- (this.h4 = 4290775857),
- (this.h5 = 1750603025),
- (this.h6 = 1694076839),
- (this.h7 = 3204075428))
- : ((this.h0 = 1779033703),
- (this.h1 = 3144134277),
- (this.h2 = 1013904242),
- (this.h3 = 2773480762),
- (this.h4 = 1359893119),
- (this.h5 = 2600822924),
- (this.h6 = 528734635),
- (this.h7 = 1541459225)),
- (this.block = this.start = this.bytes = this.hBytes = 0),
- (this.finalized = this.hashed = !1),
- (this.first = !0),
- (this.is224 = t);
- }
- function g(t, i, r) {
- var a,
- o = typeof t;
- if ('string' === o) {
- var s,
- u = [],
- c = t.length,
- l = 0;
- for (a = 0; a < c; ++a)
- (s = t.charCodeAt(a)) < 128
- ? (u[l++] = s)
- : s < 2048
- ? ((u[l++] = 192 | (s >> 6)), (u[l++] = 128 | (63 & s)))
- : s < 55296 || s >= 57344
- ? ((u[l++] = 224 | (s >> 12)),
- (u[l++] = 128 | ((s >> 6) & 63)),
- (u[l++] = 128 | (63 & s)))
- : ((s = 65536 + (((1023 & s) << 10) | (1023 & t.charCodeAt(++a)))),
- (u[l++] = 240 | (s >> 18)),
- (u[l++] = 128 | ((s >> 12) & 63)),
- (u[l++] = 128 | ((s >> 6) & 63)),
- (u[l++] = 128 | (63 & s)));
- t = u;
- } else {
- if ('object' !== o) throw new Error(e);
- if (null === t) throw new Error(e);
- if (n && t.constructor === ArrayBuffer) t = new Uint8Array(t);
- else if (!(Array.isArray(t) || (n && ArrayBuffer.isView(t)))) throw new Error(e);
- }
- t.length > 64 && (t = new f(i, !0).update(t).array());
- var d = [],
- h = [];
- for (a = 0; a < 64; ++a) {
- var g = t[a] || 0;
- (d[a] = 92 ^ g), (h[a] = 54 ^ g);
- }
- f.call(this, i, r),
- this.update(h),
- (this.oKeyPad = d),
- (this.inner = !0),
- (this.sharedMemory = r);
- }
- (f.prototype.update = function (t) {
- if (!this.finalized) {
- var i,
- r = typeof t;
- if ('string' !== r) {
- if ('object' !== r) throw new Error(e);
- if (null === t) throw new Error(e);
- if (n && t.constructor === ArrayBuffer) t = new Uint8Array(t);
- else if (!(Array.isArray(t) || (n && ArrayBuffer.isView(t)))) throw new Error(e);
- i = !0;
- }
- for (var o, s, u = 0, c = t.length, l = this.blocks; u < c; ) {
- if (
- (this.hashed &&
- ((this.hashed = !1),
- (l[0] = this.block),
- (l[16] =
- l[1] =
- l[2] =
- l[3] =
- l[4] =
- l[5] =
- l[6] =
- l[7] =
- l[8] =
- l[9] =
- l[10] =
- l[11] =
- l[12] =
- l[13] =
- l[14] =
- l[15] =
- 0)),
- i)
- )
- for (s = this.start; u < c && s < 64; ++u) l[s >> 2] |= t[u] << a[3 & s++];
- else
- for (s = this.start; u < c && s < 64; ++u)
- (o = t.charCodeAt(u)) < 128
- ? (l[s >> 2] |= o << a[3 & s++])
- : o < 2048
- ? ((l[s >> 2] |= (192 | (o >> 6)) << a[3 & s++]),
- (l[s >> 2] |= (128 | (63 & o)) << a[3 & s++]))
- : o < 55296 || o >= 57344
- ? ((l[s >> 2] |= (224 | (o >> 12)) << a[3 & s++]),
- (l[s >> 2] |= (128 | ((o >> 6) & 63)) << a[3 & s++]),
- (l[s >> 2] |= (128 | (63 & o)) << a[3 & s++]))
- : ((o = 65536 + (((1023 & o) << 10) | (1023 & t.charCodeAt(++u)))),
- (l[s >> 2] |= (240 | (o >> 18)) << a[3 & s++]),
- (l[s >> 2] |= (128 | ((o >> 12) & 63)) << a[3 & s++]),
- (l[s >> 2] |= (128 | ((o >> 6) & 63)) << a[3 & s++]),
- (l[s >> 2] |= (128 | (63 & o)) << a[3 & s++]));
- (this.lastByteIndex = s),
- (this.bytes += s - this.start),
- s >= 64
- ? ((this.block = l[16]), (this.start = s - 64), this.hash(), (this.hashed = !0))
- : (this.start = s);
- }
- return (
- this.bytes > 4294967295 &&
- ((this.hBytes += (this.bytes / 4294967296) << 0),
- (this.bytes = this.bytes % 4294967296)),
- this
- );
- }
- }),
- (f.prototype.finalize = function () {
- if (!this.finalized) {
- this.finalized = !0;
- var t = this.blocks,
- e = this.lastByteIndex;
- (t[16] = this.block),
- (t[e >> 2] |= r[3 & e]),
- (this.block = t[16]),
- e >= 56 &&
- (this.hashed || this.hash(),
- (t[0] = this.block),
- (t[16] =
- t[1] =
- t[2] =
- t[3] =
- t[4] =
- t[5] =
- t[6] =
- t[7] =
- t[8] =
- t[9] =
- t[10] =
- t[11] =
- t[12] =
- t[13] =
- t[14] =
- t[15] =
- 0)),
- (t[14] = (this.hBytes << 3) | (this.bytes >>> 29)),
- (t[15] = this.bytes << 3),
- this.hash();
- }
- }),
- (f.prototype.hash = function () {
- var t,
- e,
- n,
- i,
- r,
- a,
- s,
- u,
- c,
- l = this.h0,
- d = this.h1,
- h = this.h2,
- f = this.h3,
- g = this.h4,
- p = this.h5,
- v = this.h6,
- _ = this.h7,
- m = this.blocks;
- for (t = 16; t < 64; ++t)
- (e = (((r = m[t - 15]) >>> 7) | (r << 25)) ^ ((r >>> 18) | (r << 14)) ^ (r >>> 3)),
- (n = (((r = m[t - 2]) >>> 17) | (r << 15)) ^ ((r >>> 19) | (r << 13)) ^ (r >>> 10)),
- (m[t] = (m[t - 16] + e + m[t - 7] + n) << 0);
- for (c = d & h, t = 0; t < 64; t += 4)
- this.first
- ? (this.is224
- ? ((a = 300032),
- (_ = ((r = m[0] - 1413257819) - 150054599) << 0),
- (f = (r + 24177077) << 0))
- : ((a = 704751109),
- (_ = ((r = m[0] - 210244248) - 1521486534) << 0),
- (f = (r + 143694565) << 0)),
- (this.first = !1))
- : ((e =
- ((l >>> 2) | (l << 30)) ^ ((l >>> 13) | (l << 19)) ^ ((l >>> 22) | (l << 10))),
- (i = (a = l & d) ^ (l & h) ^ c),
- (_ =
- (f +
- (r =
- _ +
- (n =
- ((g >>> 6) | (g << 26)) ^
- ((g >>> 11) | (g << 21)) ^
- ((g >>> 25) | (g << 7))) +
- ((g & p) ^ (~g & v)) +
- o[t] +
- m[t])) <<
- 0),
- (f = (r + (e + i)) << 0)),
- (e = ((f >>> 2) | (f << 30)) ^ ((f >>> 13) | (f << 19)) ^ ((f >>> 22) | (f << 10))),
- (i = (s = f & l) ^ (f & d) ^ a),
- (v =
- (h +
- (r =
- v +
- (n =
- ((_ >>> 6) | (_ << 26)) ^
- ((_ >>> 11) | (_ << 21)) ^
- ((_ >>> 25) | (_ << 7))) +
- ((_ & g) ^ (~_ & p)) +
- o[t + 1] +
- m[t + 1])) <<
- 0),
- (e =
- (((h = (r + (e + i)) << 0) >>> 2) | (h << 30)) ^
- ((h >>> 13) | (h << 19)) ^
- ((h >>> 22) | (h << 10))),
- (i = (u = h & f) ^ (h & l) ^ s),
- (p =
- (d +
- (r =
- p +
- (n =
- ((v >>> 6) | (v << 26)) ^
- ((v >>> 11) | (v << 21)) ^
- ((v >>> 25) | (v << 7))) +
- ((v & _) ^ (~v & g)) +
- o[t + 2] +
- m[t + 2])) <<
- 0),
- (e =
- (((d = (r + (e + i)) << 0) >>> 2) | (d << 30)) ^
- ((d >>> 13) | (d << 19)) ^
- ((d >>> 22) | (d << 10))),
- (i = (c = d & h) ^ (d & f) ^ u),
- (g =
- (l +
- (r =
- g +
- (n =
- ((p >>> 6) | (p << 26)) ^
- ((p >>> 11) | (p << 21)) ^
- ((p >>> 25) | (p << 7))) +
- ((p & v) ^ (~p & _)) +
- o[t + 3] +
- m[t + 3])) <<
- 0),
- (l = (r + (e + i)) << 0);
- (this.h0 = (this.h0 + l) << 0),
- (this.h1 = (this.h1 + d) << 0),
- (this.h2 = (this.h2 + h) << 0),
- (this.h3 = (this.h3 + f) << 0),
- (this.h4 = (this.h4 + g) << 0),
- (this.h5 = (this.h5 + p) << 0),
- (this.h6 = (this.h6 + v) << 0),
- (this.h7 = (this.h7 + _) << 0);
- }),
- (f.prototype.hex = function () {
- this.finalize();
- var t = this.h0,
- e = this.h1,
- n = this.h2,
- r = this.h3,
- a = this.h4,
- o = this.h5,
- s = this.h6,
- u = this.h7,
- c =
- i[(t >> 28) & 15] +
- i[(t >> 24) & 15] +
- i[(t >> 20) & 15] +
- i[(t >> 16) & 15] +
- i[(t >> 12) & 15] +
- i[(t >> 8) & 15] +
- i[(t >> 4) & 15] +
- i[15 & t] +
- i[(e >> 28) & 15] +
- i[(e >> 24) & 15] +
- i[(e >> 20) & 15] +
- i[(e >> 16) & 15] +
- i[(e >> 12) & 15] +
- i[(e >> 8) & 15] +
- i[(e >> 4) & 15] +
- i[15 & e] +
- i[(n >> 28) & 15] +
- i[(n >> 24) & 15] +
- i[(n >> 20) & 15] +
- i[(n >> 16) & 15] +
- i[(n >> 12) & 15] +
- i[(n >> 8) & 15] +
- i[(n >> 4) & 15] +
- i[15 & n] +
- i[(r >> 28) & 15] +
- i[(r >> 24) & 15] +
- i[(r >> 20) & 15] +
- i[(r >> 16) & 15] +
- i[(r >> 12) & 15] +
- i[(r >> 8) & 15] +
- i[(r >> 4) & 15] +
- i[15 & r] +
- i[(a >> 28) & 15] +
- i[(a >> 24) & 15] +
- i[(a >> 20) & 15] +
- i[(a >> 16) & 15] +
- i[(a >> 12) & 15] +
- i[(a >> 8) & 15] +
- i[(a >> 4) & 15] +
- i[15 & a] +
- i[(o >> 28) & 15] +
- i[(o >> 24) & 15] +
- i[(o >> 20) & 15] +
- i[(o >> 16) & 15] +
- i[(o >> 12) & 15] +
- i[(o >> 8) & 15] +
- i[(o >> 4) & 15] +
- i[15 & o] +
- i[(s >> 28) & 15] +
- i[(s >> 24) & 15] +
- i[(s >> 20) & 15] +
- i[(s >> 16) & 15] +
- i[(s >> 12) & 15] +
- i[(s >> 8) & 15] +
- i[(s >> 4) & 15] +
- i[15 & s];
- return (
- this.is224 ||
- (c +=
- i[(u >> 28) & 15] +
- i[(u >> 24) & 15] +
- i[(u >> 20) & 15] +
- i[(u >> 16) & 15] +
- i[(u >> 12) & 15] +
- i[(u >> 8) & 15] +
- i[(u >> 4) & 15] +
- i[15 & u]),
- c
- );
- }),
- (f.prototype.toString = f.prototype.hex),
- (f.prototype.digest = function () {
- this.finalize();
- var t = this.h0,
- e = this.h1,
- n = this.h2,
- i = this.h3,
- r = this.h4,
- a = this.h5,
- o = this.h6,
- s = this.h7,
- u = [
- (t >> 24) & 255,
- (t >> 16) & 255,
- (t >> 8) & 255,
- 255 & t,
- (e >> 24) & 255,
- (e >> 16) & 255,
- (e >> 8) & 255,
- 255 & e,
- (n >> 24) & 255,
- (n >> 16) & 255,
- (n >> 8) & 255,
- 255 & n,
- (i >> 24) & 255,
- (i >> 16) & 255,
- (i >> 8) & 255,
- 255 & i,
- (r >> 24) & 255,
- (r >> 16) & 255,
- (r >> 8) & 255,
- 255 & r,
- (a >> 24) & 255,
- (a >> 16) & 255,
- (a >> 8) & 255,
- 255 & a,
- (o >> 24) & 255,
- (o >> 16) & 255,
- (o >> 8) & 255,
- 255 & o,
- ];
- return this.is224 || u.push((s >> 24) & 255, (s >> 16) & 255, (s >> 8) & 255, 255 & s), u;
- }),
- (f.prototype.array = f.prototype.digest),
- (f.prototype.arrayBuffer = function () {
- this.finalize();
- var t = new ArrayBuffer(this.is224 ? 28 : 32),
- e = new DataView(t);
- return (
- e.setUint32(0, this.h0),
- e.setUint32(4, this.h1),
- e.setUint32(8, this.h2),
- e.setUint32(12, this.h3),
- e.setUint32(16, this.h4),
- e.setUint32(20, this.h5),
- e.setUint32(24, this.h6),
- this.is224 || e.setUint32(28, this.h7),
- t
- );
- }),
- (g.prototype = new f()),
- (g.prototype.finalize = function () {
- if ((f.prototype.finalize.call(this), this.inner)) {
- this.inner = !1;
- var t = this.array();
- f.call(this, this.is224, this.sharedMemory),
- this.update(this.oKeyPad),
- this.update(t),
- f.prototype.finalize.call(this);
- }
- });
- var p = l();
- (p.sha256 = p),
- (p.sha224 = l(!0)),
- (p.sha256.hmac = h()),
- (p.sha224.hmac = h(!0)),
- (t.sha256 = p.sha256),
- (t.sha224 = p.sha224);
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- ((_POSignalsEntities || (_POSignalsEntities = {})).FingerprintJS = (function (t) {
- 'use strict';
- function e(t, e) {
- (t = [t[0] >>> 16, 65535 & t[0], t[1] >>> 16, 65535 & t[1]]),
- (e = [e[0] >>> 16, 65535 & e[0], e[1] >>> 16, 65535 & e[1]]);
- var n = [0, 0, 0, 0];
- return (
- (n[3] += t[3] + e[3]),
- (n[2] += n[3] >>> 16),
- (n[3] &= 65535),
- (n[2] += t[2] + e[2]),
- (n[1] += n[2] >>> 16),
- (n[2] &= 65535),
- (n[1] += t[1] + e[1]),
- (n[0] += n[1] >>> 16),
- (n[1] &= 65535),
- (n[0] += t[0] + e[0]),
- (n[0] &= 65535),
- [(n[0] << 16) | n[1], (n[2] << 16) | n[3]]
- );
- }
- function n(t, e) {
- (t = [t[0] >>> 16, 65535 & t[0], t[1] >>> 16, 65535 & t[1]]),
- (e = [e[0] >>> 16, 65535 & e[0], e[1] >>> 16, 65535 & e[1]]);
- var n = [0, 0, 0, 0];
- return (
- (n[3] += t[3] * e[3]),
- (n[2] += n[3] >>> 16),
- (n[3] &= 65535),
- (n[2] += t[2] * e[3]),
- (n[1] += n[2] >>> 16),
- (n[2] &= 65535),
- (n[2] += t[3] * e[2]),
- (n[1] += n[2] >>> 16),
- (n[2] &= 65535),
- (n[1] += t[1] * e[3]),
- (n[0] += n[1] >>> 16),
- (n[1] &= 65535),
- (n[1] += t[2] * e[2]),
- (n[0] += n[1] >>> 16),
- (n[1] &= 65535),
- (n[1] += t[3] * e[1]),
- (n[0] += n[1] >>> 16),
- (n[1] &= 65535),
- (n[0] += t[0] * e[3] + t[1] * e[2] + t[2] * e[1] + t[3] * e[0]),
- (n[0] &= 65535),
- [(n[0] << 16) | n[1], (n[2] << 16) | n[3]]
- );
- }
- function i(t, e) {
- return 32 == (e %= 64)
- ? [t[1], t[0]]
- : e < 32
- ? [(t[0] << e) | (t[1] >>> (32 - e)), (t[1] << e) | (t[0] >>> (32 - e))]
- : ((e -= 32), [(t[1] << e) | (t[0] >>> (32 - e)), (t[0] << e) | (t[1] >>> (32 - e))]);
- }
- function r(t, e) {
- return 0 == (e %= 64)
- ? t
- : e < 32
- ? [(t[0] << e) | (t[1] >>> (32 - e)), t[1] << e]
- : [t[1] << (e - 32), 0];
- }
- function a(t, e) {
- return [t[0] ^ e[0], t[1] ^ e[1]];
- }
- function o(t) {
- return (t = a(
- (t = n(
- (t = a((t = n((t = a(t, [0, t[0] >>> 1])), [4283543511, 3981806797])), [
- 0,
- t[0] >>> 1,
- ])),
- [3301882366, 444984403],
- )),
- [0, t[0] >>> 1],
- ));
- }
- function s(t, s) {
- (t = t || ''), (s = s || 0);
- var u,
- c = t.length % 16,
- l = t.length - c,
- d = [0, s],
- h = [0, s],
- f = [0, 0],
- g = [0, 0],
- p = [2277735313, 289559509],
- v = [1291169091, 658871167];
- for (u = 0; u < l; u += 16)
- (f = [
- (255 & t.charCodeAt(u + 4)) |
- ((255 & t.charCodeAt(u + 5)) << 8) |
- ((255 & t.charCodeAt(u + 6)) << 16) |
- ((255 & t.charCodeAt(u + 7)) << 24),
- (255 & t.charCodeAt(u)) |
- ((255 & t.charCodeAt(u + 1)) << 8) |
- ((255 & t.charCodeAt(u + 2)) << 16) |
- ((255 & t.charCodeAt(u + 3)) << 24),
- ]),
- (g = [
- (255 & t.charCodeAt(u + 12)) |
- ((255 & t.charCodeAt(u + 13)) << 8) |
- ((255 & t.charCodeAt(u + 14)) << 16) |
- ((255 & t.charCodeAt(u + 15)) << 24),
- (255 & t.charCodeAt(u + 8)) |
- ((255 & t.charCodeAt(u + 9)) << 8) |
- ((255 & t.charCodeAt(u + 10)) << 16) |
- ((255 & t.charCodeAt(u + 11)) << 24),
- ]),
- (d = e(
- n(
- (d = e((d = i((d = a(d, (f = n((f = i((f = n(f, p)), 31)), v)))), 27)), h)),
- [0, 5],
- ),
- [0, 1390208809],
- )),
- (h = e(
- n(
- (h = e((h = i((h = a(h, (g = n((g = i((g = n(g, v)), 33)), p)))), 31)), d)),
- [0, 5],
- ),
- [0, 944331445],
- ));
- switch (((f = [0, 0]), (g = [0, 0]), c)) {
- case 15:
- g = a(g, r([0, t.charCodeAt(u + 14)], 48));
- case 14:
- g = a(g, r([0, t.charCodeAt(u + 13)], 40));
- case 13:
- g = a(g, r([0, t.charCodeAt(u + 12)], 32));
- case 12:
- g = a(g, r([0, t.charCodeAt(u + 11)], 24));
- case 11:
- g = a(g, r([0, t.charCodeAt(u + 10)], 16));
- case 10:
- g = a(g, r([0, t.charCodeAt(u + 9)], 8));
- case 9:
- h = a(h, (g = n((g = i((g = n((g = a(g, [0, t.charCodeAt(u + 8)])), v)), 33)), p)));
- case 8:
- f = a(f, r([0, t.charCodeAt(u + 7)], 56));
- case 7:
- f = a(f, r([0, t.charCodeAt(u + 6)], 48));
- case 6:
- f = a(f, r([0, t.charCodeAt(u + 5)], 40));
- case 5:
- f = a(f, r([0, t.charCodeAt(u + 4)], 32));
- case 4:
- f = a(f, r([0, t.charCodeAt(u + 3)], 24));
- case 3:
- f = a(f, r([0, t.charCodeAt(u + 2)], 16));
- case 2:
- f = a(f, r([0, t.charCodeAt(u + 1)], 8));
- case 1:
- d = a(d, (f = n((f = i((f = n((f = a(f, [0, t.charCodeAt(u)])), p)), 31)), v)));
- }
- return (
- (d = a(d, [0, t.length])),
- (h = e((h = a(h, [0, t.length])), (d = e(d, h)))),
- (d = o(d)),
- (h = e((h = o(h)), (d = e(d, h)))),
- ('00000000' + (d[0] >>> 0).toString(16)).slice(-8) +
- ('00000000' + (d[1] >>> 0).toString(16)).slice(-8) +
- ('00000000' + (h[0] >>> 0).toString(16)).slice(-8) +
- ('00000000' + (h[1] >>> 0).toString(16)).slice(-8)
- );
- }
- var u = function () {
- return (u =
- Object.assign ||
- function (t) {
- for (var e, n = 1, i = arguments.length; n < i; n++)
- for (var r in (e = arguments[n]))
- Object.prototype.hasOwnProperty.call(e, r) && (t[r] = e[r]);
- return t;
- }).apply(this, arguments);
- };
- function c(t, e, n, i) {
- return new (n || (n = Promise))(function (r, a) {
- function o(t) {
- try {
- u(i.next(t));
- } catch (t) {
- a(t);
- }
- }
- function s(t) {
- try {
- u(i.throw(t));
- } catch (t) {
- a(t);
- }
- }
- function u(t) {
- var e;
- t.done
- ? r(t.value)
- : ((e = t.value),
- e instanceof n
- ? e
- : new n(function (t) {
- t(e);
- })).then(o, s);
- }
- u((i = i.apply(t, e || [])).next());
- });
- }
- function l(t, e) {
- var n,
- i,
- r,
- a,
- o = {
- label: 0,
- sent: function () {
- if (1 & r[0]) throw r[1];
- return r[1];
- },
- trys: [],
- ops: [],
- };
- return (
- (a = { next: s(0), throw: s(1), return: s(2) }),
- 'function' == typeof Symbol &&
- (a[Symbol.iterator] = function () {
- return this;
- }),
- a
- );
- function s(a) {
- return function (s) {
- return (function (a) {
- if (n) throw new TypeError('Generator is already executing.');
- for (; o; )
- try {
- if (
- ((n = 1),
- i &&
- (r =
- 2 & a[0]
- ? i.return
- : a[0]
- ? i.throw || ((r = i.return) && r.call(i), 0)
- : i.next) &&
- !(r = r.call(i, a[1])).done)
- )
- return r;
- switch (((i = 0), r && (a = [2 & a[0], r.value]), a[0])) {
- case 0:
- case 1:
- r = a;
- break;
- case 4:
- return o.label++, { value: a[1], done: !1 };
- case 5:
- o.label++, (i = a[1]), (a = [0]);
- continue;
- case 7:
- (a = o.ops.pop()), o.trys.pop();
- continue;
- default:
- if (
- !(r = (r = o.trys).length > 0 && r[r.length - 1]) &&
- (6 === a[0] || 2 === a[0])
- ) {
- o = 0;
- continue;
- }
- if (3 === a[0] && (!r || (a[1] > r[0] && a[1] < r[3]))) {
- o.label = a[1];
- break;
- }
- if (6 === a[0] && o.label < r[1]) {
- (o.label = r[1]), (r = a);
- break;
- }
- if (r && o.label < r[2]) {
- (o.label = r[2]), o.ops.push(a);
- break;
- }
- r[2] && o.ops.pop(), o.trys.pop();
- continue;
- }
- a = e.call(t, o);
- } catch (t) {
- (a = [6, t]), (i = 0);
- } finally {
- n = r = 0;
- }
- if (5 & a[0]) throw a[1];
- return { value: a[0] ? a[1] : void 0, done: !0 };
- })([a, s]);
- };
- }
- }
- var d = window;
- function h(t) {
- return parseInt(t);
- }
- function f(t) {
- return parseFloat(t);
- }
- function g(t) {
- return t.reduce(function (t, e) {
- return t + (e ? 1 : 0);
- }, 0);
- }
- var p = window,
- v = navigator,
- _ = document;
- function m() {
- return (
- g([
- 'MSCSSMatrix' in p,
- 'msSetImmediate' in p,
- 'msIndexedDB' in p,
- 'msMaxTouchPoints' in v,
- 'msPointerEnabled' in v,
- ]) >= 4
- );
- }
- function y() {
- return (
- g(['msWriteProfilerMark' in p, 'MSStream' in p, 'msLaunchUri' in v, 'msSaveBlob' in v]) >=
- 3 && !m()
- );
- }
- function b() {
- return (
- g([
- 'webkitPersistentStorage' in v,
- 'webkitTemporaryStorage' in v,
- 0 === v.vendor.indexOf('Google'),
- 'webkitResolveLocalFileSystemURL' in p,
- 'BatteryManager' in p,
- 'webkitMediaStream' in p,
- 'webkitSpeechGrammar' in p,
- ]) >= 5
- );
- }
- function E() {
- return (
- g([
- 'ApplePayError' in p,
- 'CSSPrimitiveValue' in p,
- 'Counter' in p,
- 0 === v.vendor.indexOf('Apple'),
- 'getStorageUpdates' in v,
- 'WebKitMediaKeys' in p,
- ]) >= 4
- );
- }
- function w() {
- return (
- g([
- 'safari' in p,
- !('DeviceMotionEvent' in p),
- !('ongestureend' in p),
- !('standalone' in v),
- ]) >= 3
- );
- }
- var S = window,
- A = document;
- function O(t, e, n) {
- (function (t) {
- return t && 'function' == typeof t.setValueAtTime;
- })(e) && e.setValueAtTime(n, t.currentTime);
- }
- function P(t) {
- var e = new Error(t);
- return (e.name = t), e;
- }
- var T = document,
- I = 'mmMwWLliI0O&1',
- D = ['monospace', 'sans-serif', 'serif'],
- C = [
- 'sans-serif-thin',
- 'ARNO PRO',
- 'Agency FB',
- 'Arabic Typesetting',
- 'Arial Unicode MS',
- 'AvantGarde Bk BT',
- 'BankGothic Md BT',
- 'Batang',
- 'Bitstream Vera Sans Mono',
- 'Calibri',
- 'Century',
- 'Century Gothic',
- 'Clarendon',
- 'EUROSTILE',
- 'Franklin Gothic',
- 'Futura Bk BT',
- 'Futura Md BT',
- 'GOTHAM',
- 'Gill Sans',
- 'HELV',
- 'Haettenschweiler',
- 'Helvetica Neue',
- 'Humanst521 BT',
- 'Leelawadee',
- 'Letter Gothic',
- 'Levenim MT',
- 'Lucida Bright',
- 'Lucida Sans',
- 'Menlo',
- 'MS Mincho',
- 'MS Outlook',
- 'MS Reference Specialty',
- 'MS UI Gothic',
- 'MT Extra',
- 'MYRIAD PRO',
- 'Marlett',
- 'Meiryo UI',
- 'Microsoft Uighur',
- 'Minion Pro',
- 'Monotype Corsiva',
- 'PMingLiU',
- 'Pristina',
- 'SCRIPTINA',
- 'Segoe UI Light',
- 'Serifa',
- 'SimHei',
- 'Small Fonts',
- 'Staccato222 BT',
- 'TRAJAN PRO',
- 'Univers CE 55 Medium',
- 'Vrinda',
- 'ZWAdobeF',
- ],
- M = {
- fontStyle: 'normal',
- fontWeight: 'normal',
- letterSpacing: 'normal',
- lineBreak: 'auto',
- lineHeight: 'normal',
- textTransform: 'none',
- textAlign: 'left',
- textDecoration: 'none',
- textShadow: 'none',
- whiteSpace: 'normal',
- wordBreak: 'normal',
- wordSpacing: 'normal',
- position: 'absolute',
- left: '-9999px',
- fontSize: '48px',
- },
- L = navigator,
- U = window,
- k = navigator,
- x = window,
- R = window,
- N = window,
- B = document,
- H = {
- osCpu: function () {
- return navigator.oscpu;
- },
- languages: function () {
- var t = [],
- e = k.language || k.userLanguage || k.browserLanguage || k.systemLanguage;
- if ((void 0 !== e && t.push([e]), Array.isArray(k.languages)))
- (b() &&
- g([
- !('MediaSettingsRange' in p),
- 'RTCEncodedAudioFrame' in p,
- '' + p.Intl == '[object Intl]',
- '' + p.Reflect == '[object Reflect]',
- ]) >= 3) ||
- t.push(k.languages);
- else if ('string' == typeof k.languages) {
- var n = k.languages;
- n && t.push(n.split(','));
- }
- return t;
- },
- colorDepth: function () {
- return window.screen.colorDepth;
- },
- deviceMemory: function () {
- return (
- (t = f(navigator.deviceMemory)),
- (e = void 0),
- 'number' == typeof t && isNaN(t) ? e : t
- );
- var t, e;
- },
- screenResolution: function () {
- var t = [h(x.screen.width), h(x.screen.height)];
- return t.sort().reverse(), t;
- },
- availableScreenResolution: function () {
- if (R.screen.availWidth && R.screen.availHeight) {
- var t = [h(R.screen.availWidth), h(R.screen.availHeight)];
- return t.sort().reverse(), t;
- }
- },
- hardwareConcurrency: function () {
- try {
- var t = h(navigator.hardwareConcurrency);
- return isNaN(t) ? 1 : t;
- } catch (t) {
- return 1;
- }
- },
- timezoneOffset: function () {
- var t = new Date().getFullYear();
- return Math.max(
- f(new Date(t, 0, 1).getTimezoneOffset()),
- f(new Date(t, 6, 1).getTimezoneOffset()),
- );
- },
- timezone: function () {
- var t;
- if (null === (t = N.Intl) || void 0 === t ? void 0 : t.DateTimeFormat)
- return new N.Intl.DateTimeFormat().resolvedOptions().timeZone;
- },
- sessionStorage: function () {
- try {
- return !!window.sessionStorage;
- } catch (t) {
- return !0;
- }
- },
- localStorage: function () {
- try {
- return !!window.localStorage;
- } catch (t) {
- return !0;
- }
- },
- indexedDB: function () {
- if (!m() && !y())
- try {
- return !!window.indexedDB;
- } catch (t) {
- return !0;
- }
- },
- openDatabase: function () {
- return !!window.openDatabase;
- },
- cpuClass: function () {
- return navigator.cpuClass;
- },
- platform: function () {
- return navigator.platform;
- },
- plugins: function () {
- if (m()) return [];
- if (navigator.plugins) {
- for (var t = [], e = 0; e < navigator.plugins.length; ++e) {
- var n = navigator.plugins[e];
- if (n) {
- for (var i = [], r = 0; r < n.length; ++r) {
- var a = n[r];
- i.push({ type: a.type, suffixes: a.suffixes });
- }
- t.push({ name: n.name, description: n.description, mimeTypes: i });
- }
- }
- return t;
- }
- },
- canvas: function () {
- var t = (function () {
- var t = document.createElement('canvas');
- return (
- (t.width = 240),
- (t.height = 140),
- (t.style.display = 'inline'),
- [t, t.getContext('2d')]
- );
- })(),
- e = t[0],
- n = t[1];
- if (
- !(function (t, e) {
- return !(!e || !t.toDataURL);
- })(e, n)
- )
- return { winding: !1, data: '' };
- n.rect(0, 0, 10, 10), n.rect(2, 2, 6, 6);
- var i = !n.isPointInPath(5, 5, 'evenodd');
- return (
- (n.textBaseline = 'alphabetic'),
- (n.fillStyle = '#f60'),
- n.fillRect(125, 1, 62, 20),
- (n.fillStyle = '#069'),
- (n.font = '11pt no-real-font-123'),
- n.fillText('Cwm fjordbank 😃 gly', 2, 15),
- (n.fillStyle = 'rgba(102, 204, 0, 0.2)'),
- (n.font = '18pt Arial'),
- n.fillText('Cwm fjordbank 😃 gly', 4, 45),
- (n.globalCompositeOperation = 'multiply'),
- (n.fillStyle = 'rgb(255,0,255)'),
- n.beginPath(),
- n.arc(50, 50, 50, 0, 2 * Math.PI, !0),
- n.closePath(),
- n.fill(),
- (n.fillStyle = 'rgb(0,255,255)'),
- n.beginPath(),
- n.arc(100, 50, 50, 0, 2 * Math.PI, !0),
- n.closePath(),
- n.fill(),
- (n.fillStyle = 'rgb(255,255,0)'),
- n.beginPath(),
- n.arc(75, 100, 50, 0, 2 * Math.PI, !0),
- n.closePath(),
- n.fill(),
- (n.fillStyle = 'rgb(255,0,255)'),
- n.arc(75, 75, 75, 0, 2 * Math.PI, !0),
- n.arc(75, 75, 25, 0, 2 * Math.PI, !0),
- n.fill('evenodd'),
- {
- winding: i,
- data: (function (t) {
- return t.toDataURL();
- })(e),
- }
- );
- },
- touchSupport: function () {
- var t,
- e = 0;
- void 0 !== L.maxTouchPoints
- ? (e = h(L.maxTouchPoints))
- : void 0 !== L.msMaxTouchPoints && (e = L.msMaxTouchPoints);
- try {
- document.createEvent('TouchEvent'), (t = !0);
- } catch (e) {
- t = !1;
- }
- return { maxTouchPoints: e, touchEvent: t, touchStart: 'ontouchstart' in U };
- },
- fonts: function () {
- var t = T.body,
- e = T.createElement('div'),
- n = T.createElement('div'),
- i = {},
- r = {},
- a = function () {
- var t = T.createElement('span');
- t.textContent = I;
- for (var e = 0, n = Object.keys(M); e < n.length; e++) {
- var i = n[e];
- t.style[i] = M[i];
- }
- return t;
- },
- o = function (t) {
- return D.some(function (e, n) {
- return t[n].offsetWidth !== i[e] || t[n].offsetHeight !== r[e];
- });
- },
- s = D.map(function (t) {
- var n = a();
- return (n.style.fontFamily = t), e.appendChild(n), n;
- });
- t.appendChild(e);
- for (var u = 0, c = D.length; u < c; u++)
- (i[D[u]] = s[u].offsetWidth), (r[D[u]] = s[u].offsetHeight);
- var l = (function () {
- for (
- var t = {},
- e = function (e) {
- t[e] = D.map(function (t) {
- var i = (function (t, e) {
- var n = a();
- return (n.style.fontFamily = "'" + t + "'," + e), n;
- })(e, t);
- return n.appendChild(i), i;
- });
- },
- i = 0,
- r = C;
- i < r.length;
- i++
- )
- e(r[i]);
- return t;
- })();
- t.appendChild(n);
- for (var d = [], h = 0, f = C.length; h < f; h++) o(l[C[h]]) && d.push(C[h]);
- return t.removeChild(n), t.removeChild(e), d;
- },
- audio: function () {
- return c(this, void 0, void 0, function () {
- var t, e, n, i, r, a;
- return l(this, function (o) {
- switch (o.label) {
- case 0:
- if (!(t = S.OfflineAudioContext || S.webkitOfflineAudioContext)) return [2, -2];
- if (
- E() &&
- !w() &&
- !(
- g([
- 'DOMRectList' in p,
- 'RTCPeerConnectionIceEvent' in p,
- 'SVGGeometryElement' in p,
- 'ontransitioncancel' in p,
- ]) >= 3
- )
- )
- return [2, -1];
- (e = new t(1, 44100, 44100)),
- ((n = e.createOscillator()).type = 'triangle'),
- O(e, n.frequency, 1e4),
- (i = e.createDynamicsCompressor()),
- O(e, i.threshold, -50),
- O(e, i.knee, 40),
- O(e, i.ratio, 12),
- O(e, i.reduction, -20),
- O(e, i.attack, 0),
- O(e, i.release, 0.25),
- n.connect(i),
- i.connect(e.destination),
- n.start(0),
- (o.label = 1);
- case 1:
- return (
- o.trys.push([1, 3, 4, 5]),
- [
- 4,
- (function (t) {
- return new Promise(function (e, n) {
- t.oncomplete = function (t) {
- return e(t.renderedBuffer);
- };
- var i = 3,
- r = function () {
- switch ((t.startRendering(), t.state)) {
- case 'running':
- setTimeout(function () {
- return n(P('timeout'));
- }, 1e3);
- break;
- case 'suspended':
- A.hidden || i--, i > 0 ? setTimeout(r, 500) : n(P('suspended'));
- }
- };
- r();
- });
- })(e),
- ]
- );
- case 2:
- return (r = o.sent()), [3, 5];
- case 3:
- if ('timeout' === (a = o.sent()).name || 'suspended' === a.name) return [2, -3];
- throw a;
- case 4:
- return n.disconnect(), i.disconnect(), [7];
- case 5:
- return [
- 2,
- (function (t) {
- for (var e = 0, n = 4500; n < 5e3; ++n) e += Math.abs(t[n]);
- return e;
- })(r.getChannelData(0)),
- ];
- }
- });
- });
- },
- pluginsSupport: function () {
- return void 0 !== navigator.plugins;
- },
- productSub: function () {
- return navigator.productSub;
- },
- emptyEvalLength: function () {
- return eval.toString().length;
- },
- errorFF: function () {
- try {
- throw 'a';
- } catch (t) {
- try {
- return t.toSource(), !0;
- } catch (t) {
- return !1;
- }
- }
- },
- vendor: function () {
- return navigator.vendor;
- },
- chrome: function () {
- return void 0 !== window.chrome;
- },
- cookiesEnabled: function () {
- try {
- B.cookie = 'cookietest=1; SameSite=Strict;';
- var t = -1 !== B.cookie.indexOf('cookietest=');
- return (
- (B.cookie = 'cookietest=1; SameSite=Strict; expires=Thu, 01-Jan-1970 00:00:01 GMT'),
- t
- );
- } catch (t) {
- return !1;
- }
- },
- };
- function F(t, e, n) {
- return c(this, void 0, void 0, function () {
- var i, r, a, o, s, c, d, h, f;
- return l(this, function (l) {
- switch (l.label) {
- case 0:
- (i = Date.now()), (r = {}), (a = 0), (o = Object.keys(t)), (l.label = 1);
- case 1:
- if (!(a < o.length)) return [3, 7];
- if (
- ((s = o[a]),
- (function (t, e) {
- for (var n = 0, i = t.length; n < i; ++n) if (t[n] === e) return !0;
- return !1;
- })(n, s))
- )
- return [3, 6];
- (c = void 0), (l.label = 2);
- case 2:
- return l.trys.push([2, 4, , 5]), (f = {}), [4, t[s](e)];
- case 3:
- return (f.value = l.sent()), (c = f), [3, 5];
- case 4:
- return (
- (d = l.sent()),
- (c =
- d && 'object' == typeof d && 'message' in d
- ? { error: d }
- : { error: { message: d } }),
- [3, 5]
- );
- case 5:
- (h = Date.now()), (r[s] = u(u({}, c), { duration: h - i })), (i = h), (l.label = 6);
- case 6:
- return a++, [3, 1];
- case 7:
- return [2, r];
- }
- });
- });
- }
- function j(t) {
- return JSON.stringify(
- t,
- function (t, e) {
- return e instanceof Error
- ? u(
- {
- name: (n = e).name,
- message: n.message,
- stack: null === (i = n.stack) || void 0 === i ? void 0 : i.split('\n'),
- },
- n,
- )
- : e;
- var n, i;
- },
- 2,
- );
- }
- function G(t) {
- return s(
- (function (t) {
- for (var e = '', n = 0, i = Object.keys(t); n < i.length; n++) {
- var r = i[n],
- a = t[r],
- o = a.error ? 'error' : JSON.stringify(a.value);
- e += (e ? '|' : '') + r.replace(/([:|\\])/g, '\\$1') + ':' + o;
- }
- return e;
- })(t),
- );
- }
- var V = (function () {
- function t() {}
- return (
- (t.prototype.get = function (t) {
- return (
- void 0 === t && (t = {}),
- c(this, void 0, void 0, function () {
- var e, n;
- return l(this, function (i) {
- switch (i.label) {
- case 0:
- return [4, F(H, void 0, [])];
- case 1:
- return (
- (e = i.sent()),
- (n = (function (t) {
- var e;
- return {
- components: t,
- get visitorId() {
- return void 0 === e && (e = G(this.components)), e;
- },
- set visitorId(t) {
- e = t;
- },
- };
- })(e)),
- t.debug &&
- console.log(
- 'Copy the text below to get the debug data:\n\n```\nversion: 3.0.5\nuserAgent: ' +
- navigator.userAgent +
- '\ngetOptions: ' +
- JSON.stringify(t, void 0, 2) +
- '\nvisitorId: ' +
- n.visitorId +
- '\ncomponents: ' +
- j(e) +
- '\n```',
- ),
- [2, n]
- );
- }
- });
- })
- );
- }),
- t
- );
- })();
- function z(t) {
- var e = (void 0 === t ? {} : t).delayFallback,
- n = void 0 === e ? 50 : e;
- return c(this, void 0, void 0, function () {
- return l(this, function (t) {
- switch (t.label) {
- case 0:
- return [
- 4,
- ((e = n),
- (i = 2 * n),
- void 0 === i && (i = 1 / 0),
- new Promise(function (t) {
- d.requestIdleCallback
- ? d.requestIdleCallback(
- function () {
- return t();
- },
- { timeout: i },
- )
- : setTimeout(t, Math.min(e, i));
- })),
- ];
- case 1:
- return t.sent(), [2, new V()];
- }
- var e, i;
- });
- });
- }
- var K = { load: z, hashComponents: G, componentsToDebugString: j },
- Y = s;
- return (
- (t.componentsToDebugString = j),
- (t.default = K),
- (t.getComponents = F),
- (t.hashComponents = G),
- (t.isChromium = b),
- (t.isDesktopSafari = w),
- (t.isEdgeHTML = y),
- (t.isGecko = function () {
- var t;
- return (
- g([
- 'buildID' in v,
- (null === (t = _.documentElement) || void 0 === t ? void 0 : t.style) &&
- 'MozAppearance' in _.documentElement.style,
- 'MediaRecorderErrorEvent' in p,
- 'mozInnerScreenX' in p,
- 'CSSMozDocumentRule' in p,
- 'CanvasCaptureMediaStream' in p,
- ]) >= 4
- );
- }),
- (t.isTrident = m),
- (t.isWebKit = E),
- (t.load = z),
- (t.murmurX64Hash128 = Y),
- t
- );
- })({})),
- (function (t) {
- 'use strict';
- var e,
- n,
- i = function (t, e) {
- var n = 'function' == typeof Symbol && t[Symbol.iterator];
- if (!n) return t;
- var i,
- r,
- a = n.call(t),
- o = [];
- try {
- for (; (void 0 === e || e-- > 0) && !(i = a.next()).done; ) o.push(i.value);
- } catch (t) {
- r = { error: t };
- } finally {
- try {
- i && !i.done && (n = a.return) && n.call(a);
- } finally {
- if (r) throw r.error;
- }
- }
- return o;
- },
- r = function (t, e, n) {
- if (n || 2 === arguments.length)
- for (var i, r = 0, a = e.length; r < a; r++)
- (!i && r in e) || (i || (i = Array.prototype.slice.call(e, 0, r)), (i[r] = e[r]));
- return t.concat(i || Array.prototype.slice.call(e));
- },
- a = new WeakMap(),
- o = new WeakMap(),
- s = new WeakMap(),
- u = new WeakMap(),
- c = new WeakMap(),
- l = {
- get: function (t, e, n) {
- if (t instanceof IDBTransaction) {
- if ('done' === e) return o.get(t);
- if ('objectStoreNames' === e) return t.objectStoreNames || s.get(t);
- if ('store' === e)
- return n.objectStoreNames[1] ? void 0 : n.objectStore(n.objectStoreNames[0]);
- }
- return f(t[e]);
- },
- set: function (t, e, n) {
- return (t[e] = n), !0;
- },
- has: function (t, e) {
- return (t instanceof IDBTransaction && ('done' === e || 'store' === e)) || e in t;
- },
- };
- function d(t) {
- return t !== IDBDatabase.prototype.transaction ||
- 'objectStoreNames' in IDBTransaction.prototype
- ? (
- n ||
- (n = [
- IDBCursor.prototype.advance,
- IDBCursor.prototype.continue,
- IDBCursor.prototype.continuePrimaryKey,
- ])
- ).includes(t)
- ? function () {
- for (var e = [], n = 0; n < arguments.length; n++) e[n] = arguments[n];
- return t.apply(g(this), e), f(a.get(this));
- }
- : function () {
- for (var e = [], n = 0; n < arguments.length; n++) e[n] = arguments[n];
- return f(t.apply(g(this), e));
- }
- : function (e) {
- for (var n = [], a = 1; a < arguments.length; a++) n[a - 1] = arguments[a];
- var o = t.call.apply(t, r([g(this), e], i(n), !1));
- return s.set(o, e.sort ? e.sort() : [e]), f(o);
- };
- }
- function h(t) {
- return 'function' == typeof t
- ? d(t)
- : (t instanceof IDBTransaction &&
- (function (t) {
- if (!o.has(t)) {
- var e = new Promise(function (e, n) {
- var i = function () {
- t.removeEventListener('complete', r),
- t.removeEventListener('error', a),
- t.removeEventListener('abort', a);
- },
- r = function () {
- e(), i();
- },
- a = function () {
- n(t.error || new DOMException('AbortError', 'AbortError')), i();
- };
- t.addEventListener('complete', r),
- t.addEventListener('error', a),
- t.addEventListener('abort', a);
- });
- o.set(t, e);
- }
- })(t),
- (n = t),
- (e || (e = [IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction])).some(
- function (t) {
- return n instanceof t;
- },
- )
- ? new Proxy(t, l)
- : t);
- var n;
- }
- function f(t) {
- if (t instanceof IDBRequest)
- return (
- (e = t),
- (n = new Promise(function (t, n) {
- var i = function () {
- e.removeEventListener('success', r), e.removeEventListener('error', a);
- },
- r = function () {
- t(f(e.result)), i();
- },
- a = function () {
- n(e.error), i();
- };
- e.addEventListener('success', r), e.addEventListener('error', a);
- }))
- .then(function (t) {
- t instanceof IDBCursor && a.set(t, e);
- })
- .catch(function () {}),
- c.set(n, e),
- n
- );
- var e, n;
- if (u.has(t)) return u.get(t);
- var i = h(t);
- return i !== t && (u.set(t, i), c.set(i, t)), i;
- }
- var g = function (t) {
- return c.get(t);
- },
- p = function () {
- return (p =
- Object.assign ||
- function (t) {
- for (var e, n = 1, i = arguments.length; n < i; n++)
- for (var r in (e = arguments[n]))
- Object.prototype.hasOwnProperty.call(e, r) && (t[r] = e[r]);
- return t;
- }).apply(this, arguments);
- },
- v = function (t, e, n, i) {
- return new (n || (n = Promise))(function (r, a) {
- function o(t) {
- try {
- u(i.next(t));
- } catch (t) {
- a(t);
- }
- }
- function s(t) {
- try {
- u(i.throw(t));
- } catch (t) {
- a(t);
- }
- }
- function u(t) {
- var e;
- t.done
- ? r(t.value)
- : ((e = t.value),
- e instanceof n
- ? e
- : new n(function (t) {
- t(e);
- })).then(o, s);
- }
- u((i = i.apply(t, e || [])).next());
- });
- },
- _ = function (t, e) {
- var n,
- i,
- r,
- a,
- o = {
- label: 0,
- sent: function () {
- if (1 & r[0]) throw r[1];
- return r[1];
- },
- trys: [],
- ops: [],
- };
- return (
- (a = { next: s(0), throw: s(1), return: s(2) }),
- 'function' == typeof Symbol &&
- (a[Symbol.iterator] = function () {
- return this;
- }),
- a
- );
- function s(a) {
- return function (s) {
- return (function (a) {
- if (n) throw new TypeError('Generator is already executing.');
- for (; o; )
- try {
- if (
- ((n = 1),
- i &&
- (r =
- 2 & a[0]
- ? i.return
- : a[0]
- ? i.throw || ((r = i.return) && r.call(i), 0)
- : i.next) &&
- !(r = r.call(i, a[1])).done)
- )
- return r;
- switch (((i = 0), r && (a = [2 & a[0], r.value]), a[0])) {
- case 0:
- case 1:
- r = a;
- break;
- case 4:
- return o.label++, { value: a[1], done: !1 };
- case 5:
- o.label++, (i = a[1]), (a = [0]);
- continue;
- case 7:
- (a = o.ops.pop()), o.trys.pop();
- continue;
- default:
- if (
- !(
- (r = (r = o.trys).length > 0 && r[r.length - 1]) ||
- (6 !== a[0] && 2 !== a[0])
- )
- ) {
- o = 0;
- continue;
- }
- if (3 === a[0] && (!r || (a[1] > r[0] && a[1] < r[3]))) {
- o.label = a[1];
- break;
- }
- if (6 === a[0] && o.label < r[1]) {
- (o.label = r[1]), (r = a);
- break;
- }
- if (r && o.label < r[2]) {
- (o.label = r[2]), o.ops.push(a);
- break;
- }
- r[2] && o.ops.pop(), o.trys.pop();
- continue;
- }
- a = e.call(t, o);
- } catch (t) {
- (a = [6, t]), (i = 0);
- } finally {
- n = r = 0;
- }
- if (5 & a[0]) throw a[1];
- return { value: a[0] ? a[1] : void 0, done: !0 };
- })([a, s]);
- };
- }
- },
- m = function (t, e) {
- var n = 'function' == typeof Symbol && t[Symbol.iterator];
- if (!n) return t;
- var i,
- r,
- a = n.call(t),
- o = [];
- try {
- for (; (void 0 === e || e-- > 0) && !(i = a.next()).done; ) o.push(i.value);
- } catch (t) {
- r = { error: t };
- } finally {
- try {
- i && !i.done && (n = a.return) && n.call(a);
- } finally {
- if (r) throw r.error;
- }
- }
- return o;
- },
- y = function (t, e, n) {
- if (n || 2 === arguments.length)
- for (var i, r = 0, a = e.length; r < a; r++)
- (!i && r in e) || (i || (i = Array.prototype.slice.call(e, 0, r)), (i[r] = e[r]));
- return t.concat(i || Array.prototype.slice.call(e));
- },
- b = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'],
- E = ['put', 'add', 'delete', 'clear'],
- w = new Map();
- function S(t, e) {
- if (t instanceof IDBDatabase && !(e in t) && 'string' == typeof e) {
- if (w.get(e)) return w.get(e);
- var n = e.replace(/FromIndex$/, ''),
- i = e !== n,
- r = E.includes(n);
- if (n in (i ? IDBIndex : IDBObjectStore).prototype && (r || b.includes(n))) {
- var a = function (t) {
- for (var e = [], a = 1; a < arguments.length; a++) e[a - 1] = arguments[a];
- return v(this, void 0, void 0, function () {
- var a, o, s;
- return _(this, function (u) {
- switch (u.label) {
- case 0:
- return (
- (a = this.transaction(t, r ? 'readwrite' : 'readonly')),
- (o = a.store),
- i && (o = o.index(e.shift())),
- [4, Promise.all([(s = o)[n].apply(s, y([], m(e), !1)), r && a.done])]
- );
- case 1:
- return [2, u.sent()[0]];
- }
- });
- });
- };
- return w.set(e, a), a;
- }
- }
- }
- (l = (function (t) {
- return p(p({}, t), {
- get: function (e, n, i) {
- return S(e, n) || t.get(e, n, i);
- },
- has: function (e, n) {
- return !!S(e, n) || t.has(e, n);
- },
- });
- })(l)),
- (t.deleteDB = function (t, e) {
- var n = (void 0 === e ? {} : e).blocked,
- i = indexedDB.deleteDatabase(t);
- return (
- n &&
- i.addEventListener('blocked', function (t) {
- return n(t.oldVersion, t);
- }),
- f(i).then(function () {})
- );
- }),
- (t.openDB = function (t, e, n) {
- var i = void 0 === n ? {} : n,
- r = i.blocked,
- a = i.upgrade,
- o = i.blocking,
- s = i.terminated,
- u = indexedDB.open(t, e),
- c = f(u);
- return (
- a &&
- u.addEventListener('upgradeneeded', function (t) {
- a(f(u.result), t.oldVersion, t.newVersion, f(u.transaction), t);
- }),
- r &&
- u.addEventListener('blocked', function (t) {
- return r(t.oldVersion, t.newVersion, t);
- }),
- c
- .then(function (t) {
- s &&
- t.addEventListener('close', function () {
- return s();
- }),
- o &&
- t.addEventListener('versionchange', function (t) {
- return o(t.oldVersion, t.newVersion, t);
- });
- })
- .catch(function () {}),
- c
- );
- }),
- (t.unwrap = g),
- (t.wrap = f);
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- function e(t, n) {
- var i;
- (n = n || {}),
- (this._id = e._generateUUID()),
- (this._promise = n.promise || Promise),
- (this._frameId = n.frameId || 'CrossStorageClient-' + this._id),
- (this._origin = e._getOrigin(t)),
- (this._requests = {}),
- (this._connected = !1),
- (this._closed = !1),
- (this._count = 0),
- (this._timeout = n.timeout || 5e3),
- (this._listener = null),
- this._installListener(),
- n.frameId && (i = document.getElementById(n.frameId)),
- i && this._poll(),
- (i = i || this._createFrame(t)),
- (this._hub = i.contentWindow);
- }
- (e.frameStyle = {
- width: 0,
- height: 0,
- border: 'none',
- display: 'none',
- position: 'absolute',
- top: '-999px',
- left: '-999px',
- }),
- (e._getOrigin = function (t) {
- var e;
- return (
- ((e = document.createElement('a')).href = t),
- e.host || (e = window.location),
- (
- (e.protocol && ':' !== e.protocol ? e.protocol : window.location.protocol) +
- '//' +
- e.host
- ).replace(/:80$|:443$/, '')
- );
- }),
- (e._generateUUID = function () {
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (t) {
- var e = (16 * Math.random()) | 0;
- return ('x' == t ? e : (3 & e) | 8).toString(16);
- });
- }),
- (e.prototype.onConnect = function () {
- var t = this;
- return this._connected
- ? this._promise.resolve()
- : this._closed
- ? this._promise.reject(new Error('CrossStorageClient has closed'))
- : (this._requests.connect || (this._requests.connect = []),
- new this._promise(function (e, n) {
- var i = setTimeout(function () {
- n(new Error('CrossStorageClient could not connect'));
- }, t._timeout);
- t._requests.connect.push(function (t) {
- if ((clearTimeout(i), t)) return n(t);
- e();
- });
- }));
- }),
- (e.prototype.set = function (t, e) {
- return this._request('set', { key: t, value: e });
- }),
- (e.prototype.getSignedPayload = function (t, e) {
- return (
- console.log('sending payload: ', t, ' deviceId: ', e),
- this._request('getSignedData', { payload: t, deviceId: e })
- );
- }),
- (e.prototype.getDeviceDetails = function (t) {
- return this._request('getDeviceDetails', { deviceName: t });
- }),
- (e.prototype.setDeviceDetails = function (t, e) {
- return this._request('setDeviceDetails', { deviceName: t, deviceId: e });
- }),
- (e.prototype.get = function (t) {
- var e = Array.prototype.slice.call(arguments);
- return this._request('get', { keys: e });
- }),
- (e.prototype.del = function () {
- var t = Array.prototype.slice.call(arguments);
- return this._request('del', { keys: t });
- }),
- (e.prototype.clear = function () {
- return this._request('clear');
- }),
- (e.prototype.getKeys = function () {
- return this._request('getKeys');
- }),
- (e.prototype.close = function (t) {
- const e = this._frameId,
- n = this;
- this._request('close')
- .catch(function (t) {})
- .finally(function () {
- try {
- var i = document.getElementById(e);
- i && !t && i.parentNode.removeChild(i),
- window.removeEventListener
- ? window.removeEventListener('message', n._listener, !1)
- : window.detachEvent('onmessage', n._listener),
- (n._connected = !1),
- (n._closed = !0);
- } catch (t) {}
- });
- }),
- (e.prototype._installListener = function () {
- var t = this;
- (this._listener = function (e) {
- var n, i, r;
- if (
- !t._closed &&
- e.data &&
- 'string' == typeof e.data &&
- ('null' === e.origin ? 'file://' : e.origin) === t._origin
- )
- if ('cross-storage:unavailable' !== e.data) {
- if (-1 !== e.data.indexOf('cross-storage:') && !t._connected) {
- if (((t._connected = !0), !t._requests.connect)) return;
- for (n = 0; n < t._requests.connect.length; n++) t._requests.connect[n](i);
- delete t._requests.connect;
- }
- if ('cross-storage:ready' !== e.data) {
- try {
- r = JSON.parse(e.data);
- } catch (t) {
- return;
- }
- r.id && t._requests[r.id] && t._requests[r.id](r.error, r.result);
- }
- } else {
- if ((t._closed || t.close(), !t._requests.connect)) return;
- for (
- i = new Error('Closing client. Could not access localStorage in hub.'), n = 0;
- n < t._requests.connect.length;
- n++
- )
- t._requests.connect[n](i);
- }
- }),
- window.addEventListener
- ? window.addEventListener('message', this._listener, !1)
- : window.attachEvent('onmessage', this._listener);
- }),
- (e.prototype._poll = function () {
- var t, e, n;
- (n = 'file://' === (t = this)._origin ? '*' : t._origin),
- (e = setInterval(function () {
- if (t._connected) return clearInterval(e);
- t._hub && t._hub.postMessage('cross-storage:poll', n);
- }, 1e3));
- }),
- (e.prototype._createFrame = function (t) {
- var n, i;
- for (i in (((n = window.document.createElement('iframe')).id = this._frameId),
- e.frameStyle))
- e.frameStyle.hasOwnProperty(i) && (n.style[i] = e.frameStyle[i]);
- return window.document.body.appendChild(n), (n.src = t), n;
- }),
- (e.prototype._request = function (t, e) {
- var n, i;
- return this._closed
- ? this._promise.reject(new Error('CrossStorageClient has closed'))
- : ((i = this)._count++,
- (n = { id: this._id + ':' + i._count, method: 'cross-storage:' + t, params: e }),
- new this._promise(function (t, e) {
- var r, a, o;
- (r = setTimeout(function () {
- i._requests[n.id] &&
- (delete i._requests[n.id],
- e(new Error('Timeout: could not perform ' + n.method)));
- }, i._timeout)),
- (i._requests[n.id] = function (a, o) {
- if ((clearTimeout(r), delete i._requests[n.id], a)) return e(new Error(a));
- t(o);
- }),
- Array.prototype.toJSON &&
- ((a = Array.prototype.toJSON), (Array.prototype.toJSON = null)),
- (o = 'file://' === i._origin ? '*' : i._origin),
- i._hub.postMessage(JSON.stringify(n), o),
- a && (Array.prototype.toJSON = a);
- }));
- }),
- (t.CrossStorageClient = e);
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function () {
- 'use strict';
- 'function' != typeof Object.assign &&
- Object.defineProperty(Object, 'assign', {
- value: function (t, e) {
- if (null === t || void 0 === t)
- throw new TypeError('Cannot convert undefined or null to object');
- for (var n = Object(t), i = 1; i < arguments.length; i++) {
- var r = arguments[i];
- if (null !== r && void 0 !== r)
- for (var a in r) Object.prototype.hasOwnProperty.call(r, a) && (n[a] = r[a]);
- }
- return n;
- },
- writable: !0,
- configurable: !0,
- });
- })(),
- Array.from ||
- (Array.from = (function () {
- var t = Object.prototype.toString,
- e = function (e) {
- return 'function' == typeof e || '[object Function]' === t.call(e);
- },
- n = Math.pow(2, 53) - 1,
- i = function (t) {
- var e = (function (t) {
- var e = Number(t);
- return isNaN(e)
- ? 0
- : 0 !== e && isFinite(e)
- ? (e > 0 ? 1 : -1) * Math.floor(Math.abs(e))
- : e;
- })(t);
- return Math.min(Math.max(e, 0), n);
- };
- return function (t) {
- var n = Object(t);
- if (null == t)
- throw new TypeError('Array.from requires an array-like object - not null or undefined');
- var r,
- a = arguments.length > 1 ? arguments[1] : void 0;
- if (void 0 !== a) {
- if (!e(a))
- throw new TypeError(
- 'Array.from: when provided, the second argument must be a function',
- );
- arguments.length > 2 && (r = arguments[2]);
- }
- for (
- var o, s = i(n.length), u = e(this) ? Object(new this(s)) : new Array(s), c = 0;
- c < s;
-
- )
- (o = n[c]), (u[c] = a ? (void 0 === r ? a(o, c) : a.call(r, o, c)) : o), (c += 1);
- return (u.length = s), u;
- };
- })()),
- (function () {
- 'use strict';
- String.prototype.endsWith ||
- (String.prototype.endsWith = function (t, e) {
- return (
- (void 0 === e || e > this.length) && (e = this.length),
- this.substring(e - t.length, e) === t
- );
- });
- })(),
- (function () {
- 'use strict';
- Promise.allSettled =
- Promise.allSettled ||
- function (t) {
- return Promise.all(
- t.map(function (t) {
- return t
- .then(function (t) {
- return { status: 'fulfilled', value: t };
- })
- .catch(function (t) {
- return { status: 'rejected', reason: t };
- });
- }),
- );
- };
- })(),
- (function (t, e) {
- 'use strict';
- var n = 'model',
- i = 'name',
- r = 'type',
- a = 'vendor',
- o = 'version',
- s = 'mobile',
- u = 'tablet',
- c = 'smarttv',
- l = function (t) {
- for (var e = {}, n = 0; n < t.length; n++) e[t[n].toUpperCase()] = t[n];
- return e;
- },
- d = function (t, e) {
- return 'string' == typeof t && -1 !== h(e).indexOf(h(t));
- },
- h = function (t) {
- return t.toLowerCase();
- },
- f = function (t, e) {
- if ('string' == typeof t)
- return (
- (t = t.replace(/^\s\s*/, '').replace(/\s\s*$/, '')),
- void 0 === e ? t : t.substring(0, 255)
- );
- },
- g = function (t, e) {
- for (var n, i, r, a, o, s, u = 0; u < e.length && !o; ) {
- var c = e[u],
- l = e[u + 1];
- for (n = i = 0; n < c.length && !o; )
- if ((o = c[n++].exec(t)))
- for (r = 0; r < l.length; r++)
- (s = o[++i]),
- 'object' == typeof (a = l[r]) && a.length > 0
- ? 2 === a.length
- ? 'function' == typeof a[1]
- ? (this[a[0]] = a[1].call(this, s))
- : (this[a[0]] = a[1])
- : 3 === a.length
- ? 'function' != typeof a[1] || (a[1].exec && a[1].test)
- ? (this[a[0]] = s ? s.replace(a[1], a[2]) : void 0)
- : (this[a[0]] = s ? a[1].call(this, s, a[2]) : void 0)
- : 4 === a.length &&
- (this[a[0]] = s ? a[3].call(this, s.replace(a[1], a[2])) : void 0)
- : (this[a] = s || void 0);
- u += 2;
- }
- },
- p = function (t, e) {
- for (var n in e)
- if ('object' == typeof e[n] && e[n].length > 0) {
- for (var i = 0; i < e[n].length; i++)
- if (d(e[n][i], t)) return '?' === n ? void 0 : n;
- } else if (d(e[n], t)) return '?' === n ? void 0 : n;
- return t;
- },
- v = {
- ME: '4.90',
- 'NT 3.11': 'NT3.51',
- 'NT 4.0': 'NT4.0',
- 2000: 'NT 5.0',
- XP: ['NT 5.1', 'NT 5.2'],
- Vista: 'NT 6.0',
- 7: 'NT 6.1',
- 8: 'NT 6.2',
- 8.1: 'NT 6.3',
- 10: ['NT 6.4', 'NT 10.0'],
- RT: 'ARM',
- },
- _ = {
- browser: [
- [/\b(?:crmo|crios)\/([\w\.]+)/i],
- [o, [i, 'Chrome']],
- [/edg(?:e|ios|a)?\/([\w\.]+)/i],
- [o, [i, 'Edge']],
- [
- /(opera mini)\/([-\w\.]+)/i,
- /(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,
- /(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i,
- ],
- [i, o],
- [/opios[\/ ]+([\w\.]+)/i],
- [o, [i, 'Opera Mini']],
- [/\bopr\/([\w\.]+)/i],
- [o, [i, 'Opera']],
- [
- /(kindle)\/([\w\.]+)/i,
- /(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,
- /(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,
- /(ba?idubrowser)[\/ ]?([\w\.]+)/i,
- /(?:ms|\()(ie) ([\w\.]+)/i,
- /(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale|qqbrowserlite|qq)\/([-\w\.]+)/i,
- /(weibo)__([\d\.]+)/i,
- ],
- [i, o],
- [/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],
- [o, [i, 'UCBrowser']],
- [/\bqbcore\/([\w\.]+)/i],
- [o, [i, 'WeChat(Win) Desktop']],
- [/micromessenger\/([\w\.]+)/i],
- [o, [i, 'WeChat']],
- [/konqueror\/([\w\.]+)/i],
- [o, [i, 'Konqueror']],
- [/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],
- [o, [i, 'IE']],
- [/yabrowser\/([\w\.]+)/i],
- [o, [i, 'Yandex']],
- [/(avast|avg)\/([\w\.]+)/i],
- [[i, /(.+)/, '$1 Secure Browser'], o],
- [/\bfocus\/([\w\.]+)/i],
- [o, [i, 'Firefox Focus']],
- [/\bopt\/([\w\.]+)/i],
- [o, [i, 'Opera Touch']],
- [/coc_coc\w+\/([\w\.]+)/i],
- [o, [i, 'Coc Coc']],
- [/dolfin\/([\w\.]+)/i],
- [o, [i, 'Dolphin']],
- [/coast\/([\w\.]+)/i],
- [o, [i, 'Opera Coast']],
- [/miuibrowser\/([\w\.]+)/i],
- [o, [i, 'MIUI Browser']],
- [/fxios\/([-\w\.]+)/i],
- [o, [i, 'Firefox']],
- [/\bqihu|(qi?ho?o?|360)browser/i],
- [[i, '360 Browser']],
- [/(oculus|samsung|sailfish)browser\/([\w\.]+)/i],
- [[i, /(.+)/, '$1 Browser'], o],
- [/(comodo_dragon)\/([\w\.]+)/i],
- [[i, /_/g, ' '], o],
- [
- /(electron)\/([\w\.]+) safari/i,
- /(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,
- /m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i,
- ],
- [i, o],
- [/(metasr)[\/ ]?([\w\.]+)/i, /(lbbrowser)/i],
- [i],
- [/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],
- [[i, 'Facebook'], o],
- [
- /safari (line)\/([\w\.]+)/i,
- /\b(line)\/([\w\.]+)\/iab/i,
- /(chromium|instagram)[\/ ]([-\w\.]+)/i,
- ],
- [i, o],
- [/\bgsa\/([\w\.]+) .*safari\//i],
- [o, [i, 'GSA']],
- [/headlesschrome(?:\/([\w\.]+)| )/i],
- [o, [i, 'Chrome Headless']],
- [/ wv\).+(chrome)\/([\w\.]+)/i],
- [[i, 'Chrome WebView'], o],
- [/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],
- [o, [i, 'Android Browser']],
- [/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],
- [i, o],
- [/version\/([\w\.]+) .*mobile\/\w+ (safari)/i],
- [o, [i, 'Mobile Safari']],
- [/version\/([\w\.]+) .*(mobile ?safari|safari)/i],
- [o, i],
- [/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],
- [
- i,
- [
- o,
- p,
- {
- '1.0': '/8',
- 1.2: '/1',
- 1.3: '/3',
- '2.0': '/412',
- '2.0.2': '/416',
- '2.0.3': '/417',
- '2.0.4': '/419',
- '?': '/',
- },
- ],
- ],
- [/(webkit|khtml)\/([\w\.]+)/i],
- [i, o],
- [/(navigator|netscape\d?)\/([-\w\.]+)/i],
- [[i, 'Netscape'], o],
- [/mobile vr; rv:([\w\.]+)\).+firefox/i],
- [o, [i, 'Firefox Reality']],
- [
- /ekiohf.+(flow)\/([\w\.]+)/i,
- /(swiftfox)/i,
- /(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,
- /(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,
- /(firefox)\/([\w\.]+)/i,
- /(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,
- /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,
- /(links) \(([\w\.]+)/i,
- ],
- [i, o],
- ],
- cpu: [
- [/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],
- [['architecture', 'amd64']],
- [/(ia32(?=;))/i],
- [['architecture', h]],
- [/((?:i[346]|x)86)[;\)]/i],
- [['architecture', 'ia32']],
- [/\b(aarch64|arm(v?8e?l?|_?64))\b/i],
- [['architecture', 'arm64']],
- [/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],
- [['architecture', 'armhf']],
- [/windows (ce|mobile); ppc;/i],
- [['architecture', 'arm']],
- [/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],
- [['architecture', /ower/, '', h]],
- [/(sun4\w)[;\)]/i],
- [['architecture', 'sparc']],
- [
- /((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i,
- ],
- [['architecture', h]],
- ],
- device: [
- [/\b(sch-i[89]0\d|shw-m380s|sm-[pt]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],
- [n, [a, 'Samsung'], [r, u]],
- [/\b((?:s[cgp]h|gt|sm)-\w+|galaxy nexus)/i, /samsung[- ]([-\w]+)/i, /sec-(sgh\w+)/i],
- [n, [a, 'Samsung'], [r, s]],
- [/\((ip(?:hone|od)[\w ]*);/i],
- [n, [a, 'Apple'], [r, s]],
- [
- /\((ipad);[-\w\),; ]+apple/i,
- /applecoremedia\/[\w\.]+ \((ipad)/i,
- /\b(ipad)\d\d?,\d\d?[;\]].+ios/i,
- ],
- [n, [a, 'Apple'], [r, u]],
- [/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],
- [n, [a, 'Huawei'], [r, u]],
- [
- /(?:huawei|honor)([-\w ]+)[;\)]/i,
- /\b(nexus 6p|\w{2,4}-[atu]?[ln][01259x][012359][an]?)\b(?!.+d\/s)/i,
- ],
- [n, [a, 'Huawei'], [r, s]],
- [
- /\b(poco[\w ]+)(?: bui|\))/i,
- /\b; (\w+) build\/hm\1/i,
- /\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,
- /\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,
- /\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i,
- ],
- [
- [n, /_/g, ' '],
- [a, 'Xiaomi'],
- [r, s],
- ],
- [/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],
- [
- [n, /_/g, ' '],
- [a, 'Xiaomi'],
- [r, u],
- ],
- [
- /; (\w+) bui.+ oppo/i,
- /\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,
- ],
- [n, [a, 'OPPO'], [r, s]],
- [/vivo (\w+)(?: bui|\))/i, /\b(v[12]\d{3}\w?[at])(?: bui|;)/i],
- [n, [a, 'Vivo'], [r, s]],
- [/\b(rmx[12]\d{3})(?: bui|;|\))/i],
- [n, [a, 'Realme'], [r, s]],
- [
- /\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,
- /\bmot(?:orola)?[- ](\w*)/i,
- /((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i,
- ],
- [n, [a, 'Motorola'], [r, s]],
- [/\b(mz60\d|xoom[2 ]{0,2}) build\//i],
- [n, [a, 'Motorola'], [r, u]],
- [/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],
- [n, [a, 'LG'], [r, u]],
- [
- /(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,
- /\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,
- /\blg-?([\d\w]+) bui/i,
- ],
- [n, [a, 'LG'], [r, s]],
- [
- /(ideatab[-\w ]+)/i,
- /lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i,
- ],
- [n, [a, 'Lenovo'], [r, u]],
- [/(?:maemo|nokia).*(n900|lumia \d+)/i, /nokia[-_ ]?([-\w\.]*)/i],
- [
- [n, /_/g, ' '],
- [a, 'Nokia'],
- [r, s],
- ],
- [/(pixel c)\b/i],
- [n, [a, 'Google'], [r, u]],
- [/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],
- [n, [a, 'Google'], [r, s]],
- [
- /droid.+ ([c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i,
- ],
- [n, [a, 'Sony'], [r, s]],
- [/sony tablet [ps]/i, /\b(?:sony)?sgp\w+(?: bui|\))/i],
- [
- [n, 'Xperia Tablet'],
- [a, 'Sony'],
- [r, u],
- ],
- [/ (kb2005|in20[12]5|be20[12][59])\b/i, /(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],
- [n, [a, 'OnePlus'], [r, s]],
- [/(alexa)webm/i, /(kf[a-z]{2}wi)( bui|\))/i, /(kf[a-z]+)( bui|\)).+silk\//i],
- [n, [a, 'Amazon'], [r, u]],
- [/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],
- [
- [n, /(.+)/g, 'Fire Phone $1'],
- [a, 'Amazon'],
- [r, s],
- ],
- [/(playbook);[-\w\),; ]+(rim)/i],
- [n, a, [r, u]],
- [/\b((?:bb[a-f]|st[hv])100-\d)/i, /\(bb10; (\w+)/i],
- [n, [a, 'BlackBerry'], [r, s]],
- [/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],
- [n, [a, 'ASUS'], [r, u]],
- [/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],
- [n, [a, 'ASUS'], [r, s]],
- [/(nexus 9)/i],
- [n, [a, 'HTC'], [r, u]],
- [
- /(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,
- /(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,
- /(alcatel|geeksphone|nexian|panasonic|sony)[-_ ]?([-\w]*)/i,
- ],
- [a, [n, /_/g, ' '], [r, s]],
- [/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],
- [n, [a, 'Acer'], [r, u]],
- [/droid.+; (m[1-5] note) bui/i, /\bmz-([-\w]{2,})/i],
- [n, [a, 'Meizu'], [r, s]],
- [/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],
- [n, [a, 'Sharp'], [r, s]],
- [
- /(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,
- /(hp) ([\w ]+\w)/i,
- /(asus)-?(\w+)/i,
- /(microsoft); (lumia[\w ]+)/i,
- /(lenovo)[-_ ]?([-\w]+)/i,
- /(jolla)/i,
- /(oppo) ?([\w ]+) bui/i,
- ],
- [a, n, [r, s]],
- [
- /(archos) (gamepad2?)/i,
- /(hp).+(touchpad(?!.+tablet)|tablet)/i,
- /(kindle)\/([\w\.]+)/i,
- /(nook)[\w ]+build\/(\w+)/i,
- /(dell) (strea[kpr\d ]*[\dko])/i,
- /(le[- ]+pan)[- ]+(\w{1,9}) bui/i,
- /(trinity)[- ]*(t\d{3}) bui/i,
- /(gigaset)[- ]+(q\w{1,9}) bui/i,
- /(vodafone) ([\w ]+)(?:\)| bui)/i,
- ],
- [a, n, [r, u]],
- [/(surface duo)/i],
- [n, [a, 'Microsoft'], [r, u]],
- [/droid [\d\.]+; (fp\du?)(?: b|\))/i],
- [n, [a, 'Fairphone'], [r, s]],
- [/(u304aa)/i],
- [n, [a, 'AT&T'], [r, s]],
- [/\bsie-(\w*)/i],
- [n, [a, 'Siemens'], [r, s]],
- [/\b(rct\w+) b/i],
- [n, [a, 'RCA'], [r, u]],
- [/\b(venue[\d ]{2,7}) b/i],
- [n, [a, 'Dell'], [r, u]],
- [/\b(q(?:mv|ta)\w+) b/i],
- [n, [a, 'Verizon'], [r, u]],
- [/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],
- [n, [a, 'Barnes & Noble'], [r, u]],
- [/\b(tm\d{3}\w+) b/i],
- [n, [a, 'NuVision'], [r, u]],
- [/\b(k88) b/i],
- [n, [a, 'ZTE'], [r, u]],
- [/\b(nx\d{3}j) b/i],
- [n, [a, 'ZTE'], [r, s]],
- [/\b(gen\d{3}) b.+49h/i],
- [n, [a, 'Swiss'], [r, s]],
- [/\b(zur\d{3}) b/i],
- [n, [a, 'Swiss'], [r, u]],
- [/\b((zeki)?tb.*\b) b/i],
- [n, [a, 'Zeki'], [r, u]],
- [/\b([yr]\d{2}) b/i, /\b(dragon[- ]+touch |dt)(\w{5}) b/i],
- [[a, 'Dragon Touch'], n, [r, u]],
- [/\b(ns-?\w{0,9}) b/i],
- [n, [a, 'Insignia'], [r, u]],
- [/\b((nxa|next)-?\w{0,9}) b/i],
- [n, [a, 'NextBook'], [r, u]],
- [/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],
- [[a, 'Voice'], n, [r, s]],
- [/\b(lvtel\-)?(v1[12]) b/i],
- [[a, 'LvTel'], n, [r, s]],
- [/\b(ph-1) /i],
- [n, [a, 'Essential'], [r, s]],
- [/\b(v(100md|700na|7011|917g).*\b) b/i],
- [n, [a, 'Envizen'], [r, u]],
- [/\b(trio[-\w\. ]+) b/i],
- [n, [a, 'MachSpeed'], [r, u]],
- [/\btu_(1491) b/i],
- [n, [a, 'Rotor'], [r, u]],
- [/(shield[\w ]+) b/i],
- [n, [a, 'Nvidia'], [r, u]],
- [/(sprint) (\w+)/i],
- [a, n, [r, s]],
- [/(kin\.[onetw]{3})/i],
- [
- [n, /\./g, ' '],
- [a, 'Microsoft'],
- [r, s],
- ],
- [/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],
- [n, [a, 'Zebra'], [r, u]],
- [/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],
- [n, [a, 'Zebra'], [r, s]],
- [/(ouya)/i, /(nintendo) ([wids3utch]+)/i],
- [a, n, [r, 'console']],
- [/droid.+; (shield) bui/i],
- [n, [a, 'Nvidia'], [r, 'console']],
- [/(playstation [345portablevi]+)/i],
- [n, [a, 'Sony'], [r, 'console']],
- [/\b(xbox(?: one)?(?!; xbox))[\); ]/i],
- [n, [a, 'Microsoft'], [r, 'console']],
- [/smart-tv.+(samsung)/i],
- [a, [r, c]],
- [/hbbtv.+maple;(\d+)/i],
- [
- [n, /^/, 'SmartTV'],
- [a, 'Samsung'],
- [r, c],
- ],
- [/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],
- [
- [a, 'LG'],
- [r, c],
- ],
- [/(apple) ?tv/i],
- [a, [n, 'Apple TV'], [r, c]],
- [/crkey/i],
- [
- [n, 'Chromecast'],
- [a, 'Google'],
- [r, c],
- ],
- [/droid.+aft(\w)( bui|\))/i],
- [n, [a, 'Amazon'], [r, c]],
- [/\(dtv[\);].+(aquos)/i],
- [n, [a, 'Sharp'], [r, c]],
- [
- /\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,
- /hbbtv\/\d+\.\d+\.\d+ +\([\w ]*; *(\w[^;]*);([^;]*)/i,
- ],
- [
- [a, f],
- [n, f],
- [r, c],
- ],
- [/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],
- [[r, c]],
- [/((pebble))app/i],
- [a, n, [r, 'wearable']],
- [/droid.+; (glass) \d/i],
- [n, [a, 'Google'], [r, 'wearable']],
- [/droid.+; (wt63?0{2,3})\)/i],
- [n, [a, 'Zebra'], [r, 'wearable']],
- [/(quest( 2)?)/i],
- [n, [a, 'Facebook'], [r, 'wearable']],
- [/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],
- [a, [r, 'embedded']],
- [/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],
- [n, [r, s]],
- [/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],
- [n, [r, u]],
- [/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],
- [[r, u]],
- [/(phone|mobile(?:[;\/]| safari)|pda(?=.+windows ce))/i],
- [[r, s]],
- [/(android[-\w\. ]{0,9});.+buil/i],
- [n, [a, 'Generic']],
- ],
- engine: [
- [/windows.+ edge\/([\w\.]+)/i],
- [o, [i, 'EdgeHTML']],
- [/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],
- [o, [i, 'Blink']],
- [
- /(presto)\/([\w\.]+)/i,
- /(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,
- /ekioh(flow)\/([\w\.]+)/i,
- /(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,
- /(icab)[\/ ]([23]\.[\d\.]+)/i,
- ],
- [i, o],
- [/rv\:([\w\.]{1,9})\b.+(gecko)/i],
- [o, i],
- ],
- os: [
- [/microsoft (windows) (vista|xp)/i],
- [i, o],
- [
- /(windows) nt 6\.2; (arm)/i,
- /(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,
- /(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,
- ],
- [i, [o, p, v]],
- [/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],
- [
- [i, 'Windows'],
- [o, p, v],
- ],
- [/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i, /cfnetwork\/.+darwin/i],
- [
- [o, /_/g, '.'],
- [i, 'iOS'],
- ],
- [/(mac os x) ?([\w\. ]*)/i, /(macintosh|mac_powerpc\b)(?!.+haiku)/i],
- [
- [i, 'Mac OS'],
- [o, /_/g, '.'],
- ],
- [/droid ([\w\.]+)\b.+(android[- ]x86)/i],
- [o, i],
- [
- /(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,
- /(blackberry)\w*\/([\w\.]*)/i,
- /(tizen|kaios)[\/ ]([\w\.]+)/i,
- /\((series40);/i,
- ],
- [i, o],
- [/\(bb(10);/i],
- [o, [i, 'BlackBerry']],
- [/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],
- [o, [i, 'Symbian']],
- [/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],
- [o, [i, 'Firefox OS']],
- [/web0s;.+rt(tv)/i, /\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],
- [o, [i, 'webOS']],
- [/crkey\/([\d\.]+)/i],
- [o, [i, 'Chromecast']],
- [/(cros) [\w]+ ([\w\.]+\w)/i],
- [[i, 'Chromium OS'], o],
- [
- /(nintendo|playstation) ([wids345portablevuch]+)/i,
- /(xbox); +xbox ([^\);]+)/i,
- /\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,
- /(mint)[\/\(\) ]?(\w*)/i,
- /(mageia|vectorlinux)[; ]/i,
- /([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,
- /(hurd|linux) ?([\w\.]*)/i,
- /(gnu) ?([\w\.]*)/i,
- /\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,
- /(haiku) (\w+)/i,
- ],
- [i, o],
- [/(sunos) ?([\w\.\d]*)/i],
- [[i, 'Solaris'], o],
- [
- /((?:open)?solaris)[-\/ ]?([\w\.]*)/i,
- /(aix) ((\d)(?=\.|\)| )[\w\.])*/i,
- /\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i,
- /(unix) ?([\w\.]*)/i,
- ],
- [i, o],
- ],
- },
- m = function (t, e) {
- if (('object' == typeof t && ((e = t), (t = void 0)), !(this instanceof m)))
- return new m(t, e).getResult();
- var n =
- t ||
- ('undefined' != typeof window && window.navigator && window.navigator.userAgent
- ? window.navigator.userAgent
- : ''),
- i = e
- ? (function (t, e) {
- var n = {};
- for (var i in t)
- e[i] && e[i].length % 2 == 0 ? (n[i] = e[i].concat(t[i])) : (n[i] = t[i]);
- return n;
- })(_, e)
- : _;
- return (
- (this.getBrowser = function () {
- var t,
- e = {};
- return (
- (e.name = void 0),
- (e.version = void 0),
- g.call(e, n, i.browser),
- (e.major =
- 'string' == typeof (t = e.version)
- ? t.replace(/[^\d\.]/g, '').split('.')[0]
- : void 0),
- e
- );
- }),
- (this.getCPU = function () {
- var t = { architecture: void 0 };
- return g.call(t, n, i.cpu), t;
- }),
- (this.getDevice = function () {
- var t = { vendor: void 0, model: void 0, type: void 0 };
- return g.call(t, n, i.device), t;
- }),
- (this.getEngine = function () {
- var t = { name: void 0, version: void 0 };
- return g.call(t, n, i.engine), t;
- }),
- (this.getOS = function () {
- var t = { name: void 0, version: void 0 };
- return g.call(t, n, i.os), t;
- }),
- (this.getResult = function () {
- return {
- ua: this.getUA(),
- browser: this.getBrowser(),
- engine: this.getEngine(),
- os: this.getOS(),
- device: this.getDevice(),
- cpu: this.getCPU(),
- };
- }),
- (this.getUA = function () {
- return n;
- }),
- (this.setUA = function (t) {
- return (n = 'string' == typeof t && t.length > 255 ? f(t, 255) : t), this;
- }),
- this.setUA(n),
- this
- );
- };
- (m.VERSION = '1.0.2'),
- (m.BROWSER = l([i, o, 'major'])),
- (m.CPU = l(['architecture'])),
- (m.DEVICE = l([n, a, r, 'console', s, c, u, 'wearable', 'embedded'])),
- (m.ENGINE = m.OS = l([i, o])),
- (t.UAParser = m);
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- ((_POSignalsEntities || (_POSignalsEntities = {})).pako = (function t(e, n, i) {
- function r(o, s) {
- if (!n[o]) {
- if (!e[o]) {
- var u = 'function' == typeof require && require;
- if (!s && u) return u(o, !0);
- if (a) return a(o, !0);
- var c = new Error("Cannot find module '" + o + "'");
- throw ((c.code = 'MODULE_NOT_FOUND'), c);
- }
- var l = (n[o] = { exports: {} });
- e[o][0].call(
- l.exports,
- function (t) {
- var n = e[o][1][t];
- return r(n || t);
- },
- l,
- l.exports,
- t,
- e,
- n,
- i,
- );
- }
- return n[o].exports;
- }
- for (var a = 'function' == typeof require && require, o = 0; o < i.length; o++) r(i[o]);
- return r;
- })(
- {
- 1: [
- function (t, e, n) {
- 'use strict';
- function i(t, e) {
- return Object.prototype.hasOwnProperty.call(t, e);
- }
- var r =
- 'undefined' != typeof Uint8Array &&
- 'undefined' != typeof Uint16Array &&
- 'undefined' != typeof Int32Array;
- (n.assign = function (t) {
- for (var e = Array.prototype.slice.call(arguments, 1); e.length; ) {
- var n = e.shift();
- if (n) {
- if ('object' != typeof n) throw new TypeError(n + 'must be non-object');
- for (var r in n) i(n, r) && (t[r] = n[r]);
- }
- }
- return t;
- }),
- (n.shrinkBuf = function (t, e) {
- return t.length === e ? t : t.subarray ? t.subarray(0, e) : ((t.length = e), t);
- });
- var a = {
- arraySet: function (t, e, n, i, r) {
- if (e.subarray && t.subarray) t.set(e.subarray(n, n + i), r);
- else for (var a = 0; a < i; a++) t[r + a] = e[n + a];
- },
- flattenChunks: function (t) {
- var e, n, i, r, a, o;
- for (i = 0, e = 0, n = t.length; e < n; e++) i += t[e].length;
- for (o = new Uint8Array(i), r = 0, e = 0, n = t.length; e < n; e++)
- (a = t[e]), o.set(a, r), (r += a.length);
- return o;
- },
- },
- o = {
- arraySet: function (t, e, n, i, r) {
- for (var a = 0; a < i; a++) t[r + a] = e[n + a];
- },
- flattenChunks: function (t) {
- return [].concat.apply([], t);
- },
- };
- (n.setTyped = function (t) {
- t
- ? ((n.Buf8 = Uint8Array),
- (n.Buf16 = Uint16Array),
- (n.Buf32 = Int32Array),
- n.assign(n, a))
- : ((n.Buf8 = Array), (n.Buf16 = Array), (n.Buf32 = Array), n.assign(n, o));
- }),
- n.setTyped(r);
- },
- {},
- ],
- 2: [
- function (t, e, n) {
- 'use strict';
- function i(t, e) {
- if (e < 65537 && ((t.subarray && o) || (!t.subarray && a)))
- return String.fromCharCode.apply(null, r.shrinkBuf(t, e));
- for (var n = '', i = 0; i < e; i++) n += String.fromCharCode(t[i]);
- return n;
- }
- var r = t('./common'),
- a = !0,
- o = !0;
- try {
- String.fromCharCode.apply(null, [0]);
- } catch (t) {
- a = !1;
- }
- try {
- String.fromCharCode.apply(null, new Uint8Array(1));
- } catch (t) {
- o = !1;
- }
- for (var s = new r.Buf8(256), u = 0; u < 256; u++)
- s[u] = u >= 252 ? 6 : u >= 248 ? 5 : u >= 240 ? 4 : u >= 224 ? 3 : u >= 192 ? 2 : 1;
- (s[254] = s[254] = 1),
- (n.string2buf = function (t) {
- var e,
- n,
- i,
- a,
- o,
- s = t.length,
- u = 0;
- for (a = 0; a < s; a++)
- 55296 == (64512 & (n = t.charCodeAt(a))) &&
- a + 1 < s &&
- 56320 == (64512 & (i = t.charCodeAt(a + 1))) &&
- ((n = 65536 + ((n - 55296) << 10) + (i - 56320)), a++),
- (u += n < 128 ? 1 : n < 2048 ? 2 : n < 65536 ? 3 : 4);
- for (e = new r.Buf8(u), o = 0, a = 0; o < u; a++)
- 55296 == (64512 & (n = t.charCodeAt(a))) &&
- a + 1 < s &&
- 56320 == (64512 & (i = t.charCodeAt(a + 1))) &&
- ((n = 65536 + ((n - 55296) << 10) + (i - 56320)), a++),
- n < 128
- ? (e[o++] = n)
- : n < 2048
- ? ((e[o++] = 192 | (n >>> 6)), (e[o++] = 128 | (63 & n)))
- : n < 65536
- ? ((e[o++] = 224 | (n >>> 12)),
- (e[o++] = 128 | ((n >>> 6) & 63)),
- (e[o++] = 128 | (63 & n)))
- : ((e[o++] = 240 | (n >>> 18)),
- (e[o++] = 128 | ((n >>> 12) & 63)),
- (e[o++] = 128 | ((n >>> 6) & 63)),
- (e[o++] = 128 | (63 & n)));
- return e;
- }),
- (n.buf2binstring = function (t) {
- return i(t, t.length);
- }),
- (n.binstring2buf = function (t) {
- for (var e = new r.Buf8(t.length), n = 0, i = e.length; n < i; n++)
- e[n] = t.charCodeAt(n);
- return e;
- }),
- (n.buf2string = function (t, e) {
- var n,
- r,
- a,
- o,
- u = e || t.length,
- c = new Array(2 * u);
- for (r = 0, n = 0; n < u; )
- if ((a = t[n++]) < 128) c[r++] = a;
- else if ((o = s[a]) > 4) (c[r++] = 65533), (n += o - 1);
- else {
- for (a &= 2 === o ? 31 : 3 === o ? 15 : 7; o > 1 && n < u; )
- (a = (a << 6) | (63 & t[n++])), o--;
- o > 1
- ? (c[r++] = 65533)
- : a < 65536
- ? (c[r++] = a)
- : ((a -= 65536),
- (c[r++] = 55296 | ((a >> 10) & 1023)),
- (c[r++] = 56320 | (1023 & a)));
- }
- return i(c, r);
- }),
- (n.utf8border = function (t, e) {
- var n;
- for (
- (e = e || t.length) > t.length && (e = t.length), n = e - 1;
- n >= 0 && 128 == (192 & t[n]);
-
- )
- n--;
- return n < 0 ? e : 0 === n ? e : n + s[t[n]] > e ? n : e;
- });
- },
- { './common': 1 },
- ],
- 3: [
- function (t, e, n) {
- 'use strict';
- e.exports = function (t, e, n, i) {
- for (var r = (65535 & t) | 0, a = ((t >>> 16) & 65535) | 0, o = 0; 0 !== n; ) {
- n -= o = n > 2e3 ? 2e3 : n;
- do {
- a = (a + (r = (r + e[i++]) | 0)) | 0;
- } while (--o);
- (r %= 65521), (a %= 65521);
- }
- return r | (a << 16) | 0;
- };
- },
- {},
- ],
- 4: [
- function (t, e, n) {
- 'use strict';
- var i = (function () {
- for (var t, e = [], n = 0; n < 256; n++) {
- t = n;
- for (var i = 0; i < 8; i++) t = 1 & t ? 3988292384 ^ (t >>> 1) : t >>> 1;
- e[n] = t;
- }
- return e;
- })();
- e.exports = function (t, e, n, r) {
- var a = i,
- o = r + n;
- t ^= -1;
- for (var s = r; s < o; s++) t = (t >>> 8) ^ a[255 & (t ^ e[s])];
- return -1 ^ t;
- };
- },
- {},
- ],
- 5: [
- function (t, e, n) {
- 'use strict';
- function i(t, e) {
- return (t.msg = T[e]), e;
- }
- function r(t) {
- return (t << 1) - (t > 4 ? 9 : 0);
- }
- function a(t) {
- for (var e = t.length; --e >= 0; ) t[e] = 0;
- }
- function o(t) {
- var e = t.state,
- n = e.pending;
- n > t.avail_out && (n = t.avail_out),
- 0 !== n &&
- (S.arraySet(t.output, e.pending_buf, e.pending_out, n, t.next_out),
- (t.next_out += n),
- (e.pending_out += n),
- (t.total_out += n),
- (t.avail_out -= n),
- (e.pending -= n),
- 0 === e.pending && (e.pending_out = 0));
- }
- function s(t, e) {
- A._tr_flush_block(
- t,
- t.block_start >= 0 ? t.block_start : -1,
- t.strstart - t.block_start,
- e,
- ),
- (t.block_start = t.strstart),
- o(t.strm);
- }
- function u(t, e) {
- t.pending_buf[t.pending++] = e;
- }
- function c(t, e) {
- (t.pending_buf[t.pending++] = (e >>> 8) & 255),
- (t.pending_buf[t.pending++] = 255 & e);
- }
- function l(t, e, n, i) {
- var r = t.avail_in;
- return (
- r > i && (r = i),
- 0 === r
- ? 0
- : ((t.avail_in -= r),
- S.arraySet(e, t.input, t.next_in, r, n),
- 1 === t.state.wrap
- ? (t.adler = O(t.adler, e, r, n))
- : 2 === t.state.wrap && (t.adler = P(t.adler, e, r, n)),
- (t.next_in += r),
- (t.total_in += r),
- r)
- );
- }
- function d(t, e) {
- var n,
- i,
- r = t.max_chain_length,
- a = t.strstart,
- o = t.prev_length,
- s = t.nice_match,
- u = t.strstart > t.w_size - K ? t.strstart - (t.w_size - K) : 0,
- c = t.window,
- l = t.w_mask,
- d = t.prev,
- h = t.strstart + z,
- f = c[a + o - 1],
- g = c[a + o];
- t.prev_length >= t.good_match && (r >>= 2), s > t.lookahead && (s = t.lookahead);
- do {
- if (
- c[(n = e) + o] === g &&
- c[n + o - 1] === f &&
- c[n] === c[a] &&
- c[++n] === c[a + 1]
- ) {
- (a += 2), n++;
- do {} while (
- c[++a] === c[++n] &&
- c[++a] === c[++n] &&
- c[++a] === c[++n] &&
- c[++a] === c[++n] &&
- c[++a] === c[++n] &&
- c[++a] === c[++n] &&
- c[++a] === c[++n] &&
- c[++a] === c[++n] &&
- a < h
- );
- if (((i = z - (h - a)), (a = h - z), i > o)) {
- if (((t.match_start = e), (o = i), i >= s)) break;
- (f = c[a + o - 1]), (g = c[a + o]);
- }
- }
- } while ((e = d[e & l]) > u && 0 != --r);
- return o <= t.lookahead ? o : t.lookahead;
- }
- function h(t) {
- var e,
- n,
- i,
- r,
- a,
- o = t.w_size;
- do {
- if (((r = t.window_size - t.lookahead - t.strstart), t.strstart >= o + (o - K))) {
- S.arraySet(t.window, t.window, o, o, 0),
- (t.match_start -= o),
- (t.strstart -= o),
- (t.block_start -= o),
- (e = n = t.hash_size);
- do {
- (i = t.head[--e]), (t.head[e] = i >= o ? i - o : 0);
- } while (--n);
- e = n = o;
- do {
- (i = t.prev[--e]), (t.prev[e] = i >= o ? i - o : 0);
- } while (--n);
- r += o;
- }
- if (0 === t.strm.avail_in) break;
- if (
- ((n = l(t.strm, t.window, t.strstart + t.lookahead, r)),
- (t.lookahead += n),
- t.lookahead + t.insert >= V)
- )
- for (
- a = t.strstart - t.insert,
- t.ins_h = t.window[a],
- t.ins_h = ((t.ins_h << t.hash_shift) ^ t.window[a + 1]) & t.hash_mask;
- t.insert &&
- ((t.ins_h = ((t.ins_h << t.hash_shift) ^ t.window[a + V - 1]) & t.hash_mask),
- (t.prev[a & t.w_mask] = t.head[t.ins_h]),
- (t.head[t.ins_h] = a),
- a++,
- t.insert--,
- !(t.lookahead + t.insert < V));
-
- );
- } while (t.lookahead < K && 0 !== t.strm.avail_in);
- }
- function f(t, e) {
- for (var n, i; ; ) {
- if (t.lookahead < K) {
- if ((h(t), t.lookahead < K && e === I)) return q;
- if (0 === t.lookahead) break;
- }
- if (
- ((n = 0),
- t.lookahead >= V &&
- ((t.ins_h =
- ((t.ins_h << t.hash_shift) ^ t.window[t.strstart + V - 1]) & t.hash_mask),
- (n = t.prev[t.strstart & t.w_mask] = t.head[t.ins_h]),
- (t.head[t.ins_h] = t.strstart)),
- 0 !== n && t.strstart - n <= t.w_size - K && (t.match_length = d(t, n)),
- t.match_length >= V)
- )
- if (
- ((i = A._tr_tally(t, t.strstart - t.match_start, t.match_length - V)),
- (t.lookahead -= t.match_length),
- t.match_length <= t.max_lazy_match && t.lookahead >= V)
- ) {
- t.match_length--;
- do {
- t.strstart++,
- (t.ins_h =
- ((t.ins_h << t.hash_shift) ^ t.window[t.strstart + V - 1]) & t.hash_mask),
- (n = t.prev[t.strstart & t.w_mask] = t.head[t.ins_h]),
- (t.head[t.ins_h] = t.strstart);
- } while (0 != --t.match_length);
- t.strstart++;
- } else
- (t.strstart += t.match_length),
- (t.match_length = 0),
- (t.ins_h = t.window[t.strstart]),
- (t.ins_h =
- ((t.ins_h << t.hash_shift) ^ t.window[t.strstart + 1]) & t.hash_mask);
- else (i = A._tr_tally(t, 0, t.window[t.strstart])), t.lookahead--, t.strstart++;
- if (i && (s(t, !1), 0 === t.strm.avail_out)) return q;
- }
- return (
- (t.insert = t.strstart < V - 1 ? t.strstart : V - 1),
- e === D
- ? (s(t, !0), 0 === t.strm.avail_out ? J : Z)
- : t.last_lit && (s(t, !1), 0 === t.strm.avail_out)
- ? q
- : X
- );
- }
- function g(t, e) {
- for (var n, i, r; ; ) {
- if (t.lookahead < K) {
- if ((h(t), t.lookahead < K && e === I)) return q;
- if (0 === t.lookahead) break;
- }
- if (
- ((n = 0),
- t.lookahead >= V &&
- ((t.ins_h =
- ((t.ins_h << t.hash_shift) ^ t.window[t.strstart + V - 1]) & t.hash_mask),
- (n = t.prev[t.strstart & t.w_mask] = t.head[t.ins_h]),
- (t.head[t.ins_h] = t.strstart)),
- (t.prev_length = t.match_length),
- (t.prev_match = t.match_start),
- (t.match_length = V - 1),
- 0 !== n &&
- t.prev_length < t.max_lazy_match &&
- t.strstart - n <= t.w_size - K &&
- ((t.match_length = d(t, n)),
- t.match_length <= 5 &&
- (t.strategy === U ||
- (t.match_length === V && t.strstart - t.match_start > 4096)) &&
- (t.match_length = V - 1)),
- t.prev_length >= V && t.match_length <= t.prev_length)
- ) {
- (r = t.strstart + t.lookahead - V),
- (i = A._tr_tally(t, t.strstart - 1 - t.prev_match, t.prev_length - V)),
- (t.lookahead -= t.prev_length - 1),
- (t.prev_length -= 2);
- do {
- ++t.strstart <= r &&
- ((t.ins_h =
- ((t.ins_h << t.hash_shift) ^ t.window[t.strstart + V - 1]) & t.hash_mask),
- (n = t.prev[t.strstart & t.w_mask] = t.head[t.ins_h]),
- (t.head[t.ins_h] = t.strstart));
- } while (0 != --t.prev_length);
- if (
- ((t.match_available = 0),
- (t.match_length = V - 1),
- t.strstart++,
- i && (s(t, !1), 0 === t.strm.avail_out))
- )
- return q;
- } else if (t.match_available) {
- if (
- ((i = A._tr_tally(t, 0, t.window[t.strstart - 1])) && s(t, !1),
- t.strstart++,
- t.lookahead--,
- 0 === t.strm.avail_out)
- )
- return q;
- } else (t.match_available = 1), t.strstart++, t.lookahead--;
- }
- return (
- t.match_available &&
- ((i = A._tr_tally(t, 0, t.window[t.strstart - 1])), (t.match_available = 0)),
- (t.insert = t.strstart < V - 1 ? t.strstart : V - 1),
- e === D
- ? (s(t, !0), 0 === t.strm.avail_out ? J : Z)
- : t.last_lit && (s(t, !1), 0 === t.strm.avail_out)
- ? q
- : X
- );
- }
- function p(t, e) {
- for (var n, i, r, a, o = t.window; ; ) {
- if (t.lookahead <= z) {
- if ((h(t), t.lookahead <= z && e === I)) return q;
- if (0 === t.lookahead) break;
- }
- if (
- ((t.match_length = 0),
- t.lookahead >= V &&
- t.strstart > 0 &&
- ((r = t.strstart - 1), (i = o[r]) === o[++r] && i === o[++r] && i === o[++r]))
- ) {
- a = t.strstart + z;
- do {} while (
- i === o[++r] &&
- i === o[++r] &&
- i === o[++r] &&
- i === o[++r] &&
- i === o[++r] &&
- i === o[++r] &&
- i === o[++r] &&
- i === o[++r] &&
- r < a
- );
- (t.match_length = z - (a - r)),
- t.match_length > t.lookahead && (t.match_length = t.lookahead);
- }
- if (
- (t.match_length >= V
- ? ((n = A._tr_tally(t, 1, t.match_length - V)),
- (t.lookahead -= t.match_length),
- (t.strstart += t.match_length),
- (t.match_length = 0))
- : ((n = A._tr_tally(t, 0, t.window[t.strstart])), t.lookahead--, t.strstart++),
- n && (s(t, !1), 0 === t.strm.avail_out))
- )
- return q;
- }
- return (
- (t.insert = 0),
- e === D
- ? (s(t, !0), 0 === t.strm.avail_out ? J : Z)
- : t.last_lit && (s(t, !1), 0 === t.strm.avail_out)
- ? q
- : X
- );
- }
- function v(t, e) {
- for (var n; ; ) {
- if (0 === t.lookahead && (h(t), 0 === t.lookahead)) {
- if (e === I) return q;
- break;
- }
- if (
- ((t.match_length = 0),
- (n = A._tr_tally(t, 0, t.window[t.strstart])),
- t.lookahead--,
- t.strstart++,
- n && (s(t, !1), 0 === t.strm.avail_out))
- )
- return q;
- }
- return (
- (t.insert = 0),
- e === D
- ? (s(t, !0), 0 === t.strm.avail_out ? J : Z)
- : t.last_lit && (s(t, !1), 0 === t.strm.avail_out)
- ? q
- : X
- );
- }
- function _(t, e, n, i, r) {
- (this.good_length = t),
- (this.max_lazy = e),
- (this.nice_length = n),
- (this.max_chain = i),
- (this.func = r);
- }
- function m() {
- (this.strm = null),
- (this.status = 0),
- (this.pending_buf = null),
- (this.pending_buf_size = 0),
- (this.pending_out = 0),
- (this.pending = 0),
- (this.wrap = 0),
- (this.gzhead = null),
- (this.gzindex = 0),
- (this.method = R),
- (this.last_flush = -1),
- (this.w_size = 0),
- (this.w_bits = 0),
- (this.w_mask = 0),
- (this.window = null),
- (this.window_size = 0),
- (this.prev = null),
- (this.head = null),
- (this.ins_h = 0),
- (this.hash_size = 0),
- (this.hash_bits = 0),
- (this.hash_mask = 0),
- (this.hash_shift = 0),
- (this.block_start = 0),
- (this.match_length = 0),
- (this.prev_match = 0),
- (this.match_available = 0),
- (this.strstart = 0),
- (this.match_start = 0),
- (this.lookahead = 0),
- (this.prev_length = 0),
- (this.max_chain_length = 0),
- (this.max_lazy_match = 0),
- (this.level = 0),
- (this.strategy = 0),
- (this.good_match = 0),
- (this.nice_match = 0),
- (this.dyn_ltree = new S.Buf16(2 * j)),
- (this.dyn_dtree = new S.Buf16(2 * (2 * H + 1))),
- (this.bl_tree = new S.Buf16(2 * (2 * F + 1))),
- a(this.dyn_ltree),
- a(this.dyn_dtree),
- a(this.bl_tree),
- (this.l_desc = null),
- (this.d_desc = null),
- (this.bl_desc = null),
- (this.bl_count = new S.Buf16(G + 1)),
- (this.heap = new S.Buf16(2 * B + 1)),
- a(this.heap),
- (this.heap_len = 0),
- (this.heap_max = 0),
- (this.depth = new S.Buf16(2 * B + 1)),
- a(this.depth),
- (this.l_buf = 0),
- (this.lit_bufsize = 0),
- (this.last_lit = 0),
- (this.d_buf = 0),
- (this.opt_len = 0),
- (this.static_len = 0),
- (this.matches = 0),
- (this.insert = 0),
- (this.bi_buf = 0),
- (this.bi_valid = 0);
- }
- function y(t) {
- var e;
- return t && t.state
- ? ((t.total_in = t.total_out = 0),
- (t.data_type = x),
- ((e = t.state).pending = 0),
- (e.pending_out = 0),
- e.wrap < 0 && (e.wrap = -e.wrap),
- (e.status = e.wrap ? Y : W),
- (t.adler = 2 === e.wrap ? 0 : 1),
- (e.last_flush = I),
- A._tr_init(e),
- C)
- : i(t, M);
- }
- function b(t) {
- var e = y(t);
- return (
- e === C &&
- (function (t) {
- (t.window_size = 2 * t.w_size),
- a(t.head),
- (t.max_lazy_match = w[t.level].max_lazy),
- (t.good_match = w[t.level].good_length),
- (t.nice_match = w[t.level].nice_length),
- (t.max_chain_length = w[t.level].max_chain),
- (t.strstart = 0),
- (t.block_start = 0),
- (t.lookahead = 0),
- (t.insert = 0),
- (t.match_length = t.prev_length = V - 1),
- (t.match_available = 0),
- (t.ins_h = 0);
- })(t.state),
- e
- );
- }
- function E(t, e, n, r, a, o) {
- if (!t) return M;
- var s = 1;
- if (
- (e === L && (e = 6),
- r < 0 ? ((s = 0), (r = -r)) : r > 15 && ((s = 2), (r -= 16)),
- a < 1 || a > N || n !== R || r < 8 || r > 15 || e < 0 || e > 9 || o < 0 || o > k)
- )
- return i(t, M);
- 8 === r && (r = 9);
- var u = new m();
- return (
- (t.state = u),
- (u.strm = t),
- (u.wrap = s),
- (u.gzhead = null),
- (u.w_bits = r),
- (u.w_size = 1 << u.w_bits),
- (u.w_mask = u.w_size - 1),
- (u.hash_bits = a + 7),
- (u.hash_size = 1 << u.hash_bits),
- (u.hash_mask = u.hash_size - 1),
- (u.hash_shift = ~~((u.hash_bits + V - 1) / V)),
- (u.window = new S.Buf8(2 * u.w_size)),
- (u.head = new S.Buf16(u.hash_size)),
- (u.prev = new S.Buf16(u.w_size)),
- (u.lit_bufsize = 1 << (a + 6)),
- (u.pending_buf_size = 4 * u.lit_bufsize),
- (u.pending_buf = new S.Buf8(u.pending_buf_size)),
- (u.d_buf = 1 * u.lit_bufsize),
- (u.l_buf = 3 * u.lit_bufsize),
- (u.level = e),
- (u.strategy = o),
- (u.method = n),
- b(t)
- );
- }
- var w,
- S = t('../utils/common'),
- A = t('./trees'),
- O = t('./adler32'),
- P = t('./crc32'),
- T = t('./messages'),
- I = 0,
- D = 4,
- C = 0,
- M = -2,
- L = -1,
- U = 1,
- k = 4,
- x = 2,
- R = 8,
- N = 9,
- B = 286,
- H = 30,
- F = 19,
- j = 2 * B + 1,
- G = 15,
- V = 3,
- z = 258,
- K = z + V + 1,
- Y = 42,
- W = 113,
- q = 1,
- X = 2,
- J = 3,
- Z = 4;
- (w = [
- new _(0, 0, 0, 0, function (t, e) {
- var n = 65535;
- for (n > t.pending_buf_size - 5 && (n = t.pending_buf_size - 5); ; ) {
- if (t.lookahead <= 1) {
- if ((h(t), 0 === t.lookahead && e === I)) return q;
- if (0 === t.lookahead) break;
- }
- (t.strstart += t.lookahead), (t.lookahead = 0);
- var i = t.block_start + n;
- if (
- (0 === t.strstart || t.strstart >= i) &&
- ((t.lookahead = t.strstart - i),
- (t.strstart = i),
- s(t, !1),
- 0 === t.strm.avail_out)
- )
- return q;
- if (
- t.strstart - t.block_start >= t.w_size - K &&
- (s(t, !1), 0 === t.strm.avail_out)
- )
- return q;
- }
- return (
- (t.insert = 0),
- e === D
- ? (s(t, !0), 0 === t.strm.avail_out ? J : Z)
- : (t.strstart > t.block_start && (s(t, !1), t.strm.avail_out), q)
- );
- }),
- new _(4, 4, 8, 4, f),
- new _(4, 5, 16, 8, f),
- new _(4, 6, 32, 32, f),
- new _(4, 4, 16, 16, g),
- new _(8, 16, 32, 32, g),
- new _(8, 16, 128, 128, g),
- new _(8, 32, 128, 256, g),
- new _(32, 128, 258, 1024, g),
- new _(32, 258, 258, 4096, g),
- ]),
- (n.deflateInit = function (t, e) {
- return E(t, e, R, 15, 8, 0);
- }),
- (n.deflateInit2 = E),
- (n.deflateReset = b),
- (n.deflateResetKeep = y),
- (n.deflateSetHeader = function (t, e) {
- return t && t.state ? (2 !== t.state.wrap ? M : ((t.state.gzhead = e), C)) : M;
- }),
- (n.deflate = function (t, e) {
- var n, s, l, d;
- if (!t || !t.state || e > 5 || e < 0) return t ? i(t, M) : M;
- if (
- ((s = t.state),
- !t.output || (!t.input && 0 !== t.avail_in) || (666 === s.status && e !== D))
- )
- return i(t, 0 === t.avail_out ? -5 : M);
- if (((s.strm = t), (n = s.last_flush), (s.last_flush = e), s.status === Y))
- if (2 === s.wrap)
- (t.adler = 0),
- u(s, 31),
- u(s, 139),
- u(s, 8),
- s.gzhead
- ? (u(
- s,
- (s.gzhead.text ? 1 : 0) +
- (s.gzhead.hcrc ? 2 : 0) +
- (s.gzhead.extra ? 4 : 0) +
- (s.gzhead.name ? 8 : 0) +
- (s.gzhead.comment ? 16 : 0),
- ),
- u(s, 255 & s.gzhead.time),
- u(s, (s.gzhead.time >> 8) & 255),
- u(s, (s.gzhead.time >> 16) & 255),
- u(s, (s.gzhead.time >> 24) & 255),
- u(s, 9 === s.level ? 2 : s.strategy >= 2 || s.level < 2 ? 4 : 0),
- u(s, 255 & s.gzhead.os),
- s.gzhead.extra &&
- s.gzhead.extra.length &&
- (u(s, 255 & s.gzhead.extra.length),
- u(s, (s.gzhead.extra.length >> 8) & 255)),
- s.gzhead.hcrc && (t.adler = P(t.adler, s.pending_buf, s.pending, 0)),
- (s.gzindex = 0),
- (s.status = 69))
- : (u(s, 0),
- u(s, 0),
- u(s, 0),
- u(s, 0),
- u(s, 0),
- u(s, 9 === s.level ? 2 : s.strategy >= 2 || s.level < 2 ? 4 : 0),
- u(s, 3),
- (s.status = W));
- else {
- var h = (R + ((s.w_bits - 8) << 4)) << 8;
- (h |=
- (s.strategy >= 2 || s.level < 2
- ? 0
- : s.level < 6
- ? 1
- : 6 === s.level
- ? 2
- : 3) << 6),
- 0 !== s.strstart && (h |= 32),
- (h += 31 - (h % 31)),
- (s.status = W),
- c(s, h),
- 0 !== s.strstart && (c(s, t.adler >>> 16), c(s, 65535 & t.adler)),
- (t.adler = 1);
- }
- if (69 === s.status)
- if (s.gzhead.extra) {
- for (
- l = s.pending;
- s.gzindex < (65535 & s.gzhead.extra.length) &&
- (s.pending !== s.pending_buf_size ||
- (s.gzhead.hcrc &&
- s.pending > l &&
- (t.adler = P(t.adler, s.pending_buf, s.pending - l, l)),
- o(t),
- (l = s.pending),
- s.pending !== s.pending_buf_size));
-
- )
- u(s, 255 & s.gzhead.extra[s.gzindex]), s.gzindex++;
- s.gzhead.hcrc &&
- s.pending > l &&
- (t.adler = P(t.adler, s.pending_buf, s.pending - l, l)),
- s.gzindex === s.gzhead.extra.length && ((s.gzindex = 0), (s.status = 73));
- } else s.status = 73;
- if (73 === s.status)
- if (s.gzhead.name) {
- l = s.pending;
- do {
- if (
- s.pending === s.pending_buf_size &&
- (s.gzhead.hcrc &&
- s.pending > l &&
- (t.adler = P(t.adler, s.pending_buf, s.pending - l, l)),
- o(t),
- (l = s.pending),
- s.pending === s.pending_buf_size)
- ) {
- d = 1;
- break;
- }
- (d =
- s.gzindex < s.gzhead.name.length
- ? 255 & s.gzhead.name.charCodeAt(s.gzindex++)
- : 0),
- u(s, d);
- } while (0 !== d);
- s.gzhead.hcrc &&
- s.pending > l &&
- (t.adler = P(t.adler, s.pending_buf, s.pending - l, l)),
- 0 === d && ((s.gzindex = 0), (s.status = 91));
- } else s.status = 91;
- if (91 === s.status)
- if (s.gzhead.comment) {
- l = s.pending;
- do {
- if (
- s.pending === s.pending_buf_size &&
- (s.gzhead.hcrc &&
- s.pending > l &&
- (t.adler = P(t.adler, s.pending_buf, s.pending - l, l)),
- o(t),
- (l = s.pending),
- s.pending === s.pending_buf_size)
- ) {
- d = 1;
- break;
- }
- (d =
- s.gzindex < s.gzhead.comment.length
- ? 255 & s.gzhead.comment.charCodeAt(s.gzindex++)
- : 0),
- u(s, d);
- } while (0 !== d);
- s.gzhead.hcrc &&
- s.pending > l &&
- (t.adler = P(t.adler, s.pending_buf, s.pending - l, l)),
- 0 === d && (s.status = 103);
- } else s.status = 103;
- if (
- (103 === s.status &&
- (s.gzhead.hcrc
- ? (s.pending + 2 > s.pending_buf_size && o(t),
- s.pending + 2 <= s.pending_buf_size &&
- (u(s, 255 & t.adler),
- u(s, (t.adler >> 8) & 255),
- (t.adler = 0),
- (s.status = W)))
- : (s.status = W)),
- 0 !== s.pending)
- ) {
- if ((o(t), 0 === t.avail_out)) return (s.last_flush = -1), C;
- } else if (0 === t.avail_in && r(e) <= r(n) && e !== D) return i(t, -5);
- if (666 === s.status && 0 !== t.avail_in) return i(t, -5);
- if (0 !== t.avail_in || 0 !== s.lookahead || (e !== I && 666 !== s.status)) {
- var f =
- 2 === s.strategy ? v(s, e) : 3 === s.strategy ? p(s, e) : w[s.level].func(s, e);
- if (((f !== J && f !== Z) || (s.status = 666), f === q || f === J))
- return 0 === t.avail_out && (s.last_flush = -1), C;
- if (
- f === X &&
- (1 === e
- ? A._tr_align(s)
- : 5 !== e &&
- (A._tr_stored_block(s, 0, 0, !1),
- 3 === e &&
- (a(s.head),
- 0 === s.lookahead &&
- ((s.strstart = 0), (s.block_start = 0), (s.insert = 0)))),
- o(t),
- 0 === t.avail_out)
- )
- return (s.last_flush = -1), C;
- }
- return e !== D
- ? C
- : s.wrap <= 0
- ? 1
- : (2 === s.wrap
- ? (u(s, 255 & t.adler),
- u(s, (t.adler >> 8) & 255),
- u(s, (t.adler >> 16) & 255),
- u(s, (t.adler >> 24) & 255),
- u(s, 255 & t.total_in),
- u(s, (t.total_in >> 8) & 255),
- u(s, (t.total_in >> 16) & 255),
- u(s, (t.total_in >> 24) & 255))
- : (c(s, t.adler >>> 16), c(s, 65535 & t.adler)),
- o(t),
- s.wrap > 0 && (s.wrap = -s.wrap),
- 0 !== s.pending ? C : 1);
- }),
- (n.deflateEnd = function (t) {
- var e;
- return t && t.state
- ? (e = t.state.status) !== Y &&
- 69 !== e &&
- 73 !== e &&
- 91 !== e &&
- 103 !== e &&
- e !== W &&
- 666 !== e
- ? i(t, M)
- : ((t.state = null), e === W ? i(t, -3) : C)
- : M;
- }),
- (n.deflateSetDictionary = function (t, e) {
- var n,
- i,
- r,
- o,
- s,
- u,
- c,
- l,
- d = e.length;
- if (!t || !t.state) return M;
- if (
- ((n = t.state), 2 === (o = n.wrap) || (1 === o && n.status !== Y) || n.lookahead)
- )
- return M;
- for (
- 1 === o && (t.adler = O(t.adler, e, d, 0)),
- n.wrap = 0,
- d >= n.w_size &&
- (0 === o &&
- (a(n.head), (n.strstart = 0), (n.block_start = 0), (n.insert = 0)),
- (l = new S.Buf8(n.w_size)),
- S.arraySet(l, e, d - n.w_size, n.w_size, 0),
- (e = l),
- (d = n.w_size)),
- s = t.avail_in,
- u = t.next_in,
- c = t.input,
- t.avail_in = d,
- t.next_in = 0,
- t.input = e,
- h(n);
- n.lookahead >= V;
-
- ) {
- (i = n.strstart), (r = n.lookahead - (V - 1));
- do {
- (n.ins_h = ((n.ins_h << n.hash_shift) ^ n.window[i + V - 1]) & n.hash_mask),
- (n.prev[i & n.w_mask] = n.head[n.ins_h]),
- (n.head[n.ins_h] = i),
- i++;
- } while (--r);
- (n.strstart = i), (n.lookahead = V - 1), h(n);
- }
- return (
- (n.strstart += n.lookahead),
- (n.block_start = n.strstart),
- (n.insert = n.lookahead),
- (n.lookahead = 0),
- (n.match_length = n.prev_length = V - 1),
- (n.match_available = 0),
- (t.next_in = u),
- (t.input = c),
- (t.avail_in = s),
- (n.wrap = o),
- C
- );
- }),
- (n.deflateInfo = 'pako deflate (from Nodeca project)');
- },
- { '../utils/common': 1, './adler32': 3, './crc32': 4, './messages': 6, './trees': 7 },
- ],
- 6: [
- function (t, e, n) {
- 'use strict';
- e.exports = {
- 2: 'need dictionary',
- 1: 'stream end',
- 0: '',
- '-1': 'file error',
- '-2': 'stream error',
- '-3': 'data error',
- '-4': 'insufficient memory',
- '-5': 'buffer error',
- '-6': 'incompatible version',
- };
- },
- {},
- ],
- 7: [
- function (t, e, n) {
- 'use strict';
- function i(t) {
- for (var e = t.length; --e >= 0; ) t[e] = 0;
- }
- function r(t, e, n, i, r) {
- (this.static_tree = t),
- (this.extra_bits = e),
- (this.extra_base = n),
- (this.elems = i),
- (this.max_length = r),
- (this.has_stree = t && t.length);
- }
- function a(t, e) {
- (this.dyn_tree = t), (this.max_code = 0), (this.stat_desc = e);
- }
- function o(t) {
- return t < 256 ? z[t] : z[256 + (t >>> 7)];
- }
- function s(t, e) {
- (t.pending_buf[t.pending++] = 255 & e),
- (t.pending_buf[t.pending++] = (e >>> 8) & 255);
- }
- function u(t, e, n) {
- t.bi_valid > L - n
- ? ((t.bi_buf |= (e << t.bi_valid) & 65535),
- s(t, t.bi_buf),
- (t.bi_buf = e >> (L - t.bi_valid)),
- (t.bi_valid += n - L))
- : ((t.bi_buf |= (e << t.bi_valid) & 65535), (t.bi_valid += n));
- }
- function c(t, e, n) {
- u(t, n[2 * e], n[2 * e + 1]);
- }
- function l(t, e) {
- var n = 0;
- do {
- (n |= 1 & t), (t >>>= 1), (n <<= 1);
- } while (--e > 0);
- return n >>> 1;
- }
- function d(t, e, n) {
- var i,
- r,
- a = new Array(M + 1),
- o = 0;
- for (i = 1; i <= M; i++) a[i] = o = (o + n[i - 1]) << 1;
- for (r = 0; r <= e; r++) {
- var s = t[2 * r + 1];
- 0 !== s && (t[2 * r] = l(a[s]++, s));
- }
- }
- function h(t) {
- var e;
- for (e = 0; e < T; e++) t.dyn_ltree[2 * e] = 0;
- for (e = 0; e < I; e++) t.dyn_dtree[2 * e] = 0;
- for (e = 0; e < D; e++) t.bl_tree[2 * e] = 0;
- (t.dyn_ltree[2 * k] = 1),
- (t.opt_len = t.static_len = 0),
- (t.last_lit = t.matches = 0);
- }
- function f(t) {
- t.bi_valid > 8
- ? s(t, t.bi_buf)
- : t.bi_valid > 0 && (t.pending_buf[t.pending++] = t.bi_buf),
- (t.bi_buf = 0),
- (t.bi_valid = 0);
- }
- function g(t, e, n, i) {
- var r = 2 * e,
- a = 2 * n;
- return t[r] < t[a] || (t[r] === t[a] && i[e] <= i[n]);
- }
- function p(t, e, n) {
- for (
- var i = t.heap[n], r = n << 1;
- r <= t.heap_len &&
- (r < t.heap_len && g(e, t.heap[r + 1], t.heap[r], t.depth) && r++,
- !g(e, i, t.heap[r], t.depth));
-
- )
- (t.heap[n] = t.heap[r]), (n = r), (r <<= 1);
- t.heap[n] = i;
- }
- function v(t, e, n) {
- var i,
- r,
- a,
- s,
- l = 0;
- if (0 !== t.last_lit)
- do {
- (i = (t.pending_buf[t.d_buf + 2 * l] << 8) | t.pending_buf[t.d_buf + 2 * l + 1]),
- (r = t.pending_buf[t.l_buf + l]),
- l++,
- 0 === i
- ? c(t, r, e)
- : (c(t, (a = K[r]) + P + 1, e),
- 0 !== (s = B[a]) && u(t, (r -= Y[a]), s),
- c(t, (a = o(--i)), n),
- 0 !== (s = H[a]) && u(t, (i -= W[a]), s));
- } while (l < t.last_lit);
- c(t, k, e);
- }
- function _(t, e) {
- var n,
- i,
- r,
- a = e.dyn_tree,
- o = e.stat_desc.static_tree,
- s = e.stat_desc.has_stree,
- u = e.stat_desc.elems,
- c = -1;
- for (t.heap_len = 0, t.heap_max = C, n = 0; n < u; n++)
- 0 !== a[2 * n]
- ? ((t.heap[++t.heap_len] = c = n), (t.depth[n] = 0))
- : (a[2 * n + 1] = 0);
- for (; t.heap_len < 2; )
- (a[2 * (r = t.heap[++t.heap_len] = c < 2 ? ++c : 0)] = 1),
- (t.depth[r] = 0),
- t.opt_len--,
- s && (t.static_len -= o[2 * r + 1]);
- for (e.max_code = c, n = t.heap_len >> 1; n >= 1; n--) p(t, a, n);
- r = u;
- do {
- (n = t.heap[1]),
- (t.heap[1] = t.heap[t.heap_len--]),
- p(t, a, 1),
- (i = t.heap[1]),
- (t.heap[--t.heap_max] = n),
- (t.heap[--t.heap_max] = i),
- (a[2 * r] = a[2 * n] + a[2 * i]),
- (t.depth[r] = (t.depth[n] >= t.depth[i] ? t.depth[n] : t.depth[i]) + 1),
- (a[2 * n + 1] = a[2 * i + 1] = r),
- (t.heap[1] = r++),
- p(t, a, 1);
- } while (t.heap_len >= 2);
- (t.heap[--t.heap_max] = t.heap[1]),
- (function (t, e) {
- var n,
- i,
- r,
- a,
- o,
- s,
- u = e.dyn_tree,
- c = e.max_code,
- l = e.stat_desc.static_tree,
- d = e.stat_desc.has_stree,
- h = e.stat_desc.extra_bits,
- f = e.stat_desc.extra_base,
- g = e.stat_desc.max_length,
- p = 0;
- for (a = 0; a <= M; a++) t.bl_count[a] = 0;
- for (u[2 * t.heap[t.heap_max] + 1] = 0, n = t.heap_max + 1; n < C; n++)
- (a = u[2 * u[2 * (i = t.heap[n]) + 1] + 1] + 1) > g && ((a = g), p++),
- (u[2 * i + 1] = a),
- i > c ||
- (t.bl_count[a]++,
- (o = 0),
- i >= f && (o = h[i - f]),
- (s = u[2 * i]),
- (t.opt_len += s * (a + o)),
- d && (t.static_len += s * (l[2 * i + 1] + o)));
- if (0 !== p) {
- do {
- for (a = g - 1; 0 === t.bl_count[a]; ) a--;
- t.bl_count[a]--, (t.bl_count[a + 1] += 2), t.bl_count[g]--, (p -= 2);
- } while (p > 0);
- for (a = g; 0 !== a; a--)
- for (i = t.bl_count[a]; 0 !== i; )
- (r = t.heap[--n]) > c ||
- (u[2 * r + 1] !== a &&
- ((t.opt_len += (a - u[2 * r + 1]) * u[2 * r]), (u[2 * r + 1] = a)),
- i--);
- }
- })(t, e),
- d(a, c, t.bl_count);
- }
- function m(t, e, n) {
- var i,
- r,
- a = -1,
- o = e[1],
- s = 0,
- u = 7,
- c = 4;
- for (0 === o && ((u = 138), (c = 3)), e[2 * (n + 1) + 1] = 65535, i = 0; i <= n; i++)
- (r = o),
- (o = e[2 * (i + 1) + 1]),
- (++s < u && r === o) ||
- (s < c
- ? (t.bl_tree[2 * r] += s)
- : 0 !== r
- ? (r !== a && t.bl_tree[2 * r]++, t.bl_tree[2 * x]++)
- : s <= 10
- ? t.bl_tree[2 * R]++
- : t.bl_tree[2 * N]++,
- (s = 0),
- (a = r),
- 0 === o
- ? ((u = 138), (c = 3))
- : r === o
- ? ((u = 6), (c = 3))
- : ((u = 7), (c = 4)));
- }
- function y(t, e, n) {
- var i,
- r,
- a = -1,
- o = e[1],
- s = 0,
- l = 7,
- d = 4;
- for (0 === o && ((l = 138), (d = 3)), i = 0; i <= n; i++)
- if (((r = o), (o = e[2 * (i + 1) + 1]), !(++s < l && r === o))) {
- if (s < d)
- do {
- c(t, r, t.bl_tree);
- } while (0 != --s);
- else
- 0 !== r
- ? (r !== a && (c(t, r, t.bl_tree), s--), c(t, x, t.bl_tree), u(t, s - 3, 2))
- : s <= 10
- ? (c(t, R, t.bl_tree), u(t, s - 3, 3))
- : (c(t, N, t.bl_tree), u(t, s - 11, 7));
- (s = 0),
- (a = r),
- 0 === o
- ? ((l = 138), (d = 3))
- : r === o
- ? ((l = 6), (d = 3))
- : ((l = 7), (d = 4));
- }
- }
- function b(t, e, n, i) {
- u(t, (A << 1) + (i ? 1 : 0), 3),
- (function (t, e, n, i) {
- f(t),
- i && (s(t, n), s(t, ~n)),
- E.arraySet(t.pending_buf, t.window, e, n, t.pending),
- (t.pending += n);
- })(t, e, n, !0);
- }
- var E = t('../utils/common'),
- w = 0,
- S = 1,
- A = 0,
- O = 29,
- P = 256,
- T = P + 1 + O,
- I = 30,
- D = 19,
- C = 2 * T + 1,
- M = 15,
- L = 16,
- U = 7,
- k = 256,
- x = 16,
- R = 17,
- N = 18,
- B = [
- 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5,
- 0,
- ],
- H = [
- 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
- 12, 12, 13, 13,
- ],
- F = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7],
- j = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15],
- G = new Array(2 * (T + 2));
- i(G);
- var V = new Array(2 * I);
- i(V);
- var z = new Array(512);
- i(z);
- var K = new Array(256);
- i(K);
- var Y = new Array(O);
- i(Y);
- var W = new Array(I);
- i(W);
- var q,
- X,
- J,
- Z = !1;
- (n._tr_init = function (t) {
- Z ||
- ((function () {
- var t,
- e,
- n,
- i,
- a,
- o = new Array(M + 1);
- for (n = 0, i = 0; i < O - 1; i++)
- for (Y[i] = n, t = 0; t < 1 << B[i]; t++) K[n++] = i;
- for (K[n - 1] = i, a = 0, i = 0; i < 16; i++)
- for (W[i] = a, t = 0; t < 1 << H[i]; t++) z[a++] = i;
- for (a >>= 7; i < I; i++)
- for (W[i] = a << 7, t = 0; t < 1 << (H[i] - 7); t++) z[256 + a++] = i;
- for (e = 0; e <= M; e++) o[e] = 0;
- for (t = 0; t <= 143; ) (G[2 * t + 1] = 8), t++, o[8]++;
- for (; t <= 255; ) (G[2 * t + 1] = 9), t++, o[9]++;
- for (; t <= 279; ) (G[2 * t + 1] = 7), t++, o[7]++;
- for (; t <= 287; ) (G[2 * t + 1] = 8), t++, o[8]++;
- for (d(G, T + 1, o), t = 0; t < I; t++) (V[2 * t + 1] = 5), (V[2 * t] = l(t, 5));
- (q = new r(G, B, P + 1, T, M)),
- (X = new r(V, H, 0, I, M)),
- (J = new r(new Array(0), F, 0, D, U));
- })(),
- (Z = !0)),
- (t.l_desc = new a(t.dyn_ltree, q)),
- (t.d_desc = new a(t.dyn_dtree, X)),
- (t.bl_desc = new a(t.bl_tree, J)),
- (t.bi_buf = 0),
- (t.bi_valid = 0),
- h(t);
- }),
- (n._tr_stored_block = b),
- (n._tr_flush_block = function (t, e, n, i) {
- var r,
- a,
- o = 0;
- t.level > 0
- ? (2 === t.strm.data_type &&
- (t.strm.data_type = (function (t) {
- var e,
- n = 4093624447;
- for (e = 0; e <= 31; e++, n >>>= 1)
- if (1 & n && 0 !== t.dyn_ltree[2 * e]) return w;
- if (0 !== t.dyn_ltree[18] || 0 !== t.dyn_ltree[20] || 0 !== t.dyn_ltree[26])
- return S;
- for (e = 32; e < P; e++) if (0 !== t.dyn_ltree[2 * e]) return S;
- return w;
- })(t)),
- _(t, t.l_desc),
- _(t, t.d_desc),
- (o = (function (t) {
- var e;
- for (
- m(t, t.dyn_ltree, t.l_desc.max_code),
- m(t, t.dyn_dtree, t.d_desc.max_code),
- _(t, t.bl_desc),
- e = D - 1;
- e >= 3 && 0 === t.bl_tree[2 * j[e] + 1];
- e--
- );
- return (t.opt_len += 3 * (e + 1) + 5 + 5 + 4), e;
- })(t)),
- (r = (t.opt_len + 3 + 7) >>> 3),
- (a = (t.static_len + 3 + 7) >>> 3) <= r && (r = a))
- : (r = a = n + 5),
- n + 4 <= r && -1 !== e
- ? b(t, e, n, i)
- : 4 === t.strategy || a === r
- ? (u(t, 2 + (i ? 1 : 0), 3), v(t, G, V))
- : (u(t, 4 + (i ? 1 : 0), 3),
- (function (t, e, n, i) {
- var r;
- for (u(t, e - 257, 5), u(t, n - 1, 5), u(t, i - 4, 4), r = 0; r < i; r++)
- u(t, t.bl_tree[2 * j[r] + 1], 3);
- y(t, t.dyn_ltree, e - 1), y(t, t.dyn_dtree, n - 1);
- })(t, t.l_desc.max_code + 1, t.d_desc.max_code + 1, o + 1),
- v(t, t.dyn_ltree, t.dyn_dtree)),
- h(t),
- i && f(t);
- }),
- (n._tr_tally = function (t, e, n) {
- return (
- (t.pending_buf[t.d_buf + 2 * t.last_lit] = (e >>> 8) & 255),
- (t.pending_buf[t.d_buf + 2 * t.last_lit + 1] = 255 & e),
- (t.pending_buf[t.l_buf + t.last_lit] = 255 & n),
- t.last_lit++,
- 0 === e
- ? t.dyn_ltree[2 * n]++
- : (t.matches++,
- e--,
- t.dyn_ltree[2 * (K[n] + P + 1)]++,
- t.dyn_dtree[2 * o(e)]++),
- t.last_lit === t.lit_bufsize - 1
- );
- }),
- (n._tr_align = function (t) {
- u(t, 2, 3),
- c(t, k, G),
- (function (t) {
- 16 === t.bi_valid
- ? (s(t, t.bi_buf), (t.bi_buf = 0), (t.bi_valid = 0))
- : t.bi_valid >= 8 &&
- ((t.pending_buf[t.pending++] = 255 & t.bi_buf),
- (t.bi_buf >>= 8),
- (t.bi_valid -= 8));
- })(t);
- });
- },
- { '../utils/common': 1 },
- ],
- 8: [
- function (t, e, n) {
- 'use strict';
- e.exports = function () {
- (this.input = null),
- (this.next_in = 0),
- (this.avail_in = 0),
- (this.total_in = 0),
- (this.output = null),
- (this.next_out = 0),
- (this.avail_out = 0),
- (this.total_out = 0),
- (this.msg = ''),
- (this.state = null),
- (this.data_type = 2),
- (this.adler = 0);
- };
- },
- {},
- ],
- '/lib/deflate.js': [
- function (t, e, n) {
- 'use strict';
- function i(t) {
- if (!(this instanceof i)) return new i(t);
- this.options = o.assign(
- {
- level: h,
- method: g,
- chunkSize: 16384,
- windowBits: 15,
- memLevel: 8,
- strategy: f,
- to: '',
- },
- t || {},
- );
- var e = this.options;
- e.raw && e.windowBits > 0
- ? (e.windowBits = -e.windowBits)
- : e.gzip && e.windowBits > 0 && e.windowBits < 16 && (e.windowBits += 16),
- (this.err = 0),
- (this.msg = ''),
- (this.ended = !1),
- (this.chunks = []),
- (this.strm = new c()),
- (this.strm.avail_out = 0);
- var n = a.deflateInit2(
- this.strm,
- e.level,
- e.method,
- e.windowBits,
- e.memLevel,
- e.strategy,
- );
- if (n !== d) throw new Error(u[n]);
- if ((e.header && a.deflateSetHeader(this.strm, e.header), e.dictionary)) {
- var r;
- if (
- ((r =
- 'string' == typeof e.dictionary
- ? s.string2buf(e.dictionary)
- : '[object ArrayBuffer]' === l.call(e.dictionary)
- ? new Uint8Array(e.dictionary)
- : e.dictionary),
- (n = a.deflateSetDictionary(this.strm, r)) !== d)
- )
- throw new Error(u[n]);
- this._dict_set = !0;
- }
- }
- function r(t, e) {
- var n = new i(e);
- if ((n.push(t, !0), n.err)) throw n.msg || u[n.err];
- return n.result;
- }
- var a = t('./zlib/deflate'),
- o = t('./utils/common'),
- s = t('./utils/strings'),
- u = t('./zlib/messages'),
- c = t('./zlib/zstream'),
- l = Object.prototype.toString,
- d = 0,
- h = -1,
- f = 0,
- g = 8;
- (i.prototype.push = function (t, e) {
- var n,
- i,
- r = this.strm,
- u = this.options.chunkSize;
- if (this.ended) return !1;
- (i = e === ~~e ? e : !0 === e ? 4 : 0),
- 'string' == typeof t
- ? (r.input = s.string2buf(t))
- : '[object ArrayBuffer]' === l.call(t)
- ? (r.input = new Uint8Array(t))
- : (r.input = t),
- (r.next_in = 0),
- (r.avail_in = r.input.length);
- do {
- if (
- (0 === r.avail_out &&
- ((r.output = new o.Buf8(u)), (r.next_out = 0), (r.avail_out = u)),
- 1 !== (n = a.deflate(r, i)) && n !== d)
- )
- return this.onEnd(n), (this.ended = !0), !1;
- (0 !== r.avail_out && (0 !== r.avail_in || (4 !== i && 2 !== i))) ||
- ('string' === this.options.to
- ? this.onData(s.buf2binstring(o.shrinkBuf(r.output, r.next_out)))
- : this.onData(o.shrinkBuf(r.output, r.next_out)));
- } while ((r.avail_in > 0 || 0 === r.avail_out) && 1 !== n);
- return 4 === i
- ? ((n = a.deflateEnd(this.strm)), this.onEnd(n), (this.ended = !0), n === d)
- : 2 !== i || (this.onEnd(d), (r.avail_out = 0), !0);
- }),
- (i.prototype.onData = function (t) {
- this.chunks.push(t);
- }),
- (i.prototype.onEnd = function (t) {
- t === d &&
- ('string' === this.options.to
- ? (this.result = this.chunks.join(''))
- : (this.result = o.flattenChunks(this.chunks))),
- (this.chunks = []),
- (this.err = t),
- (this.msg = this.strm.msg);
- }),
- (n.Deflate = i),
- (n.deflate = r),
- (n.deflateRaw = function (t, e) {
- return ((e = e || {}).raw = !0), r(t, e);
- }),
- (n.gzip = function (t, e) {
- return ((e = e || {}).gzip = !0), r(t, e);
- });
- },
- {
- './utils/common': 1,
- './utils/strings': 2,
- './zlib/deflate': 5,
- './zlib/messages': 6,
- './zlib/zstream': 8,
- },
- ],
- },
- {},
- [],
- )('/lib/deflate.js')),
- ((_POSignalsEntities || (_POSignalsEntities = {})).evaluateModernizr = function () {
- !(function (t, e, n, i) {
- function r(t, e) {
- return typeof t === e;
- }
- function a() {
- return 'function' != typeof n.createElement
- ? n.createElement(arguments[0])
- : E
- ? n.createElementNS.call(n, 'http://www.w3.org/2000/svg', arguments[0])
- : n.createElement.apply(n, arguments);
- }
- function o(t, e) {
- return !!~('' + t).indexOf(e);
- }
- function s(t, e, i, r) {
- var o,
- s,
- u,
- c,
- l = 'modernizr',
- d = a('div'),
- h = (function () {
- var t = n.body;
- return t || ((t = a(E ? 'svg' : 'body')).fake = !0), t;
- })();
- if (parseInt(i, 10))
- for (; i--; ) ((u = a('div')).id = r ? r[i] : l + (i + 1)), d.appendChild(u);
- return (
- ((o = a('style')).type = 'text/css'),
- (o.id = 's' + l),
- (h.fake ? h : d).appendChild(o),
- h.appendChild(d),
- o.styleSheet ? (o.styleSheet.cssText = t) : o.appendChild(n.createTextNode(t)),
- (d.id = l),
- h.fake &&
- ((h.style.background = ''),
- (h.style.overflow = 'hidden'),
- (c = b.style.overflow),
- (b.style.overflow = 'hidden'),
- b.appendChild(h)),
- (s = e(d, t)),
- h.fake
- ? (h.parentNode.removeChild(h), (b.style.overflow = c), b.offsetHeight)
- : d.parentNode.removeChild(d),
- !!s
- );
- }
- function u(t) {
- return t
- .replace(/([A-Z])/g, function (t, e) {
- return '-' + e.toLowerCase();
- })
- .replace(/^ms-/, '-ms-');
- }
- function c(t, n, i) {
- var r;
- if ('getComputedStyle' in e) {
- r = getComputedStyle.call(e, t, n);
- var a = e.console;
- if (null !== r) i && (r = r.getPropertyValue(i));
- else if (a) {
- a[a.error ? 'error' : 'log'].call(
- a,
- 'getComputedStyle returning null, its possible modernizr test results are inaccurate',
- );
- }
- } else r = !n && t.currentStyle && t.currentStyle[i];
- return r;
- }
- function l(t, n) {
- var r = t.length;
- if ('CSS' in e && 'supports' in e.CSS) {
- for (; r--; ) if (e.CSS.supports(u(t[r]), n)) return !0;
- return !1;
- }
- if ('CSSSupportsRule' in e) {
- for (var a = []; r--; ) a.push('(' + u(t[r]) + ':' + n + ')');
- return s(
- '@supports (' + (a = a.join(' or ')) + ') { #modernizr { position: absolute; } }',
- function (t) {
- return 'absolute' === c(t, null, 'position');
- },
- );
- }
- return i;
- }
- function d(t) {
- return t
- .replace(/([a-z])-([a-z])/g, function (t, e, n) {
- return e + n.toUpperCase();
- })
- .replace(/^-/, '');
- }
- function h(t, e, n, s) {
- function u() {
- h && (delete P.style, delete P.modElem);
- }
- if (((s = !r(s, 'undefined') && s), !r(n, 'undefined'))) {
- var c = l(t, n);
- if (!r(c, 'undefined')) return c;
- }
- for (var h, f, g, p, v, _ = ['modernizr', 'tspan', 'samp']; !P.style && _.length; )
- (h = !0), (P.modElem = a(_.shift())), (P.style = P.modElem.style);
- for (g = t.length, f = 0; f < g; f++)
- if (((p = t[f]), (v = P.style[p]), o(p, '-') && (p = d(p)), P.style[p] !== i)) {
- if (s || r(n, 'undefined')) return u(), 'pfx' !== e || p;
- try {
- P.style[p] = n;
- } catch (t) {}
- if (P.style[p] !== v) return u(), 'pfx' !== e || p;
- }
- return u(), !1;
- }
- function f(t, e) {
- return function () {
- return t.apply(e, arguments);
- };
- }
- function g(t, e, n, i, a) {
- var o = t.charAt(0).toUpperCase() + t.slice(1),
- s = (t + ' ' + A.join(o + ' ') + o).split(' ');
- return r(e, 'string') || r(e, 'undefined')
- ? h(s, e, i, a)
- : (function (t, e, n) {
- var i;
- for (var a in t)
- if (t[a] in e)
- return !1 === n ? t[a] : r((i = e[t[a]]), 'function') ? f(i, n || e) : i;
- return !1;
- })((s = (t + ' ' + T.join(o + ' ') + o).split(' ')), e, n);
- }
- function p(t, e, n) {
- return g(t, i, i, e, n);
- }
- var v = [],
- _ = {
- _version: '3.11.1',
- _config: { classPrefix: '', enableClasses: !0, enableJSClass: !0, usePrefixes: !0 },
- _q: [],
- on: function (t, e) {
- var n = this;
- setTimeout(function () {
- e(n[t]);
- }, 0);
- },
- addTest: function (t, e, n) {
- v.push({ name: t, fn: e, options: n });
- },
- addAsyncTest: function (t) {
- v.push({ name: null, fn: t });
- },
- },
- m = function () {};
- (m.prototype = _), (m = new m());
- var y = [],
- b = n.documentElement,
- E = 'svg' === b.nodeName.toLowerCase(),
- w = (function () {
- var t = !('onblur' in b);
- return function (e, n) {
- var r;
- return (
- !!e &&
- ((n && 'string' != typeof n) || (n = a(n || 'div')),
- !(r = (e = 'on' + e) in n) &&
- t &&
- (n.setAttribute || (n = a('div')),
- n.setAttribute(e, ''),
- (r = 'function' == typeof n[e]),
- n[e] !== i && (n[e] = i),
- n.removeAttribute(e)),
- r)
- );
- };
- })();
- (_.hasEvent = w),
- m.addTest('ambientlight', w('devicelight', e)),
- m.addTest('applicationcache', 'applicationCache' in e),
- (function () {
- var t = a('audio');
- m.addTest('audio', function () {
- var e = !1;
- try {
- (e = !!t.canPlayType) && (e = new Boolean(e));
- } catch (t) {}
- return e;
- });
- try {
- t.canPlayType &&
- (m.addTest(
- 'audio.ogg',
- t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''),
- ),
- m.addTest(
- 'audio.mp3',
- t.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, ''),
- ),
- m.addTest(
- 'audio.opus',
- t.canPlayType('audio/ogg; codecs="opus"') ||
- t.canPlayType('audio/webm; codecs="opus"').replace(/^no$/, ''),
- ),
- m.addTest('audio.wav', t.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')),
- m.addTest(
- 'audio.m4a',
- (t.canPlayType('audio/x-m4a;') || t.canPlayType('audio/aac;')).replace(
- /^no$/,
- '',
- ),
- ));
- } catch (t) {}
- })();
- var S = 'Moz O ms Webkit',
- A = _._config.usePrefixes ? S.split(' ') : [];
- _._cssomPrefixes = A;
- var O = { elem: a('modernizr') };
- m._q.push(function () {
- delete O.elem;
- });
- var P = { style: O.elem.style };
- m._q.unshift(function () {
- delete P.style;
- });
- var T = _._config.usePrefixes ? S.toLowerCase().split(' ') : [];
- (_._domPrefixes = T), (_.testAllProps = g);
- var I = function (t) {
- var n,
- r = L.length,
- a = e.CSSRule;
- if (void 0 === a) return i;
- if (!t) return !1;
- if ((n = (t = t.replace(/^@/, '')).replace(/-/g, '_').toUpperCase() + '_RULE') in a)
- return '@' + t;
- for (var o = 0; o < r; o++) {
- var s = L[o];
- if (s.toUpperCase() + '_' + n in a) return '@-' + s.toLowerCase() + '-' + t;
- }
- return !1;
- };
- _.atRule = I;
- var D = (_.prefixed = function (t, e, n) {
- return 0 === t.indexOf('@')
- ? I(t)
- : (-1 !== t.indexOf('-') && (t = d(t)), e ? g(t, e, n) : g(t, 'pfx'));
- });
- m.addTest('batteryapi', !!D('battery', navigator) || !!D('getBattery', navigator), {
- aliases: ['battery-api'],
- }),
- m.addTest(
- 'blobconstructor',
- function () {
- try {
- return !!new Blob();
- } catch (t) {
- return !1;
- }
- },
- { aliases: ['blob-constructor'] },
- ),
- m.addTest('contextmenu', 'contextMenu' in b && 'HTMLMenuItemElement' in e),
- m.addTest('cors', 'XMLHttpRequest' in e && 'withCredentials' in new XMLHttpRequest());
- var C = D('crypto', e);
- m.addTest('crypto', !!D('subtle', C)),
- m.addTest('customelements', 'customElements' in e),
- m.addTest('customprotocolhandler', function () {
- if (!navigator.registerProtocolHandler) return !1;
- try {
- navigator.registerProtocolHandler('thisShouldFail');
- } catch (t) {
- return t instanceof TypeError;
- }
- return !1;
- }),
- m.addTest('customevent', 'CustomEvent' in e && 'function' == typeof e.CustomEvent),
- m.addTest('dart', !!D('startDart', navigator)),
- m.addTest(
- 'dataview',
- 'undefined' != typeof DataView && 'getFloat64' in DataView.prototype,
- ),
- m.addTest('eventlistener', 'addEventListener' in e),
- m.addTest('forcetouch', function () {
- return (
- !!w(D('mouseforcewillbegin', e, !1), e) &&
- MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN &&
- MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN
- );
- }),
- m.addTest('fullscreen', !(!D('exitFullscreen', n, !1) && !D('cancelFullScreen', n, !1))),
- m.addTest('gamepads', !!D('getGamepads', navigator)),
- m.addTest('geolocation', 'geolocation' in navigator),
- m.addTest('ie8compat', !e.addEventListener && !!n.documentMode && 7 === n.documentMode),
- m.addTest('intl', !!D('Intl', e)),
- m.addTest('json', 'JSON' in e && 'parse' in JSON && 'stringify' in JSON),
- (_.testAllProps = p),
- m.addTest('ligatures', p('fontFeatureSettings', '"liga" 1')),
- m.addTest('messagechannel', 'MessageChannel' in e),
- m.addTest('notification', function () {
- if (!e.Notification || !e.Notification.requestPermission) return !1;
- if ('granted' === e.Notification.permission) return !0;
- try {
- new e.Notification('');
- } catch (t) {
- if ('TypeError' === t.name) return !1;
- }
- return !0;
- }),
- m.addTest('pagevisibility', !!D('hidden', n, !1)),
- m.addTest('performance', !!D('performance', e));
- var M = [''].concat(T);
- (_._domPrefixesAll = M),
- m.addTest('pointerevents', function () {
- for (var t = 0, e = M.length; t < e; t++) if (w(M[t] + 'pointerdown')) return !0;
- return !1;
- }),
- m.addTest('pointerlock', !!D('exitPointerLock', n)),
- m.addTest('queryselector', 'querySelector' in n && 'querySelectorAll' in n),
- m.addTest('quotamanagement', function () {
- var t = D('temporaryStorage', navigator),
- e = D('persistentStorage', navigator);
- return !(!t || !e);
- }),
- m.addTest('requestanimationframe', !!D('requestAnimationFrame', e), { aliases: ['raf'] }),
- m.addTest('serviceworker', 'serviceWorker' in navigator);
- var L = _._config.usePrefixes ? ' -webkit- -moz- -o- -ms- '.split(' ') : ['', ''];
- _._prefixes = L;
- var U = (function () {
- var t = e.matchMedia || e.msMatchMedia;
- return t
- ? function (e) {
- var n = t(e);
- return (n && n.matches) || !1;
- }
- : function (t) {
- var e = !1;
- return (
- s('@media ' + t + ' { #modernizr { position: absolute; } }', function (t) {
- e = 'absolute' === c(t, null, 'position');
- }),
- e
- );
- };
- })();
- (_.mq = U),
- m.addTest('touchevents', function () {
- if (
- 'ontouchstart' in e ||
- e.TouchEvent ||
- (e.DocumentTouch && n instanceof DocumentTouch)
- )
- return !0;
- var t = ['(', L.join('touch-enabled),('), 'heartz', ')'].join('');
- return U(t);
- }),
- m.addTest('typedarrays', 'ArrayBuffer' in e),
- m.addTest('vibrate', !!D('vibrate', navigator)),
- (function () {
- var t = a('video');
- m.addTest('video', function () {
- var e = !1;
- try {
- (e = !!t.canPlayType) && (e = new Boolean(e));
- } catch (t) {}
- return e;
- });
- try {
- t.canPlayType &&
- (m.addTest(
- 'video.ogg',
- t.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, ''),
- ),
- m.addTest(
- 'video.h264',
- t.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, ''),
- ),
- m.addTest(
- 'video.h265',
- t.canPlayType('video/mp4; codecs="hev1"').replace(/^no$/, ''),
- ),
- m.addTest(
- 'video.webm',
- t.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, ''),
- ),
- m.addTest(
- 'video.vp9',
- t.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, ''),
- ),
- m.addTest(
- 'video.hls',
- t.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, ''),
- ),
- m.addTest(
- 'video.av1',
- t.canPlayType('video/mp4; codecs="av01"').replace(/^no$/, ''),
- ));
- } catch (t) {}
- })(),
- m.addTest('webgl', function () {
- return 'WebGLRenderingContext' in e;
- });
- var k = !1;
- try {
- k = 'WebSocket' in e && 2 === e.WebSocket.CLOSING;
- } catch (t) {}
- m.addTest('websockets', k),
- m.addTest('xdomainrequest', 'XDomainRequest' in e),
- m.addTest('matchmedia', !!D('matchMedia', e)),
- (function () {
- var t, e, n, i, a, o;
- for (var s in v)
- if (v.hasOwnProperty(s)) {
- if (
- ((t = []),
- (e = v[s]).name &&
- (t.push(e.name.toLowerCase()),
- e.options && e.options.aliases && e.options.aliases.length))
- )
- for (n = 0; n < e.options.aliases.length; n++)
- t.push(e.options.aliases[n].toLowerCase());
- for (i = r(e.fn, 'function') ? e.fn() : e.fn, a = 0; a < t.length; a++)
- 1 === (o = t[a].split('.')).length
- ? (m[o[0]] = i)
- : ((m[o[0]] && (!m[o[0]] || m[o[0]] instanceof Boolean)) ||
- (m[o[0]] = new Boolean(m[o[0]])),
- (m[o[0]][o[1]] = i)),
- y.push((i ? '' : 'no-') + o.join('-'));
- }
- })(),
- delete _.addTest,
- delete _.addAsyncTest;
- for (var x = 0; x < m._q.length; x++) m._q[x]();
- t.Modernizr = m;
- })(_POSignalsEntities || (_POSignalsEntities = {}), window, document);
- });
- var __awaiter =
- (this && this.__awaiter) ||
- function (t, e, n, i) {
- return new (n || (n = Promise))(function (r, a) {
- function o(t) {
- try {
- u(i.next(t));
- } catch (t) {
- a(t);
- }
- }
- function s(t) {
- try {
- u(i.throw(t));
- } catch (t) {
- a(t);
- }
- }
- function u(t) {
- var e;
- t.done
- ? r(t.value)
- : ((e = t.value),
- e instanceof n
- ? e
- : new n(function (t) {
- t(e);
- })).then(o, s);
- }
- u((i = i.apply(t, e || [])).next());
- });
- },
- __generator =
- (this && this.__generator) ||
- function (t, e) {
- var n,
- i,
- r,
- a,
- o = {
- label: 0,
- sent: function () {
- if (1 & r[0]) throw r[1];
- return r[1];
- },
- trys: [],
- ops: [],
- };
- return (
- (a = { next: s(0), throw: s(1), return: s(2) }),
- 'function' == typeof Symbol &&
- (a[Symbol.iterator] = function () {
- return this;
- }),
- a
- );
- function s(a) {
- return function (s) {
- return (function (a) {
- if (n) throw new TypeError('Generator is already executing.');
- for (; o; )
- try {
- if (
- ((n = 1),
- i &&
- (r =
- 2 & a[0]
- ? i.return
- : a[0]
- ? i.throw || ((r = i.return) && r.call(i), 0)
- : i.next) &&
- !(r = r.call(i, a[1])).done)
- )
- return r;
- switch (((i = 0), r && (a = [2 & a[0], r.value]), a[0])) {
- case 0:
- case 1:
- r = a;
- break;
- case 4:
- return o.label++, { value: a[1], done: !1 };
- case 5:
- o.label++, (i = a[1]), (a = [0]);
- continue;
- case 7:
- (a = o.ops.pop()), o.trys.pop();
- continue;
- default:
- if (
- !(r = (r = o.trys).length > 0 && r[r.length - 1]) &&
- (6 === a[0] || 2 === a[0])
- ) {
- o = 0;
- continue;
- }
- if (3 === a[0] && (!r || (a[1] > r[0] && a[1] < r[3]))) {
- o.label = a[1];
- break;
- }
- if (6 === a[0] && o.label < r[1]) {
- (o.label = r[1]), (r = a);
- break;
- }
- if (r && o.label < r[2]) {
- (o.label = r[2]), o.ops.push(a);
- break;
- }
- r[2] && o.ops.pop(), o.trys.pop();
- continue;
- }
- a = e.call(t, o);
- } catch (t) {
- (a = [6, t]), (i = 0);
- } finally {
- n = r = 0;
- }
- if (5 & a[0]) throw a[1];
- return { value: a[0] ? a[1] : void 0, done: !0 };
- })([a, s]);
- };
- }
- },
- __assign =
- (this && this.__assign) ||
- function () {
- return (__assign =
- Object.assign ||
- function (t) {
- for (var e, n = 1, i = arguments.length; n < i; n++)
- for (var r in (e = arguments[n]))
- Object.prototype.hasOwnProperty.call(e, r) && (t[r] = e[r]);
- return t;
- }).apply(this, arguments);
- };
- !(function (t) {
- !(function (e) {
- var n = (function () {
- function n() {
- (this._isIphoneOrIPad = !1),
- (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) &&
- (this._isIphoneOrIPad = !0),
- this.initUAParser();
- }
- return (
- Object.defineProperty(n.prototype, 'userAgentData', {
- get: function () {
- return this._userAgentData;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'deviceType', {
- get: function () {
- return (
- this._deviceType ||
- (e.Util.isMobile
- ? (this._deviceType =
- this.mobileType || this.desktopType || n.UNKNOWN_DEVICE_TYPE)
- : (this._deviceType =
- this.desktopType || this.mobileType || n.UNKNOWN_DEVICE_TYPE)),
- this._deviceType
- );
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'isIphoneOrIPad', {
- get: function () {
- return this._isIphoneOrIPad;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'browserName', {
- get: function () {
- return this._userAgentData &&
- this._userAgentData.browser &&
- this._userAgentData.browser.name
- ? this._userAgentData.browser.name.trim()
- : '';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'browserVersion', {
- get: function () {
- return this._userAgentData &&
- this._userAgentData.browser &&
- this._userAgentData.browser.version
- ? this._userAgentData.browser.version.trim()
- : '';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'osName', {
- get: function () {
- return this._userAgentData && this._userAgentData.os && this._userAgentData.os.name
- ? this._userAgentData.os.name.trim()
- : '';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'osVersion', {
- get: function () {
- return this._userAgentData && this._userAgentData.os && this._userAgentData.os.version
- ? this._userAgentData.os.version.trim()
- : '';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'deviceCategory', {
- get: function () {
- return this._userAgentData && this._userAgentData.device
- ? this._userAgentData.device.type
- : '';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'engineName', {
- get: function () {
- return this._userAgentData &&
- this._userAgentData.engine &&
- this._userAgentData.engine.name
- ? this._userAgentData.engine.name.trim()
- : '';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'engineVersion', {
- get: function () {
- return this._userAgentData &&
- this._userAgentData.engine &&
- this._userAgentData.engine.version
- ? this._userAgentData.engine.version.trim()
- : '';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'cpuArchitecture', {
- get: function () {
- return this._userAgentData &&
- this._userAgentData.cpu &&
- this._userAgentData.cpu.architecture
- ? this._userAgentData.cpu.architecture.trim()
- : '';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'deviceModel', {
- get: function () {
- return this._userAgentData &&
- this._userAgentData.device &&
- this._userAgentData.device.model
- ? this._userAgentData.device.model.trim()
- : '';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'deviceVendor', {
- get: function () {
- return this._userAgentData &&
- this._userAgentData.device &&
- this._userAgentData.device.vendor
- ? this._userAgentData.device.vendor.trim()
- : '';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'desktopType', {
- get: function () {
- var t = this.browserName;
- this.browserVersion && (t = t + '(' + this.browserVersion + ')');
- var e = this.osName;
- this.osVersion && (e = e + '(' + this.osVersion + ')');
- var n = t && e ? t + '-' + e : t || e;
- return n ? n.trim() : '';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'mobileType', {
- get: function () {
- var t = this.deviceModel,
- e = this.deviceVendor,
- n = t && e ? t + ' ' + e : t || e;
- return n ? n.trim() : '';
- },
- enumerable: !1,
- configurable: !0,
- }),
- (n.prototype.initUAParser = function () {
- try {
- var n = new t.UAParser();
- n.setUA(navigator.userAgent), (this._userAgentData = n.getResult());
- } catch (t) {
- e.Logger.warn('UAParser failure', t);
- }
- }),
- (n.UNKNOWN_DEVICE_TYPE = 'unknown'),
- n
- );
- })();
- e.BrowserInfo = n;
- })(t._POSignalsUtils || (t._POSignalsUtils = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- !(function (t) {
- var e = (function () {
- function t() {}
- return (
- Object.defineProperty(t, 'CLIENT_VERSION', {
- get: function () {
- return '5.3.5w';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(t, 'SALT', {
- get: function () {
- return 'ST8irbd3bB';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(t, 'TAB_UUID_KEY', {
- get: function () {
- return 'pos_tid';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(t, 'OPS_KEY', {
- get: function () {
- return 'pos_ops';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(t, 'DEVICE_ID_KEY', {
- get: function () {
- return 'SecuredTouchDeviceId';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(t, 'LAST_DEVICE_KEY_RESYNC', {
- get: function () {
- return 'DeviceRefreshDate';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(t, 'CAPTURED_KEYBOARD_INTERACTIONS', {
- get: function () {
- return 'pos_cki';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(t, 'CAPTURED_MOUSE_INTERACTIONS', {
- get: function () {
- return 'pos_cmi';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(t, 'CAPTURED_GESTURES', {
- get: function () {
- return 'pos_cg';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(t, 'CAPTURED_INDIRECT', {
- get: function () {
- return 'pos_cie';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(t, 'CAPTURED_TAGS', {
- get: function () {
- return 'pos_ct';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(t, 'KEYBOARD_INTERACTIONS_COUNT', {
- get: function () {
- return 'pos_kic';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(t, 'MOUSE_INTERACTIONS_COUNT', {
- get: function () {
- return 'pos_mic';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(t, 'GESTURES_COUNT', {
- get: function () {
- return 'pos_gc';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(t, 'EVENT_COUNTERS', {
- get: function () {
- return 'pos_ec';
- },
- enumerable: !1,
- configurable: !0,
- }),
- t
- );
- })();
- t.Constants = e;
- })(t._POSignalsUtils || (t._POSignalsUtils = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- !(function (t) {
- var e = (function () {
- function e(t, e, n) {
- if (
- (void 0 === t && (t = 'RSA-PSS'),
- void 0 === e && (e = ['sign', 'verify']),
- void 0 === n && (n = 'SHA-256'),
- (this.signingKeyType = t),
- (this.keyUsage = e),
- (this.algorithm = n),
- (this._crypto = window.crypto || window.msCrypto),
- !this._crypto || !this._crypto.subtle)
- )
- throw new Error('Cryptography API not supported in this browser');
- }
- return (
- (e.prototype.generateKeys = function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (t) {
- return [
- 2,
- this._crypto.subtle.generateKey(
- {
- name: this.signingKeyType,
- modulusLength: 2048,
- publicExponent: new Uint8Array([1, 0, 1]),
- hash: { name: this.algorithm },
- },
- !1,
- this.keyUsage,
- ),
- ];
- });
- });
- }),
- (e.prototype.exportPublicKey = function (e) {
- return __awaiter(this, void 0, void 0, function () {
- var n, i, r;
- return __generator(this, function (a) {
- switch (a.label) {
- case 0:
- return [4, this._crypto.subtle.exportKey('spki', e.publicKey)];
- case 1:
- return (
- (n = a.sent()),
- (i = t.Util.ab2str(n)),
- (r = btoa(i)),
- t.Logger.debug('Exported base64 pub key: ', r),
- [2, r]
- );
- }
- });
- });
- }),
- (e.prototype.exportPrivateKey = function (e) {
- return __awaiter(this, void 0, void 0, function () {
- var n, i, r, a;
- return __generator(this, function (o) {
- switch (o.label) {
- case 0:
- return [4, this._crypto.subtle.exportKey('pkcs8', e.privateKey)];
- case 1:
- return (
- (n = o.sent()),
- (i = t.Util.ab2str(n)),
- (r = btoa(i)),
- (a = '-----BEGIN PRIVATE KEY-----\n' + r + '\n-----END PRIVATE KEY-----'),
- t.Logger.debug('Exported base64 pem:', a),
- [2, a]
- );
- }
- });
- });
- }),
- (e.prototype.signChallenge = function (e, n, i) {
- return (
- void 0 === i && (i = 0),
- __awaiter(this, void 0, void 0, function () {
- var r, a, o;
- return __generator(this, function (s) {
- switch (s.label) {
- case 0:
- return (
- (r = t.Util.string2buf(e)),
- [
- 4,
- this._crypto.subtle.sign(
- { name: this.signingKeyType, saltLength: i, hash: this.algorithm },
- n,
- r,
- ),
- ]
- );
- case 1:
- return (
- (a = s.sent()),
- (o = btoa(String.fromCharCode.apply(null, new Uint8Array(a)))),
- t.Logger.debug('Signed challenge: ', o),
- [2, o]
- );
- }
- });
- })
- );
- }),
- e
- );
- })();
- t.CryptoOperator = e;
- })(t._POSignalsUtils || (t._POSignalsUtils = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- !(function (t) {
- var e = (function () {
- function t() {}
- return (
- Object.defineProperty(t, 'isLogEnabled', {
- get: function () {
- return this._isLogEnabled || window['enable-logs-pingOneSignals'];
- },
- set: function (t) {
- this._isLogEnabled = t;
- },
- enumerable: !1,
- configurable: !0,
- }),
- (t.debug = function (e) {
- for (var n = [], i = 1; i < arguments.length; i++) n[i - 1] = arguments[i];
- (e = t.TAG + ' ' + e),
- t.isLogEnabled &&
- (n && n.length > 0
- ? console.debug
- ? console.debug(e, n)
- : console.log(e, n)
- : console.debug
- ? console.debug(e)
- : console.log(e));
- }),
- (t.error = function (e) {
- for (var n = [], i = 1; i < arguments.length; i++) n[i - 1] = arguments[i];
- (e = t.TAG + ' ' + e),
- t.isLogEnabled && (n && n.length > 0 ? console.error(e, n) : console.error(e));
- }),
- (t.warn = function (e) {
- for (var n = [], i = 1; i < arguments.length; i++) n[i - 1] = arguments[i];
- (e = t.TAG + ' ' + e),
- t.isLogEnabled && (n && n.length > 0 ? console.warn(e, n) : console.warn(e));
- }),
- (t.info = function (e) {
- for (var n = [], i = 1; i < arguments.length; i++) n[i - 1] = arguments[i];
- (e = t.TAG + ' ' + e),
- t.isLogEnabled && (n && n.length > 0 ? console.info(e, n) : console.info(e));
- }),
- (t.TAG = '[SignalsSDK]'),
- t
- );
- })();
- t.Logger = e;
- })(t._POSignalsUtils || (t._POSignalsUtils = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- !(function (t) {
- var e = (function () {
- function t() {}
- return (
- Object.defineProperty(t, 'INITIALIZATION_ERROR', {
- get: function () {
- return 'INITIALIZATION_ERROR';
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(t, 'UNEXPECTED_ERROR', {
- get: function () {
- return 'UNEXPECTED_ERROR';
- },
- enumerable: !1,
- configurable: !0,
- }),
- t
- );
- })();
- t.POErrorCodes = e;
- })(t._POSignalsUtils || (t._POSignalsUtils = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- !(function (e) {
- var n = (function () {
- function n() {}
- return (
- Object.defineProperty(n, 'isMobile', {
- get: function () {
- var t,
- e = !1;
- return (
- (t = navigator.userAgent || navigator.vendor || window.opera),
- (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(
- t,
- ) ||
- /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(
- t.substr(0, 4),
- )) &&
- (e = !0),
- e
- );
- },
- enumerable: !1,
- configurable: !0,
- }),
- (n.newGuid = function () {
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (t) {
- var e = (16 * Math.random()) | 0;
- return ('x' === t ? e : (3 & e) | 8).toString(16);
- });
- }),
- (n.ieFix = function () {
- (-1 != navigator.userAgent.indexOf('MSIE')
- ? /MSIE (\d+\.\d+);/
- : /Trident.*rv[ :]*(\d+\.\d+)/
- ).test(navigator.userAgent) &&
- (document.body.setAttribute('style', '-ms-touch-action:none;'),
- (document.body.style.touchAction = 'none'),
- (document.body.style.msTouchAction = 'none'));
- }),
- (n.now = function () {
- var t = window.performance || {};
- return (
- (t.now =
- t.now ||
- t.webkitNow ||
- t.msNow ||
- t.oNow ||
- t.mozNow ||
- function () {
- return new Date().getTime();
- }),
- t.now()
- );
- }),
- (n.base64Uint8Array = function (t) {
- var e,
- n = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
- i = t.length,
- r = '';
- for (e = 0; e < i; e += 3)
- (r += n[t[e] >> 2]),
- (r += n[((3 & t[e]) << 4) | (t[e + 1] >> 4)]),
- (r += n[((15 & t[e + 1]) << 2) | (t[e + 2] >> 6)]),
- (r += n[63 & t[e + 2]]);
- return (
- i % 3 == 2
- ? (r = r.substring(0, r.length - 1) + '=')
- : i % 3 == 1 && (r = r.substring(0, r.length - 2) + '=='),
- r
- );
- }),
- (n.string2buf = function (t) {
- if ('function' == typeof TextEncoder && TextEncoder.prototype.encode)
- return new TextEncoder().encode(t);
- var e,
- n,
- i,
- r,
- a,
- o = t.length,
- s = 0;
- for (r = 0; r < o; r++)
- 55296 == (64512 & (n = t.charCodeAt(r))) &&
- r + 1 < o &&
- 56320 == (64512 & (i = t.charCodeAt(r + 1))) &&
- ((n = 65536 + ((n - 55296) << 10) + (i - 56320)), r++),
- (s += n < 128 ? 1 : n < 2048 ? 2 : n < 65536 ? 3 : 4);
- for (e = new Uint8Array(s), a = 0, r = 0; a < s; r++)
- 55296 == (64512 & (n = t.charCodeAt(r))) &&
- r + 1 < o &&
- 56320 == (64512 & (i = t.charCodeAt(r + 1))) &&
- ((n = 65536 + ((n - 55296) << 10) + (i - 56320)), r++),
- n < 128
- ? (e[a++] = n)
- : n < 2048
- ? ((e[a++] = 192 | (n >>> 6)), (e[a++] = 128 | (63 & n)))
- : n < 65536
- ? ((e[a++] = 224 | (n >>> 12)),
- (e[a++] = 128 | ((n >>> 6) & 63)),
- (e[a++] = 128 | (63 & n)))
- : ((e[a++] = 240 | (n >>> 18)),
- (e[a++] = 128 | ((n >>> 12) & 63)),
- (e[a++] = 128 | ((n >>> 6) & 63)),
- (e[a++] = 128 | (63 & n)));
- return e;
- }),
- (n.utf8Encode = function (t) {
- t = t.replace(/\r\n/g, '\n');
- for (var e = '', n = 0; n < t.length; n++) {
- var i = t.charCodeAt(n);
- i < 128
- ? (e += String.fromCharCode(i))
- : i > 127 && i < 2048
- ? ((e += String.fromCharCode((i >> 6) | 192)),
- (e += String.fromCharCode((63 & i) | 128)))
- : ((e += String.fromCharCode((i >> 12) | 224)),
- (e += String.fromCharCode(((i >> 6) & 63) | 128)),
- (e += String.fromCharCode((63 & i) | 128)));
- }
- return e;
- }),
- (n.hash = function (i) {
- var r = n.hashCache.get(i);
- return r || ((r = t.sha256(i + e.Constants.SALT)), n.hashCache.set(i, r)), r;
- }),
- (n.hashMini = function (t) {
- var e,
- n,
- i = '' + JSON.stringify(t),
- r = 2166136261;
- for (e = 0, n = i.length; e < n; e++) r = (Math.imul(31, r) + i.charCodeAt(e)) | 0;
- return ('0000000' + (r >>> 0).toString(16)).substr(-8);
- }),
- (n.hashCode = function (t) {
- var e = 0,
- n = t ? t.length : 0,
- i = 0;
- if (n > 0) for (; i < n; ) e = ((e << 5) - e + t.charCodeAt(i++)) | 0;
- return e;
- }),
- (n.mod = function (t, e) {
- return ((n.hashCode(t) % e) + e) % e;
- }),
- (n.isEmail = function (t) {
- try {
- return (
- t &&
- /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
- t.toLowerCase(),
- )
- );
- } catch (t) {
- return e.Logger.warn('isEmail function failed to parse string', t), !1;
- }
- }),
- (n.getEmailDomain = function (t) {
- return n.isEmail(t) ? t.substring(t.lastIndexOf('@') + 1) : '';
- }),
- (n.extendPrimitiveValues = function (t, e, i) {
- for (var r = n.allKeys(e), a = 0; a < r.length; )
- n.isObject(e[r[a]]) || (i && (!i || void 0 !== t[r[a]])) || (t[r[a]] = e[r[a]]),
- a++;
- return t;
- }),
- (n.flatten = function (t) {
- var e = {};
- return n.dive('', t, e), e;
- }),
- (n.isFunction = function (t) {
- return t && 'function' == typeof t;
- }),
- (n.isPassiveSupported = function () {
- var t = !1,
- e = function () {};
- try {
- var n = {
- get passive() {
- return (t = !0), !0;
- },
- };
- window.addEventListener('test', e, n), window.removeEventListener('test', e, !1);
- } catch (e) {
- t = !1;
- }
- return t;
- }),
- (n.getAttribute = function (t, e) {
- try {
- if (t && 'function' == typeof t.getAttribute) return t.getAttribute(e) || '';
- } catch (t) {}
- return '';
- }),
- (n.createInvisibleElement = function (t) {
- try {
- var n = document.createElement(t);
- return (
- (n.style.display = 'none'),
- (n.style.border = 'none'),
- (n.style.position = 'absolute'),
- (n.style.top = '-999px'),
- (n.style.left = '-999px'),
- (n.style.width = '0'),
- (n.style.height = '0'),
- (n.style.visibility = 'hidden'),
- n
- );
- } catch (t) {
- return e.Logger.warn('Failed to create element', t), null;
- }
- }),
- (n.values = function (t) {
- for (var e = n.allKeys(t), i = e.length, r = Array(i), a = 0; a < i; a++)
- r[a] = t[e[a]];
- return r;
- }),
- (n.getValuesOfMap = function (t) {
- if (this.isFunction(t.values)) return Array.from(t.values());
- var e = [];
- return (
- t.forEach(function (t) {
- return e.push(t);
- }),
- e
- );
- }),
- (n.typesCounter = function (t) {
- for (var e = {}, n = 0, i = t; n < i.length; n++) {
- var r = i[n];
- e[r.type] = (e[r.type] || 0) + 1;
- }
- return e;
- }),
- (n.modifiersKeys = function (t) {
- var e = [];
- return (
- t.getModifierState &&
- [
- 'Alt',
- 'AltGraph',
- 'CapsLock',
- 'Control',
- 'Fn',
- 'FnLock',
- 'Hyper',
- 'Meta',
- 'NumLock',
- 'OS',
- 'ScrollLock',
- 'Shift',
- 'Super',
- 'Symbol',
- 'SymbolLock',
- ].forEach(function (n) {
- t.getModifierState(n.toString()) && e.push(n);
- }),
- e
- );
- }),
- (n.getElementText = function (t) {
- var e, n;
- return t instanceof HTMLInputElement
- ? ['checkbox', 'radio'].indexOf(t.type) >= 0
- ? '' + t.checked
- : t.value
- : t instanceof HTMLSelectElement
- ? null ===
- (n = null === (e = t.selectedOptions) || void 0 === e ? void 0 : e[0]) ||
- void 0 === n
- ? void 0
- : n.innerText
- : t.innerText;
- }),
- (n.getSrcElement = function (t) {
- return t.srcElement || t.target;
- }),
- (n.getObjectType = function (t) {
- try {
- var e = /function (.{1,})\(/.exec(t.constructor.toString());
- return e && e.length > 1 ? e[1] : '';
- } catch (t) {
- return '';
- }
- }),
- (n.isSelectorMatches = function (t, e, n) {
- try {
- var i = Element.prototype,
- r =
- i.matches ||
- i.webkitMatchesSelector ||
- i.mozMatchesSelector ||
- i.msMatchesSelector,
- a = 0;
- do {
- if (r.call(t, e)) return t;
- t = t.parentElement || t.parentNode;
- } while (null !== t && 1 === t.nodeType && a++ < n);
- return null;
- } catch (t) {
- return null;
- }
- }),
- (n.anySelectorMatches = function (t, n, i) {
- try {
- for (var r = 0, a = n; r < a.length; r++) {
- var o = a[r];
- if (this.isSelectorMatches(t, o, i)) return !0;
- }
- } catch (t) {
- e.Logger.warn(t);
- }
- return !1;
- }),
- (n.isArray = function (t) {
- return Array.isArray
- ? Array.isArray(t)
- : '[object Array]' === Object.prototype.toString.call(t);
- }),
- (n.safeJsonParse = function (t) {
- var n = null;
- try {
- t && (n = JSON.parse(t));
- } catch (t) {
- e.Logger.warn('Failed to parse object ' + t), (n = null);
- }
- return n;
- }),
- (n.getElementSelectionStart = function (t) {
- var e;
- try {
- e = t.selectionStart;
- } catch (t) {
- e = '';
- }
- return e;
- }),
- (n.getElementSelectionEnd = function (t) {
- var e;
- try {
- e = t.selectionEnd;
- } catch (t) {
- e = '';
- }
- return e;
- }),
- (n.isClickableInput = function (t) {
- return (
- t &&
- [
- 'button',
- 'checkbox',
- 'color',
- 'radio',
- 'range',
- 'image',
- 'submit',
- 'file',
- 'reset',
- ].indexOf(t.type) >= 0
- );
- }),
- (n.isTextInput = function (t) {
- return (
- t &&
- [
- 'date',
- 'datetime-local',
- 'email',
- 'month',
- 'number',
- 'password',
- 'search',
- 'tel',
- 'text',
- 'time',
- 'url',
- 'week',
- 'datetime',
- ].indexOf(t.type) >= 0
- );
- }),
- (n.getDeviceOrientation = function () {
- var t = screen.orientation || screen.mozOrientation || {},
- e = screen.msOrientation || t.type,
- n = t.angle;
- return {
- orientation: null === e || void 0 === e ? void 0 : e.toString(),
- angle: null === n || void 0 === n ? void 0 : n.toString(),
- };
- }),
- (n.getDevToolsState = function () {
- var t,
- e,
- n = window.outerWidth - window.innerWidth > 160,
- i = window.outerHeight - window.innerHeight > 160,
- r = n ? 'vertical' : 'horizontal';
- return (i && n) ||
- !(
- (null ===
- (e = null === (t = window.Firebug) || void 0 === t ? void 0 : t.chrome) ||
- void 0 === e
- ? void 0
- : e.isInitialized) ||
- n ||
- i
- )
- ? { open: !1, orientation: void 0 }
- : { open: !0, orientation: r };
- }),
- (n.getCookie = function (t) {
- var e = document.cookie.match('(^|;) ?' + t + '=([^;]*)(;|$)');
- return e ? e[2] : null;
- }),
- (n.setCookie = function (t, e, n) {
- var i = new Date();
- i.setTime(i.getTime() + 1e3 * n),
- (document.cookie =
- t + '=' + e + ';path=/;secure;SameSite=None;expires=' + i.toUTCString());
- }),
- (n.deleteCookie = function (t) {
- n.setCookie(t, '', -1);
- }),
- (n.delay = function (t) {
- return new Promise(function (e) {
- return setTimeout(e, t);
- });
- }),
- (n.getHostnameFromRegex = function (t) {
- if (t) {
- var e = t.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
- return e && e[1];
- }
- return null;
- }),
- (n.inIframe = function () {
- try {
- return window.self !== window.top;
- } catch (t) {
- return !0;
- }
- }),
- (n.promiseTimeout = function (t, e) {
- var n = new Promise(function (e, n) {
- var i = setTimeout(function () {
- clearTimeout(i), n(new Error('Timed out in ' + t + 'ms.'));
- }, t);
- });
- return Promise.race([e, n]);
- }),
- (n.getProperty = function (t, e) {
- return e.split('.').reduce(function (t, e) {
- return t ? t[e] : null;
- }, t);
- }),
- (n.filterReduce = function (t, e) {
- return Object.keys(t)
- .filter(function (n) {
- return e(t[n]);
- })
- .reduce(function (e, n) {
- var i;
- return __assign(__assign({}, e), (((i = {})[n] = t[n]), i));
- }, {});
- }),
- (n.dive = function (t, e, i) {
- for (var r in e)
- if (e.hasOwnProperty(r)) {
- var a = r,
- o = e[r];
- t.length > 0 && (a = t + '.' + r), n.isObject(o) ? n.dive(a, o, i) : (i[a] = o);
- }
- }),
- (n.isObject = function (t) {
- var e = typeof t;
- return 'function' === e || ('object' === e && !!t);
- }),
- (n.allKeys = function (t) {
- if (!n.isObject(t)) return [];
- var e = [];
- for (var i in t) e.push(i);
- return e;
- }),
- (n.encryptionString = function (t, e) {
- for (var n = [], i = 0; i < t.length; i++) {
- var r = t.charCodeAt(i) ^ e.charCodeAt(i % e.length);
- n.push(String.fromCharCode(r));
- }
- return n.join('');
- }),
- (n.encryptionBytes = function (t, e) {
- for (var n = new Uint8Array(t.length), i = 0; i < t.length; i++)
- n[i] = t[i] ^ e.charCodeAt(i % e.length);
- return n;
- }),
- (n.parseJwt = function (t) {
- var e = t.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'),
- n = decodeURIComponent(
- window
- .atob(e)
- .split('')
- .map(function (t) {
- return '%' + ('00' + t.charCodeAt(0).toString(16)).slice(-2);
- })
- .join(''),
- );
- return JSON.parse(n);
- }),
- (n.calculateMeanTimeDeltasBetweenEvents = function (t) {
- var e = 0;
- if ((null === t || void 0 === t ? void 0 : t.length) > 1) {
- for (var n = t[0].epochTs, i = 1; i < t.length; i++)
- (e += t[i].epochTs - n), (n = t[i].epochTs);
- e /= t.length - 1;
- }
- return e;
- }),
- (n.sortEventsByTimestamp = function (t) {
- return t.sort(function (t, e) {
- return t.eventTs > e.eventTs
- ? 1
- : t.eventTs < e.eventTs
- ? -1
- : t.epochTs > e.epochTs
- ? 1
- : t.epochTs < e.epochTs
- ? -1
- : 'click' === t.type
- ? 1
- : -1;
- });
- }),
- (n.distanceBetweenPoints = function (t, e) {
- return Math.sqrt(Math.pow(t.getX() - e.getX(), 2) + Math.pow(t.getY() - e.getY(), 2));
- }),
- (n.calculateMeanDistanceBetweenPoints = function (t) {
- var e = 0;
- if ((null === t || void 0 === t ? void 0 : t.length) > 1) {
- for (var i = 1; i < t.length; i++) e += n.distanceBetweenPoints(t[i - 1], t[i]);
- e /= t.length - 1;
- }
- return e;
- }),
- (n.filterArrayByLength = function (t, e) {
- return t.length <= e ? t : t.slice(0, e).concat(t[t.length - 1]);
- }),
- (n.keepFirstEventsWithDistance = function (t) {
- var e = t.events,
- n = t.threshold,
- i = t.min,
- r = t.max;
- if (e.length <= i) return e;
- var a,
- o = e[0];
- for (a = 1; a < e.length && a < r; a++) {
- if (
- Math.max(Math.abs(e[a].getX() - o.getX()), Math.abs(e[a].getY() - o.getY())) >= n
- )
- break;
- }
- return e.slice(0, Math.max(a + 1, i));
- }),
- (n.ab2str = function (t) {
- return String.fromCharCode.apply(null, new Uint8Array(t));
- }),
- (n.str2ab = function (t) {
- for (
- var e = new ArrayBuffer(t.length), n = new Uint8Array(e), i = 0, r = t.length;
- i < r;
- i++
- )
- n[i] = t.charCodeAt(i);
- return e;
- }),
- (n.hashCache = new Map()),
- (n.keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='),
- n
- );
- })();
- e.Util = n;
- })(t._POSignalsUtils || (t._POSignalsUtils = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {}));
- (__awaiter =
- (this && this.__awaiter) ||
- function (t, e, n, i) {
- return new (n || (n = Promise))(function (r, a) {
- function o(t) {
- try {
- u(i.next(t));
- } catch (t) {
- a(t);
- }
- }
- function s(t) {
- try {
- u(i.throw(t));
- } catch (t) {
- a(t);
- }
- }
- function u(t) {
- var e;
- t.done
- ? r(t.value)
- : ((e = t.value),
- e instanceof n
- ? e
- : new n(function (t) {
- t(e);
- })).then(o, s);
- }
- u((i = i.apply(t, e || [])).next());
- });
- }),
- (__generator =
- (this && this.__generator) ||
- function (t, e) {
- var n,
- i,
- r,
- a,
- o = {
- label: 0,
- sent: function () {
- if (1 & r[0]) throw r[1];
- return r[1];
- },
- trys: [],
- ops: [],
- };
- return (
- (a = { next: s(0), throw: s(1), return: s(2) }),
- 'function' == typeof Symbol &&
- (a[Symbol.iterator] = function () {
- return this;
- }),
- a
- );
- function s(a) {
- return function (s) {
- return (function (a) {
- if (n) throw new TypeError('Generator is already executing.');
- for (; o; )
- try {
- if (
- ((n = 1),
- i &&
- (r =
- 2 & a[0]
- ? i.return
- : a[0]
- ? i.throw || ((r = i.return) && r.call(i), 0)
- : i.next) &&
- !(r = r.call(i, a[1])).done)
- )
- return r;
- switch (((i = 0), r && (a = [2 & a[0], r.value]), a[0])) {
- case 0:
- case 1:
- r = a;
- break;
- case 4:
- return o.label++, { value: a[1], done: !1 };
- case 5:
- o.label++, (i = a[1]), (a = [0]);
- continue;
- case 7:
- (a = o.ops.pop()), o.trys.pop();
- continue;
- default:
- if (
- !(r = (r = o.trys).length > 0 && r[r.length - 1]) &&
- (6 === a[0] || 2 === a[0])
- ) {
- o = 0;
- continue;
- }
- if (3 === a[0] && (!r || (a[1] > r[0] && a[1] < r[3]))) {
- o.label = a[1];
- break;
- }
- if (6 === a[0] && o.label < r[1]) {
- (o.label = r[1]), (r = a);
- break;
- }
- if (r && o.label < r[2]) {
- (o.label = r[2]), o.ops.push(a);
- break;
- }
- r[2] && o.ops.pop(), o.trys.pop();
- continue;
- }
- a = e.call(t, o);
- } catch (t) {
- (a = [6, t]), (i = 0);
- } finally {
- n = r = 0;
- }
- if (5 & a[0]) throw a[1];
- return { value: a[0] ? a[1] : void 0, done: !0 };
- })([a, s]);
- };
- }
- });
- !(function (t) {
- var e = t.openDB;
- !(function (t) {
- var n = (function () {
- function t() {}
- return (
- (t.initDB = function () {
- return __awaiter(this, void 0, void 0, function () {
- var n,
- i = this;
- return __generator(this, function (r) {
- if (
- !(
- window.indexedDB ||
- window.mozIndexedDB ||
- window.webkitIndexedDB ||
- window.msIndexedDB
- )
- )
- throw new Error('IndexedDB is not supported');
- return (
- (n = new t()),
- [
- 2,
- new Promise(function (r) {
- return __awaiter(i, void 0, void 0, function () {
- var i;
- return __generator(this, function (a) {
- switch (a.label) {
- case 0:
- return (
- (i = n),
- [
- 4,
- e(this._PingDBName, t._version, {
- upgrade: function (e, n, i, r, a) {
- e.createObjectStore(t._storeDefaultName);
- },
- }),
- ]
- );
- case 1:
- return (i.indexedDatabase = a.sent()), r(n), [2];
- }
- });
- });
- }),
- ]
- );
- });
- });
- }),
- (t.prototype.close = function () {
- this.indexedDatabase.close();
- }),
- (t.prototype.getValue = function (e) {
- return this.indexedDatabase.get(t._storeDefaultName, e);
- }),
- (t.prototype.setValue = function (e, n) {
- return this.indexedDatabase.put(t._storeDefaultName, n, e);
- }),
- (t._PingDBName = 'Ping'),
- (t._version = 1),
- (t._storeDefaultName = 'PING_ONE'),
- t
- );
- })();
- t.IndexedDBStorage = n;
- })(t._POSignalsStorage || (t._POSignalsStorage = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- !(function (e) {
- var n = (function () {
- function e(e, n) {
- this.crossStorageClient = new t.CrossStorageClient(e, n);
- }
- return (
- (e.prototype.get = function (e) {
- var n = t._POSignalsUtils.Util.hash(e);
- return this.crossStorageClient.get(n);
- }),
- (e.prototype.del = function (e) {
- return this.crossStorageClient.del(t._POSignalsUtils.Util.hash(e));
- }),
- (e.prototype.set = function (e, n, i) {
- return this.crossStorageClient.set(t._POSignalsUtils.Util.hash(e), n, i);
- }),
- (e.prototype.onConnect = function () {
- return this.crossStorageClient.onConnect();
- }),
- (e.prototype.close = function (t) {
- return this.crossStorageClient.close(t);
- }),
- (e.prototype.getSignedPayload = function (t, e) {
- return this.crossStorageClient.getSignedPayload(t, e);
- }),
- (e.prototype.getDeviceDetails = function (e) {
- var n = t._POSignalsUtils.Util.hash(e);
- return this.crossStorageClient.getDeviceDetails(n);
- }),
- (e.prototype.setDeviceDetails = function (e, n) {
- var i = t._POSignalsUtils.Util.hash(e);
- return this.crossStorageClient.setDeviceDetails(i, n);
- }),
- e
- );
- })();
- e.CrossStorage = n;
- var i = (function () {
- function t(t) {
- this.storage = t;
- }
- return (
- (t.prototype.get = function (t) {
- return Promise.resolve(this.storage.getItem(t));
- }),
- (t.prototype.del = function (t) {
- return this.storage.removeItem(t), Promise.resolve();
- }),
- (t.prototype.set = function (t, e) {
- return this.storage.setItem(t, e), Promise.resolve();
- }),
- (t.prototype.onConnect = function () {
- return Promise.resolve();
- }),
- (t.prototype.close = function (t) {
- return Promise.resolve();
- }),
- (t.prototype.getSignedPayload = function (t, e) {
- return Promise.resolve([]);
- }),
- (t.prototype.getDeviceDetails = function (t) {
- return Promise.resolve([]);
- }),
- (t.prototype.setDeviceDetails = function (t, e) {
- return Promise.resolve([]);
- }),
- t
- );
- })();
- e.CrossStorageFallback = i;
- })(t._POSignalsStorage || (t._POSignalsStorage = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(t, e, n) {
- (this.deviceId = t), (this.dbStorage = e), (this.cryptoHandler = n);
- }
- return (
- (e.prototype.getExportedPublicKey = function () {
- return __awaiter(this, void 0, void 0, function () {
- var t;
- return __generator(this, function (e) {
- switch (e.label) {
- case 0:
- return [4, this.getDeviceKeys()];
- case 1:
- return (t = e.sent()) ? [2, this.cryptoHandler.exportPublicKey(t)] : [2];
- }
- });
- });
- }),
- (e.prototype.setDeviceKeys = function (t) {
- return __awaiter(this, void 0, void 0, function () {
- var e;
- return __generator(this, function (n) {
- switch (n.label) {
- case 0:
- return [4, this.dbStorage.setValue(this.deviceId, t)];
- case 1:
- return (e = n.sent()), (this.cachedDeviceKey = t), [2, e];
- }
- });
- });
- }),
- (e.prototype.associateDeviceKeys = function () {
- return __awaiter(this, void 0, void 0, function () {
- var e;
- return __generator(this, function (n) {
- switch (n.label) {
- case 0:
- return [4, this.cryptoHandler.generateKeys()];
- case 1:
- return (
- (e = n.sent()),
- t._POSignalsUtils.Logger.info('Associating new device domain keys'),
- [4, this.setDeviceKeys(e)]
- );
- case 2:
- return n.sent(), [2, e];
- }
- });
- });
- }),
- (e.prototype.signDeviceWithKeys = function (t) {
- return __awaiter(this, void 0, void 0, function () {
- var n, i, r;
- return __generator(this, function (a) {
- switch (a.label) {
- case 0:
- return (
- (i = (n = this.cryptoHandler).signChallenge),
- (r = [t]),
- [4, this.getDeviceKeys()]
- );
- case 1:
- return [2, i.apply(n, r.concat([a.sent().privateKey, e._default_salt]))];
- }
- });
- });
- }),
- (e.prototype.getDeviceKeys = function () {
- return __awaiter(this, void 0, void 0, function () {
- var t;
- return __generator(this, function (e) {
- switch (e.label) {
- case 0:
- return this.cachedDeviceKey
- ? [3, 2]
- : ((t = this), [4, this.dbStorage.getValue(this.deviceId)]);
- case 1:
- (t.cachedDeviceKey = e.sent()), (e.label = 2);
- case 2:
- return [2, this.cachedDeviceKey];
- }
- });
- });
- }),
- (e._default_salt = 32),
- e
- );
- })();
- t.DeviceKeys = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- !(function (e) {
- var n = (function () {
- function n() {
- (this._disabledStorage = []),
- (this.assertionValues = [
- 'BROWSER_ENGINE_VERSION',
- 'NAVIGATOR_LANGUAGE',
- 'OS_NAME',
- 'OS_VERSION',
- 'NAVIGATOR_USER_AGENT',
- 'FINGER_PRINT',
- 'RESOLUTION',
- 'PUSH_NOTIFICATIONS_SUPPORTED',
- 'COOKIES_ENABLED',
- 'IS_INCOGNITO',
- 'IS_PRIVATE_MODE',
- ]);
- try {
- window.sessionStorage.setItem('_st_storage_enabled_check', 'test'),
- window.sessionStorage.removeItem('_st_storage_enabled_check'),
- (this.signalsSessionStorage = window.sessionStorage);
- } catch (n) {
- t._POSignalsUtils.Logger.warn('session storage disabled'),
- this._disabledStorage.push('sessionStorage'),
- (this.signalsSessionStorage = new e.StorageFallback());
- }
- try {
- window.localStorage.setItem('_st_storage_enabled_check', 'test'),
- window.localStorage.removeItem('_st_storage_enabled_check'),
- (this.signalsLocalStorage = new e.StorageWrapper(window.localStorage));
- } catch (n) {
- t._POSignalsUtils.Logger.warn('local storage disabled'),
- this._disabledStorage.push('localStorage'),
- (this.signalsLocalStorage = new e.StorageWrapper(new e.StorageFallback())),
- (this.crossStorage = new e.CrossStorageFallback(this.signalsLocalStorage));
- }
- }
- return (
- (n.prototype.setStorageConfig = function (t) {
- (this.disableHub = t.disableHub),
- (this.hubUrl = t.hubUrl),
- (this.universalTrustEnabled = this.isUniversalTrustEnabled(
- t.universalDeviceIdentification,
- )),
- (this.devEnv = t.devEnv);
- }),
- Object.defineProperty(n, 'instance', {
- get: function () {
- return n._instance || (n._instance = new n()), n._instance;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'tabUUID', {
- get: function () {
- var e = this.signalsSessionStorage.getItem(
- t._POSignalsUtils.Constants.TAB_UUID_KEY,
- );
- return (
- e ||
- ((e = t._POSignalsUtils.Util.newGuid()),
- this.signalsSessionStorage.setItem(
- t._POSignalsUtils.Constants.TAB_UUID_KEY,
- e,
- )),
- e
- );
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'ops', {
- get: function () {
- var e = Number(
- this.signalsSessionStorage.getItem(t._POSignalsUtils.Constants.OPS_KEY),
- );
- return isNaN(e) ? null : e;
- },
- set: function (e) {
- e
- ? this.signalsSessionStorage.setItem(
- t._POSignalsUtils.Constants.OPS_KEY,
- e.toString(),
- )
- : this.signalsSessionStorage.removeItem(t._POSignalsUtils.Constants.OPS_KEY);
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'disabledStorage', {
- get: function () {
- return this._disabledStorage;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'sessionStorage', {
- get: function () {
- return this.signalsSessionStorage;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'localStorage', {
- get: function () {
- return this.signalsLocalStorage;
- },
- enumerable: !1,
- configurable: !0,
- }),
- (n.prototype.initDeviceIdentity = function () {
- return __awaiter(this, void 0, void 0, function () {
- var n, i, r;
- return __generator(this, function (a) {
- switch (a.label) {
- case 0:
- return (
- (i = this.signalsLocalStorage.getItem(
- t._POSignalsUtils.Constants.DEVICE_ID_KEY,
- )) && (this.cachedDeviceId = i),
- this.universalTrustEnabled
- ? ((this.deviceTrust = { attestation: {}, dtts: new Date().getTime() }),
- this.disableHub && (this.deviceTrust.hubDisabled = !0),
- (r = this),
- [4, e.IndexedDBStorage.initDB()])
- : [3, 3]
- );
- case 1:
- return (r.indexedDBStorage = a.sent()), [4, this.loadLocalDeviceTrust()];
- case 2:
- (n = a.sent()), (a.label = 3);
- case 3:
- return this.disableHub || (i && !this.shouldFallbackToP1Key(n))
- ? [3, 5]
- : [4, this.fallbackToCrossStorage(this.hubUrl)];
- case 4:
- return a.sent(), [3, 6];
- case 5:
- (this.crossStorage = new e.CrossStorageFallback(this.signalsLocalStorage)),
- (a.label = 6);
- case 6:
- return this.getDeviceId()
- ? [3, 8]
- : [4, this.associateDeviceDetails(this.disableHub)];
- case 7:
- a.sent(), (a.label = 8);
- case 8:
- return !this.universalTrustEnabled || (this.getDeviceId() && n)
- ? [3, 10]
- : [4, this.createDomainKeys(this.disableHub)];
- case 9:
- a.sent(), (a.label = 10);
- case 10:
- return [2, this.getDeviceId()];
- }
- });
- });
- }),
- (n.prototype.shouldFallbackToP1Key = function (t) {
- return (
- this.universalTrustEnabled &&
- !this.disableHub &&
- (!t || this.isRefreshRequired(this.deviceKeyRsyncIntervals))
- );
- }),
- (n.prototype.isRefreshRequired = function (e) {
- if ((void 0 === e && (e = 3), !this.deviceTrust.dtts)) return !0;
- var n = this.signalsLocalStorage.getItem(
- t._POSignalsUtils.Constants.LAST_DEVICE_KEY_RESYNC,
- );
- if (!n || isNaN(parseInt(n))) return !0;
- var i = this.deviceTrust.dtts - n > 864e5 * e;
- return i && t._POSignalsUtils.Logger.debug('Refresh required'), i;
- }),
- (n.prototype.loadLocalDeviceTrust = function () {
- return __awaiter(this, void 0, void 0, function () {
- var n, i;
- return __generator(this, function (r) {
- switch (r.label) {
- case 0:
- return (
- r.trys.push([0, 4, , 5]),
- void 0,
- this.cachedDeviceId
- ? this.cachedDeviceId
- ? ((this.domainDeviceKeys = new t.DeviceKeys(
- this.getDeviceId(),
- this.indexedDBStorage,
- new t._POSignalsUtils.CryptoOperator(),
- )),
- [4, this.domainDeviceKeys.getDeviceKeys()])
- : [3, 3]
- : (t._POSignalsUtils.Logger.debug(
- 'No device id found on customer domain',
- ),
- [2, !1])
- );
- case 1:
- return r.sent()
- ? ((n = this.deviceTrust.attestation),
- [4, this.domainDeviceKeys.getExportedPublicKey()])
- : (t._POSignalsUtils.Logger.debug(
- 'No device keys found on customer domain',
- ),
- [2, !1]);
- case 2:
- return (
- (n.deviceKey = r.sent()),
- (this.crossStorage = new e.CrossStorageFallback(this.signalsLocalStorage)),
- [2, !0]
- );
- case 3:
- return [3, 5];
- case 4:
- return (
- (i = r.sent()),
- t._POSignalsUtils.Logger.error('Domain PKI initialization failed', i),
- [2, !1]
- );
- case 5:
- return [2];
- }
- });
- });
- }),
- (n.prototype.createDomainKeys = function (e) {
- return __awaiter(this, void 0, void 0, function () {
- var n, i;
- return __generator(this, function (r) {
- switch (r.label) {
- case 0:
- return (
- r.trys.push([0, 3, , 4]),
- !e && this._disabledStorage.lastIndexOf('hub') > -1
- ? (t._POSignalsUtils.Logger.debug(
- 'Hub unavailable - skipping domain trust creation',
- ),
- [2])
- : ((this.domainDeviceKeys = new t.DeviceKeys(
- this.getDeviceId(),
- this.indexedDBStorage,
- new t._POSignalsUtils.CryptoOperator(),
- )),
- [4, this.domainDeviceKeys.associateDeviceKeys()])
- );
- case 1:
- return (
- r.sent(),
- (n = this.deviceTrust.attestation),
- [4, this.domainDeviceKeys.getExportedPublicKey()]
- );
- case 2:
- return (n.deviceKey = r.sent()), [3, 4];
- case 3:
- return (
- (i = r.sent()),
- t._POSignalsUtils.Logger.error('Domain PKI initialization failed', i),
- [3, 4]
- );
- case 4:
- return [2];
- }
- });
- });
- }),
- (n.prototype.getDeviceId = function () {
- return this.cachedDeviceId;
- }),
- (n.prototype.associateDeviceDetails = function (e) {
- var n, i;
- return __awaiter(this, void 0, void 0, function () {
- var r;
- return __generator(this, function (a) {
- switch (a.label) {
- case 0:
- return (
- t._POSignalsUtils.Logger.debug('Associating fresh device details'),
- (this.cachedDeviceId = 'Id-' + t._POSignalsUtils.Util.newGuid()),
- this.signalsLocalStorage.setItem(
- t._POSignalsUtils.Constants.DEVICE_ID_KEY,
- this.cachedDeviceId,
- ),
- e
- ? [3, 4]
- : this.universalTrustEnabled
- ? ((r = this.deviceTrust.attestation),
- [
- 4,
- this.crossStorage.setDeviceDetails(
- t._POSignalsUtils.Constants.DEVICE_ID_KEY,
- this.cachedDeviceId,
- ),
- ])
- : [3, 2]
- );
- case 1:
- return (r.fallbackDeviceKey = a.sent()[0]), [3, 4];
- case 2:
- return [
- 4,
- this.crossStorage.set(
- t._POSignalsUtils.Constants.DEVICE_ID_KEY,
- this.cachedDeviceId,
- ),
- ];
- case 3:
- a.sent(), (a.label = 4);
- case 4:
- return (
- t._POSignalsUtils.Logger.debug(
- 'PingOne Signals deviceId: ' + this.cachedDeviceId,
- ),
- [
- 2,
- [
- this.cachedDeviceId,
- null ===
- (i =
- null === (n = this.deviceTrust) || void 0 === n
- ? void 0
- : n.attestation) || void 0 === i
- ? void 0
- : i.fallbackDeviceKey,
- ],
- ]
- );
- }
- });
- });
- }),
- (n.prototype.addAssertion = function (e) {
- return __awaiter(this, void 0, void 0, function () {
- var n, i, r, a, o, s, u;
- return __generator(this, function (c) {
- switch (c.label) {
- case 0:
- if (
- (c.trys.push([0, 5, 6, 7]),
- !this.universalTrustEnabled ||
- (!this.deviceTrust.attestation.deviceKey &&
- !this.deviceTrust.attestation.fallbackDeviceKey))
- )
- return [2];
- for (
- n = (n = e.deviceId).concat('-' + e.deviceType),
- i = 0,
- r = this.assertionValues;
- i < r.length;
- i++
- )
- (a = r[i]), void 0 != e[a] && null != e[a] && (n = n.concat('-' + e[a]));
- return (
- (n = n.concat('-' + this.deviceTrust.dtts)),
- t._POSignalsUtils.Logger.debug('Device identityContract ' + n),
- this.deviceTrust.attestation.fallbackDeviceKey && this.crossStorage
- ? ((o = this.deviceTrust.attestation),
- [4, this.crossStorage.getSignedPayload(n, this.getDeviceId())])
- : [3, 2]
- );
- case 1:
- return (
- (o.deviceToken = c.sent()[1]),
- this.signalsLocalStorage.setItem(
- t._POSignalsUtils.Constants.LAST_DEVICE_KEY_RESYNC,
- new Date().getTime(),
- ),
- [3, 4]
- );
- case 2:
- return (
- (s = this.deviceTrust.attestation),
- [4, this.domainDeviceKeys.signDeviceWithKeys(n)]
- );
- case 3:
- (s.deviceToken = c.sent()), (c.label = 4);
- case 4:
- return [3, 7];
- case 5:
- return (
- (u = c.sent()),
- t._POSignalsUtils.Logger.warn('Device attestation failed:', u),
- [3, 7]
- );
- case 6:
- return (
- this.universalTrustEnabled &&
- t._POSignalsUtils.Logger.info(
- 'Device attestation ' + JSON.stringify(this.deviceTrust, null, 2),
- ),
- [7]
- );
- case 7:
- return [2];
- }
- });
- });
- }),
- (n.prototype.closeTrustStore = function () {
- try {
- this.crossStorage.close(this.devEnv),
- this.indexedDBStorage && this.indexedDBStorage.close();
- } catch (e) {
- t._POSignalsUtils.Logger.info('Unable to close trust store:', e);
- }
- }),
- (n.prototype.fallbackToCrossStorage = function (n) {
- return __awaiter(this, void 0, void 0, function () {
- var i;
- return __generator(this, function (r) {
- switch (r.label) {
- case 0:
- t._POSignalsUtils.Logger.debug(
- 'PingOne Signals cross storage is required, initializing',
- ),
- (r.label = 1);
- case 1:
- return r.trys.push([1, 3, , 4]), [4, this.initCrossStorage(n)];
- case 2:
- return (
- r.sent(),
- t._POSignalsUtils.Logger.info('PingOne Signals cross storage initiated'),
- [3, 4]
- );
- case 3:
- return (
- (i = r.sent()),
- t._POSignalsUtils.Logger.warn(
- 'PingOne Signals Session crossStorage failed to connect ' + i,
- ),
- this._disabledStorage.push('hub'),
- (this.crossStorage = new e.CrossStorageFallback(this.signalsLocalStorage)),
- [3, 4]
- );
- case 4:
- return [2];
- }
- });
- });
- }),
- (n.prototype.initCrossStorage = function (n) {
- return __awaiter(this, void 0, void 0, function () {
- var i, r, a, o, s;
- return __generator(this, function (u) {
- switch (u.label) {
- case 0:
- return (
- (i = this.universalTrustEnabled ? '1.0.7' : '1.0.1'),
- (r = 'https://apps.pingone.com/signals/web-sdk/hub-' + i + '/hub.html'),
- (a = ((null === n || void 0 === n ? void 0 : n.trim()) || r).replace(
- /\/$/,
- '',
- )).endsWith('html') || (a += '/hub.html'),
- (this.crossStorage = new e.CrossStorage(a, { timeout: 2e3 })),
- [4, this.crossStorage.onConnect()]
- );
- case 1:
- return (
- u.sent(),
- this.universalTrustEnabled
- ? [
- 4,
- this.crossStorage.getDeviceDetails(
- t._POSignalsUtils.Constants.DEVICE_ID_KEY,
- ),
- ]
- : [3, 3]
- );
- case 2:
- return (o = u.sent()), (this.cachedDeviceId = o[0]), [3, 5];
- case 3:
- return (
- (s = this),
- [4, this.crossStorage.get(t._POSignalsUtils.Constants.DEVICE_ID_KEY)]
- );
- case 4:
- (s.cachedDeviceId = u.sent()), (u.label = 5);
- case 5:
- return (
- this.cachedDeviceId
- ? this.signalsLocalStorage.setItem(
- t._POSignalsUtils.Constants.DEVICE_ID_KEY,
- this.cachedDeviceId,
- )
- : t._POSignalsUtils.Logger.info('no device id from hub'),
- this.universalTrustEnabled &&
- (o && o[1]
- ? ((this.deviceTrust.attestation.fallbackDeviceKey = o[1]),
- t._POSignalsUtils.Logger.info(
- 'Using fallback device keys from hub ' +
- this.deviceTrust.attestation.fallbackDeviceKey,
- ))
- : t._POSignalsUtils.Logger.info('failed to use any device keys')),
- [2]
- );
- }
- });
- });
- }),
- (n.prototype.isUniversalTrustEnabled = function (t) {
- return (
- void 0 !== t &&
- null !== t &&
- ('boolean' == typeof t ? t : 'string' == typeof t && 'true' === t.toLowerCase())
- );
- }),
- n
- );
- })();
- e.SessionStorage = n;
- })(t._POSignalsStorage || (t._POSignalsStorage = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- !(function (e) {
- var n = (function () {
- function e(t) {
- this.storage = t;
- }
- return (
- (e.prototype.getItem = function (e) {
- var n = t._POSignalsUtils.Util.hash(e),
- i = this.storage.getItem(n);
- return (
- i ||
- ((i = this.storage.getItem(e)) &&
- (this.storage.setItem(n, i), this.storage.removeItem(e))),
- i
- );
- }),
- (e.prototype.removeItem = function (e) {
- return this.storage.removeItem(t._POSignalsUtils.Util.hash(e));
- }),
- (e.prototype.setItem = function (e, n) {
- return this.storage.setItem(t._POSignalsUtils.Util.hash(e), n);
- }),
- e
- );
- })();
- e.StorageWrapper = n;
- var i = (function () {
- function t() {
- this.internalStorageMap = new Map();
- }
- return (
- (t.prototype.getItem = function (t) {
- return this.internalStorageMap.get(t);
- }),
- (t.prototype.removeItem = function (t) {
- this.internalStorageMap.delete(t);
- }),
- (t.prototype.setItem = function (t, e) {
- this.internalStorageMap.set(t, e);
- }),
- t
- );
- })();
- e.StorageFallback = i;
- })(t._POSignalsStorage || (t._POSignalsStorage = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {}));
- (__assign =
- (this && this.__assign) ||
- function () {
- return (__assign =
- Object.assign ||
- function (t) {
- for (var e, n = 1, i = arguments.length; n < i; n++)
- for (var r in (e = arguments[n]))
- Object.prototype.hasOwnProperty.call(e, r) && (t[r] = e[r]);
- return t;
- }).apply(this, arguments);
- }),
- (__awaiter =
- (this && this.__awaiter) ||
- function (t, e, n, i) {
- return new (n || (n = Promise))(function (r, a) {
- function o(t) {
- try {
- u(i.next(t));
- } catch (t) {
- a(t);
- }
- }
- function s(t) {
- try {
- u(i.throw(t));
- } catch (t) {
- a(t);
- }
- }
- function u(t) {
- var e;
- t.done
- ? r(t.value)
- : ((e = t.value),
- e instanceof n
- ? e
- : new n(function (t) {
- t(e);
- })).then(o, s);
- }
- u((i = i.apply(t, e || [])).next());
- });
- }),
- (__generator =
- (this && this.__generator) ||
- function (t, e) {
- var n,
- i,
- r,
- a,
- o = {
- label: 0,
- sent: function () {
- if (1 & r[0]) throw r[1];
- return r[1];
- },
- trys: [],
- ops: [],
- };
- return (
- (a = { next: s(0), throw: s(1), return: s(2) }),
- 'function' == typeof Symbol &&
- (a[Symbol.iterator] = function () {
- return this;
- }),
- a
- );
- function s(a) {
- return function (s) {
- return (function (a) {
- if (n) throw new TypeError('Generator is already executing.');
- for (; o; )
- try {
- if (
- ((n = 1),
- i &&
- (r =
- 2 & a[0]
- ? i.return
- : a[0]
- ? i.throw || ((r = i.return) && r.call(i), 0)
- : i.next) &&
- !(r = r.call(i, a[1])).done)
- )
- return r;
- switch (((i = 0), r && (a = [2 & a[0], r.value]), a[0])) {
- case 0:
- case 1:
- r = a;
- break;
- case 4:
- return o.label++, { value: a[1], done: !1 };
- case 5:
- o.label++, (i = a[1]), (a = [0]);
- continue;
- case 7:
- (a = o.ops.pop()), o.trys.pop();
- continue;
- default:
- if (
- !(r = (r = o.trys).length > 0 && r[r.length - 1]) &&
- (6 === a[0] || 2 === a[0])
- ) {
- o = 0;
- continue;
- }
- if (3 === a[0] && (!r || (a[1] > r[0] && a[1] < r[3]))) {
- o.label = a[1];
- break;
- }
- if (6 === a[0] && o.label < r[1]) {
- (o.label = r[1]), (r = a);
- break;
- }
- if (r && o.label < r[2]) {
- (o.label = r[2]), o.ops.push(a);
- break;
- }
- r[2] && o.ops.pop(), o.trys.pop();
- continue;
- }
- a = e.call(t, o);
- } catch (t) {
- (a = [6, t]), (i = 0);
- } finally {
- n = r = 0;
- }
- if (5 & a[0]) throw a[1];
- return { value: a[0] ? a[1] : void 0, done: !0 };
- })([a, s]);
- };
- }
- });
- !(function (t) {
- !(function (t) {
- var e = (function () {
- function t() {}
- return (
- (t.prototype.isCanvasSupported = function () {
- var t = document.createElement('canvas');
- return !(!t.getContext || !t.getContext('2d'));
- }),
- (t.prototype.getWebglCanvas = function (t) {
- var e = document.createElement('canvas'),
- n = null;
- try {
- n =
- 'webgl' === t
- ? e.getContext('webgl') || e.getContext('experimental-webgl')
- : e.getContext('webgl2');
- } catch (t) {}
- return n || (n = null), n;
- }),
- (t.prototype.isWebGlSupported = function (t) {
- if (!this.isCanvasSupported()) return !1;
- var e = this.getWebglCanvas(t);
- return (
- ('webgl' === t ? !!window.WebGLRenderingContext : !!window.WebGL2RenderingContext) &&
- !!e
- );
- }),
- (t.prototype.isWebGl = function (t) {
- return !!this.isWebGlSupported(t) && !!this.getWebglCanvas(t);
- }),
- (t.prototype.getWebglVendorAndRenderer = function (t) {
- try {
- if (this.isWebGlSupported(t)) {
- var e = this.getWebglCanvas(t),
- n = e.getExtension('WEBGL_debug_renderer_info');
- return (
- e.getParameter(n.UNMASKED_VENDOR_WEBGL) +
- '~' +
- e.getParameter(n.UNMASKED_RENDERER_WEBGL)
- );
- }
- } catch (t) {}
- return null;
- }),
- (t.prototype.getHasLiedLanguages = function () {
- if (void 0 !== navigator.languages)
- try {
- if (navigator.languages[0].substr(0, 2) !== navigator.language.substr(0, 2))
- return !0;
- } catch (t) {
- return !0;
- }
- return !1;
- }),
- (t.prototype.getHasLiedResolution = function () {
- return (
- window.screen.width < window.screen.availWidth ||
- window.screen.height < window.screen.availHeight
- );
- }),
- (t.prototype.getHasLiedOs = function () {
- var t,
- e = navigator.userAgent.toLowerCase(),
- n = navigator.oscpu,
- i = navigator.platform.toLowerCase();
- if (
- ((t =
- e.indexOf('windows phone') >= 0
- ? 'Windows Phone'
- : e.indexOf('win') >= 0
- ? 'Windows'
- : e.indexOf('android') >= 0
- ? 'Android'
- : e.indexOf('linux') >= 0 || e.indexOf('cros') >= 0
- ? 'Linux'
- : e.indexOf('iphone') >= 0 || e.indexOf('ipad') >= 0
- ? 'iOS'
- : e.indexOf('mac') >= 0
- ? 'Mac'
- : 'Other'),
- ('ontouchstart' in window ||
- navigator.maxTouchPoints > 0 ||
- navigator.msMaxTouchPoints > 0) &&
- 'Windows Phone' !== t &&
- 'Android' !== t &&
- 'iOS' !== t &&
- 'Other' !== t)
- )
- return !0;
- if (void 0 !== n) {
- if (
- (n = n.toLowerCase()).indexOf('win') >= 0 &&
- 'Windows' !== t &&
- 'Windows Phone' !== t
- )
- return !0;
- if (n.indexOf('linux') >= 0 && 'Linux' !== t && 'Android' !== t) return !0;
- if (n.indexOf('mac') >= 0 && 'Mac' !== t && 'iOS' !== t) return !0;
- if (
- (-1 === n.indexOf('win') && -1 === n.indexOf('linux') && -1 === n.indexOf('mac')) !=
- ('Other' === t)
- )
- return !0;
- }
- return (
- (i.indexOf('win') >= 0 && 'Windows' !== t && 'Windows Phone' !== t) ||
- ((i.indexOf('linux') >= 0 || i.indexOf('android') >= 0 || i.indexOf('pike') >= 0) &&
- 'Linux' !== t &&
- 'Android' !== t) ||
- ((i.indexOf('mac') >= 0 ||
- i.indexOf('ipad') >= 0 ||
- i.indexOf('ipod') >= 0 ||
- i.indexOf('iphone') >= 0) &&
- 'Mac' !== t &&
- 'iOS' !== t) ||
- (i.indexOf('win') < 0 &&
- i.indexOf('linux') < 0 &&
- i.indexOf('mac') < 0 &&
- i.indexOf('iphone') < 0 &&
- i.indexOf('ipad') < 0) !==
- ('Other' === t) ||
- (void 0 === navigator.plugins && 'Windows' !== t && 'Windows Phone' !== t)
- );
- }),
- (t.prototype.getHasLiedBrowser = function () {
- var t,
- e = navigator.userAgent.toLowerCase(),
- n = navigator.productSub;
- if (
- ('Chrome' ===
- (t =
- e.indexOf('firefox') >= 0
- ? 'Firefox'
- : e.indexOf('opera') >= 0 || e.indexOf('opr') >= 0
- ? 'Opera'
- : e.indexOf('chrome') >= 0
- ? 'Chrome'
- : e.indexOf('safari') >= 0
- ? 'Safari'
- : e.indexOf('trident') >= 0
- ? 'Internet Explorer'
- : 'Other') ||
- 'Safari' === t ||
- 'Opera' === t) &&
- '20030107' !== n
- )
- return !0;
- var i,
- r = eval.toString().length;
- if (37 === r && 'Safari' !== t && 'Firefox' !== t && 'Other' !== t) return !0;
- if (39 === r && 'Internet Explorer' !== t && 'Other' !== t) return !0;
- if (33 === r && 'Chrome' !== t && 'Opera' !== t && 'Other' !== t) return !0;
- try {
- throw 'a';
- } catch (t) {
- try {
- t.toSource(), (i = !0);
- } catch (t) {
- i = !1;
- }
- }
- return i && 'Firefox' !== t && 'Other' !== t;
- }),
- t
- );
- })();
- t.FingerprintLegacyMetadata = e;
- })(t._POSignalsMetadata || (t._POSignalsMetadata = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- !(function (e) {
- var n = (function () {
- function n(e, n) {
- (this.sessionData = e),
- (this.metadataParams = n),
- (this.deviceId = null),
- (this.hasMicrophone = null),
- (this.hasSpeakers = null),
- (this.hasWebcam = null),
- (this.isBatterySupported = null),
- (this.batteryLevel = null),
- (this.batteryCharging = null),
- (this.batteryChargingTime = null),
- (this.batteryDischargingTime = null),
- (this.headlessTests = new Map()),
- (this.lieTests = {}),
- (this.gpsSupported = null),
- (this.fingerPrintComponentKeys = new Set([
- 'navigatorPlatform',
- 'colorDepth',
- 'deviceMemory',
- 'pixelRatio',
- 'hardwareConcurrency',
- 'screenResolution',
- 'availableScreenResolution',
- 'timezoneOffset',
- 'timezone',
- 'sessionStorage',
- 'localStorage',
- 'indexedDB',
- 'addBehavior',
- 'openDatabase',
- 'cpuClass',
- 'platform',
- 'canvas',
- 'adBlock',
- 'touchSupport',
- 'fonts',
- 'audio',
- 'osCpu',
- 'productSub',
- 'emptyEvalLength',
- 'errorFF',
- 'chrome',
- 'cookiesEnabled',
- ])),
- (this.webGlStatus = -1),
- (this.numberOfVideoDevices = 0),
- (this.numberOfAudioDevices = 0),
- (this.videoInputDevices = []),
- (this.audioInputDevices = []),
- (this.audioOutputDevices = []),
- (this.webRtcIps = new Map()),
- (this.lastCalculatedMetadata = null),
- (this.metadataQueue = new t.PromiseQueue(1));
- }
- return (
- Object.defineProperty(n.prototype, 'OPS', {
- get: function () {
- if (!this.metadataParams.browserInfo.isIphoneOrIPad) return 0;
- var t = this.sessionData.ops;
- return t || ((t = this.getOps()), (this.sessionData.ops = t)), t;
- },
- enumerable: !1,
- configurable: !0,
- }),
- (n.prototype.getDeviceAttributes = function () {
- return __awaiter(this, void 0, void 0, function () {
- var e = this;
- return __generator(this, function (n) {
- return [
- 2,
- this.metadataQueue.add(function () {
- return __awaiter(e, void 0, void 0, function () {
- var e;
- return __generator(this, function (n) {
- switch (n.label) {
- case 0:
- return this.lastCalculatedMetadata
- ? [3, 3]
- : ((e = this), [4, this.calculateDeviceMetadata()]);
- case 1:
- return (
- (e.lastCalculatedMetadata = n.sent()),
- t._POSignalsUtils.Logger.info('calculated device attributes.'),
- t._POSignalsUtils.Logger.info(
- 'PingOne Signals deviceId: ' + this.deviceId,
- ),
- [4, this.sessionData.addAssertion(this.lastCalculatedMetadata)]
- );
- case 2:
- n.sent(), this.sessionData.closeTrustStore(), (n.label = 3);
- case 3:
- return [2, this.lastCalculatedMetadata];
- }
- });
- });
- }),
- ];
- });
- });
- }),
- (n.prototype.getObfsInfo = function () {
- return { identifier: 'x1', key: 'Xq7tSbjB517mhZwt' };
- }),
- (n.prototype.calculateDeviceMetadata = function () {
- return __awaiter(this, void 0, void 0, function () {
- var n, i, r, a, o;
- return __generator(this, function (s) {
- switch (s.label) {
- case 0:
- return (
- (this.gpsSupported = null != navigator.geolocation),
- (n = this.metadataParams.metadataBlackList),
- (i = [
- this.sessionData.initDeviceIdentity().catch(function (e) {
- t._POSignalsUtils.Logger.warn('failed to get deviceId info', e);
- }),
- this.getFingerPrint(n).catch(function (e) {
- t._POSignalsUtils.Logger.warn(
- 'failed to get fingerprint info',
- e.message,
- );
- }),
- this.getPrivateMode().catch(function (e) {
- return t._POSignalsUtils.Logger.warn('failed to get incognito info', e);
- }),
- e.Incognito.isPrivateMode().catch(function (e) {
- return t._POSignalsUtils.Logger.warn(
- 'failed to get private mode info',
- e,
- );
- }),
- this.getPermissionsMetadata().catch(function (e) {
- return t._POSignalsUtils.Logger.warn(
- 'failed to get permissions info',
- e,
- );
- }),
- new e.DetectHeadless(n).getHeadlessResults().catch(function (e) {
- return t._POSignalsUtils.Logger.warn(
- 'failed to get headless results',
- e,
- );
- }),
- new e.DetectLies(n).getAllLies().catch(function (e) {
- return t._POSignalsUtils.Logger.warn('failed to get lies results', e);
- }),
- this.audioIntVideoInit().catch(function (e) {
- return t._POSignalsUtils.Logger.warn(
- 'failed to get audio-video info',
- e,
- );
- }),
- this.batteryInit().catch(function (e) {
- return t._POSignalsUtils.Logger.warn('failed to get battery info', e);
- }),
- ]),
- [4, Promise.all(i)]
- );
- case 1:
- return (
- (o = s.sent()),
- (this.deviceId = o[0]),
- (this.fingerPrint = o[1]),
- (this.isPrivateMode = o[2]),
- (this.isPrivateModeV2 = o[3]),
- (this.permissions = o[4]),
- (this.headlessTests = o[5]),
- (this.lieTests = o[6]),
- (r = {
- ops: this.OPS,
- devicePixelRatio: window.devicePixelRatio,
- screenWidth: window.screen.width,
- screenHeight: window.screen.height,
- }),
- t._POSignalsUtils.Util.extendPrimitiveValues(r, screen, !1),
- (a = [
- {
- deviceId: this.deviceId,
- deviceType: this.metadataParams.browserInfo.deviceType,
- osVersion:
- (
- this.metadataParams.browserInfo.osName +
- ' ' +
- this.metadataParams.browserInfo.osVersion
- ).trim() || '',
- },
- ]),
- [4, this.getIdentificationMetadata(n)]
- );
- case 2:
- return [
- 2,
- __assign.apply(void 0, [
- __assign.apply(void 0, [
- __assign.apply(void 0, [
- __assign.apply(void 0, a.concat([s.sent()])),
- this.getIoMetadata(),
- ]),
- this.getSensorsMetadata(),
- ]),
- r,
- ]),
- ];
- }
- });
- });
- }),
- (n.prototype.batteryInit = function () {
- return __awaiter(this, void 0, void 0, function () {
- var e,
- n = this;
- return __generator(this, function (i) {
- switch (i.label) {
- case 0:
- return (
- (e = this),
- [
- 4,
- t._POSignalsUtils.Util.promiseTimeout(
- 50,
- new Promise(function (i, r) {
- navigator.getBattery
- ? ((n.isBatterySupported = !0),
- navigator
- .getBattery()
- .then(function (t) {
- t &&
- ((e.batteryLevel = t.level),
- (e.batteryCharging = t.charging),
- (e.batteryChargingTime = t.chargingTime),
- (e.batteryDischargingTime = t.dischargingTime)),
- i();
- })
- .catch(function (e) {
- t._POSignalsUtils.Logger.warn('Battery ' + e), i();
- }))
- : (t._POSignalsUtils.Logger.debug('Battery not supported!'), i());
- }),
- ),
- ]
- );
- case 1:
- return i.sent(), [2];
- }
- });
- });
- }),
- (n.prototype.enumerateDevicesEnabled = function () {
- var e = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
- return !t._POSignalsUtils.Util.inIframe() || !e;
- }),
- (n.prototype.getRTCPeerConnection = function () {
- var t =
- window.RTCPeerConnection ||
- window.mozRTCPeerConnection ||
- window.webkitRTCPeerConnection;
- if (!t) {
- var e = window['iframe.contentWindow'];
- e &&
- (t = e.RTCPeerConnection || e.mozRTCPeerConnection || e.webkitRTCPeerConnection);
- }
- return t;
- }),
- (n.prototype.collectWebRtc = function () {
- var t = this;
- try {
- var e = {},
- n = this.getRTCPeerConnection(),
- i = new n(
- { iceServers: [{ urls: this.metadataParams.webRtcUrl.trim() }] },
- { optional: [{ RtpDataChannels: !0 }] },
- );
- (i.onicecandidate = function (n) {
- if (n.candidate) {
- var i = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(
- n.candidate.candidate,
- )[1];
- void 0 === e[i] &&
- (n.candidate.candidate.indexOf('host') > 0
- ? t.webRtcIps.set('WEB_RTC_HOST_IP', i)
- : n.candidate.candidate.indexOf('srflx') > 0 &&
- t.webRtcIps.set('WEB_RTC_SRFLX_IP', i)),
- (e[i] = !0);
- }
- }),
- i.createDataChannel(''),
- i.createOffer(
- function (t) {
- i.setLocalDescription(
- t,
- function () {},
- function () {},
- );
- },
- function () {},
- );
- } catch (t) {}
- }),
- (n.prototype.audioIntVideoInit = function () {
- return __awaiter(this, void 0, void 0, function () {
- var e,
- n = this;
- return __generator(this, function (i) {
- switch (i.label) {
- case 0:
- return (
- (e = this),
- [
- 4,
- t._POSignalsUtils.Util.promiseTimeout(
- 50,
- new Promise(function (i, r) {
- return n.enumerateDevicesEnabled()
- ? navigator.mediaDevices && navigator.mediaDevices.enumerateDevices
- ? void navigator.mediaDevices
- .enumerateDevices()
- .then(function (t) {
- t.forEach(function (t) {
- t.kind &&
- ('audioinput' == t.kind.toLowerCase()
- ? ((e.hasMicrophone = !0),
- e.numberOfAudioDevices++,
- t.label && e.audioInputDevices.push(t.label))
- : 'videoinput' == t.kind.toLowerCase()
- ? ((e.hasWebcam = !0),
- e.numberOfVideoDevices++,
- t.label && e.videoInputDevices.push(t.label))
- : 'audiooutput' == t.kind.toLowerCase() &&
- ((e.hasSpeakers = !0),
- e.numberOfAudioDevices++,
- t.label && e.audioOutputDevices.push(t.label)));
- }),
- i();
- })
- .catch(function (e) {
- t._POSignalsUtils.Logger.warn('enumerateDevices failed', e),
- i();
- })
- : (t._POSignalsUtils.Logger.debug(
- 'enumerateDevices() not supported.',
- ),
- void i())
- : (t._POSignalsUtils.Logger.debug(
- 'enumerateDevices() cannot run within safari iframe',
- ),
- void i());
- }),
- ),
- ]
- );
- case 1:
- return i.sent(), [2];
- }
- });
- });
- }),
- (n.prototype.getFingerPrint = function (e) {
- return __awaiter(this, void 0, void 0, function () {
- var n,
- i,
- r = this;
- return __generator(this, function (a) {
- switch (a.label) {
- case 0:
- return e.has('fingerprint')
- ? [2, Promise.resolve('')]
- : ((n = new Promise(function (e, n) {
- return __awaiter(r, void 0, void 0, function () {
- var i, r;
- return __generator(this, function (a) {
- switch (a.label) {
- case 0:
- return a.trys.push([0, 3, , 4]), [4, t.FingerprintJS.load()];
- case 1:
- return [4, a.sent().get()];
- case 2:
- return (
- (i = a.sent()),
- (this.fingerPrint = i.visitorId),
- (this.fingerPrintComponents = i.components),
- e(i.visitorId),
- [3, 4]
- );
- case 3:
- return (
- (r = a.sent()),
- t._POSignalsUtils.Logger.warn(
- 'Failed to get FingerPrint ' + r,
- ),
- n({ err: r, message: 'FingerPrint failed' }),
- [3, 4]
- );
- case 4:
- return [2];
- }
- });
- });
- })),
- (i = new Promise(function (e, n) {
- return __awaiter(r, void 0, void 0, function () {
- return __generator(this, function (e) {
- switch (e.label) {
- case 0:
- return [
- 4,
- t._POSignalsUtils.Util.delay(
- this.metadataParams.fingerprintTimeoutMillis,
- ),
- ];
- case 1:
- return e.sent(), n({ message: 'Fingerprint timeout' }), [2];
- }
- });
- });
- })),
- [4, Promise.race([n, i])]);
- case 1:
- return [2, a.sent()];
- }
- });
- });
- }),
- (n.prototype.getSensorsMetadata = function () {
- var t = {};
- return (
- this.flatAndAddMetadata(t, 'DEDVCE_LIGHT_SUPPORTED', function () {
- return 'ondevicelight' in window;
- }),
- this.flatAndAddMetadata(t, 'IS_TOUCH_DEVICE', function () {
- return 'ontouchstart' in window;
- }),
- window.DeviceMotionEvent ||
- this.flatAndAddMetadata(t, 'ACCELEROMETER_SUPPORTED', function () {
- return !1;
- }),
- window.DeviceOrientationEvent ||
- this.flatAndAddMetadata(t, 'GYROSCOPE_SUPPORTED', function () {
- return !1;
- }),
- this.flatAndAddMetadata(t, 'PROXIMITY_SUPPORTED', function () {
- return 'ondeviceproximity' in window;
- }),
- t
- );
- }),
- (n.prototype.getIdentificationMetadata = function (i) {
- return __awaiter(this, void 0, void 0, function () {
- var r,
- a,
- o,
- s,
- u,
- c,
- l,
- d,
- h,
- f,
- g,
- p,
- v,
- _,
- m,
- y,
- b,
- E,
- w,
- S,
- A,
- O = this;
- return __generator(this, function (P) {
- switch (P.label) {
- case 0:
- return (
- (r = this),
- (a = {}),
- this.flatAndAddMetadata(a, 'FINGER_PRINT', function () {
- return O.fingerPrint;
- }),
- this.metadataParams.browserInfo.userAgentData &&
- (this.flatAndAddMetadata(a, 'OS_NAME', function () {
- return O.metadataParams.browserInfo.osName;
- }),
- this.flatAndAddMetadata(a, 'OS_VERSION', function () {
- return O.metadataParams.browserInfo.osVersion;
- })),
- this.metadataParams.browserInfo.userAgentData &&
- (this.flatAndAddMetadata(a, 'DEVICE_MODEL', function () {
- return O.metadataParams.browserInfo.deviceModel;
- }),
- this.flatAndAddMetadata(a, 'DEVICE_VENDOR', function () {
- return O.metadataParams.browserInfo.deviceVendor;
- })),
- this.metadataParams.browserInfo.userAgentData &&
- (this.flatAndAddMetadata(a, 'BROWSER_ENGINE_NAME', function () {
- return O.metadataParams.browserInfo.engineName;
- }),
- this.flatAndAddMetadata(a, 'BROWSER_ENGINE_VERSION', function () {
- return O.metadataParams.browserInfo.engineVersion;
- })),
- this.metadataParams.browserInfo.userAgentData &&
- this.flatAndAddMetadata(a, 'CPU_ARCHITECTURE', function () {
- return O.metadataParams.browserInfo.cpuArchitecture;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_VENDOR', function () {
- return navigator.vendor;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_PLUGINS_LENGTH', function () {
- return navigator.plugins ? navigator.plugins.length : null;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_MIME_TYPES_LENGTH', function () {
- return navigator.mimeTypes ? navigator.mimeTypes.length : null;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_LANGUAGE', function () {
- return (
- navigator.language ||
- navigator.userLanguage ||
- navigator.browserLanguage ||
- navigator.systemLanguage
- );
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_LANGUAGES', function () {
- return navigator.languages;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_MAX_TOUCH_POINTS', function () {
- return navigator.maxTouchPoints || navigator.msMaxTouchPoints;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_POINTER_ENABLED', function () {
- return navigator.pointerEnabled || navigator.msPointerEnabled;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_WEB_DRIVER', function () {
- return navigator.webdriver;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_HARDWARE_CONCURRENCY', function () {
- return navigator.hardwareConcurrency;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_VIBRATE', function () {
- return null != navigator.vibrate;
- }),
- this.flatAndAddMetadata(a, 'PUSH_NOTIFICATIONS_SUPPORTED', function () {
- return 'Notification' in window;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_APP_CODE_NAME', function () {
- return navigator.appCodeName;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_APP_NAME', function () {
- return navigator.appName;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_APP_VERSION', function () {
- return navigator.appVersion;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_ON_LINE', function () {
- return navigator.onLine;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_PLATFORM', function () {
- return navigator.platform;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_PRODUCT', function () {
- return navigator.product;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_USER_AGENT', function () {
- return navigator.userAgent;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_PDF_VIEWER_ENABLED', function () {
- return navigator.pdfViewerEnabled;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_DEVICE_MEMORY', function () {
- return navigator.deviceMemory;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_CONNECTION_RTT', function () {
- return navigator.connection ? navigator.connection.rtt : null;
- }),
- i.has('modernizr') ? [3, 2] : [4, this.safeAddModernizrFeatures(a)]
- );
- case 1:
- P.sent(), (P.label = 2);
- case 2:
- if (
- ((o = window._pingOneSignalsPingResult || window._ST_PING)
- ? this.flatAndAddMetadata(a, 'JS_CHALLENGE', function () {
- return o;
- })
- : this.flatAndAddMetadata(a, 'JS_CHALLENGE', function () {
- return 'unknown';
- }),
- (s = new e.FingerprintLegacyMetadata()),
- this.flatAndAddMetadata(a, 'IS_WEBGL', function () {
- return s.isWebGl('webgl');
- }),
- this.flatAndAddMetadata(a, 'WEBGLVENDORANDRENDERER', function () {
- return s.getWebglVendorAndRenderer('webgl');
- }),
- this.flatAndAddMetadata(a, 'IS_WEBGL2', function () {
- return s.isWebGl('webgl2');
- }),
- this.flatAndAddMetadata(a, 'WEBGL2VENDORANDRENDERER', function () {
- return s.getWebglVendorAndRenderer('webgl2');
- }),
- this.flatAndAddMetadata(a, 'HASLIEDLANGUAGES', function () {
- return s.getHasLiedLanguages();
- }),
- this.flatAndAddMetadata(a, 'HASLIEDRESOLUTION', function () {
- return s.getHasLiedResolution();
- }),
- this.flatAndAddMetadata(a, 'HASLIEDOS', function () {
- return s.getHasLiedOs();
- }),
- this.flatAndAddMetadata(a, 'HASLIEDBROWSER', function () {
- return s.getHasLiedBrowser();
- }),
- this.fingerPrintComponents)
- )
- for (l in ((u = function (t) {
- if (!c.fingerPrintComponents.hasOwnProperty(t)) return 'continue';
- var e = c.fingerPrintComponents[t];
- 'fonts' == t
- ? c.flatAndAddMetadata(a, 'JS_FONTS', function () {
- return e.value.length;
- })
- : 'canvas' == t
- ? c.flatAndAddMetadata(a, 'IS_CANVAS', function () {
- return null != e.value;
- })
- : 'screenResolution' == t && e.value && e.value.length
- ? c.flatAndAddMetadata(a, 'RESOLUTION', function () {
- return e.value.join(',');
- })
- : 'availableScreenResolution' == t && e.value && e.value.length
- ? c.flatAndAddMetadata(a, 'AVAILABLE_RESOLUTION', function () {
- return e.value.join(',');
- })
- : 'touchSupport' == t && e.value
- ? c.flatAndAddMetadata(a, 'TOUCH_SUPPORT', function () {
- return e.value;
- })
- : 'audio' == t && e.value
- ? c.flatAndAddMetadata(a, 'AUDIO_FINGERPRINT', function () {
- return e.value;
- })
- : 'osCpu' == t && e.value
- ? c.flatAndAddMetadata(a, 'OS_CPU', function () {
- return e.value;
- })
- : 'productSub' == t && e.value
- ? c.flatAndAddMetadata(a, 'PRODUCT_SUB', function () {
- return e.value;
- })
- : 'emptyEvalLength' == t && e.value
- ? c.flatAndAddMetadata(
- a,
- 'EMPTY_EVAL_LENGTH',
- function () {
- return e.value;
- },
- )
- : 'errorFF' == t && e.value
- ? c.flatAndAddMetadata(a, 'ERROR_FF', function () {
- return e.value;
- })
- : 'chrome' == t && e.value
- ? c.flatAndAddMetadata(a, 'CHROME', function () {
- return e.value;
- })
- : 'cookiesEnabled' == t && e.value
- ? c.flatAndAddMetadata(
- a,
- 'COOKIES_ENABLED',
- function () {
- return e.value;
- },
- )
- : r.fingerPrintComponentKeys.has(t) &&
- null != t &&
- c.flatAndAddMetadata(
- a,
- t.toUpperCase(),
- function () {
- return e.value;
- },
- );
- }),
- (c = this),
- this.fingerPrintComponents))
- u(l);
- for (p in (this.flatAndAddMetadata(a, 'IS_INCOGNITO', function () {
- return O.isPrivateMode;
- }),
- this.flatAndAddMetadata(a, 'IS_PRIVATE_MODE', function () {
- return O.isPrivateModeV2;
- }),
- this.flatAndAddMetadata(a, 'IS_WEB_GLSTATUS', function () {
- return O.webGlStatus;
- }),
- (d = {
- selenium:
- navigator.webdriver ||
- t._POSignalsUtils.Util.getAttribute(
- window.document.documentElement,
- 'webdriver',
- ) ||
- '',
- phantomjs: {
- _phantom: window._phantom || '',
- __phantomas: window.__phantomas || '',
- callPhantom: window.callPhantom || '',
- },
- nodejs: { Buffer: window.Buffer || '' },
- couchjs: { emit: window.emit || '' },
- rhino: { spawn: window.spawn || '' },
- chromium: {
- domAutomationController: window.domAutomationController || '',
- domAutomation: window.domAutomation || '',
- },
- outerWidth: window.outerWidth,
- outerHeight: window.outerHeight,
- }),
- this.flatAndAddMetadata(a, 'HEADLESS', function () {
- return d;
- }),
- this.flatAndAddMetadata(a, 'HEADLESS', function () {
- return O.headlessTests;
- }),
- this.flatAndAddMetadata(a, 'LIES', function () {
- var t = {};
- for (var e in O.lieTests) t[e] = JSON.stringify(O.lieTests[e]);
- return Object.keys(t).length > 0 ? t : null;
- }),
- this.flatAndAddMetadata(a, 'STEALTH', function () {
- return new e.DetectStealth(i).getStealthResult();
- }),
- this.flatAndAddMetadata(a, 'REF_LINK', function () {
- return document.referrer;
- }),
- this.flatAndAddMetadata(a, 'PLUGINS', function () {
- for (
- var t = { length: navigator.plugins.length, details: [] }, e = 0;
- e < t.length;
- e++
- )
- t.details.push({
- length: navigator.plugins[e].length,
- name: navigator.plugins[e].name,
- version: navigator.plugins[e].version,
- filename: navigator.plugins[e].filename,
- });
- return t;
- }),
- this.flatAndAddMetadata(a, 'AUDIO', function () {
- return O.numberOfAudioDevices;
- }),
- this.flatAndAddMetadata(a, 'VIDEO', function () {
- return O.numberOfVideoDevices;
- }),
- this.flatAndAddMetadata(a, 'VIDEO_INPUT_DEVICES', function () {
- return O.videoInputDevices.toString();
- }),
- this.flatAndAddMetadata(a, 'AUDIO_INPUT_DEVICES', function () {
- return O.audioInputDevices.toString();
- }),
- this.flatAndAddMetadata(a, 'AUDIO_OUTPUT_DEVICES', function () {
- return O.audioOutputDevices.toString();
- }),
- this.flatAndAddMetadata(a, 'MEDIA_CODEC_MP4_AVC1', function () {
- return O.getMediaCodec('video/mp4;; codecs = "avc1.42E01E"');
- }),
- this.flatAndAddMetadata(a, 'MEDIA_CODEC_X_M4A', function () {
- return O.getMediaCodec('audio/x-m4a');
- }),
- this.flatAndAddMetadata(a, 'MEDIA_CODEC_AAC', function () {
- return O.getMediaCodec('audio/aac');
- }),
- (h = this.metadataParams.additionalMediaCodecs),
- (f = function (t) {
- if (!h.hasOwnProperty(t)) return 'continue';
- g.flatAndAddMetadata(a, 'MEDIA_CODEC_' + t, function () {
- return O.getMediaCodec(h[t]);
- });
- }),
- (g = this),
- h))
- f(p);
- window.performance &&
- window.performance.memory &&
- (this.flatAndAddMetadata(a, 'MEMORY_HEAP_SIZE_LIMIT', function () {
- return window.performance.memory.jsHeapSizeLimit;
- }),
- this.flatAndAddMetadata(a, 'MEMORY_TOTAL_HEAP_SIZE', function () {
- return window.performance.memory.totalJSHeapSize;
- }),
- this.flatAndAddMetadata(a, 'MEMORY_USED_HEAP_SIZE', function () {
- return window.performance.memory.usedJSHeapSize;
- })),
- this.flatAndAddMetadata(a, 'IS_ACCEPT_COOKIES', function () {
- return navigator.cookieEnabled;
- }),
- this.flatAndAddMetadata(a, 'selenium_in_document', function () {
- return e.SeleniumProperties.seleniumInDocument();
- }),
- this.flatAndAddMetadata(a, 'selenium_in_window', function () {
- return e.SeleniumProperties.seleniumInWindow();
- }),
- this.flatAndAddMetadata(a, 'selenium_in_navigator', function () {
- return e.SeleniumProperties.seleniumInNavigator();
- }),
- this.flatAndAddMetadata(a, 'selenium_sequentum', function () {
- return e.SeleniumProperties.seleniumSequentum();
- }),
- this.flatAndAddMetadata(a, 'DOCUMENT_ELEMENT_SELENIUM', function () {
- return t._POSignalsUtils.Util.getAttribute(
- window.document.documentElement,
- 'selenium',
- );
- }),
- this.flatAndAddMetadata(a, 'DOCUMENT_ELEMENT_WEBDRIVER', function () {
- return t._POSignalsUtils.Util.getAttribute(
- window.document.documentElement,
- 'webdriver',
- );
- }),
- this.flatAndAddMetadata(a, 'DOCUMENT_ELEMENT_DRIVER', function () {
- return t._POSignalsUtils.Util.getAttribute(
- window.document.documentElement,
- 'driver',
- );
- }),
- this.flatAndAddMetadata(a, 'window_html_webdriver', function () {
- return !!t._POSignalsUtils.Util.getAttribute(
- document.getElementsByTagName('html')[0],
- 'webdriver',
- );
- }),
- this.flatAndAddMetadata(a, 'window_geb', function () {
- return !!window.geb;
- }),
- this.flatAndAddMetadata(a, 'window_awesomium', function () {
- return !!window.awesomium;
- }),
- this.flatAndAddMetadata(a, 'window_RunPerfTest', function () {
- return !!window.RunPerfTest;
- }),
- this.flatAndAddMetadata(a, 'window_fmget_targets', function () {
- return !!window.fmget_targets;
- }),
- this.flatAndAddMetadata(a, 'hasTrustToken', function () {
- return 'hasTrustToken' in document;
- }),
- this.flatAndAddMetadata(a, 'trustTokenOperationError', function () {
- return 'trustTokenOperationError' in XMLHttpRequest.prototype;
- }),
- this.flatAndAddMetadata(a, 'setTrustToken', function () {
- return 'setTrustToken' in XMLHttpRequest.prototype;
- }),
- this.flatAndAddMetadata(a, 'trustToken', function () {
- return 'trustToken' in HTMLIFrameElement.prototype;
- }),
- this.flatAndAddMetadata(a, 'localStorage.length', function () {
- return localStorage.length;
- }),
- this.flatAndAddMetadata(a, 'sessionStorage.length', function () {
- return sessionStorage.length;
- }),
- this.sessionData.disabledStorage.forEach(function (t) {
- O.flatAndAddMetadata(a, t.toUpperCase() + '_FAILED', function () {
- return !0;
- });
- }),
- this.flatAndAddMetadata(a, 'WEB_RTC_ENABLED', function () {
- return !!O.getRTCPeerConnection();
- }),
- this.metadataParams.webRtcUrl &&
- this.metadataParams.webRtcUrl.length > 0 &&
- (this.collectWebRtc(),
- this.webRtcIps.forEach(function (t, e) {
- null != e &&
- null != t &&
- O.flatAndAddMetadata(a, e, function () {
- return t;
- });
- }),
- this.webRtcIps.clear()),
- window.matchMedia &&
- this.flatAndAddMetadata(a, 'MQ_SCREEN', function () {
- var t = window.matchMedia(
- '(min-width: ' + (window.innerWidth - 1) + 'px)',
- );
- return { matches: t.matches, media: t.media };
- }),
- this.addIframeData(a, i),
- window.Notification &&
- this.flatAndAddMetadata(a, 'NOTIFICATION_PERMISSION', function () {
- return window.Notification.permission;
- }),
- this.flatAndAddMetadata(a, 'HAS_CHROME_APP', function () {
- return window.chrome && 'app' in window.chrome;
- }),
- this.flatAndAddMetadata(a, 'HAS_CHROME_CSI', function () {
- return window.chrome && 'csi' in window.chrome;
- }),
- this.flatAndAddMetadata(a, 'HAS_CHROME_LOADTIMES', function () {
- return window.chrome && 'loadTimes' in window.chrome;
- }),
- this.flatAndAddMetadata(a, 'HAS_CHROME_RUNTIME', function () {
- return window.chrome && 'runtime' in window.chrome;
- }),
- this.flatAndAddMetadata(a, 'CHROMIUM_MATH', n.detectChromium),
- this.addClientHints(a),
- this.flatAndAddMetadata(a, 'NAVIGATOR_KEYBOARD_SUPPORTED', function () {
- return !!navigator.keyboard;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_HID_SUPPORTED', function () {
- return !!navigator.hid;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_SERIAL_SUPPORTED', function () {
- return !!navigator.serial;
- }),
- this.flatAndAddMetadata(a, 'NAVIGATOR_PRESENTATION_SUPPORTED', function () {
- return !!navigator.presentation;
- }),
- (P.label = 3);
- case 3:
- return (
- P.trys.push([3, 6, , 7]),
- i.has('floc') || !t.Util.isFunction(document.interestCohort)
- ? [3, 5]
- : [4, t.Util.promiseTimeout(100, document.interestCohort())]
- );
- case 4:
- (v = P.sent()),
- (_ = v.id),
- (m = v.version),
- this.flatAndAddMetadata(a, 'floc_id', function () {
- return _;
- }),
- this.flatAndAddMetadata(a, 'floc_version', function () {
- return m;
- }),
- (P.label = 5);
- case 5:
- return [3, 7];
- case 6:
- return P.sent(), [3, 7];
- case 7:
- for (E in ((y = function (e) {
- b.flatAndAddMetadata(a, e, function () {
- return t._POSignalsUtils.Util.getProperty(
- window,
- O.metadataParams.dataPoints[e],
- );
- });
- }),
- (b = this),
- this.metadataParams.dataPoints))
- y(E);
- for (S in (w = this.metadataParams.propertyDescriptors))
- w.hasOwnProperty(S) &&
- (A = 'window' === S ? window : window[S]) &&
- this.addPropertyDescriptorInfo(
- A,
- S.toUpperCase() + '_PROPERTY_DESCRIPTOR',
- w[S],
- a,
- );
- return [2, a];
- }
- });
- });
- }),
- (n.prototype.addClientHints = function (e) {
- try {
- var n = navigator.userAgentData;
- if (!n) return;
- this.flatAndAddMetadata(e, 'NAVIGATOR_CLIENT_HINTS_PLATFORM', function () {
- return n.platform;
- }),
- this.flatAndAddMetadata(e, 'NAVIGATOR_CLIENT_HINTS_MOBILE', function () {
- return n.mobile;
- });
- var i = n.brands;
- if (!i) return;
- for (
- var r = function (t) {
- if (i[t].hasOwnProperty('brand') && i[t].hasOwnProperty('version')) {
- var n = i[t].brand + ':' + i[t].version;
- a.flatAndAddMetadata(e, 'NAVIGATOR_CLIENT_HINTS_BRAND_' + t, function () {
- return n;
- });
- }
- },
- a = this,
- o = 0;
- o < i.length;
- o++
- )
- r(o);
- } catch (e) {
- t._POSignalsUtils.Logger.warn('failed to add client hints', e);
- }
- }),
- (n.prototype.addPropertyDescriptorInfo = function (e, n, i, r) {
- try {
- for (
- var a = function (t) {
- o.flatAndAddMetadata(r, n + '_' + t.toUpperCase(), function () {
- var n = e.prototype ? e.prototype : e,
- i = Object.getOwnPropertyDescriptor(n, t);
- if (i) {
- var r = i.get ? i.get.toString() : void 0;
- return JSON.stringify({
- configurable: i.configurable,
- enumerable: i.enumerable,
- value: i.value,
- writable: i.writable,
- getter: null != r && r.length < 100 ? r : void 0,
- });
- }
- return 'undefined';
- });
- },
- o = this,
- s = 0,
- u = i;
- s < u.length;
- s++
- ) {
- a(u[s]);
- }
- } catch (e) {
- t._POSignalsUtils.Logger.warn('failed to add properties descriptor', e);
- }
- }),
- (n.prototype.addIframeData = function (e, n) {
- if (!n.has('IFRAME_DATA'))
- try {
- var i = t._POSignalsUtils.Util.createInvisibleElement('iframe');
- if (!i) return;
- (i.srcdoc = 'blank page'),
- document.body.appendChild(i),
- this.flatAndAddMetadata(e, 'IFRAME_CHROME', function () {
- return typeof i.contentWindow.chrome;
- }),
- this.flatAndAddMetadata(e, 'IFRAME_WIDTH', function () {
- return i.contentWindow.screen.width;
- }),
- this.flatAndAddMetadata(e, 'IFRAME_HEIGHT', function () {
- return i.contentWindow.screen.height;
- }),
- i.remove();
- } catch (e) {
- t._POSignalsUtils.Logger.warn('failed to add iframe data', e);
- }
- }),
- (n.prototype.getPermissionsMetadata = function () {
- return __awaiter(this, void 0, void 0, function () {
- var e, n, i, r, a, o;
- return __generator(this, function (s) {
- switch (s.label) {
- case 0:
- if (
- ((e = {}),
- (n = [
- 'accelerometer',
- 'accessibility-events',
- 'ambient-light-sensor',
- 'background-sync',
- 'camera',
- 'clipboard-read',
- 'clipboard-write',
- 'geolocation',
- 'gyroscope',
- 'magnetometer',
- 'microphone',
- 'midi',
- 'notifications',
- 'payment-handler',
- 'persistent-storage',
- 'push',
- ]),
- (i = []),
- navigator.permissions)
- )
- for (a in ((r = function (t) {
- var r = n[t];
- i.push(
- navigator.permissions
- .query({ name: r })
- .then(function (t) {
- e[r] = t.state;
- })
- .catch(function (t) {}),
- );
- }),
- n))
- r(a);
- s.label = 1;
- case 1:
- return s.trys.push([1, 3, , 4]), [4, Promise.all(i)];
- case 2:
- return s.sent(), [3, 4];
- case 3:
- return (o = s.sent()), t._POSignalsUtils.Logger.warn(o), [3, 4];
- case 4:
- return [2, e];
- }
- });
- });
- }),
- (n.prototype.getMediaCodec = function (t) {
- var e = document.createElement('video');
- if (e && e.canPlayType) return e.canPlayType(t);
- }),
- (n.prototype.safeAddModernizrFeatures = function (e) {
- return __awaiter(this, void 0, void 0, function () {
- var n, i, r, a, o, s;
- return __generator(this, function (u) {
- switch (u.label) {
- case 0:
- return (
- t.evaluateModernizr(),
- (n = this),
- (i = t.Modernizr),
- (r = i.prefixed),
- (a = i.hasEvent),
- this.flatAndAddMetadata(e, 'ambient_light', function () {
- return i.ambientlight;
- }),
- this.flatAndAddMetadata(e, 'application_cache', function () {
- return i.applicationcache;
- }),
- this.flatAndAddMetadata(e, 'audio', function () {
- return !!i.audio;
- }),
- i.audio &&
- this.flatAndAddMetadata(e, 'audio', function () {
- return i.audio;
- }),
- this.flatAndAddMetadata(e, 'battery_api', function () {
- return !!r('battery', navigator) || !!r('getBattery', navigator);
- }),
- this.flatAndAddMetadata(e, 'blob_constructor', function () {
- return i.blobconstructor;
- }),
- this.flatAndAddMetadata(e, 'context_menu', function () {
- return i.contextmenu;
- }),
- this.flatAndAddMetadata(e, 'cors', function () {
- return i.cors;
- }),
- this.flatAndAddMetadata(e, 'cryptography', function () {
- return i.cryptography;
- }),
- this.flatAndAddMetadata(e, 'custom_elements', function () {
- return i.customelements;
- }),
- this.flatAndAddMetadata(e, 'custom_protocol_handler', function () {
- return i.customprotocolhandler;
- }),
- this.flatAndAddMetadata(e, 'custom_event', function () {
- return i.customevent;
- }),
- this.flatAndAddMetadata(e, 'dart', function () {
- return i.dart;
- }),
- this.flatAndAddMetadata(e, 'data_view', function () {
- return i.dataview;
- }),
- this.flatAndAddMetadata(e, 'event_listener', function () {
- return i.eventlistener;
- }),
- [4, this.safeModernizrOn('exiforientation')]
- );
- case 1:
- return (
- (o = u.sent()),
- n.flatAndAddMetadata(e, 'exif_orientation', function () {
- return o;
- }),
- this.flatAndAddMetadata(e, 'force_touch', function () {
- return i.forcetouch;
- }),
- i.forcetouch &&
- (this.flatAndAddMetadata(
- e,
- 'force_touch.mouse_force_will_begin',
- function () {
- return a(r('mouseforcewillbegin', window, !1), window);
- },
- ),
- this.flatAndAddMetadata(
- e,
- 'force_touch.webkit_force_at_mouse_down',
- function () {
- return MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN;
- },
- ),
- this.flatAndAddMetadata(
- e,
- 'force_touch.webkit_force_at_force_mouse_down',
- function () {
- return MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN;
- },
- )),
- this.flatAndAddMetadata(e, 'full_screen', function () {
- return i.fullscreen;
- }),
- this.flatAndAddMetadata(e, 'game_pads', function () {
- return i.gamepads;
- }),
- this.flatAndAddMetadata(e, 'geo_location', function () {
- return i.geolocation;
- }),
- this.flatAndAddMetadata(e, 'ie8compat', function () {
- return i.ie8compat;
- }),
- [4, this.safeModernizrOn('indexeddb')]
- );
- case 2:
- return (
- (s = u.sent()),
- n.flatAndAddMetadata(e, 'indexed_db', function () {
- return s;
- }),
- this.flatAndAddMetadata(e, 'indexed_db_blob', function () {
- return i.indexeddbblob;
- }),
- this.flatAndAddMetadata(e, 'internationalization', function () {
- return i.intl;
- }),
- this.flatAndAddMetadata(e, 'json', function () {
- return i.json;
- }),
- this.flatAndAddMetadata(e, 'ligatures', function () {
- return i.ligatures;
- }),
- this.flatAndAddMetadata(e, 'media_source', function () {
- return 'MediaSource' in window;
- }),
- this.flatAndAddMetadata(e, 'message_channel', function () {
- return i.messagechannel;
- }),
- this.flatAndAddMetadata(e, 'notification', function () {
- return i.notification;
- }),
- this.flatAndAddMetadata(e, 'page_visibility', function () {
- return i.pagevisibility;
- }),
- this.flatAndAddMetadata(e, 'performance', function () {
- return i.performance;
- }),
- this.flatAndAddMetadata(e, 'pointer_events', function () {
- return i.pointerevents;
- }),
- this.flatAndAddMetadata(e, 'pointer_lock', function () {
- return i.pointerlock;
- }),
- this.flatAndAddMetadata(e, 'proximity', function () {
- return i.proximity;
- }),
- this.flatAndAddMetadata(e, 'query_selector', function () {
- return i.queryselector;
- }),
- this.flatAndAddMetadata(e, 'quota_management', function () {
- return i.quotamanagement;
- }),
- this.flatAndAddMetadata(e, 'request_animation_frame', function () {
- return i.requestanimationframe;
- }),
- this.flatAndAddMetadata(e, 'service_worker', function () {
- return i.serviceworker;
- }),
- this.flatAndAddMetadata(e, 'touch_events', function () {
- return i.touchevents;
- }),
- this.flatAndAddMetadata(e, 'typed_arrays', function () {
- return i.typedarrays;
- }),
- this.flatAndAddMetadata(e, 'vibrate', function () {
- return i.vibrate;
- }),
- this.flatAndAddMetadata(e, 'video', function () {
- return !!i.video;
- }),
- i.video &&
- this.flatAndAddMetadata(e, 'video', function () {
- return i.video;
- }),
- this.flatAndAddMetadata(e, 'web_gl', function () {
- return i.webgl;
- }),
- this.flatAndAddMetadata(e, 'web_sockets', function () {
- return i.websockets;
- }),
- this.flatAndAddMetadata(e, 'x_domain_request', function () {
- return i.xdomainrequest;
- }),
- this.flatAndAddMetadata(e, 'matchmedia', function () {
- return i.matchmedia;
- }),
- [2]
- );
- }
- });
- });
- }),
- (n.prototype.getIoMetadata = function () {
- var e = this,
- n = {},
- i = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
- return (
- this.flatAndAddMetadata(n, 'NETWORK_TYPE', function () {
- return i ? i.type : null;
- }),
- this.flatAndAddMetadata(n, 'NETWORK_DOWNLOAD_MAX', function () {
- return i ? i.downlinkMax : null;
- }),
- this.flatAndAddMetadata(n, 'BLUTOOTH_SUPPORTED', function () {
- return !!navigator.bluetooth;
- }),
- this.flatAndAddMetadata(n, 'HAS_SPEAKERS', function () {
- return e.hasSpeakers;
- }),
- this.flatAndAddMetadata(n, 'HAS_MICROPHONE', function () {
- return e.hasMicrophone;
- }),
- this.flatAndAddMetadata(n, 'HAS_CAMERA', function () {
- return e.hasWebcam;
- }),
- this.flatAndAddMetadata(n, 'BATTERY_SUPPORTED', function () {
- return e.isBatterySupported;
- }),
- this.flatAndAddMetadata(n, 'BATTERY_LEVEL', function () {
- return e.batteryLevel;
- }),
- this.flatAndAddMetadata(n, 'BATTERY_CHARGING', function () {
- return e.batteryCharging;
- }),
- this.flatAndAddMetadata(n, 'BATTERY_CHARGING_TIME', function () {
- return e.batteryChargingTime;
- }),
- this.flatAndAddMetadata(n, 'BATTERY_DISCHARGING_TIME', function () {
- return e.batteryDischargingTime;
- }),
- this.flatAndAddMetadata(n, 'GPS_SUPPORTED', function () {
- return e.gpsSupported;
- }),
- this.flatAndAddMetadata(n, 'IS_MOBILE', function () {
- return t._POSignalsUtils.Util.isMobile;
- }),
- this.flatAndAddMetadata(n, 'HAS_TOUCH', function () {
- return 'ontouchstart' in document.documentElement;
- }),
- this.flatAndAddMetadata(n, 'PERMISSIONS', function () {
- return e.permissions;
- }),
- this.flatAndAddMetadata(n, 'PREFERS_COLOR_SCHEME', function () {
- return window.matchMedia('(prefers-color-scheme: light)').matches
- ? 'light'
- : window.matchMedia('(prefers-color-scheme: dark)').matches
- ? 'dark'
- : void 0;
- }),
- n
- );
- }),
- (n.prototype.safeAddMetadata = function (e, n, i) {
- try {
- var r = new Set(this.metadataParams.metadataBlackList || []);
- null == n || null == i || r.has(n) || (e[n] = i);
- } catch (e) {
- t._POSignalsUtils.Logger.warn('Failed to add ' + n + ' -> ' + i + ', ' + e);
- }
- }),
- (n.prototype.safeModernizrOn = function (e) {
- return __awaiter(this, void 0, void 0, function () {
- var n, i;
- return __generator(this, function (r) {
- switch (r.label) {
- case 0:
- return (
- (n = new Promise(function (n) {
- try {
- t.Modernizr.on(e, function (t) {
- n(t);
- });
- } catch (i) {
- n(null),
- t._POSignalsUtils.Logger.warn(
- 'Modernizr.on Failed with feature ' + e,
- i,
- );
- }
- })),
- (i = t._POSignalsUtils.Util.delay(250).then(function () {
- return null;
- })),
- [4, Promise.race([n, i])]
- );
- case 1:
- return [2, r.sent()];
- }
- });
- });
- }),
- (n.prototype.flatAndAddMetadata = function (e, n, i) {
- try {
- var r = new Set(this.metadataParams.metadataBlackList || []);
- if (!n || r.has(n)) return;
- var a = i();
- if ('object' == typeof a && null !== a) {
- var o = t._POSignalsUtils.Util.flatten(a);
- for (var s in o) this.safeAddMetadata(e, n + '.' + s, o[s]);
- } else this.safeAddMetadata(e, n, a);
- } catch (e) {
- t._POSignalsUtils.Logger.warn('Failed to add ' + n, e);
- }
- }),
- (n.prototype.getOps = function () {
- var e,
- n = new Date(),
- i = 0;
- do {
- i++, (e = new Date().getTime() - n.getTime()), Math.sqrt(i * Math.random());
- } while (e < 500);
- var r = i / e;
- return t._POSignalsUtils.Logger.debug('Ops : ' + r), r;
- }),
- (n.prototype.getPrivateMode = function () {
- return __awaiter(this, void 0, void 0, function () {
- var t;
- return __generator(this, function (e) {
- return (
- (t = this),
- [
- 2,
- new Promise(function (e, n) {
- t.detectPrivateMode(function (t) {
- e(t);
- });
- }),
- ]
- );
- });
- });
- }),
- (n.prototype.detectPrivateMode = function (t) {
- var e,
- n = t.bind(null, !0),
- i = t.bind(null, !1);
- window.webkitRequestFileSystem
- ? window.webkitRequestFileSystem(0, 0, i, n)
- : 'MozAppearance' in document.documentElement.style
- ? (((e = indexedDB.open('test')).onerror = n), (e.onsuccess = i))
- : /constructor/i.test(window.HTMLElement) || window.safari
- ? (function () {
- try {
- localStorage.length
- ? i()
- : ((localStorage.x = 1), localStorage.removeItem('x'), i());
- } catch (t) {
- navigator.cookieEnabled ? n() : i();
- }
- })()
- : window.indexedDB || (!window.PointerEvent && !window.MSPointerEvent)
- ? i()
- : n();
- }),
- (n.detectChromium = function () {
- return (
- 1.4474840516030247 == Math.acos(0.123) &&
- 0.881373587019543 == Math.acosh(Math.SQRT2) &&
- 1.1071487177940904 == Math.atan(2) &&
- 0.5493061443340548 == Math.atanh(0.5) &&
- 1.4645918875615231 == Math.cbrt(Math.PI) &&
- -0.4067775970251724 == Math.cos(21 * Math.LN2) &&
- 9.199870313877772e307 == Math.cosh(492 * Math.LOG2E) &&
- 1.718281828459045 == Math.expm1(1) &&
- 101.76102278593319 == Math.hypot(6 * Math.PI, -100) &&
- 0.4971498726941338 == Math.log10(Math.PI) &&
- 1.2246467991473532e-16 == Math.sin(Math.PI) &&
- 11.548739357257748 == Math.sinh(Math.PI) &&
- -3.3537128705376014 == Math.tan(10 * Math.LOG2E) &&
- 0.12238344189440875 == Math.tanh(0.123) &&
- 1.9275814160560204e-50 == Math.pow(Math.PI, -100)
- );
- }),
- n
- );
- })();
- e.Metadata = n;
- })(t._POSignalsMetadata || (t._POSignalsMetadata = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- !(function (t) {
- var e = (function () {
- function t() {}
- return (
- (t.seleniumInDocument = function () {
- for (
- var t = 0,
- e = [
- '__webdriver_evaluate',
- '__selenium_evaluate',
- '__webdriver_script_function',
- '__webdriver_script_func',
- '__webdriver_script_fn',
- '__fxdriver_evaluate',
- '__driver_unwrapped',
- '__webdriver_unwrapped',
- '__driver_evaluate',
- '__selenium_unwrapped',
- '__fxdriver_unwrapped',
- ];
- t < e.length;
- t++
- ) {
- if (document[e[t]]) return !0;
- }
- return !1;
- }),
- (t.seleniumInWindow = function () {
- for (
- var t = 0,
- e = [
- '_phantom',
- '__nightmare',
- '_selenium',
- 'callPhantom',
- 'calledSelenium',
- 'callSelenium',
- '_Selenium_IDE_Recorder',
- ];
- t < e.length;
- t++
- ) {
- if (window[e[t]]) return !0;
- }
- return !1;
- }),
- (t.seleniumInNavigator = function () {
- for (
- var t = 0,
- e = [
- 'webdriver',
- '__driver_evaluate',
- '__webdriver_evaluate',
- '__selenium_evaluate',
- '__fxdriver_evaluate',
- '__driver_unwrapped',
- '__webdriver_unwrapped',
- '__selenium_unwrapped',
- '__fxdriver_unwrapped',
- '_Selenium_IDE_Recorder',
- '_selenium',
- 'calledSelenium',
- '_WEBDRIVER_ELEM_CACHE',
- 'ChromeDriverw',
- 'driver-evaluate',
- 'webdriver-evaluate',
- 'selenium-evaluate',
- 'webdriverCommand',
- 'webdriver-evaluate-response',
- '__webdriverFunc',
- '__webdriver_script_fn',
- '__$webdriverAsyncExecutor',
- '__lastWatirAlert',
- '__lastWatirConfirm',
- '__lastWatirPrompt',
- '$chrome_asyncScriptInfo',
- '$cdc_asdjflasutopfhvcZLmcfl_',
- ];
- t < e.length;
- t++
- ) {
- if (navigator[e[t]]) return !0;
- }
- return !1;
- }),
- (t.seleniumSequentum = function () {
- return (
- window.external &&
- window.external.toString() &&
- -1 != window.external.toString().indexOf('Sequentum')
- );
- }),
- t
- );
- })();
- t.SeleniumProperties = e;
- })(t._POSignalsMetadata || (t._POSignalsMetadata = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- !(function (e) {
- var n = (function () {
- function e(t) {
- this.propertyBlackList = t;
- }
- return (
- (e.prototype.getHeadlessResults = function () {
- return __awaiter(this, void 0, void 0, function () {
- var e,
- n = this;
- return __generator(this, function (i) {
- switch (i.label) {
- case 0:
- return [4, this.headlessResults(window)];
- case 1:
- return (
- (e = i.sent()),
- [
- 4,
- this.test(e, 'iframe_window', function () {
- return __awaiter(n, void 0, void 0, function () {
- var e, n;
- return __generator(this, function (i) {
- switch (i.label) {
- case 0:
- return Object.getOwnPropertyDescriptors &&
- (e = t._POSignalsUtils.Util.createInvisibleElement('iframe'))
- ? ((e.srcdoc = 'page intentionally left blank'),
- document.body.appendChild(e),
- 'function get contentWindow() { [native code] }' !==
- Object.getOwnPropertyDescriptors(
- HTMLIFrameElement.prototype,
- ).contentWindow.get.toString()
- ? [2, !0]
- : e.contentWindow === window
- ? [2, !0]
- : [4, this.headlessResults(e.contentWindow)])
- : [2];
- case 1:
- return (n = i.sent()), e.remove(), [2, n];
- }
- });
- });
- }),
- ]
- );
- case 2:
- return i.sent(), [2, e];
- }
- });
- });
- }),
- (e.prototype.headlessResults = function (t) {
- return __awaiter(this, void 0, void 0, function () {
- var e,
- n,
- i = this;
- return __generator(this, function (r) {
- switch (r.label) {
- case 0:
- return (
- (e = new Map()),
- (n = []).push(
- this.test(e, 'headless_chrome', function () {
- return __awaiter(i, void 0, void 0, function () {
- return __generator(this, function (e) {
- return [2, /HeadlessChrome/.test(t.navigator.userAgent)];
- });
- });
- }),
- ),
- n.push(
- this.test(e, 'navigator.webdriver_present', function () {
- return __awaiter(i, void 0, void 0, function () {
- return __generator(this, function (e) {
- return [2, 'webdriver' in t.navigator];
- });
- });
- }),
- ),
- n.push(
- this.test(e, 'window.chrome_missing', function () {
- return __awaiter(i, void 0, void 0, function () {
- return __generator(this, function (e) {
- return [2, /Chrome/.test(t.navigator.userAgent) && !t.chrome];
- });
- });
- }),
- ),
- n.push(
- this.test(e, 'permissions_api', function () {
- return __awaiter(i, void 0, void 0, function () {
- var e;
- return __generator(this, function (n) {
- switch (n.label) {
- case 0:
- return t.navigator.permissions && t.Notification
- ? [
- 4,
- t.navigator.permissions.query({ name: 'notifications' }),
- ]
- : [3, 2];
- case 1:
- return (
- (e = n.sent()),
- [
- 2,
- 'denied' === t.Notification.permission &&
- 'prompt' === e.state,
- ]
- );
- case 2:
- return [2];
- }
- });
- });
- }),
- ),
- n.push(
- this.test(e, 'permissions_api_overriden', function () {
- return __awaiter(i, void 0, void 0, function () {
- var e;
- return __generator(this, function (n) {
- return (e = t.navigator.permissions)
- ? 'function query() { [native code] }' !== e.query.toString()
- ? [2, !0]
- : 'function toString() { [native code] }' !==
- e.query.toString.toString()
- ? [2, !0]
- : e.query.toString.hasOwnProperty('[[Handler]]') &&
- e.query.toString.hasOwnProperty('[[Target]]') &&
- e.query.toString.hasOwnProperty('[[IsRevoked]]')
- ? [2, !0]
- : [2, e.hasOwnProperty('query')]
- : [2];
- });
- });
- }),
- ),
- n.push(
- this.test(e, 'navigator.plugins_empty', function () {
- return __awaiter(i, void 0, void 0, function () {
- return __generator(this, function (t) {
- return [2, 0 === navigator.plugins.length];
- });
- });
- }),
- ),
- n.push(
- this.test(e, 'navigator.languages_blank', function () {
- return __awaiter(i, void 0, void 0, function () {
- return __generator(this, function (t) {
- return [2, '' === navigator.languages];
- });
- });
- }),
- ),
- n.push(
- this.test(e, 'consistent_plugins_prototype', function () {
- return __awaiter(i, void 0, void 0, function () {
- var t;
- return __generator(this, function (e) {
- return (
- (t = PluginArray.prototype === navigator.plugins.__proto__),
- navigator.plugins.length > 0 &&
- (t = t && Plugin.prototype === navigator.plugins[0].__proto__),
- [2, t]
- );
- });
- });
- }),
- ),
- n.push(
- this.test(e, 'consistent_mimetypes_prototype', function () {
- return __awaiter(i, void 0, void 0, function () {
- var t;
- return __generator(this, function (e) {
- return (
- (t = MimeTypeArray.prototype === navigator.mimeTypes.__proto__),
- navigator.mimeTypes.length > 0 &&
- (t =
- t && MimeType.prototype === navigator.mimeTypes[0].__proto__),
- [2, t]
- );
- });
- });
- }),
- ),
- [4, Promise.all(n)]
- );
- case 1:
- return r.sent(), [2, e];
- }
- });
- });
- }),
- (e.prototype.test = function (e, n, i) {
- return __awaiter(this, void 0, void 0, function () {
- var r, a;
- return __generator(this, function (o) {
- switch (o.label) {
- case 0:
- return (
- o.trys.push([0, 3, , 4]),
- this.propertyBlackList.has(n)
- ? [3, 2]
- : [4, t._POSignalsUtils.Util.promiseTimeout(100, i())]
- );
- case 1:
- null != (r = o.sent()) && (e[n] = r), (o.label = 2);
- case 2:
- return [3, 4];
- case 3:
- return (
- (a = o.sent()),
- t._POSignalsUtils.Logger.warn(n + ' headless test was failed', a),
- [3, 4]
- );
- case 4:
- return [2];
- }
- });
- });
- }),
- e
- );
- })();
- e.DetectHeadless = n;
- })(t._POSignalsMetadata || (t._POSignalsMetadata = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- !(function (e) {
- var n = (function () {
- function n(t) {
- (this.propertyBlackList = t), (this.result = {});
- }
- return (
- (n.prototype.documentLie = function (t, e) {
- if (e.lied)
- for (var n = 0, i = e.lieTypes; n < i.length; n++) {
- var r = i[n];
- this.result[r] || (this.result[r] = []), this.result[r].push(t);
- }
- }),
- (n.prototype.getLies = function (t, e, i) {
- var r = this;
- if ((void 0 === i && (i = null), 'function' != typeof t))
- return { lied: !1, lieTypes: [] };
- var a = t.name.replace(/get\s/, ''),
- o = {
- undefined_properties: function () {
- return !!i && n.getUndefinedValueLie(i, a);
- },
- to_string: function () {
- return n.getToStringLie(t, a, r.iframeWindow);
- },
- prototype_in_function: function () {
- return n.getPrototypeInFunctionLie(t);
- },
- own_property: function () {
- return n.getOwnPropertyLie(t);
- },
- object_to_string_error: function () {
- return n.getNewObjectToStringTypeErrorLie(t);
- },
- },
- s = Object.keys(o).filter(function (t) {
- return !r.propertyBlackList.has('LIES.' + t) && !!o[t]();
- });
- return { lied: s.length > 0, lieTypes: s };
- }),
- (n.prototype.getAllLies = function () {
- return __awaiter(this, void 0, void 0, function () {
- var e;
- return __generator(this, function (n) {
- switch (n.label) {
- case 0:
- return this.propertyBlackList.has('LIES')
- ? [2, this.result]
- : (this.propertyBlackList.has('LIES_IFRAME') ||
- ((e = t._POSignalsUtils.Util.createInvisibleElement('iframe')) &&
- (document.body.appendChild(e), (this.iframeWindow = e))),
- [
- 4,
- Promise.all([
- this.searchLies(
- function () {
- return AnalyserNode;
- },
- { target: ['minDecibels'] },
- ),
- this.searchLies(
- function () {
- return AudioBuffer;
- },
- { target: ['copyFromChannel'] },
- ),
- this.searchLies(
- function () {
- return BiquadFilterNode;
- },
- { target: ['getFrequencyResponse'] },
- ),
- this.searchLies(
- function () {
- return CanvasRenderingContext2D;
- },
- { target: ['getLineDash'] },
- ),
- this.searchLies(
- function () {
- return DOMRect;
- },
- { target: ['height'] },
- ),
- this.searchLies(
- function () {
- return DOMRectReadOnly;
- },
- { target: ['left'] },
- ),
- this.searchLies(
- function () {
- return Element;
- },
- { target: ['getClientRects'] },
- ),
- this.searchLies(
- function () {
- return HTMLCanvasElement;
- },
- { target: ['height'] },
- ),
- this.searchLies(
- function () {
- return Math;
- },
- { target: ['sinh'] },
- ),
- this.searchLies(
- function () {
- return MediaDevices;
- },
- { target: ['enumerateDevices'] },
- ),
- this.searchLies(
- function () {
- return Navigator;
- },
- { target: ['plugins'] },
- ),
- this.searchLies(
- function () {
- return OffscreenCanvasRenderingContext2D;
- },
- { target: ['getLineDash'] },
- ),
- this.searchLies(
- function () {
- return SVGRect;
- },
- { target: ['x'] },
- ),
- ]),
- ]);
- case 1:
- return n.sent(), this.iframeWindow.remove(), [2, this.result];
- }
- });
- });
- }),
- (n.prototype.searchLies = function (e, n) {
- var i = void 0 === n ? {} : n,
- r = i.target,
- a = void 0 === r ? [] : r,
- o = i.ignore,
- s = void 0 === o ? [] : o;
- return __awaiter(this, void 0, void 0, function () {
- var n,
- i,
- r = this;
- return __generator(this, function (o) {
- try {
- if (((n = e()), void 0 === (u = n) || !u)) return [2];
- } catch (t) {
- return [2];
- }
- var u;
- return (
- (i = n.prototype ? n.prototype : n),
- Object.getOwnPropertyNames(i).forEach(function (e) {
- if (
- !(
- 'constructor' == e ||
- (a.length && !new Set(a).has(e)) ||
- (s.length && new Set(s).has(e))
- )
- ) {
- var i = /\s(.+)\]/,
- o = (n.name ? n.name : i.test(n) ? i.exec(n)[1] : void 0) + '.' + e;
- try {
- var u = n.prototype ? n.prototype : n;
- try {
- if ('function' == typeof u[e]) {
- var c = r.getLies(u[e], u);
- return void r.documentLie(o, c);
- }
- } catch (t) {}
- var l = Object.getOwnPropertyDescriptor(u, e).get,
- d = r.getLies(l, u, n);
- r.documentLie(o, d);
- } catch (n) {
- t._POSignalsUtils.Logger.warn('failed ' + e + ' test execution', n);
- }
- }
- }),
- [2]
- );
- });
- });
- }),
- (n.getUndefinedValueLie = function (t, e) {
- var n = t.name,
- i = window[n.charAt(0).toLowerCase() + n.slice(1)];
- return (
- !!i &&
- (void 0 !== Object.getOwnPropertyDescriptor(i, e) ||
- void 0 !== Reflect.getOwnPropertyDescriptor(i, e))
- );
- }),
- (n.getToStringLie = function (t, e, n) {
- var i, r;
- try {
- i = n.Function.prototype.toString.call(t);
- } catch (t) {}
- try {
- r = n.Function.prototype.toString.call(t.toString);
- } catch (t) {}
- var a = i || t.toString(),
- o = r || t.toString.toString(),
- s = function (t) {
- var e;
- return (
- ((e = {})['function ' + t + '() { [native code] }'] = !0),
- (e['function get ' + t + '() { [native code] }'] = !0),
- (e['function () { [native code] }'] = !0),
- (e['function ' + t + '() {\n [native code]\n}'] = !0),
- (e['function get ' + t + '() {\n [native code]\n}'] = !0),
- (e['function () {\n [native code]\n}'] = !0),
- e
- );
- };
- return !s(e)[a] || !s('toString')[o];
- }),
- (n.getPrototypeInFunctionLie = function (t) {
- return 'prototype' in t;
- }),
- (n.getOwnPropertyLie = function (t) {
- return (
- t.hasOwnProperty('arguments') ||
- t.hasOwnProperty('caller') ||
- t.hasOwnProperty('prototype') ||
- t.hasOwnProperty('toString')
- );
- }),
- (n.getNewObjectToStringTypeErrorLie = function (t) {
- try {
- return Object.create(t).toString(), !0;
- } catch (t) {
- var n = t.stack.split('\n'),
- i = /at Object\.apply/,
- r = !n.slice(1).find(function (t) {
- return i.test(t);
- }),
- a = 'TypeError' == t.constructor.name && n.length > 1,
- o = 'chrome' in window || e.Metadata.detectChromium();
- return !(!a || !o || (/at Function\.toString/.test(n[1]) && r)) || !a;
- }
- }),
- n
- );
- })();
- e.DetectLies = n;
- })(t._POSignalsMetadata || (t._POSignalsMetadata = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- !(function (e) {
- var n = (function () {
- function n(t) {
- (this.propertyBlackList = t), (this.result = new Map());
- }
- return (
- (n.prototype.getStealthResult = function () {
- return (
- this.addStealthTest('srcdoc_throws_error', function () {
- try {
- return !!document.createElement('iframe').srcdoc;
- } catch (t) {
- return !0;
- }
- }),
- this.addStealthTest('srcdoc_triggers_window_proxy', function () {
- var e = document.createElement('iframe');
- return (
- (e.srcdoc =
- '' +
- t._POSignalsUtils.Util.hashMini(crypto.getRandomValues(new Uint32Array(10)))),
- !!e.contentWindow
- );
- }),
- this.addStealthTest('index_chrome_too_high', function () {
- var t =
- 'cookieStore' in window
- ? 'cookieStore'
- : 'ondevicemotion' in window
- ? 'ondevicemotion'
- : 'speechSynthesis',
- e = [];
- for (var n in window) e.push(n);
- return e.indexOf('chrome') > e.indexOf(t);
- }),
- this.addStealthTest('chrome_runtime_functions_invalid', function () {
- if (!('chrome' in window && 'runtime' in window.chrome)) return !1;
- try {
- return (
- 'prototype' in window.chrome.runtime.sendMessage ||
- 'prototype' in window.chrome.runtime.connect ||
- (new window.chrome.runtime.sendMessage(),
- new window.chrome.runtime.connect(),
- !0)
- );
- } catch (t) {
- return 'TypeError' != t.constructor.name;
- }
- }),
- this.addStealthTest('Function_prototype_toString_invalid_typeError', function () {
- var t = new n.StackTraceTester();
- return (
- t.isInvalidStackTraceSize(Function.prototype.toString) ||
- t.isInvalidStackTraceSize(function () {})
- );
- }),
- this.result
- );
- }),
- (n.prototype.addStealthTest = function (e, n) {
- if (!this.propertyBlackList.has(e))
- try {
- this.result[e] = n();
- } catch (n) {
- t._POSignalsUtils.Logger.warn('stealth test ' + e + ' failed', n);
- }
- }),
- (n.StackTraceTester = (function () {
- function t() {}
- return (
- (t.prototype.isInvalidStackTraceSize = function (t) {
- var n = this;
- try {
- return (
- (this.you = function () {
- return Object.create(t).toString();
- }),
- (this.cant = function () {
- return n.you();
- }),
- (this.hide = function () {
- return n.cant();
- }),
- this.hide(),
- !0
- );
- } catch (t) {
- var i = t.stack.split('\n'),
- r = !/at Object\.apply/.test(i[1]),
- a = 'TypeError' == t.constructor.name && i.length >= 5,
- o = 'chrome' in window || e.Metadata.detectChromium();
- return (
- !(
- !a ||
- !o ||
- (r &&
- /at Function\.toString/.test(i[1]) &&
- /\.you/.test(i[2]) &&
- /\.cant/.test(i[3]) &&
- /\.hide/.test(i[4]))
- ) || !a
- );
- }
- }),
- t
- );
- })()),
- n
- );
- })();
- e.DetectStealth = n;
- })(t._POSignalsMetadata || (t._POSignalsMetadata = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- !(function (t) {
- var e = (function () {
- function t() {}
- return (
- (t.isPrivateMode = function () {
- return new Promise(function (t) {
- var e,
- n,
- i = function () {
- return t(!0);
- },
- r = function () {
- return t(!1);
- };
- try {
- if (
- ((n =
- navigator &&
- /(?=.*(opera|chrome)).*/i.test(navigator.userAgent) &&
- navigator.storage &&
- navigator.storage.estimate) &&
- navigator.storage
- .estimate()
- .then(function (t) {
- t.quota < 12e7 ? i() : r();
- })
- .catch(function (t) {
- r();
- }),
- n)
- )
- return;
- if (
- (function () {
- var t = 'MozAppearance' in document.documentElement.style;
- if (t)
- if (null == indexedDB) i();
- else {
- var e = indexedDB.open('inPrivate');
- (e.onsuccess = r), (e.onerror = i);
- }
- return t;
- })()
- )
- return;
- if (
- (function () {
- var t =
- navigator &&
- navigator.userAgent &&
- navigator.userAgent.match(/Version\/([0-9\._]+).*Safari/);
- if (t) {
- if (parseInt(t[1], 10) < 11)
- return (function () {
- try {
- localStorage.length
- ? r()
- : (localStorage.setItem('inPrivate', '0'),
- localStorage.removeItem('inPrivate'),
- r());
- } catch (t) {
- navigator.cookieEnabled ? i() : r();
- }
- return !0;
- })();
- try {
- window.openDatabase(null, null, null, null), r();
- } catch (t) {
- i();
- }
- }
- return !!t;
- })()
- )
- return;
- if (
- ((e = !window.indexedDB && (window.PointerEvent || window.MSPointerEvent)) &&
- i(),
- e)
- )
- return;
- } catch (t) {}
- return r();
- });
- }),
- t
- );
- })();
- t.Incognito = e;
- })(t._POSignalsMetadata || (t._POSignalsMetadata = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {}));
- var __extends =
- (this && this.__extends) ||
- (function () {
- var t = function (e, n) {
- return (t =
- Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array &&
- function (t, e) {
- t.__proto__ = e;
- }) ||
- function (t, e) {
- for (var n in e) e.hasOwnProperty(n) && (t[n] = e[n]);
- })(e, n);
- };
- return function (e, n) {
- function i() {
- this.constructor = e;
- }
- t(e, n),
- (e.prototype = null === n ? Object.create(n) : ((i.prototype = n.prototype), new i()));
- };
- })();
- (__awaiter =
- (this && this.__awaiter) ||
- function (t, e, n, i) {
- return new (n || (n = Promise))(function (r, a) {
- function o(t) {
- try {
- u(i.next(t));
- } catch (t) {
- a(t);
- }
- }
- function s(t) {
- try {
- u(i.throw(t));
- } catch (t) {
- a(t);
- }
- }
- function u(t) {
- var e;
- t.done
- ? r(t.value)
- : ((e = t.value),
- e instanceof n
- ? e
- : new n(function (t) {
- t(e);
- })).then(o, s);
- }
- u((i = i.apply(t, e || [])).next());
- });
- }),
- (__generator =
- (this && this.__generator) ||
- function (t, e) {
- var n,
- i,
- r,
- a,
- o = {
- label: 0,
- sent: function () {
- if (1 & r[0]) throw r[1];
- return r[1];
- },
- trys: [],
- ops: [],
- };
- return (
- (a = { next: s(0), throw: s(1), return: s(2) }),
- 'function' == typeof Symbol &&
- (a[Symbol.iterator] = function () {
- return this;
- }),
- a
- );
- function s(a) {
- return function (s) {
- return (function (a) {
- if (n) throw new TypeError('Generator is already executing.');
- for (; o; )
- try {
- if (
- ((n = 1),
- i &&
- (r =
- 2 & a[0]
- ? i.return
- : a[0]
- ? i.throw || ((r = i.return) && r.call(i), 0)
- : i.next) &&
- !(r = r.call(i, a[1])).done)
- )
- return r;
- switch (((i = 0), r && (a = [2 & a[0], r.value]), a[0])) {
- case 0:
- case 1:
- r = a;
- break;
- case 4:
- return o.label++, { value: a[1], done: !1 };
- case 5:
- o.label++, (i = a[1]), (a = [0]);
- continue;
- case 7:
- (a = o.ops.pop()), o.trys.pop();
- continue;
- default:
- if (
- !(r = (r = o.trys).length > 0 && r[r.length - 1]) &&
- (6 === a[0] || 2 === a[0])
- ) {
- o = 0;
- continue;
- }
- if (3 === a[0] && (!r || (a[1] > r[0] && a[1] < r[3]))) {
- o.label = a[1];
- break;
- }
- if (6 === a[0] && o.label < r[1]) {
- (o.label = r[1]), (r = a);
- break;
- }
- if (r && o.label < r[2]) {
- (o.label = r[2]), o.ops.push(a);
- break;
- }
- r[2] && o.ops.pop(), o.trys.pop();
- continue;
- }
- a = e.call(t, o);
- } catch (t) {
- (a = [6, t]), (i = 0);
- } finally {
- n = r = 0;
- }
- if (5 & a[0]) throw a[1];
- return { value: a[0] ? a[1] : void 0, done: !0 };
- })([a, s]);
- };
- }
- }),
- (__assign =
- (this && this.__assign) ||
- function () {
- return (__assign =
- Object.assign ||
- function (t) {
- for (var e, n = 1, i = arguments.length; n < i; n++)
- for (var r in (e = arguments[n]))
- Object.prototype.hasOwnProperty.call(e, r) && (t[r] = e[r]);
- return t;
- }).apply(this, arguments);
- });
- !(function (t) {
- !(function (t) {
- (t[(t.Unknown = 0)] = 'Unknown'),
- (t[(t.FlingRight = 1)] = 'FlingRight'),
- (t[(t.FlingLeft = 2)] = 'FlingLeft'),
- (t[(t.FlingUp = 3)] = 'FlingUp'),
- (t[(t.FlingDown = 4)] = 'FlingDown'),
- (t[(t.Diagonal = 5)] = 'Diagonal'),
- (t[(t.ScrollRight = 6)] = 'ScrollRight'),
- (t[(t.ScrollLeft = 7)] = 'ScrollLeft'),
- (t[(t.ScrollUp = 8)] = 'ScrollUp'),
- (t[(t.ScrollDown = 9)] = 'ScrollDown'),
- (t[(t.Tap = 10)] = 'Tap'),
- (t[(t.DoubleTap = 11)] = 'DoubleTap');
- })(t.GestureType || (t.GestureType = {}));
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- 'use strict';
- var e = (function () {
- function t(t, e) {
- (this.handler = t), (this.isOnce = e), (this.isExecuted = !1);
- }
- return (
- (t.prototype.execute = function (t, e, n) {
- if (!this.isOnce || !this.isExecuted) {
- this.isExecuted = !0;
- var i = this.handler;
- t
- ? setTimeout(function () {
- i.apply(e, n);
- }, 1)
- : i.apply(e, n);
- }
- }),
- t
- );
- })(),
- n = (function () {
- function t() {
- (this._wrap = new o(this)), (this._subscriptions = new Array());
- }
- return (
- (t.prototype.subscribe = function (t) {
- t && this._subscriptions.push(new e(t, !1));
- }),
- (t.prototype.sub = function (t) {
- this.subscribe(t);
- }),
- (t.prototype.one = function (t) {
- t && this._subscriptions.push(new e(t, !0));
- }),
- (t.prototype.has = function (t) {
- if (t)
- for (var e = 0, n = this._subscriptions; e < n.length; e++) {
- if (n[e].handler == t) return !0;
- }
- return !1;
- }),
- (t.prototype.unsubscribe = function (t) {
- if (t)
- for (var e = 0; e < this._subscriptions.length; e++) {
- if (this._subscriptions[e].handler == t) {
- this._subscriptions.splice(e, 1);
- break;
- }
- }
- }),
- (t.prototype.unsub = function (t) {
- this.unsubscribe(t);
- }),
- (t.prototype._dispatch = function (t, e, n) {
- for (var i = 0; i < this._subscriptions.length; i++) {
- var r = this._subscriptions[i];
- if (r.isOnce) {
- if (!0 === r.isExecuted) continue;
- this._subscriptions.splice(i, 1), i--;
- }
- r.execute(t, e, n);
- }
- }),
- (t.prototype.asEvent = function () {
- return this._wrap;
- }),
- t
- );
- })();
- t.DispatcherBase = n;
- var i = (function (t) {
- function e() {
- return (null !== t && t.apply(this, arguments)) || this;
- }
- return (
- __extends(e, t),
- (e.prototype.dispatch = function (t, e) {
- this._dispatch(!1, this, arguments);
- }),
- (e.prototype.dispatchAsync = function (t, e) {
- this._dispatch(!0, this, arguments);
- }),
- e
- );
- })(n);
- t.EventDispatcher = i;
- var r = (function (t) {
- function e() {
- return (null !== t && t.apply(this, arguments)) || this;
- }
- return (
- __extends(e, t),
- (e.prototype.dispatch = function (t) {
- this._dispatch(!1, this, arguments);
- }),
- (e.prototype.dispatchAsync = function (t) {
- this._dispatch(!0, this, arguments);
- }),
- e
- );
- })(n),
- a = (function (t) {
- function e() {
- return (null !== t && t.apply(this, arguments)) || this;
- }
- return (
- __extends(e, t),
- (e.prototype.dispatch = function () {
- this._dispatch(!1, this, arguments);
- }),
- (e.prototype.dispatchAsync = function () {
- this._dispatch(!0, this, arguments);
- }),
- e
- );
- })(n),
- o = (function () {
- function t(t) {
- (this._subscribe = function (e) {
- return t.subscribe(e);
- }),
- (this._unsubscribe = function (e) {
- return t.unsubscribe(e);
- }),
- (this._one = function (e) {
- return t.one(e);
- }),
- (this._has = function (e) {
- return t.has(e);
- });
- }
- return (
- (t.prototype.subscribe = function (t) {
- this._subscribe(t);
- }),
- (t.prototype.sub = function (t) {
- this.subscribe(t);
- }),
- (t.prototype.unsubscribe = function (t) {
- this._unsubscribe(t);
- }),
- (t.prototype.unsub = function (t) {
- this.unsubscribe(t);
- }),
- (t.prototype.one = function (t) {
- this._one(t);
- }),
- (t.prototype.has = function (t) {
- return this._has(t);
- }),
- t
- );
- })(),
- s = (function () {
- function t() {
- this._events = {};
- }
- return (
- (t.prototype.get = function (t) {
- var e = this._events[t];
- return e || ((e = this.createDispatcher()), (this._events[t] = e), e);
- }),
- (t.prototype.remove = function (t) {
- this._events[t] = null;
- }),
- t
- );
- })(),
- u = (function (t) {
- function e() {
- return (null !== t && t.apply(this, arguments)) || this;
- }
- return (
- __extends(e, t),
- (e.prototype.createDispatcher = function () {
- return new i();
- }),
- e
- );
- })(s),
- c = (function (t) {
- function e() {
- return (null !== t && t.apply(this, arguments)) || this;
- }
- return (
- __extends(e, t),
- (e.prototype.createDispatcher = function () {
- return new r();
- }),
- e
- );
- })(s),
- l = (function (t) {
- function e() {
- return (null !== t && t.apply(this, arguments)) || this;
- }
- return (
- __extends(e, t),
- (e.prototype.createDispatcher = function () {
- return new a();
- }),
- e
- );
- })(s);
- (function () {
- function t() {
- this._events = new u();
- }
- Object.defineProperty(t.prototype, 'events', {
- get: function () {
- return this._events;
- },
- enumerable: !1,
- configurable: !0,
- }),
- (t.prototype.subscribe = function (t, e) {
- this._events.get(t).subscribe(e);
- }),
- (t.prototype.sub = function (t, e) {
- this.subscribe(t, e);
- }),
- (t.prototype.unsubscribe = function (t, e) {
- this._events.get(t).unsubscribe(e);
- }),
- (t.prototype.unsub = function (t, e) {
- this.unsubscribe(t, e);
- }),
- (t.prototype.one = function (t, e) {
- this._events.get(t).one(e);
- }),
- (t.prototype.has = function (t, e) {
- return this._events.get(t).has(e);
- });
- })(),
- (function () {
- function t() {
- this._events = new c();
- }
- Object.defineProperty(t.prototype, 'events', {
- get: function () {
- return this._events;
- },
- enumerable: !1,
- configurable: !0,
- }),
- (t.prototype.subscribe = function (t, e) {
- this._events.get(t).subscribe(e);
- }),
- (t.prototype.sub = function (t, e) {
- this.subscribe(t, e);
- }),
- (t.prototype.one = function (t, e) {
- this._events.get(t).one(e);
- }),
- (t.prototype.has = function (t, e) {
- return this._events.get(t).has(e);
- }),
- (t.prototype.unsubscribe = function (t, e) {
- this._events.get(t).unsubscribe(e);
- }),
- (t.prototype.unsub = function (t, e) {
- this.unsubscribe(t, e);
- });
- })(),
- (function () {
- function t() {
- this._events = new l();
- }
- Object.defineProperty(t.prototype, 'events', {
- get: function () {
- return this._events;
- },
- enumerable: !1,
- configurable: !0,
- }),
- (t.prototype.one = function (t, e) {
- this._events.get(t).one(e);
- }),
- (t.prototype.has = function (t, e) {
- return this._events.get(t).has(e);
- }),
- (t.prototype.subscribe = function (t, e) {
- this._events.get(t).subscribe(e);
- }),
- (t.prototype.sub = function (t, e) {
- this.subscribe(t, e);
- }),
- (t.prototype.unsubscribe = function (t, e) {
- this._events.get(t).unsubscribe(e);
- }),
- (t.prototype.unsub = function (t, e) {
- this.unsubscribe(t, e);
- });
- })();
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(t) {
- (this._isStarted = !1),
- (this._isEventsStarted = !1),
- (this._gestureTimestamps = []),
- (this._maxSensorSamples = 0),
- (this._sensorsTimestampDeltaInMillis = 0),
- (this._accelerometerList = []),
- (this._gyroscopeList = []),
- (this._linearAccelerometerList = []),
- (this._rotationList = []),
- (this.orientationImplementationFix = 1),
- (this.delegate = t),
- window.navigator.userAgent.match(
- /^.*(iPhone|iPad).*(OS\s[0-9]).*(CriOS|Version)\/[.0-9]*\sMobile.*$/i,
- ) && (this.orientationImplementationFix = -1),
- (this.accelerometerUpdateHandle = this.accelerometerUpdate.bind(this)),
- (this.orientationUpdateHandle = this.orientationUpdate.bind(this));
- }
- return (
- Object.defineProperty(e.prototype, 'LAST_GESTURE_SENSOR_TIMEOUT_MILI_SECONDS', {
- get: function () {
- return 3e3;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'accX', {
- get: function () {
- return this._accX;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'accY', {
- get: function () {
- return this._accY;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'accZ', {
- get: function () {
- return this._accZ;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'lienarAccX', {
- get: function () {
- return this._lienarAccX;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'lienarAccY', {
- get: function () {
- return this._lienarAccY;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'lienarAccZ', {
- get: function () {
- return this._lienarAccZ;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'isStarted', {
- get: function () {
- return this._isStarted;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'rotX', {
- get: function () {
- return this._rotX;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'rotY', {
- get: function () {
- return this._rotY;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'rotZ', {
- get: function () {
- return this._rotZ;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'maxSensorSamples', {
- get: function () {
- return this._maxSensorSamples;
- },
- set: function (t) {
- this._maxSensorSamples = t;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'sensorsTimestampDeltaInMillis', {
- get: function () {
- return this._sensorsTimestampDeltaInMillis;
- },
- set: function (t) {
- this._sensorsTimestampDeltaInMillis = t;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'accelerometerList', {
- get: function () {
- return this.getRelevantSensorSamples(this._accelerometerList);
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'gyroscopeList', {
- get: function () {
- return this.getRelevantSensorSamples(this._gyroscopeList);
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'linearAccelerometerList', {
- get: function () {
- return this.getRelevantSensorSamples(this._linearAccelerometerList);
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'rotationList', {
- get: function () {
- return this._rotationList;
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.start = function () {
- this._isStarted ||
- ((this._isStarted = !0), t._POSignalsUtils.Logger.debug('Sensor events started...'));
- }),
- (e.prototype.getRotationListCopy = function () {
- return this._rotationList ? Array.from(this._rotationList) : [];
- }),
- (e.prototype.stop = function () {
- this._isStarted &&
- (void 0 != window.DeviceMotionEvent &&
- window.removeEventListener('devicemotion', this.accelerometerUpdateHandle, !0),
- window.DeviceOrientationEvent &&
- window.removeEventListener('deviceorientation', this.orientationUpdateHandle, !0),
- (this._isStarted = !1),
- t._POSignalsUtils.Logger.debug('Sensor events stopped'));
- }),
- (e.prototype.getRelevantSensorSamples = function (e) {
- if (
- 0 == e.length ||
- this._sensorsTimestampDeltaInMillis < 1 ||
- 0 == this._gestureTimestamps.length
- )
- return e;
- for (var n = new Map(), i = null, r = 0, a = 0; a < e.length; a++)
- for (var o = 0; o < this._gestureTimestamps.length; o++)
- (r = e[a].timestamp) >=
- (i = this._gestureTimestamps[o]).start - this._sensorsTimestampDeltaInMillis &&
- r <= i.end + this._sensorsTimestampDeltaInMillis &&
- n.set(e[a].timestamp, e[a]);
- return t._POSignalsUtils.Util.getValuesOfMap(n);
- }),
- (e.prototype.stopEvents = function () {
- this._isEventsStarted &&
- (void 0 != window.DeviceMotionEvent &&
- window.removeEventListener('devicemotion', this.accelerometerUpdateHandle, !0),
- window.DeviceOrientationEvent &&
- window.removeEventListener('deviceorientation', this.orientationUpdateHandle, !0),
- (this._isEventsStarted = !1),
- t._POSignalsUtils.Logger.debug('Sensor events stopped listening'));
- }),
- (e.prototype.startEvents = function () {
- this._isEventsStarted ||
- (void 0 != window.DeviceMotionEvent
- ? this.delegate.addEventListener(
- window,
- 'devicemotion',
- this.accelerometerUpdateHandle,
- !0,
- )
- : t._POSignalsUtils.Logger.warn('DeviceMotion not supported!'),
- window.DeviceOrientationEvent
- ? this.delegate.addEventListener(
- window,
- 'deviceorientation',
- this.orientationUpdateHandle,
- !0,
- )
- : t._POSignalsUtils.Logger.warn('DeviceOrientation not supported!'),
- t._POSignalsUtils.Logger.debug('Sensor events start listening...'),
- (this._isEventsStarted = !0));
- }),
- (e.prototype.reset = function () {
- (this._accelerometerList = []),
- (this._gyroscopeList = []),
- (this._linearAccelerometerList = []),
- (this._rotationList = []),
- this._gestureTimestamps.length > 0
- ? (this._gestureTimestamps = [
- this._gestureTimestamps[this._gestureTimestamps.length - 1],
- ])
- : (this._gestureTimestamps = []),
- (this._accX = 0),
- (this._accY = 0),
- (this._accZ = 0),
- (this._rotX = 0),
- (this._rotY = 0),
- (this._rotZ = 0);
- }),
- (e.prototype.onGesture = function (t) {
- this._isEventsStarted || this.startEvents(),
- t.events.length > 1 &&
- this._gestureTimestamps.push({
- start: t.events[0].eventTs,
- end: t.events[t.events.length - 1].eventTs,
- });
- }),
- (e.prototype.puaseSensorsCollectionIfNoActivity = function (t) {
- return (this._gestureTimestamps.length > 0
- ? this._gestureTimestamps[this._gestureTimestamps.length - 1].end
- : 0) > 0
- ? Math.abs(t - this._gestureTimestamps[this._gestureTimestamps.length - 1].end) >
- this.LAST_GESTURE_SENSOR_TIMEOUT_MILI_SECONDS && (this.stopEvents(), !0)
- : (this.stopEvents(), !0);
- }),
- (e.prototype.getDeviceAcceleration = function (t) {
- return t && null != t.x && null != t.y && null != t.z ? t : null;
- }),
- (e.prototype.accelerometerUpdate = function (e) {
- try {
- if (
- !this.delegate.collectBehavioralData() ||
- this.puaseSensorsCollectionIfNoActivity(t._POSignalsUtils.Util.now())
- )
- return;
- var n = this.getDeviceAcceleration(e.accelerationIncludingGravity);
- n &&
- ((this._accX = n.x * this.orientationImplementationFix),
- (this._accY = n.y * this.orientationImplementationFix),
- (this._accZ = n.z),
- this.safeAddSensorSample(
- {
- x: this._accX,
- y: this._accY,
- z: this._accX,
- timestamp: t._POSignalsUtils.Util.now(),
- },
- this._accelerometerList,
- ));
- var i = this.getDeviceAcceleration(e.acceleration);
- i &&
- ((this._lienarAccX = i.x * this.orientationImplementationFix),
- (this._lienarAccY = i.y * this.orientationImplementationFix),
- (this._lienarAccZ = i.z),
- this.safeAddSensorSample(
- {
- x: this._lienarAccX,
- y: this._lienarAccY,
- z: this._lienarAccZ,
- timestamp: t._POSignalsUtils.Util.now(),
- },
- this._linearAccelerometerList,
- )),
- e.rotationRate &&
- null != e.rotationRate.alpha &&
- null != e.rotationRate.beta &&
- null != e.rotationRate.gamma &&
- ((this._rotX = e.rotationRate.alpha),
- (this._rotY = e.rotationRate.beta),
- (this._rotZ = e.rotationRate.gamma),
- this.safeAddSensorSample(
- {
- x: this._rotX,
- y: this._rotY,
- z: this._rotZ,
- timestamp: t._POSignalsUtils.Util.now(),
- },
- this._gyroscopeList,
- ));
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in accelerometer handler', e);
- }
- }),
- (e.prototype.orientationUpdate = function (e) {
- try {
- if (
- !this.delegate.collectBehavioralData() ||
- this.puaseSensorsCollectionIfNoActivity(t._POSignalsUtils.Util.now())
- )
- return;
- null != e.alpha &&
- null != e.beta &&
- null != e.gamma &&
- this.safeAddSensorSample(
- { x: e.alpha, y: e.beta, z: e.gamma, timestamp: t._POSignalsUtils.Util.now() },
- this._rotationList,
- );
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in orientation handler', e);
- }
- }),
- (e.prototype.safeAddSensorSample = function (t, e) {
- this.maxSensorSamples > e.length && e.push(t);
- }),
- e
- );
- })();
- t.Sensors = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e() {
- this._pointerParams = new t.PointerParams();
- }
- return (
- Object.defineProperty(e, 'instance', {
- get: function () {
- return e._instance || (e._instance = new e()), e._instance;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'pointerParams', {
- get: function () {
- return this._pointerParams;
- },
- enumerable: !1,
- configurable: !0,
- }),
- e
- );
- })();
- t.PointerConfig = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e;
- !(function (t) {
- (t[(t.Up = 1)] = 'Up'),
- (t[(t.Down = 2)] = 'Down'),
- (t[(t.Left = 3)] = 'Left'),
- (t[(t.Right = 4)] = 'Right');
- })(e || (e = {}));
- var n = (function () {
- function n(e, n) {
- (this.BEHAVIORAL_TYPE = 'gestures'),
- (this._isStarted = !1),
- (this._onGesture = new t.EventDispatcher()),
- (this.touchSnapshotsMap = new Map()),
- (this.snapshotStartTime = new Map()),
- (this.delegate = e),
- (this.sensors = n),
- (this.touchStartHandler = this.touchStart.bind(this)),
- (this.touchMoveHandler = this.touchMove.bind(this)),
- (this.touchEndHandler = this.touchEnd.bind(this)),
- (this.touchCancelHandler = this.touchCancel.bind(this));
- }
- return (
- Object.defineProperty(n.prototype, 'onGesture', {
- get: function () {
- return this._onGesture.asEvent();
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'isStarted', {
- get: function () {
- return this._isStarted;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'SCROLL_MIN_DURATION', {
- get: function () {
- return 500;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'SWIPE_MAX_ANGLE', {
- get: function () {
- return 45;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'TAP_MOVEMENT_TRESHOLD', {
- get: function () {
- return 10;
- },
- enumerable: !1,
- configurable: !0,
- }),
- (n.prototype.countEvents = function (t) {
- for (var e = {}, n = 0, i = t; n < i.length; n++) {
- var r = i[n];
- e[r.type] = (e[r.type] || 0) + 1;
- }
- return e;
- }),
- (n.prototype.clearTouchSnapshots = function (t) {
- this.touchSnapshotsMap.delete(t), this.snapshotStartTime.delete(t);
- }),
- (n.prototype.getTouchSnapshots = function (t) {
- var e;
- return (
- this.touchSnapshotsMap.has(t)
- ? (e = this.touchSnapshotsMap.get(t))
- : ((e = []), this.touchSnapshotsMap.set(t, e)),
- e
- );
- }),
- (n.prototype.isEmpty = function () {
- return 0 === this.touchSnapshotsMap.size;
- }),
- (n.prototype.start = function () {
- this._isStarted ||
- (this.delegate.addEventListener(document, 'touchstart', this.touchStartHandler),
- this.delegate.addEventListener(document, 'touchmove', this.touchMoveHandler),
- this.delegate.addEventListener(document, 'touchend', this.touchEndHandler),
- this.delegate.addEventListener(document, 'touchcancel', this.touchCancelHandler),
- (this._isStarted = !0));
- }),
- (n.prototype.stop = function () {
- this._isStarted &&
- (document.removeEventListener('touchstart', this.touchStartHandler),
- document.removeEventListener('touchmove', this.touchMoveHandler),
- document.removeEventListener('touchend', this.touchEndHandler),
- document.removeEventListener('touchcancel', this.touchCancelHandler),
- (this._isStarted = !1));
- }),
- (n.prototype.touchStart = function (e) {
- try {
- if (!this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE)) return;
- if (t.PointerConfig.instance.pointerParams.eventsToIgnore.has(e.type)) return;
- t._POSignalsUtils.Logger.debug('touchstart(' + e.changedTouches.length + ')', e),
- e.changedTouches.length > 0 && this.pushSnapshot(e);
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in touchStart handler', e);
- }
- }),
- (n.prototype.touchMove = function (e) {
- try {
- if (!this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE)) return;
- if (t.PointerConfig.instance.pointerParams.eventsToIgnore.has(e.type)) return;
- t._POSignalsUtils.Logger.debug('touchmove(' + e.changedTouches.length + ')', e),
- e.changedTouches.length > 0 && this.pushSnapshot(e);
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in touchMove handler', e);
- }
- }),
- (n.prototype.touchEnd = function (e) {
- try {
- if (!this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE))
- return void this._onGesture.dispatch(this, null);
- if (t.PointerConfig.instance.pointerParams.eventsToIgnore.has(e.type)) return;
- t._POSignalsUtils.Logger.debug('touchend(' + e.changedTouches.length + ')', e),
- this.gestureEnd(e);
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in touchEnd handler', e);
- }
- }),
- (n.prototype.touchCancel = function (e) {
- try {
- if (!this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE))
- return void this._onGesture.dispatch(this, null);
- if (t.PointerConfig.instance.pointerParams.eventsToIgnore.has(e.type)) return;
- t._POSignalsUtils.Logger.debug('touchcancel(' + e.changedTouches.length + ')', e),
- this.gestureEnd(e);
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in touchCancel handler', e);
- }
- }),
- (n.prototype.gestureEnd = function (e) {
- e.changedTouches.length > 0 && this.pushSnapshot(e);
- for (var n = 0; n < e.changedTouches.length; n++) {
- var i = e.changedTouches.item(n),
- r = this.getTouchSnapshots(i.identifier);
- r.length > 0 &&
- (this.isTap(r)
- ? this.dispatchGesture(t.GestureType.Tap, i.identifier)
- : this.dispatchGesture(this.calcGestureType(r), i.identifier));
- }
- }),
- (n.prototype.calcGestureType = function (n) {
- var i,
- r = this.getDirection(n);
- if (this.isFling(n))
- switch (r) {
- case e.Up:
- i = t.GestureType.FlingUp;
- break;
- case e.Right:
- i = t.GestureType.FlingRight;
- break;
- case e.Down:
- i = t.GestureType.FlingDown;
- break;
- case e.Left:
- i = t.GestureType.FlingLeft;
- }
- else if (this.isScroll(n))
- switch (r) {
- case e.Up:
- i = t.GestureType.ScrollUp;
- break;
- case e.Right:
- i = t.GestureType.ScrollRight;
- break;
- case e.Down:
- i = t.GestureType.ScrollDown;
- break;
- case e.Left:
- i = t.GestureType.ScrollLeft;
- }
- return i;
- }),
- (n.prototype.pushSnapshot = function (e) {
- if (e.changedTouches && e.changedTouches.length > 0)
- for (
- var n,
- i = function () {
- var i = e.changedTouches.item(a);
- (n = i.radiusX && i.radiusY ? (i.radiusX + i.radiusY) / 2 : null),
- r.snapshotStartTime.has(i.identifier) ||
- r.snapshotStartTime.set(i.identifier, new Date().getTime());
- var o = r.getTouchSnapshots(i.identifier);
- o.length < t.PointerConfig.instance.pointerParams.maxSnapshotsCount &&
- o.push({
- type: e.type,
- eventTs: e.timeStamp,
- epochTs: new Date().getTime(),
- relativeX: i.screenX,
- relativeY: i.screenY,
- x: i.clientX,
- y: i.clientY,
- pressure: i.force,
- size: n,
- xaccelerometer: r.sensors.accX,
- yaccelerometer: r.sensors.accY,
- zaccelerometer: r.sensors.accZ,
- xlinearaccelerometer: r.sensors.lienarAccX,
- ylinearaccelerometer: r.sensors.lienarAccY,
- zlinearaccelerometer: r.sensors.lienarAccZ,
- xrotation: r.sensors.rotX,
- yrotation: r.sensors.rotY,
- zrotation: r.sensors.rotZ,
- radiusX: i.radiusX,
- radiusY: i.radiusY,
- rotationAngle: i.rotationAngle,
- pageX: i.pageX,
- pageY: i.pageY,
- getX: function () {
- return i.screenX;
- },
- getY: function () {
- return i.screenY;
- },
- });
- },
- r = this,
- a = 0;
- a < e.changedTouches.length;
- a++
- )
- i();
- }),
- (n.prototype.dispatchGesture = function (e, n) {
- var i = this.touchSnapshotsMap.get(n) || [],
- r = i.filter(function (t) {
- return 'touchmove' === t.type;
- });
- this._onGesture.dispatch(this, {
- epochTs: this.snapshotStartTime.get(n) || 0,
- counter: this.delegate.gesturesCounter,
- type: e,
- events: i,
- eventCounters: this.countEvents(i),
- duration: this.delegate.getInteractionDuration(i),
- additionalData: this.delegate.additionalData,
- uiControl: void 0,
- timeProximity: t._POSignalsUtils.Util.calculateMeanTimeDeltasBetweenEvents(r),
- meanEuclidean: t._POSignalsUtils.Util.calculateMeanDistanceBetweenPoints(r),
- reduction: {},
- }),
- this.clearTouchSnapshots(n);
- }),
- (n.prototype.isTap = function (t) {
- var e = Math.abs(t[0].x - t[1].x),
- n = Math.abs(t[0].y - t[1].y);
- return (
- 2 == t.length && e < this.TAP_MOVEMENT_TRESHOLD && n < this.TAP_MOVEMENT_TRESHOLD
- );
- }),
- (n.prototype.isFling = function (t) {
- return (
- t.length > 1 && t[t.length - 1].eventTs - t[0].eventTs < this.SCROLL_MIN_DURATION
- );
- }),
- (n.prototype.isScroll = function (t) {
- return (
- t.length > 1 && t[t.length - 1].eventTs - t[0].eventTs > this.SCROLL_MIN_DURATION
- );
- }),
- (n.prototype.getDirection = function (t) {
- var n = this.calcAngle(t[0], t[t.length - 1]);
- return n > 90 - this.SWIPE_MAX_ANGLE && n <= 90 + this.SWIPE_MAX_ANGLE
- ? e.Up
- : n > 180 - this.SWIPE_MAX_ANGLE && n <= 180 + this.SWIPE_MAX_ANGLE
- ? e.Right
- : n > 270 - this.SWIPE_MAX_ANGLE && n <= 270 + this.SWIPE_MAX_ANGLE
- ? e.Down
- : e.Left;
- }),
- (n.prototype.calcAngle = function (t, e) {
- return (180 * Math.atan2(e.y - t.y, e.x - t.x)) / Math.PI + 180;
- }),
- n
- );
- })();
- t.GestureEvents = n;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(t) {
- (this.key = t), (this.cache = this.loadFromStorage());
- }
- return (
- (e.prototype.loadFromStorage = function () {
- var t = e.sessionStorage.getItem(this.key);
- return t || (t = JSON.stringify([])), JSON.parse(t);
- }),
- (e.prototype.get = function () {
- return this.cache;
- }),
- Object.defineProperty(e.prototype, 'length', {
- get: function () {
- return this.cache.length;
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.push = function (t) {
- var n = this.cache.push(t);
- return e.sessionStorage.setItem(this.key, JSON.stringify(this.cache)), n;
- }),
- (e.prototype.set = function (t) {
- (this.cache = t), e.sessionStorage.setItem(this.key, JSON.stringify(this.cache));
- }),
- (e.prototype.remove = function (t) {
- this.cache.splice(t, 1), e.sessionStorage.setItem(this.key, JSON.stringify(this.cache));
- }),
- (e.prototype.concat = function (t) {
- return this.cache.concat(t);
- }),
- (e.prototype.clear = function () {
- (this.cache = []), e.sessionStorage.removeItem(this.key);
- }),
- (e.sessionStorage = t._POSignalsStorage.SessionStorage.instance.sessionStorage),
- e
- );
- })();
- t.StorageArray = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e() {
- (this.MAX_TAGS = 10),
- (this._tags = new t.StorageArray(t._POSignalsUtils.Constants.CAPTURED_TAGS));
- }
- return (
- Object.defineProperty(e, 'instance', {
- get: function () {
- return e._instance || (e._instance = new e()), e._instance;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'tags', {
- get: function () {
- return this._tags.get();
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'disableTags', {
- set: function (t) {
- this._disableTags = t;
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.setTag = function (e, n) {
- var i;
- if (!this._disableTags)
- if (t.PointerConfig.instance.pointerParams.enabled)
- if (e) {
- var r = t.PointerConfig.instance.pointerParams.tagsBlacklistRegex;
- if (r && (e.match(r) || (null === n || void 0 === n ? void 0 : n.match(r))))
- t._POSignalsUtils.Logger.info('Tag name or value is blacklisted');
- else if (!(this._tags.length >= this.MAX_TAGS)) {
- this._tags.push({
- name: e.trim(),
- value:
- (null === (i = null === n || void 0 === n ? void 0 : n.trim) || void 0 === i
- ? void 0
- : i.call(n)) || void 0,
- epochTs: Date.now(),
- timestamp: Date.now(),
- });
- var a = n ? e + ':' + n : e;
- t._POSignalsUtils.Logger.info('Add tag: ' + a);
- }
- } else t._POSignalsUtils.Logger.info("Can't add tag, missing name");
- else t._POSignalsUtils.Logger.info("Can't add tag, PingOneSignals SDK is disabled");
- }),
- (e.prototype.reset = function () {
- this._tags.clear();
- }),
- e
- );
- })();
- t.Tags = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(t) {
- this.client = t;
- }
- return (
- (e.prototype.calculateStrategyResult = function (e, n) {
- return {
- shouldCollect:
- this.client.getBufferSize() < t.PointerConfig.instance.pointerParams.bufferSize,
- };
- }),
- e
- );
- })();
- t.FirstInteractionsStrategy = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e;
- !(function (t) {
- (t[(t.RICH = 3)] = 'RICH'),
- (t[(t.CLICK = 2)] = 'CLICK'),
- (t[(t.MOVE = 1)] = 'MOVE'),
- (t[(t.POOR = 0)] = 'POOR');
- })(e || (e = {}));
- var n = (function () {
- function n(t) {
- (this.client = t),
- (this.MAX_INTERACTIONS_PER_TYPE = 5),
- (this.MAX_MOUSE_AND_GESTURE = this.MAX_INTERACTIONS_PER_TYPE + 1),
- (this.RICH_MOUSE_MOVES_AMOUNT = 8),
- (this.MIN_KEYBOARD_EVENTS = 4);
- }
- return (
- (n.prototype.isRichMouseInteraction = function (t) {
- return t.mousemove >= this.RICH_MOUSE_MOVES_AMOUNT && this.isClickInteraction(t);
- }),
- (n.prototype.isClickInteraction = function (t) {
- return t.mousedown > 0 && t.mouseup > 0;
- }),
- (n.prototype.isMoveInteraction = function (t) {
- return t.mousemove >= this.RICH_MOUSE_MOVES_AMOUNT;
- }),
- (n.prototype.classifyMouseInteraction = function (n) {
- var i = t._POSignalsUtils.Util.typesCounter(n.events);
- return this.isRichMouseInteraction(i)
- ? e.RICH
- : this.isClickInteraction(i)
- ? e.CLICK
- : this.isMoveInteraction(i)
- ? e.MOVE
- : e.POOR;
- }),
- (n.prototype.findMinPriorityGestureIndex = function (t, e) {
- if (0 === e.length) return -1;
- for (
- var n = t ? -1 : 0, i = t ? t.events.length : e[0].events.length, r = 0;
- r < e.length;
- r++
- )
- e[r].events.length < i && ((n = r), (i = e[r].events.length));
- return n;
- }),
- (n.prototype.calculateStrategyResult = function (t, n) {
- var i = this.client.getBehavioralData();
- switch (n) {
- case 'mouse':
- if (i.mouse.interactions.length < this.MAX_INTERACTIONS_PER_TYPE) {
- if (
- i.touch.interactions.length + i.mouse.interactions.length >=
- this.MAX_MOUSE_AND_GESTURE
- ) {
- var r = this.findMinPriorityGestureIndex(null, i.touch.interactions);
- if (-1 !== r) return { shouldCollect: !0, remove: { type: 'touch', index: r } };
- }
- return { shouldCollect: !0 };
- }
- var a = this.classifyMouseInteraction(t);
- if (a === e.POOR) return { shouldCollect: !1 };
- for (var o = -1, s = a, u = 0; u < i.mouse.interactions.length; u++) {
- var c = this.classifyMouseInteraction(i.mouse.interactions[u]);
- c < s && ((o = u), (s = c));
- }
- return -1 === o
- ? { shouldCollect: !1 }
- : { shouldCollect: !0, remove: { type: 'mouse', index: o } };
- case 'keyboard':
- if (i.keyboard.interactions.length < this.MAX_INTERACTIONS_PER_TYPE)
- return { shouldCollect: !0 };
- if (t.events.length < this.MIN_KEYBOARD_EVENTS) return { shouldCollect: !1 };
- for (u = 0; u < i.keyboard.interactions.length; u++)
- if (i.keyboard.interactions[u].events.length < this.MIN_KEYBOARD_EVENTS)
- return { shouldCollect: !0, remove: { type: 'keyboard', index: u } };
- return { shouldCollect: !1 };
- case 'touch':
- if (
- i.touch.interactions.length < this.MAX_INTERACTIONS_PER_TYPE &&
- i.touch.interactions.length + i.mouse.interactions.length <
- this.MAX_MOUSE_AND_GESTURE
- )
- return { shouldCollect: !0 };
- var l = t,
- d = this.findMinPriorityGestureIndex(l, i.touch.interactions);
- return -1 === d
- ? { shouldCollect: !1 }
- : { shouldCollect: !0, remove: { type: 'touch', index: d } };
- }
- }),
- n
- );
- })();
- t.PriorityStrategy = n;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e;
- !(function (t) {
- (t[(t.FIRST_INTERACTIONS = 0)] = 'FIRST_INTERACTIONS'),
- (t[(t.PRIORITY_INTERACTIONS = 1)] = 'PRIORITY_INTERACTIONS');
- })((e = t.BufferingStrategyType || (t.BufferingStrategyType = {})));
- var n = (function () {
- function n() {}
- return (
- (n.createBufferingStrategy = function (n, i) {
- switch (n) {
- case e.FIRST_INTERACTIONS:
- return new t.FirstInteractionsStrategy(i);
- case e.PRIORITY_INTERACTIONS:
- return new t.PriorityStrategy(i);
- }
- }),
- n
- );
- })();
- t.StrategyFactory = n;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(e) {
- (this.sessionData = e),
- (this.instanceUUID = t._POSignalsUtils.Util.newGuid()),
- (this._isBehavioralDataPaused = !1),
- (this.started = !1),
- (this.initQueue = new t.PromiseQueue(1));
- }
- return (
- (e.instance = function () {
- if (!this._instance) {
- var e = t._POSignalsStorage.SessionStorage.instance;
- if (!document.body)
- throw (
- (t._POSignalsUtils.Logger.error(
- 'PingOne Signals can be started only after DOM Ready!',
- ),
- new Error('PingOne Signals can be started only after DOM Ready!'))
- );
- this._instance = new t.Client(e, t.BufferingStrategyType.PRIORITY_INTERACTIONS);
- }
- return this._instance;
- }),
- (e.prototype.getData = function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (t) {
- switch (t.label) {
- case 0:
- if (!this.startedPromise) throw new Error('SDK not initialized');
- return [4, this.startedPromise];
- case 1:
- return t.sent(), [4, this.dataHandler.getData(Date.now())];
- case 2:
- return [2, t.sent()];
- }
- });
- });
- }),
- (e.prototype.addTag = function (e, n) {
- t.Tags.instance.setTag(e, n);
- }),
- (e.prototype.start = function (e) {
- var n, i;
- return (
- void 0 === e && (e = {}),
- __awaiter(this, void 0, void 0, function () {
- var r, a;
- return __generator(this, function (o) {
- switch (o.label) {
- case 0:
- return null === (n = e.waitForWindowLoad) || void 0 === n || n
- ? [4, this.loadEventPromise()]
- : [3, 2];
- case 1:
- o.sent(), (o.label = 2);
- case 2:
- if (
- ((this.initParams = e),
- this.validateStartParams(e),
- (this.clientVersion = t._POSignalsUtils.Constants.CLIENT_VERSION),
- this.started)
- )
- return t._POSignalsUtils.Logger.warn('SDK already initialized'), [2];
- (this.browserInfo = new t._POSignalsUtils.BrowserInfo()),
- (t._POSignalsUtils.Logger.isLogEnabled =
- !!e.consoleLogEnabled || !!e.devEnv),
- t._POSignalsUtils.Logger.info('Starting Signals SDK...'),
- (t.Tags.instance.disableTags = !!this.initParams.disableTags),
- this.sessionData.setStorageConfig(e),
- (r = t.PointerConfig.instance.pointerParams),
- (a = {
- additionalMediaCodecs: r.additionalMediaCodecs,
- browserInfo: this.browserInfo,
- fingerprintTimeoutMillis: r.fingerprintTimeoutMillis,
- metadataBlackList: new Set(
- r.metadataBlackList.concat(e.deviceAttributesToIgnore),
- ),
- propertyDescriptors: r.propertyDescriptors,
- webRtcUrl: r.webRtcUrl,
- dataPoints: r.metadataDataPoints,
- }),
- (this.metadata = new t._POSignalsMetadata.Metadata(this.sessionData, a)),
- (this.dataHandler = new t.DataHandler(
- this.clientVersion,
- this.instanceUUID,
- this.initParams,
- this.metadata,
- this,
- e.externalIdentifiers,
- this.sessionData,
- )),
- (null === (i = this.initParams.behavioralDataCollection) ||
- void 0 === i ||
- i) &&
- this.refreshListening(),
- e.lazyMetadata || this.metadata.getDeviceAttributes(),
- (this.started = !0);
- try {
- this.logInit(), this.addStartupTags();
- } catch (e) {
- t._POSignalsUtils.Logger.warn('SDK post init failed', e);
- }
- return [2];
- }
- });
- })
- );
- }),
- (e.prototype.logInit = function () {
- var e, n;
- t._POSignalsUtils.Logger.info(
- 'PingOne Signals initialized. ' +
- JSON.stringify(
- {
- timestamp: new Date().getTime(),
- sdkVersion: this.clientVersion,
- instanceUUID: this.instanceUUID,
- tabUUID: this.sessionData.tabUUID,
- },
- null,
- 2,
- ),
- );
- var i = function () {
- return t._POSignalsUtils.Logger.info('Token Ready: ' + window._pingOneSignalsToken);
- },
- r = function () {
- t._POSignalsUtils.Logger.info('Signals token fetch is disabled'),
- (window._pingOneSignalsToken = void 0);
- };
- 'skipped' ===
- (null === (e = window._pingOneSignalsToken) || void 0 === e
- ? void 0
- : e.substring(0, 'skipped'.length))
- ? r()
- : 'uninitialized' !==
- (null === (n = window._pingOneSignalsToken) || void 0 === n
- ? void 0
- : n.substring(0, 'uninitialized'.length)) && i(),
- document.addEventListener('PingOneSignalsTokenReadyEvent', i),
- document.addEventListener('PingOneSignalsTokenSkippedEvent', r);
- }),
- Object.defineProperty(e.prototype, 'isBehavioralDataPaused', {
- get: function () {
- return this._isBehavioralDataPaused;
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.getSignalsToken = function () {
- var t = '';
- if (
- 'string' == typeof window._pingOneSignalsToken &&
- 0 <= window._pingOneSignalsToken.indexOf(':')
- ) {
- var e = window._pingOneSignalsToken.match(/t:(.*?)(&|$)/g);
- e && 0 < e.length && (t = e[0].replace(/&s*$/, '').replace(/t:/, ''));
- } else
- 'string' == typeof window._pingOneSignalsToken && (t = window._pingOneSignalsToken);
- return t;
- }),
- (e.prototype.pauseBehavioralData = function () {
- this._isBehavioralDataPaused ||
- ((this._isBehavioralDataPaused = !0), this.addTag('SDK paused behaviorally'));
- }),
- (e.prototype.resumeBehavioralData = function () {
- this._isBehavioralDataPaused &&
- ((this._isBehavioralDataPaused = !1), this.addTag('SDK resumed behaviorally'));
- }),
- (e.prototype.startSignals = function (e) {
- return __awaiter(this, void 0, void 0, function () {
- var n,
- i,
- r = this;
- return __generator(this, function (a) {
- switch (a.label) {
- case 0:
- return (
- a.trys.push([0, 2, , 3]),
- (this.startedPromise = this.initQueue.add(function () {
- return r.start(e);
- })),
- [4, this.startedPromise]
- );
- case 1:
- return [2, a.sent()];
- case 2:
- throw (
- ((n = a.sent()),
- (i = {
- id: t._POSignalsUtils.POErrorCodes.INITIALIZATION_ERROR,
- message: n.message,
- code: 'SDK initialization failed.',
- }),
- new Error(JSON.stringify(i)))
- );
- case 3:
- return [2];
- }
- });
- });
- }),
- (e.prototype.validateStartParams = function (e) {
- if (!document.body)
- throw (
- (t._POSignalsUtils.Logger.error(
- 'PingOne Signals can be started only after DOM Ready!',
- ),
- new Error('PingOne Signals can be started only after DOM Ready!'))
- );
- e.externalIdentifiers = e.externalIdentifiers || {};
- }),
- (e.prototype.loadEventPromise = function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (t) {
- return [
- 2,
- new Promise(function (t) {
- 'complete' === document.readyState
- ? t()
- : window.addEventListener('load', function (e) {
- t();
- });
- }),
- ];
- });
- });
- }),
- (e.prototype.addStartupTags = function () {
- this.addTag('SDK started'),
- document.referrer && this.addTag('referrer', document.referrer),
- this.addTag('location', window.location.href);
- }),
- e
- );
- })();
- t.ClientBase = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(e) {
- (this.BEHAVIORAL_TYPE = 'indirect'),
- (this._isStarted = !1),
- (this._onClipboardEvent = new t.EventDispatcher()),
- (this.delegate = e),
- (this.onClipboardEventHandler = this.onEvent.bind(this));
- }
- return (
- Object.defineProperty(e.prototype, 'isStarted', {
- get: function () {
- return this._isStarted;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'onClipboardEvent', {
- get: function () {
- return this._onClipboardEvent.asEvent();
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.onEvent = function (e) {
- try {
- if (!this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE)) return;
- this._onClipboardEvent.dispatch(this, this.createClipboardEvent(e));
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in clipboard handler', e);
- }
- }),
- (e.prototype.createClipboardEvent = function (e) {
- var n = t._POSignalsUtils.Util.getSrcElement(e);
- return {
- category: 'ClipboardEvent',
- type: e.type,
- eventTs: e.timeStamp,
- epochTs: new Date().getTime(),
- additionalData: {
- locationHref: location.href,
- stId: this.delegate.getElementsStID(n),
- elementId: null === n || void 0 === n ? void 0 : n.id,
- },
- };
- }),
- (e.prototype.start = function () {
- this._isStarted ||
- ((this._isStarted = !0),
- this.delegate.addEventListener(document, 'cut', this.onClipboardEventHandler),
- this.delegate.addEventListener(document, 'copy', this.onClipboardEventHandler),
- this.delegate.addEventListener(document, 'paste', this.onClipboardEventHandler));
- }),
- (e.prototype.stop = function () {
- this._isStarted &&
- ((this._isStarted = !1),
- document.removeEventListener('cut', this.onClipboardEventHandler),
- document.removeEventListener('copy', this.onClipboardEventHandler),
- document.removeEventListener('paste', this.onClipboardEventHandler));
- }),
- e
- );
- })();
- t.ClipboardEvents = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(e) {
- (this.BEHAVIORAL_TYPE = 'indirect'),
- (this._isStarted = !1),
- (this._onDragEvent = new t.EventDispatcher()),
- (this.delegate = e),
- (this.onDragEventHandler = this.onEvent.bind(this));
- }
- return (
- Object.defineProperty(e.prototype, 'isStarted', {
- get: function () {
- return this._isStarted;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'onDragEvent', {
- get: function () {
- return this._onDragEvent.asEvent();
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.createDragEvent = function (t) {
- return {
- category: 'DragEvent',
- type: t.type,
- eventTs: t.timeStamp,
- epochTs: new Date().getTime(),
- additionalData: { locationHref: location.href },
- };
- }),
- (e.prototype.onEvent = function (e) {
- try {
- if (!this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE)) return;
- this._onDragEvent.dispatch(this, this.createDragEvent(e));
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in drag handler', e);
- }
- }),
- (e.prototype.start = function () {
- this._isStarted ||
- ((this._isStarted = !0),
- this.delegate.addEventListener(document, 'dragstart', this.onDragEventHandler),
- this.delegate.addEventListener(document, 'dragexit', this.onDragEventHandler),
- this.delegate.addEventListener(document, 'drop', this.onDragEventHandler),
- this.delegate.addEventListener(document, 'dragend', this.onDragEventHandler));
- }),
- (e.prototype.stop = function () {
- this._isStarted &&
- ((this._isStarted = !1),
- document.removeEventListener('dragstart', this.onDragEventHandler),
- document.removeEventListener('dragexit', this.onDragEventHandler),
- document.removeEventListener('drop', this.onDragEventHandler),
- document.removeEventListener('dragend', this.onDragEventHandler));
- }),
- e
- );
- })();
- t.DragEvents = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(e) {
- (this.BEHAVIORAL_TYPE = 'indirect'),
- (this._isStarted = !1),
- (this._onFocusEvent = new t.EventDispatcher()),
- (this.delegate = e),
- (this.onFocusEventHandler = this.onEvent.bind(this));
- }
- return (
- Object.defineProperty(e.prototype, 'isStarted', {
- get: function () {
- return this._isStarted;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'onFocusEvent', {
- get: function () {
- return this._onFocusEvent.asEvent();
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.getRelatedTarget = function (e) {
- if (!e.relatedTarget) return { type: '', stId: '', elementId: '' };
- var n = {
- type: t._POSignalsUtils.Util.getObjectType(e.relatedTarget),
- stId: '',
- elementId: '',
- };
- e.relatedTarget.id && (n.elementId = e.relatedTarget.id);
- try {
- var i = e.relatedTarget;
- n.stId = this.delegate.getElementsStID(i);
- } catch (t) {}
- return n;
- }),
- (e.prototype.createFocusEvent = function (e) {
- var n = t._POSignalsUtils.Util.getSrcElement(e),
- i = this.getRelatedTarget(e);
- return {
- category: 'FocusEvent',
- type: e.type,
- eventTs: e.timeStamp,
- epochTs: new Date().getTime(),
- additionalData: {
- locationHref: location.href,
- stId: this.delegate.getElementsStID(n),
- elementId: n ? n.id : '',
- relatedTarget: i,
- },
- };
- }),
- (e.prototype.onEvent = function (e) {
- try {
- if (!this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE)) return;
- this._onFocusEvent.dispatch(this, this.createFocusEvent(e));
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in focus handler', e);
- }
- }),
- (e.prototype.start = function () {
- this._isStarted ||
- ((this._isStarted = !0),
- this.delegate.addEventListener(document, 'DOMFocusIn', this.onFocusEventHandler),
- this.delegate.addEventListener(document, 'DOMFocusOut', this.onFocusEventHandler),
- this.delegate.addEventListener(document, 'focus', this.onFocusEventHandler),
- this.delegate.addEventListener(document, 'focusin', this.onFocusEventHandler),
- this.delegate.addEventListener(document, 'focusout', this.onFocusEventHandler));
- }),
- (e.prototype.stop = function () {
- this._isStarted &&
- ((this._isStarted = !1),
- document.removeEventListener('DOMFocusIn', this.onFocusEventHandler),
- document.removeEventListener('DOMFocusOut', this.onFocusEventHandler),
- document.removeEventListener('focus', this.onFocusEventHandler),
- document.removeEventListener('focusin', this.onFocusEventHandler),
- document.removeEventListener('focusout', this.onFocusEventHandler));
- }),
- e
- );
- })();
- t.FocusEvents = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(e) {
- (this.BEHAVIORAL_TYPE = 'indirect'),
- (this._isStarted = !1),
- (this._onUIEvent = new t.EventDispatcher()),
- (this.delegate = e),
- (this.onUIEventHandler = this.onEvent.bind(this));
- }
- return (
- Object.defineProperty(e.prototype, 'isStarted', {
- get: function () {
- return this._isStarted;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'onUIEvent', {
- get: function () {
- return this._onUIEvent.asEvent();
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.createUIEvent = function (t) {
- return {
- category: 'UIEvent',
- type: t.type,
- eventTs: t.timeStamp,
- epochTs: new Date().getTime(),
- additionalData: { locationHref: location.href },
- };
- }),
- (e.prototype.onEvent = function (e) {
- try {
- if (!this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE)) return;
- this._onUIEvent.dispatch(this, this.createUIEvent(e));
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in UIEvent handler', e);
- }
- }),
- (e.prototype.start = function () {
- this._isStarted ||
- ((this._isStarted = !0),
- this.delegate.addEventListener(document, 'resize', this.onUIEventHandler),
- this.delegate.addEventListener(document, 'scroll', this.onUIEventHandler),
- this.delegate.addEventListener(document, 'select', this.onUIEventHandler));
- }),
- (e.prototype.stop = function () {
- this._isStarted &&
- ((this._isStarted = !1),
- document.removeEventListener('resize', this.onUIEventHandler),
- document.removeEventListener('scroll', this.onUIEventHandler),
- document.removeEventListener('select', this.onUIEventHandler));
- }),
- e
- );
- })();
- t.UIEvents = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(e) {
- (this.BEHAVIORAL_TYPE = 'indirect'),
- (this.visibilityChangeEventName = 'visibilitychange'),
- (this.hiddenProperty = 'hidden'),
- (this._isStarted = !1),
- (this._onGeneralEvent = new t.EventDispatcher()),
- (this.delegate = e),
- (this.onGeneralEventHandler = this.onEvent.bind(this)),
- (this.onLangChangeHandler = this.onLangChangeEvent.bind(this)),
- (this.onOrientationChangeHandler = this.onOrientationChangeEvent.bind(this)),
- (this.onVisibilityChangeHandler = this.onVisibilityChangeEvent.bind(this)),
- void 0 !== document.msHidden
- ? ((this.hiddenProperty = 'msHidden'),
- (this.visibilityChangeEventName = 'msvisibilitychange'))
- : void 0 !== document.webkitHidden &&
- ((this.hiddenProperty = 'webkitHidden'),
- (this.visibilityChangeEventName = 'webkitvisibilitychange'));
- }
- return (
- Object.defineProperty(e.prototype, 'isStarted', {
- get: function () {
- return this._isStarted;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'onGeneralEvent', {
- get: function () {
- return this._onGeneralEvent.asEvent();
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.onEvent = function (e) {
- try {
- if (!this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE)) return;
- this._onGeneralEvent.dispatch(this, this.createGeneralEvent(e));
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in general event handler', e);
- }
- }),
- (e.prototype.onLangChangeEvent = function (e) {
- try {
- if (!this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE)) return;
- var n = this.createGeneralEvent(e);
- this._onGeneralEvent.dispatch(this, n);
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in LangChange event handler', e);
- }
- }),
- (e.prototype.onOrientationChangeEvent = function (e) {
- try {
- if (!this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE)) return;
- var n = this.createGeneralEvent(e),
- i = t._POSignalsUtils.Util.getDeviceOrientation();
- (n.additionalData.deviceOrientation = i.orientation),
- (n.additionalData.deviceAngle = i.angle),
- this._onGeneralEvent.dispatch(this, n);
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in OrientationChange event handler', e);
- }
- }),
- (e.prototype.onVisibilityChangeEvent = function (e) {
- try {
- if (!this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE)) return;
- var n = this.createGeneralEvent(e);
- (n.additionalData.hidden = !!document[this.hiddenProperty]),
- document.visibilityState &&
- (n.additionalData.visibilityState = document.visibilityState.toString()),
- this._onGeneralEvent.dispatch(this, n);
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in VisibilityChange event handler', e);
- }
- }),
- (e.prototype.createGeneralEvent = function (t) {
- return {
- category: 'Event',
- type: t.type,
- eventTs: t.timeStamp,
- epochTs: new Date().getTime(),
- additionalData: { locationHref: location.href },
- };
- }),
- (e.prototype.start = function () {
- this._isStarted ||
- ((this._isStarted = !0),
- this.delegate.addEventListener(
- document,
- this.visibilityChangeEventName,
- this.onVisibilityChangeHandler,
- ),
- this.delegate.addEventListener(document, 'change', this.onGeneralEventHandler),
- this.delegate.addEventListener(
- document,
- 'fullscreenchange',
- this.onGeneralEventHandler,
- ),
- this.delegate.addEventListener(document, 'invalid', this.onGeneralEventHandler),
- this.delegate.addEventListener(window, 'languagechange', this.onLangChangeHandler),
- this.delegate.addEventListener(
- window,
- 'orientationchange',
- this.onOrientationChangeHandler,
- ),
- this.delegate.addEventListener(document, 'seeked', this.onGeneralEventHandler),
- this.delegate.addEventListener(document, 'seeking', this.onGeneralEventHandler),
- this.delegate.addEventListener(document, 'selectstart', this.onGeneralEventHandler),
- this.delegate.addEventListener(
- document,
- 'selectionchange',
- this.onGeneralEventHandler,
- ),
- this.delegate.addEventListener(document, 'submit', this.onGeneralEventHandler),
- this.delegate.addEventListener(document, 'volumechange', this.onGeneralEventHandler),
- this.delegate.addEventListener(document, 'reset', this.onGeneralEventHandler),
- this.delegate.addEventListener(document, 'textInput', this.onGeneralEventHandler));
- }),
- (e.prototype.stop = function () {
- this._isStarted &&
- ((this._isStarted = !1),
- document.removeEventListener(
- this.visibilityChangeEventName,
- this.onVisibilityChangeHandler,
- ),
- document.removeEventListener('change', this.onGeneralEventHandler),
- document.removeEventListener('fullscreenchange', this.onGeneralEventHandler),
- document.removeEventListener('invalid', this.onGeneralEventHandler),
- window.removeEventListener('languagechange', this.onLangChangeHandler),
- window.removeEventListener('orientationchange', this.onOrientationChangeHandler),
- document.removeEventListener('seeked', this.onGeneralEventHandler),
- document.removeEventListener('seeking', this.onGeneralEventHandler),
- document.removeEventListener('selectstart', this.onGeneralEventHandler),
- document.removeEventListener('selectionchange', this.onGeneralEventHandler),
- document.removeEventListener('submit', this.onGeneralEventHandler),
- document.removeEventListener('volumechange', this.onGeneralEventHandler),
- document.removeEventListener('reset', this.onGeneralEventHandler),
- document.removeEventListener('textInput', this.onGeneralEventHandler));
- }),
- e
- );
- })();
- t.GeneralEvents = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(e) {
- (this.DEFAULT_INDIRECT_IDLE_INTERVAL = 1e3),
- (this.MAX_INDIRECT_EVENTS = 25),
- (this._onIndirect = new t.EventDispatcher()),
- (this.indirectEvents = []),
- (this.idleTimeInMillis = this.DEFAULT_INDIRECT_IDLE_INTERVAL),
- (this.lastIndirectEventTimestamp = 0),
- (this._isStarted = !1),
- (this.clipboardEvents = new t.ClipboardEvents(e)),
- this.clipboardEvents.onClipboardEvent.subscribe(this.handleEvent.bind(this)),
- (this.dragEvents = new t.DragEvents(e)),
- this.dragEvents.onDragEvent.subscribe(this.handleEvent.bind(this)),
- (this.focusEvents = new t.FocusEvents(e)),
- this.focusEvents.onFocusEvent.subscribe(this.handleEvent.bind(this)),
- (this.uiEvents = new t.UIEvents(e)),
- this.uiEvents.onUIEvent.subscribe(this.handleEvent.bind(this)),
- (this.generalEvents = new t.GeneralEvents(e)),
- this.generalEvents.onGeneralEvent.subscribe(this.handleEvent.bind(this)),
- (this.onTimeElapsedHandler = this.onTimeElapsed.bind(this));
- }
- return (
- Object.defineProperty(e.prototype, 'onIndirect', {
- get: function () {
- return this._onIndirect.asEvent();
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.onTimeElapsed = function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (t) {
- return (
- this.indirectEvents.length > 0 &&
- new Date().getTime() - this.lastIndirectEventTimestamp >=
- this.idleTimeInMillis &&
- this.dispatch(),
- [2]
- );
- });
- });
- }),
- (e.prototype.handleEvent = function (t, e) {
- (this.lastIndirectEventTimestamp = new Date().getTime()), this.pushEvent(e);
- }),
- (e.prototype.pushEvent = function (t) {
- this.indirectEvents.push(t),
- this.indirectEvents.length >= this.MAX_INDIRECT_EVENTS && this.dispatch();
- }),
- (e.prototype.clearBuffer = function () {
- var t = { events: this.indirectEvents };
- return (this.indirectEvents = []), t;
- }),
- (e.prototype.dispatch = function () {
- try {
- clearInterval(this.updateIntervalHandle),
- this._onIndirect.dispatch(this, this.clearBuffer()),
- (this.updateIntervalHandle = setInterval(
- this.onTimeElapsedHandler,
- t.PointerConfig.instance.pointerParams.indirectIntervalMillis,
- ));
- } catch (e) {
- t._POSignalsUtils.Logger.warn('Failed to dispatch indirect events', e);
- }
- }),
- Object.defineProperty(e.prototype, 'isStarted', {
- get: function () {
- return this._isStarted;
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.start = function () {
- this._isStarted ||
- ((this.updateIntervalHandle = setInterval(
- this.onTimeElapsedHandler,
- t.PointerConfig.instance.pointerParams.indirectIntervalMillis,
- )),
- this.clipboardEvents.start(),
- this.dragEvents.start(),
- this.focusEvents.start(),
- this.uiEvents.start(),
- this.generalEvents.start(),
- (this._isStarted = !0));
- }),
- (e.prototype.stop = function () {
- this._isStarted &&
- (this.clipboardEvents.stop(),
- this.dragEvents.stop(),
- this.focusEvents.stop(),
- this.uiEvents.stop(),
- this.generalEvents.stop(),
- clearInterval(this.updateIntervalHandle),
- (this.updateIntervalHandle = null),
- (this._isStarted = !1));
- }),
- (e.prototype.unsubscribe = function () {
- this.clipboardEvents.onClipboardEvent.unsubscribe(this.handleEvent.bind(this)),
- this.dragEvents.onDragEvent.unsubscribe(this.handleEvent.bind(this)),
- this.focusEvents.onFocusEvent.unsubscribe(this.handleEvent.bind(this)),
- this.uiEvents.onUIEvent.unsubscribe(this.handleEvent.bind(this)),
- this.generalEvents.onGeneralEvent.unsubscribe(this.handleEvent.bind(this));
- }),
- e
- );
- })();
- t.IndirectClient = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e() {
- (this.config = {}), (this._cacheHash = 0), (this.cache = new Map());
- }
- return (
- (e.prototype.refreshCssSelectors = function (e) {
- try {
- if (!e) return;
- var n = t._POSignalsUtils.Util.hashCode(JSON.stringify(e));
- if (this._cacheHash === n) return;
- (this.config = e), (this._cacheHash = n), (this.cache = new Map());
- } catch (e) {
- t._POSignalsUtils.Logger.warn('Failed to set css selectors', e);
- }
- }),
- (e.prototype.getIdentification = function (e, n) {
- if (null === this.cache.get(e)) return null;
- if (void 0 !== this.cache.get(e)) return this.cache.get(e);
- for (var i in this.config)
- try {
- if (!this.config.hasOwnProperty(i)) continue;
- var r = this.config[i] || [];
- t._POSignalsUtils.Util.isArray(r) || (r = [].concat(r));
- for (var a = 0, o = r; a < o.length; a++) {
- var s = o[a];
- if (t._POSignalsUtils.Util.isSelectorMatches(e, s, n))
- return this.cache.set(e, i), i;
- }
- } catch (e) {
- t._POSignalsUtils.Logger.warn('Failed to find selector for ' + i, e);
- }
- return this.cache.set(e, null), null;
- }),
- Object.defineProperty(e.prototype, 'cacheHash', {
- get: function () {
- return this._cacheHash;
- },
- enumerable: !1,
- configurable: !0,
- }),
- e
- );
- })();
- t.ElementsIdentifications = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(e, n) {
- (this.BEHAVIORAL_TYPE = 'eventKeyboard'),
- (this._isStarted = !1),
- (this._onInteraction = new t.EventDispatcher()),
- (this._onEnterPress = new t.EventDispatcher()),
- (this._onObfuscatedValue = new t.EventDispatcher()),
- (this.interactionsMap = new Map()),
- (this._fieldsIdentifications = new t.ElementsIdentifications()),
- (this.keyStrokeMap = new Map()),
- (this.delegate = e),
- (this.uiControlManager = n),
- (this.onKeyDownHandle = this.onKeyDown.bind(this)),
- (this.onKeyUpHandle = this.onKeyUp.bind(this)),
- (this.onFocusHandle = this.onFocus.bind(this)),
- (this.onBlurHandle = this.onBlur.bind(this));
- }
- return (
- Object.defineProperty(e.prototype, 'isStarted', {
- get: function () {
- return this._isStarted;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'onInteraction', {
- get: function () {
- return this._onInteraction.asEvent();
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'onEnterPress', {
- get: function () {
- return this._onEnterPress.asEvent();
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'onObfuscatedValue', {
- get: function () {
- return this._onObfuscatedValue.asEvent();
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.refreshKeyboardCssSelectors = function (t) {
- this._fieldsIdentifications.refreshCssSelectors(t);
- }),
- Object.defineProperty(e.prototype, 'modifiersKeys', {
- get: function () {
- return [
- 'Alt',
- 'AltGraph',
- 'CapsLock',
- 'Control',
- 'Fn',
- 'FnLock',
- 'Hyper',
- 'Meta',
- 'NumLock',
- 'OS',
- 'ScrollLock',
- 'Shift',
- 'Super',
- 'Symbol',
- 'SymbolLock',
- ];
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'specialKeys', {
- get: function () {
- return [
- 'Tab',
- 'Shift',
- 'Backspace',
- 'Enter',
- 'CapsLock',
- 'Meta',
- 'Delete',
- 'Alt',
- 'ArrowDown',
- 'ArrowUp',
- 'Control',
- 'ArrowLeft',
- 'End',
- 'Unidentified',
- 'Home',
- 'ArrowRight',
- 'Insert',
- 'Pause',
- 'PageDown',
- 'PageUp',
- 'F1',
- 'F2',
- 'F3',
- 'F4',
- 'F5',
- 'F6',
- 'F7',
- 'F8',
- 'F9',
- 'F10',
- 'F11',
- 'F12',
- 'AltGraph',
- 'Escape',
- ];
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.countEvent = function (t, e) {
- e && (e.eventCounters[t] = (e.eventCounters[t] || 0) + 1);
- }),
- (e.prototype.clearBuffer = function () {
- var e = t._POSignalsUtils.Util.getValuesOfMap(this.interactionsMap);
- return this.interactionsMap.clear(), e;
- }),
- (e.prototype.start = function () {
- this._isStarted
- ? t._POSignalsUtils.Logger.debug('Desktop Keyboard events already listening')
- : (this.delegate.addEventListener(document, 'keydown', this.onKeyDownHandle),
- this.delegate.addEventListener(document, 'keyup', this.onKeyUpHandle),
- this.delegate.addEventListener(document, 'focus', this.onFocusHandle, !0),
- this.delegate.addEventListener(document, 'blur', this.onBlurHandle, !0),
- (this._isStarted = !0),
- t._POSignalsUtils.Logger.debug('Desktop Keyboard events start listening...'));
- }),
- (e.prototype.stop = function () {
- this._isStarted
- ? (document.removeEventListener('keydown', this.onKeyDownHandle),
- document.removeEventListener('keyup', this.onKeyUpHandle),
- document.removeEventListener('focus', this.onFocusHandle, !0),
- document.removeEventListener('blur', this.onBlurHandle, !0),
- (this._isStarted = !1),
- t._POSignalsUtils.Logger.debug('Desktop Keyboard events stop listening...'))
- : t._POSignalsUtils.Logger.debug('Desktop Keyboard events already stopped');
- }),
- (e.prototype.getInteractionFromElement = function (e) {
- var n,
- i = null,
- r = null,
- a = t._POSignalsUtils.Util.getSrcElement(e);
- if (
- a &&
- a instanceof HTMLInputElement &&
- !t._POSignalsUtils.Util.isClickableInput(a) &&
- t._POSignalsUtils.Util.isFunction(a.getAttribute) &&
- !(null === (n = a.hasAttribute) || void 0 === n
- ? void 0
- : n.call(a, 'data-st-ignore')) &&
- !t._POSignalsUtils.Util.anySelectorMatches(
- a,
- t.PointerConfig.instance.pointerParams.keyboardCssSelectorsBlacklist,
- 0,
- )
- ) {
- r = this.delegate.getElementsStID(a);
- for (
- var o = t.PointerConfig.instance.pointerParams.keyboardIdentifierAttributes, s = 0;
- s < o.length && !r;
- s++
- )
- r = a.getAttribute(o[s]);
- r &&
- !t.PointerConfig.instance.pointerParams.keyboardFieldBlackList.has(r) &&
- ((i = this.interactionsMap.get(a)) ||
- ((i = {
- epochTs: new Date().getTime(),
- stId: r,
- elementId: t._POSignalsUtils.Util.getAttribute(a, 'id'),
- name: t._POSignalsUtils.Util.getAttribute(a, 'name'),
- type: t._POSignalsUtils.Util.getAttribute(a, 'type'),
- events: [],
- counter: this.delegate.keyboardCounter,
- eventCounters: {},
- duration: 0,
- numOfDeletions: 0,
- additionalData: this.delegate.additionalData,
- }),
- this.interactionsMap.set(a, i)));
- }
- return i;
- }),
- (e.prototype.getKeyCode = function (e) {
- return e.keyCode
- ? e.keyCode
- : e.which
- ? e.which
- : e.code
- ? t._POSignalsUtils.Util.hashCode(e.code)
- : t._POSignalsUtils.Util.hashCode(e.key) + (e.location || 0);
- }),
- (e.prototype.getKeyboardEvent = function (t) {
- return t || window.event;
- }),
- (e.prototype.getKeystrokeId = function (e, n) {
- var i,
- r = this.getKeyCode(e);
- return (
- 'keyup' === n &&
- (this.keyStrokeMap.has(r)
- ? ((i = this.keyStrokeMap.get(r)), this.keyStrokeMap.delete(r))
- : (i = t._POSignalsUtils.Util.newGuid())),
- 'keydown' === n &&
- (this.keyStrokeMap.has(r) && e.repeat
- ? (i = this.keyStrokeMap.get(r))
- : ((i = t._POSignalsUtils.Util.newGuid()), this.keyStrokeMap.set(r, i))),
- i
- );
- }),
- (e.prototype.createKeyboardInteractionEvent = function (e, n) {
- var i = t._POSignalsUtils.Util.getSrcElement(n),
- r = i.value ? i.value.toString().length : 0;
- return {
- type: e,
- eventTs: n.timeStamp,
- epochTs: new Date().getTime(),
- selectionStart: t._POSignalsUtils.Util.getElementSelectionStart(i),
- selectionEnd: t._POSignalsUtils.Util.getElementSelectionEnd(i),
- key: null,
- keystrokeId: null,
- currentLength: r,
- };
- }),
- (e.prototype.enrichKeyboardEvent = function (e, n) {
- (this.modifiersKeys.indexOf(e.key) >= 0 || this.specialKeys.indexOf(e.key) >= 0) &&
- (n.key = e.key),
- (n.keystrokeId = this.getKeystrokeId(e, n.type));
- var i = t._POSignalsUtils.Util.getSrcElement(e);
- n.currentLength = String(i.value).length;
- }),
- (e.prototype.onFocus = function (e) {
- var n, i;
- try {
- if (!this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE))
- return void this._onInteraction.dispatch(this, null);
- e = this.getKeyboardEvent(e);
- var r = this.getInteractionFromElement(e);
- if (
- (this.countEvent(e.type, r),
- t.PointerConfig.instance.pointerParams.eventsToIgnore.has(e.type))
- )
- return;
- if (r) {
- var a = this.createKeyboardInteractionEvent('focus', e);
- r.events.push(a);
- var o = this.uiControlManager.createUIControlData(e);
- o &&
- ((r.uiControl = { uiElement: o.uiElement, enrichedData: o.enrichedData }),
- (null === (i = null === (n = o.uiElement) || void 0 === n ? void 0 : n.id) ||
- void 0 === i
- ? void 0
- : i.length) > 0 &&
- t._POSignalsUtils.Logger.info(
- "Typing in element with id '" + o.uiElement.id + "'",
- ));
- }
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in keyboard focus handler', e);
- }
- }),
- (e.prototype.onKeyUp = function (e) {
- try {
- if (
- ((13 !== (e = this.getKeyboardEvent(e)).keyCode && 13 !== e.which) ||
- this._onEnterPress.dispatch(this, t._POSignalsUtils.Util.getSrcElement(e)),
- !this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE))
- )
- return void this._onInteraction.dispatch(this, null);
- var n = this.getInteractionFromElement(e);
- if (
- (this.countEvent(e.type, n),
- t.PointerConfig.instance.pointerParams.eventsToIgnore.has(e.type))
- )
- return;
- if (n) {
- var i = this.createKeyboardInteractionEvent('keyup', e);
- this.enrichKeyboardEvent(e, i), n.events.push(i);
- } else this.keyStrokeMap.delete(this.getKeyCode(e));
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in keyUp handler', e);
- }
- }),
- (e.prototype.isEmpty = function () {
- return 0 === this.interactionsMap.size;
- }),
- (e.prototype.onKeyDown = function (e) {
- try {
- if (!this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE))
- return void this._onInteraction.dispatch(this, null);
- e = this.getKeyboardEvent(e);
- var n = this.getInteractionFromElement(e);
- if (
- (this.countEvent(e.type, n),
- t.PointerConfig.instance.pointerParams.eventsToIgnore.has(e.type))
- )
- return;
- if (n) {
- var i = this.createKeyboardInteractionEvent('keydown', e);
- this.enrichKeyboardEvent(e, i), n.events.push(i);
- }
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in keyDown handler', e);
- }
- }),
- (e.prototype.onBlur = function (e) {
- try {
- e = this.getKeyboardEvent(e);
- var n = this.getInteractionFromElement(e);
- if (!this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE))
- return void this._onInteraction.dispatch(this, null);
- if (
- (this.countEvent(e.type, n),
- t.PointerConfig.instance.pointerParams.eventsToIgnore.has(e.type))
- )
- return;
- if (n) {
- var i = this.createKeyboardInteractionEvent('blur', e);
- n.events.push(i),
- (n.duration = this.delegate.getInteractionDuration(n.events)),
- (n.numOfDeletions = this.calculateNumOfDeletions(n.events));
- var r = t._POSignalsUtils.Util.getSrcElement(e);
- this.interactionsMap.delete(r), this._onInteraction.dispatch(this, n);
- }
- } catch (e) {
- t._POSignalsUtils.Logger.warn('error in blur handler', e);
- }
- }),
- (e.prototype.calculateNumOfDeletions = function (t) {
- if (!(null === t || void 0 === t ? void 0 : t[0])) return 0;
- for (var e = 0, n = t[0].currentLength, i = 1; i < t.length; i++)
- t[i].currentLength < n && e++, (n = t[i].currentLength);
- return e;
- }),
- Object.defineProperty(e.prototype, 'fieldsIdentifications', {
- get: function () {
- return this._fieldsIdentifications;
- },
- enumerable: !1,
- configurable: !0,
- }),
- e
- );
- })();
- t.Keyboard = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(e, n) {
- var i,
- r = this,
- a = t.PointerConfig.instance.pointerParams.uiModelingElementFilters,
- o = t._POSignalsUtils.Util.getAttribute,
- s = null === (i = e.getBoundingClientRect) || void 0 === i ? void 0 : i.call(e);
- (this._htmlElement = e),
- (this._data = {
- location: this.getUIElementAttribute(a.location, function () {
- return window.location.href;
- }),
- id: this.getUIElementAttribute(a.id, function () {
- return o(e, 'id');
- }),
- aria_label: this.getUIElementAttribute(a.aria_label, function () {
- return o(e, 'aria-label');
- }),
- data_st_field: this.getUIElementAttribute(a.data_st_field, function () {
- return n.getElementsStID(e);
- }),
- data_st_tag: this.getUIElementAttribute(a.data_st_tag, function () {
- return o(e, 'data-st-tag');
- }),
- data_selenium: this.getUIElementAttribute(a.data_selenium, function () {
- return o(e, 'data-selenium');
- }),
- data_selenium_id: this.getUIElementAttribute(a.data_selenium_id, function () {
- return o(e, 'data-selenium-id');
- }),
- data_testid: this.getUIElementAttribute(a.data_testid, function () {
- return o(e, 'data-testid');
- }),
- data_test_id: this.getUIElementAttribute(a.data_test_id, function () {
- return o(e, 'data-test-id');
- }),
- data_qa_id: this.getUIElementAttribute(a.data_qa_id, function () {
- return o(e, 'data-qa-id');
- }),
- data_id: this.getUIElementAttribute(a.data_id, function () {
- return o(e, 'data-id');
- }),
- name: this.getUIElementAttribute(a.name, function () {
- return o(e, 'name');
- }),
- placeholder: this.getUIElementAttribute(a.placeholder, function () {
- return o(e, 'placeholder');
- }),
- role: this.getUIElementAttribute(a.role, function () {
- return o(e, 'role');
- }),
- type: this.getUIElementAttribute(a.type, function () {
- return o(e, 'type');
- }),
- nodeTypeInt: this.getUIElementAttribute(a.nodeTypeInt, function () {
- return e.nodeType;
- }),
- nodeName: this.getUIElementAttribute(a.nodeName, function () {
- return e.nodeName;
- }),
- cursorType: this.getUIElementAttribute(a.cursorType, function () {
- return window.getComputedStyle(e).cursor;
- }),
- text: this.getUIElementAttribute(a.text, function () {
- return r.getElementText(e);
- }),
- textLength: this.getUIElementAttribute(a.textLength, function () {
- var t;
- return (
- (null === (t = r.getElementText(e)) || void 0 === t ? void 0 : t.length) || null
- );
- }),
- bottom: this.getUIElementAttribute(a.bottom, function () {
- return null === s || void 0 === s ? void 0 : s.bottom;
- }),
- height: this.getUIElementAttribute(a.height, function () {
- return null === s || void 0 === s ? void 0 : s.height;
- }),
- left: this.getUIElementAttribute(a.left, function () {
- return null === s || void 0 === s ? void 0 : s.left;
- }),
- right: this.getUIElementAttribute(a.right, function () {
- return null === s || void 0 === s ? void 0 : s.right;
- }),
- top: this.getUIElementAttribute(a.top, function () {
- return null === s || void 0 === s ? void 0 : s.top;
- }),
- width: this.getUIElementAttribute(a.width, function () {
- return null === s || void 0 === s ? void 0 : s.width;
- }),
- x: this.getUIElementAttribute(a.x, function () {
- return null === s || void 0 === s ? void 0 : s.x;
- }),
- y: this.getUIElementAttribute(a.y, function () {
- return null === s || void 0 === s ? void 0 : s.y;
- }),
- }),
- (this._data.elementId = this.getStrongestElementID());
- }
- return (
- Object.defineProperty(e.prototype, 'data', {
- get: function () {
- return t._POSignalsUtils.Util.filterReduce(this._data, function (t) {
- return null != t && '' !== t;
- });
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'htmlElement', {
- get: function () {
- return this._htmlElement;
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.getUIElementAttribute = function (e, n) {
- var i;
- try {
- if (
- null === (i = null === e || void 0 === e ? void 0 : e.enabled) ||
- void 0 === i ||
- i
- ) {
- var r = n();
- return (
- 'string' == typeof r &&
- ('number' == typeof (null === e || void 0 === e ? void 0 : e.maxLength) &&
- r.length > e.maxLength &&
- (r = r.substring(0, e.maxLength)),
- (null === e || void 0 === e ? void 0 : e.filterRegex) &&
- (r = r.replace(new RegExp(e.filterRegex, 'g'), '*'))),
- r
- );
- }
- } catch (e) {
- t._POSignalsUtils.Logger.warn('Failed to add ui element attribute', e);
- }
- return null;
- }),
- (e.prototype.getStrongestElementID = function () {
- return (
- this._data.data_st_field ||
- this._data.data_selenium_id ||
- this._data.data_selenium ||
- this._data.data_testid ||
- this._data.data_test_id ||
- this._data.data_qa_id ||
- this._data.data_id ||
- this._data.id ||
- ''
- );
- }),
- (e.prototype.getElementText = function (e) {
- return e instanceof HTMLInputElement && !t._POSignalsUtils.Util.isClickableInput(e)
- ? null
- : t._POSignalsUtils.Util.getElementText(e);
- }),
- (e.prototype.equals = function (t) {
- return (
- !!t &&
- !(t.location && location.href.indexOf(t.location) < 0) &&
- (!t.elementId || t.elementId === this._data.elementId) &&
- (!t.id || t.id === this._data.id) &&
- (!t.aria_label || t.aria_label === this._data.aria_label) &&
- (!t.data_st_field || t.data_st_field === this._data.data_st_field) &&
- (!t.data_st_tag || t.data_st_tag === this._data.data_st_tag) &&
- (!t.data_selenium || t.data_selenium === this._data.data_selenium) &&
- (!t.data_selenium_id || t.data_selenium_id === this._data.data_selenium_id) &&
- (!t.data_testid || t.data_testid === this._data.data_testid) &&
- (!t.data_test_id || t.data_test_id === this._data.data_test_id) &&
- (!t.data_qa_id || t.data_qa_id === this._data.data_qa_id) &&
- (!t.data_id || t.data_id === this._data.data_id) &&
- (!t.name || t.name === this._data.name) &&
- (!t.placeholder || t.placeholder === this._data.placeholder) &&
- (!t.role || t.role === this._data.role) &&
- (!t.type || t.type === this._data.type) &&
- (!t.nodeTypeInt || t.nodeTypeInt === this._data.nodeTypeInt) &&
- (!t.nodeName || t.nodeName === this._data.nodeName) &&
- (!t.cursorType || t.cursorType === this._data.cursorType) &&
- (!t.text || t.text === this._data.text) &&
- (!t.textLength || t.textLength === this._data.textLength) &&
- (!t.bottom || t.bottom === this._data.bottom) &&
- (!t.height || t.height === this._data.height) &&
- (!t.left || t.left === this._data.left) &&
- (!t.right || t.right === this._data.right) &&
- (!t.top || t.top === this._data.top) &&
- (!t.width || t.width === this._data.width) &&
- (!t.x || t.x === this._data.x) &&
- (!t.y || t.y === this._data.y)
- );
- }),
- (e.createCssSelector = function (t) {
- var e = '';
- return (
- (null === t || void 0 === t ? void 0 : t.nodeName) && (e += t.nodeName.toLowerCase()),
- (null === t || void 0 === t ? void 0 : t.id) && (e += '[id="' + t.id + '"]'),
- (null === t || void 0 === t ? void 0 : t.aria_label) &&
- (e += '[aria-label="' + t.aria_label + '"]'),
- (null === t || void 0 === t ? void 0 : t.data_st_field) &&
- (e += '[data-st-field="' + t.data_st_field + '"]'),
- (null === t || void 0 === t ? void 0 : t.data_st_tag) &&
- (e += '[data-st-tag="' + t.data_st_tag + '"]'),
- (null === t || void 0 === t ? void 0 : t.data_selenium) &&
- (e += '[data-selenium="' + t.data_selenium + '"]'),
- (null === t || void 0 === t ? void 0 : t.data_selenium_id) &&
- (e += '[data-selenium-id="' + t.data_selenium_id + '"]'),
- (null === t || void 0 === t ? void 0 : t.data_testid) &&
- (e += '[data-testid="' + t.data_testid + '"]'),
- (null === t || void 0 === t ? void 0 : t.data_test_id) &&
- (e += '[data-test-id="' + t.data_test_id + '"]'),
- (null === t || void 0 === t ? void 0 : t.data_qa_id) &&
- (e += '[data-qa-id="' + t.data_qa_id + '"]'),
- (null === t || void 0 === t ? void 0 : t.data_id) &&
- (e += '[data-id="' + t.data_id + '"]'),
- (null === t || void 0 === t ? void 0 : t.name) && (e += '[name="' + t.name + '"]'),
- (null === t || void 0 === t ? void 0 : t.placeholder) &&
- (e += '[placeholder="' + t.placeholder + '"]'),
- (null === t || void 0 === t ? void 0 : t.role) && (e += '[role="' + t.role + '"]'),
- (null === t || void 0 === t ? void 0 : t.type) && (e += '[type="' + t.type + '"]'),
- e
- );
- }),
- e
- );
- })();
- t.UiElement = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(t) {
- this._clientDelegate = t;
- }
- return (
- (e.prototype.createUIControlData = function (e) {
- var n = t._POSignalsUtils.Util.getSrcElement(e);
- if (!n) return null;
- var i = t.PointerConfig.instance.pointerParams.uiModelingBlacklistRegex;
- if (i && window.location.href.match(i))
- return (
- t._POSignalsUtils.Logger.debug('ui control data is disabled for this url'), null
- );
- var r = new t.UiElement(n, this._clientDelegate);
- return this.findMatchingUiControl(r) || { uiElement: r.data };
- }),
- (e.prototype.findMatchingUiControl = function (e, n) {
- void 0 === n && (n = 0);
- try {
- var i = t.PointerConfig.instance.pointerParams.uiControlsConfig;
- if (0 === i.length) return null;
- if (n > t.PointerConfig.instance.pointerParams.uiModelingMaxMatchingParents)
- return null;
- for (var r = !1, a = 0, o = i; a < o.length; a++) {
- var s = o[a];
- if ((s.tagConfig || s.enrichedData) && ((r = !0), e.equals(s.uiElement)))
- return {
- uiElement: e.data,
- enrichedData: s.enrichedData,
- tagConfig: s.tagConfig,
- };
- }
- if (!r) return null;
- var u = e.htmlElement.parentElement;
- if ((null === u || void 0 === u ? void 0 : u.nodeType) === Node.ELEMENT_NODE) {
- var c = new t.UiElement(u, this._clientDelegate);
- return this.findMatchingUiControl(c, n + 1);
- }
- } catch (e) {
- t._POSignalsUtils.Logger.warn('failed to find matching ui control', e);
- }
- return null;
- }),
- (e.prototype.convertToTagValueConfig = function (e) {
- var n;
- return {
- context:
- null === (n = null === e || void 0 === e ? void 0 : e.uiElement) || void 0 === n
- ? void 0
- : n.location,
- valueSelector: t.UiElement.createCssSelector(
- null === e || void 0 === e ? void 0 : e.uiElement,
- ),
- operation: null === e || void 0 === e ? void 0 : e.operation,
- valueMandatory: null === e || void 0 === e ? void 0 : e.valueMandatory,
- };
- }),
- e
- );
- })();
- t.UIControlManager = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(e, n) {
- (this.BEHAVIORAL_TYPE = 'mouse'),
- (this._isStarted = !1),
- (this._onInteraction = new t.EventDispatcher()),
- (this._onClickEvent = new t.EventDispatcher()),
- (this.lastMouseInteractionTimestamp = null),
- (this.mouseEventsCounter = 0),
- (this.eventCounters = {}),
- (this.delegate = e),
- (this.uiControlManager = n),
- (this.wheelOptions = !!t._POSignalsUtils.Util.isPassiveSupported() && { passive: !0 }),
- (this.onPointerHandle = this.onPointerEvent.bind(this)),
- (this.onClickHandle = this.onClick.bind(this)),
- (this.onDblclickHandle = this.onMouseClickEvent.bind(this)),
- (this.onMousedownHandle = this.onMouseClickEvent.bind(this)),
- (this.onMousemoveHandle = this.onMouseEvent.bind(this)),
- (this.onMouseoutHandle = this.onMouseout.bind(this)),
- (this.onMouseoverHandle = this.onMouseEvent.bind(this)),
- (this.onMouseupHandle = this.onMouseClickEvent.bind(this)),
- (this.onWheelHandle = this.onMouseEvent.bind(this)),
- (this.interactionUpdateHandle = this.interactionUpdate.bind(this));
- }
- return (
- Object.defineProperty(e.prototype, 'isStarted', {
- get: function () {
- return this._isStarted;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'onInteraction', {
- get: function () {
- return this._onInteraction.asEvent();
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'onClickEvent', {
- get: function () {
- return this._onClickEvent.asEvent();
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.countEvent = function (t) {
- this.eventCounters[t] = (this.eventCounters[t] || 0) + 1;
- }),
- (e.prototype.interactionUpdate = function () {
- this.lastMouseInteraction
- ? new Date().getTime() - this.lastMouseInteractionTimestamp >=
- t.PointerConfig.instance.pointerParams.mouseIdleTimeoutMillis && this.dispatch()
- : !this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE) &&
- new Date().getTime() - this.lastMouseInteractionTimestamp <=
- t.PointerConfig.instance.pointerParams.mouseIntervalMillis &&
- this.dispatch();
- }),
- (e.prototype.enrichLastInteraction = function () {
- var e;
- if (this.lastMouseInteraction) {
- (this.lastMouseInteraction.eventCounters = this.eventCounters),
- (this.lastMouseInteraction.duration = this.delegate.getInteractionDuration(
- this.lastMouseInteraction.events,
- ));
- var n =
- null === (e = this.lastMouseInteraction.events) || void 0 === e
- ? void 0
- : e.filter(function (t) {
- return 'mousemove' === t.type;
- });
- (this.lastMouseInteraction.timeProximity =
- t._POSignalsUtils.Util.calculateMeanTimeDeltasBetweenEvents(n)),
- (this.lastMouseInteraction.meanEuclidean =
- t._POSignalsUtils.Util.calculateMeanDistanceBetweenPoints(n));
- }
- }),
- (e.prototype.dispatch = function () {
- try {
- this.enrichLastInteraction(),
- this._onInteraction.dispatch(this, this.lastMouseInteraction),
- (this.eventCounters = {}),
- (this.lastMouseInteraction = null),
- (this.mouseEventsCounter = 0);
- } catch (e) {
- t._POSignalsUtils.Logger.warn('Failed to dispatch mouse events', e);
- }
- }),
- (e.prototype.updateInteraction = function (e, n) {
- this.lastMouseInteraction ||
- (this.lastMouseInteraction = {
- epochTs: new Date().getTime(),
- events: [],
- counter: this.delegate.mouseCounter,
- additionalData: this.delegate.additionalData,
- eventCounters: {},
- duration: 0,
- timeProximity: 0,
- uiControl: void 0,
- meanEuclidean: 0,
- reduction: {},
- }),
- this.lastMouseInteraction.events.push(e),
- this.mouseEventsCounter++,
- n &&
- ((this.lastMouseInteraction.uiControl = {
- uiElement: n.uiElement,
- enrichedData: n.enrichedData,
- }),
- this.delegate.addUiControlTags(n.tagConfig)),
- this.mouseEventsCounter >= t.PointerConfig.instance.pointerParams.maxMouseEvents &&
- this.dispatch();
- }),
- (e.prototype.start = function () {
- this._isStarted
- ? t._POSignalsUtils.Logger.debug('Desktop Mouse events already listening')
- : (this.delegate.addEventListener(document, 'click', this.onClickHandle, !0),
- this.delegate.addEventListener(document, 'dblclick', this.onDblclickHandle),
- this.delegate.addEventListener(document, 'mousedown', this.onMousedownHandle),
- this.delegate.addEventListener(document, 'mousemove', this.onMousemoveHandle),
- this.delegate.addEventListener(document, 'mouseout', this.onMouseoutHandle),
- this.delegate.addEventListener(document, 'mouseover', this.onMouseoverHandle),
- this.delegate.addEventListener(document, 'mouseup', this.onMouseupHandle),
- this.delegate.addEventListener(
- document,
- 'wheel',
- this.onWheelHandle,
- this.wheelOptions,
- ),
- this.delegate.addEventListener(document, 'pointerover', this.onPointerHandle),
- this.delegate.addEventListener(document, 'pointerenter', this.onPointerHandle),
- this.delegate.addEventListener(document, 'pointerdown', this.onPointerHandle),
- this.delegate.addEventListener(document, 'pointermove', this.onPointerHandle),
- this.delegate.addEventListener(document, 'pointerup', this.onPointerHandle),
- this.delegate.addEventListener(document, 'pointercancel', this.onPointerHandle),
- this.delegate.addEventListener(document, 'pointerout', this.onPointerHandle),
- this.delegate.addEventListener(document, 'pointerleave', this.onPointerHandle),
- (this.updateIntervalHandle = setInterval(
- this.interactionUpdateHandle,
- t.PointerConfig.instance.pointerParams.mouseIntervalMillis,
- )),
- (this._isStarted = !0),
- t._POSignalsUtils.Logger.debug('Desktop Mouse events start listening...'));
- }),
- (e.prototype.stop = function () {
- this._isStarted
- ? (document.removeEventListener('click', this.onClickHandle, !0),
- document.removeEventListener('dblclick', this.onDblclickHandle),
- document.removeEventListener('mousedown', this.onMousedownHandle),
- document.removeEventListener('mousemove', this.onMousemoveHandle),
- document.removeEventListener('mouseout', this.onMouseoutHandle),
- document.removeEventListener('mouseover', this.onMouseoverHandle),
- document.removeEventListener('mouseup', this.onMouseupHandle),
- document.removeEventListener('wheel', this.onWheelHandle, this.wheelOptions),
- document.removeEventListener('pointerover', this.onPointerHandle),
- document.removeEventListener('pointerenter', this.onPointerHandle),
- document.removeEventListener('pointerdown', this.onPointerHandle),
- document.removeEventListener('pointermove', this.onPointerHandle),
- document.removeEventListener('pointerup', this.onPointerHandle),
- document.removeEventListener('pointercancel', this.onPointerHandle),
- document.removeEventListener('pointerout', this.onPointerHandle),
- document.removeEventListener('pointerleave', this.onPointerHandle),
- clearInterval(this.updateIntervalHandle),
- (this.updateIntervalHandle = null),
- (this._isStarted = !1),
- t._POSignalsUtils.Logger.debug('Desktop Mouse events stop listening...'))
- : t._POSignalsUtils.Logger.debug('Desktop Mouse events already stopped');
- }),
- (e.prototype.onClick = function (e) {
- var n, i;
- try {
- this.lastMouseInteractionTimestamp = new Date().getTime();
- var r = t._POSignalsUtils.Util.getSrcElement(e);
- if (
- (this._onClickEvent.dispatch(this, r),
- !this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE))
- )
- return;
- if (
- (this.countEvent(e.type),
- t.PointerConfig.instance.pointerParams.eventsToIgnore.has(e.type))
- )
- return;
- var a = this.uiControlManager.createUIControlData(e);
- this.updateInteraction(this.createMouseClickEvent(e.type, e), a),
- this.dispatch(),
- (null ===
- (i =
- null === (n = null === a || void 0 === a ? void 0 : a.uiElement) || void 0 === n
- ? void 0
- : n.id) || void 0 === i
- ? void 0
- : i.length) > 0 &&
- t._POSignalsUtils.Logger.info(
- "Tapped on element with id '" + a.uiElement.id + "'",
- );
- } catch (n) {
- t._POSignalsUtils.Logger.warn('error in ' + e.type + ' handler', n);
- }
- }),
- (e.prototype.onMouseout = function (e) {
- try {
- this.onMouseEvent(e);
- var n = e.relatedTarget || e.toElement;
- (n && 'HTML' !== n.nodeName) || this.dispatch();
- } catch (n) {
- t._POSignalsUtils.Logger.warn('error in ' + e.type + ' handler', n);
- }
- }),
- (e.prototype.onMouseEvent = function (e) {
- try {
- if (
- ('wheel' !== e.type && (this.lastMouseInteractionTimestamp = new Date().getTime()),
- !this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE))
- )
- return;
- if (
- (this.countEvent(e.type),
- t.PointerConfig.instance.pointerParams.eventsToIgnore.has(e.type))
- )
- return;
- this.updateInteraction(this.createMouseEvent(e.type, e));
- } catch (n) {
- t._POSignalsUtils.Logger.warn('error in ' + e.type + ' handler', n);
- }
- }),
- (e.prototype.onMouseClickEvent = function (e) {
- try {
- if (
- ((this.lastMouseInteractionTimestamp = new Date().getTime()),
- !this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE))
- )
- return;
- if (
- (this.countEvent(e.type),
- t.PointerConfig.instance.pointerParams.eventsToIgnore.has(e.type))
- )
- return;
- this.updateInteraction(this.createMouseClickEvent(e.type, e));
- } catch (n) {
- t._POSignalsUtils.Logger.warn('error in ' + e.type + ' handler', n);
- }
- }),
- (e.prototype.onPointerEvent = function (e) {
- try {
- if (
- ((this.lastMouseInteractionTimestamp = new Date().getTime()),
- !this.delegate.collectBehavioralData(this.BEHAVIORAL_TYPE))
- )
- return;
- if (
- (this.countEvent(e.type),
- t.PointerConfig.instance.pointerParams.eventsToIgnore.has(e.type))
- )
- return;
- this.updateInteraction(this.createPointerEvent(e.type, e));
- } catch (n) {
- t._POSignalsUtils.Logger.warn('error in ' + e.type + ' handler', n);
- }
- }),
- (e.prototype.clearBuffer = function () {
- var t = null;
- return (
- this.lastMouseInteraction && (t = this.lastMouseInteraction),
- (this.lastMouseInteraction = null),
- t
- );
- }),
- (e.prototype.isEmpty = function () {
- return !this.lastMouseInteraction;
- }),
- (e.prototype.createMouseEvent = function (t, e) {
- return {
- type: t,
- eventTs: e.timeStamp,
- epochTs: new Date().getTime(),
- button: e.button,
- offsetX: e.offsetX,
- offsetY: e.offsetY,
- pageX: e.pageX,
- pageY: e.pageY,
- screenX: e.screenX,
- screenY: e.screenY,
- getX: function () {
- return e.screenX;
- },
- getY: function () {
- return e.screenY;
- },
- };
- }),
- (e.prototype.createPointerEvent = function (t, e) {
- var n = this.createMouseEvent(t, e);
- return __assign(__assign({}, n), {
- pointerId: e.pointerId,
- width: e.width,
- height: e.height,
- pressure: e.pressure,
- tangentialPressure: e.tangentialPressure,
- tiltX: e.tiltX,
- tiltY: e.tiltY,
- twist: e.twist,
- pointerType: e.pointerType,
- isPrimary: e.isPrimary,
- });
- }),
- (e.prototype.createMouseClickEvent = function (e, n) {
- var i = this.createMouseEvent(e, n);
- if (n.target && t._POSignalsUtils.Util.isFunction(n.target.getBoundingClientRect)) {
- var r = n.target.getBoundingClientRect();
- (i.targetBottom = r.bottom),
- (i.targetHeight = r.height),
- (i.targetLeft = r.left),
- (i.targetRight = r.right),
- (i.targetTop = r.top),
- (i.targetWidth = r.width),
- (i.targetX = r.x),
- (i.targetY = r.y);
- }
- return i;
- }),
- e
- );
- })();
- t.Mouse = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(t) {
- (this.counter = 0), (this.key = t), (this.counter = this.loadFromStorage());
- }
- return (
- (e.prototype.loadFromStorage = function () {
- var t = e.sessionStorage.getItem(this.key);
- return Number(t) || 0;
- }),
- (e.prototype.get = function () {
- return this.counter;
- }),
- (e.prototype.increment = function (t) {
- void 0 === t && (t = 1),
- (this.counter += t),
- e.sessionStorage.setItem(this.key, this.counter);
- }),
- (e.prototype.decrement = function (t) {
- void 0 === t && (t = 1), this.increment(-1 * t);
- }),
- (e.prototype.reset = function () {
- (this.counter = 0), e.sessionStorage.removeItem(this.key);
- }),
- (e.sessionStorage = t._POSignalsStorage.SessionStorage.instance.sessionStorage),
- e
- );
- })();
- t.StorageCounter = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(t) {
- (this.mapKey = t), (this.cache = this.loadFromStorage());
- }
- return (
- (e.prototype.loadFromStorage = function () {
- var t = e.sessionStorage.getItem(this.mapKey);
- return t || (t = JSON.stringify({})), JSON.parse(t);
- }),
- (e.prototype.asMap = function () {
- return this.cache;
- }),
- (e.prototype.set = function (t, n, i) {
- void 0 === i && (i = !0),
- (this.cache[t] = n),
- i && e.sessionStorage.setItem(this.mapKey, JSON.stringify(this.cache));
- }),
- (e.prototype.sync = function () {
- e.sessionStorage.setItem(this.mapKey, JSON.stringify(this.cache));
- }),
- (e.prototype.get = function (t) {
- return this.cache[t];
- }),
- (e.prototype.delete = function (t) {
- delete this.cache[t], e.sessionStorage.setItem(this.mapKey, JSON.stringify(this.cache));
- }),
- (e.prototype.values = function () {
- return t._POSignalsUtils.Util.values(this.cache);
- }),
- (e.prototype.clear = function () {
- (this.cache = {}), e.sessionStorage.removeItem(this.mapKey);
- }),
- (e.sessionStorage = t._POSignalsStorage.SessionStorage.instance.sessionStorage),
- e
- );
- })();
- t.StorageMap = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e() {
- (this.config = {}), (this._cacheHash = 0), (this.cache = new Map());
- }
- return (
- (e.prototype.refreshConfig = function (e) {
- try {
- if (!e) return;
- var n = t._POSignalsUtils.Util.hashCode(JSON.stringify(e));
- if (this._cacheHash === n) return;
- (this.config = e), (this._cacheHash = n), (this.cache = new Map());
- } catch (e) {
- t._POSignalsUtils.Logger.warn('Failed to set css selectors', e);
- }
- }),
- (e.prototype.getMatchingTags = function (e, n) {
- var i = this.cache.get(e);
- if (i) return i;
- var r = {};
- for (var a in this.config)
- try {
- if (!this.config.hasOwnProperty(a)) continue;
- var o = this.config[a].selector || [];
- t._POSignalsUtils.Util.isArray(o) || (o = [].concat(o));
- for (var s = 0, u = o; s < u.length; s++) {
- var c = u[s];
- t._POSignalsUtils.Util.isSelectorMatches(e, c, n) && (r[a] = this.config[a]);
- }
- } catch (e) {
- t._POSignalsUtils.Logger.warn('Failed to get the config for ' + a + ' tag', e);
- }
- return this.cache.set(e, r), r;
- }),
- (e.prototype.getValue = function (e, n) {
- if (n && e)
- switch (((n = n.trim()), e)) {
- case 'email_domain':
- return t._POSignalsUtils.Util.getEmailDomain(n);
- case 'obfuscate':
- return '' + t._POSignalsUtils.Util.mod(n, 1e3);
- case 'plain':
- return n;
- case 'zip':
- return n.substr(0, 3);
- case 'length':
- return '' + n.length;
- }
- return '';
- }),
- Object.defineProperty(e.prototype, 'cacheHash', {
- get: function () {
- return this._cacheHash;
- },
- enumerable: !1,
- configurable: !0,
- }),
- e
- );
- })();
- t.TagsIdentifications = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e() {
- this._reduceFactorMap = null;
- }
- return (
- Object.defineProperty(e.prototype, 'reduceFactorMap', {
- get: function () {
- return this._reduceFactorMap;
- },
- set: function (t) {
- this._reduceFactorMap = t;
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.reduceEventsByFactor = function (e) {
- var n = this;
- try {
- if (!e || 0 === e.length || !this.reduceFactorMap) return e;
- for (var i = new Map(), r = [], a = 0; a < e.length; a++)
- i.get(e[a].type) ? i.get(e[a].type).push(a) : i.set(e[a].type, [a]);
- i.forEach(function (t, e) {
- var i = n.reduceFactorMap[e] ? Number(n.reduceFactorMap[e]) : 0;
- n.reduceByFactor(i, t, function (e) {
- r[t[e]] = !0;
- });
- });
- var o = [];
- for (a = 0; a < e.length; a++) r[a] && o.push(e[a]);
- return (
- e.length !== o.length &&
- t._POSignalsUtils.Logger.debug(
- e.length - o.length + ' events reduced out of ' + e.length,
- ),
- o
- );
- } catch (n) {
- return t._POSignalsUtils.Logger.warn('Failed to reduce events', n), e;
- }
- }),
- (e.prototype.reduceByFactor = function (t, e, n) {
- t = Math.min(t, 1);
- for (
- var i = Math.round(Math.max(e.length * (1 - t), 2)),
- r = (e.length - 1) / (i - 1),
- a = Math.min(e.length, i),
- o = 0;
- o < a;
- o++
- ) {
- n(Math.round(o * r));
- }
- }),
- e
- );
- })();
- t.ReduceFactor = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(t) {
- this.algorithm = t;
- }
- return (
- (e.prototype.reduce = function (n, i) {
- if (-1 === e.TYPES_TO_REDUCE.indexOf(i)) return { keptEvents: n, epsilon: 0 };
- if (n.length <= e.MIN_EVENTS_TO_REDUCE) return { keptEvents: n, epsilon: 0 };
- var r = n.length < 50 ? 0.55 : n.length < 100 ? 0.35 : 0.2,
- a = n.length < 50 ? 1 : n.length < 100 ? 3 : 7,
- o = this.algorithm.reduceEvents(n, a),
- s = o.length / n.length;
- if (o.length >= 10 && s >= r) return { keptEvents: o, epsilon: a };
- var u = n.length < 50 ? 0.1 : n.length < 100 ? 0.3 : 0.7,
- c = this.algorithm.reduceEvents(n, u),
- l = c.length / n.length;
- if (c.length <= e.MIN_EVENTS_TO_REDUCE || l <= r) return { keptEvents: c, epsilon: u };
- var d =
- (Math.min(a, Math.pow(a, s / r)) * Math.abs(l - r) + u * Math.abs(s - r)) /
- Math.abs(s - l);
- return (
- (d < u || d > a) &&
- t._POSignalsUtils.Logger.warn(
- 'linear weighted average - calculated epsilon is out of range, lowEpsilon: ' +
- u +
- ', highEpsilon: ' +
- a +
- ', epsilon: ' +
- d,
- ),
- { keptEvents: this.algorithm.reduceEvents(n, d), epsilon: d }
- );
- }),
- (e.MIN_EVENTS_TO_REDUCE = 18),
- (e.TYPES_TO_REDUCE = ['mousemove', 'touchmove']),
- e
- );
- })();
- t.RDPEpsilonStrategy = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e(t) {
- this.rdpStrategy = t;
- }
- return (
- (e.prototype.reduceWithRPD = function (e) {
- var n = this;
- if (!e || 0 === e.length) return { events: e, reductionInfo: {} };
- for (var i = new Map(), r = [], a = 0, o = e; a < o.length; a++) {
- var s = o[a];
- i.get(s.type) ? i.get(s.type).push(s) : i.set(s.type, [s]);
- }
- var u = {};
- return (
- i.forEach(function (t, e) {
- var i = n.rdpStrategy.reduce(t, e),
- a = i.keptEvents,
- o = i.epsilon;
- o > 0 && (u[e] = { epsilon: o, originalLength: t.length, keptLength: a.length }),
- (r = r.concat(a));
- }),
- { events: t._POSignalsUtils.Util.sortEventsByTimestamp(r), reductionInfo: u }
- );
- }),
- e
- );
- })();
- t.ReduceRDP = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function t() {}
- return (
- (t.prototype.getSqDist = function (t, e) {
- var n = t.getX() - e.getX(),
- i = t.getY() - e.getY();
- return n * n + i * i;
- }),
- (t.prototype.getSqSegDist = function (t, e, n) {
- var i = e.getX(),
- r = e.getY(),
- a = n.getX() - i,
- o = n.getY() - r;
- if (0 !== a || 0 !== o) {
- var s = ((t.getX() - i) * a + (t.getY() - r) * o) / (a * a + o * o);
- s > 1 ? ((i = n.getX()), (r = n.getY())) : s > 0 && ((i += a * s), (r += o * s));
- }
- return (a = t.getX() - i) * a + (o = t.getY() - r) * o;
- }),
- (t.prototype.simplifyRadialDist = function (t, e) {
- for (var n, i = t[0], r = [i], a = 1, o = t.length; a < o; a++)
- (n = t[a]), this.getSqDist(n, i) > e && (r.push(n), (i = n));
- return i !== n && r.push(n), r;
- }),
- (t.prototype.simplifyDPStep = function (t, e, n, i, r) {
- for (var a, o = i, s = e + 1; s < n; s++) {
- var u = this.getSqSegDist(t[s], t[e], t[n]);
- u > o && ((a = s), (o = u));
- }
- o > i &&
- (a - e > 1 && this.simplifyDPStep(t, e, a, i, r),
- r.push(t[a]),
- n - a > 1 && this.simplifyDPStep(t, a, n, i, r));
- }),
- (t.prototype.simplifyDouglasPeucker = function (t, e) {
- var n = t.length - 1,
- i = [t[0]];
- return this.simplifyDPStep(t, 0, n, e, i), i.push(t[n]), i;
- }),
- (t.prototype.simplify = function (t, e, n) {
- if (t.length <= 2) return t;
- var i = void 0 !== e ? e * e : 1;
- return (
- (t = n ? t : this.simplifyRadialDist(t, i)), (t = this.simplifyDouglasPeucker(t, i))
- );
- }),
- (t.prototype.reduceEvents = function (t, e) {
- return this.simplify(t, e);
- }),
- t
- );
- })();
- t.RDPReduction = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e() {}
- return (
- (e.prototype.filterMoveEvents = function (e, n) {
- if (e.length <= 18) return e;
- for (
- var i = e.filter(function (t) {
- return t.type === n;
- }),
- r = t._POSignalsUtils.Util.keepFirstEventsWithDistance({
- events: i,
- threshold: 200,
- min: 18,
- max: 30,
- }),
- a = -1,
- o = {},
- s = 0;
- s < e.length;
- s++
- ) {
- var u = e[s];
- u.type !== n &&
- ('mousedown' !== u.type ? o[u.type] || (r.push(u), (o[u.type] = !0)) : (a = s));
- }
- return a >= 0 && r.push(e[a]), t._POSignalsUtils.Util.sortEventsByTimestamp(r);
- }),
- e
- );
- })();
- t.EventsReduction = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e() {
- (this.reduceFactor = new t.ReduceFactor()),
- (this.reduceRDP = new t.ReduceRDP(new t.RDPEpsilonStrategy(new t.RDPReduction()))),
- (this.eventsReduction = new t.EventsReduction());
- }
- return (
- Object.defineProperty(e.prototype, 'reduceFactorMap', {
- set: function (t) {
- this.reduceFactor.reduceFactorMap = t;
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.prototype.reduceGesture = function (t) {
- var e = this.reduceRDP.reduceWithRPD(t.events);
- (t.events = this.eventsReduction.filterMoveEvents(e.events, 'touchmove')),
- (t.reduction = e.reductionInfo);
- }),
- (e.prototype.reduceKeyboardInteraction = function (e) {
- e.events = t._POSignalsUtils.Util.filterArrayByLength(e.events, 50);
- }),
- (e.prototype.reduceMouseInteraction = function (t) {
- var e = this.reduceRDP.reduceWithRPD(t.events);
- (t.events = this.eventsReduction.filterMoveEvents(e.events, 'mousemove')),
- (t.reduction = e.reductionInfo);
- }),
- e
- );
- })();
- t.ReductionManager = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function (e) {
- function n(n, i) {
- var r = e.call(this, n) || this;
- return (
- (r.tagsWithValueIdentifications = new t.TagsIdentifications()),
- (r.reductionManager = new t.ReductionManager()),
- (r.lastGestureTimestamp = 0),
- (r.currentBufferSize = 0),
- (r.bufferingStrategy = t.StrategyFactory.createBufferingStrategy(i, r)),
- (r.capturedKeyboardInteractions = new t.StorageArray(
- t._POSignalsUtils.Constants.CAPTURED_KEYBOARD_INTERACTIONS,
- )),
- (r.keyboardInteractionsCount = new t.StorageCounter(
- t._POSignalsUtils.Constants.KEYBOARD_INTERACTIONS_COUNT,
- )),
- (r.mouseInteractionsCount = new t.StorageCounter(
- t._POSignalsUtils.Constants.MOUSE_INTERACTIONS_COUNT,
- )),
- (r.gesturesCount = new t.StorageCounter(t._POSignalsUtils.Constants.GESTURES_COUNT)),
- (r.eventCounters = new t.StorageMap(t._POSignalsUtils.Constants.EVENT_COUNTERS)),
- (r.capturedMouseInteractions = new t.StorageArray(
- t._POSignalsUtils.Constants.CAPTURED_MOUSE_INTERACTIONS,
- )),
- (r.capturedGestures = new t.StorageArray(
- t._POSignalsUtils.Constants.CAPTURED_GESTURES,
- )),
- (r.capturedIndirectEvents = new t.StorageArray(
- t._POSignalsUtils.Constants.CAPTURED_INDIRECT,
- )),
- (r.currentBufferSize =
- r.capturedGestures.length +
- r.capturedMouseInteractions.length +
- r.capturedKeyboardInteractions.length),
- (r.uiControlManager = new t.UIControlManager(r)),
- (r.keyboard = new t.Keyboard(r, r.uiControlManager)),
- r.keyboard.onInteraction.subscribe(r.handleKeyboardInteraction.bind(r)),
- r.keyboard.onEnterPress.subscribe(r.handleStTagOnEnter.bind(r)),
- r.keyboard.onObfuscatedValue.subscribe(r.handleTagValueOnBlur.bind(r)),
- (r.mouse = new t.Mouse(r, r.uiControlManager)),
- r.mouse.onInteraction.subscribe(r.handleMouseInteraction.bind(r)),
- r.mouse.onClickEvent.subscribe(r.handleStTagOnClick.bind(r)),
- (r.sensors = new t.Sensors(r)),
- (r.gesture = new t.GestureEvents(r, r.sensors)),
- r.gesture.onGesture.subscribe(r.handleGesture.bind(r)),
- (r.indirect = new t.IndirectClient(r)),
- r.indirect.onIndirect.subscribe(r.handleIndirect.bind(r)),
- (r.onUrlChangeHandler = r.onUrlChange.bind(r)),
- (r.onEventHandler = r.onEvent.bind(r)),
- r
- );
- }
- return (
- __extends(n, e),
- Object.defineProperty(n.prototype, 'keyboardCounter', {
- get: function () {
- return this.keyboardInteractionsCount.get();
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'mouseCounter', {
- get: function () {
- return this.mouseInteractionsCount.get();
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'gesturesCounter', {
- get: function () {
- return this.gesturesCount.get();
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(n.prototype, 'additionalData', {
- get: function () {
- var e = t._POSignalsUtils.Util.getDeviceOrientation();
- return {
- locationHref: location.href,
- devTools: t._POSignalsUtils.Util.getDevToolsState(),
- innerWidth:
- window.innerWidth ||
- document.documentElement.clientWidth ||
- document.body.clientWidth,
- innerHeight:
- window.innerHeight ||
- document.documentElement.clientHeight ||
- document.body.clientHeight,
- outerWidth: window.outerWidth,
- outerHeight: window.outerHeight,
- width: screen.width,
- height: screen.height,
- availWidth: screen.availWidth,
- availHeight: screen.availHeight,
- pixelRatio: window.devicePixelRatio,
- deviceOrientation: e.orientation,
- deviceAngle: e.angle,
- };
- },
- enumerable: !1,
- configurable: !0,
- }),
- (n.prototype.getBehavioralData = function () {
- return (
- this.clearIndirectBuffer(),
- {
- mouse: {
- count: this.mouseInteractionsCount.get(),
- interactions: this.capturedMouseInteractions.get(),
- },
- keyboard: {
- count: this.keyboardInteractionsCount.get(),
- interactions: this.capturedKeyboardInteractions.get(),
- },
- touch: {
- count: this.gesturesCount.get(),
- interactions: this.capturedGestures.get(),
- },
- indirect: { events: this.capturedIndirectEvents.get() },
- eventCounters: this.eventCounters.asMap(),
- }
- );
- }),
- (n.prototype.getBufferSize = function () {
- return this.currentBufferSize;
- }),
- (n.prototype.getInteractionDuration = function (t) {
- return (null === t || void 0 === t ? void 0 : t.length) > 0
- ? t[t.length - 1].epochTs - t[0].epochTs
- : 0;
- }),
- (n.prototype.dispose = function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (t) {
- return (
- this.stopListening(),
- this.keyboard.onInteraction.unsubscribe(
- this.handleKeyboardInteraction.bind(this),
- ),
- this.keyboard.onEnterPress.unsubscribe(this.handleStTagOnEnter.bind(this)),
- this.keyboard.onObfuscatedValue.unsubscribe(this.handleTagValueOnBlur.bind(this)),
- this.mouse.onInteraction.unsubscribe(this.handleMouseInteraction.bind(this)),
- this.mouse.onClickEvent.unsubscribe(this.handleStTagOnClick.bind(this)),
- this.gesture.onGesture.unsubscribe(this.handleGesture.bind(this)),
- this.indirect.unsubscribe(),
- this.indirect.onIndirect.unsubscribe(this.handleIndirect.bind(this)),
- [2]
- );
- });
- });
- }),
- (n.prototype.collectBehavioralData = function (e) {
- if (this.isBehavioralDataPaused) return !1;
- var n = t.PointerConfig.instance.pointerParams.behavioralBlacklist;
- return !(e && n && n[e]) || !Boolean(window.location.href.match(n[e]));
- }),
- (n.prototype.getElementsStID = function (e) {
- try {
- return (
- t._POSignalsUtils.Util.getAttribute(e, 'data-st-field') ||
- this.keyboard.fieldsIdentifications.getIdentification(e, 0) ||
- ''
- );
- } catch (e) {
- return t._POSignalsUtils.Logger.warn('failed to get element stId', e), '';
- }
- }),
- (n.prototype.addEventListener = function (e, n, i, r) {
- t.PointerConfig.instance.pointerParams.eventsBlackList.has(n) ||
- (e.addEventListener(n, this.onEventHandler, r), e.addEventListener(n, i, r));
- }),
- (n.prototype.addUiControlTags = function (e) {
- if ((null === e || void 0 === e ? void 0 : e.length) > 0)
- for (var n = !1, i = 0, r = e; i < r.length; i++) {
- var a = r[i];
- try {
- if (null === a || void 0 === a ? void 0 : a.name) {
- var o = this.uiControlManager.convertToTagValueConfig(a.value);
- n = this.addSingleTagWithValue(a.name, o) || n;
- }
- } catch (e) {
- t._POSignalsUtils.Logger.warn('failed to add tag config', e);
- }
- }
- }),
- (n.prototype.refreshListening = function () {
- var e = t.PointerConfig.instance;
- this.tagsWithValueIdentifications.refreshConfig(e.pointerParams.remoteTags),
- (this.reductionManager.reduceFactorMap = e.pointerParams.eventsReduceFactorMap),
- this.keyboard.refreshKeyboardCssSelectors(e.pointerParams.keyboardCssSelectors),
- (this.sensors.maxSensorSamples = e.pointerParams.maxSensorSamples),
- (this.sensors.sensorsTimestampDeltaInMillis = e.pointerParams.sensorsDeltaInMillis),
- this.mouse.start(),
- this.keyboard.start(),
- this.gesture.start(),
- this.indirect.start(),
- 0 == e.pointerParams.maxSensorSamples ? this.sensors.stop() : this.sensors.start(),
- this.addEventListener(window, '_onlocationchange', this.onUrlChangeHandler),
- this.addEventListener(window, 'popstate', this.onUrlChangeHandler);
- }),
- (n.prototype.addSingleTagWithValue = function (e, n) {
- try {
- if (
- (null === n || void 0 === n ? void 0 : n.context) &&
- !Boolean(window.location.href.match(n.context))
- )
- return !1;
- var i = '';
- if (
- (null === n || void 0 === n ? void 0 : n.operation) &&
- (null === n || void 0 === n ? void 0 : n.valueSelector)
- ) {
- var r = document.querySelector(n.valueSelector);
- if (r) {
- var a = t._POSignalsUtils.Util.getElementText(r);
- i = this.tagsWithValueIdentifications.getValue(n.operation, a);
- }
- }
- if ((null === n || void 0 === n ? void 0 : n.valueMandatory) && !i)
- return (
- t._POSignalsUtils.Logger.warn("tag '" + e + "' wasn't added. value is missing"),
- !1
- );
- this.addTag(e, i);
- } catch (n) {
- t._POSignalsUtils.Logger.warn('failed to add ' + e + ' tag', n);
- }
- return !1;
- }),
- (n.prototype.addTagsWithValue = function (t) {
- var e = !1;
- for (var n in t) t.hasOwnProperty(n) && (e = this.addSingleTagWithValue(n, t[n]) || e);
- }),
- (n.prototype.handleStTagOnEnter = function (e, n) {
- n instanceof HTMLInputElement &&
- t._POSignalsUtils.Util.isTextInput(n) &&
- this.handleStTagElement(n);
- }),
- (n.prototype.handleTagValueOnBlur = function (t, e) {
- e && this.addTag(e.fieldKey, e.obfuscatedValue);
- }),
- (n.prototype.handleStTagOnClick = function (e, n) {
- (n instanceof HTMLInputElement && !t._POSignalsUtils.Util.isClickableInput(n)) ||
- this.handleStTagElement(n);
- }),
- (n.prototype.handleMouseInteraction = function (t, e) {
- if (e) {
- this.mouseInteractionsCount.increment(),
- this.reductionManager.reduceMouseInteraction(e);
- var n = this.bufferingStrategy.calculateStrategyResult(e, 'mouse');
- n.shouldCollect &&
- (n.remove && this.removeInteraction(n.remove),
- this.capturedMouseInteractions.push(e),
- this.lastGestureTimestamp !== e.events[e.events.length - 1].eventTs &&
- this.currentBufferSize++,
- this.eventCounters.sync());
- }
- }),
- (n.prototype.handleIndirect = function (t, e) {
- this.addIndirectEvents(e), this.eventCounters.sync();
- }),
- (n.prototype.handleKeyboardInteraction = function (t, e) {
- if (e) {
- this.keyboardInteractionsCount.increment(),
- this.reductionManager.reduceKeyboardInteraction(e);
- var n = this.bufferingStrategy.calculateStrategyResult(e, 'keyboard');
- n.shouldCollect &&
- (n.remove && this.removeInteraction(n.remove),
- this.capturedKeyboardInteractions.push(e),
- this.currentBufferSize++,
- this.eventCounters.sync());
- }
- }),
- (n.prototype.handleGesture = function (t, e) {
- var n;
- if (this.isValidGesture(e)) {
- this.gesturesCount.increment(), this.reductionManager.reduceGesture(e);
- var i = this.bufferingStrategy.calculateStrategyResult(e, 'touch');
- i.shouldCollect &&
- (i.remove && this.removeInteraction(i.remove),
- this.sensors.onGesture(e),
- this.capturedGestures.push(e),
- this.currentBufferSize++,
- (this.lastGestureTimestamp =
- null === (n = e.events[e.events.length - 1]) || void 0 === n
- ? void 0
- : n.eventTs),
- this.eventCounters.sync());
- }
- }),
- (n.prototype.clearIndirectBuffer = function () {
- var t = this.indirect.clearBuffer();
- this.addIndirectEvents(t);
- }),
- (n.prototype.removeInteraction = function (t) {
- switch (t.type) {
- case 'mouse':
- this.capturedMouseInteractions.remove(t.index);
- break;
- case 'keyboard':
- this.capturedKeyboardInteractions.remove(t.index);
- break;
- case 'touch':
- this.capturedGestures.remove(t.index);
- }
- }),
- (n.prototype.addIndirectEvents = function (e) {
- var n;
- if (
- (null === (n = null === e || void 0 === e ? void 0 : e.events) || void 0 === n
- ? void 0
- : n.length) > 0
- ) {
- for (
- var i = [],
- r = t._POSignalsUtils.Util.typesCounter(this.capturedIndirectEvents.get()),
- a = 0,
- o = e.events;
- a < o.length;
- a++
- ) {
- var s = o[a];
- t.PointerConfig.instance.pointerParams.highPriorityIndirectEvents.has(s.type) &&
- this.capturedIndirectEvents.length + i.length <
- t.PointerConfig.instance.pointerParams.maxIndirectEvents &&
- i.push(s),
- r[s.type] > 0 || (i.push(s), (r[s.type] = 1));
- }
- this.capturedIndirectEvents.set(this.capturedIndirectEvents.concat(i));
- }
- }),
- (n.prototype.onUrlChange = function () {
- this.addTag('location', window.location.href);
- }),
- (n.prototype.onEvent = function (t) {
- this.isBehavioralDataPaused ||
- this.eventCounters.set(t.type, (this.eventCounters.get(t.type) || 0) + 1, !1);
- }),
- (n.prototype.handleStTagElement = function (e) {
- if (e) {
- var n = t.PointerConfig.instance.pointerParams.maxSelectorChildren,
- i = this.tagsWithValueIdentifications.getMatchingTags(e, n);
- this.addTagsWithValue(i);
- var r = t._POSignalsUtils.Util.isSelectorMatches(e, '[data-st-tag]', n);
- if (r instanceof Element) {
- var a = t._POSignalsUtils.Util.getAttribute(r, 'data-st-tag'),
- o = t._POSignalsUtils.Util.getAttribute(r, 'data-st-tag-value');
- a && this.addTag(a, o);
- }
- }
- }),
- (n.prototype.stopListening = function () {
- this.keyboard.stop(),
- this.mouse.stop(),
- this.gesture.stop(),
- this.indirect.stop(),
- this.sensors.stop(),
- window.removeEventListener('_onlocationchange', this.onUrlChangeHandler),
- window.removeEventListener('popstate', this.onUrlChangeHandler);
- }),
- (n.prototype.clearBehavioralData = function () {
- this.capturedKeyboardInteractions.clear(),
- this.capturedMouseInteractions.clear(),
- this.capturedGestures.clear(),
- this.capturedIndirectEvents.clear(),
- this.sensors.reset(),
- t.Tags.instance.reset(),
- (this.currentBufferSize = 0),
- this.keyboardInteractionsCount.reset(),
- this.mouseInteractionsCount.reset(),
- this.gesturesCount.reset(),
- this.eventCounters.clear();
- }),
- (n.prototype.isValidGesture = function (e) {
- var n, i;
- return (
- (null === (n = null === e || void 0 === e ? void 0 : e.events) || void 0 === n
- ? void 0
- : n.length) > 0 &&
- (null === (i = null === e || void 0 === e ? void 0 : e.events) || void 0 === i
- ? void 0
- : i.length) < t.PointerConfig.instance.pointerParams.maxSnapshotsCount
- );
- }),
- n
- );
- })(t.ClientBase);
- t.Client = e;
- })(_POSignalsEntities || (_POSignalsEntities = {}));
- var _POSignalsEntities,
- _pingOneSignals = (function () {
- function t() {}
- return (
- (t.getData = function () {
- return _POSignalsEntities.ClientBase.instance().getData();
- }),
- (t.init = function (t) {
- return (
- _POSignalsEntities._POSignalsUtils.Util.ieFix(),
- _POSignalsEntities.ClientBase.instance().startSignals(t)
- );
- }),
- (t.initSilent = function (t) {
- return this.init(t);
- }),
- (t.pauseBehavioralData = function () {
- _POSignalsEntities.ClientBase.instance().pauseBehavioralData();
- }),
- (t.resumeBehavioralData = function () {
- _POSignalsEntities.ClientBase.instance().resumeBehavioralData();
- }),
- t
- );
- })(),
- onDomReady = function (t) {
- 'loading' !== document.readyState ? t() : document.addEventListener('DOMContentLoaded', t);
- };
- onDomReady(function () {
- if (!window._pingOneSignalsReady) {
- var t = new CustomEvent('PingOneSignalsReadyEvent');
- document.dispatchEvent(t), (window._pingOneSignalsReady = !0);
- }
- }),
- (function (t) {
- var e = (function () {
- function e(t, e, n, i, r, a, o) {
- (this.clientVersion = t),
- (this.instanceUUID = e),
- (this.initParams = n),
- (this.metadata = i),
- (this.behavioralDataHandler = r),
- (this.externalIdentifiers = a),
- (this.sessionStorage = o);
- }
- return (
- (e.prototype.getData = function (t) {
- return __awaiter(this, void 0, void 0, function () {
- var e;
- return __generator(this, function (n) {
- switch (n.label) {
- case 0:
- return [4, this.getRiskData(t)];
- case 1:
- return (e = n.sent()), [2, this.toString(e)];
- }
- });
- });
- }),
- (e.prototype.getRiskData = function (e) {
- return __awaiter(this, void 0, void 0, function () {
- var n, i;
- return __generator(this, function (r) {
- switch (r.label) {
- case 0:
- return (i = {}), [4, this.metadata.getDeviceAttributes()];
- case 1:
- return (
- (i.deviceAttributes = r.sent()),
- (i.behavioral = this.behavioralDataHandler.getBehavioralData()),
- (i.tags = t.Tags.instance.tags),
- (i.sdkConfig = this.initParams),
- (i.epochTs = e),
- (i.instanceUUID = this.instanceUUID),
- (i.tabUUID = t._POSignalsStorage.SessionStorage.instance.tabUUID),
- (i.origin = location.origin),
- (i.href = location.href),
- (i.sdkVersion = this.clientVersion),
- (i.platform = 'web'),
- (i.clientToken = window._pingOneSignalsToken),
- (i.externalIdentifiers = this.externalIdentifiers),
- (n = i),
- this.sessionStorage.deviceTrust &&
- (n.deviceTrust = this.sessionStorage.deviceTrust),
- [2, n]
- );
- }
- });
- });
- }),
- (e.prototype.toString = function (e) {
- var n,
- i = this.metadata.getObfsInfo();
- try {
- n = t._POSignalsUtils.Util.string2buf(JSON.stringify(e));
- } catch (t) {
- throw new Error('Failed to create data, ' + t.message);
- }
- try {
- n = t.pako.gzip(n);
- } catch (t) {
- throw new Error('Failed to compress data, ' + t.message);
- }
- try {
- n = t._POSignalsUtils.Util.encryptionBytes(n, i.key);
- } catch (t) {
- throw new Error('failed to obfuscate data, ' + t.message);
- }
- try {
- return t._POSignalsUtils.Util.base64Uint8Array(n) + '.' + btoa(i.identifier);
- } catch (t) {
- throw new Error('failed to encode data, ' + t.message);
- }
- }),
- e
- );
- })();
- t.DataHandler = e;
- })(_POSignalsEntities || (_POSignalsEntities = {})),
- (function (t) {
- var e = (function () {
- function e() {
- this._configuration = {
- enabled: e.ENABLED_DEFAULT,
- bufferSize: e.BUFFER_SIZE_DEFAULT,
- maxSnapshotsCount: e.MAX_SNAPSHOTS_COUNT_DEFAULT,
- sensors: e.SENSORS_DEFAULT,
- metadataBlacklist: e.METADATA_BLACK_LIST_DEFAULT,
- tagsBlacklistRegex: e.TAGS_BLACK_LIST_REGEX_DEFAULT,
- behavioralBlacklist: e.BEHAVIORAL_BLACK_LIST_DEFAULT,
- webRtcUrl: e.WEB_RTC_URL_DEFAULT,
- eventsBlackList: e.EVENTS_BLACK_LIST_DEFAULT,
- eventsToIgnore: e.EVENTS_TO_IGNORE_DEFAULT,
- highPriorityIndirectEvents: e.HIGH_PRIORITY_INDIRECT_EVENTS_DEFAULT,
- indirectIntervalMillis: e.INDIRECT_INTERVAL_MILLIS_DEFAULT,
- mouseIntervalMillis: e.MOUSE_INTERVAL_MILLIS_DEFAULT,
- mouseIdleTimeoutMillis: e.MOUSE_IDLE_TIMEOUT_MILLIS_DEFAULT,
- maxMouseEvents: e.MAX_MOUSE_EVENTS_DEFAULT,
- maxIndirectEvents: e.MAX_INDIRECT_EVENTS_DEFAULT,
- keyboardFieldBlackList: e.KEYBOARD_FIELD_BLACK_LIST_DEFAULT,
- keyboardCssSelectors: e.KEYBOARD_CSS_SELECTORS_DEFAULT,
- keyboardCssSelectorsBlacklist: e.KEYBOARD_CSS_SELECTORS_BLACKLIST_DEFAULT,
- keyboardIdentifierAttributes: e.KEYBOARD_IDENTIFIER_ATTRIBUTES_DEFAULT,
- remoteTags: e.REMOTE_TAGS_DEFAULT,
- maxSelectorChildren: e.MAX_SELECTOR_CHILDREN_DEFAULT,
- eventsReduceFactorMap: e.EVENTS_REDUCE_FACTOR_MAP_DEFAULT,
- propertyDescriptors: e.PROPERTY_DESCRIPTORS_DEFAULT,
- additionalMediaCodecs: e.ADDITIONAL_MEDIA_CODECS_DEFAULT,
- fingerprintTimeoutMillis: e.FINGER_PRINT_TIMEOUT_MILLIS_DEFAULT,
- metadataDataPoints: e.METADATA_DATA_POINTS_DEFAULT,
- uiModeling: e.UI_MODELING_CONFIG_DEFAULT,
- uiControl: e.UI_CONTROL_LIST_DEFAULT,
- };
- }
- return (
- (e.prototype.updateParams = function (t) {
- t && (this._configuration = t);
- }),
- Object.defineProperty(e.prototype, 'enabled', {
- get: function () {
- return 'boolean' == typeof this._configuration.enabled
- ? this._configuration.enabled
- : e.ENABLED_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'bufferSize', {
- get: function () {
- return 'number' == typeof this._configuration.bufferSize &&
- this._configuration.bufferSize > 0
- ? this._configuration.bufferSize
- : e.BUFFER_SIZE_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'maxSnapshotsCount', {
- get: function () {
- return 'number' == typeof this._configuration.maxSnapshotsCount &&
- this._configuration.maxSnapshotsCount >= 0
- ? this._configuration.maxSnapshotsCount
- : e.MAX_SNAPSHOTS_COUNT_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'maxSensorSamples', {
- get: function () {
- var t = this._configuration.sensors;
- return t && 'number' == typeof t.maxSensorSamples && t.maxSensorSamples >= 0
- ? t.maxSensorSamples
- : e.SENSORS_DEFAULT.maxSensorSamples;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'sensorsDeltaInMillis', {
- get: function () {
- var t = this._configuration.sensors;
- return t && 'number' == typeof t.sensorsDeltaInMillis && t.sensorsDeltaInMillis >= 0
- ? t.sensorsDeltaInMillis
- : e.SENSORS_DEFAULT.sensorsDeltaInMillis;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'metadataBlackList', {
- get: function () {
- var n;
- return t._POSignalsUtils.Util.isArray(this._configuration.metadataBlacklist) &&
- (null === (n = this._configuration.metadataBlacklist) || void 0 === n
- ? void 0
- : n.length) > 0
- ? this._configuration.metadataBlacklist
- : e.METADATA_BLACK_LIST_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'behavioralBlacklist', {
- get: function () {
- return this._configuration.behavioralBlacklist
- ? this._configuration.behavioralBlacklist
- : e.BEHAVIORAL_BLACK_LIST_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'tagsBlacklistRegex', {
- get: function () {
- return 'string' == typeof this._configuration.tagsBlacklistRegex
- ? this._configuration.tagsBlacklistRegex
- : e.TAGS_BLACK_LIST_REGEX_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'webRtcUrl', {
- get: function () {
- return 'string' == typeof this._configuration.webRtcUrl
- ? this._configuration.webRtcUrl
- : e.WEB_RTC_URL_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'eventsBlackList', {
- get: function () {
- return (
- t._POSignalsUtils.Util.isArray(this._configuration.eventsBlackList) &&
- (this._configuration.eventsBlackList = new Set(
- this._configuration.eventsBlackList,
- )),
- this._configuration.eventsBlackList instanceof Set
- ? this._configuration.eventsBlackList
- : e.EVENTS_BLACK_LIST_DEFAULT
- );
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'eventsToIgnore', {
- get: function () {
- return (
- t._POSignalsUtils.Util.isArray(this._configuration.eventsToIgnore) &&
- (this._configuration.eventsToIgnore = new Set(
- this._configuration.eventsToIgnore,
- )),
- this._configuration.eventsToIgnore instanceof Set
- ? this._configuration.eventsToIgnore
- : e.EVENTS_TO_IGNORE_DEFAULT
- );
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'highPriorityIndirectEvents', {
- get: function () {
- return (
- t._POSignalsUtils.Util.isArray(this._configuration.highPriorityIndirectEvents) &&
- (this._configuration.highPriorityIndirectEvents = new Set(
- this._configuration.highPriorityIndirectEvents,
- )),
- this._configuration.highPriorityIndirectEvents instanceof Set
- ? this._configuration.highPriorityIndirectEvents
- : e.HIGH_PRIORITY_INDIRECT_EVENTS_DEFAULT
- );
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'indirectIntervalMillis', {
- get: function () {
- return 'number' == typeof this._configuration.indirectIntervalMillis &&
- this._configuration.indirectIntervalMillis > 0
- ? this._configuration.indirectIntervalMillis
- : e.INDIRECT_INTERVAL_MILLIS_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'mouseIntervalMillis', {
- get: function () {
- return 'number' == typeof this._configuration.mouseIntervalMillis &&
- this._configuration.mouseIntervalMillis > 0
- ? this._configuration.mouseIntervalMillis
- : e.MOUSE_INTERVAL_MILLIS_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'mouseIdleTimeoutMillis', {
- get: function () {
- return 'number' == typeof this._configuration.mouseIdleTimeoutMillis &&
- this._configuration.mouseIdleTimeoutMillis > 0
- ? this._configuration.mouseIdleTimeoutMillis
- : e.MOUSE_IDLE_TIMEOUT_MILLIS_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'maxMouseEvents', {
- get: function () {
- return 'number' == typeof this._configuration.maxMouseEvents &&
- this._configuration.maxMouseEvents >= 0
- ? this._configuration.maxMouseEvents
- : e.MAX_MOUSE_EVENTS_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'maxIndirectEvents', {
- get: function () {
- return 'number' == typeof this._configuration.maxIndirectEvents &&
- this._configuration.maxIndirectEvents >= 0
- ? this._configuration.maxIndirectEvents
- : e.MAX_INDIRECT_EVENTS_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'keyboardFieldBlackList', {
- get: function () {
- return (
- t._POSignalsUtils.Util.isArray(this._configuration.keyboardFieldBlackList) &&
- (this._configuration.keyboardFieldBlackList = new Set(
- this._configuration.keyboardFieldBlackList,
- )),
- this._configuration.keyboardFieldBlackList instanceof Set
- ? this._configuration.keyboardFieldBlackList
- : e.KEYBOARD_FIELD_BLACK_LIST_DEFAULT
- );
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'keyboardCssSelectors', {
- get: function () {
- return this._configuration.keyboardCssSelectors
- ? this._configuration.keyboardCssSelectors
- : e.KEYBOARD_CSS_SELECTORS_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'keyboardCssSelectorsBlacklist', {
- get: function () {
- return t._POSignalsUtils.Util.isArray(
- this._configuration.keyboardCssSelectorsBlacklist,
- )
- ? this._configuration.keyboardCssSelectorsBlacklist
- : e.KEYBOARD_CSS_SELECTORS_BLACKLIST_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'keyboardIdentifierAttributes', {
- get: function () {
- return t._POSignalsUtils.Util.isArray(
- this._configuration.keyboardIdentifierAttributes,
- )
- ? this._configuration.keyboardIdentifierAttributes
- : e.KEYBOARD_IDENTIFIER_ATTRIBUTES_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'remoteTags', {
- get: function () {
- return this._configuration.remoteTags
- ? this._configuration.remoteTags
- : e.REMOTE_TAGS_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'maxSelectorChildren', {
- get: function () {
- return 'number' == typeof this._configuration.maxSelectorChildren &&
- this._configuration.maxSelectorChildren > 0
- ? this._configuration.maxSelectorChildren
- : e.MAX_SELECTOR_CHILDREN_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'eventsReduceFactorMap', {
- get: function () {
- return this._configuration.eventsReduceFactorMap
- ? this._configuration.eventsReduceFactorMap
- : e.EVENTS_REDUCE_FACTOR_MAP_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'propertyDescriptors', {
- get: function () {
- return this._configuration.propertyDescriptors
- ? this._configuration.propertyDescriptors
- : e.PROPERTY_DESCRIPTORS_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'additionalMediaCodecs', {
- get: function () {
- return this._configuration.additionalMediaCodecs
- ? this._configuration.additionalMediaCodecs
- : e.ADDITIONAL_MEDIA_CODECS_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'fingerprintTimeoutMillis', {
- get: function () {
- return 'number' == typeof this._configuration.fingerprintTimeoutMillis &&
- this._configuration.fingerprintTimeoutMillis > 0
- ? this._configuration.fingerprintTimeoutMillis
- : e.FINGER_PRINT_TIMEOUT_MILLIS_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'metadataDataPoints', {
- get: function () {
- return this._configuration.metadataDataPoints
- ? this._configuration.metadataDataPoints
- : e.METADATA_DATA_POINTS_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'uiModelingBlacklistRegex', {
- get: function () {
- var t;
- return 'string' ==
- typeof (null === (t = this._configuration.uiModeling) || void 0 === t
- ? void 0
- : t.blacklistRegex)
- ? this._configuration.uiModeling.blacklistRegex
- : e.UI_MODELING_CONFIG_DEFAULT.blacklistRegex;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'uiModelingElementFilters', {
- get: function () {
- var t;
- return (
- null === (t = this._configuration.uiModeling) || void 0 === t
- ? void 0
- : t.uiElementFilters
- )
- ? this._configuration.uiModeling.uiElementFilters
- : e.UI_MODELING_CONFIG_DEFAULT.uiElementFilters;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'uiModelingMaxMatchingParents', {
- get: function () {
- var t;
- return 'number' ==
- typeof (null === (t = this._configuration.uiModeling) || void 0 === t
- ? void 0
- : t.maxMatchingParents)
- ? this._configuration.uiModeling.maxMatchingParents
- : e.UI_MODELING_CONFIG_DEFAULT.maxMatchingParents;
- },
- enumerable: !1,
- configurable: !0,
- }),
- Object.defineProperty(e.prototype, 'uiControlsConfig', {
- get: function () {
- return t._POSignalsUtils.Util.isArray(this._configuration.uiControl)
- ? this._configuration.uiControl
- : e.UI_CONTROL_LIST_DEFAULT;
- },
- enumerable: !1,
- configurable: !0,
- }),
- (e.ENABLED_DEFAULT = !0),
- (e.BUFFER_SIZE_DEFAULT = 4),
- (e.MAX_SNAPSHOTS_COUNT_DEFAULT = 500),
- (e.METADATA_BLACK_LIST_DEFAULT = []),
- (e.TAGS_BLACK_LIST_REGEX_DEFAULT = ''),
- (e.BEHAVIORAL_BLACK_LIST_DEFAULT = {}),
- (e.WEB_RTC_URL_DEFAULT = ''),
- (e.EVENTS_BLACK_LIST_DEFAULT = new Set()),
- (e.EVENTS_TO_IGNORE_DEFAULT = new Set([
- 'pointerover',
- 'pointerenter',
- 'pointerdown',
- 'pointermove',
- 'pointerup',
- 'pointercancel',
- 'pointerout',
- 'pointerleave',
- 'dragstart',
- 'dragexit',
- 'drop',
- 'dragend',
- ])),
- (e.MAX_INDIRECT_EVENTS_DEFAULT = 15),
- (e.HIGH_PRIORITY_INDIRECT_EVENTS_DEFAULT = new Set([
- 'copy',
- 'cut',
- 'paste',
- 'resize',
- 'orientationchange',
- 'languagechange',
- 'submit',
- 'select',
- ])),
- (e.INDIRECT_INTERVAL_MILLIS_DEFAULT = 1e3),
- (e.MOUSE_INTERVAL_MILLIS_DEFAULT = 1e3),
- (e.MOUSE_IDLE_TIMEOUT_MILLIS_DEFAULT = 1e3),
- (e.MAX_MOUSE_EVENTS_DEFAULT = 500),
- (e.KEYBOARD_FIELD_BLACK_LIST_DEFAULT = new Set()),
- (e.KEYBOARD_CSS_SELECTORS_DEFAULT = {}),
- (e.KEYBOARD_CSS_SELECTORS_BLACKLIST_DEFAULT = []),
- (e.KEYBOARD_IDENTIFIER_ATTRIBUTES_DEFAULT = [
- 'data-selenium',
- 'data-selenium-id',
- 'data-testid',
- 'data-test-id',
- 'data-qa-id',
- 'data-id',
- 'id',
- ]),
- (e.REMOTE_TAGS_DEFAULT = {
- dv_form_submit: { selector: '[data-skbuttontype="form-submit"]' },
- login_attempt_email_domain: {
- selector: '[data-st-tag="login.login_attempt"]',
- operation: 'email_domain',
- valueSelector: '[data-st-field="username"]',
- valueMandatory: !0,
- },
- login_attempt_hash: {
- selector: '[data-st-tag="login.login_attempt"]',
- operation: 'obfuscate',
- valueSelector: '[data-st-field="username"]',
- valueMandatory: !0,
- },
- login_attempt_length: {
- selector: '[data-st-tag="login.login_attempt"]',
- operation: 'length',
- valueSelector: '[data-st-field="username"]',
- valueMandatory: !0,
- },
- registration_attempt_email_domain: {
- selector: '[data-st-tag="registration.registration_attempt"]',
- operation: 'email_domain',
- valueSelector: '[data-st-field="username"]',
- valueMandatory: !0,
- },
- registration_attempt_hash: {
- selector: '[data-st-tag="registration.registration_attempt"]',
- operation: 'obfuscate',
- valueSelector: '[data-st-field="username"]',
- valueMandatory: !0,
- },
- registration_attempt_length: {
- selector: '[data-st-tag="registration.registration_attempt"]',
- operation: 'length',
- valueSelector: '[data-st-field="username"]',
- valueMandatory: !0,
- },
- }),
- (e.MAX_SELECTOR_CHILDREN_DEFAULT = 2),
- (e.EVENTS_REDUCE_FACTOR_MAP_DEFAULT = {}),
- (e.PROPERTY_DESCRIPTORS_DEFAULT = {
- chrome: ['app', 'csi', 'loadtimes', 'runtime'],
- navigator: ['webdriver'],
- Navigator: ['languages', 'hardwareConcurrency'],
- window: ['outerWidth', 'outerHeight'],
- Screen: ['width', 'height'],
- }),
- (e.ADDITIONAL_MEDIA_CODECS_DEFAULT = {}),
- (e.FINGER_PRINT_TIMEOUT_MILLIS_DEFAULT = 3e3),
- (e.METADATA_DATA_POINTS_DEFAULT = {}),
- (e.UI_CONTROL_LIST_DEFAULT = []),
- (e.UI_MODELING_CONFIG_DEFAULT = {
- blacklistRegex: '',
- uiElementFilters: { text: { maxLength: 25 }, placeholder: { maxLength: 25 } },
- maxMatchingParents: 2,
- }),
- (e.SENSORS_DEFAULT = { maxSensorSamples: 1, sensorsDeltaInMillis: 0 }),
- e
- );
- })();
- t.PointerParams = e;
- })(_POSignalsEntities || (_POSignalsEntities = {}));
- window._POSignalsEntities = _POSignalsEntities;
- window._pingOneSignals = _pingOneSignals;
-}
-// Ping Identity INC.
-// � ALL RIGHTS RESERVED
-//Build: 563 Wed May 01 2024 10:49:20 GMT+0000 (Coordinated Universal Time)
diff --git a/packages/ping-protect/tsconfig.json b/packages/ping-protect/tsconfig.json
deleted file mode 100644
index 999bce7c5..000000000
--- a/packages/ping-protect/tsconfig.json
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "extends": "../../tsconfig.base.json",
- "compilerOptions": {
- "module": "ES2020",
- "forceConsistentCasingInFileNames": true,
- "strict": true,
- "noImplicitOverride": false,
- "noPropertyAccessFromIndexSignature": false,
- "skipLibCheck": true,
- "noImplicitReturns": true,
- "noFallthroughCasesInSwitch": true,
- "types": [
- "vitest/globals",
- "vitest/importMeta",
- "vite/client",
- "node",
- "vitest"
- ]
- },
- "files": [],
- "include": [],
- "references": [
- {
- "path": "./tsconfig.lib.json"
- },
- {
- "path": "./tsconfig.spec.json"
- }
- ]
-}
diff --git a/packages/ping-protect/tsconfig.lib.json b/packages/ping-protect/tsconfig.lib.json
deleted file mode 100644
index a64c903c9..000000000
--- a/packages/ping-protect/tsconfig.lib.json
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "../../dist/packages/javascript-sdk",
- "sourceMap": true,
- "noPropertyAccessFromIndexSignature": false,
- "lib": ["DOM", "DOM.Iterable", "es2023"],
- "module": "ES2020",
- "target": "ES2020",
- "declaration": true,
- "declarationMap": true,
- "strict": true,
- "esModuleInterop": true,
- "skipLibCheck": true,
- "moduleResolution": "Bundler"
- },
- "include": ["src/**/*.ts", "src/lib/ping-signals-sdk.js"],
- "files": [],
- "exclude": [
- "vitest.config.ts",
- "vitest.setup.ts",
- "tsconfig*.json",
- "project.json",
- ".eslintrc",
- "src/**/*.test.ts"
- ]
-}
diff --git a/packages/ping-protect/tsconfig.spec.json b/packages/ping-protect/tsconfig.spec.json
deleted file mode 100644
index 6ab1469ef..000000000
--- a/packages/ping-protect/tsconfig.spec.json
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "compilerOptions": {
- "outDir": "../../dist/packages/ping-protect",
- "sourceMap": true,
- "noPropertyAccessFromIndexSignature": false,
- "lib": ["DOM", "DOM.Iterable", "es2023"],
- "module": "Node16",
- "target": "ES2020",
- "declaration": true,
- "declarationMap": true,
- "strict": true,
- "esModuleInterop": true,
- "skipLibCheck": true,
- "moduleResolution": "Node16",
- "types": ["node", "vitest", "vitest/client"]
- },
- "include": [
- "vite.config.ts",
- "src/**/*.test.ts",
- "src/**/*.spec.ts",
- "src/**/*.test.tsx",
- "src/**/*.spec.tsx",
- "src/**/*.test.js",
- "src/**/*.spec.js",
- "src/**/*.test.jsx",
- "src/**/*.spec.jsx",
- "src/**/*.d.ts"
- ]
-}
diff --git a/packages/ping-protect/typedoc.json b/packages/ping-protect/typedoc.json
deleted file mode 100644
index b10d8a660..000000000
--- a/packages/ping-protect/typedoc.json
+++ /dev/null
@@ -1,68 +0,0 @@
-{
- "entryPointStrategy": "expand",
- "entryPoints": ["./src/index.ts"],
- "tsconfig": "tsconfig.lib.json",
- "compilerOptions": {},
- "exclude": [
- "**/*.(spec|test|e2e).ts",
- "**/*.mock.*",
- "**/*.data.*",
- "docs/**",
- "tests/**",
- "specs/**",
- "spec/**",
- "test/**"
- ],
- "externalPattern": ["**/node_modules/**"],
- "excludeExternals": true,
- "excludeInternal": false,
- "excludePrivate": false,
- "excludeProtected": false,
- "excludeNotDocumented": false,
- "externalSymbolLinkMappings": {},
- "out": "./docs",
- "emit": "docs",
- "theme": "typedoc-github-theme",
- "name": "ping-protect",
- "includeVersion": true,
- "readme": "./README.md",
- "disableSources": false,
- "excludeTags": [],
- "cname": "",
- "sourceLinkTemplate": "",
- "gitRevision": "master",
- "gitRemote": "origin",
- "lang": "en",
- "githubPages": true,
- "hideGenerator": true,
- "searchInComments": false,
- "cleanOutputDir": true,
- "titleLink": "",
- "navigationLinks": {},
- "sidebarLinks": {},
- "commentStyle": "all",
- "categorizeByGroup": true,
- "defaultCategory": "Other",
- "categoryOrder": [],
- "sort": ["visibility", "required-first", "source-order"],
- "visibilityFilters": {
- "protected": true,
- "private": true,
- "inherited": true,
- "external": true
- },
- "searchCategoryBoosts": {},
- "searchGroupBoosts": {},
- "preserveWatchOutput": false,
- "skipErrorChecking": false,
- "validation": {
- "notExported": true,
- "invalidLink": true,
- "notDocumented": true
- },
- "requiredToBeDocumented": [],
- "treatWarningsAsErrors": false,
- "intentionallyNotExported": [],
- "logLevel": "Verbose",
- "plugin": ["typedoc-plugin-rename-defaults", "typedoc-github-theme"]
-}
diff --git a/packages/ping-protect/vite.config.ts b/packages/ping-protect/vite.config.ts
deleted file mode 100644
index e013bcdfc..000000000
--- a/packages/ping-protect/vite.config.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-///
-import { defineConfig } from 'vite';
-import dts from 'vite-plugin-dts';
-
-export default defineConfig({
- cacheDir: '../../node_modules/.vite/ping-protect',
- build: {
- lib: {
- entry: 'src/index.ts',
- name: 'ping-protect',
- formats: ['es'],
- fileName: (extension, filename) => `${filename}.js`,
- },
- rollupOptions: {
- external: ['@forgerock/javascript-sdk'],
- output: {
- dir: './dist',
- preserveModules: true,
- preserveModulesRoot: 'src',
- },
- },
- },
- plugins: [
- dts({
- declarationOnly: false,
- rollupTypes: true,
- entryRoot: 'src',
- tsconfigPath: './tsconfig.lib.json',
- }),
- ],
- test: {
- reporters: ['default'],
- globals: true,
- setupFiles: ['./vitest.setup.ts'],
- watch: !process.env['CI'],
- coverage: {
- reporter: ['text', 'json', 'html'],
- enabled: Boolean(process.env['CI']),
- reportsDirectory: './coverage',
- provider: 'v8',
- },
- deps: {
- optimizer: {
- web: {
- include: ['vitest-canvas-mock'],
- },
- },
- },
- environment: 'jsdom',
- include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
- },
-});
diff --git a/packages/ping-protect/vitest.setup.ts b/packages/ping-protect/vitest.setup.ts
deleted file mode 100644
index 644736e02..000000000
--- a/packages/ping-protect/vitest.setup.ts
+++ /dev/null
@@ -1 +0,0 @@
-import 'vitest-canvas-mock';
diff --git a/packages/token-vault/.babelrc b/packages/token-vault/.babelrc
deleted file mode 100644
index fd4cbcdef..000000000
--- a/packages/token-vault/.babelrc
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "presets": [
- [
- "@nx/js/babel",
- {
- "useBuiltIns": "usage"
- }
- ]
- ]
-}
diff --git a/packages/token-vault/.eslintrc.json b/packages/token-vault/.eslintrc.json
deleted file mode 100644
index 9d9c0db55..000000000
--- a/packages/token-vault/.eslintrc.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "extends": ["../../.eslintrc.json"],
- "ignorePatterns": ["!**/*"],
- "overrides": [
- {
- "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
- "rules": {}
- },
- {
- "files": ["*.ts", "*.tsx"],
- "rules": {}
- },
- {
- "files": ["*.js", "*.jsx"],
- "rules": {}
- }
- ]
-}
diff --git a/packages/token-vault/CHANGELOG.md b/packages/token-vault/CHANGELOG.md
deleted file mode 100644
index 4d69ea8d0..000000000
--- a/packages/token-vault/CHANGELOG.md
+++ /dev/null
@@ -1,12 +0,0 @@
-### [4.2.0] - 2023-09-11
-
-Security: - Proxy config declaring URLs is now required and will be used to generate an allow list of origins to check again prior to fowarding a request.
-
-## [4.1.2] - 2023-07-24
-
-Features:
-
-- Initial release of Token Vault
-- Initial NPM deployment for latest version (4.1.2)
-- Token vault is sync'd to the same version of the SDK.
-- @forgerock/javascript-sdk is a peer dependency of Token vault, meaning the application must install it independently.
diff --git a/packages/token-vault/LICENSE b/packages/token-vault/LICENSE
deleted file mode 100644
index a1e82df86..000000000
--- a/packages/token-vault/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2023 ForgeRock
-
-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.
diff --git a/packages/token-vault/README.md b/packages/token-vault/README.md
deleted file mode 100644
index 720283794..000000000
--- a/packages/token-vault/README.md
+++ /dev/null
@@ -1,471 +0,0 @@
-# Token Vault
-
-Token Vault is a feature by ForgeRock that provides an additional layer of security for storing OAuth/OIDC tokens in a JavaScript application (SPA). This is useful for applications that need a higher level of security or have third-party code execution in their application that is not fully trusted. Once configured and setup, you can build your app, [use the ForgeRock SDK](https://backstage.forgerock.com/docs/sdks/latest/whatsnew/index.html), and interact with protected resources as you normally would. Token Vault is entirely framework and library agnostic.
-
-Token Vault is a plugin to our [JavaScript SDK](https://www.npmjs.com/package/@forgerock/javascript-sdk). It is developed around the idea of "Origin Isolation", which you can [read more about in this article](https://github.com/ForgeRock/appAuthHelper/blob/master/origin_isolation.md). To accomplish this, it uses both a Service Worker to intercept allowlisted URLs from emitted `fetch` requests (what we will call an Interceptor) and an `iframe` hosted on a different origin that acts as a proxy and OAuth/OIDC token management layer (what we'll call the Proxy.
-
-It's important to note that we consider this an _advanced_ usage of the ForgeRock JavaScript SDK and not a standard use case. Implementing this feature into your web application is inherently complicated, so we don't recommend this during the prototyping or proof-of-concept stage of development. Only implement this when you have established a core understanding of the ForgeRock system and the ForgeRock JavaScript SDK.
-
-## Overall Design
-
-There are three main entities involved in a normal implementation of a ForgeRock SDK protected web application (JavaScript, Single-Page Application or SPA to be precise):
-
-1. Your JavaScript application (a SPA)
-2. The ForgeRock JavaScript SDK (an npm package)
-3. The ForgeRock server (Identity Cloud or a stand-alone Access Manager)
-
-To implement the Token Vault into your application for increased token security, you'll need one more npm package: the Token Vault. This new package provides a few more items to your overall system:
-
-1. The Token Vault Client, a JavaScript SDK plugin
-2. The Token Vault Interceptor (the Service Worker)
-3. The Token Vault Proxy (the iframe)
-
-It's not important to know exactly how all of these are wired together, but loosely understanding the major components is important. The JavaScript SDK and the Token Vault are both npm packages and are designed to work together to provide a seamless developer experience.
-
-## How it Works
-
-We won't go into too much detail here, so let's start with the basics. The end result of implementing the Token Vault plugin is a system that resembles this:
-
-1. **Main App**: JavaScript SPA using the ForgeRock SDK and the Token Vault Client, running on `https://app.example.com`
-2. **Token Vault Interceptor**: a Service Worker registered on Main App, running on `https://app.example.com`
-3. **Token Vault Proxy**: an `iframe` app injected into Main App, running on `https://proxy.example.com`
-
-### Browser Storage
-
-Whether it's Web Storage API or IndexedDB, any data stored within the browser is restricted by the web app's origin (aka. scheme, domain and port), which is [known as the Same-Origin Policy](https://www.w3.org/Security/wiki/Same_Origin_Policy). We will be leveraging this "same-origin" restriction to store the OAuth/OIDC Tokens (just "tokens" from here on out) we collect using the [Authorization Code Flow](https://backstage.forgerock.com/docs/am/7/oauth2-guide/oauth2-authz-grant-pkce.html) and keep them out of reach from malicious actors.
-
-### Iframe (aka the Proxy)
-
-Though rarely used in modern web applications, we will be taking advantage of the fact that [iframes (aka inline frames)](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) can be embedded within web applications and form a parent-child relationship. As long as the two frames (main app and the child iframe) share the same parent domain, what's called a first-party context, they can communicate with one another without restriction.
-
-As you'll see shortly, it will be important for the two frames to differ by origin _but_ share a parent domain. This special relationship will allow us to store tokens out of reach from code running in the main app, but allow the main app to "proxy" requests through this iframe in order for the Access Token to be attached to the outbound call. This allows tokens to go into the Proxy, but not come out.
-
-### Service Worker (aka the Interceptor)
-
-[Service workers are a complex feature provided by modern browsers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers), but our use of them is quite simple: to intercept a restricted list of URL when a `fetch` request is emitted from the main app. This request is then forwarded to the iframe acting as the proxy.
-
-This restricted list of URLs are the configured endpoints that need _interception_ as they require authorization to succeed. Since the main application does not have access to the stored tokens, they must be "proxied" through the iframe in order for the Access Token to be attached to the outbound call.
-
-### The Sequence, Simplified
-
-When your application requests tokens from the ForgeRock server (Authorization Server) using the SDK, it will use the [Authorization Code Flow with PKCE](https://backstage.forgerock.com/docs/am/7/oauth2-guide/oauth2-authz-grant-pkce.html). The last request in this flow is a call to the `/access_token` endpoint. This request is intercepted and forwarded to the Proxy. When the Proxy receives the tokens in the response, it will store them within its origin, which should be different than the main app.
-
-Before it returns the response to the main app, it redacts the token values from the response body. This ensures the main app never receives or stores the tokens. The Proxy then stores the tokens on behalf of the main app and will be available as a proxy to be used for any future "protected calls" that require the Access Token to be attached to the request.
-
-When any request is made by the main app that is configured for authorization the Interceptor will forward it to the Proxy. This includes the usual requests made from the SDK, like requesting user info or revoking tokens. The Proxy will attach the Access Token to the outbound request, and then return the response to the main app with it resolves. If the tokens have expired or become invalid, the main app will receive a 400 response from the proxy.
-
-## ForgeRock Server Setup
-
-Configuration is the key to success with this setup, so take extra care to ensure it's correct and consistent throughout your setup.
-
-### CORS
-
-First, configure your [ForgeRock server's CORS settings](https://backstage.forgerock.com/docs/idcloud/latest/tenants/configure-cors.html) (if using ForgeRock's Identity Cloud product, there's a [preset JavaScript SDK CORS configuration](https://backstage.forgerock.com/docs/sdks/latest/serverconfiguration/cloud/allow-am-resource-requests-trusted-domains.html) that can be used as a starter):
-
-1. **Accepted origins**: these should be the origins (scheme, domain and port) for your app AND proxy
-2. **Accepted methods**: `GET` and `POST` are enough
-3. **Accepted headers**: `authorization` `accept-api-version` `x-requested-with` `content-type` `accept`
-4. **Allow credentials**: checked/enabled
-
-An example or your origins can be `http://localhost:5173` and `http://localhost:5174` for your local development computer or `https://app.example.com` and `https://proxy.example.com` for production.
-
-### OAuth
-
-Configure your [OAuth client within the ForgeRock server](https://backstage.forgerock.com/docs/sdks/latest/serverconfiguration/cloud/create-oauth2-client.html):
-
-1. **Client ID**: Any alphanumeric string can be used here to identity this client
-2. **Client secret**: keep this blank
-3. **Sign-in URLs**: This URLs should be fully qualified URLs that you want ForgeRock to redirect to provide the Authorization Code for you to collect tokens; if you're using a dynamic value like `location.href`, make sure to pay close attention to trailing slashes
-4. **Grant types**: `Authorization Code` and `Refresh Token`
-5. **Scopes**: `openid` `email` `profile` and any others you need for your app
-6. **Response types**: `code` `token` `id_token` `refresh_token`
-7. **Token endpoint authentication method**: `none`
-8. **Client type**: `Public`
-9. **Implied consent**: this needs to be _enabled_ if you are using Embedded Login (if you are using Centralized Login, you can leave this disabled)
-
-#### Refresh Tokens
-
-In a typical web application using the ForgeRock SDK, we would _not_ recommend the use of Refresh Tokens. But, Token Vault increases the level of token security to allow its use for automatically refreshing Access Tokens without any intervention. To enable this, ensure the use of `Refresh Token` grant is set in the OAuth client and `refresh_token` as a response type within your ForgeRock server.
-
-## Application Setup
-
-In a "normal" setup, a web app usually requires a few things:
-
-1. A dependency/package manager (npm, Yarn, etc)
-2. An application framework (React, Angular, etc)
-3. Some kind of module bundler (Webpack, Vite, etc)
-4. Some kind of web server (Node, Nginx, Apache, etc)
-
-In the most modern web applications, the last two are often the same technology. For Angular, it can often be the last three. Vite can be both the module bundler/resolver and the web server. Webpack, another bundler, has the `webpack-dev-server`.
-
-To build an app that implements Token Vault, we will need to adjust the last two in the list above: module bundler and web server. Because of this, you'll want to be familiar with configuring these two layers of technology.
-
-### Module Bundler
-
-The change involved with your module bundler is required because the Interceptor, a Service Worker, needs to be built differently from your main application's bundle. This is due to browser inconsistency with supported language features, and therefore we recommend the Interceptor be unified and "down-leveled" into a single output file for cross-browser compatibility.
-
-You'll want to create a separate bundler config file dedicated to your interceptor. It should be configured to produce a single file without ES Module syntax. Webpack (v5 or earlier), will do this be default. The configuration file dedicated to your main application can be the default configuration or your own, preferred configuration.
-
-Finally, the Proxy should also have its own module bundler as it's technically a different application from your main app. Though, for this, the default configuration should work without issue.
-
-### Web Server
-
-The change involved with your web server is due to the Proxy, an "iframed" application, that needs to be served from a different origin from your main application. This is what necessitates the need for a dedicated server for just the Proxy itself.
-
-The important thing to note here is that the server for the Proxy needs to be running on a different port for `localhost` or a different sub-domain for production.
-
-Lastly, the web server for the main application needs to avoid rewriting incoming URLs as there's a redirection back to your application from the ForgeRock server, and its query parameters need to be preserved and read by the SDK. If you're seeing timeout issues related to the `/authorize` request, even thought it succeeds and redirects back to your app with the `code` and `state` query parameters (and the request to `/access_token` isn't made). This is likely your server rewriting the URL to `/`, stripping the query parameters from the request and not allowing it to resolve correctly.
-
-### Codebase Structure (recommended)
-
-You are free to structure your code in whatever way makes sense to you and for your application, but here's a recommendation that helps us manage the different pieces. If you use Vite, this structure may look familiar.
-
-```txt
---root
- |--.env <-- store the shared config here
- |--package.json <-- We use npm workspaces
- |--app/ <-- Directory for your main application
- |--public/
- |--
- |--src/
- |--main.js
- |--
- |--interceptor/ <-- Interceptor should be separate from app code
- |--interceptor.js
- |--index.html
- |--package.json
- |--vite.config.js <-- Builds the main app
- |--vite.interceptor.config.js <-- Dedicated build for Interceptor
- |--proxy/ <-- Dedicated directory for the Proxy
- |--src/
- |--proxy.js
- |--index.html
- |--package.json
- |--vite.config.js <-- Builds the Proxy app
-```
-
-Let's take a look at some of the more important files.
-
-First, `app/src/index.html`:
-
-```html
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-```
-
-Next, `app/src/main.js`:
-
-```js
-import { Config, TokenManager } from '@forgerock/javascript-sdk';
-import { client } from '@forgerock/token-vault';
-
-const register = client({
- /* global config */
-});
-
-register.interceptor();
-register.proxy(document.getElementById('token-vault'));
-
-const tokenVaultStore = register.store();
-
-Config.set({
- /* ForgeRock SDK config */
-});
-```
-
-Now, let's look at `app/interceptor/interceptor.js`:
-
-```js
-import { interceptor } from '@forgerock/token-vault';
-
-interceptor({
- /* config */
-});
-```
-
-Lastly, let's look at `proxy/src/proxy.js`:
-
-```js
-import { proxy } from '@forgerock/token-vault';
-
-proxy({
- /* config */
-});
-```
-
-### Application Configuration
-
-As you can see in the above example files, there's a good amount of duplicated configuration that needs to happen within all these entities at build-time, so we recommend having a central, single place for this configuration to be stored in your codebase. Each entity being configured independently is to ensure the highest level of security. Passing around configuration at runtime between entities in the system could be a potential vector, so we don't have a mechanism to do this.
-
-We frequently make use of `.env` files, which can be picked up by module bundlers like Vite or dedicated npm modules like `dotenv`. The example code below will uses literal values for clarity, but this increases human error as it's too easy to make a typo, so we don't recommend this in your actual implementation.
-
-There are three locations that need to be properly configured:
-
-#### The Main App
-
-This configuration should be within your app's `index` or `main` file. First, let's initialize the Token Vault Client as you saw above:
-
-```js
-// app/src/main.js
-import { Config, TokenManager } from '@forgerock/javascript-sdk';
-import { client } from '@forgerock/token-vault';
-
-/**
- * This factory function takes in a config object and returns
- * the necessary methods to setup the iframe ("proxy"), the
- * service worker ("interceptor"), and the token store replacement
- * API ("store").
- */
-const register = client({
- app: {
- origin: 'http://localhost:5173',
- },
- interceptor: {
- file: '/interceptor.js',
- },
- proxy: {
- origin: 'http://localhost:5175',
- },
-});
-
-/**
- * Sets up the service worker for intercepting fetch requests
- */
-register.interceptor({
- /* optional interceptor worker config */
-});
-
-/**
- * Injects the iframe into the DOM to setup the proxy
- * Make sure to pass in the required, real DOM element as the zeroeth argument
- */
-register.proxy(document.getElementById('token-vault'), {
- /* optional proxy config */
-});
-
-/**
- * Creates the store replacement for the SDK
- */
-const tokenVaultStore = register.store({
- /* optional store config */
-});
-```
-
-Then, within the same file, you must configure the SDK. Here's the minimum configuration for the SDK:
-
-```js
-// app/src/main.js
-// ...
-// Configuring the SDK (values should be your own)
-Config.set({
- clientId: 'WebOAuthClient',
- redirectUri: location.href,
- scope: 'openid email profile',
- serverConfig: {
- baseUrl: 'https//auth.example.com/am/',
- timeout: 5000,
- },
- realmPath: 'alpha',
- // Replace the default token store with Token Vault's store
- tokenStore: tokenVaultStore,
-});
-```
-
-#### The Interceptor
-
-This configuration should be within the Service Worker's entry file, which is separate from your main application code. This is also the file to which your `client()` method config object property of `interceptor.file` method references. The minimum configuration is the following:
-
-```js
-// app/interceptor/inteceptor.js
-import { interceptor } from '@forgerock/token-vault';
-
-interceptor({
- interceptor: {
- // Only fully qualified URLs can be used here, or
- // a single, ending glob can be used
- urls: [
- /* Your protected endpoint URLs */
- ],
- },
- forgerock: {
- // The below MUST match what you configured in your main app
- serverConfig: {
- baseUrl: 'https//auth.example.com/am/',
- timeout: 5000,
- },
- realmPath: 'alpha',
- },
-});
-```
-
-Note: The `interceptor.urls` array is a required property and will also be shared with the upcoming Proxy configuration, so it's best to store this array as a global, build-time value in the project. If not provided, your Interceptor will throw an error of "Config: `config.interceptor.urls` is required".
-
-These urls can accept a `/*` ending to match any request from a particular root domain and path without having to declare each and every unique endpoint that's used in your app. Please note that this isn't a full glob-pattern feature, but just a single ending `*` (wildcard).
-
-#### The Proxy
-
-This configuration should be within your Proxy's entry file. The minimum configuration is the following:
-
-```js
-// proxy/src/proxy.js
-import { proxy } from '@forgerock/token-vault';
-
-proxy({
- app: {
- // This MUST match the origin on which your main app runs
- origin: 'https://app.example.com',
- },
- forgerock: {
- // The below MUST match what you configured in your main app and interceptor
- clientId: 'WebOAuthClient',
- redirectUri: location.href,
- scope: 'openid email profile',
- serverConfig: {
- baseUrl: 'https//auth.example.com/am/',
- timeout: 5000,
- },
- realmPath: 'alpha',
- },
- proxy: {
- urls: [
- /* Your protected endpoints; should be identical to `interceptor.urls` */
- ],
- },
-});
-```
-
-Note: the `proxy.urls`, which is shared with `interceptor.urls` from the Interceptor configuration, is a required property for security. If not provided, your Proxy will `throw` an error or "Config: `config.proxy.urls` is required".
-
-## Building the Code
-
-Token Vault requires a bit more building/bundling configuration than a "normal" JavaScript app with the SDK. This is because Token Vault requires 3 different bundles:
-
-1. Your main application
-2. Your Token Vault Interceptor (Service Worker)
-3. Your Token Vault Proxy (`iframe`)
-
-The configuration for the main application and the Proxy can usually be left as default using any of the popular bundlers (Webpack, Vite, etc.), or any configuration you deem best for you and your project. The Interceptor, on the other hand, does require a specific configuration for bundling, which we'll cover next.
-
-### Bundling the Interceptor
-
-To provide the best cross-browser support, the Interceptor requires a dedicated bundle configuration to ensure it results in a _single-file_ output, down-leveled to at least ES2020 without _any_ ES Module syntax. We recommend using a separate `vite.interceptor.config.js` or `webpack.interceptor.config.js` for the Interceptor, and a separate command that consumes this separate configuration file.
-
-Note: for Vite users, we've had the best results with bundling into an IIFE. Webpack's defaults, on the other hand, tend to work quite well.
-
-## Using the Token Vault
-
-Once the Token Vault is properly setup, you can use the JavaScript SDK and any HTTP/fetch library to request protected resources. With the exception of using Refresh Tokens and the token storage mechanism, the remainder of the [documentation for the ForgeRock JavaScript SDK](https://backstage.forgerock.com/docs/sdks/latest/whatsnew/index.html) will remain consistent. The Token Vault will manage your token's lifecycle automatically and, if Refresh Token is enabled in your OAuth client, automatic Access Token refreshing will be handled by the Token Vault as well.
-
-### Requesting & Using Tokens
-
-You can request tokens and have them safely stored within the Token Vault Proxy using the usual `TokenManager` class from the SDK:
-
-```js
-import { TokenManager } from '@forgerock/javascript-sdk';
-
-const tokens = TokenManager.getTokens();
-
-console.log(tokens); // Refresh & Access Token values will be redacted
-```
-
-After successfully requesting tokens, you should notice within your browser's developer tools that the tokens are stored under the proxy's origin, not your app's origin. You may also notice that the response your app, and therefore the SDK itself, contains redacted values. This is expected behavior and for additional security.
-
-For example:
-
-```json
-{
- "accessToken": "REDACTED",
- "idToken": "eyJ0eXAiOiJKV1QiLCJra…7r8soMCk8A7QdQpg",
- "refreshToken": "REDACTED",
- "tokenExpiry": 1690712227226
-}
-```
-
-### Revoking Tokens
-
-To remove tokens and log the user out, use the `FRUser` class:
-
-```js
-import { FRUser } from '@forgerock/javascript-sdk';
-
-FRUser.logout();
-```
-
-This will destroy the user's session, revoke tokens on the server and remove tokens from the browser.
-
-### Validating Tokens
-
-### Convenience Methods
-
-There are a few convenience functions that can be found on the `tokenVaultStore`. These methods are introduced since the main application will not have direct access to the tokens.
-
-#### The `has` Method
-
-This is a way of asking the Token Vault if it has the tokens. It only returns an object with a `hasTokens` prop and a boolean value. It does _not_ return the tokens.
-
-```js
-const tokenVaultStore = register.store();
-
-const { hasTokens } = tokenVaultStore.has();
-
-console.log(hasTokens); // logs `true` or `false`
-```
-
-It's worth noting that this method doesn't validate the tokens, but just reflects the presence of tokens. If you want to validate the tokens, it's best to use the `UserManager.getCurrentUser` method. If that method returns user data, then the tokens are validated by the Authorization Server.
-
-#### The `refresh` Method
-
-This is a method to manually ask the Token Vault to refresh its tokens. The Token Vault will attempt to refresh tokens automatically for you, but this will force a refresh of the tokens, if needed. This method will return an object with a `refreshTokens` property with a boolean value.
-
-```js
-const tokenVaultStore = register.store();
-
-const { refreshTokens } = tokenVaultStore.refresh();
-
-console.log(refreshTokens); // logs `true` or `false`
-```
-
-#### Making Requests
-
-You are free to use the native `fetch` API or any any HTTP request library that emits a `fetch` event. There's also the `HttpClient` module that is available for use from the JavaScript SDK.
-
-## FAQs
-
-### Q: How Do I Fix CORS Errors?
-
-Make sure your CORS configuration in your ForgeRock server allows/accepts origins from both the origin of your app, but also your Token Vault Proxy. These two origins should be unique from one another, and there both need to be configured in your ForgeRock server.
-
-### Q: Why Am I Getting an Iframe Error?
-
-This is likely an error coming from the `/authorize` request to collect OAuth/OIDC tokens. First, make sure you're using version 4 of the SDK. If you are using version 4, then the quickest way to diagnose the issue is to copy the full URL from the network tab in your dev tools and paste it into your browser's URL field to directly visit it.
-
-A `400` error coming from the `/authorize` endpoint is likely a misconfiguration. If a consent page is rendering, then ensure you enable implied consent both within your OAuth Provider and OAuth client.
-
-Lastly, make sure you don't have third-party cookies disabled. Chromium browser's Incognito/Private mode as well as Safari disable third-party cookies by default.
-
-### Q: Why Are the Tokens Not Being Stored?
-
-If you are receiving tokens from the `/access_token` endpoint, but they are not getting stored, this is likely to happen if you've setup Token Vault within your application, but the Interceptor is not catching your request and forwarding it to the Proxy. Only the Proxy can store tokens when Token Vault is enabled.
-
-To fix this, ensure your config is identical between your main app's SDK config found in `Config.set()` and the config found in your Interceptor file. This is why we recommend using using environment variables, rather than hardcoding the values directly in all the modules.
-
-### Q: Why Does the Interceptor (Service Worker) Not work/error in Firefox or Safari?
-
-You're Interceptor bundler is likely not bundling to a single file, and language features are present in the bundle that the browser doesn't support in a Service Worker context. Ensure that your bundler (eg. Vite or Webpack) configuration is creating a single file output and down-leveled to `ES2020`. This is why we recommend a dedicated bundle config for your Interceptor file/module, separate from your application bundle.
-
-### Q: Why Am I Getting `400 Proxy Error`?
-
-These errors often occur when the Proxy itself is encountering an error, and not an HTTP error response from the server. If you inspect the network tab in your dev tools, there should be an error message in the response to help further debug the issue.
diff --git a/packages/token-vault/package.json b/packages/token-vault/package.json
deleted file mode 100644
index 4314d9d77..000000000
--- a/packages/token-vault/package.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "name": "@forgerock/token-vault",
- "version": "4.2.0",
- "private": false,
- "type": "module",
- "files": ["dist/*"],
- "repository": {
- "type": "git",
- "url": "git+https://github.com:ForgeRock/forgerock-javascript-sdk.git",
- "directory": "packages/token-vault"
- },
- "main": "./dist/index.js",
- "module": "./dist/index.js",
- "types": "./dist/index.d.ts",
- "exports": {
- ".": {
- "types": "./dist/index.d.ts",
- "import": "./dist/index.js",
- "require": "./dist/index.js",
- "default": "./dist/index.js"
- }
- },
- "dependencies": {
- "@forgerock/javascript-sdk": "workspace:*"
- }
-}
diff --git a/packages/token-vault/project.json b/packages/token-vault/project.json
deleted file mode 100644
index 5478dfba2..000000000
--- a/packages/token-vault/project.json
+++ /dev/null
@@ -1,46 +0,0 @@
-{
- "name": "token-vault",
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
- "sourceRoot": "packages/token-vault/src",
- "projectType": "library",
- "tags": ["scope:package"],
- "targets": {
- "docs": {
- "command": "pnpm typedoc --options {projectRoot}/typedoc.json"
- },
- "build": {
- "inputs": [
- "default",
- "^default",
- {
- "externalDependencies": ["vite"]
- }
- ],
- "outputs": ["{projectRoot}/dist"]
- },
- "test": {
- "inputs": [
- "default",
- "^default",
- {
- "externalDependencies": ["vitest"]
- }
- ],
- "options": {
- "config": "./vite.config.ts"
- },
- "configurations": {
- "watch": {
- "watch": true
- }
- }
- },
- "lint": {
- "options": {
- "fix": true,
- "ignore-path": ".eslintignore",
- "args": ["**/*.ts"]
- }
- }
- }
-}
diff --git a/packages/token-vault/src/index.ts b/packages/token-vault/src/index.ts
deleted file mode 100644
index d04b151d3..000000000
--- a/packages/token-vault/src/index.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { interceptor as interceptorModule } from './lib/worker/index.js';
-import { client as clientModule } from './lib/client.js';
-import { proxy as proxyModule } from './lib/proxy.js';
-
-export const client = clientModule;
-export const interceptor = interceptorModule;
-export const proxy = proxyModule;
diff --git a/packages/token-vault/src/lib/client.ts b/packages/token-vault/src/lib/client.ts
deleted file mode 100644
index 9c5bf8708..000000000
--- a/packages/token-vault/src/lib/client.ts
+++ /dev/null
@@ -1,201 +0,0 @@
-import type { Tokens } from '@forgerock/javascript-sdk';
-import type { BaseConfig } from './types/index.js';
-import { ClientInit } from './types/client.types.js';
-
-type ClientConfigInit = Partial;
-interface ClientConfig extends ClientConfigInit {
- app: BaseConfig['app'];
- forgerock?: BaseConfig['forgerock'];
- interceptor: BaseConfig['interceptor'];
- proxy: BaseConfig['proxy'];
-}
-
-/** ****************************************************************
- * @function client - Initialize the Token Vault Client
- * @param {Object} config - The configuration object for the client
- * @returns {}
- * @example const register = client({
- * app: {
- * origin: 'http://app.example.com',
- * url: 'http://app.example.com/path',
- * },
- * forgerock: {
- * serverConfig: {
- * baseUrl: 'https://openam.forgerock.com/am',
- * }]
- * },
- * interceptor: {
- * file: 'http://app.example.com/path/interceptor.js',
- * scope: '/',
- * },
- * proxy: {
- * origin: 'http://proxy.example.com',
- * url: 'http://proxy.example.com/path',
- * },
- * });
- */
-export function client(config: ClientConfig): ClientInit {
- let tokenVaultProxyEl: HTMLIFrameElement;
-
- return {
- /** ****************************************************
- * @method interceptor - Register the Token Vault Interceptor
- * @param {BaseConfig['interceptor']} options - The configuration object for the interceptor
- * @returns {Promise} - The Service Worker registration
- * @example register.interceptor();
- */
- interceptor: async function (options?: BaseConfig['interceptor']) {
- const filename = options?.file || config.interceptor.file;
- const moduleType = options?.type || config?.interceptor?.type || 'module';
- const scope = options?.scope || config?.interceptor?.scope || '/';
-
- const registerServiceWorker = () => {
- if ('serviceWorker' in navigator) {
- try {
- return navigator.serviceWorker.register(filename, {
- type: moduleType,
- scope: scope,
- });
- } catch (error) {
- console.error(
- `Token Vault Interceptor (Service Worker) registration failed with ${error}`,
- );
- }
- }
- return;
- };
-
- return registerServiceWorker();
- },
-
- /** ****************************************************
- * @method proxy - Register the Token Vault Proxy
- * @param {HTMLElement} target - The target element to append the proxy iframe to
- * @param {BaseConfig['proxy']} options - The configuration object for the proxy
- * @returns {Promise}
- * @example register.proxy(document.getElementById('token-vault'));
- */
- proxy: function (target: HTMLElement, options?: BaseConfig): Promise {
- const fetchEventName = config?.events?.fetch || 'TVP_FETCH_RESOURCE';
- const frameId = options?.proxy?.id || config?.proxy?.id || 'token-vault-iframe';
- const proxyOrigin = options?.proxy?.origin || config?.proxy.origin || 'http://localhost:9000';
- const proxyUrl = options?.proxy?.path ? `${proxyOrigin}/${config?.proxy?.path}` : proxyOrigin;
-
- const fragment = document.createElement('iframe');
- fragment.setAttribute('id', frameId);
- fragment.setAttribute('src', proxyUrl);
- fragment.setAttribute('style', 'display: none');
-
- tokenVaultProxyEl = target.appendChild(fragment);
-
- console.log(`App origin: ${window.location.origin}`);
- console.log(`Proxy origin: ${proxyOrigin}`);
- console.log(`iframe URL: ${tokenVaultProxyEl.contentWindow?.location.href}`);
-
- navigator.serviceWorker.addEventListener('message', (event) => {
- if (event.data?.type === fetchEventName) {
- tokenVaultProxyEl.contentWindow?.postMessage(
- { type: fetchEventName, request: event.data.request },
- proxyOrigin,
- [event.ports[0]],
- );
- }
- });
-
- return new Promise((resolve) => {
- tokenVaultProxyEl.onload = () => {
- resolve(tokenVaultProxyEl);
- };
- });
- },
-
- /** ****************************************************
- * @method store - Register the Token Vault Store
- * @returns {Promise} - The Token Vault token store object
- * @example const tokenStore = register.store();
- */
- store: function () {
- const clientId = config?.forgerock?.clientId || 'WebOAuthClient';
- const hasTokenEventName = config?.events?.has || 'TVP_HAS_TOKENS';
- const refreshTokenEventName = config?.events?.refresh || 'TVP_REFRESH_TOKENS';
- const removeTokenEventName = config?.events?.remove || 'TVP_REMOVE_TOKENS';
-
- return {
- /**
- * @method get - A noop method that replaces the default get method
- * @returns {Promise}
- */
- get(): Promise {
- // Tokens are not retrievable from the iframe
- return Promise.resolve(null as unknown as Tokens);
- },
-
- /**
- * @method has - Check if tokens exist in the Token Vault
- * @returns {Promise<{ hasTokens: boolean }>} - True if tokens exist, false if not
- */
- has(): Promise<{ hasTokens: boolean }> {
- const proxyChannel = new MessageChannel();
-
- return new Promise((resolve) => {
- tokenVaultProxyEl.contentWindow?.postMessage(
- { type: hasTokenEventName, clientId },
- config.proxy.origin,
- [proxyChannel.port2],
- );
- proxyChannel.port1.onmessage = (event) => {
- resolve(event.data);
- };
- });
- },
-
- /**
- * @method refresh - Refresh tokens in the Token Vault
- * @returns {Promise<{ refreshTokens: boolean }>}
- */
- refresh(): Promise<{ refreshTokens: boolean }> {
- const proxyChannel = new MessageChannel();
-
- return new Promise((resolve) => {
- tokenVaultProxyEl.contentWindow?.postMessage(
- { type: refreshTokenEventName, clientId },
- config.proxy.origin,
- [proxyChannel.port2],
- );
- proxyChannel.port1.onmessage = (event) => {
- resolve(event.data);
- };
- });
- },
-
- /**
- * @method remove - Remove tokens from the Token Vault
- * @returns {Promise}
- */
- remove(clientId: string): Promise {
- const proxyChannel = new MessageChannel();
-
- return new Promise((resolve) => {
- tokenVaultProxyEl.contentWindow?.postMessage(
- { type: removeTokenEventName, clientId },
- config.proxy.origin,
- [proxyChannel.port2],
- );
- proxyChannel.port1.onmessage = () => {
- resolve(undefined);
- };
- });
- },
-
- /**
- * @method set - A noop method that replaces the default set method
- * @param {Tokens} _ - The tokens to store
- * @returns {Promise}
- */
- set(): Promise {
- return Promise.resolve(undefined);
- },
- };
- },
- };
-}
diff --git a/packages/token-vault/src/lib/network/index.ts b/packages/token-vault/src/lib/network/index.ts
deleted file mode 100644
index 76e93c039..000000000
--- a/packages/token-vault/src/lib/network/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from './network.utilities.js';
diff --git a/packages/token-vault/src/lib/network/network.utilities.test.ts b/packages/token-vault/src/lib/network/network.utilities.test.ts
deleted file mode 100644
index aec219f28..000000000
--- a/packages/token-vault/src/lib/network/network.utilities.test.ts
+++ /dev/null
@@ -1,209 +0,0 @@
-import {
- createErrorResponse,
- evaluateUrlForInterception,
- extractOrigins,
- generateAmUrls,
- getBaseUrl,
- getEndpointPath,
- getRealmUrlPath,
- parseQuery,
- resolveUrl,
- stringifyQueryParams,
-} from './network.utilities.js';
-
-describe('Test network utility functions', () => {
- // Test evaluateUrlForInterception with matching URL
- it('evaluateUrlForInterception should return true for matching URLs', () => {
- const urls = ['https://example.com', 'https://example.com/*'];
- const url = 'https://example.com';
- expect(evaluateUrlForInterception(url, urls)).toBe(true);
- });
-
- // Test evaluateUrlForInterception with non-matching URL
- it('evaluateUrlForInterception should return false for non-matching URLs', () => {
- const urls = ['https://example.com', 'https://example.com/*'];
- const url = 'https://example.org';
- expect(evaluateUrlForInterception(url, urls)).toBe(false);
- });
-
- // Test evaluateUrlForInterception with matching URL containing blob
- it('evaluateUrlForInterception should return true for matching URLs with blob', () => {
- const urls = ['https://example.com', 'https://example.com/*'];
- const url = 'blob:https://example.com/1234';
- expect(evaluateUrlForInterception(url, urls)).toBe(true);
- });
-
- // Test extractOrigins
- it('extractOrigins should return an array of unique origins from array of URLs', () => {
- const expected = [
- 'https://example.com',
- 'http://example.com',
- 'https://example.com:8443',
- 'https://my.forgeblocks.com',
- ];
- const urls = [
- 'https://example.com/a',
- 'http://example.com/b',
- 'https://example.com:8443/c',
- 'https://example.com/d',
- 'http://example.com/e',
- 'https://my.forgeblocks.com/am',
- ];
- expect(extractOrigins(urls)).toStrictEqual(expected);
- });
-
- // Test createErrorResponse with `fetch_error` type
- it('createErrorResponse should return error response', () => {
- const error = new Error('Test error');
- const response = createErrorResponse('fetch_error', error);
- expect(response).toEqual({
- body: {
- error: 'fetch_error',
- message: 'Test error',
- },
- headers: { 'content-type': 'application/json' },
- ok: false,
- redirected: false,
- type: 'error',
- status: 400,
- statusText: 'Token Vault Proxy Error',
- });
- });
- // Test createErrorResponse with `no_tokens` type
- it('createErrorResponse should return error response', () => {
- const response = createErrorResponse('no_tokens', null);
- expect(response).toEqual({
- body: {
- error: 'no_tokens',
- message: 'Unknown error',
- },
- headers: { 'content-type': 'application/json' },
- ok: false,
- redirected: false,
- type: 'error',
- status: 400,
- statusText: 'Token Vault Proxy Error',
- });
- });
-
- // Test generateUrls with missing slash
- it('generateUrls should return URLs with missing slash', () => {
- const forgerockConfig = {
- serverConfig: {
- baseUrl: 'https://example.com/am',
- },
- realmPath: 'root',
- };
- const urls = generateAmUrls(forgerockConfig);
- expect(urls).toEqual({
- accessToken: 'https://example.com/am/oauth2/realms/root/access_token',
- revoke: 'https://example.com/am/oauth2/realms/root/token/revoke',
- session: 'https://example.com/am/oauth2/realms/root/connect/endSession?',
- userInfo: 'https://example.com/am/oauth2/realms/root/userinfo',
- });
- });
- // Test generateUrls with ending slash and /alpha realm
- it('generateUrls should return URLs with ending slash and /alpha realm', () => {
- const forgerockConfig = {
- serverConfig: {
- baseUrl: 'https://example.com/am/',
- },
- realmPath: 'alpha',
- };
- const urls = generateAmUrls(forgerockConfig);
- expect(urls).toEqual({
- accessToken: 'https://example.com/am/oauth2/realms/root/realms/alpha/access_token',
- revoke: 'https://example.com/am/oauth2/realms/root/realms/alpha/token/revoke',
- session: 'https://example.com/am/oauth2/realms/root/realms/alpha/connect/endSession?',
- userInfo: 'https://example.com/am/oauth2/realms/root/realms/alpha/userinfo',
- });
- });
-
- // Test getBaseUrl
- it('getBaseUrl should return base URL', () => {
- const url = new URL('https://example.com');
-
- const baseUrl = getBaseUrl(url);
- expect(baseUrl).toBe('https://example.com');
- });
-
- // Test getEndpointPath
- it('getEndpointPath should return endpoint path', () => {
- const endpointPath = getEndpointPath('authenticate');
- expect(endpointPath).toBe('json/realms/root/authenticate');
- });
- // Test getEndpointPath with /alpha realm
- it('getEndpointPath should return endpoint path with alpha realm', () => {
- const endpointPath = getEndpointPath('authenticate', 'alpha');
- expect(endpointPath).toBe('json/realms/root/realms/alpha/authenticate');
- });
- // Test getEndpointPath with /alpha realm starting with slash
- it('getEndpointPath should return endpoint path with /alpha realm', () => {
- const endpointPath = getEndpointPath('authenticate', '/alpha');
- expect(endpointPath).toBe('json/realms/root/realms/alpha/authenticate');
- });
- // Test getEndpointPath with /alpha for authorize endpoint
- it('getEndpointPath should return endpoint path with /alpha for authorize endpoint', () => {
- const endpointPath = getEndpointPath('authorize', '/alpha');
- expect(endpointPath).toBe('oauth2/realms/root/realms/alpha/authorize');
- });
-
- // Test getRealmUrlPath
- it('getRealmUrlPath should return realm URL path', () => {
- const realmUrlPath = getRealmUrlPath('root');
- expect(realmUrlPath).toBe('realms/root');
- });
- // Test getRealmUrlPath with /alpha realm
- it('getRealmUrlPath should return realm URL path with alpha realm', () => {
- const realmUrlPath = getRealmUrlPath('alpha');
- expect(realmUrlPath).toBe('realms/root/realms/alpha');
- });
- // test getRealmUrlPath with /alpha realm starting with slash
- it('getRealmUrlPath should return realm URL path with /alpha realm', () => {
- const realmUrlPath = getRealmUrlPath('/alpha');
- expect(realmUrlPath).toBe('realms/root/realms/alpha');
- });
- // Test getRealmUrlPath with /alpha with trailing slash
- it('getRealmUrlPath should return realm URL path w/o being affected by trailing slash', () => {
- const realmUrlPath = getRealmUrlPath('alpha/');
- expect(realmUrlPath).toBe('realms/root/realms/alpha');
- });
-
- // Test parseQuery
- it('parseQuery should return query object', () => {
- const query = parseQuery('https://example.com?test=1&test2=2');
- expect(query).toEqual({ test: '1', test2: '2' });
- });
- // Test parseQuery with empty query
- it('parseQuery should return empty object', () => {
- const query = parseQuery('https://example.com');
- expect(query).toEqual({});
- });
-
- // Test resolve function
- it('resolveUrl should return a full URL with path', () => {
- const url = resolveUrl('https://example.com', 'test');
- expect(url).toBe('https://example.com/test');
- });
- // Test resolve function with path starting with slash
- it('resolveUrl should return a full URL with path starting with slash', () => {
- const url = resolveUrl('https://example.com', '/test');
- expect(url).toBe('https://example.com/test');
- });
- // Test resolve function with path starting with slash and base URL ending with slash
- it('resolveUrl should return a full URL with path starting and ending with slashes', () => {
- const url = resolveUrl('https://example.com/', '/test/');
- expect(url).toBe('https://example.com/test/');
- });
-
- // Test stringifyQueryParams with basic record
- it('stringifyQueryParams should return query string', () => {
- const query = stringifyQueryParams({ test: '1', test2: '2' });
- expect(query).toBe('test=1&test2=2');
- });
- // Test stringifyQueryParams with empty record
- it('stringifyQueryParams should return empty string', () => {
- const query = stringifyQueryParams({});
- expect(query).toBe('');
- });
-});
diff --git a/packages/token-vault/src/lib/network/network.utilities.ts b/packages/token-vault/src/lib/network/network.utilities.ts
deleted file mode 100644
index e1a4eca96..000000000
--- a/packages/token-vault/src/lib/network/network.utilities.ts
+++ /dev/null
@@ -1,330 +0,0 @@
-/// reference libs="WebWorker"
-import type { ConfigOptions } from '@forgerock/javascript-sdk';
-import type {
- ConfigurablePaths,
- CustomPathConfig,
- RequestHeaders,
- ResponseClone,
- ResponseHeaders,
-} from '../types/index.js';
-
-/** ****************************************************************
- * @function checkForMissingSlash
- * @param {string} url - The URL to check for a missing slash
- * @returns {string} - The URL with a slash appended to the end if it was missing
- */
-export function checkForMissingSlash(url: string) {
- if (url && url.charAt(url.length - 1) !== '/') {
- return url + '/';
- }
- return url;
-}
-
-/** ****************************************************************
- * @function cloneResponse - Clone a response
- * @param {Response} response - The response to clone
- * @returns {Promise} - The cloned response
- */
-export async function cloneResponse(response: Response): Promise {
- // Clone and redact the response
- const clone = response.clone();
-
- let body;
- try {
- body = await getBodyJsonOrText(clone);
- } catch (error) {
- // Leave body undefined
- }
-
- return {
- // Conditionally set the body property
- ...(body && { body }),
- headers: getResponseHeaders(clone),
- ok: clone.ok,
- redirected: clone.redirected,
- status: clone.status,
- statusText: clone.statusText,
- type: clone.type,
- url: clone.url,
- };
-}
-
-/** ****************************************************************
- * @function createErrorResponse - Create an error response
- * @param {string} type - The type of error
- * @param {Error} error - The error object
- * @returns {Object} - An error response object
- */
-export function createErrorResponse(
- type: 'fetch_error' | 'no_tokens' | 'refresh_error',
- error: unknown,
-) {
- const message = error instanceof Error ? error.message : 'Unknown error';
-
- return {
- body: {
- error: type,
- message: message,
- },
- headers: { 'content-type': 'application/json' },
- ok: false,
- redirected: false,
- type: 'error',
- /**
- * Using the status code of 0 to indicate an opaque network error
- * error without a server response.
- *
- * https://fetch.spec.whatwg.org/#concept-network-error
- */
- status: 400,
- statusText: 'Token Vault Proxy Error',
- };
-}
-
-/** ****************************************************************
- * @function evaluateUrlForInterception - Evaluate a URL to see if it should be intercepted
- * @param {string} url - The URL to evaluate
- * @param {string[]} urls - The URLs to check against
- * @returns {boolean} - Whether or not the URL should be intercepted
- */
-export function evaluateUrlForInterception(url: string, urls: string[]) {
- // Loop through the urls and check if the url matches
- for (const u of urls) {
- // If the url ends with a * then check if the url starts with the prefix
- if (u.endsWith('*')) {
- // Remove the * from the end of the url
- const prefix = u.slice(0, -1);
- // Check if the url starts with the prefix
- if (url.startsWith(prefix)) {
- return true;
- }
- }
- // Do full URL matching
- if (url.includes(u)) {
- return true;
- }
- }
- // No match
- return false;
-}
-
-/** ****************************************************************
- * @function extractOrigins - Extract a set of origins from URLs
- * @param {string[]} urls - array of urls
- * @returns {string[]} - array of origins
- */
-export function extractOrigins(urls: string[]): string[] {
- const origins: Set = new Set();
-
- urls.forEach((url) => {
- const { origin } = new URL(url);
- origins.add(origin);
- });
-
- return Array.from(origins);
-}
-
-/** ****************************************************************
- * @function generateAmUrls - Generate the URLs for interception
- * @param forgerockConfig - The ForgeRock config object
- * @returns {Object} - An object containing the URLs for interception
- */
-export function generateAmUrls(forgerockConfig: ConfigOptions) {
- const baseUrl = checkForMissingSlash(forgerockConfig?.serverConfig?.baseUrl || '');
- const realmPath = forgerockConfig?.realmPath || 'root';
-
- return {
- accessToken: `${resolveUrl(baseUrl, getEndpointPath('accessToken', realmPath))}`,
- revoke: `${resolveUrl(baseUrl, getEndpointPath('revoke', realmPath))}`,
- session: `${resolveUrl(baseUrl, getEndpointPath('endSession', realmPath))}?`,
- userInfo: `${resolveUrl(baseUrl, getEndpointPath('userInfo', realmPath))}`,
- };
-}
-
-/** ****************************************************************
- * @function getBaseUrl - Get the base URL from a URL
- * Returns the base URL including protocol, hostname and any non-standard port.
- * The returned URL does not include a trailing slash.
- * @param {string} url - The URL to get the base URL from
- * @returns {string} - The base URL
- */
-export function getBaseUrl(url: URL) {
- const isNonStandardPort =
- (url.protocol === 'http:' && ['', '80'].indexOf(url.port) === -1) ||
- (url.protocol === 'https:' && ['', '443'].indexOf(url.port) === -1);
- const port = isNonStandardPort ? `:${url.port}` : '';
- const baseUrl = `${url.protocol}//${url.hostname}${port}`;
- return baseUrl;
-}
-
-/**
- * @function getResponseBodyBlob - Get the response's body blob
- * @param {Response} response - The response to get the body
- * @returns {Promise} - The response body blob
- */
-export async function getResponseBodyBlob(response: Response) {
- const blob = await response.clone().blob();
-
- if (blob && blob.size) {
- return blob;
- }
- return;
-}
-
-/**
- * @function getRequestBodyBlob - Get the request's body blob
- * @param {Request} request - The request to get the body blob from
- * @returns {Promise} - The request body blob
- */
-export async function getRequestBodyBlob(request: Request): Promise {
- // Return undefined early if GET or HEAD
- if (['GET', 'HEAD'].includes(request.method)) {
- return;
- }
-
- const blob = await request.clone().blob();
-
- if (blob && blob.size) {
- return blob;
- }
- return;
-}
-
-/** ****************************************************************
- * @function getResponseHeaders - Get the response headers
- * @param {Response} response - The response to get the headers from
- * @returns {ResponseHeaders} - The response headers
- */
-export function getResponseHeaders(response: Response) {
- return Array.from(response.headers.keys()).reduce((acc, key: string) => {
- acc[key] = response.headers.get(key);
- return acc;
- }, {});
-}
-
-/**
- * @function getRequestHeaders - Get the request headers
- * @param {Request} request - The request to get the headers from
- * @returns {RequestHeaders} - The request headers
- */
-export function getRequestHeaders(request: Request) {
- return Array.from(request.headers.keys()).reduce((acc, key) => {
- acc[key] = request.headers.get(key);
- return acc;
- }, {});
-}
-
-/** ****************************************************************
- * @function getBodyJsonOrText - Get the response body as JSON or text
- * @param {Response} response - The response to get the body from
- * @returns {Promise} - The response body as JSON or text
- */
-export async function getBodyJsonOrText(response: Response) {
- const contentType = response.headers.get('Content-Type');
- if (contentType && contentType.indexOf('application/json') > -1) {
- return await response.json();
- }
- return await response.text();
-}
-
-/** ****************************************************************
- * @function getEndpointPath - Get the endpoint path
- * @param {ConfigurablePaths} endpoint - The endpoint to get the path for
- * @param {string} realmPath - The realm path
- * @param {CustomPathConfig} customPaths - The custom paths
- * @returns {string} - The endpoint path
- */
-export function getEndpointPath(
- endpoint: ConfigurablePaths,
- realmPath?: string,
- customPaths?: CustomPathConfig,
-): string {
- const realmUrlPath = getRealmUrlPath(realmPath);
- const defaultPaths = {
- authenticate: `json/${realmUrlPath}/authenticate`,
- authorize: `oauth2/${realmUrlPath}/authorize`,
- accessToken: `oauth2/${realmUrlPath}/access_token`,
- endSession: `oauth2/${realmUrlPath}/connect/endSession`,
- userInfo: `oauth2/${realmUrlPath}/userinfo`,
- revoke: `oauth2/${realmUrlPath}/token/revoke`,
- sessions: `json/${realmUrlPath}/sessions/`,
- };
- if (customPaths && customPaths[endpoint]) {
- // TypeScript is not correctly reading the condition above
- // It's thinking that customPaths[endpoint] may result in undefined
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
- // @ts-ignore
- return customPaths[endpoint];
- } else {
- return defaultPaths[endpoint];
- }
-}
-
-/** ****************************************************************
- * @function getRealmUrlPath - Get the realm URL path
- * @param {string} realmPath - The realm path
- * @returns {string} - The realm URL path
- */
-export function getRealmUrlPath(realmPath?: string) {
- // Split the path and scrub segments
- const names = (realmPath || '')
- .split('/')
- .map((x) => x.trim())
- .filter((x) => x !== '');
-
- // Ensure 'root' is the first realm
- if (names[0] !== 'root') {
- names.unshift('root');
- }
-
- // Concatenate into a URL path
- const urlPath = names.map((x) => `realms/${x}`).join('/');
- return urlPath;
-}
-
-/** ****************************************************************
- * @function parseQuery - Parse a query string into an object
- * @param {string} fullUrl - The full URL to parse
- * @returns {Record} - The parsed query string
- */
-export function parseQuery(fullUrl: string) {
- const url = new URL(fullUrl);
- const query: Record = {};
- url.searchParams.forEach((v, k) => (query[k] = v));
- return query;
-}
-
-/** ****************************************************************
- * @function resolveUrl - Resolve a URL
- * @param {string} baseUrl - The base URL
- * @param {string} path - The path to resolve
- * @returns {string} - The resolved URL
- */
-export function resolveUrl(baseUrl: string, path: string) {
- const url = new URL(baseUrl);
-
- if (path.startsWith('/')) {
- return `${getBaseUrl(url)}${path}`;
- }
-
- const basePath = url.pathname.split('/');
- const destPath = path.split('/').filter((x) => !!x);
- const newPath = [...basePath.slice(0, -1), ...destPath].join('/');
-
- return `${getBaseUrl(url)}${newPath}`;
-}
-
-/** ****************************************************************
- * @function stringifyQueryParams - Stringify query parameters
- * @param {Record} data - The query parameters to stringify
- * @returns {string} - The stringified query parameters
- */
-export function stringifyQueryParams(data: Record) {
- const pairs: string[] = [];
- for (const k in data) {
- if (data[k]) {
- pairs.push(k + '=' + encodeURIComponent(data[k]));
- }
- }
- return pairs.join('&');
-}
diff --git a/packages/token-vault/src/lib/proxy.ts b/packages/token-vault/src/lib/proxy.ts
deleted file mode 100644
index ca7d45904..000000000
--- a/packages/token-vault/src/lib/proxy.ts
+++ /dev/null
@@ -1,495 +0,0 @@
-import {
- cloneResponse,
- createErrorResponse,
- extractOrigins,
- generateAmUrls,
-} from './network/index.js';
-import { EventsConfig, ProxyConfig, ServerTokens } from './types/index.js';
-import {
- refreshTokens,
- storeTokens,
- getTokens,
- tokenExpiryWithinThreshold,
-} from './token.utils.js';
-
-/** ****************************************************************
- * @function proxy - Initialize the Token Vault Proxy
- * @param {ProxyConfig} config - The configuration object for the proxy
- * @returns {void}
- * @example proxy({
- * forgerock: { ... },
- * app: { ... },
- * proxy: { ... }
- * });
- */
-export function proxy(config: ProxyConfig) {
- if (!config.proxy.origin) {
- throw new Error('Config: `config.proxy.origin` is required');
- }
- /**
- * Client default configuration
- */
- const clientId = config.forgerock?.clientId || 'WebOAuthClient';
- const clientOrigin = config.app.origin || 'http://localhost:8000';
- const oauthThreshold = config.forgerock?.oauthThreshold || 30 * 1000;
- const scope = config.forgerock?.scope || 'openid email';
- const redactedTokens = config.proxy?.redact || ['access_token', 'refresh_token'];
-
- /**
- * Default event names
- * These can be overridden in the config
- */
- const eventDefaults = [
- { name: 'TVP_FETCH_RESOURCE', type: 'fetch' },
- { name: 'TVP_HAS_TOKENS', type: 'has' },
- { name: 'TVP_REFRESH_TOKENS', type: 'refresh' },
- { name: 'TVP_REMOVE_TOKENS', type: 'remove' },
- ] as const;
-
- /**
- * Generate the event names provided in the config or use the defaults
- */
- const eventsObj = eventDefaults.reduce((acc, event) => {
- const eventName = config.events?.[event.type] || event.name;
- acc[event.type] = eventName;
- return acc;
- }, {} as EventsConfig);
-
- function objectKeys(obj: Obj): (keyof Obj)[] {
- return Object.keys(obj) as (keyof Obj)[];
- }
- /**
- * Generate AM URLs
- */
- const amUrlObj = generateAmUrls(config?.forgerock);
- const amUrlArray = objectKeys(amUrlObj).map((key) => {
- return amUrlObj[key];
- });
-
- /**
- * Generate origins from URLs
- */
- // Throw if URLs are not declared
- if (!config.proxy.urls) {
- throw new Error('Config: `config.proxy.urls` is required');
- }
- const allowedOrigins = extractOrigins([...config.proxy.urls, ...amUrlArray]);
-
- /**
- * Create the proxy iframe
- */
- window.addEventListener('message', async (event) => {
- const requestType = event.data?.type || '';
- const responseChannel = event.ports[0];
-
- console.log(`Received ${requestType} event from ${event.origin}`);
-
- /** ****************************************************
- * FILTER OUT ALL UNRECOGNIZED OR ERROR PRONE EVENTS
- *******************************************************/
-
- // Ignore all messages that don't come from the registered client
- if (event.origin !== clientOrigin) {
- return;
- }
-
- // Ignore all messages that don't have a response channel
- if (!responseChannel) {
- return;
- }
-
- // Ignore all message with event types that are unrecognized
- if (!eventDefaults.find((item) => item.name === requestType)) {
- responseChannel.postMessage({
- error: 'unrecognized_event',
- message: `Unrecognized event type: ${requestType}`,
- });
- return;
- }
-
- /** ****************************************************
- * HAS TOKEN
- * DO NOT RETURN THE TOKEN!
- *******************************************************/
- if (requestType === eventsObj.has) {
- const tokens = getTokens(clientId);
-
- // Check if the Access Token exists
- // DO NOT RETURN THE TOKEN ITSELF! ONLY RETURN TRUE/FALSE!
- const hasTokens = Boolean(tokens?.accessToken);
- responseChannel.postMessage({ hasTokens });
-
- return;
- }
-
- /** ****************************************************
- * REFRESH TOKEN
- *******************************************************/
- if (requestType === eventsObj.refresh) {
- const tokens = getTokens(clientId);
-
- if (!tokens?.refreshToken) {
- responseChannel.postMessage({
- error: 'no_tokens',
- message: 'No OAuth/OIDC tokens to refresh',
- });
-
- return;
- }
-
- try {
- const response = await refreshTokens({
- clientId,
- refreshToken: tokens.refreshToken,
- scope,
- url: amUrlObj.accessToken,
- });
-
- // Check for error and build error message
- if (!response.ok) {
- // Only read json on response if not ok
- const errorResponse = await response.json();
- let errorMessage;
- if (errorResponse?.error === 'invalid_grant') {
- // "invalid_grant" usually means expired or invalid refresh token
- errorMessage = 'Invalid or expired refresh token';
- } else {
- errorMessage = errorResponse?.error;
- }
- throw new Error(errorMessage);
- }
- storeTokens(response, clientId);
-
- responseChannel.postMessage({ refreshTokens: true });
-
- return;
- } catch (error) {
- // Something went wrong, remove tokens and return error
- localStorage.removeItem(clientId);
- responseChannel.postMessage({
- error: 'refresh_error',
- message: error instanceof Error ? error.message : 'Error refreshing tokens',
- });
-
- return;
- }
- }
-
- /** ****************************************************
- * REMOVE TOKENS
- *******************************************************/
- if (requestType === eventsObj.remove) {
- localStorage.removeItem(clientId);
- responseChannel.postMessage({ removeToken: true });
-
- return;
- }
-
- /** ****************************************************
- * CATCH ALL UNRECOGNIZED EVENTS
- *******************************************************/
- if (requestType !== eventsObj.fetch) {
- responseChannel.postMessage({
- error: 'unrecognized_event',
- message: `Unrecognized event: ${requestType}`,
- });
- return;
- }
-
- /** ****************************************************
- * FETCH PROTECTED RESOURCE
- *******************************************************/
- console.log(`Proxying ${event.data?.request?.url}`);
-
- const request = event.data?.request || {};
- const requestUrl = request?.url || '';
- const requestOrigin = new URL(requestUrl)?.origin;
- const tokens = getTokens(clientId);
-
- /** ****************************************************
- * IGNORE ALL REQUESTS TO UNRECOGNIZED ORIGINS
- * Ensure request origin is allow listed; if not return early
- */
- if (!requestUrl || !allowedOrigins.includes(requestOrigin)) {
- responseChannel.postMessage({
- error: 'unrecognized_origin',
- message: `Unrecognized origin: ${requestOrigin}. Please configure URLs in Proxy.`,
- });
- return;
- }
-
- /** ****************************************************
- * ACCESS TOKEN ENDPOINT
- */
- if (request.url?.includes('access_token')) {
- let response;
- try {
- response = await fetch(request.url, {
- ...request.options,
- headers: new Headers({
- ...request.options.headers,
- }),
- });
- } catch (error) {
- const errorResponse = createErrorResponse('fetch_error', error);
- responseChannel.postMessage(errorResponse);
- return;
- }
-
- const clonedResponse = await cloneResponse(response);
- // Redact configured tokens from response body
- if (clonedResponse.body) {
- const body = clonedResponse.body as ServerTokens;
- clonedResponse.body = redactedTokens.reduce((acc, token) => {
- if (body[token]) {
- acc[token] = 'REDACTED';
- } else {
- acc[token] = body[token];
- }
- return acc;
- }, {} as ServerTokens);
- }
-
- // Store tokens in local storage
- storeTokens(response, clientId);
- responseChannel.postMessage(clonedResponse);
-
- return;
- }
-
- // The remainder of events require tokens to be present
- if (!tokens) {
- const errorResponse = createErrorResponse(
- 'no_tokens',
- new Error('No OAuth/OIDC tokens found'),
- );
- responseChannel.postMessage(errorResponse);
- return;
- }
-
- /** ****************************************************
- * TOKEN REVOCATION ENDPOINT
- * Requires the token to be sent in the body
- */
- if (request.url?.includes('token/revoke')) {
- const bodyString = await request.options?.body?.text();
- const body = new URLSearchParams(bodyString);
- body.append('token', tokens.accessToken);
-
- let response;
- try {
- response = await fetch(request.url, {
- ...request.options,
- body,
- });
- } catch (error) {
- const errorResponse = createErrorResponse('fetch_error', error);
- responseChannel.postMessage(errorResponse);
- return;
- }
-
- const clonedResponse = await cloneResponse(response);
- responseChannel.postMessage(clonedResponse);
- return;
- }
-
- /** ****************************************************
- * END SESSION ENDPOINT
- * requires the id_token_hint to be sent as a query parameter
- */
- if (request.url?.includes('connect/endSession')) {
- const url = new URL(request.url);
- url.searchParams.append('id_token_hint', tokens?.idToken);
- console.log(url.toString());
-
- let response;
- try {
- response = await fetch(url.toString(), request.options);
- } catch (error) {
- const errorResponse = createErrorResponse('fetch_error', error);
- responseChannel.postMessage(errorResponse);
- return;
- }
-
- const clonedResponse = await cloneResponse(response);
- responseChannel.postMessage(clonedResponse);
- return;
- }
-
- /** ****************************************************
- * NON-UNIQUE ENDPOINTS
- * All other requests require the access token to be sent
- * in the Authorization header
- */
- let response;
-
- /**
- * CHECK ACCESS TOKEN THRESHOLD
- * If Access Token is within threshold, skip to auto token refresh
- */
- if (!tokenExpiryWithinThreshold(oauthThreshold, tokens.tokenExpiry)) {
- // Access token is outside threshold
- try {
- response = await fetch(request.url, {
- ...request.options,
- headers: new Headers({
- ...request.options.headers,
- authorization: `Bearer ${tokens ? tokens?.accessToken : ''}`,
- }),
- });
- } catch (error) {
- const errorResponse = createErrorResponse('fetch_error', error);
- responseChannel.postMessage(errorResponse);
- return;
- }
-
- /**
- * SUCCESSFUL RESPONSE
- * If the response is ok, just return the response
- */
- if (response.ok) {
- const clonedResponse = await cloneResponse(response);
- responseChannel.postMessage(clonedResponse);
- return;
- }
-
- /**
- * NON-401 ERROR RESPONSE
- * If the response is NOT a 401, just return the response
- */
- if (response.status !== 401) {
- const clonedResponse = await cloneResponse(response);
- responseChannel.postMessage(clonedResponse);
- return;
- }
- }
-
- /**
- * ACCESS TOKEN WITHIN EXPIRY THRESHOLD OR 401 UNAUTHORIZED RESPONSE
- * At this point, the response is both NOT OK and status code is 401.
- * Because of this 401, try to refresh the Access Token.
- * If a new Access Token is received, use it to make the request again.
- * If the refresh fails, return the original response
- */
- let newTokenResponse: Response;
- try {
- newTokenResponse = await refreshTokens({
- clientId,
- refreshToken: tokens.refreshToken,
- scope,
- url: amUrlObj.accessToken,
- });
- } catch (error) {
- // Remove the tokens from localStorage and return error
- localStorage.removeItem(clientId);
-
- /**
- * Clone the original response if it exists
- * Otherwise, create a new error response
- */
- const errorResponse = response
- ? await cloneResponse(response)
- : createErrorResponse('refresh_error', error);
-
- const clonedResponse = errorResponse;
- responseChannel.postMessage(clonedResponse);
- return;
- }
-
- /**
- * FAILED REFRESH RESPONSE
- * If the refresh token request fails, remove the tokens from localStorage
- * and return the original response.
- */
- if (!newTokenResponse.ok) {
- localStorage.removeItem(clientId);
-
- /**
- * Clone the original response if it exists
- * Otherwise, create a new error response
- */
- const errorResponse = response
- ? await cloneResponse(response)
- : createErrorResponse('fetch_error', new Error('Unable to refresh token'));
-
- const clonedResponse = errorResponse;
- responseChannel.postMessage(clonedResponse);
- return;
- }
-
- let newTokens: ServerTokens | undefined;
-
- try {
- // Parse the response for the new Access Token
- newTokens = await newTokenResponse.clone().json();
- } catch (error) {
- // leave newTokens undefined
- }
-
- /**
- * ACCESS TOKEN NOT FOUND
- * If a new Access Token is NOT received, remove the tokens from
- * localStorage and return the original response.
- */
- if (!newTokens || !newTokens.access_token) {
- // Remove the tokens from localStorage
- localStorage.removeItem(clientId);
-
- /**
- * Clone the original response if it exists
- * Otherwise, create a new error response
- */
- const errorResponse = response
- ? await cloneResponse(response)
- : createErrorResponse('fetch_error', new Error('Unable to refresh token'));
- responseChannel.postMessage(errorResponse);
- return;
- }
-
- /**
- * SUCCESSFUL REFRESH RESPONSE
- * If a new Access Token is received, store it in localStorage
- */
- storeTokens(newTokenResponse, clientId);
-
- // Recall the request with the new Access Token
- let newResponse: Response;
- try {
- // Replace the initial `response`
- newResponse = await fetch(request.url, {
- ...request.options,
- headers: new Headers({
- ...request.options.headers,
- /**
- * To avoid re-parsing JSON or re-reading from localStorage,
- * we use the new Access Token directly from the response body.
- * So, use snake_case as it's the server's format.
- */
- authorization: `Bearer ${newTokens.access_token}`,
- }),
- });
- } catch (error) {
- /**
- * Clone the original response if it exists
- * Otherwise, create a new error response
- */
- const errorResponse = response
- ? await cloneResponse(response)
- : createErrorResponse(
- 'fetch_error',
- new Error('Unable to re-request resourse with refreshed token'),
- );
-
- responseChannel.postMessage(errorResponse);
- return;
- }
-
- /**
- * RE-REQUEST RESPONSE
- * At this point, regardless of the response status, return the it.
- */
- const clonedResponse = await cloneResponse(newResponse);
- responseChannel.postMessage(clonedResponse);
- return;
- });
-}
diff --git a/packages/token-vault/src/lib/token.utils.test.ts b/packages/token-vault/src/lib/token.utils.test.ts
deleted file mode 100644
index 93562bb7a..000000000
--- a/packages/token-vault/src/lib/token.utils.test.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { tokenExpiryWithinThreshold } from './token.utils.js';
-import { vi } from 'vitest';
-
-const oauthThreshold = 120000;
-const aboutToExpire = 60000;
-const notAboutToExpire = 180000;
-const tokenExpiryNotSet = undefined;
-
-describe('Test Token Manager utils', () => {
- // We want to avoid race conditions between expected and actual date values
- beforeAll(() => {
- // Override date functions to return a static date temporarily
- vi.useFakeTimers();
- vi.setSystemTime(new Date('25 Mar 2022 16:50:00 GMT').getTime());
- });
-
- it('Should return true if tokens expire within configured threshold', () => {
- const expiresSoon = tokenExpiryWithinThreshold(oauthThreshold, Date.now() + aboutToExpire);
- expect(expiresSoon).toBe(true);
- });
-
- it('Should return false if tokens expire outside configured threshold', () => {
- const expiresSoon = tokenExpiryWithinThreshold(oauthThreshold, Date.now() + notAboutToExpire);
- expect(expiresSoon).toBe(false);
- });
-
- it('Should return false if token expiry is not set', () => {
- const expiresSoon = tokenExpiryWithinThreshold(
- tokenExpiryNotSet,
- Date.now() + notAboutToExpire,
- );
- expect(expiresSoon).toBe(false);
- });
-
- afterAll(() => {
- // Reset timers
- vi.useRealTimers();
- });
-});
diff --git a/packages/token-vault/src/lib/token.utils.ts b/packages/token-vault/src/lib/token.utils.ts
deleted file mode 100644
index dbd1f8e79..000000000
--- a/packages/token-vault/src/lib/token.utils.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { ClientTokens, RefreshOAuth2TokensOptions, ServerTokens } from './types/index.js';
-import { stringifyQueryParams } from './network/index.js';
-
-/** ****************************************************************
- * @function getTokens - Get the tokens for a client from local storage
- * @param {string} clientId - The client ID
- * @returns {ClientTokens | undefined} - The tokens for the client
- */
-export function getTokens(clientId: string): ClientTokens | undefined {
- const tokensString = localStorage.getItem(clientId);
- let tokens;
-
- if (tokensString) {
- try {
- tokens = JSON.parse(tokensString) || undefined;
- } catch (error) {
- // TODO: Handle error more intelligently
- }
- }
-
- return tokens;
-}
-
-/** ****************************************************************
- * @function refreshTokens - Refresh the OAuth2 tokens for a client
- * @param {RefreshOAuth2TokensOptions} config - The configuration object for the refresh request
- * @returns {Promise} - The response from the refresh request
- */
-export async function refreshTokens(config: RefreshOAuth2TokensOptions): Promise {
- const requestParams = {
- client_id: config.clientId || '',
- grant_type: 'refresh_token',
- refresh_token: config.refreshToken || '',
- scope: config.scope || 'openid',
- };
-
- const body = stringifyQueryParams(requestParams);
- const init = {
- body,
- headers: new Headers({
- 'Content-Length': body.length.toString(),
- 'Content-Type': 'application/x-www-form-urlencoded',
- }),
- method: 'POST',
- };
-
- const response = await fetch(config.url, init);
-
- return response;
-}
-
-/** ****************************************************************
- * @function storeTokens - Store the tokens for a client in local storage
- * @param {Response} response - The response from the refresh request
- * @param {string} clientId - The client ID
- * @returns {Promise} - A promise that resolves when the tokens are stored
- */
-export async function storeTokens(response: Response, clientId: string) {
- const newTokens: ServerTokens | undefined = await response.json();
-
- if (!newTokens) {
- throw new Error('No tokens found in response');
- }
-
- let tokenExpiry: number | undefined;
- if (newTokens.expires_in) {
- tokenExpiry = Date.now() + newTokens.expires_in * 1000;
- }
-
- const clientTokens: ClientTokens = {
- accessToken: newTokens.access_token,
- idToken: newTokens.id_token,
- refreshToken: newTokens.refresh_token,
- scope: newTokens.scope,
- tokenExpiry,
- };
- localStorage.setItem(clientId, JSON.stringify(clientTokens));
-}
-
-/** ****************************************************************
- * @function tokenExpiryWithinThreshold - Check if the token expiry is within the threshold
- * @param {number | undefined} oauthThreshold - The threshold for token expiry
- * @param {number | undefined} tokenExpiry - The expiry time for the token
- * @returns {boolean} - Whether the token expiry is within the threshold
- */
-export function tokenExpiryWithinThreshold(oauthThreshold?: number, tokenExpiry?: number): boolean {
- console.log(oauthThreshold);
- console.log(tokenExpiry);
- if (oauthThreshold && tokenExpiry) {
- return tokenExpiry - oauthThreshold < Date.now();
- }
- return false;
-}
diff --git a/packages/token-vault/src/lib/types/client.types.ts b/packages/token-vault/src/lib/types/client.types.ts
deleted file mode 100644
index 1b0301017..000000000
--- a/packages/token-vault/src/lib/types/client.types.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import type { Tokens } from '@forgerock/javascript-sdk';
-import type { BaseConfig } from './config.types.js';
-
-export type ClientInit = {
- interceptor: (
- options?: BaseConfig['interceptor'],
- ) => Promise;
- proxy: (target: HTMLElement, options?: BaseConfig) => Promise;
- store: () => {
- get: (clientId: string) => Promise;
- set: (clientId: string, token: Tokens) => Promise