Skip to content

Commit

Permalink
feat: create new package for cookie utilities (#1759)
Browse files Browse the repository at this point in the history
* feat: create new package for cookie utilities

* feat: finish the utility integration

* chore: clean up exports

* fix: improve test coverage

* fix: address ai bot review comments

* chore: fix readme

* fix: pkg exports
  • Loading branch information
saikumarrs authored Jun 25, 2024
1 parent 7d8f6d6 commit 92826a4
Show file tree
Hide file tree
Showing 59 changed files with 1,080 additions and 251 deletions.
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@
"cancelAnimationFrame",
"navigator.sendBeacon",
"Uint8Array",
"Set"
"Set",
"atob"
]
},
"env": {
Expand Down
2 changes: 1 addition & 1 deletion jest.preset.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ module.exports = {
},
testEnvironmentOptions: {
...nxPreset.testEnvironmentOptions,
url: 'http://www.test-host.com',
url: 'https://www.test-host.com',
runScripts: 'dangerously',
resources: 'usable',
},
Expand Down
14 changes: 14 additions & 0 deletions package-lock.json

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

17 changes: 17 additions & 0 deletions packages/analytics-js-cookies/.jscpd.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"threshold": 5,
"reporters": ["html", "console"],
"pattern": "**/*",
"ignore": [
"**/__tests__/**",
"**/__mocks__/**",
"**/__fixtures__/**",
"**/node_modules/**",
"*.test.*"
],
"absolute": true,
"gitignore": true,
"output": "./reports/",
"mode": "strict",
"format": ["typescript", "tsx"]
}
11 changes: 11 additions & 0 deletions packages/analytics-js-cookies/.size-limit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* DO NOT EDIT the size limits configured in this file.
* Should you update them, please contact CODEOWNERS.
*/
module.exports = [
{
name: 'Cookies Utilities',
path: 'dist/**/*.js',
limit: '2 KiB',
},
];
3 changes: 3 additions & 0 deletions packages/analytics-js-cookies/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Changelog

This file was generated using [@jscutlery/semver](https://github.com/jscutlery/semver).
Empty file.
21 changes: 21 additions & 0 deletions packages/analytics-js-cookies/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2021 RudderStack

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.
78 changes: 78 additions & 0 deletions packages/analytics-js-cookies/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
## [![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](https://www.typescriptlang.org/)

<p align="center">
<a href="https://rudderstack.com/">
<img alt="RudderStack" width="512" src="https://raw.githubusercontent.com/rudderlabs/rudder-sdk-js/develop/assets/rs-logo-full-light.jpg">
</a>
<br />
<caption>The Customer Data Platform for Developers</caption>
</p>
<p align="center">
<b>
<a href="https://rudderstack.com">Website</a>
·
<a href="https://rudderstack.com/docs/stream-sources/rudderstack-sdk-integration-guides/rudderstack-javascript-sdk/">Documentation</a>
·
<a href="https://rudderstack.com/join-rudderstack-slack-community">Community Slack</a>
</b>
</p>

---

# @rudderstack/analytics-js-cookies

RudderStack JavaScript SDK utility for cookies.

## APIs

### `getDecryptedCookie`

This function decrypts and returns the RudderStack JavaScript SDK cookie values.

The return type is either a `string` or an `object` as some cookies like user ID, anonymous user ID have string values while user traits are objects.

It returns `null` in either of the following scenarios:

- If the cookie is not present.
- If the cookie is not properly encrypted.
- It only decrypts the cookies that are created by the RudderStack JavaScript SDK encryption version "v3".
- If the decrypted cookie value is not a valid JSON string.
- If the provided cookie name is not a valid RudderStack JavaScript SDK cookie name.

> If unencrypted, the cookie value will be returned as is.
> Any errors during decryption are swallowed by the function, returning `null`.
The following are the available cookie key exports:
- `userIdKey`: The key for the user ID cookie.
- `userTraitsKey`: The key for the user traits cookie.
- `anonymousUserIdKey`: The key for the anonymous user ID cookie.
- `groupIdKey`: The key for the group ID cookie.
- `groupTraitsKey`: The key for the group traits cookie.
- `pageInitialReferrerKey`: The key for the page initial referrer cookie.
- `pageInitialReferringDomainKey`: The key for the page initial referring domain cookie.
- `sessionInfoKey`: The key for the session ID cookie.
- `authTokenKey`: The key for the auth token cookie.


```javascript
import {
getDecryptedCookie,
anonymousUserIdKey,
userTraitsKey,
} from '@rudderstack/analytics-js-cookies';

const anonymousId = getDecryptedCookie(anonymousUserIdKey);
console.log('Anonymous User ID: ', anonymousId);
// Output: Anonymous User ID: 2c5b6d48-ea90-43a2-a2f6-457d27f90328

const userTraits = getDecryptedCookie(userTraitsKey);
console.log('User Traits: ', userTraits);
// Output: User Traits: {"email":"[email protected]","name":"John Doe"}

const invalidCookie = getDecryptedCookie('invalid-cookie-name');
console.log('Invalid Cookie: ', invalidCookie);
// Output: Invalid Cookie: null
```

> For detailed documentation on the RudderStack JavaScript SDK, click [**here**](https://www.rudderstack.com/docs/sources/event-streams/sdks/rudderstack-javascript-sdk/).
Original file line number Diff line number Diff line change
@@ -1,7 +1,21 @@
import { cookie } from '../../../../src/services/StoreManager/component-cookie';
import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';
import { cookie } from '../../src/component-cookie';

class MockLogger implements ILogger {
error = jest.fn();
}

const mockLoggerInstance = new MockLogger();

beforeEach(() => {
const allCookies = cookie();
Object.keys(allCookies).forEach(cookieName => {
cookie(cookieName, null);
});
});

// TODO: clean up structure here, clean up cookie before each test
describe('cookie(name, value)', () => {
describe('cookies', () => {
it('should set a cookie', () => {
cookie('name', 'tobi');
expect('tobi').toEqual(cookie('name'));
Expand All @@ -23,7 +37,29 @@ describe('cookie(name, value)', () => {
it('should ignore URIError', () => {
cookie('bad', '%');
cookie('bad', null);
expect(undefined).toEqual(cookie('bad'));

cookie('bad', '\ud83d', undefined, mockLoggerInstance);
expect(mockLoggerInstance.error).toHaveBeenCalledTimes(1);
expect(mockLoggerInstance.error).toHaveBeenNthCalledWith(
1,
'Failed to encode the cookie data.',
expect.any(Error),
);

expect(cookie('bad')).toEqual('undefined');
});

it('should return undefined if the cookies are not encoded properly', () => {
document.cookie = 'name=tobi%ferret';
expect(cookie('name')).toEqual(undefined);

// delete cookie
document.cookie = 'name=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
});

it('should set cookie as per the options', () => {
cookie('name', 'tobi', { domain: '.test-host.com', path: '/', secure: true, samesite: 'None' });
expect(document.cookie.includes('name=tobi')).toBeTruthy();
});
});

Expand Down Expand Up @@ -62,4 +98,14 @@ describe('cookie()', () => {
expect('loki').toEqual(obj.name);
expect('ferret').toEqual(obj.species);
});

it('should return all cookies if the first argument is not a valid string', () => {
cookie('name', 'loki');
cookie('species', 'ferret');
const obj = cookie(false);

expect(2).toEqual(Object.keys(obj).length);
expect('loki').toEqual(obj.name);
expect('ferret').toEqual(obj.species);
});
});
122 changes: 122 additions & 0 deletions packages/analytics-js-cookies/__tests__/cookieUtilities.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import {
anonymousUserIdKey,
authTokenKey,
groupIdKey,
groupTraitsKey,
pageInitialReferrerKey,
pageInitialReferringDomainKey,
sessionInfoKey,
userIdKey,
userTraitsKey,
} from '../src';
import { encrypt, decrypt, getDecryptedCookie } from '../src/cookiesUtilities';

describe('Cookie Utilities', () => {
describe('encrypt', () => {
it('should encrypt the value', () => {
expect(encrypt('test-data')).toBe('RS_ENC_v3_dGVzdC1kYXRh');
});
});

describe('decrypt', () => {
it('should decrypt the value', () => {
expect(decrypt('RS_ENC_v3_dGVzdC1kYXRh')).toBe('test-data');
});

it('should return same data if it is not a supported encryption format', () => {
expect(decrypt('test-data')).toBe('test-data');
});

it('should throw error if the value is not properly encrypted', () => {
expect(() => decrypt('RS_ENC_v3_dGVzdC1kYXRh-some-random-data')).toThrow();
});
});

describe('getDecryptedCookie', () => {
it('should return the decrypted cookie value', () => {
// JSON.stringify('test-data') -> '"test-data"'
document.cookie = 'rl_anonymous_id=RS_ENC_v3_InRlc3QtZGF0YSI=';
expect(getDecryptedCookie('rl_anonymous_id')).toBe('test-data');

// delete cookie
document.cookie = 'rl_anonymous_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
});

it('should return null if the cookie is not present', () => {
expect(getDecryptedCookie('rl_anonymous_id')).toBeNull();
});

it('should return value if the cookie is not encrypted', () => {
document.cookie = 'rl_anonymous_id="test-data"';
expect(getDecryptedCookie('rl_anonymous_id')).toBe('test-data');

// delete cookie
document.cookie = 'rl_anonymous_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
});

it('should return null if the cookie is not properly encrypted', () => {
document.cookie = 'rl_anonymous_id=RS_ENC_v3_InRlc3QtZGF0YQ==';
expect(getDecryptedCookie('rl_anonymous_id')).toBeNull();

// delete cookie
document.cookie = 'rl_anonymous_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
});

it('should return null if the cookie value is not parsable', () => {
// the encrypted value is '"test-data' (missing closing double quote)

document.cookie = 'rl_anonymous_id=RS_ENC_v3_InRlc3QtZGF0YQ==';
expect(getDecryptedCookie('rl_anonymous_id')).toBeNull();

// delete cookie
document.cookie = 'rl_anonymous_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
});

it('should return null if the provided cookie name is not valid', () => {
expect(getDecryptedCookie('invalid_cookie_name')).toBeNull();
});

it('should return decrypted cookie value if the cookie value is an object', () => {
document.cookie = 'rl_trait=RS_ENC_v3_ewogICJ0ZXN0LWtleSI6ICJ0ZXN0LXZhbHVlIgp9';
expect(getDecryptedCookie('rl_trait')).toEqual({ 'test-key': 'test-value' });

// delete cookie
document.cookie = 'rl_trait=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
});

it('should return decrypted cookie values for all the allowed cookies', () => {
document.cookie = 'rl_user_id=RS_ENC_v3_InRlc3QtdXNlcl9pZCI=';
document.cookie = 'rl_trait=RS_ENC_v3_ewogICJ0ZXN0LWtleSI6ICJ0ZXN0LXZhbHVlIgp9';
document.cookie = 'rl_anonymous_id=RS_ENC_v3_InRlc3QtZGF0YSI=';
document.cookie = 'rl_group_id=RS_ENC_v3_InRlc3QtZ3JvdXBfaWQi';
document.cookie = 'rl_group_trait=RS_ENC_v3_ewogICJ0ZXN0LWtleSI6ICJ0ZXN0LXZhbHVlIgp9';
document.cookie = 'rl_page_init_referrer=RS_ENC_v3_InRlc3QtcGFnZV9pbml0X3JlZmVycmVyIg==';
document.cookie =
'rl_page_init_referring_domain=RS_ENC_v3_InRlc3QtcGFnZV9pbml0X3JlZmVycmluZ19kb21haW4i';
document.cookie = 'rl_session=RS_ENC_v3_ewogICJ0ZXN0LWtleSI6ICJ0ZXN0LXZhbHVlIgp9';
document.cookie = 'rl_auth_token=RS_ENC_v3_InRlc3QtdG9rZW4i';
expect(getDecryptedCookie(userIdKey)).toBe('test-user_id');
expect(getDecryptedCookie(userTraitsKey)).toEqual({ 'test-key': 'test-value' });
expect(getDecryptedCookie(anonymousUserIdKey)).toBe('test-data');
expect(getDecryptedCookie(groupIdKey)).toBe('test-group_id');
expect(getDecryptedCookie(groupTraitsKey)).toEqual({ 'test-key': 'test-value' });
expect(getDecryptedCookie(pageInitialReferrerKey)).toBe('test-page_init_referrer');
expect(getDecryptedCookie(pageInitialReferringDomainKey)).toBe(
'test-page_init_referring_domain',
);
expect(getDecryptedCookie(sessionInfoKey)).toEqual({ 'test-key': 'test-value' });
expect(getDecryptedCookie(authTokenKey)).toBe('test-token');

// delete cookies
document.cookie = 'rl_user_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
document.cookie = 'rl_trait=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
document.cookie = 'rl_anonymous_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
document.cookie = 'rl_group_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
document.cookie = 'rl_group_trait=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
document.cookie = 'rl_page_init_referrer=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
document.cookie = 'rl_page_init_referring_domain=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
document.cookie = 'rl_session=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
document.cookie = 'rl_auth_token=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
});
});
});
14 changes: 14 additions & 0 deletions packages/analytics-js-cookies/babel.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"presets": [
[
"@babel/env",
{
"corejs": "3.6",
"useBuiltIns": "entry",
"bugfixes": true
}
],
"@babel/typescript"
],
"plugins": []
}
Loading

0 comments on commit 92826a4

Please sign in to comment.