Skip to content
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

Support new expiresAt/expiresIn/token/passed fields with trackOnce({ fraud: true }) and trackVerified() #159

Merged
merged 17 commits into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ Radar.initialize('prj_test_pk_...', { /* options */ });

Add the following script in your `html` file
```html
<script src="https://js.radar.com/v4.1.18/radar.min.js"></script>
<script src="https://js.radar.com/v4.2.0-beta.0/radar.min.js"></script>
```

Then initialize the Radar SDK
Expand All @@ -73,8 +73,8 @@ To create a map, first initialize the Radar SDK with your publishable key. Then
```html
<html>
<head>
<link href="https://js.radar.com/v4.1.18/radar.css" rel="stylesheet">
<script src="https://js.radar.com/v4.1.18/radar.min.js"></script>
<link href="https://js.radar.com/v4.2.0-beta.0/radar.css" rel="stylesheet">
<script src="https://js.radar.com/v4.2.0-beta.0/radar.min.js"></script>
</head>

<body>
Expand All @@ -98,8 +98,8 @@ To create an autocomplete input, first initialize the Radar SDK with your publis
```html
<html>
<head>
<link href="https://js.radar.com/v4.1.18/radar.css" rel="stylesheet">
<script src="https://js.radar.com/v4.1.18/radar.min.js"></script>
<link href="https://js.radar.com/v4.2.0-beta.0/radar.css" rel="stylesheet">
<script src="https://js.radar.com/v4.2.0-beta.0/radar.min.js"></script>
</head>

<body>
Expand Down Expand Up @@ -130,8 +130,8 @@ To power [geofencing](https://radar.com/documentation/geofencing/overview) exper
```html
<html>
<head>
<link href="https://js.radar.com/v4.1.18/radar.css" rel="stylesheet">
<script src="https://js.radar.com/v4.1.18/radar.min.js"></script>
<link href="https://js.radar.com/v4.2.0-beta.0/radar.css" rel="stylesheet">
<script src="https://js.radar.com/v4.2.0-beta.0/radar.min.js"></script>
</head>

<body>
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "radar-sdk-js",
"version": "4.1.18",
"version": "4.2.0-beta.0",
Copy link
Collaborator

Choose a reason for hiding this comment

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

Are we shipping these changes as 4.2?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Removing trackVerifiedToken() and renaming the error codes are breaking changes, so should prob be 4.2.x instead of 4.1.x

"description": "Web Javascript SDK for Radar, location infrastructure for mobile and web apps.",
"homepage": "https://radar.com",
"type": "module",
Expand Down
52 changes: 39 additions & 13 deletions src/api/track.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import TripsAPI from './trips';
import { signJWT } from '../util/jwt';
import { ping } from '../util/net';

import type { RadarTrackParams, RadarTrackResponse } from '../types';
import type { RadarTrackParams, RadarTrackResponse, RadarTrackVerifiedResponse } from '../types';

class TrackAPI {
static async trackOnce(params: RadarTrackParams) {
Expand Down Expand Up @@ -160,29 +160,55 @@ class TrackAPI {
sclVal,
cslVal,
};

let { user, events, token, expiresAt } = response;
const location = { latitude, longitude, accuracy };
let passed;
let expiresIn;
if (expiresAt) {
expiresAt = Date.parse(expiresAt);
passed = user?.fraud?.passed && user?.country?.passed && user?.state?.passed;
expiresIn = expiresAt ? (expiresAt.getMilliseconds() - new Date().getMilliseconds()) / 1000 : null;
}

const trackRes = {
user,
events,
location,
token,
expiresAt,
expiresIn,
passed,
} as RadarTrackVerifiedResponse;

if (options.debug) {
trackRes.response = response;
}

return trackRes;
}
} else {
response = await Http.request({
method: 'POST',
path: 'track',
data: body,
});
}

const { user, events } = response;
const location = { latitude, longitude, accuracy };
const { user, events } = response;
const location = { latitude, longitude, accuracy };

const trackRes = {
user,
events,
location,
} as RadarTrackResponse;
const trackRes = {
user,
events,
location,
} as RadarTrackResponse;

if (options.debug) {
trackRes.response = response;
}
if (options.debug) {
trackRes.response = response;
}

return trackRes;
return trackRes;
}
}
}

Expand Down
27 changes: 13 additions & 14 deletions src/api/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import Logger from '../logger';
import Session from '../session';
import Storage from '../storage';

import type { RadarTrackParams, RadarTrackResponse, RadarTrackTokenResponse } from '../types';
import type { RadarTrackParams, RadarTrackResponse, RadarTrackVerifiedResponse } from '../types';

class VerifyAPI {
static async trackVerified(params: RadarTrackParams, encrypted: Boolean = false) {
Expand Down Expand Up @@ -53,7 +53,7 @@ class VerifyAPI {
host: apple ? 'https://radar-verify.com:52516' : 'http://localhost:52516',
});

const { user, events, token } = response;
let { user, events, token, expiresAt } = response;
let location;
if (user && user.location && user.location.coordinates && user.locationAccuracy) {
location = {
Expand All @@ -62,24 +62,23 @@ class VerifyAPI {
accuracy: user.locationAccuracy,
};
}

if (encrypted) {
const trackTokenRes = {
token,
} as RadarTrackTokenResponse;

if (options.debug) {
trackTokenRes.response = response;
}

return trackTokenRes;
let passed;
let expiresIn;
if (expiresAt) {
expiresAt = Date.parse(expiresAt);
passed = user?.fraud?.passed && user?.country?.passed && user?.state?.passed;
expiresIn = expiresAt ? (expiresAt.getMilliseconds() - new Date().getMilliseconds()) / 1000 : null;
}

const trackRes = {
user,
events,
location,
} as RadarTrackResponse;
token,
expiresAt,
expiresIn,
passed,
} as RadarTrackVerifiedResponse;

if (options.debug) {
trackRes.response = response;
Expand Down
18 changes: 9 additions & 9 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,19 @@ export class RadarLocationError extends RadarError {
}
}

export class RadarLocationPermissionsError extends RadarError {
export class RadarPermissionsError extends RadarError {
constructor(message: string) {
super(message);
this.name = 'RadarLocationPermissionsError';
this.name = 'RadarPermissionsError';
Copy link
Contributor Author

Choose a reason for hiding this comment

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

To match mobile SDKs

this.status = 'ERROR_PERMISSIONS';
}
}

export class RadarDesktopAppError extends RadarError {
export class RadarVerifyAppError extends RadarError {
constructor() {
super('Desktop app not running.');
this.name = 'RadarDesktopAppError';
this.status = 'ERROR_DESKTOP_APP';
super('Radar Verify app not running.');
this.name = 'RadarVerifyAppError';
Copy link
Contributor Author

Choose a reason for hiding this comment

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

To account for Radar Verify desktop AND mobile apps

this.status = 'ERROR_VERIFY_APP';
}
}

Expand Down Expand Up @@ -131,11 +131,11 @@ export class RadarServerError extends RadarError {
}
}

export class RadarTimeoutError extends RadarError {
export class RadarNetworkError extends RadarError {
constructor() {
super('Request timed out.');
this.name = 'RadarTimeoutError';
this.status = 'ERROR_TIMED_OUT';
this.name = 'RadarNetworkError';
Copy link
Contributor Author

Choose a reason for hiding this comment

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

To match mobile SDKs

this.status = 'ERROR_NETWORK';
}
}

Expand Down
10 changes: 5 additions & 5 deletions src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@ import Logger from './logger';

import {
RadarBadRequestError,
RadarDesktopAppError,
RadarForbiddenError,
RadarLocationError,
RadarLocationPermissionsError,
RadarNetworkError,
RadarNotFoundError,
RadarPaymentRequiredError,
RadarPermissionsError,
RadarPublishableKeyError,
RadarRateLimitError,
RadarServerError,
RadarTimeoutError,
RadarUnauthorizedError,
RadarUnknownError,
RadarVerifyAppError,
} from './errors';

export type HttpMethod = 'GET' | 'PUT' | 'PATCH' | 'POST' | 'DELETE';
Expand Down Expand Up @@ -110,11 +110,11 @@ class Http {

const error = response?.meta?.error;
if (error === 'ERROR_PERMISSIONS') {
return reject(new RadarLocationPermissionsError('Location permissions not granted.'));
return reject(new RadarPermissionsError('Location permissions not granted.'));
} else if (error === 'ERROR_LOCATION') {
return reject(new RadarLocationError('Could not determine location.'));
} else if (error === 'ERROR_NETWORK') {
return reject(new RadarTimeoutError());
return reject(new RadarNetworkError());
}

if (xhr.status == 200) {
Expand Down
4 changes: 0 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,6 @@ class Radar {
return VerifyAPI.trackVerified(params);
}

public static trackVerifiedToken(params: RadarTrackParams = {}) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

If we don't want this to be a breaking change, could we potentially pass the params here to track width { fraud: true }?

Could also include a deprecation notice:

Logger.warn('DEPRECATED - trackVerifiedToken will be removed in a future release.');

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Nobody uses this in prod yet (except for our demo page), so I think we're fine to skip this

return VerifyAPI.trackVerified(params, true);
}

public static getContext(params: Location) {
return ContextAPI.getContext(params);
}
Expand Down
17 changes: 6 additions & 11 deletions src/navigator.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,14 @@
import Config from './config';
import Logger from './logger';
import Storage from './storage';
import { RadarLocationError, RadarLocationPermissionsError } from './errors';
import { RadarLocationError, RadarPermissionsError } from './errors';

import type { LocationAuthorization, NavigatorPosition } from './types';

interface PositionOptionOverrides {
desiredAccuracy?: string;
}

// https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPositionError
const PERMISSION_ERROR_MESSAGES: any = {
1: 'Permission denied.',
2: 'Position unavailable.',
3: 'Timeout.',
};

const DEFAULT_POSITION_OPTIONS: PositionOptions = {
maximumAge: 0,
timeout: 1000 * 30, // 30 seconds
Expand Down Expand Up @@ -95,9 +88,11 @@ class Navigator {
return resolve({ latitude, longitude, accuracy });
},
(err: GeolocationPositionError) => { // location call failed or user did not grant permission
if (err && err.code) {
const message = PERMISSION_ERROR_MESSAGES[err.code.toString()] || 'unknown';
return reject(new RadarLocationPermissionsError(message));
if (err && err.code === 1) {
// https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPositionError
// code 1 means permission denied
// codes 2 and 3 mean location unavailable or timeout
return reject(new RadarPermissionsError('Permission denied.'));
}
return reject(new RadarLocationError('Could not determine location.'));
},
Expand Down
8 changes: 6 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ export type RadarEventType =
| 'user.updated_trip'
| 'user.approaching_trip_destination'
| 'user.arrived_at_trip_destination'
| 'user.stopped_trip';
| 'user.stopped_trip'
| 'user.failed_fraud';

export interface RadarGeofence {
_id: string;
Expand Down Expand Up @@ -212,8 +213,11 @@ export interface RadarTrackResponse extends RadarResponse {
events?: RadarEvent[];
}

export interface RadarTrackTokenResponse extends RadarResponse {
export interface RadarTrackVerifiedResponse extends RadarTrackResponse {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Could also be a separate interface instead of extending RadarTrackResponse

token?: String;
expiresAt?: Date;
expiresIn?: number;
passed?: boolean;
}

export interface RadarContextResponse extends RadarResponse {
Expand Down
2 changes: 1 addition & 1 deletion src/version.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export default '4.1.18';
export default '4.2.0-beta.0';
2 changes: 1 addition & 1 deletion test/api/track.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ describe('Track', () => {
await Track.trackOnce({});
throw new Error('Test did not throw expected error.');
} catch (err: any) {
expect(err.name).toEqual('RadarLocationPermissionsError');
expect(err.name).toEqual('RadarPermissionsError');
expect(err.message).toEqual('Permission denied.');
expect(err.status).toEqual('ERROR_PERMISSIONS');
}
Expand Down
4 changes: 2 additions & 2 deletions test/navigator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ import { nycOffice, enableLocation } from './utils';
describe('Navigator', () => {
describe('getCurrentPosition', () => {
describe('location permissions denied', () => {
it('should throw a RadarLocationPermissionsError', async () => {
it('should throw a RadarPermissionsError', async () => {
try {
await Navigator.getCurrentPosition();
throw new Error('Response should not succeed.');
} catch (err: any) {
expect(err.name).toEqual('RadarLocationPermissionsError');
expect(err.name).toEqual('RadarPermissionsError');
expect(err.message).toEqual('Permission denied.');
expect(err.status).toEqual('ERROR_PERMISSIONS');
}
Expand Down
Loading