Skip to content

Commit 0dbbccb

Browse files
committed
feat(pencil) Updated sdk readme
1 parent 4745b09 commit 0dbbccb

7 files changed

Lines changed: 134 additions & 72 deletions

File tree

CHANGELOG.md

Lines changed: 0 additions & 7 deletions
This file was deleted.

README.md

Lines changed: 85 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -27,31 +27,30 @@
2727
</p>
2828
<hr/>
2929

30-
SecureNative Node.JS agent provides application security monitoring and protection from OWASP TOP 10 security threats at run-time through dynamic instrumentation of business logic and user behaviour.
30+
[SecureNative](https://www.securenative.com/) performs user monitoring by analyzing user interactions with your application and various factors such as network, devices, locations and access patterns to stop and prevent account takeover attacks.
3131

32-
SecureNative monitors and protects applications from common security threats such as:
32+
## Install the SDK
3333

34-
- Bad bots
35-
- 3rd party packages vulnerabilities
36-
- SQL/NoSQL injections
37-
- XSS attacks
38-
- Massive security scans
39-
- Raise of HTTP errors (40X, 50X)
40-
- Anomaly Usage
41-
- Content Scrapping
42-
- Adaptive Authentication, prevent ATO (Account Takeover)
34+
Navigate to your application project folder and enter:
4335

44-
## Installation
36+
```bash
37+
npm i @securenative/sdk
38+
```
4539

46-
Please create free account at [register](https://console.securenative.com/register) to get api key.
40+
Verify that `@securenative/sdk` appears in your package to your `package.json`.
4741

48-
Install SecureNative agent:
42+
## Initialize the SDK
4943

50-
```bash
51-
npm i @securenative/agent
52-
```
44+
To get your *API KEY*, login to your SecureNative account and go to project settings page:
45+
46+
```js
47+
import { SecureNative, EventTypes } from "@securenative/sdk";
48+
or;
49+
const { SecureNative, EventTypes } = require("@securenative/sdk"); // if your using ES5
50+
```
5351

54-
Verify that `@securenative/agent` appears in your package to your `package.json`.
52+
### Option 1: Initialize via Config file
53+
SecureNative can automatically load your config from *securenative.json* that you can add to your application folder.
5554

5655
```shell script
5756
cat > securenative.json <<EOF
@@ -62,10 +61,75 @@ cat > securenative.json <<EOF
6261
EOF
6362
```
6463

65-
Add SecureNative as first dependency to your main module
64+
### Option 2: Initialize via config options
65+
66+
```java
67+
SecureNative.init({ apiKey: "Your API_KEY" });
68+
```
69+
70+
## Getting SecureNative instance
71+
Once initialized, sdk will create a singleton instance which you can get:
72+
```java
73+
const secureNative = SecureNative.getInstance();
74+
```
75+
76+
## Tracking events
77+
78+
Once the SDK has been initialized, tracking requests sent through the SDK
79+
instance. Make sure you build event with the EventBuilder:
80+
81+
82+
```js
83+
import { SecureNative, EventTypes, contextFromRequest } from "@securenative/sdk";
84+
85+
secureNative.track({
86+
event: EventTypes.LOG_IN,
87+
userId: '1234',
88+
userTraits: {
89+
name: 'Your Name',
90+
email: 'name@gmail.com'
91+
},
92+
context: contextFromRequest(req)
93+
});
94+
```
95+
96+
If you don't have acess to request object you can construct the context manually:
6697

6798
```js
68-
require('securenative');
99+
secureNative.track({
100+
event: EventTypes.LOG_IN,
101+
userId: '1234',
102+
userTraits: {
103+
name: 'Your Name',
104+
email: 'name@gmail.com'
105+
},
106+
context: {
107+
ip: '10.0.0.0',
108+
clientToken: 'Token from client',
109+
headers: {
110+
"user-agent": 'Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405"'
111+
}
112+
}
113+
});
114+
```
115+
116+
## Verify events
117+
```js
118+
119+
const verifyResult = await secureNative.verify({
120+
event: EventTypes.LOG_IN,
121+
userId: '1234',
122+
userTraits: {
123+
name: 'Your Name',
124+
email: 'name@gmail.com'
125+
},
126+
context: contextFromRequest(req)
127+
})
128+
129+
verifyResult.riskLevel // Low, Medium, High
130+
verifyResult.score // Risk score: 0 -1 (0 - Very Low, 1 - Very High)
131+
verifyResult.triggers // ["TOR", "New IP", "New City"]
132+
}
69133
```
70134

71135
## Configuration
@@ -75,8 +139,7 @@ require('securenative');
75139
| SECURENATIVE_API_KEY | string | false | none | SecureNative api key |
76140
| SECURENATIVE_APP_NAME | string | false | package.json | Name of application source |
77141
| SECURENATIVE_API_URL | string | true | https://api.securenative.com/v1/collector | Default api base address |
78-
| SECURENATIVE_INTERVAL | number | true | 1000 | Default interval for SDK to try to persist events |
79-
| SECURENATIVE_HEARTBEAT_INTERVAL | number | true | 1000 | Default agent hearbeat interval |
142+
| SECURENATIVE_INTERVAL | number | true | 1000 | Default interval for SDK to try to persist events | |
80143
| SECURENATIVE_MAX_EVENTS | number | true | 1000 | Max in-memory events queue |
81144
| SECURENATIVE_TIMEOUT | number | true | 1500 | API call timeout in ms |
82145
| SECURENATIVE_AUTO_SEND | Boolean | true | true | Should api auto send the events |

src/enums/event-type.ts

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,4 @@
11
enum EventType {
2-
AGENT_LOG_IN = "sn.agent.login",
3-
AGENT_LOG_OUT = "sn.agent.logout",
4-
AGENT_CONFIG = "sn.agent.config",
5-
HEART_BEAT = "sn.agent.heartbeat",
6-
ERROR = "sn.agent.error",
72
LOG_IN = "sn.user.login",
83
LOG_IN_CHALLENGE = "sn.user.login.challenge",
94
LOG_IN_FAILURE = "sn.user.login.failure",

src/index.ts

Lines changed: 1 addition & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,9 @@
1-
import fetch from 'node-fetch';
2-
import ConfigurationManager from "./configuration-manager";
31
import SecureNative from "./securenative";
42
import EventType from './enums/event-type';
5-
import { Logger } from "./logger";
6-
import { compareVersions } from './utils/utils';
7-
import { Package, PackageManager } from "./package-manager";
8-
import { join } from "path";
9-
import EventManager from "./event-manager";
103
import { contextFromRequest } from './utils/utils';
114

12-
const PACKAGE_FILE_NAME = 'package.json';
13-
const appPkg: Package = PackageManager.getPackage(join(process.cwd(), PACKAGE_FILE_NAME));
14-
const config = ConfigurationManager.getConfig();
15-
16-
// set default app name
17-
if (!config.appName) {
18-
ConfigurationManager.setConfigKey('appName', appPkg.name);
19-
}
20-
21-
const eventManager = new EventManager(fetch, config);
22-
const secureNative = new SecureNative(eventManager, config);
23-
24-
// init logger
25-
Logger.initLogger(config);
26-
Logger.debug("Loaded Configurations", JSON.stringify(config));
27-
28-
Logger.debug('Starting version compatibility check');
29-
30-
if (compareVersions(process.version, config.minSupportedVersion) < 0) {
31-
console.warn(`This version of Node.js ${process.version} isn't supported by SecureNative, minimum required version is ${config.minSupportedVersion}`);
32-
console.warn(`Visit our docs to find out more: https://docs.securenative.com/docs/integrations/sdk/#install-via-npm-javascript`);
33-
}
34-
355
export {
366
contextFromRequest,
37-
secureNative,
7+
SecureNative,
388
EventType as EventTypes
399
};

src/securenative.spec.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,17 @@ const expect = chai.expect;
1010

1111
describe('SecureNative', () => {
1212
it('Should fail to create new instance when params are null', () => {
13-
expect(() => new SecureNative(null, null)).to.throw('Unable to create SecureNative instance, invalid config provided');
13+
expect(() => SecureNative.getInstance()).to.throw('You need to init sdk first!');
1414
});
1515

1616
it('Should have all public methods defined', () => {
1717
const config = ConfigurationManager.getConfig();
1818
config.disable = true;
1919
const fetcher = fetchMock.sandbox().post('*', 200);
2020
const eventManager = new EventManager(fetcher, config);
21-
const secureNative = new SecureNative(eventManager, config);
22-
21+
SecureNative.initialize(eventManager, config);
22+
const secureNative = SecureNative.getInstance();
23+
2324
expect(secureNative).to.have.property('track');
2425
expect(secureNative).to.have.property('verify');
2526
});

src/securenative.ts

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,57 @@ import { EventOptions } from './types/event-options';
33
import EventManager from './event-manager';
44
import ApiManager from './api-manager';
55
import VerifyResult from './types/verify-result';
6+
import { Logger } from './logger';
7+
import { PackageManager, Package } from './package-manager';
8+
import ConfigurationManager from './configuration-manager';
9+
import { join } from 'path';
10+
11+
const PACKAGE_FILE_NAME = 'package.json';
612

713
export default class SecureNative {
814
private apiManager: ApiManager;
9-
10-
constructor(eventManager: EventManager, options: SecureNativeOptions) {
15+
private static instance = null;
16+
17+
private constructor(eventManager: EventManager, options: SecureNativeOptions) {
1118
if (!eventManager || !options) {
1219
throw new Error('Unable to create SecureNative instance, invalid config provided');
1320
}
1421
this.apiManager = new ApiManager(eventManager, options);
1522
}
1623

24+
public static init(options: SecureNativeOptions) {
25+
const defaultOptions = ConfigurationManager.getConfig();
26+
const config: SecureNativeOptions = { ...options, ...defaultOptions };
27+
28+
const eventManager = new EventManager(fetch, config);
29+
SecureNative.initialize(eventManager, config);
30+
}
31+
32+
public static initialize(eventManager: EventManager, options: SecureNativeOptions) {
33+
if (SecureNative.instance) {
34+
throw new Error('This SDK was already initialized');
35+
}
36+
37+
const appPkg: Package = PackageManager.getPackage(join(process.cwd(), PACKAGE_FILE_NAME));
38+
// set default app name
39+
if (!options.appName) {
40+
ConfigurationManager.setConfigKey('appName', appPkg.name);
41+
}
42+
43+
// init logger
44+
Logger.initLogger(options);
45+
Logger.debug('Loaded Configurations', JSON.stringify(options));
46+
47+
SecureNative.instance = new SecureNative(eventManager, options);
48+
}
49+
50+
public static getInstance(): SecureNative {
51+
if (SecureNative.instance == null) {
52+
throw new Error('You need to init sdk first!');
53+
}
54+
return SecureNative.instance;
55+
}
56+
1757
public track(opts: EventOptions) {
1858
return this.apiManager.track(opts);
1959
}

src/types/securenative-options.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import FailoveStrategy from "../enums/failover-strategy";
1+
import FailoveStrategy from '../enums/failover-strategy';
22

33
export type SecureNativeOptions = {
44
apiKey?: string;
@@ -12,4 +12,4 @@ export type SecureNativeOptions = {
1212
logLevel?: string;
1313
failoverStrategy?: FailoveStrategy;
1414
minSupportedVersion?: string;
15-
}
15+
};

0 commit comments

Comments
 (0)