Skip to content

SDKS-3941: Migrate Protect from Legacy to new Ping SDK #274

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .changeset/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"@forgerock/davinci-app",
"@forgerock/davinci-suites",
"@forgerock/mock-api-v2",
"@forgerock/local-release-tool"
"@forgerock/local-release-tool",
"@pingidentity/protect"
]
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@
"commit": "git cz",
"commitlint": "commitlint --edit",
"create-package": "nx g @nx/js:library",
"generate-docs": "typedoc",
"format": "pnpm nx format:write",
"generate-docs": "typedoc",
"lint": "nx affected --target=lint",
"local-release": "pnpm ts-node tools/release/release.ts",
"nx": "nx",
Expand Down
135 changes: 135 additions & 0 deletions packages/protect/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# Ping Protect

The Ping Protect module is intended to be used along with the ForgeRock JavaScript SDK to provide the Ping Protect feature.

## 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. PingOne Advanced Identity Cloud (aka PingOne AIC) platform or an up-to-date Ping Identity Access Management (aka PingAM)
2. PingOne tenant with Protect enabled
3. A Ping Protect Service configured in AIC or AM
4. A journey/tree with the appropriate Protect Nodes
5. A client application with the `@forgerock/javascript-sdk` and `@pingidentity/protect` modules installed

## Quick Start for Client Application

Install both modules and their latest versions:

```sh
npm install @forgerock/javascript-sdk @pingidentity/protect
```

The `@pingidentity/protect` module has a `createProtect()` function that accepts configuration options and returns a set of methods for interacting with Protect. The two main responsibilities of the Ping Protect module are the initialization of the profiling and data collection and the completion and preparation of the collected data for the server. You can find these two methods on the API returned by `createProtect()`.

- `start()`
- `getData()`

When calling `createProtect()`, 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.

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.

```js
import { createProtect } from '@pingidentity/protect';

// Call early in your application startup
const protect = await createProtect({ envId: '12345' });
await protect.start();
```

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
if (step.getCallbacksOfType('PingOneProtectInitializeCallback')) {
try {
// Asynchronous call
await protect.start();
} 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
let data;

if (step.getCallbacksOfType('PingOneProtectEvaluationCallback')) {
try {
// Asynchronous call
data = await protect.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 protect.start();
} 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 protect.getData();
} catch (err) {
callback.setClientError(err.message);
}
}
```

## Full API

```js
// Protect methods
start();
getData();
pauseBehavioralData();
resumeBehavioralData();
```

```js
// PingOneProtectInitializeCallback methods
callback.getConfig();
callback.setClientError();
```

```js
// PingOneProtectEvaluationCallback methods
callback.setData();
callback.setClientError();
callback.getPauseBehavioralData();
```
56 changes: 56 additions & 0 deletions packages/protect/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import baseConfig from '../../eslint.config.mjs';

export default [
{
ignores: ['**/dist'],
},
...baseConfig,
{
files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
// Override or add rules here
rules: {},
},
{
files: ['**/*.ts', '**/*.tsx'],
// Override or add rules here
rules: {},
},
{
files: ['**/*.js', '**/*.jsx'],
// Override or add rules here
rules: {},
},
{
files: ['**/*.json'],
rules: {
'@nx/dependency-checks': [
'error',
{
ignoredFiles: ['{projectRoot}/vite.config.{js,ts,mjs,mts}'],
},
],
},
languageOptions: {
parser: await import('jsonc-eslint-parser'),
},
},
{
ignores: [
'**/*.md',
'LICENSE',
'README.md',
'.babelrc',
'.env*',
'.bin',
'dist',
'.eslintignore',
'docs',
'coverage',
'vite.config.*.timestamp*',
'*tsconfig.tsbuildinfo*',
'**/**/mock-data/*.d.ts*',
'src/lib/signals-sdk.js',
'**/.DS_Store',
],
},
];
46 changes: 46 additions & 0 deletions packages/protect/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ancheetah Can we mark sideEffects in this package.json. I believe we have to mark the signals sdk as a side effect like we do in legacy.

"name": "@pingidentity/protect",
"version": "0.0.0",
"private": true,
"repository": {
"type": "git",
"url": "git+https://github.com/ForgeRock/ping-javascript-sdk.git",
"directory": "packages/protect"
},
"sideEffects": ["dist/src/lib/signals-sdk.js"],
"type": "module",
"exports": {
".": {
"types": "./dist/src/index.d.ts",
"import": "./dist/src/index.js",
"default": "./dist/src/index.js"
},
"./package.json": "./package.json",
"./types": "./dist/src/types.js"
},
"main": "./dist/src/index.js",
"module": "./dist/src/index.js",
"files": ["dist"],
"scripts": {
"lint": "pnpm nx nxLint",
"test": "pnpm nx nxTest",
"test:watch": "pnpm nx nxTest --watch"
},
"dependencies": {},
"nx": {
"tags": ["scope:package"],
"targets": {
"build": {
"executor": "@nx/js:tsc",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "packages/protect/dist",
"main": "packages/protect/src/index.ts",
"tsConfig": "packages/protect/tsconfig.lib.json",
"generatePackageJson": false,
"assets": []
}
}
}
}
}
10 changes: 10 additions & 0 deletions packages/protect/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
*
* Copyright © 2025 Ping Identity Corporation. All right reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
*/

export * from './lib/protect.js';
109 changes: 109 additions & 0 deletions packages/protect/src/lib/protect.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
*
* Copyright © 2025 Ping Identity Corporation. All right reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
*/

import { createProtect } from './protect.js';
import { ProtectConfig, Protect } from './protect.types.js';

describe('createProtect', () => {
const config: ProtectConfig = {
envId: '12345',
consoleLogEnabled: true,
deviceAttributesToIgnore: ['userAgent'],
lazyMetadata: false,
behavioralDataCollection: true,
deviceKeyRsyncIntervals: 14,
enableTrust: false,
disableTags: false,
disableHub: false,
};

async function getProtect(options: ProtectConfig): Promise<Protect> {
const protect: Protect = await createProtect(options);
expect(protect).toBeDefined();
assertType<Protect>(protect);
return protect;
}

beforeEach(() => {
vi.mock('./signals-sdk.js', () => {
return {
default: {
init: vi.fn(),
getData: vi.fn(),
pauseBehavioralData: vi.fn(),
resumeBehavioralData: vi.fn(),
},
};
});

if (typeof window === 'undefined') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
global.window = {} as any;
}

window._pingOneSignals = {
init: vi.fn().mockResolvedValue(undefined),
getData: vi.fn().mockResolvedValue('mocked-data'),
pauseBehavioralData: vi.fn(),
resumeBehavioralData: vi.fn(),
};
});

afterEach(() => {
vi.clearAllMocks();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
delete (window as any)._pingOneSignals;
});

it('should be defined', () => {
expect(createProtect).toBeDefined();
});

it('should return protect methods', async () => {
const protect = await getProtect(config);
expect(protect.start).toBeDefined();
expect(protect.getData).toBeDefined();
expect(protect.pauseBehavioralData).toBeDefined();
expect(protect.resumeBehavioralData).toBeDefined();
});

it('should call start', async () => {
const protect = await getProtect(config);
const protectMock = vi.spyOn(protect, 'start');
await protect.start();
expect(protectMock).toHaveBeenCalled();
expect(window._pingOneSignals.init).toHaveBeenCalledWith(config);
});

it('should call getData', async () => {
const protect = await getProtect(config);
const protectMock = vi.spyOn(protect, 'getData');
await protect.getData();
expect(protectMock).toHaveBeenCalled();
});

it('should call pauseBehavioralData', async () => {
const protect = await getProtect(config);
const protectMock = vi.spyOn(protect, 'pauseBehavioralData');
protect.pauseBehavioralData();
expect(protectMock).toHaveBeenCalled();
});

it('should call resume behavioralData', async () => {
const protect = await getProtect(config);
const protectMock = vi.spyOn(protect, 'resumeBehavioralData');
protect.resumeBehavioralData();
expect(protectMock).toHaveBeenCalled();
});

it('should error on failed signals sdk load', async () => {
vi.doUnmock('./signals-sdk.js');
await expect(createProtect(config)).rejects.toThrowError('Failed to load PingOne Signals SDK');
});
});
Loading
Loading