@workos-inc/node 7.30.0 → 7.31.0-beta.actions1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/lib/actions/actions.d.ts +19 -0
  2. package/lib/actions/actions.js +53 -0
  3. package/lib/actions/actions.spec.d.ts +1 -0
  4. package/lib/actions/actions.spec.js +78 -0
  5. package/lib/actions/fixtures/action-context.json +39 -0
  6. package/lib/actions/interfaces/response-payload.d.ts +23 -0
  7. package/lib/actions/interfaces/response-payload.js +2 -0
  8. package/lib/common/crypto/CryptoProvider.d.ts +32 -0
  9. package/lib/common/crypto/CryptoProvider.js +13 -0
  10. package/lib/common/crypto/CryptoProvider.spec.d.ts +1 -0
  11. package/lib/common/crypto/CryptoProvider.spec.js +57 -0
  12. package/lib/common/crypto/NodeCryptoProvider.d.ts +12 -0
  13. package/lib/common/crypto/NodeCryptoProvider.js +73 -0
  14. package/lib/common/crypto/SignatureProvider.d.ts +13 -0
  15. package/lib/common/crypto/SignatureProvider.js +53 -0
  16. package/lib/common/crypto/SignatureProvider.spec.d.ts +1 -0
  17. package/lib/common/crypto/SignatureProvider.spec.js +66 -0
  18. package/lib/common/crypto/SubtleCryptoProvider.d.ts +15 -0
  19. package/lib/common/crypto/SubtleCryptoProvider.js +75 -0
  20. package/lib/common/crypto/index.d.ts +4 -0
  21. package/lib/common/crypto/index.js +20 -0
  22. package/lib/common/net/fetch-client.spec.d.ts +1 -0
  23. package/lib/common/net/fetch-client.spec.js +140 -0
  24. package/lib/common/net/index.d.ts +5 -0
  25. package/lib/common/net/index.js +31 -0
  26. package/lib/common/net/node-client.js +1 -0
  27. package/lib/common/net/node-client.spec.d.ts +1 -0
  28. package/lib/common/net/node-client.spec.js +140 -0
  29. package/lib/common/utils/unreachable.d.ts +10 -0
  30. package/lib/common/utils/unreachable.js +18 -0
  31. package/lib/fga/fga.spec.js +0 -609
  32. package/lib/index.d.ts +3 -0
  33. package/lib/index.js +12 -0
  34. package/lib/index.worker.d.ts +3 -0
  35. package/lib/index.worker.js +6 -0
  36. package/lib/organizations/fixtures/clear-stripe-customer-id.json +13 -0
  37. package/lib/organizations/fixtures/set-stripe-customer-id-disabled.json +4 -0
  38. package/lib/organizations/fixtures/set-stripe-customer-id.json +14 -0
  39. package/lib/organizations/interfaces/organization.interface.d.ts +2 -0
  40. package/lib/organizations/interfaces/update-organization-options.interface.d.ts +2 -0
  41. package/lib/organizations/organizations.spec.js +39 -0
  42. package/lib/organizations/serializers/organization.serializer.js +3 -9
  43. package/lib/organizations/serializers/update-organization-options.serializer.js +1 -0
  44. package/lib/user-management/interfaces/authenticate-with-session-cookie.interface.d.ts +2 -0
  45. package/lib/user-management/session.js +2 -1
  46. package/lib/user-management/session.spec.js +2 -1
  47. package/lib/user-management/user-management.js +2 -1
  48. package/lib/user-management/user-management.spec.js +2 -1
  49. package/lib/webhooks/webhooks.d.ts +9 -9
  50. package/lib/webhooks/webhooks.js +11 -36
  51. package/lib/webhooks/webhooks.spec.js +23 -46
  52. package/lib/widgets/fixtures/get-token-error.json +5 -0
  53. package/lib/widgets/fixtures/token.json +3 -0
  54. package/lib/widgets/interfaces/get-token.d.ts +19 -0
  55. package/lib/widgets/interfaces/get-token.js +13 -0
  56. package/lib/widgets/widgets.d.ts +7 -0
  57. package/lib/widgets/widgets.js +25 -0
  58. package/lib/widgets/widgets.spec.d.ts +1 -0
  59. package/lib/widgets/widgets.spec.js +49 -0
  60. package/lib/workos.d.ts +5 -0
  61. package/lib/workos.js +9 -2
  62. package/lib/workos.spec.js +5 -1
  63. package/package.json +2 -1
@@ -0,0 +1,19 @@
1
+ import { CryptoProvider } from '../common/crypto/crypto-provider';
2
+ import { AuthenticationActionResponseData, ResponsePayload, UserRegistrationActionResponseData } from './interfaces/response-payload';
3
+ export declare class Actions {
4
+ private signatureProvider;
5
+ constructor(cryptoProvider: CryptoProvider);
6
+ private get computeSignature();
7
+ get verifyHeader(): ({ payload, sigHeader, secret, tolerance, }: {
8
+ payload: any;
9
+ sigHeader: string;
10
+ secret: string;
11
+ tolerance?: number | undefined;
12
+ }) => Promise<boolean>;
13
+ serializeType(type: AuthenticationActionResponseData['type'] | UserRegistrationActionResponseData['type']): "authentication_action_response" | "user_registration_action_response";
14
+ signResponse(data: AuthenticationActionResponseData | UserRegistrationActionResponseData, secret: string): Promise<{
15
+ object: string;
16
+ payload: ResponsePayload;
17
+ signature: string;
18
+ }>;
19
+ }
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.Actions = void 0;
13
+ const crypto_1 = require("../common/crypto");
14
+ const unreachable_1 = require("../common/utils/unreachable");
15
+ class Actions {
16
+ constructor(cryptoProvider) {
17
+ this.signatureProvider = new crypto_1.SignatureProvider(cryptoProvider);
18
+ }
19
+ get computeSignature() {
20
+ return this.signatureProvider.computeSignature.bind(this.signatureProvider);
21
+ }
22
+ get verifyHeader() {
23
+ return this.signatureProvider.verifyHeader.bind(this.signatureProvider);
24
+ }
25
+ serializeType(type) {
26
+ switch (type) {
27
+ case 'authentication':
28
+ return 'authentication_action_response';
29
+ case 'user_registration':
30
+ return 'user_registration_action_response';
31
+ default:
32
+ return (0, unreachable_1.unreachable)(type);
33
+ }
34
+ }
35
+ signResponse(data, secret) {
36
+ return __awaiter(this, void 0, void 0, function* () {
37
+ let errorMessage;
38
+ const { verdict, type } = data;
39
+ if (verdict === 'Deny' && data.errorMessage) {
40
+ errorMessage = data.errorMessage;
41
+ }
42
+ const responsePayload = Object.assign({ timestamp: Date.now(), verdict }, (verdict === 'Deny' &&
43
+ data.errorMessage && { error_message: errorMessage }));
44
+ const response = {
45
+ object: this.serializeType(type),
46
+ payload: responsePayload,
47
+ signature: yield this.computeSignature(responsePayload.timestamp, responsePayload, secret),
48
+ };
49
+ return response;
50
+ });
51
+ }
52
+ }
53
+ exports.Actions = Actions;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const crypto_1 = __importDefault(require("crypto"));
16
+ const workos_1 = require("../workos");
17
+ const action_context_json_1 = __importDefault(require("./fixtures/action-context.json"));
18
+ const workos = new workos_1.WorkOS('sk_test_Sz3IQjepeSWaI4cMS4ms4sMuU');
19
+ const crypto_2 = require("../common/crypto");
20
+ describe('Actions', () => {
21
+ let secret;
22
+ beforeEach(() => {
23
+ secret = 'secret';
24
+ });
25
+ describe('signResponse', () => {
26
+ describe('type: authentication', () => {
27
+ it('returns a signed response', () => __awaiter(void 0, void 0, void 0, function* () {
28
+ const nodeCryptoProvider = new crypto_2.NodeCryptoProvider();
29
+ const response = yield workos.actions.signResponse({
30
+ type: 'authentication',
31
+ verdict: 'Allow',
32
+ }, secret);
33
+ const signedPayload = `${response.payload.timestamp}.${JSON.stringify(response.payload)}`;
34
+ const expectedSig = yield nodeCryptoProvider.computeHMACSignatureAsync(signedPayload, secret);
35
+ expect(response.object).toEqual('authentication_action_response');
36
+ expect(response.payload.verdict).toEqual('Allow');
37
+ expect(response.payload.timestamp).toBeGreaterThan(0);
38
+ expect(response.signature).toEqual(expectedSig);
39
+ }));
40
+ });
41
+ describe('type: user_registration', () => {
42
+ it('returns a signed response', () => __awaiter(void 0, void 0, void 0, function* () {
43
+ const nodeCryptoProvider = new crypto_2.NodeCryptoProvider();
44
+ const response = yield workos.actions.signResponse({
45
+ type: 'user_registration',
46
+ verdict: 'Deny',
47
+ errorMessage: 'User already exists',
48
+ }, secret);
49
+ const signedPayload = `${response.payload.timestamp}.${JSON.stringify(response.payload)}`;
50
+ const expectedSig = yield nodeCryptoProvider.computeHMACSignatureAsync(signedPayload, secret);
51
+ expect(response.object).toEqual('user_registration_action_response');
52
+ expect(response.payload.verdict).toEqual('Deny');
53
+ expect(response.payload.timestamp).toBeGreaterThan(0);
54
+ expect(response.signature).toEqual(expectedSig);
55
+ }));
56
+ });
57
+ });
58
+ describe('verifyHeader', () => {
59
+ it('aliases to the signature provider', () => __awaiter(void 0, void 0, void 0, function* () {
60
+ const spy = jest.spyOn(
61
+ // tslint:disable-next-line
62
+ workos.actions['signatureProvider'], 'verifyHeader');
63
+ const timestamp = Date.now() * 1000;
64
+ const unhashedString = `${timestamp}.${JSON.stringify(action_context_json_1.default)}`;
65
+ const signatureHash = crypto_1.default
66
+ .createHmac('sha256', secret)
67
+ .update(unhashedString)
68
+ .digest()
69
+ .toString('hex');
70
+ yield workos.actions.verifyHeader({
71
+ payload: action_context_json_1.default,
72
+ sigHeader: `t=${timestamp}, v1=${signatureHash}`,
73
+ secret,
74
+ });
75
+ expect(spy).toHaveBeenCalled();
76
+ }));
77
+ });
78
+ });
@@ -0,0 +1,39 @@
1
+ {
2
+ "user": {
3
+ "object": "user",
4
+ "id": "01JATCHZVEC5EPANDPEZVM68Y9",
5
+ "email": "jane@foocorp.com",
6
+ "first_name": "Jane",
7
+ "last_name": "Doe",
8
+ "email_verified": true,
9
+ "profile_picture_url": "https://example.com/jane.jpg",
10
+ "created_at": "2024-10-22T17:12:50.746Z",
11
+ "updated_at": "2024-10-22T17:12:50.746Z"
12
+ },
13
+ "ip_address": "50.141.123.10",
14
+ "user_agent": "Mozilla/5.0",
15
+ "issuer": "test",
16
+ "object": "authentication_action_context",
17
+ "organization": {
18
+ "object": "organization",
19
+ "id": "01JATCMZJY26PQ59XT9BNT0FNN",
20
+ "name": "Foo Corp",
21
+ "allow_profiles_outside_organization": false,
22
+ "domains": [],
23
+ "lookup_key": "my-key",
24
+ "created_at": "2024-10-22T17:12:50.746Z",
25
+ "updated_at": "2024-10-22T17:12:50.746Z"
26
+ },
27
+ "organization_membership": {
28
+ "object": "organization_membership",
29
+ "id": "01JATCNVYCHT1SZGENR4QTXKRK",
30
+ "user_id": "01JATCHZVEC5EPANDPEZVM68Y9",
31
+ "organization_id": "01JATCMZJY26PQ59XT9BNT0FNN",
32
+ "role": {
33
+ "slug": "member"
34
+ },
35
+ "status": "active",
36
+ "created_at": "2024-10-22T17:12:50.746Z",
37
+ "updated_at": "2024-10-22T17:12:50.746Z"
38
+ }
39
+ }
@@ -0,0 +1,23 @@
1
+ export interface ResponsePayload {
2
+ timestamp: number;
3
+ verdict?: 'Allow' | 'Deny';
4
+ errorMessage?: string;
5
+ }
6
+ interface AllowResponseData {
7
+ verdict: 'Allow';
8
+ }
9
+ interface DenyResponseData {
10
+ verdict: 'Deny';
11
+ errorMessage?: string;
12
+ }
13
+ export type AuthenticationActionResponseData = (AllowResponseData & {
14
+ type: 'authentication';
15
+ }) | (DenyResponseData & {
16
+ type: 'authentication';
17
+ });
18
+ export type UserRegistrationActionResponseData = (AllowResponseData & {
19
+ type: 'user_registration';
20
+ }) | (DenyResponseData & {
21
+ type: 'user_registration';
22
+ });
23
+ export {};
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Interface encapsulating the various crypto computations used by the library,
3
+ * allowing pluggable underlying crypto implementations.
4
+ */
5
+ export declare abstract class CryptoProvider {
6
+ encoder: TextEncoder;
7
+ /**
8
+ * Computes a SHA-256 HMAC given a secret and a payload (encoded in UTF-8).
9
+ * The output HMAC should be encoded in hexadecimal.
10
+ *
11
+ * Sample values for implementations:
12
+ * - computeHMACSignature('', 'test_secret') => 'f7f9bd47fb987337b5796fdc1fdb9ba221d0d5396814bfcaf9521f43fd8927fd'
13
+ * - computeHMACSignature('\ud83d\ude00', 'test_secret') => '837da296d05c4fe31f61d5d7ead035099d9585a5bcde87de952012a78f0b0c43
14
+ */
15
+ abstract computeHMACSignature(payload: string, secret: string): string;
16
+ /**
17
+ * Asynchronous version of `computeHMACSignature`. Some implementations may
18
+ * only allow support async signature computation.
19
+ *
20
+ * Computes a SHA-256 HMAC given a secret and a payload (encoded in UTF-8).
21
+ * The output HMAC should be encoded in hexadecimal.
22
+ *
23
+ * Sample values for implementations:
24
+ * - computeHMACSignature('', 'test_secret') => 'f7f9bd47fb987337b5796fdc1fdb9ba221d0d5396814bfcaf9521f43fd8927fd'
25
+ * - computeHMACSignature('\ud83d\ude00', 'test_secret') => '837da296d05c4fe31f61d5d7ead035099d9585a5bcde87de952012a78f0b0c43
26
+ */
27
+ abstract computeHMACSignatureAsync(payload: string, secret: string): Promise<string>;
28
+ /**
29
+ * Cryptographically determine whether two signatures are equal
30
+ */
31
+ abstract secureCompare(stringA: string, stringB: string): Promise<boolean>;
32
+ }
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CryptoProvider = void 0;
4
+ /**
5
+ * Interface encapsulating the various crypto computations used by the library,
6
+ * allowing pluggable underlying crypto implementations.
7
+ */
8
+ class CryptoProvider {
9
+ constructor() {
10
+ this.encoder = new TextEncoder();
11
+ }
12
+ }
13
+ exports.CryptoProvider = CryptoProvider;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const crypto_1 = __importDefault(require("crypto"));
16
+ const NodeCryptoProvider_1 = require("./NodeCryptoProvider");
17
+ const SubtleCryptoProvider_1 = require("./SubtleCryptoProvider");
18
+ const webhook_json_1 = __importDefault(require("../../webhooks/fixtures/webhook.json"));
19
+ const SignatureProvider_1 = require("./SignatureProvider");
20
+ describe('CryptoProvider', () => {
21
+ let payload;
22
+ let secret;
23
+ let timestamp;
24
+ let signatureHash;
25
+ beforeEach(() => {
26
+ payload = webhook_json_1.default;
27
+ secret = 'secret';
28
+ timestamp = Date.now() * 1000;
29
+ const unhashedString = `${timestamp}.${JSON.stringify(payload)}`;
30
+ signatureHash = crypto_1.default
31
+ .createHmac('sha256', secret)
32
+ .update(unhashedString)
33
+ .digest()
34
+ .toString('hex');
35
+ });
36
+ describe('when computing HMAC signature', () => {
37
+ it('returns the same for the Node crypto and Web Crypto versions', () => __awaiter(void 0, void 0, void 0, function* () {
38
+ const nodeCryptoProvider = new NodeCryptoProvider_1.NodeCryptoProvider();
39
+ const subtleCryptoProvider = new SubtleCryptoProvider_1.SubtleCryptoProvider();
40
+ const stringifiedPayload = JSON.stringify(payload);
41
+ const payloadHMAC = `${timestamp}.${stringifiedPayload}`;
42
+ const nodeCompare = yield nodeCryptoProvider.computeHMACSignatureAsync(payloadHMAC, secret);
43
+ const subtleCompare = yield subtleCryptoProvider.computeHMACSignatureAsync(payloadHMAC, secret);
44
+ expect(nodeCompare).toEqual(subtleCompare);
45
+ }));
46
+ });
47
+ describe('when securely comparing', () => {
48
+ it('returns the same for the Node crypto and Web Crypto versions', () => __awaiter(void 0, void 0, void 0, function* () {
49
+ const nodeCryptoProvider = new NodeCryptoProvider_1.NodeCryptoProvider();
50
+ const subtleCryptoProvider = new SubtleCryptoProvider_1.SubtleCryptoProvider();
51
+ const signatureProvider = new SignatureProvider_1.SignatureProvider(subtleCryptoProvider);
52
+ const signature = yield signatureProvider.computeSignature(timestamp, payload, secret);
53
+ expect(nodeCryptoProvider.secureCompare(signature, signatureHash)).toEqual(subtleCryptoProvider.secureCompare(signature, signatureHash));
54
+ expect(nodeCryptoProvider.secureCompare(signature, 'foo')).toEqual(subtleCryptoProvider.secureCompare(signature, 'foo'));
55
+ }));
56
+ });
57
+ });
@@ -0,0 +1,12 @@
1
+ import { CryptoProvider } from './CryptoProvider';
2
+ /**
3
+ * `CryptoProvider which uses the Node `crypto` package for its computations.
4
+ */
5
+ export declare class NodeCryptoProvider extends CryptoProvider {
6
+ /** @override */
7
+ computeHMACSignature(payload: string, secret: string): string;
8
+ /** @override */
9
+ computeHMACSignatureAsync(payload: string, secret: string): Promise<string>;
10
+ /** @override */
11
+ secureCompare(stringA: string, stringB: string): Promise<boolean>;
12
+ }
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ Object.defineProperty(exports, "__esModule", { value: true });
35
+ exports.NodeCryptoProvider = void 0;
36
+ const crypto = __importStar(require("crypto"));
37
+ const CryptoProvider_1 = require("./CryptoProvider");
38
+ /**
39
+ * `CryptoProvider which uses the Node `crypto` package for its computations.
40
+ */
41
+ class NodeCryptoProvider extends CryptoProvider_1.CryptoProvider {
42
+ /** @override */
43
+ computeHMACSignature(payload, secret) {
44
+ return crypto
45
+ .createHmac('sha256', secret)
46
+ .update(payload, 'utf8')
47
+ .digest('hex');
48
+ }
49
+ /** @override */
50
+ computeHMACSignatureAsync(payload, secret) {
51
+ return __awaiter(this, void 0, void 0, function* () {
52
+ const signature = yield this.computeHMACSignature(payload, secret);
53
+ return signature;
54
+ });
55
+ }
56
+ /** @override */
57
+ secureCompare(stringA, stringB) {
58
+ return __awaiter(this, void 0, void 0, function* () {
59
+ const bufferA = this.encoder.encode(stringA);
60
+ const bufferB = this.encoder.encode(stringB);
61
+ if (bufferA.length !== bufferB.length) {
62
+ return false;
63
+ }
64
+ // Generate a random key for HMAC
65
+ const key = crypto.randomBytes(32); // Generates a 256-bit key
66
+ const hmacA = crypto.createHmac('sha256', key).update(bufferA).digest();
67
+ const hmacB = crypto.createHmac('sha256', key).update(bufferB).digest();
68
+ // Perform a constant time comparison
69
+ return crypto.timingSafeEqual(hmacA, hmacB);
70
+ });
71
+ }
72
+ }
73
+ exports.NodeCryptoProvider = NodeCryptoProvider;
@@ -0,0 +1,13 @@
1
+ import { CryptoProvider } from './CryptoProvider';
2
+ export declare class SignatureProvider {
3
+ private cryptoProvider;
4
+ constructor(cryptoProvider: CryptoProvider);
5
+ verifyHeader({ payload, sigHeader, secret, tolerance, }: {
6
+ payload: any;
7
+ sigHeader: string;
8
+ secret: string;
9
+ tolerance?: number;
10
+ }): Promise<boolean>;
11
+ getTimestampAndSignatureHash(sigHeader: string): [string, string];
12
+ computeSignature(timestamp: any, payload: any, secret: string): Promise<string>;
13
+ }
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.SignatureProvider = void 0;
13
+ const exceptions_1 = require("../exceptions");
14
+ class SignatureProvider {
15
+ constructor(cryptoProvider) {
16
+ this.cryptoProvider = cryptoProvider;
17
+ }
18
+ verifyHeader({ payload, sigHeader, secret, tolerance = 180000, }) {
19
+ return __awaiter(this, void 0, void 0, function* () {
20
+ const [timestamp, signatureHash] = this.getTimestampAndSignatureHash(sigHeader);
21
+ if (!signatureHash || Object.keys(signatureHash).length === 0) {
22
+ throw new exceptions_1.SignatureVerificationException('No signature hash found with expected scheme v1');
23
+ }
24
+ if (parseInt(timestamp, 10) < Date.now() - tolerance) {
25
+ throw new exceptions_1.SignatureVerificationException('Timestamp outside the tolerance zone');
26
+ }
27
+ const expectedSig = yield this.computeSignature(timestamp, payload, secret);
28
+ if ((yield this.cryptoProvider.secureCompare(expectedSig, signatureHash)) ===
29
+ false) {
30
+ throw new exceptions_1.SignatureVerificationException('Signature hash does not match the expected signature hash for payload');
31
+ }
32
+ return true;
33
+ });
34
+ }
35
+ getTimestampAndSignatureHash(sigHeader) {
36
+ const signature = sigHeader;
37
+ const [t, v1] = signature.split(',');
38
+ if (typeof t === 'undefined' || typeof v1 === 'undefined') {
39
+ throw new exceptions_1.SignatureVerificationException('Signature or timestamp missing');
40
+ }
41
+ const { 1: timestamp } = t.split('=');
42
+ const { 1: signatureHash } = v1.split('=');
43
+ return [timestamp, signatureHash];
44
+ }
45
+ computeSignature(timestamp, payload, secret) {
46
+ return __awaiter(this, void 0, void 0, function* () {
47
+ payload = JSON.stringify(payload);
48
+ const signedPayload = `${timestamp}.${payload}`;
49
+ return yield this.cryptoProvider.computeHMACSignatureAsync(signedPayload, secret);
50
+ });
51
+ }
52
+ }
53
+ exports.SignatureProvider = SignatureProvider;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const crypto_1 = __importDefault(require("crypto"));
16
+ const SubtleCryptoProvider_1 = require("./SubtleCryptoProvider");
17
+ const webhook_json_1 = __importDefault(require("../../webhooks/fixtures/webhook.json"));
18
+ const SignatureProvider_1 = require("./SignatureProvider");
19
+ describe('SignatureProvider', () => {
20
+ let payload;
21
+ let secret;
22
+ let timestamp;
23
+ let signatureHash;
24
+ const signatureProvider = new SignatureProvider_1.SignatureProvider(new SubtleCryptoProvider_1.SubtleCryptoProvider());
25
+ beforeEach(() => {
26
+ payload = webhook_json_1.default;
27
+ secret = 'secret';
28
+ timestamp = Date.now() * 1000;
29
+ const unhashedString = `${timestamp}.${JSON.stringify(payload)}`;
30
+ signatureHash = crypto_1.default
31
+ .createHmac('sha256', secret)
32
+ .update(unhashedString)
33
+ .digest()
34
+ .toString('hex');
35
+ });
36
+ describe('verifyHeader', () => {
37
+ it('returns true when the signature is valid', () => __awaiter(void 0, void 0, void 0, function* () {
38
+ const sigHeader = `t=${timestamp}, v1=${signatureHash}`;
39
+ const options = { payload, sigHeader, secret };
40
+ const result = yield signatureProvider.verifyHeader(options);
41
+ expect(result).toBeTruthy();
42
+ }));
43
+ });
44
+ describe('getTimestampAndSignatureHash', () => {
45
+ it('returns the timestamp and signature when the signature is valid', () => {
46
+ const sigHeader = `t=${timestamp}, v1=${signatureHash}`;
47
+ const timestampAndSignature = signatureProvider.getTimestampAndSignatureHash(sigHeader);
48
+ expect(timestampAndSignature).toEqual([
49
+ timestamp.toString(),
50
+ signatureHash,
51
+ ]);
52
+ });
53
+ });
54
+ describe('computeSignature', () => {
55
+ it('returns the computed signature', () => __awaiter(void 0, void 0, void 0, function* () {
56
+ const signature = yield signatureProvider.computeSignature(timestamp, payload, secret);
57
+ expect(signature).toEqual(signatureHash);
58
+ }));
59
+ });
60
+ describe('when in an environment that supports SubtleCrypto', () => {
61
+ it('automatically uses the subtle crypto library', () => {
62
+ // tslint:disable-next-line
63
+ expect(signatureProvider['cryptoProvider']).toBeInstanceOf(SubtleCryptoProvider_1.SubtleCryptoProvider);
64
+ });
65
+ });
66
+ });
@@ -0,0 +1,15 @@
1
+ import { CryptoProvider } from './CryptoProvider';
2
+ /**
3
+ * `CryptoProvider which uses the SubtleCrypto interface of the Web Crypto API.
4
+ *
5
+ * This only supports asynchronous operations.
6
+ */
7
+ export declare class SubtleCryptoProvider extends CryptoProvider {
8
+ subtleCrypto: SubtleCrypto;
9
+ constructor(subtleCrypto?: SubtleCrypto);
10
+ computeHMACSignature(_payload: string, _secret: string): string;
11
+ /** @override */
12
+ computeHMACSignatureAsync(payload: string, secret: string): Promise<string>;
13
+ /** @override */
14
+ secureCompare(stringA: string, stringB: string): Promise<boolean>;
15
+ }
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.SubtleCryptoProvider = void 0;
13
+ const CryptoProvider_1 = require("./CryptoProvider");
14
+ /**
15
+ * `CryptoProvider which uses the SubtleCrypto interface of the Web Crypto API.
16
+ *
17
+ * This only supports asynchronous operations.
18
+ */
19
+ class SubtleCryptoProvider extends CryptoProvider_1.CryptoProvider {
20
+ constructor(subtleCrypto) {
21
+ super();
22
+ // If no subtle crypto is interface, default to the global namespace. This
23
+ // is to allow custom interfaces (eg. using the Node webcrypto interface in
24
+ // tests).
25
+ this.subtleCrypto = subtleCrypto || crypto.subtle;
26
+ }
27
+ computeHMACSignature(_payload, _secret) {
28
+ throw new Error('SubleCryptoProvider cannot be used in a synchronous context.');
29
+ }
30
+ /** @override */
31
+ computeHMACSignatureAsync(payload, secret) {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ const encoder = new TextEncoder();
34
+ const key = yield this.subtleCrypto.importKey('raw', encoder.encode(secret), {
35
+ name: 'HMAC',
36
+ hash: { name: 'SHA-256' },
37
+ }, false, ['sign']);
38
+ const signatureBuffer = yield this.subtleCrypto.sign('hmac', key, encoder.encode(payload));
39
+ // crypto.subtle returns the signature in base64 format. This must be
40
+ // encoded in hex to match the CryptoProvider contract. We map each byte in
41
+ // the buffer to its corresponding hex octet and then combine into a string.
42
+ const signatureBytes = new Uint8Array(signatureBuffer);
43
+ const signatureHexCodes = new Array(signatureBytes.length);
44
+ for (let i = 0; i < signatureBytes.length; i++) {
45
+ signatureHexCodes[i] = byteHexMapping[signatureBytes[i]];
46
+ }
47
+ return signatureHexCodes.join('');
48
+ });
49
+ }
50
+ /** @override */
51
+ secureCompare(stringA, stringB) {
52
+ return __awaiter(this, void 0, void 0, function* () {
53
+ const bufferA = this.encoder.encode(stringA);
54
+ const bufferB = this.encoder.encode(stringB);
55
+ if (bufferA.length !== bufferB.length) {
56
+ return false;
57
+ }
58
+ const algorithm = { name: 'HMAC', hash: 'SHA-256' };
59
+ const key = (yield crypto.subtle.generateKey(algorithm, false, [
60
+ 'sign',
61
+ 'verify',
62
+ ]));
63
+ const hmac = yield crypto.subtle.sign(algorithm, key, bufferA);
64
+ const equal = yield crypto.subtle.verify(algorithm, key, hmac, bufferB);
65
+ return equal;
66
+ });
67
+ }
68
+ }
69
+ exports.SubtleCryptoProvider = SubtleCryptoProvider;
70
+ // Cached mapping of byte to hex representation. We do this once to avoid re-
71
+ // computing every time we need to convert the result of a signature to hex.
72
+ const byteHexMapping = new Array(256);
73
+ for (let i = 0; i < byteHexMapping.length; i++) {
74
+ byteHexMapping[i] = i.toString(16).padStart(2, '0');
75
+ }
@@ -0,0 +1,4 @@
1
+ export * from './NodeCryptoProvider';
2
+ export * from './SubtleCryptoProvider';
3
+ export * from './CryptoProvider';
4
+ export * from './SignatureProvider';